Skip to content

fix(storage): read role checkouts without walking each task's history - #1404

Merged
zhaozhaozz merged 1 commit into
agent-CI-Infra:mainfrom
zhaozhaozz:fix/issue-1398-storage-refresh-stall
Nov 26, 2026
Merged

zhaozhaozz merged 1 commit into
agent-CI-Infra:mainfrom
zhaozhaozz:fix/issue-1398-storage-refresh-stall

Conversation

@zhaozhaozz

Copy link
Copy Markdown
Collaborator

Fixes #1398

Problem

The storage refresh (every five minutes) and the hourly workspace sweep decide which directories an unfinished task can still use. Part of that is each role's newest checkout, read per task with:

SELECT … FROM task_history WHERE task_id=? AND type='role_candidate' ORDER BY id DESC

No index covers task_id together with type, so SQLite seeks task_history_run (task_id=?) and reads every history row of the task to compare its type, then sorts. Long-lived tasks have tens of thousands of rows, so this is one random page read per row.

Measured read-only on production (v0.4.13, 2026-11-26, in a separate node:sqlite process inside the bot container):

  • 65 unfinished tasks hold directories; their history is 473,266 rows across 8,893 runs, of which 16,940 rows have no run.
  • Running the current query for each of them took 65.9 s in total (slowest task 8.2 s, 42 tasks over 100 ms). That matches the 65.7 s and 70.5 s [stall] lines seen at five-minute intervals.
  • With the role checkout reads stubbed out, the rest of unfinishedTaskWorkspaces across all 7 projects took 0.84 s (at most 0.5 s for one project).

Change

src/projects/workspace-cleanup.ts: the newest role_candidate per role of each task now comes from a per-store cache:

  • First read of a task, through existing indexes only:
    1. its runs: SELECT DISTINCT run_id … WHERE task_id IN (…) AND run_id IS NOT NULL (covering task_history_run);
    2. those runs' candidates: INDEXED BY task_history_run_type (run_id=? AND type=?);
    3. its rows without a run: INDEXED BY task_history_run (task_id=? AND run_id IS NULL).
  • After that, only rows added since are read, as one rowid range at the end of the table: WHERE id>? AND type='role_candidate'. This is exact for two reasons. task_history.id is AUTOINCREMENT, so it only grows. And role_candidate rows are never rewritten: the payload migration only moves operation and runtime_log bodies, and history is deleted only together with its task.
  • Unchanged decision: the newest row per role, then the review-round cutoff on that row.
  • Bounded cache: least recently used tasks past 10,000 are dropped and read again if asked.
  • primeRoleCandidates(store): once per store, reads the unfinished tasks holding directories one task at a time, with setImmediate between tasks. StorageReport.refresh() and WorkspaceCleanup.sweep() call it before their loops, so the first pass after a start does not do it all in one block.
  • src/app/storage.ts: the refresh also yields between projects.

Why no new index

Adding task_history(task_id,type,id), or a partial index on role_candidate, would build on start over 13.2M rows in an 87 GB database.

  • Cost: the build scans the whole table. A full scan of one of its indexes alone took 90 s on production under the current I/O pressure (PSI some ≈ 77%).
  • Failure risk: a full index sorts about 0.7 GB of keys through SQLite temp files, and SQLITE_TMPDIR is the control plane's 512 MB /tmp tmpfs. A deploy could fail on start with database or disk is full.
  • Not needed: the existing indexes already give the result exactly.

Equivalence and evidence

  • Production (read-only): the per-task query and the new index reads returned the same 270 rows for the 65 tasks. The first-read path took 5.3 s and 10.4 s in two runs, under heavy I/O. In the new code that time is spread one task at a time after each start; later refreshes read only the table end.

  • Local benchmark: production-shaped database (3.0M history rows; 65 unfinished tasks with 514k rows, 10.3k runs and 19k rows without a run). One storage-refresh pass, with the page cache dropped (POSIX_FADV_DONTNEED) before each run, two runs each:

    first pass longest event-loop block next pass (after 2,000 new rows) longest block
    main 2f2195a6 36.8 s / 36.9 s 36.8 s / 36.9 s 0.85 s / 0.88 s 0.85 s / 0.88 s
    this PR 5.2 s / 5.2 s 0.48 s / 0.46 s 20 ms / 21 ms 9 ms / 10 ms

    The storage-page summaries from both versions are identical (same digest).

  • Tests:

    • test/ut/src/storage/history-lookup-plan.test.mjs pins the plans with EXPLAIN QUERY PLAN: covering task_history_run, task_history_run_type (run_id=? AND type=?), task_history_run (task_id=? AND run_id=?) and INTEGER PRIMARY KEY (rowid>?). It also checks that no statement seeks task_history_run (task_id=?) alone or scans the table. Against main's module this test fails on the old task_history_run (task_id=?) | USE TEMP B-TREE FOR ORDER BY plan.
    • test/ut/src/projects/workspace-cleanup.test.mjs adds two tests:
      1. A newer checkout of a role, written after the first read, replaces the older one. A task whose candidates predate the cache is read in full when first asked. Rows with and without a run both count, and the storage-page summary agrees.
      2. The first read after a start goes one task at a time, with the event loop turning between tasks.

Verification

Head e125b736, Node v22:

  • npm ci → 0
  • (cd runner && npm ci) → 0
  • npm run check → 0
  • npm test → 1: 347 of 352 sets passed (2842/2852 tests). The five failed sets fail for reasons outside this change, and each passes when run alone with node --test:
    • runner-transport: EADDRINUSE, because the deep worktree path pushes the socket path past 108 bytes; passes 4/4 with a short TMPDIR.
    • distributed-nodes (5/5), service-step-timing (6/6), pi-mailbox (4/4), codex-harness (68/68): timeouts and duration assertions under parallel load.

The storage refresh (every five minutes) and the hourly workspace sweep
read each unfinished task's role checkouts with
task_id=? AND type='role_candidate'. No index covers task_id with type,
so every history row of the task was read to compare its type: in
production 0.1-8 s per task, 65.9 s for the 65 unfinished tasks holding
directories, in one synchronous block every five minutes.

A task's newest checkout per role is now read once through the indexes
there are (its runs from task_history_run, their candidates from
task_history_run_type, its rows without a run), then only the rows added
since, a rowid range at the end of the table. History ids only grow and a
role_candidate row is never rewritten, so the result is the same as
reading the whole history. The first refresh or sweep after a start reads
the tasks one at a time, yielding between them, and the refresh yields
between projects. No index is added: building one on task_history
(13.2M rows) at start would read the whole table and sort it through the
512 MB /tmp of the control plane.

Fixes agent-CI-Infra#1398
@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Reviewed head e125b7361ec1a9534fc2a8eb3b623b21079b9f40.

The cached newest role_candidate per role is now read through the existing task_history_run, task_history_run_type and rowid indexes, and the id>? tail read picks up rows added since. That predicate is sound here: task_history.id is AUTOINCREMENT and role_candidate rows are not rewritten (the payload migration only moves operation/runtime_log bodies; history rows are deleted only with their task).

I compared the cached result against an independent full-history read (newest row per role, ORDER BY id DESC) over randomized sequences of candidates with and without a run, interleaving reads of two tasks: every round kept exactly the same set of directories per task, and the storage-page summary agreed.

Required checks (unit, e2e, the four image builds, CodeQL) pass on this head. No blocking findings — enqueued for merge.

@agent-ci-infra-bot agent-ci-infra-bot Bot 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.

Reviewed commit: e125b73
Coverage: PR #1404; 5 changed file(s)

Comment thread src/app/storage.ts
const nowMs = Date.now();
// The role checkouts first, a task at a time, then one project at a time, yielding between them (#1398): a
// project's records take a few hundred ms in production.
await primeRoleCandidates(this.store);

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.

F1 (medium, suggestion): the cold role-checkout read this call is meant to spread has already happened above it, in one synchronous block.

This await primeRoleCandidates(this.store) is the only place the refresh warms the cache, but this.computer(row) runs for every computer in the loop just above (src/app/storage.ts:130) before this line, and it calls workspaceClasses() (:198), which calls retention() → unfinishedWorkspacesState() → roleCandidates(store, ids) with every unfinished task that owns a listed directory of that project. this.classified (:57) is empty on a fresh process, so that is exactly the cold read: per project, one SELECT DISTINCT run_id … IN (all that project's unfinished ids) plus the run/run_id IS NULL candidate reads, run synchronously for all projects in the same loop. When this line is then reached, every id is already in cache.tasks, so the for loop inside primeRoleCandidates neither reads nor yields.

Evidence: tracing a real StorageReport.refresh() (6 unfinished tasks in one project, manager scan carrying result.tasks) shows the only role read is a single batch of 6 task ids inside computer(), and no per-task (IN (1)) read afterwards; calling workspaceClasses() alone shows the same single batch of 6. So the one-task-at-a-time priming that this PR describes as the fix (“StorageReport.refresh() and WorkspaceCleanup.sweep() call it before their loops, so the first pass after a start does not do it all in one block”) does not happen on the refresh path — the sweep path is fine because sweep() primes before its project loop. With the PR's own production figures (first-read path 5.3 s / 10.4 s for 65 tasks) the first refresh after each start/deploy still blocks the event loop for seconds, which is what #1398 asks to remove, and the added docs/design/storage-and-knowledge.md sentence (“启动后首次存储页刷新或清理逐任务预热并让出事件循环”) does not describe this path.

Suggested fix: move the prime call above the manager.computers loop (e.g. right after the manager read, before const computers = …), so the cold read is spread per task before workspaceClasses() asks for the same tasks; then add a StorageReport.refresh() test that the first role read is per task when the scan carries tasks — the two new tests only drive primeRoleCandidates() and unfinishedTaskWorkspaces() directly, so neither covers this ordering. If the ordering is intentionally left as is, the PR description and that docs sentence should be corrected instead, because the first refresh after a start still blocks for the full cold read.

@agent-ci-infra-bot

Copy link
Copy Markdown
Contributor

Review of PR #1404 (e125b736 vs 2f2195a6)

The core change is sound and I could not find a wrong keep-set. Findings below are ordered by severity; F1 is medium (suggestion).

What I verified on e125b736

  • npm ci, tsc build and npm run check pass. node --test test/ut/src/storage/history-lookup-plan.test.mjs test/ut/src/projects/workspace-cleanup.test.mjs → 26/26; test/ut/src/storage/storage-everything.test.mjs, storage-manager-stale.test.mjs, test/st/src/storage/storage-page.test.mjs, storage-overview.test.mjs → 19/19.
  • First-read completeness holds by construction: the run list comes from task_history.run_id values on the task's own rows (src/projects/workspace-cleanup.ts:301), not from task_runs, so a row is found whatever its run points at; a row with run_id IS NULL is covered by :305, and '' is included in the IS NOT NULL run list. I also checked that the incremental assumption is real: only operation/runtime_log bodies are rewritten (src/storage/migration.ts:235-246, WHERE id=? on data only), trace_history_scope only rewrites run_id/actor/source_ref, task deletion is the only path that removes task_history rows (ON DELETE CASCADE), and every insert lets AUTOINCREMENT assign the id.
  • Differential test against the old query: 25 randomized rounds × 40 steps × 5 tasks (rows with and without runs, worktree ids, rows added between reads, partial task batches) comparing the old per-task type='role_candidate' ORDER BY id DESC result with the new cache through unfinishedTaskWorkspaces().active — no mismatch. Review-round cutoffs and decidedTasks filtering are untouched.
  • The recurring 5-minute refresh is genuinely fixed: after the first pass, role reads are a rowid range and the refresh no longer walks a task history.

Findings

  • F1 (medium, suggestion) — primeRoleCandidates() is called too late in StorageReport.refresh(): the cold per-task read it is meant to spread already happened synchronously in this.computer()/workspaceClasses(), so the first refresh after a start still blocks once for the whole cold read, and the new docs/PR claim that it is spread is not what the code does. Fix is a move of one call (details inline).

Not reported

  • The claim about production timing, the index plans, and "no new index" are consistent with the code and the pinned EXPLAIN QUERY PLAN test.
  • I did not re-measure production scale; my ordering evidence uses a production-shaped fixture and a real StorageReport, and the timing figures quoted for impact are the PR's own.

Reviewed commit: e125b73
Coverage: PR #1404; 5 changed file(s)

Merged via the queue into agent-CI-Infra:main with commit a6c824c Nov 26, 2026
12 checks passed
@zhaozhaozz
zhaozhaozz deleted the fix/issue-1398-storage-refresh-stall branch November 26, 2026 08:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Storage refresh blocks the event loop for 20–70 s every 5 minutes (unfinished task workspace history scan)

1 participant