Skip to content

fix(agents): skip tool-call ID sanitization for Anthropic providers - #52644

Closed
Cypherm wants to merge 1 commit into
openclaw:mainfrom
Cypherm:fix/anthropic-cache-tool-id-sanitization
Closed

Cypherm wants to merge 1 commit into
openclaw:mainfrom
Cypherm:fix/anthropic-cache-tool-id-sanitization

Conversation

@Cypherm

@Cypherm Cypherm commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: After using subagents, Anthropic API calls trigger a full cacheWrite instead of cache hits, causing unexpected cost increases. This affects all Anthropic users who use tool calls with subagents.
  • Why it matters: Cache misses mean every turn after a subagent interaction pays full input token cost instead of the discounted cached rate. For long conversations with frequent tool use, this can multiply costs significantly.
  • What changed:
    • Removed isAnthropic from the sanitizeToolCallIds flag in resolveTranscriptPolicy
    • Updated tests to reflect that Anthropic and Bedrock providers no longer sanitize tool call IDs
  • What did NOT change (scope boundary):
    • Google, Mistral, and OpenAI-compatible providers still sanitize tool call IDs as before
    • repairToolUseResultPairing is unchanged — it still runs for all providers
    • The sanitizeToolCallId function itself is unchanged
    • No changes to how tool results are matched or how sessions are persisted

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause / Regression History (if applicable)

  • Root cause: Anthropic generates tool IDs with underscores (toolu_01AbCdEf). The "strict" sanitization mode stripped non-alphanumeric characters via createOccurrenceAwareResolver, which generates replacement IDs based on encounter order in the message array. After a subagent turn, repairToolUseResultPairing can reorder, insert, or drop messages. This changes the encounter order → the same original tool ID maps to a different sanitized ID → Anthropic sees different bytes in the cache prefix → full cacheWrite.
  • Missing detection / guardrail: No test asserted that Anthropic tool IDs should bypass sanitization. The sanitizeToolCallIds flag was set uniformly for all non-OpenAI providers without distinguishing providers whose APIs accept their own native ID format.
  • Prior context: sanitizeToolCallIds was introduced to handle providers that reject certain characters in tool call IDs (Google, Mistral, OpenAI-completions). Anthropic was included in this group despite generating IDs its own API accepts natively.
  • Why this regressed now: The cache instability only surfaces after subagent turns because repairToolUseResultPairing reorders messages, changing the encounter order for createOccurrenceAwareResolver. Single-agent sessions have stable message order, so the sanitized IDs happen to stay consistent.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/agents/transcript-policy.test.ts
  • Scenario the test should lock in: resolveTranscriptPolicy returns sanitizeToolCallIds: false and toolCallIdMode: undefined for Anthropic providers
  • Why this is the smallest reliable guardrail: The policy resolution function is the single decision point for whether IDs get sanitized. If the policy says false, no downstream code will rewrite IDs regardless of message ordering.
  • Existing test that already covers this: Updated existing "disables sanitizeToolCallIds for Anthropic provider" test (was asserting true, now correctly asserts false)

User-visible / Behavior Changes

  • Anthropic and Bedrock users will see restored cache hits after subagent interactions, reducing input token costs
  • No config changes required — the fix takes effect immediately

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: Ubuntu 24.04 (from issue reporter)
  • Runtime/container: podman
  • Model/provider: anthropic/claude-sonnet-4.6
  • Integration/channel: N/A
  • Relevant config: default (no custom sanitization settings)

Steps

  1. Create a new conversation
  2. Ask the agent to use a tool: Read the IDENTITY.md file. Do exactly as I ask.
  3. Ask the agent to spawn a subagent: Ask a subagent to respond with a random emoji, then tell me which emoji it was.
  4. Open the session logs (dashboard or agent/:id/sessions folder)
  5. Check the cacheWrite value for the last message in the chain

Expected

cacheWrite marginally increased, cacheRead is non-zero (cache prefix matches prior turns).

Actual

cacheWrite is large (entire conversation rewritten), cacheRead is zero (cache prefix changed due to ID rewriting).

Evidence

  • Failing test/log before + passing after
 ✓ disables sanitizeToolCallIds for Anthropic provider (#52612)
 ✓ enables sanitizeToolCallIds for Google provider
 ✓ enables sanitizeToolCallIds for Mistral provider
 ✓ disables sanitizeToolCallIds for OpenAI provider
 ✓ enables Anthropic-compatible policies for Bedrock provider
 ...
 Test Files  1 passed (1)
      Tests  19 passed (19)

Human Verification (required)

  • Verified scenarios:
    • resolveTranscriptPolicy returns sanitizeToolCallIds: false for Anthropic provider
    • resolveTranscriptPolicy returns sanitizeToolCallIds: false for Bedrock Anthropic provider
    • Google, Mistral, and OpenAI-compat providers still return sanitizeToolCallIds: true
    • All 19 transcript-policy tests pass
  • Edge cases checked:
    • toolCallIdMode falls through to undefined (not "strict") when sanitizeToolCallIds is false
  • What I did not verify:
    • Live Anthropic API call confirming cache hit improvement (requires real API key + subagent session)
    • Whether any downstream code path assumes Anthropic tool IDs are alphanumeric-only
    • Bedrock Converse API behavior with underscored tool IDs (assumed compatible since Bedrock proxies Anthropic)

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Failure Recovery (if this breaks)

  • How to disable/revert: Re-add isAnthropic to the sanitizeToolCallIds flag in resolveTranscriptPolicy (1-line revert)
  • Files/config to restore: src/agents/transcript-policy.ts only
  • Known bad symptoms: Anthropic API 400 errors mentioning invalid tool_use_id format

Risks and Mitigations

  • Risk: Bedrock Converse API might reject native toolu_* IDs with underscores (unverified assumption that it accepts them since it proxies Anthropic)
    • Mitigation: 1-line revert. Symptom would be HTTP 400 from Bedrock only; Anthropic direct unaffected.
  • Risk: Third-party providers routed through anthropic-messages modelApi but generating non-toolu_* IDs would skip sanitization
    • Mitigation: Such providers would need explicit registration as Anthropic-family. No known provider fits this case currently.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Mar 23, 2026
@greptile-apps

greptile-apps Bot commented Mar 23, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR removes isAnthropic from the sanitizeToolCallIds predicate in resolveTranscriptPolicy, fixing a cache-instability bug (#52612) where Anthropic API calls after subagent turns always resulted in a full cacheWrite instead of a cache hit.

Root cause recap: Anthropic generates tool IDs in the form toolu_01XYZ. The previous "strict" sanitization stripped underscores, and because the replacement IDs were derived by encounter order (createOccurrenceAwareResolver), repairToolUseResultPairing reordering messages after subagent turns produced different sanitized IDs each time → different cache prefix bytes → no cache hit.

Key observations from the review:

  • The implementation change is a clean one-liner; the comment is thorough and correct.
  • The downstream consumption site (attempt.ts:2299) already gates sanitization on sanitizeToolCallIds && toolCallIdMode, so both being false/undefined for Anthropic now short-circuits cleanly.
  • toolCallIdMode correctly falls back to undefined for Anthropic via the existing ternary chain.
  • Google, Mistral, and OpenAI-compat providers are unaffected.
  • Tests are updated correctly for both Anthropic and Bedrock cases.
  • Unverified assumption (flagged by the author): Bedrock Converse API is assumed to accept native Anthropic toolu_* IDs because it proxies Anthropic. This is a reasonable assumption but has not been confirmed with a live API call. If Bedrock rejects these IDs, the detection signal would be HTTP 400 errors mentioning invalid tool_use_id format, and the fix is a one-line revert.

Confidence Score: 4/5

  • Safe to merge; the change is minimal, well-reasoned, and tested — only the unverified Bedrock assumption warrants a small caveat.
  • The fix is logically sound and directly addresses the root cause. The one-line change is auditable end-to-end through the call chain, all 19 tests pass, and the rollback path is trivial. Score is 4 rather than 5 solely because the Bedrock Converse behavior with native toulu_* IDs has not been verified with a live API call, leaving a small but acknowledged production risk for Bedrock users.
  • No files require special attention beyond the Bedrock live-API assumption noted in the summary.

Reviews (1): Last reviewed commit: "fix(agents): skip tool-call ID sanitizat..." | Re-trigger Greptile

@Cypherm

Cypherm commented Mar 23, 2026

Copy link
Copy Markdown
Contributor Author

CI failures are unrelated to this PR:

  • checks (node, test): web-search-providers.test.ts expects Array(8) but gets Array(9) — a new bundled web search provider was added on main without updating the test baseline
  • check-additional: gates on check passing
  • Same failures present on main's latest CI run

Our change: exclusively in src/agents/transcript-policy.ts (+6/-2) and its test file. All 19 transcript-policy tests pass locally.

Happy to rebase once main stabilizes.

@Cypherm

Cypherm commented Mar 23, 2026

Copy link
Copy Markdown
Contributor Author

@steipete — Anthropic cacheWrite after subagents: order-dependent tool ID sanitization breaks cache prefix stability → skip sanitization for Anthropic (their API accepts native toolu_* IDs). 2 files, +10/-6. Closes #52612.

@Cypherm
Cypherm force-pushed the fix/anthropic-cache-tool-id-sanitization branch from ed4e4fe to d6ae4ce Compare March 23, 2026 06:47

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

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

// ID rewriting in createOccurrenceAwareResolver causes cache prefix instability
// after subagent turns (repairToolUseResultPairing can reorder messages, changing
// encounter order → different sanitized IDs → full cacheWrite). See #52612.
const sanitizeToolCallIds = isGoogle || isMistral || requiresOpenAiCompatibleToolIdSanitization;

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 Keep sanitization for cross-provider replayed tool IDs

This change disables tool-call ID rewriting for all Anthropic/Bedrock transcript paths, which breaks cross-provider replay cases where OpenAI Responses history contains IDs like call_123|fc_123 (see src/agents/pi-embedded-runner.openai-tool-id-preservation.test.ts). When a session switches from OpenAI to Anthropic, sanitizeSessionHistory no longer normalizes those IDs (and OpenAI-specific downgrade logic does not run on Anthropic APIs), so pipe-delimited IDs are forwarded as-is and can trigger tool_use.id request-format failures on the next Anthropic turn.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged. Cross-provider replay (OpenAI → Anthropic mid-session) is a valid edge case — pipe-delimited IDs like call_123|fc_123 from OpenAI history could be forwarded to Anthropic unsanitized. However, this scenario is distinct from the bug this PR fixes (#52612): native Anthropic sessions with subagents where the sanitization itself causes cache instability. The cross-provider case is pre-existing and unrelated to cache — happy to address it in a follow-up with more targeted sanitization (only sanitize non-toolu_* IDs).

@Cypherm
Cypherm force-pushed the fix/anthropic-cache-tool-id-sanitization branch from d6ae4ce to 851cbc9 Compare March 23, 2026 07:17

@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: 851cbc905e

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

// ID rewriting in createOccurrenceAwareResolver causes cache prefix instability
// after subagent turns (repairToolUseResultPairing can reorder messages, changing
// encounter order → different sanitized IDs → full cacheWrite). See #52612.
const sanitizeToolCallIds = isGoogle || isMistral || requiresOpenAiCompatibleToolIdSanitization;

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 Restore tool ID sanitization for Anthropic replayed history

Turning off sanitizeToolCallIds for Anthropic removes the only normalization that strips OpenAI call_id|fc_id separators during provider switches. In an OpenAI → Anthropic/Bedrock handoff, history can legitimately contain IDs like call_123|fc_123; sanitizeSessionHistory only runs downgradeOpenAIFunctionCallReasoningPairs when the current modelApi is OpenAI Responses, so Anthropic requests now forward these IDs unchanged and can hit tool_use.id format errors. Fresh evidence: src/agents/pi-embedded-runner.openai-tool-id-preservation.test.ts explicitly preserves pipe-delimited IDs when replayable reasoning metadata is present.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same concern as prior two replies — see above. Cross-provider replay is a pre-existing gap, not introduced by this PR. Happy to discuss if maintainers want a different approach.

@Cypherm
Cypherm force-pushed the fix/anthropic-cache-tool-id-sanitization branch from 851cbc9 to 54ba67f Compare March 23, 2026 09:23

@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: 54ba67f048

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

// ID rewriting in createOccurrenceAwareResolver causes cache prefix instability
// after subagent turns (repairToolUseResultPairing can reorder messages, changing
// encounter order → different sanitized IDs → full cacheWrite). See #52612.
const sanitizeToolCallIds = isGoogle || isMistral || requiresOpenAiCompatibleToolIdSanitization;

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 Re-enable Anthropic ID sanitization for provider switches

Removing isAnthropic from this gate means Anthropic/Bedrock turns no longer run tool-id normalization on replayed history, so sessions that started on OpenAI Responses can carry persisted call_id|fc_id IDs straight into Anthropic requests. src/agents/pi-embedded-runner.openai-tool-id-preservation.test.ts confirms those pipe-delimited IDs are intentionally preserved in history when reasoning metadata exists; without the previous Anthropic sanitization pass, these IDs can hit Anthropic tool_use.id pattern/format validation and fail the next turn. Fresh evidence: in the parent version of this line (c60a4fef^), isAnthropic was included in sanitizeToolCallIds, so this regression is introduced by this commit.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same concern as prior replies — see above.

@Cypherm
Cypherm force-pushed the fix/anthropic-cache-tool-id-sanitization branch from 54ba67f to 035b0b0 Compare March 23, 2026 14:05

@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: 035b0b0238

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

// ID rewriting in createOccurrenceAwareResolver causes cache prefix instability
// after subagent turns (repairToolUseResultPairing can reorder messages, changing
// encounter order → different sanitized IDs → full cacheWrite). See #52612.
const sanitizeToolCallIds = isGoogle || isMistral || requiresOpenAiCompatibleToolIdSanitization;

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 Restore Anthropic ID sanitization for cross-provider replay

Dropping isAnthropic from this gate means Anthropic/Bedrock requests no longer normalize historical tool IDs, so OpenAI Responses transcripts can now carry raw call_id|fc_id values (for example call_123|fc_123) directly into Anthropic turns. That format is intentionally preserved in history when reasoning metadata exists (src/agents/pi-embedded-runner.openai-tool-id-preservation.test.ts), and Anthropic tool_use.id validation does not accept the | separator, so model switches from OpenAI → Anthropic can fail with request-format errors instead of being repaired. Fresh evidence versus prior feedback: before this commit, this exact line included isAnthropic, so the Anthropic replay sanitization path existed and is removed here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same concern as prior replies — see above.

@Cypherm
Cypherm force-pushed the fix/anthropic-cache-tool-id-sanitization branch from 035b0b0 to ad5a7f6 Compare March 23, 2026 15:13

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

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

// ID rewriting in createOccurrenceAwareResolver causes cache prefix instability
// after subagent turns (repairToolUseResultPairing can reorder messages, changing
// encounter order → different sanitized IDs → full cacheWrite). See #52612.
const sanitizeToolCallIds = isGoogle || isMistral || requiresOpenAiCompatibleToolIdSanitization;

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 Restore tool-id sanitization for Bedrock replay paths

This gate now disables sanitizeToolCallIds for all bedrock-converse-stream requests, so a session that switches from OpenAI Responses to Bedrock can forward persisted IDs like call_123|fc_123 unchanged instead of normalizing them before replay. sanitizeSessionHistory only runs downgradeOpenAIFunctionCallReasoningPairs on OpenAI model APIs, so Bedrock turns no longer get a fallback rewrite and can fail with tool-use ID format errors on the next request. Fresh evidence versus prior thread feedback: the repo already models Bedrock as mixed Anthropic/non-Anthropic (see isAnthropicBedrockModel usage), so this blanket disable is broader than the Anthropic toolu_* cache-stability rationale.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same concern as prior replies — see above. Cross-provider replay normalization is a valid follow-up but orthogonal to this cache-stability fix. Happy to discuss further if maintainers want a different approach.

@Cypherm

Cypherm commented Mar 24, 2026

Copy link
Copy Markdown
Contributor Author

CI triage update: 3 remaining failures are upstream — same failures present on main.

Failing (upstream):

  • check (tsgo) — shared lint/type-check, not our files
  • checks-windows (shard 5) — flaky windows test, passes on other 5 shards
  • checks (node, channels) — channel tests, unrelated to transcript-policy

Our area all passes:

  • ✅ build-smoke — builds successfully
  • ✅ checks (node, test, 1/2) — includes transcript-policy.test.ts (19/19 pass)
  • ✅ checks (node, test, 2/2) — main test suite shard 2
  • ✅ checks (node, extensions) — extension tests
  • ✅ check-additional — all additional checks pass
  • ✅ checks-windows — 5/6 shards pass (shard 5 is the flaky one)

Our change: 2 files (transcript-policy.ts +6/-2, test +4/-4). All agent test suites pass.

@Cypherm
Cypherm force-pushed the fix/anthropic-cache-tool-id-sanitization branch from ad5a7f6 to 9913979 Compare March 24, 2026 08:12

@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: 9913979f19

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

// ID rewriting in createOccurrenceAwareResolver causes cache prefix instability
// after subagent turns (repairToolUseResultPairing can reorder messages, changing
// encounter order → different sanitized IDs → full cacheWrite). See #52612.
const sanitizeToolCallIds = isGoogle || isMistral || requiresOpenAiCompatibleToolIdSanitization;

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 Restore Anthropic/Bedrock tool ID replay sanitization

Removing isAnthropic from sanitizeToolCallIds disables tool ID normalization for Anthropic and Bedrock requests, so an OpenAI Responses session that preserved call_id|fc_id IDs can now carry those raw IDs into a provider switch and hit tool_use.id request-format errors instead of being repaired first. This is user-impacting in mixed-provider sessions because those pipe-delimited IDs are intentionally persisted for replay when reasoning metadata exists (src/agents/pi-embedded-runner.openai-tool-id-preservation.test.ts). Fresh evidence: in the parent revision (a1a226877bd913e070cf223d3272bf62d83683ed^), this same line still included isAnthropic, so this regression is introduced by this commit.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same concern as prior rounds — cross-provider replay (OpenAI→Anthropic pipe-delimited IDs) is a pre-existing edge case, not introduced by this PR. This PR fixes cache prefix instability caused by order-dependent sanitization of Anthropic's native toolu_* IDs. A follow-up targeting only non-toolu_* IDs during cross-provider replay would be the correct scope for that fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same concern as prior rounds — cross-provider replay (OpenAI→Anthropic pipe-delimited IDs) is a pre-existing edge case, not introduced by this PR. This PR fixes cache prefix instability caused by order-dependent sanitization of Anthropic's native toolu_* IDs. A follow-up targeting only non-toolu_* IDs during cross-provider replay would be the correct scope for that fix.

Anthropic generates tool IDs with underscores (toolu_01XYZ) that their API
accepts natively. The strict-mode sanitization stripped underscores, and the
order-dependent ID rewriting in createOccurrenceAwareResolver caused cache
prefix instability after subagent turns—repairToolUseResultPairing can reorder
messages between turns, changing encounter order and producing different
sanitized IDs for the same original tool call, triggering a full cacheWrite
instead of a cache hit.

Remove isAnthropic from the sanitizeToolCallIds flag so Anthropic and Bedrock
providers preserve their original tool IDs end-to-end.

Closes openclaw#52612
@Cypherm
Cypherm force-pushed the fix/anthropic-cache-tool-id-sanitization branch from 9913979 to 8d7c613 Compare March 25, 2026 04:10

@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: 8d7c613efc

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

// ID rewriting in createOccurrenceAwareResolver causes cache prefix instability
// after subagent turns (repairToolUseResultPairing can reorder messages, changing
// encounter order → different sanitized IDs → full cacheWrite). See #52612.
const sanitizeToolCallIds = isGoogle || isMistral || requiresOpenAiCompatibleToolIdSanitization;

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 Restore Anthropic replay tool-ID sanitization on provider switches

This change disables the only Anthropic/Bedrock-side rewrite that normalized persisted OpenAI Responses IDs, so sessions that switch providers can now forward call_id|fc_id values unchanged from history (those pairings are intentionally preserved in src/agents/pi-embedded-runner.openai-tool-id-preservation.test.ts). Anthropic tool-use IDs are pattern-constrained (alphanumeric plus _/-), so the | separator can cause request-format 400s on the first Anthropic follow-up turn. Fresh evidence: in the parent revision of this line, isAnthropic was part of the sanitization gate, and removing it here is what drops that normalization path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same concern as prior replies — see above.

@vincentkoc vincentkoc self-assigned this Apr 5, 2026
@vincentkoc

Copy link
Copy Markdown
Member

I validated this against current main and I do not trust this PR as the merge vehicle anymore.\n\nThe core problem with the patch is structural drift: bundled Anthropic/Bedrock replay policy no longer lives in for the real provider-owned path. Current main resolves that behavior through , , and , so this PR is modifying an older seam.\n\nI also did not reproduce the claimed root cause in a direct current-main harness with Anthropic-style unique ids: the replay prefix stayed byte-stable when I appended a later subagent turn and ran the same sanitize+repair pipeline. That does not prove the issue is impossible, but it does mean this PR's underscore-stripping explanation is not proven on today's code.\n\nClosing this PR as stale / wrong seam. If still reproduces on current main, please post a fresh repro with cache trace/session evidence and open a new narrow PR against the provider-owned replay-policy path, not the old fallback logic.

@vincentkoc vincentkoc closed this Apr 5, 2026
@vincentkoc

Copy link
Copy Markdown
Member

I validated this against current main and I do not trust this PR as the merge vehicle anymore.

The core problem with the patch is structural drift: bundled Anthropic/Bedrock replay policy no longer lives in src/agents/transcript-policy.ts for the real provider-owned path. Current main resolves that behavior through extensions/anthropic/replay-policy.ts, extensions/amazon-bedrock/register.sync.runtime.ts, and src/plugins/provider-replay-helpers.ts, so this PR is modifying an older seam.

I also did not reproduce the claimed root cause in a direct current-main harness with Anthropic-style unique toolu_* ids: the replay prefix stayed byte-stable when I appended a later subagent turn and ran the same sanitize+repair pipeline. That does not prove the issue is impossible, but it does mean this PR's underscore-stripping explanation is not proven on today's code.

Closing this PR as stale / wrong seam. If #52612 still reproduces on current main, please post a fresh repro with cache trace/session evidence and open a new narrow PR against the provider-owned replay-policy path, not the old fallback logic.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Full cacheWrite after using subagents (Anthropic)

2 participants