Skip to content

perf(sessions): avoid archive recovery stalls before replies - #158559

Merged
steipete merged 7 commits into
mainfrom
perf/l25-archive-admission-20260925
Sep 26, 2026
Merged

steipete merged 7 commits into
mainfrom
perf/l25-archive-admission-20260925

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes pauses before replies when an existing session checks for pending transcript archives behind background reclamation, even though no archives need recovery.

User Impact

Ordinary lifecycle upserts skip empty archive recovery. Real archive recovery, retention, and write settlement remain intact; there are no protocol, configuration, schema, or upgrade changes.

Why This Change Was Made

The lifecycle row reader now carries a pending-archive fact from the same snapshot, bound to the physical database identity. Unknown or replaced identities retain conservative recovery, and archive-producing mutations and Doctor transfers still publish. Standalone probes reuse the history reader without archive FIFO or writer admission. Maintenance finalization requests admission for native access and keeps it through commit publication, while preparation and validation allow foreground writes to proceed.

Evidence

Same Testbox (4 CPUs, Linux, Node 26.9.0), exact baseline cc23d2a7f8b versus candidate f838c345e0d; fresh isolated state, mock provider, three turns per client, A/B/B/A order with identical timeline instrumentation. Values below are medians of the two trial medians; warm means turns 2–3.

Metric 1 client: before → after 5 clients: before → after
Warm session initialization 92.39 → 6.24 ms (-93.2%) 193.02 → 63.09 ms (-67.3%)
Warm send → first delta 278.46 → 177.56 ms (-36.2%) 744.19 → 535.51 ms (-28.0%)
Cold session initialization 278.77 → 16.67 ms 547.43 → 94.52 ms
Pending archive probes per trial 4 → 0 16 → 0

Archive/reclamation worker constructions fell from 6 → 2 for one client and 19 → 3/2 for five; background reclamation remained enabled. All 72 turns completed, with no failed/pending turns, disconnects, or integrity errors. Both five-client candidate trials recorded one pre-load chat.metadata access-change UNAVAILABLE error, also observed in the earlier campaign investigation. Those runs remain completed-with-errors; these small instrumented trials do not establish 50-session capacity.

Dedicated Testbox run: full builds passed in 7:37.75 / 8:09.72; node scripts/check-changed.mjs passed in 24:50.00. The same changed gate also passed locally (3828.31 s).

All 120 candidate tests passed. Commands used node scripts/run-vitest.mjs <file> --maxWorkers=1:

Test file (under src/config/sessions/) Tests Command wall
session-accessor.sqlite-archive-session.test.ts 21 34.66 s
session-accessor.sqlite-fresh-upsert-archive.test.ts 10 26.53 s
session-accessor.sqlite-maintenance-admission.test.ts 1 12.57 s
session-entry-read.worker.test.ts 15 18.57 s
Grouped maintenance-worker, archive.worker, archive-admission, and handle-lifecycle suites 73 62.17 s

The archive suite retains native file-publication, crash-recovery, and worker-retirement contracts that a mocked helper cannot prove; its wall time includes worker preparation. CI test seconds are pending.

The two new empty-recovery assertions and revised maintenance-admission assertion all fail on the original code (21.73 s), with only those two test files copied onto the baseline. Raw assertions confirm the intended failures. The proof script's strict text classifier reported a false negative because Vitest abbreviated the maintenance expected array; this was manually verified against the failing source line, without rerunning or changing the test.

Every Gateway exited normally, all isolated states and child processes were cleaned up, the result archive checksum matched, and the lease is stopped. Initial proof attempts were stopped before measurements for a native-sync source-identity mismatch, slow local wrapper preparation, and the now-fixed line-cap violation.

The local focused run passed 66 tests across archive publication/recovery, lifecycle upserts, snapshot freshness, maintenance admission, and cached-handle closure (1156.51 s wall on the saturated host, including cold worker compilation). The parameter-type extraction afterward produces identical normalized JavaScript.

Deslop completed without further changes. Independent Codex review of the final branch found no actionable P0–P2 findings.

Production: +212/-160 lines (net +52); tests: +181/-93 (net +88); docs: +8. The production growth carries snapshot/identity facts through the existing reader and replaces the old per-probe worker operation. The existing lifecycle parameter type was moved to its types owner to keep the projection module within its line cap.

Overlap inspected: #158530 (diagnostic reader), #158450 (artifact reader), #158401 (creation path aliases), and #157934 (archive-worker identity). Their production hunks are separate from this recovery/admission cutover; the worker operations use distinct request kinds and the same existing reader owner. No PR is stacked here.

Landing CI repair

Exact-head CI run 36210394268 found a static import cycle through lifecycle state, agent execution, and the replacement implementation; CI fail-fast then cancelled the remaining jobs. The same cycle reproduced locally on f838c345e0dd128649952e799cbc953dbc66299e. Replacement request/result types now live in a leaf contract consumed directly by all four callers. No runtime behavior changed: all four existing modules produce identical normalized JavaScript.

The existing check:madge-import-cycles regression gate failed before this repair and passes afterward with zero cycles. Core typechecking, targeted lint, formatting, and git diff --check also pass. No duplicate source-shape test was added.

Independent Codex review of the landing repair found no actionable P0–P2 findings.

The next exact-head run, 36212378732, passed the architecture repair and exposed a stale assertion in session-accessor.sqlite-cleanup-reclamation.test.ts: two warm empty cleanup passes expected two worker constructions, while the new shared history reader correctly constructs one. The full local file reproduced that single failure with seven siblings passing. The existing case now explicitly requires warm reader reuse while retaining its diagnostic-phase, native-error identity, cleanup-result, and persisted-data checks. All eight tests pass after the correction (110.38 s command wall using node scripts/run-vitest.mjs <file> --maxWorkers=1; 6.28 s summed test execution in the preceding CI run). No production behavior or timeout changed for this correction.

Independent Codex review of the test correction found no actionable P0–P2 findings.

Run 36213751658 then exposed the corresponding stale writer-diagnostic sequence in session-accessor.sqlite-writer-owners.test.ts. The approved scheduling change removes the outer maintenance-finalize admission and the empty pending-archive probe's writer admission. Its existing coalescing case now requires the exact remaining sequence, including all three native worker-commit admissions and one finalization diagnostic; stale-row deletion and active-row preservation checks remain. The full local file reproduced the failure with seven siblings passing, then passed all eight tests after correction (72.41 s command wall; 7.02 s summed execution in the preceding CI run). Independent Codex review found no actionable P0–P2 findings, and a bounded sibling audit found no additional stale worker-count or admission expectations. No CI run was retried without a diagnosed repair.

Run 36214968626 exposed five prepared-admission fixture assertions: lifecycle callbacks now await the history reader, and maintenance validation intentionally permits foreground writers before native commit admission. The cases now require those behaviors while retaining final callback/FIFO, integrity, authority, and archival checks. Cold lifecycle fixtures also await retained reader cleanup before invalidating admission; synchronous close could leave resources draining and make best-effort finalization return before the probe. A complete local replay reproduced all five failures with 25 siblings passing. The repaired file plus the maintenance commit-settlement sibling pass all 31 tests (80.65 s grouped command wall; prepared-admission recorded 25.06 s test execution in the preceding CI run). These native integrity and deletion/archival boundary cases retain their real worker/subprocess proof; no timers or timeouts were added. Independent Codex review found no actionable P0–P2 findings, and the broader sibling FIFO audit found no further affected expectations.

Run 36216465597 was blocked by an unrelated main regression: the UI E2E graph imported ControlUiRootState from its retired exporter after #158464. The same TS2459 reproduced on current main and the corrected import passed the exact graph. Main fix da8149b8ba7d88d76dbe7979986e307a4542e6f0 landed concurrently with that diagnosis; no duplicate fix was published. Current main was merged into this PR without conflicts to incorporate it and obtain fresh merge-ref CI.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L labels Sep 26, 2026
@steipete
steipete marked this pull request as ready for review September 26, 2026 02:02
@clawsweeper

clawsweeper Bot commented Sep 26, 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.

@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 Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 12:39 AM ET / 04:39 UTC (Revision 5).

ClawSweeper review

What this changes

The branch reads session rows and pending-archive state in one SQLite worker snapshot, skips empty archive recovery during ordinary updates, and delays maintenance writer admission until native work needs it.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still takes the archive-probe path associated with the reported reply stalls. The branch has credible Gateway timing evidence, and this review found no definite introduced defect.

