<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alptug Dilek on Medium]]></title>
        <description><![CDATA[Stories by Alptug Dilek on Medium]]></description>
        <link>https://medium.com/@alptugd?source=rss-ddaa965289b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RJg1IqK65tP4Wd6pAaUqgg.jpeg</url>
            <title>Stories by Alptug Dilek on Medium</title>
            <link>https://medium.com/@alptugd?source=rss-ddaa965289b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:31:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alptugd/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[When LLMs Are Forced to Be Wrong: A Case Study with Sonnet and Opus]]></title>
            <link>https://medium.com/@alptugd/when-llms-are-forced-to-be-wrong-a-case-study-with-sonnet-and-opus-8b6e94398882?source=rss-ddaa965289b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b6e94398882</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-extraction]]></category>
            <dc:creator><![CDATA[Alptug Dilek]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 00:00:57 GMT</pubDate>
            <atom:updated>2026-04-27T21:34:29.885Z</atom:updated>
            <content:encoded><![CDATA[<p>I expected this to be a straightforward comparison.</p><p>It wasn’t.</p><p>Both models failed, not randomly, but systematically.</p><p>They didn’t just make mistakes. They were being forced to be wrong.</p><p>As a long-time fan of Galatasaray S.K., I picked a few chaotic Champions League matches full of edge cases: dense scoring, cancellations, and messy commentary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k3dGdEKhrv-OTgPv.jpg" /><figcaption>From a much happier night: Galatasaray 1–0 Liverpool. The matches in this post were far less straightforward.</figcaption></figure><p>Then I gave two models, Claude Sonnet and Opus, a structured prompt and asked them to extract goal timestamps from noisy Turkish ASR transcripts.</p><p>In many cases, it worked exactly as expected. Clear signals led to correct answers. Even dense sequences of goals were handled without much trouble.</p><p>But things started to break as the signal got weaker. It started with ambiguity, then misleading commentary, and eventually a match with no usable signal at all.</p><p>That’s when both models began to behave in a way that was hard to ignore. They didn’t return uncertain answers. They didn’t skip the goal. They picked something that looked plausible and justified it.</p><p>Not because they misunderstood the task. But because the system required an answer, even when the data didn’t support one.</p><p>This post isn’t really about which model is better. It’s about what happens when signals are unclear, misleading, or missing, and the model is not allowed to say “I don’t know.”</p><p>Before diving into the cases, one important detail: all initial runs were done with low effort under default settings.</p><p>This means the models were encouraged to respond quickly with minimal internal reasoning. The prompt itself carries most of the structure, so the goal here was to see how well each model follows explicit constraints without relying on deeper reasoning. It’s also the more cost-efficient and faster way to run these kinds of evaluations.</p><h3>Prompt Overview</h3><p>The task sounds simple: given a noisy Turkish ASR transcript of a football match and a structured goals.json file, extract the timestamp of each goal.</p><p>In practice, it’s a constrained extraction problem.</p><p>The transcript provides raw, unstructured commentary from a short highlight segment (typically 8–10 minutes), not the full match. The goals.json file defines the expected number of goals and their score progression. The model must align the two.</p><p>The prompt frames this as a multi-step process:</p><ul><li><strong>Detect candidates</strong>: identify segments that might correspond to goals using strong and weak linguistic signals</li><li><strong>Filter invalid events</strong>: discard negations, cancelled goals (offside, foul), and replays</li><li><strong>Select under constraints</strong>: choose the earliest valid signal for each goal while maintaining score progression and chronological order</li><li><strong>Validate globally</strong>: ensure all selected timestamps are consistent, increasing, and collectively valid</li></ul><p>This effectively turns a noisy transcript into a constrained search problem, where the model must satisfy multiple competing rules at once.</p><p>In other words, the model is not just detecting goals. It is solving a constrained selection problem under uncertainty.</p><p>When the signal is clear, this works well.</p><p>When it isn’t, the constraints begin to compete with each other.</p><h3>Case Study 1 — Early vs Strong Signal</h3><p>To make this concrete, let’s start with a relatively simple case.</p><p>In this rather heartbreaking match between Eintracht Frankfurt and Galatasaray S.K. (5–1), most goals have clear signals in the transcript. On the surface, this is the kind of scenario where you’d expect both models to behave identically.</p><p>And for the most part, they do.</p><p>Except for one small detail that turns out to be surprisingly important.</p><p>For the first goal, there are two valid signals:</p><ul><li>An early mention: “Yunus … gol”</li><li>A slightly later, more emphatic sequence: “gol gol gol”</li></ul><p>The prompt explicitly instructs the model to select the earliest valid signal for each goal.</p><p>Both signals refer to the same event. But only one satisfies the rule: <strong>pick the earliest valid signal</strong>.</p><p>Here’s what happens:</p><ul><li>Claude Sonnet consistently selects the earlier timestamp</li><li>Claude Opus consistently selects the later one</li></ul><p>This difference is small-just a few seconds-but it’s systematic.</p><p>Sonnet follows the instruction literally. Opus prefers the stronger, more emphatic signal.</p><p>When I increased the effort level to medium, Opus corrected itself and selected the earlier timestamp.</p><p>That makes this a useful baseline:</p><blockquote><em>When the signal is clear and the task is well-defined, both models perform well. Differences appear when multiple valid interpretations exist, and reasoning depth can change which one is chosen.</em></blockquote><h3>Case Study 2 — Dense Sequences, No Ambiguity</h3><p>The second match between Galatasaray S.K. and Juventus F.C. (5–2), a much more enjoyable one for a Galatasaray fan, introduces a different kind of challenge: multiple goals in quick succession.</p><p>In some cases, goals occur within the same minute, with overlapping commentary and limited separation between events. This is where you might expect models to merge events or lose track of ordering.</p><p>They don’t.</p><p>Both Claude Sonnet and Claude Opus correctly identify all goal timestamps, consistently across runs.</p><p>The reason is simple: despite the density, each goal still has a clear signal and clean score progression. There’s no ambiguity about which segment corresponds to which event.</p><p>This highlights an important point:</p><blockquote><em>Dense sequences are not inherently difficult. Problems arise when signals compete, not when they are close together.</em></blockquote><h3>Case Study 3 — Ambiguity and Instability</h3><p>The third match between Juventus F.C. and Galatasaray S.K. (3–2) introduces a more difficult scenario: goals that are not clearly signaled.</p><p>Some goals are described without an explicit “gol,” others rely on indirect phrases or score updates, and in some cases multiple weak candidates appear close together. The structure is still there, but it’s no longer clean.</p><p>This is where things start to break.</p><p>Unlike the previous cases, both Claude Sonnet and Claude Opus become inconsistent. Across runs, they select different timestamps for the same goal, even though the input and prompt remain identical.</p><p>These runs were performed using the CLI’s default settings, which are intended to be low-randomness. Despite that, the variation observed here is not driven by randomness alone, but by multiple plausible interpretations in the input.</p><p>For example, one goal is inferred only through score progression. With no explicit signal, the models alternate between:</p><ul><li>an earlier summary-like segment</li><li>a slightly later score confirmation</li><li>or another nearby weak candidate</li></ul><p>All of these are plausible. None are clearly dominant.</p><p>A similar pattern appears in extra time, where delayed confirmation and noisy commentary make it harder to identify the exact moment of the goal. The models again choose different points depending on the run.</p><p>What changes here is not capability, but determinism.</p><p>Increasing the effort level improves this behavior, but does not eliminate it completely. The models become more consistent across runs, and in some cases converge on the correct timestamp. However, for goals with only weak signals, variation still remains. The ambiguity is reduced — but not resolved.</p><blockquote><em>When multiple weak candidates exist and no strong signal anchors the event, the problem becomes underdetermined, meaning multiple answers are equally plausible. The models don’t consistently fail; they become unstable.</em></blockquote><h3>Case Study 4 — Missing Signal and Forced Errors</h3><p>The final match between Liverpool F.C. and Galatasaray S.K. (4–0) pushes the setup to its limit.</p><p>This time, the problem is not ambiguity. It’s the absence of a valid signal.</p><p>Two strong goal-like signals appear in the transcript:</p><ul><li>one is later cancelled for offside</li><li>another is followed by a foul decision</li></ul><p>According to the rules, both must be discarded.</p><p>The actual goal, however, is not clearly described at all. The commentary only repeats the player’s name, with no explicit goal signal and no immediate score update.</p><p>This leaves the model with no valid candidate.</p><p>And yet, it still has to return one.</p><p>This is where both Claude Sonnet and Claude Opus fail, completely but in different ways.</p><ul><li>Sonnet consistently selects the later “top ağlara gitti” <em>(the ball is in the back of the net)</em> segment, ignoring the subsequent foul</li><li>Opus consistently selects the earlier “4–0 oldu” <em>(the score is now 4–0)</em> segment, despite the offside cancellation</li></ul><p>In both cases, the models identify a strong signal, notice conflicting context, and proceed anyway.</p><p>The behavior is not random. It’s systematic.</p><p>You can see this directly in the reasoning:</p><p><strong>Claude Sonnet:</strong> “This is the only remaining goal signal after the cancelled one, and the final score confirms it.”</p><p><strong>Claude Opus:</strong> “This is the only 4–0 score mention in the transcript, despite the later offside review.”</p><p>In both cases, the models explicitly acknowledge conflicting evidence-and proceed anyway.</p><p>What’s happening here is not a failure of detection, but a failure of constraint.</p><blockquote><em>When no valid candidate exists, the task becomes impossible under the given rules. Instead of abstaining, the models construct an answer by selecting the least inconsistent signal.</em></blockquote><p>This is the same pattern from earlier cases, taken to its extreme.</p><p>The models are not just making mistakes.</p><p>They are being forced to be wrong.</p><p>Increasing the effort level does not resolve this failure.</p><p>Claude Sonnet continues to select the same invalid candidate, despite taking significantly longer to process the input-suggesting more extensive checking without a change in outcome.</p><p>Claude Opus, on the other hand, shifts its behavior and begins selecting a different invalid candidate. The answer changes, but it remains incorrect.</p><p>In other words, more effort alters the path — but not the result.</p><h3>Takeaways</h3><p>Across these four cases, a consistent pattern emerges:</p><p>When signals are clear, both Claude Sonnet and Claude Opus perform reliably. Even dense sequences of goals are handled without issue as long as each event has a clear anchor.</p><p><strong>As ambiguity increases, behavior changes.</strong> With multiple weak candidates, the models no longer converge on a single answer. The problem becomes underdetermined, with multiple plausible interpretations, and the output becomes unstable.</p><p>And when the signal disappears entirely, the failure mode shifts again.</p><p>The models don’t skip the goal, because they are not allowed to. They don’t return uncertainty. They select the most plausible remaining candidate and justify it-even when it violates the rules.</p><p>This is not a model-specific issue. Both models exhibit the same pattern under different conditions.</p><p>The root cause is structural.</p><p>The prompt defines how to select among candidates, but it never defines what to do when no valid candidate exists.</p><p>Combined with the requirement to return exactly one timestamp per goal (the prompt enforces a single output per goal), this forces the model to produce an answer even when the data cannot support one.</p><p>That leads to a key insight:</p><blockquote><em>When a system requires an answer, it will produce one-even if it has to be wrong.</em></blockquote><h3>What I would change</h3><p>Two small changes would significantly improve the system:</p><ul><li>Allow abstention: if no valid candidate exists, return null instead of forcing a choice</li><li>Strengthen tie-breaking: define explicit fallback rules when multiple weak candidates exist</li></ul><p>These changes would not improve performance in easy cases. But they would prevent systematic errors in the hardest ones.</p><h3>What about higher effort?</h3><p>Increasing the effort level helps — but only up to a point.</p><p>In ambiguous cases, more effort reduces instability. The models follow the rules more consistently and are more likely to converge on the same answer.</p><p>But in cases where the signal is missing, more effort does not recover the correct result. It only changes how the models justify their choice — and sometimes which incorrect answer they select.</p><blockquote><em>Reasoning improves decisions when information exists. It cannot recover information that isn’t there.</em></blockquote><p><em>This article was developed with the help of AI tools. The experiments, analysis, and conclusions are my own.</em></p><p><em>Originally published at </em><a href="https://alptugdilek.com/blog/posts/when-llms-are-forced-to-be-wrong-a-case-study-with-sonnet-and-opus/"><em>https://alptugdilek.com</em></a><em> on April 26, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b6e94398882" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why My Claude Prompt Cache Hit Rate Was Stuck at ~50%]]></title>
            <link>https://medium.com/@alptugd/why-my-claude-prompt-cache-hit-rate-was-stuck-at-50-18675a1d416b?source=rss-ddaa965289b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/18675a1d416b</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Alptug Dilek]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 00:00:36 GMT</pubDate>
            <atom:updated>2026-04-14T08:29:07.002Z</atom:updated>
            <content:encoded><![CDATA[<p>I was running the same prompt multiple times against Claude. This is a common pattern when evaluating LLM outputs, since models can produce different results across runs.</p><p>In a 5-run batch, runs 2–5 should have been nearly free with prompt caching.</p><p>It didn’t.</p><h3>Why This Matters</h3><p>Prompt caching is one of the most effective cost optimizations in the Claude API. When you send identical input multiple times, <a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">Anthropic prompt caching</a> caches processed tokens server-side so subsequent calls skip reprocessing the prompt.</p><p>After the first call warms the cache, reads are much cheaper. Cache reads cost about 10% of normal input token prices. For large prompts, this can reduce input costs by 80–90% across repeated calls.</p><p>The expected behavior is simple:</p><ul><li>Run 1 <strong>warms the cache</strong></li><li>Runs 2–5 are <strong>nearly free</strong></li></ul><p>That wasn’t happening.</p><h3>What I Observed</h3><p>I observed this behavior while running claude-sonnet-4-6, though the issue is not model-specific.</p><p>When I looked at raw token usage across runs, each call re-created roughly half the cache instead of reading it:</p><pre>run_1: 24,075 tokens  (cache_read=0,     cache_create=24,073)  ← warms cache<br>run_2: 24,096 tokens  (cache_read=11780, cache_create=12,314)  ← should be full read<br>run_3: 24,117 tokens  (cache_read=11780, cache_create=12,335)<br>run_4: 24,138 tokens  (cache_read=11780, cache_create=12,356)<br>run_5: 24,159 tokens  (cache_read=11780, cache_create=12,377)</pre><p>A quick note on the fields: cache_create is the number of tokens written to the cache on that call. You pay full input price for these.</p><p>cache_read is the number of tokens read from an existing cache, which is roughly 10× cheaper. In a healthy batch run, only run 1 should have cache_create. Subsequent runs should be almost entirely cache_read.</p><p>Cache hit rate was stuck around <strong>50%</strong> when it should have been close to <strong>100%</strong> from run 2 onward.</p><p>For a ~24K token prompt, that meant paying full price for roughly 12,000 tokens on every run. This effectively doubled input processing cost across the experiment.</p><h3>The Real Clue: The Input Was Growing</h3><p>The numbers reveal something subtle. The total input was not stable. It grew by about 21 tokens per run.</p><ul><li>Run 1: 24,075 tokens</li><li>Run 5: 24,159 tokens (<strong>+84 tokens</strong>)</li></ul><p>The prompt file, transcript, and goals had not changed.</p><p>Prompt caching is prefix-based and keyed by exact content. Even a single token difference invalidates the cache from that point onward. Because the input kept changing, the second cache breakpoint never matched the previous run. That forced partial re-creation every time.</p><p>The cache key was never stable because the input was never stable.</p><h3>The Culprit: Git Status Injection</h3><p>I was invoking Claude using claude -p (Claude Code&#39;s CLI print mode) in a shell script and piping the prompt via stdin.</p><p>What I did not realize was that Claude Code injects workspace context when running inside a git repository. This includes:</p><p>git status includes untracked files.</p><p>My batch script creates three files per run:</p><p>Each run added new untracked files. That changed git status, which changed the injected context, which changed the input, which invalidated the cache.</p><p>The growth was remarkably consistent at about 21 tokens per run. The output files had identical structure, so each run added the same token footprint.</p><p>The prompt file was identical. The transcript was identical. But the effective input was not.</p><h3>The Fix</h3><p>Running Claude from a neutral directory outside the git repository prevents workspace context injection. Combined with --no-session-persistence, the input becomes truly static.</p><pre>TMP_INPUT=&quot;$(mktemp /tmp/claude_input_XXXXXX.txt)&quot;<br>trap &#39;rm -f &quot;$TMP_INPUT&quot;&#39; EXIT<br><br># build prompt into TMP_INPUT ...<br><br>(cd /tmp &amp;&amp; claude -p --no-session-persistence --output-format json \<br>  --model &quot;$MODEL&quot; &lt; &quot;$TMP_INPUT&quot; &gt; &quot;$OUTPUT&quot;)</pre><h3><strong>Why This Fix Works Reliably</strong></h3><ul><li>-p runs Claude in print mode for scripting</li><li>--no-session-persistence prevents history from being saved</li><li>cd /tmp removes git workspace context</li></ul><p>Running from /tmp means:</p><ul><li>no git repository</li><li>no workspace memory</li><li>no injected context</li><li>no hidden input changes</li></ul><p>After this change:</p><ul><li>runs 2–5 showed full cache reads</li><li>cache_create dropped to zero after run 1</li><li>input size stayed constant</li><li>costs dropped as expected</li></ul><h3>You Can Reproduce This</h3><p>Run inside a git repository:</p><pre>echo &quot;test&quot; | claude -p --no-session-persistence --output-format json \<br>  --model &quot;$MODEL&quot; | jq &#39;{cache_read: .usage.cache_read_input_tokens, cache_create: .usage.cache_creation_input_tokens}&#39;</pre><p>Then run from /tmp:</p><pre>echo &quot;test&quot; | (cd /tmp &amp;&amp; claude -p --no-session-persistence --output-format json \<br>  --model &quot;$MODEL&quot;) | jq &#39;{cache_read: .usage.cache_read_input_tokens, cache_create: .usage.cache_creation_input_tokens}&#39;</pre><p>Don’t be surprised by the token counts. The &quot;test&quot; prompt itself is only a couple of tokens. The thousands of tokens in cache_read and cache_create come from the system prompt that Claude Code injects automatically. That injected context is exactly what we&#39;re measuring.</p><h3>What I Measured</h3><p>Here’s what I measured across four consecutive runs.</p><p>Between run 1 and run 2 everything was committed, clearing untracked files from git status.</p><p>Between run 3 and run 4 a new dummy file was added.</p><pre>┌─────┬─────────────┬────────────┬──────────────┬────────────────────────────────────────────────────────────┐<br>│ Run │  Location   │ cache_read │ cache_create │                           notes                            │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 1   │ project dir │ 12,057     │ 4,821        │ no warm cache, untracked files present                     │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 1   │ /tmp        │ 12,057     │ 4,482        │ no warm cache                                              │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 2   │ project dir │ 12,057     │ 4,630        │ committed between runs — git context changed, still a miss │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 2   │ /tmp        │ 16,539     │ 0            │ full cache hit                                             │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 3   │ project dir │ 16,687     │ 0            │ nothing changed since run 2 — finally a full hit           │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 3   │ /tmp        │ 16,539     │ 0            │ full cache hit                                             │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 4   │ project dir │ 12,057     │ 4,638        │ one new untracked file added — cache broken again          │<br>├─────┼─────────────┼────────────┼──────────────┼────────────────────────────────────────────────────────────┤<br>│ 4   │ /tmp        │ 16,539     │ 0            │ unaffected                                                 │<br>└─────┴─────────────┴────────────┴──────────────┴────────────────────────────────────────────────────────────┘</pre><p>/tmp is stable across all runs. The project directory breaks whenever git status changes. A commit, a new file, or any workspace change can invalidate the cache.</p><h3>The Generalizable Lesson</h3><p>Prompt caching only works if your input is byte-for-byte identical across calls.</p><p>When using high-level CLI tools instead of calling the API directly, invisible context can be injected into your prompts:</p><ul><li>git workspace state</li><li>session history</li><li>project memory</li><li>environment metadata</li></ul><p>These do not appear in your prompt file. They do not cause errors. They quietly inflate token counts and invalidate caching.</p><p>If you are using claude -p in evaluation scripts or batch pipelines, inspect your raw API responses. Look at:</p><ul><li>cache_read_input_tokens</li><li>cache_creation_input_tokens</li></ul><p>If cache_creation_input_tokens stays high after the first run, your input is not as static as you think.</p><p><em>This article evolved through discussions with AI. The investigation, measurements, and final conclusions are my own.</em></p><p><em>Originally published at </em><a href="https://alptugdilek.com/blog/posts/why-my-claude-prompt-cache-hit-rate-was-stuck-at-around-50-percent/"><em>https://alptugdilek.com</em></a><em> on April 14, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18675a1d416b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code Started Calling Haiku After a Version Update]]></title>
            <link>https://medium.com/@alptugd/claude-code-started-calling-haiku-after-a-version-update-9170f75989a8?source=rss-ddaa965289b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9170f75989a8</guid>
            <category><![CDATA[programming-tools]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Alptug Dilek]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 00:00:07 GMT</pubDate>
            <atom:updated>2026-04-14T12:06:39.319Z</atom:updated>
            <content:encoded><![CDATA[<p>While investigating a prompt caching issue in my Claude Code evaluation scripts, I noticed something else unexpected in the raw API responses: a Haiku call I never asked for, appearing alongside my Opus calls.</p><p>I previously wrote about this caching issue in an earlier post:</p><p><a href="https://medium.com/@alptugd/why-my-claude-prompt-cache-hit-rate-was-stuck-at-50-18675a1d416b">Why My Claude Prompt Cache Hit Rate Was Stuck at Around 50%</a></p><h3>The discovery</h3><p>I was inspecting the modelUsage field in the raw JSON response, something that&#39;s easy to miss unless you inspect raw responses, when I saw this:</p><pre>&quot;claude-haiku-4-5-20251001&quot;: {<br>  &quot;inputTokens&quot;: 10856,<br>  &quot;outputTokens&quot;: 16,<br>  &quot;costUSD&quot;: 0.010936<br>},<br>&quot;claude-opus-4-6&quot;: {<br>  &quot;inputTokens&quot;: 2,<br>  &quot;outputTokens&quot;: 2438,<br>  &quot;costUSD&quot;: 0.163684<br>}</pre><p>I specified Opus. I was running a simple claude -p single-turn call. No subagents, no tools, no complex workflows. Yet Haiku read my entire prompt (10,856 tokens) and produced 16 tokens before Opus did the actual work.</p><h3>Pinning the version</h3><p>My older batch runs didn’t show this behavior. By checking the .jsonl session files Claude Code stores locally, I was able to confirm which version those runs were on:</p><pre>cat ~/.claude-personal/projects/.../session.jsonl | jq -r &#39;.version&#39; | sort -u<br># 2.1.104</pre><p>Current version on my machine: <strong>2.1.107</strong></p><p>I then ran a controlled test: downgrade, test, upgrade, test.</p><pre>claude install 2.1.104<br>echo &quot;test&quot; | (cd /tmp &amp;&amp; claude -p --no-session-persistence \<br>  --output-format json --model claude-opus-4-6) | jq &#39;.modelUsage&#39;</pre><h3>2.1.104 — Opus only</h3><pre>{<br>  &quot;claude-opus-4-6&quot;: {<br>    &quot;inputTokens&quot;: 5,<br>    &quot;outputTokens&quot;: 15,<br>    &quot;cacheReadInputTokens&quot;: 0,<br>    &quot;cacheCreationInputTokens&quot;: 22798,<br>    &quot;costUSD&quot;: 0.1428875<br>  }<br>}</pre><h3>2.1.107 — Haiku appears</h3><pre>{<br>  &quot;claude-haiku-4-5-20251001&quot;: {<br>    &quot;inputTokens&quot;: 339,<br>    &quot;outputTokens&quot;: 11,<br>    &quot;cacheReadInputTokens&quot;: 0,<br>    &quot;cacheCreationInputTokens&quot;: 0,<br>    &quot;costUSD&quot;: 0.000394<br>  },<br>  &quot;claude-opus-4-6&quot;: {<br>    &quot;inputTokens&quot;: 5,<br>    &quot;outputTokens&quot;: 16,<br>    &quot;cacheReadInputTokens&quot;: 23291,<br>    &quot;cacheCreationInputTokens&quot;: 0,<br>    &quot;costUSD&quot;: 0.012070<br>  }<br>}</pre><p>Reproducible on my machine, version-pinned, no other variables changed.</p><h3>What I observed</h3><ul><li>On my machine, Haiku is being called internally on every claude -p invocation on version 2.1.107</li><li>It wasn’t happening on version 2.1.104</li><li>It reads the prompt and produces a very small number of tokens (11–16)</li><li>It happens on simple single-turn calls with no explicit subagent usage</li><li>The Haiku call never benefits from prompt caching (cache_read=0)</li><li>The cost scales with prompt size. My 26k token transcripts generated ~10k token Haiku calls</li><li>On my 26k token transcripts, Haiku added roughly $0.01 per call. Against an Opus call costing ~$0.16, that’s about 6–7% overhead you didn’t ask for and can’t currently opt out of</li><li>It appeared between two patch versions (2.1.104 → 2.1.107). <br>I couldn’t find any release notes describing this change in the Claude Code changelog:<br><a href="https://code.claude.com/docs/en/changelog#2-1-107">https://code.claude.com/docs/en/changelog#2-1-107</a></li></ul><h3>What I don’t know</h3><p>The exact internal mechanism is unclear. Based on the <a href="https://code.claude.com/docs/en/sub-agents.md">official sub-agents documentation</a>, built-in subagents such as Explore use Haiku by default. This suggests Claude Code may be invoking an internal subagent automatically. A related <a href="https://github.com/anthropics/claude-code/issues/22445">community GitHub issue</a> discusses similar unexpected model routing behavior. But I haven’t confirmed the exact cause, only the behavior.</p><p>It’s also possible the Haiku call is doing something useful, for example routing or classifying the prompt before the Opus call. If that were the case, you would expect to see some benefit in the Opus token counts or latency across versions. I didn’t measure latency, and the token counts don’t show an obvious savings. So the net effect, from where I’m sitting, looks like added cost with no visible upside.</p><p>Constantine Mirin documented a <a href="https://mirin.pro/blog/claude-code-subagents-haiku-telemetry/">similar finding through OpenTelemetry monitoring</a>, finding that 36% of Haiku subagent calls were doing complex reasoning tasks rather than simple lookups. Worth reading alongside this.</p><h3>What you can do</h3><p>Check your own runs by inspecting the raw response:</p><pre>echo &quot;test&quot; | claude -p --output-format json --model claude-opus-4-6 | jq &#39;.modelUsage&#39;</pre><p>If you see a model you didn’t ask for, your request is being routed. As of now I haven’t found a reliable way to suppress it. If you know of a flag or workaround that does, I’d love to hear it.</p><h3>The bigger picture</h3><p>Two posts in, and both findings came from the same place: inspecting raw API responses Claude Code doesn’t surface in its normal output.</p><p>Silent cache invalidation. Silent model routing.</p><p>If you’re running Claude Code in scripts or batch pipelines, it’s worth looking at what’s actually being sent and billed, not just the output.</p><p><em>This article evolved through discussions with AI. The findings and conclusions are my own.</em></p><p><em>Originally published at </em><a href="https://alptugdilek.com/blog/posts/claude-code-started-calling-haiku-after-a-version-update/"><em>https://alptugdilek.com</em></a><em> on April 14, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9170f75989a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visitor Pattern Strikes Back in Java]]></title>
            <link>https://medium.com/@alptugd/visitor-pattern-strikes-back-in-java-fbfc7694e5cb?source=rss-ddaa965289b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbfc7694e5cb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[visitor-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Alptug Dilek]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 00:00:57 GMT</pubDate>
            <atom:updated>2026-04-09T20:09:50.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern Java quietly made the Visitor pattern relevant again. Sealed classes, records, and pattern matching changed the tradeoffs. It might be time to revisit Visitor.</p><p>For years, the Visitor pattern has been somewhat underrated in Java. I’ve encountered it far less in real-world codebases than I would have expected.</p><p>Part of the reason is simple: it used to be hard to justify.</p><p>The Visitor pattern was often considered too verbose. And honestly, that wasn’t entirely wrong.</p><p>But modern Java has changed something important. Not the Visitor pattern itself, but how we model domain hierarchies.</p><p>That makes Visitor worth revisiting.</p><h3>The Problem</h3><p>Imagine you’re building a payment system that supports multiple payment types:</p><ul><li>Credit Card</li><li>PayPal</li><li>Bank Transfer</li></ul><p>You might model it like this:</p><pre><br>sealed interface Payment<br>        permits Payment.CreditCard, Payment.PayPal, Payment.BankTransfer {<br><br>    record CreditCard(String number) implements Payment {}<br>    record PayPal(String email) implements Payment {}<br>    record BankTransfer(String iban) implements Payment {}<br>}</pre><p>Now you want to process payments.</p><pre>void process(Payment payment) {<br>    if (payment instanceof CreditCard cc) {<br>        ...<br>    } else if (payment instanceof PayPal pp) {<br>        ...<br>    } else if (payment instanceof BankTransfer bt) {<br>        ...<br>    }<br>}</pre><p>This works, but problems appear over time:</p><ul><li>Logic spreads across the codebase</li><li>Harder to maintain</li><li>Easy to forget new types</li><li>No strong compile-time guarantees</li></ul><h3>Enter Visitor</h3><p>Instead, you can use the Visitor pattern:</p><pre>sealed interface Payment<br>        permits Payment.CreditCard, Payment.PayPal, Payment.BankTransfer {<br><br>    &lt;T&gt; T accept(Visitor&lt;T&gt; visitor);<br><br>    interface Visitor&lt;T&gt; {<br>        T creditCard(CreditCard creditCard);<br>        T payPal(PayPal payPal);<br>        T bankTransfer(BankTransfer bankTransfer);<br>    }<br><br>    record CreditCard(String number) implements Payment {<br>        public &lt;T&gt; T accept(Visitor&lt;T&gt; visitor) {<br>            return visitor.creditCard(this);<br>        }<br>    }<br><br>    record PayPal(String email) implements Payment {<br>        public &lt;T&gt; T accept(Visitor&lt;T&gt; visitor) {<br>            return visitor.payPal(this);<br>        }<br>    }<br><br>    record BankTransfer(String iban) implements Payment {<br>        public &lt;T&gt; T accept(Visitor&lt;T&gt; visitor) {<br>            return visitor.bankTransfer(this);<br>        }<br>    }<br>}</pre><p>Yes, this is still somewhat verbose; but sealed classes change something important.</p><h3>Compile-Time Exhaustiveness</h3><p>Now imagine adding a new payment type:</p><pre>record ApplePay(String token) implements Payment {}</pre><p>The compiler immediately tells you:</p><blockquote><em>You forgot to handle ApplePay</em></blockquote><p>This is the real power of Visitor.</p><ul><li>No silent bugs</li><li>No missed cases</li><li>No runtime surprises</li></ul><p>With sealed classes, the hierarchy is closed. The compiler knows all variants and enforces exhaustiveness.</p><p>This is what makes Visitor far more compelling in modern Java.</p><h3>A Small but Meaningful Style Shift</h3><p>Traditionally, Visitor implementations used a single method name:</p><pre>interface Visitor&lt;T&gt; {<br>    T visit(CreditCard creditCard);<br>    T visit(PayPal payPal);<br>    T visit(BankTransfer bankTransfer);<br>}</pre><p>However, Java also allows a more expressive alternative:</p><pre>interface Visitor&lt;T&gt; {<br>    T creditCard(CreditCard creditCard);<br>    T payPal(PayPal payPal);<br>    T bankTransfer(BankTransfer bankTransfer);<br>}</pre><p>This can improve readability and domain clarity. It’s not a new capability, but modern Java tends to favor clarity over strict pattern conventions.</p><h3>Java 17 vs Java 21: Visitor vs Pattern Matching</h3><p>If you’re using Java 17, you typically have:</p><ul><li>Sealed classes</li><li>Records</li><li>No pattern matching for switch</li></ul><p>In that world, Visitor becomes a very practical solution.</p><p>With Java 21, you can also write:</p><pre>switch (payment) {<br>    case CreditCard cc -&gt; ...<br>    case PayPal pp -&gt; ...<br>    case BankTransfer bt -&gt; ...<br>}</pre><p>Now pattern matching becomes a strong alternative.</p><p><strong>A practical rule of thumb:</strong></p><p>Use Visitor when:</p><ul><li>You have multiple behaviors</li><li>Logic grows complex</li><li>You want reusable operations</li><li>You’re on Java 17</li></ul><p>Use pattern matching when:</p><ul><li>You’re on Java 21+</li><li>Logic is small</li><li>Used in one place</li><li>Simpler is better</li></ul><p>Both are valid tools.</p><h3>Why Visitor Is Relevant Again</h3><p>A common guideline for Visitor is that it works well when the set of types is stable but new operations are added over time.</p><p>That still applies. But modern Java introduces another reason.</p><p>We model closed hierarchies more often now, and Visitor fits naturally there.</p><p>Visitor didn’t change.</p><p>Java did.</p><h3>Final Thought</h3><p>Sealed classes make Visitor more practical. Pattern matching offers a concise alternative.</p><p><strong>The Visitor strikes back.</strong></p><p><em>This article evolved through discussions with AI. The ideas and final opinions are my own.</em></p><p><em>Originally published at </em><a href="https://alptugdilek.com/blog/posts/visitor-pattern-strikes-back-in-java/"><em>https://alptugdilek.com</em></a><em> on April 8, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbfc7694e5cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>