fix(gateway): a wake after an agent eviction reuses the session-context pin #131032
Independent verification on the PR head (5ba9d1f1): pin-wiring suite 13/13 green on Linux. Reusing the session on wake after agent eviction holds. No findings.
Nit (non-blocking, no re-push needed on my account): the comment at the top of _evict_cached_agent ("a fresh agent must re-render its session-context bytes (the pin)") is now only true for the next human turn; an internal turn restores the durable snapshot instead. Worth a one-line tweak there so the two docstrings don't disagree, either in this PR or a follow-up.
Review (maintainer-side, P0 sweep). Verdict: correct, minimal, merge-ready pending CI; merge decision is Teknium's.
Premise confirmed on origin/main: _evict_cached_agent clears only conversation.ephemeral_pin and keeps channel_pin; _rehydrate_prompt_pins returns early when either pin is set, so the first internal event after /stop, /undo, /model, /compress, /login, /moa or a config-model eviction renders from the origin-only source and the next human turn re-keys back (A→B→A, two agent rebuilds).
History: the pre-f660ba2289 rehydrate restored the context pin independently when it was None (and kept a live channel pin). f660 collapsed that into the either-pin early return and documented the resulting eviction behaviour as intentional, but nothing in the pin design needs it: an internal event already reuses an existing pin verbatim regardless of change-key (_pinned_session_context_prompt, "an internal event is never a real metadata change"), and the snapshot is re-persisted after every turn (run_turn.py → _persist_prompt_pins), so what this PR adopts after an eviction is exactly the bytes the last human turn sent. Human turns never rehydrate, so f660's actual goal (an evicted agent re-renders on the next human turn) still holds.
Fences still hold with the widened rehydrate (checked, not assumed):
SessionPromptPinMixin.get_prompt_pin(expected_session_id=…) refuses a route whose session id moved; reset_session builds a fresh SessionEntry (no pin), so /new cannot revive the old conversation's bytes.switch_session(preserve_prompt_pin=False) on /resume and the startup CLI-adopt path; compression repoints keep it (same conversation, correct).privacy.redact_pii is still rejected in _pinned_session_context_prompt (existing test test_internal_event_never_reuses_prompt_pin_from_another_privacy_policy).channel_pin instead of overwriting it is right: it is the latest human turn's, same source as the snapshot.Live red/green (worktree on current main, fake-HOME runner):
1 failed, 12 passed — AssertionError: wake after eviction re-rendered the session context (A->B->A)test_internal_event_pin_wiring.py 13/13; plus test_prompt_tail_freeze.py, test_agent_cache.py, test_session.py, test_undo_rewind_session.py, test_session_model_reset.py, test_goal_resume_restart.py → 124 passed, 0 failed. ruff check clean.Sweep: no other open PR touches the eviction guard; #126167 / #127208 (synthetic goal/heartbeat/resume turns) are a different trigger and, as the body says, would inherit this path. Idle-TTL/LRU eviction (run_turn_runner.py::_pop_cached_agent_for_eviction) pops the cache without touching the pin, so it was never affected.
One non-blocking nit inline. CI runs for this head were parked at action_required; approved them.
Thanks. Agreed on the nit: the comment at gateway/run_agent_cache.py:781 ("a fresh agent must re-render its session-context bytes") is now true only for the next human turn, since _rehydrate_prompt_pins restores the durable snapshot for an internal turn. I'm not pushing it to this head, so the CI runs you approved stay valid. The one-line tweak will go in the next change that touches run_agent_cache.py (or I'll add it here if you'd rather have it in this PR).
AI code review — automated review for reference; please use your judgment.
The channel_pin is None half of the fix has no test — reverting it keeps the suite green
Both halves of this change are correct, but only one of them is covered. Reverting theephemeral_pin guard (gateway/run_agent_cache.py:627) killstest_first_internal_event_after_agent_eviction_keeps_effective_prompt. Reverting thechannel_pin guard (:642) leaves all 13 tests passing:
- if conversation.channel_pin is None:
- conversation.channel_pin = (pin["channel_prompt"], pin["parent_chat_id"])
+ conversation.channel_pin = (pin["channel_prompt"], pin["parent_chat_id"])
channel_pin appears exactly once in tests/ (test_internal_event_pin_wiring.py:354), and that
line is only assert ... channel_pin is not None — satisfied by any value, so it cannot distinguish
"kept the live pin" from "clobbered it with the stale durable one".
The guard is load-bearing, not cosmetic
_evict_cached_agent (:786) clears ephemeral_pin and keeps channel_pin — that is the whole
premise of this PR. So on the wake, the in-memory channel_pin is the fresher value (written by the
live turn before the eviction) while the durable snapshot may be older. Seeding that state directly
and calling _rehydrate_prompt_pins alone:
head (guard present): channel_pin = ('LIVE-NEW-hint.', '1513247605675790346')
mutant (guard removed): channel_pin = ('DURABLE-OLD-hint.', '1513247605675790346')
Same seed, same durable pin — the mutant replaces a fresh channel prompt with a stale one, which is
exactly the A→B→A re-key the surrounding docstring is trying to prevent. On a restart there is no
in-memory pin so the two agree, which is why the pre-existing restart test passes either way.
Suggested
Extend the new eviction test to pin the channel side too — drive a human turn with onechannel_prompt, evict, rehydrate with a durable snapshot carrying a different one, and assertchannel_pin still holds the live value. That kills the mutant and pins the half of the fix that is
currently undefended. Happy to send the test as a patch if useful.
For the record, the ephemeral_pin half is well covered — mutation on it fails the new test, as
expected. Base is 12 passed, head 13 passed, no other regressions.
[P1] Revalidate ownership after the async read before adopting the pins
This widened guard admits a post-eviction read while the live channel pin survives. The read checks expected_session_id under the store lock, but returns a detached copy. The await and unconditional adoption separate that check from publishing the pins.
A reachable ordering is: human turn in S1 → eviction → internal wake reads S1's pin → /new invalidates the generation, clears conversation state, and rotates the route to S2 → the old read returns and installs S1's pins into _session_state(session_key). The actual reset handler does clear the pins correctly; the late reader repopulates them afterward. A fresh, current-generation S2 wake then reuses them. The stale-result discard does not undo this shared-state mutation; rehydration also precedes acquisition of the turn lease.
I reproduced this with the real store, real generation checks, full message handler, actual /new, and a worker barrier after the real read released its lock. test_read_in_flight_cannot_repopulate_reset_conversation in the runnable probe file in the review body fails on this head: S2's durable pin is None, but the fresh wake's captured _run_agent input has S1's exact context and OLD CHANNEL. This proves a conversation-isolation failure at the prompt-input boundary; no provider execution or broader transcript/credential exposure is claimed.
Attribution: the lack of an adoption fence already exists for a cold-process read. This change newly makes the same race reachable in the ordinary same-process eviction state, where the previous surviving-channel guard returned without reading. The identical probe passes on both reported base 7817bf52 and parent 357f51c4.
Required repair: validate the captured conversation/session ownership and run or boundary epoch immediately before publishing the async result, and do not replace a context pin installed while awaiting. An object-identity check alone is insufficient: the boundary funnel clears the same conversation object in place. Apply the adoption rule to every caller of this helper while retaining the intended eviction continuity.
Regression contract: suspend the real read after copying S1; complete /new; release it; assert a fresh current-generation S2 wake uses neither S1 context nor S1 channel. Also assert that a live successor human pin cannot be overwritten by a delayed read. The third included probe demonstrates that latter helper-level failure: old context is installed beside NEW CHANNEL. Both failure paths must be rejected at adoption, while an unchanged-owner eviction still restores its valid snapshot.
[P2] Keep the restored context coherent with the surviving live channel
Preserving a live channel pin here is correct, but the context installed immediately above can be older than that channel. The pin writer publishes its in-memory routing entry only after saving the candidate. A failed save therefore retains the older durable snapshot. Persistence deliberately catches that failure and allows the human turn to run with its newer live pins.
Concrete sequence: persist human context/channel A; a later human turn renders a renamed channel and CURRENT TOPIC with channel B; its snapshot save raises OSError; the human run still receives B; recover storage and evict the agent, which clears live context B while retaining channel B; an internal wake now restores durable context A and keeps channel B. The wake's prompt inputs roll backward and lose the current metadata, violating the claimed reuse of the last human render.
test_failed_persist_does_not_restore_older_context in the runnable review-body probes drives this through the real store and message handler, injecting failure only at the candidate snapshot save. On this head, the captured wake input equals the exact old context, omits CURRENT TOPIC, and retains NEW CHANNEL. The probe passes on reported base 7817bf52 and parent 357f51c4, which do not resurrect A in this surviving-channel state; they still have the original origin-only-render problem this PR aims to fix. This is a newly introduced rollback, conditional on a metadata change, failed snapshot write, eviction, and an internal first turn.
Required repair: preserve an identity-bound coherent live context/channel snapshot for internal reuse across resource eviction, or track freshness/failed persistence so rehydration cannot adopt an older durable context beside newer live channel state. Keep true conversation-boundary invalidation and the next human turn's rerender behavior. Overwriting the newer channel with durable A would merely make both halves stale.
Regression contract: after the failed B save and eviction, assert the wake receives context B and channel B, including CURRENT TOPIC; a subsequent human turn must not cause a backward/forward prompt jump. Also cover successful persistence, restart with no live pair, and conversation reset so retained live state does not escape its owner. The measured failure here is stale and mixed prompt input; no model-response or authorization consequence is asserted.
Reviewed 5ba9d1f12b15574597122cbe81596ca1ea40745f against reported base 7817bf522af3caf54b30ae59f16157469d7638fc.
The ordinary human → eviction → wake case works, but I would hold this head for the two reproduced defects below. Restoring a persisted snapshot needs both an ownership check at adoption and a freshness rule when the live and persisted state diverge.
/new can install the old conversation's pins after the reset. The store's session-ID fence passes before the reset; the detached result is later adopted into the current state for the routing key without revalidation. A subsequent, current-generation wake in the new session consumes the old context and channel despite having no durable pin. This PR exposes that existing asynchronous adoption flaw to same-process eviction, where the old channel guard previously prevented the read.
The implementation-local mechanism, required repair, and regression contract are in the two inline comments on gateway/run_agent_cache.py.
Independent behavioral evidence, separate from suite receipts
On Linux, Python 3.14.7, pytest 9.1.1, using scripts/run_tests.sh with isolated test homes and file retries disabled:
| Checkout | Existing pin-wiring suite | Three reviewer probes |
| --- | --- | --- |
| PR head 5ba9d1f1 | 13 passed | 3 failed |
| Reported PR base 7817bf52 | Not rerun in this control | 3 passed |
| Pre-change parent 357f51c4 | Not rerun in this control | 3 passed |
The same probe file was used in all three checkouts. The relevant cache, turn, session-store, reset, and original wiring-fixture sources are identical between the two controls. Their passing result means these specific regressions are absent; it does not mean the base implements the PR's intended prompt continuity correctly.
The head's captured observations were:
WRITE_FAILURE {'wake_reverted_to_old_context': True, 'wake_channel': 'NEW CHANNEL', 'live_topic_missing': True}
RESET_RACE {'session_rotated': True, 'durable_pin_empty': True, 'wake_uses_old_context': True, 'wake_channel': 'OLD CHANNEL'}
SUCCESSOR_RACE {'wake_uses_old_context': True, 'wake_channel': 'NEW CHANNEL'}
The first two probes drive the real message handler with a real SessionStore and asynchronous facade. The reset probe runs the actual /new handler and restores the real generation checks that the existing fixture stubs. Its barrier is after the real locked, session-ID-fenced read has returned a detached copy. The third probe exercises the helper's adoption race against a successor human pin; it supports P1 rather than adding another finding, and does not establish a separate concurrent-admission scenario.
These probes reuse the PR's runner fixture, including its unrelated admission, lease, hook, and provider stubs. _run_agent is captured, so the measured sink is its context/channel input, not a live model response. The runtime has the dependencies needed for these files, rather than a full locked installation; optional plugin imports warned about missing requests. No full-suite or provider E2E claim is made.
Reconciliation with the earlier discussion
The earlier 13/13 verification is reproducible. It establishes the ordinary case, not these interleavings or persistence failures. The earlier review's reset-fence conclusion misses the interval between the worker's fenced read and event-loop adoption. The privacy-policy rejection remains effective in the existing suite; this review does not allege a privacy-flag bypass.
Enough1122's live-versus-durable channel coverage concern remains relevant. My write-failure probe produces that divergence through the real persistence path and confirms the head preserves NEW CHANNEL; preserving it alone still leaves the stale context. I did not independently rerun that comment's channel-guard mutation. The docstring nit is separate and nonblocking.
The current Python CI job succeeded on this head. The check-run inventory was 22 successful and 36 skipped. Those statuses do not assert the two contracts exercised here. The same adoption rule also needs to hold for any synthetic-turn callers using this helper, including the paths discussed in #126167 and #127208; the concrete reproductions here use this PR's internal-event path.
State transitions
Each diagram embeds its semantic-role legend. Evidence confidence remains explicit in the reported observations. The repair branches are proposals, not validated patches.
%%{init: {'theme':'dark','themeVariables':{'background':'#0d1117','primaryTextColor':'#e6edf3','lineColor':'#94a3b8'}}}%%
flowchart TB
subgraph CORE[" "]
direction TB
A["Human turn: context A for S1"] --> B["Evict agent: retain channel<br/>pin"]
B --> C["Worker reads A; S1 fence<br/>passes"]
C --> D["/new rotates route to S2 and<br/>clears pins"]
D --> E["Late read installs A on<br/>routing key"]
E --> F["Fresh S2 wake consumes S1<br/>context"]
D --> G["Proposed: recheck ownership<br/>before adoption"]
G --> H["Discard displaced read"]
end
CORE ~~~ LEGEND
subgraph LEGEND["Legend"]
direction TB
subgraph KEY_0[" "]
direction LR
LE["Blue<br/>Incoming"]:::normal
LT["Amber<br/>Transition / pending"]:::repair
LE ~~~ LT
end
subgraph KEY_1[" "]
direction LR
LF["Red<br/>Failure"]:::failure
LO["Purple<br/>Ownership / policy"]:::authority
LF ~~~ LO
end
KEY_0 ~~~ KEY_1
end
style CORE fill:#0d1117,stroke:#30363d,color:#e6edf3
style LEGEND fill:#0d1117,stroke:#30363d,color:#e6edf3
style KEY_0 fill:none,stroke:none
style KEY_1 fill:none,stroke:none
classDef normal fill:#172554,stroke:#60a5fa,color:#eff6ff,stroke-width:2px;
classDef repair fill:#451a03,stroke:#fbbf24,color:#fffbeb,stroke-width:2px;
classDef failure fill:#450a0a,stroke:#f87171,color:#fef2f2,stroke-width:2px;
classDef authority fill:#3b0764,stroke:#c084fc,color:#faf5ff,stroke-width:2px;
class A normal
class C authority
class B,D,G,H repair
class E,F failure
click A "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L666-L691" "Pinned implementation or proposed-repair boundary"
click B "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L767-L786" "Pinned implementation or proposed-repair boundary"
click C "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/session_prompt_pin.py#L71-L81" "Pinned implementation or proposed-repair boundary"
click D "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/slash_commands_session.py#L155-L186" "Pinned implementation or proposed-repair boundary"
click E "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L628-L643" "Pinned implementation or proposed-repair boundary"
click F "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L680-L685" "Pinned implementation or proposed-repair boundary"
click G "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L628-L643" "Pinned implementation or proposed-repair boundary"
click H "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L628-L643" "Pinned implementation or proposed-repair boundary"
%%{init: {'theme':'dark','themeVariables':{'background':'#0d1117','primaryTextColor':'#e6edf3','lineColor':'#94a3b8'}}}%%
flowchart TB
subgraph CORE[" "]
direction TB
A["Persist context A and<br/>channel A"] --> B["Human renders context B and<br/>channel B"]
B --> C["Snapshot write fails;<br/>durable A survives"]
C --> D["Eviction clears live context<br/>B"]
D --> E["Wake restores durable<br/>context A"]
E --> F["Run input: context A with<br/>live channel B"]
D --> G["Proposed: retain coherent<br/>live pair"]
G --> H["Wake reuses B with B"]
end
CORE ~~~ LEGEND
subgraph LEGEND["Legend"]
direction TB
subgraph KEY_0[" "]
direction LR
LE["Blue<br/>Incoming"]:::normal
LT["Amber<br/>Transition / pending"]:::repair
LE ~~~ LT
end
subgraph KEY_1[" "]
direction LR
LF["Red<br/>Failure"]:::failure
LD["Teal<br/>Durable state"]:::durable
LF ~~~ LD
end
KEY_0 ~~~ KEY_1
end
style CORE fill:#0d1117,stroke:#30363d,color:#e6edf3
style LEGEND fill:#0d1117,stroke:#30363d,color:#e6edf3
style KEY_0 fill:none,stroke:none
style KEY_1 fill:none,stroke:none
classDef normal fill:#172554,stroke:#60a5fa,color:#eff6ff,stroke-width:2px;
classDef repair fill:#451a03,stroke:#fbbf24,color:#fffbeb,stroke-width:2px;
classDef failure fill:#450a0a,stroke:#f87171,color:#fef2f2,stroke-width:2px;
classDef durable fill:#134e4a,stroke:#2dd4bf,color:#f0fdfa,stroke-width:2px;
class A durable
class B normal
class D,G,H repair
class C,E,F failure
click A "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L645-L664" "Pinned implementation or proposed-repair boundary"
click B "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L666-L716" "Pinned implementation or proposed-repair boundary"
click C "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/session_prompt_pin.py#L49-L69" "Pinned implementation or proposed-repair boundary"
click D "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L767-L786" "Pinned implementation or proposed-repair boundary"
click E "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L628-L643" "Pinned implementation or proposed-repair boundary"
click F "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L680-L716" "Pinned implementation or proposed-repair boundary"
click G "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L645-L664" "Pinned implementation or proposed-repair boundary"
click H "https://github.com/NousResearch/hermes-agent/blob/5ba9d1f12b15574597122cbe81596ca1ea40745f/gateway/run_agent_cache.py#L680-L716" "Pinned implementation or proposed-repair boundary"
<details>
<summary>Runnable reviewer probes (three tests; two findings)</summary>
Save the following as tests/gateway/test_review_prompt_pin_boundaries.py beside the existing wiring test. In a Python 3.14 test environment with the project's test dependencies, run from the checkout:
HERMES_TEST_FILE_RETRIES=0 scripts/run_tests.sh \
tests/gateway/test_review_prompt_pin_boundaries.py \
tests/gateway/test_internal_event_pin_wiring.py \
--file-timeout 90 -j 1 -s
The probe assertions target the newly observed regressions. The repair contracts in the inline comments additionally require full B/B continuity; simply falling back to an origin-only render would not satisfy the intended fix.
"""Independent review probes: real routing store, captured model boundary."""
import asyncio
import importlib.util
import threading
from dataclasses import replace
from pathlib import Path
import pytest
from gateway.platforms.base import MessageEvent
from gateway.session import SessionStore
_harness_spec = importlib.util.spec_from_file_location(
"pin_review_harness", Path(__file__).with_name("test_internal_event_pin_wiring.py"))
_harness = importlib.util.module_from_spec(_harness_spec)
_harness_spec.loader.exec_module(_harness)
_make_runner = _harness._make_runner
_human_thread_source = _harness._human_thread_source
_wake_thread_source = _harness._wake_thread_source
_capture = _harness._capture
async def _drive(runner, turns, *, channel_prompt=None):
for internal, source in turns:
key = runner._session_key_for_source(source)
generation = runner._begin_session_run_generation(key)
event = MessageEvent(text="[review] wake" if internal else "hi", source=source,
message_id=None if internal else source.message_id,
internal=internal, channel_prompt=None if internal else channel_prompt)
await runner._handle_message_with_agent(event, source, key, generation)
def runner_and_store(monkeypatch, tmp_path):
runner = _make_runner(monkeypatch)
from gateway.run import GatewayRunner
# Restore actual generation checks that the PR's wiring fixture replaces.
runner._is_session_run_current = GatewayRunner._is_session_run_current.__get__(runner)
runner._begin_session_run_generation = GatewayRunner._begin_session_run_generation.__get__(runner)
store = SessionStore(tmp_path / "sessions", runner.config)
runner.session_store = store
# Keep a real SessionStore and real async facade. Only the model boundary is captured.
runner._session_db = None
source = _human_thread_source()
entry = store.get_or_create_session(source)
key = entry.session_key
calls = []
_capture(runner, calls)
return runner, store, source, entry, key, calls
@pytest.mark.asyncio
async def test_failed_persist_does_not_restore_older_context(monkeypatch, tmp_path):
runner, store, source, entry, key, calls = runner_and_store(monkeypatch, tmp_path)
await _drive(runner, ((False, source),), channel_prompt="OLD CHANNEL")
old_context = calls[-1]["context_prompt"]
old_snapshot = store.get_prompt_pin(key, expected_session_id=entry.session_id)
save = store._save_entry
def fail_pin_write(session_key, *, entry_data=None, lock_held=False):
if entry_data is not None and entry_data.get("prompt_pin") != old_snapshot:
raise OSError("review synthetic routing-store outage")
return save(session_key, entry_data=entry_data, lock_held=lock_held)
monkeypatch.setattr(store, "_save_entry", fail_pin_write)
fresh_source = replace(source, chat_name="RENAMED CHANNEL", chat_topic="CURRENT TOPIC")
await _drive(runner, ((False, fresh_source),), channel_prompt="NEW CHANNEL")
fresh_context = calls[-1]["context_prompt"]
assert fresh_context != old_context
assert store.get_prompt_pin(key, expected_session_id=entry.session_id) == old_snapshot
monkeypatch.setattr(store, "_save_entry", save)
runner._evict_cached_agent(key)
await _drive(runner, ((True, _wake_thread_source()),))
observed = calls[-1]
print("WRITE_FAILURE", {"wake_reverted_to_old_context": observed["context_prompt"] == old_context,
"wake_channel": observed["channel_prompt"],
"live_topic_missing": "CURRENT TOPIC" not in observed["context_prompt"]})
assert observed["context_prompt"] != old_context, "older durable context resurrected after failed save"
@pytest.mark.asyncio
async def test_read_in_flight_cannot_repopulate_reset_conversation(monkeypatch, tmp_path):
runner, store, source, entry, key, calls = runner_and_store(monkeypatch, tmp_path)
await _drive(runner, ((False, source),), channel_prompt="OLD CHANNEL")
old_context = calls[-1]["context_prompt"]
old_sid = entry.session_id
runner._evict_cached_agent(key)
got_copy, release = threading.Event(), threading.Event()
read = store.get_prompt_pin
def paused_read(*args, **kwargs):
pin = read(*args, **kwargs) # real session-id fence, real copy, real lock released
got_copy.set()
if not release.wait(10):
raise TimeoutError("review barrier")
return pin
monkeypatch.setattr(store, "get_prompt_pin", paused_read)
task = asyncio.create_task(_drive(runner, ((True, _wake_thread_source()),)))
# Base does not read at all when the surviving channel pin exists.
for _ in range(1000):
if got_copy.is_set() or task.done():
break
await asyncio.sleep(.001)
assert got_copy.is_set() or task.done(), "probe did not reach read barrier"
# Exercise the actual /new command while the old read owns only a detached copy.
runner._cleanup_old_agent_for_reset = __import__('unittest.mock', fromlist=['AsyncMock']).AsyncMock()
runner._fire_session_reset_hooks = __import__('unittest.mock', fromlist=['AsyncMock']).AsyncMock()
monkeypatch.setattr(runner, "_reset_notice_session_info", lambda source: "")
await runner._handle_reset_command(MessageEvent(text="/new", source=source))
current_entry = store.lookup_by_session_key(key)
assert current_entry.session_id != old_sid
assert current_entry.prompt_pin is None
release.set()
await task
monkeypatch.setattr(store, "get_prompt_pin", read)
await _drive(runner, ((True, _wake_thread_source()),))
current_entry = store.lookup_by_session_key(key)
observed = calls[-1]
print("RESET_RACE", {"session_rotated": current_entry.session_id != old_sid,
"durable_pin_empty": current_entry.prompt_pin is None,
"wake_uses_old_context": observed["context_prompt"] == old_context,
"wake_channel": observed["channel_prompt"]})
assert observed["context_prompt"] != old_context, "late read installed old context across /new"
@pytest.mark.asyncio
async def test_late_read_cannot_replace_a_successor_human_pin(monkeypatch, tmp_path):
runner, store, source, entry, key, calls = runner_and_store(monkeypatch, tmp_path)
await _drive(runner, ((False, source),), channel_prompt="OLD CHANNEL")
old_context = calls[-1]["context_prompt"]
runner._evict_cached_agent(key)
got_copy, release = threading.Event(), threading.Event()
read = store.get_prompt_pin
def paused_read(*args, **kwargs):
pin = read(*args, **kwargs)
got_copy.set()
if not release.wait(10):
raise TimeoutError("review barrier")
return pin
monkeypatch.setattr(store, "get_prompt_pin", paused_read)
task = asyncio.create_task(runner._rehydrate_prompt_pins(key, entry.session_id))
for _ in range(1000):
if got_copy.is_set() or task.done():
break
await asyncio.sleep(.001)
assert got_copy.is_set() or task.done(), "probe did not reach read barrier"
fresh_source = replace(source, chat_name="RENAMED CHANNEL", chat_topic="CURRENT TOPIC")
await _drive(runner, ((False, fresh_source),), channel_prompt="NEW CHANNEL")
fresh_context = calls[-1]["context_prompt"]
assert fresh_context != old_context
release.set()
await task
monkeypatch.setattr(store, "get_prompt_pin", read)
await _drive(runner, ((True, _wake_thread_source()),))
observed = calls[-1]
print("SUCCESSOR_RACE", {"wake_uses_old_context": observed["context_prompt"] == old_context,
"wake_channel": observed["channel_prompt"]})
assert observed["context_prompt"] == fresh_context, "late read overwrote successor human context"
</details>
Current status after rechecking exact head 5ba9d1f12b and current main (51609d827b): the A→B→A cache-prefix defect is still real, but this implementation remains blocked by the two reproduced races in @andrexibiza's review.
The safer current-main direction is to avoid widening durable rehydration to ordinary cache eviction at all:
1. Treat prompt pins as conversation-scoped, not agent-instance-scoped. _clear_conversation_scope() already owns /new, /resume, and other true boundaries. A soft _evict_cached_agent() should keep the coherent live ephemeral_pin + channel_pin pair (while still clearing vc_last). Then /model, /undo, /stop rebuild the agent without forcing an internal wake through stale durability, and a failed set_prompt_pin() cannot restore durable A beside live channel B.
2. Keep durable rehydrate cold-start-only, but fence adoption after the await. Capture the session run generation before get_prompt_pin(), then immediately before assignment require: same generation/session ownership, no live context pin appeared, and no live channel pin appeared. This closes the /new read→adopt race and prevents a successor human render from being overwritten.
3. Pin both failure shapes with regressions:
- human B/B rendered, durable write fails, agent evicted, internal wake must use live B/B—not durable A/B;
- durable S1 read blocked, /new advances generation and clears scope, read completes, S1 pins must not install into S2.
This also answers @Enough1122's coverage point: the channel guard is load-bearing and needs a direct assertion, not only the end-to-end ephemeral-prompt equality.
The branch is now non-mergeable and has not moved since October 3. I would update rather than merge this head. Credit: @jonpol01 identified and implemented the original continuity seam; @andrexibiza supplied the runnable P1/P2 counterexamples; @Enough1122 identified the untested channel-pin invariant.
Salvaged into #139865, merged as 8eecd1cb09, with your commit and authorship kept. _rehydrate_prompt_pins now returns early only when the context pin exists and keeps a live channel pin. Thank you @jonpol01.
teknium1
jonpol01
What does this PR do?
_rehydrate_prompt_pinsnow restores the durable snapshot whenever the context pin is missing, and keeps a live channel pin instead of overwriting it. So an internal event after an eviction reuses the last human render, exactly as it does after a restart.Human turns are unchanged: they never call rehydrate, so an evicted agent's next human turn still re-renders from its real source, as f660ba2289 intends. Existing checks still apply: the snapshot is keyed on the session id (so
/new,/resumeand auto-reset never revive it), and a pin rendered under a differentprivacy.redact_piisetting is still rejected.Intent
@kshitijk4poor's f660ba2289 says rehydrate runs "only when this process holds no pins for the key (a restart)" and that "an evicted agent still re-renders instead of reviving the snapshot". This keeps that for human turns, which never rehydrate and still re-render after an eviction. It changes only internal events, whose source has no chat or user names. On those, re-rendering does not pick up anything new; it produces the degraded B bytes, and the next human turn switches back to A.
Compared with #127208 and #126167
#127208 (EdderTalmor) and #126167 (JoaoMarcos44) preserve pins across synthetic goal, heartbeat and resume turns, which are not internal events. That is a different trigger, and neither changes the eviction guard. If either lands, its turns go through the same rehydrate path and get this fix too.
Related Issue
Fixes #131031
Type of Change
Changes Made
gateway/run_agent_cache.py:_rehydrate_prompt_pinskeys its early return on the context pin only and does not overwrite a live channel pin. The docstrings of it and_pinned_session_context_promptnow name the eviction case.tests/gateway/test_internal_event_pin_wiring.py: one invariant test, human turn → eviction → internal wake → human turn, asserting that all three requests carry the same effective ephemeral prompt.user-guide/messaging/index.mdis about the/modeloverride.How to Test
Python 3.14 (the runner printed
HERMES_PYTHON: ~/.cache/hermes-agent-test-venvs/<worktree>/bin/python). Run on the fix applied to currentmain(7817bf522a; the merge is clean).gateway/run_agent_cache.pyreverted tomain,scripts/run_tests.sh tests/gateway/test_internal_event_pin_wiring.pygives 1 failed, 12 passed:AssertionError: wake after eviction re-rendered the session context (A->B->A).test_session.py,test_agent_cache.py,test_prompt_tail_freeze.py,test_resume_command.py,test_goal_resume_restart.py,test_undo_rewind_session.py,test_session_model_reset.py,test_login_command.py,test_moa_one_shot_restore.py,test_model_command_*.py,test_shutdown_cache_cleanup.py,test_telegram_topic_mode.py, and others; 22 files): 258 passed, 0 failed, 1 skipped.ruff checkon the changed files is clean.Checklist
Code
fix(scope):,feat(scope):, etc.)pytest tests/ -qand all tests pass. I ran only the related files listed above viascripts/run_tests.sh, not the full suite.Documentation & Housekeeping
docs/, docstrings) — or N/Acli-config.yaml.exampleif I added/changed config keys — or N/ACONTRIBUTING.mdorAGENTS.mdif I changed architecture or workflows — or N/A