Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

Clean up temporary state files after failed writes

aifanatic16253c740493
diff --git a/tests/test_contribution_state_temp_cleanup.py b/tests/test_contribution_state_temp_cleanup.py
new file mode 100644
index 0000000..7f31ba7
--- /dev/null
+++ b/tests/test_contribution_state_temp_cleanup.py
@@ -0,0 +1,18 @@
+import pytest
+from tokeneconomizer.plugin.store import Store
+
[email protected]("failure", ["serialize", "replace"])
+def test_failed_write_keeps_original_without_temporary_files(tmp_path, monkeypatch, failure):
+ store = Store(tmp_path)
+ store.write("state.json", {"old": True})
+ value = {"bad": object()}
+ error = TypeError
+ if failure == "replace":
+ def fail(*args):
+ raise OSError("replace failed")
+ monkeypatch.setattr("tokeneconomizer.plugin.store.os.replace", fail)
+ value, error = {"new": True}, OSError
+ with pytest.raises(error):
+ store.write("state.json", value)
+ assert store.read("state.json") == {"old": True}
+ assert not list(tmp_path.glob("*.tmp"))
diff --git a/tokeneconomizer/plugin/store.py b/tokeneconomizer/plugin/store.py
index 72b172d..b38e1b6 100644
--- a/tokeneconomizer/plugin/store.py
+++ b/tokeneconomizer/plugin/store.py
@@ -68,9 +68,15 @@ class Store:
target = self.path(name)
os.makedirs(os.path.dirname(target), exist_ok=True)
tmp = f"{target}.{os.getpid()}.tmp"
- with open(tmp, "w", encoding="utf-8") as fh:
- json.dump(obj, fh, indent=2, sort_keys=True)
- os.replace(tmp, target)
+ try:
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(obj, fh, indent=2, sort_keys=True)
+ os.replace(tmp, target)
+ finally:
+ try:
+ os.unlink(tmp)
+ except FileNotFoundError:
+ pass
return target
def append(self, name, record):