[Bug Report] google-vertex/global Implicit Caching: Retroactive 30k–38k Prefix Eviction & Multi-Turn Replica Thrashing When input_audio Enters Conversation History
Overview & Multimodal Message Structure
We ran two controlled multi-turn benchmarks (Test A and Test B) on google-vertex/global (with sticky session_id) to test how Vertex AI’s implicit context cache handles a standard production chat harness that injects a small dynamic runtime context block (~100–200 tokens) into the text part of only the latest user message (Turn N), stripping that dynamic block from Turn N when Turn N+1 is sent.
Because multimodal attachments (image_url / input_audio) are appended as content parts after the user’s text content part, the structure of Turn N on the wire is:
- In
Test A(Dynamic Block at END of User Text):
[User Text] + [Dynamic Block (<200 tok)] + [Audio/Image Part (when present)]- For text-only messages, stripping
[Dynamic Block]onTurn N+1removes tokens only from the very end ofTurn N, so zero historical tokens shift position. - For audio messages (
#28), stripping[Dynamic Block]onTurn N+1shifts theinput_audiopart left by<200tokens at boundaryK, while leaving all prior history0..K(~71.5ktokens) 100% byte-identical.
- For text-only messages, stripping
- In
Test B(Dynamic Block at START of User Text):
[Dynamic Block (~200 tok)] + [User Text] + [Audio/Image Part (when present)]- Stripping
[Dynamic Block]onTurn N+1shiftsTurn N’s content (whether text, image, or audio) left by~200tokens at boundaryK, while leaving all prior history0..K100% byte-identical.
- Stripping
Key Finding: Apples-to-Apples Modality Comparison at Boundary K
When [Dynamic Block] is stripped at token offset K on Turn N+1 (leaving tokens 0..K 100% untouched):
- Shifted TEXT (
Test B #10): Vertex preserves 100% of the prior cache0..K(31.1kand36.8k), re-prefills only the shifted text block once, and serves the full new prefix from cache on the very next turn. - Shifted IMAGE (
Test B #40): Vertex preserves 100% of the prior cache0..K(58.2k) and serves the image prefix (59.3k) on the very next turn. - Shifted AUDIO (
Test A #28,Test B #24,Test B #44): Instead of preserving the untouched prefix0..K, shifting aninput_audioblock left by<200tokens causes Vertex to retroactively evict 11,000 to 38,000+ tokens of untouched prior text history beforeK, drop to0cached tokens (Test B #31), thrash across backend replicas on subsequent 1-token.messages, and poison subsequent large text appends (Test B #64).
(Note: Across all logs below, Vertex maintains a standard ~2,062-token uncached tail window, so a “100% clean cache hit” on an input of X tokens reports Cached ≈ X - 2,062.)
Test A: [User Text] + [Dynamic Block (<200 tok)] + [Audio (when present)]
1. Expected Behavior (Verified on Pure Text #16, #20, #38)
- Because
[Dynamic Block]is at the very end of pure-text messages, stripping it onTurn N+1(inside Vertex’s2,062-token uncached tail window) never shifts the text. - Appending
+13.5ktext (#16) or+26.6ktext (#38) preserves 100% of the existing cache on the initial turn (#17/#39) and immediately serves the new text from cache on the very first follow-up turn (#19hits42.8k / 44.9k;#41hits99.4k / 101.4k).
2. What SHOULD Have Happened vs. What ACTUALLY Happened at #28 (+3.2k Audio Append)
- Before
#28, the pure-text conversation is sitting cleanly atIn: ~71.5k | Cached: ~69.5k(#27). - At
#28, the user message is[User Text (".")] + [Dynamic Block (<200 tok)] + [input_audio (~3.2k tok)], starting at token offset~71.5k. - On
#29(when#28is sent), Vertex hits the existing text cache (Cached: ~69.5k) and prefills[Dynamic Block] + [input_audio]. - On
#31(a 1-token.ping 20 seconds later),[Dynamic Block]inside#28is stripped, shifting#28’s3.2k-tokeninput_audiopart left by<200tokens to offset~71.5k. All~71.5ktokens of prior text history (#1..#27) before#28are 100% untouched and byte-identical. - Expected: Just like shifted text (
Test B #13,#21) and shifted images (Test B #43),#31should have preserved the entire~69.5k-token prior text cache and only re-prefilled the3.2k-token audio clip. - Actual Bug: On
#31, Vertex retroactively evicted ~38,200 tokens of completely untouched prior text history (31.3k..69.5k), collapsingCachedfrom~69.5kall the way back to the System Prompt (~31.3kcached tokens) before recovering to~72.7kon#33.
#15 | t+00:00s | In: ~31.4k tokens | Cached: ~29.4k | (Baseline System Prompt + short turns)
--- [User #16: Appends +13.5k tokens of TEXT (Dynamic block after text)] ---
#17 | t+00:10s | In: ~44.9k tokens | Cached: ~29.4k | <-- Expected: hits prior cache, prefills #16
#19 | t+00:17s | In: ~44.9k tokens | Cached: ~42.8k | <-- Expected: next turn immediately caches #16!
--- [User #20: Appends +26.5k tokens of TEXT (Dynamic block after text)] ---
#21 | t+00:32s | In: ~71.3k tokens | Cached: ~42.7k | <-- Preserves 100% of prior 42.8k cache
#23 | t+00:39s | In: ~71.5k tokens | Cached: ~42.9k |
#25 | t+00:48s | In: ~71.5k tokens | Cached: ~69.5k | <-- Locks in 69.5k cached
#27 | t+00:59s | In: ~71.5k tokens | Cached: ~69.5k |
--- [User #28: Appends +3.2k tokens of AUDIO (Text + Dynamic block + Audio); #30..#36 are 1-token "." pings] ---
#29 | t+01:51s | In: ~74.8k tokens | Cached: ~69.5k | <-- Turn of audio: hits 69.5k text cache
#31 | t+02:11s | In: ~74.8k tokens | Cached: ~31.3k | <-- BUG: Stripping dynamic block at 71.5k EVICTS ~38.2k tokens of untouched prior text (31.3k..69.5k)!
#33 | t+02:23s | In: ~74.8k tokens | Cached: ~72.7k | <-- Recovers to 72.7k on subsequent turn
#35 | t+02:33s | In: ~74.8k tokens | Cached: ~72.7k |
--- [User #38: Appends +26.6k tokens of TEXT (Dynamic block after text); #40..#42 are 1-token "." pings] ---
#39 | t+03:16s | In: ~101.4k tokens | Cached: ~74.3k | <-- Expected: hits prior 74.3k cache
#41 | t+03:26s | In: ~101.4k tokens | Cached: ~99.4k | <-- Expected: next turn immediately caches 99.4k / 101.4k!
Test B: [Dynamic Block (~200 tok)] + [User Text] + [Audio/Image (when present)]
- Expected on Shifted Text (
#10,#18) & Shifted Image (#40):- At
#18(+11.1ktext at boundaryK ≈ 36.8k):#19hits35.0k→#21strips the dynamic block at36.8k, preserving 100% of0..36.8k(Cached: 36.8k) while re-prefilling#18→#23locks in46.1k. - At
#40(+1.1kimage at boundaryK ≈ 58.2k):#41hits58.2k→#43preserves58.2kwhen the image shifts left →#45locks in59.3k.
- At
- Actual Bug Once Audio Enters History (
#24,#44, and Subsequent Text#64):- Retroactive Eviction Behind Boundary
K(#27/): Instead of stopping at token~48.0kon#27or token~61.4kon#47(where the dynamic block was stripped), shifting aninput_audioblock left caused Vertex to discard 11,000 to 30,000 tokens of untouched prior history and collapse backwards to pre-audio checkpoints (36.8kand31.1k). - Multi-Turn Replica Thrashing on Byte-Identical 1-Token
.Messages (#27–#37/–#57): On subsequent 1-token.turns where neither the prior history nor the audio blocks changed by a single byte, consecutive requests spaced 10–38 seconds apart bounced across worker replicas:#25(46.1k) →#27(36.8k) →#29(36.8k) →#31(0cached tokens!) →#33(58.2k) →#35(31.1k— drops 27k cached tokens 38s later!) →#37(58.2k).#45(59.3k) →#47(31.1k) →#49(31.1k) →#51(60.1k) →#53(31.1k— drops 29k tokens 13s later!) →#55(31.1k) →#57(62.6k).
- Poisoned Prefix on
#64(+13.3kText Append After Historical Audio): On#65(the very turn#64was appended at the end, before#64’s dynamic block was even stripped), having two historical audio clips in the prefix caused Vertex to evict62.6kdown to31.1kfor three consecutive turns (#65,#67,#69) before finally promoting76.2kon#71.
- Retroactive Eviction Behind Boundary
Minimal Standalone Python Reproducer (Synthetic Data)
Below is a standalone script using synthetic text and a generated 440Hz WAV buffer to reproduce the Test A retroactive prefix eviction on Turn #28 -> #31:
import base64
import io
import math
import os
import struct
import time
import wave
import requests
API_KEY = os.environ["OPENROUTER_API_KEY"]
MODEL = "google/gemini-4-argon"
SESSION_ID = f"vertex-audio-cache-repro-{int(time.time())}"
def make_token_block(prefix: str, target_tokens: int) -> str:
# ~15 tokens per line -> deterministic token count
lines = max(1, target_tokens // 15)
return "\n".join(f"{prefix} section {i}: alpha bravo charlie delta." for i in range(lines))
def make_dummy_wav_b64(seconds: int = 100, sample_rate: int = 8000) -> str:
# Gemini tokenizes audio by duration (~32 tok/sec -> 100s = ~3,200 tokens).
# 8kHz 16-bit mono keeps the base64 payload small (~2.1 MB) while producing ~3,200 tokens.
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sample_rate)
one_sec = b"".join(
struct.pack("<h", int(4000 * math.sin(2.0 * math.pi * 440.0 * t / sample_rate)))
for t in range(sample_rate)
)
w.writeframes(one_sec * seconds)
return base64.b64encode(buf.getvalue()).decode("ascii")
SYS_PROMPT = (
"You are in a prompt-caching benchmark. Reply with only the single word 'Yep.' to every message.\n\n"
+ make_token_block("System baseline", 31000)
)
TEXT_13K = make_token_block("Block A", 13500)
TEXT_26K = make_token_block("Block B", 26500)
AUDIO_3K_B64 = make_dummy_wav_b64(seconds=120) # ~3,200 tokens
DYN_TAG_START = "\n<dynamic_system_context>\n"
DYN_TAG_END = "\n</dynamic_system_context>"
messages = [{"role": "system", "content": SYS_PROMPT}]
turn_num = 1
def strip_previous_dynamic_context():
for m in messages:
if m["role"] == "user" and isinstance(m["content"], list):
for part in m["content"]:
if part.get("type") == "text":
txt = part["text"]
idx = txt.find(DYN_TAG_START)
if idx != -1:
part["text"] = txt[:idx]
def send_turn(label: str, user_text: str = ".", include_audio: bool = False):
global turn_num
strip_previous_dynamic_context()
# ~150-token dynamic block appended to the END of the latest user text part (Test A)
dyn_block = (
f"{DYN_TAG_START}"
f"Current turn: {turn_num} | Timestamp: {time.time():.3f}\n"
+ ("Runtime state token padding. " * 25)
+ f"{DYN_TAG_END}"
)
content = [{"type": "text", "text": user_text + dyn_block}]
if include_audio:
content.append({
"type": "input_audio",
"input_audio": {"data": AUDIO_3K_B64, "format": "wav"},
})
messages.append({"role": "user", "content": content})
payload = {
"model": MODEL,
"session_id": SESSION_ID,
"provider": {
"only": ["google-vertex"],
"allow_fallbacks": False,
},
"reasoning": {"effort": "low"},
"max_tokens": 4096,
"messages": messages,
}
resp = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
json=payload,
timeout=120,
)
resp.raise_for_status()
data = resp.json()
if "error" in data:
raise RuntimeError(f"API Error: {data['error']}")
usage = data.get("usage", {})
prompt_tok = usage.get("prompt_tokens", 0)
cached_tok = (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)
cost = usage.get("cost", 0.0)
reply_text = (data["choices"][0]["message"].get("content") or "Yep.").strip()
print(
f"#{turn_num:<3d} | {label:<22s} | In: {prompt_tok:>7,d} | "
f"Cached: {cached_tok:>7,d} | Cost: ${cost:.4f}"
)
# Append assistant reply without reasoning_details (reasoning_turns_kept = 0)
messages.append({"role": "assistant", "content": reply_text})
turn_num += 1
time.sleep(3)
if __name__ == "__main__":
# 1. Warm up ~31k System Prompt root checkpoint
send_turn("Cold Init (~31k)", "Reply Yep.")
for i in range(4):
send_turn(f"Warmup '.' #{i+1}", ".")
# 2. Append +13.5k Text -> caches immediately on next turn
send_turn("Append +13.5k Text", TEXT_13K)
send_turn("Verify +13.5k Cached", ".")
# 3. Append +26.5k Text -> caches up to ~69.5k
send_turn("Append +26.5k Text", TEXT_26K)
for i in range(3):
send_turn(f"Verify ~71.5k #{i+1}", ".")
# 4. Append +3.2k Audio -> watch next turn evict ~38k of prior text back to ~31k!
send_turn("Append +3.2k AUDIO", ".", include_audio=True)
for i in range(4):
send_turn(f"Post-Audio '.' #{i+1}", ".")