Skip to content

observe-metrics: read findings at one sha (thousands of git processes per tick on a big fleet) - #982

Merged
hhff merged 5 commits into
mainfrom
operator/observe-metrics-fast
Dec 5, 2026
Merged

hhff merged 5 commits into
mainfrom
operator/observe-metrics-fast

Conversation

@hhff

@hhff hhff commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Cause

On devteam-dev (kit v0.114.0, ~540 tickets, ~760 branches, ~60 worktrees), observe-metrics ran 30+ minutes and its caller's bound killed it. A second run, with the spend backlog already written, printed nothing in 30 min: 2m49s user, 6m58s sys. Supervisors skip a step that slow, and spend lines and metrics observations went stale for days in 3 fleets.

The step reads its findings through collectMetrics(0) with git read live. Without the read cache, each ticket's branch is resolved by its own git rev-parse --verify refs/heads/ticket/<id>^{commit} (and the origin/ one), several times per ticket. Each open branch's reviews/ folder is also listed several times. With 120 tickets in a fixture that came to 1,863 git processes in one tick, about 15 per ticket. Each one is forked from a node process holding the fleet's large log in memory, and that is where the sys time goes. metrics, status and ack already avoid this with readsAtOneSha / the GIT_READ_ONLY cache. observe-metrics writes, so it never turned the cache on.

Scratch folders in run/ and the worktrees themselves were not the cause. 40 kit-copy scratch dirs and 20 worktrees changed nothing measurable in a second run. The per-worktree tidy only runs every 30 min.

Change

cmdObserveMetrics now does three reads inside readsAtOneSha, the read phase ack already uses for the same collectMetrics(0):

  • collectMetrics(0) (the findings)
  • the digest's nextMoves()
  • the hub cache's nextMoves()

Each git question is asked once, ticket refs resolve from one for-each-ref, and each open branch's reviews are listed once per phase. Every log write (observations, the digest) happens after the caches are dropped, so it never acts on a stale read; the moves cache file is written after them too. (collectMetrics' own cache files are still written inside the phase.)

The real run's CPU profile (devteam-dev, v0.114.0)

node --cpu-prof of one observe-metrics on devteam-dev: 2,554 s sampled (SIGINT at 25 min, exit at 42m35s; 4m07 user, 8m41 sys). 2,235 s (87%) is the self time of spawnSync, the synchronous git processes git() starts. All of it is under collectMetrics (2,318 s) plus nextMoves / writeMovesCache. Top 10 by total time (function:line in v0.114.0's devteam.mjs):

total s function what it is
2,318 collectMetrics:21509 the findings, read live
1,871 ticketReviews:6505 / ticketReviewsRead:6511 each ticket's review records
1,670 srcRead:3985 one git show per review file (no batch outside a read phase)
1,147 reviewPasses:6582 walks every ticket's reviews again
593 reviewStats:6535 and again (no reviewMemo outside a read phase)
472 misRated:22556 and again
387 modelTierStats:21378 and again
296 resolveCommit:2883 one rev-parse per ref (no for-each-ref listing)
239 ticketBranchRef:4120 each ticket's branch, resolved per call
181 srcList:4049 each branch's reviews/ listed per call

Below those: workerState 163 s (57 s self, plus a 105 s filter of the whole log once per ticket), nextMoves 160 s, writeMovesCache 59 s, tidyFinishedWorktrees 38 s, readLog/foldLog 39 s. The only synchronous fs time of note was readFileSync (23 s). Nothing walked run/ or the worktrees' files.

The whole read side is the git work that readsAtOneSha exists to share (reviewMemo, batched cat-file, one for-each-ref, a tree index per commit). Every hot path above is inside one of the three calls now wrapped. The second commit groups the log's lines by writer once per read (workerState, ~160 s in the profile), with the same lines in the same order.

Timings (fixture, through the test harness)

300 tickets, 150 ticket branches, 30 worktrees, 40 kit-copy scratch dirs in run/. The old and new kit ran alternately on the same fixture:

wall user sys
before (origin/main) 116.4 s, 123.3 s 6.5 s 23.8–24.5 s
after 4.0 s, 3.6 s 0.6 s 0.4 s

With 120 tickets, the git processes in a second tick went from 1,863 to 300. The remaining ~1 per ticket is one listing per open branch per read phase.

Tests

  • test/reads-at-a-sha.test.mjs, new subtest. observe-metrics with live reads (DEVTEAM_TEST_LIVE_READS=1) and at one sha, under a frozen clock, must:

    • give the same output and write the same log, line for line
    • write nothing while a read cache is on (DEVTEAM_TEST_READ_CACHE_TRACE)
    • ask no ticket ref one at a time
    • list each open branch's reviews at most once per phase
    • start under half the git calls

    Mutation check: with the collectMetrics wrap removed, the subtest goes red ("no ticket ref asked one at a time").

  • test/next-moves-findings.test.mjs: the source-shape assertion on the last statements of cmdObserveMetrics now expects writeMovesCache(readsAtOneSha(() => nextMoves())).

  • Locally, all 19 test files that call observe-metrics pass (423 tests), and next-moves-findings passes again after its update.

Not tested: a run against a real fleet (by design); the profile above is from the operator's profiled run, read read-only. The workerState grouping has no test of its own: it is CPU only, gives the same lines in the same order, and is covered by the suites that read worker state (components G1 goldens, next-moves, fleet-idle, worktree-tidy, ooda-learning, reads-at-a-sha: all pass locally).

Not in this PR (separate causes, found on the way)

  • metrics --json as the operator role also timed out at 300 s on devteam-dev. That command already reads git cached. The likely cost is spend parsing: usageCache().save() skips the operator, so every operator metrics re-parses all of the fleet's Claude Code transcripts (~8,200 files, ~10.9 GB).
  • The supervisor's own transcript there is 845 MB. That is above node's max string length (536,870,888), so cachedParse's readFileSync(f, 'utf8') throws on every tick. The file is read whole each time and parsed as empty, so the supervisor's spend goes unmeasured.

Both need their own PR.

Opened by the box operator.

🤖 Generated with Claude Code

hhff and others added 2 commits December 4, 2026 07:55
… sha

The tick's metrics step called collectMetrics with git read live: each
ticket's branch was resolved with its own rev-parse, several times over,
and each open branch's reviews listed again and again. On a fleet of ~540
tickets that is thousands of git processes forked from a large node
process per tick (sys-heavy), so observe-metrics ran past its caller's
bound and supervisors skipped it, leaving spend and metrics lines stale.

collectMetrics now runs inside readsAtOneSha, as ack and metrics already
read it; the digest's and the hub cache's nextMoves reads too. Every write
still comes after the caches are dropped.

Fixture, 300 tickets / 150 branches / 30 worktrees / 40 scratch kit
copies in run/: 116-123 s (6.5 s user, 24 s sys) before, 3.6-4.0 s
(0.6 s user, 0.4 s sys) after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A real devteam-dev observe-metrics profile spent ~160 s in workerState,
which filtered the whole log once per ticket. The lines are now grouped by
writer once per read of the log (memo) and looked up.

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

hhff commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

PR #982 review a1: observe-metrics reads at one sha; workerState grouping

  • Reviewer: operator-review-a1 (fresh subagent, Claude Opus 5.5), not the author
  • Head: fe4cca7
  • Date: 2026-12-04 UTC

What I ran vs only read

  • Read: the diff (2 commits), readsAtOneSha, git(), appendLog (drops the log cache on every write), memo/readLog/dropLogCache, withLogAt (swaps logCache for a new object, so the new memo follows it), observeFindings, cmdObserveMetrics, collectMetrics (all of it, looking for writes), nextMoves (memoised per log read, no writes), writeStuckDigest/keepStuckDigest, writeMovesCache/movesReadAt, and the other readsAtOneSha callers (ack, goal).
  • Ordering in cmdObserveMetrics: phase 1 (collectMetrics(0)) returns before observeFindings appends anything. Phase 2 (nextMoves) returns before keepStuckDigest, which refolds the log under its lock before it writes. Phase 3 runs after tidyFinishedWorktrees and dropLogCache. In writeMovesCache(readsAtOneSha(() => nextMoves())), the default at = movesReadAt() is evaluated after the moves, on the same log read, which is the same order as before. Each phase uses a fresh gitReadCache and reviewMemo. refCommits, landingsMemo and treeIndexes are keyed on the cache's identity, so nothing git-derived carries from one phase into the next.
  • test/reads-at-a-sha.test.mjs at head: 7/7 pass (405 s).
  • Probe, another fixture shape (a scratch test in my clone, through the harness, hub port pointed away). Ten tickets: one branch deleted, one branch only on origin, one branch ahead of origin with a CHANGES code review, one merged ticket whose branch moved on after the merge, and worker phase lines (build, merging, blocked, done). I ran observe-metrics live (DEVTEAM_TEST_LIVE_READS=1) and at one sha under a frozen clock. Identical: stdout, stderr, every log file line for line, run/cache/next-moves.json and run/cache/unattended.json byte for byte. Both observation writes were traced read cache off. Git calls: 227 live, 88 at one sha. A second tick on the resulting state (the dedup path) was also identical. 1/1 pass.
  • Timings probe (20 tickets with the same shapes, live and one sha run alternately, box under load at nice 19): live 79.2 s / 71.9 s with 377-378 git calls; one sha 24.3 s / 39.6 s with 113 git calls. The direction holds (about 3.3x fewer git calls, 2-3x less wall time). I could not reproduce the 300-ticket table: a 56-ticket fixture did not finish building within the 600 s file timeout on this box.
  • workerState grouping: I checked the Map grouping against lines.filter((l) => l.by === id) on 2,000 random logs (writers include undefined, '', __proto__, constructor and absent ids): 0 mismatches in elements or order. Nothing mutates the shared arrays: workerState only uses filter, map and [...], and there are 13 call sites, all through workerState. No code assigns, splices or sorts readLog().lines in place. The memo is per log read, so it is invalidated by every appendLog and by withLogAt.
  • Mutation M1: I removed the collectMetrics wrap. reads-at-a-sha went red: subtest 5, "no ticket ref asked one at a time" (5 pass, 2 fail). Restored.
  • test/next-moves-findings.test.mjs: timed out at 600 s locally under box load (memory working set at 40 G), with no failure reported before the timeout. CI's test job, which includes it, is green at the head.
  • CI at head: test success, box-image success.

Findings

Id Severity Rule Where Finding
F1 Minor quality.md §1 (docs/claims agree with code) PR body "Every write ... happens after the caches are dropped"; collectMetrics (writeMovesCache(moves), unattendedHigh(..., { record: !since })) collectMetrics(0) itself writes run/cache/next-moves.json, high-seen.json and unattended.json while phase 1's cache is on. The test's trace covers only appendLog, so it can't see these. This does no harm: the values come from one consistent read seconds old, ack already does the same, the moves cache is rewritten last from a fresh phase, and my probe found both files byte-identical to the live run. The claim should say "every log write".

Notes

  • Mutation M2 (not run): replacing the third wrap with plain writeMovesCache() is caught only by next-moves-findings' source-shape assertion, not by a behavioural test. That is acceptable for a pure CPU path.
  • The workerState grouping has no test of its own (the PR says so). My randomized equivalence check is above.
  • Staleness and races: the read phases are now seconds long where they used to take minutes. A ref moved, a branch deleted, an ack or a question asked during the run is seen exactly as live reads would see it at the start of the phase. Live reads could also mix answers from different moments within one run, so the one-sha read is the more consistent of the two. Ack filtering and observation dedup read the log, which this PR does not cache. I found no new race.
  • No governance surface: no authority or owner-only rule is touched.

Opened by the box operator.

Verdict: APPROVE fe4cca7

No textual conflicts. log-unsynced's git log -1 of origin/chore-log and
observe-metrics-overdue's byType/span reads run inside collectMetrics'
readsAtOneSha phase: cached once each, nothing in the phase moves that
ref, and neither finding writes the log.

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

hhff commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Merged origin/main (8cb127d, which includes #980 observe-metrics-overdue, #984 and #983 log-unsynced) into this branch as a1e391b. This was a merge, with no rebase and no force-push.

Conflicts: none in the text. I still checked how main's new code behaves inside this PR's read phases:

  • log-unsynced (logUnsynced, called from collectMetrics, which observe-metrics now runs inside readsAtOneSha): its git log -1 --format=%ct%x00%s refs/remotes/origin/chore-log is a GIT_READS call, so it is asked once per phase and then cached. Nothing in the phase fetches or moves that ref. The tick's fetches (fetchLinkPrs and the links' fetch) and log-sync all run outside it, so the cached answer is the ref as the tick left it. Its per-file tails come from readLog(), whose cache is separate from gitReadCache and is dropped by every appendLog.
  • observe-metrics-overdue (observeMetricsOverdue): it reads only readLog()'s byType and span, no git. observeSpend and writeLearning write before the phase starts, and those writes drop the fold, so the phase sees the spend lines this tick just wrote.
  • Writes: neither finding writes the log. The log writes that follow (observeFindings, the digest) still happen after the phase ends. metrics: log-unsynced, said on every wait report #983's cmdWait changes only print the findings; wait gets metrics from a read-only child process, which this PR doesn't touch.
  • linesOfWriter (this PR) memoizes on the fold, so the new tails/span fields don't affect it.

PR body: following the approval's Minor, "Every write" is now "Every log write". The body also says that collectMetrics' own cache files are still written inside the phase.

Tests (node test/run.mjs, local, DEVTEAM_BOX=off): reads-at-a-sha 7/7, next-moves-findings 10/10, observe-metrics-overdue 9/9, log-unsynced 5/5, every-report-findings 42/42. All pass.

Opened by the box operator.

Conflict in test/next-moves-findings.test.mjs: kit-1202 moved A9-A12 to
test/next-moves-findings.output.test.mjs and its siblings. Took main's
side, and carried this PR's one change there: the source-shape
assertion on cmdObserveMetrics' last statements expects
writeMovesCache(readsAtOneSha(() => nextMoves())). devteam.mjs had no
change on main since the last merge.

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

hhff commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Merged origin/main again (2f5dd15, which includes #988 kit-1202) into this branch as 8b3662a. This was a merge, with no rebase and no force-push.

Conflict: test/next-moves-findings.test.mjs. kit-1202 moved A9–A12 out of this file and into test/next-moves-findings.output.test.mjs and its sibling files. I took main's side, so the file now matches main exactly. I then carried this PR's one test change to where that test now lives: the A12 source-shape assertion on cmdObserveMetrics' last statements in next-moves-findings.output.test.mjs now expects writeMovesCache(readsAtOneSha(() => nextMoves())). devteam.mjs had no changes on main since the last merge, so the three readsAtOneSha phases and the read/write analysis in my earlier comment still hold.

CI at a1e391b: the 3 failures were the known flaky browser e2e tests, not this PR. kit (24, chrome 4/5) failed in project-hosts-e2e, kit (24, chrome 5/5) failed in dashboard-loop (a peek-hash timeout), and tests is the aggregate check (run 47343593240).

Tests (local, DEVTEAM_BOX=off): reads-at-a-sha 7/7, next-moves-findings 9/9, next-moves-findings.output 10/10, observe-metrics-overdue 10/10, log-unsynced 9/9, every-report-findings 5/5. All pass.

Opened by the box operator.

@hhff

hhff commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

PR #982 review d1: delta since APPROVE at fe4cca7 (two main merges: #980, #983, #984, #988)

  • Reviewer: operator-review-d1 (fresh subagent, Claude Opus 5.5), not the author
  • Head: 8b3662a
  • Date: 2026-12-04 UTC

What I ran vs only read

Ran, in a scratch clone at the head with DEVTEAM_HUB_PORT set to an unused port, DEVTEAM_BOX=off and DEVTEAM_IMAGE_HUB unset, using testslot nice -n 19 node test/run.mjs:

  • test/reads-at-a-sha.test.mjs: 7/7 pass
  • test/next-moves-findings.output.test.mjs: 10/10 pass. kit-1202-upkeep-files-split: upkeep, next-moves and plain-words test files: none over 60 s, no test over 30 s #988 moved A12 here, and this PR's changed assertion moved with it.
  • test/next-moves-findings.test.mjs: 9/9 pass
  • test/observe-metrics-overdue.test.mjs: 10/10 pass
  • test/log-unsynced.test.mjs: 9/9 pass
  • test/every-report-findings.test.mjs: 5/5 pass
  • Mutation: changed observeFindings(readsAtOneSha(() => collectMetrics(0))) back to observeFindings(collectMetrics(0)). reads-at-a-sha went RED: 2 fail, subtest 5 failed with "no ticket ref asked one at a time". Restored afterwards, and git status shows the tree clean.

Read only:

  • PR diff unchanged. I compared the PR diff against main at fe4cca7's merge base (2649d82) with the diff at the head. Ignoring index and hunk lines they are identical, except that the test file moved from next-moves-findings.test.mjs to next-moves-findings.output.test.mjs (the kit-1202-upkeep-files-split: upkeep, next-moves and plain-words test files: none over 60 s, no test over 30 s #988 split). The devteam.mjs hunks (linesOfWriter, the three readsAtOneSha wraps in cmdObserveMetrics) are byte-identical. kit-1202-upkeep-files-split: upkeep, next-moves and plain-words test files: none over 60 s, no test over 30 s #988 changed no file under docs/, so no function moved out of devteam.mjs, and the wraps and calls are as intended.
  • logUnsynced inside the cached collectMetrics. readsAtOneSha creates a fresh gitReadCache when it starts and sets it to null in finally. Nothing outside the call primes or keeps it. In cmdObserveMetrics:
    • fetchLinkMains, probeLinks, fetchLinkPrs, observeSpend and writeLearning all run before the first cache exists.
    • observeFindings' appendLog calls run after that cache is dropped.
    • The digest's moves and the hub's moves cache each get a new cache.
    • So git log -1 refs/remotes/origin/chore-log always reads the ref as this run's fetch left it. observe-metrics never runs log-sync or pushes, so nothing moves that ref inside a read phase.
    • No log write runs on cached reads. The test's "no write with a cache on" check also passes.
  • observeMetricsOverdue reads only the fold (byType, span), with no git.
  • foldLog gets its tails and span from the lines. Its prefetchAt(mainSha()) is keyed by full sha (immutable). mainSha runs inside a fresh cache, so it sees the post-fetch main.
  • CI at the head: box-image succeeded; test is still queued.

Findings

Findings: none.

Notes

  • Minor (pre-existing, not from this delta): inside a read phase, logUnsynced's tip read and the rest of collectMetrics answer as of the phase start. That is the intended readsAtOneSha semantics, and nothing in the phase writes.
  • I could not check CI's test job, which is still queued.

Opened by the box operator.

Verdict: APPROVE 8b3662a

@hhff

hhff commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

PR #982 review d2: delta since APPROVE at 8b3662a

  • Reviewer: operator-review-d2 (fresh subagent, Opus 5.5), not the author
  • Head: 6effc7a
  • Date: 2026-12-05T13:16Z

Delta review. The last approval was d1, APPROVE 8b3662af7ca6bc81bd7da618e61b39ff57eb12a9. The head 6effc7a is a merge with two parents: 8b3662a and origin/main at 37ce3e9 (#997).

What I ran vs only read

  • (1) Merge redone. I checked out 8b3662a and ran git merge 37ce3e96. Only docs/devteam/scripts/devteam.mjs needed an auto-merge, and git resolved it without conflicts. My merge's tree is 26a0ac356cb26a0ddee06b1a6086d93eb5da39bd, the same tree as 6effc7a's. The merge commit carries no hidden edit.

  • (2) The PR's own diff. I compared git diff 2f5dd15e 8b3662af (the approved diff against its old base) with git diff 37ce3e96 6effc7a6 (the diff against main now). Leaving out the index/@@ lines, they are the same. Three files change: devteam.mjs (linesOfWriter memo in workerState, and readsAtOneSha wrapping the findings, the digest's moves and writeMovesCache in cmdObserveMetrics), test/next-moves-findings.output.test.mjs and test/reads-at-a-sha.test.mjs.

  • (3) Main since the old base (2f5dd15..37ce3e9, 23 merges). devteam.mjs is the only engine file that changed. Its hunks touch:

    • parseReview (new proofCites)
    • verdictHolds, checkTicket and checkPr (test-proof cites, forge option)
    • the new test-proof command and its helpers (proofProblem, proofVerdict, codeSince*, showBytes)
    • cdpBrowser/browserLoad test timeouts
    • help text and the command table

    None of them touch readsAtOneSha, memo, readLog/dropLogCache, workerState, collectMetrics, observeFindings, nextMoves, writeStuckDigest, writeMovesCache or cmdObserveMetrics. On the PR's paths:

    • checkTicket and proofVerdict are reached only from check-ticket, check-pr and test-proof. Neither collectMetrics nor nextMoves calls them.
    • verdictHolds's other caller (cmdValidate, ${projectRel}/reviews/) never matches the new proof path (proofOf needs tickets/<id>/reviews/).
    • The new gate lines (proof, proof_cmd, tests: []) are only appended by test-proof. The PR's per-writer grouping (linesOfWriter) keeps every line of each writer, so they reach workerState as before.
    • No new metrics finding, field or caller sits outside the PR's fast path, and nothing new writes under the read caches.
    • Main did not change the PR's test files (reads-at-a-sha, next-moves-findings.output, observe-metrics-overdue). From the test/lib split, only test/lib/kit.mjs gained fixtureRun bounding in bareProject/peekFixture/inboxFixture. That bounds the same commands and has no semantic effect on these tests.
  • (4) Tests at the head, one file at a time via testslot, with the hub port moved off the real hub and DEVTEAM_IMAGE_HUB unset:

    File Result
    test/reads-at-a-sha.test.mjs 7/7 pass
    test/next-moves-findings.output.test.mjs 10/10 pass
    test/observe-metrics-overdue.test.mjs 10/10 pass
  • Mutation. I reverted observeFindings(readsAtOneSha(() => collectMetrics(0))) to the live observeFindings(collectMetrics(0)). reads-at-a-sha went red: 5 pass, 2 fail. I restored the line afterwards.

  • (5) CI at 6effc7a. box-image passed. On attempt 1, test failed on one shard only, kit (18, rest 8/8). The cause was test/gateway-grant.test.mjs timing out at 120 s after its last subtest (C17); test/timings.json fits that file at 3.4 s. The same file passed on Node 20, 22 and 24. It tests gateway OAuth grants and goes nowhere near workerState or observe-metrics, so I judged it an unrelated Node 18 hang. I reran it once (gh run rerun 47516355250 --failed). Attempt 2: test passed. Run 47516355250 is green at the head.

Findings

Findings: none.

Notes

  • I did not repeat d1's full review of the PR's logic. The PR's diff is byte-identical to the one d1 approved, so this review only covers what changed since.
  • The Node 18 gateway-grant hang is a flake candidate worth tracking apart from this PR.

Opened by the box operator.

Verdict: APPROVE 6effc7a

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