Skip to content

fix(pending-input): make committed source-turn replay terminal at admission - #9

Closed
amittell wants to merge 2 commits into
upgrade-v2026.9.4from
fix/pending-input-reinject-dedupe-9.4
Closed

amittell wants to merge 2 commits into
upgrade-v2026.9.4from
fix/pending-input-reinject-dedupe-9.4

Conversation

@amittell

Copy link
Copy Markdown
Owner

What

A re-presentation of an already-executed channel source turn id (after its owning run died without a done signal — model 502 / timeout / gateway restart) is admitted as a fresh agent turn. Observed live: one Telegram DM inbound re-presented ~10x; on rh-bot it re-projected automation/heartbeat notices into the DM all of 2026-09-12.

Root cause

stageSessionPendingInput's committed-transcript-replay branch (the input is found already committed in the transcript) returned state: "queued", so stageApproved (state !== "consumed") was true and the re-drive executed a new model run. The transcript append itself is idempotent (no duplicate message) — only the fresh agent turn is the defect.

Fix (7 lines, one branch)

The committed-replay branch now returns state: "consumed" — terminal at admission. Re-presentation of an already-executed source turn id is suppressed; no new custody minted; no schema migration.

  • Unchanged: the restart-recovery guard (restart-recovery-claim.ts, persistedSourceTurnId !== sourceTurnId throw) — legitimate restart/reconnect re-staging still works.
  • Boundary: a legitimately re-delivered message whose source turn already executed is now suppressed at admission (intended at-most-once behavior; nothing user-visible changes for genuine redelivery since transcript dedupe was already idempotent).

Commits

  1. d79cb299d78 — test: port re-drive suppression test to the 9.4 line (test-first)
  2. b56a6007e8c — fix: committed source-turn replay terminal at admission (9.4)

Test-first proof (on this 9.4 base, release/2026.9.4 @ 3a9d69db)

  • Unfixed 9.4 code: session-accessor.pending-inputs.test.ts → 1 failed | 38 passed; failure at expect(reDrivenStaged).toBe(false) (line 195, AssertionError: expected true to be false) — proves the defect on this line.
  • Fixed: same file → 39/39 passed.
  • Affected suites on the fixed 9.4 line, all green:
    • restart-recovery-receipt.test.ts → 8/8 (restart-recovery guard not regressed)
    • queue.pending-inputs.test.ts → 5/5
    • chat-pending-inputs.test.ts → 2/2
  • Verified independently on the 9.3 lineage as well (HEAD 848076312ed, fix/pending-input-reinject-dedupe-20260912): same test fails on unfixed base, passes fixed; suites pending-inputs 39, session-accessor 129, transcript-store 17, schema 7, persistence 38, restart-recovery-claim 15.

Porting note

Ported from the 9.3-line fix; the pending-inputs file diverged ~150 lines between 9.3 and 9.4, so this was a clean manual port + full re-test on the 9.4 line, not a blind cherry-pick.

Ports the test from the 9.3-line fix (848076312ed): a re-presented,
already-executed channel source turn id must be suppressed at admission
instead of minting a fresh agent turn. Expected to FAIL on unfixed code
(staged.reDrivenStaged stays true); the fix follows in the next commit.
…ission (9.4)

Port of the 9.3-line fix (848076312ed) to release/2026.9.4: the committed
transcript replay branch of stageSessionPendingInput returned state:"queued",
so a re-presentation of an already-executed channel source turn id (after the
owning run died without a done signal: 502 / timeout / restart) was admitted
as a FRESH agent turn. That re-drive loop is what re-delivered one Telegram DM
inbound ~10x and, on this host, re-presented automation notices all day.

The committed-replay branch now returns state:"consumed" - terminal at
admission. Re-presentation of an already-executed source turn id is suppressed
at admission instead of minting a fresh agent turn; the idempotent transcript
append still resolves to the committed message. No new custody is minted; no
schema migration; the restart-recovery guard (restart-recovery-claim.ts,
persistedSourceTurnId !== sourceTurnId) is untouched, so legitimate
restart/reconnect re-staging still works.

