Files
DeepTutor/tests/capabilities/test_mastery_status_snapshot.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

261 lines
10 KiB
Python

import json
from unittest.mock import AsyncMock
import pytest
from deeptutor.capabilities.mastery.loop import MasteryLoopCapability
from deeptutor.capabilities.mastery.tools import MasteryStatusTool
from deeptutor.core.context import UnifiedContext
from deeptutor.core.tool_protocol import ToolResult
@pytest.mark.asyncio
async def test_snapshot_is_fresh_scoped_and_includes_pending_answer(monkeypatch):
calls = []
async def read(**kwargs):
calls.append(kwargs)
return ToolResult(
success=True,
content=json.dumps(
{
"path_id": kwargs["_mastery_path_id"],
"revision": len(calls),
"pending_interaction": {"status": "answered", "learner_answer": "B"},
}
),
)
monkeypatch.setattr(MasteryStatusTool, "execute", staticmethod(read))
cap = MasteryLoopCapability()
context = UnifiedContext(
session_id="s",
metadata={
"mastery_mode": True,
"mastery_path_id": "p1",
"mastery_session_mode": "review",
},
)
first = await cap.pre_loop(context, None)
assert '"learner_answer": "B"' in first.content
assert calls[0]["_mastery_session_mode"] == "review"
context.metadata["mastery_path_id"] = "p2"
second = await cap.pre_loop(context, None)
assert '"path_id": "p2"' in second.content
assert '"revision": 2' in second.content
assert "p1" not in second.content
@pytest.mark.asyncio
async def test_no_snapshot_on_read_failure_or_inactive_path(monkeypatch):
read = AsyncMock(return_value=ToolResult(success=False, content="unavailable"))
monkeypatch.setattr(MasteryStatusTool, "execute", read)
cap = MasteryLoopCapability()
assert await cap.pre_loop(UnifiedContext(), None) is None
read.assert_not_called()
context = UnifiedContext(metadata={"mastery_mode": True, "mastery_path_id": "p"})
assert await cap.pre_loop(context, None) is None
assert "otherwise call this FIRST" in MasteryStatusTool().get_definition().description
@pytest.mark.asyncio
async def test_binding_change_during_read_discards_snapshot(monkeypatch):
context = UnifiedContext(metadata={"mastery_mode": True, "mastery_path_id": "p1"})
async def read(**kwargs):
context.metadata["mastery_path_id"] = "p2"
return ToolResult(success=True, content=json.dumps({"path_id": "p1"}))
monkeypatch.setattr(MasteryStatusTool, "execute", staticmethod(read))
assert await MasteryLoopCapability().pre_loop(context, None) is None
@pytest.mark.asyncio
async def test_prepass_failure_keeps_tool_fallback_and_grade_seed(monkeypatch):
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
async def read(**kwargs):
raise RuntimeError("unavailable")
monkeypatch.setattr(MasteryStatusTool, "execute", staticmethod(read))
context = UnifiedContext(
metadata={
"mastery_mode": True,
"mastery_path_id": "p1",
"mastery_card_grade": {"is_correct": True, "result": {"learner_answer": "B"}},
}
)
pipeline = AgenticChatPipeline(language="en")
assert await pipeline._capability_pre_loop_briefings(context, None) == ""
seed = pipeline._capability_pre_loop_seed(context)
assert "engine reports: correct" in seed
assert 'they answered "B"' in seed
assert "otherwise call this FIRST" in MasteryStatusTool().get_definition().description
def _full_status() -> dict:
from deeptutor.capabilities.mastery.tools import (
OPEN_QUESTION_INSTRUCTION,
WORKING_BRIEF_INSTRUCTION,
)
from deeptutor.learning.teaching import TEACHING_FOCUS_INSTRUCTION, TEACHING_GUIDANCE
untouched = {
"id": "kp0",
"name": "Function notation",
"type": "procedure",
"prerequisite_ids": [],
"topic_source_ids": [],
"status": "new",
"mastery": 0.0,
"mastery_source": "",
"override_note": "",
"deferred": False,
}
started = {
**untouched,
"id": "kp1",
"prerequisite_ids": ["kp0"],
"status": "learning",
"mastery": 0.4,
}
return {
"status": "active",
"path_revision": 5,
"path_id": "p",
"path_name": "Derivatives",
"goal": "",
"sources": [],
"mode": "study",
"next": {
"action": "answer_pending",
"knowledge_point_id": "kp0",
"pending_prompt": "What is f(-2)?",
"pending_question": {"question_id": "q", "prompt": "What is f(-2)?"},
"session_id": "",
},
"map": {
"counts": {"total": 2},
"modules": [{"id": "m", "knowledge_points": [untouched, started]}],
},
"learner_profile": {
"prior_knowledge": "Starting from zero",
"time_budget": "",
"preferences": "",
"teaching_preferences": {},
"teaching_observations": {},
"teaching_focus": {
"knowledge_point_id": "kp0",
"observations": [],
"instruction": TEACHING_FOCUS_INSTRUCTION,
},
"teaching_guidance": TEACHING_GUIDANCE,
},
"intake_needed": False,
"learning_stages": {"kp0": "not_yet_covered", "kp1": "explained"},
"visual_requirements": {
"kp0": {"required": [], "demonstrated": []},
"kp1": {"required": ["graph"], "demonstrated": []},
},
"pending_interaction": {
"question_id": "q",
"status": "awaiting_input",
"instruction": OPEN_QUESTION_INSTRUCTION,
"session_id": "s",
},
"due_review_ids": [],
"state_scope": "working_brief",
"inspection_instruction": WORKING_BRIEF_INSTRUCTION,
}
def test_snapshot_keeps_this_turns_state_and_drops_fixed_text_and_defaults():
"""Issue #2922: each kept snapshot is paid for once, so it carries only state."""
from deeptutor.capabilities.mastery.snapshot import compact_status
full = _full_status()
brief = compact_status(full)
text = json.dumps(brief)
for fixed in (
full["inspection_instruction"],
full["pending_interaction"]["instruction"],
full["learner_profile"]["teaching_guidance"],
full["learner_profile"]["teaching_focus"]["instruction"],
):
assert fixed not in text
points = brief["map"]["modules"][0]["knowledge_points"]
assert points[0] == {"id": "kp0", "name": "Function notation", "type": "procedure"}
assert points[1]["prerequisite_ids"] == ["kp0"]
assert points[1]["status"] == "learning" and points[1]["mastery"] == 0.4
assert brief["learning_stages"] == {"kp1": "explained"}
assert brief["visual_requirements"] == {"kp1": {"required": ["graph"], "demonstrated": []}}
assert brief["learner_profile"] == {"prior_knowledge": "Starting from zero"}
assert brief["next"]["pending_question"] == {"question_id": "q", "prompt": "What is f(-2)?"}
assert "pending_prompt" not in brief["next"]
assert brief["pending_interaction"] == {"question_id": "q", "status": "awaiting_input"}
for key in ("goal", "sources", "due_review_ids", "intake_needed", "inspection_instruction"):
assert key not in brief
assert brief["state_scope"] == "working_brief"
assert len(text) < len(json.dumps(full)) * 0.4
def test_snapshot_keeps_guidance_that_is_specific_to_this_card():
from deeptutor.capabilities.mastery.snapshot import compact_status
full = _full_status()
full["pending_interaction"]["instruction"] = "This pending card belongs to an earlier one."
full["learner_profile"]["teaching_focus"]["observations"] = [{"key": "k", "text": "Lost"}]
brief = compact_status(full)
assert brief["pending_interaction"]["instruction"] == full["pending_interaction"]["instruction"]
assert brief["learner_profile"]["teaching_focus"] == {
"knowledge_point_id": "kp0",
"observations": [{"key": "k", "text": "Lost"}],
}
@pytest.mark.parametrize("language", ["en", "zh"])
def test_the_system_prompt_states_the_fixed_snapshot_guidance_once(language):
from deeptutor.capabilities.mastery.pipeline import MasteryPromptAssembler
from deeptutor.capabilities.mastery.tools import (
GROUP_REPLY_INSTRUCTION,
INTAKE_INSTRUCTION,
OPEN_QUESTION_INSTRUCTION,
WORKING_BRIEF_INSTRUCTION,
)
from deeptutor.learning.teaching import TEACHING_FOCUS_INSTRUCTION, TEACHING_GUIDANCE
from deeptutor.services.prompt import get_prompt_manager
prompts = get_prompt_manager().load_prompts("mastery", "mastery_loop", language)
assembler = MasteryPromptAssembler(prompts=prompts, language=language)
blocks = assembler.foundation_blocks(UnifiedContext(metadata={"mastery_mode": True}))
system = "\n".join(block.content for block in blocks)
for fixed in (
WORKING_BRIEF_INSTRUCTION,
INTAKE_INSTRUCTION,
OPEN_QUESTION_INSTRUCTION,
GROUP_REPLY_INSTRUCTION,
TEACHING_GUIDANCE,
TEACHING_FOCUS_INSTRUCTION,
):
assert system.count(fixed) == 1
assert "[Current-turn mastery_status snapshot]" in system
assert "{" + "working_brief}" not in system
@pytest.mark.asyncio
async def test_pre_loop_sends_the_short_header_and_the_compact_payload(monkeypatch):
from deeptutor.capabilities.mastery.history import SNAPSHOT_HEADER
from deeptutor.capabilities.mastery.snapshot import compact_status
full = _full_status()
async def read(**kwargs):
return ToolResult(success=True, content=json.dumps(full))
monkeypatch.setattr(MasteryStatusTool, "execute", staticmethod(read))
context = UnifiedContext(metadata={"mastery_mode": True, "mastery_path_id": "p"})
block = await MasteryLoopCapability().pre_loop(context, None)
assert block.content.startswith(SNAPSHOT_HEADER)
assert json.loads(block.content[len(SNAPSHOT_HEADER) :]) == compact_status(full)
assert "already read mastery_status" not in block.content