Skip to content

The agent that grows with you

fix(gateway): durable prompt pins never outlive their privacy policy

kshitijk4poorf660ba2289be
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index 8d5852ccdc8..f0fda2a3d4d 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -14,7 +14,9 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
from agent.interrupt_compat import _accepts_keyword
from gateway.config import Platform
-from gateway.session import SessionSource, build_session_context_prompt
+from gateway.session import (
+ PROMPT_PIN_VERSION, SessionSource, build_session_context_prompt, sanitize_prompt_pin,
+)
from gateway.run_shutdown import _log_suppressed
from hermes_cli.config import DEFAULT_CONFIG, cfg_get
from hermes_cli.local_runtime.endpoint import LLAMACPP_ALIASES
@@ -618,81 +620,48 @@ 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], 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
- 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
+ def _rehydrate_prompt_pins(self, session_key: str, expected_session_id: Optional[str]):
+ """Adopt the durable pin snapshot when this process holds no pins for *session_key* (a
+ restart). Eviction clears only ``ephemeral_pin`` and keeps ``channel_pin``, so an evicted
+ agent still re-renders instead of reviving the snapshot. Returns the session state."""
+ state = self._peek_session_state(session_key)
+ if state is not None and (
+ state.conversation.ephemeral_pin is not None or state.conversation.channel_pin is not None
+ ):
+ return state
try:
- persisted = getter(session_key, expected_session_id=expected_session_id)
+ pin = sanitize_prompt_pin(
+ self.session_store.get_prompt_pin(session_key, expected_session_id=expected_session_id))
except Exception:
+ # Cache continuity only: a routing-store fault must not fail the turn.
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)
+ return state
+ if pin is None:
+ return state
+ state = self._session_state(session_key)
+ state.conversation.ephemeral_pin = (pin["context_key"], pin["context_prompt"], pin["redact_pii"])
+ state.conversation.channel_pin = (pin["channel_prompt"], pin["parent_chat_id"])
+ return state
- def _prompt_pin_snapshot(self, session_key: Optional[str]) -> Optional[Dict[str, Any]]:
- """Current coherent pair of context/channel pins, ready for durable storage."""
+ async def _persist_prompt_pins(self, session_key: Optional[str], expected_session_id: Optional[str]) -> None:
+ """Persist this conversation's pins before the agent runs; the store no-ops an unchanged
+ snapshot and refuses a session that has moved on."""
state = self._peek_session_state(session_key) if session_key else None
if state is None:
- return None
+ return
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:
+ if ephemeral_pin is None or channel_pin is None:
+ return
+ snapshot = sanitize_prompt_pin({
+ "version": PROMPT_PIN_VERSION, "context_key": ephemeral_pin[0],
+ "context_prompt": ephemeral_pin[1], "redact_pii": ephemeral_pin[2],
+ "channel_prompt": channel_pin[0], "parent_chat_id": channel_pin[1],
+ })
+ if snapshot is None:
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,
- )
+ 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)
@@ -708,13 +677,16 @@ class GatewayAgentCacheMixin:
source rebuilt from the persisted origin, without chat_name/user_name/message_id. Rendering
from it re-keyed the pin, and the next human turn re-keyed it back (A→B→A), rewriting
already-sent system bytes each time. An internal event is never a real metadata change, so
- it reuses an existing pin verbatim; with no pin yet it renders and pins as usual."""
+ it reuses an existing pin verbatim (restored from the session store after a restart); with
+ no pin yet it renders and pins as usual. The pin records the ``privacy.redact_pii`` it was
+ rendered under: bytes from another privacy policy are never reused, even by an internal
+ event."""
_pin_state = self._peek_session_state(session_key) if session_key else None
+ if internal and session_key:
+ _pin_state = self._rehydrate_prompt_pins(session_key, expected_session_id)
_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, 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 _eph_pin is not None and _eph_pin[2] != redact_pii:
+ _eph_pin = None
if internal and _eph_pin is not None:
return _eph_pin[1]
_eph_key = self._ephemeral_change_key(context, redact_pii)
@@ -722,12 +694,11 @@ class GatewayAgentCacheMixin:
return _eph_pin[1]
text = build_session_context_prompt(context, redact_pii=redact_pii)
if session_key:
- self._session_state(session_key).conversation.ephemeral_pin = (_eph_key, text)
+ self._session_state(session_key).conversation.ephemeral_pin = (_eph_key, text, redact_pii)
return text
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.
@@ -735,7 +706,7 @@ class GatewayAgentCacheMixin:
prompt (looked up by chat/thread/``parent_chat_id``). Internal events carry
``channel_prompt=None`` and a source without ``parent_chat_id``, so they dropped both and
toggled the system prompt like the context pin did. Human turns record their inputs;
- internal turns reuse them."""
+ internal turns reuse them (the context pin, resolved first, restores both after a restart)."""
if not session_key:
return channel_prompt, source
if not internal:
@@ -743,10 +714,6 @@ 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, expected_session_id)
- 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 9bd03d813f4..fce45bed818 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2199,7 +2199,6 @@ 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 a44fcb58797..e9f5f4b3ece 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -477,27 +477,34 @@ def sanitize_model_override(override: Optional[Dict[str, Any]]) -> Optional[Dict
return cleaned or None
-_PROMPT_PIN_VERSION = 1
+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:
+ """Validated durable snapshot of the exact ephemeral inputs reused by internal turns.
+
+ ``redact_pii`` is the ``privacy.redact_pii`` the context bytes were rendered under; a pin
+ without it cannot prove which privacy policy produced them and is refused."""
+ 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")
+ redact_pii = pin.get("redact_pii")
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 not isinstance(redact_pii, bool):
+ 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,
+ "version": PROMPT_PIN_VERSION,
"context_key": context_key,
"context_prompt": context_prompt,
+ "redact_pii": redact_pii,
"channel_prompt": channel_prompt,
"parent_chat_id": parent_chat_id,
}
@@ -1145,8 +1152,7 @@ class SessionStore(
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,
+ self, session_key: str, pin: Dict[str, Any], *, expected_session_id: Optional[str] = None,
) -> bool:
"""Persist effective prompt inputs without letting a stale turn cross a boundary.
@@ -1154,24 +1160,19 @@ class SessionStore(
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.
"""
+ from dataclasses import replace
+
cleaned = sanitize_prompt_pin(pin)
- if pin is not None and cleaned is None:
+ if 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:
+ if entry is None or (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
+ if entry.prompt_pin != cleaned:
+ self._save_entry(
+ session_key, entry_data=replace(entry, prompt_pin=cleaned).to_dict(), lock_held=True)
+ entry.prompt_pin = cleaned
return True
def get_prompt_pin(
diff --git a/gateway/session_state.py b/gateway/session_state.py
index 918327bf30b..61b95b50186 100644
--- a/gateway/session_state.py
+++ b/gateway/session_state.py
@@ -49,7 +49,7 @@ class ConversationState:
last_resolved_model: str = "" # last successfully-resolved non-empty model
queued_events: List[Any] = field(default_factory=list) # /queue overflow FIFO (head in adapter)
sidecar_notes: List[str] = field(default_factory=list) # one-shot must-deliver notes
- ephemeral_pin: Optional[Tuple[Any, ...]] = None # pinned session-context (change_key, text)
+ ephemeral_pin: Optional[Tuple[Any, ...]] = None # pinned session-context (change_key, text, redact_pii)
# (channel_prompt, parent_chat_id) of the last non-internal turn; internal events reuse it
channel_pin: Optional[Tuple[Optional[str], Optional[str]]] = None
vc_last: Optional[str] = None # last voice-channel context delivered
diff --git a/tests/gateway/test_internal_event_pin_wiring.py b/tests/gateway/test_internal_event_pin_wiring.py
index ceb6b856a00..f28611f516a 100644
--- a/tests/gateway/test_internal_event_pin_wiring.py
+++ b/tests/gateway/test_internal_event_pin_wiring.py
@@ -320,7 +320,6 @@ 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"
-
@pytest.mark.asyncio
async def test_first_internal_event_after_restart_rehydrates_durable_prompt_pins(monkeypatch):
config = GatewayConfig()
@@ -370,6 +369,7 @@ async def test_human_first_after_restart_ignores_stale_durable_prompt_pin(monkey
"version": 1,
"context_key": "stale-key",
"context_prompt": "STALE CONTEXT",
+ "redact_pii": False,
"channel_prompt": "Stale channel prompt.",
"parent_chat_id": "stale-parent",
}
@@ -395,17 +395,27 @@ async def test_human_first_after_restart_ignores_stale_durable_prompt_pin(monkey
@pytest.mark.asyncio
-async def test_unchanged_human_prompt_pin_does_not_rewrite_durable_store(monkeypatch):
- durable: dict = {}
+async def test_internal_event_never_reuses_prompt_pin_from_another_privacy_policy(monkeypatch):
+ """A pin rendered with redact_pii off must not reach the model once redaction is on, not even
+ through the internal-event reuse path after a restart."""
+ import gateway.run as gr
+
+ monkeypatch.setattr(gr, "_load_gateway_config", lambda: {"privacy": {"redact_pii": True}})
+ durable = {
+ "value": {
+ "version": 1,
+ "context_key": "unredacted-key",
+ "context_prompt": "UNREDACTED CONTEXT",
+ "redact_pii": False,
+ "channel_prompt": "Channel hint.",
+ "parent_chat_id": None,
+ }
+ }
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.",
- )
+ await _drive(runner, ((True, _wake_source()),))
- assert len(calls) == 2
- assert runner.session_store.set_prompt_pin.call_count == 1
+ assert calls[0]["context_prompt"] != "UNREDACTED CONTEXT"
+ assert calls[0]["channel_prompt"] == "Channel hint."
diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.py
index 468a824d3c2..efef50a88ca 100644
--- a/tests/gateway/test_session.py
+++ b/tests/gateway/test_session.py
@@ -1541,6 +1541,7 @@ class TestGatewayRoutingTable:
"version": 1,
"context_key": "ctx-key",
"context_prompt": "exact session context",
+ "redact_pii": False,
"channel_prompt": "Channel hint.",
"parent_chat_id": "parent-1",
}
@@ -1570,37 +1571,13 @@ class TestGatewayRoutingTable:
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_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()
+ new_pin = dict(pin, context_key="new-key", context_prompt="new context")
+ assert restarted.set_prompt_pin(entry.session_key, new_pin, expected_session_id=fresh.session_id)
+ assert restarted.get_prompt_pin(entry.session_key, expected_session_id=old_session_id) is None
+ assert restarted.get_prompt_pin(entry.session_key, expected_session_id=fresh.session_id) == new_pin
+ restarted._db.close()
def test_switch_session_preserves_prompt_pin_unless_boundary_requests_clear(self, tmp_path):
config = GatewayConfig()
@@ -1610,6 +1587,7 @@ class TestGatewayRoutingTable:
"version": 1,
"context_key": "ctx-key",
"context_prompt": "exact session context",
+ "redact_pii": False,
"channel_prompt": None,
"parent_chat_id": None,
}