Skip to content

The agent that grows with you

fix(gateway): fence prompt pin rehydration

JoaoMarcos443275dcead3ab
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index 60d11de00db..8d5852ccdc8 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -618,7 +618,9 @@ class GatewayAgentCacheMixin:
return None
return f"[Voice channel now: {vc_now or 'not connected to a voice channel'}]"
- def _rehydrate_prompt_pins(self, session_key: Optional[str]) -> None:
+ def _rehydrate_prompt_pins(
+ self, session_key: Optional[str], expected_session_id: Optional[str] = None,
+ ) -> None:
"""Restore durable prompt pins lazily for the first internal turn after a gateway restart."""
if not session_key:
return
@@ -630,7 +632,7 @@ class GatewayAgentCacheMixin:
if not callable(getter):
return
try:
- persisted = getter(session_key)
+ persisted = getter(session_key, expected_session_id=expected_session_id)
except Exception:
logger.debug("Failed to read persisted prompt pin for %s", session_key, exc_info=True)
return
@@ -697,6 +699,7 @@ class GatewayAgentCacheMixin:
def _pinned_session_context_prompt(
self, context, redact_pii: bool, session_key: Optional[str], *, internal: bool = False,
+ expected_session_id: Optional[str] = None,
) -> str:
"""Session-context prompt pinned per session: key hit → pinned bytes reused VERBATIM (immune
to renderer nondeterminism); key miss → re-render and re-pin (rename, topic edit, /sethome).
@@ -709,7 +712,7 @@ class GatewayAgentCacheMixin:
_pin_state = self._peek_session_state(session_key) if session_key else None
_eph_pin = _pin_state.conversation.ephemeral_pin if _pin_state else None
if internal and _eph_pin is None:
- self._rehydrate_prompt_pins(session_key)
+ self._rehydrate_prompt_pins(session_key, expected_session_id)
_pin_state = self._peek_session_state(session_key) if session_key else None
_eph_pin = _pin_state.conversation.ephemeral_pin if _pin_state else None
if internal and _eph_pin is not None:
@@ -724,6 +727,7 @@ class GatewayAgentCacheMixin:
def _pinned_channel_inputs(
self, session_key: Optional[str], channel_prompt: Optional[str], source: SessionSource, *, internal: bool,
+ expected_session_id: Optional[str] = None,
):
"""``(channel_prompt, source)`` for this turn's agent run.
@@ -740,7 +744,7 @@ class GatewayAgentCacheMixin:
state = self._peek_session_state(session_key)
pin = state.conversation.channel_pin if state else None
if pin is None:
- self._rehydrate_prompt_pins(session_key)
+ self._rehydrate_prompt_pins(session_key, expected_session_id)
state = self._peek_session_state(session_key)
pin = state.conversation.channel_pin if state else None
if pin is None:
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index a12c28ac1eb..9bd03d813f4 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2077,6 +2077,7 @@ class GatewayTurnMixin:
# the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.
context_prompt = self._pinned_session_context_prompt(
context, _redact_pii, session_key, internal=event.internal,
+ expected_session_id=session_entry.session_id,
)
# Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt
@@ -2198,6 +2199,7 @@ class GatewayTurnMixin:
# Internal events reuse the last human turn's channel inputs (see _pinned_channel_inputs).
_turn_channel_prompt, _turn_source = self._pinned_channel_inputs(
session_key, event.channel_prompt, source, internal=event.internal,
+ expected_session_id=_run_start_session_id,
)
if not event.internal:
# Persist the coherent context+channel pair before execution: a crash during the
diff --git a/gateway/session.py b/gateway/session.py
index cd0a096d7ae..10d69881a3e 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -1173,11 +1173,17 @@ class SessionStore(
entry.prompt_pin = dict(cleaned) if cleaned is not None else None
return True
- def get_prompt_pin(self, session_key: str) -> Optional[Dict[str, Any]]:
- """Return a defensive copy of the persisted effective prompt-pin snapshot."""
+ def get_prompt_pin(
+ self, session_key: str, *, expected_session_id: Optional[str] = None,
+ ) -> Optional[Dict[str, Any]]:
+ """Return the prompt pin only while the route still owns the caller's session."""
with self._lock:
entry = self._entry_locked(session_key)
- return dict(entry.prompt_pin) if entry and entry.prompt_pin else None
+ if entry is None:
+ return None
+ if expected_session_id is not None and entry.session_id != expected_session_id:
+ return None
+ return dict(entry.prompt_pin) if entry.prompt_pin else None
def reset_session(self, session_key: str, display_name: Optional[str] = None) -> Optional[SessionEntry]:
"""Force reset a session, creating a new session ID."""
diff --git a/tests/gateway/test_internal_event_pin_wiring.py b/tests/gateway/test_internal_event_pin_wiring.py
index 9cdaae76d9a..ceb6b856a00 100644
--- a/tests/gateway/test_internal_event_pin_wiring.py
+++ b/tests/gateway/test_internal_event_pin_wiring.py
@@ -93,7 +93,9 @@ def _make_runner(
store.load_transcript.return_value = []
store.has_platform_message_id.return_value = False
if durable_prompt_pin is not None:
- def _get_prompt_pin(_key):
+ def _get_prompt_pin(_key, *, expected_session_id=None):
+ if expected_session_id is not None:
+ assert expected_session_id == "sess-wiring"
value = durable_prompt_pin.get("value")
return dict(value) if isinstance(value, dict) else None
diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.py
index 07441bc206c..ba157671b8c 100644
--- a/tests/gateway/test_session.py
+++ b/tests/gateway/test_session.py
@@ -1559,6 +1559,36 @@ class TestGatewayRoutingTable:
assert restarted.get_prompt_pin(entry.session_key) is None
restarted._db.close()
+ def test_prompt_pin_read_is_fenced_to_the_resolved_session(self, tmp_path):
+ config = GatewayConfig()
+ store = SessionStore(sessions_dir=tmp_path, config=config)
+ entry = store.get_or_create_session(self._source())
+ old_session_id = entry.session_id
+ old_pin = {
+ "version": 1,
+ "context_key": "old-key",
+ "context_prompt": "old context",
+ "channel_prompt": "Old channel.",
+ "parent_chat_id": "old-parent",
+ }
+ assert store.set_prompt_pin(entry.session_key, old_pin, expected_session_id=old_session_id)
+
+ fresh = store.reset_session(entry.session_key)
+ assert fresh is not None and fresh.session_id != old_session_id
+ new_pin = dict(old_pin, context_key="new-key", context_prompt="new context")
+ assert store.set_prompt_pin(
+ entry.session_key, new_pin, expected_session_id=fresh.session_id,
+ )
+
+ # A turn that resolved before the boundary must not consume the new conversation's pin.
+ assert store.get_prompt_pin(
+ entry.session_key, expected_session_id=old_session_id,
+ ) is None
+ assert store.get_prompt_pin(
+ entry.session_key, expected_session_id=fresh.session_id,
+ ) == new_pin
+ store._db.close()
+
def test_switch_session_preserves_prompt_pin_unless_boundary_requests_clear(self, tmp_path):
config = GatewayConfig()
store = SessionStore(sessions_dir=tmp_path, config=config)