feat(relay): session-span segmentation for continuous sessions

Continuous gateway sessions keep the Relay session scope open for days;
close-driven export means the session root span and out-of-turn marks
never export until /new or idle-end, and a crash loses the open segment
entirely.

Opt-in segmentation (both defaults OFF => scope lifecycle byte-identical
to today):

  gateway.telemetry.session_segments.on_compaction: false
  gateway.telemetry.session_segments.max_turns: 0

Rotation closes the current session scope and pushes the next segment
(same session_id attribute, plus hermes.session.segment=N and
segment_reason=compaction|max_turns) ONLY at a turn boundary in
begin_turn — never mid-turn (scope stack is LIFO). Compaction completion
just flags rotate_pending (observer semantics, nothing on the compaction
critical path); legacy rotating compaction closes the orphaned old
session scope so its segment exports. Both native calls ride the
existing bounded scope-op executor: a wedged rotation costs one segment
span, never the agent. Segment bookkeeping advances even on native
failure so a degraded rotation cannot retry every turn.
This commit is contained in:
Victor Kyriazakos
2026-08-13 03:17:30 +00:00
committed by Teknium
parent 1df33dccfe
commit 11c74beffa
3 changed files with 600 additions and 0 deletions
+14
View File
@@ -2092,6 +2092,20 @@ def _notify_context_engine_compression_complete(
old_session_id: str,
) -> bool:
"""Notify the active context engine after a durable compression commit."""
# Relay session-span segmentation (opt-in, gateway.telemetry.
# session_segments.on_compaction): flag the session so its telemetry
# scope rotates at the next turn boundary. Observer semantics — a
# failure here must never undo or delay the committed compression.
try:
from agent import relay_runtime
relay_runtime.SESSION_COORDINATOR.notify_session_compacted(
profile_key=relay_runtime.current_profile_key(),
session_id=new_session_id,
old_session_id=old_session_id,
)
except Exception:
logger.debug("relay segment rotation notification failed", exc_info=True)
callback = getattr(agent.context_compressor, "on_session_start", None)
if not callable(callback):
return False
+209
View File
@@ -104,6 +104,61 @@ class RelaySession:
closing: bool = False
handle: Any = None
context: contextvars.Context | None = None
# --- session-span segmentation (continuous sessions) ---
# Segment index of the CURRENT session scope (0 = first). Rotation
# closes the current scope and pushes segment N+1 at a turn boundary.
segment: int = 0
# Turns completed within the current segment (max_turns accounting).
segment_turns: int = 0
# Set by compaction notification; consumed at the next begin_turn.
rotate_pending: bool = False
# ---------------------------------------------------------------------------
# Session-span segmentation config (gateway.telemetry.session_segments).
# Cached at first read; both defaults OFF => rotation never fires and the
# scope lifecycle is byte-identical to the pre-segmentation behavior.
# ---------------------------------------------------------------------------
_SEGMENTS_CONFIG: dict[str, Any] | None = None
_SEGMENTS_CONFIG_LOCK = threading.Lock()
def _segments_config() -> dict[str, Any]:
"""Resolve session-segmentation settings; inert defaults when unset."""
global _SEGMENTS_CONFIG
if _SEGMENTS_CONFIG is None:
with _SEGMENTS_CONFIG_LOCK:
if _SEGMENTS_CONFIG is None:
on_compaction = False
max_turns = 0
try:
from gateway.run import _load_gateway_config # late import
telemetry = (
(_load_gateway_config().get("gateway") or {}).get(
"telemetry"
)
or {}
)
segments = telemetry.get("session_segments") or {}
on_compaction = bool(segments.get("on_compaction", False))
try:
max_turns = max(0, int(segments.get("max_turns", 0) or 0))
except (TypeError, ValueError):
max_turns = 0
except Exception: # noqa: BLE001 - config absence must not crash
pass
_SEGMENTS_CONFIG = {
"on_compaction": on_compaction,
"max_turns": max_turns,
}
return _SEGMENTS_CONFIG
def _reset_segments_config_for_tests() -> None:
global _SEGMENTS_CONFIG
_SEGMENTS_CONFIG = None
class RelayRuntime:
@@ -210,6 +265,79 @@ class RelayRuntime:
session.context = context
return session
def rotate_session_scope(self, session: RelaySession, *, reason: str) -> None:
"""Close the current session scope and open the next segment.
Called ONLY at a turn boundary (before the turn scope pushes), never
mid-turn: the scope stack is LIFO and rotating under a live child
would close a parent out of order. Both native calls are bounded by
``_SCOPE_OP_TIMEOUT`` — a wedged rotation costs one segment span,
never the agent. Segment bookkeeping advances even when a native
call fails, so a degraded rotation cannot retry on every turn.
"""
with session.lock:
if session.closing or session.handle is None:
return
old_handle = session.handle
# Advance bookkeeping FIRST: a failed native call must not leave
# rotate_pending set (tight rotation loop on every turn).
session.segment += 1
session.segment_turns = 0
session.rotate_pending = False
try:
self.run_in_session(
session,
self.relay.scope.pop,
old_handle,
output={"hermes.session.segment_reason": reason},
metadata={
RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION,
RUNTIME_INSTANCE_KEY: self.runtime_id,
},
timeout=_SCOPE_OP_TIMEOUT,
)
except Exception:
logger.warning(
"Hermes Relay segment close failed (session=%s segment=%d); "
"abandoning the old segment span",
session.session_id,
session.segment - 1,
exc_info=True,
)
scope_metadata = {
RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION,
RUNTIME_INSTANCE_KEY: self.runtime_id,
"hermes.session.segment": session.segment,
"hermes.session.segment_reason": reason,
}
parent_handle = None
if session.parent_session_id:
with self._sessions_lock:
parent_handle = self._subagent_parent_handles.get(
session.session_id
)
scope_metadata["nemo_relay_scope_role"] = "subagent"
context = contextvars.Context()
try:
session.handle = _scope_op_executor().submit(
context.run,
self.relay.scope.push,
SESSION_SCOPE,
self.relay.ScopeType.Agent,
handle=parent_handle,
input={},
metadata=scope_metadata,
).result(timeout=_SCOPE_OP_TIMEOUT)
session.context = context
except Exception:
logger.warning(
"Hermes Relay segment open failed (session=%s segment=%d); "
"keeping the prior scope handle",
session.session_id,
session.segment,
exc_info=True,
)
def register_subagent(
self,
event: dict[str, Any],
@@ -774,6 +902,27 @@ class RelaySessionCoordinator:
and isinstance(lease.host, RelayRuntime)
and lease.session is not None
):
# Session-span segmentation: consume a pending rotation (set by
# compaction) or the max_turns cap HERE — the only point where
# no turn scope is live on this session's stack, so the session
# scope can close/reopen without violating LIFO order.
try:
config = _segments_config()
session = lease.session
cap = config["max_turns"]
if (config["on_compaction"] and session.rotate_pending) or (
cap > 0 and session.segment_turns >= cap
):
reason = (
"compaction"
if config["on_compaction"] and session.rotate_pending
else "max_turns"
)
lease.host.rotate_session_scope(session, reason=reason)
except Exception:
logger.warning(
"Hermes Relay segment rotation failed", exc_info=True
)
try:
turn.handle = lease.host.run_in_session(
lease.session,
@@ -828,6 +977,17 @@ class RelaySessionCoordinator:
"Hermes Relay turn finalization failed", exc_info=True
)
finally:
try:
# Segment turn accounting (max_turns rotation trigger).
if (
turn._active_registered
and isinstance(lease.host, RelayRuntime)
and lease.session is not None
):
with lease.session.lock:
lease.session.segment_turns += 1
except Exception: # noqa: BLE001 - accounting must never block
pass
try:
# Delegated agents own one turn. Close their conversation
# while the active-turn guard is still held so a parent
@@ -848,6 +1008,55 @@ class RelaySessionCoordinator:
self._unregister_active_turn(turn)
self._reset_turn_context(turn)
def notify_session_compacted(
self,
*,
profile_key: str,
session_id: str,
old_session_id: str = "",
) -> None:
"""React to a completed compaction, per compaction mode.
In-place compaction (``old_session_id`` empty or equal to
``session_id``): flag the session for segment rotation at its next
turn boundary. Never rotates immediately — a compaction can
complete while a turn is live, and rotation under a live turn
scope would violate the scope stack's LIFO order; ``begin_turn``
consumes the flag.
Legacy rotating compaction (``old_session_id`` differs): the next
turn acquires a fresh Relay session under the new id on its own,
but the OLD session's scope would stay open forever — an
unexported orphan. Close it now so the pre-compaction segment
exports.
Unknown sessions and disabled config are silent no-ops; this
method must never add work or failure modes to the compaction
critical path.
"""
try:
if not _segments_config()["on_compaction"]:
return
host = self.registry.for_profile(profile_key)
if not isinstance(host, RelayRuntime):
return
if old_session_id and old_session_id != session_id:
# Rotating compaction: export the orphaned pre-compaction
# session scope (close_session is already bounded).
host.close_session({"session_id": old_session_id})
return
with host._sessions_lock:
session = host._sessions.get(session_id)
if session is None:
return
with session.lock:
if not session.closing:
session.rotate_pending = True
except Exception: # noqa: BLE001 - telemetry must never block compaction
logger.warning(
"Hermes Relay compaction notification failed", exc_info=True
)
def has_active_turn(self, *, profile_key: str, session_id: str) -> bool:
"""Return whether a turn is still running for one profile/session."""
key = (profile_key, session_id)
+377
View File
@@ -0,0 +1,377 @@
"""Session-span segmentation for continuous sessions.
Continuous gateway sessions keep the Relay session scope open indefinitely;
close-driven export means the session root span (and out-of-turn marks) are
unexported until /new or idle-end, and a crash loses the whole segment.
Segmentation closes the current session scope at a TURN BOUNDARY and pushes
a fresh one, chaining segments via metadata:
gateway.telemetry.session_segments.on_compaction (default False)
gateway.telemetry.session_segments.max_turns (default 0 = unlimited)
Both defaults off => behavior identical to today (no rotation, ever).
Rotation never happens mid-turn: compaction only sets rotate_pending,
consumed at the next begin_turn before the turn scope pushes.
"""
from __future__ import annotations
import threading
from typing import Any
import pytest
from agent import relay_runtime
from agent.relay_runtime import (
RelayRuntime,
RelaySessionCoordinator,
)
class _ScopeHandle:
def __init__(self, name: str, seq: int) -> None:
self.name = name
self.seq = seq
class _FakeScopeModule:
def __init__(self, wedge_pop: threading.Event | None = None) -> None:
self._wedge = wedge_pop
self._seq = 0
self.pushes: list[dict[str, Any]] = [] # {name, metadata, handle}
self.pops: list[_ScopeHandle] = []
def push(self, name: str, scope_type: Any, **kwargs: Any) -> _ScopeHandle:
self._seq += 1
self.pushes.append(
{
"name": name,
"metadata": dict(kwargs.get("metadata") or {}),
"parent": kwargs.get("handle"),
"seq": self._seq,
}
)
return _ScopeHandle(name, self._seq)
def pop(self, handle: _ScopeHandle, **kwargs: Any) -> None:
if self._wedge is not None:
self._wedge.wait()
self.pops.append(handle)
def event(self, *args: Any, **kwargs: Any) -> None:
return None
class _FakeSubscribers:
def __init__(self) -> None:
self.flushed = 0
def flush(self) -> None:
self.flushed += 1
class _FakeScopeType:
Function = "function"
Agent = "agent"
class _FakeRelay:
def __init__(self, wedge_pop: threading.Event | None = None) -> None:
self.scope = _FakeScopeModule(wedge_pop)
self.subscribers = _FakeSubscribers()
self.ScopeType = _FakeScopeType()
def get_scope_stack(self) -> None:
return None
_LIVE: list[tuple[RelayRuntime, _FakeRelay]] = []
def _make_runtime(fake: _FakeRelay) -> RelayRuntime:
runtime = RelayRuntime(relay=fake, profile_key="/tmp/test-profile")
_LIVE.append((runtime, fake))
return runtime
@pytest.fixture(autouse=True)
def _teardown_runtimes():
"""Unwedge and drain every runtime so exit paths never replay wedged ops."""
yield
for runtime, fake in _LIVE:
if fake.scope._wedge is not None:
fake.scope._wedge.set()
runtime.shutdown()
_LIVE.clear()
@pytest.fixture(autouse=True)
def _fast_scope_timeout(monkeypatch):
monkeypatch.setattr(relay_runtime, "_SCOPE_OP_TIMEOUT", 1.0)
@pytest.fixture(autouse=True)
def _default_config(monkeypatch):
"""No config on disk by default; tests override _segments_config directly."""
monkeypatch.setattr(
"gateway.run._load_gateway_config", lambda: {}, raising=False
)
relay_runtime._reset_segments_config_for_tests()
def _set_segments(monkeypatch, *, on_compaction=False, max_turns=0):
monkeypatch.setattr(
"gateway.run._load_gateway_config",
lambda: {
"gateway": {
"telemetry": {
"session_segments": {
"on_compaction": on_compaction,
"max_turns": max_turns,
}
}
}
},
raising=False,
)
relay_runtime._reset_segments_config_for_tests()
@pytest.fixture()
def coordinator() -> RelaySessionCoordinator:
return RelaySessionCoordinator()
def _acquire(coordinator, runtime, session_id="sess-1"):
class _Registry:
def for_profile(self, key):
return runtime
coordinator.registry = _Registry()
coordinator._prepare_session = lambda host, ctx: None
return coordinator.acquire_conversation(
profile_key=runtime.profile_key,
session_id=session_id,
platform="test",
)
def _session_pushes(fake):
return [p for p in fake.scope.pushes if p["name"] == relay_runtime.SESSION_SCOPE]
def _run_turn(coordinator, lease, turn_id):
turn = coordinator.begin_turn(lease, turn_id=turn_id, task_id=f"task-{turn_id}")
coordinator.end_turn(turn, outcome="success")
return turn
class TestDefaultsNeverRotate:
def test_no_rotation_across_many_turns_and_compactions(self, coordinator):
fake = _FakeRelay()
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
assert lease.session is not None
coordinator.notify_session_compacted(
profile_key=runtime.profile_key, session_id="sess-1"
)
for i in range(5):
_run_turn(coordinator, lease, f"t{i}")
assert len(_session_pushes(fake)) == 1, (
"defaults off must never rotate the session scope — "
"today's behavior is the contract"
)
class TestCompactionRotation:
def test_compaction_rotates_at_next_begin_turn_not_immediately(
self, coordinator, monkeypatch
):
_set_segments(monkeypatch, on_compaction=True)
fake = _FakeRelay()
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
original_handle = lease.session.handle
coordinator.notify_session_compacted(
profile_key=runtime.profile_key, session_id="sess-1"
)
# No rotation yet — compaction only flags; scope stack untouched.
assert len(_session_pushes(fake)) == 1
assert not fake.scope.pops
turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task1")
sessions = _session_pushes(fake)
assert len(sessions) == 2, "rotation must happen at the next begin_turn"
# Old session scope was popped before the new push.
assert any(p.seq == 1 for p in fake.scope.pops), "old segment scope popped"
assert lease.session.handle is not original_handle
# The turn scope parents to the NEW segment handle.
turn_push = [p for p in fake.scope.pushes if p["name"] == relay_runtime.TURN_SCOPE][-1]
assert turn_push["parent"] is lease.session.handle
coordinator.end_turn(turn, outcome="success")
def test_segment_metadata_on_rotated_scope(self, coordinator, monkeypatch):
_set_segments(monkeypatch, on_compaction=True)
fake = _FakeRelay()
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
coordinator.notify_session_compacted(
profile_key=runtime.profile_key, session_id="sess-1"
)
_run_turn(coordinator, lease, "t1")
new_seg = _session_pushes(fake)[-1]["metadata"]
assert new_seg.get("hermes.session.segment") == 1
assert new_seg.get("hermes.session.segment_reason") == "compaction"
def test_unknown_session_compaction_is_noop(self, coordinator, monkeypatch):
_set_segments(monkeypatch, on_compaction=True)
fake = _FakeRelay()
runtime = _make_runtime(fake)
_acquire(coordinator, runtime)
# Must not raise, must not rotate anything.
coordinator.notify_session_compacted(
profile_key=runtime.profile_key, session_id="never-seen"
)
assert len(_session_pushes(fake)) == 1
def test_rotating_compaction_closes_old_session_scope(
self, coordinator, monkeypatch
):
"""Legacy compaction rotates to a child session id: the OLD session's
scope must close (export) instead of orphaning unexported forever."""
_set_segments(monkeypatch, on_compaction=True)
fake = _FakeRelay()
runtime = _make_runtime(fake)
_acquire(coordinator, runtime, session_id="parent-1")
assert not fake.scope.pops
coordinator.notify_session_compacted(
profile_key=runtime.profile_key,
session_id="child-1",
old_session_id="parent-1",
)
assert len(fake.scope.pops) == 1, (
"rotating compaction must close the old session scope"
)
assert fake.subscribers.flushed >= 1
def test_rotating_compaction_noop_when_disabled(self, coordinator, monkeypatch):
fake = _FakeRelay()
runtime = _make_runtime(fake)
_acquire(coordinator, runtime, session_id="parent-1")
coordinator.notify_session_compacted(
profile_key=runtime.profile_key,
session_id="child-1",
old_session_id="parent-1",
)
assert not fake.scope.pops, "defaults off: rotating compaction is a no-op"
class TestMaxTurnsRotation:
def test_rotates_after_cap(self, coordinator, monkeypatch):
_set_segments(monkeypatch, max_turns=2)
fake = _FakeRelay()
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
for i in range(5):
_run_turn(coordinator, lease, f"t{i}")
# turns 0,1 in segment 0; rotation before turn 2; turns 2,3 in
# segment 1; rotation before turn 4.
sessions = _session_pushes(fake)
assert len(sessions) == 3, "cap of 2 over 5 turns => 2 rotations"
assert sessions[-1]["metadata"].get("hermes.session.segment_reason") == "max_turns"
def test_zero_cap_means_unlimited(self, coordinator, monkeypatch):
_set_segments(monkeypatch, max_turns=0)
fake = _FakeRelay()
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
for i in range(4):
_run_turn(coordinator, lease, f"t{i}")
assert len(_session_pushes(fake)) == 1
class TestRotationSafety:
def test_never_rotates_mid_turn(self, coordinator, monkeypatch):
_set_segments(monkeypatch, on_compaction=True)
fake = _FakeRelay()
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task1")
# Compaction lands while the turn is LIVE.
coordinator.notify_session_compacted(
profile_key=runtime.profile_key, session_id="sess-1"
)
assert len(_session_pushes(fake)) == 1, "no rotation while a turn is live"
coordinator.end_turn(turn, outcome="success")
assert len(_session_pushes(fake)) == 1, "end_turn does not rotate either"
# The NEXT turn consumes the pending rotation.
turn2 = coordinator.begin_turn(lease, turn_id="t2", task_id="task2")
assert len(_session_pushes(fake)) == 2
coordinator.end_turn(turn2, outcome="success")
def test_wedged_rotation_is_bounded_and_agent_continues(
self, coordinator, monkeypatch
):
_set_segments(monkeypatch, on_compaction=True)
wedge = threading.Event() # never set until teardown
fake = _FakeRelay(wedge_pop=wedge)
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
coordinator.notify_session_compacted(
profile_key=runtime.profile_key, session_id="sess-1"
)
result: list[Any] = []
def _begin():
result.append(
coordinator.begin_turn(lease, turn_id="t1", task_id="task1")
)
worker = threading.Thread(target=_begin, daemon=True)
worker.start()
worker.join(5.0)
assert not worker.is_alive(), (
"begin_turn must return even when the rotation pop wedges — "
"a wedged pipeline costs one segment span, never the agent"
)
turn = result[0]
coordinator.end_turn(turn, outcome="success")
def test_subagent_children_parent_to_new_segment_after_rotation(
self, coordinator, monkeypatch
):
_set_segments(monkeypatch, on_compaction=True)
fake = _FakeRelay()
runtime = _make_runtime(fake)
lease = _acquire(coordinator, runtime)
coordinator.notify_session_compacted(
profile_key=runtime.profile_key, session_id="sess-1"
)
_run_turn(coordinator, lease, "t1") # consumes rotation
new_handle = lease.session.handle
child = runtime.register_subagent(
{"parent_session_id": "sess-1", "child_session_id": "child-1"}
)
assert child is not None
child_push = [
p
for p in fake.scope.pushes
if p["name"] == relay_runtime.SESSION_SCOPE
and p["parent"] is not None
][-1]
assert child_push["parent"] is new_handle, (
"post-rotation children must parent to the new segment handle"
)