Skip to content

fix(channels): ingress claimNext starves other conversations when one blocked lane fills the scan window - #161997

Open
YangManBOBO wants to merge 15 commits into
openclaw:mainfrom
YangManBOBO:fix/ingress-lane-starvation-v2
Open

YangManBOBO wants to merge 15 commits into
openclaw:mainfrom
YangManBOBO:fix/ingress-lane-starvation-v2

Conversation

@YangManBOBO

@YangManBOBO YangManBOBO commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where the durable ingress queue's claimNext silently 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:

  1. SQL blocked-lane filter skipped when deriveLaneKey is passed. The production drain always passes deriveLaneKey (ingress-drain.ts:793), but the SQL WHERE clause that excludes rows with a stored lane_key in the blocked set only runs when deriveLaneKey is 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.

  2. 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.

  3. 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/reconcileStoredLaneKey callback that makes an earlier row eligible was not detected, and the next call could wrongly skip past rows the new policy would claim.

  4. 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 receivedAt before 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. claimNext scans the first 100 rows (all lane-A, all blocked) and returns null, 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:

  1. Always apply the SQL stored-lane filter. The !claimOptions?.deriveLaneKey guard is removed. The SQL filter is harmless when deriveLaneKey is also passed: rows with a stored lane_key in the blocked set are excluded (correct — the stored key is authoritative), and rows with NULL lane_key pass through to JS-level derivation and filtering (existing behavior). This alone fully restores the WhatsApp/Discord path.

  2. 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.

  3. 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.

  4. 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 receivedAt enqueue, 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.

  5. 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 no receivedAt to 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.

  6. Register the new test in the database-worker lane. ingress-queue.resume.test.ts was missing from databaseWorkerCoreTestFiles in test/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 with laneKey="blocked" then 1 row with laneKey="free" — on main, claimNext({deriveLaneKey, blockedLaneKeys:["blocked"], scanLimit:100}) returns null; on fix returns row-100. Derived-lane variant enqueues 100 rows without stored lane key where deriveLaneKey returns "blocked" for each, then 1 row deriving to "free" — on main returns null; on fix paginates and returns row-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 with 1 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 no receivedAt; 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 createChannelIngressQueue against a real SQLite state file:

=== Scenario A: stored-lane blocked prefix fills the scan window (SQL filter) ===
claimNext(blocked=[blocked], scanLimit=100, deriveLaneKey) => "free-A"
  (free-A is row 100, beyond the 100-row window; must be claimed)

=== Scenario B: derived-lane blocked prefix beyond one snapshot (keyset paging) ===
claimNext(blocked=[blocked], scanLimit=100, deriveLaneKey) => "free-B"
  (free-B is row 100+201 beyond the snapshot cap of scanLimit+100; must page and be claimed)

=== Scenario C: blocked set exceeds SQLite bind budget ===
claimNext(40000 blocked lanes, deriveLaneKey) => "free-C"
  (the SQL predicate stays bounded, no bind-variable overflow)

=== Scenario D: earlier row enqueued between direct claims keeps ordering ===
claimNext #1 (blocks 6000-8200, budget exhausted => null) => null
enqueue earlier-free (receivedAt before retained cursor) => "accepted"
claimNext #2 (must claim earlier-free before free-tail) => "earlier-free"

On unfixed main, the same trace returns null for every claimNext — 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 resolveLaneKey helper (ingress-drain.ts) already uses deriveLaneKey ?? laneKey ?? id — the stored lane key is authoritative and the drain already prefers it. The blockedLaneKeys set in drainOnce is 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.

… 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.
@clawsweeper

clawsweeper Bot commented Sep 30, 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 P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 30, 2026
@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: A direct claimNext call returns null without reaching free-B.
  • After: The selector advances beyond the blocked window and claims free-B.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful and source-reviewed with production-owner SQLite evidence, but the strongest exercised boundary is an in-process queue harness rather than a shipped channel entry point.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The supplied runtime output exercises createChannelIngressQueue through the real SQLite worker with stored and derived blocked prefixes, an oversized blocked-key set, and an earlier enqueue; subsequent real-queue regressions cover retained-prefix and cursor-policy repairs.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Direct ingress selection can leave an unrelated conversation waiting despite an eligible pending message.
Reason: The canonical report establishes the existing eligibility contract, and the patch repairs it through the shared owner without expanding the public queue API.

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
Reviewed head: 6592de7a6a028d0b58bf901761f85ba07343f0ff

Before merge

None.

Findings

None.

Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

  • Bounded snapshot selection and stored-lane filtering changes intended behavior with a stated reason (unknown: The broker cutover preserved bounded host selection and native snapshot checks; git log -S could not establish the earliest introduction because historical blobs were unavailable.)
  • Worker-owned ingress operations keeps the original intent (f0b78f5: Move operational queue reads and writes off the Gateway thread while preserving one FIFO storage owner and claim fencing.)
  • Live lane-policy admission keeps the original intent (271d915: Revalidate lane observations at transaction and commit admission so queued claims do not use stale policy.)
  • Worker inventory and test-lane registration keeps the original intent (f0b78f5: Keep worker-only SQL classification and broker-dependent queue tests aligned with the execution owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +566, Tests +702, Other +1. Total +1269 across 10 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 6 585 19 +566
Tests 3 703 1 +702
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 10 1289 20 +1269

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +585/-19; tests +702/-1 Production growth implements paging and retained-prefix correctness; regression coverage exercises distinct ordering, replacement, callback-policy, and bind-budget failures.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #127476
Summary: This PR addresses the canonical direct-selection starvation report; the earlier drain repair covers a related scheduling mitigation.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: The remaining direct-selection defect can suppress eligible messages, but the shared production drain already mitigates the original blocked-prefix scenario.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-01T06:30:11.356Z sha e4e9cd6 :: blocked before merge. :: [P2] Revalidate retained progress after writes from other handles | [P2] Invalidate progress when releasing a minimal claim reference
  • reviewed 2026-10-01T07:19:38.467Z sha 6e3e7eb :: blocked before merge. :: [P2] Revalidate retained progress after writes from other handles | [P2] Invalidate progress when releasing a minimal claim reference
  • reviewed 2026-10-01T14:51:25.873Z sha 19dd5cb :: blocked before merge. :: [P2] Include the previous cursor row when resuming scan accounting | [P2] Detect prefix replacements instead of comparing only row counts
  • reviewed 2026-10-09T13:30:34.914Z sha 3523cb4 :: needs changes before merge. :: [P2] Fingerprint the persisted inputs that determine derived lanes | [P2] Fold prefix fingerprints without expanding them into arguments
  • reviewed 2026-10-13T04:28:49.166Z sha 3f32dda :: needs changes before merge. :: [P2] Validate the cursor row before resuming past it
  • reviewed 2026-10-14T13:35:40.784Z sha 75c5afb :: needs changes before merge. :: [P2] Validate the cursor row before resuming past it
  • reviewed 2026-10-14T15:46:13.247Z sha 28f25e3 :: needs changes before merge. :: [P2] Validate the cursor row before resuming past it | [P2] Invalidate saved progress when a stable callback changes its policy
  • reviewed 2026-10-15T02:19:39.980Z sha a378415 :: needs changes before merge. :: [P2] Re-evaluate the retained cursor row under current lane policy

Reviewed October 14, 2026, 11:49 PM ET / October 15, 2026, 03:49 UTC (Revision 11).

@YangManBOBO

Copy link
Copy Markdown
Contributor Author

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

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 1, 2026
…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.
@YangManBOBO

Copy link
Copy Markdown
Contributor Author

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.
@YangManBOBO

Copy link
Copy Markdown
Contributor Author

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
esumes past a blocked prefix that spans multiple resumed pages.

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
evalidates the resume cursor when another handle replaces an earlier row without changing the count.

Verification (head 3523cb4):

ode scripts/run-vitest.mjs run src/channels/message/ingress-queue.resume.test.ts - 9/9 pass

ode 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

  • pnpm tsgo:core - pass
  • oxlint on changed files + git diff --check - clean

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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).
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 14, 2026
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.
@YangManBOBO

Copy link
Copy Markdown
Contributor Author

Both remaining P2 findings are fixed at head a378415:

1. Validate the cursor row before resuming past it (P2). The prefix read in ingress-queue.claim-prefix.kernel.ts now also fingerprints the pending cursor row itself in the same pinned read. The strict-before prefix count/fingerprint cannot observe an equal-position replacement (same id + receivedAt, different lane-policy inputs); a cursor-row mismatch now drops the keyset and the scan restarts from the front. New regression: revalidates the cursor row itself when another handle replaces it at the same position — fails on 28f25e3 (claims free tail instead of the replaced row), passes on this head.

2. Invalidate saved progress when a stable callback changes its policy (P2). A resumed derived-lane scan now sets includePrefixRows on its first paged request; the worker returns the materialized scan-visible prefix rows (already read for the fingerprint, one pinned query), and the host re-evaluates every skipped row under the current callback via the same resolveLane used by the live scan. A row that now resolves outside the blocked set drops the keyset and the scan restarts from the front, so live lane policy is honored for skipped rows too — without requiring callers to replace their function. New regression: invalidates the resume cursor when a stable callback changes its captured policy — fails on 28f25e3 (claims free tail instead of row-0), passes on this head.

On the Live lane-policy checks provenance item (271d915): the original contract — claims use current lane policy at transaction and commit admission — is preserved. Rows being claimed were and are re-evaluated at admission (the preparedLanes recheck in claimNext); with finding 2 fixed, skipped rows are also re-evaluated under the current policy before a retained cursor may skip them, so the resume cache no longer bypasses live policy for either case.

Verification:

  • node scripts/run-vitest.mjs run src/channels/message/ingress-queue.resume.test.ts src/channels/message/ingress-queue.test.ts src/channels/message/ingress-queue.claim-ownership.test.ts — all pass (resume suite 17/17, incl. both new regressions)
  • Fail-proof: both new regressions fail on 28f25e3, pass on this head
  • pnpm tsgo:core + plugin-sdk test type leaf — pass
  • pnpm build:plugin-sdk:dts (uncached) — pass
  • pnpm check:database-worker-ratchet --base <merge-base> --staged — T1 223 → 223, OK
  • oxlint on changed files + git diff --check — clean

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Oct 15, 2026
…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.
@YangManBOBO

Copy link
Copy Markdown
Contributor Author

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 (includePrefixRows path in ingress-queue.claim-prefix.kernel.ts), and the host re-evaluates its lane under the current callback too. A captured-policy flip at the cursor position (same callback identity, no persisted change) now drops the keyset and the scan restarts from the front. New regression: invalidates the resume cursor when a stable callback frees the cursor row itself — fails on the pre-fix head (claims free tail instead of the cursor row), passes here. The equal-position replacement case from the previous round is covered by the existing cursor-fingerprint regression; every skipped row (strict-before prefix + cursor row) is now validated by both persisted fingerprints and current policy.

2. Conflict resolution. Merged current upstream/main (771a901). The enqueue conflict in ingress-queue.ts was resolved by keeping upstream's assertOperationCurrent threading plus this PR's invalidateResumeBefore on accepted enqueues. Upstream's new src/cron/store/event-ingress.ts caller passed the removed deriveLaneKey request flag; cut over (its blockedLaneKeys is empty, so the flag was a no-op under both semantics). GitHub mergeability recheck pending, but the local merge is clean.

Verification (worktree, exact head):

  • node scripts/run-vitest.mjs run src/channels/message/ingress-queue.resume.test.ts — 18/18 pass, incl. the new cursor-position regression
  • node scripts/run-vitest.mjs run src/channels/message/ingress-queue.test.ts src/channels/message/ingress-queue.claim-ownership.test.ts — pass
  • Fail-proof: new regression fails on pre-fix source, passes on this head
  • pnpm tsgo:core + node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.plugin-sdk.json --incremental — pass
  • pnpm build:plugin-sdk:dts (uncached, 741s) — pass
  • pnpm check:database-worker-ratchet --base 771a90134bb --staged — T1 223 → 223, OK
  • oxlint on changed files + git diff --check — clean

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 15, 2026
steipete added a commit that referenced this pull request Oct 25, 2026
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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