Skip to content

The agent that grows with you

fix(files): allow one full read after compaction

Enzo Adami02a6e9522884
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 26b15eb9372..edc7f2c3859 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -5574,13 +5574,10 @@ def compress_context(
else:
agent.context_compressor._verify_compaction_cleared_threshold = True
- # Reset the file-read dedup stub-hit counters. The dedup mtime map
- # is preserved on purpose: a file that hasn't changed since the task
- # last read it still returns the lightweight "unchanged" stub after
- # compression, instead of re-sending the full content — which would
- # re-bloat the context we just reclaimed and defeat dedup exactly
- # when long sessions need it most (issue #84857). Only the stub-hit
- # counters reset so the 2-stub hard block restarts fresh.
+ # Advance file-read dedup to a fresh generation while preserving the
+ # mtime map. The first read of each unchanged key returns full content
+ # that compaction may have omitted; later reads return lightweight
+ # stubs. Stub-hit counters restart at the same boundary (#84857).
try:
from tools.file_tools import reset_file_dedup
reset_file_dedup(task_id)
diff --git a/tests/tools/test_file_read_guards.py b/tests/tools/test_file_read_guards.py
index 1f32ee16cc1..52321a637f2 100644
--- a/tests/tools/test_file_read_guards.py
+++ b/tests/tools/test_file_read_guards.py
@@ -391,7 +391,7 @@ class TestFileDedup(unittest.TestCase):
_read_tracker.clear()
self._tmpdir = _make_safe_tempdir("hermes-dedup-")
self._tmpfile = os.path.join(self._tmpdir, "dedup_test.txt")
- with open(self._tmpfile, "w") as f:
+ with open(self._tmpfile, "w", encoding="utf-8") as f:
f.write("line one\nline two\n")
def tearDown(self):
@@ -463,7 +463,7 @@ class TestDedupStubLoopGuard(unittest.TestCase):
_read_tracker.clear()
self._tmpdir = tempfile.mkdtemp()
self._tmpfile = os.path.join(self._tmpdir, "loop_test.txt")
- with open(self._tmpfile, "w") as f:
+ with open(self._tmpfile, "w", encoding="utf-8") as f:
f.write("line one\nline two\n")
def tearDown(self):
@@ -530,7 +530,7 @@ class TestDedupStubLoopGuard(unittest.TestCase):
# File changes — mtime updates
time.sleep(0.05)
- with open(self._tmpfile, "w") as f:
+ with open(self._tmpfile, "w", encoding="utf-8") as f:
f.write("brand new content\n")
r4 = json.loads(read_file_tool(self._tmpfile, task_id="loop"))
@@ -591,12 +591,16 @@ class TestDedupStubLoopGuard(unittest.TestCase):
reset_file_dedup("loop")
- # Post-compression: block counters cleared — the unchanged file
- # returns the lightweight dedup stub (dedup map survives), with
- # no error and no hard block.
+ # Post-compression: block counters cleared and exact content is served
+ # once because the earlier payload may no longer be in context.
r4 = json.loads(read_file_tool(self._tmpfile, task_id="loop"))
self.assertNotIn("error", r4)
- self.assertTrue(r4.get("dedup"))
+ self.assertNotIn("dedup", r4)
+ self.assertIn("content", r4)
+
+ # The next unchanged read in this generation is lightweight again.
+ r5 = json.loads(read_file_tool(self._tmpfile, task_id="loop"))
+ self.assertTrue(r5.get("dedup"))
# ---------------------------------------------------------------------------
@@ -604,15 +608,13 @@ class TestDedupStubLoopGuard(unittest.TestCase):
# ---------------------------------------------------------------------------
class TestDedupResetOnCompression(unittest.TestCase):
- """reset_file_dedup should preserve the dedup mtime map so
- post-compression reads of unchanged files still return the lightweight
- stub (issue #84857)."""
+ """Compaction starts a new full-content recovery generation."""
def setUp(self):
_read_tracker.clear()
self._tmpdir = tempfile.mkdtemp()
self._tmpfile = os.path.join(self._tmpdir, "compress_test.txt")
- with open(self._tmpfile, "w") as f:
+ with open(self._tmpfile, "w", encoding="utf-8") as f:
f.write("original content\n")
def tearDown(self):
@@ -624,10 +626,10 @@ class TestDedupResetOnCompression(unittest.TestCase):
pass
@patch("tools.file_tools._get_file_ops")
- def test_reset_preserves_dedup(self, mock_ops):
- """After reset_file_dedup, the same read still returns the stub."""
+ def test_first_post_compaction_read_recovers_exact_content(self, mock_ops):
+ """First post-compaction read is full; later reads deduplicate."""
mock_ops.return_value = _make_fake_ops(
- content="original content\n", file_size=18,
+ content="SECRET_EXACT_LINE=42\n", file_size=21,
)
# First read — populates dedup cache
read_file_tool(self._tmpfile, task_id="comp")
@@ -639,11 +641,15 @@ class TestDedupResetOnCompression(unittest.TestCase):
# Simulate compression
reset_file_dedup("comp")
- # Read again — unchanged file still dedups: no full re-send, so
- # post-compaction re-reads don't re-inject the same content
+ # Exact prior bytes may have been omitted from the summary, so the
+ # first read in the new generation must restore them.
r_post = json.loads(read_file_tool(self._tmpfile, task_id="comp"))
- self.assertEqual(r_post.get("dedup"), True,
- "Post-compression read of unchanged file should stub")
+ self.assertNotIn("dedup", r_post)
+ self.assertIn("SECRET_EXACT_LINE=42", r_post.get("content", ""))
+
+ # The persisted mtime map still saves tokens after that recovery read.
+ r_again = json.loads(read_file_tool(self._tmpfile, task_id="comp"))
+ self.assertTrue(r_again.get("dedup"))
@patch("tools.file_tools._get_file_ops")
@@ -659,12 +665,12 @@ class TestDedupResetOnCompression(unittest.TestCase):
reset_file_dedup("loop")
- # 3rd read — still deduped (lightweight stub), not blocked
+ # First read in the new generation returns full content, not a stale
+ # block or a stub that points to compacted-away bytes.
r3 = json.loads(read_file_tool(self._tmpfile, task_id="loop"))
- # Should NOT be blocked or warned — counter restarted since dedup
- # intercepted reads before they reached the counter
self.assertNotIn("error", r3)
- self.assertTrue(r3.get("dedup"))
+ self.assertNotIn("dedup", r3)
+ self.assertIn("content", r3)
# ---------------------------------------------------------------------------
@@ -763,7 +769,7 @@ class TestWriteInvalidatesDedup(unittest.TestCase):
_read_tracker.clear()
self._tmpdir = _make_safe_tempdir("hermes-write-dedup-")
self._tmpfile = os.path.join(self._tmpdir, "write_dedup.txt")
- with open(self._tmpfile, "w") as f:
+ with open(self._tmpfile, "w", encoding="utf-8") as f:
f.write("original content\n")
def tearDown(self):
diff --git a/tools/file_tools.py b/tools/file_tools.py
index 322baed6704..7c4a5fff2ba 100644
--- a/tools/file_tools.py
+++ b/tools/file_tools.py
@@ -1133,10 +1133,12 @@ _file_ops_cache: dict = {}
# "read_history": set of (path, offset, limit) tuples for get_read_files_summary
# "dedup": dict mapping (resolved_path, offset, limit) → mtime float
# Used to skip re-reads of unchanged files. Survives
-# context compression: only the per-key stub-hit
-# counters are cleared on compression, so unchanged
-# files keep returning the lightweight stub instead of
-# re-sending full content (issue #84857).
+# context compression so unchanged files can resume
+# returning lightweight stubs after one recovery read.
+# "dedup_generation_reads": set of dedup keys whose full content has been
+# served since the latest compaction boundary. Cleared on
+# compression so the first post-compaction read can recover
+# exact bytes that the summary may have omitted.
# "read_timestamps": dict mapping resolved_path → modification-time float
# recorded when the file was last read (or written) by
# this task. Used by write_file and patch to detect
@@ -1242,6 +1244,15 @@ def _cap_read_tracker_data(task_data: dict) -> None:
except (StopIteration, KeyError):
break
+ generation_reads = task_data.get("dedup_generation_reads")
+ if generation_reads is not None and len(generation_reads) > _DEDUP_CAP:
+ excess = len(generation_reads) - _DEDUP_CAP
+ for _ in range(excess):
+ try:
+ generation_reads.pop()
+ except KeyError:
+ break
+
ts = task_data.get("read_timestamps")
if ts is not None and len(ts) > _READ_TIMESTAMPS_CAP:
excess = len(ts) - _READ_TIMESTAMPS_CAP
@@ -1801,7 +1812,8 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str =
task_data = _read_tracker.setdefault(task_id, {
"last_key": None, "consecutive": 0,
"read_history": set(), "dedup": {},
- "dedup_hits": {}, "read_timestamps": {},
+ "dedup_hits": {}, "dedup_generation_reads": set(),
+ "read_timestamps": {},
})
# Backward-compat for pre-existing tracker entries that predate
# dedup_hits/read_timestamps (long-lived task or crossed an
@@ -1810,12 +1822,14 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str =
task_data["dedup_hits"] = {}
if "read_timestamps" not in task_data:
task_data["read_timestamps"] = {}
+ generation_reads = task_data.setdefault("dedup_generation_reads", set())
cached_mtime = task_data.get("dedup", {}).get(dedup_key)
+ content_served_in_generation = dedup_key in generation_reads
if cached_mtime is not None:
try:
current_mtime = os.path.getmtime(resolved_str)
- if current_mtime == cached_mtime:
+ if current_mtime == cached_mtime and content_served_in_generation:
# Count repeated stub returns so weak tool-followers that
# ignore the "refer to earlier result" hint don't burn
# their iteration budget in an infinite read loop. After
@@ -1939,6 +1953,7 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str =
# reset its hit counter. (File either changed or stat failed
# earlier and we fell through.)
task_data["dedup_hits"].pop(dedup_key, None)
+ task_data.setdefault("dedup_generation_reads", set()).add(dedup_key)
task_data["read_history"].add((path, offset, limit))
if task_data["last_key"] == read_key:
task_data["consecutive"] += 1
@@ -2017,17 +2032,14 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str =
def reset_file_dedup(task_id: str = None):
- """Reset the read-dedup stub-hit counters after context compression.
+ """Advance the read-dedup generation after context compression.
Called after context compression. The per-key ``dedup`` mtime map is
- PRESERVED: a file that has not changed on disk since the task last read
- it still returns the lightweight "unchanged" stub instead of re-sending
- the full content — this is what stops long-session token usage from
- re-bloating the context we just reclaimed after every compaction
- (issue #84857). Only the per-key stub-hit counters (``dedup_hits``)
- are cleared, so the 2-stub hard block restarts fresh: a model that hits
- the stub right after compression is never blocked by hits accumulated
- before it.
+ preserved, but the generation-read set is cleared. The first unchanged
+ read of each key after compaction therefore returns full content that may
+ have been summarized away; later reads in the same generation return the
+ lightweight stub. Stub-hit counters are also cleared so the hard block
+ restarts fresh (issue #84857).
Call with a task_id to reset just that task, or without to reset all.
"""
@@ -2037,10 +2049,12 @@ def reset_file_dedup(task_id: str = None):
if task_data:
if "dedup_hits" in task_data:
task_data["dedup_hits"].clear()
+ task_data.setdefault("dedup_generation_reads", set()).clear()
else:
for task_data in _read_tracker.values():
if "dedup_hits" in task_data:
task_data["dedup_hits"].clear()
+ task_data.setdefault("dedup_generation_reads", set()).clear()
def notify_other_tool_call(task_id: str = "default"):