Priority: P2
Reviewed head: ed4abd3ebfd6d5749f831d6f7488a8bd8b621b00

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has focused owner-boundary coverage and credible real-Gateway timing evidence, with no definite correctness or security finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body reports real Gateway chat turns on one Linux Testbox with an isolated state and mock provider, comparing the baseline with the candidate and observing faster warm initialization and first reply deltas. Its later head retains the central production path; the disclosed five-client metadata errors and capacity limit remain explicit. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body reports real Gateway chat turns on one Linux Testbox with an isolated state and mock provider, comparing the baseline with the candidate and observing faster warm initialization and first reply deltas. Its later head retains the central production path; the disclosed five-client metadata errors and capacity limit remain explicit. No stored-data contract changes.
Evidence reviewed 8 items Current-main behavior: Current main still requests archive publication for ordinary maintained upserts, and its exact-entry worker result has no pending-archive fact. The branch's central shortcut is therefore still useful.
Introduced snapshot path: The PR uses the existing history reader for a lifecycle projection when the database supports worker execution, while retaining the native path for removals and repair.
Archive decision and fallback: The commit uses the snapshot's pending fact only when its physical database identity matches; otherwise it retains conservative recovery. Archive-producing mutations, removals, and Doctor transfers still request publication.
Findings None None.
Security None None.

How this fits together

The session lifecycle layer updates per-agent SQLite session rows as chat turns proceed. Its history worker supplies row and archive facts; archive publication and maintenance can otherwise delay the next reply.

flowchart LR
  A[Chat turn] --> B[Session lifecycle update]
  B --> C[History worker snapshot]
  C --> D[Writer commit]
  D --> E{Archive recovery needed?}
  E -- No --> F[Reply continues]
  E -- Yes --> G[Archive publisher]
  G --> F
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +52, Tests +88, Docs +8. Total +148 across 25 files.

View PR surface stats
Area Files Added Removed Net
Source 17 212 160 +52
Tests 7 181 93 +88
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 25 401 253 +148

Review metrics

Metric Value Why it matters
Warm session initialization 1 client: 92.39 → 6.24 ms; 5 clients: 193.02 → 63.09 ms The reported same-Testbox Gateway trials measure the latency of the affected reply path.
Production versus test growth production net +52 lines; tests net +88 lines The stated production growth carries snapshot and identity facts through the existing reader while retiring the separate pending probe.

Technical review

Best possible solution:

Keep ordinary replies free of empty archive-recovery waits while preserving pending-archive recovery, database replacement checks, and native write settlement.

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

No current-main runtime replay was performed in this read-only review. Current main retains the reported probe path, and the PR supplies a detailed Gateway before-and-after run on an earlier baseline and candidate.

Is this the best way to solve the issue?

Yes. Reusing the existing history worker and retaining the native archive publisher is a focused way to remove the empty-recovery delay without adding a second storage owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 3afde1f98247.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR addresses measurable reply latency in an existing session path without evidence of a broader outage.
  • 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. Sufficient (live_output): The PR body reports real Gateway chat turns on one Linux Testbox with an isolated state and mock provider, comparing the baseline with the candidate and observing faster warm initialization and first reply deltas. Its later head retains the central production path; the disclosed five-client metadata errors and capacity limit remain explicit. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body reports real Gateway chat turns on one Linux Testbox with an isolated state and mock provider, comparing the baseline with the candidate and observing faster warm initialization and first reply deltas. Its later head retains the central production path; the disclosed five-client metadata errors and capacity limit remain explicit. No stored-data contract changes.

Evidence

What I checked:

  • Current-main behavior: Current main still requests archive publication for ordinary maintained upserts, and its exact-entry worker result has no pending-archive fact. The branch's central shortcut is therefore still useful. (src/config/sessions/session-accessor.sqlite-projection.ts:541, 3afde1f98247)
  • Introduced snapshot path: The PR uses the existing history reader for a lifecycle projection when the database supports worker execution, while retaining the native path for removals and repair. (src/config/sessions/session-accessor.sqlite-lifecycle-state.ts:368, ed4abd3ebfd6)
  • Archive decision and fallback: The commit uses the snapshot's pending fact only when its physical database identity matches; otherwise it retains conservative recovery. Archive-producing mutations, removals, and Doctor transfers still request publication. (src/config/sessions/session-accessor.sqlite-projection.ts:514, ed4abd3ebfd6)
  • Snapshot freshness coverage: The new worker test checks that a concurrent archive insert remains outside the first SQLite snapshot and becomes visible on the next read; it also checks publication-state changes. (src/config/sessions/session-entry-read.worker.test.ts:100, ed4abd3ebfd6)
  • Maintenance settlement: Native commit admission still surrounds worker settlement and publication after the outer preparation admission is removed; the revised admission test exercises foreground writes during preparation and validation. (src/config/sessions/session-accessor.sqlite-reclamation-run.ts:96, ed4abd3ebfd6)
  • Real behavior evidence: The captured PR body reports same-Testbox A/B/B/A Gateway turns with a mock provider: 72 turns completed, warm session initialization fell from 92.39 to 6.24 ms for one client and from 193.02 to 63.09 ms for five. The five-client candidate trials each recorded a pre-load metadata error and are explicitly marked completed-with-errors. The later head retains identical blobs for the central lifecycle, projection, archive, and reclamation files; this evidence does not establish 50-session capacity.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • joshavant: 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 (4 earlier review cycles)
  • reviewed 2026-09-26T02:09:10.154Z sha f838c34 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T02:48:01.958Z sha e494bb2 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T03:14:35.052Z sha c1218db :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T04:06:28.048Z sha 72f65b9 :: needs maintainer review before merge. :: none

Move replacement request and result types into a leaf contract so lifecycle archive admission does not cycle through the agent execution adapter and maintenance implementation. Migrate every consumer without compatibility re-exports.

Validation: the existing Madge cycle gate fails on f838c34 and passes after extraction; core typechecking, targeted lint, formatting, and diff checks pass. Existing modules compile to identical normalized runtime JavaScript. Independent Codex review found no actionable P0-P2 findings.
The pending-archive probe now shares the history reader. Update the existing diagnostics case to require one worker across both warm cleanup passes, preserving native failure identity, phase diagnostics, and stored data assertions.

Reproduced the exact CI assertion locally with seven passing siblings. All eight tests pass after the correction (110.38 seconds command wall); independent Codex review found no actionable P0-P2 findings.
…ter spans

Keep the exact maintenance coalescing sequence while dropping the retired outer finalization and empty archive-probe writer spans. Require the three native commit admissions and one finalization diagnostic, and preserve persisted stale/active entry checks.

The full file reproduced the CI failure with seven passing siblings. All eight tests pass after correction (72.41 seconds wall); independent Codex review found no actionable P0-P2 findings. A bounded sibling audit found no further stale admission or worker-count expectations.
Await retained reader cleanup before forcing lifecycle cold validation. Verify asynchronous lifecycle callbacks and foreground progress during maintenance validation while preserving native integrity, authority, commit order, and archive postconditions.

Reproduced the five stale assertions in the complete prepared-admission file. The repaired file plus maintenance settlement sibling pass all 31 tests (80.65 seconds wall). Independent Codex review found no actionable P0-P2 findings.
@steipete
steipete merged commit 0d7a4e8 into main Sep 26, 2026
203 of 205 checks passed
@steipete
steipete deleted the perf/l25-archive-admission-20260925 branch September 26, 2026 05:15
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
…w#158559)

* perf(sessions): keep archive recovery off empty chat upserts

* refactor(sessions): share lifecycle mutation parameter type

* fix(sessions): break lifecycle replacement contract import cycle

Move replacement request and result types into a leaf contract so lifecycle archive admission does not cycle through the agent execution adapter and maintenance implementation. Migrate every consumer without compatibility re-exports.

Validation: the existing Madge cycle gate fails on f838c34 and passes after extraction; core typechecking, targeted lint, formatting, and diff checks pass. Existing modules compile to identical normalized runtime JavaScript. Independent Codex review found no actionable P0-P2 findings.

* test(sessions): require archive reader reuse across warm cleanup

The pending-archive probe now shares the history reader. Update the existing diagnostics case to require one worker across both warm cleanup passes, preserving native failure identity, phase diagnostics, and stored data assertions.

Reproduced the exact CI assertion locally with seven passing siblings. All eight tests pass after the correction (110.38 seconds command wall); independent Codex review found no actionable P0-P2 findings.

* test(sessions): assert native maintenance writer admission without outer spans

Keep the exact maintenance coalescing sequence while dropping the retired outer finalization and empty archive-probe writer spans. Require the three native commit admissions and one finalization diagnostic, and preserve persisted stale/active entry checks.

The full file reproduced the CI failure with seven passing siblings. All eight tests pass after correction (72.41 seconds wall); independent Codex review found no actionable P0-P2 findings. A bounded sibling audit found no further stale admission or worker-count expectations.

* test(sessions): align cold admission fixtures with worker-backed reads

Await retained reader cleanup before forcing lifecycle cold validation. Verify asynchronous lifecycle callbacks and foreground progress during maintenance validation while preserving native integrity, authority, commit order, and archive postconditions.

Reproduced the five stale assertions in the complete prepared-admission file. The repaired file plus maintenance settlement sibling pass all 31 tests (80.65 seconds wall). Independent Codex review found no actionable P0-P2 findings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation 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