Skip to content

feat(storage): keep webhook bodies out of control.sqlite - #1407

Open
zhaozhaozz wants to merge 1 commit into
agent-CI-Infra:mainfrom
zhaozhaozz:feat/issue-1403-deliveries-out-of-db
Open

zhaozhaozz wants to merge 1 commit into
agent-CI-Infra:mainfrom
zhaozhaozz:feat/issue-1403-deliveries-out-of-db

Conversation

@zhaozhaozz

Copy link
Copy Markdown
Collaborator

Refs #1403 (phase 2 of 4, see the plan; phase 1 was #1405).

What

deliveries.payload (webhook bodies) is the next largest body in control.sqlite: 8.38 GB in 422.5 k rows in production, none removed by retention yet.

  • New deliveries (src/app/webhook.ts): an accepted body larger than 2 KiB is written to its own file, webhook-bodies/<project>/<id[:2]>/<id> beside the database (_ for no project), as the received bytes (mode 0600). The write and its fdatasync run with async IO before the transaction that inserts the row; the file is removed again if that transaction fails. The row keeps an empty payload, the file in payload_ref, its sha256 and size in payload_sha256 / payload_bytes (the columns the retention cleanup already kept for a removed body), and in payload_summary the few fields the delivery list shows, in the body's own shape. A refused request's digest and a body of at most 2 KiB stay in the row as before.
  • One reader (deliveryBody(), src/storage/webhook-bodies.ts): returns the received bytes from the file (checked against the row's sha256) or from the row. An unreadable file is a DeliveryBodyError (delivery_body_missing / delivery_body_corrupt, file system error as cause).
  • Existing rows move through a new deliveries phase of PayloadMigration (second, after task_runs). Each file is written, then synced off the event loop and read back against its hash. Only after that does the row point at it. A slice moves at most 40 rows, because clearing a body frees its overflow pages and 150 rows took 150–190 ms to commit. Refused, small and already removed rows stay. If retention removed a body in the meantime, it stays removed and the new file is deleted.
  • Why one file per delivery, not a daily append file: the retention cleanup removes bodies one delivery at a time. A delivery an external executor has not received yet keeps its body, and only whole files can be removed.

Read paths covered

  • Console event list (/api/events, deliveryResult): reads payload_summary, falls back to the inline body for rows without one; never reads files.
  • Console event detail (/api/events/:id): deliveryBody(); an unreadable file shows an empty payload with payload_unreadable: <code> instead of failing the view.
  • External executors' event polling (src/external/events.ts) and subscription forwarding (src/external/forward.ts): deliveryBody(); a forward whose body cannot be read fails as source_unavailable, before the delivery is claimed.
  • Retention (webhook_payload_days): the row is cleared as before (payload_removed_at, sha256 and size kept, payload_ref cleared, summary kept so the list still names the repository) and the file is removed after the transaction commits; a delivery an executor still has to receive keeps its file.
  • Project deletion: removes webhook-bodies/<project>/ with the trajectory files.
  • Refused-archive accounting (src/app/delivery-audit.ts) only reads refused rows, whose digests stay inline. No query filters on body fields.
  • Storage page: new directory row Webhook 正文 webhook-bodies.

Side effect: the UPDATE deliveries SET response=? that follows every accepted delivery no longer rewrites a ~18 KB row.

Bytes per day (production, read-only sample 2026-11-19 → 11-26)

accepted deliveries 252,600 in 7 days (≈36 k/day), 4.45 GB
written into control.sqlite before ≈636 MB/day
after the header columns only (ref, sha256, size and list summary: ≈300 B per delivery, ≈11 MB/day)
files written instead ≈636 MB/day, one file per delivery (no dedup)

Existing 8.38 GB move in the background after deploy. As with phase 1, the database file shrinks only after a compaction, which will be planned separately.

Background migration speed (synthetic)

.tmp benchmark (not committed): 5,000 accepted deliveries of 18.6 KB (93 MB), default options, local disk, machine load ≈2: 37 s (135 rows/s, 2.5 MB/s), failed 0, 0 bytes left in rows. Longest event-loop block 103 ms; p99 49 ms. Before the 40-row cap, one apply of ~150 rows took up to 190 ms. At this rate production's 422.5 k rows take about an hour on an idle disk, longer under IO pressure. Like the other phases, the migration pauses for the disk reserve and for descriptor exhaustion.

Retention

Unchanged: webhook_payload_days (unset in production) still removes bodies one delivery at a time with the same skip rule; files go with their rows and with the project.

Tests

New or changed tests:

  • test/st/src/storage/webhook-bodies.test.mjs (new):
    • A large accepted body is written to its own file (0600), with the received bytes verbatim, including non-canonical formatting.
    • The row keeps only ref, sha256, size and summary.
    • A body of at most 2 KiB stays inline.
    • The list shows the repository from the summary without the body.
    • The detail view, external event polling and subscription forwarding all return the received body.
    • A tampered file reports payload_unreadable: delivery_body_corrupt in the detail view and makes a forward fail as source_unavailable.
    • Deleting the project removes its body directory.
  • test/st/src/storage/storage-retention.test.mjs: file-backed bodies past webhook_payload_days lose their file. The row keeps sha256, size and summary and reads as empty. A body an executor still has to receive keeps its file until it has been sent.
  • test/ut/src/storage/trajectory-migration.test.mjs: legacy inline rows read identically before and after the migration (bytes and deliveryResult). Accepted large bodies move, including one without a project (filed under _). Refused, small and removed rows stay. deliveries is read by rowid ranges.
  • test/ut/static/storage-page-labels.test.mjs: the new storage row label.
  • test/ut/src/storage/history-lookup-plan.test.mjs: its raw INSERT INTO deliveries VALUES(...) now names its columns, because the body columns exist from store start-up.
  • test/fixtures/external-helpers.mjs: externalFixture takes control-plane options (here a larger maxBodyBytes; the harness default of 2 KiB never produces a body over the threshold).

Local record for head 23e8f953 (on 8a211c13, current main):

command exit result
npm ci / (cd runner && npm ci) 0 / 0 lockfiles unchanged
npm run check 0
BOT_TEST_JOBS=8 npm test 1 2866 / 2870; failed sets codex-harness (wall-clock budgets, machine load 10–14) and runner-transport
node test/framework/test-sets.mjs --jobs 1 test/st/src/harness/codex-harness.test.mjs 0 68 / 68
TMPDIR=$PWD/.tmp/s node --test test/ut/manager/runner-transport.test.mjs 0 4 / 4 (known EADDRINUSE from a Unix socket path over 108 bytes in this deep worktree)

deliveries.payload holds about 8.4 GB of the production database and
grows by about 640 MB a day (252,600 accepted deliveries in the last
week, almost all over 2 KiB). An accepted body larger than 2 KiB is now
written to its own file, webhook-bodies/<project>/<id[:2]>/<id>, and
synced off the event loop before the row is inserted. The row keeps an
empty payload, the file in payload_ref, its sha256 and size in the
payload_sha256 / payload_bytes columns the retention cleanup already
keeps, and in payload_summary the few fields the delivery list shows.

Every reader goes through deliveryBody(): the console's event detail
(which reports payload_unreadable instead of failing), external
executors' event polling and subscription forwarding (an unreadable
body counts as an unavailable source). The list reads the summary.
Refused requests' digests and bodies of at most 2 KiB stay in the row.

One file per delivery keeps the retention cleanup per delivery: a body
past webhook_payload_days loses its file after the row is committed, and
a delivery an external executor still has to receive keeps its body.
Deleting a project removes its body directory. Existing rows move
through a new deliveries phase of the background migration, which
writes each file, syncs it, reads it back against its hash and only
then points the row at it. The storage page counts the new directory.

Refs agent-CI-Infra#1403
@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Reviewed head 23e8f953 against origin/main (8a211c13): single linear commit, all required checks green, and the ingest / read / retention / migration / project-deletion paths and their tests match the described design (body written and fdatasynced before the row, file removed when the transaction fails, sha256 checked on every read, retention keeps the body of an undelivered forward, the deliveries migration slice re-checks payload_ref/payload_removed_at before updating, and files go only after the rows commit). Two items need to be addressed before this can be queued.

Blocking

  1. docs/features/deployment-and-operations.md:138 and :152 — backup/restore list does not include webhook-bodies/. The bot-data volume description and the stop-write backup list still enumerate only control.sqlite, trajectories/, feedback/, channel-resources/, … . After this PR deliveries.payload_ref points into <data>/webhook-bodies/..., so an operator restoring exactly per this list gets rows whose bodies no longer exist: the console detail then reports payload_unreadable and external forwarding/polling fail for every delivery still in its window. Please add webhook-bodies/ to both the volume row and the stop-write backup line (next to feedback/ and channel-resources/), and state that it must be restored together with control.sqlite.

  2. static/settings/page.js:108 — UI change without screenshots. This adds a visible row to the storage page. Per the project review rules, a UI text/structure change needs real screenshots of the affected page attached to the PR (1440 and 390 CSS px, full viewport, not committed to the branch). Please attach them to the PR description or a comment.

Non-blocking suggestions

  1. src/external/events.ts:30 — one unreadable body blocks the whole event poll. A DeliveryBodyError from deliveryBody() escapes EventPoller.poll(), so GET /external/events returns 500 and the cursor does not advance; a single missing/corrupt file keeps failing every poll for that repository until the row leaves the 24-hour window. src/external/forward.ts:36 treats the same condition as source_unavailable; the poller could fail or skip just that event, or report it in the payload, instead of failing the whole request. (Rows emptied by retention already had this failure mode, but the new missing-file state makes it easier to reach.)

  2. src/storage/webhook-bodies.ts:77-79 — transient read errors look like a missing file. Every read error, including EMFILE/EAGAIN under descriptor pressure, is wrapped as delivery_body_missing, and Forwarder turns any DeliveryBodyError into a terminal failed: source_unavailable row. Consider separating transient resource errors (the migration does this with exhausted()) so a descriptor shortage does not permanently drop a subscription forward.

  3. payload_unreadable is not shown anywhere. GET /api/events/:id returns it (src/app/queries.ts:218), but static/app/delivery.js renders the raw section as "payload": "", which reads exactly like a body removed by retention. Consider showing the code in that section.

  4. No sweep for webhook-bodies/ files that no row points at. A write that fails part-way (ENOSPC/EIO) leaves a file because only a failed transaction calls removeDeliveryBody (src/app/webhook.ts:220), and a post-commit unlink that fails in retention (src/storage/retention.ts:466/480) is recorded once and never retried. The daily cleanup already sweeps orphan files for feedback/ and sync-blobs/; the same sweep (older than an hour, no matching deliveries.payload_ref) would keep this directory bounded.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant