Skip to content

fix(history): keep committed reads responsive during writer stalls - #167446

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-chat-history-worker-timeout-isolation-20260919
Oct 8, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-chat-history-worker-timeout-isolation-20260919

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: chat history, reactions, and progress-card reads become unavailable when transcript searches occupy every foreground reader while waiting behind a stalled agent-database writer. Related: #167396 fixed one writer deadlock; this change isolates its read-side blast radius.

User Impact

Committed session data remains readable while writable transcript-index readiness is blocked. Worker host callbacks consume the caller's deadline, including queue time; code-mode approval waits retain their existing approval-aware budget. No schema, configuration, stored data, permissions, or update migration changes.

Why This Change Was Made

Transcript search retains a native reader across a host index-readiness exchange so its freshness check uses the same SQLite connection. That exchange can await the writer, and previously occupied the same worker slots as foreground reads. Search now uses a separately bounded lane under the existing database custody and cleanup owner. Generic worker exchanges retain the caller deadline, and transcript-index requests forward its cancellation signal into writer admission. Queued work cancels; accepted writes retain settlement custody.

Production TypeScript grows by 43 lines. The requested non-test/non-doc diff is +96/-46, including seven package README lines. Growth preserves two concrete contracts: same-connection search freshness and approval-aware code-mode deadlines. Search keeps its existing concurrency cap, at the cost of a separate lazily started worker set. The existing owner supplies idle retirement and shutdown. The transcript runtime's duplicate deadline calculation is removed.

Evidence

Provider: blacksmith-testbox; lease: tbx_01m4ef1zac8wnyytkezefv25g0; base: 6070074dabf6b45f74d4039590cd307640317862.

  • The real chat.history handler reads a committed synthetic message while the canonical writer queue is held and search capacity is occupied. Baseline: no reply during a 6,514.77 ms observation window, ending at the fixture's 10-second cutoff. Candidate: identical committed history in 9.34 ms, before releasing the writer. This is a blocked-writer availability measurement, not an ordinary-throughput benchmark.
  • All three callback-deadline regressions fail against the original scheduler and pass with the fix: stalled callback, attempted deadline renewal, and attempted renewal after an earlier response shortened the deadline.
  • Focused run: 28 tests passed across history, worker pool, and transcript-search worker files. Search cancellation also settles before the held writer is released, then a new search returns the same committed result.
  • Independent review: fixed the first pass's shortened-deadline finding; both subsequent passes were scoped-clean through P2, including the final deadline-helper extraction required by the scheduler line cap.
  • Sibling run: 444 tests passed in 43 files, including code-mode approval waits, worker lifecycle, history pagination, reactions, progress-card authorization, transcript search, and projection readiness. Export-name collision guard passed; both closure files passed 20 tests. Remote command time: 331.84 s.
  • pnpm test <file> --maxWorkers=1 wall time: chat-history-worker.test.ts 18.33 s; worker-task-pool.test.ts 8.16 s; session-transcript-search.worker.test.ts 12.97 s. These suites exercise real worker and SQLite ownership; the new callback cases use a fake clock.
  • Tooling failures corrected: the first sibling selector matched no test files; the initial changed gate caught the scheduler line cap. Deadline arming moved to the existing expiration helper, with no rule or baseline changes.

node scripts/check-changed.mjs passed its structural checks and all core, core-test, extension, and extension-test typechecks, then stopped at an inherited Knip failure: src/talk/client-voice-session-store.ts: ClientVoiceToolEffect (production and full-tree scans). node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts fails identically on a clean, independently installed checkout of current main dcd3ca7a7fd53cfd5aa09579bb4665a422fbd6ba. That source is untouched by this PR. All ten remaining commands from the native changed-check plan passed when run directly; the failed guard remains reported as failed.

The final extraction replay passed 91 affected tests across 11 files, the export collision guard, and 20 closure tests. pnpm build exited 0 in 189.2 s. It reported a Control UI startup-JS size advisory (365.2 KiB versus 364.7 KiB); no UI source changes are included.

Remote runs all used the provider and lease above:

Command/run Result
Baseline/candidate node scripts/run-vitest.mjs for history and pool deadlines, then the three focused files with --maxWorkers=1 Expected baseline failures; candidate 28 tests passed; 148.24 s
Initial sibling selection Runner rejected an unmatched history filter before executing tests; corrected to explicit file globs
Sibling suites, check-export-name-collisions.mts, and both closure files 444 sibling + 20 closure tests passed; 331.84 s
Three standalone pnpm test <file> --maxWorkers=1 runs, then node scripts/check-changed.mjs Tests passed; line-cap failure fixed by coherent helper extraction
node scripts/check-changed.mjs after extraction Typechecks and prior guards passed; inherited unused-export failure; 1,941.77 s
Clean-main check-deadcode-exports.mts, remaining native-plan commands, final affected/closure suites, and pnpm build Same baseline failure independently reproduced; all remaining candidate commands passed; 651.24 s

