Skip to content

fix: prevent phantom toolResult from corrupting sessions - #39353

Closed
alvinttang wants to merge 4 commits into
openclaw:mainfrom
alvinttang:fix/21985-phantom-toolresult-stopreason
Closed

alvinttang wants to merge 4 commits into
openclaw:mainfrom
alvinttang:fix/21985-phantom-toolresult-stopreason

Conversation

@alvinttang

Copy link
Copy Markdown
Contributor

Summary

  • Fix session-permanent corruption caused by phantom toolResult entries with empty toolCallId
  • When a fallback model returns stopReason: "toolUse" but the response content has NO actual toolCall blocks (only thinking + text), downstream repair creates phantom toolResult entries that permanently corrupt the session
  • Detect the mismatch in repairToolUseResultPairing and correct stopReason to "stop" so no synthetic toolResult entries are generated

Fixes #21985

Test plan

  • Verify sessions with stopReason: "toolUse" and no toolCall blocks no longer create phantom toolResults
  • Verify normal tool use flows with valid toolCall blocks still work correctly
  • Verify existing session repair for valid tool use is not affected

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Mar 8, 2026

@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: 223e032e62

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +412 to +414
if (stopReason === "toolUse") {
const corrected = { ...assistant, stopReason: "stop" };
out.push(corrected as AgentMessage);

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.

P1 Badge Mark stopReason correction as a transcript change

When this branch rewrites an assistant message from stopReason: "toolUse" to "stop", changed is never set, so repairToolUseResultPairing can return the original messages array at the end (changedOrMoved stays false). In the exact scenario this commit targets (assistant has toolUse stop reason but no tool-call blocks), the correction is dropped and downstream code still sees the uncorrected transcript, so phantom tool-result generation is not actually prevented.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR bundles two independent fixes: (1) correcting a phantom toolResult corruption bug in repairToolUseResultPairing by detecting when stopReason: "toolUse" is set but no actual tool call blocks exist, and (2) a security fix in normalizeProviders that prevents resolved API-key secrets from being persisted as plaintext in models.json by replacing them with their canonical env var name.

  • The session-repair fix has a critical logic bug: the new branch that pushes the corrected message to out never sets changed = true, so repairToolUseResultPairing returns the original uncorrected messages array whenever the stopReason correction is the only change in the repair pass — silently defeating the fix.
  • The models-config.providers.ts env var reverse-lookup is well-guarded and safe; two new tests cover it correctly.
  • No unit test is added for the repairToolUseResultPairing change, leaving the new code path completely untested.

Confidence Score: 2/5

  • Not safe to merge — the primary session-repair fix is broken and will not take effect in its intended scenario.
  • The models-config secret-persistence fix is correct and well-tested. However, the headline fix in session-transcript-repair.ts has a definitive logic bug: changed is never set to true when the stopReason correction is applied, so the function returns the original unmodified messages in the exact scenario the PR is trying to fix. This means sessions that only have the phantom stopReason: "toolUse" issue remain corrupted after the repair runs.
  • src/agents/session-transcript-repair.ts — missing changed = true in the new correction branch, and no test coverage for the new code path.

Last reviewed commit: 223e032

Comment on lines +412 to +414
if (stopReason === "toolUse") {
const corrected = { ...assistant, stopReason: "stop" };
out.push(corrected as AgentMessage);

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.

changed flag not set — correction is silently discarded

When stopReason === "toolUse" with no tool calls, the code builds a corrected message and pushes it to out, but never sets changed = true. The function's return path at the end checks changedOrMoved ? out : messages — so if this stopReason correction is the only mutation in the entire repair pass, changed remains false, and the function returns the original messages array rather than out. The correction is silently dropped.

Suggested change
if (stopReason === "toolUse") {
const corrected = { ...assistant, stopReason: "stop" };
out.push(corrected as AgentMessage);
if (stopReason === "toolUse") {
const corrected = { ...assistant, stopReason: "stop" };
changed = true;
out.push(corrected as AgentMessage);

This means sessions where the phantom toolUse stopReason is the sole problem would continue to be corrupted even after the repair is applied, defeating the purpose of the fix.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/session-transcript-repair.ts
Line: 412-414

Comment:
**`changed` flag not set — correction is silently discarded**

When `stopReason === "toolUse"` with no tool calls, the code builds a `corrected` message and pushes it to `out`, but never sets `changed = true`. The function's return path at the end checks `changedOrMoved ? out : messages` — so if this stopReason correction is the **only** mutation in the entire repair pass, `changed` remains `false`, and the function returns the original `messages` array rather than `out`. The correction is silently dropped.

```suggestion
      if (stopReason === "toolUse") {
        const corrected = { ...assistant, stopReason: "stop" };
        changed = true;
        out.push(corrected as AgentMessage);
```

This means sessions where the phantom `toolUse` stopReason is the sole problem would continue to be corrupted even after the repair is applied, defeating the purpose of the fix.

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

Comment thread src/agents/models-config.providers.ts Outdated
Comment on lines +528 to +538
if (
typeof currentApiKey === "string" &&
currentApiKey.trim() &&
!ENV_VAR_NAME_RE.test(currentApiKey.trim())
) {
const envVarName = resolveEnvApiKeyVarName(normalizedKey);
if (envVarName && process.env[envVarName] === currentApiKey) {
mutated = true;
normalizedProvider = { ...normalizedProvider, apiKey: envVarName };
}
}

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.

Consider collision risk for short/common API key values

The reverse-lookup guard process.env[envVarName] === currentApiKey is a strict equality check against the resolved env var value. If the env var's value is a short or common string (e.g., a test key like "test" or "none"), this could produce a false positive match, silently replacing a legitimate literal API key with the env var name in the persisted config.

A comment noting this assumption — i.e., that real secret values are long enough to make accidental collision negligible — would help future maintainers understand why a length or entropy guard was deliberately omitted.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/models-config.providers.ts
Line: 528-538

Comment:
**Consider collision risk for short/common API key values**

The reverse-lookup guard `process.env[envVarName] === currentApiKey` is a strict equality check against the resolved env var value. If the env var's value is a short or common string (e.g., a test key like `"test"` or `"none"`), this could produce a false positive match, silently replacing a legitimate literal API key with the env var name in the persisted config.

A comment noting this assumption — i.e., that real secret values are long enough to make accidental collision negligible — would help future maintainers understand why a length or entropy guard was deliberately omitted.

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

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.

Acknowledged. The collision risk is negligible for real API keys (which are typically 40+ character random strings), but adding a brief comment noting this assumption is a good idea for future maintainers. Will add that alongside the fix.

@alvinttang

Copy link
Copy Markdown
Contributor Author

Fixed — added the missing changed = true when correcting stopReason. The repair now correctly returns the fixed messages.

gambletan and others added 3 commits March 8, 2026 17:02
…claw#38757)

When apiKey values are resolved from env var substitution by loadConfig(),
the plaintext secret was being persisted to agents/*/agent/models.json.

Add a reverse-lookup in normalizeProviders() that detects when an apiKey
matches a known provider env var's value and replaces it with the env var
name, preventing secrets from being written to disk.
When a fallback model returns stopReason 'toolUse' but the response
content contains no actual toolCall blocks (only thinking + text),
the uncorrected stopReason causes downstream repair code to create
phantom toolResult entries with empty toolCallId and toolName. These
phantom entries permanently corrupt the session, causing all
subsequent requests to fail with tool pairing errors.

Detect the mismatch between stopReason='toolUse' and empty toolCalls
in repairToolUseResultPairing, and correct stopReason to 'stop' so
no synthetic toolResults are generated.

Fixes openclaw#21985

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alvinttang
alvinttang force-pushed the fix/21985-phantom-toolresult-stopreason branch from 7236491 to 5828919 Compare March 8, 2026 09:02

@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: 58289194e2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/models-config.providers.ts Outdated
// var name), check whether it matches the canonical env var for this provider.
// This prevents resolveConfigEnvVars()-resolved secrets from being persisted
// to models.json as plaintext. (Fixes #38757)
const currentApiKey = normalizedProvider.apiKey;

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.

P1 Badge Remove duplicate apiKey reverse-lookup block

normalizeProviders now contains two consecutive copies of the reverse-lookup snippet, and this second copy redeclares const currentApiKey in the same scope. That causes a duplicate identifier parse/type-check error, so the agents config module cannot compile/load until one copy is removed.

Useful? React with 👍 / 👎.

@gambletan

Copy link
Copy Markdown
Contributor

Thanks for catching the duplicate const currentApiKey declaration in models-config.providers.ts. Looking into removing the duplicate reverse-lookup block now — will push a fix shortly.

@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 Apr 23, 2026
@steipete

Copy link
Copy Markdown
Contributor

Closing this as implemented after Codex review.

Current main already prevents this malformed stopReason: "toolUse" case at the producer boundary, so the PR's transcript-repair change is redundant on top of current code.

What I checked:

  • Producer-side fix exists on main: processOpenAICompletionsStream now downgrades stopReason from "toolUse" to "stop" when no toolCall blocks were emitted, which addresses the exact malformed assistant message described by this PR before it can enter session history. (src/agents/openai-transport-stream.ts:1379, 7d4718373698)
  • Regression test covers the malformed case: There is a dedicated test asserting that a completions stream ending with finish_reason: "tool_calls" but no actual tool-call blocks leaves output.stopReason === "stop" and emits no tool calls. (src/agents/openai-transport-stream.test.ts:2157, 7d4718373698)
  • PR diff is not present in transcript repair on main: repairToolUseResultPairing still passes through assistant messages with zero extracted tool calls unchanged, which shows the PR's exact patch did not land there. The behavior is instead handled earlier in the stream layer. (src/agents/session-transcript-repair.ts:471, 7d4718373698)

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

Review notes: reviewed against cb2c36b04975; fix evidence: commit 7d4718373698.

@steipete steipete closed this Apr 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: XS stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Cross-provider failover creates phantom toolResult with empty toolCallId, permanently corrupting session

3 participants