Repository navigation
perf(acp): avoid full-session scans when resuming - #165550
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 October 5, 2026, 10:19 AM ET / 14:19 UTC (Revision 6). ClawSweeper reviewWhat this changesACP, OpenClaw’s external-agent session subsystem, replaces full-session resume scans with indexed worker lookups while preserving canonical ownership checks. Merge readiness⛔ Blocked before merge - 3 items remain The optimization remains useful on current main, and no introduced correctness defect was found. The prior review’s persistent-index acceptance question remains unresolved. Priority: P2 Review scores
Verification
How this fits togetherACP spawn receives a resume identifier and requester context, locates the recorded session, and verifies requester ownership. That decision gates external-agent initialization. flowchart TD
A[Resume request] --> B[Indexed metadata worker]
B --> C[Matching session candidates]
C --> D[Canonical session reader]
D --> E[Identity and lifecycle recheck]
E --> F[Requester ownership check]
F --> G[Resume or reject]
Decision needed
Why: Compatibility evidence establishes preserved rows and schema version, but the repository’s storage checkpoint separately requires recorded acceptance of the new persistent representation. Before merge
Agent review detailsSecurityNone. PR surfaceSource +172, Tests +313, Docs +14, Other -1. Total +498 across 17 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep one indexed worker lookup with canonical ownership checks and an accepted storage design covering construction costs, write maintenance, and rollback. Do we have a high-confidence way to reproduce the issue? Yes: missing or late-matching resume IDs traverse retained sessions on current main, and the supplied production-owner benchmark measures that path; this read-only review did not execute it. Is this the best way to solve the issue? Yes: indexed selection through the existing worker and canonical reader removes the scan without creating a competing cache or changing requester policy; storage acceptance remains separate. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e698b96e7480. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
Replace the synchronous session-wide walk with indexed ACP identity selection and canonical worker reads. Preserve backend, requester, ordering, and lifecycle checks, and recheck the selected identity after awaiting its entry. Add same-version indexes through the existing schema owner.
Move ACP list, metadata, and resume dispatch out of the central worker and exercise the production command boundary. Cover resume ID replacement during the canonical entry read.
Reject unresolved metadata aliases and internal-effects records before canonical entry reads, using the existing qualifier and listing predicate. Cover the old-versus-new ownership boundary and finish worker-only naming, lint, and the exact mock-baseline shrink.
Move ACP command, result, and row declarations into the existing read contract so the worker and shared-state protocol share a leaf dependency. Serialized shapes and runtime queries stay unchanged.
c67211c to
f077af4
Compare
* perf(acp): resolve resume ownership with indexed worker reads Replace the synchronous session-wide walk with indexed ACP identity selection and canonical worker reads. Preserve backend, requester, ordering, and lifecycle checks, and recheck the selected identity after awaiting its entry. Add same-version indexes through the existing schema owner. * fix(acp): keep metadata read dispatch in its owner Move ACP list, metadata, and resume dispatch out of the central worker and exercise the production command boundary. Cover resume ID replacement during the canonical entry read. * fix(acp): preserve canonical resume lookup eligibility Reject unresolved metadata aliases and internal-effects records before canonical entry reads, using the existing qualifier and listing predicate. Cover the old-versus-new ownership boundary and finish worker-only naming, lint, and the exact mock-baseline shrink. * fix(acp): remove the worker protocol import cycle Move ACP command, result, and row declarations into the existing read contract so the worker and shared-state protocol share a leaf dependency. Serialized shapes and runtime queries stay unchanged.
What Problem This Solves
Supplying
resumeSessionIdto ACPsessions_spawnsynchronously walks every target-agent session, rereads each canonical entry, and decodes ACP metadata. A missing or late-matching ID blocks the Gateway event loop in proportion to retained session history.User Impact
Resume lookup selects matching IDs in the shared-state worker and reads their canonical entries through the existing session reader. Requester ownership, backend scoping, lifecycle binding, and live caller checks remain enforced. Unknown IDs require one indexed query and no canonical entry reads.
Why This Change Was Made
Replace the full walk with two nonunique expression indexes over the existing agent/ACPX resume IDs and one worker lookup operation. ACP command/result types live with the ACP read contract, so the shared-state protocol and worker both depend on that contract. The indexes preserve historical string trimming and ignore invalid or non-string identities. ACP runtime options and unrelated metadata are not transferred or decoded. The selected ID and lifecycle are rechecked after awaiting the canonical entry.
External IDs are not unique: resumed sessions can record the same ID under several local keys. The existing session-key ordering and first-live-owner decision remain intact. A unique hit reads one canonical entry; duplicate IDs can require additional candidate entry reads to skip stale lifecycles. This is bounded by matching IDs rather than all sessions.
Storage: the existing writable schema owner installs the indexes at the same schema version. Initial construction scans ACP metadata and uses temporary disk; writes maintain both indexes. Canonical rows, retention, durability, and permissions are unchanged. Older same-version builds ignore the additive indexes, preserving binary rollback.
Non-test/docs LOC delta: +171: production +172 (239 additions, 67 deletions), plus a one-line shrink of the mock baseline. Growth is required for the previously missing indexed storage query and worker protocol, plus the asynchronous lifecycle join and current-ID recheck. The old synchronous walk is removed; there is no native fallback or parallel cache.
Evidence
On a synthetic 10,000-node / 10,000-window fixture, the real resume-ownership entry point produced identical results for randomized requests, and the query kernel matched a separate randomized fixture including malformed and non-string IDs.
The final 100-sample measurement follows 30 warmup calls. Hit maximum was 12.68 ms; miss maximum was 3.16 ms. Warm medians meet 5 ms, but hit p95 and the hard 5 ms bound do not. An earlier 100-sample run before the final canonical-key filter measured hit median/p95 3.50/4.85 ms; the final candidate's numbers above are authoritative.
The indexed query alone measured 0.016 ms (hit) / 0.011 ms (miss) median. The owner observer recorded 500,050 host SQLite method calls across ten old hit lookups and zero across ten new hit lookups; misses showed the same before/after call counts.
Cold standalone owner startup, including initially starting the reader workers, was 0.445 s before / 5.264 s after. Process RSS was about 1.32 GB in both measured hit batches; isolated cold worker startup raised it from 0.85 GB to 1.21 GB. This ordered process retains old caches and reader workers, so it is not an isolated memory comparison. Full Gateway startup and production latency were not measured.
All 76 tests across eight focused ACP/spawn files passed, including zero-host-SQL ownership, both ID forms, backend/requester mismatch, duplicate ordering, lifecycle resets, incognito exclusion, request retirement, an ID change during the awaited entry read, and rejection of unresolved metadata aliases/internal-effects keys. Direct before/after probes of those three alias/internal cases now agree. Replaying the new owner regression against the original synchronous function failed specifically at the no-main-thread-SQL assertion. Query-plan proof uses both resume indexes with no table scan; upgrade proof preserves canonical rows and schema version.
Measured
pnpm test <file> --maxWorkers=1wall time on Testbox:session-meta-resume.test.ts7.55 s;acp-spawn-resume.worker.test.ts12.44 s (3.57 s test time);acp-spawn.test.ts14.37 s. Exact-head CI took 529 s from first job start to final gate completion and 11,226 aggregate active-job seconds, including setup and all selected suites; these are campaign totals, not marginal new-test cost.Provider:
blacksmith-testbox, profileopenclaw-check. Proof leases:tbx_01m45r7ff15q589wccg6mzjs59(complete changed-gate/typecheck and baseline reproduction) andtbx_01m45w65cjxvgreqq38skw4esm(final canonical-key fix, benchmark, focused checks, and remaining guards), both warmed from this lane branch. Commands:node scripts/run-vitest.mjs <ACP/spawn files> --maxWorkers=1, the individualpnpm testruns above,node scripts/check-changed.mjs --staged --base 4f05baa4f524f436e10514831b80a35ec982d33f, and the synthetic harness vianode --import ./scripts/tsx.mjs. The changed gate passed core typechecking and all 27 test typecheck shards, then failed at Knip on inherited dead exports. The exact baseline4f05baa4f524f436e10514831b80a35ec982d33freproduces the same eight production and five full-tree findings; the five defining files and their symbol references are unchanged on main snapshotae5a95772c02af57c7add70391ad0241dd5c50a8. Remaining planned guards, script lint, all changed-file lint, and the final affected production/test typechecks passed separately without disabling Knip. Full core lint completed with only three inherited max-lines failures:src/gateway/server-methods.authorization.test.ts,src/channels/message/ingress-queue.test.ts, andsrc/config/sessions/session-transcript-worker.types.ts. Each file is byte-identical between the tested base and lane; newer main fixes the ingress case only. Earlier native sync timeouts were resolved by pinning the Testbox ref to the lane branch, with normal sync retained.CI run 37305815315 found one PR-specific type-dependency cycle in Madge; its other selected jobs passed. The cycle was repaired by moving the ACP command/result/row types to the existing ACP contract file. On
tbx_01m45zj6jeacpdntqh0m2zt1d2,pnpm check:madge-import-cycles, core and affected test typing, 13 focused read/ownership tests, lint, and formatting all passed. Runtime SQL and message shapes are unchanged. The next CI run exposed an inherited deferred-migration import cycle; rebasing onto upstream fix21901766c534preserved all four lane patches exactly. On headf077af4b7979, Testboxtbx_01m461fbcmhkbg7a6wexee4tecpassed Madge (zero cycles), core plus the two affected test typechecks, and 56 tests across five ACP/spawn files in 376.10 command seconds. CI 37311569926 finished with 56 successful jobs, 24 skipped jobs, and two failed test jobs plus their aggregate gate. Both failures come from an upstream packaging omission in that fix:scripts/pr-lib/wrapper-components.txtlackssrc/infra/deferred-plugin-migrations.contract.ts. Two cases intest/scripts/eager-import-closure.test.tsand three cases intest/scripts/pr-worktree-provision.test.tsfail because the extracted wrapper cannot load that module. The contract, importer, inventory, and wrapper tests are unchanged by this lane. Running the full 17-test closure file in an isolated worktree at exact basef1930848on the same lease reproduced the same two failures (15 passed) in 27.90 command seconds; the diagnostic wrapper succeeded because it required that observed failure, not because the tests passed. Current main snapshot4ce5c0b54b05still has the omission. Its one-line inventory repair belongs upstream; no unrelated patch is included here. All remaining selected checks passed, including guards, lint, production/test types, docs, and ACP-related suites. CI is not green; the PR remains open for the upstream repair and the lead’s landing workflow.Independent Codex reviews of the implementation, extraction, gate cleanup, canonical-key eligibility, and CI repair were clean through P2. All owned leases are stopped. No production Gateway or state was modified.
Inherited Knip failures
extensions/google-meet/src/transports/types.ts:GoogleMeetJoinResultextensions/memory-wiki/src/compiled-cache.ts:MemoryWikiImportInsightCluster,MemoryWikiImportInsightsStatus,MemoryWikiOverviewCluster,MemoryWikiOverviewStatusextensions/workboard/src/gateway-helpers.ts:resolveGatewayWorkboardWorkspaceAccessextensions/x/src/spend.ts:X_STREAM_HEADROOM_MICRO_USDsrc/meeting-bot/runtime-facade-types.ts:MeetingRuntimeOwnerThese are outside the ACP change. Baseline reproduction temporarily restored only the lane's changed paths to the exact base, verified the complete working tree against that SHA, ran the same Knip command, and restored/verified the candidate in
finally.