Skip to content

fix: keep other chats responsive during cold history restoration - #200930

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-cold-restore-writer-hold-20260919
Nov 18, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-cold-restore-writer-hold-20260919

Conversation

@steipete

@steipete steipete commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Related: #200076

What Problem This Solves

Restoring a large archived conversation holds the agent database writer while it decodes and rebuilds the whole transcript. Messages in other conversations then wait behind that restore, even when storage is otherwise idle.

User Impact

Other conversations can write between restore batches. Readers continue to see the complete cold archive until restoration finishes; an interrupted restore remains cold and can be retried. No schema, configuration, or retention changes are required.

Why This Change Was Made

Prepare payloads outside writer admission and reuse the navigation and identity projections already retained by cold storage. Replace the full-session delete and replay with batches of at most 256 records, releasing the shared writer reservation after each batch. The existing cold marker remains the visibility boundary. The existing worker accepts its commit grant only for final hot publication, then retains custody through settlement. Published legacy archives still rebuild their missing projections.

Production source grows by 174 lines (+277/-103) for bounded orchestration, admission release, and prepared-payload replay. This removes the monolithic restore path without introducing a scheduler, durable progress state, or schema change. The obsolete rollback-only navigation benchmark restore arm is replaced by the real restore-flow harness; the memory benchmark retains its explicit frozen pre-batched baseline interface.

Evidence

Final measured head: 6fb80f96f82abf462f65a99abffd60fa491a1fca. Five serial A1/A2/B cycles used fresh copies of a synthetic 37.3 GiB agent database: 2,401 sessions, 6.05 million events, a 50,000-event cold target, and 100 concurrent real transcript appends to another session. Controls use parent 7f395779d12a0c5d16ed28d8cf4d37fbe8c098ec. Host: Apple M3 Ultra, 512 GiB RAM, Node 26.12.1, APFS, shared host load. These are synthetic measurements, not production filesystem latency guarantees.

Median across five runs A1 A2 Candidate
Per-restore maximum writer hold 24,827 ms 19,283 ms 236 ms
Public restore elapsed 43,967 ms 33,437 ms 18,661 ms
Per-append cumulative reservation wait, p99 35,110 ms 23,190 ms 75 ms
Process CPU, including concurrent appends 31.100 s 27.650 s 20.000 s

Every candidate hold and p99 queue wait beat every control. Candidate maximum holds ranged from 181 to 735 ms; the 735 ms sample spent 721 ms at COMMIT and 13.6 ms in the transaction body. Candidate queue p99 ranged from 52 to 230 ms. All 15 runs passed exact JSON/sequence/timestamp verification for all 50,000 restored events, plus identity, active-row and FTS counts. No median elapsed/CPU regression exceeded the predeclared 20% limit; both improved substantially.

Separate A/A/B profiles included collected-object heap sampling across all observed transaction isolates. Cold-owner sampled allocations fell from 4.449/4.431 GB to 3.900 GB (about 12%); sampled owner CPU fell from 21.34/18.59 s to 10.12 s. Whole-process lifetime sampled allocations increased from 13.820/13.754 GB to 15.115 GB (about 9–10%, 24 observed isolates versus 22). These are allocation traffic estimates, not retained-heap measurements; the whole-process increase is retained in the result. All three profiled restores also passed exact verification.

  • The 10,000-row regression fails on the exact parent: a 5,317 ms reservation exceeds its 1,000 ms budget. It passes with this change and proves a real foreground writer completes while the cold marker remains after a durable payload batch.
  • Final custody/lifecycle/admission suites: 45 tests passed. Main-thread filesystem suite: 4 passed. Existing accepted-close/cancellation assertions remain unchanged. Foreign conversation alternatives, physical replacement refusal, and exact retry recovery pass. Earlier focused storage, chunk, worker, payload and actor-residency proof remains applicable.
  • Abort/reopen proof interrupts a 600-event restore after a durable batch and verifies exact recovery for both retained-navigation and published legacy archive layouts.
  • A real isolated Gateway upgrade from latest stable 2026.11.5 restored two archived sessions, preserved all nine original events and timestamps exactly, accepted new messages, preserved settings, and shut down cleanly. Repeated on the final production source.
  • Affected Control UI browser tests: 17 passed. Transcript-search UI end-to-end tests: 4 passed.
  • Initial and repair pnpm check:changed, final focused lint/typechecks, and runtime/Control UI artifact builds passed. Final independent Codex review found no actionable P0–P2 findings.
  • Two initial measurement cycles were rejected because fixture configuration was not loaded into the runtime policy owner. The harness now loads that owner and asserts disk eviction is disabled. A subsequent qualified pre-repair series is preserved separately; the table above uses the final source.

CI run 44224828739 exposed two PR-caused defects (accepted custody and old benchmark API callers); both are fixed at the measured head. No failure is being classified as inherited. Exact-head CI run 44231605844 and the final ClawSweeper review gate landing.

Prepare restore payloads before writer admission, reuse retained navigation, and replay bounded batches while the cold marker owns reader visibility. Preserve recoverable partial replay for current and legacy archives without schema or configuration changes.
@clawsweeper

clawsweeper Bot commented Nov 18, 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 scripts Repository scripts size: L labels Nov 18, 2026
@steipete
steipete marked this pull request as ready for review November 18, 2026 02:39
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T03:39:58.828049Z 6fb80f9 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Restore archived transcripts in bounded transactions so other conversations can write between batches.

Example: Restore a 50,000-event archive while another conversation submits 100 transcript appends.

  • Before: Reported control median maximum writer holds were 24.8 and 19.3 seconds.
  • After: The candidate median maximum hold was 236 milliseconds, with exact restored-event verification.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Controlled production-path measurements, Gateway upgrade evidence, focused recovery coverage, and passing exact-head CI support the focused implementation.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Final-head evidence exercises the public restoration owner with real concurrent transcript appends on a synthetic 37.3 GiB database, reports substantially shorter writer holds with exact restoration checks, and records an isolated latest-stable Gateway upgrade preserving settings, events, and timestamps.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Messages in other conversations wait while a large archived transcript monopolizes their shared database writer.
Reason: The maintainer-authored direction addresses measured contention while preserving transcript contents, existing storage ownership, and recoverability.

Merge readiness

✅ Ready for maintainer review

This PR addresses a remaining writer-contention problem on main; both earlier findings are resolved, and no actionable defect remains in the reviewed head.

Priority: P2
Reviewed head: 6fb80f96f82abf462f65a99abffd60fa491a1fca

Before merge

None.

Findings

None.

Agent review details

How this fits together

The session archive worker reads verified cold chunks, prepares transcript payloads, and writes through the existing agent database admission owner; the cold marker controls reader visibility until final publication.

flowchart TD
  A[Restore request] --> B[Archive worker queue]
  B --> C[Verify chunks and prepare payloads]
  C --> D[Bounded writer admissions]
  E[Other conversation writes] --> D
  D --> F[Final hot publication]
  G[History readers] --> H[Complete cold archive]
  F --> G
Loading

Technical review

Best possible solution:

Use the existing archive worker and writer admission owner for bounded replay, retaining cold visibility until accepted final publication.

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