No live Gateway was modified or restarted. Hosted CI run 37840545200 passed on f67a919c90ec: 671 s wall time, 78 completed jobs, and 4,986 aggregate job-seconds across 20 successful Node test jobs (job-level cost, not per-test timing).

Isolate transcript-search readiness from foreground history workers while
preserving same-connection revision checks and database cleanup custody.
Keep host exchanges within the caller deadline and forward cancellation to
queued index-status writes; accepted writes still settle before release.
Preserve code-mode approval waits under their existing budget owner.

A wedged-writer fixture returned committed history in 9.34 ms versus no
baseline reply during a 6.5-second observation window. Focused and sibling
proof ran on Blacksmith Testbox, with independent review through P2.
@clawsweeper

clawsweeper Bot commented Oct 8, 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 agents Agent runtime and tooling plugin: code-mode-quickjs size: M labels Oct 8, 2026
@steipete
steipete marked this pull request as ready for review October 8, 2026 20:35
@steipete
steipete enabled auto-merge (squash) October 8, 2026 20:35
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The branch separates transcript searches from committed-history readers, bounds worker host callbacks by the caller’s deadline, and forwards search cancellation into writer admission while preserving Code Mode approval budgets.

Example: Read chat history while searches wait behind a stalled writer.

  • Before: The history request cannot return “Committed needle” while searches occupy every foreground reader.
  • After: The history request returns the same “Committed needle” message before the writer is released.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A useful, coherent repair with meaningful real-worker regression evidence, whose strongest demonstrated path remains an in-process handler harness.
Proof confidence 🦐 gold shrimp (3/6) The Repository State identifies MEMBER authorship, so the external-contributor gate does not apply, and no material authority change triggers additional proof. Supplied Testbox evidence exercises the production history handler, real reader workers, and held writer admission with observed after-fix history recovery, but remains in-process coverage. Source inspection verifies unchanged schemas, stored formats, and settings.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Users cannot load already-saved conversation data when concurrent searches wait behind a stalled database writer.
Reason: Committed reads should remain available independently of writable index maintenance. The established area owner explains the bounded resource and callback-budget changes, including preservation of approval waits.

Merge readiness

✅ Ready for maintainer review

This PR addresses a remaining availability defect beyond the merged writer-deadlock fix. No actionable introduced bug was found; the implementation is coherent, with confidence limited by in-process rather than running-Gateway proof.

Priority: P1
Reviewed head: f67a919c90ecf8414ff53d373547f76a7ffd819a

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied comparison invokes the registered history handler inside a test process; it does not show the stalled-writer scenario through a client connected to a running Gateway.
Agent review details

How this fits together

The Gateway reads saved conversations through SQLite reader workers while an ordered writer maintains the search index. Search requests exchange readiness information with that writer before validating their results.

flowchart TD
  A[Transcript search] --> B[Separate bounded search readers]
  B --> C[Index readiness callback]
  C --> D[Ordered database writer]
  B --> E[Same-connection freshness check]
  F[Chat history request] --> G[Committed-history readers]
  G --> H[Saved messages returned]
Loading

Technical review

Best possible solution:

Keep writable search readiness independent of committed-data readers under the existing custody owner, with caller-bounded cancellation and explicit approval-aware budget ownership.

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

Yes. Shared reader capacity plus writer-backed readiness establishes the starvation path, and the supplied regression forces that ordering with real workers; this review did not execute it.

Is this the best way to solve the issue?

Yes. The existing resource owner can isolate the competing workload while preserving same-connection freshness and accepted-write settlement; the deadline repair also preserves both Code Mode budget owners.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head delta. Search selects a separate bounded lane, and that lane joins the existing retirement, database-close, and memory-pressure lifecycle. (src/config/sessions/session-transcript-worker-resources.ts:128, f67a919c90ec)
  • Current-main necessity: The introduced delta starts from main’s shared history/search lane. Later main changes to the touched reader and type files add separate session-maintenance operations, without implementing search isolation or callback deadlines. (src/config/sessions/session-transcript-worker-readers.ts:243, 220e7949fe87)
  • Related merged fix is distinct: fix: prevent chat stalls during progress-card saves #167396 is merged and separates writer-held target discovery from history cleanup. Its stated scope removes a circular wait; it does not isolate searches waiting behind another stalled writer. (b2d00be586ee)
  • Integration provenance: The verified GitHub test merge records the exact fetched main parent followed by the pinned PR head. Main’s additions to the reader/type files occur outside the introduced search hunks. (17688e4d56e2)
  • History availability regression: The added regression invokes the registered chat.history handler with real SQLite workers while the canonical writer reservation is held and search capacity is occupied. The fully read PR body reports no baseline reply during its observation window and identical candidate history in 9.34 ms before writer release. This is in-process handler proof, not a running-Gateway client trace. (src/gateway/server-methods/chat-history-worker.test.ts:47, f67a919c90ec)
  • Deadline and cancellation coverage: The new cases cover stalled callbacks, attempted deadline renewal, preservation of an already-shortened deadline, cancellation before writer release, and a subsequent successful search. The body reports baseline failures and passing candidate runs; this read-only review did not execute them. (src/config/sessions/session-transcript-search.worker.test.ts:261, f67a919c90ec)

Likely related people:

  • Peter Steinberger: Raw commit 6aa9262 adds src/config/sessions/session-transcript-worker-resources.ts:125 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6aa926265782; files: src/config/sessions/session-transcript-worker-resources.ts)
  • Jason (Json): Raw commit b2d00be adds src/config/sessions/session-transcript-worker-resources.ts:138 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b2d00be586ee; files: src/config/sessions/session-transcript-worker-resources.ts)

PR surface

Source +43, Tests +182, Docs +16. Total +241 across 17 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 11 89 46 +43
Tests 3 185 3 +182
Docs 3 16 0 +16
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 290 49 +241

Review metrics

Metric Value Why it matters
Additional reader capacity 1 lazy search pool, capped at 1–8 workers The explicitly disclosed resource growth isolates stalled readiness without introducing a second database lifecycle owner.
Worker API budget mode 1 optional API parameter; 2 bundled executors migrated The explicit owner-budget mode preserves approval pauses while ordinary callbacks consume the caller deadline.

Labels

Label changes:

  • add P1: A stalled writer can currently suppress committed chat-history and related reads when searches exhaust foreground reader capacity.
  • add merge-risk: 🚨 compatibility: The public worker API changes callback timeout behavior; the area owner explicitly documents that tradeoff and preserves approval-aware behavior through the new mode.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: A stalled writer can currently suppress committed chat-history and related reads when searches exhaust foreground reader capacity.
  • merge-risk: 🚨 compatibility: The public worker API changes callback timeout behavior; the area owner explicitly documents that tradeoff and preserves approval-aware behavior through the new mode.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 8, 2026, 4:42 PM ET / 20:42 UTC.

@steipete
steipete merged commit 486cdae into main Oct 8, 2026
211 of 215 checks passed
@steipete
steipete deleted the steipete/perf-micro-chat-history-worker-timeout-isolation-20260919 branch October 8, 2026 20:47
jalehman added a commit that referenced this pull request Oct 8, 2026
Since #167446 the worker pool arms its first timeout as the enqueue-anchored
deadline minus performance.now(), so a clamped budget schedules a delay just
below MAX_TIMER_TIMEOUT_MS. Assert the clamp contract (within the Node cap and
not short-circuited) instead of exact equality.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…penclaw#167446)

Isolate transcript-search readiness from foreground history workers while
preserving same-connection revision checks and database cleanup custody.
Keep host exchanges within the caller deadline and forward cancellation to
queued index-status writes; accepted writes still settle before release.
Preserve code-mode approval waits under their existing budget owner.

A wedged-writer fixture returned committed history in 9.34 ms versus no
baseline reply during a 6.5-second observation window. Focused and sibling
proof ran on Blacksmith Testbox, with independent review through P2.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…67513)

Since openclaw#167446 the worker pool arms its first timeout as the enqueue-anchored
deadline minus performance.now(), so a clamped budget schedules a delay just
below MAX_TIMER_TIMEOUT_MS. Assert the clamp contract (within the Node cap and
not short-circuited) instead of exact equality.
RomneyDa pushed a commit that referenced this pull request Oct 9, 2026
Backport the worker-runtime and SQLite/shared-state cancellation portion of
#167740 onto the release owners. Keep queued cancellation separate from accepted
native settlement, preserve FIFO and independent coalesced callers, and retain
cleanup custody. Carry cancellation through plugin-state and agent writes.

Adapt the necessary deadline ownership contract from #167446 without importing
its history refactor. Code Mode keeps its existing approval-aware host budget.
Use structured operation labels for diagnostics; raw callback strings retain
the worker-entrypoint fallback and never become log payloads.

This is a selected backport, not full #167740 coverage: its newer ACP/worktree,
history/usage and cold-restoration portions are deliberately not imported.

Proof: 200 distinct tests across 10 files; original host-wait suspension fails
all five deadline cases; donor raw-string labeling fails the payload case.
Physical frozen install, worker-runtime build, core types, all 27 core test
graphs, three zero-entry Knip scans, changed-source guards and scoped lint pass.
Post-review diagnostic repair has fresh affected build/type/lint/test proof.

Deadline ownership portion adapted from 486cdae.
(cherry picked from commit 7dd2721)
(cherry picked from commit b7984f6845f075a5f92825926632575bbcc0202c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. plugin: code-mode-quickjs rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M 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