Files
DeepTutor/tests/capabilities/test_mastery_packet_cache_prefix.py
Antonio-Faure 88f649283c fix(mastery): keep an unchanged lesson packet in place so requests stay cacheable
prepare_model_request removed and re-appended the lesson packet (and its
original-page images) at the end of every model request. Each tool round
therefore moved ~3.3K tokens of packet and pages behind the new tool
results, and the next turn removed the stored packet from history, so no
request was a prefix extension of the previous one and every round re-paid
the packet and everything after it.

Deliver the packet like a runtime snapshot: an unchanged packet stays at
the position where it was first sent (within the turn and in replayed
history), and only a changed packet replaces it. The page images are
projected right after the packet instead of at the end of the request.

Refs #3186
2026-12-02 17:38:54 +08:00

194 lines
7.8 KiB
Python

"""The lesson packet must not break the append-only growth of model requests.
Provider prompt caches reuse a request only up to its first byte that differs
from an earlier request. Every model round of a mastery turn, and the first
round of the next turn, must therefore extend the previous request rather than
rewrite it: the source packet and its original pages stay where they were first
sent, and only a changed packet is delivered again.
"""
from __future__ import annotations
import json
import os
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from deeptutor.capabilities.mastery.history import project_mastery_replay
from deeptutor.capabilities.mastery.pipeline import MasteryLoopPipeline
from deeptutor.core.context import UnifiedContext
from deeptutor.learning import lesson_evidence, policy, storage
from tests.agents.chat.test_agent_loop import _isolated_runtime as _isolated_runtime
from tests.agents.chat.test_agent_loop import _llm_chunk, _Registry, _run, _ScriptedChatClient
def _evidence(evidence_id: str = "verified") -> dict:
page_text = "The learning curve flattens as practice accumulates. " * 60
return {
"id": evidence_id,
"status": "ready",
"knowledge_point_id": "kp",
"sources": [
{
"ref": {"kb_ref": "kb", "document_key": "book.pdf", "page_index": index},
"quote": "The learning curve flattens",
"text": page_text,
"supports": "Defines the learning curve.",
}
for index in range(4)
],
"coverage": {"complete": True, "scope": "objective", "focus": "", "missing": ""},
"created_at": 1700000000.0,
}
def _pages(_sources) -> dict:
return {
"role": "user",
"content": [
{"type": "text", "text": "Original PDF pages for the verified active objective."},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,UEFHRQ=="}},
],
}
@pytest.fixture
def lesson(monkeypatch):
progress = SimpleNamespace(book_id="path", modules=[object()], lesson_evidence={})
store = SimpleNamespace(
load=Mock(return_value=progress),
get_topic=Mock(return_value=SimpleNamespace(sources=[])),
)
monkeypatch.setattr(storage, "LearningStore", lambda: store)
monkeypatch.setattr(
policy, "next_objective", lambda _: SimpleNamespace(knowledge_point_id="kp")
)
monkeypatch.setattr(lesson_evidence, "selected_scope", Mock(return_value={"selected": ["b"]}))
cache = Mock(return_value=_evidence())
monkeypatch.setattr(lesson_evidence, "cached_lesson", cache)
monkeypatch.setattr(lesson_evidence, "image_message", _pages)
return SimpleNamespace(cache=cache)
def _client(tool_rounds: int) -> _ScriptedChatClient:
rounds = [
[
_llm_chunk(
tool_calls=[
{"id": f"call{i}", "name": "web_search", "arguments": f'{{"query":"q{i}"}}'}
],
finish_reason="tool_calls",
)
]
for i in range(tool_rounds)
]
return _ScriptedChatClient(
[*rounds, [_llm_chunk(content="A source-backed explanation.", finish_reason="stop")]]
)
async def _turn(monkeypatch, client, *, history=None, message="Teach me the learning curve."):
pipeline = MasteryLoopPipeline(language="en")
pipeline.model = "gpt-4o" # A window the request fits: no context-guard trimming.
pipeline.registry = _Registry()
monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _: ["web_search"])
monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
monkeypatch.setattr(pipeline, "_capability_finish_instruction", lambda *_: None)
context = UnifiedContext(
session_id="s", user_message=message, metadata={"mastery_path_id": "path"}
)
if history is not None:
context.runtime.model_history = project_mastery_replay(history, keep_snapshots=True)
await _run(pipeline, context)
return context
def _wire(call: dict) -> list[str]:
return [json.dumps(message, ensure_ascii=False, sort_keys=True) for message in call["messages"]]
def prefix_report(calls: list[dict]) -> list[tuple[int, int, int, int]]:
"""``(common_messages, len_prev_messages, common_chars, prev_chars)`` per pair."""
report = []
for previous, current in zip(calls, calls[1:]):
a, b = _wire(previous), _wire(current)
common = 0
while common < min(len(a), len(b)) and a[common] == b[common]:
common += 1
flat_a, flat_b = "".join(a), "".join(b)
chars = 0
while chars < min(len(flat_a), len(flat_b)) and flat_a[chars] == flat_b[chars]:
chars += 1
report.append((common, len(a), chars, len(flat_a)))
return report
PRINT = bool(os.getenv("MASTERY_PREFIX_REPORT"))
def _print(calls, report):
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
for n, call in enumerate(calls):
shape = []
for m in call["messages"]:
text = m["content"] if isinstance(m.get("content"), str) else json.dumps(m)
tag = "PACKET" if "VERIFIED ACTIVE" in text else ("PAGES" if "UEFHRQ" in text else "")
shape.append(f"{m['role'][0]}{tag and ':' + tag}({len(enc.encode(text))})")
print(f"req{n}", " ".join(shape))
for n, (common, prev, chars, flat) in enumerate(report):
a, b = "".join(_wire(calls[n])), "".join(_wire(calls[n + 1]))
print(
f"req{n}->req{n + 1}: common msgs {common}/{prev}; common tokens "
f"{len(enc.encode(a[:chars]))}/{len(enc.encode(a))}; next total {len(enc.encode(b))}"
)
@pytest.mark.asyncio
async def test_requests_grow_append_only_within_and_across_turns(monkeypatch, lesson):
first = _client(3)
turn = await _turn(monkeypatch, first)
second = _client(1)
await _turn(monkeypatch, second, history=turn.runtime.model_turn["messages"], message="Go on.")
calls = [*first.calls, *second.calls]
report = prefix_report(calls)
if PRINT:
_print(calls, report)
for common, previous, _chars, _flat in report:
assert common == previous, report
# The packet and its pages were each sent once, at one position.
for call in calls:
wire = json.dumps(call["messages"])
assert wire.count("VERIFIED ACTIVE LESSON SOURCE PACKET") == 1
assert wire.count("UEFHRQ==") == 1
# As before, the first round ends with the learner's words, then the packet
# and its pages.
tail = first.calls[0]["messages"][-3:]
assert tail[0]["content"].startswith("Teach me the learning curve.")
assert "VERIFIED ACTIVE" in tail[1]["content"] and "UEFHRQ==" in json.dumps(tail[2])
assert all("_lesson" not in key for call in calls for m in call["messages"] for key in m)
@pytest.mark.asyncio
async def test_changed_packet_is_redelivered_once_and_growth_resumes(monkeypatch, lesson):
# A tool (e.g. mastery_prepare_lesson) changes the packet after round two.
lesson.cache.side_effect = [_evidence("first")] * 2 + [_evidence("second")] * 3
client = _client(3)
await _turn(monkeypatch, client)
report = prefix_report(client.calls)
if PRINT:
_print(client.calls, report)
packet_at = next(
i for i, m in enumerate(client.calls[0]["messages"]) if "VERIFIED ACTIVE" in str(m)
)
assert [common == previous for common, previous, *_ in report] == [True, False, True]
assert report[1][0] == packet_at # Only the replaced packet and what followed it.
for call in client.calls[2:]:
wire = json.dumps(call["messages"])
assert wire.count("VERIFIED ACTIVE LESSON SOURCE PACKET") == 1
packet = next(m["content"] for m in call["messages"] if "VERIFIED ACTIVE" in str(m))
assert '"id": "second"' in packet and '"id": "first"' not in wire