Repository navigation
Description
Describe the bug
Formatting the same unchanged Msg history more than once can produce different serialized tool-result content when a ToolResultBlock contains Base64-backed media.
The confirmed affected paths are:
- tool-result stringification through
AbstractBaseFormatter, reproduced throughDashScopeMultiAgentFormatter; GeminiMessageConverter.
Before the fix, both paths materialized Base64 media with Files.createTempFile(...). Each formatting pass therefore created a new randomly named temporary file, and the absolute path became part of the serialized tool-result text.
The message history and decoded media bytes were unchanged, but the formatted provider request was different.
To Reproduce
- Create a
ToolResultBlockcontaining anImageBlockbacked by aBase64Source. - Add it to a tool-role
Msg. - Format the same
Msgtwice throughDashScopeMultiAgentFormatterorGeminiMessageConverter. - Compare the serialized tool-result output.
No external model or API credentials are required.
Expected behavior
Within the same running process, identical decoded media content and the same media type should produce the same materialized path and therefore the same formatted tool-result output.
Different decoded media content should continue to produce different materialized paths.
Actual behavior
Every formatting pass creates a new randomly named temporary file, even when the decoded media content has not changed.
Why this affects prompt and token caching
Prompt or prefix caching generally depends on a byte-identical input prefix. Appending a new user message or tool result at the end of an unchanged history can preserve the existing cached prefix.
Before this fix, the historical tool-result text itself contained a newly generated temporary path on every formatting pass. For example:
The returned image can be found at: /tmp/agentscope_123456.png
could become:
The returned image can be found at: /tmp/agentscope_987654.png
even though the decoded media bytes and the logical message history were unchanged.
This changes the serialized request at a historical position. For providers that use continuous prompt or prefix caching, the prefix before the changed path may remain reusable, but the suffix starting at the changed path can no longer match the previous cached prefix. If the changed tool result appears early in a long history, a larger portion of the request may lose cache reuse.
As a result:
- reported cached-input-token counts may decrease;
- more input tokens may be processed as uncached input;
- request latency and input-token cost may increase, depending on provider caching semantics;
- cache reuse becomes less stable across repeated formatting of the same message history.
The exact cache accounting and pricing behavior is provider-specific. This issue does not claim that every provider invalidates its entire cache or that every provider exposes the same cache-token fields.
Impact before the fix
- Unchanged message history produces different provider requests.
- A historical prefix changes even when the logical message content is unchanged.
- Provider-side prompt or prefix cache reuse may be reduced from the changed path onward.
- Cached input-token counts may decrease while more input tokens are processed as uncached input.
- Depending on provider behavior, request latency and input-token cost may increase.
- Repeated formatting creates redundant temporary files.
- Replays and debugging are less reproducible because the serialized tool-result text changes between formatting passes.
Scope
This issue is confirmed for the specific tool-result stringification paths described above. It does not imply that every provider or every multimodal tool-result path is affected.
Proposed fix and expected impact after the fix
The accompanying fix:
- derives the target identity from SHA-256 of the decoded media bytes;
- keeps materialized files inside a JVM-unique temporary directory;
- derives a sanitized extension from the MIME type;
- publishes complete staging files before exposing the deterministic target;
- validates existing targets and rejects symbolic links, non-regular files, and mismatched content;
- reuses the shared materialization logic from
AbstractBaseFormatterandGeminiMessageConverter; - preserves existing formatter method signatures and serialized text structure.
After the fix, formatting unchanged Base64-backed tool-result media repeatedly within the same JVM reuses the same materialized path, so the serialized tool-result text remains stable. This preserves the opportunity for providers with prompt or prefix caching to reuse the same historical prefix.
Different decoded content produces a different content-addressed target.
The fix does not guarantee cache hits, because cache policy, cache boundaries, minimum prefix lengths, expiration, and billing semantics remain provider-specific.
The deterministic guarantee is intentionally process-local. The per-process directory is not automatically cleaned up, and invalid existing targets fail closed rather than being overwritten.
Official references
- Java
Files.createTempFile: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html#createTempFile(java.lang.String,java.lang.String,java.nio.file.attribute.FileAttribute...) - Gemini context caching and similar request prefixes: https://ai.google.dev/gemini-api/docs/generate-content/caching?hl=en
Environment
- AgentScope-Java:
main - Project version:
2.0.3-SNAPSHOT - Java: 17
- OS: macOS
Activity
liugy789 commentedon Sep 18, 2026
I reproduced this issue on the current
mainbranch and prepared a focused, API-compatible fix.The planned scope is:
MediaUtils;AbstractBaseFormatterandGeminiMessageConverter;Temporary-file TTL, global cleanup scheduling, cross-process path determinism, provider-specific cache-control protocols, and broader multimodal protocol changes will remain out of scope.
I will submit a focused pull request after this issue is recorded and the final CI verification is available.
liugy789 commentedon Sep 18, 2026
The implementation is available in #3200.
The pull request is based on
main@594343c6ef29f26eea3cbbb2d6f92b1e5b9696deand contains the focused formatter/media-materialization fix described above. Its CI checks are now running; the PR records the local verification results and the remaining environment-level test-runtime limitation.oss-maintainer commentedon Sep 18, 2026
Issue Evaluation: confirmed
Verified against
main(dc15ff42c, 2.0.4-SNAPSHOT) by reading the actual code paths, not just the report.Root cause — confirmed on both reported paths
agentscope-core/src/main/java/io/agentscope/core/formatter/AbstractBaseFormatter.javaconvertToolResultToString(:204) dispatchesImageBlock/AudioBlock/VideoBlock/DataBlocktoconvertMediaBlockToTextReference(:245)Base64Sourcebranch (:251-261) writesString.format("The returned %s can be found at: %s", mediaType, filePath)saveBase64DataToTempFile(:294-312) doesFiles.createTempFile("agentscope_", extension)(:300) →Files.write(:306) → returnstempFile.toAbsolutePath()(:311)So a fresh random absolute path is produced on every formatting call and it lands inside the serialized tool-result text. Formatters are stateless and re-run per request (e.g.
DashScopeChatModel.java:301 callsformatter.format(messages)), so an unchangedMsghistory yields different request bytes each call.agentscope-extensions/.../gemini/formatter/GeminiMessageConverter.javaholds a private duplicate of the same helper (:341-359,createTempFileat :347), and its javadoc (:334) already states the file "will not be automatically deleted".GeminiChatFormatterbuilds this converter without the injected function, so it uses the duplicate.Scope of the affected / unaffected paths (more precise than the report)
DashScopeChatFormatter:60,DashScopeMultiAgentFormatter:73/323,AnthropicBaseFormatter:50,OpenAIBaseFormatter:61,OpenAIMultiAgentFormatter:85,GeminiMultiAgentFormatter:119 — all affected for Base64-backed tool-result media.GeminiMediaConverter:111-112,DashScopeMediaConverter:71-75/124-128,AnthropicMediaConverter:66-72/129-135,OpenAIMessageConverter:199-206/274-276,OllamaMediaConverter:53-55. Ollama's tool-result path also overridesconvertToolResultToStringwithout media materialization (OllamaMultiAgentFormatter:460-476).Impact: loses provider-side prompt/prefix-cache reuse from the changed path onward, makes record/replay and golden tests order-dependent, and leaks one undeleted temp file per media block per formatting call. No crash or data corruption — the semantic content is unchanged, only the path string.
On the proposed fix (
MediaUtils-shared, SHA-256 content-addressed name under a JVM-unique temp dir, atomic publish, validate existing target). The direction is minimal and backward compatible; four concrete points worth pinning down:agentscope_prefix and the MIME-derived extension:GeminiMessageConverterTest:345-347 asserts both, andOllamaChatFormatter:338 parses the text withPattern.compile("can be found at: ([^\\s\\n]+)"). Key the identity on bytes + mediaType/extension, not hash alone.AbstractBaseFormatter.saveBase64DataToTempFileisprotected, so keep it as a delegating method rather than removing it.FileAlreadyExistsExceptionas success and validateNOFOLLOW_LINKS+ regular file + content/size before trusting an existing target;ATOMIC_MOVEonto an existing file can fail on Windows, so a fallback path is needed (this also closes today's create→write partial-read window).deleteOnExit) should be stated explicitly rather than left implicit.Existing tests hide the nondeterminism rather than assert it: ground-truth tests regex-normalize the line to
<TEMP_FILE>(GeminiChatFormatterGroundTruthTest:184,GeminiMultiAgentFormatterGroundTruthTest:314,DashScopeMultiAgentFormatterGroundTruthTest:846,DashScopeChatFormatterGroundTruthTest:641). A regression test should format the sameMsgtwice and assert byte-identical serialized output.Note:
MediaUtils.javaonmainis only a file/URL → base64 utility (fileToBase64:91,downloadUrlToBase64:113,urlToBase64DataUrl:233); there is no base64 → deterministic-file helper yet, so the shared home proposed in the report does not exist today.Next step: the reporter already opened #3200 (
main@594343c6, all current checks green) whose scope matches the analysis above, so no separate fix proposal is generated for this issue — that would only duplicate the existing PR. Review of #3200 is handled by the PR-review workflow. Maintainers may want to decide explicitly on the two open design points (per-JVM vs cross-restart path stability, and temp-dir retention) before merge.Automated evaluation by github-manager-bot