Product case study · November 17, 2026

Ask Claude Code to fix a JSON save that destroys the old file

Reproduce a destructive JSON save, ask Claude Code for an atomic replacement, and test that failed writes preserve the previous file.

Reading time
7 min
Checked
Nov 17, 2026
Superbash Learn default editorial graphic used for this Python file-saving tutorial
Prepare the replacement before touching the last good copy.
Bottom line

A failed save should leave the previous file readable. Test that promise before trusting a successful round trip.

A settings save throws an error. You fix the input and try again, only to discover that the previous settings have already vanished. The mistake happened before the error: the program opened the only good copy in write mode.

This exercise gives Claude Code a file-saving bug with a concrete acceptance rule: if preparation or replacement fails, preserve the old bytes. A successful save alone cannot prove that rule. You need to make a save fail on purpose.

You need Python 3.8 or newer, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. Use a disposable local directory with ordinary files, one writer and no symlinks. The Python baseline and reference repair below were tested locally; the agent prompt is an authored exercise, not a recorded Claude session. Official documentation was checked November 17, 2026.

Make the destructive save visible

Create the practice folder and a deliberately unsafe implementation:

save_lab=$(mktemp -d)
cd "$save_lab"
cat > saver.py <<'PY'
import json
import os

def save_json(path, data):
    with open(path, "w", encoding="utf-8") as stream:
        json.dump(data, stream, ensure_ascii=False, allow_nan=False)
PY

Python documents that open with mode w truncates an existing file. Meanwhile, JSON encoding can reject an unsupported object. The order matters: even if encoding fails immediately, opening the target has already discarded its contents.

Save the following as test_saver.py. Each test gets its own temporary directory, so the exercise never needs your real settings file.

import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from saver import save_json

class SaveTests(unittest.TestCase):
    def setUp(self):
        self.folder = tempfile.TemporaryDirectory()
        self.addCleanup(self.folder.cleanup)
        self.root = Path(self.folder.name)
        self.target = self.root / "settings.json"
        self.old = b'{"theme": "old"}\n'
        self.target.write_bytes(self.old)

    def assert_only_target(self):
        self.assertEqual(set(self.root.iterdir()), {self.target})

    def test_success(self):
        data = {"theme": "caf\u00e9"}
        save_json(self.target, data)
        self.assertEqual(json.loads(self.target.read_text("utf-8")), data)
        self.assert_only_target()

    def test_bad_value_preserves_old(self):
        with self.assertRaises(TypeError):
            save_json(self.target, {"bad": object()})
        self.assertEqual(self.target.read_bytes(), self.old)
        self.assert_only_target()

    def test_nan_preserves_old(self):
        with self.assertRaises(ValueError):
            save_json(self.target, {"bad": float("nan")})
        self.assertEqual(self.target.read_bytes(), self.old)
        self.assert_only_target()

    def test_replace_failure_preserves_old(self):
        with patch("saver.os.replace", side_effect=OSError("injected")) as replace:
            with self.assertRaisesRegex(OSError, "injected"):
                save_json(self.target, {"theme": "new"})
            replace.assert_called_once()
        self.assertEqual(self.target.read_bytes(), self.old)
        self.assert_only_target()

if __name__ == "__main__":
    unittest.main()

Run python3 -m unittest -v. The baseline passes the success test and fails the other three. The replacement test also checks a specific design choice: this exercise requires os.replace, and the baseline never calls it. That injected error is a controlled test, not a simulation of every disk failure.

Give the agent a failure contract

Start claude in the practice folder. Check its working directory and active permissions, then paste:

Read saver.py and test_saver.py. Run python3 -m unittest -v.
Explain when the existing file loses its contents.

Change only saver.py. Keep save_json(path, data).
Serialize strict JSON before touching the destination: UTF-8,
ensure_ascii=False, allow_nan=False. Use a unique temporary file
in the target's parent directory. Close it before os.replace.
Never open the destination in write mode or delete it first.
Propagate failures and clean up the temporary file on normal
exception paths. Preserve the original bytes if replacement fails.

Use the Python standard library. Do not change tests, install
packages, commit, delegate or access external services.
Run the unchanged tests and report actual results. If execution
is unavailable, say so. Explain what this does NOT guarantee
about power loss, permissions or concurrent writers.

Anthropic’s common workflows recommends giving debugging tasks a reproduction and a verification command. Here, the failure contract prevents the agent from declaring victory after writing one valid JSON file. The prompt scopes the work; review tool requests because prose instructions are not filesystem isolation.

Inspect where the replacement happens

This is a reference repair to compare with the agent’s result:

import json
import os
from pathlib import Path
import tempfile

def save_json(path, data):
    path = Path(path)
    payload = json.dumps(
        data, ensure_ascii=False, allow_nan=False
    ).encode("utf-8")
    temporary = None
    try:
        with tempfile.NamedTemporaryFile(
            mode="wb", dir=path.parent,
            prefix=f".{path.name}.", suffix=".tmp", delete=False
        ) as stream:
            temporary = Path(stream.name)
            stream.write(payload)
        os.replace(temporary, path)
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)

json.dumps creates the serialized string before any destination change. Encoding it before creating the temporary file also catches UTF-8 encoding errors at that stage. This holds the full payload in memory, which is reasonable for small settings files, not a recommendation for huge exports.

NamedTemporaryFile supplies a unique name. delete=False keeps the temporary file available after closing; the finally block handles cleanup. Placing it beside the target avoids the cross-filesystem replacement problem. The code closes the stream before replacing the destination.

Python documents os.replace as atomic when successful, with the POSIX requirement noted. This means the replacement is a single filesystem operation rather than a sequence that empties and refills the destination. An already-open reader may still hold the old file; the operation does not update every reader’s existing handle.

Exit Claude and run python3 -m unittest -v yourself. The reference implementation passed all four checks locally. Inspect the implementation as well: a green test suite is not permission to remove the close-before-replace step or move the temporary file to an unrelated filesystem.

Decide whether this is enough for your application

I would use this exercise to teach an agent what a failed operation must preserve. That is often a more useful requirement than “handle errors gracefully,” which says little about the state left behind.

The repair has deliberate limits:

  • No power-loss durability promise. Closing a stream is not a disk-sync protocol. This example does not call fsync on the file or parent directory, and these tests do not emulate a crash.
  • No writer coordination. Two writers can each prepare a valid replacement; the later replacement can overwrite the earlier one’s work. Applications needing conflict detection require a separate design.
  • No metadata preservation. The replacement uses the temporary file’s metadata. Existing permissions, ownership and extended attributes are not copied by this function.
  • Cleanup can fail too. A killed process can leave a temporary file behind. A permission error during cleanup can mask an earlier exception. Production recovery needs to account for both.

If the injected failure test fails, first check for an early destination write or a swallowed exception. If replacement fails on a real machine, retain the original and investigate directory permissions and filesystem behavior; do not “fix” it by deleting the destination before renaming. If only cleanup fails, inspect the specific temporary path instead of deleting every .tmp file in the directory.

Keep the exercise in its disposable folder until your application has an explicit policy for durability, concurrent writers and metadata. Those are separate promises, and each deserves its own evidence.

Sources

Checked November 17, 2026:

Put this to work

The difference between atomic replacement, durability and concurrent-writer coordination.

Try

Repair a Python JSON saver in a disposable practice folder.

Prove it worked

Run four checks covering success, rejected data, replacement failure and temporary-file cleanup.

Keep in view

  • Expose a save that truncates the old file before serialization succeeds.
  • Ask Claude Code to write a temporary sibling and replace the target.
  • Inject a replacement failure and check the original bytes survive.
Learn the workflow: Start a supervised Claude Code project session