Skip to content

feat: let a scheduler start the audit event purge instead of the server's timer - #2397

Merged
fforootd merged 4 commits into
mainfrom
claude/xenodochial-archimedes-f4763f
Oct 28, 2026
Merged

fforootd merged 4 commits into
mainfrom
claude/xenodochial-archimedes-f4763f

Conversation

@fforootd

@fforootd fforootd commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Summary

The hosted cloud's audit event purge has not been running. In the 48 hours to 2026-10-27 14:31 UTC, production logged 14 event retention: purge failed lines and no purged events line. Every failure is a connection failure to PlanetScale's PgBouncer: tls error: EOF, unexpected EOF, client_login_timeout or a deadline. Each was logged during whichever request had cold-started the instance. RetentionJob starts a purge as the server starts, from a goroutine outside any request, and a Vercel function runs only while it serves one.

This PR lets something outside the process own the schedule, without changing a self-hosted server:

  • Server: a new setting, events.retention.trigger_secret. When it is set, the server runs no purge loop. Instead, each GET or POST to /cron/events-retention that carries the secret as a bearer token runs one purge and answers {"deleted": n}. Any other request to the path gets 401, and a failed purge gets 500. When it is unset (the default), the server purges hourly in process as before. The path is mounted outside the API: it is not in the OpenAPI document, and its request goes through only the request-ID, request-log and recover middleware.
  • A run is the same DeleteEventsOlderThan the loop calls, so it is idempotent. A run gets 4½ minutes, under Vercel's 300 s default, and extends its own write deadline past the server's 30 s WriteTimeout. Two runs in one process wait for each other; across instances, Postgres's row locks keep an overlap safe. Every triggered run logs a line, including one that deletes nothing.
  • Cloud: vercel.json gets a Cron Job that calls the path at minute 17 of every hour. The launcher writes CRON_SECRET into nextgen.yaml as the trigger secret and takes it out of the environment. A production or preview build fails without it, so a deployment that would never purge cannot replace the one serving. Vercel's docs pair top-level crons with services (their Render migration guide), and vercel.json validates against Vercel's published schema.
  • Role: ADR 049 §2 says the purge runs as a dedicated role with DELETE on events. The production failures connect as pscale_api_…, the role behind CLOUD_DATABASE_URL. Per the runbook, that role inherits pg_write_all_data, so it may delete from every table. No deployment has a dedicated role: the server opens one pool. ADR 049 gets a dated amendment that records both decisions: who starts the purge, and that it runs as the server's role until a deployment needs the split.
  • Docs: the runbook's environment table and Operating section, a new "Audit event retention" section in docs/quick-start/configuration.md, and the cloud README's launcher row.

Validation

  • go test -race -count=1 ./internal/audit/ ./cmd/server/ ./apps/cloud/launcher/: pass.
  • go run ./tools/analyzers/cmd/analyzers on those packages, plain and with postgres_integration and sqlite_integration: pass. gofmt -l is clean; go build ./... passes.
  • New tests, each checked by breaking the code it guards:
    • Trigger handler (internal/audit): 401, 405, 500 and the response shape. Run against a real http.Server with 50 ms timeouts, it outlasts the write timeout; dropping the deadline extension fails with EOF. Purges in one process run one after the other; dropping that guard fails. A triggered run is its own job root even under an incoming trace context; dropping WithNewRoot fails.
    • cmd/server: the mux mounts the path only when given a trigger, with the proxy's request ID. Config loads the key from the file and from the environment and refuses a short secret.
    • Launcher: renders the secret (a quote round-trips through YAML), unsets CRON_SECRET, and refuses a deployment without it, in serving and at build time. A vercel.json test pins the cron's path to the server's constant and checks that no redirect or earlier rewrite captures it. A wrong path fails it, and so does a capturing rewrite.
  • vercel.json checked with ajv-cli against https://openapi.vercel.sh/vercel.json: valid.
  • One run on this PR's preview (cloud-qg447hb01-zitadel.vercel.app, commit ef362837a):
    • Without the cron secret, behind the bypass header: the server answered 401 with WWW-Authenticate: Bearer.
    • With it: 200 {"deleted":0} in 6 ms, and one event retention: purged events line under the request's ID.
    • The instance cold-started on the 401 request and logged no purge failed. The count is 0 because this preview's database was created by its own build.
    • Before the variable existed, this branch's first preview build failed on the launcher's new guard ("CRON_SECRET must be set for a preview deployment"), as designed.
  • After merging main (2026-10-28, 47 commits, among them the turbo-built cloud, build(deploy): build every cloud service through one turbo graph #2425): the same Go tests, gofmt, the analyzers and the schema check pass. The migrate task passes the whole environment through, so the build still sees CRON_SECRET.
  • Not yet done: the first scheduled run in production, which can only happen after merge.

Release notes / changeset

.changeset/events-retention-trigger.md: @zitadel/server minor. A server that runs only while serving a request can leave the purge to an outside scheduler through events.retention.trigger_secret; without it, the hourly purge is unchanged.

Notes

  • CRON_SECRET is set (2026-10-27) as a sensitive variable for Production and, with a different value, for Preview (all branches). Both values are owner-only in ~/.zitadel/cloud/<env>/cron-secret on the machine that minted them, and still need to go into 1Password.
  • Deployment Protection: the project uses Standard Protection (all_except_custom_domains). Vercel calls a cron on the production deployment URL, and its docs don't say whether those calls pass Vercel Authentication. Check the first run after merge under Settings → Cron Jobs → View Logs. A 401 from Vercel's login page, rather than the server's, means the run is blocked.
  • First run: no logged run in the window succeeded, so the backlog may be large, and the purge is one DELETE with no index leading on created_at. If a run times out, the runbook gives the batched DELETE to clear the backlog by hand.
  • Same cause, out of scope: the request audit batch flush (a duplicate events_pkey on retry) and the master key migration (client_login_timeout) also run outside a request. This PR doesn't fix them; the fix isn't shared.
  • ADR 065: it proposes an in-process job loop with no HTTP surface, which has the same limit on Vercel. The amendment notes it.
  • docs: show how to find the cloud's errors in Vercel's logs #2396's runbook example: its Errors bullet named a failed retention run as an error outside a request. On the cloud that run now answers 500 on its cron request, so this PR names the request audit event flush instead.

🤖 Generated with Claude Code

…er's timer

The hosted cloud's purge never ran: a Vercel function runs only while it
serves a request, so the in-process loop's first purge started at each cold
start, outside the request that started the instance, and failed while
connecting to PgBouncer.

- events.retention.trigger_secret: set, the server keeps no timer and
  purges once per GET or POST to /cron/events-retention that carries the
  secret as a bearer token. Unset, the default, a server purges hourly in
  process as before. Purges in one process wait for each other.
- The cloud: a Vercel Cron Job in vercel.json calls the path hourly, and
  the launcher turns CRON_SECRET into the trigger secret; a deployment's
  build fails without it.
- ADR 049 amended: who starts the purge, and that it runs as the server's
  role rather than a dedicated one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
cloud Ready Ready Preview Oct 28, 2026 9:51pm UTC

Request Review

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦋 Changeset detected

Latest commit: 6ceeb8e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 24 packages
Name Type
@zitadel/server Minor
@zitadel/cli Minor
@zitadel/testing Minor
@zitadel/server-linux-x64 Minor
@zitadel/server-linux-arm64 Minor
@zitadel/server-darwin-x64 Minor
@zitadel/server-darwin-arm64 Minor
@zitadel/server-win32-x64 Minor
@zitadel/api Minor
@zitadel/config Minor
@zitadel/components Minor
@zitadel/sdk-core Minor
@zitadel/sdk-next Minor
@zitadel/sdk-nuxt Minor
@zitadel/sdk-react Minor
@zitadel/sdk-vue Minor
@zitadel/sdk-angular Minor
@zitadel/sdk-solid Minor
@zitadel/sdk-svelte Minor
@zitadel/sdk-qwik Minor
@zitadel/sdk-sveltekit Minor
@zitadel/sdk-solid-start Minor
@zitadel/sdk-qwik-router Minor
@zitadel/sdk-tanstack-start Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

fforootd added a commit that referenced this pull request Oct 28, 2026
Revert wording the package does not need, so the change stays clear of
the open PRs that edit the same files: the README's build.sh row (beside
the row #2397 changes), two runbook phrasings, the root turbo.json header
and the turborepo.md bullet on ignored files in input globs, which the
rework of #2420 covers. The cloud task's own comment keeps why it
excludes .vercel/ and the other ignored trees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fforootd added a commit that referenced this pull request Oct 28, 2026
…o task

The server service's build command now installs (the Go preset runs no
installCommand) and runs `turbo run deploy --filter=@zitadel/cloud`.
@zitadel/cloud's new `deploy` task depends on `build` (the launcher, from
the cache when nothing it compiles changed) and runs deploy.sh, the former
build.sh without its install and turbo call: copy the binary to
$VERCEL_OUTPUT_FILE, then migrate. It is never cached, and it passes the
whole environment through (`passThroughEnv: ["*"]`): the launcher checks
every variable the function needs at build time, so a variable strict mode
hid (CRON_SECRET, which #2397 adds, or any later one) would fail every
deployment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fforootd and others added 2 commits October 28, 2026 14:38
…chimedes-f4763f

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The runbook's Errors bullet (#2396) gave a failed event retention run as an
error outside any request. On the cloud the purge now runs in its cron
request and a failed run answers 500, so the example is the request audit
event flush instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fforootd
fforootd marked this pull request as ready for review October 28, 2026 21:39
Copilot AI balanced review requested due to automatic review settings October 28, 2026 21:39
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
🔒 Security Review ✅ Completed 2026-10-28T21:42:06.412749Z 0f7bedf Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

An unresolved active finding remains, flagging that the runbook's Preview CRON_SECRET row omits the build requirement and could mislead operators into skipping a secret needed for the preview build.

1 open issue
What changed in this PR

The hosted cloud runs as a Vercel function that only executes while serving a request, so the server's in-process hourly RetentionJob timer never reliably runs the audit-event purge (production logged only purge failed, no successful runs). This PR lets an external scheduler own the purge schedule without changing self-hosted behavior: a new events.retention.trigger_secret setting switches the server from its in-process timer to an HTTP trigger at /cron/events-retention (bearer-token authenticated), which Vercel Cron calls hourly. When the secret is unset (the default), the hourly in-process purge is unchanged.

Changes:

  • Server: adds TriggerSecret config with validation (≥16 printable ASCII chars), a Trigger() HTTP handler (GET/POST + constant-time bearer check, 401/405/500, write-deadline extension to outlast WriteTimeout, per-process serialization via a purging token), and startJobSpan now takes a ctx with WithNewRoot(); the trigger is mounted outside the API with a minimal middleware chain.
  • Cloud: vercel.json cron job, launcher maps CRON_SECRET into the config file and removes it from the environment, failing deployed builds without it.
  • Docs/changeset: ADR 049 dated amendment, runbook + quick-start config sections, and a @zitadel/server minor changeset.
File Description
internal/​audit/​retention.go Core: TriggerSecret config, Validate/CheckTriggerSecret, serialized deleteExpired, bearer-authenticated Trigger() handler
internal/​audit/​tracing.go startJobSpan takes ctx + WithNewRoot() so a request-started run is still a job root
internal/​audit/​shipper.go Pass context.Background() to the new startJobSpan signature
internal/​audit/​retention_test.go /​ tracing_test.go Thorough tests: validation, auth, method, 500, serialization, timeouts, tracing
cmd/​server/​server.go Wire retentionJob.Trigger() into buildHTTPMux, default + mount the trigger path
cmd/​server/​config.go Add Events.Retention.Validate to startup validation
cmd/​server/​*_test.go Update buildHTTPMux callers; config-load and mount tests
apps/​cloud/​launcher/​main.go Read/validate CRON_SECRET, render trigger_secret into config, unset env
apps/​cloud/​launcher/​main_test.go Launcher + vercel.json cron routing tests
vercel.json Add hourly cron on /cron/events-retention
docs/​*, .changeset/​*, apps/​cloud/​README.md ADR amendment, runbook/config docs, changeset

I raised one minor documentation comment: the Preview CRON_SECRET runbook row omits that the build also fails without it, while the launcher enforces it identically for production and preview deployments. The implementation itself is correct and well-tested — the middleware chain preserves the write-deadline extension through Unwrap(), the bearer check is constant-time and length-independent, per-process purge serialization is handled, and all buildHTTPMux/startJobSpan call sites are updated.

One item is deferred to a human: whether Vercel Cron actually reaches the endpoint past Deployment Protection can only be confirmed by the first production run after merge (the author flagged this uncertainty).

Review effort: Balanced

Comment thread docs/runbooks/cloud.md Resolved
The launcher refuses every deployment without it, preview included, so the
runbook's Preview row no longer reads as if the secret were optional.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fforootd
fforootd added this pull request to the merge queue Oct 28, 2026
Merged via the queue into main with commit a6fb3ce Oct 28, 2026
21 of 22 checks passed
@fforootd
fforootd deleted the claude/xenodochial-archimedes-f4763f branch October 28, 2026 22:15
@github-project-automation github-project-automation Bot moved this from Inbox to Done in Engineering Kanban Oct 28, 2026

This branch was successfully deployed

1 active deployment
Preview — 6ceeb8e3 Deployed Oct 28, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

2 participants