Skip to content

refactor: move delivery queues to SQLite - #88665

Merged
steipete merged 6 commits into
mainfrom
refactor/sqlite-delivery-queues
May 31, 2026
Merged

steipete merged 6 commits into
mainfrom
refactor/sqlite-delivery-queues

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Summary

  • Move outbound and session delivery queues from JSON sidecar files into the shared OpenClaw SQLite state table.
  • Add doctor migration for legacy queue JSON, removing fully migrated queue dirs and leaving only malformed/conflicting sources in place.
  • Scrub transient delivery queue rows from SQLite backup snapshots and preserve failed queue rows from stale acks.

Real behavior proof

Behavior addressed: Delivery queue state now persists in SQLite instead of random JSON queue files, with doctor migration for old queue files and backup scrubbing for transient pending rows.
Real environment tested: Local OpenClaw checkout on macOS, Node/pnpm repo wrappers.
Exact steps or command run after this patch: pnpm test src/infra/state-migrations.test.ts src/infra/outbound/delivery-queue.storage.test.ts src/infra/backup-create.test.ts src/infra/session-delivery-queue.storage.test.ts src/infra/outbound/delivery-queue.recovery.test.ts src/infra/outbound/delivery-queue.reconnect-drain.test.ts extensions/telegram/src/action-runtime.test.ts; git diff --check; pnpm exec oxlint src/infra/delivery-queue-sqlite.ts src/infra/state-migrations.ts src/infra/outbound/delivery-queue.storage.test.ts src/infra/backup-create.ts src/infra/backup-create.test.ts src/infra/state-migrations.test.ts src/infra/outbound/delivery-queue-storage.ts src/infra/session-delivery-queue-storage.ts src/infra/session-delivery-queue.storage.test.ts src/infra/outbound/delivery-queue.recovery.test.ts src/infra/outbound/delivery-queue.reconnect-drain.test.ts extensions/telegram/src/action-runtime.test.ts; node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo && node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core-test.tsbuildinfo && node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.extensions.test.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/extensions-test.tsbuildinfo; .agents/skills/autoreview/scripts/autoreview --mode local.
Evidence after fix: Focused tests passed 3 Vitest shards: unit-fast 12 tests, infra 75 tests, Telegram 78 tests. Targeted oxlint, diff whitespace, and all three tsgo lanes passed. Final autoreview reported no accepted/actionable findings.
Observed result after fix: Runtime queue operations use delivery_queue_entries; legacy queue files import through doctor; fully migrated source dirs are removed; conflicting/malformed sources remain for manual cleanup; backup archives include a scrubbed SQLite snapshot without delivery queue rows.
What was not tested: Full pnpm check:changed did not finish green because core lint reported an unrelated pre-existing issue in src/agents/openai-transport-stream.ts:3527; touched-file lint and type/test proof passed after that.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels May 31, 2026
@clawsweeper

clawsweeper Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed May 31, 2026, 12:24 PM ET / 16:24 UTC.

Summary
The PR moves outbound and session delivery queue persistence from JSON sidecar files to shared SQLite state, with doctor migration and backup scrubbing changes.

PR surface: Source +556, Tests +80, Other +1. Total +637 across 22 files.

Reproducibility: yes. by source inspection: run the legacy queue migration once with a failed JSON entry plus a malformed sibling so the directory remains, then run it again after the row already exists. The second run rebuilds failed_at with a new Date.now() and compares that column as a conflict.

Review metrics: 2 noteworthy metrics.

  • Legacy queue migration: 2 legacy queue dirs -> 1 SQLite table. Both outbound and session queue upgrade paths now depend on one doctor migration into delivery_queue_entries.
  • Backup scrub path: 1 SQLite snapshot scrubber added. Backups now rewrite a SQLite snapshot to remove queue rows instead of relying only on file-path volatile filters.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦐 gold shrimp
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Fix the failed-row idempotence bug and add a rerun-with-leftover-source regression test.
  • Rebase and resolve the current merge conflicts against main.
  • Attach redacted terminal/live output from an actual doctor, backup, or runtime queue scenario.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body lists focused tests, lint, typecheck, and autoreview output, but it still needs redacted terminal/live output from an actual doctor migration, backup creation, or runtime queue scenario; after updating the PR body, ClawSweeper should re-review automatically or a maintainer can comment @clawsweeper re-review.

Risk before merge

  • [P1] Merging this storage migration changes how existing installs preserve durable outbound and session delivery queue state during upgrade.
  • [P1] The PR body still provides focused tests, lint, typecheck, and autoreview summaries, not redacted terminal/live output from an actual doctor, backup, or runtime queue scenario.
  • [P1] The branch is currently dirty against main, with merge-tree conflicts in agent shell snapshot tests and the unused-file allowlist.

Maintainer options:

  1. Fix idempotence, then prove upgrade (recommended)
    Use a stable failed-row timestamp or ignore failed_at in legacy-row comparison, add a rerun-with-leftover-source test, and attach real upgrade proof before merge.
  2. Require explicit live proof
    A maintainer can require redacted terminal or live-output proof from actual openclaw doctor --fix, backup creation, or runtime queue recovery before accepting the migration risk.
  3. Pause the branch
    If the migration is not urgent, pause or close until conflicts and unrelated test churn are removed from a narrower replacement branch.

Next step before merge

  • [P1] Needs human/contributor handling because real behavior proof is missing, the branch has merge conflicts, and the compatibility-sensitive migration still has a code defect.

Security
Cleared: No concrete security or supply-chain regression was found; the diff does not add third-party code, dependency changes, workflow permissions, or secret-handling changes.

Review findings

  • [P2] Keep failed delivery migration idempotent — src/infra/state-migrations.ts:919
Review details

Best possible solution:

Land the SQLite queue migration only after failed-row migration is idempotent, the branch rebases cleanly, and redacted real doctor/backup/runtime proof is attached.

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

Yes, by source inspection: run the legacy queue migration once with a failed JSON entry plus a malformed sibling so the directory remains, then run it again after the row already exists. The second run rebuilds failed_at with a new Date.now() and compares that column as a conflict.

Is this the best way to solve the issue?

No, not yet. SQLite is the right destination for this state, but the PR should first make failed-entry migration idempotent, rebase cleanly, and provide real upgrade/runtime proof.

Full review comments:

  • [P2] Keep failed delivery migration idempotent — src/infra/state-migrations.ts:919
    When a failed legacy entry is imported but malformed or conflicting siblings leave the source directory behind, the next doctor run rebuilds that same row with a new failed_at timestamp. Because legacyDeliveryQueueRowsMatch compares failed_at, the already-imported row is reported as a conflict and the legacy queue can remain stuck; use a stable timestamp or exclude failed_at from the idempotence check.
    Confidence: 0.89

Overall correctness: patch is incorrect
Overall confidence: 0.86

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 5b310a7b27fa.

Label changes

Label justifications:

  • P1: The PR changes durable message-delivery storage and upgrade behavior for existing installs, so review urgency is higher than ordinary cleanup.
  • merge-risk: 🚨 compatibility: Removing steady-state JSON queues makes existing installs depend on a correct doctor migration and clean upgrade path.
  • merge-risk: 🚨 message-delivery: Outbound and session delivery recovery use these queues, so migration or storage mistakes can affect message retry and delivery behavior.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body lists focused tests, lint, typecheck, and autoreview output, but it still needs redacted terminal/live output from an actual doctor migration, backup creation, or runtime queue scenario; after updating the PR body, ClawSweeper should re-review automatically or a maintainer can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +556, Tests +80, Other +1. Total +637 across 22 files.

View PR surface stats
Area Files Added Removed Net
Source 10 775 219 +556
Tests 11 444 364 +80
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 22 1220 583 +637

What I checked:

  • Failed legacy rows use a fresh run timestamp: The PR builds migrated failed queue rows with failed_at set to the current migration run time, so the same source row can produce a different SQLite row on a later doctor run. (src/infra/state-migrations.ts:919, ef0182d07521)
  • Idempotence comparison includes failed_at: legacyDeliveryQueueRowsMatch compares failed_at, which makes an already-imported failed row look conflicting if the legacy source directory remains for a later run. (src/infra/state-migrations.ts:941, ef0182d07521)
  • Migration coverage misses rerun-with-leftovers case: The added migration test covers clean import of pending and failed JSON files, but it does not cover rerunning doctor after malformed or conflicting sources leave the legacy directory in place. (src/infra/state-migrations.test.ts:284, ef0182d07521)
  • Current main has durable failed queue state: Current main stores outbound and session failed deliveries in failed/ queue locations, so preserving failed-row upgrade semantics is part of the compatibility surface this PR must migrate safely. (src/infra/outbound/delivery-queue-storage.ts:256, 5b310a7b27fa)
  • Current head is dirty against main: A read-only merge-tree check against current main reports conflicts in agent shell snapshot tests and the unused-file allowlist, matching GitHub's dirty mergeability state. (5b310a7b27fa)
  • Repository policy makes this compatibility-sensitive: Root AGENTS.md says persistent runtime state belongs in SQLite and legacy stores should migrate through doctor, but also treats state migrations, fallback removal, and message delivery paths as compatibility-sensitive before merge. (AGENTS.md:68, 5b310a7b27fa)

Likely related people:

  • steipete: Recent main history shows Peter Steinberger carrying the delivery-queue storage split, state-migration surface, backup creation code, and SQLite schema import that this PR builds on. (role: recent area contributor; confidence: high; commits: 562e4a1791fb, e93216080aa1, d1bec469af22; files: src/infra/outbound/delivery-queue-storage.ts, src/infra/session-delivery-queue-storage.ts, src/infra/state-migrations.ts)
  • nabbilkhan: The outbound delivery crash-recovery queue behavior appears to date to the merged crash-recovery commit that added the original durable delivery queue path. (role: introduced behavior; confidence: medium; commits: 207e2c5affa9; files: src/infra/outbound/delivery-queue.ts, src/infra/outbound/deliver.ts)
  • vincentkoc: Recent migration and type-boundary work touched the same migration/storage surfaces, including legacy migration cold paths. (role: adjacent owner; confidence: medium; commits: 97ee0c6fd339, 74e7b8d47b18; files: src/infra/state-migrations.ts, src/infra/backup-create.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00074dbdb7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const warnings: string[] = [];
for (const queue of LEGACY_DELIVERY_QUEUE_DIRS) {
const queueDir = resolveLegacyDeliveryQueuePath(params.stateDir, queue.dirName);
const files = listLegacyDeliveryQueueFiles(queueDir);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Import legacy failed delivery entries

For legacy installs that already have delivery-queue/failed/*.json or session-delivery-queue/failed/*.json, this scan only imports root-level pending *.json files, and the later rm -r of the queue directory deletes the failed/ subdirectory whenever any pending file was imported. The new SQLite storage still preserves failed entries via status = 'failed', so this migration loses/orphans existing permanent-failure records instead of moving them into delivery_queue_entries.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels May 31, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 31422aed09

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/infra/state-migrations.ts Outdated
entry_json: JSON.stringify({ ...params.entry, id: params.id, enqueuedAt, retryCount }),
enqueued_at: enqueuedAt,
updated_at: params.now,
failed_at: params.status === "failed" ? params.now : null,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make failed-queue migration idempotent

When a legacy failed entry is imported but the source directory is left behind (for example because another JSON file was malformed or rmSync failed), this stores failed_at using the current run's timestamp. The next doctor --fix rebuilds the same failed row with a different failed_at, and legacyDeliveryQueueRowsMatch compares that column, so the already-imported row is reported as a conflict and the legacy queue remains stuck even after the operator fixes the malformed file. Use a stable timestamp for legacy failed rows or exclude failed_at from the idempotence comparison.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the refactor/sqlite-delivery-queues branch from 31422ae to fa58942 Compare May 31, 2026 16:11
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label May 31, 2026
@steipete
steipete force-pushed the refactor/sqlite-delivery-queues branch from fa58942 to ef0182d Compare May 31, 2026 16:16

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ef0182d075

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +125 to +127
.onConflict((conflict) =>
conflict.columns(["queue_name", "id"]).doUpdateSet({
status: (eb) => eb.ref("excluded.status"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve failed rows when re-enqueueing idempotent deliveries

When a session delivery with an idempotencyKey has already been moved to status = 'failed', enqueueSessionDelivery does not see it because loadDeliveryQueueEntry only returns pending rows; the insert then hits the (queue_name, id) primary key and this conflict handler rewrites the failed row back to pending with retryCount: 0 and failed_at: null. That loses the permanent-failure record the new table is meant to retain, and differs from the previous JSON layout where a new pending file could coexist with the old failed/ entry for the same idempotency key.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the refactor/sqlite-delivery-queues branch from af361cd to 756de07 Compare May 31, 2026 16:38

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 756de077d9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

return JSON.parse(
fs.readFileSync(path.join(tmpDir, "delivery-queue", `${id}.json`), "utf-8"),
) as Record<string, unknown>;
const { db } = openOpenClawStateDatabase({ env: { ...process.env, OPENCLAW_STATE_DIR: tmpDir } });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Close cached SQLite handles before removing temp dirs

These helpers now open cached openOpenClawStateDatabase connections under each per-test tmpDir, but the suite cleanup still removes the fixture root without closing the cache. On Windows (and any runner that rejects deleting open SQLite files), the afterAll rmSync/withTempDir cleanup for delivery-queue tests can fail or leak temp state because the database handle remains open; add a test cleanup path such as closeOpenClawStateDatabaseForTest() before deleting these temp directories.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 1af4c03 into main May 31, 2026
150 checks passed
@steipete
steipete deleted the refactor/sqlite-delivery-queues branch May 31, 2026 16:43
scribe-dandelion-cult pushed a commit to karmaterminal/openclaw that referenced this pull request May 31, 2026
… queue

Three integration/unit test files were reading the legacy JSON-file
queue directory (/session-delivery-queue/*.json) to verify
durable-queue persistence behavior. Upstream's SQLite-substrate
extraction (commit 1af4c03 openclaw#88665) moved that storage into the
delivery_queue_entries table; the JSON dir no longer exists at runtime.

Tests cured:
- src/auto-reply/continuation/cross-session-targeting.test.ts (3 sites)
  - 'persists the durable queue file for non-attached recipients'
  - 'acks the durable queue file after the live in-memory return is consumed'
  - 'persists one durable queue file per recipient on multi-target fanout'
- src/auto-reply/continuation/cross-session-targeting.nonexistent-target.test.ts (1 site)
  - 'persists the durable queue file for nonexistent target (real)'
- src/agents/subagent-announce.targeted-return.integration.test.ts (helper + 1 direct site)
  - readQueuedSystemEventDeliveries helper rewritten
  - 'writes queue file, logs targeted-return, and drains the recipient System context'

Pattern: replace
  const queueDir = path.join(stateDir, 'session-delivery-queue');
  const entries = await fs.readdir(queueDir);
  const jsonFiles = entries.filter((e) => e.endsWith('.json'));
  JSON.parse(await fs.readFile(path.join(queueDir, file), 'utf-8'))
with the substrate-agnostic API call:
  const persisted = await loadPendingSessionDeliveries(stateDir);

The QueuedSessionDelivery[] return shape is identical to what the JSON
read produced (storage layer maintains the same payload contract), so
downstream .kind/.sessionKey/.idempotencyKey/.text assertions still hold.

The 'deliveredMarkers' (.delivered files) check is dropped — that was
a JSON-substrate-specific artifact verifying ack-then-rename didn't fire
(per #578/#580); the SQLite substrate has no rename-on-ack semantic, so
the assertion is moot. Behavioral guarantee (queue entry persists
until recovery loop drains) is now verified via the loadPending count
(would be 0 if entry was acked/removed).

Test results at byte (emeric-host worktree):
- cross-session-targeting.test.ts: 18/18 PASS (was 15/18)
- cross-session-targeting.nonexistent-target.test.ts: 26/26 PASS (was 25/26)
- subagent-announce.targeted-return.integration.test.ts: 3/3 PASS (was 0/1)

Net: 11 tests cured from ENOENT-class regression; -64 lines (test cleanup
since loadPendingSessionDeliveries returns parsed entries directly).

Co-authored-by: cael🩸 <[email protected]>
Co-authored-by: silas🌫 <[email protected]>
Co-authored-by: emeric-dandelion-cult <[email protected]>
Co-authored-by: Copilot <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jun 1, 2026
* refactor: move delivery queues to sqlite

* fix: satisfy delivery queue sqlite boundaries

* test: remove stale reasoning replay assertion

* fix: migrate failed delivery queue entries

* test: stabilize exec shell snapshot mocks

* fix: clean legacy delivery queue markers
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
* refactor: move delivery queues to sqlite

* fix: satisfy delivery queue sqlite boundaries

* test: remove stale reasoning replay assertion

* fix: migrate failed delivery queue entries

* test: stabilize exec shell snapshot mocks

* fix: clean legacy delivery queue markers
Feelw00 added a commit to Feelw00/openclaw that referenced this pull request Jun 19, 2026
…its turn has run

The session-delivery recovery path drainQueuedEntry
(src/infra/session-delivery-queue-recovery.ts) delivers an entry then acks it
(at-least-once). If the agent turn re-runs (dispatchAssembledChannelTurn, which can
send via the message tool) but the process dies before ack, the entry stays pending
and the next recovery blind-replays it: the same turn runs twice (non-idempotent
LLM/tool side effects) and its reply is sent twice.

openclaw#88665 moved both delivery queues onto a shared SQLite backing with a recovery_state
column; the parallel outbound queue uses it to refuse a blind replay without adapter
reconciliation, but the session-delivery drain neither set nor read it.

Wire recovery_state into the session drain at the turn-execution boundary so the
refuse decision is precise:
- The deliver seam (server-restart-sentinel.ts) reports onSendAttemptStart right
  before the agent turn runs, and onSendDeferred if that attempt was merely deferred
  because the session was busy (the busy turn produces a busy-retry response, no
  durable work). The no-op deliver paths (systemEvent / changed-session / no-route)
  never run the turn and report neither.
- drainQueuedEntry persists the send marker on onSendAttemptStart (and clears it on
  onSendDeferred). A recovered entry still carrying the marker is refused (fail-safe
  moveToFailed). On a thrown deliver, a turn that began running (sendAttempted) is
  refused even if it threw after sending, while a pre-send / busy-deferred / no-op
  failure stays retryable (at-least-once preserved for genuine pre-send failures).

This matches the outbound queue's no-reconcile contract and addresses the
sent-before-error case (a turn that sends then throws is no longer cleared and
replayed). Tradeoff: a crash in the narrow window after the turn starts but before
ack moves the entry to failed/ rather than replaying it (fail-safe over at-least-once),
the same product choice the outbound queue makes without a reconcile capability.

Adds regression tests: crash-before-ack, recovered-marker refuse, sent-before-error
throw refuse, and pre-send failure stays retryable.

AI-assisted: drafted with claude code (claude-opus-4-8).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: telegram Channel integration: telegram commands Command implementations maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant