Skip to content

go: deepseek-v4.1-flash prompt cache regresses to the first image whenever a new image is added #51993

Closed as not planned

Description

@woc621

Description

On OpenCode Go, when a deepseek-v4.1-flash session gains a new image (user attachment or read tool result), that one request's prompt cache only matches up to the first image already in the conversation; the first image and everything after it are re-processed as uncached input. The next request recovers.

The prefix sent is byte-identical to the previous request except for the appended message (verified by capturing the request bodies), and the same regression reproduces with raw HTTP replays against https://opencode.ai/zen/go/v1/chat/completions and on V1 1.18.33, so I believe this is gateway/model-side. That said:

  • ~1 KB test images did not reproduce it; 860 KB PNGs (1500x950) reproduce reliably.
  • A minimal direct probe (small system prompt, no tools) showed only partial matches; the trigger condition on the gateway side is not fully mapped.

Raw gateway replay of captured payloads, prompt_tokens / cached_tokens:

text         10170 / 384
+ image A    11038 / 10112
text         11051 / 11008
+ image B    11920 / 10112   <- cache regresses to the first-image boundary
text         11933 / 11904

Same shape on V2 2.0.10 and V1 1.18.33 (V1: previous prompt 8830, cache read 7808 on the image-B request).

Real impact: in a long session the cache read stays pinned at the first image's position whenever a new image is read; I observed 57k-84k tokens re-read per new image (boundaries at 48,768 and 24,576).

Related but not duplicates: #41093 (Kimi K3, caching stops entirely instead of one-request regression), #51985 (Anthropic image trimming), #50258 / #42935 (Go cache drops with no image trigger).

Plugins

Local skill-tracker + huaweicloud plugin config; not involved - the raw HTTP reproduction does not use the client.

OpenCode version

2.0.10 (also reproduced on 1.18.33)

Steps to reproduce

  1. opencode run -m opencode-go/deepseek-v4.1-flash "Reply with exactly: hi" (new session).
  2. Continue with an image: -f big_a.png "Describe this image in 3 words." (1500x950 PNG, ~860 KB).
  3. Continue with text only, so the image prefix gets cached: "Reply with exactly: ok".
  4. Continue with a second image: -f big_b.png "Describe this new image in 3 words.".
  5. Inspect per-request tokens: the step-4 cache.read drops back to the pre-image value (10,112) instead of covering step 3's prompt (11,051).

Screenshot and/or share link

No share link. Captured request bodies and the test images are saved locally and can be attached if useful.

Operating System

Linux 6.8.0-106-generic x86_64

Terminal

Headless opencode run CLI (no TTY)

Activity

  1. added
    needs:compliance
    and removed
    needs:compliance
    on Sep 29, 2026
  2. github-actions commented on Sep 29, 2026

    @github-actions
    Contributor

    Thanks for updating the issue with the required description and reproduction details!

  3. woc621 commented on Sep 30, 2026

    @woc621
    Author

    Update: the regression looks gateway-side, not upstream — identical payloads behave correctly on the DeepSeek API.

    I replayed the same captured request bodies (same system prompt, tools, messages, image bytes) against two endpoints.

    1. https://opencode.ai/zen/go/v1/chat/completions (fresh session affinity):
    req  text        prompt=10178 cached=10112
    req  +image A    prompt=11046 cached=10112
    req  text        prompt=11059 cached=11008
    req  +image B    prompt=11928 cached=10112   <- regresses to the first-image boundary
    req  text        prompt=11941 cached=11904
    
    1. https://api.deepseek.com/chat/completions (deepseek-flash), same payload content:
    req  text        prompt=10171 hit=0
    req  +image A    prompt=11039 hit=10112
    req  text        prompt=11052 hit=10880
    req  +image B    prompt=11921 hit=11008   <- matches through image A, no regression
    req  text        prompt=11934 hit=11776
    

    Same result when the images are referenced through the DeepSeek Files API ({"type":"file","file_id":...}): no regression.

    The Go response headers for the affected route:

    x-opencode-endpoint-id: orcarouter-dsv4.1flash
    x-opencode-upstream-model-id: deepseek/deepseek-v4.1-flash
    

    For reference, file_id cannot be used through the Go gateway at all: GET /v1/files returns 404, and a {"type":"file","file_id":...} content block returns 422 Upstream request failed: Endpoint is unavailable.

    So the cache loss appears specific to the gateway's handling of image content on this route, while the upstream API caches image prefixes correctly.

  4. Dante-dan commented on Oct 1, 2026

    @Dante-dan
    Contributor

    I traced the checked-in Console request path at 02c3891. There is a useful boundary to check before changing the client:

    • The Go chat route enters as oa-compat. If the selected provider is also oa-compat, the body converter returns the body unchanged, and the provider helper only adds streaming usage options. It does not fetch or re-encode the images.
    • The handler still applies the configured model/payload overrides and passes session affinity downstream. The actual provider format and overrides come from deployment configuration. On a same-format response, the reported cache usage is passed through; the accounting normalizer is not what changes the raw cached_tokens in your replay.

    Could the gateway maintainers compare the outbound message/image prefix hashes for the text-after-A and image-B requests on orcarouter-dsv4.1flash, and confirm the deployed revision/provider format? That would distinguish Console conversion/configuration from downstream image preprocessing/cache-key behavior. Only sanitized hashes and the relevant non-secret configuration are needed; please do not post API keys or the full provider configuration.

    One deployment clue: this revision's Console handler forwards only content-type and cache-control response headers, whereas your replay returned x-opencode-endpoint-id. I have not reproduced the live failure, so the checked-in path may differ from the deployed route that served your requests.

  5. hugobatista commented on Oct 1, 2026

    @hugobatista

    Reproduced on 2.0.21 (Linux, opencode-go/deepseek-v4.1-flash). One correction that may save a threshold hunt: image size is not a factor.

    The report notes "~1 KB test images did not reproduce it". I get a regression at every size, down to a 1,047-byte PNG. One growing session, tool-less agent, two warm-up text turns:

    step input cache.read total
    +1k (1,047 B) 212 7424 7636 boundary
    text 120 7552 7672 recovered
    +64k (65,825 B) 493 7424 7917 regression → 7424
    text 135 7808 7943 recovered
    +256k (266,266 B) 742 7424 8166 regression → 7424
    text 117 8064 8181 recovered
    +860k (883,017 B) 967 7424 8391 regression → 7424
    text 106 8320 8426 recovered

    cache.read returns to exactly the first-image boundary on every image entry, and the whole suffix after that boundary is re-billed. A 15x15 PNG is enough, so cropping or downscaling does not avoid it.

    Reproduction — repro.py attached. No captured payloads needed: opencode run plus per-step counters read from the opencode DB. It generates a byte-accurate size ladder (noise PNGs, binary-searched on edge length), runs a tool-less agent, warms up two text turns, and prints the table above.

    python3 repro.py opencode-go/deepseek-v4.1-flash

    Requires opencode, ImageMagick's convert, and read access to opencode.db. One integration note: opencode run resolves the project from $PWD, so the subprocess needs env={**os.environ, "PWD": WORK} — cwd= alone is not enough and the custom agent is not found.

    Impact on a real session (1000 requests, ~560k context, 48 images over ~2.5h): 17 of those requests carried ~2.33M re-processed tokens — 31% of total spend — at ~$0.035 per image read versus ~$0.0025 for a normal request, TTFT 10.2s versus 4.3s. The cost scales with session length, since the re-processed suffix is everything after the first image.

    note: Running the same probe and the same client against deepseek/deepseek-flash directly (api.deepseek.com) shows no regression — cache.read advances monotonically across image entries (7424 → 7680 → 7808 → 8064) where the Go gateway pins it at 7424.

    repro.py

  6. Dante-dan commented on Oct 2, 2026

    @Dante-dan
    Contributor

    The 1,047-byte case rules out an image-size threshold; resizing would not address the boundary you measured.

    There is also a correction to my earlier source comparison. On current dev at a79ecfe, the handler first tries proxyInference. New Console keys and eligible migrated legacy keys route Go chat requests to /go/openai/v1/chat/completions at the configured inference destination. That proxy returns the downstream response directly, so the x-opencode-endpoint-id header can be consistent with this checked-in path; my earlier comparison covered the older legacy handler.

    The proxy's prepared-body stream replaces the top-level model value and replays the remaining bytes, with usage-option insertion disabled on this path. It does not decode or re-encode the images. The remaining distinction is which route/revision actually served the failing requests and whether the inference destination changes the existing image prefix or its cache key. Correlating the image-B request and the following text request at that boundary would resolve that distinction; the local DB counters alone cannot show it.

    I read the attached probe but have not run the live model requests. This source comparison does not establish which revision your endpoint deployed.

  7. hugobatista commented on Oct 2, 2026

    @hugobatista

    You asked for the image-B request and the text request after it correlated on the wire, and said the local DB counters cannot show it. I ran a local proxy to get the API's own numbers. The counters were fine: for all ten steps, usage.prompt_tokens and prompt_tokens_details.cached_tokens from the response are identical to what opencode stored in its database. The gateway really does return the cache back at the first image boundary.

    Then the same requests, replayed, stopped doing it.

    step prompt cached, via the client cached, same bodies replayed
    warm up 1 7437 0 0
    warm up 2 7494 7424 7424
    +1k 7697 7424 7680
    text 7788 7680 7680
    +4k 7991 7424 7936
    text 8008 7936 7936
    +16k 8211 7424 8192
    text 8245 8064 8192
    +64k 8448 7424 8448
    text 8491 8448 8448

    Identical prompt_tokens at every step, so these are the same bodies. The replay also used the client's own headers, the client's own session id, the client's own 5 second pacing, and it ran through the same route minutes later. x-opencode-endpoint-id was orcarouter-dsv4.1flash on all thirty steps, client and replay alike.

    So none of these explain the difference: payload, headers, session id, pacing, route, model and image size are all held constant between a regressing run and a clean one.

    I cannot point at anything else from outside. The endpoint header does not predict the outcome. It reads orcarouter-dsv4.1flash on the regressing run and on both clean replays, and the raw regression earlier today reads novita-deepseek. Two ids have regressed and one id has done both, so the header is not identifying whatever differs between these runs.

    Which leaves your logs as the only place left to check. log/endpoint-node-evidence.json has the log_id of every step of all three runs: two sets of identical bytes, one regressing and one clean. Whatever the difference is, it has to be visible there.

    Two supporting observations:

    • Raw replays of my own synthetic bodies regressed 3 times inside about 90 seconds at 14:54, then twenty consecutive clean ladders in the half hour after that, across both routes and both novita-deepseek and orcarouter-dsv4.1flash. Same bytes, same headers, opposite results, minutes apart. - The client path regressed in every session I ran today, 6 of 6. So this is not hard to hit through the client, even while my own replays stay clean.

    Shapes do not matter. All three regressed in that window: standalone image, text and image in one user message, and the hoisted tool-result form. Size does not matter either, unchanged from my last comment: 1 kB regresses like 860 kB.

    Files attached

    file what it is for
    gorepro.py the probe, Python 3 + stdlib, generates its own image ladder
    log/endpoint-node-evidence.json the table above, all three runs, log_id per step
    log/transcript-cli-1790952361.json the regressing client run, second column
    log/transcript-go-tool-1790949366.json a raw regression at 14:56, one of the three in that window
    log/transcript-go-tool-1790950026.json the same bodies, same route, 11 minutes later, clean

    Repro

    python3 gorepro.py go tool    # raw HTTP, tool-result shape
    python3 gorepro.py matrix     # raw matrix
    python3 gorepro.py cli        # same ladder through opencode run

    Needs an opencode-go key in ~/.local/share/opencode/auth.json. Headers: Authorization, Content-Type, x-opencode-session, any real User-Agent. Nothing else required. Authorization is never printed or saved, and each run self-checks its own output.

    Session impact is unchanged: ~2.33M re-processed tokens over 17 image-carrying requests, 31% of that session's spend.

    endpoint-node-evidence.json
    transcript-cli-1790952361.json
    transcript-go-tool-1790950026.json
    transcript-go-tool-1790949366.json

    gorepro.py

  8. hugobatista commented on Oct 2, 2026

    @hugobatista

    then twenty consecutive clean ladders in the half hour after that

    confirmed that this is warmed cache with the prefix. when adding nonce on the beginning of the session, i could reproduce the same behavior than cli, and cache regression.

  9. Dante-dan commented on Oct 2, 2026

    @Dante-dan
    Contributor

    The nonce result explains the clean replay comparison: it had already warmed the image-bearing prefix, rather than demonstrating a different client code path.

    There is a concrete sign of that in endpoint-node-evidence.json: at step 4, the preceding request has 7,788 prompt tokens, but the clean replay reports 7,936 cached tokens; at step 8 it reports all 8,448 prompt tokens cached. Those hits extend into the newly appended request itself. The attached gorepro.py also uses a deterministic preamble; a new session UUID alone does not make that prefix cold.

    For operator tracing, step 4 is particularly useful: first execution 1c2ba98f-fca4-436b-9468-97698cec48bf drops to 7,424; following text cdd75aee-f780-4949-b415-fb7176f67a42 recovers to 7,936; same-session replay 128eb3b8-50c8-43b8-ad04-90dbc9eeb583 already hits 7,936. The comparison now needs to account for cache state before those requests, not just matching bodies and route headers.

    This narrows the failure to first-seen image-bearing prefixes on the Go path. It does not yet establish whether downstream image preprocessing, cache insertion, or cache selection causes it. I have not run live model requests.

  10. Kaikaikaifang commented on Oct 10, 2026

    @Kaikaikaifang

    Independent corroboration: a controlled image-position test reproduces this on OpenCode Go, but not on the official DeepSeek API.

    We tested a fixed synthetic conversation containing approximately 29.5k–30.2k input tokens and deterministic 1024×1024 PNGs. The two variants differed only in the order of the first user message's content parts:

    1. Image A, then the long text.
    2. The same long text, then image A.

    For each variant, we repeated the baseline, appended text, appended the same image, and appended a different image. Each extension started from exactly the same fixed baseline history; model-generated responses were not fed back into later requests.

    Results

    Numbers below are cached input tokens / total input tokens.

    Request Go: image before text Go: text before image Official DeepSeek: image before text Official DeepSeek: text before image
    Identical baseline repeat 29,440 / 29,499 29,440 / 29,498 29,312 / 29,499 29,312 / 29,498
    Append text 29,440 / 29,512 29,440 / 29,511 29,312 / 29,512 29,312 / 29,511
    Append the same image 0 / 30,164 28,672 / 30,163 29,440 / 30,164 29,440 / 30,163
    Repeat same-image request 30,080 / 30,164 30,080 / 30,163 29,952 / 30,164 29,952 / 30,163
    Append a different image 0 / 30,164 28,800 / 30,163 29,440 / 30,164 29,440 / 30,163
    Repeat new-image request 30,080 / 30,164 30,080 / 30,163 29,952 / 30,164 29,952 / 30,163

    On Go, appending either the same or a different image invalidated reuse of the long text after the first image, while placing that text before the first image preserved approximately 95% cache reuse. Identical repeats recovered to approximately 99.7%.

    On the official DeepSeek endpoint, both content orders preserved approximately 97.6% reuse when an image was appended. The position-dependent regression did not reproduce there.

    Controls

    • Wire model ID: deepseek-flash.
    • OpenAI-compatible Chat Completions.
    • Thinking enabled, effort max.
    • Maximum output: 256 tokens per request.
    • Zero retries.
    • Public Pi provider adapters, with a Pi User-Agent.
    • Stable x-opencode-session within each Go experiment.
    • Separate sessions between experiments; we do not assume that a new session guarantees a cold content cache.
    • A read-only serialization observer confirmed unchanged baseline message prefixes, stable request options, and identical payload fingerprints for repeated requests.
    • All inputs were synthetic. No repository source, application transcripts, or customer data were sent.
    • Each endpoint completed two eight-request groups successfully.

    The long input was ordinary text, not historical reasoning_content; reported input usage confirmed that it actually entered the context.

    Interpretation and limitations

    This supports the first-image-boundary behavior described in this issue and provides an image-position control. It does not identify the internal cause—multimodal preprocessing, cache insertion/selection, or the deployed service path.

    The Go and direct tests were separate runs/accounts, and we have not established that their backend revisions were identical. We also did not capture upstream routing identifiers, so we cannot attribute our result to a particular upstream.

    Could the team confirm which backend revision serves deepseek-flash on Go, and whether there is an officially supported request format that preserves multimodal prefix reuse without reordering or dropping historical observations?

  11. yingzhi0808 commented on Oct 10, 2026

    @yingzhi0808

    Independent reproduction — same shape, quantified per-turn

    Environment: macOS; pi coding agent driving Figma through a plugin bridge; model opencode-go/deepseek-v4.1-flash; one session on 2026-10-10 with 246 assistant turns. The images entering that session are inline PNG previews of Figma nodes (typically 30–200 KB base64 each): 51 image blocks / 6.3 MB in total.

    Method: parsed the session's own usage log (per-request input / cacheRead) and bucketed every assistant turn by "did the request append a new image since the previous assistant turn".

    new images since previous request | turns | avg cache hit | avg fresh (re-billed)
    0                                 |  181  |     94.8%     |   14k
    1                                 |   39  |     33.1%     |  234k
    

    Restricted to requests whose total context was over 250k tokens:

    no new image |  96 turns | 94.1% hit | 371k ctx |  22k re-billed
    new image    |  32 turns | 28.7% hit | 384k ctx | 272k re-billed
    

    On the image-bearing requests the cache read pins to the same few boundaries as in your report — 99,712 / 99,200 / 38,272 (also 25,088 / 36,864) — consistent with regressing to the first-image position and recovering on the next request. Across the session, ~9.1M of the 11.78M fresh input tokens (77%) came from those 39 image turns.

    Two notes:

    Happy to share the bucketing script or the raw per-turn dump if that helps.

  12. fwang commented on Oct 11, 2026

    @fwang
    Contributor

    can someone share the session id for a session with this issue?

  13. hugobatista commented on Oct 11, 2026

    @hugobatista

    ses_eca71fcac0674ae484acbad676

  14. echopharmsu commented on Oct 12, 2026

    @echopharmsu

    Confirming this from a real long-running session (not a synthetic replay), and adding a second,
    distinct cache-loss pattern I think belongs to #50258 / #42935 instead.

    Environment: a third-party harness (DeepSeek Harness) calling https://opencode.ai/zen/go/v1,
    model deepseek-v4.1-flash, requests carry x-opencode-session. Numbers below are taken from the
    client's own per-request session records (input_tokens, cache_read_tokens), no raw capture needed.

    1) Image-triggered regression — matches your description exactly (partial loss, fixed boundary)

    Session: 151 model requests, 22 image content blocks (user screenshots, 17 KB–707 KB PNGs).
    7 of 151 requests account for 82% of ALL uncached input in the session. In 5 of those, the cache read
    is pinned at a constant value while uncached input grows with context:

    #116  uncached 234,090  cached 249,856  (51.6% hit)
    #122  uncached 245,379  cached 251,136  (50.6%)
    #125  uncached 255,327  cached 251,136  (49.6%)
    #128  uncached 260,501  cached 251,136  (49.1%)
    #135  uncached 279,437  cached 251,136  (47.3%)
    

    251,136 and 249,856 are both multiples of 64. All five bursts occur 1–2 log events after an
    image-bearing message
    , and the following request recovers to 99%+ — i.e. the same
    "regresses to the first image boundary, next request recovers" shape you documented.
    Our images are 17 KB–707 KB, consistent with your "~1 KB did not reproduce, 860 KB reliably does".

    2) Separate pattern: idle gap, not an image (probably #50258 / #42935)

    Binning requests by the gap since the previous request, same session set:

    gap e3cecbf6 (545 reqs) 0002f22b (1400 reqs)
    ≤10s 97.6% 95.3%
    10–60s 97.5% 95.4%
    1–5min 99.2% 93.0%
    5–30min 99.0% 89.4%
    30–60min 66.4% (n=3) 92.5%
    >2h 0.1% (n=3) 18.1% (n=11, 9/11 requests <60%)

    Here the cache read collapses to ~0 instead of sitting at a fixed boundary, so it looks like plain
    eviction rather than the image regression. A control session with no images and no gap >30 min
    stayed at 98.4%+ across every bucket, with ~1.5k uncached tokens per request on average.

    Happy to share the per-request tables or the session logs if useful.

  15. opencodejr commented on Oct 28, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report and the raw HTTP replays. They make it clear that each new image makes the prompt cache fall back to the first image's position for one request, and that you are billed for that extra uncached input on OpenCode Go.

    Your replays send byte-identical prefixes straight to https://opencode.ai/zen/go/v1/chat/completions, and the same thing happens on both v1 and v2. So this looks like OpenCode Go gateway or provider behaviour, not something the OpenCode app can change. OpenCode Go and inference billing are handled by the team through support, not GitHub issues. Please email [email protected] with these details. The captured request bodies and the ~860 KB test images would be especially useful. If you have already emailed, the team will get to it, especially now that we have seen it here.

    Please keep account details, email addresses and any payment information out of this public issue and put them only in the email.

    Related issues you mentioned, for reference:

    The bot will close this issue in 1 day.

  16. opencodejr commented on Oct 29, 2026

    @opencodejr
    Contributor

    Closing this now. OpenCode Go gateway and billing questions, including this prompt-cache regression, are handled by email rather than in GitHub issues. Thanks again for the detailed replays, @woc621. If anything is still open, please email [email protected] and include your captured request bodies and test images. Please keep account and payment details out of this public thread.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions