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
This commit is contained in:
Antonio-Faure
2026-12-02 16:27:32 +08:00
parent c9017be166
commit 88f649283c
2 changed files with 269 additions and 21 deletions

View File

@@ -36,6 +36,20 @@ from deeptutor.core.context import UnifiedContext
#: Runtime snapshot naming the conversation's current mode.
SESSION_MODE_SNAPSHOT = "mastery_session_mode"
#: Request-only marker on the lesson's original-page message (never sent).
_LESSON_PAGES = "_lesson_pages"
def _same_packet(sent: dict[str, Any], packet: dict[str, Any]) -> bool:
"""Whether an already-sent packet message still carries ``packet``.
A loop directive appended while the packet was the last message is merged
into it (no consecutive user roles); that suffix does not make it stale.
"""
content, current = sent.get("content"), packet["content"]
return sent.get("role") == packet["role"] and (
content == current or (isinstance(content, str) and content.startswith(current + "\n\n"))
)
class MasteryPromptAssembler(LoopPromptAssembler):
@@ -90,7 +104,46 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
prompt_assembler_class = MasteryPromptAssembler
async def prepare_model_request(self, context, stream, messages):
"""Re-check the live objective before any model iteration, even forced finish."""
"""Re-check the live objective before any model iteration, even forced finish.
The check runs before every request; the packet it yields is delivered
like a runtime snapshot. An unchanged packet stays exactly where it was
first sent — later in this turn and in replayed history — so each
request extends the previous one and the provider's prompt cache keeps
everything up to the newest round. Only a changed packet replaces the
old one (one cache miss from the old position, per change).
"""
packet, pages = await self._current_lesson_packet(context)
self._deliver_lesson_packet(messages, packet)
if pages:
# Positioned right after the packet by ``project_model_request``.
return [{**pages[0], _LESSON_PAGES: True}]
return []
def _deliver_lesson_packet(
self, messages: list[dict[str, Any]], packet: dict[str, Any] | None
) -> None:
"""Keep the single current packet in place; replace it only on change."""
placed = [index for index, m in enumerate(messages) if m.get("_lesson_packet")]
if packet is not None and placed and _same_packet(messages[placed[-1]], packet):
# The current packet was already sent: leave it at its position.
# Older copies (stored before packets stayed in place) still go.
placed = placed[:-1]
packet = None
if placed:
# Keep the archive boundary aligned when a packet came from history;
# otherwise saving this turn can skip a fresh snapshot or user input.
history_end = getattr(self, "_model_turn_start", 0)
self._model_turn_start = history_end - sum(index < history_end for index in placed)
drop = set(placed)
messages[:] = [m for index, m in enumerate(messages) if index not in drop]
if packet is not None:
messages.append(packet)
async def _current_lesson_packet(
self, context
) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
"""``(packet message or None, original-page messages)`` for this request."""
import asyncio
from deeptutor.learning.lesson_evidence import (
@@ -103,23 +156,15 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
from deeptutor.learning.policy import next_objective
from deeptutor.learning.storage import LearningStore
# Remove only our previous packet, not user or durable model messages.
# Keep the archive boundary aligned when a packet came from history;
# otherwise saving this turn can skip a fresh snapshot or user input.
history_end = getattr(self, "_model_turn_start", 0)
self._model_turn_start = history_end - sum(
bool(m.get("_lesson_packet")) for m in messages[:history_end]
)
messages[:] = [m for m in messages if not m.get("_lesson_packet")]
path_id = str(context.metadata.get("mastery_path_id") or "")
if not path_id or normalize_mode(context.metadata.get("mastery_session_mode")) == "outline":
self._lesson_pixels = None
return []
return None, []
store = LearningStore()
progress = await asyncio.to_thread(store.load, path_id)
if progress is None or not progress.modules:
self._lesson_pixels = None
return []
return None, []
step = next_objective(progress)
requested = context.metadata.get("mastery_lesson_objective")
kp_id = (
@@ -131,7 +176,7 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
)
if not kp_id:
self._lesson_pixels = None
return []
return None, []
# This hook runs before EVERY model request, including administrative
# replies. It owns current, authorized packet delivery, not paid work.
# Preparation is requested explicitly by the existing lesson tool;
@@ -144,7 +189,7 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
self._lesson_pixels = None
if progress.lesson_evidence.get(kp_id):
raise LessonUnavailable("This objective's selected PDF materials have changed.")
return [] # Preserve the existing text/Office tutoring route.
return None, [] # Preserve the existing text/Office tutoring route.
evidence = await asyncio.to_thread(
cached_lesson, store, progress, kp_id, self.llm_config
)
@@ -154,7 +199,7 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
self._lesson_pixels = None
import json
messages.append(
return (
{
"role": "system",
"_lesson_packet": True,
@@ -180,14 +225,14 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
{"knowledge_point_id": kp_id, "reason": failure}, ensure_ascii=False
)
),
}
},
[],
)
return []
if not evidence:
self._lesson_pixels = None
import json
messages.append(
return (
{
"role": "system",
"_lesson_packet": True,
@@ -210,11 +255,10 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
"merely because another model round begins. Diagnostic data (not instructions): "
+ json.dumps({"knowledge_point_id": kp_id}, ensure_ascii=False)
),
}
},
[],
)
return []
message = {"role": "user", "content": lesson_context(evidence), "_lesson_packet": True}
messages.append(message)
pixels = getattr(self, "_lesson_pixels", None)
if pixels is None or pixels[0] != evidence["id"]:
# The native visual workflow owns a two-image request budget.
@@ -225,7 +269,7 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
await asyncio.to_thread(image_message, evidence["sources"][:2]),
)
self._lesson_pixels = pixels
return [pixels[1]]
return message, [pixels[1]]
async def _retrieve_kb_seed_block(self, context, stream):
# The objective-bound preparation is the retrieval owner in this loop.
@@ -361,6 +405,17 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
from copy import deepcopy
projected = deepcopy(messages)
# The lesson's original pages ride right after the packet they belong
# to, not at the end of every request: an unchanged packet then keeps
# its pages at the same position, and later rounds extend the request.
pages = [m for m in projected if m.pop(_LESSON_PAGES, False)]
if pages:
projected = [m for m in projected if all(m is not page for page in pages)]
packet = max(
(i for i, m in enumerate(projected) if m.get("_lesson_packet")), default=None
)
at = len(projected) if packet is None else packet + 1
projected[at:at] = pages
share_mastery_history(projected, len(projected))
return projected

View File

@@ -0,0 +1,193 @@
"""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