Skip to content

The agent that grows with you

fix(relay): emit no compaction mark from an uninstrumented turn or a detached fork

mnajafian-nv1c97c0ec35e1
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py
index 3edd95d5969..8794219f8d9 100644
--- a/agent/codex_runtime.py
+++ b/agent/codex_runtime.py
@@ -254,10 +254,7 @@ def _record_codex_app_server_compaction(agent, turn, *, approx_tokens: int | Non
if not force:
# Hermes-forced compactions are recorded by their compress_context attempt; this one Codex ran alone.
from agent.compaction_events import publish_provider_native
- publish_provider_native(
- session_id=getattr(agent, "session_id", None) or "",
- compression_count=getattr(compressor, "compression_count", None),
- )
+ publish_provider_native(agent)
return True
diff --git a/agent/compaction_events.py b/agent/compaction_events.py
index 1257d01f18d..b282845e4b7 100644
--- a/agent/compaction_events.py
+++ b/agent/compaction_events.py
@@ -2,7 +2,8 @@
One record per ``compress_context`` attempt (built from the attempt telemetry seam), per
micro-compaction pass, per committed proactive tool-result prune, and per Codex-native thread
-compaction Hermes observes. The payload is flat because OpenTelemetry exporters flatten only top-level
+compaction Hermes observes. A persistence-detached fork (background review) shares the live session id
+but rewrites only its own throwaway transcript, so it publishes nothing. The payload is flat because OpenTelemetry exporters flatten only top-level
keys; every categorical field comes from a closed set with an ``other`` fallback; no field carries
message, summary, focus-topic, error or path text. Publishing never raises into compaction.
"""
@@ -15,6 +16,8 @@ import threading
import uuid
from typing import Any
+from agent.model_metadata import estimate_messages_tokens_rough
+
logger = logging.getLogger(__name__)
SCHEMA_NAME = "hermes.compaction"
@@ -230,28 +233,39 @@ def _publish(build: Any, *args: Any, **kwargs: Any) -> None:
logger.log(logging.WARNING if first else logging.DEBUG, "compaction event publish failed", exc_info=True)
+def _publishes_for(agent: Any) -> bool:
+ """A persistence-detached fork (background review) rewrites only its own throwaway transcript."""
+ return not getattr(agent, "_persist_disabled", False)
+
+
def publish_attempt(agent: Any, record: dict[str, Any]) -> None:
"""Publish one ``compress_context`` attempt record (the attempt telemetry seam calls this)."""
- _publish(lambda: attempt_payload(
- record, compression_count=getattr(getattr(agent, "context_compressor", None), "compression_count", None),
- ))
+ if _publishes_for(agent):
+ _publish(lambda: attempt_payload(
+ record, compression_count=getattr(getattr(agent, "context_compressor", None), "compression_count", None),
+ ))
def publish_micro(record: dict[str, Any]) -> None:
- """Publish one micro-compaction pass record."""
+ """Publish one micro-compaction pass record. The finalizer never runs micro-compaction for a fork."""
_publish(micro_payload, record)
-def publish_prune(
- *, session_id: str, tokens_before: int, tokens_after: int, messages: int, tool_results_pruned: int,
-) -> None:
- """Publish one committed proactive tool-result prune."""
- _publish(
- prune_payload, session_id=session_id, tokens_before=tokens_before, tokens_after=tokens_after,
- messages=messages, tool_results_pruned=tool_results_pruned,
- )
+def publish_prune(agent: Any, messages: list, pruned: list, tool_results_pruned: int) -> None:
+ """Publish one committed proactive tool-result prune, measured like the attempt record (rough estimate of
+ the message list the model sees next)."""
+ if _publishes_for(agent):
+ _publish(lambda: prune_payload(
+ session_id=getattr(agent, "session_id", None) or "", tokens_before=estimate_messages_tokens_rough(messages),
+ tokens_after=estimate_messages_tokens_rough(pruned), messages=len(pruned),
+ tool_results_pruned=tool_results_pruned,
+ ))
-def publish_provider_native(*, session_id: str, compression_count: Any = None) -> None:
+def publish_provider_native(agent: Any) -> None:
"""Publish one provider-native compaction Hermes observed but did not run."""
- _publish(provider_native_payload, session_id=session_id, compression_count=compression_count)
+ if _publishes_for(agent):
+ _publish(
+ provider_native_payload, session_id=getattr(agent, "session_id", None) or "",
+ compression_count=getattr(getattr(agent, "context_compressor", None), "compression_count", None),
+ )
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 851482c2b79..06cdf502460 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -30,7 +30,6 @@ from agent.auxiliary_client import (
call_llm,
extract_content_or_reasoning,
)
-from agent.compaction_events import publish_prune
from agent.context_engine import ContextEngine, sanitize_memory_context
from agent.context_compressor_prellm import PreLlmSkipMixin
from agent.context_compressor_summary import SummaryDispatchMixin
@@ -3484,10 +3483,6 @@ class ContextCompressor(
self._proactive_prune_rearm_tokens = next_rearm_tokens
# Reclamation just ran: let a future lockout warn again.
self._last_reclaim_block_warn = None
- publish_prune(
- session_id=session_id or "", tokens_before=before, tokens_after=after, messages=len(pruned_msgs),
- tool_results_pruned=pruned_count,
- )
return pruned_msgs, pruned_count
def _compute_summary_budget(self, turns_to_summarize: list[dict[str, Any]]) -> int:
diff --git a/agent/relay_compaction.py b/agent/relay_compaction.py
index a7ea44ee40e..f34fdc8712f 100644
--- a/agent/relay_compaction.py
+++ b/agent/relay_compaction.py
@@ -1,9 +1,10 @@
"""Emit ``hermes.compaction`` records as NeMo Relay marks on the owning session's scope stack.
The mark goes under the live turn of the same session when there is one, else under that session's
-scope (gateway hygiene and other out-of-turn compactions). The session's own stack matters: Relay resets
-LLM-history freshness only for the agent scope that owns a ``compaction`` mark, so the next LLM start
-after a committed rewrite records the full history again. No live Relay host or session scope means
+scope (gateway hygiene and other out-of-turn compactions), and never from a turn Relay does not
+instrument. The session's own stack matters: Relay resets LLM-history freshness only for the agent scope
+that owns a ``compaction`` mark, so the next LLM start after a committed rewrite records the full history
+again. No live Relay host or session scope means
there is nothing to record. Relay exporters are configured by the user, so the mark adds no outbound
path of its own.
"""
@@ -21,7 +22,12 @@ COMPACTION_DATA_SCHEMA = {"name": "hermes.compaction", "version": "1"}
def _resolve_target(session_id: str) -> tuple[relay_runtime.RelayRuntime, relay_runtime.RelaySession, Any] | None:
- """``(host, session, parent handle)`` for ``session_id``: its live turn first, then its session scope."""
+ """``(host, session, parent handle)`` for ``session_id``: its live turn first, then its session scope.
+
+ A turn Relay does not instrument (a second concurrent turn on the session, such as a background-review
+ fork) gets nothing: its compaction rewrote its own transcript, not the live session's."""
+ if not relay_runtime.relay_instrumentation_enabled():
+ return None
turn = relay_runtime.active_turn(session_id)
host = turn.lease.live_runtime() if turn is not None else None
if host is not None:
diff --git a/agent/turn_preflight.py b/agent/turn_preflight.py
index f6351f95b33..0495d2aaee1 100644
--- a/agent/turn_preflight.py
+++ b/agent/turn_preflight.py
@@ -385,6 +385,9 @@ def compress_after_tool_results(
# conversation_history: rows already carry _DB_PERSISTED_MARKER, and on a
# stale in-place flag the helper could seed unpersisted rows.
if _pruned_n and _pruned_msgs is not messages:
+ from agent.compaction_events import publish_prune
+
+ publish_prune(agent, messages, _pruned_msgs, _pruned_n)
messages = _pruned_msgs
# A committed prune is a content-loss boundary like compaction: demoted skill_view /
# read_file bodies survive only as one-line markers, so the repeat-read dedup must
diff --git a/tests/agent/test_compaction_events.py b/tests/agent/test_compaction_events.py
index ab67a16d852..2697f964486 100644
--- a/tests/agent/test_compaction_events.py
+++ b/tests/agent/test_compaction_events.py
@@ -249,30 +249,61 @@ def test_micro_compaction_pass_publishes_one_record(published, outcome, name, ex
assert payload["tokens_reclaimed"] == 300
-def test_committed_proactive_prune_publishes_one_record(published):
+def _prune_after_tool_results(persist_disabled):
+ """Drive the post-tool caller with the attempt budget spent, so it takes the proactive prune branch."""
+ from agent.turn_preflight import compress_after_tool_results
+
compressor = _compressor(
proactive_prune_tokens=48_000, proactive_prune_min_result_chars=8_000, protect_first_n=2, protect_last_n=4,
)
- compressor._session_id = "prune-session"
+ compressor.last_prompt_tokens = 120_000
+ agent = SimpleNamespace(
+ context_compressor=compressor, compression_enabled=True, session_id="prune-session", tools=[],
+ _persist_disabled=persist_disabled, _usage_anchor=None, _compression_feasibility_checked=True,
+ _warn_context_overflow_blocked=lambda *_args: None,
+ )
msgs = [{"role": "system", "content": "sys"}]
for i in range(8):
msgs.append({"role": "assistant", "content": "", "tool_calls": [
{"id": f"c{i}", "type": "function", "function": {"name": "terminal", "arguments": "{}"}}
]})
msgs.append({"role": "tool", "tool_call_id": f"c{i}", "content": (chr(65 + i) + SECRET) * 600 if i < 3 else "ok"})
+ verdict = compress_after_tool_results(
+ agent, messages=msgs, system_message="sys", user_message="ask", active_system_prompt="sys",
+ conversation_history=None, compression_attempts=3, max_compression_attempts=3, effective_task_id="task",
+ final_response=None, turn_exit_reason=None, current_turn_user_idx=0,
+ )
+ return msgs, verdict.messages
+
- _result, pruned = compressor.prune_tool_results_only(msgs, current_tokens=120_000)
+def test_committed_proactive_prune_publishes_one_record(published):
+ msgs, pruned = _prune_after_tool_results(persist_disabled=False)
+ assert pruned is not msgs
[(session_id, name, payload)] = published
assert (session_id, name) == ("prune-session", "compaction")
assert (payload["kind"], payload["method"], payload["trigger"]) == (
"prune_tool_results", "deterministic_prune", "proactive_prune",
)
- assert payload["tool_results_pruned"] == pruned and payload["tokens_reclaimed"] > 0
+ assert payload["tool_results_pruned"] > 0 and payload["tokens_reclaimed"] > 0
+ assert payload["token_count_method"] == "estimate_rough"
assert payload["messages_before"] == payload["messages_after"] == len(msgs)
assert SECRET not in json.dumps(payload)
+def test_a_persistence_detached_fork_publishes_nothing(published):
+ """A background-review fork shares the live session id but rewrites only its own transcript."""
+ agent = _Agent(_compressor())
+ agent._persist_disabled = True
+
+ with patch.object(agent.context_compressor, "_generate_summary", return_value="SANITIZED SUMMARY"):
+ compressed, _ = compress_context(agent, _messages(), "system prompt", approx_tokens=80_000, trigger="pre_api")
+ msgs, pruned = _prune_after_tool_results(persist_disabled=True)
+
+ assert len(compressed) < len(_messages()) and pruned is not msgs
+ assert published == []
+
+
def test_rotation_publishes_after_the_split_with_the_attempts_own_session(published):
"""A rotating commit re-points the agent at a child session and its memory flush resets the compressor's
telemetry; the record is still built from this attempt's telemetry and names the session it started in."""
diff --git a/tests/agent/test_relay_compaction.py b/tests/agent/test_relay_compaction.py
index b73097f6b43..f20db7c7a74 100644
--- a/tests/agent/test_relay_compaction.py
+++ b/tests/agent/test_relay_compaction.py
@@ -132,3 +132,20 @@ def test_no_relay_session_skips_quietly(relay):
def test_no_relay_host_skips_quietly(monkeypatch):
monkeypatch.setattr(relay_runtime, "HOST_REGISTRY", _Registry(None))
assert emit_compaction_mark("s1", "compaction", _committed("s1")) is False
+
+
+def test_a_turn_relay_does_not_instrument_records_no_mark(relay):
+ """A second concurrent turn on a live session (a background-review fork, or a concurrent gateway turn) runs
+ with Relay instrumentation off. Its compaction must not mark the live session or reset its freshness."""
+ fake, runtime, coordinator = relay
+ lease = coordinator.acquire_conversation(profile_key=runtime.profile_key, session_id="s1", platform="cli")
+ live = coordinator.begin_turn(lease, turn_id="live", task_id="task")
+ fork = coordinator.begin_turn(lease, turn_id="fork", task_id="task")
+ try:
+ assert fork.relay_enabled is False
+ assert emit_compaction_mark("s1", "compaction", _committed("s1")) is False
+ finally:
+ coordinator.end_turn(fork, outcome="success")
+ coordinator.end_turn(live, outcome="success")
+
+ assert fake.scope.events == []