From 26ca96adfe837bc06208866e44b6d739e84f765b Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 16:38:57 +0700 Subject: [PATCH 01/12] fix: preserve prose around embedded externalized references --- reconcile.py | 3 ++- tests/test_native_carrier_replay.py | 38 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tests/test_native_carrier_replay.py diff --git a/reconcile.py b/reconcile.py index 1aecad3c0..415be8c23 100644 --- a/reconcile.py +++ b/reconcile.py @@ -27,6 +27,7 @@ from .externalize import ( extract_externalized_ref, + is_externalized_placeholder, externalized_tool_result_has_persisted_output_marker, find_externalized_tool_result_content_for_call, load_externalized_payload, @@ -467,7 +468,7 @@ def live_file_generation_identity() -> str: session_id=session_id, ) tool_calls = self._restore_ingest_payload_placeholders_in_value(tool_calls, session_id=session_id) - ref = extract_externalized_ref(content) + ref = extract_externalized_ref(content) if is_externalized_placeholder(content) else None if ref and "quarantined_assistant_output" not in content: payload = load_externalized_payload( ref, diff --git a/tests/test_native_carrier_replay.py b/tests/test_native_carrier_replay.py new file mode 100644 index 000000000..c4a53159b --- /dev/null +++ b/tests/test_native_carrier_replay.py @@ -0,0 +1,38 @@ +"""Embedded archive references must not replace a native carrier's prose.""" +from hermes_lcm.config import LCMConfig +from hermes_lcm.engine import LCMEngine +from hermes_lcm.externalize import is_externalized_placeholder, maybe_externalize_payload + + +def test_native_carrier_embedded_reference_preserves_cold_replay(tmp_path): + config = LCMConfig(database_path=str(tmp_path / "lcm.db"), + large_output_externalization_enabled=True, + large_output_externalization_threshold_chars=1000) + home = str(tmp_path / "home") + engine = LCMEngine(config=config, hermes_home=home) + engine.on_session_start("carrier", conversation_id="owned", platform="cli", context_length=200000) + archived = "different archived payload " * 1300 + inner = maybe_externalize_payload(archived, kind="raw_payload", role="user", + session_id="carrier", config=config, hermes_home=home) + assert inner is not None and is_externalized_placeholder(inner["placeholder"]) + whole = {"role": "user", "content": inner["placeholder"]} + assert engine._message_replay_identity(whole)[1] == archived + prose = "Native retained summary. " * 500 + "\nArchive reference: " + inner["placeholder"] + "\nCurrent task remains active." + assert not is_externalized_placeholder(prose) + messages = [{"role": "user", "content": prose}, {"role": "assistant", "content": "retained answer"}] + try: + engine.ingest(messages) + stored = engine._store.get_session_messages("carrier") + assert len(stored) == 2 and is_externalized_placeholder(stored[0]["content"]) + stored_identity = engine._message_replay_identity(stored[0], stored_row=True) + assert stored_identity[1] == prose + identity_matches = engine._message_replay_identity(messages[0]) == stored_identity + finally: + engine.shutdown() + cold = LCMEngine(config=config, hermes_home=home) + try: + cold.on_session_start("carrier", conversation_id="owned", platform="cli", context_length=200000) + cold.ingest(messages) + assert (identity_matches, cold._store.get_session_count("carrier")) == (True, 2) + finally: + cold.shutdown() From 19173873325a7df8e2980d6cbc002b087c3a0e82 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 17:10:32 +0700 Subject: [PATCH 02/12] fix: use logical ownership for compaction source admission --- compaction.py | 19 ++- engine.py | 39 +++-- lifecycle_state.py | 179 +++++++++++++++++++--- reconcile.py | 25 +-- store.py | 21 +++ tests/test_issue_5_contiguous_frontier.py | 5 +- tests/test_owner_core_v12.py | 84 ++++++++++ 7 files changed, 323 insertions(+), 49 deletions(-) create mode 100644 tests/test_owner_core_v12.py diff --git a/compaction.py b/compaction.py index 243c18019..1d4171514 100644 --- a/compaction.py +++ b/compaction.py @@ -616,10 +616,7 @@ def _stored_publication_filter_exclusions( proofs = dict(initial_proofs) after_store_id = expected_frontier while after_store_id < covered_end: - rows = self._store.get_session_messages_after( - self._session_id, - after_store_id=after_store_id, - ) + rows = self._owner_history(after_store_id=after_store_id) if not rows: break for row in rows: @@ -1139,6 +1136,20 @@ def _compress_impl(self, messages: List[Dict[str, Any]], source_store_ids = sorted(dict.fromkeys(source_store_ids)) consumed_store_ids = self._get_store_ids_for_messages(source_lookup_chunk) consumed_store_ids = sorted(dict.fromkeys(consumed_store_ids)) + required_messages = [message for message in source_lookup_chunk + if not self._is_replayed_context_scaffold_message(message)] + required_ids = self._get_store_ids_for_messages(required_messages) + if len(set(required_ids)) != len(required_messages): + fallback = anchor_source_messages + if leaf_passes: + fallback = self._assemble_committed_compaction_context( + working_messages, anchor_source_messages, 2**63 - 1) + return self._fail_open_after_publication_failure( + fallback, LifecyclePublicationConflictError("Unmapped required source occurrence"), + compress_started=_compress_started, + threshold_full_sweep_active=threshold_full_sweep_active, + recovery_assembly_cap=recovery_assembly_cap, + leaf_passes=leaf_passes, context_is_assembled=True) earliest_at, latest_at = self._store.get_time_bounds(source_store_ids) summary_tokens = count_tokens(summary_text) diff --git a/engine.py b/engine.py index 4e99c71e0..aff826781 100644 --- a/engine.py +++ b/engine.py @@ -4452,13 +4452,35 @@ def _log_session_filter_diagnostics(self) -> None: # -- Internal: message ingestion --------------------------------------- + def _owner_history(self, *, after_store_id=0, limit=10000, latest=False, + count_only=False, producer_session_id=None): + if not self._conversation_id: + producer = producer_session_id or self._session_id + if count_only: + return self._store.get_session_count(producer) + if latest: + return self._store.get_session_tail(producer, limit=limit) + return self._store.get_session_messages_after(producer, after_store_id=after_store_id, limit=limit) + return self._store.get_conversation_messages_after(self._conversation_id, + after_store_id=after_store_id, limit=limit, latest=latest, + count_only=count_only, producer_session_id=producer_session_id) + + def _owned_summary_roots(self): + from .lifecycle_state import admitted_summary_roots + if not self._conversation_id: + nodes = self._dag.get_session_nodes(self._session_id) + return [node for depth in sorted({n.depth for n in nodes}) + for node in self._dag.get_uncondensed_at_depth(self._session_id, depth)] + roots = admitted_summary_roots(self._dag._conn, self._conversation_id, self._session_id) + return [self._dag.get_node(node_id) for node_id in sorted(roots)] + def _schedule_ingest_cursor_reconciliation(self) -> None: """Mark existing-session rebinds for cursor repair on next ingest.""" self._ingest_cursor_needs_reconcile = False if not self._session_id or self._session_ignored or self._session_stateless: return try: - self._ingest_cursor_needs_reconcile = self._store.get_session_count(self._session_id) > 0 + self._ingest_cursor_needs_reconcile = self._owner_history(count_only=True, producer_session_id=self._session_id) > 0 except Exception as exc: # pragma: no cover - defensive only logger.debug("LCM ingest cursor reconciliation probe failed: %s", exc) self._ingest_cursor_needs_reconcile = False @@ -4537,11 +4559,8 @@ def _has_prior_raw_externalized_placeholder_row(self, store_id: int, msg: Dict[s raw_identity = self._raw_externalized_placeholder_replay_identity(msg) after_store_id = 0 while True: - rows = self._store.get_session_messages_after( - self._session_id, - after_store_id=after_store_id, - limit=1000, - ) + rows = self._owner_history(after_store_id=after_store_id, limit=1000, + producer_session_id=self._session_id) if not rows: return False for row in rows: @@ -5989,9 +6008,7 @@ def _maybe_condense( fanin = max(1, self._config.condensation_fanin) for depth in range(upper): - uncondensed = self._dag.get_uncondensed_at_depth( - self._session_id, depth - ) + uncondensed = [node for node in self._owned_summary_roots() if node.depth == depth] if len(uncondensed) < fanin: continue @@ -6570,14 +6587,14 @@ def _assemble_context( # Node ids placed in the summary prefix — used to dedupe proactive-recall # injection against summaries already visible in the active context. active_summary_node_ids: set = set() - all_nodes = self._dag.get_session_nodes(self._session_id) + all_nodes = self._owned_summary_roots() if all_nodes: # Group by depth, take the most recent uncondensed at each level # For active context, we want the highest-level summaries # that haven't been condensed into even higher levels depths = sorted(set(n.depth for n in all_nodes), reverse=True) for d in depths: - uncondensed = self._dag.get_uncondensed_at_depth(self._session_id, d) + uncondensed = [node for node in all_nodes if node.depth == d] for node in uncondensed: active_summary_node_ids.add(node.node_id) depth_label = { diff --git a/lifecycle_state.py b/lifecycle_state.py index 4aeea2b3c..561122175 100644 --- a/lifecycle_state.py +++ b/lifecycle_state.py @@ -11,6 +11,7 @@ from __future__ import annotations import functools +import json import sqlite3 import threading import time @@ -29,6 +30,149 @@ class LifecyclePublicationConflictError(RuntimeError): """Raised when compaction publication cannot prove its source frontier.""" +_LEGACY_ASCII_WHITESPACE = "\t\n\v\f\r " + + +def legacy_blank_clause(column: str) -> str: + """Use the existing legacy common-ASCII whitespace convention in SQL.""" + chars = "char(9) || char(10) || char(11) || char(12) || char(13) || char(32)" + return f"({column} IS NULL OR TRIM({column}, {chars}) = '')" + + +def unambiguous_legacy_session_ids( + conn: sqlite3.Connection, + conversation_id: str, + session_ids: set[str], +) -> set[str]: + """Return blank-row session owners with exactly one lifecycle binding. + + Explicit ``messages.conversation_id`` values remain authoritative. A + blank legacy row may use a session binding only when neither lifecycle + index nor explicitly owned raw rows associate it with another conversation. + """ + candidates = {str(value) for value in session_ids if str(value)} + if not candidates: + return set() + return { + candidate + for candidate in candidates + if conn.execute( + f""" + SELECT EXISTS( + SELECT 1 FROM lcm_lifecycle_state + WHERE conversation_id = ? + AND (current_session_id = ? OR last_finalized_session_id = ?) + ) AND NOT EXISTS( + SELECT 1 + FROM lcm_lifecycle_state + INDEXED BY idx_lcm_lifecycle_current_session + WHERE current_session_id = ? AND conversation_id != ? + ) AND NOT EXISTS( + SELECT 1 + FROM lcm_lifecycle_state + INDEXED BY idx_lcm_lifecycle_last_finalized_session + WHERE last_finalized_session_id = ? AND conversation_id != ? + ) AND NOT EXISTS( + SELECT 1 FROM messages INDEXED BY idx_msg_session + WHERE session_id = ? AND NOT {legacy_blank_clause('conversation_id')} + AND conversation_id != ? + ) + """, + ( + conversation_id, candidate, candidate, + candidate, conversation_id, candidate, conversation_id, + candidate, conversation_id, + ), + ).fetchone()[0] + } + + +def conversation_producers(conn, conversation_id, session_id): + """Bound candidate queries by explicit producers and durable bindings.""" + row = conn.execute( + "SELECT current_session_id, last_finalized_session_id FROM lcm_lifecycle_state " + "WHERE conversation_id = ?", (conversation_id,), + ).fetchone() + bound = {str(value) for value in (row or ()) if value} + producers = {str(row[0]) for row in conn.execute( + "SELECT DISTINCT session_id FROM messages WHERE conversation_id = ?", + (conversation_id,), + )} + return producers | bound | {session_id}, unambiguous_legacy_session_ids(conn, conversation_id, bound) + + +def admitted_summary_roots(conn, conversation_id, session_id, *, before_node_id=None, + include_descendants=False): + """Return roots with complete same-owner lineage, ignoring foreign roots. + + Queries use the existing producer index; raw ownership, never producer + equality, admits a node. Invalid parents cannot hide valid child roots. + ``include_descendants`` applies the same validation to explicit expansion. + """ + producers, legacy = conversation_producers(conn, conversation_id, session_id) + rows = conn.execute( + "SELECT node_id, depth, source_ids, source_type, LENGTH(summary), token_count " + "FROM summary_nodes INDEXED BY idx_nodes_session_latest " + "WHERE session_id IN (SELECT value FROM json_each(?)) " + "AND (? IS NULL OR node_id < ?)", + (json.dumps(sorted(producers)), before_node_id, before_node_id), + ).fetchall() + nodes = {int(row[0]): row for row in rows} + validated, visiting = {}, set() + + def validate(node_id): + if node_id in validated: + return validated[node_id] + row = nodes.get(node_id) + if node_id in visiting: + return None + if row is None or not row[4] or not row[5]: + validated[node_id] = None + return None + visiting.add(node_id) + represented = set() + try: + sources = [int(value) for value in json.loads(row[2])] + if not sources or len(sources) != len(set(sources)): + raise ValueError("invalid source list") + if row[3] == "messages": + raw = conn.execute( + "SELECT store_id, conversation_id, session_id FROM messages " + "WHERE store_id IN (SELECT value FROM json_each(?))", + (json.dumps(sources),), + ).fetchall() + if len(raw) != len(sources) or any( + str(item[1] or "").strip(_LEGACY_ASCII_WHITESPACE) != conversation_id and not + (not str(item[1] or "").strip(_LEGACY_ASCII_WHITESPACE) and item[2] in legacy) + for item in raw + ): + raise ValueError("foreign or missing source") + represented.update(sources) + elif row[3] == "nodes": + for child in sources: + if child not in nodes or nodes[child][1] >= row[1]: + raise ValueError("invalid child") + child_sources = validate(child) + if child_sources is None or represented & child_sources: + raise ValueError("invalid or repeated lineage") + represented.update(child_sources) + else: + raise ValueError("invalid source type") + except (ValueError, TypeError): + represented = None + visiting.remove(node_id) + validated[node_id] = represented + return represented + + for node_id in nodes: + validate(node_id) + children = {int(child) for node_id, row in nodes.items() + if validated[node_id] is not None and row[3] == "nodes" + for child in json.loads(row[2])} + return {node_id: sources for node_id, sources in validated.items() + if sources is not None and (include_descendants or node_id not in children)} + + def _synchronized(method): """Serialize a read-modify-write method on the store's reentrant lock. @@ -975,15 +1119,18 @@ def stage_compaction_publication( snapshot_ids = sorted( set(all_covered_ids + excluded_ids + list(exclusion_proofs)) ) + _producers, legacy = conversation_producers(conn, conversation_id, session_id) + owner_sql = "(m.conversation_id = ? OR (" + legacy_blank_clause("m.conversation_id") + ") AND m.session_id IN (SELECT value FROM json_each(?)))" + owner_args = (conversation_id, json.dumps(sorted(legacy))) snapshot_rows = conn.execute( - """ + f""" SELECT m.store_id, m.conversation_id, m.content FROM json_each(?) AS source CROSS JOIN messages AS m - WHERE m.store_id = source.value AND m.session_id = ? + WHERE m.store_id = source.value AND {owner_sql} ORDER BY m.store_id """, - (str(snapshot_ids), session_id), + (str(snapshot_ids), *owner_args), ).fetchall() if [int(row[0]) for row in snapshot_rows] != snapshot_ids: raise LifecyclePublicationConflictError( @@ -1002,13 +1149,13 @@ def stage_compaction_publication( "Compaction publication filter exclusion changed" ) rows = conn.execute( - """ - SELECT store_id, conversation_id, content - FROM messages - WHERE session_id = ? AND store_id > ? AND store_id <= ? - ORDER BY store_id + f""" + SELECT m.store_id, m.conversation_id, m.content + FROM messages AS m + WHERE {owner_sql} AND m.store_id > ? AND m.store_id <= ? + ORDER BY m.store_id """, - (session_id, expected_frontier, covered_end), + (*owner_args, expected_frontier, covered_end), ).fetchall() authoritative_ids = [int(row[0]) for row in rows] proven_ids = sorted(covered_ids + excluded_ids) @@ -1019,17 +1166,9 @@ def stage_compaction_publication( f"authoritative={authoritative_ids}, covered={covered_ids}, " f"excluded={excluded_ids})" ) - if conn.execute( - """ - SELECT 1 - FROM summary_nodes AS node, json_each(node.source_ids) AS source - WHERE node.session_id = ? AND node.source_type = 'messages' - AND node.node_id != ? - AND source.value IN (SELECT value FROM json_each(?)) - LIMIT 1 - """, - (session_id, publication_node_id, str(all_covered_ids)), - ).fetchone(): + claimed = admitted_summary_roots(conn, conversation_id, session_id, include_descendants=True) + if any(node_id != publication_node_id and set(all_covered_ids) & sources + for node_id, sources in claimed.items()): raise LifecyclePublicationConflictError( "Compaction publication source lineage is already claimed" ) diff --git a/reconcile.py b/reconcile.py index 415be8c23..fa8375e49 100644 --- a/reconcile.py +++ b/reconcile.py @@ -1483,7 +1483,7 @@ def _reconcile_ingest_cursor_from_store( return 0 try: - session_count = self._store.get_session_count(self._session_id) + session_count = self._owner_history(count_only=True, producer_session_id=self._session_id) except Exception as exc: # pragma: no cover - defensive only logger.debug("LCM ingest cursor reconciliation count failed: %s", exc) return 0 @@ -1518,7 +1518,7 @@ def _reconcile_ingest_cursor_from_store( return 0 tail_limit = min(max(len(messages) * 4, 64), session_count) - stored_rows = self._store.get_session_tail(self._session_id, limit=tail_limit) + stored_rows = self._owner_history(limit=tail_limit, latest=True, producer_session_id=self._session_id) if not stored_rows: return 0 stored_tail_rows = [ @@ -1566,10 +1566,7 @@ def _reconcile_ingest_cursor_from_store( return cursor incoming_identities = self._effective_replay_identities(messages) - stored_head_rows = self._store.get_session_messages( - self._session_id, - limit=tail_limit, - ) + stored_head_rows = self._owner_history(limit=tail_limit, producer_session_id=self._session_id) stored_head = [self._message_replay_identity(row, stored_row=True) for row in stored_head_rows] # Stale-snapshot proof uses the raw durable prefix. Ignore-message # filters may suppress noisy rows for tail reconciliation, but filtered @@ -1655,11 +1652,11 @@ def _replayed_tool_segment_indexes_after_cursor( """ if not self._session_id or cursor >= len(messages): return set() - session_count = self._store.get_session_count(self._session_id) + session_count = self._owner_history(count_only=True, producer_session_id=self._session_id) if session_count <= 0: return set() tail_limit = min(max(len(messages) * 4, 64), session_count) - stored_rows = self._store.get_session_tail(self._session_id, limit=tail_limit) + stored_rows = self._owner_history(limit=tail_limit, latest=True, producer_session_id=self._session_id) stored_identity_counts = Counter( identity for identity in ( @@ -1938,6 +1935,13 @@ def _get_store_id_map_for_messages(self, messages: List[Dict[str, Any]]) -> dict ) if active_matches == 1: candidates.append(retained_anchor) + if candidates and self._conversation_id: + from .lifecycle_state import unambiguous_legacy_session_ids + legacy = unambiguous_legacy_session_ids(self._store._conn, self._conversation_id, + {row.get("session_id") for row in candidates if row.get("session_id")}) + candidates = [row for row in candidates if row.get("conversation_id") == self._conversation_id + or (not str(row.get("conversation_id") or "").strip("\t\n\v\f\r ") + and row.get("session_id") in legacy)] if candidates: candidates = list( { @@ -1949,10 +1953,7 @@ def _get_store_id_map_for_messages(self, messages: List[Dict[str, Any]]) -> dict candidates.sort(key=lambda candidate: int(candidate["store_id"])) next_candidate_after = self._last_compacted_store_id while True: - page = self._store.get_session_messages_after( - self._session_id, - after_store_id=next_candidate_after, - ) + page = self._owner_history(after_store_id=next_candidate_after) if not page: break candidates.extend(page) diff --git a/store.py b/store.py index 01c545abd..5c05d879a 100644 --- a/store.py +++ b/store.py @@ -27,6 +27,7 @@ refuse_schema_version_too_new, run_versioned_migrations, ) +from .lifecycle_state import legacy_blank_clause, unambiguous_legacy_session_ids from .config import LCMConfig from .ingest_protection import protect_message_for_ingest, protect_messages_for_ingest from .search_query import ( @@ -796,6 +797,26 @@ def load_session_page( ).fetchall() return [self._row_to_dict(r) for r in rows] + def get_conversation_messages_after(self, conversation_id, *, after_store_id=0, + limit=10000, latest=False, count_only=False, producer_session_id=None): + """Read the explicit logical owner plus uniquely bound legacy rows.""" + state = self._conn.execute("SELECT current_session_id, last_finalized_session_id " + "FROM lcm_lifecycle_state WHERE conversation_id = ?", (conversation_id,)).fetchone() + legacy = unambiguous_legacy_session_ids(self._conn, conversation_id, + {value for value in (state or ()) if value}) + where = ["(conversation_id = ? OR (" + legacy_blank_clause("conversation_id") + + ") AND session_id IN (SELECT value FROM json_each(?)))", "store_id > ?"] + args = [conversation_id, json.dumps(sorted(legacy)), after_store_id] + if producer_session_id is not None: + where.append("session_id = ?") + args.append(producer_session_id) + if count_only: + return self._conn.execute("SELECT COUNT(*) FROM messages WHERE " + " AND ".join(where), args).fetchone()[0] + rows = self._conn.execute(f"SELECT {_MESSAGE_SELECT_COLUMNS} FROM messages WHERE " + + " AND ".join(where) + (" ORDER BY store_id DESC" if latest else " ORDER BY store_id") + + " LIMIT ?", [*args, limit]).fetchall() + return [self._row_to_dict(row) for row in (reversed(rows) if latest else rows)] + def load_session_window( self, session_id: str, diff --git a/tests/test_issue_5_contiguous_frontier.py b/tests/test_issue_5_contiguous_frontier.py index 5e56cf85f..1e7a8c22f 100644 --- a/tests/test_issue_5_contiguous_frontier.py +++ b/tests/test_issue_5_contiguous_frontier.py @@ -382,11 +382,12 @@ def test_filter_exclusion_scan_pages_to_the_covered_end( last_page = [{"store_id": 10_001, "content": "DROP_ME"}] calls = [] - def paged_rows(_session_id, after_store_id=0, limit=10_000): + def paged_rows(conversation_id, after_store_id=0, limit=10_000, **kwargs): + assert conversation_id == "issue-5-filter-pages" calls.append((after_store_id, limit)) return first_page if after_store_id == 0 else last_page - monkeypatch.setattr(engine._store, "get_session_messages_after", paged_rows) + monkeypatch.setattr(engine._store, "get_conversation_messages_after", paged_rows) try: proofs = engine._stored_publication_filter_exclusions( 0, diff --git a/tests/test_owner_core_v12.py b/tests/test_owner_core_v12.py new file mode 100644 index 000000000..f46f064ae --- /dev/null +++ b/tests/test_owner_core_v12.py @@ -0,0 +1,84 @@ +"""Small logical-owner regression surface, with producer-local replay.""" +import pytest +import hermes_lcm.engine as engine_module +from hermes_lcm.config import LCMConfig +from hermes_lcm.dag import SummaryNode +from hermes_lcm.engine import LCMEngine + + +@pytest.fixture +def engine(tmp_path): + value = LCMEngine(config=LCMConfig(database_path=str(tmp_path / "lcm.db"), + fresh_tail_count=1, leaf_chunk_tokens=1, incremental_max_depth=0), hermes_home=str(tmp_path / "home")) + value.on_session_start("producer", conversation_id="owned", platform="cli", context_length=200000) + yield value + value.shutdown() + + +def history(): + return [{"role": "user", "content": "request one"}, + {"role": "assistant", "content": "answer one"}, + {"role": "user", "content": "request two"}, + {"role": "assistant", "content": "answer two"}, + {"role": "user", "content": "retained tail"}] + + +def test_compaction_cannot_map_foreign_copies(engine, monkeypatch): + active = history() + foreign = engine._store.append_batch("producer", [*active, {"role": "assistant", "content": "other history"}], conversation_id="foreign") + blank = engine._store.append_batch("producer", [{"role": "assistant", "content": "unknown blank"}], conversation_id="") + original = [tuple(row) for row in engine._store._conn.execute("SELECT * FROM messages ORDER BY store_id")] + engine.ingest(active) + own = [row["store_id"] for row in engine._store.get_session_messages("producer") if row["conversation_id"] == "owned"] + assert len(own) == len(active) + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("Owned summary", 1)) + result = engine.compress(active, force=True) + assert engine.last_compression_status == "compacted" + nodes = engine._dag.get_session_nodes("producer") + assert {sid for node in nodes for sid in node.source_ids} == set(own[:-1]) + assert result[-1] == active[-1] + assert [tuple(row) for row in engine._store._conn.execute("SELECT * FROM messages WHERE store_id <= ? ORDER BY store_id", (blank[-1],))] == original + assert engine._lifecycle.get_by_conversation("owned").current_frontier_store_id == own[-2] + + +def test_foreign_full_history_cannot_prove_current_replay(engine): + active = history() + engine._store.append_batch("producer", active, conversation_id="foreign") + engine._ingest_cursor_needs_reconcile = True + engine.ingest(active) + assert sum(row["conversation_id"] == "owned" for row in engine._store.get_session_messages("producer")) == len(active) + + +def test_explicit_owned_other_producer_is_publication_source(engine): + message = {"role": "assistant", "content": "owned prior producer source"} + source = engine._store.append_batch("earlier", [message], conversation_id="owned")[0] + assert engine._get_store_id_map_for_messages([message]).get(id(message)) == source + node = SummaryNode(session_id="producer", depth=0, summary="owned prefix", token_count=2, + source_token_count=10, source_ids=[source], source_type="messages", created_at=1) + engine._dag.add_node(node, before_commit=lambda conn, node_id: engine._lifecycle.stage_compaction_publication( + conn, "owned", "producer", node_id, 0, [source])) + assert engine._lifecycle.get_by_conversation("owned").current_frontier_store_id == source + assert engine._store.get(source)["session_id"] == "earlier" + + +def test_unmapped_required_occurrence_preserves_input(engine, monkeypatch): + active = history() + engine.ingest(active) + original = engine._get_store_ids_for_messages + def omit_required(messages): + return original(messages)[1:] + monkeypatch.setattr(engine, "_get_store_ids_for_messages", omit_required) + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("summary", 1)) + assert engine.compress(active, force=True) == active + assert engine.last_compression_status == "error" + assert not engine._dag.get_session_nodes("producer") + assert engine._lifecycle.get_by_conversation("owned").current_frontier_store_id == 0 + + +def test_assembly_selects_only_valid_owned_lineage(engine): + for producer, owner, text in [("producer", "foreign", "FOREIGN"), ("earlier", "owned", "OWNED")]: + source = engine._store.append_batch(producer, [{"role": "assistant", "content": text}], conversation_id=owner)[0] + engine._dag.add_node(SummaryNode(session_id=producer, depth=0, summary=text, + token_count=2, source_token_count=10, source_ids=[source], source_type="messages", created_at=1)) + assembled = str(engine._assemble_context(None, [])) + assert "OWNED" in assembled and "FOREIGN" not in assembled From bc4ff8f40e8c338413a3608e3149644068032e99 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 17:15:08 +0700 Subject: [PATCH 03/12] fix: require exact explicit ownership for summary roots --- lifecycle_state.py | 2 +- tests/test_owner_core_v12.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lifecycle_state.py b/lifecycle_state.py index 561122175..49a1777e4 100644 --- a/lifecycle_state.py +++ b/lifecycle_state.py @@ -142,7 +142,7 @@ def validate(node_id): (json.dumps(sources),), ).fetchall() if len(raw) != len(sources) or any( - str(item[1] or "").strip(_LEGACY_ASCII_WHITESPACE) != conversation_id and not + str(item[1] or "") != conversation_id and not (not str(item[1] or "").strip(_LEGACY_ASCII_WHITESPACE) and item[2] in legacy) for item in raw ): diff --git a/tests/test_owner_core_v12.py b/tests/test_owner_core_v12.py index f46f064ae..19bf68329 100644 --- a/tests/test_owner_core_v12.py +++ b/tests/test_owner_core_v12.py @@ -82,3 +82,21 @@ def test_assembly_selects_only_valid_owned_lineage(engine): token_count=2, source_token_count=10, source_ids=[source], source_type="messages", created_at=1)) assembled = str(engine._assemble_context(None, [])) assert "OWNED" in assembled and "FOREIGN" not in assembled + + +def test_nonblank_legacy_owner_is_exact_across_history_and_roots(tmp_path): + engine = LCMEngine(config=LCMConfig(database_path=str(tmp_path / "lcm.db")), + hermes_home=str(tmp_path / "home")) + try: + engine.on_session_start("producer", conversation_id="owned", platform="cli", context_length=200000) + source = engine._store.append_batch("producer", [{"role": "assistant", "content": "legacy source"}], conversation_id="owned")[0] + # Simulate a legacy raw import; current append normalizes owner values. + with engine._store._conn: + engine._store._conn.execute("UPDATE messages SET conversation_id = ? WHERE store_id = ?", (" owned ", source)) + engine._dag.add_node(SummaryNode(session_id="producer", depth=0, + summary="legacy explicit owner", token_count=3, source_token_count=10, + source_ids=[source], source_type="messages", created_at=1)) + assert engine._owner_history() == [] + assert engine._owned_summary_roots() == [] + finally: + engine.shutdown() From 5505dd82333440748c886b940411da2174381f41 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 17:51:59 +0700 Subject: [PATCH 04/12] fix: restore finalized same-session frontier without reset --- lifecycle_state.py | 11 ++++++--- tests/test_owner_core_v12.py | 45 ++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/lifecycle_state.py b/lifecycle_state.py index 49a1777e4..c6ba611d2 100644 --- a/lifecycle_state.py +++ b/lifecycle_state.py @@ -328,11 +328,16 @@ def bind_session( last_reset_at = None if existing is not None: + resume_frontier = ( + existing.last_finalized_frontier_store_id + if existing.last_finalized_session_id == session_id + and existing.last_reset_at is None else 0 + ) if existing.current_session_id == session_id: + if resume_frontier > existing.current_frontier_store_id: + return self.advance_frontier(conversation_id, session_id, resume_frontier) return existing - current_frontier = ( - existing.current_frontier_store_id if existing.current_session_id == session_id else 0 - ) + current_frontier = resume_frontier current_bound_at = ( existing.current_bound_at if existing.current_session_id == session_id else now ) diff --git a/tests/test_owner_core_v12.py b/tests/test_owner_core_v12.py index 19bf68329..ca54e5ec9 100644 --- a/tests/test_owner_core_v12.py +++ b/tests/test_owner_core_v12.py @@ -100,3 +100,48 @@ def test_nonblank_legacy_owner_is_exact_across_history_and_roots(tmp_path): assert engine._owned_summary_roots() == [] finally: engine.shutdown() + + +def test_same_session_cold_resume_preserves_committed_frontier(engine, monkeypatch): + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("Committed owned history", 1)) + active = engine.compress(history(), force=True) + assert engine.last_compression_status == "compacted" + state = engine._lifecycle.get_by_conversation("owned") + committed = state.current_frontier_store_id + assert committed > 0 + sources = {sid for node in engine._owned_summary_roots() for sid in node.source_ids} + assert sources == {row["store_id"] for row in engine._owner_history() if row["store_id"] <= committed} + count = engine._store.get_session_count("producer") + engine.on_session_end("producer", active) + ended = engine._lifecycle.get_by_conversation("owned") + assert ended.current_session_id is None + assert ended.last_finalized_session_id == "producer" + assert ended.last_finalized_frontier_store_id == committed + assert engine._store.get_session_count("producer") == count + config, home = engine._config, engine._hermes_home + engine.shutdown() + cold = LCMEngine(config=config, hermes_home=str(home)) + try: + cold.on_session_start("producer", conversation_id="owned", platform="cli", context_length=200000) + resumed = cold._lifecycle.get_by_conversation("owned") + assert (resumed.current_frontier_store_id, cold._last_compacted_store_id) == (committed, committed) + assert cold._store.get_session_count("producer") == count + # Reproduce the already-rebound zero state written by the old version. + cold._lifecycle._conn.execute("UPDATE lcm_lifecycle_state SET current_frontier_store_id = 0 WHERE conversation_id = ?", ("owned",)) + assert cold._lifecycle.bind_session("producer", conversation_id="owned").current_frontier_store_id == committed + # Publish the remaining tail normally, then ensure an older finalized + # checkpoint cannot rewind the newer committed frontier. + tail_id = max(row["store_id"] for row in cold._owner_history()) + tail_node = SummaryNode(session_id="producer", depth=0, summary="tail", token_count=1, + source_token_count=2, source_ids=[tail_id], source_type="messages", created_at=2) + cold._dag.add_node(tail_node, before_commit=lambda conn, node_id: cold._lifecycle.stage_compaction_publication( + conn, "owned", "producer", node_id, committed, [tail_id])) + assert cold._lifecycle.bind_session("producer", conversation_id="owned").current_frontier_store_id == tail_id + assert cold._lifecycle.bind_session("other-producer", conversation_id="owned").current_frontier_store_id == 0 + cold._lifecycle.finalize_session("owned", "producer", frontier_store_id=tail_id) + cold._lifecycle.record_reset("owned") + assert cold._lifecycle.bind_session("producer", conversation_id="owned").current_frontier_store_id == 0 + assert cold._lifecycle.bind_session("other-producer", conversation_id="owned").current_frontier_store_id == 0 + assert cold._store.get_session_count("producer") == count + finally: + cold.shutdown() From 41268605560c44352013d1de8499a1cf86b3f373 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 20:14:48 +0700 Subject: [PATCH 05/12] fix: preserve exact replay proof across Hermes compression callbacks --- engine.py | 42 ++++++++++++++++---- reconcile.py | 5 ++- tests/test_issue_3_retained_user_anchor.py | 13 ++++++- tests/test_lcm_engine.py | 9 ++++- tests/test_owner_core_host_callbacks.py | 45 ++++++++++++++++++++++ tests/test_owner_core_v12.py | 2 +- 6 files changed, 102 insertions(+), 14 deletions(-) create mode 100644 tests/test_owner_core_host_callbacks.py diff --git a/engine.py b/engine.py index aff826781..234f4f895 100644 --- a/engine.py +++ b/engine.py @@ -2636,7 +2636,8 @@ def _prepare_retained_user_anchor( ), ) return registered_row - self._write_retained_user_anchor(None) + # Keep exact occurrence proof until the host supplies a projection + # without this row; returning None removes anchor protection now. return None durable_users = self._durable_real_user_messages() if len(durable_users) != 1: @@ -3087,9 +3088,14 @@ def _host_source_from_session_state(state: Any) -> tuple[str, Any]: and session_id and source_session_id != session_id ) + can_continue_in_place = bool( + source_session_id == session_id == previous_session_id + and _state_conversation_matches(source_state) + ) + can_continue = can_reassign or can_continue_in_place boundary_placeholder_budget = {} boundary_placeholder_ordinals: dict[str, set[int]] = {} - if can_reassign: + if can_continue: if previous_session_id == source_session_id: boundary_placeholder_budget = self._active_replay_generated_placeholder_digest_budget() boundary_placeholder_ordinals = self._generated_placeholder_digest_ordinals_for_active_replay( @@ -3159,7 +3165,7 @@ def _host_source_from_session_state(state: Any) -> tuple[str, Any]: session_id, moved_nodes, ) - elif old_session_id: + elif old_session_id and not can_continue_in_place: logger.warning( "LCM compression boundary skipped carry-over: old_session_id=%s does not match bound session=%s", old_session_id, @@ -3191,7 +3197,9 @@ def _host_source_from_session_state(state: Any) -> tuple[str, Any]: if state is not None: self._last_compacted_store_id = state.current_frontier_store_id self._clear_pending_reset_boundary() - self._compression_boundary_ingest_pending = can_reassign + self._compression_boundary_ingest_pending = can_continue + if can_continue_in_place: + self._schedule_ingest_cursor_reconciliation() self._compression_boundary_active_placeholder_digest_budget = boundary_placeholder_budget self._compression_boundary_active_placeholder_digest_ordinals = boundary_placeholder_ordinals self._log_session_filter_diagnostics() @@ -3214,7 +3222,7 @@ def _on_session_start_unlocked(self, session_id: str, **kwargs) -> None: self._lcm_current_start_allows_bypass_lineage = False requested_platform = str(kwargs.get("platform") or self._session_platform or "") pre_reset_preserve_ambiguous_no_frame_old_session = False - if boundary_reason == "compression" and old_session_id and old_session_id != session_id: + if boundary_reason == "compression" and old_session_id: old_session_auxiliary_generation = self._in_process_auxiliary_caller_generation( old_session_id ) @@ -3293,7 +3301,7 @@ def _on_session_start_unlocked(self, session_id: str, **kwargs) -> None: logger.debug("LCM host fallback compressor reset failed", exc_info=True) self._host_fallback_compressor = None self._host_fallback_session_id = "" - if boundary_reason == "compression" and old_session_id and old_session_id != session_id: + if boundary_reason == "compression" and old_session_id: old_session_is_suppressed_foreground = self._auxiliary_lineage_suppressed_as_foreground( old_session_id ) @@ -3774,6 +3782,17 @@ def _on_session_end_unlocked( _SESSION_END_BUSY_TIMEOUT_MS, ): is_current_session_full_history_end = session_id == self._session_id + cached_source = self._last_active_replay_source_identities + if ( + is_current_session_full_history_end + and len(cached_source) > self._ingest_cursor + and len(messages) >= len(cached_source) + and [self._message_replay_identity(message) for message in messages[:len(cached_source)]] + == cached_source + ): + # Only an exact original-history prefix proves this cursor + # belongs to the shorter projection returned by compress(). + self._schedule_ingest_cursor_reconciliation() try: # Best-effort final flush. Keep this path bounded because # host gateways call session-end hooks from lifecycle paths @@ -6587,6 +6606,7 @@ def _assemble_context( # Node ids placed in the summary prefix — used to dedupe proactive-recall # injection against summaries already visible in the active context. active_summary_node_ids: set = set() + owned_summary_parts = [] all_nodes = self._owned_summary_roots() if all_nodes: # Group by depth, take the most recent uncondensed at each level @@ -6607,7 +6627,9 @@ def _assemble_context( f"{node.summary}\n" f"[Expand for details: {node.expand_hint}]" ) + owned_summary_parts.append(summary_parts[-1]) + selected_parts = [] retained_generated_context_parts: list[str] = [] if summary_parts: selected_parts = summary_parts @@ -6626,7 +6648,8 @@ def _assemble_context( if retained_user_msg is not None: retained_generated_context_parts.append(combined) else: - result.append({"role": summary_role, "content": combined}) + result.append({"role": summary_role, "content": combined, + "_compressed_summary": True}) # Proactive memory injection (SPEC F, default-off). One bounded block is # placed adjacent to the summary prefix — a stable position below the @@ -6735,7 +6758,10 @@ def _assemble_context( # Persist proof only for the exact provider-visible compacted snapshot # assembled by this engine. Ingested input is not trusted replay proof. - self._remember_compacted_active_replay_snapshot(result) + trusted_assembly = any(part in selected_parts and any( + part in (normalize_content_value(message.get("content")) or "") for message in result + ) for part in owned_summary_parts) + self._remember_compacted_active_replay_snapshot(result, trusted_assembly=trusted_assembly) return result def _is_budget_droppable_tail_message(self, message: Dict[str, Any]) -> bool: diff --git a/reconcile.py b/reconcile.py index fa8375e49..597ae3d8e 100644 --- a/reconcile.py +++ b/reconcile.py @@ -630,10 +630,11 @@ def _load_compacted_active_replay_snapshot_digests(self) -> list[str]: def _remember_compacted_active_replay_snapshot( self, messages: List[Dict[str, Any]], + *, trusted_assembly: bool = False, ) -> None: self._remember_replay_snapshot( _COMPACTED_ACTIVE_REPLAY_METADATA_PREFIX, - self._compacted_active_replay_snapshot_digest(messages), + self._replay_snapshot_digest(messages, require_lcm_system_note=not trusted_assembly), ) # -- Session-end full-history proof (consumed ONLY by current-session @@ -1009,7 +1010,7 @@ def active_identity( and self._matches_store_tail_suffix(sanitized_replay_tail, candidate_prefix) ) matches_raw_tail = self._matches_store_tail_suffix(stored_tail, candidate_prefix) - engine_snapshot_digest = self._compacted_active_replay_snapshot_digest(candidate_messages) + engine_snapshot_digest = self._replay_snapshot_digest(candidate_messages, require_lcm_system_note=False) session_end_snapshot_digest = ( self._session_end_replay_snapshot_digest(candidate_messages) if allow_session_end_replay_proof diff --git a/tests/test_issue_3_retained_user_anchor.py b/tests/test_issue_3_retained_user_anchor.py index 134befd75..80b3225e2 100644 --- a/tests/test_issue_3_retained_user_anchor.py +++ b/tests/test_issue_3_retained_user_anchor.py @@ -548,12 +548,16 @@ def test_preflight_second_user_invalidates_prepared_anchor( try: engine.compress(first) assert engine._leading_anchor_count(first) == 2 + registered = engine._store.read_metadata_json(engine._retained_user_anchor_metadata_key()) + assert registered["store_id"] > 0 engine.threshold_tokens = 1 messages = [ *first, {"role": "user", "content": "second user invalidates the anchor"}, ] should_compress = engine.should_compress_preflight(messages) + assert engine._prepared_retained_user_anchor is None + assert engine._leading_anchor_count(messages) == 1 anchor_metadata = engine._store.read_metadata_json( engine._retained_user_anchor_metadata_key() ) @@ -561,7 +565,7 @@ def test_preflight_second_user_invalidates_prepared_anchor( engine.shutdown() assert should_compress is True - assert anchor_metadata == {"store_id": 0, "version": 1} + assert anchor_metadata == registered def test_second_real_user_disqualifies_first_raw_anchor( @@ -598,6 +602,13 @@ def test_second_real_user_disqualifies_first_raw_anchor( *_tool_chain(count=4), ] ) + assert engine._prepared_retained_user_anchor is None + # The host now supplies the adopted projection; stale proof can retire. + adopted = engine.compress(second_result) + assert adopted + source_ids = [source_id for node in engine._dag.get_session_nodes(engine._session_id) + if node.source_type == "messages" for source_id in node.source_ids] + assert len(source_ids) == len(set(source_ids)) anchor_metadata = engine._store.read_metadata_json( engine._retained_user_anchor_metadata_key() ) diff --git a/tests/test_lcm_engine.py b/tests/test_lcm_engine.py index ba2f7a494..0d9bc2dd7 100644 --- a/tests/test_lcm_engine.py +++ b/tests/test_lcm_engine.py @@ -11058,6 +11058,9 @@ def test_compress_reassembles_backed_active_summary_marker_on_noop( instance.on_session_start("backed-summary-session", platform="telegram", context_length=200000) summary_text = "backed compressed details\nExpand for details about: backed prior" + source_id = instance._store.append_batch(instance._session_id, + [{"role": "assistant", "content": "backed prior"}], + conversation_id=instance._conversation_id)[0] node_id = instance._dag.add_node( SummaryNode( session_id="backed-summary-session", @@ -11065,7 +11068,7 @@ def test_compress_reassembles_backed_active_summary_marker_on_noop( summary=summary_text, token_count=3, source_token_count=50, - source_ids=[1], + source_ids=[source_id], source_type="messages", created_at=time.time(), earliest_at=time.time(), @@ -11092,13 +11095,15 @@ def fail_summary(**_kwargs): {"role": "assistant", "content": "fresh tail answer"}, ] + instance._store.append_batch(instance._session_id, messages[1:], + conversation_id=instance._conversation_id) try: result = instance.compress(messages) nodes = instance._dag.get_session_nodes("backed-summary-session") finally: instance.shutdown() - assert result == messages + assert result == [{**messages[0], "_compressed_summary": True}, *messages[1:]] assert len(nodes) == 1 assert nodes[0].node_id == node_id assert instance._ingest_cursor == len(result) diff --git a/tests/test_owner_core_host_callbacks.py b/tests/test_owner_core_host_callbacks.py new file mode 100644 index 000000000..0e122b3fc --- /dev/null +++ b/tests/test_owner_core_host_callbacks.py @@ -0,0 +1,45 @@ +import pytest +import hermes_lcm.engine as engine_module +from hermes_lcm.config import LCMConfig +from hermes_lcm.engine import LCMEngine + +@pytest.mark.parametrize("include_system", [True, False]) +def test_same_session_compression_boundary_survives_cold_resume(tmp_path, monkeypatch, include_system): + config = LCMConfig(database_path=str(tmp_path / "same-session.db"), + fresh_tail_count=80, leaf_chunk_tokens=1, incremental_max_depth=0) + value = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + value.on_session_start("same", conversation_id="conversation", platform="cli", context_length=200000) + messages = ([{"role": "system", "content": "system"}] if include_system else []) + [ + {"role": "user" if i % 2 == 0 else "assistant", "content": f"ordinary turn {i}"} + for i in range(120) + ] + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("VISIBLE_BOUNDARY_SUMMARY", 1)) + active = value.compress(messages, force=True) + assert value.last_compression_status == "compacted" + assert len(active) > 64 and active[-80:] == messages[-80:] + assert any(message.get("_compressed_summary") for message in active[:-80]) + assert not any(message.get("_compressed_summary") for message in active[-80:]) + before = value._store.get_session_count("same") + counts = {"after_compress": before} + # Hermes commit_memory_session forwards the ending history to on_session_end. + value.on_session_end("same", messages) + counts["after_end"] = value._store.get_session_count("same") + value.on_session_start("same", old_session_id="same", boundary_reason="compression", + conversation_id="conversation", platform="cli", context_length=200000) + counts["after_boundary"] = value._store.get_session_count("same") + value.shutdown() + cold = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + try: + cold.on_session_start("same", conversation_id="conversation", platform="cli", context_length=200000) + cold.ingest(active) + counts["after_cold"] = cold._store.get_session_count("same") + print({"include_system": include_system, "counts": counts}, flush=True) + assert counts == dict.fromkeys(counts, before), "lifecycle boundary duplicated history" + fresh = [*active, {"role": "user", "content": "one new turn after cold resume"}] + cold.ingest(fresh) + assert cold._store.get_session_count("same") == before + 1 + cold.ingest(fresh) + assert cold._store.get_session_count("same") == before + 1 + finally: + cold.shutdown() + diff --git a/tests/test_owner_core_v12.py b/tests/test_owner_core_v12.py index ca54e5ec9..e94d2927d 100644 --- a/tests/test_owner_core_v12.py +++ b/tests/test_owner_core_v12.py @@ -25,7 +25,7 @@ def history(): def test_compaction_cannot_map_foreign_copies(engine, monkeypatch): active = history() - foreign = engine._store.append_batch("producer", [*active, {"role": "assistant", "content": "other history"}], conversation_id="foreign") + engine._store.append_batch("producer", [*active, {"role": "assistant", "content": "other history"}], conversation_id="foreign") blank = engine._store.append_batch("producer", [{"role": "assistant", "content": "unknown blank"}], conversation_id="") original = [tuple(row) for row in engine._store._conn.execute("SELECT * FROM messages ORDER BY store_id")] engine.ingest(active) From f72ea75c03244a08d945cf2f3829aa38c7de44f3 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 20:20:56 +0700 Subject: [PATCH 06/12] test: align retained lineage proof with active projection lifetime --- tests/test_issue_3_retained_anchor_lineage.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/test_issue_3_retained_anchor_lineage.py b/tests/test_issue_3_retained_anchor_lineage.py index 8514edb44..d0f61e91a 100644 --- a/tests/test_issue_3_retained_anchor_lineage.py +++ b/tests/test_issue_3_retained_anchor_lineage.py @@ -75,7 +75,7 @@ def test_scaffold_shaped_real_user_requires_atomic_provenance(tmp_path) -> None: assert mapped[id(active[1])] == prompt_row["store_id"] -def test_second_real_user_clears_retained_anchor_registration(tmp_path) -> None: +def test_second_real_user_retires_protection_before_omitted_anchor_proof(tmp_path) -> None: engine = _engine(tmp_path, "retained-lineage-clear") initial = [ {"role": "system", "content": "stable system"}, @@ -90,7 +90,11 @@ def test_second_real_user_clears_retained_anchor_registration(tmp_path) -> None: try: engine.compress(initial) + registered = engine._store.read_metadata_json(engine._retained_user_anchor_metadata_key()) + assert registered["store_id"] > 0 active = engine.compress(later) + assert engine._prepared_retained_user_anchor is None + assert engine._leading_anchor_count(active) == 1 engine._last_compacted_store_id = max( row["store_id"] for row in engine._store.get_session_messages(engine._session_id) @@ -99,11 +103,16 @@ def test_second_real_user_clears_retained_anchor_registration(tmp_path) -> None: metadata = engine._store.read_metadata_json( engine._retained_user_anchor_metadata_key() ) + assert metadata == registered + assert mapped[id(active[1])] == registered["store_id"] + engine.compress([initial[0], *later[3:]]) + metadata = engine._store.read_metadata_json(engine._retained_user_anchor_metadata_key()) + mapped_after_omission = engine._get_store_id_map_for_messages([active[1]]) finally: engine.shutdown() assert metadata == {"store_id": 0, "version": 1} - assert id(active[1]) not in mapped + assert id(active[1]) not in mapped_after_omission def test_duplicate_active_identity_cannot_claim_registered_occurrence(tmp_path) -> None: From 6c5d418407e740aecd4a41dbb53d94c0c304d1c9 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 20:53:02 +0700 Subject: [PATCH 07/12] fix: renew exact active snapshot with proven durable append --- engine.py | 32 +++++- reconcile.py | 36 ++++++ tests/test_owner_core_host_callbacks.py | 145 ++++++++++++++++++++++++ 3 files changed, 212 insertions(+), 1 deletion(-) diff --git a/engine.py b/engine.py index 234f4f895..ff93e1ab7 100644 --- a/engine.py +++ b/engine.py @@ -4889,6 +4889,10 @@ def _ingest_messages( ) return self._redact_active_replay_messages(messages) + append_binding = (self._conversation_id, self._session_id) + append_prefix_cursor = self._ingest_cursor + append_prefix_proven = bool(0 < append_prefix_cursor < len(messages) + and self._owned_exact_snapshot_prefix(messages[:append_prefix_cursor])) n = len(messages) cursor = min(max(self._ingest_cursor, 0), n) scan_start = 0 if self._ingest_cursor_needs_reconcile else cursor @@ -5295,13 +5299,39 @@ def _ingest_messages( active_replay_messages[absolute_idx] = stubbed_message estimates = [count_message_tokens(m) for m in protected_messages] + renew_snapshot = bool(append_prefix_proven and cursor == append_prefix_cursor + and [idx for idx, _msg in messages_to_store_with_index] == list(range(cursor, n)) + and self._snapshot_append_is_lossless(messages[cursor:]) + and self._snapshot_append_is_lossless(active_replay_messages[cursor:]) + and all(self._message_replay_identity(active) == self._message_replay_identity(stored, stored_row=True) + for active, stored in zip(active_replay_messages[cursor:], protected_messages))) + append_floor = self._store._conn.execute("SELECT COALESCE(MAX(store_id), 0) FROM messages").fetchone()[0] + def append_metadata(message, store_id): + rows = self._real_user_scaffold_metadata_rows(message, store_id) + if not renew_snapshot or append_binding != (self._conversation_id, self._session_id): + return rows + state = self._lifecycle.get_by_conversation(append_binding[0]) + if state is None or state.current_session_id != append_binding[1]: + return rows + appended = self._store._conn.execute( + "SELECT COUNT(*) FROM messages WHERE store_id > ? AND session_id = ? AND conversation_id = ?", + (append_floor, append_binding[1], append_binding[0]), + ).fetchone()[0] + if appended != n - cursor or not self._owned_exact_snapshot_prefix(active_replay_messages[:cursor]): + return rows + digest = self._replay_snapshot_digest(active_replay_messages, require_lcm_system_note=False) + if digest: + digests = [d for d in self._load_compacted_active_replay_snapshot_digests() if d != digest] + rows.append((self._active_replay_snapshot_metadata_key(), + json.dumps({"version": 1, "digests": (digests + [digest])[-16:]}, sort_keys=True))) + return rows self._store._append_protected_batch( self._session_id, protected_messages, estimates, source=self._session_platform, conversation_id=self._conversation_id, - metadata_factory=self._real_user_scaffold_metadata_rows, + metadata_factory=append_metadata, metadata_messages=[ msg for _idx, msg in messages_to_store_with_index ], diff --git a/reconcile.py b/reconcile.py index 597ae3d8e..e55f40d0a 100644 --- a/reconcile.py +++ b/reconcile.py @@ -637,6 +637,42 @@ def _remember_compacted_active_replay_snapshot( self._replay_snapshot_digest(messages, require_lcm_system_note=not trusted_assembly), ) + def _owned_exact_snapshot_prefix(self, messages): + """Admit renewal only from a registered snapshot with current owned lineage.""" + digest = self._replay_snapshot_digest(messages, require_lcm_system_note=False) + if not digest or digest not in self._load_compacted_active_replay_snapshot_digests(): + return False + if any(_has_lossy_redacted_identity(self._message_replay_identity(m)) for m in messages): + return False + roots = {node.node_id: node for node in self._owned_summary_roots()} + seen = set() + raw = [] + for message in messages: + if message.get("role") == "system": + continue + if self._is_replayed_context_scaffold_message(message): + content = normalize_content_value(message.get("content")) or "" + ids = {int(value) for value in re.findall(r"Summary \(d\d+, node (\d+)\)", content)} + if not ids or not ids <= roots.keys(): + return False + seen.update(ids) + else: + raw.append(message) + mapping = self._get_store_id_map_for_messages(raw) + ids = [mapping.get(id(message), 0) for message in raw] + if not seen or not ids or not all(ids) or ids != sorted(set(ids)): + return False + rows = self._store._conn.execute( + "SELECT conversation_id FROM messages WHERE store_id IN (SELECT value FROM json_each(?))", + (json.dumps(ids),), + ).fetchall() + return len(rows) == len(ids) and all(row[0] == self._conversation_id for row in rows) + + def _snapshot_append_is_lossless(self, messages): + return all(not _has_lossy_redacted_identity(self._message_replay_identity(message)) + and not self._is_replayed_context_scaffold_message(message) + and not self._matches_ignore_message_patterns(message) for message in messages) + # -- Session-end full-history proof (consumed ONLY by current-session # full-history session-end ingest) -- diff --git a/tests/test_owner_core_host_callbacks.py b/tests/test_owner_core_host_callbacks.py index 0e122b3fc..9669f02f3 100644 --- a/tests/test_owner_core_host_callbacks.py +++ b/tests/test_owner_core_host_callbacks.py @@ -43,3 +43,148 @@ def test_same_session_compression_boundary_survives_cold_resume(tmp_path, monkey finally: cold.shutdown() + +@pytest.mark.parametrize("include_system", [False]) +def test_current_post_turn_replay(tmp_path, monkeypatch, include_system): + config = LCMConfig(database_path=str(tmp_path / "same-session.db"), + fresh_tail_count=80, leaf_chunk_tokens=1, incremental_max_depth=0) + value = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + value.on_session_start("same", conversation_id="conversation", platform="cli", context_length=200000) + messages = ([{"role": "system", "content": "system"}] if include_system else []) + [ + {"role": "user" if i % 2 == 0 else "assistant", "content": f"ordinary turn {i}"} + for i in range(120) + ] + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("VISIBLE_BOUNDARY_SUMMARY", 1)) + active = value.compress(messages, force=True) + assert value.last_compression_status == "compacted" + assert len(active) > 64 and active[-80:] == messages[-80:] + assert any(message.get("_compressed_summary") for message in active[:-80]) + assert not any(message.get("_compressed_summary") for message in active[-80:]) + before = value._store.get_session_count("same") + counts = {"after_compress": before} + # Hermes commit_memory_session forwards the ending history to on_session_end. + value.on_session_end("same", messages) + counts["after_end"] = value._store.get_session_count("same") + value.on_session_start("same", old_session_id="same", boundary_reason="compression", + conversation_id="conversation", platform="cli", context_length=200000) + counts["after_boundary"] = value._store.get_session_count("same") + value.shutdown() + cold = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + try: + cold.on_session_start("same", conversation_id="conversation", platform="cli", context_length=200000) + cold.ingest(active) + counts["after_cold"] = cold._store.get_session_count("same") + print({"include_system": include_system, "counts": counts}, flush=True) + assert counts == dict.fromkeys(counts, before), "lifecycle boundary duplicated history" + fresh = [*active, {"role": "user", "content": "one new turn after cold resume"}] + cold.ingest(fresh) + assert cold._store.get_session_count("same") == before + 1 + fresh.append({"role": "assistant", "content": "one actual reply"}) + cold.ingest(fresh) + counts["after_turn"] = cold._store.get_session_count("same") + digest = cold._replay_snapshot_digest(fresh, require_lcm_system_note=False) + registered = digest in cold._load_compacted_active_replay_snapshot_digests() + cold.on_session_end("same", fresh) + counts["after_turn_end"] = cold._store.get_session_count("same") + cold.shutdown() + reopened = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + try: + reopened.on_session_start("same", conversation_id="conversation", platform="cli", context_length=200000) + cursor = reopened._reconcile_ingest_cursor_from_store(fresh) + reopened.ingest(fresh) + counts["after_turn_cold"] = reopened._store.get_session_count("same") + print({"counts": counts, "active_length": len(fresh), "registered": registered, "cursor": cursor}, flush=True) + assert counts["after_turn"] == counts["after_turn_end"] == before + 2 + assert counts["after_turn_cold"] == before + 2 + finally: + reopened.shutdown() + finally: + cold.shutdown() + + + +def _renewal_engine(tmp_path, monkeypatch): + config = LCMConfig(database_path=str(tmp_path / "renewal.db"), fresh_tail_count=4, + leaf_chunk_tokens=1, incremental_max_depth=0) + engine = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + engine.on_session_start("same", conversation_id="owned", platform="cli", context_length=200000) + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("owned summary", 1)) + history = [{"role": "user" if i % 2 == 0 else "assistant", "content": f"turn {i}"} for i in range(12)] + active = engine.compress(history, force=True) + engine.ingest(active) + assert engine._owned_exact_snapshot_prefix(active) + return engine, active + + +@pytest.mark.parametrize("kind", ["text", "tools"]) +def test_renewal_persists_fresh_repeated_occurrences(tmp_path, monkeypatch, kind): + engine, active = _renewal_engine(tmp_path, monkeypatch) + pair = ([{"role": "user", "content": "repeat"}, {"role": "assistant", "content": "repeat"}] + if kind == "text" else [{"role": "assistant", "content": "", "tool_calls": [ + {"id": "same-call", "type": "function", "function": {"name": "test", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "same-call", "content": "same result"}]) + try: + before = engine._store.get_session_count("same") + for expected in [2, 4]: + active = [*active, *pair] + engine.ingest(active) + assert engine._store.get_session_count("same") == before + expected + digest = engine._replay_snapshot_digest(active, require_lcm_system_note=False) + assert digest in engine._load_compacted_active_replay_snapshot_digests() + engine._schedule_ingest_cursor_reconciliation() + engine.ingest(active) + assert engine._store.get_session_count("same") == before + 4 + finally: + engine.shutdown() + + +@pytest.mark.parametrize("mode", ["unregistered", "foreign", "skipped", "lossy"]) +def test_renewal_declines_unproven_append(tmp_path, monkeypatch, mode): + import re + class _FakeTimeoutPattern: + def __init__(self, pattern): + self.pattern = pattern + self._compiled = re.compile(pattern) + def search(self, text, *, timeout=None): + assert timeout is not None + return self._compiled.search(text) + engine, active = _renewal_engine(tmp_path, monkeypatch) + try: + suffix = [{"role": "user", "content": "new suffix"}] + if mode == "unregistered": + engine._store.write_metadata_json([engine._active_replay_snapshot_metadata_key()], '{}') + elif mode == "foreign": + engine.on_session_start("same", conversation_id="foreign", platform="cli", context_length=200000) + elif mode == "skipped": + engine._compiled_ignore_message_patterns = [_FakeTimeoutPattern("new suffix")] + else: + suffix[0]["content"] = "[LCM sensitive redaction: name=password_assignment; chars=8]" + before = engine._store.get_session_count("same") + extended = [*active, *suffix] + engine.ingest(extended) + if mode == "skipped": + assert engine._store.get_session_count("same") == before + digest = engine._replay_snapshot_digest(extended, require_lcm_system_note=False) + assert digest not in engine._load_compacted_active_replay_snapshot_digests() + finally: + engine.shutdown() + + +def test_renewal_metadata_and_rows_rollback_together(tmp_path, monkeypatch): + import sqlite3 + engine, active = _renewal_engine(tmp_path, monkeypatch) + try: + before = engine._store.get_session_count("same") + proofs = engine._load_compacted_active_replay_snapshot_digests() + original = engine._real_user_scaffold_metadata_rows + def metadata(message, store_id): + return [*original(message, store_id), ("test-original-scaffold-proof", "preserved")] + monkeypatch.setattr(engine, "_real_user_scaffold_metadata_rows", metadata) + engine._store._conn.execute("CREATE TRIGGER reject_renewal BEFORE UPDATE ON metadata BEGIN SELECT RAISE(ABORT, 'synthetic rollback'); END") + with pytest.raises(sqlite3.IntegrityError): + engine._ingest_messages([*active, {"role": "user", "content": "new suffix"}]) + assert engine._store.get_session_count("same") == before + assert engine._load_compacted_active_replay_snapshot_digests() == proofs + assert engine._store._conn.execute("SELECT value FROM metadata WHERE key='test-original-scaffold-proof'").fetchone() is None + finally: + engine.shutdown() From cb1dc6932d14f9e630fc173b84f822e644a9d9f7 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 21:09:02 +0700 Subject: [PATCH 08/12] fix: renew snapshots after reconciled compression callbacks safely --- engine.py | 42 ++++++++++------- reconcile.py | 9 ++-- tests/test_owner_core_host_callbacks.py | 63 +++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 22 deletions(-) diff --git a/engine.py b/engine.py index ff93e1ab7..54e5ab496 100644 --- a/engine.py +++ b/engine.py @@ -4890,9 +4890,6 @@ def _ingest_messages( return self._redact_active_replay_messages(messages) append_binding = (self._conversation_id, self._session_id) - append_prefix_cursor = self._ingest_cursor - append_prefix_proven = bool(0 < append_prefix_cursor < len(messages) - and self._owned_exact_snapshot_prefix(messages[:append_prefix_cursor])) n = len(messages) cursor = min(max(self._ingest_cursor, 0), n) scan_start = 0 if self._ingest_cursor_needs_reconcile else cursor @@ -5299,13 +5296,14 @@ def _ingest_messages( active_replay_messages[absolute_idx] = stubbed_message estimates = [count_message_tokens(m) for m in protected_messages] - renew_snapshot = bool(append_prefix_proven and cursor == append_prefix_cursor + renew_snapshot = bool(0 < cursor < n + and append_binding == (self._conversation_id, self._session_id) + and self._owned_exact_snapshot_prefix(messages[:cursor]) and [idx for idx, _msg in messages_to_store_with_index] == list(range(cursor, n)) and self._snapshot_append_is_lossless(messages[cursor:]) and self._snapshot_append_is_lossless(active_replay_messages[cursor:]) and all(self._message_replay_identity(active) == self._message_replay_identity(stored, stored_row=True) for active, stored in zip(active_replay_messages[cursor:], protected_messages))) - append_floor = self._store._conn.execute("SELECT COALESCE(MAX(store_id), 0) FROM messages").fetchone()[0] def append_metadata(message, store_id): rows = self._real_user_scaffold_metadata_rows(message, store_id) if not renew_snapshot or append_binding != (self._conversation_id, self._session_id): @@ -5316,8 +5314,8 @@ def append_metadata(message, store_id): appended = self._store._conn.execute( "SELECT COUNT(*) FROM messages WHERE store_id > ? AND session_id = ? AND conversation_id = ?", (append_floor, append_binding[1], append_binding[0]), - ).fetchone()[0] - if appended != n - cursor or not self._owned_exact_snapshot_prefix(active_replay_messages[:cursor]): + ).fetchone() + if appended is None or appended[0] != n - cursor or not self._owned_exact_snapshot_prefix(active_replay_messages[:cursor]): return rows digest = self._replay_snapshot_digest(active_replay_messages, require_lcm_system_note=False) if digest: @@ -5325,17 +5323,25 @@ def append_metadata(message, store_id): rows.append((self._active_replay_snapshot_metadata_key(), json.dumps({"version": 1, "digests": (digests + [digest])[-16:]}, sort_keys=True))) return rows - self._store._append_protected_batch( - self._session_id, - protected_messages, - estimates, - source=self._session_platform, - conversation_id=self._conversation_id, - metadata_factory=append_metadata, - metadata_messages=[ - msg for _idx, msg in messages_to_store_with_index - ], - ) + with self._store._write_lock: + append_floor = None + if renew_snapshot: + floor_row = self._store._conn.execute("SELECT COALESCE(MAX(store_id), 0) FROM messages").fetchone() + if floor_row is None: + renew_snapshot = False + else: + append_floor = floor_row[0] + self._store._append_protected_batch( + self._session_id, + protected_messages, + estimates, + source=self._session_platform, + conversation_id=self._conversation_id, + metadata_factory=append_metadata, + metadata_messages=[ + msg for _idx, msg in messages_to_store_with_index + ], + ) # Rollup staleness is driven by summary-node PUBLICATION # (_invalidate_rollups_for_published_node at every add_node site), not by # raw ingest: marking a period stale before its covering summary exists diff --git a/reconcile.py b/reconcile.py index e55f40d0a..d63fcab47 100644 --- a/reconcile.py +++ b/reconcile.py @@ -662,10 +662,11 @@ def _owned_exact_snapshot_prefix(self, messages): ids = [mapping.get(id(message), 0) for message in raw] if not seen or not ids or not all(ids) or ids != sorted(set(ids)): return False - rows = self._store._conn.execute( - "SELECT conversation_id FROM messages WHERE store_id IN (SELECT value FROM json_each(?))", - (json.dumps(ids),), - ).fetchall() + with self._store._write_lock: + rows = self._store._conn.execute( + "SELECT conversation_id FROM messages WHERE store_id IN (SELECT value FROM json_each(?))", + (json.dumps(ids),), + ).fetchall() return len(rows) == len(ids) and all(row[0] == self._conversation_id for row in rows) def _snapshot_append_is_lossless(self, messages): diff --git a/tests/test_owner_core_host_callbacks.py b/tests/test_owner_core_host_callbacks.py index 9669f02f3..3b2e2a45e 100644 --- a/tests/test_owner_core_host_callbacks.py +++ b/tests/test_owner_core_host_callbacks.py @@ -188,3 +188,66 @@ def metadata(message, store_id): assert engine._store._conn.execute("SELECT value FROM metadata WHERE key='test-original-scaffold-proof'").fetchone() is None finally: engine.shutdown() + + +def test_direct_assistant_after_compression_boundary_renews_snapshot(tmp_path, monkeypatch): + engine, active = _renewal_engine(tmp_path, monkeypatch) + try: + # Force another compaction, then exercise the exact host callback order. + history = [*active, *[{"role": "user" if i % 2 == 0 else "assistant", + "content": f"additional turn {i}"} for i in range(20)]] + adopted = engine.compress(history, force=True) + before = engine._store.get_session_count("same") + engine.on_session_end("same", history) + engine.on_session_start("same", old_session_id="same", boundary_reason="compression", + conversation_id="owned", platform="cli", context_length=200000) + appended = [*adopted, {"role": "assistant", "content": "final assistant response"}] + engine.ingest(appended) + assert engine._store.get_session_count("same") == before + 1 + digest = engine._replay_snapshot_digest(appended, require_lcm_system_note=False) + assert digest in engine._load_compacted_active_replay_snapshot_digests() + config, home = engine._config, engine._hermes_home + engine.shutdown() + cold = LCMEngine(config=config, hermes_home=str(home)) + try: + cold.on_session_start("same", conversation_id="owned", platform="cli", context_length=200000) + cold.ingest(appended) + assert cold._store.get_session_count("same") == before + 1 + finally: + cold.shutdown() + finally: + engine.shutdown() + + +@pytest.mark.parametrize("missing", ["floor", "count"]) +def test_missing_renewal_readback_preserves_fresh_ingestion(tmp_path, monkeypatch, missing): + engine, active = _renewal_engine(tmp_path, monkeypatch) + connection = engine._store._conn + class MissingReadback: + def fetchone(self): + return None + class ConnectionProxy: + def __enter__(self): + connection.__enter__() + return self + def __exit__(self, *args): + return connection.__exit__(*args) + def __getattr__(self, name): + return getattr(connection, name) + def execute(self, query, parameters=()): + if ((missing == "floor" and query == "SELECT COALESCE(MAX(store_id), 0) FROM messages") + or (missing == "count" and query.startswith("SELECT COUNT(*) FROM messages WHERE store_id >"))): + assert engine._store._write_lock._is_owned() + return MissingReadback() + return connection.execute(query, parameters) + try: + before = engine._store.get_session_count("same") + proofs = engine._load_compacted_active_replay_snapshot_digests() + engine._store._conn = ConnectionProxy() + appended = [*active, {"role": "assistant", "content": "fresh despite missing readback"}] + engine._ingest_messages(appended) + assert engine._store.get_session_count("same") == before + 1 + assert engine._load_compacted_active_replay_snapshot_digests() == proofs + finally: + engine._store._conn = connection + engine.shutdown() From f5e8360e85eb6a7bffd2b0c421a1c7ec7f612e0f Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 23:19:21 +0700 Subject: [PATCH 09/12] fix: refuse overlapping historical summary roots without mutation --- docs/operator-guide.md | 10 ++++++++++ lifecycle_state.py | 12 ++++++++++++ tests/test_owner_core_v12.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/docs/operator-guide.md b/docs/operator-guide.md index 81e75863c..4ba9f1f6b 100644 --- a/docs/operator-guide.md +++ b/docs/operator-guide.md @@ -198,6 +198,16 @@ prepends the policy. The canonical file and digest source is ## Troubleshooting +### `Overlapping historical summary roots; original data retained` + +LCM refuses to assemble or publish when two independent historical summaries +claim the same stored occurrence. Older session-local publication could create +this state when reopening A after an A→B compression rollover. All raw rows, +summaries and lifecycle state remain stored; retrying does not select a winner. +Preserve a coherent database backup and investigate the conflicting source +lineage on a copy. Do not delete a summary, reset the conversation or advance the +frontier merely to clear the error. + ### `hermes plugins` shows `lcm (not found)` but LCM tools exist If `plugins.enabled` contains `hermes-lcm`, `context.engine: lcm` is set, and diff --git a/lifecycle_state.py b/lifecycle_state.py index c6ba611d2..427a85e90 100644 --- a/lifecycle_state.py +++ b/lifecycle_state.py @@ -169,6 +169,18 @@ def validate(node_id): children = {int(child) for node_id, row in nodes.items() if validated[node_id] is not None and row[3] == "nodes" for child in json.loads(row[2])} + # Older session-local publication could re-summarize a source after an + # A->B->A rollover. Never expose both claims or silently choose one: retain + # the database and require an explicit recovery of that ambiguous history. + claimed = set() + for node_id, sources in validated.items(): + if sources is None or node_id in children: + continue + if claimed & sources: + raise LifecyclePublicationConflictError( + "Overlapping historical summary roots; original data retained" + ) + claimed.update(sources) return {node_id: sources for node_id, sources in validated.items() if sources is not None and (include_descendants or node_id not in children)} diff --git a/tests/test_owner_core_v12.py b/tests/test_owner_core_v12.py index e94d2927d..4743994ea 100644 --- a/tests/test_owner_core_v12.py +++ b/tests/test_owner_core_v12.py @@ -4,6 +4,7 @@ from hermes_lcm.config import LCMConfig from hermes_lcm.dag import SummaryNode from hermes_lcm.engine import LCMEngine +from hermes_lcm.lifecycle_state import LifecyclePublicationConflictError, admitted_summary_roots @pytest.fixture @@ -84,6 +85,34 @@ def test_assembly_selects_only_valid_owned_lineage(engine): assert "OWNED" in assembled and "FOREIGN" not in assembled +@pytest.mark.parametrize("include_descendants", [False, True]) +def test_legacy_rollover_overlap_refuses_admission_without_mutation(engine, monkeypatch, include_descendants): + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("First summary", 1)) + active = engine.compress(history(), force=True) + first = engine._dag.get_session_nodes("producer")[0] + engine.rollover_session("producer", "successor", previous_messages=active, + boundary_reason="compression", platform="cli", context_length=200000) + engine.on_session_end("successor", []) + engine.on_session_start("producer", conversation_id="owned", platform="cli", context_length=200000) + # Reproduce the persisted second root from the executed main7fb A->B->A + # lifecycle trace. That version reset A's frontier and checked only A nodes, + # allowing this second publication while the first root remained under B. + engine._dag.add_node(SummaryNode(session_id="producer", depth=0, + summary="Second independently generated summary", token_count=5, + source_token_count=first.source_token_count, source_ids=first.source_ids, + source_type="messages", created_at=first.created_at + 1)) + def snapshot(): + return {table: [tuple(row) for row in engine._store._conn.execute(f"SELECT * FROM {table}")] + for table in ("messages", "summary_nodes", "lcm_lifecycle_state")} + before = snapshot() + with pytest.raises(LifecyclePublicationConflictError, match="Overlapping historical summary roots"): + admitted_summary_roots(engine._store._conn, "owned", "producer", + include_descendants=include_descendants) + with pytest.raises(LifecyclePublicationConflictError, match="Overlapping historical summary roots"): + engine._assemble_context(None, []) + assert snapshot() == before + + def test_nonblank_legacy_owner_is_exact_across_history_and_roots(tmp_path): engine = LCMEngine(config=LCMConfig(database_path=str(tmp_path / "lcm.db")), hermes_home=str(tmp_path / "home")) From 50742df1ab59cdb0c171f5a1f1fda0bb170f029b Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 23:27:40 +0700 Subject: [PATCH 10/12] fix: reset the ingest cursor for empty continued sessions --- docs/operator-guide.md | 2 +- engine.py | 2 ++ lifecycle_state.py | 2 +- tests/test_owner_core_v12.py | 17 +++++++++++++++++ 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/operator-guide.md b/docs/operator-guide.md index 4ba9f1f6b..6e02e70e3 100644 --- a/docs/operator-guide.md +++ b/docs/operator-guide.md @@ -198,7 +198,7 @@ prepends the policy. The canonical file and digest source is ## Troubleshooting -### `Overlapping historical summary roots; original data retained` +### `Overlapping historical summary roots` LCM refuses to assemble or publish when two independent historical summaries claim the same stored occurrence. Older session-local publication could create diff --git a/engine.py b/engine.py index 54e5ab496..564af38b7 100644 --- a/engine.py +++ b/engine.py @@ -4500,6 +4500,8 @@ def _schedule_ingest_cursor_reconciliation(self) -> None: return try: self._ingest_cursor_needs_reconcile = self._owner_history(count_only=True, producer_session_id=self._session_id) > 0 + if not self._ingest_cursor_needs_reconcile: + self._ingest_cursor = 0 except Exception as exc: # pragma: no cover - defensive only logger.debug("LCM ingest cursor reconciliation probe failed: %s", exc) self._ingest_cursor_needs_reconcile = False diff --git a/lifecycle_state.py b/lifecycle_state.py index 427a85e90..8b3aa9ffc 100644 --- a/lifecycle_state.py +++ b/lifecycle_state.py @@ -178,7 +178,7 @@ def validate(node_id): continue if claimed & sources: raise LifecyclePublicationConflictError( - "Overlapping historical summary roots; original data retained" + "Overlapping historical summary roots: source lineage already claimed; original data retained" ) claimed.update(sources) return {node_id: sources for node_id, sources in validated.items() diff --git a/tests/test_owner_core_v12.py b/tests/test_owner_core_v12.py index 4743994ea..fcf1dc816 100644 --- a/tests/test_owner_core_v12.py +++ b/tests/test_owner_core_v12.py @@ -50,6 +50,23 @@ def test_foreign_full_history_cannot_prove_current_replay(engine): assert sum(row["conversation_id"] == "owned" for row in engine._store.get_session_messages("producer")) == len(active) +def test_empty_filtered_history_boundary_stores_next_fresh_turn(engine): + class DropOnlyPattern: + pattern = "DROP_SYNTHETIC" + def search(self, text, timeout=None): + return object() if self.pattern in str(text) else None + engine._compiled_ignore_message_patterns = [DropOnlyPattern()] + engine.ingest([{"role": "user", "content": "DROP_SYNTHETIC"}]) + assert engine._owner_history(count_only=True) == 0 + assert engine._ingest_cursor == 1 + engine.on_session_start("producer", conversation_id="owned", platform="cli", + context_length=200000, boundary_reason="compression", old_session_id="producer") + fresh = [{"role": "user", "content": "fresh unfiltered user turn"}] + engine.ingest(fresh) + engine.ingest(fresh) + assert [row["content"] for row in engine._owner_history()] == [fresh[0]["content"]] + + def test_explicit_owned_other_producer_is_publication_source(engine): message = {"role": "assistant", "content": "owned prior producer source"} source = engine._store.append_batch("earlier", [message], conversation_id="owned")[0] From d1e3938115248a1712a33fa51fb15b85b1e50a38 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 23:41:24 +0700 Subject: [PATCH 11/12] fix: preserve proven legacy ownership during lifecycle transitions --- lifecycle_state.py | 48 ++++++-- .../references/session-lifecycle.md | 12 ++ tests/test_legacy_bind_v18.py | 103 ++++++++++++++++++ 3 files changed, 156 insertions(+), 7 deletions(-) create mode 100644 tests/test_legacy_bind_v18.py diff --git a/lifecycle_state.py b/lifecycle_state.py index 8b3aa9ffc..1243a75ae 100644 --- a/lifecycle_state.py +++ b/lifecycle_state.py @@ -199,6 +199,24 @@ def wrapper(self, *args, **kwargs): return wrapper +def _ownership_transition(method): + """Keep proven legacy attribution and pointer changes in one write transaction.""" + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + with self._lock: + # This connection's public lifecycle methods own their autocommit + # transactions. Lock SQLite before reading the old ownership proof. + self._conn.execute("BEGIN IMMEDIATE") + try: + result = method(self, *args, **kwargs) + self._conn.commit() + return result + except BaseException: + self._conn.rollback() + raise + return wrapper + + @dataclass class LifecycleState: conversation_id: str @@ -317,7 +335,22 @@ def get_by_session(self, session_id: str | None) -> LifecycleState | None: ).fetchone() return self._row_to_state(row) - @_synchronized + def _promote_bound_legacy_rows(self, state: LifecycleState | None) -> None: + if state is None or self._conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='messages'" + ).fetchone() is None: + return + producers = {value for value in (state.current_session_id, state.last_finalized_session_id) if value} + proven = unambiguous_legacy_session_ids(self._conn, state.conversation_id, producers) + if proven: + self._conn.execute( + "UPDATE messages SET conversation_id = ? " + "WHERE session_id IN (SELECT value FROM json_each(?)) AND " + + legacy_blank_clause("conversation_id"), + (state.conversation_id, json.dumps(sorted(proven))), + ) + + @_ownership_transition def bind_session( self, session_id: str, @@ -347,7 +380,8 @@ def bind_session( ) if existing.current_session_id == session_id: if resume_frontier > existing.current_frontier_store_id: - return self.advance_frontier(conversation_id, session_id, resume_frontier) + self.stage_frontier_advance(self._conn, conversation_id, session_id, resume_frontier) + return self.get_by_conversation(conversation_id) return existing current_frontier = resume_frontier current_bound_at = ( @@ -374,6 +408,7 @@ def bind_session( ) last_reset_at = existing.last_reset_at + self._promote_bound_legacy_rows(existing) self._conn.execute( """ INSERT INTO lcm_lifecycle_state( @@ -424,12 +459,11 @@ def bind_session( now, ), ) - self._conn.commit() state = self.get_by_conversation(conversation_id) assert state is not None return state - @_synchronized + @_ownership_transition def finalize_session( self, conversation_id: str | None, @@ -439,6 +473,7 @@ def finalize_session( state = self.get_by_conversation(conversation_id) if state is None: return None + self._promote_bound_legacy_rows(state) now = time.time() current_session_id = state.current_session_id current_frontier = state.current_frontier_store_id @@ -472,10 +507,9 @@ def finalize_session( state.conversation_id, ), ) - self._conn.commit() return self.get_by_conversation(state.conversation_id) - @_synchronized + @_ownership_transition def record_rollover( self, conversation_id: str, @@ -492,6 +526,7 @@ def record_rollover( ): return state + self._promote_bound_legacy_rows(state) now = time.time() last_finalized_frontier = max( int(finalized_frontier_store_id or 0), @@ -534,7 +569,6 @@ def record_rollover( now, ), ) - self._conn.commit() updated = self.get_by_conversation(conversation_id) assert updated is not None return updated diff --git a/skills/hermes-lcm/references/session-lifecycle.md b/skills/hermes-lcm/references/session-lifecycle.md index 59fac53a0..ab08ecdb2 100644 --- a/skills/hermes-lcm/references/session-lifecycle.md +++ b/skills/hermes-lcm/references/session-lifecycle.md @@ -4,6 +4,18 @@ Hermes `/new` starts a new host session. LCM-X binds that session to its own lif Do not promise that `/new` deletes historical LCM data. Earlier rows remain in `lcm.db` unless an explicitly authorized cleanup removes them, and they remain available through bounded cross-session recall. +Before binding, finalization, or rollover replaces existing lifecycle pointers, +LCM makes already-proven legacy ownership explicit on rows whose conversation ID +is blank. This requires the existing unambiguous binding predicate: another +conversation binding or any explicitly foreign row under that producer prevents +promotion. The proof read, blank-owner update, and lifecycle transition share one +SQLite write transaction. Source IDs, producer session IDs, content, and nonblank +conversation IDs remain unchanged. + +This preserves attribution before it would be forgotten; it does not infer an +owner for already-orphaned or ambiguous legacy rows. Operators must not use a +neighboring row, a shared producer ID alone, or a carried summary as repair proof. + ## `/lcm rotate` `/lcm rotate` is different from `/new`: diff --git a/tests/test_legacy_bind_v18.py b/tests/test_legacy_bind_v18.py new file mode 100644 index 000000000..5607a30c7 --- /dev/null +++ b/tests/test_legacy_bind_v18.py @@ -0,0 +1,103 @@ +"""Preserve already-proven legacy ownership before lifecycle pointers move.""" +import pytest + +import hermes_lcm.engine as engine_module +from hermes_lcm.config import LCMConfig +from hermes_lcm.engine import LCMEngine + + +def _legacy_engine(tmp_path): + config = LCMConfig(database_path=str(tmp_path / "legacy.db"), fresh_tail_count=1, + leaf_chunk_tokens=1, incremental_max_depth=0) + engine = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + messages = [{"role": "user" if i % 2 == 0 else "assistant", + "content": f"legacy synthetic turn {i}"} for i in range(5)] + # Released append_batch omitted conversation_id; the old binding is the proof. + engine._store.append_batch("A", messages) + engine.on_session_start("A", conversation_id="owned", platform="cli", context_length=200000) + return engine, messages + + +def test_legacy_summary_survives_two_rollovers_and_restart(tmp_path, monkeypatch): + engine, messages = _legacy_engine(tmp_path) + config = engine._config + monkeypatch.setattr(engine_module, "summarize_with_escalation", + lambda **kwargs: ("SYNTHETIC_LEGACY_SUMMARY", 1)) + try: + engine.compress(messages, force=True) + before = engine._store._conn.execute( + "SELECT store_id,session_id,content FROM messages ORDER BY store_id").fetchall() + assert len(before) == 5 + assert engine._store._conn.execute( + "SELECT COUNT(*) FROM messages WHERE conversation_id = ''").fetchone()[0] == 5 + roots = {node.node_id for node in engine._owned_summary_roots()} + assert roots + for old, new in [("A", "B"), ("B", "C")]: + engine.rollover_session(old, new, previous_messages=[], boundary_reason="compression", + platform="cli", context_length=200000) + assert {node.node_id for node in engine._owned_summary_roots()} == roots + assert engine._store._conn.execute( + "SELECT store_id,session_id,content FROM messages ORDER BY store_id").fetchall() == before + assert engine._store._conn.execute( + "SELECT COUNT(*) FROM messages WHERE conversation_id = 'owned'").fetchone()[0] == 5 + engine.shutdown() + engine = LCMEngine(config=config, hermes_home=str(tmp_path / "home")) + engine.on_session_start("C", conversation_id="owned", platform="cli", context_length=200000) + assert {node.node_id for node in engine._owned_summary_roots()} == roots + assert any("SYNTHETIC_LEGACY_SUMMARY" in m.get("content", "") + for m in engine._assemble_context(None, [])) + finally: + engine.shutdown() + + +@pytest.mark.parametrize("conflict", ["binding", "explicit-owner"]) +def test_ambiguous_legacy_owner_is_not_promoted(tmp_path, conflict): + engine, _ = _legacy_engine(tmp_path) + try: + if conflict == "binding": + engine._lifecycle.bind_session("A", conversation_id="foreign") + else: + engine._store.append_batch("A", [{"role": "user", "content": "foreign row"}], + conversation_id="foreign") + before = engine._store._conn.execute("SELECT * FROM messages ORDER BY store_id").fetchall() + engine._lifecycle.finalize_session("owned", "A") + assert engine._store._conn.execute("SELECT * FROM messages ORDER BY store_id").fetchall() == before + finally: + engine.shutdown() + + +@pytest.mark.parametrize("transition", ["bind", "finalize", "rollover"]) +def test_owner_promotion_rolls_back_with_transition(tmp_path, transition): + engine, _ = _legacy_engine(tmp_path) + lifecycle = engine._lifecycle + conn = lifecycle._conn + before = lifecycle.get_by_conversation("owned") + statements = [] + + class FailingConnection: + def __getattr__(self, name): + return getattr(conn, name) + def execute(self, sql, *args): + normalized = " ".join(sql.split()) + statements.append(normalized) + if normalized.startswith(("INSERT INTO lcm_lifecycle_state", "UPDATE lcm_lifecycle_state")): + assert conn.execute("SELECT COUNT(*) FROM messages WHERE conversation_id = 'owned'").fetchone()[0] == 5 + raise RuntimeError("synthetic transition failure") + return conn.execute(sql, *args) + + lifecycle._conn = FailingConnection() + try: + with pytest.raises(RuntimeError, match="synthetic transition failure"): + if transition == "bind": + lifecycle.bind_session("B", conversation_id="owned") + elif transition == "finalize": + lifecycle.finalize_session("owned", "A") + else: + lifecycle.record_rollover("owned", old_session_id="A", new_session_id="B") + assert statements[0] == "BEGIN IMMEDIATE" + assert not conn.in_transaction + assert lifecycle.get_by_conversation("owned") == before + assert conn.execute("SELECT COUNT(*) FROM messages WHERE conversation_id = ''").fetchone()[0] == 5 + finally: + lifecycle._conn = conn + engine.shutdown() From c6a1246b3f05191a0ca10e1d12173c167563e235 Mon Sep 17 00:00:00 2001 From: Eva Date: Wed, 9 Sep 2026 23:58:50 +0700 Subject: [PATCH 12/12] fix: include producer session in cross-session summary hints --- engine.py | 5 ++++- tests/test_owner_core_v12.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/engine.py b/engine.py index 564af38b7..e303a622c 100644 --- a/engine.py +++ b/engine.py @@ -6660,10 +6660,13 @@ def _assemble_context( 1: "Session Arc", 2: "Durable", }.get(d, f"Depth-{d}") + expand_hint = node.expand_hint + if node.session_id != self.current_session_id: + expand_hint = lcm_tools._session_expand_hint(node.node_id, node.session_id) summary_parts.append( f"[{depth_label} Summary (d{d}, node {node.node_id})]\n" f"{node.summary}\n" - f"[Expand for details: {node.expand_hint}]" + f"[Expand for details: {expand_hint}]" ) owned_summary_parts.append(summary_parts[-1]) diff --git a/tests/test_owner_core_v12.py b/tests/test_owner_core_v12.py index fcf1dc816..8183237c1 100644 --- a/tests/test_owner_core_v12.py +++ b/tests/test_owner_core_v12.py @@ -191,3 +191,33 @@ def test_same_session_cold_resume_preserves_committed_frontier(engine, monkeypat assert cold._store.get_session_count("producer") == count finally: cold.shutdown() + + +@pytest.mark.parametrize("producer", ["producer", "prior'\\producer"]) +def test_cross_session_assembled_hint_expands_owned_sources(engine, monkeypatch, producer): + import ast + import json + import re + from hermes_lcm.tools import lcm_expand + + engine.on_session_start(producer, conversation_id="owned", platform="cli", context_length=200000) + monkeypatch.setattr(engine_module, "summarize_with_escalation", lambda **kw: ("Owned summary", 1)) + active = engine.compress(history(), force=True) + node = engine._owned_summary_roots()[0] + assert f"[Expand for details: {node.expand_hint}]" in str(active) + rows = [tuple(row) for row in engine._store._conn.execute("SELECT * FROM messages ORDER BY store_id")] + engine.on_session_end(producer, active) + engine.on_session_start("new-producer", conversation_id="owned", platform="cli", context_length=200000) + assembled = engine._assemble_context(None, [history()[-1]]) + content = "\n".join(message.get("content", "") for message in assembled) + assert f"[Recent Summary (d0, node {node.node_id})]" in content + hint = re.search(r"\[Expand for details: (.*?)\]", content).group(1) + call = ast.parse(hint, mode="eval").body + assert isinstance(call, ast.Call) and call.func.id == "lcm_expand" + args = {keyword.arg: ast.literal_eval(keyword.value) for keyword in call.keywords} + expanded = json.loads(lcm_expand(args, engine=engine)) + assert "error" not in expanded, expanded + assert args["session_id"] == producer + assert [message["content"] for message in expanded["expanded"]] == [message["content"] for message in history()[:-1]] + assert [tuple(row) for row in engine._store._conn.execute("SELECT * FROM messages ORDER BY store_id")] == rows + assert engine._dag.get_node(node.node_id).session_id == producer