Current-main source exposes the monolithic writer hold, supported by the supplied base-failing regression and controlled measurements; no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is a focused repair using existing ownership: prepare outside admission, replay bounded units, and preserve the cold marker until completion without adding a schema or competing queue.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Atomic cold restoration changes intended behavior with a stated reason (9a3eb15: Decode chunks once with bounded memory and roll back the complete restoration on invalid metadata.)
  • Retained navigation and archive replay keeps the original intent (fce0e56: Serve bounded history reads from retained navigation while writes restore canonical archive payloads.)
  • Batched transcript insertion keeps the original intent (947947b: Reduce per-row SQL overhead while preserving archive order, exact data, and immediate foreign keys.)
  • Accepted mutation custody keeps the original intent (2c4413a: Move blocking filesystem work off the Gateway thread while preserving physical identity, authority, and accepted-work settlement.)
  • Navigation benchmark restoration arm changes intended behavior with a stated reason (fce0e56: Compare retained page reads with restoration followed by the same reader using rollback for repeatability; durable bounded restoration now requires the separate restore-flow workload.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +174, Tests +203, Docs +4, Other +30. Total +411 across 18 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 277 103 +174
Tests 6 241 38 +203
Docs 1 8 4 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 4 153 123 +30
Total 18 679 268 +411

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test growth Production +174 net lines; tests +203 net lines Growth supplies bounded orchestration and idempotent replay, with distinct foreground-interleaving and interrupted-recovery coverage rather than another scheduler or persistent progress model.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Large archived-session restores delay unrelated conversation writes sharing an agent database.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • 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 (1 earlier review cycle)
  • reviewed 2026-11-18T02:54:47.122Z sha f056da3 :: needs changes before merge. :: [P2] Preserve accepted restore custody across subsequent admissions | [P2] Migrate the remaining callers of the removed restore interface

Reviewed November 17, 2026, 11:09 PM ET / November 18, 2026, 04:09 UTC (Revision 2).

Keep provisional restore batches cold and recoverable, and preserve accepted close and cancellation custody for final hot publication. Migrate benchmark consumers and verify refused-publication recovery without changing the existing commit owner.
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed all three items from the previous review on 6fb80f96f82abf462f65a99abffd60fa491a1fca:

  1. Accepted restore custody. Provisional batches now return before requesting a commit grant; acceptance happens only at final hot publication (worker lines 462–480). There is no later admission that can reject already accepted publication. The unchanged accepted-close and accepted-cancellation tests pass, along with the pre-acceptance refusal case.

  2. Remaining restore callers. The memory benchmark uses the bounded restoration owner and preserves its named frozen pre-batched baseline contract (memory harness). The navigation benchmark retains its storage and page-owner measurements; its rollback-only restore counterfactual could not represent durable bounded transactions, so its header directs restoration measurements to the real restore-flow harness (navigation harness). Both current and frozen-baseline memory smoke runs restored 600 events byte-identically; navigation storage/page smoke and script typechecking pass.

  3. Original accepted-mutation intent (fix: reduce Gateway stalls under filesystem pressure #197510). The existing physical-source and accepted-authority checks remain immediately after the final grant (runtime lines 165–185); no new lifetime flag or authority mode was added. Foreign accepted alternatives are checked after that grant, while each provisional unit still validates its authoritative source rows. Refusal tests compare the durable state immediately before final publication, retain the cold marker/archive, and prove exact retry recovery (physical custody test); the direct replacement test additionally proves the replacement file is untouched (filesystem test).

Final proof: 45 custody/lifecycle/admission tests plus 4 filesystem tests passed; pnpm check:changed, focused lint/types, builds, stable Gateway upgrade and independent Codex review are green. The 10,000-row regression fails on the exact parent at 5,317 ms and passes with the fix, including a real foreground write before hot publication (regression).

The PR body now includes final five-cycle A/A/B and separate profiles. Median maximum writer holds are 24.8/19.3 s in controls versus 236 ms; worst candidate hold is 735 ms. Median append queue p99 is 35.1/23.2 s versus 75 ms. All 18 timed/profiled 50,000-event restores passed exact verification. Owner allocation falls about 12%; whole-process lifetime sampled allocation rises about 9–10%, explicitly retained in the evidence. Exact-head CI is still running; no inherited-failure exception is claimed.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 18, 2026
@steipete
steipete merged commit b83408f into main Nov 18, 2026
149 of 150 checks passed
@steipete
steipete deleted the steipete/perf-micro-cold-restore-writer-hold-20260919 branch November 18, 2026 04:12
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…nclaw#200930)

* fix: keep other chats responsive during cold history restoration

Prepare restore payloads before writer admission, reuse retained navigation, and replay bounded batches while the cold marker owns reader visibility. Preserve recoverable partial replay for current and legacy archives without schema or configuration changes.

* docs(perf): describe bounded restore measurements

* test(perf): qualify restore runtime policy before timing

* fix(sessions): accept cold restore at final publication

Keep provisional restore batches cold and recoverable, and preserve accepted close and cancellation custody for final hot publication. Migrate benchmark consumers and verify refused-publication recovery without changing the existing commit owner.
RomneyDa added a commit that referenced this pull request Nov 18, 2026
* fix(update): include cold archives in candidate snapshots

Co-authored-by: steipete <[email protected]>

* fix(update): preserve file archives in rehearsal snapshots

Co-authored-by: steipete <[email protected]>

* fix(update): preserve source WAL state during archive inventory

Classify cold archive SQL under its existing candidate-state subprocess owner. Preserve incomplete WAL source families so header inspection retains private cleanup custody.

Co-authored-by: steipete <[email protected]>

---------

Co-authored-by: steipete <[email protected]>

Release adaptation: the baseline does not contain the #195487 header-cleanup
suite. Keep that unrelated suite absent; carry the new incomplete-WAL inventory
assertions into the existing inventory suite instead. Add a per-change 214-line
allocation for the source regression, chunk fallback, and WAL preservation tests.
No schema, updater protocol, authority, or archive-integrity changes.

Companion audit at 9e917f0:
- #200733 is selected as the next dependency-closure repair: missing archives
  must warn instead of blocking updates, and Windows copies must not share live
  read-only inode attributes. Do not qualify this intermediate checkpoint alone.
- #200076 and #200930 are independent cold-history performance changes, not
  prerequisites for this snapshot repair.
- #201009, #200994, #200866, #200577, #200805, #200802, and #200732 overlap only
  adjacent update documentation and independent repair flows; not prerequisites.

Proof on base 309067b:
- New production-subprocess regression: 4/4 fail before, 4/4 pass after.
- Cold archives, chunks, and inventory: 31/31 pass after.
- Additional budget/cleanup/import siblings: 46/47 pass. Configured-cache
  containment fails identically on the unchanged base at budget.test.ts:737;
  retained as an independent failure, not weakened or repaired here.
- Targeted lint and format, documentation links, SQLite worker ratchet, and
  test-line ratchet pass. SQLite T1 counts remain 170; compatibility 15.
- Worker typecheck was blocked at dependency custody, without guard bypass.
  Parent canonical core typecheck, typed lint (five files), and formatting
  passed with its owned dependencies. Full installed-upgrade/FRV proof remains
  pending the assembled candidate, including selected companion #200733.

(cherry picked from commit 802e3f7)

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
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: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. scripts Repository scripts 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