Skip to content

fix: keep session delivery persistence from blocking the Gateway - #147887

Merged
steipete merged 2 commits into
mainfrom
codex/session-delivery-worker-main-20260914
Sep 14, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/session-delivery-worker-main-20260914

Conversation

@steipete

@steipete steipete commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session-delivery queue APIs returned Promises while executing SQLite on the Gateway thread, including during retry scheduling and restart recovery.

User Impact

Queue persistence moves to the existing shared-state worker while preserving deduplication, retry bookkeeping, settlement, and restart recovery. No configuration, schema, or retained-data migration is required.

Why This Change Was Made

Producers, recovery, generated-media preparation, and the scheduler carry one captured database context through the operation. Scheduler shutdown joins admitted reads and drains before database closure. Queue records retain their existing JSON serialization boundary; compound task/subagent transactions remain on their existing native owner.

Real-worker fixtures use the canonical fork owners across focused, watch, full-suite, and CI selection. The composition retains current main's noncreating Health reads, Health writes, diagnostics, and task/flow behavior.

Evidence

The runtime change passed fresh independent P2 review, all 36 changed-gate commands, 19 selected routing tests, five ordinary behavior cases, and the normal package build.

A plain-Node child using that exact compiled build passed a synthetic enqueue/read/reopen/recovery/settlement/reopen flow: exactly one delivery and settlement, no replay, and zero parent SQLite calls across six observed methods through final close. All 60 source files and 9,422 runtime files were verified before and after execution; fixture and process cleanup completed.

CI exposed an aggregate-versus-singleton expectation in the helper-routing test. The original focused control failed and the corrected control passed, along with fresh P2 review and all 16 follow-up checks. Only that test changed afterward; the 60 previously qualified files and all compiled runtime files remain byte-identical.

Run standalone queue persistence on the existing shared-state worker. Carry captured database context through producers, recovery, generated media, and retry scheduling, and join admitted scheduler work before closure. Preserve queue JSON, deduplication, retry, and settlement contracts.

Retain compound task/subagent transactions and current main Health, diagnostics, and task/flow behavior. Route real-worker fixtures through their canonical fork owners and remove obsolete test-only queue facades.

Validation: fresh P2 review, full 36-command changed gate, 19 selected routing tests, and five ordinary queue/Health/media/settlement cases passed.
@clawsweeper

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

@steipete
steipete marked this pull request as ready for review September 14, 2026 04:27
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 14, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 14, 2026, 1:13 AM ET / 05:13 UTC (Revision 2).

ClawSweeper review

What this changes

Moves session-delivery persistence into the existing shared-state worker, carries database context through recovery and settlement, and updates test routing for worker-backed execution.

Merge readiness

✅ Ready for maintainer review

This remains useful: current main and the latest release still execute session-delivery persistence synchronously. No introduced correctness or security defect was identified, and the follow-up test correction preserves the routing assertions.

Priority: P2
Reviewed head: d96dca783501a857ac1b106db0a817a57f64c953

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent worker migration with meaningful persistence and lifecycle coverage and no blocking finding from source review.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied maintainer-author context exempts this internal persistence change from the external-contributor proof gate; the body additionally reports a compiled queue recovery flow with no replay or parent SQLite calls.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied maintainer-author context exempts this internal persistence change from the external-contributor proof gate; the body additionally reports a compiled queue recovery flow with no replay or parent SQLite calls.
Evidence reviewed 9 items Current main still needs the change: The fetched main implementation declares asynchronous queue APIs but directly calls synchronous delivery-queue database helpers for enqueue, reads, retries, and completion.
Latest-release comparison: The v2026.9.4 tree identifies blob 54924209a198c8294d5c528ed8eaf720f21c4ebc for this file. Reading that blob through GitHub confirmed the same synchronous persistence pattern.
Worker and serialization boundary: Standalone operations use the existing shared-state worker owner; payload preparation retains the JSON serialization boundary and existing insert-only/update-pending behavior. The worker invokes the existing connection-bound queue kernels.
Findings None None.
Security None None.

How this fits together

The session-delivery queue retains restart continuations and agent completion messages until delivery and settlement finish. Gateway producers and recovery feed this queue; its scheduler retries pending work and records durable completion.

flowchart LR
  A[Restart and agent messages] --> B[Captured database context]
  B --> C[Shared-state worker]
  C --> D[SQLite delivery queue]
  D --> E[Recovery and retry scheduler]
  E --> F[Session delivery]
  F --> G[Durable settlement]
  G --> C
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +244, Tests +816, Docs +9, Other +11. Total +1080 across 61 files.

View PR surface stats
Area Files Added Removed Net
Source 19 795 551 +244
Tests 38 1497 681 +816
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 3 15 4 +11
Total 61 2316 1236 +1080

Review metrics

Metric Value Why it matters
Net code growth Production +244 lines; tests and test support +796; tooling +32 Production growth supplies worker commands and explicit context propagation, with coverage for persistence and lifecycle invariants.

Technical review

Best possible solution:

Keep standalone queue persistence on the shared-state worker while preserving the existing record format, compound transaction ownership, and shutdown settlement ordering.

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

Yes, from source: current-main queue APIs directly execute synchronous SQLite helpers despite returning Promises. No runtime reproduction was executed in this read-only review.

Is this the best way to solve the issue?

Yes. Reusing the existing shared-state worker and queue kernels addresses the blocking operations without introducing another persistence owner or changing stored records.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded Gateway responsiveness improvement for durable session delivery, without evidence of an urgent widespread outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied maintainer-author context exempts this internal persistence change from the external-contributor proof gate; the body additionally reports a compiled queue recovery flow with no replay or parent SQLite calls.

Evidence

What I checked:

  • Current main still needs the change: The fetched main implementation declares asynchronous queue APIs but directly calls synchronous delivery-queue database helpers for enqueue, reads, retries, and completion. (src/infra/session-delivery-queue-storage.ts:161, e9a1e2fce8ca)
  • Latest-release comparison: The v2026.9.4 tree identifies blob 54924209a198c8294d5c528ed8eaf720f21c4ebc for this file. Reading that blob through GitHub confirmed the same synchronous persistence pattern. (src/infra/session-delivery-queue-storage.ts, 3a9d69db306c)
  • Worker and serialization boundary: Standalone operations use the existing shared-state worker owner; payload preparation retains the JSON serialization boundary and existing insert-only/update-pending behavior. The worker invokes the existing connection-bound queue kernels. (src/infra/session-delivery-queue-storage.ts:19, d96dca783501)
  • Scheduler lifecycle: Shutdown fences new scheduling and joins pending reads and active drains. Scheduling checks both captured admissions and matching database identities before loading an entry. (src/infra/session-delivery-queue-runtime.ts:154, d96dca783501)
  • Behavioral regression coverage: Inspected storage tests exercise deduplication, completion receipts, retry accounting, retained media, and absence of parent-thread SQLite calls. Runtime tests cover delayed reads, replacement owners, drain joining, retry recovery, and clock changes. These tests were inspected, not executed during this read-only review. (src/infra/session-delivery-queue.storage.test.ts, d96dca783501)
  • Re-review continuity: The previous review contained no findings. Comparison with its reviewed head confirms that only the helper-routing test changed afterward; the correction distinguishes singleton worker ownership from aggregate Gateway ownership. (test/scripts/test-projects-routing.test.ts:688, d96dca783501)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Leon-SK668: 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 (1 earlier review cycle)
  • reviewed 2026-09-14T04:37:32.197Z sha 80023f0 :: needs maintainer review before merge. :: none

Normalize the dedicated Gateway worker config when comparing singleton file selection with a mixed Gateway aggregate. Keep importer completeness, exact-once membership, includes, forwarded arguments, and watch-mode assertions unchanged.

The original case reproduced the hosted Large 15 failure. The corrected case, fresh P2 review, and all 16 selected changed checks pass. Runtime sources and compiled artifacts remain identical to the qualified parent.
@steipete
steipete merged commit d20490a into main Sep 14, 2026
190 of 192 checks passed
@steipete
steipete deleted the codex/session-delivery-worker-main-20260914 branch September 14, 2026 06:27
@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 15, 2026
…nclaw#147887)

* fix(state): move session delivery queue operations to shared worker

Run standalone queue persistence on the existing shared-state worker. Carry captured database context through producers, recovery, generated media, and retry scheduling, and join admitted scheduler work before closure. Preserve queue JSON, deduplication, retry, and settlement contracts.

Retain compound task/subagent transactions and current main Health, diagnostics, and task/flow behavior. Route real-worker fixtures through their canonical fork owners and remove obsolete test-only queue facades.

Validation: fresh P2 review, full 36-command changed gate, 19 selected routing tests, and five ordinary queue/Health/media/settlement cases passed.

* test: preserve leaf ownership in helper routing checks

Normalize the dedicated Gateway worker config when comparing singleton file selection with a mixed Gateway aggregate. Keep importer completeness, exact-once membership, includes, forwarded arguments, and watch-mode assertions unchanged.

The original case reproduced the hosted Large 15 failure. The corrected case, fresh P2 review, and all 16 selected changed checks pass. Runtime sources and compiled artifacts remain identical to the qualified parent.
obviyus added a commit that referenced this pull request Sep 17, 2026
Refs #147887

## What Problem This Solves
The startup queue retry test can stop its runtime after the SQLite scan but before the scheduled delivery starts.

## Why This Change Was Made
A zero-delay timer created during a fake-clock tick is due at the next millisecond. Drain the pending timer before stop joins delivery. The test alone advances its clock; this state has one writer.

## User Impact
Test-only repair of a false failure; production delivery and shutdown stay unchanged.

## Evidence
The [original CI failure](https://github.com/openclaw/openclaw/actions/runs/35180792378/job/105072674481) expects one delivery but gets zero. Real-SQLite controls reproduce both reply orders: the old wait fails during a tick; the corrected wait passes both. Disabling the drain still fails delivery and persistence checks.

All 56 runtime, recovery, storage and real-Gateway clock-jump cases pass.

`node scripts/run-vitest.mjs src/infra/session-delivery-queue-runtime.test.ts`

## Compatibility
One test line changes. No runtime, schema, configuration, dependency or public interface changes.

## Consumers
Only the existing startup pending-scan retry test changes.

## Invalidation
Each case stops its runtime before closing its database and restores real timers.

## Tests
The 999+1 ms retry boundary, no early delivery, exactly one delivery, and empty pending rows remain asserted.

## Contention
Stop still cancels unadmitted timers and joins only admitted work.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 18, 2026
…w#150631)

Refs openclaw#147887

## What Problem This Solves
The startup queue retry test can stop its runtime after the SQLite scan but before the scheduled delivery starts.

## Why This Change Was Made
A zero-delay timer created during a fake-clock tick is due at the next millisecond. Drain the pending timer before stop joins delivery. The test alone advances its clock; this state has one writer.

## User Impact
Test-only repair of a false failure; production delivery and shutdown stay unchanged.

## Evidence
The [original CI failure](https://github.com/openclaw/openclaw/actions/runs/35180792378/job/105072674481) expects one delivery but gets zero. Real-SQLite controls reproduce both reply orders: the old wait fails during a tick; the corrected wait passes both. Disabling the drain still fails delivery and persistence checks.

All 56 runtime, recovery, storage and real-Gateway clock-jump cases pass.

`node scripts/run-vitest.mjs src/infra/session-delivery-queue-runtime.test.ts`

## Compatibility
One test line changes. No runtime, schema, configuration, dependency or public interface changes.

## Consumers
Only the existing startup pending-scan retry test changes.

## Invalidation
Each case stops its runtime before closing its database and restores real timers.

## Tests
The 999+1 ms retry boundary, no early delivery, exactly one delivery, and empty pending rows remain asserted.

## Contention
Stop still cancels unadmitted timers and joins only admitted work.

Co-authored-by: Ayaan Zaidi <[email protected]>
karmafeast pushed a commit to karmaterminal/openclaw that referenced this pull request Sep 26, 2026
Put back upstream b1c68b9 content that the continuation line had
silently reverted in shared files. Every row has a keep/restore
disposition recorded in the round journal. Feature hunks are preserved.

Production:
- announce deps: use callSubagentLifecycleGateway for the wake and
  cleanup deps (openclaw#146369 inherited Gateway binding).
- reply-delivery: clear blockSourceText on superseded deferred replies
  (openclaw#143722).
- stream-rendering: record a block reply as delivered only when it has
  text (openclaw#135751).
- gateway runtime handles: carry hotReloadStatus through the managed
  reload.
- sweep-kill and sweeper: honor retired cancellations
  (reconcileRetiredSubagentCancellation), and pass the run's Gateway
  context resolver into sweep session deletes.
- registry read: per-child snapshot reads (openclaw#154727), so the Gateway
  event loop is not blocked.
- session delivery queue: read the post-enqueue status inside the SQLite
  worker instead of on the main thread, restoring the openclaw#147887 invariant.

Tests restored to upstream's coverage:
- task-registry kernel test: back to upstream's kernel functions.
- double-announce: real outbound adapter retry outcomes (openclaw#131419).
- side-question: listener-failure hooks case (openclaw#144828).
- session-delivery storage: main-thread-SQL idle assertion (openclaw#157458).
- media-only: the re-resolved auth selection assertion.
- resume persistence: activation uses the real recovery-runtime shape.

The resume "steered requester turn" test was adapted for upstream's
async task lookup (openclaw#157634). Its stub now settles like the real waker,
and the test waits for settle before an exact count, with a
no-pending-wake assertion added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Fq5EX9ESA3CG9cuZxVoKAK
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 3, 2026
…rage API

The continuation merge re-widened every session-delivery storage
operation to OpenClawStateWorkerContext | stateDir | undefined and
resolved the state dir inside the storage owner. Restore upstream's
required OpenClawStateWorkerContext parameter and its plain
moveSessionDeliveryToFailed (upstream removed the status-probing catch
in openclaw#147887).

Continuation events persist only a delivery-queue state dir, so their
callers bind it once through captureContinuationQueueContext. The
post-compaction delivery dep now requires a context; its single call
site supplies the fallback. Tests pass the context they already hold.

Refs #1418

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 3, 2026
Block: cosmetic drift in session-delivery-queue.records.ts.

Restores upstream b51feb9's systemEvent agentId doc comment ("Preserves
ownership when a durable event targets the literal global session.") over
the older openclaw#147887 (d20490a) wording, and moves SESSION_DELIVERY_QUEUE_NAME
back above the type declarations where upstream keeps it.

Stayed: the codec type move (QueuedSessionDelivery and payload types derived
from session-delivery-queue-codec.ts) is unchanged.

Home: restored to upstream (drift residue).

Refs #1418

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant