The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): mark a micro-compaction in a rotated child on the turn it ran in
mnajafian-nv814cde892a56
diff --git a/agent/compaction_events.py b/agent/compaction_events.pyindex 54393f75cc4..2c79f7292c3 100644--- a/agent/compaction_events.py+++ b/agent/compaction_events.py@@ -269,9 +269,10 @@ def publish_attempt(agent: Any, record: dict[str, Any]) -> None:), turn_session_id=_turn_session_id(agent))-def publish_micro(record: dict[str, Any]) -> None:- """Publish one micro-compaction pass record. The finalizer never runs micro-compaction for a fork."""- _publish(micro_payload, record)+def publish_micro(record: dict[str, Any], *, turn_session_id: str | None = None) -> None:+ """Publish one micro-compaction pass record. The finalizer never runs micro-compaction for a fork, and passes+ the session its turn started in (``_turn_session_id``) because the pass may run in a rotated child."""+ _publish(micro_payload, record, turn_session_id=turn_session_id)def publish_prune(agent: Any, messages: list, pruned: list, tool_results_pruned: int) -> None:diff --git a/agent/micro_compaction.py b/agent/micro_compaction.pyindex 02255683f0e..5fd5ffa3ceb 100644--- a/agent/micro_compaction.py+++ b/agent/micro_compaction.py@@ -201,10 +201,13 @@ class MicroCompactionMixin:self._micro_compact_consecutive_failures = 0self._micro_compact_last_failure_cursor = -1- def _micro_compact(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ def _micro_compact(+ self, messages: list[dict[str, Any]], *, turn_session_id: Optional[str] = None,+ ) -> list[dict[str, Any]]:"""Run one round of micro-compaction (entry point from ``finalize_turn()``). Returns the(possibly modified) list and syncs the session DB via ``archive_and_compact`` (the- append-only flush alone would double-load on resume)."""+ append-only flush alone would double-load on resume). ``turn_session_id`` is the session the+ caller's turn started in; it parents the pass's Relay mark when this session has no scope yet."""if not self._micro_compact_enabled:return messages@@ -235,7 +238,8 @@ class MicroCompactionMixin:def _telemetry(outcome: str, result: list[dict[str, Any]], **extra: Any) -> None:self._emit_micro_compaction_telemetry(outcome=outcome, messages_before=n_messages, messages_after=len(result),- tokens_before=_tokens_before, duration_ms=int((time.monotonic() - _started_at) * 1000), **extra,+ tokens_before=_tokens_before, duration_ms=int((time.monotonic() - _started_at) * 1000),+ turn_session_id=turn_session_id, **extra,)if _skip: # unanswerable watermark (unbounded archive) or a stale generation (no lease): skip@@ -341,6 +345,7 @@ class MicroCompactionMixin:def _emit_micro_compaction_telemetry(self, *, outcome: str, messages_before: int, messages_after: int, tokens_before: int | None,tokens_after: int | None, exchange_tokens: int | None = None, duration_ms: int | None = None,+ turn_session_id: str | None = None,) -> None:"""Emit one content-free JSON log line for a micro-compaction pass.``tokens_delta`` < 0 means the pass shrank the transcript; ``*_total`` fields accumulate."""@@ -369,7 +374,7 @@ class MicroCompactionMixin:"occupancy_pct": occupancy, "main_model": self.model or "", "aux_model": self.summary_model or "",}logger.info("micro compaction telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":")))- publish_micro(payload)+ publish_micro(payload, turn_session_id=turn_session_id)except Exception as exc:logger.debug("failed to emit micro-compaction telemetry: %s", exc)diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex 797fe7e7ee6..9fd39ec52d1 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -303,7 +303,10 @@ def _micro_compact_after_turn(agent, messages, final_response, logger, task_id)and not getattr(agent, "_persist_disabled", False)):_before = len(messages)- _compacted = _compressor._micro_compact(messages)+ # A rotating compaction earlier in this turn may have moved the agent to a child session.+ _compacted = _compressor._micro_compact(+ messages, turn_session_id=getattr(agent, "_inflight_turn_session_id", None),+ )# Defrag rewrites the newest MICRO marker in place and pops _db_persisted;# the compressor flags us to invalidate the flush-scan cursor, else the# rewritten row is identity-skipped (stale).diff --git a/tests/agent/test_pre_compress_checkpoint_contract.py b/tests/agent/test_pre_compress_checkpoint_contract.pyindex 69cce6f17c1..28dec1e1586 100644--- a/tests/agent/test_pre_compress_checkpoint_contract.py+++ b/tests/agent/test_pre_compress_checkpoint_contract.py@@ -500,7 +500,7 @@ def test_turn_finalizer_never_micro_compacts_while_checkpoint_gate_armed(def __init__(self):self.calls = 0- def _micro_compact(self, messages):+ def _micro_compact(self, messages, **_kwargs):self.calls += 1return list(messages)diff --git a/tests/agent/test_read_dedup_rewrite_boundaries.py b/tests/agent/test_read_dedup_rewrite_boundaries.pyindex bb57326a266..7e723b6e92f 100644--- a/tests/agent/test_read_dedup_rewrite_boundaries.py+++ b/tests/agent/test_read_dedup_rewrite_boundaries.py@@ -100,8 +100,8 @@ def test_micro_compaction_splice_rearms_read_dedup(served, splice, monkeypatch):# A splice returns a new list with the oldest exchange folded into the rolling summary;# a no-op (nothing to absorb, or a defrag) returns the input list.compressor._micro_compact = (- (lambda messages: [{"role": "user", "content": "[MICRO] loaded demo-skill"}, *messages[4:]])- if splice else (lambda messages: messages))+ (lambda messages, **_kw: [{"role": "user", "content": "[MICRO] loaded demo-skill"}, *messages[4:]])+ if splice else (lambda messages, **_kw: messages))agent.context_compressor = compressoragent.client.chat.completions.create.return_value = SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(diff --git a/tests/agent/test_relay_compaction.py b/tests/agent/test_relay_compaction.pyindex 7d1a155b58d..ffbe4dba2a9 100644--- a/tests/agent/test_relay_compaction.py+++ b/tests/agent/test_relay_compaction.py@@ -220,3 +220,49 @@ def test_every_rotation_in_one_turn_is_marked_on_that_turn(relay, tmp_path, monk]assert all(mark["handle"] is turn.handle for mark in marks)assert all(mark["data"]["split_status"] == "rotated_committed" for mark in marks)+++def test_a_post_turn_micro_compaction_in_a_rotated_child_is_marked_on_the_turn(relay, tmp_path, monkeypatch):+ """A rotating commit moves the agent to a child session with no Relay scope. The micro-compaction pass the+ finalizer then runs in that child, before the turn ends, must be marked on the live turn like the+ rotation itself, not dropped."""+ import logging++ from agent.agent_runtime_helpers import note_turn_persisted, note_turn_start+ from agent.turn_finalizer import _micro_compact_after_turn+ from hermes_state import SessionDB+ from run_agent import AIAgent++ fake, runtime, coordinator = relay+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")+ agent = AIAgent(+ api_key="test-key", base_url="https://openrouter.ai/api/v1", model="test/model", quiet_mode=True,+ session_db=SessionDB(db_path=tmp_path / "state.db"), session_id="rotating-session",+ skip_context_files=True, skip_memory=True,+ )+ agent.compression_in_place = False+ compressor = agent.context_compressor+ compressor.tail_token_budget = 10+ lease = coordinator.acquire_conversation(profile_key=runtime.profile_key, session_id="rotating-session", platform="cli")+ turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task")+ note_turn_start(agent, "t1")+ try:+ with patch.object(compressor, "_generate_summary", return_value="SANITIZED SUMMARY"):+ compacted, _ = agent._compress_context(+ [{"role": "system", "content": "sys"}, *_transcript(0)], "sys", approx_tokens=80_000,+ trigger="turn_start_threshold",+ )+ child = agent.session_id+ compressor._micro_compact_enabled = True+ with patch.object(compressor, "_micro_summarize_one", return_value="ROLLING SUMMARY"):+ _micro_compact_after_turn(+ agent, compacted + _transcript(10), "done", logging.getLogger(__name__), "task",+ )+ finally:+ note_turn_persisted(agent)+ coordinator.end_turn(turn, outcome="success")+ agent.close()++ assert child != "rotating-session"+ micro = [event for event in fake.scope.events if event["data"]["kind"] == "micro_summarize"]+ assert [(mark["data"]["session_id"], mark["handle"]) for mark in micro] == [(child, turn.handle)]diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 909d6491d0a..e60265876f1 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -166,8 +166,9 @@ The mark is parented to the live `hermes.turn` of the same session, or to theWith `compression.in_place: false`, a rotating commit moves the agent to achild session that has no Relay scope until a later Relay-managed LLM call orthe next turn opens one. While it has none, a compaction in the child (a-second preflight pass, for example) is parented to the live `hermes.turn` the-agent started in, and `data.session_id` still names the child. No mark is+second preflight pass, or the micro-compaction pass that runs before the turn+ends) is parented to the live `hermes.turn` the agent started in, and+`data.session_id` still names the child. No mark isemitted from a turn Relay does not instrument (a second concurrent turn on thesame session) or from a persistence-detached fork such as background review:their compaction rewrites only their own transcript.