Skip to content

fix(queue): preserve lifecycle state across replay failures - #1375

Merged
vincentkoc merged 1 commit into
mainfrom
fix/worker-replay-idempotency
Sep 3, 2026
Merged

vincentkoc merged 1 commit into
mainfrom
fix/worker-replay-idempotency

Conversation

@vincentkoc

Copy link
Copy Markdown
Member

Related: #1368

What Problem This Solves

Fixes an issue where a lost Worker response could replay a committed lifecycle operation, mutate canonical state twice, or fail to restore derived Bay and alarm state after the canonical transaction had already committed.

This is the server prerequisite only. It does not re-enable client-side post-effect retries.

Why This Change Was Made

Router receipts and terminal dispositions now use durable operation identity inside the lifecycle projection transaction. Same-identity replays skip canonical mutation but always rerun idempotent Bay materialization and scheduling; conflicting terminal operation kinds return HTTP 409.

The router endpoint preserves the deployed f7 ordering rule for a matching receipt followed by a newer or equal non-routed terminal, and additionally preserves any authoritative requeue when a delayed router request had not committed a receipt. This endpoint rule is intentionally narrower than the lifecycle store contract: applyTerminalDisposition still permits requeue-to-route transitions for other callers, as covered by queue-policy tests.

Terminal operation IDs remain for the projection lifetime with no eviction. Old rows without the field load as an empty ledger; malformed or duplicate entries are rejected.

Peter Steinberger authored the original publication-retry work and is credited in the signed commit. This prerequisite is separated because the server behavior must differ from the source PR before post-effect retries can safely return.

User Impact

Operators get deterministic lifecycle recovery after ambiguous Worker failures: duplicate delivery cannot recreate canonical effects, overwrite a later requeue, or leave Bay/alarm projections stale.

There is no new public API or configuration surface.

OpenClaw Bay Impact

The public Bay projection and schema are unchanged. Duplicate router and terminal deliveries rerun the existing idempotent syncBayLifecycle path after the canonical transaction, so a post-commit materialization failure can recover without changing lifecycle facts.

Documentation Impact

Reviewed docs/live-dashboard.md. No documentation change is needed: post-effect requests remain deliberately one-shot, and this PR only repairs the Worker prerequisite needed before that availability tradeoff can be reconsidered.

Evidence

  • Signed head: ba3822b6cf179d98bcaf2444e6974deb6095e752
  • Base: 674841bcdc0a826ff4555f945cc81f122db0d6c2
  • Scope: three files only.
  • Production: +98/-80, net +18.
  • Tests: +238/-87, net +151.
  • Focused proof: 436 passed, 0 failed:
    • publication lifecycle: 79
    • Bay routes: 115
    • queue runtime: 187
    • queue policy: 55
  • CI=1 pnpm run check:static: passed.
  • pnpm run build:all: passed.
  • pnpm run lint: passed.
  • pnpm run format: passed on 808 files.
  • git diff --check: passed.

Regression coverage includes:

  • all eight non-routed terminal kinds with matching newer/equal receipt timestamps remain unchanged;
  • terminal older than its matching receipt returns 409 atomically;
  • receiptless non-requeue returns 409 without recording a receipt;
  • receiptless requeue returns 200 and remains authoritative without a driver;
  • post-commit derived failure replay reruns Bay and scheduling without canonical mutation;
  • terminal same-ID/same-kind replay is a no-op; same-ID/different-kind returns 409;
  • more than 32 terminal IDs remain deduplicated for the projection lifetime;
  • malformed and duplicate ledgers are rejected, while a row with no ledger loads;
  • transaction rollback and the existing direct-command acknowledgement finalizer coverage remain intact.

Review precedence

Two local review suggestions were considered and rejected after direct source/history audit:

  1. A distinct router receipt does not automatically override an existing requeue at this delayed-router endpoint. That would reintroduce the failed-before-commit ordering bug. Other store callers retain the intentional requeue-to-route transition.
  2. String terminal IDs and { kind: null } entries are not deployed durable states. Before f7 the field did not exist; f7 introduced the field and writes only concrete { operationId, kind } entries. The removed reader bridge covered an unmerged predecessor shape, not a shipped migration.

Real Behavior Proof

Claim: the real Worker HTTP boundary preserves a requeue across delayed router delivery, makes completed router and terminal replays canonical no-ops, and rejects a conflicting terminal operation kind.

Surface: Wrangler 4.107 running the production Worker and SQLite Durable Object locally over HTTP loopback. GitHub App installation and repository metadata were served by an ephemeral local mock; no private endpoint, credential, or repository data was retained.

Command:

bash /tmp/clawsweeper-worker-replay-proof.sh "$PWD" 8796

Observed result:

{"ok":true,"transport":"HTTP loopback","runtime":"Wrangler Worker with SQLite Durable Object","router":{"delayed_receipt_preserved_requeue":true,"duplicate_left_updated_at_unchanged":true},"terminal":{"duplicate_left_updated_at_unchanged":true,"conflicting_kind_status":409}}

Limits: this proves the production Worker/SQLite/HTTP boundary locally. It does not claim deployment or a live queue mutation. Docker was unavailable. Two AWS Crabbox attempts failed before running repository commands: one because local Actions hydration did not support pnpm/[email protected], and one on broker DNS/EOF plus cancel-create timeout. A local full pnpm run check fallback reached unrelated terminal proof/PTY infrastructure failures; the focused owner-boundary suites and all static/build/lint/format gates above are green.

No deployment, queue dispatch, cancellation, retry, or other live operation was performed.

Preserve authoritative endpoint terminal ordering while making router and terminal replays transactionally duplicate-safe.

Co-authored-by: Peter Steinberger <[email protected]>
@clawsweeper

clawsweeper Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Please review exact head ba3822b6cf179d98bcaf2444e6974deb6095e752. The PR body contains the current-main proof, real Worker/SQLite transport trace, and explicit maintainer precedence rationale for the endpoint requeue fence and deployed ledger shape.

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 3, 2026, 9:39 AM ET / 13:39 UTC.

ClawSweeper review

What this changes

The PR makes lifecycle router and terminal callbacks idempotent across lost responses while rerunning Bay materialization and alarm scheduling after committed replays.

Merge readiness

⛔ Blocked before merge - 5 items remain

Keep this PR open: its replay recovery approach is useful, but it removes a currently accepted durable ledger representation and lacks the Docker-backed Crabbox proof required by repository policy.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The PR has focused replay evidence and scope, but a persisted-format compatibility regression and the policy-required proof gap block merge readiness.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Evidence reviewed 4 items Introduced durable-format regression: Current main accepts persisted string terminal-operation IDs by converting them to records with a null kind; the PR changes the reader to reject non-object or null-kind entries as an invalid lifecycle projection row.
Regression test codifies rejection: The introduced test explicitly treats a string terminal-operation ID as an invalid row, removing coverage for the compatibility behavior present on current main.
Lifecycle history context: The current lifecycle code on main contains the legacy decoder, and recent history identifies merged PR #1368 as the preceding publication-retry change in this surface.
Findings 1 actionable finding [P1] Retain readable legacy terminal-operation ledgers
Security None None.

How this fits together

Exact-review lifecycle callbacks persist queue state in a SQLite Durable Object. Those lifecycle facts drive terminal finalization, OpenClaw Bay telemetry, and subsequent queue scheduling.

flowchart LR
  A[Lifecycle callback] --> B[Exact-review queue route]
  B --> C[SQLite lifecycle projection]
  C --> D{Replay or new operation}
  D --> E[Bay lifecycle telemetry]
  D --> F[Queue alarm scheduling]
  D --> G[Terminal finalization]
Loading

Decision needed

Question Recommendation
Should Martin approve an evidence-in-progress exception to the required Docker-backed Crabbox proof for this lifecycle queue change? Require Crabbox proof: Keep the PR blocked until the repaired exact head has Docker-backed Crabbox local-container proof with the required provider, image, lease, artifact, limits, and observed result.

Why: The repository policy reserves that exception to Martin, while the available proof was run outside the required Crabbox environment.

