Skip to content

perf(acp): avoid full-session scans when resuming - #165550

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-acp-resume-point-lookup-20260919
Oct 5, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-acp-resume-point-lookup-20260919

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Supplying resumeSessionId to ACP sessions_spawn synchronously 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.

10,000-session owner lookup Before median (10 samples) Warmed after median (100 samples) Warmed after p95
Last-entry hit 381.25 ms 4.23 ms 9.56 ms
Miss 371.57 ms 0.39 ms 0.76 ms

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=1 wall time on Testbox: session-meta-resume.test.ts 7.55 s; acp-spawn-resume.worker.test.ts 12.44 s (3.57 s test time); acp-spawn.test.ts 14.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, profile openclaw-check. Proof leases: tbx_01m45r7ff15q589wccg6mzjs59 (complete changed-gate/typecheck and baseline reproduction) and tbx_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 individual pnpm test runs above, node scripts/check-changed.mjs --staged --base 4f05baa4f524f436e10514831b80a35ec982d33f, and the synthetic harness via node --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 baseline 4f05baa4f524f436e10514831b80a35ec982d33f reproduces the same eight production and five full-tree findings; the five defining files and their symbol references are unchanged on main snapshot ae5a95772c02af57c7add70391ad0241dd5c50a8. 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, and src/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 fix 21901766c534 preserved all four lane patches exactly. On head f077af4b7979, Testbox tbx_01m461fbcmhkbg7a6wexee4tec passed 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.txt lacks src/infra/deferred-plugin-migrations.contract.ts. Two cases in test/scripts/eager-import-closure.test.ts and three cases in test/scripts/pr-worktree-provision.test.ts fail 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 base f1930848 on 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 snapshot 4ce5c0b54b05 still 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: GoogleMeetJoinResult
  • extensions/memory-wiki/src/compiled-cache.ts: MemoryWikiImportInsightCluster, MemoryWikiImportInsightsStatus, MemoryWikiOverviewCluster, MemoryWikiOverviewStatus
  • extensions/workboard/src/gateway-helpers.ts: resolveGatewayWorkboardWorkspaceAccess
  • extensions/x/src/spend.ts: X_STREAM_HEADROOM_MICRO_USD
  • src/meeting-bot/runtime-facade-types.ts: MeetingRuntimeOwner

These 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.

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L labels Oct 5, 2026
@steipete
steipete marked this pull request as ready for review October 5, 2026 11:53
@steipete
steipete enabled auto-merge (squash) October 5, 2026 11:55
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 10:19 AM ET / 14:19 UTC (Revision 6).

ClawSweeper review

What this changes

ACP, 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
Reviewed head: 2a40e6779561ad9b1e0b55e6ea033d7af1c211f7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with meaningful production-boundary evidence and no actionable correctness finding; storage acceptance remains a separate human decision.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured Testbox before/after probe exercises the production resume-ownership entry point with real database workers and observes faster hits/misses with zero host SQL calls. Populated same-version reopen evidence verifies preserved canonical rows and version after index installation; full Gateway startup and production latency remain outside the claimed coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured Testbox before/after probe exercises the production resume-ownership entry point with real database workers and observes faster hits/misses with zero host SQL calls. Populated same-version reopen evidence verifies preserved canonical rows and version after index installation; full Gateway startup and production latency remain outside the claimed coverage.
Evidence reviewed 9 items Pinned introduced change: Inspected the complete introduced hunks against the pinned base. Raw commit records confirm the original head parents are 685e187 and 1746280. The final checkout status is clean.
Current main still scans sessions: Resume ownership validation on fetched main enumerates canonical session entries and synchronously reads ACP metadata until it finds a matching identity. The central performance improvement remains absent.
Latest release retains enumeration: The v2026.9.8 source also enumerates session entries during resume authorization; it was inspected through GitHub’s contents API.
Findings None None.
Security None None.

How this fits together

ACP 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]
Loading

Decision needed

Question Recommendation
Should the two same-version ACP resume indexes be accepted with their documented construction and write-maintenance costs? Accept the additive indexes: Record acceptance of the documented storage costs and rollback contract while retaining the demonstrated reduction in Gateway-thread work.

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

  • Resolve merge risk (P1) - Acceptance of the two persistent expression indexes remains unrecorded: existing databases must construct them using metadata scans and temporary disk, and subsequent metadata writes maintain both indexes.
  • Complete next step (P2) - Record maintainer acceptance of the two persistent resume indexes and their documented construction and write-maintenance costs, or resolve that storage choice before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +172, Tests +313, Docs +14, Other -1. Total +498 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 11 239 67 +172
Tests 3 397 84 +313
Docs 2 15 1 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 17 651 153 +498

Review metrics

Metric Value Why it matters
Persistent lookup indexes 2 nonunique expression indexes; unchanged schema version Existing databases construct these indexes, and subsequent metadata writes maintain them.
Measured resume lookup 10,000 sessions: hit median 381.25 → 4.23 ms; miss median 371.57 → 0.39 ms The production-owner probe supports the optimization while disclosing a 9.56 ms hit p95.

Stored data model

Persistent data-model change detected: database schema: src/state/openclaw-state-schema.sql. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Record index acceptance (recommended)
    Accept the additive indexes and explicitly record their existing-database construction and ongoing write-maintenance tradeoffs.
  2. Pause for representative measurements
    Defer the storage decision until construction and maintenance measurements establish an acceptable operator impact.

Technical review

Best 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.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: The new persistent indexes change existing-database admission and write costs whose acceptance remains unresolved despite preserved-row compatibility evidence.

Label justifications:

  • P2: This is a bounded ACP performance improvement with measured reductions in synchronous Gateway work.
  • merge-risk: 🚨 compatibility: The new persistent indexes change existing-database admission and write costs whose acceptance remains unresolved despite preserved-row compatibility evidence.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured Testbox before/after probe exercises the production resume-ownership entry point with real database workers and observes faster hits/misses with zero host SQL calls. Populated same-version reopen evidence verifies preserved canonical rows and version after index installation; full Gateway startup and production latency remain outside the claimed coverage.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Testbox before/after probe exercises the production resume-ownership entry point with real database workers and observes faster hits/misses with zero host SQL calls. Populated same-version reopen evidence verifies preserved canonical rows and version after index installation; full Gateway startup and production latency remain outside the claimed coverage.

Evidence

What I checked:

  • Pinned introduced change: Inspected the complete introduced hunks against the pinned base. Raw commit records confirm the original head parents are 685e187 and 1746280. The final checkout status is clean. (2a40e6779561)
  • Current main still scans sessions: Resume ownership validation on fetched main enumerates canonical session entries and synchronously reads ACP metadata until it finds a matching identity. The central performance improvement remains absent. (src/agents/subagents/spawn/acp-spawn-requester.ts:177, e698b96e7480)
  • Latest release retains enumeration: The v2026.9.8 source also enumerates session entries during resume authorization; it was inspected through GitHub’s contents API. (src/agents/subagents/spawn/acp-spawn-requester.ts:246, fc23bc864e45)
  • Canonical ownership remains authoritative: Indexed selection preserves string-ID, backend, canonical-key, incognito, internal-session, and ordering checks. The canonical reader rejects stale lifecycle bindings and rechecks the ID after awaiting the entry. Requester validation and spawn retain caller-currentness assertions. (src/acp/runtime/session-meta-resume.ts:39, 2a40e6779561)
  • Scoped production behavior proof: The captured body, sourceRevision 5ffab98a6359f021f2fd45eb23e0953ef3c9e1d2f15bbd2d78c28ccae09a5088, reports Testbox before/after probes through the production resume-ownership entry point with real database workers and 10,000 sessions. Hit median improved from 381.25 to 4.23 ms and miss median from 371.57 to 0.39 ms; observed host SQL calls fell to zero. Hit p95 was 9.56 ms, and cold standalone startup increased from 0.445 to 5.264 seconds. Full Gateway startup and production latency were not measured. This reviewer did not execute target code.
  • Existing-state compatibility: The reported passing reopen regression constructs both indexes on populated same-version state and verifies unchanged canonical rows and user_version. The production schema owner installs missing indexes inside its existing migration transaction, with canonical-shape and maintenance validation. No columns, canonical row transformations, retention rules, or permissions change. (src/acp/runtime/session-meta-resume.test.ts:111, 2a40e6779561)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-05T11:58:39.920Z sha 0bfc600 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T12:05:25.470Z sha 0bfc600 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T12:39:36.920Z sha c67211c :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T13:03:27.470Z sha f077af4 :: blocked before merge. :: none
  • reviewed 2026-10-05T13:46:24.221Z sha 685e187 :: blocked before merge. :: none

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.
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 5, 2026
@steipete
steipete merged commit 0237767 into main Oct 5, 2026
135 checks passed
@steipete
steipete deleted the steipete/perf-micro-acp-resume-point-lookup-20260919 branch October 5, 2026 14:25
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
* 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant