19527db731
* 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.
88 lines
3.7 KiB
Python
88 lines
3.7 KiB
Python
"""Regression test for #48031 — /model switch lost after session auto-reset.
|
|
|
|
When `/model X` is the FIRST message after an idle/daily/suspended auto-reset,
|
|
it stores a session model override but the `was_auto_reset` flag is left True
|
|
(the slash-command path doesn't pass through the message handler that consumes
|
|
it). On the NEXT regular message, the auto-reset cleanup block in
|
|
`_handle_message_with_agent` pops the freshly-stored override BEFORE the flag
|
|
is consumed, so the switch is silently lost and resolution falls back to the
|
|
config default — while the session DB still shows the switched model (a
|
|
two-sources-of-truth divergence).
|
|
|
|
The fix consumes `was_auto_reset` at two sites:
|
|
1. the cleanup block in gateway/run.py captures it into a local and sets the
|
|
attribute False immediately (so it can't re-fire next message);
|
|
2. the slash-command model path in gateway/slash_commands.py consumes it
|
|
before storing the override (so a /model-first-after-reset isn't wiped).
|
|
|
|
These are AST invariants — load-bearing pins that fail if either consume is
|
|
removed (mirrors test_35809_auto_reset_clean_context.py's approach).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import ast
|
|
import inspect
|
|
|
|
from gateway import run as gateway_run
|
|
from gateway import slash_commands as gateway_slash
|
|
|
|
|
|
def _assigns_false(node: ast.AST, attr: str) -> bool:
|
|
"""True if `node` contains an assignment `<something>.<attr> = False`."""
|
|
for sub in ast.walk(node):
|
|
if isinstance(sub, ast.Assign):
|
|
for tgt in sub.targets:
|
|
if (
|
|
isinstance(tgt, ast.Attribute)
|
|
and tgt.attr == attr
|
|
and isinstance(sub.value, ast.Constant)
|
|
and sub.value.value is False
|
|
):
|
|
return True
|
|
return False
|
|
|
|
|
|
def test_run_consumes_was_auto_reset_in_cleanup_block():
|
|
"""The auto-reset cleanup block in gateway/run.py must set
|
|
`session_entry.was_auto_reset = False` so the cleanup (which pops the
|
|
session model/reasoning overrides) cannot re-fire on the next message and
|
|
wipe an override stored between turns (#48031)."""
|
|
tree = ast.parse(inspect.getsource(gateway_run))
|
|
|
|
# Find the cleanup branch: an `if <flag>:` block that clears the
|
|
# conversation scope (post-funnel: one _clear_conversation_scope call
|
|
# replaced the inline override pops) AND clears the flag. We assert at
|
|
# least one such block sets was_auto_reset False.
|
|
found = False
|
|
for node in ast.walk(tree):
|
|
if not isinstance(node, ast.If):
|
|
continue
|
|
calls = {
|
|
n.func.attr
|
|
for n in ast.walk(node)
|
|
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
|
|
}
|
|
# The cleanup block routes through the conversation-scope funnel —
|
|
# fingerprint of the transient-state cleanup.
|
|
if "_clear_conversation_scope" in calls and _assigns_false(node, "was_auto_reset"):
|
|
found = True
|
|
break
|
|
assert found, (
|
|
"gateway/run.py auto-reset cleanup block must consume "
|
|
"`was_auto_reset` (set it False) so it can't re-fire and wipe a "
|
|
"model override stored between turns (#48031)."
|
|
)
|
|
|
|
|
|
def test_slash_command_model_path_consumes_was_auto_reset():
|
|
"""The slash-command model path in gateway/slash_commands.py must consume
|
|
`was_auto_reset` before storing the new model override, so a
|
|
/model-first-after-auto-reset isn't wiped by the next message's cleanup
|
|
(#48031)."""
|
|
src = inspect.getsource(gateway_slash)
|
|
tree = ast.parse(src)
|
|
assert _assigns_false(tree, "was_auto_reset"), (
|
|
"gateway/slash_commands.py model path must set "
|
|
"`was_auto_reset = False` before storing the model override (#48031)."
|
|
)
|