AI Coding Agents
Deduplicate repeated file reads in a coding agent
Deduplicate a coding agent’s repeated file reads only when the current file matches an earlier full result that the model can still see. Return a short reference to the original tool call and turn, invalidate it on writes and rewinds, and return full text when compaction, context editing, or a hook has removed or changed the evidence.
Check what Claude Code’s issue history establishes
A second read sometimes asks for the same bytes and sometimes tests whether an edit changed them. A coding agent can also reopen a file because the original output disappeared from its active history. A useful deduplication rule distinguishes all three cases before replacing any result with a reference.
Issue #40123 reports a gap in the Claude Code Read tool documentation for compact line numbers and deduplication of unchanged rereads. Issue #60684 reports that a stale file unchanged response followed an edit made outside Claude Code. Use these reports to design regression tests for your reader, including checks for the cases when the disk contents or the visible conversation changes. Issue #40123 · Issue #60684
The table gives tracker titles and dispositions as of November 30, 2026. Titles appear as tracker text with inline code formatting removed and dashes replaced by colons. Each row suggests a regression test for your reader.
| Issue | Tracker title | State and reason | Regression to cover |
|---|---|---|---|
| #40123 | [DOCS] Read tool docs omit compact line-number output and unchanged re-read deduplication | CLOSED / NOT_PLANNED | A valid stub identifies the earlier full read |
| #60684 | [BUG] Read tool returns "file unchanged" after external on-disk edits, serving a stale cached snapshot | CLOSED / NOT_PLANNED | A change made outside the tool still returns fresh text |
| #60722 | [BUG] Read tool dedup cache not cleared on conversation revert: "file unchanged" returned when content is no longer in visible context | CLOSED / NOT_PLANNED | Reverting a conversation drops anchors from removed turns |
| #55042 | [Bug] Read tool cache survives esc-esc rewind, returning "unchanged" stubs without content | CLOSED / NOT_PLANNED | A reread after rewind can reconstruct the missing evidence |
| #42264 | [Bug] "Unchanged since last read" error when reading file previously accessed in reverted conversation state | CLOSED / COMPLETED | A previously seen file may need a new full turn after revert |
| #68536 | Rewind then Read same file incorrectly shows "Unchanged since last read" | CLOSED / COMPLETED | The first reread after rewinding past the original result returns full text |
| #64882 | [BUG] Model re-reads an unchanged file in a loop, ignoring repeated "Wasted call: file unchanged" rejections (bare rejection gives a context-corrupted model nothing to recover from) | CLOSED / COMPLETED | A reread after a stub returns full text to break the loop |
| #88118 | Read dedup does not account for PostToolUse updatedToolOutput: repeated Reads bypass substituting hooks, and readFileState records disk content the model never received | CLOSED / COMPLETED | Establish an anchor only after any output substitution |
The hook case is an important boundary. Claude Code’s hooks reference documents that PostToolUse can replace the result through updatedToolOutput before it is sent to Claude. The tracker describes what happens if a deduper bases its record on pre-hook disk content. In your host, record the text that actually reaches the model. If a hook redacts or transforms it, run that hook on full reads and exclude the transformed results from this reference implementation’s anchors. Claude Code hooks · Issue #88118
Verify the bytes and the visible result
File identity and result visibility are different inputs. Use a canonical path under the workspace root and compare a file stamp with its content hash. An external edit can change the bytes while keeping the file length and modification time. Size and modification time alone would miss that change. The reference hashes each read and compares that digest along with the stamp, which includes modification time. It checks for visible metadata changes while reading and uses a successful match only for the current read.
The earlier result must also be an exact full payload that still appears in the model’s active prompt. A transcript index and a raw event store may retain entries long after context editing clears the content. Anthropic’s tool-result clearing can replace old results with text marking their removal. Claude Code’s context-window documentation also describes selectively re-reading files after compaction and sometimes carrying a path reference alone. Build the visible-ID set from the request’s surviving full results, and omit uncertain IDs when a server manages context across requests. Anthropic context editing · Claude Code context window
Save the next two Python blocks in order as read_cache.py. The first block captures a local UTF-8 file and defines the stub. It uses the earlier result’s tool call ID and turn. A stable serialization avoids adding new entropy such as a read timestamp or a per-call counter.
import hashlib
import json
import os
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class FullRead:
path: Path
stamp: tuple
digest: str
text: str
tool_use_id: str
turn: int
generation: int
def stamp(stat):
return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
def snapshot(path):
with path.open("rb") as stream:
before = stamp(os.fstat(stream.fileno()))
data = stream.read()
after = stamp(os.fstat(stream.fileno()))
if before != after or after != stamp(path.stat()):
raise RuntimeError("file changed during read; retry")
return after, hashlib.sha256(data).hexdigest(), data.decode("utf-8")
def unchanged_stub(anchor):
return json.dumps(
{"status": "unchanged", "tool_use_id": anchor.tool_use_id, "turn": anchor.turn},
sort_keys=True, separators=(",", ":"),
)
Use these helpers inside one serialized agent session. The implementation reads complete files from a trusted workspace. If your tool supports offsets or language-aware rendering, make the requested range and rendering format part of its identity before allowing stubs for partial results. A reference to a visible slice provides no evidence about another slice. Enforce file access policy before invoking the reader, and keep separate state for separate sessions or users.
class ReadCache:
# shortcut: one serialized session on a trusted local tree; add host locking
# and sandboxed file access before sharing it across concurrent requests.
def __init__(self, root):
self.root = root.resolve()
self.anchors = {}
self.stubbed = set()
self.generation = 0
def path_for(self, relative_path):
requested = Path(relative_path)
if requested.is_absolute():
raise ValueError("expected a relative path")
path = (self.root / requested).resolve()
path.relative_to(self.root)
return path
def read(self, relative_path, tool_use_id, turn, visible_ids, force_full=False):
path = self.path_for(relative_path)
version, digest, text = snapshot(path)
anchor = self.anchors.get(path)
if anchor and (anchor.stamp, anchor.digest) != (version, digest):
self.invalidate_write()
anchor = None
if (anchor and anchor.tool_use_id in visible_ids
and anchor.tool_use_id not in self.stubbed and not force_full):
self.stubbed.add(anchor.tool_use_id)
return unchanged_stub(anchor), None
pending = FullRead(path, version, digest, text, tool_use_id, turn, self.generation)
return text, pending
def record_delivery(self, pending, delivered_text):
if pending is None or pending.generation != self.generation:
return
previous = self.anchors.pop(pending.path, None)
if previous:
self.stubbed.discard(previous.tool_use_id)
if pending.text == delivered_text:
self.anchors[pending.path] = pending
def invalidate_write(self):
self.generation += 1
self.anchors.clear()
self.stubbed.clear()
def rewind(self):
self.invalidate_write()
Call record_delivery after the host has applied hooks and accepted the final text. This is where the candidate either becomes an anchor or loses eligibility. Provide the visible full-result IDs when calling read, and keep tool call IDs unique within the session. If a live transformation can change between reads, use force_full and apply the current transformation on every such request. Call invalidate_write when a write may have changed the workspace, even when a formatter writes the same bytes, and call rewind before serving reads on the reverted branch. A generation change prevents a pending delivery from repopulating a discarded cache.
This implementation allows one stub per anchor and then serves a full result on the next request. That tradeoff helps a model recover if an earlier reference was usable in principle but the model still asks for the file again. Expose an explicit full-read option too. It lets a caller request exact content when it intends to quote code or prepare an edit. Both paths still run the current file check.
A file snapshot answers what the tool observed at read time. A later write can still race with a model that plans an edit based on that observation. Keep the edit tool’s own current-content check in place. The read cache handles the transport of evidence to the agent, and an edit should still fail safely when the text it intends to replace has changed. If the read fails because the file disappeared, forward that failure and let the agent choose whether to resolve the path again. The earlier successful contents describe an earlier state.
When you wire up visibility tracking, check the final request assembled for the model after the host performs its context reduction. For each visible ID, ask whether the full text sits behind that ID in the current request or whether it has been replaced with a short note. A retained call with a removed result can otherwise look eligible to code that inspects only call metadata. Prefer dropping an ambiguous anchor and paying for a full read over sending a reference the agent cannot resolve. This also keeps correctness independent of cache expiration. Request visibility is about what evidence the model receives, even when the provider has to process the full prompt again.
Record the reason for a full-read fallback in host telemetry. Separate freshness changes, lost visibility, hook bypass, and repeated requests following a stub. They imply different fixes. A high rate of lost anchors after edits is expected with the deliberately broad invalidation here. A high rate after context clearing may mean the old results were rarely useful for references, even with a working history cache. Keep these measurements outside the stub so its serialized payload stays stable.
Keep appended history stable and test recovery
Byte-stable serialization and prompt-prefix reuse solve different problems. Generate stubs as new tool results and leave the earlier full result and any already-sent stubs unchanged. Where Anthropic prompt caching applies, the prefix through a breakpoint must match exactly for a hit. Appending a stable reference limits the new result’s size. Replacing an older full result in a previously sent prefix changes that prefix regardless of how consistently the replacement is serialized. A new tool call envelope can also differ even when two stub payloads are identical. Anthropic prompt caching · ByteCosts prompt cache invalidation guide
Start the local trial with a full read, then repeat it with the original ID visible. The first repeat should identify the full result and its turn. Ask again and verify that the new response contains the file. Write separate cases with a fresh cache and a delivered full read for each. Change the file outside the read tool with a same-length edit and restore its original modification time. Simulate a rewind by calling rewind(), or simulate context clearing by removing the original ID from the visible set. In each case the next read should return full text. Also substitute the output of a forced full read before calling record_delivery() and verify that the earlier anchor can no longer produce a stub.
Add a case that rejects a path outside the workspace. To check stable stub bytes, run two fresh caches against the same file, record an identical anchor in each, and compare their first stubs with different reread call IDs and turns. When integrating this with an MCP file tool, keep the state in a host that knows which results the model can see, or pass trusted visibility metadata from that host. A server that sees only incoming file requests can safely serve full text whenever that information is absent.
Estimate savings in a session with repeat reads
Assume one initial full read, four repeated requests for the file, and six later requests carrying the resulting history. Each full read adds 3,000 input tokens and each stub adds 25. Assume that each repeated result is added to a five-minute cache write on its first send and that every later send of that result hits the cache. Each of the four repeated results then gets nine, eight, seven, or six cache reads, respectively. The initial full read appears in both scenarios, so remove its cost from the comparison.
As of November 30, 2026, the Claude Sonnet 5.5 rates used here are $2.50 per million tokens for five-minute cache writes and $0.10 per million cache read tokens. The incremental estimate is (write tokens × 2.50 + cache read tokens × 0.10) / 1000000. The host, token counts, and cache behavior are assumptions for this example. Anthropic pricing · ByteCosts pricing index
| Repeat policy | Write tokens | Later cache read tokens | Incremental estimate |
|---|---|---|---|
| Four full rereads | 12,000 | 90,000 | $0.039000 |
| Stub, full, stub, full | 6,050 | 42,400 | $0.019365 |
| Difference | 5,950 | 47,600 | $0.019635 |
Each retained duplicate contributes another input charge on every request that carries it. To assess your own session, count full responses displaced, forced recoveries, and the requests that carry each result. Compare those counts with cache read and write usage. If rereads are small or the agent often requests full recovery immediately, the saved tokens may be too few to justify changing the read tool. Keep result correctness and the next successful edit in the trial alongside token charges.
Decide where to turn deduplication on
Adopt this policy for full reads in a host that can establish both current file identity and actual result visibility. Replay a session that includes an external formatter, a rewind after a failed edit, and a tool result removed during context reduction. Check that the agent makes the same evidence-based decision in the optimized run and that it recovers a current file whenever the original becomes unavailable.
Use a structured compaction checkpoint to carry active paths across a reset and rebuild the anchor set from successful full reads afterward. For evidence from shell commands, use the test output triage filter to register a durable log and narrow line ranges. Both workflows give the agent a dependable way to recover exact evidence when the prompt only carries a reference.
Sources
- Read tool documentation, issue #40123 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- External file edits, issue #60684 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- Conversation revert, issue #60722 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- Rewind and retained file reads, issue #55042 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- Reads after reverting a conversation, issue #42264 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- Unchanged read after rewind, issue #68536 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- Repeated unchanged read rejections, issue #64882 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- Tool output substitution, issue #88118 (Anthropic Claude Code issue tracker, accessed 2026-11-30)
- Hooks reference (Anthropic, accessed 2026-11-30)
- Context window in Claude Code (Anthropic, accessed 2026-11-30)
- Context editing (Anthropic, accessed 2026-11-30)
- Prompt caching (Anthropic, accessed 2026-11-30)
- Claude API pricing (Anthropic, accessed 2026-11-30)
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
Deduplicate repeated file reads in a coding agent. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/dedupe-repeated-file-reads/
Sources
- Read tool documentation, issue 40123
- External file edits, issue 60684
- Conversation revert, issue 60722
- Rewind and retained file reads, issue 55042
- Reads after reverting a conversation, issue 42264
- Unchanged read after rewind, issue 68536
- Repeated unchanged read rejections, issue 64882
- Tool output substitution, issue 88118
- Hooks reference
- Context window in Claude Code
- Context editing
- Prompt caching
- Claude API pricing