Skip to content

improve: reduce retained code in session read workers - #183248

Merged
steipete merged 7 commits into
mainfrom
steipete/perf-agent-db-borrower-split-20261025
Oct 25, 2026
Merged

steipete merged 7 commits into
mainfrom
steipete/perf-agent-db-borrower-split-20261025

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Fresh evidence — 2026-10-25

Current head: 7cb7671433cea335fad369d6d1657c0001a6017b. Baseline: 77a7ce297e981298390150cdb6c57988bf769925, containing both fixture repairs (#183823 and #183244). The six borrower patches rebased without conflicts or patch changes. Production source remains +121 LOC, including the prior +11-line idle-timer correction; the split preserves writable admission and lifecycle ownership while passive readers avoid that import graph.

Measurements ran on fd4a1b8754ed8d14df5c9892cd17596228171913. The only subsequent change is the goal-event test mock described below. Exact Git comparison proves all production and benchmark files are byte-identical. Node 26.12.1, synthetic production session-transcript workers, one retained session/two messages, fresh worker per sample, alternating order. Latencies precede forced GC. All 140 requested samples completed, without discarded samples, outlier trimming or retries. Loaded-module inventories and source hashes are retained with the reports. These are worker-retention measurements, not allocation, promotion, natural-GC or whole-Gateway measurements.

Retained heap

Five alternating pairs per cell, n=5 per side. MiB = 2^20 bytes. Values are median [min–max]; script counts are medians.

Task / history prewarm Base heap MiB Head heap MiB Absolute / relative change Loaded scripts base→head
prewarm / false 55.112 [55.050–55.114] 38.580 [38.574–38.583] -16.533 MiB / -30.00% 2155→1236
session-entry-read / false 70.729 [70.729–70.731] 67.069 [67.065–67.076] -3.661 MiB / -5.18% 2750→2649
session-entry-list / false 61.719 [61.718–61.720] 57.054 [57.053–57.056] -4.665 MiB / -7.56% 2444→2327
history-page / false 67.989 [67.987–67.992] 65.871 [65.870–65.875] -2.119 MiB / -3.12% 2628→2571
prewarm / true 67.835 [67.833–67.836] 65.719 [65.718–65.722] -2.116 MiB / -3.12% 2635→2578
session-entry-read / true 75.210 [75.207–75.212] 73.250 [73.248–73.448] -1.960 MiB / -2.61% 2885→2830
session-entry-list / true 69.305 [69.303–69.314] 67.171 [67.169–67.172] -2.134 MiB / -3.08% 2676→2618
history-page / true 68.179 [68.177–68.179] 66.062 [66.060–66.068] -2.117 MiB / -3.11% 2635→2578

Cold readiness and A/A

Ten alternating pairs per row, n=10 per side. Milliseconds; median / nearest-rank p90 / maximum. p90 and maxima are descriptive at this sample count.

Workload Base (or A) Head (or B) Median Δ Paired mean Δ p90 Δ
history-page 1375.44 / 1488.22 / 1522.34 1386.70 / 1403.74 / 1427.04 +11.26 ms (+0.819%) -15.97 ms (-0.983%) -5.676%
session-entry-list 1369.84 / 1378.55 / 1449.02 1376.02 / 1423.94 / 1490.63 +6.17 ms (+0.451%) +15.68 ms (+1.133%) +3.292%
Identical-baseline history A/A 1376.35 / 1429.21 / 1567.93 1380.33 / 1466.52 / 1497.73 +3.98 ms (+0.289%) +1.07 ms (+0.188%) +2.610%

The earlier strict A/A tolerance rule is not met. Its median tolerance is 0.289471% and p90 tolerance is 2.610194%. Both candidate medians exceed that median tolerance; entry-list p90 also exceeds the p90 tolerance. History improves on paired mean, p90 and maximum, while entry-list has a small increase. These are not 20% regressions, but this run is not described as a cold-ready pass or a universal startup speedup. The lead must assess this tradeoff against the reproduced heap reduction; no after-the-fact threshold change or timing rerun was used.

Five-pair timing context

The heap runs also recorded these medians in ms, n=5 per side. Keep these separate from the ten-pair cold-ready decision above.

Task / history prewarm Ready base→head First task base→head Total base→head
prewarm / false 1388.79→1427.86 2338.65→1144.40 3749.14→2570.21
session-entry-read / false 1385.63→1375.41 4024.36→3474.11 5401.15→4893.96
session-entry-list / false 1375.98→1374.68 2898.30→2352.13 4283.31→3718.21
history-page / false 1384.94→1370.89 3551.05→3237.95 4945.23→4608.84
prewarm / true 4929.86→4604.17 20.40→20.82 4950.72→4624.35
session-entry-read / true 4939.29→4614.36 981.33→979.37 5912.28→5591.24
session-entry-list / true 4921.17→4645.00 203.05→196.36 5124.22→4841.36
history-page / true 4949.71→4713.34 29.59→31.55 4980.34→4743.31

Recorded one-minute host load ranges: heap-5pairs 1.43–2.93, cold-10pairs 2.72–3.59, history-aa-10pairs 2.58–3.31. Benchmarks ran serially on the Linux rig; no Team workloads or production profiles were taken.

Correctness and CI

The twenty-pair interleaved Linux replay completed on the exact current head and pinned base: 420/420 executed cases passed per revision, 840/840 total; zero base failures, zero head-only failures and no evidence gaps. Odd pairs ran head then base; even pairs ran base then head. One worker, retries disabled, all native invocations accepted their first attempt. The source tree and shared dependency identity remained unchanged. Independent native-report audit confirmed case identities, counts, ordering and log hashes.

Replay scope Cases per side per pair Base passes Head passes Failures
openclaw-agent-execution.close-wedge.test.ts (full file) 10 200 200 0
session-accessor.sqlite-session-row.test.ts (full file) 8 160 160 0
Child inline follow-up (timeout) 1 20 20 0
Warm repository readers 1 20 20 0
Thinking claim (delivered-event) 1 20 20 0
Total: 20 pairs, 40 sides 21 420 420 0

These are 80 wrapper invocations, expanding into 160 native configuration invocations. Focused selections skip 73 siblings per invocation; those skipped records are excluded from the pass counts. The five archived failure targets each passed twenty times per side. No CI reruns or benchmark retries were used.

The first rebased-head CI found an inherited collection failure in sessions-goal.event-custody.test.ts: its closed node:worker_threads mock lacked workerData. The newest scheduled main run at diagnosis (40231115290) has the same signature, and the single file reproduced it locally. The current head supplies the real main-thread value workerData: null; Worker/native/process sentinels and custody assertions stay unchanged. Focused proof: pre-fix collection failure, post-fix 3/3 tests, changed-file format/core lint/diff checks clean, independent subagent review (autoreview route unavailable) clean. No production code changed. This is a real fixture repair push, not a CI rerun for green.

Exact-head CI is green: run 40233477966 completed successfully for 7cb7671433cea335fad369d6d1657c0001a6017b. The completed PR rollup contains 139 successful, 52 skipped and one neutral context, with no failures or pending checks. Review and focused format/lint checks are clean. This PR remains open and unmerged for the lead; the cold-ready tolerance limitation above still requires the lead's judgment.

After any eventual deploy, compare session-transcript worker retained heap and cold readiness, and watch terminal-authority rejection and duplicate PR-notification signals.

Reproduction commands

node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output <new-heap-dir> --baseline-ref 77a7ce297e981298390150cdb6c57988bf769925 --samples 5
node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output <new-cold-dir> --baseline-ref 77a7ce297e981298390150cdb6c57988bf769925 --samples 10 --prewarm false --task-kind history-page --task-kind session-entry-list
node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output <new-aa-dir> --baseline-ref 77a7ce297e981298390150cdb6c57988bf769925 --samples 10 --prewarm false --control --task-kind history-page

Historical evidence and investigation

The records below are preserved in their original chronology. Earlier pending, merge-readiness and performance conclusions describe their then-current heads; the fresh results above supersede them.

Fixture prerequisites — updated 2026-10-25

Both reported failure signatures reproduce at base under controlled fixture ordering. No borrower-specific mechanism was established and no production authority check was weakened.

Fixture repair Status and exact identity Fresh proof
Repository PR reader: #183823 Ready, awaiting maintainer merge; head b79ba0107a6cb60c674a585ba9dd3b277c24422f Original mock under forced replacement settlement: three events instead of two. Source-aware mock: full file 42 passed/one existing skip; 20/20 independent selected-case repetitions, retries disabled. Changed-file format/lint and independent review clean.
Child completion: #183244 Already merged; PR head f8199f86b2078ba7d043bf9e863fc1f9eca5b611, merge 8bf40264cfd9678800465a59fad4d596b566a5a8 Fresh merged-source full file: 30/30. Twenty independent processes exercise all three inline statuses: 60/60 passed, retries disabled. A join-removal mutation control reproduces the post-capture authority rejection; the same probe with the merged join passes. Original baseline failure evidence remains below.

The child fix landed independently while the prerequisite work was underway, so no competing child PR was opened. Its registry wait is released only after completion can be observed, or after teardown has removed the owner. It also prevents the redundant successful background wait from emitting a second lifecycle end. Both prerequisite repairs are test-only.

Borrower acceptance remains pending. Once #183823 is merged, rebase this branch onto main containing both fixtures, push the rebased head, then collect five alternating fresh-worker forced-GC samples per side, the ten-pair Linux cold-ready comparison plus A/A, the twenty-pair interleaved five-file base/head replay with zero head-only failures, and exact-head green CI. The isolated Linux setup and pinned Node 26.12.1 are prepared; none of that fresh borrower acceptance evidence has run yet. Historical performance numbers below are not new-head acceptance evidence. This PR stays open and unmerged for the lead.

Deterministic ordering investigation — 2026-10-25

Not ready to merge. The bounded investigation reproduced both reported signatures under explicitly controlled ordering on main as well as the borrower candidate. It did not establish a deterministic borrower-head failure that passes on base. No production guard was weakened, no new cache or lock was added, and the diagnostic probes are not committed as product regressions.

Remote PR head remains 74da2731f640bbb191a1cca2bbd7f186d3299f9c. The local branch was fast-forward checked, rebased onto main 31fcb0657b2e7cccd20a8af5056a2fd51e56899f, and installed once with pnpm install --frozen-lockfile. The rebased candidate is 703e8baffe77671a02c4f227d3c868897f3f5481, not pushed. One import conflict retained main's inlined read-only companion and the candidate's borrower imports. The idle-timer installer fix and static-import audit remain intact.

All new probes used the same physical macOS checkout and install, repository test wrapper, one worker, and no timing sleeps. Baseline and candidate tests were byte-identical apart from the same applied diagnostic patch.

Controlled ordering Main Borrower candidate Samples per side
Repository deletion: settle replacement loading before changing the mock response Fails: three events instead of two Fails: same three-event assertion 1
Child timeout: hold terminal preparation until inline acknowledgement and requester settlement finish Pass Pass 1
Child timeout: independent wait enters capture during the fixture's existing reset; capture resumes after reset deletes the run Fails: Subagent terminal execution changed, completion line 224 Fails: same guard and stack 1
Repository deletion with mock response derived from the admitted target's source, keeping forced replacement settlement Pass Pass 1

These counts describe deterministic diagnostic executions, not a flake-frequency estimate or the requested 20-pair acceptance run.

Repository-event mechanism

The original warm-reader fixture changes f.load to the empty response only after awaiting repository deletion and the notification read. currentWatcher in control-ui-session-pr-subscriptions.ts clears the delivered hash when the target identity changes and starts a replacement load. Letting that work settle before updating the mock delivers the old snapshot again, followed by the empty snapshot: three events. The preceding no-SQL assertions still pass.

The real branch loader in control-ui-session-prs.ts returns an empty response when its admitted target has no source. The fixture's constant mock temporarily contradicts that contract. A source-aware mock installed before deletion removes the contradiction without weakening the event count or SQL assertions. This is a demonstrated fixture issue on both revisions, not evidence of a new freshness-check path introduced by the borrower split.

Child-completion mechanism and limits

The original pair-12 log failed in 2.462 seconds with 29 sibling cases skipped. (timeout) is the parameter, not a test-runner timeout. The exception occurs at the currency check after captureSubagentRunResult.

The fixture supplies terminal responses to two independent waits. Its root-work observer can finish while the registry's background wait has not entered the terminal-completion root. retainGatewayRootWorkAdmissionContinuation retains only an existing root. The fixture then calls its existing resetSubagentRegistryForTests, which awaits deleting registry rows before clearing runtime state. Deferred gates expose a possible overlap: the wait enters capture during that awaited reset, the reset deletes its owner, and capture resumes. The unchanged terminal guard correctly rejects. The root observer subsequently records that inner-root rejection even though the background wait handles retirement.

The probe controls the existing reset's timing; it adds no extra reset and no sleep. It establishes a reachable fixture teardown race matching the signature on both revisions. The historical log lacks ordering instrumentation, so it does not prove that this exact interleaving caused that historical occurrence. Inline acknowledgement, receipt decoding, hydration, and publication preserve durable identity/runtime keys; no borrower-specific loss was found. Existing lifecycle tests require rejection after genuine authority loss, so relaxing this guard would violate their contract. The narrow follow-up is to join terminal publication before the fixture resets its registry, then drain cleanup roots.

Proof commands and outstanding acceptance

The files were run individually through node scripts/run-vitest.mjs <file> -t <selector> --maxWorkers=1:

  • src/gateway/control-ui-session-pr-access.test.ts, selector reuses prepared repository rows.
  • src/agents/openclaw-tools.sessions-send-child-coordination.test.ts, selector consumes an inline child follow-up result without a second requester delivery \(timeout\).

A combined base invocation stopped after the intentionally failing Gateway probe; the child base probe was then run separately. No retries for green, CI reruns, Team workloads, leases, or production profiles were used. Temporary diagnostic edits are preserved as patches for follow-up and removed from the working tree.

The requested fresh five-sample heap comparison, ten-pair Linux cold-ready comparison with A/A control, 20-pair five-file replay, committed regressions, and green exact-head CI remain outstanding. Historical heap/latency measurements below remain historical and are not acceptance evidence for the rebased candidate. No new performance numbers are claimed. If this is later cleared for deployment, inspect session-transcript worker retained heap/code and cold readiness, alongside terminal-completion rejection counts and duplicate PR notification events. Do not use a relative GC rise on a tiny baseline as a gate; the supplied absolute decision rules remain applicable.


What Problem This Solves

Session transcript readers loaded writable admission, migration, and lifecycle modules merely to resolve a read scope or borrow an already admitted handle. The real entry-read task also dynamically imported a mixed exact-read module, bringing the writer graph back after a narrow preload.

User Impact

Session reads retain less code and heap. Synchronous writer admission and the existing idle-retention, explicit-revocation, maintenance, and engine contracts remain unchanged. No schema or configuration change. The quiet Linux follow-up meets the maintainer’s measurement rule for the two flagged cold-ready cells. Earlier Mac measurements remain recorded below; no universal startup-speedup claim is made.

Why This Change Was Made

Read-scope resolution and passive admitted-handle borrowing now have narrow owners. The writable lifecycle remains the only handle publisher, opener, lease holder, migration owner, timer owner, and closer. Readers and writers share the existing borrower pins and failure visibility. Pins block idle eviction; explicit disposal invalidates claims immediately; maintenance closes cached handles before its callback. History target discovery imports existing path, registry, and ownership readers directly. Engine/PostgreSQL runtime correctness is retained; the engine implementation is unchanged.

Exact selection, memory access, identity/source checks, canonical continuations, and rollback/error handling stay in one shared implementation. Four existing synchronous APIs use a separate writable-admission facade; public barrel APIs remain intact. This completes the path actually exercised by entry-read workers.

Production is +689/−568 lines, net +121, against merge-base 973f0a249e373e2036cf515ac913b77c5957b803. The growth pays for explicit module/import boundaries and preserved synchronous entry APIs around shared selection logic. No new database state, caches, timers, or promises were added. Tests and test harnesses are +76/−20 lines, net +56; the mock inventory also shrinks by three lines. Both requested contract-test extensions are committed: multiple pins retain an idle handle, and explicit close immediately revokes an outstanding claim without a late release harming a reopened handle. No fenced files, sqlite-store backend, or scripts/perf/README.md were edited. ClawSweeper identified three extracted dependencies missing from the explicit PR-wrapper inventory. The existing inventory/source-closure checks reproduced the omissions; adding exactly those three paths makes all four selected checks pass. No wrapper execution or authority behavior changed.

Evidence

Read-path CI causation after the latest main merge

Head: f6378d49ed35a8454eafd2dfff493a232c4fc525. Merge-base with fetched main: 1c4520e9ebb666cda1ee55bafcb0ff1cc320e414. Fast-forwarded first, then completed pnpm install --frozen-lockfile. The three test files are byte-identical. Sequential comparisons used the same physical checkout and node_modules; its inode, install-metadata hash and lockfile hash stayed unchanged. Local coordinator: Node 26.12.1; test runtime: pinned Bun 1.4.4-canary.1+807211511.

Reported case Base full-file run Head full-file run Attribution
control-ui-session-pr-access: warm repository readers Pass (42 passed, 1 skipped in file) Pass (42 passed, 1 skipped) CI extra-event failure not reproduced; not classified inherited
Codex run-attempt: private native history Fail: expected 0 to be greater than 0, line 1926 (126 other tests pass) Same failure and counts Confirmed inherited
sessions-create-thinking-claim: delivered-event Pass (3/3 in file) Pass (3/3) CI missing-claim failure not reproduced; not classified inherited

Inherited mechanism: main's #183457 (10c6c29f4b1b, ancestor of this base) changed clonePromptHookEvent to copy message envelopes and clone only unowned nested values. The test's counter recognizes whole message objects crossing structuredClone; those envelopes no longer cross it. Both private-payload assertions pass before the clone-count assertion fails. A direct owner probe confirms one nested-value clone, zero whole-message clones, preserved visible text, a copied envelope and omitted private metadata. This PR does not modify that implementation or assertion.

The two failing Gateway shard groups were replayed once per revision with their exact CI selectors/configs and two-worker setting: 312 passed, 2 skipped across 29 files on each side. A quiet Linux comparison of the two Gateway files also passed on both sides: 45 passed, 1 skipped each, using the same physical install there and the same pinned runtimes. Neither Gateway CI failure is reproduced or explained by these passes. An initial local shard setup stopped before collection because CI mode selected stock Bun; it was corrected to the verified pinned binary, with that setup log retained separately.

Remaining source evidence: the repository-reader CI failure is the final event count after deletion; its preceding no-SQL checks passed. The unchanged subscription owner clears delivery identity and starts replacement loading when the repository target changes, while the fixture switches its loader response only after awaiting deletion and notification. That is a plausible scheduling sensitivity, not an established cause. The thinking CI failure is the second low assertion, after the persisted low entry, delivered low payload and first low claim all passed; the later stale-list/event settlement remains unexplained. The admitted facade still calls its reader synchronously with unchanged projection/options. No field-loss mechanism was demonstrated.

No source, test assertion, or baseline changes were made, and no empty commit or CI rerun was used. CI run 40180216431 remains red on this exact head: 110 successful jobs, 25 skipped, the three reported test jobs and the gate failed. No merge.

Lead review follow-up: import ordering and missing-timer custody

Recorded head: 0eba919f17f46f11b2c9910c17da7860f6b064a4 (fix(state): restore borrower idle timer installation).

Finding 1 — no newly deferred production import. Audited every changed JS/TS module against merge-base 973f0a249e373e2036cf515ac913b77c5957b803, including the exact-read kernel, both admitted-read facades, all static re-exports, and transitive local source dependencies. There are zero static-to-dynamic production conversions. The only production dynamic-import deltas move an unchanged awaited transcript-context import and retarget an existing awaited list-worker import. All seven direct transcript-preparation callers await it; the facades and exact-read kernel remain synchronous. The timer repair adds no production import edges.

Both CI roots retain eager plugin-runtime paths on base and head: terminal-recovery directly imports plugins/runtime.ts; follow-up execution reaches it through reply-operation run-state support → abort → model fallback → harness registry. Runtime statically imports agent-events.ts. The CI stack instead enters through the unchanged watchdog placement-recovery import, which can outlive operation settlement. The test harness initially mocks agent-events; runner retirement later resets mocks and evaluated module state, allowing a surviving import to attempt fresh evaluation. Thus the proposed new-deferred-import mechanism is unrelated to this split. The particular CI escape remains unreproduced; no claim is made that passing replay fixed it, and no production wait was added to change the protected nonblocking successor-admission contract. Complete inventory and source traces follow in the collapsed audit.

Finding 2 — fixed. The base lookup could install a missing timer; the borrower copy only refreshed one. Borrower lookup now calls a refresh/installer function registered on the shared singleton by the writable lifecycle before any handle publication. It uses the existing installer unchanged, including shutdown-cleanup-signal handling, borrower pins, transactions, and close/lease cleanup. Readers still do not import lifecycle machinery. The singleton is retired after test custody drains, so its newly retained owner callback cannot cross test generations.

The regression removes the existing timer, reads the cached handle through the borrower module, and checks that the database remains open until the idle deadline, then closes and releases its durable lease. It failed on the previous head at database.db.isOpen after the TTL (received true, expected false), then passed with the repair. All 90 tests across the eight lifecycle/lease/identity/maintenance files, 33 follow-up execution tests, and four worker-cache lifecycle tests passed: 127 tests in 10 files, 155.23 seconds through the repository wrapper. The new regression itself took 114 ms in the passing run. Formatting, targeted lint, state/logging and root-test typecheck lanes, and full-owner independent P0–P2 review passed. Simplification review retained only the installer delegation, its type contract, one regression, and singleton retirement: +11 production lines and +21 test/harness lines in this repair. No new cache, timer implementation, async boundary, or production import was added.

Historical CI: 40176221972, superseded by the merged-head comparison above. The backup/terminal defects were subsequently fixed on main by #183448 and #183470. Earlier evidence remains tied to its recorded heads.

The detailed import audit in the preceding body revision is condensed here: against base 973f0a249e373e2036cf515ac913b77c5957b803 and head 91b8d97c0d1d1ccdd68e6d4aff62b0922eb177b3, there were zero new production deferred callsites or static-to-dynamic conversions. Exact-read and writable-admission facades remain synchronous; the moved transcript-context import and retargeted list-worker import remain awaited. Both affected CI roots already reach plugin runtime eagerly. The missing-timer repair and its red/green regression are described above. This condensation preserves room for the current investigation; it does not change that audit conclusion.

Causation follow-up after the update-branch merge

Causation comparison head: 91b8d97c0d1d1ccdd68e6d4aff62b0922eb177b3. Merge-base: 973f0a249e373e2036cf515ac913b77c5957b803. Fast-forwarded first and completed pnpm install --frozen-lockfile. Each host compared the two revisions serially using the same physical node_modules installation, with its inode, lockfile hash, and install-metadata hash unchanged. All three requested test files are identical between the revisions. No production code, test assertions, or baselines were changed in this investigation.

Requested test Merge-base PR head Attribution
test/cli-state-sqlite.e2e.test.ts, Git backup diagnostics 6 passed, 1 failed: missing stderr-tail-🦞 at 304:32 Same 6 passed, 1 failed and exact signature Inherited, directly reproduced at base.
test/e2e/qa-lab/runtime/agent-terminal-delivery.e2e.test.ts, strict NO_REPLY prefixes Failed at 337:53: expected No answer was returned. Ask again if you still need one., received ⚠️ The model reached its output token limit before generating an answer. Please try again. Same exact assertion and text Inherited, directly reproduced at base.
src/auto-reply/reply/followup-turn-execution.test.ts 33/33 passed 33/33 passed CI teardown failure not reproduced; attribution unresolved. Passing replays are not a fix.

Local commands used the repository wrapper, node scripts/run-vitest.mjs <exact-file> --maxWorkers=1, without an outer timeout. The baseline E2E runtime preparation took 14m23s and was allowed to finish. Node was 26.12.1; test execution used the repository-pinned Bun 1.4.4-canary.1+807211511.

Backup mechanism: the injected Git push failure did happen on both revisions: the preceding assertion for git push failed (code=1, termination=exit) passed. Local backup success and remote push failure are intentionally reported together. Main commit 3d1956124001 (#181586), already present at the merge-base, sanitizes the complete warning into one line. Literal \n then becomes part of the URL query value consumed by credential redaction, swallowing the diagnostic marker. A synthetic call through the real terminal sanitizer and redactor preserves the marker with real newlines and loses it after escaping. This is diagnostic rendering, not a missing maintenance observation.

Terminal mechanism: source inspection traces the host-generated incomplete/token-limit notice into meta.finalAssistantVisibleText in terminal-resolution.ts. result-fallback-classifier.ts then treats that text as deliverable assistant output before reaching its fallback-safe incomplete-turn branch. A synthetic call through the real classifier returns incomplete_result without that metadata text and no fallback classification with it. These owners are unchanged between base and head. The exact failing E2E assertion is retained; the following assertion also requires both primary and fallback models, so replacing the expected notice would hide behavior rather than repair it.

Teardown investigation: the database is still closing message is deliberately injected at followup-runner.heartbeat-drain.test.ts:84; that test passes in CI and on both revisions. The actual CI suite-load failure is EnvironmentTeardownError importing agent-events.ts through plugin runtime, with its stack rooted in dispatch-from-config.terminal-recovery.test.ts. A plausible source-level mechanism is the stalled-producer fixture advancing fake time past the cleanup deadline, starting the watchdog's lazy placement-recovery import, then retiring the owner before the import finishes. That timing has not been reproduced. Watchdog close intentionally does not join pending recovery; existing coverage permits successor admission while old recovery is blocked, so adding a production wait would change the ownership contract without demonstrated causation.

To restore the missing shard context, ran the saved native CI selection on isolated Linux with fresh private /tmp and /var/tmp, unchanged dependencies, pinned Bun, two concurrent plans and two Vitest workers:

Linux comparison Merge-base PR head
Exact dispatch group 28 files / 325 tests passed 28 files / 325 tests passed
Original complete failing shard, including concurrent cron groups 95 files / 868 tests passed 95 files / 868 tests passed

The complete shard contains cron-isolated 49/409, storage 10/89, cron-service 8/45, and dispatch 28/325 (files/tests). Both native invocations completed all four plans with zero failures. This is a bounded reproduction attempt, not a CI rerun or an inherited-failure claim for teardown. Linux used Node 26.12.1 as coordinator; CI used Node 24.22.1 with the same pinned Bun revision. An initial Mac dispatch-group attempt encountered an unrelated pre-existing /tmp/mock-sessions.sqlite schema-31 fixture; it was not counted as causal evidence, and the shared file was left untouched.

Final-head lifecycle guards: seven additional files passed 71/71 tests (lease owner, identity, lease, leasehold, readonly scope, module identity, and asynchronous lifecycle). The 18/18 maintenance tests passed inside the complete shard and were reused, for 89 passing cases across the eight requested lifecycle/lease/identity/maintenance files. No guard was retried.

CI run 40169736859 remains red at this exact head: 105 jobs passed, 25 skipped, and three test jobs plus the aggregate gate failed. The failed jobs are CLI diagnostics, terminal QA, and follow-up suite teardown. The two assertion failures now have direct merge-base evidence; teardown remains unresolved. No speculative repair, empty push, rerun-for-green, merge, or automatic merge was performed. Earlier Mac and quiet-Linux performance results below remain historical measurements of their recorded heads.

Earlier performance evidence (recorded heads)

Pre-update-branch proof head: 661b5b32bad12166fad4fc0af2fcf4bcdd368b3f. The quiet Linux measurements used 0cc91a43635f6deb3f8e25209a0beb24d488f788; the subsequent commit changes only test fixtures and shrinks their obsolete mock baseline. All measured production and proof-script inputs remain unchanged.

Acceptance rule recorded before measurement: compare the same synthetic production session-transcript worker workload on the parent and candidate in five alternating pairs for each prewarm mode. Force GC after latency measurements; collect loaded-script count, V8 code/bytecode bytes, heap bytes, and the merged heap analyzer's retained-code union. Use real session entries and transcript messages. Loaded script/code and retained heap should decrease; report median, p95, and spread separately by mode and task kind. A latency regression of 20% or more requires investigation and explicit acceptance rather than a claim of success. Run cold-ready and first-task measurements for prewarm, entry-read, entry-list, and history-page tasks. Record host load.

Quiet Linux follow-up: cold-ready time only

The two flagged cells pass the rule recorded before sampling. Production remains unchanged at 0cc91a43635f6deb3f8e25209a0beb24d488f788, compared with db440e9d6220b5da5b9ffcede13556de9d502ea1.

Linux x86-64, eight AMD EPYC-Milan vCPUs, Node 26.12.1, approximately 30.6 GiB RAM. Ten alternating baseline/candidate pairs per cell and ten unchanged-baseline history A/A pairs; all 60 requested samples completed, with no discarded samples or retries. One-minute host load was 0.61–1.54 for the comparisons and 1.30–1.75 for A/A. Recorded source hashes were verified after the run; the isolated checkout remained clean.

Times are milliseconds. Median is the average of observations five and six; p90 is observation nine; max is observation ten. The max is not p95.

Cold-ready cell Baseline median Candidate median Baseline p90 Candidate p90 Baseline max Candidate max
History page 1180.529 1182.913 1192.578 1191.004 1194.802 1240.582
Entry list 1176.886 1174.132 1202.418 1199.214 1202.804 1231.188
Identical-source history control Label A Label B B vs A
Median 1179.479 1176.888 -0.220%
p90 1200.353 1211.188 +0.903%
Max 1232.242 1219.700 -1.018%

The predeclared A/A tolerances are 0.219608% for median and 0.902683% for p90. History median changes +0.202011%, inside its tolerance, and p90 improves 0.132001%. Entry-list median improves 0.234051% and p90 improves 0.266448%. Both pass. History/list maxima increase 3.831607% / 2.359813% and remain explicitly reported; the approximately 40% Mac sample-max changes do not reproduce here. No production mechanism or median regression of 20% was found, so no production edit or regression acceptance was needed.

node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output /path/to/rig/cold-10pairs --baseline-ref db440e9d6220 --samples 10 --prewarm false --task-kind history-page --task-kind session-entry-list
node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output /path/to/rig/history-aa-10pairs --baseline-ref db440e9d6220 --samples 10 --prewarm false --control --task-kind history-page
Quiet-node rule recorded before sampling

The maintainer requested a new measurement to resolve the two cold-ready flags, without accepting a regression. On an isolated quiet Linux rig with Node 26.12.1, run only non-prewarmed history-page and session-entry-list, ten alternating baseline/candidate pairs each, plus one ten-pair unchanged-baseline A/A history-page control. Keep all earlier Mac results above as recorded. Production source stays unchanged.

Evaluate cold-ready time only. Report the ordinary median, nearest-rank p90 (ninth sorted observation of ten), and maximum separately; the maximum is not labeled p95. Record host load and source identity. For each statistic (median and p90), define the A/A tolerance as the absolute percentage difference between its two identically sourced labels. A candidate passes when both its median and p90 are no worse than baseline plus the corresponding A/A tolerance, or improve. A reproducible median regression of 20% or more on the quiet node keeps the PR draft and requires a causal startup investigation. Passing the rule permits marking this PR ready and proceeding through CI; no merge is authorized.

Original Mac measurements and initial draft disposition — retained as recorded

Five alternating pairs per task/mode use real session-transcript workers and a synthetic one-session/two-message fixture created through production writer owners. Each sample gets a fresh worker; timings precede forced GC, followed by script/code capture. History and corrected entry-read additionally have all 40 heap snapshots analyzed by the merged analyzer. Orders are baseline→candidate for pairs 1/3/5 and candidate→baseline for 2/4. No valid samples or outliers were discarded.

Baseline: db440e9d6220b5da5b9ffcede13556de9d502ea1. History/list/prewarm candidate: 71e80b868c87f4b809e488de96dc69b654608d95; corrected entry candidate: 7b5ce4ffaf76affc8366657848d1e8511a66c7b4 (production identical to 39bdefae184fc68e51f8e1efe65362d429f30469). Source SHA-256 maps were recorded and verified after sampling. All loaded-path inventories prove the final exact-read correction does not intersect history/list/prewarm, so those original results, including regressions, are retained.

Node v26.12.1; 32 logical CPUs. The host remained oversubscribed by unrelated work: 1-minute load ranges were 62.78–72.69 (history), 73.39–101.65 (original task series), and 55.50–103.72 (corrected entry). No task-owned checks/builds overlapped acceptance sampling. These are small synthetic worker-boundary measurements, not whole-Gateway throughput or natural-GC latency claims.

Retention decreases are consistent; latency acceptance remains unresolved. Cold-ready p95 worsened 41.16% for history and 36.94% for entry-list, exceeding the predeclared 20% gate. Corrected entry has no ≥20% p50/p95 latency regression, but its smaller regressions are included below. The draft PR needs explicit owner acceptance of the unresolved flags; noisy-host evidence does not waive them.

All memory/code values are MiB (2²⁰ bytes) and timings ms. Each side has n=5; p95 is nearest-rank (the maximum), not a precise tail estimate. Deltas compare candidate with baseline. cold means history prewarm disabled; prewarmed means enabled. “Ready” ends after worker startup/prewarm, “first” is the requested task after readiness, “total” is ready + first. Analyzer union is codeByScript.total.retainedBytes, never a sum of overlapping script rows.

Task/mode Loaded scripts, median B→C (Δ) Forced-GC heap, median B→C (Δ) Analyzer retained union, median B→C (Δ)
cold history-page 2,608→2,551 (-2.19%) 67.444→65.296 (-3.18%) 30.732→29.836 (-2.92%)
cold entry-read 2,731→2,631 (-3.66%) 70.237→66.582 (-5.20%) 31.767→30.323 (-4.55%)
cold entry-list 2,430→2,313 (-4.81%) 61.231→56.576 (-7.60%) not snapshotted
cold prewarm 2,147→1,230 (-42.71%) 54.676→38.261 (-30.02%) not snapshotted
prewarmed history-page 2,615→2,558 (-2.18%) 67.590→65.468 (-3.14%) 30.768→29.873 (-2.91%)
prewarmed entry-read 2,865→2,810 (-1.92%) 74.656→72.689 (-2.64%) 33.532→32.692 (-2.51%)
prewarmed entry-list 2,656→2,598 (-2.18%) 68.714→66.577 (-3.11%) not snapshotted
prewarmed prewarm 2,615→2,558 (-2.18%) 67.243→65.114 (-3.17%) not snapshotted
All latency distributions and deltas (p50 / p95 [min–max], ms)

Positive deltas are all retained below, including those below the 20% gate.

Task/mode Metric Baseline Candidate Δ p50 / p95
cold history-page ready 2,077.26 / 2,210.74 [1,726.98–2,210.74] 1,841.40 / 3,120.68 [1,716.83–3,120.68] -11.35% / +41.16%
cold history-page first 5,502.88 / 5,893.31 [5,141.29–5,893.31] 5,520.30 / 6,202.32 [5,109.87–6,202.32] +0.32% / +5.24%
cold history-page total 7,651.73 / 7,970.57 [7,068.28–7,970.57] 7,361.69 / 9,323.00 [6,837.48–9,323.00] -3.79% / +16.97%
cold entry-read ready 1,705.76 / 1,848.63 [1,472.25–1,848.63] 1,705.53 / 2,089.34 [1,337.04–2,089.34] -0.01% / +13.02%
cold entry-read first 5,771.51 / 6,792.97 [5,335.19–6,792.97] 4,578.87 / 7,631.92 [4,272.53–7,631.92] -20.66% / +12.35%
cold entry-read total 7,391.81 / 8,498.72 [6,807.44–8,498.72] 6,111.74 / 9,721.26 [5,628.02–9,721.26] -17.32% / +14.38%
cold entry-list ready 2,013.99 / 2,657.55 [1,528.88–2,657.55] 2,062.06 / 3,639.23 [1,769.13–3,639.23] +2.39% / +36.94%
cold entry-list first 5,064.51 / 7,893.95 [3,520.44–7,893.95] 3,916.06 / 4,366.86 [3,801.16–4,366.86] -22.68% / -44.68%
cold entry-list total 7,078.50 / 10,281.25 [5,121.26–10,281.25] 6,025.96 / 7,555.28 [5,572.55–7,555.28] -14.87% / -26.51%
cold prewarm ready 1,936.42 / 2,447.54 [1,527.67–2,447.54] 1,973.64 / 2,501.29 [1,659.45–2,501.29] +1.92% / +2.20%
cold prewarm first 3,784.50 / 4,793.72 [3,680.06–4,793.72] 1,810.67 / 2,052.51 [1,659.28–2,052.51] -52.16% / -57.18%
cold prewarm total 5,616.48 / 7,210.13 [5,312.17–7,210.13] 3,758.35 / 4,553.81 [3,318.73–4,553.81] -33.08% / -36.84%
prewarmed history-page ready 7,361.59 / 13,547.16 [7,147.46–13,547.16] 7,311.26 / 12,715.34 [7,066.02–12,715.34] -0.68% / -6.14%
prewarmed history-page first 39.95 / 273.47 [19.62–273.47] 32.60 / 99.66 [18.46–99.66] -18.40% / -63.56%
prewarmed history-page total 7,400.66 / 13,820.63 [7,169.74–13,820.63] 7,343.86 / 12,814.99 [7,084.48–12,814.99] -0.77% / -7.28%
prewarmed entry-read ready 6,633.47 / 9,935.16 [5,923.58–9,935.16] 6,796.68 / 8,556.06 [6,473.00–8,556.06] +2.46% / -13.88%
prewarmed entry-read first 1,308.21 / 1,688.58 [1,242.89–1,688.58] 1,360.71 / 1,687.77 [1,154.78–1,687.77] +4.01% / -0.05%
prewarmed entry-read total 8,322.04 / 11,243.37 [7,336.47–11,243.37] 8,479.07 / 10,167.67 [7,627.78–10,167.67] +1.89% / -9.57%
prewarmed entry-list ready 8,428.59 / 11,199.79 [7,017.19–11,199.79] 7,231.62 / 9,314.31 [7,050.84–9,314.31] -14.20% / -16.83%
prewarmed entry-list first 258.28 / 903.66 [225.57–903.66] 281.73 / 431.00 [246.96–431.00] +9.08% / -52.31%
prewarmed entry-list total 8,657.77 / 11,522.42 [7,275.47–11,522.42] 7,501.96 / 9,745.31 [7,297.80–9,745.31] -13.35% / -15.42%
prewarmed prewarm ready 7,999.01 / 12,001.90 [6,462.57–12,001.90] 7,162.84 / 9,765.18 [6,051.94–9,765.18] -10.45% / -18.64%
prewarmed prewarm first 37.61 / 147.85 [21.16–147.85] 18.30 / 49.75 [13.83–49.75] -51.35% / -66.35%
prewarmed prewarm total 8,066.25 / 12,149.75 [6,483.73–12,149.75] 7,191.37 / 9,814.93 [6,070.24–9,814.93] -10.85% / -19.22%
All memory/code distributions and deltas (p50 / p95 [min–max], MiB)

V8 code includes metadata; bytecode includes metadata. Analyzer shallow code and retained union are distinct from V8 counters. Script counts in the overview are constant within every side/group.

Task/mode Metric Baseline Candidate Δ p50 / p95
cold history-page forced heap 67.444 / 67.566 [67.440–67.566] 65.296 / 65.298 [65.294–65.298] -3.18% / -3.36%
cold history-page V8 code 1.895 / 1.906 [1.893–1.906] 1.885 / 1.886 [1.884–1.886] -0.53% / -1.02%
cold history-page V8 bytecode 2.255 / 2.255 [2.255–2.255] 2.222 / 2.222 [2.222–2.222] -1.45% / -1.45%
cold history-page analyzer code shallow 12.318 / 12.332 [12.316–12.332] 12.123 / 12.124 [12.122–12.124] -1.58% / -1.69%
cold history-page analyzer retained union 30.732 / 30.746 [30.730–30.746] 29.836 / 29.837 [29.835–29.837] -2.92% / -2.96%
cold entry-read forced heap 70.237 / 70.244 [70.190–70.244] 66.582 / 66.597 [66.580–66.597] -5.20% / -5.19%
cold entry-read V8 code 1.879 / 1.882 [1.877–1.882] 1.872 / 1.886 [1.872–1.886] -0.36% / +0.17%
cold entry-read V8 bytecode 2.280 / 2.280 [2.279–2.280] 2.225 / 2.225 [2.225–2.225] -2.41% / -2.41%
cold entry-read analyzer code shallow 12.471 / 12.476 [12.468–12.476] 12.159 / 12.176 [12.158–12.176] -2.51% / -2.41%
cold entry-read analyzer retained union 31.767 / 31.772 [31.763–31.772] 30.323 / 30.340 [30.322–30.340] -4.55% / -4.51%
cold entry-list forced heap 61.231 / 61.235 [61.229–61.235] 56.576 / 56.580 [56.568–56.580] -7.60% / -7.60%
cold entry-list V8 code 1.834 / 1.837 [1.833–1.837] 1.797 / 1.800 [1.791–1.800] -2.00% / -2.04%
cold entry-list V8 bytecode 2.118 / 2.118 [2.118–2.118] 2.045 / 2.045 [2.045–2.045] -3.42% / -3.42%
cold prewarm forced heap 54.676 / 54.679 [54.657–54.679] 38.261 / 38.268 [38.259–38.268] -30.02% / -30.01%
cold prewarm V8 code 1.754 / 1.760 [1.752–1.760] 1.611 / 1.613 [1.607–1.613] -8.18% / -8.33%
cold prewarm V8 bytecode 1.945 / 1.945 [1.944–1.945] 1.649 / 1.649 [1.649–1.649] -15.22% / -15.22%
prewarmed history-page forced heap 67.590 / 67.594 [67.568–67.594] 65.468 / 65.476 [65.465–65.476] -3.14% / -3.13%
prewarmed history-page V8 code 1.865 / 1.868 [1.808–1.868] 1.856 / 1.858 [1.855–1.858] -0.49% / -0.53%
prewarmed history-page V8 bytecode 2.257 / 2.257 [2.257–2.257] 2.224 / 2.224 [2.224–2.224] -1.45% / -1.45%
prewarmed history-page analyzer code shallow 12.292 / 12.296 [12.230–12.296] 12.099 / 12.102 [12.097–12.102] -1.57% / -1.58%
prewarmed history-page analyzer retained union 30.768 / 30.773 [30.706–30.773] 29.873 / 29.878 [29.872–29.878] -2.91% / -2.91%
prewarmed entry-read forced heap 74.656 / 74.660 [74.655–74.660] 72.689 / 72.698 [72.687–72.698] -2.64% / -2.63%
prewarmed entry-read V8 code 1.888 / 1.889 [1.886–1.889] 1.885 / 1.887 [1.882–1.887] -0.16% / -0.12%
prewarmed entry-read V8 bytecode 2.366 / 2.366 [2.366–2.366] 2.337 / 2.337 [2.337–2.337] -1.25% / -1.25%
prewarmed entry-read analyzer code shallow 12.896 / 12.897 [12.893–12.897] 12.726 / 12.729 [12.724–12.729] -1.32% / -1.30%
prewarmed entry-read analyzer retained union 33.532 / 33.534 [33.530–33.534] 32.692 / 32.696 [32.689–32.696] -2.51% / -2.50%
prewarmed entry-list forced heap 68.714 / 68.724 [68.706–68.724] 66.577 / 66.579 [66.572–66.579] -3.11% / -3.12%
prewarmed entry-list V8 code 1.849 / 1.856 [1.846–1.856] 1.844 / 1.845 [1.840–1.845] -0.29% / -0.61%
prewarmed entry-list V8 bytecode 2.265 / 2.265 [2.265–2.265] 2.234 / 2.234 [2.234–2.234] -1.38% / -1.38%
prewarmed prewarm forced heap 67.243 / 67.245 [67.229–67.245] 65.114 / 65.118 [65.113–65.118] -3.17% / -3.16%
prewarmed prewarm V8 code 1.796 / 1.800 [1.793–1.800] 1.787 / 1.788 [1.786–1.788] -0.53% / -0.67%
prewarmed prewarm V8 bytecode 2.186 / 2.186 [2.186–2.186] 2.153 / 2.153 [2.153–2.153] -1.50% / -1.50%
All worsening p50/p95 cells, including small changes
Task/mode Metric Worsening cells
cold history-page ready p95 +41.16% gate flag
cold history-page first p50 +0.32%; p95 +5.24%
cold history-page total p95 +16.97%
cold entry-read ready p95 +13.02%
cold entry-read first p95 +12.35%
cold entry-read total p95 +14.38%
cold entry-read V8 code p95 +0.17%
cold entry-list ready p50 +2.39%; p95 +36.94% gate flag
cold prewarm ready p50 +1.92%; p95 +2.20%
prewarmed entry-read ready p50 +2.46%
prewarmed entry-read first p50 +4.01%
prewarmed entry-read total p50 +1.89%
prewarmed entry-list first p50 +9.08%

The original entry-read series exposed a real incomplete cutover: a dynamic first-task import of session-accessor.sqlite-exact-read.ts reloaded the writable DB/scope graph. Its scripts increased 2731→2734 cold and 2865→2868 prewarmed; cold first-task p95 rose 30.53%, and prewarmed ready p95 / first-task median / total p95 rose 47.44% / 38.86% / 41.48%. Those original raw results are preserved. The synchronous writable facade was moved into its admitted-read owner and only affected entry-read was measured again. Every corrected candidate inventory excludes openclaw-agent-db.ts, openclaw-agent-db-lifecycle.ts, session-accessor.sqlite-scope.ts, and session-accessor.sqlite-entry-admitted-read.ts after a real entry result.

The first corrected-entry attempt was a setup failure, with zero valid samples: Node strip-only substitution rejected an existing TypeScript parameter property. Node 26 also rejects the proposed mode: "transform"; that invalid approach was removed before measurements. The supported correction preprocesses only strip-rejected source in the parent using already-installed esbuild 0.28.2 and repository tsconfig, before timers. Both baseline and candidate exact-read sources use the same transform. The only other transformed file is an unloaded test source. Original raw sources remain preserved; the worker hook is byte-identical to baseline and no compiler is retained inside measured workers. Prior history/list/prewarm loaded sources remain on the unchanged strip path.

Bounded A/A control: five alternating cold-history pairs load identical baseline source for both labels. This tests unchanged-code variability under the current host load; it neither reruns the primary candidate comparison nor disproves its flags.

A/A metric Label A Label B Δ p50 / p95
ready 2,158.46 / 2,646.70 [1,777.65–2,646.70] 1,760.70 / 2,253.50 [1,635.77–2,253.50] -18.43% / -14.86%
first 6,470.90 / 6,599.86 [4,842.10–6,599.86] 5,352.96 / 5,609.92 [5,159.57–5,609.92] -17.28% / -15.00%
total 8,758.31 / 9,081.94 [6,746.04–9,081.94] 7,131.14 / 7,836.40 [6,877.28–7,836.40] -18.58% / -13.71%

A/A 1-minute host load: 82.12–89.69; all ten inventories contain 2608 scripts. The observed A/A spread describes uncertainty only; primary history/list cold-ready p95 gate flags remain open.

The committed workload commands are:

node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output /path/to/proof/history --baseline-ref db440e9d6220 --samples 5 --task-kind history-page --snapshots
node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output /path/to/proof/tasks --baseline-ref db440e9d6220 --samples 5 --task-kind prewarm --task-kind session-entry-read --task-kind session-entry-list
node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output /path/to/proof/entry-final --baseline-ref db440e9d6220 --samples 5 --task-kind session-entry-read --snapshots
node --import ./scripts/tsx.mjs scripts/perf/session-transcript-code-measure.mjs --output /path/to/proof/control --baseline-ref db440e9d6220 --samples 5 --prewarm false --control --task-kind history-page
node --import ./scripts/tsx.mjs scripts/perf/agent-db-borrower-gateway-proof.ts --state-dir /path/to/proof/gateway

--snapshots runs the merged scripts/heap-snapshot-diff.mjs --code-by-script analyzer for every snapshot. Retained rows overlap, so the table uses the analyzer's union, never a sum of per-script retained values. Forced-GC retention does not measure allocation churn or natural-GC latency. These are synthetic real-worker measurements; Gateway correctness is separate evidence.

Final-source correctness passed through an isolated development Gateway and four real WebSocket clients. All seven concurrent RPCs succeeded before maintenance and all seven afterward. During maintenance, three list reads and the writer succeeded; three history reads returned visible temporary-unavailable/resources-closing refusals and recovered afterward. The parent-process admitted handle was closed and its retained claim invalidated before the maintenance callback. Main-session transcript markers survived. The historical v2026.9.9 fixture migrated from schema 24 to 34 and passed integrity checking; historical row-content equality was not tested. This checks same-process borrower custody separately from worker-local RPC activity; it does not inspect worker-local pin counts.

One final-source Gateway attempt exposed a proof-script defect: its allowed maintenance-error matcher recognized “closed” but not “closing,” and its rejection could escape before the maintenance promise was joined. The script now joins both operations with Promise.allSettled, then rethrows unexpected failures. The corrected rerun passed with the refusals described above and clean shutdown.

Focused validation passed: 325 tests across 23 files for lifecycle, leases, identity, maintenance, disposal, read scopes, writer preparation, target ownership, committed reads, and history integration; one existing Windows-only path case was skipped on macOS. The final exact-reader correction passed another 501 tests across 10 files, including read workers, memory/environment capture, source/rollback errors, sandbox, Doctor recovery, agent defaults, and Gateway handlers. Core/scripts typechecks, changed-file lint, formatting, and diff checks pass. Independent Codex review of the original full change and the final continuation found no actionable P0–P2 findings. Simplification retained one selection owner and one writable-admission adapter.

The full build passed at 71e80b868c87 in 11m 44s. It emitted an unrelated Control UI CSS-budget advisory (1558.2 KiB versus 1558.1 KiB); no UI files changed. The final continuation has targeted checks and live Gateway proof, not a repeated full build. The wrapper inventory correction additionally passed all four focused checks after two failed before the correction. The quiet-node measurement now permits ready status. Exact-head CI finished red; its terminal results and failure attribution are recorded below. No merge is authorized.

Historical CI follow-up at the test-only repair head

The first ready run (40166712800, head 0cc91a43635f6deb3f8e25209a0beb24d488f788) found two PR-owned test-contract issues. The repair at 661b5b32bad12166fad4fc0af2fcf4bcdd368b3f documents why three synthetic lifecycle fixtures isolate real state, removes exactly their three obsolete mock-baseline entries, and points the target-dedupe work-count spy at the registry-listing owner used by production. Assertions and production behavior are unchanged.

The four affected test files pass (30 tests). The three lifecycle files took 26.32 seconds wall time together; target dedupe took 109.74 seconds including a cold compiler preparation (four tests, 102.41 seconds Vitest duration). Mock-export ratchet, changed-file formatting/lint, diff checks, and independent P0–P2 review pass. No production lines changed in this follow-up. This push is a real repair; no failed CI job was rerun for green.

Three additional failures from that first run remain explicitly unresolved: CLI Git-backup diagnostic tail preservation, child-follow-up completion, and terminal delivery after a token-limit response. The newest scheduled main observed during diagnosis (40165856223, 34a8d5c04cb5c9bad829b72936385cc71f3ed431) has six different failures; none establishes a matching inherited signature for these three. The child-follow-up file passed a bounded local 30-test replay; that does not prove a repair. The CLI formatting/redaction probe preserved both expected tail markers, but did not reproduce the exact pinned-Bun shipped-CLI entry point. The unchanged terminal-delivery test reproduced the exact CI assertion locally: expected the missing-answer notice, received the output-token-limit warning. The likely mechanism is host-generated warning text being treated as deliverable assistant text before fallback classification; changing the expected notice would hide the subsequent required-fallback assertion. Both implicated production files and the test are byte-identical to scheduled main, which proves source identity but not a matching main-run failure. This production defect remains untouched under the measurement-only scope.

Natural CI for the repaired head (40167851556) finished FAILURE with four failed ordinary jobs and a failed aggregate gate. All three PostgreSQL conformance shards passed. The failure-report job completed successfully. CodeQL and all five selected Critical Quality checks passed; no PR checks remain pending. The required aggregate gate is red. The corrected mock-ratchet job passed. The earlier child and dedupe failures did not appear in the settled ordinary jobs; their focused local suites pass, but changed shard numbering is not being used as per-test CI proof.

Failed check Exact evidence and attribution
CLI diagnostic test Repeats missing stderr-tail-🦞 in Git-backup failure output; unresolved, with no matching newest-main failure.
Terminal-delivery QA Repeats the line 337 token-limit-warning mismatch and reproduces locally; likely existing fallback-handling defect, but no matching newest-main failed job.
Dependency-installation wrapper test Matched inherited signature: publishes one complete dependency installation when creators overlap, timeout 120000 ms at test/scripts/pr-wrappers.test.ts:1446:2, exactly matches newest scheduled main job 121086753163.
Lint test/helpers/claude-managed-settings.ts:21:5, no-recursive-readdir: introduced by incoming main base cfa7f09c6395ce5956f9acfab025fd46131e0b59 in GitHub merge checkout f6be8c5d6b5a5caeeefb657a68610f2205b85051; file absent from this branch. Newest scheduled-main lint passed, so this is source-attributed to incoming main but not a matching scheduled-main failure.

The latest scheduled-main reference checked for this comparison is 40165856223, completed failure at 34a8d5c04cb5c9bad829b72936385cc71f3ed431. The automatic failure reporter classifies lint, CLI, and terminal QA as unknown. It labels the wrapper failure new because it compares numeric small-1 against a passing main small-1 job and explicitly says selected scope was not compared. The manual signature comparison above instead locates the identical failing test in main small-31; this is diagnostic attribution, not an automatic exemption or a green gate. No reruns, new baseline allowances, production edits, or assertion weakening were used to chase green. The preceding run was superseded by this real test repair: five failed jobs retain their evidence, PostgreSQL shard 3 passed, and shards 1/2 plus the final gate were canceled. Ready status reflects the passed performance measurement rule, not a claim that CI is green. The lead owns merging; no merge or automatic merge has been requested.

@clawsweeper

clawsweeper Bot commented Oct 25, 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 gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 25, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR separates session readers from writable database imports while sharing existing handle custody and lifecycle behavior.

Example: Read a synthetic saved session containing two messages in a cold entry-read worker.

  • Before: The recorded worker loaded 2,731 scripts and retained 70.237 MiB of forced-GC heap.
  • After: The recorded worker loaded 2,631 scripts and retained 66.582 MiB of forced-GC heap.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful measured improvement with production-path evidence, focused lifecycle regressions, and no actionable findings; broad current-head CI is still running.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied production-worker measurements establish reduced retained code and heap, and an isolated Gateway with real WebSocket clients exercises history, listing, writes, maintenance refusal, recovery, and claim revocation; the latest timer repair additionally has a recorded red-before/green-after lifecycle regression.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Session read workers retain writable admission and migration code that their read operations do not need.
Reason: The maintainer-authored direction has measurable retained-memory benefits, and the implementation keeps the established lifecycle and synchronous API contracts.

Merge readiness

✅ Ready for maintainer review

This PR remains worthwhile, with no actionable findings at the reviewed head; the timer repair restores borrower lookup behavior, the recorded Linux acceptance rule is satisfied, and current-head CI remains pending.

Priority: P2
Reviewed head: 0eba919f17f46f11b2c9910c17da7860f6b064a4

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway history and session-entry requests reach read workers that resolve physical stores and consume admitted database handles; the writable lifecycle retains opening, migration, leases, timers, and closure.

flowchart LR
  Gateway[Gateway requests] --> Workers[Session read workers]
  Workers --> Scope[Read scope resolution]
  Scope --> Borrower[Shared borrower state]
  Borrower --> Database[Admitted database handle]
  Lifecycle[Writable lifecycle] --> Borrower
  Lifecycle --> Database
Loading

Technical review

Best possible solution:

Keep narrow read imports and shared borrower custody, with the existing writable lifecycle remaining the sole opener and timer owner.

Do we have a high-confidence way to reproduce the issue?

Source tracing and the supplied baseline/candidate worker measurements establish unnecessary writer imports; this read-only review executed no target code.

Is this the best way to solve the issue?

The split uses existing selection, routing, and lifecycle owners, removes replaced implementations, and preserves public barrel exports without adding another opener or timer implementation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6e298fbd79e0.

Provenance checked

  • Shared database borrowing and lifecycle custody keeps the original intent (9a6a97f: Keep cold reconciliation responsive while one lifecycle owns pending admission, borrower pins, eviction, and native close settlement.)
  • Physical session scope resolution keeps the original intent (b70c538: Share database ownership, incognito, path, and cache resolution without changing caller normalization or errors.)
  • Idle handle retention and CLI lease release keeps the original intent (f8ce98e: Release idle CLI leases promptly while retaining the Gateway window and preserving borrowed handles and transactions.)
  • Synchronous entry compatibility and shared selection keeps the original intent (refactor(sessions): cut over snapshot callbacks and SDK reads to workers #169637: Move runtime reads to workers while retaining documented synchronous SDK compatibility during migration.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +121, Tests +56, Docs +8, Other +457. Total +642 across 68 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 43 689 568 +121
Tests 20 76 20 +56
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 4 603 146 +457
Total 68 1376 734 +642

Review metrics

Metric Value Why it matters
Production versus test growth Production +689/−568, net +121; tests and harnesses +76/−20, net +56. Growth establishes import boundaries and preserves synchronous admission around shared selection logic; added tests cover distinct timer, pin, and revocation failures.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 other: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: Measured session-worker memory savings provide useful improvement without evidence of an urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-25T04:45:34.732Z sha 71e80b8 :: needs changes before merge. :: [P2] Include the extracted modules in the PR wrapper inventory
  • reviewed 2026-10-25T05:03:44.914Z sha 71e80b8 :: blocked before merge. :: [P2] Include the extracted dependencies in the PR wrapper inventory
  • reviewed 2026-10-25T05:35:17.030Z sha 0cc91a4 :: blocked before merge. :: none
  • reviewed 2026-10-25T05:42:11.171Z sha 0cc91a4 :: blocked before merge. :: none

Reviewed October 25, 2026, 4:30 AM ET / 08:30 UTC (Revision 5).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 25, 2026
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Oct 25, 2026
@steipete steipete changed the title improve: reduce session read worker startup and retained code improve: reduce retained code in session read workers Oct 25, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The wrapper inventory finding is fixed in 0cc91a4. The existing inventory/source-closure checks reproduced exactly three missing dependencies; adding those paths makes all four selected checks pass. No wrapper execution or authority behavior changed.

The real entry-read measurement also exposed and corrected a dynamic import back into writable admission. The PR body now has the completed five-pair measurements, loaded-script inventories, code/heap distributions, every worsening metric, unchanged-code control, final-source Gateway proof, and scoped verification. The branch and body are current.

The PR remains draft: history and entry-list cold-ready p95 regressions of 41.16% and 36.94% remain unresolved. The control describes measurement variability; it does not waive those flags or supply owner acceptance.

@clawsweeper

clawsweeper Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. labels Oct 25, 2026
@steipete
steipete marked this pull request as ready for review October 25, 2026 05:45
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T20:46:15.685684Z fd4a1b8 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 7cb7671433cea335fad369d6d1657c0001a6017b
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/runtime-status.legacy.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Head 0eba919f17f46f11b2c9910c17da7860f6b064a4 restores missing-timer installation through the writable lifecycle owner. The regression is red before the fix and green afterward; 127 focused tests and the affected static checks pass. The PR body contains the complete import-order audit and the current CI link.

@clawsweeper

clawsweeper Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Oct 25, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Closing without merging. The heap win is real (session-transcript worker post-GC heap −2.6% to −7.6%, cold prewarm −30%). The latency flags were cleared on a quiet Linux node, and both review findings (late-import trace, idle-timer install) were resolved. What decides it is the CI risk signal:

Three CI runs on three heads each failed a different small set of agent-DB lifecycle and session tests. A final interleaved 20× base/head run on the Linux rig, with the same node_modules, gave:

Test Head failures Base failures
Inline child follow-up (timeout, "Subagent terminal execution changed") 1/20 0/20
Warm readers: prepared repository rows (extra event) 1/20 0/20
Close-wedge: native cleanup cause 20/20 20/20
Session-row: facts before cancellation observers 20/20 20/20
Thinking claim (delivered-event) 0/20 0/20

The two head-only failures are exactly the signatures CI hit on this PR's heads, and neither ever failed at base (0/40). That suggests a timing change in subagent completion and warm reads. For +110 production lines and a single-digit worker-heap saving, that isn't worth carrying.

The two 20/20 failures happen on base too. They are pre-existing main defects and are being reported separately.

Branch steipete/perf-agent-db-borrower-split-20261025 is kept for anyone who wants to revisit the split with a deterministic proof of subagent-completion ordering.

…ecycle

Keep read scope and admitted-handle lookup out of the writable opener graph while preserving synchronous writer admission, shared idle pins, explicit revocation, maintenance custody, and engine support. Extend the existing idle-custody and identity contracts and add repeatable worker/Gateway proof workloads.
Keep shared selection and error handling in the read owner while preserving synchronous writable admission in its own entry facade. Real worker measurements exposed this dynamic import path after the initial borrower split. Join the concurrent Gateway proof operations before cleanup and recognize the existing resources-closing maintenance refusal.
Keep the worker loader unchanged and preserve raw captured sources. Use the existing compiler only for valid syntax rejected by native stripping, with identical preparation for baseline and candidate before timers start.
Add the three extracted runtime dependencies named by the existing inventory and readonly-location closure checks. Preserve explicit extraction scope and all wrapper authority behavior.
Delegate cached borrower activity to the writable lifecycle installer, preserving missing-timer installation and shutdown cleanup behavior without importing the lifecycle into readers. Retire its callback with the test singleton generation and cover idle eviction plus lease release after a missing timer.
@steipete
steipete force-pushed the steipete/perf-agent-db-borrower-split-20261025 branch from 74da273 to fd4a1b8 Compare October 25, 2026 20:43
@steipete
steipete merged commit ee6efea into main Oct 25, 2026
201 checks passed
@steipete
steipete deleted the steipete/perf-agent-db-borrower-split-20261025 branch October 25, 2026 23:01
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
* perf(sessions): separate passive database borrowing from writable lifecycle

Keep read scope and admitted-handle lookup out of the writable opener graph while preserving synchronous writer admission, shared idle pins, explicit revocation, maintenance custody, and engine support. Extend the existing idle-custody and identity contracts and add repeatable worker/Gateway proof workloads.

* perf(sessions): keep exact readers off the writable admission graph

Keep shared selection and error handling in the read owner while preserving synchronous writable admission in its own entry facade. Real worker measurements exposed this dynamic import path after the initial borrower split. Join the concurrent Gateway proof operations before cleanup and recognize the existing resources-closing maintenance refusal.

* test(perf): prepare non-erasable TypeScript outside worker measurements

Keep the worker loader unchanged and preserve raw captured sources. Use the existing compiler only for valid syntax rejected by native stripping, with identical preparation for baseline and candidate before timers start.

* fix(tooling): include borrowed database readers in the PR wrapper

Add the three extracted runtime dependencies named by the existing inventory and readonly-location closure checks. Preserve explicit extraction scope and all wrapper authority behavior.

* test: align borrower split fixtures with narrow owners

* fix(state): restore borrower idle timer installation

Delegate cached borrower activity to the writable lifecycle installer, preserving missing-timer installation and shutdown cleanup behavior without importing the lifecycle into readers. Retire its callback with the test singleton generation and cover idle eviction plus lease release after a missing timer.

* test(gateway): declare main-thread data in goal fixture
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime 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. scripts Repository scripts security-sensitive-changed size: XL 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