Skip to content

The agent that grows with you

fix(gateway): persist internal prompt pins

JoaoMarcos440ba9e1b7f0e4
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index e186721223c..60d11de00db 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -618,6 +618,83 @@ 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:
+ """Restore durable prompt pins lazily for the first internal turn after a gateway restart."""
+ if not session_key:
+ return
+ state = self._session_state(session_key)
+ if state.conversation.ephemeral_pin is not None and state.conversation.channel_pin is not None:
+ return
+ store = getattr(self, "session_store", None)
+ getter = getattr(store, "get_prompt_pin", None)
+ if not callable(getter):
+ return
+ try:
+ persisted = getter(session_key)
+ except Exception:
+ logger.debug("Failed to read persisted prompt pin for %s", session_key, exc_info=True)
+ return
+ if not isinstance(persisted, dict):
+ return
+ context_key, context_prompt = persisted.get("context_key"), persisted.get("context_prompt")
+ channel_prompt, parent_chat_id = persisted.get("channel_prompt"), persisted.get("parent_chat_id")
+ if isinstance(context_key, str) and context_key and isinstance(context_prompt, str):
+ if state.conversation.ephemeral_pin is None:
+ state.conversation.ephemeral_pin = (context_key, context_prompt)
+ if (
+ (channel_prompt is None or isinstance(channel_prompt, str))
+ and (parent_chat_id is None or isinstance(parent_chat_id, str))
+ and state.conversation.channel_pin is None
+ ):
+ state.conversation.channel_pin = (channel_prompt, parent_chat_id)
+
+ def _prompt_pin_snapshot(self, session_key: Optional[str]) -> Optional[Dict[str, Any]]:
+ """Current coherent pair of context/channel pins, ready for durable storage."""
+ state = self._peek_session_state(session_key) if session_key else None
+ if state is None:
+ return None
+ ephemeral_pin, channel_pin = state.conversation.ephemeral_pin, state.conversation.channel_pin
+ if not (
+ isinstance(ephemeral_pin, tuple) and len(ephemeral_pin) == 2
+ and isinstance(ephemeral_pin[0], str) and isinstance(ephemeral_pin[1], str)
+ and isinstance(channel_pin, tuple) and len(channel_pin) == 2
+ ):
+ return None
+ channel_prompt, parent_chat_id = channel_pin
+ if channel_prompt is not None and not isinstance(channel_prompt, str):
+ return None
+ if parent_chat_id is not None and not isinstance(parent_chat_id, str):
+ return None
+ return {
+ "version": 1,
+ "context_key": ephemeral_pin[0],
+ "context_prompt": ephemeral_pin[1],
+ "channel_prompt": channel_prompt,
+ "parent_chat_id": parent_chat_id,
+ }
+
+ async def _persist_prompt_pins(
+ self, session_key: Optional[str], expected_session_id: Optional[str],
+ ) -> None:
+ """Persist changed human-turn pins before agent execution; failures stay cache-only."""
+ snapshot = self._prompt_pin_snapshot(session_key)
+ if snapshot is None or not session_key:
+ return
+ store = getattr(self, "session_store", None)
+ getter = getattr(store, "get_prompt_pin", None)
+ try:
+ if callable(getter) and getter(session_key) == snapshot:
+ return
+ except Exception:
+ logger.debug("Failed to compare persisted prompt pin for %s", session_key, exc_info=True)
+ try:
+ await self.async_session_store.set_prompt_pin(
+ session_key, snapshot, expected_session_id=expected_session_id,
+ )
+ except Exception:
+ # Durability protects cache continuity; a store outage must not block the user turn.
+ logger.debug("Failed to persist prompt pin for %s", session_key, exc_info=True)
+
def _pinned_session_context_prompt(
self, context, redact_pii: bool, session_key: Optional[str], *, internal: bool = False,
) -> str:
@@ -631,6 +708,10 @@ class GatewayAgentCacheMixin:
it reuses an existing pin verbatim; with no pin yet it renders and pins as usual."""
_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)
+ _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:
return _eph_pin[1]
_eph_key = self._ephemeral_change_key(context, redact_pii)
@@ -658,6 +739,10 @@ class GatewayAgentCacheMixin:
return channel_prompt, source
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)
+ state = self._peek_session_state(session_key)
+ pin = state.conversation.channel_pin if state else None
if pin is None:
return channel_prompt, source
pinned_prompt, pinned_parent = pin
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 07331241108..a12c28ac1eb 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2199,6 +2199,10 @@ class GatewayTurnMixin:
_turn_channel_prompt, _turn_source = self._pinned_channel_inputs(
session_key, event.channel_prompt, source, internal=event.internal,
)
+ if not event.internal:
+ # Persist the coherent context+channel pair before execution: a crash during the
+ # human turn may be followed by an internal startup-resume on the next process.
+ await self._persist_prompt_pins(session_key, _run_start_session_id)
agent_result = await self._run_agent(
message=message_text, context_prompt=prepared.context_prompt, history=history, source=_turn_source,
session_id=_run_start_session_id, session_key=session_key,
diff --git a/gateway/session.py b/gateway/session.py
index 06cfa4ae333..cd0a096d7ae 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -477,6 +477,32 @@ def sanitize_model_override(override: Optional[Dict[str, Any]]) -> Optional[Dict
return cleaned or None
+_PROMPT_PIN_VERSION = 1
+
+
+def sanitize_prompt_pin(pin: Any) -> Optional[Dict[str, Any]]:
+ """Validated durable snapshot of the exact ephemeral inputs reused by internal turns."""
+ if not isinstance(pin, dict) or pin.get("version") != _PROMPT_PIN_VERSION:
+ return None
+ context_key = pin.get("context_key")
+ context_prompt = pin.get("context_prompt")
+ channel_prompt = pin.get("channel_prompt")
+ parent_chat_id = pin.get("parent_chat_id")
+ if not isinstance(context_key, str) or not context_key or not isinstance(context_prompt, str):
+ return None
+ if channel_prompt is not None and not isinstance(channel_prompt, str):
+ return None
+ if parent_chat_id is not None and not isinstance(parent_chat_id, str):
+ return None
+ return {
+ "version": _PROMPT_PIN_VERSION,
+ "context_key": context_key,
+ "context_prompt": context_prompt,
+ "channel_prompt": channel_prompt,
+ "parent_chat_id": parent_chat_id,
+ }
+
+
@dataclass
class SessionEntry:
"""Routing-index entry: maps a session key to its current session ID and metadata."""
@@ -533,6 +559,9 @@ class SessionEntry:
# "default" spelled out). The key namespace only says where the turn RUNS; after a restart this is
# what says which bot may deliver to it. None = unknown (row predates the field, or standalone).
transport_profile: Optional[str] = None
+ # Exact session-context/channel inputs from the last human turn. Append-only dataclass field so
+ # older positional construction of transport_profile keeps its meaning.
+ prompt_pin: Optional[Dict[str, Any]] = None
# Fields (de)serialized verbatim, in wire order (``from_dict`` reads them with
# ``data.get(name, <dataclass default>)``), split around the three ISO-datetime/token keys.
@@ -562,6 +591,9 @@ class SessionEntry:
if self.model_override:
# Defence-in-depth against an unsanitized dict stored directly.
result["model_override"] = sanitize_model_override(self.model_override)
+ if self.prompt_pin:
+ # Same defence-in-depth: routing JSON must never preserve malformed pin state.
+ result["prompt_pin"] = sanitize_prompt_pin(self.prompt_pin)
if self.transport_profile:
result["transport_profile"] = self.transport_profile
if self.origin:
@@ -604,6 +636,7 @@ class SessionEntry:
last_resume_marked_at=_parse_iso(data.get("last_resume_marked_at")),
active_turn_token=token, active_turn_started_at=started_at,
model_override=sanitize_model_override(data.get("model_override")),
+ prompt_pin=sanitize_prompt_pin(data.get("prompt_pin")),
transport_profile=transport_profile if isinstance(transport_profile, str) and transport_profile else None,
**plain,
)
@@ -1110,6 +1143,42 @@ class SessionStore(
entry = self._entry_locked(session_key)
return dict(entry.model_override) if entry and entry.model_override else None
+ def set_prompt_pin(
+ self, session_key: str, pin: Optional[Dict[str, Any]], *,
+ expected_session_id: Optional[str] = None,
+ ) -> bool:
+ """Persist effective prompt inputs without letting a stale turn cross a boundary.
+
+ The candidate is durable before the in-memory entry is published. The expected session id
+ is the turn's launch identity: a concurrent reset or resume makes this a no-op instead of
+ writing the old conversation's system bytes onto the new one.
+ """
+ cleaned = sanitize_prompt_pin(pin)
+ if pin is not None and cleaned is None:
+ return False
+ with self._lock:
+ entry = self._entry_locked(session_key)
+ if entry is None:
+ return False
+ if expected_session_id is not None and entry.session_id != expected_session_id:
+ return False
+ if entry.prompt_pin == cleaned:
+ return True
+ candidate = entry.to_dict()
+ if cleaned is None:
+ candidate.pop("prompt_pin", None)
+ else:
+ candidate["prompt_pin"] = cleaned
+ self._save_entry(session_key, entry_data=candidate, lock_held=True)
+ 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."""
+ with self._lock:
+ entry = self._entry_locked(session_key)
+ return dict(entry.prompt_pin) if entry and 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."""
with self._lock:
@@ -1224,6 +1293,7 @@ class SessionStore(
# restart-resume freshness gate (#85709).
def switch_session(
self, session_key: str, target_session_id: str, *, expected_session_id: Optional[str] = None,
+ preserve_prompt_pin: bool = True,
) -> Optional[SessionEntry]:
"""Point a session key at an existing session ID (``/resume``): ends the current row and
reopens the target so resume matches the CLI.
@@ -1231,6 +1301,8 @@ class SessionStore(
``expected_session_id`` makes the repoint a compare-and-swap: ``None`` is returned when
the key no longer points at that session, so a caller that resolved against a snapshot
across an await (async-delegation re-pin) cannot overwrite a concurrent /new or /resume.
+ Prompt pins follow non-boundary repoints by default; /resume opts out explicitly because it
+ starts a different conversation on the same routing key.
"""
with self._lock:
old_entry = self._entry_locked(session_key)
@@ -1247,6 +1319,10 @@ class SessionStore(
new_entry = self._replace_route_locked(
session_key, old_entry, target_session_id, _now(),
display_name=old_entry.display_name, model_override=old_entry.model_override,
+ prompt_pin=(
+ dict(old_entry.prompt_pin)
+ if preserve_prompt_pin and old_entry.prompt_pin is not None else None
+ ),
)
if self._db_for_key(session_key) and old_entry.session_id:
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index 23c856091fd..1975312bc69 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -893,7 +893,9 @@ class GatewaySessionCommandsMixin:
if current_entry.session_id == target_id:
return t("gateway.resume.already_on", name=name)
self._release_running_agent_state(session_key)
- new_entry = await self.async_session_store.switch_session(session_key, target_id)
+ new_entry = await self.async_session_store.switch_session(
+ session_key, target_id, preserve_prompt_pin=False,
+ )
if not new_entry:
return t("gateway.resume.switch_failed")
# Conversation boundary: all conversation-scoped state + security state in one funnel call.
diff --git a/tests/gateway/test_internal_event_pin_wiring.py b/tests/gateway/test_internal_event_pin_wiring.py
index a7bde68c055..9cdaae76d9a 100644
--- a/tests/gateway/test_internal_event_pin_wiring.py
+++ b/tests/gateway/test_internal_event_pin_wiring.py
@@ -47,7 +47,9 @@ def _wake_source() -> SessionSource:
return SessionSource(**_ORIGIN)
-def _make_runner(monkeypatch, config: GatewayConfig | None = None):
+def _make_runner(
+ monkeypatch, config: GatewayConfig | None = None, *, durable_prompt_pin: dict | None = None,
+):
import agent.model_metadata as mm
import gateway.run as gr
import gateway.session as gs
@@ -90,6 +92,18 @@ def _make_runner(monkeypatch, config: GatewayConfig | None = None):
)
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):
+ value = durable_prompt_pin.get("value")
+ return dict(value) if isinstance(value, dict) else None
+
+ def _set_prompt_pin(_key, value, *, expected_session_id=None):
+ assert expected_session_id == "sess-wiring"
+ durable_prompt_pin["value"] = dict(value) if isinstance(value, dict) else None
+ return True
+
+ store.get_prompt_pin.side_effect = _get_prompt_pin
+ store.set_prompt_pin.side_effect = _set_prompt_pin
r.session_store = store
return r
@@ -303,3 +317,93 @@ async def test_event_backed_followup_overrides_inherited_channel_prompt(monkeypa
assert len(calls) == 1
assert calls[0]["channel_prompt"] == "Queued event prompt.", "event prompt must win over the inherited one"
+
+
+async def test_first_internal_event_after_restart_rehydrates_durable_prompt_pins(monkeypatch):
+ config = GatewayConfig()
+ config.platforms[Platform.DISCORD] = PlatformConfig(
+ enabled=True,
+ channel_overrides={PARENT_ID: ChannelOverride(system_prompt="Parent persona.")},
+ )
+ durable: dict = {}
+
+ before = _make_runner(monkeypatch, config, durable_prompt_pin=durable)
+ calls_before: list[dict] = []
+ _capture(before, calls_before)
+ await _drive(before, ((False, _human_thread_source()),), channel_prompt="Channel hint.")
+
+ persisted = durable.get("value")
+ assert isinstance(persisted, dict)
+ assert persisted["channel_prompt"] == "Channel hint."
+ assert persisted["parent_chat_id"] == PARENT_ID
+
+ # A brand-new runner has no ConversationState. The first post-restart event is internal.
+ after = _make_runner(monkeypatch, config, durable_prompt_pin=durable)
+ calls_after: list[dict] = []
+ _capture(after, calls_after)
+ await _drive(
+ after,
+ ((True, _wake_thread_source()), (False, _human_thread_source())),
+ channel_prompt="Channel hint.",
+ )
+
+ human, first_internal, next_human = calls_before[0], calls_after[0], calls_after[1]
+ assert after._peek_session_state(KEY).conversation.ephemeral_pin is not None
+ assert after._peek_session_state(KEY).conversation.channel_pin is not None
+ assert first_internal["context_prompt"] == human["context_prompt"] == next_human["context_prompt"]
+ assert first_internal["channel_prompt"] == human["channel_prompt"] == next_human["channel_prompt"]
+ assert (
+ first_internal["source"].parent_chat_id
+ == human["source"].parent_chat_id
+ == next_human["source"].parent_chat_id
+ )
+ assert _effective_ephemeral(after, first_internal) == _effective_ephemeral(before, human)
+
+
+async def test_human_first_after_restart_ignores_stale_durable_prompt_pin(monkeypatch):
+ durable = {
+ "value": {
+ "version": 1,
+ "context_key": "stale-key",
+ "context_prompt": "STALE CONTEXT",
+ "channel_prompt": "Stale channel prompt.",
+ "parent_chat_id": "stale-parent",
+ }
+ }
+ config = GatewayConfig()
+ config.platforms[Platform.DISCORD] = PlatformConfig(
+ enabled=True,
+ channel_overrides={PARENT_ID: ChannelOverride(system_prompt="Parent persona.")},
+ )
+ runner = _make_runner(monkeypatch, config, durable_prompt_pin=durable)
+ calls: list[dict] = []
+ _capture(runner, calls)
+
+ await _drive(runner, ((False, _human_thread_source()),), channel_prompt="Fresh channel prompt.")
+
+ assert len(calls) == 1
+ assert calls[0]["context_prompt"] != "STALE CONTEXT"
+ assert calls[0]["channel_prompt"] == "Fresh channel prompt."
+ assert calls[0]["source"].parent_chat_id == PARENT_ID
+ assert durable["value"]["context_prompt"] == calls[0]["context_prompt"]
+ assert durable["value"]["channel_prompt"] == "Fresh channel prompt."
+ assert durable["value"]["parent_chat_id"] == PARENT_ID
+
+
+async def test_unchanged_human_prompt_pin_does_not_rewrite_durable_store(monkeypatch):
+ durable: dict = {}
+ runner = _make_runner(monkeypatch, durable_prompt_pin=durable)
+ calls: list[dict] = []
+ _capture(runner, calls)
+
+ await _drive(
+ runner,
+ ((False, _human_source()), (False, _human_source())),
+ channel_prompt="Stable channel prompt.",
+ )
+
+ assert len(calls) == 2
+ assert runner.session_store.set_prompt_pin.call_count == 1
diff --git a/tests/gateway/test_resume_command.py b/tests/gateway/test_resume_command.py
index a114eae376a..8d6e0b006e3 100644
--- a/tests/gateway/test_resume_command.py
+++ b/tests/gateway/test_resume_command.py
@@ -127,6 +127,7 @@ class TestHandleResumeCommand:
}
await runner._handle_resume_command(event)
+ assert runner.session_store.switch_session.call_args.kwargs["preserve_prompt_pin"] is False
# The resumed chat's override + pending note are cleared...
assert key not in runner._session_model_overrides
assert key not in runner._pending_model_notes
diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.py
index 758a78f94f6..07441bc206c 100644
--- a/tests/gateway/test_session.py
+++ b/tests/gateway/test_session.py
@@ -1520,6 +1520,68 @@ class TestGatewayRoutingTable:
assert rehydrated.model_override == {"model": "test-model"}
restarted._db.close()
+ def test_prompt_pin_survives_restart_and_stale_writer_cannot_cross_reset(self, tmp_path):
+ config = GatewayConfig()
+ store = SessionStore(sessions_dir=tmp_path, config=config)
+ entry = store.get_or_create_session(self._source())
+ pin = {
+ "version": 1,
+ "context_key": "ctx-key",
+ "context_prompt": "exact session context",
+ "channel_prompt": "Channel hint.",
+ "parent_chat_id": "parent-1",
+ }
+ assert store.set_prompt_pin(
+ entry.session_key, pin, expected_session_id=entry.session_id,
+ )
+ assert store.get_prompt_pin(entry.session_key) == pin
+ assert not store.set_prompt_pin(
+ entry.session_key, {"version": 1}, expected_session_id=entry.session_id,
+ )
+ assert store.get_prompt_pin(entry.session_key) == pin
+
+ # Prove the primary state.db routing index carries the pin by removing the JSON mirror.
+ (tmp_path / "sessions.json").unlink()
+ old_session_id = entry.session_id
+ store._db.close()
+
+ restarted = SessionStore(sessions_dir=tmp_path, config=config)
+ assert restarted.get_prompt_pin(entry.session_key) == pin
+
+ fresh = restarted.reset_session(entry.session_key)
+ assert fresh is not None and fresh.session_id != old_session_id
+ assert restarted.get_prompt_pin(entry.session_key) is None
+
+ stale = dict(pin, context_prompt="stale old-conversation bytes")
+ assert not restarted.set_prompt_pin(
+ entry.session_key, stale, expected_session_id=old_session_id,
+ )
+ assert restarted.get_prompt_pin(entry.session_key) is None
+ restarted._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)
+ entry = store.get_or_create_session(self._source())
+ pin = {
+ "version": 1,
+ "context_key": "ctx-key",
+ "context_prompt": "exact session context",
+ "channel_prompt": None,
+ "parent_chat_id": None,
+ }
+ assert store.set_prompt_pin(entry.session_key, pin, expected_session_id=entry.session_id)
+
+ moved = store.switch_session(entry.session_key, "internal-repoint")
+ assert moved is not None and moved.prompt_pin == pin
+
+ boundary = store.switch_session(
+ entry.session_key, "resume-target", preserve_prompt_pin=False,
+ )
+ assert boundary is not None and boundary.prompt_pin is None
+ assert store.get_prompt_pin(entry.session_key) is None
+ store._db.close()
+
def test_write_sessions_json_false_stops_producing_file(self, tmp_path):
config = GatewayConfig(write_sessions_json=False)
store = SessionStore(sessions_dir=tmp_path, config=config)