Skip to content

fix(delivery-queue): skip stale first-attempt entries during startup recovery - #54900

Closed
Drickon wants to merge 1 commit into
openclaw:mainfrom
Drickon:pr/delivery-queue-stale-ttl
Closed

Drickon wants to merge 1 commit into
openclaw:mainfrom
Drickon:pr/delivery-queue-stale-ttl

Conversation

@Drickon

@Drickon Drickon commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Problem

When the gateway restarts, the delivery queue replays pending entries from previous runs. This is the correct behavior for messages that genuinely failed to send (network errors, provider downtime, etc.).

However, messages that were enqueued but not yet sent when the gateway stopped — due to an intentional restart or graceful shutdown — are also replayed. These entries have retryCount === 0 and no lastAttemptAt, making them indistinguishable from crash survivors. The result: stale, out-of-context messages delivered to users long after the conversation that generated them.

Example: A user session generates 5 outbound messages. The gateway restarts before they're sent. On startup, recovery replays all 5 — delivering content from the previous session into the current one.

Solution

Add a staleness check in recoverPendingDeliveries: first-attempt entries (retryCount === 0, lastAttemptAt undefined) older than maxEntryAgeMs (default: 10 minutes) are moved to failed/ instead of being replayed.

Entries with retryCount > 0 are unaffected — they are legitimate retry candidates regardless of age (a message that failed to send should keep retrying).

The check can be disabled by passing maxEntryAgeMs: 0 to recoverPendingDeliveries.

Changes

  • delivery-queue-recovery.ts: add DEFAULT_MAX_ENTRY_AGE_MS, skippedStale field to RecoverySummary, maxEntryAgeMs opt to recoverPendingDeliveries, staleness check in recovery loop
  • delivery-queue.recovery.test.ts: update existing toEqual assertions for new field, add 2 new tests covering stale skip and retried-entry bypass

Tests

All 13 tests pass (pnpm exec vitest run src/infra/outbound/delivery-queue.recovery.test.ts).

@greptile-apps

greptile-apps Bot commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a staleness guard to recoverPendingDeliveries that moves first-attempt entries (retryCount === 0, no lastAttemptAt) older than maxEntryAgeMs (default 10 minutes) to failed/ instead of replaying them on startup. This correctly prevents messages queued in a prior session from being delivered out-of-context after a gateway restart, while leaving legitimate retry candidates (retryCount > 0) completely unaffected.\n\nKey changes:\n- DEFAULT_MAX_ENTRY_AGE_MS constant (10 minutes) added with clear JSDoc explaining the intent and the opt-out mechanism (maxEntryAgeMs: 0).\n- Staleness check is correctly ordered: after the MAX_RETRIES guard and before the backoff-eligibility check.\n- skippedStale added to RecoverySummary and surfaced in the completion log line.\n- Two new tests cover both sides of the feature; all existing test assertions updated for the new field.\n\nOne minor style note: maxEntryAgeMs is re-derived from opts inside the loop on every iteration rather than once before the loop (see inline comment).

Confidence Score: 5/5

Safe to merge — the feature is well-scoped, logic is correct, and tests cover both new paths and existing regression scenarios.

The staleness check is logically sound and properly positioned in the recovery loop. No existing behavior is broken: entries enqueued within the same session are well within the 10-minute window, and retried entries bypass the check entirely. The only finding is a trivial style issue (loop-invariant constant resolved inside the loop), which does not affect correctness.

No files require special attention.

Important Files Changed

Filename Overview
src/infra/outbound/delivery-queue-recovery.ts Adds staleness check for first-attempt entries during startup recovery. Logic is correct and properly ordered. One minor style issue: maxEntryAgeMs is resolved on every loop iteration rather than once before the loop.
src/infra/outbound/delivery-queue.recovery.test.ts Existing assertions updated for the new skippedStale field; two new tests added covering the stale-skip path and the retried-entry bypass. Both tests are correct and exercise the right conditions.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/infra/outbound/delivery-queue-recovery.ts
Line: 215-216

Comment:
**Constant resolved inside the loop on every iteration**

`maxEntryAgeMs` is derived purely from `opts.maxEntryAgeMs` and never changes between iterations, so it doesn't need to be recomputed in each pass of the loop. Hoist it above the loop alongside `deadline` and `summary`.

```suggestion
  const maxEntryAgeMs =
    opts.maxEntryAgeMs !== undefined ? opts.maxEntryAgeMs : DEFAULT_MAX_ENTRY_AGE_MS;

  for (let i = 0; i < pending.length; i++) {
```

Then remove the two lines inside the loop body.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(delivery-queue): skip stale first-at..." | Re-trigger Greptile

Comment on lines +215 to +216
const maxEntryAgeMs =
opts.maxEntryAgeMs !== undefined ? opts.maxEntryAgeMs : DEFAULT_MAX_ENTRY_AGE_MS;

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 Constant resolved inside the loop on every iteration

maxEntryAgeMs is derived purely from opts.maxEntryAgeMs and never changes between iterations, so it doesn't need to be recomputed in each pass of the loop. Hoist it above the loop alongside deadline and summary.

Suggested change
const maxEntryAgeMs =
opts.maxEntryAgeMs !== undefined ? opts.maxEntryAgeMs : DEFAULT_MAX_ENTRY_AGE_MS;
const maxEntryAgeMs =
opts.maxEntryAgeMs !== undefined ? opts.maxEntryAgeMs : DEFAULT_MAX_ENTRY_AGE_MS;
for (let i = 0; i < pending.length; i++) {

Then remove the two lines inside the loop body.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/outbound/delivery-queue-recovery.ts
Line: 215-216

Comment:
**Constant resolved inside the loop on every iteration**

`maxEntryAgeMs` is derived purely from `opts.maxEntryAgeMs` and never changes between iterations, so it doesn't need to be recomputed in each pass of the loop. Hoist it above the loop alongside `deadline` and `summary`.

```suggestion
  const maxEntryAgeMs =
    opts.maxEntryAgeMs !== undefined ? opts.maxEntryAgeMs : DEFAULT_MAX_ENTRY_AGE_MS;

  for (let i = 0; i < pending.length; i++) {
```

Then remove the two lines inside the loop body.

How can I resolve this? If you propose a fix, please make it concise.

@Drickon

Drickon commented Apr 4, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main, CI is green. Happy to address any feedback when you get a chance.

…recovery

When the gateway restarts, the delivery queue replays any pending entries
from previous runs. This is the intended crash-recovery behavior for messages
that genuinely failed to send (network error, provider down, etc.).

However, messages enqueued during an active session but not yet sent when the
gateway stops — due to an intentional restart or graceful shutdown — are also
replayed. These entries have retryCount=0 and no lastAttemptAt, making them
indistinguishable from crash survivors. The result is stale, out-of-context
messages delivered to users long after the conversation that generated them.

This change adds a staleness check: first-attempt entries (retryCount === 0,
lastAttemptAt undefined) older than maxEntryAgeMs (default: 10 minutes) are
moved to failed/ instead of being replayed. Entries with retryCount > 0 are
unaffected — they are legitimate retry candidates regardless of age.

The check can be disabled by passing maxEntryAgeMs: 0 to recoverPendingDeliveries.
@Drickon
Drickon force-pushed the pr/delivery-queue-stale-ttl branch from b74caf3 to f7c8699 Compare April 4, 2026 20:06

@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: f7c8699eb6

ℹ️ 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 +218 to +219
const isFirstAttempt = entry.retryCount === 0 && entry.lastAttemptAt === undefined;
if (maxEntryAgeMs > 0 && isFirstAttempt && now - entry.enqueuedAt > maxEntryAgeMs) {

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 Keep stale filtering for budget-deferred first attempts

This stale gate only runs when retryCount === 0, but entries skipped by the recovery time budget are marked via failDelivery(...) in deferRemainingEntriesForBudget, which increments retryCount even though no delivery attempt happened. In a large backlog where maxRecoveryMs is hit, old never-attempted entries will be converted to retryCount > 0, bypass this new stale check on the next startup, and can still be replayed out of context. Consider tracking "attempted" separately (or preserving first-attempt status for budget deferrals) so stale protection still applies after budget rollover.

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close this PR as superseded: the stale replay problem is real, but the remaining TTL/default/expire-action decision is already tracked in the open canonical issue, and this branch is conflicting, proof-missing, and stale against current recovery safeguards.

Canonical path: Close this stale branch and keep the TTL/default/expire-action decision in #16555, then use a fresh current-main PR once maintainers choose the compatibility policy.

So I’m closing this here and keeping the remaining discussion on #16555.

Review details

Best possible solution:

Close this stale branch and keep the TTL/default/expire-action decision in #16555, then use a fresh current-main PR once maintainers choose the compatibility policy.

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

Yes, at source level: current main persists enqueuedAt and replays eligible pending entries at startup with no age check. This read-only review did not run a live gateway/channel restart reproduction.

Is this the best way to solve the issue?

No. The PR is a plausible mitigation, but not the best current solution because the canonical issue still owns the TTL/default/expire-action policy and this branch is stale against current recovery safeguards.

Security review:

Security review cleared: The diff touches delivery queue runtime and tests only and introduces no dependency, workflow, secret, package, or supply-chain changes.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • nabbilkhan: Commit 207e2c5 introduced the outbound delivery crash-recovery queue and startup replay behavior this expiry work extends. (role: introduced behavior; confidence: high; commits: 207e2c5affa9; files: src/infra/outbound/delivery-queue.ts, src/infra/outbound/deliver.ts, src/gateway/server.impl.ts)
  • steipete: Commit 562e4a1 split delivery queue storage/recovery, and the canonical TTL issue includes maintainer-facing direction on the unresolved expiry policy. (role: area refactor and product-direction contributor; confidence: high; commits: 562e4a1791fb; files: src/infra/outbound/delivery-queue-recovery.ts, src/infra/outbound/delivery-queue-storage.ts, src/infra/outbound/delivery-queue.ts)
  • Yzx: Commit 75c1790 changed budget-deferred outbound recovery behavior in the same recovery/test files this stale branch predates. (role: adjacent recovery contributor; confidence: medium; commits: 75c1790b504c; files: src/infra/outbound/delivery-queue-recovery.ts, src/infra/outbound/delivery-queue.recovery.test.ts)
  • mcaxtr: Commit 95d4673 added reconnect pending-delivery drain behavior and tests that any final expiry policy needs to preserve consistently. (role: adjacent reconnect-drain contributor; confidence: medium; commits: 95d467398e46; files: src/infra/outbound/delivery-queue-recovery.ts, src/infra/outbound/delivery-queue-storage.ts, src/infra/outbound/delivery-queue.reconnect-drain.test.ts)

Codex review notes: model internal, reasoning high; reviewed against 4644e0c10256.

@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. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P2 Normal backlog priority with limited blast radius. 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 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 19, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 9, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed 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. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. labels Jun 9, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 10, 2026
@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. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 14, 2026
@clawsweeper clawsweeper Bot added the mantis: telegram-visible-proof Mantis should capture Telegram visible proof. label Jun 14, 2026
@clawsweeper

clawsweeper Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Jun 14, 2026

This branch had an error being deployed

1 failed deployment
qa-live-shared — f7c8699e Deployed Jun 14, 2026 by clawsweeper[bot] via Run agentic native Telegram proof #165652
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mantis: telegram-visible-proof Mantis should capture Telegram visible proof. 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. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant