hermes-agent/tests/gateway/test_conversation_scope_funnel.py
Teknium 19527db731
fix(gateway): per-session turn lease + conversation-scope funnel (#64934) (#67401)
* fix(gateway): serialize concurrent turns per resolved session_id with a turn lease

Closes the serialization half of #64934. The busy guards are keyed by
routing key, but the durable transcript is owned by session_id — and
switch_session() makes the key→id mapping many-to-one (/resume from a
second chat/topic, CLI-continuity rebinding, async-delegation pinning,
topic-binding tip-walks). Two routing keys mapped to one session_id ran
concurrent turns on two different agent objects, invisible to every
per-key guard: flushes persisted in completion order, the identity-marker
dedup swallowed rows, and the second turn ran on a stale history base —
leaving a permanent user;user alternation wedge.

The fix: an asyncio lease keyed by RESOLVED session_id (gateway/turn_lease.py),
acquired in _handle_message_with_agent after session resolution is final
(post switch_session/tip-walk), immediately before the transcript load, and
released in _handle_message's finally on every exit path. Tokens are granted
per (routing key, run generation) so a stale unwind can never release a newer
turn's lease (#28686 ownership lesson). Same-key messages never reach the
acquisition point mid-turn (both routing-key guards hold them), so the lock
is uncontended outside the alias-key route — where the second turn now waits
for the first turn's flush and logs one WARNING naming the session and both
routing keys (pairs with the #67371 tripwire).

Fail-open: a stuck holder degrades to today's unserialized behavior with a
loud ERROR after agent.gateway_timeout — never a wedged session; a degraded
token holds nothing and can't steal the lease. Registry is size-capped and
never evicts a live lease. Persist-disabled review forks never dispatch
through _handle_message, so they cannot contend.

Known limits (tracked on #64934): CLI-continuity cross-process pairs need a
DB-level lease; mid-turn compression rotation leaves a small alias window
for a follow-up at the binding-sync sites.

Validation: 8 behavior tests (alias-key wait + flush order, no cross-session
contention, generation-scoped idempotent release, timeout fail-open without
lease theft, bounded registry, bare-runner-safe release wiring) + E2E against
a real SessionStore reproducing the issue's switch_session alias route —
strict alternation and arrival order preserved.

* refactor(gateway): conversation-scope funnel + mid-turn lease rebind

Completes the #64934 system beyond the point fix. Two structural changes,
both eliminating whole bug classes rather than instances:

1. _clear_conversation_scope — THE single conversation-boundary funnel.
   /new, /resume, auto-reset, expiry finalization, and the
   compression-exhausted reset each carried a hand-copied pop-list of the
   per-session dicts, and the lists drifted every time a new dict was
   added (#48031, #58403, #10702, #35809 were all 'boundary X forgot
   dict Y' bugs). All five sites now make one funnel call driven by the
   _CONVERSATION_SCOPED_STATE registry; adding a new conversation-scoped
   dict means adding one name to the registry, and every boundary picks
   it up automatically. Scope rules documented at the registry: turn-scoped
   state, the monotonic generation counter, and the agent cache are
   deliberately excluded (different lifecycles).

2. SessionTurnLeaseRegistry.rebind — the held turn lease now FOLLOWS
   mid-turn compression rotation. Both rotation sites (session-hygiene
   pre-compression, agent-result session_id swap) alias the same
   _SessionLease object under the new id, so an alias routing key
   resolving the fresh child (topic tip-walk) still serializes against
   the in-flight turn. Closes the rotation-alias window flagged as a
   known limit on #64934. Ownership-checked like release; when the
   target id already has a live lease the rebind fails open with a loud
   WARNING (never a mid-turn deadlock).

Tests: 3 new rebind behavior tests + 5 funnel behavior tests (including
a real-setter drift guard); the two AST change-detector pins in
test_10710/test_48031 were re-pointed at the funnel and the #58403 pin
converted to a behavioral test. E2E: rotation-alias scenario against a
real SessionStore + SessionDB — turn B on the fresh child waits behind
the rotated holder, sees its rows, alternation intact.
2026-07-19 03:49:29 -07:00

78 lines
3.4 KiB
Python

"""Behavior tests for _clear_conversation_scope — the single conversation-
boundary funnel (#64934 follow-up).
Boundaries (/new, /resume, auto-reset, expiry finalization,
compression-exhausted reset) used to each carry a hand-copied pop-list of the
per-session dicts, and the lists drifted whenever a new dict was added
(#48031, #58403, #10702, #35809 were all "boundary X forgot dict Y" bugs).
The funnel clears every dict registered in _CONVERSATION_SCOPED_STATE plus
the boundary security state, in one call.
"""
from gateway.run import _CONVERSATION_SCOPED_STATE, GatewayRunner
KEY = "agent:main:telegram:dm:777"
OTHER = "agent:main:discord:dm:888"
def _bare_runner() -> GatewayRunner:
runner = object.__new__(GatewayRunner)
for attr in _CONVERSATION_SCOPED_STATE:
setattr(runner, attr, {KEY: object(), OTHER: object()})
# Turn-scoped state that the funnel must NOT touch.
runner._running_agents = {KEY: object()}
runner._running_agents_ts = {KEY: 1.0}
runner._session_run_generation = {KEY: 7}
return runner
def test_funnel_clears_every_registered_dict_for_key_only():
runner = _bare_runner()
runner._clear_conversation_scope(KEY, reason="test")
for attr in _CONVERSATION_SCOPED_STATE:
store = getattr(runner, attr)
assert KEY not in store, f"{attr} not cleared by funnel"
assert OTHER in store, f"{attr} cleared the wrong session"
def test_funnel_leaves_turn_scoped_and_generation_state_alone():
runner = _bare_runner()
runner._clear_conversation_scope(KEY, reason="test")
# Turn-scoped: owned by _release_running_agent_state / dispatch finally.
assert KEY in runner._running_agents
assert KEY in runner._running_agents_ts
# Generation counter is monotonic by design (#28686) — never reset.
assert runner._session_run_generation[KEY] == 7
def test_funnel_is_bare_runner_safe_and_empty_key_noop():
runner = object.__new__(GatewayRunner)
# No dicts initialized at all — must not raise (pitfall #17).
runner._clear_conversation_scope(KEY, reason="test")
runner._clear_conversation_scope("", reason="test")
def test_funnel_clears_state_written_by_real_setters():
"""Behavioral invariant: state written through the runner's real setter
paths is cleared by the funnel. Guards against a registry entry drifting
out of sync with the attribute the setter actually writes (a typo'd
registry name would silently clear nothing and resurrect the
boundary-drift bug class the funnel exists to kill)."""
runner = object.__new__(GatewayRunner)
# Real setter: lazily creates _session_reasoning_overrides.
runner._set_session_reasoning_override(KEY, {"effort": "high"})
assert runner._session_reasoning_overrides.get(KEY) == {"effort": "high"}
runner._clear_conversation_scope(KEY, reason="test")
assert KEY not in runner._session_reasoning_overrides
def test_funnel_also_clears_boundary_security_state():
runner = _bare_runner()
runner._pending_approvals = {KEY: {"cmd": "rm -rf"}, OTHER: {}}
runner._update_prompt_pending = {KEY: True}
runner._pending_skills_reload_notes = {KEY: "note"}
runner._clear_conversation_scope(KEY, reason="test")
assert KEY not in runner._pending_approvals
assert OTHER in runner._pending_approvals
assert KEY not in runner._update_prompt_pending
assert KEY not in runner._pending_skills_reload_notes