perf(webui): reuse versioned history navigation snapshots
This commit is contained in:
1 parent
103840171b
commit
af68da3280
6 files changed
+288
-103
No files matched your search
@@ -192,8 +192,9 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time
|
||||
manager.save(session)
|
||||
changed = {}
|
||||
for path, previous in initial.items():
|
||||
request_path = path + "?since=" + json.loads(previous.body)["revision"]
|
||||
response = await gateway.http._dispatch_session_routes(
|
||||
Request(path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path,
|
||||
Request(request_path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["ETag"] != previous.headers["ETag"]
|
||||
@@ -203,3 +204,138 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time
|
||||
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"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("missing_user", [False, True])
|
||||
async def test_cached_history_routes_skip_replay_and_canonical_reads(tmp_path, monkeypatch, missing_user):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:cached-history"
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create(key)
|
||||
for i in range(3):
|
||||
session.messages.extend([
|
||||
{"role": "user", "content": f"question {i}", "webui_turn_id": f"input-{i}"},
|
||||
{"role": "assistant", "content": f"answer {i}"},
|
||||
])
|
||||
if not missing_user or i < 2:
|
||||
transcript.append_transcript_object(key, {"event": "user", "text": f"question {i}", "turn_id": f"input-{i}"})
|
||||
transcript.append_transcript_object(key, {"event": "message", "text": f"answer {i}"})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end"})
|
||||
manager.save(session)
|
||||
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%3Acached-history/webui-thread"
|
||||
initial = {}
|
||||
for path in (base + "?direction=latest&limit=2", base + "/prompts"):
|
||||
response = await gateway.http._dispatch_session_routes(Request(path, Headers(auth)), path.split("?")[0])
|
||||
assert response.status_code == 200
|
||||
initial[path] = response
|
||||
prompts = json.loads(initial[base + "/prompts"].body)
|
||||
assert len(prompts["prompts"]) == 3
|
||||
|
||||
def unexpected_work(*args, **kwargs):
|
||||
pytest.fail("unchanged history was rebuilt")
|
||||
|
||||
monkeypatch.setattr(transcript, "_build_prompt_view", unexpected_work)
|
||||
monkeypatch.setattr(transcript, "_read_transcript_file", unexpected_work)
|
||||
monkeypatch.setattr(manager, "read_session_file", unexpected_work)
|
||||
monkeypatch.setattr("nanobot.webui.ws_http.build_webui_thread_response", unexpected_work)
|
||||
for path, previous in initial.items():
|
||||
conditional = path + ("&" if "?" in path else "?") + "since=" + json.loads(previous.body)["revision"]
|
||||
response = await gateway.http._dispatch_session_routes(
|
||||
Request(conditional, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path.split("?")[0],
|
||||
)
|
||||
assert response.status_code == 304 and not response.body
|
||||
# An ordinary directory read also reuses the view, with or without `since`.
|
||||
for suffix in ("", "?since=" + prompts["revision"]):
|
||||
response = await gateway.http._dispatch_session_routes(Request(base + "/prompts" + suffix, Headers(auth)), base + "/prompts")
|
||||
assert response.status_code == 200
|
||||
data = json.loads(response.body)
|
||||
assert data["prompts"] == ([] if suffix else prompts["prompts"])
|
||||
assert data["replaceFrom"] == (3 if suffix else 0)
|
||||
# Eviction must not turn a valid conditional request into a replay either.
|
||||
transcript._PROMPT_SNAPSHOTS.clear()
|
||||
for path, previous in initial.items():
|
||||
response = await gateway.http._dispatch_session_routes(
|
||||
Request(path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path.split("?")[0],
|
||||
)
|
||||
assert response.status_code == 304 and not response.body
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("endpoint", ["", "/prompts"])
|
||||
async def test_canonical_change_during_recovery_is_not_cached(tmp_path, monkeypatch, endpoint):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:racing-history"
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create(key)
|
||||
session.messages = [
|
||||
{"role": "user", "content": "question", "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 = Headers([("Authorization", "Bearer test-token")])
|
||||
original_read = manager.read_session_file
|
||||
changed = False
|
||||
|
||||
def read_and_commit(key):
|
||||
nonlocal changed
|
||||
data = original_read(key)
|
||||
if not changed:
|
||||
changed = True
|
||||
session.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00"
|
||||
manager.save(session)
|
||||
return data
|
||||
|
||||
monkeypatch.setattr(manager, "read_session_file", read_and_commit)
|
||||
path = "/api/sessions/websocket%3Aracing-history/webui-thread" + endpoint
|
||||
mixed = await gateway.http._dispatch_session_routes(Request(path, auth), path)
|
||||
assert changed and mixed.status_code == 200
|
||||
assert "ETag" not in mixed.headers and "revision" not in json.loads(mixed.body)
|
||||
current = await gateway.http._dispatch_session_routes(Request(path, auth), path)
|
||||
assert current.status_code == 200 and current.headers["ETag"]
|
||||
data = json.loads(current.body)
|
||||
if endpoint:
|
||||
assert data["prompts"][0]["createdAt"] == 1780394460000
|
||||
else:
|
||||
user = next(event for event in data["events"] if event["event"] == "user_message")
|
||||
assert user["created_at_ms"] == 1780394460000
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_anchor", [False, True])
|
||||
def test_indexed_backfill_preserves_unique_in_suffix_matching(tmp_path, monkeypatch, with_anchor):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:repeated-answers"
|
||||
answers = ["same answer", "anchor answer", "same answer"] if with_anchor else ["same answer"] * 2
|
||||
messages = []
|
||||
for position, answer in enumerate(answers):
|
||||
user = {"role": "user", "content": f"question {position}", "webui_turn_id": f"input-{position}"}
|
||||
messages.extend([user, {"role": "assistant", "content": answer}])
|
||||
if position < len(answers) - 1:
|
||||
transcript.append_transcript_object(key, {"event": "user", "text": user["content"], "turn_id": user["webui_turn_id"]})
|
||||
transcript.append_transcript_object(key, {"event": "message", "text": answer})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end"})
|
||||
prompts = transcript.build_prompt_index(key, session_messages_loader=lambda: messages)
|
||||
# A unique intervening answer advances the alignment past the first duplicate.
|
||||
assert len(prompts) == (len(answers) if with_anchor else 1)
|
||||
page = transcript.build_webui_thread_response(key, limit=1, session_messages=messages)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [user["text"] for user in users] == (["question 2"] if with_anchor else [])
|
||||
if with_anchor:
|
||||
assert users[0]["projection_id"] == prompts[-1]["id"]
|
||||
Reference in new issue
Block a user