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

377 lines
15 KiB
Python

from copy import deepcopy
import json
from deeptutor.capabilities.mastery.history import share_mastery_history
from deeptutor.services.session.model_history import _MASTERY_SNAPSHOT_NOTICE, normalize_model_turn
def exchange(call_id, name, payload):
return [
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": call_id,
"type": "function",
"function": {
"name": name,
"arguments": '{"reason":"learner requested a change"}',
},
}
],
},
{
"role": "tool",
"tool_call_id": call_id,
"name": name,
"content": json.dumps(payload, ensure_ascii=False),
},
]
def large_state():
return {
"name": "Course",
"modules": [
{"id": "m1", "objective": "Learner confused A with B. " * 90},
{"id": "m2", "objective": "Explain using the successful example. " * 90},
],
}
def expand_shared(messages):
"""Every reference must resolve directly to a full inline value."""
payloads = {}
snapshots = 0
for message in messages:
if message.get("role") == "tool":
try:
payloads[("tool_call_id", message["tool_call_id"])] = json.loads(message["content"])
except ValueError:
pass
if message.get("_context_snapshot") == "mastery_status_snapshot":
snapshots += 1
payloads[("snapshot", snapshots)] = json.loads(
message["content"][len(_MASTERY_SNAPSHOT_NOTICE) :]
)
def expand(value):
if isinstance(value, dict):
if set(value) == {"$mastery_same_value"}:
ref = value["$mastery_same_value"]
if "snapshot" in ref:
target = payloads[("snapshot", ref.get("occurrence", 1))]
else:
target = payloads[("tool_call_id", ref["tool_call_id"])]
for part in ref["pointer"].split("/")[1:]:
key = part.replace("~1", "/").replace("~0", "~")
target = target[int(key)] if isinstance(target, list) else target[key]
assert "$mastery_same_value" not in json.dumps(target)
return target
return {key: expand(child) for key, child in value.items()}
if isinstance(value, list):
return [expand(child) for child in value]
return value
return {key: expand(value) for key, value in payloads.items()}
def test_exact_reconstruction_preserves_unique_old_state_and_all_dialogue():
original_map = large_state()
revised_map = deepcopy(original_map)
revised_map["modules"][0]["objective"] = "An earlier misconception was corrected. " * 90
messages = [
{"role": "user", "content": "I still confuse A and B; that explanation did not help."},
*exchange("build", "mastery_build", {"map": original_map, "status": "built"}),
*exchange("revise", "mastery_revise", {"map": revised_map, "progress_reset": ["m1"]}),
*exchange("status", "mastery_status", {"map": revised_map, "path_id": "p"}),
{"role": "assistant", "content": "Here is the explanation that helped you."},
]
before = deepcopy(messages)
expected = expand_shared(before)
share_mastery_history(messages, len(messages))
assert expand_shared(messages) == expected
assert len(json.dumps(messages)) < len(json.dumps(before)) * 0.65
assert [m for m in messages if m["role"] != "tool"] == [
m for m in before if m["role"] != "tool"
]
assert normalize_model_turn({"version": 1, "messages": messages}) is not None
assert json.loads(messages[4]["content"])["progress_reset"] == ["m1"]
def test_appending_repeated_state_preserves_the_projected_request_prefix() -> None:
"""Repeated state must not change the bytes of an earlier request prefix."""
messages = []
previous = []
for index in range(5):
messages.extend(exchange(f"status{index}", "mastery_status", {"map": large_state()}))
projected = deepcopy(messages)
share_mastery_history(projected, len(projected))
assert json.dumps(projected[: len(previous)], ensure_ascii=False) == json.dumps(
previous, ensure_ascii=False
)
assert expand_shared(projected) == expand_shared(messages)
previous = projected
def test_adding_a_current_snapshot_preserves_the_projected_history_prefix() -> None:
"""A transient runtime snapshot must not replace a historical full value."""
payload = {"path_id": "p", "map": large_state()}
history = exchange("old", "mastery_status", payload)
previous = deepcopy(history)
share_mastery_history(previous, len(previous))
snapshot = {
"role": "user",
"content": _MASTERY_SNAPSHOT_NOTICE + json.dumps(payload),
"_context_snapshot": "mastery_status_snapshot",
}
projected = deepcopy([*history, snapshot])
share_mastery_history(projected, len(history))
assert projected[: len(history)] == previous
assert projected[-1] == snapshot
assert expand_shared(projected) == expand_shared([*history, snapshot])
def status_snapshot(payload):
return {
"role": "user",
"content": _MASTERY_SNAPSHOT_NOTICE + json.dumps(payload),
"_context_snapshot": "mastery_status_snapshot",
}
def test_replayed_status_snapshots_keep_earlier_turns_byte_identical() -> None:
"""Issue #2922: replay keeps sent snapshots, so a changed status adds a second one.
Projection of an earlier turn must not depend on snapshots appended later,
otherwise every status change rewrites the cached request prefix.
"""
first_map = large_state()
second_map = deepcopy(first_map)
second_map["modules"][1]["objective"] = "The learner now explains the example alone. " * 90
turn_one = [
status_snapshot({"path_id": "p", "map": first_map}),
{"role": "user", "content": "Start the lesson."},
*exchange("s1", "mastery_status", {"path_id": "p", "map": first_map}),
{"role": "assistant", "content": "Lesson one."},
]
previous = deepcopy(turn_one)
share_mastery_history(previous, len(previous))
assert "$mastery_same_value" in previous[3]["content"]
turn_two = [
status_snapshot({"path_id": "p", "map": second_map}),
{"role": "user", "content": "Continue."},
*exchange("s2", "mastery_status", {"path_id": "p", "map": second_map}),
]
messages = [*turn_one, *turn_two]
projected = deepcopy(messages)
share_mastery_history(projected, len(projected))
assert projected[: len(previous)] == previous
assert projected[len(turn_one)] == messages[len(turn_one)]
reference = json.loads(projected[-1]["content"])["map"]["$mastery_same_value"]
assert reference == {"snapshot": "mastery_status_snapshot", "occurrence": 2, "pointer": "/map"}
assert expand_shared(projected) == expand_shared(messages)
def test_current_snapshot_and_current_tool_results_are_full_anchors_only():
payload = {"path_id": "p", "map": large_state()}
messages = exchange("old", "mastery_status", payload) + exchange(
"old2", "mastery_status", payload
)
boundary = len(messages)
messages += [
{
"role": "user",
"content": _MASTERY_SNAPSHOT_NOTICE + json.dumps(payload),
"_context_snapshot": "mastery_status_snapshot",
},
{"role": "user", "content": "Actual question"},
*exchange("current", "mastery_status", payload),
]
original = deepcopy(messages)
share_mastery_history(messages, boundary)
assert messages[boundary:] == original[boundary:]
assert expand_shared(messages) == expand_shared(original)
assert messages[1] == original[1]
assert "$mastery_same_value" in messages[3]["content"]
def test_sources_grades_answers_unknown_fields_and_tools_are_not_projected():
evidence = {"map": large_state(), "source_quotes": "Keep exact source words. " * 90}
messages = [
*exchange("rag", "rag", evidence),
*exchange("answer", "ask_user", evidence),
*exchange("grade", "mastery_grade", evidence),
*exchange("state", "mastery_status", evidence),
*exchange("state2", "mastery_status", evidence),
]
original = deepcopy(messages)
share_mastery_history(messages, len(messages))
assert messages[:6] == original[:6]
assert json.loads(messages[7]["content"])["source_quotes"] == evidence["source_quotes"]
def test_ambiguous_call_ids_and_malformed_state_are_left_untouched():
messages = [
*exchange("duplicate", "mastery_status", {"map": large_state()}),
*exchange("duplicate", "mastery_status", {"map": large_state()}),
*exchange("broken", "mastery_status", {"map": large_state()}),
]
messages[-1]["content"] = '{"map": malformed}'
original = deepcopy(messages)
share_mastery_history(messages, len(messages))
assert messages == original
def test_no_reference_chains_and_json_pointer_special_keys():
payload = {"map": {"a/b~c": large_state()}}
messages = [m for i in range(4) for m in exchange(f"s{i}", "mastery_status", payload)]
original = deepcopy(messages)
share_mastery_history(messages, len(messages))
assert expand_shared(messages) == expand_shared(original)
assert messages[1] == original[1]
once = deepcopy(messages)
share_mastery_history(messages, len(messages))
assert messages == once
def test_similar_but_different_values_are_not_merged():
messages = [
*exchange("a", "mastery_profile", {"learner_profile": {"difficulty": "A" * 900}}),
*exchange("b", "mastery_profile", {"learner_profile": {"difficulty": "B" * 900}}),
]
original = deepcopy(messages)
share_mastery_history(messages, len(messages))
assert messages == original
def test_json_pointer_escaping_resolves_partial_sharing():
common = {"detail": "Keep this exact explanation. " * 100}
first = {"map": {"a/b~c": common, "revision_note": "before"}}
second = {"map": {"a/b~c": common, "revision_note": "after"}}
messages = exchange("first", "mastery_status", first) + exchange(
"second", "mastery_status", second
)
original = deepcopy(messages)
share_mastery_history(messages, len(messages))
assert "/map/a~1b~0c" in messages[3]["content"]
assert expand_shared(messages) == expand_shared(original)
def test_current_round_projection_is_disposable_and_preserves_changed_state():
from deeptutor.capabilities.mastery.pipeline import MasteryLoopPipeline
pipeline = MasteryLoopPipeline.__new__(MasteryLoopPipeline)
state = large_state()
changed = deepcopy(state)
changed["modules"][0]["objective"] = "A distinct new objective. " * 90
messages = (
exchange("before", "mastery_status", {"map": state})
+ exchange("same", "mastery_status", {"map": state})
+ exchange("changed", "mastery_status", {"map": changed})
)
original = deepcopy(messages)
projected = pipeline.project_model_request(messages)
assert messages == original
assert expand_shared(projected) == expand_shared(original)
assert projected[1] == original[1]
assert "$mastery_same_value" in projected[3]["content"]
def test_short_header_snapshots_are_still_shared_anchors() -> None:
"""Snapshots now start with only their first line; older sessions keep the long notice."""
from deeptutor.capabilities.mastery.history import SNAPSHOT_HEADER, snapshot_payload_text
payload = {"path_id": "p", "map": large_state()}
snapshot = {
"role": "user",
"content": SNAPSHOT_HEADER + json.dumps(payload),
"_context_snapshot": "mastery_status_snapshot",
}
messages = [snapshot, *exchange("later", "mastery_status", payload)]
projected = deepcopy(messages)
share_mastery_history(projected, len(projected))
assert projected[0] == snapshot
reference = json.loads(projected[-1]["content"])["map"]["$mastery_same_value"]
assert reference == {"snapshot": "mastery_status_snapshot", "pointer": "/map"}
assert json.loads(snapshot_payload_text(snapshot["content"])) == payload
legacy = _MASTERY_SNAPSHOT_NOTICE + json.dumps(payload)
assert json.loads(snapshot_payload_text(legacy)) == payload
assert snapshot_payload_text("[Runtime context: workspace]\n{}") is None
def _status_with_defaults():
points = [
{
"id": f"kp{n}",
"name": f"Point {n}: derivatives of composed functions",
"type": "procedure",
"prerequisite_ids": [],
"topic_source_ids": [],
"status": "learning" if n == 0 else "new",
"mastery": 0.4 if n == 0 else 0,
"mastery_source": "",
"override_note": "",
"deferred": False,
}
for n in range(12)
]
return {
"path_id": "p",
"map": {"name": "Derivatives", "modules": [{"id": "m1", "knowledge_points": points}]},
"learning_stages": {f"kp{n}": "not_yet_covered" for n in range(12)},
}
def test_a_full_status_result_shares_the_map_a_compact_snapshot_already_sent():
"""The snapshot leaves defaults out; a later full read must still reuse it."""
from deeptutor.capabilities.mastery.history import SNAPSHOT_HEADER, STATE_REFERENCE_NOTICE
from deeptutor.capabilities.mastery.snapshot import compact_status
full = _status_with_defaults()
snapshot = {
"role": "user",
"content": SNAPSHOT_HEADER + json.dumps(compact_status(full)),
"_context_snapshot": "mastery_status_snapshot",
}
messages = [snapshot, *exchange("read", "mastery_status", full)]
projected = deepcopy(messages)
share_mastery_history(projected, len(projected))
assert projected[0] == snapshot
shared = json.loads(projected[-1]["content"])
assert shared["map"] == {
"$mastery_same_value": {
"snapshot": "mastery_status_snapshot",
"pointer": "/map",
"defaults_omitted": True,
}
}
assert len(projected[-1]["content"]) < len(messages[-1]["content"]) / 2
# The reference resolves to the compact map, which is the full one less defaults.
sent = json.loads(snapshot["content"][len(SNAPSHOT_HEADER) :])
assert sent["map"] == compact_status(full)["map"]
assert '"defaults_omitted": true' in STATE_REFERENCE_NOTICE
def test_a_changed_map_is_not_shared_with_an_older_compact_snapshot():
from deeptutor.capabilities.mastery.history import SNAPSHOT_HEADER
from deeptutor.capabilities.mastery.snapshot import compact_status
before = _status_with_defaults()
after = deepcopy(before)
after["map"]["modules"][0]["knowledge_points"][3]["status"] = "learning"
snapshot = {
"role": "user",
"content": SNAPSHOT_HEADER + json.dumps(compact_status(before)),
"_context_snapshot": "mastery_status_snapshot",
}
messages = [snapshot, *exchange("read", "mastery_status", after)]
projected = deepcopy(messages)
share_mastery_history(projected, len(projected))
assert json.loads(projected[-1]["content"])["map"] == after["map"]