Skip to content

fix: skip stale responses in interrupt queue mode via generationId - #19452

Closed
kisjovan wants to merge 3 commits into
openclaw:mainfrom
kisjovan:fix/interrupt-queue-duplicate-response-19426
Closed

kisjovan wants to merge 3 commits into
openclaw:mainfrom
kisjovan:fix/interrupt-queue-duplicate-response-19426

Conversation

@kisjovan

@kisjovan kisjovan commented Feb 17, 2026 •

Copy link
Copy Markdown

Problem

In interrupt queue mode, when a second message arrives while the first response is being generated/sent, the first response still gets delivered before the second (correct) response. This happens because the abort arrives too late — the response is already in the outbound pipeline.

Solution

Implements a generationId approach as discussed in #19426:

  1. queue/state.ts — Added per-session generation counter (SESSION_GENERATION_IDS map) with getSessionGenerationId, incrementSessionGenerationId, and isGenerationCurrent helpers.

  2. get-reply-run.ts — On interrupt (when clearing queue and aborting), increment the session's generationId. Capture it and pass to runReplyAgent.

  3. agent-runner.ts — Before delivering the final response, check if the run's generationId still matches the session's latest. If superseded by a newer interrupt, skip sending and log the drop.

Changes

  • 3 files changed, 45 insertions
  • Zero behavioral change for non-interrupt queue modes (generationId defaults to 0 and only increments on interrupt)

Fixes #19426

Greptile Summary

This PR implements a generationId mechanism to suppress stale responses in interrupt queue mode. When a second message arrives while the first response is in the outbound pipeline, the first response is now dropped at the delivery point instead of being sent to the user. The approach — a per-session monotonic counter incremented on each interrupt, captured at run-start, and validated before delivery — is conceptually sound and well-scoped.

Two issues were found:

  • Missing generationId in all existing test call-sites (will break CI): generationId: number was added as a required field on the runReplyAgent params type, but none of the existing tests in agent-runner.runreplyagent.test.ts or agent-runner.misc.runreplyagent.test.ts pass it. This produces TypeScript compilation errors. At JS runtime, the missing field is undefined, and isGenerationCurrent(key, undefined) always returns false, causing the stale-response guard to fire on every test run and drop all replies — breaking every test that checks the returned payload. Making generationId optional (defaulting to 0) or adding generationId: 0 to all existing test call-sites is required.

  • SESSION_GENERATION_IDS is never cleaned up (memory leak): The new module-level map accumulates an entry for every session that ever triggers an interrupt, but clearSessionQueues / clearFollowupQueue (called on abort, session reset, and subagent stop) only clean up FOLLOWUP_QUEUES, not SESSION_GENERATION_IDS. In a long-running gateway serving many sessions, this is an unbounded memory leak. The fix is to delete the map entry when the session's followup queue is cleared.

Confidence Score: 2/5

  • Not safe to merge: the new required generationId parameter breaks all existing test call-sites and will cause TypeScript build failures; the missing cleanup path creates a memory leak in long-running processes.
  • The core logic of the generationId approach is correct, but two concrete defects block merging: (1) generationId is a required param not added to any existing test call-sites, breaking TypeScript compilation and making every omitted-param test assert on a dropped response; (2) SESSION_GENERATION_IDS has no cleanup path, leaking memory per session over time.
  • src/auto-reply/reply/agent-runner.ts (required param breaks all existing tests), src/auto-reply/reply/queue/cleanup.ts (SESSION_GENERATION_IDS never cleaned up), src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts and agent-runner.runreplyagent.test.ts (all call-sites missing generationId)

Last reviewed commit: d5ecfa5

(4/5) You can add custom instructions or style guidelines for the agent here!

When a second message arrives while the first response is being generated,
the abort may come too late (response already in outbound pipeline), causing
duplicate responses.

Fix: assign an incremental generationId per session queue. Each interrupt
increments the counter. Before delivering a response, verify the run's
generationId still matches the session's latest — if not, the response was
superseded and is silently dropped.

Fixes openclaw#19426

@greptile-apps greptile-apps 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.

3 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

@greptile-apps

greptile-apps Bot commented Feb 17, 2026

Copy link
Copy Markdown
Contributor
Additional Comments (2)

src/auto-reply/reply/queue/cleanup.ts
SESSION_GENERATION_IDS never cleaned up

clearSessionQueues (and clearFollowupQueue) clean up FOLLOWUP_QUEUES but leave the corresponding entry in SESSION_GENERATION_IDS alive. Every session that is aborted, reset, or ended leaks an entry into the module-level map indefinitely. For long-running gateway processes with many sessions or repeated abort cycles, this is an unbounded memory leak.

The SESSION_GENERATION_IDS entry should be removed at the same point FOLLOWUP_QUEUES is cleaned up (i.e., inside clearFollowupQueue, or via a companion helper called from clearSessionQueues). A clearSessionGenerationId(key) export from queue/state.ts, called per-key in clearSessionQueues alongside clearFollowupQueue, would close the leak without changing the existing public API surface.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/auto-reply/reply/queue/cleanup.ts
Line: 11:29

Comment:
**`SESSION_GENERATION_IDS` never cleaned up**

`clearSessionQueues` (and `clearFollowupQueue`) clean up `FOLLOWUP_QUEUES` but leave the corresponding entry in `SESSION_GENERATION_IDS` alive. Every session that is aborted, reset, or ended leaks an entry into the module-level map indefinitely. For long-running gateway processes with many sessions or repeated abort cycles, this is an unbounded memory leak.

The `SESSION_GENERATION_IDS` entry should be removed at the same point `FOLLOWUP_QUEUES` is cleaned up (i.e., inside `clearFollowupQueue`, or via a companion helper called from `clearSessionQueues`). A `clearSessionGenerationId(key)` export from `queue/state.ts`, called per-key in `clearSessionQueues` alongside `clearFollowupQueue`, would close the leak without changing the existing public API surface.

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

src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts
Missing required generationId parameter breaks existing tests

generationId: number is now a required field in runReplyAgent's params type. All existing calls to runReplyAgent in this file (and in agent-runner.runreplyagent.test.ts) omit it, so they will fail TypeScript compilation.

More critically, at JS runtime the missing field is undefined, and isGenerationCurrent(queueKey, undefined) evaluates to (SESSION_GENERATION_IDS.get(key) ?? 0) === undefined → false. This means every test that runs without setting generationId will hit the stale-response guard and return undefined instead of the expected reply, breaking all assertions on the returned payload.

The parameter should either be made optional (defaulting to 0, which preserves existing behaviour when no interrupt has occurred), or all existing test call-sites need to pass generationId: 0.

      isActive: false,
      isStreaming: false,
      typing,
      sessionCtx,
      sessionEntry,
      sessionStore: { [sessionKey]: sessionEntry },
      sessionKey,
      storePath: undefined,
      defaultModel: "anthropic/claude-opus-4-5",
      agentCfgContextTokens: 100_000,
      resolvedVerboseLevel: "off",
      isNewSession: false,
      blockStreamingEnabled: false,
      resolvedBlockStreamingBreak: "message_end",
      shouldInjectGroupIntro: false,
      typingMode: "instant",
      generationId: 0,
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts
Line: 158:182

Comment:
**Missing required `generationId` parameter breaks existing tests**

`generationId: number` is now a required field in `runReplyAgent`'s params type. All existing calls to `runReplyAgent` in this file (and in `agent-runner.runreplyagent.test.ts`) omit it, so they will fail TypeScript compilation.

More critically, at JS runtime the missing field is `undefined`, and `isGenerationCurrent(queueKey, undefined)` evaluates to `(SESSION_GENERATION_IDS.get(key) ?? 0) === undefined` → `false`. This means **every test that runs without setting `generationId`** will hit the stale-response guard and return `undefined` instead of the expected reply, breaking all assertions on the returned payload.

The parameter should either be made optional (defaulting to `0`, which preserves existing behaviour when no interrupt has occurred), or all existing test call-sites need to pass `generationId: 0`.

```suggestion
      isActive: false,
      isStreaming: false,
      typing,
      sessionCtx,
      sessionEntry,
      sessionStore: { [sessionKey]: sessionEntry },
      sessionKey,
      storePath: undefined,
      defaultModel: "anthropic/claude-opus-4-5",
      agentCfgContextTokens: 100_000,
      resolvedVerboseLevel: "off",
      isNewSession: false,
      blockStreamingEnabled: false,
      resolvedBlockStreamingBreak: "message_end",
      shouldInjectGroupIntro: false,
      typingMode: "instant",
      generationId: 0,
```

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

- Make generationId optional in runReplyAgent params to avoid breaking
  existing callers that don't pass it
- Export SESSION_GENERATION_IDS map for test access
- Add comprehensive tests for getSessionGenerationId,
  incrementSessionGenerationId, and isGenerationCurrent helpers

Fixes CI on PR openclaw#19452
- Add clearSessionGenerationId() export to state.ts
- Call it from clearSessionQueues() in cleanup.ts alongside
  existing clearFollowupQueue calls
- Add tests for the new helper

Addresses Greptile review: unbounded SESSION_GENERATION_IDS growth
@kisjovan

Copy link
Copy Markdown
Author

Hey team 👋 Both issues from the greptile review have been addressed in follow-up commits:

  1. Memory leak fix → 4fc1b8603 — added clearSessionGenerationId() called from clearSessionQueues/clearFollowupQueue
  2. generationId optional → 308922e80 — made it optional with default 0, added generation state tests

CI is all green. This is a real pain point for anyone using interrupt queue mode — duplicate/stale responses get sent to users after every interrupt. Would love a maintainer review when you get a chance 🙏

@kisjovan

Copy link
Copy Markdown
Author

cc @vincentkoc @obviyus — would appreciate a review if you have a moment!

@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 Mar 17, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #pr-thunderdome-dangerzone on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

amittell added a commit to amittell/openclaw that referenced this pull request Oct 1, 2026
…pe append

Review finding on 9e0cdd2c129: the test built the context with
buildReplyPromptEnvelopeBase, which skips appendCurrentInboundContext.
Real turns with thread notes, system events or channel prompt context go
through buildReplyPromptEnvelope and that append, so a dropped carrierText
there would have reverted the fix unseen. The test now uses the full
envelope with one system event. At 1d5d6c8 the version-3 case fails
with a bare "openclaw#19452:" followed by the appended event; the version-4 pin,
now including the appended fragment, passes before and after.
amittell added a commit to amittell/openclaw that referenced this pull request Oct 11, 2026
…nventory

Run A (all --changed shards at a25baa1) failed 16 tests, all in
fork-pinned areas. Each is TEST-DRIFT: the fork behaviour holds on 10.1
and only the test setup changed upstream. Each fix has a revert control
that fails for the right reason.

- attempt-prompt-context (Telegram current-message carrier, v3/v4):
  openclaw#163471 replaced the BEGIN/END internal-context wrapper with an
  "OpenClaw runtime context:" label applied at model send. The fork's
  carrierText still states the body. Control: without carrierText the v3
  case fails on a bare "openclaw#19452:".
- session-context (runtime carriers at compaction boundaries, 3, an
  upstream test): openclaw#161281 pins the summary exactly, and the fork's
  checkpoint line collides with that. The cut point is unchanged from
  9.9. Controls: no checkpoint line -> 14/21; a cut between the carrier
  and its user -> 19/21.
- pending-inputs.redrive: openclaw#163582 made listSessionPendingInputs async.
  Control: without the fork's terminal block, 10.1 admits a fresh turn
  for a committed source turn ("expected true to be false").
- agent-runner-failure-reply (3) and assistant-failure (1): the 10.1 copy
  from openclaw#163381, under this carry's precedent (the fork keeps its
  classification and takes 10.1's copy). The transport cases now also
  assert "not took too long"; without that, the old negatives passed with
  the fork code removed. assistant-failure asserts the FailoverError
  fields (provider, model) in place of the old text. The 9.9 build did
  not rotate profiles on this path either (probe at 9eea409).
- owner-only-tool-stubs (4) and attempt.owner-only-tool-stubs (2): openclaw#154239
  makes non-owner turns use the real `sessions` tool, limited to
  assign_owner, rather than denying it. Alex, 2026-10-11: take upstream's
  rule. The tests therefore expect every owner-only tool except
  `sessions` to be stubbed. openclaw#164296 makes the tool-surface bridge add the
  Tool Search controls itself, so the attempt test covers Tool Search
  off, on, and Code Mode. Controls: with the fork's stub shaping off,
  5/8; with the refusal line removed, 0/4.

Also adds src/agents/owner-only-tool-stub-marker.ts to
scripts/pr-lib/wrapper-components.txt. tool-policy.ts has imported it since
the 9.9 carry and it was never listed, which failed eager-import-closure.
With the line, eager-import-closure is 18/18 and pr-wrappers 217/217.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size: L stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Interrupt queue mode sends duplicate response when second message arrives during generation

1 participant