Files
DeepTutor/tests/capabilities/test_mastery_memory_route.py
wojiecihuo ce831dd4c3 fix: keep sent runtime snapshots in mastery replay, and keep them small (#2992)
* fix: keep sent runtime snapshots in mastery replay

Mastery replay dropped every runtime snapshot from history and the loop
re-appended them after it, so each follow-up request diverged from the
previous one at message 1 and only tools + system hit the prompt cache.

- project_mastery_replay(keep_snapshots=True) for the tutor request and
  its token accounting; memory material still drops snapshots
- replay_group no longer blanks a tagged mastery_status_snapshot while
  removing the legacy fused suffix
- status snapshot anchors are numbered from the start (occurrence), so a
  later snapshot never changes how an earlier turn is projected

Refs #2922

* fix: keep runtime snapshots out of the mastery history budget

Replayed snapshots stay in the request so follow-up turns extend the cached prefix, but counting them made a large mastery_status snapshot push the history over its 20k budget after two turns; the next turn then paid a memory rewrite and a full prefix miss. The budget now measures the learning history only, as before. Refs #2922

* fix: bound the runtime snapshots kept in mastery history

Keeping sent snapshots out of the history budget entirely let many short
exchanges accumulate them without limit (80 quiz-style turns: 5.4k counted,
62k sent). Dialogue still keeps to the plan; dialogue plus snapshots keep to
twice the plan, and only as far as the model's window allows. Refs #2922

* fix: keep only this turn's state in the mastery status snapshot

Every mastery turn sends a fresh mastery_status snapshot and, since the
replay change, keeps earlier ones in history, so whatever a snapshot
carries is paid for once per turn and then kept. A full status read
repeats fixed guidance (open question, question group, working brief,
intake, teaching guidance and focus) and every default value of every
knowledge point.

The snapshot now drops empty and default values and the fixed guidance.
That guidance lives in named constants and is stated once in a new
mastery_status_guide system block, which also explains the omitted
defaults. Snapshots start with a one-line header; history sharing reads
both the header and the longer notice older sessions stored. An explicit
mastery_status call still returns the full payload.

Measured over 54 recorded snapshots: working briefs 1,454 -> 645 tokens
(median), full outline snapshots 6,352 -> 2,954. The guide adds 861
tokens (en) to the cached system prompt.

Refs #2922

* fix: size the exact tail the way the plan does, and share full reads with compact snapshots

Two gaps left by keeping snapshots in mastery replay (review on #2992):

- Recent-history selection counted kept snapshots in full while the plan
  discounted them, so a session of short exchanges with large snapshots
  archived most of them as soon as selection ran. ContextBuilder now sizes
  the candidate tail through _recent_history_tokens(), and the mastery
  builder answers with the same _plan_tokens() measure.
- Snapshots carry the compact form of map, learner_profile, learning_stages
  and visual_requirements, so a later full mastery_status result never matched
  them exactly. Sharing now also compares a full field's compact form and
  marks such references with "defaults_omitted": true, which the state
  reference notice explains.

Also: rename _next to _compact_next_step, and say in the status guide that
the omitted-default rules cover only what the snapshot includes.

Refs #2922
2026-11-28 12:57:21 +08:00

268 lines
9.9 KiB
Python

"""Mastery history accounting uses the same routed, image-projected replay as the request."""
from copy import deepcopy
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from deeptutor.capabilities.mastery.history import project_mastery_replay
from deeptutor.capabilities.mastery.memory import MasteryContextBuilder, _plan_tokens
from deeptutor.services.llm.image_replay import deduplicate_user_images
from deeptutor.services.session.context_builder import _count_model_context_tokens
from deeptutor.services.session.model_history import replay_history
def _routed_rows():
return [
{"id": 1, "role": "user", "content": "Explain the diagram."},
{
"id": 2,
"role": "assistant",
"content": "The diagram illustrates the mechanism.",
"metadata": {
"model_turn": {
"version": 1,
"route": {"provider": "source-provider", "model": "source-model"},
"messages": [
{"role": "user", "content": "Explain the diagram."},
{
"role": "assistant",
"content": "The diagram illustrates the mechanism.",
"reasoning_content": "route-specific reasoning " * 1000,
"thinking_blocks": [
{
"type": "thinking",
"thinking": "Private thought",
"signature": "opaque-signature",
}
],
},
],
}
},
},
]
@pytest.mark.parametrize(
"route",
[
None,
{"provider": "source-provider", "model": "source-model"},
{"provider": "other-provider", "model": "other-model"},
],
)
def test_mastery_accounting_uses_requested_route_without_mutating_records(route):
rows = _routed_rows()
original = deepcopy(rows)
builder = MasteryContextBuilder(MagicMock())
expected = _count_model_context_tokens(
deduplicate_user_images(project_mastery_replay(replay_history(rows, route=route)))
)
assert builder._model_tokens(rows, route=route) == expected
assert rows == original
def test_route_free_mastery_accounting_keeps_existing_replay_behavior():
rows = _routed_rows()
builder = MasteryContextBuilder(MagicMock())
assert builder._model_tokens(rows) == _count_model_context_tokens(
deduplicate_user_images(project_mastery_replay(replay_history(rows)))
)
@pytest.mark.asyncio
async def test_final_mastery_token_count_projects_duplicate_images_without_changing_history():
image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,aGVsbG8="}}
rows = [
{"id": 1, "role": "user", "content": "Look at the diagram."},
{
"id": 2,
"role": "assistant",
"content": "The same diagram remains relevant.",
"metadata": {
"model_turn": {
"version": 1,
"messages": [
{"role": "user", "content": [deepcopy(image)]},
{"role": "assistant", "content": "The diagram illustrates the mechanism."},
{"role": "user", "content": [deepcopy(image)]},
{"role": "assistant", "content": "The same diagram remains relevant."},
],
}
},
},
]
original = deepcopy(rows)
store = MagicMock()
store.get_session = AsyncMock(
return_value={"compressed_summary": "", "summary_up_to_msg_id": 0}
)
store.get_messages_for_context = AsyncMock(return_value=rows)
store.update_summary = AsyncMock()
builder = MasteryContextBuilder(store)
builder._summarize = AsyncMock()
built = await builder.build(
session_id="synthetic-session",
llm_config=SimpleNamespace(model="synthetic-model", context_window=272000, max_tokens=8192),
)
assert built.token_count == _count_model_context_tokens(
deduplicate_user_images(built.model_history)
)
assert built.model_history == project_mastery_replay(replay_history(rows), keep_snapshots=True)
assert rows == original
builder._summarize.assert_not_awaited()
store.update_summary.assert_not_awaited()
def _snapshot_turn(row_id: int, question: str, answer: str, snapshot: str | None):
messages = []
if snapshot is not None:
messages.append(
{
"role": "user",
"content": f"[Runtime context: workspace]\n{snapshot}",
"_context_snapshot": "workspace",
}
)
messages += [
{"role": "user", "content": question},
{"role": "assistant", "content": answer},
]
return [
{"id": row_id, "role": "user", "content": question},
{
"id": row_id + 1,
"role": "assistant",
"content": answer,
"metadata": {"model_turn": {"version": 1, "messages": messages}},
},
]
async def _build(rows, context_window=272000):
store = MagicMock()
store.get_session = AsyncMock(
return_value={"compressed_summary": "", "summary_up_to_msg_id": 0}
)
store.get_messages_for_context = AsyncMock(return_value=rows)
store.update_summary = AsyncMock()
builder = MasteryContextBuilder(store)
builder._summarize = AsyncMock()
return await builder.build(
session_id="synthetic-session",
llm_config=SimpleNamespace(
model="synthetic-model", context_window=context_window, max_tokens=8192
),
)
@pytest.mark.asyncio
async def test_replayed_snapshots_stay_in_place_so_follow_up_turns_extend_the_prefix():
"""Issue #2922: dropping sent snapshots shifted history and broke the prompt cache."""
first = _snapshot_turn(
1, "Explain the chain rule.", "Differentiate outside, then inside.", "/w"
)
second = _snapshot_turn(3, "One more example?", "Try sin(x^2).", "/w2")
turn_two = await _build(first)
turn_three = await _build([*first, *second])
assert turn_two.model_history[0]["_context_snapshot"] == "workspace"
assert turn_two.model_history == turn_three.model_history[: len(turn_two.model_history)]
assert [m.get("_context_snapshot") for m in turn_three.model_history] == [
"workspace",
None,
None,
"workspace",
None,
None,
]
assert turn_three.token_count == _count_model_context_tokens(
deduplicate_user_images(project_mastery_replay(turn_three.model_history))
)
@pytest.mark.asyncio
async def test_one_large_kept_snapshot_does_not_force_a_memory_rewrite():
"""A large status snapshot must not trigger a memory rewrite on its own.
The real DeepSeek run hit this: after two mastery turns an 18k-character
mastery_status snapshot pushed the replayed history over the 20k budget,
and the third turn paid a memory call plus a full prefix miss.
"""
bulky = "status line\n" * 8000
rows = _snapshot_turn(1, "Explain the chain rule.", "Outside, then inside.", bulky)
built = await _build(rows)
assert _count_model_context_tokens(built.model_history) > built.budget
assert built.model_history[0]["_context_snapshot"] == "workspace"
assert built.model_history[-1]["content"] == "Outside, then inside."
assert built.token_count <= built.budget
@pytest.mark.asyncio
async def test_kept_snapshots_stay_bounded_over_a_long_session():
"""Uncounted snapshots must not grow without limit across short exchanges.
A quiz-style session adds little dialogue per turn but a changed status
snapshot each time, so a dialogue-only count never reaches the budget.
"""
rows = []
for turn in range(120):
status = " ".join(str((turn + 1) * 7919 * n % 1_000_003) for n in range(400))
rows += _snapshot_turn(2 * turn + 1, f"Answer {turn}?", "Correct. Next one.", status)
built = await _build(rows)
assert _count_model_context_tokens(built.model_history) <= 2 * built.budget
assert built.token_count <= built.budget
@pytest.mark.asyncio
async def test_small_windows_give_kept_snapshots_no_extra_room():
rows = []
for turn in range(120):
status = " ".join(str((turn + 1) * 7919 * n % 1_000_003) for n in range(400))
rows += _snapshot_turn(2 * turn + 1, f"Answer {turn}?", "Correct. Next one.", status)
built = await _build(rows, context_window=32000)
assert built.budget == 11200
assert _count_model_context_tokens(built.model_history) <= built.budget
def test_recent_history_selection_discounts_kept_snapshots_like_the_plan():
"""A small dialogue with large kept snapshots keeps its tail exact.
The plan already discounts kept snapshots by the window headroom, but the
recent-tail selection counted them in full, so a quiz-style session with
tiny exchanges archived most of them the moment selection ran.
"""
status = " ".join(str(7919 * n % 1_000_003) for n in range(150))
rows = []
for turn in range(10):
rows += _snapshot_turn(2 * turn + 1, f"Answer {turn}?", "Correct.", status)
builder = MasteryContextBuilder(MagicMock())
builder._snapshot_headroom = 2
recent_budget = 1500
_older, recent = builder._select_recent_messages(rows, recent_budget)
def plan(tail):
return _plan_tokens(replay_history(tail), "", 2)
kept = len(recent) // 2
sent = _count_model_context_tokens(replay_history(rows[-2:]))
assert sent > 200 # each exchange is mostly snapshot
assert recent == rows[-2 * kept :]
assert plan(recent) <= recent_budget
assert kept == 10 or plan(rows[-2 * (kept + 1) :]) > recent_budget
# Counting snapshots in full would keep only recent_budget // sent exchanges.
assert kept > recent_budget // sent