Skip to content

The agent that grows with you

fix(worker): project live compaction dicts onto the closed handoff fields

Teknium4cd8444d245a
diff --git a/agent/runtime_session_compression.py b/agent/runtime_session_compression.py
index f8490b19944..013deec20ba 100644
--- a/agent/runtime_session_compression.py
+++ b/agent/runtime_session_compression.py
@@ -1,6 +1,19 @@
"""Concrete worker compression APIs; scope and receipts stay in RuntimeSessionStore."""
+def _handoff_rows(messages):
+ """Project live compaction dicts onto the owner's closed handoff fields.
+
+ Micro-compaction and proactive prune hand over the live list, whose dicts carry worker-local
+ bookkeeping (``_db_persisted``, ``_micro_compact_marker``, a tool row's wire ``name``, risk tags)
+ that SessionDB's insert simply never reads. The owner's boundary stays closed; sending those keys
+ would fail the receipt and leave the journal stuck pending, refusing every later write.
+ """
+ from hermes_state_runtime import HANDOFF_MESSAGE_FIELDS
+ return [{k: v for k, v in m.items() if k in HANDOFF_MESSAGE_FIELDS} if isinstance(m, dict) else m
+ for m in messages]
+
+
class RuntimeSessionCompressionMixin:
def _append_compression_messages(self, session_id, messages, compression_lock_holder,
turn_lease_holder, turn_lease_ttl_seconds):
@@ -60,7 +73,7 @@ class RuntimeSessionCompressionMixin:
# coverage travels the same way: the owner proves it inside the commit transaction.
carried = [dict(m) for m in carried_messages or [] if isinstance(m, dict)]
unresolved = None if unresolved_held is None else [dict(m) for m in unresolved_held if isinstance(m, dict)]
- result = self._apply('compression.archive', dict(messages=compacted_messages,
+ result = self._apply('compression.archive', dict(messages=_handoff_rows(compacted_messages),
model_config_patch=model_config_patch, watermark=watermark, lock_holder=lock_holder,
tail_count=tail_count, carried_messages=carried, covered_ids=covered_ids,
unresolved_held=unresolved))
@@ -74,7 +87,7 @@ class RuntimeSessionCompressionMixin:
lease_ttl_seconds=300.0, watermark=None, watermark_ceiling=None):
self._session(parent_session_id)
result = self._apply('compression.publish', dict(child_session_id=child_session_id, source=source,
- messages=messages, model=model, model_config=model_config, system_prompt=system_prompt,
+ messages=_handoff_rows(messages), model=model, model_config=model_config, system_prompt=system_prompt,
cwd=cwd, profile_name=profile_name, compression_lock_holder=compression_lock_holder,
require_compression_lease=require_compression_lease, require_lease_refresh=require_lease_refresh,
lease_ttl_seconds=lease_ttl_seconds, watermark=watermark, watermark_ceiling=watermark_ceiling))
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 9d6f8bc9fc9..336cc8d7f75 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -509,6 +509,9 @@ _MESSAGE_FIELDS = frozenset({
# Main's durable message identity (message_uid / merge witness / tool-call uids) and the alternation
# repair's row counts ride every persisted dict; the owner's insert and coverage read them.
}) | PERSISTENCE_ONLY_MESSAGE_FIELDS | {ABSORBED_ROW_IDS}
+# Compaction handoffs (archive/publish) also carry the summary's user-turn flag. This is the closed
+# boundary the owner validates AND the projection the worker facade applies to live dicts first.
+HANDOFF_MESSAGE_FIELDS = _MESSAGE_FIELDS | {'_compressed_summary_has_user_turn'}
# Row state the owner's transcript repair stamps on each message (main mutates the caller's dict
# in place; a worker gets it back as an annotation). None = absent, so a stale adoption is cleared.
_ROW_ANNOTATION_KEYS = ('_row_id', 'timestamp', DB_ROW_SNAPSHOT, CANONICAL_ROW)
diff --git a/hermes_state_worker_compression.py b/hermes_state_worker_compression.py
index 02386552d5f..929a303ed7e 100644
--- a/hermes_state_worker_compression.py
+++ b/hermes_state_worker_compression.py
@@ -201,7 +201,7 @@ def worker_history(db, conn, sid, payload):
-def archive_on_connection(db, conn, session_id: str, compacted_messages: List[Dict[str, Any]], model_config_patch: Optional[Dict[str, Any]]=None, watermark: Optional[int]=None, lock_holder: Optional[str]=None, tail_count: int=0, carried_messages: Optional[List[Dict[str, Any]]]=None, covered_ids: Optional[List[int]]=None, unresolved_held: Optional[List[Dict[str, Any]]]=None):
+def archive_on_connection(db, conn, session_id: str, compacted_messages: list[dict[str, Any]], model_config_patch: Optional[dict[str, Any]]=None, watermark: Optional[int]=None, lock_holder: Optional[str]=None, tail_count: int=0, carried_messages: Optional[list[dict[str, Any]]]=None, covered_ids: Optional[list[int]]=None, unresolved_held: Optional[list[dict[str, Any]]]=None):
# The owner's in-place compaction body, on this receipt's connection: one implementation, so
# main's coverage/merge/timestamp/display-order fixes reach worker and mutation verbs too.
return db._archive_and_compact_on_conn(conn, session_id, compacted_messages,
@@ -209,7 +209,7 @@ def archive_on_connection(db, conn, session_id: str, compacted_messages: List[Di
tail_count=tail_count, carried_messages=carried_messages, covered_ids=covered_ids,
unresolved_held=unresolved_held)
-def publish_on_connection(db, conn, *, parent_session_id: str, child_session_id: str, source: str, messages: List[Dict[str, Any]], model: str=None, model_config: Dict[str, Any]=None, system_prompt: str=None, cwd: str=None, profile_name: str=None, compression_lock_holder: str=None, require_compression_lease: bool=True, require_lease_refresh: bool=False, lease_ttl_seconds: float=300.0, watermark: Optional[int]=None, watermark_ceiling: Optional[int]=None):
+def publish_on_connection(db, conn, *, parent_session_id: str, child_session_id: str, source: str, messages: list[dict[str, Any]], model: str=None, model_config: dict[str, Any]=None, system_prompt: str=None, cwd: str=None, profile_name: str=None, compression_lock_holder: str=None, require_compression_lease: bool=True, require_lease_refresh: bool=False, lease_ttl_seconds: float=300.0, watermark: Optional[int]=None, watermark_ceiling: Optional[int]=None):
# The owner's rotation body (lease, closure, child row, timestamps, tail clone, local target,
# auto-archive lift) on this receipt's connection, so the two paths cannot drift.
db._publish_compression_child_on_conn(conn, parent_session_id=parent_session_id,
@@ -226,11 +226,11 @@ def worker_watermark(db, conn, sid, payload):
def _handoff_messages(conn, sid, messages):
- from hermes_state_runtime import _MESSAGE_FIELDS
+ from hermes_state_runtime import HANDOFF_MESSAGE_FIELDS
if not isinstance(messages, list) or len(messages) > 1000:
raise RuntimeStoreError('invalid_params')
for msg in messages:
- if not isinstance(msg, dict) or set(msg) - _MESSAGE_FIELDS - {'_compressed_summary_has_user_turn'} or msg.get('role') not in ('user', 'assistant', 'system', 'tool'):
+ if not isinstance(msg, dict) or set(msg) - HANDOFF_MESSAGE_FIELDS or msg.get('role') not in ('user', 'assistant', 'system', 'tool'):
raise RuntimeStoreError('invalid_params')
if '_row_id' in msg and not conn.execute('SELECT 1 FROM messages WHERE session_id=? AND id=?',
(sid, msg['_row_id'])).fetchone():
diff --git a/tests/hermes_state/test_runtime_worker_compaction.py b/tests/hermes_state/test_runtime_worker_compaction.py
index 367369548ed..ea476e895cf 100644
--- a/tests/hermes_state/test_runtime_worker_compaction.py
+++ b/tests/hermes_state/test_runtime_worker_compaction.py
@@ -69,3 +69,32 @@ def test_in_place_archive_without_a_lease_persists_from_a_worker(worker):
assert db._read_one("SELECT COUNT(*) FROM messages WHERE session_id='owned' AND compacted=1")[0] == 2
store.append_messages_batch('owned', [{'role': 'user', 'content': 'after'}])
assert [r['content'] for r in store.get_messages_as_conversation('owned')] == ['pruned', 'after']
+
+
+def test_micro_compaction_live_dicts_persist_through_the_worker_like_direct(worker):
+ """The real micro-compaction commit hands its LIVE list (``_db_persisted`` stamps, the marker's
+ ``_micro_compact_marker``) to archive_and_compact. The worker facade projects those dicts onto the
+ closed handoff fields; otherwise the owner refuses the receipt and the sticky journal refuses every
+ later persist of the session (helix4u #4)."""
+ import types
+ from agent.context_compressor import COMPRESSED_SUMMARY_METADATA_KEY, MICRO_COMPACT_MARKER_KEY
+ from agent.micro_compaction import MicroCompactionMixin
+ db, store = worker
+ db.create_session('direct', 'cli')
+ durable = {}
+ for sid, sdb in (('direct', db), ('owned', store)):
+ live = [{'role': 'user', 'content': 'u1'}, {'role': 'assistant', 'content': 'a1'},
+ {'role': 'user', 'content': 'u2'}]
+ sdb.append_messages_batch(sid, live)
+ for message in live:
+ message['_db_persisted'] = True # sync_flushed_message_markers' post-commit stamp
+ marker = {'role': 'assistant', 'content': 'micro summary', COMPRESSED_SUMMARY_METADATA_KEY: True,
+ MICRO_COMPACT_MARKER_KEY: True, '_compressed_summary_has_user_turn': False}
+ compacted = [live[0], marker, live[2]]
+ assert MicroCompactionMixin._sync_micro_compact_to_db(
+ types.SimpleNamespace(_session_db=sdb, _session_id=sid), compacted)
+ assert marker[MICRO_COMPACT_MARKER_KEY] and marker['_db_persisted'] and isinstance(marker['_row_id'], int)
+ sdb.append_messages_batch(sid, [{'role': 'assistant', 'content': 'after'}])
+ durable[sid] = [r['content'] for r in db.get_messages_as_conversation(sid)]
+ assert store.failure is None and store.journal['pending'] == []
+ assert durable['owned'] == durable['direct'] == ['u1', 'micro summary', 'u2', 'after']