Skip to content

The agent that grows with you

perf(state): the ancestor stamp's unset probe reads only the walked rows

kshitijk4poor22c9cf36a736
diff --git a/hermes_state_compression.py b/hermes_state_compression.py
index bb98dfed046..31ad895dc58 100644
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@ -115,6 +115,8 @@ _CREATED_ROW_SQL = "SELECT parent_session_id, created_source FROM sessions WHERE
# surface? One query, so a fully stamped chain is skipped without the per-hop validated walk below.
# A parent that did not end by compression (a reset or branch source) is not a chain edge, so an
# unset row behind one does not send every write down that walk.
+# CROSS JOIN keeps ``up`` the outer loop: without ANALYZE stats SQLite otherwise scans sessions
+# and probes ``up`` for each row, a full-table read on every stamped write.
_UNSET_ANCESTOR_SQL = """
WITH RECURSIVE up(pid, n) AS (
SELECT parent_session_id, 1 FROM sessions WHERE id = ?
@@ -122,7 +124,7 @@ _UNSET_ANCESTOR_SQL = """
SELECT s.parent_session_id, up.n + 1 FROM up JOIN sessions s ON s.id = up.pid
WHERE s.end_reason = 'compression' AND s.created_source = ? AND up.n < ?
)
- SELECT 1 FROM up JOIN sessions s ON s.id = up.pid
+ SELECT 1 FROM up CROSS JOIN sessions s ON s.id = up.pid
WHERE s.end_reason = 'compression' AND """ + _UNSET_CREATED_SQL.format(col="s.created_source") + """
LIMIT 1
"""
diff --git a/tests/hermes_state/test_compression_created_source.py b/tests/hermes_state/test_compression_created_source.py
index e1f7d6552ce..1921d3929b0 100644
--- a/tests/hermes_state/test_compression_created_source.py
+++ b/tests/hermes_state/test_compression_created_source.py
@@ -118,3 +118,17 @@ def test_unset_parent_behind_a_reset_edge_takes_the_fast_path(tmp_path):
assert _created(db, "legacy") is None
finally:
db.close()
+
+
+def test_unset_ancestor_probe_reads_only_the_walked_rows(tmp_path):
+ """The fast path runs on every usage write of a stamped compression child: its final lookup
+ must join the walked ids to sessions by key, never scan the table (ms per write at 30k rows)."""
+ from hermes_state_compression import _CHAIN_CAP, _UNSET_ANCESTOR_SQL
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ plan = [row[3] for row in db._conn.execute(
+ "EXPLAIN QUERY PLAN " + _UNSET_ANCESTOR_SQL, ("tip", "cli", _CHAIN_CAP))]
+ assert not [step for step in plan if step.startswith("SCAN") and "up" not in step.split()], plan
+ finally:
+ db.close()