Skip to content

The agent that grows with you

perf(state): reuse unchanged local lineage projections

Tugrul Guner3e8e7bd3bfbf
diff --git a/hermes_state_local.py b/hermes_state_local.py
index dfb6541d93c..fd39d4c1bf1 100644
--- a/hermes_state_local.py
+++ b/hermes_state_local.py
@@ -1,6 +1,8 @@
"""Private local creation receipts in the canonical runtime transaction owner."""
import json
+import threading
import time
+from collections import OrderedDict
from hermes_state_runtime import RuntimeStoreError, _epoch, _json
@@ -326,11 +328,48 @@ def local_lineage_index(conn):
return superseded, heads
+def _lineage_version(conn):
+ # data_version sees OTHER connections' commits; total_changes sees this connection's writes.
+ return conn.total_changes, conn.execute('PRAGMA main.data_version').fetchone()[0]
+
+
+def _copy_lineage_index(value):
+ superseded, heads = value
+ return set(superseded), {key: (owner, list(lineage)) for key, (owner, lineage) in heads.items()}
+
+
+def _cached_local_lineage_index(db, conn):
+ # Owned by this SessionDB, not a process-global path/id cache. Bound retained connections
+ # across read-pool churn and close/reopen; a closed/replaced connection cannot match a new one.
+ cache, lock = db.__dict__.setdefault('_local_lineage_cache', (OrderedDict(), threading.Lock()))
+ if conn.in_transaction:
+ # A snapshot or uncommitted answer must never outlive its transaction (including rollback).
+ with lock:
+ cache.pop(conn, None)
+ return local_lineage_index(conn)
+ version = _lineage_version(conn)
+ with lock:
+ saved = cache.get(conn)
+ if saved is not None and saved[0] == version:
+ cache.move_to_end(conn)
+ return _copy_lineage_index(saved[1])
+ value = local_lineage_index(conn)
+ # A concurrent writer may commit between the receipt scan and the end_reason reads. Never
+ # publish that in-flight projection as a stable cache entry; the next call must rebuild it.
+ if not conn.in_transaction and _lineage_version(conn) == version:
+ with lock:
+ cache[conn] = (version, value)
+ cache.move_to_end(conn)
+ if len(cache) > 8:
+ cache.popitem(last=False)
+ return _copy_lineage_index(value)
+
+
def exclude_superseded_segments(db, where_clauses, params):
"""Drop earlier reset segments from a listing or count query (one conversation, one row),
in SQL before paging; returns ``heads`` for :func:`annotate_local_lineages`."""
with db._read_ctx() as conn:
- superseded, heads = local_lineage_index(conn)
+ superseded, heads = _cached_local_lineage_index(db, conn)
if superseded:
where_clauses.append("s.id NOT IN (SELECT value FROM json_each(?))")
params.append(json.dumps(sorted(superseded)))
diff --git a/scripts/benchmark_local_lineage.py b/scripts/benchmark_local_lineage.py
new file mode 100644
index 00000000000..69d490ac662
--- /dev/null
+++ b/scripts/benchmark_local_lineage.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""Measure #143833's projection on synthetic data, never the user's state.db.
+
+Run: python scripts/benchmark_local_lineage.py --prompt-bytes 8192
+The unchanged index builder is the uncached control; the cached path is the one
+used by session list/count calls. Timings are component timings, not UI latency.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import platform
+import sqlite3
+import statistics
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from hermes_state import SessionDB
+from hermes_state_local import POLICY_PREFIX, _cached_local_lineage_index, local_lineage_index
+
+
+def measure(fn, repeat, expected):
+ samples = []
+ for _ in range(repeat):
+ start = time.perf_counter_ns()
+ result = fn()
+ samples.append((time.perf_counter_ns() - start) / 1_000_000)
+ assert result == expected
+ return {'median_ms': statistics.median(samples), 'min_ms': min(samples), 'max_ms': max(samples)}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--receipts', type=int, default=2098)
+ parser.add_argument('--sessions', type=int, default=4583)
+ parser.add_argument('--prompt-bytes', type=int, default=8192)
+ parser.add_argument('--reset-lineages', type=int, default=0)
+ parser.add_argument('--repeat', type=int, default=9)
+ args = parser.parse_args()
+ if not (0 <= args.reset_lineages <= args.receipts and args.sessions >= args.receipts + args.reset_lineages
+ and args.receipts > 0 and args.prompt_bytes >= 0 and args.repeat > 0):
+ parser.error('positive counts, nonnegative payload, and enough sessions for owners plus reset children required')
+ with tempfile.TemporaryDirectory(prefix='hermes-lineage-bench-') as folder:
+ db = SessionDB(db_path=Path(folder) / 'state.db')
+ try:
+ conn = db._conn
+ assert conn is not None
+ conn.executemany('INSERT INTO sessions(id,source,started_at,end_reason) VALUES(?,?,0,?)', (
+ (f's-{i}', 'cli', 'session_reset' if i < args.reset_lineages else None)
+ for i in range(args.sessions)))
+ conn.executemany('INSERT INTO state_meta(key,value) VALUES(?,?)', (
+ (POLICY_PREFIX + f's-{i}', json.dumps({
+ 'session_id': f's-{i}',
+ 'lineage': [f's-{i}', f's-{args.receipts+i}'] if i < args.reset_lineages else [f's-{i}'],
+ 'policy': {'request_json': json.dumps({'prompt': 'x' * args.prompt_bytes})},
+ })) for i in range(args.receipts)))
+ conn.commit()
+ with db._read_ctx() as reader:
+ expected = local_lineage_index(reader)
+ assert len(expected[0]) == args.reset_lineages
+ uncached = measure(lambda: local_lineage_index(reader), args.repeat, expected)
+ cold = measure(lambda: _cached_local_lineage_index(db, reader), 1, expected)
+ warm = measure(lambda: _cached_local_lineage_index(db, reader), args.repeat, expected)
+ scans = []
+ reader.set_trace_callback(lambda sql: scans.append(sql) if 'FROM state_meta' in sql and 'GLOB' in sql else None)
+ try:
+ for _ in range(args.repeat):
+ assert _cached_local_lineage_index(db, reader) == expected
+ warm_scans = len(scans)
+ # Any committed DB write conservatively invalidates, not just receipt writes.
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', ('benchmark-write', '1'))
+ conn.commit()
+ invalidated = measure(lambda: _cached_local_lineage_index(db, reader), 1, expected)
+ invalidated_scans = len(scans) - warm_scans
+ finally:
+ reader.set_trace_callback(None)
+ assert warm_scans == 0 and invalidated_scans == 1
+ print(json.dumps({
+ 'workload': vars(args), 'python': platform.python_version(), 'sqlite': sqlite3.sqlite_version,
+ 'platform': platform.system(), 'synthetic': True, 'uncached': uncached,
+ 'cache_first_read': cold, 'cache_warm': warm, 'after_committed_write': invalidated,
+ 'warm_receipt_scans': warm_scans, 'after_write_receipt_scans': invalidated_scans,
+ }, indent=2))
+ finally:
+ db.close()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/hermes_state/test_local_lineage_cache.py b/tests/hermes_state/test_local_lineage_cache.py
new file mode 100644
index 00000000000..8e07499600e
--- /dev/null
+++ b/tests/hermes_state/test_local_lineage_cache.py
@@ -0,0 +1,179 @@
+"""Regression for #143833: reuse reset projections without stale SQLite snapshots."""
+import json
+import sqlite3
+from concurrent.futures import ThreadPoolExecutor
+from threading import Barrier
+
+import pytest
+
+from hermes_state import SessionDB
+from hermes_state_local import POLICY_PREFIX, _cached_local_lineage_index
+
+
+def db(tmp_path):
+ database = SessionDB(db_path=tmp_path / 'state.db')
+ database.create_session('owner', source='cli')
+ database.create_session('head', source='cli')
+ assert database._conn is not None
+ database._conn.execute("UPDATE sessions SET end_reason='session_reset' WHERE id='owner'")
+ database._conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (
+ POLICY_PREFIX + 'owner', json.dumps({'session_id': 'owner', 'lineage': ['owner', 'head']})))
+ database._conn.commit()
+ yield database
+ database.close()
+
+
+def _receipt_scans(statements):
+ return [sql for sql in statements if 'FROM state_meta' in sql and 'GLOB' in sql and POLICY_PREFIX in sql]
+
+
+def test_unchanged_session_lists_and_counts_scan_receipts_once(db):
+ statements = []
+ with db._read_ctx() as conn:
+ conn.set_trace_callback(statements.append)
+ for _ in range(5):
+ rows = db.list_sessions_rich(limit=10)
+ assert [row['id'] for row in rows] == ['head']
+ assert set(rows[0]['_lineage_ids']) == {'owner', 'head'}
+ assert db.session_count(exclude_children=True) == 1
+ assert db.session_count_by_source(exclude_children=True) == {'cli': 1}
+ assert len(_receipt_scans(statements)) == 1
+
+
[email protected]('mutation', ['extend', 'retire', 'end_reason', 'delete_head'])
+def test_committed_writer_changes_refresh_the_pooled_reader(db, mutation):
+ assert [row['id'] for row in db.list_sessions_rich()] == ['head']
+ assert db._conn is not None
+ if mutation == 'extend':
+ db.create_session('tail', source='cli')
+ db._conn.execute("UPDATE sessions SET end_reason='session_reset' WHERE id='head'")
+ db._conn.execute('UPDATE state_meta SET value=? WHERE key=?', (
+ json.dumps({'session_id': 'owner', 'lineage': ['owner', 'head', 'tail']}), POLICY_PREFIX + 'owner'))
+ expected = {'tail'}
+ elif mutation == 'retire':
+ db._conn.execute('DELETE FROM state_meta WHERE key=?', (POLICY_PREFIX + 'owner',))
+ expected = {'owner', 'head'}
+ elif mutation == 'end_reason':
+ db._conn.execute("UPDATE sessions SET end_reason='compression' WHERE id='owner'")
+ expected = {'owner', 'head'}
+ else:
+ db._conn.execute("DELETE FROM sessions WHERE id='head'")
+ expected = set()
+ db._conn.commit()
+ assert {row['id'] for row in db.list_sessions_rich()} == expected
+ assert db.session_count(exclude_children=True) == len(expected)
+
+
[email protected]('finish', ['commit', 'rollback'])
+def test_same_connection_transactions_do_not_publish_intermediate_results(db, finish):
+ conn = db._conn
+ assert conn is not None
+ before = _cached_local_lineage_index(db, conn)
+ conn.execute('BEGIN')
+ conn.execute('DELETE FROM state_meta WHERE key=?', (POLICY_PREFIX + 'owner',))
+ assert _cached_local_lineage_index(db, conn) == (set(), {})
+ getattr(conn, finish)()
+ expected = (set(), {}) if finish == 'commit' else before
+ assert _cached_local_lineage_index(db, conn) == expected
+ # Same-connection autocommit writes must invalidate too (data_version alone cannot see them).
+ conn.execute('INSERT OR REPLACE INTO state_meta(key,value) VALUES(?,?)', (
+ POLICY_PREFIX + 'owner', json.dumps({'session_id': 'owner', 'lineage': ['owner', 'head']})))
+ conn.commit()
+ assert _cached_local_lineage_index(db, conn) == before
+
+
+def test_read_snapshot_does_not_outlive_its_transaction(db):
+ with db._read_ctx() as reader:
+ before = _cached_local_lineage_index(db, reader)
+ reader.execute('BEGIN')
+ assert _cached_local_lineage_index(db, reader) == before
+ assert db._conn is not None
+ db._conn.execute('DELETE FROM state_meta WHERE key=?', (POLICY_PREFIX + 'owner',))
+ db._conn.commit()
+ assert _cached_local_lineage_index(db, reader) == before
+ reader.rollback()
+ assert _cached_local_lineage_index(db, reader) == (set(), {})
+
+
+def test_commit_during_projection_is_not_cached_as_a_stable_result(db):
+ statements = []
+ changed = False
+ with db._read_ctx() as reader:
+ def trace(sql):
+ nonlocal changed
+ statements.append(sql)
+ if not changed and 'SELECT id,end_reason' in sql:
+ changed = True
+ assert db._conn is not None
+ db._conn.execute('DELETE FROM state_meta WHERE key=?', (POLICY_PREFIX + 'owner',))
+ db._conn.commit()
+ reader.set_trace_callback(trace)
+ try:
+ _cached_local_lineage_index(db, reader)
+ assert changed
+ assert _cached_local_lineage_index(db, reader) == (set(), {})
+ assert _cached_local_lineage_index(db, reader) == (set(), {})
+ finally:
+ reader.set_trace_callback(None)
+ assert len(_receipt_scans(statements)) == 2
+
+
+def test_callers_cannot_mutate_the_cached_projection(db):
+ with db._read_ctx() as reader:
+ superseded, heads = _cached_local_lineage_index(db, reader)
+ superseded.clear()
+ heads['head'][1].append('foreign-session')
+ heads.clear()
+ assert _cached_local_lineage_index(db, reader) == ({'owner'}, {'head': ('owner', ['owner', 'head'])})
+
+
+def test_connection_churn_is_bounded_and_other_databases_stay_isolated(db, tmp_path):
+ # Real handles can churn independently of the pool without retaining an unbounded cache.
+ conns = [sqlite3.connect(f'file:{db.db_path}?mode=ro', uri=True) for _ in range(12)]
+ try:
+ for conn in conns:
+ assert _cached_local_lineage_index(db, conn)[0] == {'owner'}
+ cache, _lock = db._local_lineage_cache
+ assert len(cache) <= 8
+ other = SessionDB(db_path=tmp_path / 'other.db')
+ try:
+ with other._read_ctx() as conn:
+ assert _cached_local_lineage_index(other, conn) == (set(), {})
+ finally:
+ other.close()
+ finally:
+ for conn in conns:
+ conn.close()
+
+
+def test_concurrent_lists_keep_the_same_projection(db):
+ barrier = Barrier(6)
+ def read(_):
+ barrier.wait(timeout=10)
+ return [{row['id'] for row in db.list_sessions_rich()} for _ in range(5)]
+ with ThreadPoolExecutor(max_workers=6) as pool:
+ for result in pool.map(read, range(6)):
+ assert result == [{'head'}] * 5
+
+
+def test_read_only_legacy_database_needs_no_schema_change(tmp_path):
+ path = tmp_path / 'legacy.db'
+ conn = sqlite3.connect(path)
+ conn.executescript('CREATE TABLE sessions(id TEXT PRIMARY KEY,end_reason TEXT);'
+ 'CREATE TABLE state_meta(key TEXT PRIMARY KEY,value TEXT);')
+ conn.executemany('INSERT INTO sessions VALUES(?,?)', [('old', 'session_reset'), ('new', None)])
+ conn.execute('INSERT INTO state_meta VALUES(?,?)', (
+ POLICY_PREFIX + 'old', json.dumps({'session_id': 'old', 'lineage': ['old', 'new']})))
+ conn.commit()
+ conn.close()
+ before = path.read_bytes()
+ db = SessionDB(db_path=path, read_only=True)
+ try:
+ with db._read_ctx() as reader:
+ expected = ({'old'}, {'new': ('old', ['old', 'new'])})
+ assert _cached_local_lineage_index(db, reader) == expected
+ assert _cached_local_lineage_index(db, reader) == expected
+ finally:
+ db.close()
+ assert path.read_bytes() == before