Product case study · November 24, 2026

Ask Claude Code why a file reader keeps returning yesterday's text

Reproduce a stale file-read cache, give Claude Code a freshness contract, and test edits, deletions and invalid UTF-8 in one Python process.

Reading time
6 min
Checked
Nov 24, 2026
A charcoal paper archive holds an old blue card beside a fresh ochre card and a circular arrow on warm paper.
The same filename can point to different evidence tomorrow.
Bottom line

If every call must read the current file, caching by pathname breaks the contract. Test a second read after the file changes.

Your report script reads a brief, you edit the brief, and the next report still contains the old wording. Restarting the script appears to fix it. That is a useful clue: the program may be remembering a result that no longer describes the file.

In this lab, ask Claude Code to repair a Python reader whose cache survives between calls. The important decision comes before the patch: must a read use the current file, or is an older snapshot acceptable? Here, every call must read again.

You’ll need Bash on macOS, Linux or WSL, Python 3, and an installed, signed-in Claude Code. The Python fixture and reference repair were tested locally on November 24, 2026. The agent prompt is an authored exercise, not a recorded Claude run. Official sources were checked on the same date. All files are disposable local samples.

Reproduce two reads with an edit between them

Create a practice folder and save the deliberately broken reader:

cache_lab=$(mktemp -d /tmp/claude-file-cache.XXXXXX)
cd "$cache_lab"
cat > reader.py <<'PY'
from functools import lru_cache
from pathlib import Path


@lru_cache(maxsize=32)
def read_brief(path):
    return Path(path).read_text(encoding="utf-8")
PY
cat > demo.py <<'PY'
from pathlib import Path
from tempfile import TemporaryDirectory
from reader import read_brief

with TemporaryDirectory() as folder:
    path = Path(folder) / "brief.txt"
    path.write_text("draft", encoding="utf-8")
    print(read_brief(path))
    path.write_text("ready", encoding="utf-8")
    print(read_brief(path))
PY
python3 demo.py

The broken demo prints draft twice. Both reads happen inside one process, and the write completes before the second call. Running two separate Python commands would miss this reproduction because each starts with a new cache.

Python’s lru_cache reference documents reuse of results based on function arguments. Our argument is a path; editing its contents does not change that argument. The decorator has no instruction to check the file again.

Give freshness a testable meaning

Save this as SPEC.md:

read_brief(path) accepts an absolute pathlib.Path to a small local file.
On every call, read the file as UTF-8 and return its text without stripping
whitespace. A completed edit before the call must be visible to that call.
A missing file must raise FileNotFoundError, including after a successful read.
Invalid UTF-8 must raise UnicodeDecodeError, including after a successful read.
Do not serve the last successful value when the current read fails.
An empty file returns an empty string. Do not write to the input file.
There is no caching or speed requirement. Concurrent writers, remote filesystems,
byte-for-byte newline preservation and relative paths are out of scope.
Change only reader.py. Keep this spec, demo.py and test_reader.py fixed.
Use only the standard library. Do not install packages or access the network.

The failure policy matters. Returning old text after a file disappears can make a report look complete when its source is gone. This exercise requires an error so the caller can decide what to do.

Save the following as test_reader.py. Each test gets a fresh directory; the two reads within a test deliberately share a process and pathname.

import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from reader import read_brief


class ReaderTests(unittest.TestCase):
    def setUp(self):
        self.folder = TemporaryDirectory()
        self.addCleanup(self.folder.cleanup)
        self.path = Path(self.folder.name) / "brief.txt"

    def test_completed_edit_is_visible(self):
        self.path.write_text("draft", encoding="utf-8")
        self.assertEqual(read_brief(self.path), "draft")
        self.path.write_text("ready", encoding="utf-8")
        self.assertEqual(read_brief(self.path), "ready")

    def test_deleted_file_raises(self):
        self.path.write_text("draft", encoding="utf-8")
        self.assertEqual(read_brief(self.path), "draft")
        self.path.unlink()
        with self.assertRaises(FileNotFoundError):
            read_brief(self.path)

    def test_invalid_utf8_after_success_raises(self):
        self.path.write_text("draft", encoding="utf-8")
        self.assertEqual(read_brief(self.path), "draft")
        self.path.write_bytes(b"\xff")
        with self.assertRaises(UnicodeDecodeError):
            read_brief(self.path)

    def test_empty_file(self):
        self.path.write_text("", encoding="utf-8")
        self.assertEqual(read_brief(self.path), "")

    def test_preserves_text_and_does_not_write(self):
        text = "  café\nsecond line\n"
        self.path.write_text(text, encoding="utf-8")
        before = self.path.read_bytes()
        self.assertEqual(read_brief(self.path), text)
        self.assertEqual(self.path.read_bytes(), before)

Run the baseline with Python’s standard-library unittest runner:

python3 -m unittest -v test_reader

Locally, five tests ran and three failed: the completed edit, deletion and invalid UTF-8 checks. Empty input and text preservation already passed. Keeping those passing checks protects useful behavior while the agent repairs freshness.

Ask Claude to repair the reader

Start claude from the practice folder and paste:

Read SPEC.md, reader.py, demo.py and test_reader.py.
Run python3 demo.py and python3 -m unittest -v test_reader.
Explain why the second read returns old content even though the write finished.
Repair only reader.py to satisfy the existing freshness and error contract.
Do not edit tests, spec or demo, install packages, commit or delegate.
Do not add a timeout, background watcher or caller-managed invalidation step.
Run both commands again and report their actual output and exit status.
Explain the tradeoff of your patch and any behavior these tests do not prove.

Anthropic’s debugging workflow recommends providing reproduction commands and steps. Here, the tests also prevent “fixing” the symptom by weakening the requirement. Review active tool permissions: a prompt specifies requested scope but does not create a filesystem sandbox.

If the agent proposes restarting the program after every edit, point it back to the two calls in one process. If it changes the expected value to draft, reject the test edit. If it catches every read error and returns the previous text, rerun the deletion test: the contract explicitly requires that failure to remain visible.

Review the smallest reference repair

Replace the contents of reader.py with:

from pathlib import Path


def read_brief(path):
    return Path(path).read_text(encoding="utf-8")

This removes the decorator and its unused import. Path.read_text opens the file, returns decoded text and closes it. There is no application-level saved result between calls.

Run the same commands:

python3 -m unittest -v test_reader
python3 demo.py

The reference repair passed all five tests locally, and the demo printed:

draft
ready

The tradeoff is an actual file read for every call. That is the requested behavior for this small brief reader; this lab makes no speed claim. It also does not prove safe behavior while another process is halfway through rewriting a file. A completed write before a read is a narrower promise than a consistent snapshot during concurrent writes.

If the application really needs caching

Decide how old a result may be and who is responsible for invalidating it before adding caching back. Python exposes cache_clear() for explicit invalidation, but making every caller remember to use it would change this lab’s interface contract. A time limit would likewise allow old content during the permitted interval.

For this fixture, a quick review question catches another incomplete fix: would the patch still work when draft becomes ready? They have the same length. File size alone cannot distinguish them. The first regression test deliberately keeps that case.

Keep the before-and-after evidence with your change: the baseline failures, the repaired test result, and the demo’s two different lines. For an agent-generated report tool, that evidence is more useful than a reassuring statement that the cache was refreshed.

Sources

Checked November 24, 2026:

Put this to work

Why caching a function's pathname argument does not track changes to the file.

Try

Give Claude Code a small file reader, a fixed contract and five regression tests.

Prove it worked

Run the same tests before and after the repair without restarting between reads.

Keep in view

  • Reproduce a reader that returns old text after a completed edit.
  • Define freshness before asking an agent to optimize file access.
  • Check changed, deleted and invalid files inside the same process.
Learn the workflow: Set up your first Claude Code project session