Before merge

  • Retain readable legacy terminal-operation ledgers (P1) - Current main converts persisted string IDs to { operationId, kind: null }, but this validator rejects both forms. A previously readable lifecycle row will then make its replay callback return 409 instead of recovering. Keep a read-only legacy decoder and add an upgrade replay regression; do not write new legacy entries.
  • Resolve merge risk (P1) - A projection stored in the legacy representation current main accepts will be rejected during replay, returning 409 and preventing lifecycle recovery for that record.
  • Resolve merge risk (P1) - The supplied loopback trace does not satisfy the repository’s required Docker-backed Crabbox proof for queue/runtime changes.
  • Complete next step (P2) - Restore compatibility for legacy terminal-operation ledgers, then provide Docker-backed Crabbox proof for the repaired exact head or obtain Martin’s express exception.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] Retain readable legacy terminal-operation ledgers — dashboard/exact-review-lifecycle.ts:1944-1945
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production versus test delta production +98/-80; tests +238/-87 A small net production change modifies durable lifecycle-row decoding and is accompanied by substantial replay coverage.

Merge-risk options

Maintainer options:

  1. Restore legacy ledger decoding (recommended)
    Preserve current-main decoding for legacy string and null-kind ledger entries without creating new legacy entries, then add an upgrade replay regression.
  2. Pause for a supported migration
    Keep the PR as a draft if maintainers instead want to retire the representation through an explicit migration and verified deployment plan.

Technical review

Best possible solution:

Retain a read-only compatibility decoder for legacy terminal-operation ledger entries, never write that form again, add an upgrade replay regression, and validate the repaired exact head in Docker-backed Crabbox.

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

Yes, source-reproducible: replay a persisted lifecycle row whose terminal-operation ledger uses the string or null-kind representation that current main decodes; this branch rejects that row before callback recovery.

Is this the best way to solve the issue?

No. Durable rows accepted by current main need a read compatibility path; stricter validation can apply to new writes after legacy values have been decoded.

Full review comments:

  • [P1] Retain readable legacy terminal-operation ledgers — dashboard/exact-review-lifecycle.ts:1944-1945
    Current main converts persisted string IDs to { operationId, kind: null }, but this validator rejects both forms. A previously readable lifecycle row will then make its replay callback return 409 instead of recovering. Keep a read-only legacy decoder and add an upgrade replay regression; do not write new legacy entries.
    Confidence: 0.93

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 674841bcdc0a.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: The introduced decoder rejects a durable terminal-operation representation that current main accepts.
  • add merge-risk: 🚨 availability: Affected lifecycle callback replays would return 409 instead of recovering their queue state.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: The defect is a bounded but merge-blocking lifecycle recovery compatibility regression for persisted rows.
  • merge-risk: 🚨 compatibility: The introduced decoder rejects a durable terminal-operation representation that current main accepts.
  • merge-risk: 🚨 availability: Affected lifecycle callback replays would return 409 instead of recovering their queue state.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Martin Cleary: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Restore current-main compatibility for legacy terminal-operation ledgers and add an upgrade replay test.
  • Run the repaired exact head in Docker-backed Crabbox local-container, or obtain Martin’s express evidence-in-progress exception.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-03T13:34:38.902Z sha ba3822b :: blocked before merge. :: none

@vincentkoc

Copy link
Copy Markdown
Member Author

Maintainer disposition for the remaining rank-up move: Docker-backed Crabbox proof is deferred because Docker is unavailable on this host and both recorded AWS attempts failed before repository execution (Actions hydration incompatibility, then broker DNS/EOF). This is an optional rank-up, not a code finding; the exact-head review found no actionable defect and states real-behavior proof is not required for this maintainer-authored PR. The PR body retains the redacted Wrangler Worker + SQLite HTTP proof and the precise proof limits.

@vincentkoc
vincentkoc marked this pull request as ready for review September 3, 2026 13:40
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 3, 2026
@vincentkoc
vincentkoc merged commit 69ec53b into main Sep 3, 2026
28 of 29 checks passed
@vincentkoc
vincentkoc deleted the fix/worker-replay-idempotency branch September 3, 2026 13:41
@vincentkoc

Copy link
Copy Markdown
Member Author

Late compatibility finding resolved by deployment/source provenance: pre-f7c9afb15584b1837893877fdb3eca64f321b8bd rows had no terminalOperationIds field and load as []; deployed f7c9afb only wrote concrete { operationId, kind } entries. Dashboard deploy history contains f7c9afb (run 33712345842) and this PR's merge 69ec53b00f118593cf878d21d2975c8a52a84e3c (run 33762545402), not intermediate ce24cc9/29f171d3 heads. No deployed string/null ledger needs compatibility, so strict concrete-kind conflict detection remains correct; follow-up #1376 is closed unmerged.

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

Labels

merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant