Repository navigation
refactor: move delivery queues to SQLite - #88665
Conversation
|
Codex review: needs real behavior proof before merge. Reviewed May 31, 2026, 12:24 PM ET / 16:24 UTC. Summary 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 Review metrics: 2 noteworthy metrics.
Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Proof guidance:
Risk before merge
Maintainer options:
Next step before merge
Security Review findings
Review detailsBest 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 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model gpt-5.5, reasoning high; reviewed against 5b310a7b27fa. Label changesLabel justifications:
Evidence reviewedPR surface: Source +556, Tests +80, Other +1. Total +637 across 22 files. View PR surface stats
What I checked:
Likely related people:
What the crustacean ranks mean
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
|
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| 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, |
There was a problem hiding this comment.
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 👍 / 👎.
31422ae to
fa58942
Compare
fa58942 to
ef0182d
Compare
There was a problem hiding this comment.
💡 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".
| .onConflict((conflict) => | ||
| conflict.columns(["queue_name", "id"]).doUpdateSet({ | ||
| status: (eb) => eb.ref("excluded.status"), |
There was a problem hiding this comment.
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 👍 / 👎.
af361cd to
756de07
Compare
There was a problem hiding this comment.
💡 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 } }); |
There was a problem hiding this comment.
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 👍 / 👎.
… 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]>
* 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
* 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
…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]>
Summary
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:changeddid not finish green because core lint reported an unrelated pre-existing issue insrc/agents/openai-transport-stream.ts:3527; touched-file lint and type/test proof passed after that.