Repository navigation
feat(storage): keep run context and config snapshots out of control.sqlite - #1405
Conversation
|
Blocking: the new Where
Expected vs actual
Evidence (built this head
|
| run | result |
|---|---|
| 400 tasks, default limits | phase migrated: 800, failed: 0; 400 descriptors into trajectories/ still open after the phase finished (0 before it) |
1,500 tasks, ulimit -n 1024 |
failed: 1005, last_error: "task_runs rowid 3000: EMFILE: too many open files, open '.../task-1499/legacy.jsonl'"; 1,005 of 3,000 rows still hold their whole snapshots |
ulimit -n 1024 is the soft limit of this deployment's control-plane container (docker exec bot-bot-1 ulimit -n → 1024, hard 524288), i.e. the same Compose service this PR deploys into.
At production's numbers from the PR description (69.7k runs over ~9.4k tasks, ≈19 MB/s on an idle disk, "a few times longer" under IO pressure) a 30-minute window holds roughly 1.5k–4.7k distinct task files, and a ~30-minute pass holds all of them, so the phase reaches the descriptor limit well before the table is walked.
Impact
EMFILEis counted as a row failure and the read loop then advances the cursor past the row; the phase marks itselffinished_atand later passes start atWHERE rowid > cursor, so those rows are never retried. The 37 GB this PR is about stay incontrol.sqliteand the storage page only shows afailedcount.- While the control plane is at the limit, unrelated
openSync/accept calls fail too (my probe could not even open/proc/self/fdat that point), so the background migration can break webhook, manager and model-gateway file/socket opens for its duration.
Suggested fix
- Append through the migration's own
append()socloseTouched()bounds the descriptors: for example letstoredRunSnapshot()take an optional append callback ((scope, type, id, data) => this.append(scope, type, id, data)), or split "build the header" from "append the record" and append in the phase. - Add a regression test that migrates more tasks than
openFilesand asserts the descriptor count stays bounded (e.g. count/proc/self/fdlinks into<store>/trajectorieson Linux, or expose the open-handle count), plus that no row keeps its body under a lowulimit -n. - Consider not advancing the cursor past a move that failed with
EMFILE/ENFILE/ENOMEM, or leaving the phase unfinished whilefailed > 0, so a transient resource error is retried instead of silently leaving the largest bodies in the database.
Non-blocking note: retention of shared records
storedRunSnapshot() (src/storage/payloads.ts:122-124) lets a new run reference the record in an earlier run's file, and that reference is not bounded by age. With trajectory_days set, a file expires trajectory_days after it was closed, and the latest run's column may point all the way back to the task's first identical context, so a run started today can read trajectory_expired as soon as that oldest file expires, while its own file is still inside the window. The PR body says "Retention unchanged in effect"; either bound the reuse (for example only share with records from files younger than the project's window) or state the behavior in docs/design/storage-and-knowledge.md.
Verified without findings
- Both columns are only read through
runSnapshot():traceSource(src/tasks/trace.ts:175), the runs view withinclude_snapshots=1(same function), andrecoverRoleCheckpoint(src/roles/recovery.ts:11); there is no othercontext_snapshot/config_snapshotreader insrc/. src/storage/migration.ts:206keeps non-canonical snapshot text inline, so an unmigrated row still reads byte-identically, and theJSON.stringify(JSON.parse(text))guard is the same transformationrunSnapshot()performs.- Syncing only
refs.at(-1)per move is still sufficient: both refs of atask_runsmove belong to the same legacy file (reuse is per task), andsync()fdatasyncs the file. docs/features/deployment-and-operations.mdanddocs/design/storage-and-knowledge.mdare both updated; no verification artifacts or workflow files in the diff; the branch is a single linear commit on currentmain.
|
第 3 次检视,更新于 2026-11-26 10:47 UTC,检视提交 3323cfa Review — head
|
|
Thanks, the descriptor finding was right: the Fixed in
On the retention note, I chose to document the behavior rather than change it.
|
…qlite task_runs.context_snapshot and config_snapshot hold about 37 GB of the production database (476 KB + 54 KB per run). A snapshot larger than 2 KiB is now appended to the run's trajectory file as one event record; the column keeps its header (schema_version, sha256, original_bytes, complete, ...) and the record's ref in $trajectory. A context identical to the one the task's latest run stored shares that run's record. Every reader goes through runSnapshot(): traceSource task_runs:<id>: context|config (the runs view with include_snapshots, the read_task_record tools) and recoverRoleCheckpoint. Rows written before this move in the background through a new task_runs migration phase into the task's legacy trajectory file; they read the same before and after. Refs agent-CI-Infra#1403
The task_runs phase appended through store.trajectories.append, so the legacy files it opened were never registered with the migration and stayed open until the 30-minute idle close: one descriptor per task, which reaches EMFILE at production scale. storedRunSnapshot now takes the append to use and the phase passes the migration's own, which closes files beyond openFiles after each slice. A row that runs out of descriptors or memory (EMFILE, ENFILE, ENOMEM) is no longer counted failed and passed by the cursor: the slice ends before it (or is dropped when a record cannot be read back for that reason), the migration's files are closed, and the row is read again after a pause. Document that a shared context record expires with the earlier run's file when trajectory_days is set. Refs agent-CI-Infra#1403
ddf655b to
5aea041
Compare
|
Rebased onto |
…riptors Trajectories.read() and getBlob() report a file they cannot open as trajectory_truncated without saying why, so the migration's check for EMFILE/ENFILE/ENOMEM never matched while reading records back: a slice verified while the process was out of descriptors counted its rows as failed and the cursor passed them. TrajectoryError now carries the file system error as its cause, and the migration looks through it. Readers see the same code and message as before. Refs agent-CI-Infra#1403
|
New head
|
|
Reviewed head What I verified on this head:
Enqueued with |
| }); | ||
| this.logSlowSlice(phase.name, 'verify', this.now() - verifyStarted, moves.length); | ||
| // A record that could not be read back for want of descriptors is not known to be bad: the whole slice is read again. | ||
| if (unchecked) { await this.waitForResources(); continue; } |
There was a problem hiding this comment.
suggestion (medium): a slice retried after running out of descriptors appends its records a second time; the lines from the dropped attempt are never referenced, so each retry adds up to a slice's worth of snapshot bodies to the trajectory files for good.
Why: move() appends at read time (storedRunSnapshot(..., (scope, type, id, data) => this.append(...)) at :222-223), before the slice is synced and verified. When verification cannot run (unchecked here) or the pre-apply sync fails (:141), the slice continues without applying and without moving the cursor, so the next attempt calls move() for the same rows and appends new lines. The lines of the dropped attempt are unreferenced; nothing rewrites a trajectory file (cleanup only removes whole files, by closed_at), so they stay until the file expires. waitForResources() also clears this.contexts (:87), so a retried row whose context was shared with the previous run's record now appends its own copy instead of sharing it.
Measured at this head (built dist, 400 tasks × 2 legacy runs → 800 records of ~2.8 KB, default openFiles: 32, exhaustedMs: 20):
ulimit -n |
retry rounds | migrated | failed | record lines | orphan lines | bytes on disk |
|---|---|---|---|---|---|---|
| 1024 | 0 | 800 | 0 | 800 | 0 | 2.4 MB |
| 64 | 10 | 800 | 0 | 1050 | 250 | 3.2 MB |
| 40 | 166 | 800 | 0 | 6172 | 5372 | 19.1 MB |
orphan lines counts lines whose record id appears more than once (appends no row points at); all 800 rows read back identical to the fixture in every run, so this is disk growth, not data loss. At production sizes (~530 KB per migrated run) a 200-row slice is ~106 MB, so a retry series like the ulimit -n 40 row can write gigabytes while the phase is stalling on descriptors — the case this retry path exists for. The new test throws once from read and checks failed/the read view, so it does not see this.
Fix options: remember each move's refs (and columns) per rowid for the current slice and apply/verify those on retry instead of calling move() again; or closeTouched(0) before verification so read-back, not the append, is what must fit under the limit; and keep the dropped rows' contexts entries so a retry does not write an extra unshared context record.
|
Local test record for |
Refs #1403 (phase 1 of 4, see the plan).
What
task_runs.context_snapshot/config_snapshotare the largest bodies incontrol.sqlite(≈37 GB of 87 GB, 476 KB + 54 KB per run). They now live in the trajectory file store:beginRun,src/tasks/trace.ts): a snapshot larger than 2 KiB is appended to the run's trajectory file as oneeventrecord before the row is inserted. The column keeps a header only:{"$trajectory":"<file>:<offset>:<length>:<sha256>","schema_version":1,"sha256":…,"original_bytes":…,"complete":…}(≈250 bytes). Smaller snapshots stay inline.sha256and size, record not expired), the new row points at that record instead of writing it again. The lookup readsoctet_length(context_snapshot)first, so a latest run that still holds a whole legacy snapshot costs one record header, not its body (measured: 1.1 ms vs 689 ms for 100 rows of 4 MB).runSnapshot(),src/storage/payloads.ts) returns the exact texttraceSnapshotproduced, for migrated, unmigrated and small inline rows alike. An unreadable record (missing, truncated, expired file) reads as{complete:false, missing_reason}like every other trajectory-backed source.task_runsphase ofPayloadMigration(first in the walk, since it is the largest): rowid slices, files synced off the event loop, every record read back against its hash before the row's columns are replaced; resumable from its cursor. Runs of a task with the same context share one record here too. Records are appended through the migration's ownappend(), so like every other phase its open files are bounded:openFiles(32) kept between slices plus the files of the slice being moved (a slice reads for at mostreadMsand at most 200 rows). A row that runs out of descriptors or memory (EMFILE/ENFILE/ENOMEM), while being moved or while its records are read back, is read again after a pause instead of being counted failed and passed by the cursor;TrajectoryErrornow carries the file system error as itscauseso the read-back case is recognised. A snapshot whose text is not the canonical JSON of its value (never written by the bot; only hand-made rows) stays in its column so it still reads byte-identical.Read paths covered
traceSource(task, 'task_runs:<id>:context|config'), which serves the task trace API (section=source, andsection=runs&include_snapshots=1) and every tool that reads trace references:read_task_record(Manager/team, retries, long execution, Manager recovery, consolidation), the role gateway's trace read, and task commands.recoverRoleCheckpoint(src/roles/recovery.ts), which compares the dev run'ssource_sha.json_extractor otherwise), so no extra column or index is needed.Side effects: columns added after the snapshots (
role,harness,lease_scope,run_context, …) no longer sit behind ~0.5 MB of overflow pages, so per-run reads of them (the role gateway'sSELECT * FROM task_runs WHERE id=?on every gateway call, board/flow queries onrole) and everyUPDATE task_runs(status, lease, recovery mode, CLI version) stop reading/rewriting the snapshot bodies once a row is new or migrated.Bytes per day (production, read-only sample 2026-11-19 → 11-26)
attempt)control.sqlitebeforeThe existing ≈37 GB (69.7 k rows) move in the background after deploy (storage page → 历史数据迁移 →
task_runs). The database file only shrinks after a compaction, which needs downtime and separate approval; it will be planned with measurements on a copy once all phases are in.Background migration speed (synthetic copy)
.tmpbenchmark on this branch (not committed): 1,000 legacy runs, 260 KB context + 21 KB config each, half of them on the same context as the task's previous run, defaultPayloadMigrationoptions on a local disk:At that rate production's ≈37 GB would take about half an hour of slices on an idle disk; with production's IO pressure expect a few times longer. It only pauses for the disk reserve, like the other phases.
Retention
New records live in the run's trajectory file, migrated ones in the task's
legacytrajectory file, so they followtrajectory_dayslike the run's other records (unset in production = keep everything) and are removed with the project. One difference whentrajectory_daysis set: a shared context record stays in the earlier run's file, so a later run's context snapshot expires with that earlier file, possibly before the later run's other records (stated indocs/design/storage-and-knowledge.md).Tests
New or changed tests:
test/ut/src/tasks/task-trace.test.mjs: new runs keep only a header in both columns and the record sits in the run's own file; trace source andinclude_snapshots=1read the whole snapshot; an unchanged context shares the record, a changed one does not; a small snapshot stays inline; an expired record reads astrajectory_expiredand is never shared; a legacy inline row reads as before.test/ut/src/storage/trajectory-migration.test.mjs: the legacy fixture now has runs (shared context, small config, non-canonical text); every trace source reads identically before and after the migration, including across a restart mid-walk; runs of a task share one context record; 40 tasks withopenFiles: 4never hold more than 5 migration files open and leave no descriptor intotrajectories/(fails before the fix with 40); a row whose append hitsEMFILEis moved after a pause, not counted failed (fails before the fix); a slice whose read-back hitsEMFILEis read again withfailed: 0(fails without thecausecheck), andread()/getBlob()of a missing file carrycause.code === 'ENOENT';task_runsis read by rowid ranges.test/st/src/roles/roles.test.mjs:recoverRoleCheckpointreconciles from a dev run whose context is in its trajectory record.test/st/src/agent/agent-runtime.test.mjs: the immutable run config is read throughrunSnapshot().Local record for head
3323cfa8(on4a407415, currentmain):npm run checkBOT_TEST_JOBS=8 npm testrunner-transportTMPDIR=$PWD/.tmp/s node --test test/ut/manager/runner-transport.test.mjsEADDRINUSEfrom a Unix socket path over 108 bytes in this deep worktreeOlder records below are for the earlier heads.
Local record for head
ddf655b3(ona6c824ca). Head5aea0415is the same two commits rebased onto4a407415(#1406) without conflicts (git range-diffshows both patches identical;docs/features/deployment-and-operations.mdkeeps main's rate-limit sentence and adds this PR's line); on itnpm run checkexited 0, and thenpm testrecord below still applies to this code:npm ci/(cd runner && npm ci)npm run checkBOT_TEST_JOBS=8 npm testdistributed-nodes(node_agent_connect_timeout),runner-transportnode test/framework/test-sets.mjs --jobs 1 test/st/src/cluster/distributed-nodes.test.mjsTMPDIR=$PWD/.tmp/s node --test test/ut/manager/runner-transport.test.mjsEADDRINUSEfrom a Unix socket path over 108 bytes in this deep worktreeThe review's reproduction on this head (1,500 tasks × 2 legacy runs,
ulimit -n 1024, default options,.tmpprobe):migrated 3000,failed 0, 0 rows still holding a whole snapshot, 0 descriptors intotrajectories/left open afterwards; sampling every 20 ms saw at most 37 at once, and the bot review measured peaks of ~130 with small rows (32 kept + one slice's files). The review measured 1,005 rows failing withEMFILEona2cfd24ein that setup.Earlier head
a2cfd24e:npm run check0;npm test2852 / 2859 (codex-harnesswall-clock budgets under load,runner-transportsocket path);codex-harnessalone failed only the "Codex model reroute" wall-clock test, which also fails onmainunder the same load (4.8–6.8 s from interrupt to end, budget 3.5 s); CIunitpassed it.