Skip to content

[Bug]: Base64 tool-result formatting creates nondeterministic temporary paths #3199

Open

Description

@liugy789

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 through DashScopeMultiAgentFormatter;
  • 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

  1. Create a ToolResultBlock containing an ImageBlock backed by a Base64Source.
  2. Add it to a tool-role Msg.
  3. Format the same Msg twice through DashScopeMultiAgentFormatter or GeminiMessageConverter.
  4. 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 AbstractBaseFormatter and GeminiMessageConverter;
  • 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

Environment

  • AgentScope-Java: main
  • Project version: 2.0.3-SNAPSHOT
  • Java: 17
  • OS: macOS

Activity

  1. liugy789 commented on Sep 18, 2026

    @liugy789
    ContributorAuthor

    I reproduced this issue on the current main branch and prepared a focused, API-compatible fix.

    The planned scope is:

    • derive a stable file identity from SHA-256 of the decoded media bytes;
    • keep materialized files inside a JVM-unique temporary directory;
    • centralize the materialization logic in MediaUtils;
    • reuse it from AbstractBaseFormatter and GeminiMessageConverter;
    • preserve the existing formatter method signatures and serialized text structure;
    • preserve stable historical request prefixes so providers can continue reusing prompt or prefix caches when their caching policies allow it;
    • safely handle concurrent publication, invalid files, symbolic links, and file systems without atomic moves;
    • add regression coverage for the shared formatter path and Gemini.

    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.

  2. liugy789 commented on Sep 18, 2026

    @liugy789
    ContributorAuthor

    The implementation is available in #3200.

    The pull request is based on main@594343c6ef29f26eea3cbbb2d6f92b1e5b9696de and 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.

  3. oss-maintainer commented on Sep 18, 2026

    @oss-maintainer
    Collaborator

    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

    1. agentscope-core/src/main/java/io/agentscope/core/formatter/AbstractBaseFormatter.java
      • convertToolResultToString (:204) dispatches ImageBlock/AudioBlock/VideoBlock/DataBlock to convertMediaBlockToTextReference (:245)
      • the Base64Source branch (:251-261) writes String.format("The returned %s can be found at: %s", mediaType, filePath)
      • saveBase64DataToTempFile (:294-312) does Files.createTempFile("agentscope_", extension) (:300) → Files.write (:306) → returns tempFile.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 calls formatter.format(messages)), so an unchanged Msg history yields different request bytes each call.
    2. agentscope-extensions/.../gemini/formatter/GeminiMessageConverter.java holds a private duplicate of the same helper (:341-359, createTempFile at :347), and its javadoc (:334) already states the file "will not be automatically deleted". GeminiChatFormatter builds this converter without the injected function, so it uses the duplicate.

    Scope of the affected / unaffected paths (more precise than the report)

    • Inheriting the base-class helper: DashScopeChatFormatter:60, DashScopeMultiAgentFormatter:73/323, AnthropicBaseFormatter:50, OpenAIBaseFormatter:61, OpenAIMultiAgentFormatter:85, GeminiMultiAgentFormatter:119 — all affected for Base64-backed tool-result media.
    • Not affected (base64 stays inline/in-memory, no temp file): 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 overrides convertToolResultToString without 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:

    • keep the agentscope_ prefix and the MIME-derived extension: GeminiMessageConverterTest:345-347 asserts both, and OllamaChatFormatter:338 parses the text with Pattern.compile("can be found at: ([^\\s\\n]+)"). Key the identity on bytes + mediaType/extension, not hash alone.
    • AbstractBaseFormatter.saveBase64DataToTempFile is protected, so keep it as a delegating method rather than removing it.
    • publication must tolerate FileAlreadyExistsException as success and validate NOFOLLOW_LINKS + regular file + content/size before trusting an existing target; ATOMIC_MOVE onto an existing file can fail on Windows, so a fallback path is needed (this also closes today's create→write partial-read window).
    • determinism is per-JVM by design, so the JVM-unique directory still grows across restarts; a retention story (shutdown-hook cleanup or 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 same Msg twice and assert byte-identical serialized output.

    Note: MediaUtils.java on main is 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

  4. added
    area/core
    bug
    on Sep 18, 2026
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

    area/corebug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions