Skip to content

fix(worker-runtime,infra): bound host callbacks and recover WAL-blocked readers - #179693

Closed
evomach wants to merge 3 commits into
openclaw:mainfrom
evomach:fix/wal-checkpoint-blocked-reader-recovery
Closed

evomach wants to merge 3 commits into
openclaw:mainfrom
evomach:fix/wal-checkpoint-blocked-reader-recovery

Conversation

@evomach

@evomach evomach commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

fix(worker-runtime,infra): bound host callbacks and recover WAL-blocked readers

What Problem This Solves

On production gateways, WAL checkpoint maintenance can become permanently stuck
(PASSIVE blocked by a reader, consecutiveBlocked climbing for hours, external
TRUNCATE busy=1, restart-only recovery). The stuck reader is invisible to current
diagnostics (blockingOwner:"unknown", trackedReaders:0, transactionOpen:false).

The mechanism: a pooled worker parked in an interactive task exchange holds an
unexhausted native node:sqlite cursor; the task has no deadline, so a host request
handler that never settles can never be cancelled, the worker is never retired, and its
connection pins the WAL read mark forever. This PR bounds the host-callback phase for
deadline-less interactive tasks (so the existing cancel → retire → unwind path finally
fires) and adds a WAL-blocked-reader safety net that rotates idle pooled connections
when a checkpoint stays blocked for ~2 minutes. The live incident this fixes: gateway
2026.10.4 on host EVOMACH-PETROS, state/openclaw.sqlite pinned at frame 129 with
2133+ consecutive blocked observations and a 181 MB journal.

Evidence

Live symptom (host EVOMACH-PETROS, gateway 2026.10.4). WAL checkpoints on
state/openclaw.sqlite and agents/main/agent/openclaw-agent.sqlite stayed
PASSIVE blocked by a reader permanently: consecutiveBlocked reached 2133+, only
129/44081 frames folded (WAL grew to 181 MB), external TRUNCATE returned busy=1, and
only a gateway restart folded the journals. Diagnostics reported
blockingOwner:"unknown", trackedReaders:0, transactionOpen:false — the pin was
invisible to wrapper tracking.

Root cause (proven, file:line). Long-lived pooled read workers park inside
interactive task exchanges:

  1. src/transcripts/store-export.worker.ts:106,111 and
    src/agents/subagents/registry/subagent-registry.store.worker.ts:103 run
    await channel.request(batch) after BEGIN with a suspended iterate(); their
    cleanup (ROLLBACK + close) only runs if the await settles.
  2. src/state/openclaw-state-read-worker.ts startRun passes no timeoutMs in task
    options. packages/worker-runtime/src/worker-task-pool-core.ts arms a task timer only
    when options.timeoutMs is set (and re-arms after each host response). An async host
    handler that never settles — e.g. src/transcripts/store-worker-client.ts:47 awaiting
    a consumer that never returns — leaves the task with no deadline forever: no
    timeout, no cancel, no retire, and the parked worker (with its native cursor) pins the
    WAL read mark indefinitely.
  3. Cross-thread reproduction (node:sqlite, Node 24.18, two threads) reproduces the live
    fingerprint exactly: after a parked reader plus WAL growth, PASSIVE busy=0 log=1326 checkpointed=664 and TRUNCATE busy=1, and the wal-index header keeps an aReadMark
    pinned at the abandoned frame — with transactionOpen=false and zero tracked readers,
    matching the live diagnostics. Abandoning an unexhausted iterate() (with or without
    an open transaction) is sufficient to pin the mark; it survives COMMIT/ROLLBACK on
    the same connection and releases only when the statement is re-stepped to exhaustion
    or the connection closes.
  4. Both historical block episodes began within minutes of OS freeze/thaw gaps (518 s /
    7.5 h / 55 min / 23 min), consistent with suspended async consumers being abandoned at
    yield boundaries. Cancel → retire → unwind demonstrably works (the repro's
    pool.rotate() folded the WAL in milliseconds), so the bug is purely that nothing ever
    triggers cancellation for deadline-less interactive tasks.
  5. The iterateSqliteQuerySync generator wrapper in src/infra/kysely-sync.ts is itself
    sound (try/finally disposes the statement on every close path); a sustained pin
    requires the generator to be held by a suspended async frame — the same class the
    watchdog below bounds.

This fix.

  • packages/worker-runtime: a bounded host-callback watchdog. When an interactive
    (onRequest) exchange arrives on a task that currently has no deadline, the pool
    arms a watchdog (hostCallbackTimeoutMs, default 300 s) so a never-settling host
    handler times the task out, which cancels and retires the parked worker — letting its
    native cleanup unwind and release the pinned read mark. Tasks with an explicit deadline
    keep their existing authority (watchdog stays disarmed); hostTimeout:"owner" (Code
    Mode) keeps its unbounded owner-managed wait; a healthy multi-chunk stream is unaffected
    because each host response re-arms the normal timeout.
  • src/infra/sqlite-wal-blocked-reader-recovery.ts (new, registered in
    scripts/pr-lib/wrapper-components.txt): safety net. If any WAL stays blocked for 12
    consecutive checkpoint observations (~2 min), registered recovery hooks rotate idle
    pooled worker connections, so pinned read marks are released even for leak vectors this
    fix does not yet cover. A 10-minute cooldown bounds the fan-out.
  • src/infra/worker-task-pool.ts: both pool entry points (WorkerTaskPool,
    createOwnedWorkerTaskPool) register a rotate hook for their lifetime; rotation never
    interrupts running tasks (it defers until they settle).

Tests (green).
packages/worker-runtime/src/worker-task-pool.host-callback-timeout.test.ts (4 new):
never-settling handler times out and the parked worker is terminated; a healthy 6-chunk
stream is not capped; hostTimeout:"owner" stays unbounded; an explicit task deadline
remains the authority. Full packages/worker-runtime shard passes 30/30 under
vitest.unit-support.config.ts. src/infra/sqlite-wal-blocked-reader-recovery.test.ts
(4 new): threshold trigger, cooldown throttle, unregister, failing-hook containment —
green under vitest.infra.config.ts. check:wrapper-shadowing passes;
check:import-cycles reports 0 runtime cycles. (worker-task-pool.owned.test.ts and one
sqlite-wal/sqlite-wal-checkpoint case fail identically without this diff on this
Windows host: workerScriptName ERR_INVALID_FILE_URL_PATH and APFS-evidence tests;
unrelated to the change.)

Honesty note. The exact per-call-site culprit (which consumer abandoned which
iterator) cannot be named from existing gateway diagnostics without instrumented replay;
this PR fixes the mechanism (an unbounded host-callback phase strands a parked worker)
and adds recovery for any residual pin, rather than patching one call site. The
WORKER_HOST_CALLBACK_TIMEOUT process warning added by the timeout path names the
pending exchange (or the worker file behind it), which will localize each real offender
as it fires.

What to watch after this ships

  • WAL health: consecutiveBlocked should reset within ~14 ticks (~2 min) instead of
    climbing for hours; walBytes should fall back to MB scale.
  • WORKER_HOST_CALLBACK_TIMEOUT warnings: a non-zero rate identifies the exact stranded
    consumers (the message names the pending exchange or the worker file behind it) — the
    signal for follow-up per-site fixes.
  • A sustained recurrence of blocks despite rotation would mean a pinned connection is
    held outside worker-task pools (e.g. a long-lived hostTimeout:"owner" task); the
    warning stream plus wal-index aReadMark slots would localize it.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 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 the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Oct 21, 2026
@evomach
evomach force-pushed the fix/wal-checkpoint-blocked-reader-recovery branch 2 times, most recently from 3825145 to 275fb92 Compare October 21, 2026 18:16
@evomach evomach closed this Oct 21, 2026
@evomach evomach reopened this Oct 21, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Adds a five-minute watchdog for deadline-less host callbacks and rotates worker pools after sustained SQLite WAL checkpoint blocking.

Example: A transcript export's first asynchronous chunk consumer never returns.

  • Before: The worker can retain its SQLite snapshot indefinitely.
  • After: The proposed watchdog cancels the task after 300 seconds and starts worker retirement.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The repair targets a real source gap, but automatic recovery can block healthy work and the supplied tests do not establish production recovery.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A stranded streaming reader can prevent WAL reclamation until the Gateway restarts.
Reason: The callback gap merits repair, while the SDK-wide default and public override extend beyond the demonstrated database failure.

Merge readiness

⛔ Blocked before merge - 4 items remain

This PR addresses a concrete unbounded worker callback path that remains on current main, but the automatic recovery introduces availability defects and the SDK-wide timeout policy needs an owner decision.

Priority: P2
Reviewed head: 8986d7e2d62b69a00a980b8fd9939491599429c8
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should the new 300-second callback default and override apply to every SDK WorkerTaskPool, or remain internal to SQLite streaming readers?
  • Recommendation: Scope the repair to database streaming: Use the existing task deadline at the affected reader owner and avoid introducing a public override without a demonstrated consumer.
  • Why: The exported pool previously allowed these deadline-less callbacks, and no recorded owner decision approves the broader default or new task option.

Before merge

  • Add real behavior proof - The supplied validation exercises a synthetic worker and a standalone SQLite connection; neither demonstrates the changed scheduler and registered recovery hooks releasing a parked Gateway reader after the fix. Provide redacted terminal output or logs for that path, including preserved streaming and approval behavior on a fresh installation and an upgrade; redact credentials, IPs, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Keep WAL recovery from pausing healthy pool dispatch (P1) - Every owned pool now rotates when any database reaches the blocked threshold. startRotate disables dispatch immediately and waits for every captured task before retiring even idle slots. For example, a shared-state export stalled in its first host callback triggers recovery around two minutes, but remains active until the five-minute watchdog; ordinary reads then queue for the remaining three minutes despite spare reader capacity. The same hook also reaches unrelated pools. Remove the blanket registrations or recover eligible reader resources without entering the whole-pool rotation barrier.
  • Propagate asynchronous rotation failures to the recovery owner (P2) - Both production hooks return undefined and swallow core.rotate rejection. If native termination or artifact cleanup fails, the retirement owner sets rotationFailed and refuses subsequent dispatch, while the registry sees a successful hook and never emits SQLITE_WAL_BLOCKED_RECOVERY_FAILED. This leaves a background-triggered pool outage without the recovery failure signal. Return the rotation promise and retain an observable recovery path for the failed pool.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] Keep WAL recovery from pausing healthy pool dispatch — src/infra/worker-task-pool.ts:73-75
  • [P2] Propagate asynchronous rotation failures to the recovery owner — src/infra/worker-task-pool.ts:31-33

Tests

  • Low-value test src/infra/sqlite-wal-blocked-reader-recovery.test.ts: Replace the direct blocker.close callback test with the actual registered pool recovery path: it still passes if both production rotation registrations are removed or broken.
  • Low-value test packages/worker-runtime/src/worker-task-pool.host-callback-timeout.test.ts: Replace the owner-wait control with one that advances beyond the watchdog budget; waiting 60 ms without overriding the 300000 ms default cannot detect an incorrectly armed watchdog.
  • Missing end-to-end proof: Supply a Gateway streaming-reader trace showing timeout, native reader retirement, WAL progress, and an independent read completing during recovery, with base-failing regression and fresh-install/upgrade coverage for the changed default.
Agent review details

How this fits together

SQLite streaming readers exchange chunks with host consumers through the worker scheduler; checkpoint observations feed the proposed recovery registry, which invokes pool rotation.

flowchart TD
  A[Transcript export] --> B[Worker task pool]
  B --> C[SQLite streaming reader]
  C --> D[Host chunk consumer]
  D --> B
  E[WAL checkpoint observations] --> F[Recovery registry]
  F --> B
Loading

Technical review

Best possible solution:

Bound the stranded callback through the existing deadline owner and keep WAL recovery scoped to reader resources without pausing unrelated pool dispatch.

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

Source establishes that an unresolved first asynchronous chunk callback can retain a streaming reader without a task deadline; identifying that callback as the reported production blocker remains unproven.

Is this the best way to solve the issue?

A bounded callback is useful, but process-wide rotation is broader than the demonstrated failure and conflicts with the existing scheduler's pause-and-drain semantics.

Full review comments:

  • [P1] Keep WAL recovery from pausing healthy pool dispatch — src/infra/worker-task-pool.ts:73-75
    Every owned pool now rotates when any database reaches the blocked threshold. startRotate disables dispatch immediately and waits for every captured task before retiring even idle slots. For example, a shared-state export stalled in its first host callback triggers recovery around two minutes, but remains active until the five-minute watchdog; ordinary reads then queue for the remaining three minutes despite spare reader capacity. The same hook also reaches unrelated pools. Remove the blanket registrations or recover eligible reader resources without entering the whole-pool rotation barrier.
    Confidence: 0.99
  • [P2] Propagate asynchronous rotation failures to the recovery owner — src/infra/worker-task-pool.ts:31-33
    Both production hooks return undefined and swallow core.rotate rejection. If native termination or artifact cleanup fails, the retirement owner sets rotationFailed and refuses subsequent dispatch, while the registry sees a successful hook and never emits SQLITE_WAL_BLOCKED_RECOVERY_FAILED. This leaves a background-triggered pool outage without the recovery failure signal. Return the rotation promise and retain an observable recovery path for the failed pool.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 7dd2721 adds packages/worker-runtime/src/worker-task-pool-owned.ts:20 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7dd2721609c9; files: packages/worker-runtime/src/worker-task-pool-owned.ts)

PR surface

Source +114, Tests +326, Other +1. Total +441 across 8 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 5 122 8 +114
Tests 2 326 0 +326
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 8 449 8 +441

Review metrics

Metric Value Why it matters
New task policy option 1 optional hostCallbackTimeoutMs parameter; default 300000 ms; 0 disables This expands behavior reachable through the released WorkerTaskPool SDK surface and requires an explicit compatibility decision.

Labels

Label changes:

  • add P2: The reported WAL growth and unbounded callback warrant a focused reliability repair; a current widespread outage is not established.
  • add merge-risk: 🚨 compatibility: The new default bounds previously unbounded callbacks on the exported WorkerTaskPool API.
  • add merge-risk: 🚨 availability: Automatic whole-pool rotation can stop healthy queued readers behind a slow active task.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: The reported WAL growth and unbounded callback warrant a focused reliability repair; a current widespread outage is not established.
  • merge-risk: 🚨 availability: Automatic whole-pool rotation can stop healthy queued readers behind a slow active task.
  • merge-risk: 🚨 compatibility: The new default bounds previously unbounded callbacks on the exported WorkerTaskPool API.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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.

Reviewed October 21, 2026, 5:54 PM ET / 21:54 UTC.

@evomach

evomach commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up commit 90197113124 — live-gateway re-block diagnosis:

The pool-side recovery from this PR could not fire for the shared-state store's second block episode. Root cause is a thread-scope mismatch:

  • The checkpoint-listener and recovery registries are per-thread global singletons (Symbol.for on each thread's globalThis).
  • The shared-state WAL maintenance chains run on worker threads (state worker + agent execution workers). The live gateway showed three independent consecutiveBlocked chains (2897/2142/1962) on threadId 9/12/13, each holding one long-lived pinned connection.
  • registerSqliteWalBlockedReaderRecovery was only armed on threads that create a WorkerTaskPool (the main thread). Worker threads that observe the sustained block had an empty hook set, and pool rotation on the main thread cannot close worker-thread handles regardless.

This commit arms a thread-local recovery at every worker-thread state-DB open that has a real maintenance owner: on a sustained block the thread recycles its own cached state handles (closeOpenClawStateDatabase PASSIVE), and the state/agent-execution workers release their long-lived retains so the reference-counted close can retire the pinned connection. The next PASSIVE tick folds the journal. Recovery firing is now logged (Recycling thread-local shared-state readers after sustained WAL block) — the previous hook was silent.

Also verified in the running dist bundle (gateway import graph, src-BfpxX0MF.mjs): the worker host-callback watchdog is armed by default at 300s (DEFAULT_HOST_CALLBACK_TIMEOUT_MS = 3e5), except for tasks with the deliberate hostTimeout: "owner" opt-out.

Regression coverage: src/state/openclaw-state-db-open.wal-recovery.test.ts (arm once per thread, threshold gating, cooldown, safe reference-counted close). 7/7 WAL recovery tests green; worker lane tests (imports boundary, cleanup, idle, settlement) 26/26 green.

…er threads

The shared-state WAL maintenance chains live on worker threads (state worker,
agent execution workers), while the blocked-reader recovery registry and
checkpoint listeners are per-thread global singletons. Pool-side recovery was
only ever armed on the pool-owning main thread, so a sustained block observed
on a worker thread reached no hook at all, and pool rotation could not close
worker-thread handles anyway. Arm a thread-local recovery at every worker-thread
state-DB open that recycles that thread's cached handles, and release the
long-lived retains held by the state/agent-execution workers so the reference-
counted close can retire the pinned connection.
@evomach
evomach force-pushed the fix/wal-checkpoint-blocked-reader-recovery branch from 9019711 to f664f03 Compare October 23, 2026 14:01
@evomach evomach closed this Oct 23, 2026
@evomach evomach reopened this Oct 23, 2026
@evomach

evomach commented Oct 24, 2026

Copy link
Copy Markdown
Contributor Author

Closing per owner directive 2026-10-24: upstream PR work retired; the full fix stack now lives on the local fork main (merge 31bc2929b92 + 90197113124), CI-proven in the consolidation worktree. Local-only delivery going forward.

@evomach evomach closed this Oct 24, 2026
@evomach
evomach deleted the fix/wal-checkpoint-blocked-reader-recovery branch October 24, 2026 07:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant