Skip to content

improve(outbound): batch delivery ownership checks during recovery - #154591

Merged
steipete merged 3 commits into
mainfrom
codex/delivery-receipt-prune-read-reuse
Sep 21, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/delivery-receipt-prune-read-reuse

Conversation

@steipete

@steipete steipete commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Restart recovery checks delivery custody one ID at a time on the Gateway thread, repeatedly reading namespaces and pruning the same receipt group.

User Impact

Recovery can check multiple pending deliveries in one worker operation, keeping these SQLite reads and receipt cleanup off the Gateway thread. Namespace precedence, settled/failed ownership, receipt retention, and stored data stay unchanged. Single-ID calls incur worker overhead; the measured latency benefit is in batches.

Why This Change Was Made

The existing delivery owner now reads bounded ID batches in one transaction, prunes each encountered producer prefix once, and rereads only after an actual deletion. The outbound lookup and all its callers await the existing shared-state worker. Restart recovery submits its complete delivery list once and rechecks cancellation afterward. The connection-bound single-ID API still serves existing compound transactions through the same kernel.

This is part of the maintainer-requested SQLite optimization campaign. It introduces no schema, configuration, upgrade, durability, or retention migration.

Stored-data compatibility: the state schemas, schema version, migrations, queue serialization, and completion-retention parser are unchanged from base 94a88aa994e. The existing pruning SQL retains the same predicates; only its deletion count is returned to avoid an unnecessary reread. Existing database fixtures cover canonical and retired namespace receipts, pending/failed ownership, and expiry. The files flagged by the automated data-model check change lookup routing, not persisted layout or backfill behavior; no migration is required.

Evidence

  • Hosted CI exposed a type-inclusive import cycle. Moving the unchanged ownership lookup into a leaf kernel removes the broad payload-type dependency: the complete import graph now has zero cycles, all 47 focused tests pass, and full changed-code validation passes.

  • CI confirms both cycle guards pass. Its Kysely guard also required moving the existing raw-query justification onto the query expression after the new result binding; the full guard now passes, and emitted JavaScript is identical.

  • Refreshed onto main 761725d03f294aaddc399a759a0755d34a0e1ecf. This incorporates merged fix(update): keep model authentication from blocking updates #154453, which removes the failing in-update repair test path, and the Discord pacing fixture repair: readiness now waits for the first encoded source packet rather than playback admission. The upstream deferred-encoder regression and recorded 20 standalone/three original-suite runs cover that premature-readiness defect; they do not prove the historical hosted zero-packet failure had the same cause. All three optimization/CI-repair commits remain patch-identical after rebase (git range-diff). New-head CI remains required. The earlier ACP Doctor warning did not recur in the subsequent hosted job; interrupted local reproduction did not establish its cause.

  • 707 tests passed across the affected delivery, Gateway, recovery, and channel callers (269.48 s wall). A further 47 focused tests passed (38.10 s wall, one worker; overlaps the captured-context tests).

  • Real public worker coverage checks captured state and supervisor mode, preserves duplicate/missing results, and observes zero main-thread SQLite statements. Receipt and namespace tests cover expiry and pending/failed precedence. The original owner violates the retained-receipt SELECT budget (2); the candidate uses 1.

  • Synthetic indexed SQLite parity also covers 1,201 IDs, duplicate IDs, and missing IDs. No platform network I/O was involved.

  • Full changed-code validation passed (2,766.48 s wall): production and test types, typed lint, dead exports, schema, import-cycle, and repository guards. The final obsolete-wrapper cleanup also passed 43 affected tests (68.73 s wall).

Warm latency in a real isolated shared-state database, comparing the original per-ID store admission/read calls with the public batch worker API (Node 26.8.2; 20 warmups, five alternating rounds, 50 iterations per round or 20 for 100 IDs):

Receipt type IDs Original Batch worker
Pending 1 0.125 ms 0.565 ms
Pending 10 0.519 ms 0.609 ms
Pending 100 4.943 ms 0.705 ms
Bounded completion 1 0.288 ms 0.643 ms
Bounded completion 10 3.040 ms 0.903 ms
Bounded completion 100 59.694 ms 1.531 ms

The source worker's first cold operation took 5.825 s and is excluded from the warm table; packaged startup was not measured. End-of-run RSS was 705 MB, not a before/after memory comparison. Query-only measurements separately show ten pending owners falling from 0.143 to 0.031 ms and ten bounded receipts from 1.638 to 0.192 ms. These measurements do not establish end-to-end message delivery latency.

@clawsweeper

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

@steipete
steipete marked this pull request as ready for review September 21, 2026 07:49
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 21, 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 21, 2026
@clawsweeper

clawsweeper Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 21, 2026, 6:06 AM ET / 10:06 UTC (Revision 6).

ClawSweeper review

What this changes

Moves delivery ownership lookups into the existing SQLite worker and batches restart-recovery checks while preserving receipt expiry and namespace precedence.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this remains a useful optimization absent from current main. No blocking defect was found. The prior import-cycle concern is resolved, and the earlier migration blocker does not apply to the preserved storage contract.

Priority: P2
Reviewed head: 7d526cf467f6f69b34a2663e53bcd77609d26b1d

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with relevant real-database measurements, preserved storage semantics, and no blocking findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied real SQLite benchmark exercises the changed public worker lookup and records improved warm batch latency; boundary coverage additionally checks captured state and zero main-thread SQL. This supports the internal optimization without claiming live-channel or packaged cold-start performance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied real SQLite benchmark exercises the changed public worker lookup and records improved warm batch latency; boundary coverage additionally checks captured state and zero main-thread SQL. This supports the internal optimization without claiming live-channel or packaged cold-start performance.
Evidence reviewed 8 items Pinned implementation: The introduced delta batches unique IDs in chunks of 500 within one transaction, prunes each namespace/prefix once, rereads only after deletion, and reconstructs results in requested order.
Current main still needs the optimization: Fetched main retains synchronous, single-ID ownership lookup through getDeliveryQueueEntryOwners; the requested worker batch operation is not present there.
Latest release check: The v2026.9.5 source also retains the synchronous single-ID implementation, so the supplied latest release does not contain this optimization.
Findings None None.
Security None None.

How this fits together

The outbound delivery queue records whether a message is pending, completed, or failed. Restart recovery consults those records to decide whether to defer, resume, or settle interrupted work.

flowchart TD
  A[Interrupted sessions] --> B[Collect delivery IDs]
  B --> C[Shared SQLite worker]
  C --> D[Read queue namespaces]
  D --> E[Apply existing receipt expiry]
  E --> F[Ordered ownership results]
  F --> G[Defer resume or settle recovery]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +65, Tests +79. Total +144 across 24 files.

View PR surface stats
Area Files Added Removed Net
Source 12 175 110 +65
Tests 12 149 70 +79
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 24 324 180 +144

Review metrics

Metric Value Why it matters
Production versus test growth Production net +65 lines; tests net +79 lines Production growth supports bounded batching through the existing owner; tests protect ordering, expiry, and worker isolation.
Reported warm batch latency 100 bounded receipts: 59.694 ms → 1.531 ms The measured benefit is batch lookup latency; single-ID calls are slower and end-to-end delivery was not measured.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/infra/outbound/delivery-queue-ownership.kernel.ts, migration/backfill/repair: src/infra/outbound/delivery-queue-storage.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep ownership reads and receipt cleanup in the existing worker, with one ordered batch per recovery decision and the existing transaction-bound API for compound operations.

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

Not applicable to a functional bug: current source establishes repeated synchronous per-ID lookups, and the supplied benchmark measures their overhead.

Is this the best way to solve the issue?

Yes. Extending the existing worker and transaction kernel avoids a competing storage owner, and the inspected diff preserves the persisted contract.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded recovery-performance improvement with no demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 supplied real SQLite benchmark exercises the changed public worker lookup and records improved warm batch latency; boundary coverage additionally checks captured state and zero main-thread SQL. This supports the internal optimization without claiming live-channel or packaged cold-start performance.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied real SQLite benchmark exercises the changed public worker lookup and records improved warm batch latency; boundary coverage additionally checks captured state and zero main-thread SQL. This supports the internal optimization without claiming live-channel or packaged cold-start performance.

Evidence

What I checked:

  • Pinned implementation: The introduced delta batches unique IDs in chunks of 500 within one transaction, prunes each namespace/prefix once, rereads only after deletion, and reconstructs results in requested order. (src/infra/delivery-queue-sqlite.kernel.ts:109, 7d526cf467f6)
  • Current main still needs the optimization: Fetched main retains synchronous, single-ID ownership lookup through getDeliveryQueueEntryOwners; the requested worker batch operation is not present there. (src/infra/outbound/delivery-queue-storage.ts, c2d8511f0e1d)
  • Latest release check: The v2026.9.5 source also retains the synchronous single-ID implementation, so the supplied latest release does not contain this optimization. (src/infra/outbound/delivery-queue-storage.ts, ec9c1a13db89)
  • Prior compatibility blocker resolved: The pruning SQL predicates, retention parser, serialization, and state schemas remain unchanged. The changed return value reports whether deletion occurred; it does not introduce a migration or new retention policy. The storage review checkpoint expressly exempts bounded query improvements that preserve these contracts. (src/infra/delivery-queue-sqlite-bound.ts:71, 7d526cf467f6)
  • Worker and caller boundaries: The lookup uses the existing worker admission owner and rechecks captured admission after awaiting results. Outbound callers recheck cancellation; restart recovery rechecks shouldContinue. The leaf ownership kernel removes the previously reported broad payload dependency. Lookup results do not mint platform-send authority. (src/infra/outbound/delivery-queue-storage.ts:85, 7d526cf467f6)
  • Behavior and performance evidence: The supplied body snapshot, sourceRevision a51b9c57fa1203df5c32abba05990ad3de7fda9e7417f0ac47b7cce6820410e6, reports a real isolated shared-state database benchmark through the public batch worker API: 100 bounded receipts improved from 59.694 ms to 1.531 ms warm. It explicitly reports slower single-ID calls, a 5.825-second source-worker cold operation, and no end-to-end delivery claim. Reported focused tests cover captured state, supervisor-mode rejection, duplicate/missing IDs, expiry, precedence, and zero main-thread SQL. Tests were not executed during this read-only review.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • galiniliev: 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 (5 earlier review cycles)
  • reviewed 2026-09-21T07:58:22.647Z sha 6a93c13 :: blocked before merge. :: none
  • reviewed 2026-09-21T08:10:42.743Z sha 6a93c13 :: blocked before merge. :: [P2] Extract the ownership lookup into a dependency leaf
  • reviewed 2026-09-21T08:58:52.391Z sha 51fa3b690e2021fd7881a6e0ec7b558659ea31d8 :: blocked before merge. :: none
  • reviewed 2026-09-21T09:18:20.540Z sha 455c48edea71837fc28accf5508e896574f3a611 :: blocked before merge. :: none
  • reviewed 2026-09-21T09:44:00.714Z sha 0e19a88df49dcd064e2a3c2c9dfd1eb31b709a23 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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. and removed 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 21, 2026
@steipete
steipete force-pushed the codex/delivery-receipt-prune-read-reuse branch from 455c48e to 0e19a88 Compare September 21, 2026 09:35
@steipete
steipete force-pushed the codex/delivery-receipt-prune-read-reuse branch from 0e19a88 to 7d526cf Compare September 21, 2026 09:57
@steipete
steipete merged commit 71382da into main Sep 21, 2026
218 checks passed
@steipete
steipete deleted the codex/delivery-receipt-prune-read-reuse branch September 21, 2026 10:26
@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 22, 2026
…penclaw#154591)

* improve(outbound): batch delivery ownership checks during recovery

* fix(delivery): isolate ownership lookup kernel

* fix(delivery): retain raw query justification on expression
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime maintainer Maintainer-authored PR 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