Skip to content

[Bug]: Replay normalization leaves a stale turn boundary and drops current input/tool results #146331

Closed

Description

@fray-ai

Bug type

Behavior bug (incorrect output/state without crash)

Beta release blocker

No

Summary

In the embedded runner's deferred context-engine tool loop, replay normalization can shorten history after prePromptMessageCount was captured; the stale boundary can then classify the current user/runtime input and new tool results as history and drop them when reassembling the next model call.

This report isolates the message-preservation failure with a deterministic, no-network fixture using functions extracted from the installed release. It does not require a particular model or access to private conversations.

Steps to reproduce

  1. Use an existing npm installation of OpenClaw 2026.9.3, on a supported Node version.
  2. Save the executable fixture below as repro.mjs and run node repro.mjs /absolute/path/to/node_modules/openclaw. It reads the installed JavaScript modules; it does not start a Gateway, call a model, or modify installation/config/session data.
  3. The fixture builds 84 historical messages: 78 ordinary entries and six removable NO_REPLY assistant entries. The installed normalizeAssistantReplayContent reduces this to 78.
  4. Preserve the pre-normalization boundary (84), as the observed source ordering permits. Append a synthetic current runtime item and user request, then two call/result rounds.
  5. The installed installContextEngineLoopHook receives a synthetic deferred context engine that returns only committed history. Check the hook's returned model context after each round.
  6. Repeat with the boundary computed from the normalized history (78). This is a boundary-rebased control, not a full integration test of the proposed source patch.

Expected behavior

Current input and newly produced tool call/result pairs remain in the model context across tool-loop reassembly. The existing hook implements this contract by reserving tokens for pendingMessages and appending them after the engine's assembled history. The rebased control preserves the current runtime/user and both tool results.

Actual behavior

The executable fixture completes successfully only if it detects the faulty behavior and the preserving control. Observed output:

Case Iteration Source messages Engine input messages Current user/runtime preserved New tool results preserved
Stale boundary = 84 Initial 80 Not called Yes N/A
Stale boundary = 84 After tool round 1 82 82 No None
Stale boundary = 84 After tool round 2 84 84 No None
Rebased boundary = 78 Initial 80 78 Yes N/A
Rebased boundary = 78 After tool round 1 82 78 Yes Round 1
Rebased boundary = 78 After tool round 2 84 78 Yes Rounds 1 and 2

With the stale boundary, the engine returns the same 84-entry history after each tool round, and the pending suffix is empty. With the rebased boundary, output grows to 86, 88, and 90 messages. There is no context-budget pressure in this fixture.

OpenClaw version

Executed against npm release 2026.9.3, build commit 1391f7cd2d40ab5bbcf2f5f831d3a64f520e72d7.

Also inspected current main at 9233c9dd07bf91ca43a41551c669a4a4be618d9d: the relevant ordering and slice remain present. No full test suite or end-to-end reproduction on main is claimed.

Operating system

Ubuntu 24.04.4 LTS; Node.js v26.8.1.

Install method

Global npm installation.

Model

None for the deterministic reproduction. The motivating user report involved meta/muse-spark-1.3 with an external context engine, but the fixture does not establish complete historical causality or model-specific prevalence.

Provider / routing chain

Reproduction: installed replay normalizer -> installed embedded context-engine loop hook -> synthetic history-only deferred context engine. Zero provider requests.

Additional provider/model setup details

The failure requires a shortened replay history and a stale pre-prompt boundary in the deferred-turn path. The fake engine models a committed-history-only result; the host is responsible for retaining the uncommitted active tail. No external plugin source or credentials are needed to run the fixture.

Source evidence

At the inspected main revision:

  1. prepareEmbeddedAttemptPromptContext filters heartbeat artifacts and then captures sessionMessages.length as prePromptMessageCount (line 432).
  2. runEmbeddedAttemptPromptPhase copies that count into runtime state.
  3. submitEmbeddedAttemptPrompt subsequently calls normalizeAssistantReplayContent and replaces the history without rebasing that count.
  4. installContextEngineLoopHook obtains historyLength from the stored getter and runs providerMessages.slice(historyLength). A shortened prefix can make that suffix empty or incomplete.

The earlier length clamp in the hook controls whether to reassemble; it does not rebase the later history/pending split.

Proposed fix (not deployed)

Move replay normalization into prepareEmbeddedAttemptPromptContext, before capturing the boundary and building hook/precheck views:

let sessionMessages = normalizeAssistantReplayContent(
  filterHeartbeatTranscriptArtifacts(
    input.messages,
    input.prompt.heartbeatSummary?.ackMaxChars,
    input.prompt.heartbeatSummary?.prompt,
  ),
);
if (sessionMessages !== input.messages) {
  input.replaceSessionMessages(sessionMessages);
}
// Reconcile provider projections using this same normalized history.
const prePromptMessageCount = sessionMessages.length;

Remove the subsequent length-changing normalization in submitEmbeddedAttemptPrompt and use the already normalized history there, including any snapshot references. This keeps the fence and its message array in the same coordinate system, before current runtime/user/tool messages are inserted. The raw durable transcript should remain unchanged.

Do not hard-code a subtraction of six, clamp the fence to the current array length, or recalculate it after appending the current turn. Those approaches can still classify active messages as history.

Suggested regression coverage for the integrated patch:

  • Removable replay artifacts followed by new user/runtime input and two tool rounds: preserve every active item exactly once and in order.
  • A no-op normalization control and normalization that changes content without changing count.
  • Pre-persisted user/replay/recovery paths: neither duplicate nor drop the current user.
  • Runtime-only/finalization turns and parallel tool call/result pairs.
  • Deferred context-engine and standalone paths; preserve ingestion/checkpoint behavior.

Longer-term hardening could use stable active-turn identities/anchors and a preservation invariant before provider submission. That is distinct from this minimal ordering fix, and must not rewrite immutable durable transcript anchors.

Screenshots, recordings, and evidence

The following executable fixture is synthetic and version-pinned because it extracts functions from a published bundle with hashed filenames. It deliberately fails if an unexpected dependency branch is reached. It is not a replacement for a repository integration regression test.

Executable reproduction (save as repro.mjs)
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { isDeepStrictEqual } from 'node:util';
import vm from 'node:vm';
import assert from 'node:assert/strict';
if (!process.argv[2]) throw new Error('Usage: node repro.mjs /absolute/path/to/node_modules/openclaw');
const root=process.argv[2];
const source=await readFile(`${root}/dist/builtin-openclaw-FlPOnMHc.mjs`,'utf8');
const require=createRequire(`${root}/package.json`);
const transports=await import(require.resolve('@openclaw/ai/transports'));
const imports=await Promise.all([
  import(`${root}/dist/record-coerce-DItp3I4t.mjs`),
  import(`${root}/dist/display-text-sanitize-J8UnEavN.mjs`),
  import(`${root}/dist/tokens-DwD7c00a.mjs`),
  import(`${root}/dist/ai-transport-runtime-host-BvhFsKp5.mjs`),
  import(`${root}/dist/stream-message-shared-sKH7NjHK.mjs`),
  import(`${root}/dist/transcript-only-openclaw-assistant-CVgy4bjA.mjs`),
  import(`${root}/dist/usage-BpC2Ujh-.mjs`),
  import(`${root}/dist/tool-call-id-CnwowhSs.mjs`),
  import(`${root}/dist/compaction-B8syZLTn.mjs`),
]);
const sandbox={
  isDeepStrictEqual,
  asOptionalRecord:imports[0].a,
  stripInternalMetadataForDisplay:imports[1].t,
  isSilentReplyPayloadText:imports[2].i,
  isReasoningOnlyLengthAssistantTurn:imports[3].i,
  hasOnlyAssistantReasoningContent:imports[3].r,
  isStreamErrorFallbackContent:imports[4].a,
  isTranscriptOnlyOpenClawAssistantMessage:imports[5].s,
  hasNonzeroUsage:imports[6].a,
  normalizeUsage:imports[6].c,
  extractToolCallsFromAssistant:imports[7].t,
  estimateTokens:imports[8].u,
  replaceCompactionReplayOwnerContent:transports.replaceCompactionReplayOwnerContent,
  // These are never reached by this synthetic fixture; fail rather than simulate them.
  hasPersistedMedia(){throw new Error('fixture unexpectedly requires persisted media');},
  isZeroUsageEmptyStopAssistantTurn(){throw new Error('fixture unexpectedly requires zero-usage branch');},
};
const between=(a,b)=>source.slice(source.indexOf(a),source.indexOf(b,source.indexOf(a)));
const extracted=[
  'const TRANSCRIPT_PROMPT_TEXT_KEY = "__openclawTranscriptPromptText";',
  'const MANAGED_DISPLAY_BLOCK_TYPES = new Set(["attachment","attachment_error","audio","image","video"]);',
  between('function getTranscriptPromptText(', 'function replaceToolResultContent('),
  between('function sanitizeUserReplayContent(', 'function normalizeAssistantUsageSnapshot('),
  between('function installContextEngineLoopHook(', 'function installToolResultContextGuard('),
  'globalThis.audit={normalizeAssistantReplayContent,installContextEngineLoopHook};',
].join('\n');
// Guard extraction end boundary; source is installed code, not reimplemented logic.
assert(extracted.length<25000);
vm.runInNewContext(extracted,sandbox);
const {normalizeAssistantReplayContent,installContextEngineLoopHook}=sandbox.audit;
const history=Array.from({length:78},(_,i)=>({role:i%2?'assistant':'user',content:`Historical item ${i}`,timestamp:i}));
const assembled=[...history,...Array.from({length:6},(_,i)=>({role:'assistant',content:'NO_REPLY',timestamp:100+i}))];
const normalized=normalizeAssistantReplayContent(assembled);
assert.equal(assembled.length,84);
assert.equal(normalized.length,78);
const runtime={role:'custom',customType:'openclaw.runtime-context',content:'CURRENT_RUNTIME_MARKER',timestamp:200};
const user={role:'user',content:'CURRENT_USER: summarize NEW_TOPIC',timestamp:201};
const toolRound=i=>[{role:'assistant',content:[{type:'toolCall',id:`call${i}`,name:'read_fixture',arguments:{id:i}}],timestamp:202+i*2},{role:'toolResult',toolCallId:`call${i}`,toolName:'read_fixture',content:[{type:'text',text:`CURRENT_TOOL_RESULT_${i}`}],timestamp:203+i*2}];
async function run(label,fence){
  const calls=[];
  const agent={};
  const remove=installContextEngineLoopHook({agent,sessionId:'synthetic',sessionKey:'synthetic',tokenBudget:1048576,modelId:'synthetic',getPrePromptMessageCount:()=>fence,deferredTurn:{prompt:'CURRENT_USER: summarize NEW_TOPIC'},contextEngine:{async assemble(p){calls.push({inputMessages:p.messages.length,tokenBudget:p.tokenBudget});return {messages:assembled};}}});
  let messages=[...normalized,runtime,user];
  const rows=[];
  for(let i=0;i<3;i++){
    if(i)messages=[...messages,...toolRound(i)];
    const output=await agent.transformContext(messages);
    const serialized=JSON.stringify(output);
    rows.push({iteration:i,sourceMessages:messages.length,assembled:calls.at(-1)??null,outputMessages:output.length,currentUser:serialized.includes('CURRENT_USER:'),currentRuntime:serialized.includes('CURRENT_RUNTIME_MARKER'),toolResults:[1,2].filter(j=>serialized.includes(`CURRENT_TOOL_RESULT_${j}`))});
  }
  remove();
  return {label,fence,rows};
}
const stale=await run('installed ordering: count before normalization',assembled.length);
const rebased=await run('control: count from same normalized coordinate system',normalized.length);
assert(stale.rows[0].currentUser);
assert(!stale.rows[1].currentUser);
assert(!stale.rows[2].currentUser);
assert(stale.rows[1].assembled.inputMessages===82&&stale.rows[2].assembled.inputMessages===84);
assert(stale.rows[1].assembled.tokenBudget===1048576);
assert.deepEqual(stale.rows[1].toolResults,[]);
assert(rebased.rows.every(x=>x.currentUser&&x.currentRuntime));
assert.deepEqual(rebased.rows[2].toolResults,[1,2]);
console.log(JSON.stringify({testedRelease:'2026.9.3',extractedModule:'dist/builtin-openclaw-FlPOnMHc.mjs',synthetic:true,providerRequests:0,normalization:{before:assembled.length,after:normalized.length},stale,rebased},null,2));

Impact and severity

Affected tested path: embedded deferred context-engine tool loop with a history-shrinking replay normalization. Deterministic for the provided fixture. Practical consequence: a valid tool result and current task can be absent from the next model call without an error, allowing an answer to revert to an older topic. Population frequency and all-model/channel prevalence: NOT_ENOUGH_INFO.

Additional information

No production patch, restart, provider request, or private transcript publication was performed for this report. Last known good release: NOT_ENOUGH_INFO.

Searched existing issues/PRs for prePromptMessageCount, normalizeAssistantReplayContent, and context-loss terms. Related coordinate discussion #128509 concerns durable commitTurn anchors and payload semantics; this report concerns an in-memory pending-tail boundary and does not propose altering that contract.

Activity

  1. added
    P2
    clawsweeper:fix-shape-clear
    clawsweeper:queueable-fix
    clawsweeper:source-repro
    impact:session-state
    issue-rating: 🦞 diamond lobster
    no-stale
    on Sep 12, 2026
  2. clawsweeper commented on Sep 12, 2026

    @clawsweeper
    Contributor

    Thanks for the context here. I did a careful shell check against current main, and this is already implemented.

    The reported loss of current input and tool results is fixed on current main by the merged repair at #147531. That commit is included in v2026.9.5, and current regression coverage checks multiple tool rounds.

    Root-cause cluster
    Relationship: fixed_by_candidate
    Canonical: #147531
    Summary: The merged repair addresses the issue's replay-boundary failure; earlier proposed fixes were closed without merging.

    Members:

    Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

    So I’m closing this as already implemented rather than keeping a duplicate issue open.

    Review details

    Best possible solution:

    Keep the shipped boundary ordering and its multi-round preservation regression in place.

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

    Yes, the issue and merged repair document a failing pre-fix deferred tool loop with removable replay entries and multiple model requests. Current main contains the fix, so this review did not establish a current-main failure.

    Is this the best way to solve the issue?

    Yes. Normalizing replay before recording the boundary keeps the history array and boundary in one coordinate system; current tests cover the resulting model requests.

    Security review:

    Security review: This is issue triage; no proposed patch is under security review.

    AGENTS.md: found and applied where relevant.

    What I checked:

    Likely related people:

    • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
    • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
    • MertBasar0: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

    Codex review notes: model internal, reasoning medium; reviewed against 4d1c5d19ecc8; fix evidence: release v2026.9.5, commit 24425bfdc1cd.

  3. clawsweeper commented on Sep 12, 2026

    @clawsweeper
    Contributor

    🦞⚠️
    Automatic implementation stopped before completion.
    Reason: The automatic implementation worker stopped before all deterministic gates completed. Open the workflow run for the exact blocker.
    Worker: https://github.com/openclaw/clawsweeper/actions/runs/34713199486

    Automatic implementation progress:

  4. MertBasar0 commented on Sep 12, 2026

    @MertBasar0
    Contributor

    Picking this up — I have the failure reproduced against current main (9b59fe4ef7d) with the real modules, so posting the mechanism before opening a PR.

    The boundary does get clamped, but not at the slice that matters. installContextEngineLoopHook computes a fenced copy:

    const prePromptMessageCount = Math.max(0, Math.min(
      transcriptMessages.length,
      lastSeenLength ?? params.getPrePromptMessageCount?.() ?? transcriptMessages.length,
    ));

    and then the deferred branch re-reads the raw getter, unclamped:

    const historyLength = params.deferredTurn
      ? (params.getPrePromptMessageCount?.() ?? 0)
      : providerMessages.length;
    const pendingMessages = providerMessages.slice(historyLength);

    src/agents/embedded-agent-runner/tool-result-context-guard.ts:420.

    Ordering confirmed in source: prepareEmbeddedAttemptPromptContext captures prePromptMessageCount = sessionMessages.length (attempt-prompt-build.ts:432), and submitEmbeddedAttemptPrompt later replaces activeSession.agent.state.messages with normalizeAssistantReplayContent(...) (attempt-prompt-submit.ts:107). attempt-prompt-phase.ts calls them in that order (181, then 395), so the captured count can outrun the messages that remain.

    One note for anyone writing coverage: a single-call fixture never reaches the defect. When the getter exceeds the array, the fenced copy clamps to the array length and the transcriptMessages.length <= prePromptMessageCount early-return fires, so assemble is never called and the raw messages come back looking correct. The stale value only reaches the slice on a later call, once lastSeenLength was seeded while the array was shorter. deferredTurn also has no coverage in tool-result-context-guard.test.ts today, which is consistent with this surviving.

    With a deferred engine that serves only committed history, the failing assertion on current main is the message loss itself:

    AssertionError: expected [ committed h1, committed h2 ] to include { role: 'user', ... }
    

    i.e. the current user request is absent from the next model call. Reusing the already-fenced count for the deferred slice turns that green; 80/80 across both guard suites. PR shortly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2clawsweeper:fix-shape-clearclawsweeper:queueable-fixclawsweeper:source-reproimpact:session-stateissue-rating: 🦞 diamond lobsterno-stale

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions