fix(sessions): preserve cross-session input ownership and history (#6613)
* fix(webui): reconcile cross-session history by message ID * fix(sessions): preserve target authority and input ownership Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed. Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430. * fix(sessions): complete input identity integration across boundaries Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery. Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run. * fix(sessions): unify input recording and block remote commands * fix(webui): keep input ownership checks page-bounded Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages. Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed. * fix(webui): preserve response ownership during history replay * fix: resolve strict typing in response replay * fix: preserve continuation ownership during recovery * test: diagnose stuck gateway asyncio shutdown * test: retain gateway thread stack diagnostics * test(webui): stabilize native autoscroll browser setup
This commit is contained in:
1 parent
0ce335bf12
commit
394a78e82d
51 files changed
+1412
-334
No files matched your search
@@ -0,0 +1,154 @@
|
||||
from nanobot.webui.transcript import TranscriptReplayStats
|
||||
|
||||
|
||||
def test_grouped_backfill_keeps_response_input_order_in_page_and_index(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:backfill-order"
|
||||
ids = ["input:first", "input:second", "input:third"]
|
||||
messages = [
|
||||
{"role": "user", "content": name, "input_id": input_id}
|
||||
for name, input_id in zip(("first", "second", "third"), ids)
|
||||
] + [{"role": "assistant", "content": "answer"}]
|
||||
history.append(key, {"event": "user", "text": "second", "input_id": ids[1]})
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ids})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
def loader():
|
||||
return messages
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
stats = TranscriptReplayStats()
|
||||
page = history.build(key, limit=1, session_messages_loader=loader, stats=stats)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [event["text"] for event in users] == ["first", "second", "third"]
|
||||
assert [prompt["inputId"] for prompt in index] == ids
|
||||
assert [prompt["id"] for prompt in index] == [event["projection_id"] for event in users]
|
||||
assert stats.parsed_records < 10
|
||||
|
||||
|
||||
def test_identity_backfill_is_not_repeated_by_legacy_answer_matching(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:backfill-duplicate"
|
||||
messages = [
|
||||
{"role": "user", "content": "question", "input_id": "input:one"},
|
||||
{"role": "assistant", "content": "answer"},
|
||||
]
|
||||
history.append(key, {"event": "message", "text": "answer"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ["input:one"]})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
def loader():
|
||||
return messages
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
page = history.build(key, limit=10, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [prompt["inputId"] for prompt in index] == ["input:one"]
|
||||
assert [event["text"] for event in users] == ["question"]
|
||||
assert index[0]["id"] == users[0]["projection_id"]
|
||||
latest = history.build(key, limit=1, session_messages_loader=loader)
|
||||
older = history.build(key, limit=1, before=latest["page"]["before_cursor"], session_messages_loader=loader)
|
||||
paged_users = [event for part in (older, latest) for event in part["events"] if event["event"] == "user_message"]
|
||||
assert [event["projection_id"] for event in paged_users] == [index[0]["id"]]
|
||||
|
||||
|
||||
def test_empty_response_inputs_do_not_use_legacy_answer_matching(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:empty-response-inputs"
|
||||
messages = [
|
||||
{"role": "user", "content": "question", "input_id": "input:one"},
|
||||
{"role": "assistant", "content": "answer"},
|
||||
]
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": []})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
history.append(key, {"event": "message", "text": "answer"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
|
||||
def loader():
|
||||
return messages
|
||||
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
page = history.build(key, limit=10, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [prompt["inputId"] for prompt in index] == ["input:one"]
|
||||
assert [event["projection_id"] for event in users] == [index[0]["id"]]
|
||||
latest = history.build(key, limit=1, session_messages_loader=loader)
|
||||
older = history.build(key, limit=1, before=latest["page"]["before_cursor"], session_messages_loader=loader)
|
||||
assert not [event for event in older["events"] if event["event"] == "user_message"]
|
||||
assert [event["projection_id"] for event in latest["events"] if event["event"] == "user_message"] == [index[0]["id"]]
|
||||
|
||||
|
||||
def test_truncated_turn_applies_plan_when_reference_anchor_is_dropped(history, tmp_path, monkeypatch):
|
||||
from nanobot.webui import transcript
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 5)
|
||||
key = "websocket:truncated-backfill"
|
||||
ids = ["input:a", "input:b", "input:c"]
|
||||
messages = [{"role": "user", "content": text, "input_id": ident}
|
||||
for text, ident in zip(("A", "B", "C"), ids)]
|
||||
history.append(key, {"event": "user", "text": "B", "input_id": ids[1]})
|
||||
history.append(key, {"event": "message", "text": "first", "response_input_ids": ids[:2]})
|
||||
for i in range(12):
|
||||
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
|
||||
history.append(key, {"event": "message", "text": "last", "response_input_ids": ids[2:]})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
index = history.prompts(key, session_messages_loader=lambda: messages)
|
||||
page = history.build(key, limit=10, session_messages_loader=lambda: messages)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert page["page"]["truncated_oversized_turn"]
|
||||
assert not page["page"]["has_more_before"]
|
||||
assert [event["text"] for event in users] == ["A", "B", "C"]
|
||||
assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index]
|
||||
|
||||
|
||||
def test_truncated_turn_recovers_even_if_all_missing_references_were_dropped(history, tmp_path, monkeypatch):
|
||||
from nanobot.webui import transcript
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 4)
|
||||
key = "websocket:truncated-no-reference"
|
||||
messages = [{"role": "user", "content": "A", "input_id": "a"}]
|
||||
history.append(key, {"event": "user", "text": "B", "input_id": "b"})
|
||||
history.append(key, {"event": "message", "text": "old", "response_input_ids": ["a", "b"]})
|
||||
for i in range(10):
|
||||
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
|
||||
history.append(key, {"event": "message", "text": "new"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
index = history.prompts(key, session_messages_loader=lambda: messages)
|
||||
page = history.build(key, limit=10, session_messages_loader=lambda: messages)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert page["page"]["truncated_oversized_turn"]
|
||||
assert [event["text"] for event in users] == ["A", "B"]
|
||||
assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index]
|
||||
|
||||
|
||||
def test_completed_stream_compaction_and_truncation_keep_shared_backfill_anchor(history, tmp_path, monkeypatch):
|
||||
from nanobot.webui import transcript
|
||||
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:stream-anchor"
|
||||
ids = ["input:a", "input:b", "input:c"]
|
||||
messages = [{"role": "user", "content": text, "input_id": ident}
|
||||
for text, ident in zip(("A", "B", "C"), ids)]
|
||||
history.append(key, {"event": "user", "text": "B", "input_id": ids[1]})
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ids})
|
||||
for i in range(10):
|
||||
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
|
||||
for text in ("one", "two", "three"):
|
||||
history.append(key, {"event": "delta", "text": text})
|
||||
history.append(key, {"event": "stream_end", "text": "onetwothree"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
|
||||
def loader():
|
||||
return messages
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
stats = TranscriptReplayStats()
|
||||
full = history.build(key, limit=10, session_messages_loader=loader, stats=stats)
|
||||
assert stats.compacted_delta_records == 3
|
||||
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 8)
|
||||
truncated_stats = TranscriptReplayStats()
|
||||
truncated = history.build(key, limit=10, session_messages_loader=loader, stats=truncated_stats)
|
||||
assert truncated["page"]["truncated_oversized_turn"]
|
||||
assert truncated_stats.compacted_delta_records == 3
|
||||
expected_ids = [prompt["id"] for prompt in index]
|
||||
assert [prompt["inputId"] for prompt in index] == ids
|
||||
for page in (full, truncated):
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [event["text"] for event in users] == ["A", "B", "C"]
|
||||
assert [event["projection_id"] for event in users] == expected_ids
|
||||
@@ -89,6 +89,64 @@ async def test_remote_proxy_with_real_gateway_chat_settings_and_renewal(
|
||||
_stop_gateway(process)
|
||||
|
||||
|
||||
# Test-only injection: report locations without task names, frame data or source.
|
||||
_TASK_DIAGNOSTICS = """
|
||||
import asyncio, os, signal, sys
|
||||
if sys.platform.startswith('linux') and os.name == 'posix':
|
||||
original_run = asyncio.run
|
||||
def diagnostic_run(coro, *args, **kwargs):
|
||||
async def wrapped():
|
||||
loop = asyncio.get_running_loop()
|
||||
def dump_tasks():
|
||||
with open(os.environ['SMOKE_TASK_DIAGNOSTICS'], 'w', encoding='utf-8') as output:
|
||||
print('Gateway async task locations:', file=output)
|
||||
for number, task in enumerate(asyncio.all_tasks(loop), 1):
|
||||
for frame in task.get_stack():
|
||||
code = frame.f_code
|
||||
print(f'{number} {os.path.basename(code.co_filename)} {code.co_name} {frame.f_lineno}', file=output)
|
||||
print('Gateway async task locations end', file=output)
|
||||
loop.add_signal_handler(signal.SIGUSR1, dump_tasks)
|
||||
return await coro
|
||||
return original_run(wrapped(), *args, **kwargs)
|
||||
asyncio.run = diagnostic_run
|
||||
"""
|
||||
|
||||
|
||||
async def _stop_inline_gateway(process: subprocess.Popen[bytes], *, diagnostics: Path, timeout: float = 30) -> None:
|
||||
if process.poll() is not None:
|
||||
return
|
||||
if sys.platform == "win32":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
else:
|
||||
process.terminate()
|
||||
try:
|
||||
await asyncio.to_thread(process.wait, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
if sys.platform.startswith("linux") and os.name == "posix":
|
||||
try:
|
||||
process.send_signal(signal.SIGUSR1)
|
||||
await asyncio.to_thread(process.wait, timeout=1)
|
||||
except (ProcessLookupError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
finally:
|
||||
await asyncio.to_thread(process.wait, timeout=10)
|
||||
if diagnostics.exists():
|
||||
print(diagnostics.read_text(encoding="utf-8"))
|
||||
stacks = diagnostics.with_name("gateway-stacks.log")
|
||||
if stacks.exists():
|
||||
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
|
||||
stacks.read_text(encoding="utf-8"))
|
||||
print("Gateway shutdown stack locations:", frames[-80:])
|
||||
raise
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
@@ -583,7 +641,7 @@ async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during
|
||||
config = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
|
||||
config_path.write_text(json.dumps(config), encoding="utf-8")
|
||||
launcher = """
|
||||
launcher = _TASK_DIAGNOSTICS + """
|
||||
import asyncio, faulthandler, httpx, sys
|
||||
from pathlib import Path
|
||||
from nanobot.session.state import SessionState
|
||||
@@ -615,6 +673,8 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
|
||||
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
|
||||
"LOCALAPPDATA": str(home), "TMP": str(tmp_path), "TEMP": str(tmp_path),
|
||||
"NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1"})
|
||||
diagnostics = tmp_path / "gateway-tasks.log"
|
||||
env["SMOKE_TASK_DIAGNOSTICS"] = str(diagnostics)
|
||||
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
||||
process = None
|
||||
try:
|
||||
@@ -717,23 +777,53 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
|
||||
release_close.set()
|
||||
release_checkpoint.set()
|
||||
try:
|
||||
if process is not None and process.poll() is None:
|
||||
if sys.platform == "win32":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
else:
|
||||
process.terminate()
|
||||
try:
|
||||
# Keep the test model/barrier server live while its client exits.
|
||||
await asyncio.to_thread(process.wait, timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
await asyncio.to_thread(process.wait, timeout=10)
|
||||
stacks = tmp_path / "gateway-stacks.log"
|
||||
if stacks.exists():
|
||||
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
|
||||
stacks.read_text(encoding="utf-8"))
|
||||
print("Gateway shutdown stack locations:", frames[-80:])
|
||||
raise
|
||||
if process is not None:
|
||||
# Keep the model/barrier server live while its client exits.
|
||||
await _stop_inline_gateway(process, diagnostics=diagnostics)
|
||||
finally:
|
||||
await server.cleanup()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not (sys.platform.startswith("linux") and os.name == "posix"), reason="Linux signals only")
|
||||
@pytest.mark.asyncio
|
||||
async def test_inline_gateway_timeout_dumps_tasks_and_reaps(tmp_path: Path, capsys: pytest.CaptureFixture) -> None:
|
||||
(tmp_path / "gateway-stacks.log").write_text(
|
||||
'Thread secret\n File "/private/path/gateway.py", line 42 in blocked\n secret source\n'
|
||||
)
|
||||
log_path = tmp_path / "diagnostic.log"
|
||||
diagnostics = tmp_path / "tasks.log"
|
||||
script = _TASK_DIAGNOSTICS + """
|
||||
async def blocked():
|
||||
secret_variable = 'must-not-appear-in-diagnostics'
|
||||
await asyncio.Event().wait()
|
||||
async def main():
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
asyncio.create_task(blocked(), name='private-task-name')
|
||||
print('ready', flush=True)
|
||||
await asyncio.Event().wait()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
with log_path.open("wb") as log:
|
||||
process = subprocess.Popen([sys.executable, "-c", script], stdout=log, stderr=subprocess.STDOUT,
|
||||
env={**os.environ, "SMOKE_TASK_DIAGNOSTICS": str(diagnostics)})
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
while "ready" not in log_path.read_text() and time.monotonic() < deadline:
|
||||
await asyncio.sleep(0.01)
|
||||
assert "ready" in log_path.read_text()
|
||||
with pytest.raises(subprocess.TimeoutExpired):
|
||||
await _stop_inline_gateway(process, diagnostics=diagnostics, timeout=0.1)
|
||||
assert process.returncode is not None
|
||||
captured = capsys.readouterr().out
|
||||
assert "('gateway.py', '42', 'blocked')" in captured
|
||||
assert "/private/path" not in captured
|
||||
assert "secret source" not in captured
|
||||
output = diagnostics.read_text()
|
||||
assert "Gateway async task locations end" in output
|
||||
assert "<string> blocked " in output
|
||||
assert "private-task-name" not in output
|
||||
assert "must-not-appear-in-diagnostics" not in output
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
@@ -13,16 +13,21 @@ from nanobot.webui.client_contract import webui_contract
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
def test_complete_index_and_bidirectional_pages_without_loading_model_messages(history, tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize("identified", [False, True])
|
||||
def test_complete_index_and_bidirectional_pages_without_loading_model_messages(history, tmp_path, monkeypatch, identified):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:navigation"
|
||||
for i in range(120):
|
||||
history.append(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}"})
|
||||
history.append(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}"})
|
||||
input_identity = {"input_id": f"user:t{i}"} if identified else {}
|
||||
response_identity = {"response_input_ids": [f"user:t{i}"]} if identified else {}
|
||||
history.append(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}", **input_identity})
|
||||
history.append(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}", **response_identity})
|
||||
history.append(key, {"event": "turn_end", "chat_id": "navigation", "turn_id": f"t{i}"})
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("page scanned full history")))
|
||||
latest = history.build(key, limit=3)
|
||||
index = history.prompts(key)
|
||||
assert len(index) == 120
|
||||
latest = history.build(key, limit=3)
|
||||
assert len(latest["events"]) < len(index)
|
||||
target = index[42]
|
||||
stats = transcript.TranscriptReplayStats()
|
||||
@@ -148,6 +153,64 @@ def test_recovered_prompt_identity_time_and_cursor_survive_pages(history, tmp_pa
|
||||
assert history.prompts(key, session_messages_loader=loader) == index
|
||||
|
||||
|
||||
@pytest.mark.parametrize("second_recorded", [True, False])
|
||||
@pytest.mark.parametrize("grouped", [True, False])
|
||||
def test_cross_session_inputs_are_reconciled_by_identity_across_turns(
|
||||
history, tmp_path, monkeypatch, second_recorded, grouped,
|
||||
):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:cross-session-replay"
|
||||
provenance = [
|
||||
{"message_id": f"message-{i}", "session": {"id": "handle_" + "1" * 32, "name": "luma"}}
|
||||
for i in range(2)
|
||||
]
|
||||
input_ids = [f"session-message:{source['message_id']}" for source in provenance]
|
||||
messages = [
|
||||
{"role": "user", "content": "original question", "input_id": "user:original"},
|
||||
{"role": "assistant", "content": "original answer"},
|
||||
]
|
||||
history.append(key, {"event": "user", "text": "original question", "input_id": "user:original"})
|
||||
for i, source in enumerate(provenance):
|
||||
messages.append({"role": "user", "content": "same message", "session_message": source, "input_id": input_ids[i]})
|
||||
if not grouped or i == 1:
|
||||
messages.append({"role": "assistant", "content": f"answer {i}"})
|
||||
if i == 0 or second_recorded:
|
||||
history.append(key, {"event": "user", "text": "same message", "session_message": source, "input_id": input_ids[i]})
|
||||
history.append(key, {"event": "message", "text": "original answer", "response_input_ids": ["user:original"]})
|
||||
assert [prompt["answerPreview"] for prompt in history.prompts(key)] == ["original answer"] + [""] * (2 if second_recorded else 1)
|
||||
history.append(key, {"event": "turn_end"})
|
||||
for i in ([1] if grouped else range(2)):
|
||||
history.append(key, {"event": "message", "text": f"answer {i}", "response_input_ids": input_ids if grouped else [input_ids[i]]})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
|
||||
def loader():
|
||||
assert not second_recorded, "complete display history must not load model history"
|
||||
return messages
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
if second_recorded:
|
||||
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("page scanned full history")))
|
||||
latest = history.build(key, limit=1, session_messages_loader=loader)
|
||||
assert [event["text"] for event in latest["events"] if event["event"] == "user_message"] == (
|
||||
[] if second_recorded else ["same message"]
|
||||
)
|
||||
page = history.build(key, limit=10, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [user["text"] for user in users] == ["original question", "same message", "same message"]
|
||||
assert [user["provenance"]["session_message"]["message_id"] for user in users[1:]] == [
|
||||
"message-0", "message-1",
|
||||
]
|
||||
prompts = history.prompts(key, session_messages_loader=loader)
|
||||
assert [prompt["id"] for prompt in prompts] == [user["projection_id"] for user in users]
|
||||
assert [prompt["answerPreview"] for prompt in prompts] == ["original answer", "answer 1" if grouped else "answer 0", "answer 1"]
|
||||
assert [prompt["inputId"] for prompt in prompts] == ["user:original", *input_ids]
|
||||
revision = history.revision(key)
|
||||
history.append(key, {"event": "user", "text": "same message", "session_message": provenance[0], "input_id": input_ids[0]})
|
||||
assert history.revision(key) == revision
|
||||
assert history.build(key, limit=10, session_messages_loader=loader) == page
|
||||
assert history.build(key, limit=1, session_messages_loader=loader) == latest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recovered_public_index_and_page_validators_include_canonical_timestamp(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
@@ -331,3 +394,26 @@ def test_indexed_backfill_preserves_unique_in_suffix_matching(history, tmp_path,
|
||||
assert [user["text"] for user in users] == (["question 2"] if with_anchor else [])
|
||||
if with_anchor:
|
||||
assert users[0]["projection_id"] == prompts[-1]["id"]
|
||||
|
||||
|
||||
def test_recover_multiple_missing_inputs_for_one_answer_across_pages(history, tmp_path, monkeypatch):
|
||||
"""A grouped answer can stand for multiple inputs absent from display history."""
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:missing-grouped-inputs"
|
||||
ids = ["session-message:first", "session-message:second"]
|
||||
messages = [
|
||||
{"role": "user", "content": "first", "input_id": ids[0]},
|
||||
{"role": "user", "content": "second", "input_id": ids[1]},
|
||||
{"role": "assistant", "content": "shared answer"},
|
||||
]
|
||||
history.append(key, {"event": "message", "text": "shared answer", "response_input_ids": ids})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
def loader():
|
||||
return messages
|
||||
|
||||
page = history.build(key, limit=1, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [event["text"] for event in users] == ["first", "second"]
|
||||
prompts = history.prompts(key, session_messages_loader=loader)
|
||||
assert [prompt["inputId"] for prompt in prompts] == ids
|
||||
assert [prompt["id"] for prompt in prompts] == [event["projection_id"] for event in users]
|
||||
Reference in new issue
Block a user