Repository navigation
fix(channels): ingress claimNext starves other conversations when one blocked lane fills the scan window - #161997
YangManBOBO wants to merge 15 commits into
Conversation
… blocked lane fills the scan window Fixes a defect where the durable ingress queue's claimNext silently starves unrelated conversations when one busy lane fills the entire scan window. Two minimal changes in claimNext: 1. Always apply the SQL stored-lane filter. The `!claimOptions?.deriveLaneKey` guard is removed so the stored-lane filter runs even when deriveLaneKey is passed, restoring the WhatsApp/Discord path where lane keys are stored at enqueue time. The blocked set is bound as a single JSON table value (json_each) so a retry-heavy account cannot exceed SQLite's per-query bind-variable budget; the JS pass still rechecks every row. 2. Keyset-cursor pagination. When an entire scan window is lane-blocked, claimNext pages forward with a bounded keyset cursor (up to CHANNEL_INGRESS_CLAIM_SCAN_PAGE_BUDGET pages) instead of only walking the in-memory snapshot, so a free lane beyond a blocked prefix stays reachable for derive-only channels (Telegram/Slack). Adds table-driven regression coverage for stored and derived blocked-lane rows beyond the bounded snapshot and for a blocked set exceeding SQLite's bind budget.
…y callbacks change
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR adds stored-lane filtering, keyset paging, and validated resume progress so direct ingress claims can reach conversations beyond a blocked backlog. Example: An account has 100 derived-lane events blocked in conversation A, followed by event free-B, with scanLimit 100.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: current main retains the direct-selection defect, and this PR resolves the previous cursor-row finding without a new actionable correctness or security finding. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe shared ingress queue stores account-scoped inbound events in SQLite; worker snapshots and channel lane callbacks select durable claims that the ingress drain dispatches. flowchart LR
A[Channel adapters] --> B[Ingress queue]
B --> C[Shared state worker]
C --> D[SQLite event rows]
D --> E[Paged lane selection]
E --> C
C --> F[Claimed event dispatch]
Technical reviewBest possible solution: Land the queue-owned selection repair while preserving the existing drain candidate window, durable lane semantics, and native admission checks. Do we have a high-confidence way to reproduce the issue? Yes: current-main source returns null for 100 valid derived-blocked rows followed by a free row at scanLimit 100, consistent with the supplied real SQLite trace; this review ran no target code. Is this the best way to solve the issue? The shared queue is the correct repair boundary, and the latest change completes the previous cursor-policy repair while preserving existing admission and drain contracts. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 494d418aa125. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +566, Tests +702, Other +1. Total +1269 across 10 files. Added test files: 1. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (10 earlier review cycles; latest 8 shown)
Reviewed October 14, 2026, 11:49 PM ET / October 15, 2026, 03:49 UTC (Revision 11). |
|
Addressed the review: invalidated the resume cursor when an earlier row is enqueued between direct claims (plus recovery/release/resubmit), added a regression test for the exact two-call case, and posted real SQLite runtime proof in the PR body. @clawsweeper re-review |
…queue state The retained direct-scan cursor was trusted from the creating closure alone, so a write from another handle (enqueue, release, recover, resubmit) or a minimal id-and-token release could insert a pending row before the cursor and be skipped by the keyset resume. Count the scan-visible pending rows strictly before the cursor in the same pinned read as the paged snapshot and record it at retention. On resume and on every paged direct-scan snapshot, revalidate against that count in the same read; on mismatch, drop the keyset and rescan from the front. Reset the scan on claim conflict so a write behind an in-flight page cursor is not skipped either. Add regressions for a cross-handle earlier enqueue, a write landed during paging, and a minimal-reference release.
|
Addressed the review: the retained direct-scan cursor is now revalidated against authoritative queue state. The scan records the count of scan-visible pending rows strictly before the cursor at retention; the worker recomputes that count in the same pinned read as the paged snapshot, and any mismatch (a write from any handle, or a minimal id-and-token release) drops the keyset and rescans from the front. The same revalidation applies to every paged direct-scan snapshot, and a claim conflict resets the scan so writes behind an in-flight page cursor are not skipped. Added regressions for a cross-handle earlier enqueue, a write landed during paging, and a minimal-reference release. Real SQLite worker proof is in the PR body. @clawsweeper re-review |
…tting writes Count-only revalidation of a retained direct-scan resume cursor cannot observe a write that removes one row before the cursor and inserts another earlier one: the count is preserved and the stale keyset is accepted, skipping the earlier row. Track a 64-bit FNV-1a fingerprint of the scan-visible pending rows before the cursor in the authoritative snapshot and compare it alongside the count. Materialize the prefix rows in the same pinned read, compose the fingerprint across pages by folding in the previous cursor row, and invalidate the keyset on any mismatch.
|
ClawSweeper's two remaining P2 findings are fixed and verified: 1. Resume accounting off-by-one (blocked prefix across pages). On resume the walk is now seeded with pendingBeforeCursor + 1 (including the cursor row) so a re-retained cursor records rows strictly before it without double-subtracting. New regression test 2. Count-only comparison missed offsetting writes. The authoritative snapshot now materializes the scan-visible pending rows before the cursor in the same pinned read and computes a 64-bit FNV-1a membership fingerprint, compared alongside the count. The prefix fingerprint is composed across pages by folding in the previous cursor row (new ingress-queue.claim-prefix.kernel.ts). New regression test Verification (head 3523cb4):ode scripts/run-vitest.mjs run src/channels/message/ingress-queue.resume.test.ts - 9/9 passode scripts/run-vitest.mjs run src/channels/message/ingress-queue.test.ts src/channels/message/ingress-queue.claim-ownership.test.ts src/channels/message/ingress-queue.dead-letters.test.ts - 57/57 pass
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Upstream main migrated the ingress kernel to EngineConnection (Postgres engine adapters). The textual merge kept this PR's prefix revalidation but left the new claim-prefix kernel on DatabaseSync, which failed the plugin-sdk declaration build on the synthetic merge ref (TS2345 at the readChannelIngressPrefixInDatabase call in ingress-queue.kernel.ts).
Address the two remaining review findings on retained direct-scan progress: 1. Validate the cursor row itself on resume. The strict-before prefix count and fingerprint cannot observe an equal-position replacement of the cursor row (same id and received time, different lane-policy inputs), so the resumed page would skip a row made eligible that way. The prefix read now also fingerprints the pending cursor row in the same pinned read, and a mismatch drops the keyset. 2. Invalidate retained progress when a stable callback changes its captured policy. Callback identity cannot prove an unchanged lane policy, so a resumed derived-lane scan now requests the materialized prefix rows and re-evaluates each skipped row under the current callback. A row that now resolves outside the blocked set drops the keyset and the scan restarts from the front. Both regressions fail on 28f25e3 and pass on this head.
|
Both remaining P2 findings are fixed at head a378415: 1. Validate the cursor row before resuming past it (P2). The prefix read in 2. Invalidate saved progress when a stable callback changes its policy (P2). A resumed derived-lane scan now sets On the Verification:
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…arvation-v2 # Conflicts: # src/channels/message/ingress-queue.ts
… policy The strict-before prefix rows are re-evaluated on resume, but the cursor row itself was only checked by persisted fingerprint, which cannot observe a captured-policy change behind a stable callback. When the resume revalidates a derived-lane scan, the worker now returns the materialized cursor row alongside the prefix rows and the host re-evaluates its lane too, so a policy flip at the cursor position also drops the keyset. New regression (stable callback frees the cursor row itself) fails on the pre-fix head and passes here.
|
The remaining P2 finding and the branch conflict are resolved at head 6592de7: 1. Re-evaluate the retained cursor row under current lane policy (P2). When a resumed derived-lane scan revalidates, the worker now returns the materialized cursor row alongside the strict-before prefix rows ( 2. Conflict resolution. Merged current upstream/main (771a901). The Verification (worktree, exact head):
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
An explicit cron run reads its authorized job definition and private scratch separately inside a SQLite read transaction. Read both in one dialect-layer LEFT JOIN so they share a statement snapshot, removing three SQL statements per SQLite run without another worker request. The job reader keeps its all-column authorization relation, ordered narrow projection, exact returned-ID check, existing decoder/config revision and legacy creation fallback. Missing scratch still reports revision 0; deletion keeps its revision tombstone. The standalone maintenance reader remains. No schema, cache, write, receipt, claim-before-effect, delivery authority, FIFO or 64-receipt retention change. PostgreSQL retains the shared reader's outer read-only transaction and rollback: its exact-job read is 4→3 SQL, not 4→1. SQLite exact-job is 4→1, heartbeat 3→1; PostgreSQL heartbeat remains 3→3. Accepted noncontract edges: an absent/malformed job can now require scratch SELECT privilege, and malformed job plus unsafe numeric scratch can reject the numeric data first. These do not remove the existing caller/source/cancellation checks. The production delta is +3 lines: one joined query replaces the transaction and duplicate read while sharing NULL handling with heartbeat. Existing test files cover read-after-write, tombstones, missing jobs/monitors and both database engines. No new suite or runner is added. Acceptance was registered before measurement: the committed `scripts/bench-cron-run.mts` drives signed WebSocket `cron.run` against an isolated synthetic Gateway/provider, once cold and twice warm. Each run must produce one start, one finish, one Responses request and exact-run history verification. Compare execution, history verification and settlement separately and together, plus shutdown and the entire invocation. The scratch owner must fall from 4→1 SQL with 1 request and 0 MAIN throughout; no cost may be deferred outside the run. Keep cold/warm separate and report median/p95/range. Three same-platform alternating pairs when calm, or one pair plus source attribution under campaign load. Counts and profiles make no latency/CPU-speed claim; timing claims require the timing lock, load below 24 and ≥5 alternating samples per arm. A 20% user-facing regression stops acceptance. Delivery mode none does not claim an external-send proof. The same-platform explicit comparison (baseline 814e732, candidate 93a6c4) gives: | SQL / requests / MAIN | Baseline | Candidate | | --- | --- | --- | | Cold execution + verification + settlement | 257 / 80 / 0 | 254 / 78 / 0 | | Warm 1 | 247 / 64 / 0 | 235 / 60 / 0 | | Warm 2 | 252 / 61 / 0 | 245 / 65 / 0 | | Warm median | 249.5 / 62.5 / 0 | 240 / 62.5 / 0 | | Warm descriptive p95 | 252 / 64 / 0 | 245 / 65 / 0 | | Warm range | 247–252 / 61–64 / 0 | 235–245 / 60–65 / 0 | | Shutdown | 22 / 6 / 5 | 40 / 10 / 5 | | Whole invocation | 1383 / 356 / 58 | 1369 / 352 / 58 | Each of the three runs completed one start, finish, Responses request and exact history verification. The scratch owner is exactly 4/1/0 → 1/1/0 in every run, all in its execution phase, with no extra or deferred scratch requests. All execution/verification/settlement phases are SQL-error-free and runtime MAIN remains zero. The count comparison is diagnostic, not an error-free full invocation: the frozen analyzer rejects two failed shutdown `state_leases` DELETEs (`database is locked`). Shutdown exceeds the 20% stop threshold; it was stopped and explicitly accepted by the coordinator as inherited after an independent main shutdown-lock reproduction. The separate SHUTDOWNLOCK lane owns that repair. The scratch join changes no lease code or writes. No latency or CPU-speed claim is made. The frozen 3.1.5 standard workload is a different scheduled `cron.add` flow: three valid baselines gave 06.cron 231/62/0, 235/65/0, 233/63/0 (median 233/63/0), versus ordinary warm 45/12/0. The descriptive excess is 188 SQL/51 requests, not causal subtraction. One extra standard setup aborted before any Gateway; it supplies no performance evidence. The existing scratch source is identical across that baseline and the explicit baseline. Full current-standard delta is deferred to the next census. Validation: count regression red on baseline (2 SELECTs and BEGIN/COMMIT), all 17 scratch-store tests green on the candidate; two isolated Codex P0–P2 reviews scoped-clean. The existing two-engine conformance test passed on actual SQLite and PostgreSQL 17, with catalog/trigger parity and cleanup verified. Test cost: scratch cases totaled 6.528 s (125.95 s file duration, mostly transform); the two engine cases totaled 1.846 s (260.62 s file duration, mostly transform). The candidate build and official source-freshness check passed at measured runtime head 93a6c4d; the three-sample invocation completed with the shutdown limitation above. Exact-head CI run 40176443806 completed successfully: 39 successful jobs, 26 skipped, no failures, including all three actual PostgreSQL shards, production/test types, lint, source contracts, Madge, and worker/T1/dialect ratchets. The earlier run passed types, lint and source contracts but found a worker-inventory omission: the new direct query was conservatively labeled T1. Head a187ecf corrects only inventory metadata and regenerates its snapshot: the worker snapshot and its private heartbeat helper are W, while the native Doctor reader stays T3. No runtime or SQL change is involved. The generated snapshot also catches up existing main classifications; targeted script lint and formatting pass. The two production reviews remain valid; this tooling-only correction adds no production review round. PG review approved the semantics at 68c24c4, and the coordinator explicitly carried REVIEW-OK to 93a6c4d because only benchmark TypeScript annotations changed. Candidate counts and the inherited-shutdown disposition are recorded; the corrected head’s CI and all three PG shards passed. The test-only import relocation avoids another open PR's adjacent import change; production bytes remain identical to both isolated reviews and database proof. The benchmark annotations fix CI TS7022 without changing emitted behavior. Final-head overlap at a187ecf: complete shared-index base-versus-candidate merge-tree comparison covers 21 peers (#183410, #183285, #181057, #180871, #180286, #180139, #169241, #168956, #168615, #167546, #167471, #165039, #161997, #157922, #157693, #156613, #141004, #137788, #136476, #129388, #121204). No new source conflict paths, regions or messages. Six peers (#181057, #180871, #180139, #169241, #129388, #121204) have added or changed conflicts confined to the fully generated worker inventory. The coordinator explicitly accepted this class because main's snapshot was stale and generated outputs must be regenerated, not hand-edited. The same exact-head disposition carries PG REVIEW-OK because runtime bytes are unchanged. Exact-head CI and all three PostgreSQL shards passed. PG checklist: (1) read-only; existing writer transaction/advisory-lock, DML/conflict and cross-store commit ordering unchanged. (2) At most one joined row via the existing composite primary keys, original job fields plus four scratch fields, unchanged 256 KiB scratch write bound. (3) No cache/generation or invalidation change; one statement snapshot, existing outer PG read transaction retained. (4) No schema/admission/identity/retry/probe change. (5) Same worker owner, one request, no MAIN expansion; target 4→1 SQL in all three real Gateway runs, with the inherited shutdown failure disclosed above. (6) Actual PostgreSQL 17 and SQLite owner conformance passed; all three final-head PostgreSQL CI shards and the other selected static checks passed. Knip was run separately because ordinary PR CI excludes it. The canonical candidate export scan failed with 26 script, 20 production and 16 full-tree findings; none is in a changed file. All 62 occurrences (52 unique file/symbol pairs), scanner/config/compiler inputs and package inputs are unchanged from merge-base dada70f. The only removed imports, runSqliteReadSnapshotSync and loadCronRows, both retain multiple real production consumers. Current-main diagnostic sections reported 14 script and 7 production findings; main has already repaired 40 candidate occurrences in unrelated changes. Its separate full-tree scan was intentionally stopped after the coordinator accepted the source-attributed inherited findings; it is not a passing full-main scan. No ignored exports, baselines or unrelated code were changed. The failed candidate scan is explicitly accepted as inherited; all branch changes and selected CI static checks pass. Pre-merge shared-index refresh retains 17 open peers from that audit. Only #180871 moved (f140f16); its fresh base-versus-candidate comparison still adds conflicts solely in the generated worker inventory, within the coordinator-accepted class. No new source conflicts. Co-authored-by: Peter Steinberger <[email protected]>
An explicit cron run reads its authorized job definition and private scratch separately inside a SQLite read transaction. Read both in one dialect-layer LEFT JOIN so they share a statement snapshot, removing three SQL statements per SQLite run without another worker request. The job reader keeps its all-column authorization relation, ordered narrow projection, exact returned-ID check, existing decoder/config revision and legacy creation fallback. Missing scratch still reports revision 0; deletion keeps its revision tombstone. The standalone maintenance reader remains. No schema, cache, write, receipt, claim-before-effect, delivery authority, FIFO or 64-receipt retention change. PostgreSQL retains the shared reader's outer read-only transaction and rollback: its exact-job read is 4→3 SQL, not 4→1. SQLite exact-job is 4→1, heartbeat 3→1; PostgreSQL heartbeat remains 3→3. Accepted noncontract edges: an absent/malformed job can now require scratch SELECT privilege, and malformed job plus unsafe numeric scratch can reject the numeric data first. These do not remove the existing caller/source/cancellation checks. The production delta is +3 lines: one joined query replaces the transaction and duplicate read while sharing NULL handling with heartbeat. Existing test files cover read-after-write, tombstones, missing jobs/monitors and both database engines. No new suite or runner is added. Acceptance was registered before measurement: the committed `scripts/bench-cron-run.mts` drives signed WebSocket `cron.run` against an isolated synthetic Gateway/provider, once cold and twice warm. Each run must produce one start, one finish, one Responses request and exact-run history verification. Compare execution, history verification and settlement separately and together, plus shutdown and the entire invocation. The scratch owner must fall from 4→1 SQL with 1 request and 0 MAIN throughout; no cost may be deferred outside the run. Keep cold/warm separate and report median/p95/range. Three same-platform alternating pairs when calm, or one pair plus source attribution under campaign load. Counts and profiles make no latency/CPU-speed claim; timing claims require the timing lock, load below 24 and ≥5 alternating samples per arm. A 20% user-facing regression stops acceptance. Delivery mode none does not claim an external-send proof. The same-platform explicit comparison (baseline 814e732, candidate 93a6c4) gives: | SQL / requests / MAIN | Baseline | Candidate | | --- | --- | --- | | Cold execution + verification + settlement | 257 / 80 / 0 | 254 / 78 / 0 | | Warm 1 | 247 / 64 / 0 | 235 / 60 / 0 | | Warm 2 | 252 / 61 / 0 | 245 / 65 / 0 | | Warm median | 249.5 / 62.5 / 0 | 240 / 62.5 / 0 | | Warm descriptive p95 | 252 / 64 / 0 | 245 / 65 / 0 | | Warm range | 247–252 / 61–64 / 0 | 235–245 / 60–65 / 0 | | Shutdown | 22 / 6 / 5 | 40 / 10 / 5 | | Whole invocation | 1383 / 356 / 58 | 1369 / 352 / 58 | Each of the three runs completed one start, finish, Responses request and exact history verification. The scratch owner is exactly 4/1/0 → 1/1/0 in every run, all in its execution phase, with no extra or deferred scratch requests. All execution/verification/settlement phases are SQL-error-free and runtime MAIN remains zero. The count comparison is diagnostic, not an error-free full invocation: the frozen analyzer rejects two failed shutdown `state_leases` DELETEs (`database is locked`). Shutdown exceeds the 20% stop threshold; it was stopped and explicitly accepted by the coordinator as inherited after an independent main shutdown-lock reproduction. The separate SHUTDOWNLOCK lane owns that repair. The scratch join changes no lease code or writes. No latency or CPU-speed claim is made. The frozen 3.1.5 standard workload is a different scheduled `cron.add` flow: three valid baselines gave 06.cron 231/62/0, 235/65/0, 233/63/0 (median 233/63/0), versus ordinary warm 45/12/0. The descriptive excess is 188 SQL/51 requests, not causal subtraction. One extra standard setup aborted before any Gateway; it supplies no performance evidence. The existing scratch source is identical across that baseline and the explicit baseline. Full current-standard delta is deferred to the next census. Validation: count regression red on baseline (2 SELECTs and BEGIN/COMMIT), all 17 scratch-store tests green on the candidate; two isolated Codex P0–P2 reviews scoped-clean. The existing two-engine conformance test passed on actual SQLite and PostgreSQL 17, with catalog/trigger parity and cleanup verified. Test cost: scratch cases totaled 6.528 s (125.95 s file duration, mostly transform); the two engine cases totaled 1.846 s (260.62 s file duration, mostly transform). The candidate build and official source-freshness check passed at measured runtime head 93a6c4d; the three-sample invocation completed with the shutdown limitation above. Exact-head CI run 40176443806 completed successfully: 39 successful jobs, 26 skipped, no failures, including all three actual PostgreSQL shards, production/test types, lint, source contracts, Madge, and worker/T1/dialect ratchets. The earlier run passed types, lint and source contracts but found a worker-inventory omission: the new direct query was conservatively labeled T1. Head a187ecf corrects only inventory metadata and regenerates its snapshot: the worker snapshot and its private heartbeat helper are W, while the native Doctor reader stays T3. No runtime or SQL change is involved. The generated snapshot also catches up existing main classifications; targeted script lint and formatting pass. The two production reviews remain valid; this tooling-only correction adds no production review round. PG review approved the semantics at 68c24c4, and the coordinator explicitly carried REVIEW-OK to 93a6c4d because only benchmark TypeScript annotations changed. Candidate counts and the inherited-shutdown disposition are recorded; the corrected head’s CI and all three PG shards passed. The test-only import relocation avoids another open PR's adjacent import change; production bytes remain identical to both isolated reviews and database proof. The benchmark annotations fix CI TS7022 without changing emitted behavior. Final-head overlap at a187ecf: complete shared-index base-versus-candidate merge-tree comparison covers 21 peers (openclaw#183410, openclaw#183285, openclaw#181057, openclaw#180871, openclaw#180286, openclaw#180139, openclaw#169241, openclaw#168956, openclaw#168615, openclaw#167546, openclaw#167471, openclaw#165039, openclaw#161997, openclaw#157922, openclaw#157693, openclaw#156613, openclaw#141004, openclaw#137788, openclaw#136476, openclaw#129388, openclaw#121204). No new source conflict paths, regions or messages. Six peers (openclaw#181057, openclaw#180871, openclaw#180139, openclaw#169241, openclaw#129388, openclaw#121204) have added or changed conflicts confined to the fully generated worker inventory. The coordinator explicitly accepted this class because main's snapshot was stale and generated outputs must be regenerated, not hand-edited. The same exact-head disposition carries PG REVIEW-OK because runtime bytes are unchanged. Exact-head CI and all three PostgreSQL shards passed. PG checklist: (1) read-only; existing writer transaction/advisory-lock, DML/conflict and cross-store commit ordering unchanged. (2) At most one joined row via the existing composite primary keys, original job fields plus four scratch fields, unchanged 256 KiB scratch write bound. (3) No cache/generation or invalidation change; one statement snapshot, existing outer PG read transaction retained. (4) No schema/admission/identity/retry/probe change. (5) Same worker owner, one request, no MAIN expansion; target 4→1 SQL in all three real Gateway runs, with the inherited shutdown failure disclosed above. (6) Actual PostgreSQL 17 and SQLite owner conformance passed; all three final-head PostgreSQL CI shards and the other selected static checks passed. Knip was run separately because ordinary PR CI excludes it. The canonical candidate export scan failed with 26 script, 20 production and 16 full-tree findings; none is in a changed file. All 62 occurrences (52 unique file/symbol pairs), scanner/config/compiler inputs and package inputs are unchanged from merge-base 71bc695. The only removed imports, runSqliteReadSnapshotSync and loadCronRows, both retain multiple real production consumers. Current-main diagnostic sections reported 14 script and 7 production findings; main has already repaired 40 candidate occurrences in unrelated changes. Its separate full-tree scan was intentionally stopped after the coordinator accepted the source-attributed inherited findings; it is not a passing full-main scan. No ignored exports, baselines or unrelated code were changed. The failed candidate scan is explicitly accepted as inherited; all branch changes and selected CI static checks pass. Pre-merge shared-index refresh retains 17 open peers from that audit. Only openclaw#180871 moved (f140f16); its fresh base-versus-candidate comparison still adds conflicts solely in the generated worker inventory, within the coordinator-accepted class. No new source conflicts. Co-authored-by: Peter Steinberger <[email protected]>
What Problem This Solves
Fixes an issue where the durable ingress queue's
claimNextsilently starves unrelated conversations when one busy lane fills the entire scan window. A WhatsApp group (or Slack channel, Telegram chat, etc.) with enough spooled inbound events can block delivery for all other conversations on the same account — hours of silence, no errors, no visible failure.Four complementary defects in
claimNext:SQL blocked-lane filter skipped when
deriveLaneKeyis passed. The production drain always passesderiveLaneKey(ingress-drain.ts:793), but the SQL WHERE clause that excludes rows with a storedlane_keyin the blocked set only runs whenderiveLaneKeyis absent. WhatsApp and Discord store lane keys at enqueue time, so those rows could be efficiently excluded at the SQL level — but in production, they never are.No keyset pagination when the scan window is all lane-blocked. When all rows in the window are valid but blocked, the while loop exits immediately and returns
null, even though claimable rows exist beyond the window.Resume cursor not invalidated when lane-policy callbacks change (review finding). The direct-claim resume cursor was stored as booleans only, so a changed
deriveLaneKey/reconcileStoredLaneKeycallback that makes an earlier row eligible was not detected, and the next call could wrongly skip past rows the new policy would claim.Resume cursor not invalidated when an earlier row is enqueued between direct claims (review finding). After a direct claim exhausts its budget and retains a cursor, a new free-lane event enqueued with
receivedAtbefore that cursor was skipped by the keyset predicate (received_at > cursor), so the earlier event could be claimed after a later one.Concrete scenario: WhatsApp group A accumulates 100 spooled events during a long agent turn (lane-A blocked). A DM from user B arrives after the flood.
claimNextscans the first 100 rows (all lane-A, all blocked) and returnsnull, never reaching B's row at position 101. B waits indefinitely. The stalled behavior survives across drain cycles because the same blocked prefix is re-scanned each time.Why This Change Was Made
Minimal changes in
claimNext:Always apply the SQL stored-lane filter. The
!claimOptions?.deriveLaneKeyguard is removed. The SQL filter is harmless whenderiveLaneKeyis also passed: rows with a storedlane_keyin the blocked set are excluded (correct — the stored key is authoritative), and rows with NULLlane_keypass through to JS-level derivation and filtering (existing behavior). This alone fully restores the WhatsApp/Discord path.Keyset cursor for lane-blocked windows. When the entire scan window consists of valid but lane-blocked rows (none claimable, none corrupt), a keyset cursor advances past the last scanned row and re-queries, bounded by a page budget so stop responsiveness is preserved. When the budget runs out on a direct scan, the cursor is retained so the next direct call resumes past the blocked prefix instead of restarting at the queue front.
Invalidate the resume cursor on callback change (review finding). The direct-scan resume state now retains the lane-policy callbacks by identity; when they change, the cursor is discarded and the scan restarts, so a changed policy that makes an earlier row eligible is honored instead of skipped. Cleared whenever a claim succeeds or the scan reaches the end of the queue.
Invalidate the resume cursor on an earlier enqueue (review finding). Any write that adds a pending row sorting before the retained cursor — an explicit earlier
receivedAtenqueue, a recovered/released claim, or a resubmit — now invalidates the cursor so the next direct call rescans from the front and claims the earlier row first. Rows enqueued after the cursor keep the resume benefit.Authoritative queue-state revalidation of retained and in-flight cursors (review findings: cross-handle writes and minimal-reference release). Closure-side invalidation cannot observe writes from other queue handles, and
release({ id, claim: { token } })carries noreceivedAtto run the guard. The scan now records, at retention, the authoritative count of scan-visible pending rows strictly before the cursor, and the worker counts the same predicate in the same pinned read as the paged snapshot. On resume and on every paged direct-scan snapshot the count is revalidated against the queue; a mismatch means a write from any handle inserted or removed a row before the cursor, so the keyset is dropped and the scan restarts from the front. A claim conflict also resets the scan so a write landing behind an in-flight page cursor is not skipped. This covers cross-handle enqueue/release/recover/resubmit and id-and-token-only releases without a per-release ordering query.Register the new test in the database-worker lane.
ingress-queue.resume.test.tswas missing fromdatabaseWorkerCoreTestFilesintest/vitest/vitest.database-worker-core-paths.mjs, which ran it in a bun fast lane without the host broker (SqliteWorkerError: Shared-state admission requires the host broker). It is now registered beside its sibling ingress-queue tests.User Impact
Durable channels (WhatsApp, Discord, Telegram, Slack, and any channel using the shared ingress queue) no longer experience unbounded delivery stalls when one conversation is busy. Messages from other conversations proceed normally with no config, protocol, or persisted-state changes.
Evidence
Regression coverage
ingress-queue.test.ts(2 new, table-driven): stored-lane variant enqueues 100 rows withlaneKey="blocked"then 1 row withlaneKey="free"— on main,claimNext({deriveLaneKey, blockedLaneKeys:["blocked"], scanLimit:100})returnsnull; on fix returnsrow-100. Derived-lane variant enqueues 100 rows without stored lane key wherederiveLaneKeyreturns "blocked" for each, then 1 row deriving to "free" — on main returnsnull; on fix paginates and returnsrow-100.ingress-queue.resume.test.ts(new): "resumes direct claim scans past a blocked prefix beyond the page budget", "invalidates the resume cursor when the lane-policy callbacks change", and "invalidates the resume cursor when an earlier row is enqueued between direct claims". The cursor-invalidation tests fail against the old boolean-only logic and against a build without the earlier-enqueue invalidation (stash proof: the earlier-enqueue test fails with1 failed).Authoritative revalidation regressions (latest review fix): "revalidates the resume cursor against authoritative state when another handle enqueues an earlier row" (a second queue handle writes an earlier row the first handle's closure cannot see; the resume must claim it first), "revalidates the resume cursor when a minimal claim reference releases an earlier row" (
release({ id, claim: { token } })with noreceivedAt; the released row must be claimed before the tail), and "revalidates the in-flight page cursor when another handle writes during paging" (a write lands between pages of one call via the claim clock; the keyset must be dropped and the earlier row claimed). Each fails without the authoritative count revalidation and passes with it.Against unfixed main, the new tests fail (claimNext returns null, never reaching the free lane past the blocked window). Pre-existing tests pass unchanged.
node scripts/run-vitest.mjs run src/channels/message/ingress-queue.resume.test.ts→ 7 passed;node scripts/run-vitest.mjs run src/channels/message/ingress-queue.test.ts src/channels/message/ingress-queue.claim-ownership.test.ts src/channels/message/ingress-queue.dead-letters.test.ts→ 57 passed;node scripts/run-vitest.mjs run src/channels/message/ingress-queue.test.ts src/channels/message/ingress-queue.dead-letters.test.ts→ 46 passed. Core typecheck (tsgo -p tsconfig.core.json) → exit 0.Runtime proof (real SQLite queue through the worker)
A focused production-queue trace drives the real
createChannelIngressQueueagainst a real SQLite state file:On unfixed main, the same trace returns
nullfor everyclaimNext— the free lane beyond the blocked window is never reached, and Scenario D's earlier enqueue would be skipped by the retained cursor.Sibling-surface context
The ingress drain's
resolveLaneKeyhelper (ingress-drain.ts) already usesderiveLaneKey ?? laneKey ?? id— the stored lane key is authoritative and the drain already prefers it. TheblockedLaneKeysset indrainOnceis computed identically from active/claimed/retry-delayed lanes regardless of this change. No drain, claim, or delivery behavior is altered beyond claimNext no longer returning false negatives when a blocked lane fills the scan window.