Test-first: the ported re-drive suppression test (d79cb29) FAILS on
unfixed 9.4 code at expect(reDrivenStaged).toBe(false) and passes 39/39 with
this fix.

Boundary note: a legitimately re-delivered message whose source turn already
executed is now suppressed at admission (intended at-most-once behavior).
Copilot AI lite review requested due to automatic review settings September 13, 2026 01:49
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T01:56:18.403571Z b56a600 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

The fix is covered by passing regression tests and preserves idempotent transcript handling.

Pull request overview

This PR prevents committed source-turn replays from being admitted as fresh agent turns.

Changes:

  • Marks committed transcript replays as consumed.
  • Adds regression coverage for replay suppression and transcript idempotency.
File summaries
File Description
src/config/sessions/session-accessor.pending-inputs.ts Suppresses committed source-turn replays at admission.
src/config/sessions/session-accessor.pending-inputs.test.ts Verifies replay suppression and no duplicate transcript message.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

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

Copy link
Copy Markdown

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: b56a6007e8

ℹ️ 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".

// idempotent transcript append still resolves to the committed message.
return {
state: "queued",
state: "consumed",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve committed turns for reconnect recovery

When a Control UI turn has persisted its user message and restart claim but the Gateway dies before agent dispatch completes, reconnect reuses the same run ID. chat-send-handler.ts stages at lines 276-286 and treats isPendingInputConsumed() as cached terminal success at lines 287-296, so this new state returns status: "ok" instead of reaching the reconnect dispatch/recovery path. A transcript commit proves persistence, not agent execution—the added test likewise calls only persistApproved()—so the post-persistence crash window now silently loses the reply; terminal status needs to come from the execution/recovery claim rather than transcript presence alone.

AGENTS.md reference: AGENTS.md:L31-L34

Useful? React with 👍 / 👎.

target,
message: sourceMessage,
});
const originalStaged = await original.stageApproved?.({

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Exercise replay through the actual channel entry point

For the reported Telegram/channel redelivery, get-reply-run-execute.ts constructs the recorder and agent-runner-execute.ts:259 sends it through admitUserTurn(), whose restart-recovery controller persists it directly; a repo-wide search shows no production auto-reply caller of stageApproved (only the Control UI and Gateway agent entry points call it). This test manually invokes stageApproved, so it can pass while the ordinary channel path never reaches the changed branch and continues re-executing the duplicate source turn. Apply or verify suppression at the channel/restart-recovery admission owner instead.

AGENTS.md reference: AGENTS.md:L31-L34

Useful? React with 👍 / 👎.

@amittell

Copy link
Copy Markdown
Owner Author

Holding - not merging. Validation found a regression in the single production change.

The committed-replay flip (state:"queued" -> state:"consumed") breaks 3 restart-recovery tests in src/gateway/server.chat.gateway-server-chat-b.test.ts:

  • "chat.send retains a restart interruption after SQLite admission commits"
  • "chat.send releases an unadopted durable claim after dispatch rejection"
  • "chat.send leaves a post-admission routing rejection retryable"

Controlled A/B, same unmodified file, 9.3 lineage (CI is red on the identical 3):

  • base ed57183: Test Files 1 passed (1), 0 failed
  • this change: Test Files 1 failed (1), 3 failed
  • only production delta is the one-line flip; the added tests do not touch chat-b

Mechanism: chat-send-handler.ts checks isPendingInputConsumed() and, when true, short-circuits to a cached "ok" instead of re-driving recovery. The committed-replay branch is also reached by legitimate restart-recovery, so reporting it "consumed" drops redelivery of an interrupted turn after SQLite admission commits.

It also does not fix the observed defect: re-presentations of an already-delivered inbound continued after deploy, so this branch is not the seam driving the re-drive.

Separate: check-lint-core-4 is red - the added test pushes session-accessor.pending-inputs.test.ts to 1047 effective lines (cap 1000, max-lines).

Net: do not merge as-is. A v2 is needed that targets the actual re-drive seam and passes the full gateway chat.send + restart-recovery suites before any deploy.

@amittell

Copy link
Copy Markdown
Owner Author

Superseded - closing per Alex (2026-09-14).

This PR's core flip (blanket committed-replay queued->consumed) is the regression documented in the 22:34Z 'Holding - not merging' comment: it breaks the 3 chat-b restart-recovery cases and trips both P1 findings (post-persistence crash window loses the reply; test doesn't exercise the real channel entry point).

The corrected 9.4 port - channel-bound-key re-drive rule + pending non-terminal recovery-claim guard (preserves reconnect recovery), run-id keys keep isSourceTurnReplay untouched (protects agent.wait) - lands in the replacement PR fix/reinject-94-bodyless -> deploy/v2026.9.4-carry-20260914, based on the live carry HEAD (37ea9f1), A/B-verified on that exact base.

Head branch fix/pending-input-reinject-dedupe-9.4 left in place (not force-pushed).

@amittell amittell closed this Sep 14, 2026
amittell added a commit that referenced this pull request Sep 15, 2026
…esentations

Alex's ruling: a committed source turn is terminal at admission only if the turn
actually completed. Measured at the call site, the signal that separates the two
cases is who OWNS the idempotency key - which is what this fix's own contract
already said:

    "the channel source turn id is the message idempotency key; the run id is
     distinct and randomized per execution"

    re-presentation   key "channel-user:v1:deadbeef"        runId "re-driven-run"
                      a channel source turn id under a NEW unrelated run id
                                                            -> consumed (terminal)

    retry             key "idem-restart-safe-abort-restart:user"
                      runId "idem-restart-safe-abort-restart"
                      the run re-driving itself after a restart interruption, a
                      dispatch rejection, or a post-admission routing rejection
                                                            -> queued (admitted)

Two earlier discriminators are recorded here because both were wrong and the
reasons are useful:

  - "no resumable pending-input row survives" - unusable. All three chat.send
    retries reach this branch with `existing` null, exactly like the re-drive.
  - "the committed body differs" - unusable alone. The retries replay identical
    role and content, so a body compare calls them re-presentations too. It did
    fix the agent.wait case (different body, same key), which is why it looked
    sufficient for one commit.

Both were established by instrumenting the branch and printing the real state
rather than reasoning about it; the probe output is what showed key-vs-runId as
the one field that actually differs.

Verified:
    session-accessor.pending-inputs.redrive.test.ts    1 passed   (PR #9 intent held)
    server.chat.gateway-server-chat.test.ts           73 passed   (was 1 failed)
    server.chat.gateway-server-chat-b.test.ts        138 passed   (was 3 failed)
    src/config/sessions/ (whole family)   143 files, 1860 passed

This closes the last of the carry regressions: 13 of 13 tests across 4 files that
passed on both the pristine v2026.9.4 tag and the fork 9.3 tip.
amittell added a commit that referenced this pull request Sep 15, 2026
…ership consumes

01f985c made a committed source turn terminal at admission unless the key
belongs to the current run. That is right for the ghost re-drive, and it misses
one case: restart recovery re-drives a source turn under a NEW recovery run id,
so its key belongs to the ORIGINAL run and never to this one. Key ownership
therefore consumes it and the legitimate re-delivery is dropped - PR #9's P1,
and the case PR #10's claim guard exists for.

So a committed replay stays admitted when EITHER the key belongs to this run OR
a restart-recovery claim still owes this exact source turn. A delivered-terminal
receipt does not authorize a re-drive (terminal-pending and delivery-ambiguous
still do). Both key forms are matched because a claim records the source turn id
while the replay may arrive as "<sourceTurnId>:user".

Composed from three prior designs rather than picking one: key ownership
(01f985c, on this line), the channel-bound claim guard and its
delivered-terminal refinement (PR #10 40d4337 + 2cb4984, built on the
carry's byte-compare), and the ":user"-stripped source match (fbee1cab18a,
unpushed on rh-bot). Uses the canonical hasRestartRecoverySourceClaim /
hasRestartRecoveryTerminalRun helpers instead of re-implementing the claim
shape; note the "active" variant is deliberately NOT used, since it requires
entry.status === "running" and a recovery entry is "failed".

Also reads the session entry row once and reuses it, instead of re-reading the
same row inside the committed branch of the same exclusive write.

PRE-FIX CONTROL (measured on this branch, before the seam change): the ported
PR #10 suite ran 2 passed / 1 failed, failing on the assertion
"expected false to be true" in the terminal-pending recovery case - the exact
case above, failing on its assertion rather than on an import.
amittell added a commit that referenced this pull request Sep 17, 2026
…nt is 12

Corrects a claim I committed in bdaeba5. Append-only: the original lines are
kept byte-identical because they were true when written, and a dated correction
follows them.

The note said check-max-lines-ratchet.mts "exits 0 on all nine ... and never asks
whether an unledgered file is under budget". Literally true, and it was read - by
me and by the seat whose finding I was corroborating - as "nothing checks the cap".
False. scripts/check-changed.mts:876 schedules createTargetedCoreLintCommands for
changed src/ paths, with a lint:core fallback at :884 and :909, and oxlint enforces
the 700-line cap, so the changed-files lane fails an over-cap commit. The ratchet
stops suppressions spreading and does that job. We missed the cap check because we
grepped check-changed for "max-lines", and ordinary lint never contains that string.
The originating seat caught it by filing it as a durable issue (#9), which forced a
claim-by-claim re-check.

The count was also stale. A whole-repo scan at 1d54102,
node scripts/run-oxlint.mjs src ui packages extensions, 31,434 files, 219s, finds 13
max-lines errors: 12 production files over the 700 cap and one test file over the
1000 cap. None is in config/max-lines-baseline.txt and all 13 differ from the
v2026.9.4 tag, so neither grandfathering nor upstream debt explains any of them.
Issue #9 lists 6 of those 12 with identical figures; the full list and the question
of how the six were selected are on #9.

The open question the correction leaves is why over-cap files landed past a lane
that rejects them. Candidate, unconfirmed: nothing currently runs that lane on this
branch - pushes run no check:changed, and hosted CI refuses all 31 placements.
amittell added a commit that referenced this pull request Sep 17, 2026
Merges the parked save/pending-input-marker (b386f827465 + 9ac9aecaa2d) into the 9.4
line, collapsing the seam to ONE rule as that commit required of whoever merged it:
"two rules now live at that seam, split by key space, and the duplication is deliberate
and MUST NOT survive a merge."

The collapsed rule, one expression, arm chosen by KEY SPACE:

  channel-user:v1:<hash>   deterministic per inbound messageId, so a committed hit is a
                           re-drive by definition, body or not -> terminal, unless a live
                           restart-recovery claim still owes this exact source.
  everything else          run-id keys carry no such determinism: a re-presentation of an
                           ANSWERED turn and a re-drive of a turn that DIED mid-run arrive
                           identically -> the answered-turn marker decides.

Kept from 9.4 (c986d87), which is the refined side: requiresRecoveryRedelivery via
hasRestartRecoverySourceClaim on BOTH key forms plus the delivered-terminal exclusion,
rather than the marker branch's narrower inline claim compare. Kept from the marker
branch: the answered-turn marker itself and its stamping sites.

CORRECTION to the marker commit's stated reason, measured here. It said key ownership
"can never fail: every caller of stageApproved builds the key as <runId>:user from the
same runId it passes, so the consumed arm was dead code". That is right for an in-process
retry and wrong across a RECORDER boundary: 9ac9aecaa2d's own cases re-present under a NEW
run id while the key still names the original run, and restart recovery does the same. So
key ownership did not merely never-consume - it ALSO consumed legitimate re-drives whose
key belonged to another run. Key space, not key ownership, selects the arm; the marker is
the terminal test on the run-id side.

Measured in this tree (Air, node 22.23.1):
  pending-inputs + redrive + redrive-bodyless + completed-turn      50 tests, all pass
  chat-send-pending-inputs, chat-pending-inputs, restart-recovery
    (agent-command, main-session-recovery, receipt)                375 tests, 13 files, pass
    - this is the regression that held PR #9: its blanket queued->consumed flip broke three
      restart-recovery cases. None of them fails here.
  pnpm tsgo:core  exit 0
  mutation control, collapsed rule replaced by the old key-ownership predicate with all
    marker plumbing kept: 6 failed, every one an AssertionError reading
    "expected 'consumed' to be 'queued'". An earlier control that reverted the whole file
    is NOT evidence - it failed to load, because the file it reverted to has no request
    hash to import.

NOT measured, and the marker commit said the same: that the two success sites stamp the
marker in a live run. Their wiring is verified by source and by the accessor tests, not by
a gateway run.
amittell pushed a commit that referenced this pull request Nov 25, 2026
…on (openclaw#204437)

## Result

The scheduled live job "Verify live agent prompt prefix reuse" passes again. It has failed on every scheduled run since 2026-11-17, while the real OpenAI cache held: after a reopen, the uncached tokens are the same as before openclaw#200163.

## Cause

openclaw#200163 (1fa849c) stopped sending reasoning item IDs next to encrypted reasoning on cold replay, to fix `item_conflict`. A warm continuation still inherits the stored output items, IDs included. So across a reopen, history item 2 changes from `{id, type, summary, encrypted_content}` to `{type, summary, encrypted_content}`. The live gate reported exactly this on every run since 11-17:

```
openai release turn 4: prefix changed segment=history[2] path=$.keys[2]   ("id" -> "summary")
```

IDs render no model tokens. openclaw#200163 changed the transport unit test to ignore reasoning envelopes, but the release gate (`embedded-agent-runner.cache.test-support.ts`) kept its own copy of the rule that ignored only function-call and assistant-message envelopes. Three tests had three copies of the rule, and they diverged.

## Change

- `omitResponsesReplayEnvelopes` in `scripts/e2e/lib/anthropic-cache/prefix-stability.mts`, the owner of prefix snapshots, is now the one definition of token-free Responses envelopes: `id` and `status` on function calls, reasoning items and assistant messages.
- The release gate, the transport history-prefix test and the cold-prefix test all use it. Their local copies are deleted.
- No production code changes. The wire shape from openclaw#200163 stays, so its `item_conflict` fix is untouched.

## Evidence

Real OpenAI API (`gpt-5.6-luna`), the release prompt-prefix scenario: 3 warm turns, then a reopen on turn 4, 3 requests per turn. Per-request usage comes from the scenario's own cache diagnostics:

| Request | Base `89d07fe5` (parent of openclaw#200163): cacheRead / prompt, uncached | `main` b4cc3bc, gate ignoring reasoning IDs: cacheRead / prompt, uncached |
|---|---|---|
| turn 3 #7 | 96,709 / 97,116, **407** | 96,587 / 96,994, **407** |
| turn 3 #8 | 96,881 / 104,554, 7,673 | 96,759 / 104,431, 7,672 |
| turn 3 #9 | 104,551 / 111,983, 7,432 | 104,428 / 111,860, 7,432 |
| **turn 4 (reopen) #10** | 111,980 / 112,191, **211** | 111,857 / 112,068, **211** |
| turn 4 #11 | 112,152 / 119,629, 7,477 | 112,029 / 119,506, 7,477 |
| turn 4 #12 | 119,626 / 127,058, 7,432 | 119,503 / 126,935, 7,432 |

The reopen request reuses the whole previous prompt in both arms, so the retry prefix is fully cached. The scenario's own check (each request reuses at least 80% of the preceding prompt) passes in both arms.

- The same scenario with the unchanged gate on `main` fails locally with the CI signature. On this head it passes (OpenAI).
- `anthropic-cache-prefix-stability.test.ts`: a new case checks that a warm continuation and its cold replay give equal snapshots, and that changed ciphertext still fails at `history[1]`. 11 passed. `openai-responses-client.history-prefix.test.ts` 8 passed, `embedded-agent-runner.responses-cold-prefix.test.ts` 10 passed.
- Real-API dispatch of the scheduled live workflow on this branch: https://github.com/openclaw/openclaw/actions/runs/45338721403, `validate_release_live_cache` passed.
- New unit cases: changed function-call arguments, call ids and assistant content still fail at the changed index; the projection strips only `id` and `status`.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants