Merge pull request #69040 from NousResearch/bb/fix-verify-candidate-warm-payload

fix(tui_gateway): candidate-inclusive display on warm/live + child-watch resume (#65919 fallout)
This commit is contained in:
brooklyn! 2026-07-21 21:16:38 -05:00 • committed by GitHub
commit 8f51376db3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 322 additions and 2 deletions

View file

@ -1536,6 +1536,238 @@ def test_session_resume_uses_parent_lineage_for_display(monkeypatch):
assert captured["history_calls"] == [("tip", False), ("tip", True)]
def test_live_visible_history_prefers_db_display_with_candidate():
"""A warm/live session must serve the persisted DISPLAY lineage, not the
collapsed in-memory model history.
Regression for #65919's cross-session fallout: verification candidates
(finish_reason=verification_required) are persisted but collapsed out of the
model working history by repair_message_sequence. Building the live-reuse
payload from ``display_history_prefix + history`` therefore dropped the
substantive answer, while the eager session.resume path still showed it —
the two payloads for the same session disagreed. This asserts the live path
now matches the eager/REST display projection by construction.
"""
# In-memory model history: the candidate has been collapsed away.
in_memory = [
{"role": "user", "content": "do the thing"},
{"role": "assistant", "content": "terse verified reply"},
]
# Persisted display lineage: the candidate (substantive answer) survives.
display_with_candidate = [
{"role": "user", "content": "do the thing"},
{"role": "assistant", "content": "long substantive answer",
"finish_reason": "verification_required"},
{"role": "assistant", "content": "terse verified reply"},
]
class DB:
def get_messages_as_conversation(
self, key, include_ancestors=False, repair_alternation=False
):
assert key == "s1"
assert include_ancestors is True
return list(display_with_candidate)
result = server._live_visible_history({"session_key": "s1"}, DB(), in_memory)
assert result == display_with_candidate
def test_live_visible_history_falls_back_without_db_or_key():
in_memory = [{"role": "user", "content": "hi"}]
# No DB handle available.
assert server._live_visible_history({"session_key": "s"}, None, in_memory) == in_memory
# DB available but the session has no persist key yet.
class DB:
def get_messages_as_conversation(self, *a, **k): # pragma: no cover - not reached
raise AssertionError("must not query without a session_key")
assert server._live_visible_history({}, DB(), in_memory) == in_memory
def test_live_visible_history_falls_back_when_db_empty():
"""A brand-new live session whose first turn hasn't been flushed keeps its
in-memory history rather than rendering empty."""
in_memory = [{"role": "user", "content": "fresh turn not flushed yet"}]
class EmptyDB:
def get_messages_as_conversation(self, *a, **k):
return []
assert server._live_visible_history({"session_key": "s"}, EmptyDB(), in_memory) == in_memory
def test_live_visible_history_falls_back_when_db_raises():
in_memory = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "yo"}]
class BrokenDB:
def get_messages_as_conversation(self, *a, **k):
raise RuntimeError("db exploded")
assert server._live_visible_history({"session_key": "s"}, BrokenDB(), in_memory) == in_memory
def test_live_visible_history_keeps_candidate_and_fresh_tail():
"""The hard case: the persisted candidate (missing from in-memory) AND a
not-yet-flushed live turn (missing from the DB) must BOTH survive."""
# Persisted display: has the verification candidate, lags the newest turn.
db_display = [
{"role": "user", "content": "turn 1"},
{"role": "assistant", "content": "long substantive answer",
"finish_reason": "verification_required"},
{"role": "assistant", "content": "terse verified reply"},
]
# In-memory model history: candidate collapsed out, but has a fresh turn 2.
in_memory = [
{"role": "user", "content": "turn 1"},
{"role": "assistant", "content": "terse verified reply"},
{"role": "user", "content": "turn 2 not flushed"},
{"role": "assistant", "content": "turn 2 reply not flushed"},
]
class DB:
def get_messages_as_conversation(self, key, include_ancestors=False, repair_alternation=False):
return list(db_display)
result = server._live_visible_history({"session_key": "s1"}, DB(), in_memory)
assert result == [
{"role": "user", "content": "turn 1"},
{"role": "assistant", "content": "long substantive answer",
"finish_reason": "verification_required"},
{"role": "assistant", "content": "terse verified reply"},
{"role": "user", "content": "turn 2 not flushed"},
{"role": "assistant", "content": "turn 2 reply not flushed"},
]
def test_reconcile_display_with_live_trusts_db_when_tail_absent():
"""If the DB tail isn't in memory (DB ahead / diverged), don't duplicate —
serve the persisted display."""
db_display = [
{"role": "user", "content": "a"},
{"role": "assistant", "content": "b"},
]
in_memory = [{"role": "user", "content": "unrelated"}]
assert server._reconcile_display_with_live(db_display, in_memory) == db_display
assert server._reconcile_display_with_live([], in_memory) == in_memory
assert server._reconcile_display_with_live(db_display, []) == db_display
def test_live_visible_history_matches_eager_resume_with_real_db(tmp_path):
"""E2E cross-builder consistency against a real SessionDB.
A persisted verification candidate (finish_reason=verification_required)
is collapsed out of the model history by repair_message_sequence but kept
in the display lineage (#65919). The warm/live projection
(_live_visible_history) must equal the eager session.resume display
projection — both keeping the candidate — so switching to a live session
shows the same substantive answer a cold resume would.
"""
from hermes_state import SessionDB
db = SessionDB(db_path=tmp_path / "state.db")
db.create_session("s1", source="tui")
db.append_message("s1", role="user", content="do the thing")
db.append_message(
"s1", role="assistant", content="long substantive answer",
finish_reason="verification_required",
)
db.append_message(
"s1", role="assistant", content="terse verified reply", finish_reason="stop",
)
model_history, display_history = db.get_resume_conversations("s1")
# The divergence #65919 introduced: candidate absent from the model
# projection, present in the display projection.
assert not any("long substantive" in (m.get("content") or "") for m in model_history)
assert any("long substantive" in (m.get("content") or "") for m in display_history)
# Eager session.resume serves the display projection.
eager_messages = server._history_to_messages(display_history)
# Warm/live reuse: in-memory history is the collapsed model projection.
live_history = server._live_visible_history({"session_key": "s1"}, db, list(model_history))
# They must agree — the candidate survives the warm switch.
assert server._history_to_messages(live_history) == eager_messages
assert any(m.get("text") == "long substantive answer" for m in eager_messages)
def test_live_visible_history_keeps_candidate_and_new_flushed_turn_real_db(tmp_path):
"""Real-DB variant of the combined case: a candidate from turn 1 AND a
fully-flushed turn 2 both appear once."""
from hermes_state import SessionDB
db = SessionDB(db_path=tmp_path / "state.db")
db.create_session("s1", source="tui")
db.append_message("s1", role="user", content="turn 1")
db.append_message(
"s1", role="assistant", content="candidate answer",
finish_reason="verification_required",
)
db.append_message("s1", role="assistant", content="verified reply", finish_reason="stop")
db.append_message("s1", role="user", content="turn 2")
db.append_message("s1", role="assistant", content="turn 2 reply", finish_reason="stop")
model_history, display_history = db.get_resume_conversations("s1")
live_history = server._live_visible_history({"session_key": "s1"}, db, list(model_history))
texts = [m.get("text") for m in server._history_to_messages(live_history)]
assert texts == [
"turn 1",
"candidate answer",
"verified reply",
"turn 2",
"turn 2 reply",
]
def test_lazy_child_watch_resume_serves_candidate_inclusive_display(monkeypatch, tmp_path):
"""The delegated-child watch-window cold resume (lazy=True) must serve the
verbatim display projection so a persisted verification candidate is not
collapsed out of the watch window (#65919 sibling of the warm-payload fix).
"""
from hermes_state import SessionDB
db = SessionDB(db_path=tmp_path / "state.db")
db.create_session("child1", source="tui")
db.append_message("child1", role="user", content="child prompt")
db.append_message(
"child1", role="assistant", content="child substantive answer",
finish_reason="verification_required",
)
db.append_message(
"child1", role="assistant", content="child terse reply", finish_reason="stop",
)
lease = types.SimpleNamespace(session_id="child1", release=lambda: None)
monkeypatch.setattr(server, "_get_db", lambda: db)
monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)
monkeypatch.setattr(
server, "_claim_active_session_slot", lambda *a, **k: (lease, None)
)
monkeypatch.setattr(
server, "_deferred_session_record", lambda *a, **k: {"created_at": 123.0}
)
monkeypatch.setattr(server, "_claim_or_reuse_live", lambda *a, **k: None)
monkeypatch.setattr(server, "_child_run_active", lambda *a, **k: False)
monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda *a, **k: None)
resp = server.handle_request(
{
"id": "1",
"method": "session.resume",
"params": {"session_id": "child1", "lazy": True},
}
)
assert "error" not in resp, resp
texts = [m.get("text") for m in resp["result"]["messages"]]
assert "child substantive answer" in texts
assert texts == ["child prompt", "child substantive answer", "child terse reply"]
def test_session_resume_follows_compression_tip(monkeypatch, tmp_path):
"""Resuming a rotated-out parent id must load the continuation's messages.

View file

@ -6301,7 +6301,20 @@ def _(rid, params: dict) -> dict:
# A delegated child mid-run emits no session events of its own — report
# its liveness from the relay registry so the window shows a busy turn.
child_running = _child_run_active(target)
messages = _history_to_messages(history)
# User-visible messages use the VERBATIM display projection (child-only,
# no ancestors — matching the repaired read above), so model-invisible
# rows persisted by #65919 (verification candidates collapsed by
# repair_message_sequence) survive in the watch window just as they do
# on the eager resume + REST paths. The repaired ``history`` above still
# feeds live replay. Fall back to it if the display read fails.
try:
display_history = db.get_messages_as_conversation(
target, repair_alternation=False
)
except Exception:
logger.debug("child-watch display projection read failed", exc_info=True)
display_history = history
messages = _history_to_messages(display_history)
return _ok(
rid,
{
@ -6668,6 +6681,77 @@ def _fallback_session_info(session: dict) -> dict:
}
def _reconcile_display_with_live(
db_display: list[dict], in_memory: list[dict]
) -> list[dict]:
"""Merge the persisted DISPLAY lineage with the in-memory live history.
Two projections of the same session that each hold something the other
lacks:
- ``db_display`` — the verbatim persisted lineage. It includes
*model-invisible* rows (verification candidates, finish_reason
``verification_required`` / ``verify_hook_continue``) that the in-memory
model history collapses out via ``repair_message_sequence`` (#65919), but
it can lag the newest turn by a flush.
- ``in_memory`` — ``display_history_prefix + session["history"]``. It is the
freshest recency authority (a just-appended turn may not be flushed yet)
but it is the collapsed *model* projection, so it is missing candidates.
The merge keeps the DB display (candidate-inclusive) as the base and appends
only the in-memory tail that the DB does not yet cover, anchored on the last
DB row's ``(role, text)``. This satisfies BOTH invariants at once: the
substantive verification answer survives a warm/live switch (matching the
eager resume + REST payloads), and a not-yet-flushed live turn is not
dropped.
"""
if not db_display:
return in_memory
if not in_memory:
return db_display
def _key(msg: dict) -> tuple:
return (msg.get("role"), _coerce_message_text(msg.get("content")))
anchor = _key(db_display[-1])
last_shared = -1
for idx, msg in enumerate(in_memory):
if isinstance(msg, dict) and _key(msg) == anchor:
last_shared = idx
if last_shared == -1:
# The DB tail isn't present in memory (DB is ahead, or the histories
# diverged) — trust the persisted display rather than risk duplicating.
return db_display
return list(db_display) + list(in_memory[last_shared + 1 :])
def _live_visible_history(session: dict, db, in_memory_fallback: list[dict]) -> list[dict]:
"""Return the user-visible DISPLAY projection for a live/warm session.
Serving the raw in-memory *model* history for the user-visible payload
dropped model-invisible rows (verification candidates persisted by #65919)
whenever a warm/live session was reused, while the eager ``session.resume``
path (which reads the verbatim display lineage) still showed them — the two
payloads disagreed about the same session, which is the cross-session
"substantive answer vanishes on switch" class of bug.
This reconciles the persisted display lineage (candidate-inclusive, via
``get_messages_as_conversation(..., include_ancestors=True)`` — the same
read the eager resume and REST paths use) with the fresh in-memory tail, so
all surfaces agree while a not-yet-flushed turn is still shown. Falls back to
the in-memory history when the DB/session_key is unavailable or the DB read
fails.
"""
key = session.get("session_key")
if db is not None and key:
try:
display = db.get_messages_as_conversation(key, include_ancestors=True)
return _reconcile_display_with_live(display, in_memory_fallback)
except Exception:
logger.debug("live display projection read failed", exc_info=True)
return in_memory_fallback
def _live_session_payload(
sid: str,
session: dict,
@ -6683,12 +6767,16 @@ def _live_session_payload(
session["transport"] = transport
if touch:
session["last_active"] = time.time()
history = list(session.get("display_history_prefix") or []) + list(
in_memory_history = list(session.get("display_history_prefix") or []) + list(
session.get("history") or []
)
inflight = _inflight_snapshot(session)
queued = _queued_prompt_snapshot(session)
running = bool(session.get("running"))
# Prefer the persisted display lineage (candidate-inclusive) so this payload
# matches the eager session.resume + REST transcript; the DB has its own
# lock, so read it outside the session history lock.
history = _live_visible_history(session, _get_db(), in_memory_history)
payload = {
"info": _fallback_session_info(session),
"message_count": len(history),