fix(session): prevent consumed follow-ups from replaying after restart (#6299)
* fix(session): atomically acknowledge consumed follow-ups * refactor(webui): drop legacy follow-up replay compatibility
This commit is contained in:
1 parent
743d40bbba
commit
53e0edf709
17 files changed
+645
-215
No files matched your search
@@ -205,31 +205,20 @@ async def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) ->
|
||||
|
||||
async def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = await loop.sessions.state.get("websocket:chat")
|
||||
session.metadata[PENDING_FOLLOWUPS_KEY] = [
|
||||
{
|
||||
"id": "followup-1",
|
||||
"sender_id": "user",
|
||||
"chat_id": "chat",
|
||||
"content": "queued while busy",
|
||||
"media": [],
|
||||
"metadata": {},
|
||||
}
|
||||
]
|
||||
|
||||
persisted = await loop._persist_user_message_early(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="user",
|
||||
chat_id="chat",
|
||||
content="queued while busy",
|
||||
metadata={PENDING_FOLLOWUP_ID_KEY: "followup-1"},
|
||||
),
|
||||
session,
|
||||
loop.provider.aclose = AsyncMock()
|
||||
message = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="queued while busy",
|
||||
)
|
||||
|
||||
assert persisted is True
|
||||
assert PENDING_FOLLOWUPS_KEY not in session.metadata
|
||||
try:
|
||||
identifier = await loop.sessions.state.queue_followup(message.session_key, message)
|
||||
message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier
|
||||
# Control: unlike mid-turn injection, this draft already sees the journal.
|
||||
session = await loop.sessions.state.get(message.session_key)
|
||||
assert await loop._persist_user_message_early(message, session)
|
||||
assert PENDING_FOLLOWUPS_KEY not in session.metadata
|
||||
assert PENDING_FOLLOWUPS_KEY not in (await loop.sessions.state.get(session.key)).metadata
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None:
|
||||
@@ -598,34 +587,6 @@ def test_save_turn_commits_summary_boundary_without_rewriting_raw_history() -> N
|
||||
]
|
||||
|
||||
|
||||
def test_save_turn_acknowledges_every_merged_recovery_followup() -> None:
|
||||
"""Persisting a merged injected row retires every durable follow-up ID."""
|
||||
loop = _mk_loop()
|
||||
session = Session(
|
||||
key="test:recovery-followups",
|
||||
metadata={
|
||||
PENDING_FOLLOWUPS_KEY: [
|
||||
{"id": "first"},
|
||||
{"id": "second"},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
loop._save_turn(
|
||||
session,
|
||||
[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "first\n\nsecond",
|
||||
PENDING_FOLLOWUP_ID_KEY: ["first", "second"],
|
||||
}
|
||||
],
|
||||
skip=0,
|
||||
)
|
||||
|
||||
assert PENDING_FOLLOWUPS_KEY not in session.metadata
|
||||
|
||||
|
||||
def test_save_turn_keeps_image_placeholder_and_runtime_context() -> None:
|
||||
loop = _mk_loop()
|
||||
session = Session(key="test:image")
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Follow-up consumption commits against the owner, not an old turn snapshot."""
|
||||
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.bus.events import INBOUND_META_TURN_ID, InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import PENDING_FOLLOWUP_ID_KEY, pending_followups
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
|
||||
|
||||
def _loop(sessions):
|
||||
loop = AgentLoop.__new__(AgentLoop)
|
||||
loop.sessions = sessions
|
||||
return loop
|
||||
|
||||
|
||||
def _input(text, turn_id):
|
||||
return InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content=text,
|
||||
timestamp=datetime(2026, 10, 18, 19, 0, 0),
|
||||
metadata={INBOUND_META_TURN_ID: turn_id},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("count", [1, 2])
|
||||
@pytest.mark.parametrize("leave_unconsumed", [False, True])
|
||||
async def test_late_consumption_commits_history_and_only_its_ids(tmp_path, monkeypatch, count, leave_unconsumed):
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui")
|
||||
sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
state = sessions.state
|
||||
try:
|
||||
draft = await state.get("websocket:chat")
|
||||
draft.add_message("user", "initial input")
|
||||
await state.prepare_input(draft)
|
||||
consumed = []
|
||||
for index in range(count):
|
||||
message = _input(f"follow-up {index}", f"input-{index}")
|
||||
consumed.append(await state.queue_followup(draft.key, message))
|
||||
await state.checkpoint_view(draft, {"phase": "final_response"})
|
||||
_loop(sessions)._save_turn(draft, [
|
||||
*[
|
||||
{"role": "user", "content": f"follow-up {index}", PENDING_FOLLOWUP_ID_KEY: identifier}
|
||||
for index, identifier in enumerate(consumed)
|
||||
],
|
||||
{"role": "assistant", "content": "completed answer"},
|
||||
], skip=0)
|
||||
if leave_unconsumed:
|
||||
await state.queue_followup(draft.key, _input("arrived after model boundary", "late-input"))
|
||||
await state.finish_turn(draft)
|
||||
committed = await state.get(draft.key)
|
||||
expected = ["arrived after model boundary"] if leave_unconsumed else []
|
||||
assert [item.content for item in pending_followups(committed)] == expected
|
||||
assert [item["content"] for item in committed.messages] == [
|
||||
"initial input", *[f"follow-up {index}" for index in range(count)], "completed answer",
|
||||
]
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
reopened = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
try:
|
||||
bus = MessageBus()
|
||||
await RecoveryCoordinator(reopened, bus).scan()
|
||||
queued = []
|
||||
while not bus.inbound.empty():
|
||||
queued.append(bus.inbound.get_nowait().content)
|
||||
assert queued == expected
|
||||
assert (await reopened.state.get(draft.key)).messages == committed.messages
|
||||
finally:
|
||||
await reopened.state.aclose()
|
||||
|
||||
|
||||
async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(tmp_path):
|
||||
sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
state = sessions.state
|
||||
try:
|
||||
draft = await state.get("websocket:chat")
|
||||
draft.add_message("user", "initial input")
|
||||
await state.prepare_input(draft)
|
||||
identifier = await state.queue_followup(draft.key, _input("consumed input", "follow-up"))
|
||||
_loop(sessions)._save_turn(draft, [
|
||||
{"role": "user", "content": "consumed input", PENDING_FOLLOWUP_ID_KEY: identifier},
|
||||
{"role": "assistant", "content": "completed answer"},
|
||||
], skip=0)
|
||||
with sqlite3.connect(sessions._store.path) as db:
|
||||
db.execute("""CREATE TRIGGER reject_ack BEFORE DELETE ON pending_inputs
|
||||
BEGIN SELECT RAISE(ABORT, 'failed follow-up commit'); END""")
|
||||
with pytest.raises(sqlite3.IntegrityError, match="failed follow-up commit"):
|
||||
await state.finish_turn(draft)
|
||||
# Both the durable snapshot and published cache remain at the pre-commit boundary.
|
||||
for stored in (sessions.read_session_snapshot(draft.key), state.peek(draft.key)):
|
||||
assert [row["content"] for row in stored.messages] == ["initial input"]
|
||||
assert [item.content for item in pending_followups(stored)] == ["consumed input"]
|
||||
with sqlite3.connect(sessions._store.path) as db:
|
||||
db.execute("DROP TRIGGER reject_ack")
|
||||
await state.finish_turn(draft)
|
||||
committed = sessions.read_session_snapshot(draft.key)
|
||||
assert [row["content"] for row in committed.messages] == [
|
||||
"initial input", "consumed input", "completed answer",
|
||||
]
|
||||
assert pending_followups(committed) == []
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_recovered_input_keeps_admission_identity_and_timestamp(tmp_path):
|
||||
sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
state = sessions.state
|
||||
message = _input("queued input", "original-input")
|
||||
try:
|
||||
draft = await state.get(message.session_key)
|
||||
await state.queue_followup(draft.key, message)
|
||||
recovered = pending_followups(await state.get(draft.key))[0]
|
||||
assert recovered.timestamp == message.timestamp
|
||||
assert recovered.metadata[INBOUND_META_TURN_ID] == "original-input"
|
||||
assert await _loop(sessions)._persist_user_message_early(recovered, draft)
|
||||
row = (await state.get(draft.key)).messages[-1]
|
||||
assert row["timestamp"] == message.timestamp.isoformat()
|
||||
assert row[INBOUND_META_TURN_ID] == "original-input"
|
||||
assert pending_followups(await state.get(draft.key)) == []
|
||||
finally:
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path):
|
||||
import asyncio
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="completed answer"))
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path / "workspace", model="test-model")
|
||||
loop.sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
try:
|
||||
draft = await loop.sessions.state.get("websocket:chat")
|
||||
draft.add_message("user", "initial input")
|
||||
await loop.sessions.state.prepare_input(draft)
|
||||
queue = asyncio.Queue()
|
||||
for turn_id in ("first-input", "second-input"):
|
||||
message = _input("intentionally identical text", turn_id)
|
||||
identifier = await loop.sessions.state.queue_followup(draft.key, message)
|
||||
message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier
|
||||
queue.put_nowait(message)
|
||||
runtime = loop.llm_runtime()
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=draft.get_history(), current_message=None),
|
||||
runtime=runtime, session=draft, pending_queue=queue,
|
||||
request_context=RequestContext(
|
||||
channel="websocket", chat_id="chat", session_key=draft.key,
|
||||
turn_id="active-run", runtime=runtime,
|
||||
),
|
||||
)
|
||||
loop._save_turn(draft, result.messages, skip=2)
|
||||
await loop.sessions.state.finish_turn(draft)
|
||||
stored = await loop.sessions.state.get(draft.key)
|
||||
injected = [row for row in stored.messages if row.get("role") == "user"][1:]
|
||||
assert [public_history_message(row)["content"] for row in injected] == ["intentionally identical text"] * 2
|
||||
assert [row[INBOUND_META_TURN_ID] for row in injected] == ["first-input", "second-input"]
|
||||
assert [row["timestamp"] for row in injected] == ["2026-10-18T19:00:00"] * 2
|
||||
assert pending_followups(stored) == []
|
||||
provider.chat_stream_with_retry.assert_awaited_once()
|
||||
finally:
|
||||
await loop.aclose()
|
||||
@@ -522,6 +522,32 @@ def test_latest_page_reads_active_chunk_once(tmp_path, monkeypatch) -> None:
|
||||
assert read_chunk_ids == ["active"]
|
||||
|
||||
|
||||
def test_cold_complete_page_does_not_parse_unselected_transcript_files(tmp_path, monkeypatch) -> None:
|
||||
key = "websocket:cold-bounded-page"
|
||||
_write_segmented_turns(tmp_path, monkeypatch, key, "cold-bounded-page", 12)
|
||||
original = transcript_module._read_transcript_file
|
||||
reads: list[Path] = []
|
||||
|
||||
def track_read(path):
|
||||
reads.append(path)
|
||||
return original(path)
|
||||
|
||||
def fail_if_loaded():
|
||||
raise AssertionError("complete pages must not load canonical history")
|
||||
|
||||
monkeypatch.setattr(transcript_module, "_read_transcript_file", track_read)
|
||||
latest = build_webui_thread_response(key, limit=1, session_messages_loader=fail_if_loaded)
|
||||
|
||||
assert latest is not None
|
||||
assert _message_contents(latest) == _numbered_turn_texts(12, 12)
|
||||
assert reads == [transcript_module.webui_transcript_path(key)]
|
||||
transcript_module.build_prompt_index(key, session_messages_loader=fail_if_loaded)
|
||||
reads.clear()
|
||||
warmed = build_webui_thread_response(key, limit=1, session_messages_loader=fail_if_loaded)
|
||||
assert warmed == latest
|
||||
assert reads == [transcript_module.webui_transcript_path(key)]
|
||||
|
||||
|
||||
def test_page_cursor_survives_active_rotation_after_latest_page(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
|
||||
@@ -9,6 +9,7 @@ from websockets.http11 import Request
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui import transcript
|
||||
from nanobot.webui.client_contract import webui_contract
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
@@ -122,3 +123,83 @@ def test_summary_deltas_rebuild_after_append_rewrite_eviction_and_delete(tmp_pat
|
||||
assert transcript.prompt_index_response(key, replaced["revision"])["replaceFrom"] == 0
|
||||
transcript.delete_webui_transcript(key)
|
||||
assert transcript.prompt_index_response(key, replaced["revision"])["prompts"] == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("input_id", [None, "injected-guidance"])
|
||||
def test_recovered_prompt_identity_time_and_cursor_survive_pages(tmp_path, monkeypatch, input_id):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:recovered-navigation"
|
||||
messages = [{"role": "system", "content": "context"}]
|
||||
for i in range(2):
|
||||
user = {"role": "user", "content": "same guidance", "timestamp": f"2026-06-02T10:0{i}:00+00:00"}
|
||||
if input_id:
|
||||
user["webui_turn_id"] = f"{input_id}-{i}"
|
||||
messages.extend([user, {"role": "assistant", "content": f"answer {i}"}])
|
||||
transcript.append_transcript_object(key, {"event": "message", "text": f"answer {i}", "turn_id": f"execution-{i}"})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end", "turn_id": f"execution-{i}"})
|
||||
def loader():
|
||||
return messages
|
||||
|
||||
cold_page = transcript.build_webui_thread_response(key, limit=1, session_messages_loader=loader)
|
||||
index = transcript.build_prompt_index(key, session_messages_loader=loader)
|
||||
assert transcript.build_webui_thread_response(key, limit=1, session_messages_loader=loader) == cold_page
|
||||
assert len(index) == 2
|
||||
assert index[0]["id"] != index[1]["id"]
|
||||
assert [prompt["createdAt"] for prompt in index] == [1780394400000, 1780394460000]
|
||||
for position, prompt in enumerate(index):
|
||||
page = transcript.build_webui_thread_response(key, after=prompt["cursor"], limit=1, session_messages_loader=loader)
|
||||
user = next(event for event in page["events"] if event["event"] == "user_message")
|
||||
assert user["projection_id"] == prompt["id"]
|
||||
assert user["created_at_ms"] == prompt["createdAt"]
|
||||
assert user.get("turn_id") == (f"{input_id}-{position}" if input_id else None)
|
||||
assert transcript.build_prompt_index(key, session_messages_loader=loader) == index
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recovered_public_index_and_page_validators_include_canonical_timestamp(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:canonical-revision"
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create(key)
|
||||
session.messages = [
|
||||
{"role": "user", "content": "guidance", "webui_turn_id": "input", "timestamp": "2026-06-02T10:00:00+00:00"},
|
||||
{"role": "assistant", "content": "answer"},
|
||||
]
|
||||
manager.save(session)
|
||||
for event in ({"event": "message", "text": "answer"}, {"event": "turn_end"}):
|
||||
transcript.append_transcript_object(key, event)
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=manager,
|
||||
static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json",
|
||||
default_restrict_to_workspace=False, runtime_model_name=None,
|
||||
runtime_surface="browser", runtime_capabilities_overrides=None,
|
||||
)
|
||||
gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60
|
||||
auth = [("Authorization", "Bearer test-token")]
|
||||
base = "/api/sessions/websocket%3Acanonical-revision/webui-thread"
|
||||
initial = {}
|
||||
for path in (base, base + "/prompts"):
|
||||
response = await gateway.http._dispatch_session_routes(Request(path, Headers(auth)), path)
|
||||
assert response.status_code == 200
|
||||
initial[path] = response
|
||||
unchanged = await gateway.http._dispatch_session_routes(
|
||||
Request(path, Headers([*auth, ("If-None-Match", response.headers["ETag"])])), path,
|
||||
)
|
||||
assert unchanged.status_code == 304
|
||||
# A canonical-only update must invalidate the recovered display even when
|
||||
# transcript artifacts and the session's updated_at are unchanged.
|
||||
session.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00"
|
||||
manager.save(session)
|
||||
changed = {}
|
||||
for path, previous in initial.items():
|
||||
response = await gateway.http._dispatch_session_routes(
|
||||
Request(path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["ETag"] != previous.headers["ETag"]
|
||||
changed[path] = json.loads(response.body)
|
||||
user = next(event for event in changed[base]["events"] if event["event"] == "user_message")
|
||||
prompt = changed[base + "/prompts"]["prompts"][0]
|
||||
assert user["created_at_ms"] == prompt["createdAt"] == 1780394460000
|
||||
assert user["projection_id"] == prompt["id"]
|
||||
assert prompt["id"] == json.loads(initial[base + "/prompts"].body)["prompts"][0]["id"]
|
||||
Reference in new issue
Block a user