Repository navigation
perf(gateway): reuse prepared assistant identities and avatars - #158597
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 26, 2026, 8:04 AM ET / 12:04 UTC (Revision 16). ClawSweeper reviewWhat this changesThe branch moves agent identity and avatar preparation into workers, reuses prepared results, and updates Gateway, CLI, search, and export callers. Merge readiness⛔ Blocked before merge - 3 items remain Keep open. The optimization is still absent from current main, but unscoped session search still prepares identities for configured agents that have no candidate sessions. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway reads agent configuration and workspace identity files to serve names and avatars to Control UI and other clients. Session search uses those names when selecting session rows. flowchart LR
A[Agent config and workspace files] --> B[File workers]
B --> C[Prepared identities and avatars]
C --> D[Gateway responses]
D --> E[Control UI and clients]
F[Candidate sessions] --> G[Search selection]
C --> G
G --> D
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +442, Tests +446. Total +888 across 41 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Derive search identity preparation from candidate session targets while retaining scoped-agent behavior, current name matching, and the synchronous Plugin SDK contract. Do we have a high-confidence way to reproduce the issue? Yes, by source inspection: configure agents with no sessions, run an unscoped session search, and observe identity preparation for those unused agents. I did not execute that scenario in this read-only review. Is this the best way to solve the issue? The worker-owned avatar preparation is a sound fit. The search addition needs candidate-based admission so a small result set does not wait on an unrelated roster. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against e4515f17ce1e. LabelsLabel changes: No label changes. Label justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (15 earlier review cycles; latest 8 shown)
|
Keep Control UI bootstrap and agent listing available when optional identity or avatar worker preparation rejects. Preserve explicit identity-file errors, add entrypoint regressions, and remove redundant deferred generic arguments reported by CI.
Keep the resident-row no-yield fixture independent of intentional worker file admission. Preserve all selection, no-yield, and row-read assertions; real identity-file freshness remains covered by the search suite.
Resolve the Control UI import overlap after both branches retired the synchronous descriptor paths. Preserve the worker-backed avatar flow and current main static-file serving.
Keep the real equal-size rewrite and restored mtime while explicitly advancing the admitted descriptor ctime. This removes filesystem tick timing from the cache invalidation assertion without weakening body, identity, or replacement checks.
Incorporate the immutable main parent from CI run 36234168110 without rebasing. The merged source matches that CI checkout exactly; its original 22-file Gateway server group passes all 273 tests locally. This replay does not establish a fix for the unreproduced state-directory probe failure.
Retain at most three exact state-root probe stacks in the existing performance assertion. Preserve the real filesystem calls, count comparisons, and cleanup. CI observed 56 probes versus zero, but exact merged-source shard replay did not reproduce it; diagnostics preserve that uncertainty without adding a speculative workaround.
Keep main’s temporary-directory helper and migrated callers while retaining worker-kernel ownership of avatar descriptor and growth proof. Focused HTTP/avatar tests, targeted types and lint pass; fresh review of the merged candidate is clean through P2.
Include the verified main repair for scenario references to the retired QA channel forwarding barrel. The combined catalog suite passes all 56 tests. The PR delta retains the same stable patch ID as the previously reviewed candidate.
|
Merged via squash.
|
…law#158597) * perf(gateway): prepare assistant identities and avatar responses * test(agents): type avatar rejection cases as fixed pairs * test(gateway): assert the shared avatar response ETag * fix(agents): preserve optional identity reads on worker failure Keep Control UI bootstrap and agent listing available when optional identity or avatar worker preparation rejects. Preserve explicit identity-file errors, add entrypoint regressions, and remove redundant deferred generic arguments reported by CI. * test(gateway): prepare identity input for resident row proof Keep the resident-row no-yield fixture independent of intentional worker file admission. Preserve all selection, no-yield, and row-read assertions; real identity-file freshness remains covered by the search suite. * test(ui): import retained asset root state from its owner * fix(agents): retain explicit identity overflow diagnostics * test(gateway): observe worker-backed bootstrap identity reads * test(gateway): pause prepared avatars for authority checks * test(agents): control avatar cache ctime invalidation fixture Keep the real equal-size rewrite and restored mtime while explicitly advancing the admitted descriptor ctime. This removes filesystem tick timing from the cache invalidation assertion without weakening body, identity, or replacement checks. * test(gateway): capture state-directory probe failure provenance Retain at most three exact state-root probe stacks in the existing performance assertion. Preserve the real filesystem calls, count comparisons, and cleanup. CI observed 56 probes versus zero, but exact merged-source shard replay did not reproduce it; diagnostics preserve that uncertainty without adding a speculative workaround.
What Problem This Solves
Many browsers loading assistant identities and avatars can repeatedly block the Gateway thread on file admission, large identity parsing, and duplicate image work.
User Impact
Control UI bootstrap, agent rosters, and avatar responses reuse prepared content while file edits, atomic replacements, config changes, authentication, and native inline-avatar responses retain their existing behavior. There are no Gateway protocol, configuration, or database schema changes. The shipped synchronous avatar SDK contract remains synchronous.
Why This Change Was Made
The identity-file and local-avatar owners now acquire files in workers and retain bounded snapshots after fresh admission. URL projection and thumbnail delivery carry the same prepared revision. Descriptor custody, containment, hardlink rejection, size bounds, and cleanup stay with the file owner. Internal Gateway, CLI, search, and export callers use the asynchronous acquisition path.
Channel-avatar cold misses share one load, and an older completion cannot replace the current image. Thumbnail jobs remain coalesced while pending, independently of the four-entry completed-image cache. A deferred eviction test also protects the local avatar cache's byte accounting.
Evidence
Three paired runs of 100 warm conditional requests through the avatar handler, using the same 2,787,170-byte synthetic identity file, 2,090,343-byte PNG, and 27,773-byte thumbnail:
The CPU reduction is 91.5%. These are warmed synthetic handler measurements on a contended shared host, comparing the built baseline with the candidate source. Worker startup and network transport are excluded. Six overlapping thumbnail requests for five sources performed six decodes before and five after; the duplicate now reuses the same result. The channel HTTP regression verifies ten overlapping GET/HEAD requests share one media read.
node scripts/run-vitest.mjs src/agents/identity-file.test.ts src/gateway/assistant-identity.test.ts src/gateway/assistant-avatar.test.ts src/gateway/assistant-avatar-http.test.ts src/gateway/channel-avatar-http.test.ts src/gateway/session-utils.search.test.ts src/commands/agents.test.ts --maxWorkers=1, 1,180.68 seconds wall. Transformation and worker preparation dominated this host's runtime.control-ui.http.test.ts,server-methods/agent.test.ts, andclaws/export.test.ts, filtered to avatar/identity/bootstrap/export behavior). The unrelated 453 Gateway cases were intentionally excluded. Final channel-avatar and chat-reply-context proof: 31 tests passed in 263.07 seconds wall, including the shared-ETag assertion and assistant reply labels.pnpm buildpassed on Blacksmith Testbox in 534.12 seconds after a frozen-lockfile install (providerblacksmith-testbox, leasetbx_01m3dnfaxz1z7kn0q6bnb3s3xh, lease run). It emitted a non-blocking Control UI startup-JS budget warning (362.7 KiB versus 362.6 KiB); no UI source changed.d76ba3ca38378c4fadfe53e0445ad7216b60726b.The open-PR overlap scan found shared files with #158567 (upload controls), #158548 (playback metadata), #158464 (static serving), #158443 (worker registry), #158378 (identity parser cleanup), and #158310 (Claw export). The identity parser cleanup was reconciled with the new acquisition kernel during landing, preserving its nullable parser result and the worker-backed read path.
Landing corrections and proof
Exact-head CI run 36213123921 found three redundant
createDeferred<void>()type arguments in the avatar fixtures (typescript/no-unnecessary-type-arguments); these now use the helper's existingvoiddefault. The failed lint job caused the remaining run to be cancelled; it was not rerun to seek a green result.The completed ClawSweeper review also found that worker admission or availability failures could escape optional workspace identity and avatar reads. Workspace presentation now treats failed identity preparation as absent; the shared local-avatar acquisition owner returns the existing
unreadableresult, preserving the Gateway, CLI, and export fallback behavior. Explicit identity-file reads continue to report errors. This resolves both reported review findings without changing the worker pool or adding caller-specific fallbacks.The two authenticated bootstrap failure cases and the agent-list JSON failure case were each observed failing on the original implementation with the injected worker error, then passing after the repair. The bootstrap proof also exercised 29 existing cases (31 total, 53.44 seconds Vitest wall including cold worker compilation); the focused CLI regression took 4.43 seconds. The full CLI-list file passed 15 tests with its existing one skipped test in 16.36 seconds; identity/avatar owner coverage passed 26 tests across two files in 8.46 seconds. The latter combined wrapper command took 29.68 seconds wall. Focused lint passed in 32.96 seconds, formatting and
git diff --checkpassed, and isolated Codex review of the corrections is scoped-clean through P2. Hosted CI remains the complete exact-head gate.The next exact-head run, 36214689007 at
80c49b4ed12f0fae5ea4d1097c9f5b46b15d71a9, found two deterministic failures insession-utils.perf.test.ts. Its synthetic resident-row fixture did not supply the new identity-admission dependency, so intentional worker I/O triggered the fixture's no-yield assertion before row selection. Both failures reproduced locally. The test now supplies a completed missing-identity snapshot at that dependency, scoped and restored within the test; every existing no-yield, zero row-read, zero charged-work, and output assertion is retained. Production search still freshly admits the real workspace identity. The full performance and search suites passed together (37 tests; 69.11 seconds wrapper wall, 61.42 seconds Vitest wall), including atomic identity-file replacement between searches. Focused lint passed in 31.73 seconds; isolated Codex review is scoped-clean through P2. Source and fixture failures were not retried without corresponding verified corrections.During CI for
674ff94775c32e2d99323941462063fae0742c56, main advanced with the Control UI static-file worker change and GitHub reported a content conflict. Current main was merged into the PR (no rebase). The sole conflict was a now-unused file-reader import block; both the prepared avatar path and main's static-file path are retained. Focused merged-source verification passed all 189 tests acrosscontrol-ui.http.test.ts,assistant-avatar-http.test.ts, andassistant-avatar.test.ts(275.67 seconds wrapper wall; 234.70 seconds Vitest wall, dominated by transformation). Control UI lint andgit diff --checkpassed, and independent review of the complete PR diff against merged main is scoped-clean through P2.CI run 36216841560 exposed a missed main-side type consumer migration:
control-ui-retained-assets.e2e.test.tsstill importedControlUiRootStatefromcontrol-ui.tsafter main moved the type toserver-control-ui-root.ts. The same stale import was present on current main; main's latest recorded CI run 36217288599 was successful rather than evidence of a known red-main check. The test now imports the type from its owner, without a compatibility re-export or runtime/assertion changes. The focusedcore-test-ui-e2egraph reproduced TS2459 before the fix (30.41 seconds wall) and passed after it (10.17 seconds wall); formatting, whitespace validation, and independent P2 review passed.CI run 36217992246 found an explicit-file CLI diagnostic regression: the worker snapshot retained the oversized-file classification but the caller discarded the nested filesystem error, removing the
File exceeds ...diagnostic andtoo-largecode from both human and JSON errors. The caller now reconstructs the typedFsSafeErrorcause from the known overflow result while preserving the outer identity-file message and optional workspace fallback. The existing CLI regression failed locally before the repair without assertion changes. The full identity-command suite (23 tests, 66.57 seconds Vitest wall) and identity-file suite (16 tests, 10.64 seconds) then passed; combined wrapper wall was 100.60 seconds, dominated by worker preparation. Focused lint, formatting, whitespace validation, and independent P2 review passed.CI run 36219089079 exposed one HTTP test still observing workspace identity reads via main-thread
realpathSync. Bootstrap already returned the correct real identity; the assertion contradicted the intentional worker migration. The failure reproduced locally. The test now observes the actualprepareIdentityFilecall without stubbing it, verifies static routes skip that work, and requires zero main-thread identity filesystem calls for bootstrap as well as static routes. All HTTP and identity response assertions remain. The complete file passed 10 tests (26.93 seconds wrapper wall, 18.99 seconds Vitest wall), with focused lint and independent P2 review clean. A bounded review of other identity/avatar test callers found no additional concrete missed async migrations.CI run 36220112920 failed the filesystem import-boundary guard on a newer main-side ACPX migration (
ccaeab168629, #158551), which was absent from the PR head but included in its test merge. The defect reproduced on isolated main63f1dec2b57e6883b65eaa108cd287bd29d6d551. Main repair9d5ab59b5af88ccfac7af258a5a872caee5eeaf5switches that one import to the existing public SDK export; no allowlist, baseline, test assertion, or migration logic changes. It passed 23 boundary tests, 14 ACPX migration tests, formatting, whitespace validation, and independent review before direct main publication. The repair was merged into this PR. Combined-tree proof passed 49 boundary/HTTP/identity tests in 59.27 seconds wrapper wall, and fresh review of the complete PR diff against merged main is scoped-clean through P2.CI run 36221832093 then found a newer main-side chained assertion in progress snapshot coercion. Clean main reproduced the guard failure. Main fix
66b812f26e725cd709e08860d2cb46ba496cd308(published through merge007822d8693cb8d9474e7df773610123e1da1e02after a concurrent-main push rejection) uses a native Reflect invocation without asserting a boxed value is already primitive. It preserves JSON ToNumber semantics, including custom hooks and BigInt rejection, and passed both lint guards, core types, 47 existing progress/history-budget tests, and independent review. The repair was merged into this PR without conflicts; all 207 HTTP/progress tests passed in 54.75 seconds wrapper wall. The PR delta's stable patch ID is unchanged from the preceding reviewed candidate, so its completed P2 review remains valid across this mechanical merge.CI run 36223037178 passed the Node counterpart (1,056 tests) before the pinned Bun 1.4.3 canary build segfaulted during worker startup, before its tests ran (SIGSEGV at address 0x2, 514 ms elapsed, 0.44 GiB peak RSS with ample free memory). A single exact-job diagnostic replay on the same head and runtime passed as attempt 2 on the workflow-selected GitHub Ubuntu fallback runner (21 minutes). This demonstrates that the startup crash did not repeat; it is not a claim that the native runtime bug was fixed. The 82 jobs cancelled after the original crash were resumed through the failed/cancelled-jobs recovery path, with source and runtime pins unchanged.
Attempt 3's sole underlying failure was a stale response-authority fixture: avatar and thumbnail cases waited for the retired descriptor reader and timed out, cancelling the remaining jobs. The avatar timeout reproduced locally. The fixture now wraps real local-avatar preparation, asserts that the expected PNG bytes were successfully prepared before pausing, and preserves every 401/no-bytes/no-image-header/no-cookie assertion after authority changes. It also detects an early completed response and always releases and joins the pending handler, so a missing pause fails promptly rather than hanging. All four authority cases passed in 51.53 seconds wrapper wall (44.84 seconds Vitest wall; 6% test execution), with unchanged timeouts, clean lint/formatting, and independent review clean through P2 after closing the prepared-bytes proof gap.
While CI run 36227074145 was pending, main #158378 introduced the anticipated identity-parser conflict. Main was merged without rebasing. Its nullable parser and writer simplifications remain; the worker snapshot now stores the parser result directly instead of restoring the retired identityHasValues helper. Prepared reads, descriptor custody, overflow diagnostics, and the synchronous SDK contract remain intact. After reconciling current main's frozen dependencies, all 79 focused identity/avatar/CLI/search tests passed in 141.60 seconds wrapper wall, lint and whitespace checks passed, and fresh review of the full candidate is scoped-clean through P2.
CI run 36228419186 hit the already-observed main fixture race in
server.sessions.archive-failed-worker.test.ts: synchronous fixture close starts asynchronous worker retirement, and reopening can hit the correct closing-admission guard. The original 22-file shard replay passed 273 tests in 250.26 seconds; that passing replay is not evidence of a fix. Main owner fix6c7544adc9826fa637425a2fa967389e0507a800explicitly awaits retirement before the scoped reset/reopen and also repairs cleanup teardown. It was merged here without changing the PR patch ID. The combined archive/cleanup proof passed all 11 tests in 324.13 seconds wrapper wall (cold worker preparation and host contention dominated); no production guard, schema, timeout, or assertion was weakened. The owner's reviewed main repair and its wider evidence are recorded in that commit.CI run 36230423580 found three newly introduced main-side Codex filesystem imports outside the approved dependency surface. Existing main fix
f2532a051f7a2c73731f7725184bff33b3b14f1froutes those error checks through the public error-runtime SDK while preserving ENOENT/ENOTDIR handling; it changes no allowlist. Its commit records Linux reproduction, 243 focused checks, build/changed gates, and P2 review. The patch and SDK equivalence were inspected, including maintained Codex marketplace source. After merging it, the PR patch ID remains unchanged and the exact import-boundary test independently passes all 23 cases (132.28 seconds wrapper wall on the contended host).CI run 36232223693 found a filesystem-timing assumption in the avatar fixture: it rewrote equal-length bytes and restored mtime without ensuring ctime changed. Holding the admitted descriptor's ctime constant reproduced the exact stale-byte assertion locally; the CI log itself did not print the stat tuple, so a coarse timestamp tick is the supported diagnosis rather than directly captured runner telemetry. The fixture now controls only ctime for the original device/inode, forwards all fstat options unchanged, and retains real writes, reads, and the modified-body assertion. It also verifies unchanged device, inode, mtime, and size. No timers, retries, relaxed assertions, or production changes were added. All 18 avatar-owner and sibling tests passed in 10.30 seconds wrapper wall (6.86 seconds Vitest wall); the failed CI case took 0.005 seconds, and the cache-budget sibling accounted for 3.672 seconds. Independent review is scoped-clean through P2.
Freshness limitation: the shipped Gateway avatar cache already used path/device/inode/size/mtime/ctime as its revision. A rewrite preserving that entire tuple is not detected; this PR shares that existing metadata contract with CLI readers. The repaired test proves ctime invalidation, not content-hash freshness.
The focused
check-changedrun for this fixture passed, including the affected core-test type graph, lint, formatting, guards, and all three unused-export scans. The rest of the PR retains its previously recorded hosted/build proof; the new pushed head is gated again by hosted CI.CI run 36234168110 at head
7e0caf57204c57f2bc56c41824458a5906801804failed the conventional state-directory reuse assertion inserver.sessions.store-paths.test.ts: automatic-runtime search made 56 state-root existence checks while the pinned-runtime path made zero. Final job metadata identifieschecks-node-compact-small-15as the underlying failed shard; the extension shard was cancelled. The dependency-review status briefly said security review was incomplete, then succeeded four seconds later in the same workflow; no retry was requested.This failure remains unexplained after bounded investigation. The standalone case, complete owning file, and original 22-file/two-worker shared Gateway-server group passed locally. The first attempted broad replay used the aggregate local selector and was stopped after 445.47 seconds; it was replaced with the exact group recovered from CI's recorded plan. The exact group passed all 273 tests in 387.66 seconds. CI tested merge
1f9e5a48c15191e93643400cc7a28e07a4441f63, incorporating main90869ccd9cfb36461a85a87f2cfd04a2714c320b. That immutable main parent was merged here without rebasing; the combined tree matched CI's source exactly, and its original group again passed all 273 tests in 251.77 seconds. No matching state-root probes were observed during these local runs. The automatic-auth path preserves its prepared state environment; background catalog or startup work remains a possible but unproven cause. Passing replays are not evidence of a fix.The existing assertion now retains at most three exact state-root call stacks, labeled by search/runtime branch, in its failure message. Real filesystem calls, count comparisons, cleanup, and timeouts are unchanged; no production workaround or assertion relaxation was added. The final owning file passed all 10 tests in 34.77 seconds wrapper wall (32.47 seconds Vitest wall); CI's original failing case took 4.736 seconds. Independent review is scoped-clean through P2. This unresolved failure and the earlier native Bun startup crash remain explicit limitations, with landing still subject to the normal exact-head CI and native gates.
Targeted Gateway-server test types, lint, formatting, and whitespace validation passed for the diagnostic change. Hosted CI remains the full candidate gate.
Exact-head CI run 36236553886 completed successfully for
cb4f9da10bc609a6d2526af5bec5a6de15ef42ae. Native preparation passed, but merge admission stopped before dispatch because main advanced with2bdf8709fce5and conflicted incontrol-ui.http.test.ts. The tool confirmed no merge request or outcome existed; its exact retained lock was recovered after verifying no child tools remained. Current main was merged without rebasing. The resolution preserves main's tracked temporary-directory helper and migrated callers, while preserving this PR's retirement of obsolete main-thread avatar-read fixtures; byte-free metadata admission, bounded growth and descriptor cleanup remain covered by the worker file-owner tests. All 153 focused HTTP/avatar tests passed in 132.90 seconds wrapper wall, targeted Gateway test types and lint passed, and fresh independent review of the full merged candidate is clean through P2. The new head requires fresh hosted CI before native landing is repeated.CI run 36238633476 failed the QA scenario catalog after main's
eaf8d916f7faremoved a private forwarding barrel. Two scenario YAML files still referencedextensions/qa-channel/src/protocol.tsinstead of its existing SDK owner. The exact catalog assertion reproduced on isolated clean main (55 passed, 1 failed); main repair18b0130a21b9b9aa6856b419ca0d22897f960c25changes only those two references tosrc/plugin-sdk/qa-channel-protocol.ts. All 56 tests then passed, formatting and independent P2 review were clean, and the repair was published directly to main after reconciling a concurrent-main push rejection. No test assertion or scenario behavior changed. After merging the repair here without rebasing, all 56 catalog tests independently pass in 3.97 seconds wrapper wall. The PR delta's stable patch ID is unchanged from the preceding reviewed candidate, so that review remains valid. The failed run was not rerun; the corrected new head starts fresh CI.