Skip to content

The agent that grows with you

fix(relay): mark a second rotating compaction on the turn it ran in

mnajafian-nv0edc904913e5
diff --git a/agent/compaction_events.py b/agent/compaction_events.py
index 408a2450b95..9107dd858ee 100644
--- a/agent/compaction_events.py
+++ b/agent/compaction_events.py
@@ -230,7 +230,7 @@ def provider_native_payload(*, session_id: str, compression_count: Any = None) -
)
-def _publish(build: Any, *args: Any, **kwargs: Any) -> None:
+def _publish(build: Any, *args: Any, turn_session_id: str | None = None, **kwargs: Any) -> None:
"""Build one record and fan it out to the built-in Relay integration. Never raises into compaction: the
first failure logs at WARNING with its traceback, later ones at DEBUG."""
global _warned
@@ -238,7 +238,7 @@ def _publish(build: Any, *args: Any, **kwargs: Any) -> None:
payload = build(*args, **kwargs)
from agent.relay_compaction import emit_compaction_mark
- emit_compaction_mark(payload["session_id"], event_name(payload), payload)
+ emit_compaction_mark(payload["session_id"], event_name(payload), payload, turn_session_id=turn_session_id)
except Exception:
with _warned_lock:
first, _warned = not _warned, True
@@ -250,12 +250,19 @@ def _publishes_for(agent: Any) -> bool:
return not getattr(agent, "_persist_disabled", False)
+def _turn_session_id(agent: Any) -> str | None:
+ """The session the agent's current turn started in; a rotating commit moves ``agent.session_id`` off it
+ mid-turn. ``None`` outside a turn."""
+ value = getattr(agent, "_inflight_turn_session_id", None)
+ return value if isinstance(value, str) and value else None
+
+
def publish_attempt(agent: Any, record: dict[str, Any]) -> None:
"""Publish one ``compress_context`` attempt record (the attempt telemetry seam calls this)."""
if _publishes_for(agent):
_publish(lambda: attempt_payload(
record, compression_count=getattr(getattr(agent, "context_compressor", None), "compression_count", None),
- ))
+ ), turn_session_id=_turn_session_id(agent))
def publish_micro(record: dict[str, Any]) -> None:
@@ -271,7 +278,7 @@ def publish_prune(agent: Any, messages: list, pruned: list, tool_results_pruned:
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,
- ))
+ ), turn_session_id=_turn_session_id(agent))
def publish_provider_native(agent: Any) -> None:
@@ -280,4 +287,5 @@ def publish_provider_native(agent: Any) -> None:
_publish(
provider_native_payload, session_id=getattr(agent, "session_id", None) or "",
compression_count=getattr(getattr(agent, "context_compressor", None), "compression_count", None),
+ turn_session_id=_turn_session_id(agent),
)
diff --git a/agent/relay_compaction.py b/agent/relay_compaction.py
index f34fdc8712f..0fac75e75f6 100644
--- a/agent/relay_compaction.py
+++ b/agent/relay_compaction.py
@@ -1,7 +1,8 @@
"""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), and never from a turn Relay does not
+scope (gateway hygiene and other out-of-turn compactions), else under the live turn the compacting agent
+started in (a child session a rotating commit created mid-turn), 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
@@ -21,18 +22,16 @@ logger = logging.getLogger(__name__)
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.
-
- 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
+def _turn_target(session_id: str) -> tuple[relay_runtime.RelayRuntime, relay_runtime.RelaySession, Any] | 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:
- session = turn.lease.session
- return host, session, turn.handle or session.handle
+ if host is None:
+ return None
+ session = turn.lease.session
+ return host, session, turn.handle or session.handle
+
+
+def _session_target(session_id: str) -> tuple[relay_runtime.RelayRuntime, relay_runtime.RelaySession, Any] | None:
host = relay_runtime.HOST_REGISTRY.for_profile(create=False)
if not isinstance(host, relay_runtime.RelayRuntime):
return None
@@ -42,9 +41,31 @@ def _resolve_target(session_id: str) -> tuple[relay_runtime.RelayRuntime, relay_
return host, session, session.handle
-def emit_compaction_mark(session_id: str, name: str, data: dict[str, Any]) -> bool:
- """Emit one mark; returns False when no Relay session owns ``session_id``."""
- target = _resolve_target(session_id) if session_id else None
+def _resolve_target(
+ session_id: str, turn_session_id: str | None = None,
+) -> tuple[relay_runtime.RelayRuntime, relay_runtime.RelaySession, Any] | None:
+ """``(host, session, parent handle)`` for ``session_id``: its live turn, then its session scope, then the
+ live turn of ``turn_session_id``.
+
+ ``turn_session_id`` is the session the compacting agent's turn started in. A rotating commit moves the
+ agent to a child session that has no Relay scope until the next turn opens one, so a later rotation in
+ the same turn is marked on that turn. When the child already has a scope, that scope owns the next LLM
+ starts for the child and keeps the mark. 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
+ target = _turn_target(session_id) or _session_target(session_id)
+ if target is None and turn_session_id:
+ target = _turn_target(turn_session_id)
+ return target
+
+
+def emit_compaction_mark(
+ session_id: str, name: str, data: dict[str, Any], *, turn_session_id: str | None = None,
+) -> bool:
+ """Emit one mark; returns False when no Relay scope owns ``session_id`` (see ``_resolve_target``)."""
+ target = _resolve_target(session_id, turn_session_id) if session_id else None
if target is None:
logger.debug("no live Relay session for %s; %s mark not recorded", session_id or "none", name)
return False
diff --git a/tests/agent/test_compaction_events.py b/tests/agent/test_compaction_events.py
index 3915a0678b9..02bd8755b54 100644
--- a/tests/agent/test_compaction_events.py
+++ b/tests/agent/test_compaction_events.py
@@ -38,7 +38,7 @@ def published(monkeypatch):
marks = []
monkeypatch.setattr(
"agent.relay_compaction.emit_compaction_mark",
- lambda session_id, name, data: marks.append((session_id, name, data)) or True,
+ lambda session_id, name, data, **_kwargs: marks.append((session_id, name, data)) or True,
)
return marks
diff --git a/tests/agent/test_relay_compaction.py b/tests/agent/test_relay_compaction.py
index f20db7c7a74..7d1a155b58d 100644
--- a/tests/agent/test_relay_compaction.py
+++ b/tests/agent/test_relay_compaction.py
@@ -8,6 +8,7 @@ hygiene runs outside any turn). Relay resets LLM-history freshness only for the
from __future__ import annotations
from typing import Any
+from unittest.mock import patch
import pytest
@@ -149,3 +150,73 @@ def test_a_turn_relay_does_not_instrument_records_no_mark(relay):
coordinator.end_turn(live, outcome="success")
assert fake.scope.events == []
+
+
+def test_a_turn_fallback_lands_only_on_the_turn_the_agent_started_in(relay):
+ """An unscoped child session falls back to the live turn only when the agent's turn started in that
+ turn's session; a turn of any other session never receives the mark."""
+ fake, runtime, coordinator = relay
+ lease = coordinator.acquire_conversation(profile_key=runtime.profile_key, session_id="s1", platform="cli")
+ turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task")
+ try:
+ assert emit_compaction_mark("child", "compaction", _committed("child"), turn_session_id="other") is False
+ assert emit_compaction_mark("child", "compaction", _committed("child"), turn_session_id="s1") is True
+ finally:
+ coordinator.end_turn(turn, outcome="success")
+
+ [event] = fake.scope.events
+ assert (event["handle"], event["data"]["session_id"]) == (turn.handle, "child")
+
+
+def _transcript(start: int) -> list[dict[str, Any]]:
+ filler = " ".join(["context"] * 200)
+ return [
+ message
+ for idx in range(start, start + 10)
+ for message in (
+ {"role": "user", "content": f"user message {idx} {filler}"},
+ {"role": "assistant", "content": f"assistant reply {idx} {filler}"},
+ )
+ ]
+
+
+def test_every_rotation_in_one_turn_is_marked_on_that_turn(relay, tmp_path, monkeypatch):
+ """With ``compression.in_place: false`` each commit moves the agent to a child session, and the child has
+ no Relay scope while the turn that rotated into it is still running. A second rotation in that turn (a
+ multi-pass preflight) must still be marked on the live turn, not dropped."""
+ from agent.agent_runtime_helpers import note_turn_persisted, note_turn_start
+ 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
+ agent.context_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(agent.context_compressor, "_generate_summary", return_value="SANITIZED SUMMARY"):
+ first, _ = agent._compress_context(
+ [{"role": "system", "content": "sys"}, *_transcript(0)], "sys", approx_tokens=80_000,
+ trigger="turn_start_threshold",
+ )
+ child = agent.session_id
+ agent._compress_context(first + _transcript(10), "sys", approx_tokens=80_000, trigger="turn_start_threshold")
+ finally:
+ note_turn_persisted(agent)
+ coordinator.end_turn(turn, outcome="success")
+ agent.close()
+
+ assert "rotating-session" != child != agent.session_id
+ marks = [event for event in fake.scope.events if event["name"].startswith("compaction")]
+ assert [(mark["name"], mark["data"]["session_id"]) for mark in marks] == [
+ ("compaction", "rotating-session"), ("compaction", child),
+ ]
+ assert all(mark["handle"] is turn.handle for mark in marks)
+ assert all(mark["data"]["split_status"] == "rotated_committed" for mark in marks)
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 9551b5cad22..028d2d2c6b2 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -163,9 +163,14 @@ history is still `committed` (the model sees the compacted history next), with
The mark is parented to the live `hermes.turn` of the same session, or to the
`hermes.session` scope when compaction runs outside a turn (gateway hygiene).
-No mark is emitted from a turn Relay does not instrument (a second concurrent
-turn on the same session) or from a persistence-detached fork such as
-background review: their compaction rewrites only their own transcript.
+With `compression.in_place: false`, a rotating commit moves the agent to a
+child session that has no Relay scope until a later Relay-managed LLM call or
+the 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
+emitted from a turn Relay does not instrument (a second concurrent turn on the
+same session) or from a persistence-detached fork such as background review:
+their compaction rewrites only their own transcript.
`data` is flat so OpenTelemetry flattens every field into
`nemo_relay.mark.data.<key>`. Every v1 key is present on every mark; a value
@@ -213,9 +218,6 @@ report the same compaction again.
Known gaps in v1:
-- With `compression.in_place: false`, a second rotating compaction in the same
- turn emits no mark: its new session has no Relay scope until the next turn,
- which opens fresh.
- With `gateway.telemetry.session_segments.on_compaction: true`, a rotating
commit outside any turn closes the old Relay session before the mark is
emitted, so the mark is dropped. No current caller does this: manual