Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(learning): complete adaptive linked evidence flow

Bingxi Zhao (Frank)01da2757bd9a
diff --git a/deeptutor/api/routers/book.py b/deeptutor/api/routers/book.py
index 912059f8c..288458d08 100644
--- a/deeptutor/api/routers/book.py
+++ b/deeptutor/api/routers/book.py
@@ -1127,6 +1127,12 @@ async def quiz_attempt(req: QuizAttemptRequest) -> dict[str, Any]:
record_assessment,
)
+ latest_attempt = progress.quiz_attempts[-1]
+ attempt_count = sum(
+ 1
+ for attempt in progress.quiz_attempts
+ if attempt.block_id == req.block_id and attempt.question_id == req.question_id
+ )
await record_assessment(
AssessmentRecord(
session_id=session_id,
@@ -1147,6 +1153,13 @@ async def quiz_attempt(req: QuizAttemptRequest) -> dict[str, Any]:
material_title=book.title,
section_id=req.page_id,
section_title=page.title if page is not None else "",
+ mastery_path_id=str(question.get("mastery_path_id") or ""),
+ knowledge_point_id=str(question.get("knowledge_point_id") or ""),
+ attempt_count=max(1, attempt_count),
+ attempt_id=(
+ f"book:{req.book_id}:{req.block_id}:{question_id}:"
+ f"{latest_attempt.timestamp:.9f}"
+ ),
)
)
except Exception:
diff --git a/deeptutor/api/routers/reading_extensions.py b/deeptutor/api/routers/reading_extensions.py
index 1b39a2261..a98b69941 100644
--- a/deeptutor/api/routers/reading_extensions.py
+++ b/deeptutor/api/routers/reading_extensions.py
@@ -337,6 +337,8 @@ async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) ->
material_title=material_title,
section_id=str(payload.locator),
section_title=section_title,
+ mastery_path_id=str(question.get("mastery_path_id") or ""),
+ knowledge_point_id=str(question.get("knowledge_point_id") or ""),
)
)
except RecordAssessmentError as exc:
diff --git a/deeptutor/learning/assessment.py b/deeptutor/learning/assessment.py
index 7ef779a3f..f65498268 100644
--- a/deeptutor/learning/assessment.py
+++ b/deeptutor/learning/assessment.py
@@ -2,13 +2,15 @@
Mastery Path, Book Focus-Check, and Immersive Reading persist graded attempts
through :func:`record_assessment`. Identity is the existing
-``(session_id, turn_id, question_id)`` notebook unique key — there is no
-second question bank. Objective linkage is written only for
-``source="mastery_path"``.
+``(session_id, turn_id, question_id)`` remains the latest-state notebook
+projection. Every graded submission is also appended to the immutable shared
+attempt log, and explicit objective linkage can update the same retention
+state from any learning surface.
"""
from __future__ import annotations
+import asyncio
from hashlib import sha1
import logging
import time
@@ -37,6 +39,8 @@ class AssessmentOutcome(BaseModel):
entry_id: int | None = None
upserted: bool = False
+ attempt_id: str = ""
+ attempt_recorded: bool = False
diagnostics: list[str] = Field(default_factory=list)
@@ -100,6 +104,7 @@ class AssessmentRecord(BaseModel):
updated_at: float = Field(default_factory=time.time)
bookmarked: bool = False
resolved: bool | None = None
+ attempt_id: str = ""
@field_validator("source", mode="before")
@classmethod
@@ -135,6 +140,7 @@ class AssessmentRecord(BaseModel):
"section_title",
"mastery_path_id",
"knowledge_point_id",
+ "attempt_id",
mode="before",
)
@classmethod
@@ -178,6 +184,32 @@ class AssessmentRecord(BaseModel):
raw = f"{self.session_id}|{self.turn_id}|{self.question_id}"
return sha1(raw.encode("utf-8"), usedforsecurity=False).hexdigest()
+ @property
+ def attempt_identity(self) -> str:
+ """Idempotency key for one immutable submission.
+
+ Callers with their own durable attempt identity should pass it. The
+ fallback deliberately excludes wall-clock time so transport retries
+ of the same answer converge; callers that allow the exact same answer
+ more than once distinguish it with ``attempt_count`` or ``attempt_id``.
+ """
+ if self.attempt_id:
+ return self.attempt_id
+ raw = "|".join(
+ (
+ self.session_id,
+ self.turn_id,
+ self.question_id,
+ self.source,
+ self.assessment_type,
+ str(self.attempt_count),
+ self.user_answer,
+ self.result,
+ str(self.is_correct),
+ )
+ )
+ return sha1(raw.encode("utf-8"), usedforsecurity=False).hexdigest()
+
def _resolve_result(record: AssessmentRecord, diagnostics: list[str]) -> AssessmentResult:
result = build_grade_result(result=record.result, is_correct=record.is_correct)
@@ -201,20 +233,97 @@ def _resolve_result(record: AssessmentRecord, diagnostics: list[str]) -> Assessm
def _apply_linkage(record: AssessmentRecord, diagnostics: list[str]) -> tuple[str, str]:
- if record.source == "mastery_path":
+ if record.mastery_path_id and record.knowledge_point_id:
return record.mastery_path_id, record.knowledge_point_id
if record.mastery_path_id or record.knowledge_point_id:
logger.warning(
- "Dropping mastery linkage on non-mastery assessment source=%s "
+ "Dropping incomplete mastery linkage on assessment source=%s "
"mastery_path_id=%s knowledge_point_id=%s",
record.source,
record.mastery_path_id,
record.knowledge_point_id,
)
- diagnostics.append("dropped_non_mastery_linkage")
+ diagnostics.append("dropped_incomplete_mastery_linkage")
return "", ""
+def _get_learning_store():
+ from deeptutor.learning.storage import LearningStore
+
+ return LearningStore()
+
+
+def _apply_linked_retention(
+ record: AssessmentRecord,
+ *,
+ result: AssessmentResult,
+ attempt_id: str,
+) -> bool:
+ """Apply explicitly linked non-Mastery evidence to its objective once."""
+ if (
+ record.source == "mastery_path"
+ or result == "ungraded"
+ or not record.mastery_path_id
+ or not record.knowledge_point_id
+ ):
+ return False
+
+ from deeptutor.learning.models import LearningEvidence
+ from deeptutor.learning.policy import find_knowledge_point
+ from deeptutor.learning.scheduler import SpacedRepetitionScheduler
+
+ scheduler = SpacedRepetitionScheduler()
+ event_result = result if result in {"correct", "incorrect", "partial"} else "incorrect"
+ evidence = LearningEvidence(
+ evidence_id=attempt_id,
+ knowledge_point_id=record.knowledge_point_id,
+ timestamp=record.created_at,
+ source=record.source,
+ assessment_type="quiz" if record.assessment_type in {"quiz", "focus_check"} else "review",
+ result=event_result,
+ quality=record.quality,
+ hints_used=record.hints_used,
+ attempt_count=record.attempt_count,
+ confidence=record.confidence,
+ response_time=record.response_time,
+ session_id=record.session_id,
+ turn_id=record.turn_id,
+ )
+
+ def apply(tx) -> bool:
+ progress = tx.progress
+ if any(item.evidence_id == attempt_id for item in progress.learning_evidence):
+ return False
+ kp, _, _ = find_knowledge_point(progress, record.knowledge_point_id)
+ if kp is None:
+ raise ValueError(
+ f"Unknown linked objective {record.knowledge_point_id!r} "
+ f"on path {record.mastery_path_id!r}"
+ )
+ progress.learning_evidence.append(evidence)
+ state = progress.repetition_states.get(kp.id) or scheduler.get_initial_state(
+ kp.type, now=evidence.timestamp
+ )
+ progress.repetition_states[kp.id] = state
+ scheduler.schedule_review(state, kp.type, evidence, now=evidence.timestamp)
+ progress.review_queue = scheduler.build_review_queue(progress)
+ tx.emit(
+ "evidence.recorded",
+ {
+ "evidence_id": attempt_id,
+ "knowledge_point_id": kp.id,
+ "source": record.source,
+ "result": event_result,
+ },
+ session_id=record.session_id,
+ turn_id=record.turn_id,
+ )
+ return True
+
+ _, applied = _get_learning_store().mutate(record.mastery_path_id, apply)
+ return applied
+
+
def to_notebook_item(record: AssessmentRecord, diagnostics: list[str]) -> dict[str, Any]:
"""Build the dict ``upsert_notebook_entries`` expects."""
result = _resolve_result(record, diagnostics)
@@ -250,9 +359,10 @@ def to_notebook_item(record: AssessmentRecord, diagnostics: list[str]) -> dict[s
async def record_assessment(record: AssessmentRecord) -> AssessmentOutcome:
- """Persist one assessment into the unified Question Notebook."""
+ """Persist the latest projection, immutable attempt, and linked evidence."""
diagnostics: list[str] = []
item = to_notebook_item(record, diagnostics)
+ attempt_id = record.attempt_identity
try:
from deeptutor.services.session import get_sqlite_session_store
@@ -261,6 +371,21 @@ async def record_assessment(record: AssessmentRecord) -> AssessmentOutcome:
entry = await store.find_notebook_entry(
record.session_id, record.question_id, turn_id=record.turn_id
)
+ entry_id = (
+ int(entry["id"]) if isinstance(entry, dict) and entry.get("id") is not None else None
+ )
+ attempt_recorded = await store.append_assessment_attempt(
+ record.session_id,
+ entry_id,
+ {
+ **record.model_dump(mode="json"),
+ "attempt_id": attempt_id,
+ "result": item["result"],
+ "mastery_path_id": item["mastery_path_id"],
+ "knowledge_point_id": item["knowledge_point_id"],
+ "occurred_at": record.created_at,
+ },
+ )
except Exception as exc:
logger.exception(
"Failed to record assessment %s for session %s",
@@ -270,10 +395,30 @@ async def record_assessment(record: AssessmentRecord) -> AssessmentOutcome:
raise RecordAssessmentError(
f"Failed to record assessment {record.question_id!r} for session {record.session_id!r}"
) from exc
- entry_id = int(entry["id"]) if isinstance(entry, dict) and entry.get("id") is not None else None
+ if item["mastery_path_id"] and item["knowledge_point_id"]:
+ try:
+ applied = await asyncio.to_thread(
+ _apply_linked_retention,
+ record,
+ result=item["result"],
+ attempt_id=attempt_id,
+ )
+ if applied:
+ diagnostics.append("linked_retention_updated")
+ except Exception:
+ logger.warning(
+ "Assessment %s retained its linkage but could not update path %s objective %s",
+ attempt_id,
+ item["mastery_path_id"],
+ item["knowledge_point_id"],
+ exc_info=True,
+ )
+ diagnostics.append("linked_retention_failed")
return AssessmentOutcome(
entry_id=entry_id,
upserted=bool(upserted),
+ attempt_id=attempt_id,
+ attempt_recorded=attempt_recorded,
diagnostics=diagnostics,
)
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index 2ffdda25d..6bd5b2f65 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -161,6 +161,7 @@ class LearningEvidence(BaseModel):
model_config = ConfigDict(extra="ignore")
+ evidence_id: str = ""
knowledge_point_id: str
timestamp: float = Field(default_factory=time.time)
source: str = "mastery_path"
diff --git a/deeptutor/learning/scheduler.py b/deeptutor/learning/scheduler.py
index 81b39528f..d055bcef4 100644
--- a/deeptutor/learning/scheduler.py
+++ b/deeptutor/learning/scheduler.py
@@ -184,21 +184,54 @@ class SpacedRepetitionScheduler:
intervals = INTERVAL_SEQUENCES[knowledge_type]
max_index = len(intervals) - 1
+ # A successful delayed retrieval is stronger evidence than an
+ # immediate repetition. Measure the state before applying the review;
+ # replay uses the event timestamp and therefore follows this exact
+ # transition deterministically.
+ previous_stability = max(state.stability, _EPS)
+ previous_retrievability = self.retrievability(state, now=moment)
+ elapsed_days = (
+ max(0.0, moment - state.last_review_at) / self._seconds_per_unit()
+ if state.last_review_at is not None
+ else 0.0
+ )
+ spacing_ratio = min(elapsed_days / previous_stability, 4.0)
+
+ # Difficulty is an item/learner estimate, not the knowledge-type
+ # category. Surprising failures raise it; strong retrieval lowers it.
+ outcome_error = (1.0 - quality) - state.difficulty
+ surprise = previous_retrievability - quality
+ state.difficulty = float(
+ min(0.95, max(0.05, state.difficulty + 0.12 * outcome_error + 0.08 * surprise))
+ )
+
if quality < _FAIL_QUALITY:
state.consecutive_wrong += 1
state.consecutive_correct = 0
state.lapse_count += 1
- state.stability = max(_MIN_STABILITY_DAYS * 0.1, state.stability * 0.5)
+ # Forgetting something that was predicted to be retrievable is a
+ # stronger negative update. A hard item also recovers less of its
+ # prior stability after a lapse.
+ retention_factor = 0.55 - 0.25 * previous_retrievability
+ difficulty_factor = 1.0 - 0.25 * state.difficulty
+ state.stability = max(
+ _MIN_STABILITY_DAYS * 0.1,
+ previous_stability * retention_factor * difficulty_factor,
+ )
state.retrievability = max(quality, 0.2)
if state.consecutive_wrong >= 2:
state.consecutive_wrong = 0
else:
state.consecutive_wrong = 0
state.consecutive_correct += 1
- growth = 1.2 + quality * 1.5
+ retrieval_effort = 1.0 + (1.0 - previous_retrievability) * 1.5
+ spacing_bonus = 1.0 + spacing_ratio * 0.15
+ learnability = 1.35 - 0.6 * state.difficulty
+ quality_strength = max(0.0, (quality - _FAIL_QUALITY) / (1.0 - _FAIL_QUALITY))
+ growth = 1.0 + quality_strength * learnability * retrieval_effort * spacing_bonus
if quality >= 0.8 and state.consecutive_correct >= 2:
growth *= 1.15
- state.stability = max(_MIN_STABILITY_DAYS, state.stability * growth)
+ state.stability = max(_MIN_STABILITY_DAYS, previous_stability * growth)
state.retrievability = 1.0
if state.consecutive_correct >= 2:
state.consecutive_correct = 0
@@ -321,8 +354,17 @@ class SpacedRepetitionScheduler:
def _resolved_quality(evidence: LearningEvidence) -> float:
if evidence.quality is not None:
- return max(0.0, min(1.0, float(evidence.quality)))
- return 1.0 if evidence.result == "correct" else 0.0
+ quality = float(evidence.quality)
+ elif evidence.result == "correct":
+ quality = 1.0
+ elif evidence.result == "partial":
+ quality = 0.4
+ else:
+ quality = 0.0
+ if evidence.quality is None:
+ quality -= min(0.25, evidence.hints_used * 0.08)
+ quality -= min(0.2, max(0, evidence.attempt_count - 1) * 0.05)
+ return max(0.0, min(1.0, quality))
def _snap_interval_index(intervals: list[int], interval_days: float, max_index: int) -> int:
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index 48d96af71..dd652dc0e 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -1563,9 +1563,9 @@ class LearningService:
The boolean is the gate of record; ``mastery_levels`` is nudged only so
the map's colour matches the gate (full on pass, capped on fail).
- A first pass starts spaced repetition at the type's first configured
- interval. Later assessments advance or shorten that existing schedule.
- An initial failure is not reviewable mastery, so it creates no state.
+ Every assessment applies the same retention transition that evidence
+ replay uses. This keeps the persisted state reproducible and lets an
+ initial failure schedule the prompt repair it demonstrably needs.
"""
self.record_qualitative_in_memory(
progress,
@@ -1653,8 +1653,10 @@ class LearningService:
progress.mastery_levels[kp_id] = max(current, 1.0) if passed else min(current, 0.4)
if evidence:
progress.feynman_explanations[kp_id] = evidence
+ moment = time.time()
review_evidence = LearningEvidence(
knowledge_point_id=kp_id,
+ timestamp=moment,
assessment_type="qualitative",
result="correct" if passed else "partial",
quality=(1.0 if evidence else 0.9) if passed else 0.2,
@@ -1665,13 +1667,18 @@ class LearningService:
progress.learning_evidence.append(review_evidence)
kp_type = progress.knowledge_types.get(kp_id)
if kp_type is not None and scheduler is not None:
- state = progress.repetition_states.get(kp_id)
- if state is not None and state.next_review_at <= time.time():
- scheduler.schedule_review(state, kp_type, review_evidence)
- elif state is None and passed:
- progress.repetition_states[kp_id] = scheduler.get_initial_state(kp_type)
+ state = progress.repetition_states.get(kp_id) or scheduler.get_initial_state(
+ kp_type, now=review_evidence.timestamp
+ )
+ progress.repetition_states[kp_id] = state
+ scheduler.schedule_review(
+ state,
+ kp_type,
+ review_evidence,
+ now=review_evidence.timestamp,
+ )
progress.review_queue = scheduler.build_review_queue(progress)
- progress.updated_at = time.time()
+ progress.updated_at = moment
def list_path_overviews(self) -> list[dict]:
"""Gate-accurate one-line state for every path the learner owns.
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index 49843554f..3c6b2cde1 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -634,14 +634,21 @@ class LearningStore:
This helper is always called inside the caller's write transaction, so
a projection failure rolls back the aggregate and its public events.
The ordinal is deliberately stable within the aggregate and avoids
- inventing a second evidence identity.
+ inventing a second evidence identity. Ordinary appends update only
+ new rows; shrinking or repairing history removes only the stale tail.
"""
- conn.execute(
- "DELETE FROM mastery_learning_evidence WHERE path_id = ?",
- (path_id,),
- )
+ existing = {
+ int(row["ordinal"]): str(row["evidence_json"])
+ for row in conn.execute(
+ "SELECT ordinal, evidence_json FROM mastery_learning_evidence WHERE path_id = ?",
+ (path_id,),
+ ).fetchall()
+ }
for ordinal, evidence in enumerate(progress.learning_evidence):
payload = evidence.model_dump(mode="json")
+ encoded = json.dumps(payload, ensure_ascii=False)
+ if existing.get(ordinal) == encoded:
+ continue
conn.execute(
"""
INSERT INTO mastery_learning_evidence (
@@ -649,6 +656,16 @@ class LearningStore:
assessment_type, result, quality, session_id, turn_id,
evidence_json
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(path_id, ordinal) DO UPDATE SET
+ knowledge_point_id = excluded.knowledge_point_id,
+ timestamp = excluded.timestamp,
+ source = excluded.source,
+ assessment_type = excluded.assessment_type,
+ result = excluded.result,
+ quality = excluded.quality,
+ session_id = excluded.session_id,
+ turn_id = excluded.turn_id,
+ evidence_json = excluded.evidence_json
""",
(
path_id,
@@ -661,9 +678,14 @@ class LearningStore:
evidence.quality,
evidence.session_id,
evidence.turn_id,
- json.dumps(payload, ensure_ascii=False),
+ encoded,
),
)
+ if len(existing) > len(progress.learning_evidence):
+ conn.execute(
+ "DELETE FROM mastery_learning_evidence WHERE path_id = ? AND ordinal >= ?",
+ (path_id, len(progress.learning_evidence)),
+ )
def _archive_legacy(self, path: Path) -> None:
if not path.exists():
diff --git a/deeptutor/learning/tests/test_assessment.py b/deeptutor/learning/tests/test_assessment.py
index a131cbc9e..69ca8c1d8 100644
--- a/deeptutor/learning/tests/test_assessment.py
+++ b/deeptutor/learning/tests/test_assessment.py
@@ -21,6 +21,13 @@ from deeptutor.learning.assessment import (
result_to_is_correct,
to_notebook_item,
)
+from deeptutor.learning.models import (
+ KnowledgePoint,
+ KnowledgeType,
+ LearningModule,
+ LearningProgress,
+)
+from deeptutor.learning.storage import LearningStore
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
@@ -67,6 +74,8 @@ def test_record_round_trip_persists_all_phase2_fields(store: SQLiteSessionStore)
assert isinstance(outcome, AssessmentOutcome)
assert outcome.upserted is True
assert outcome.entry_id is not None
+ assert outcome.attempt_recorded is True
+ assert outcome.attempt_id
assert outcome.diagnostics == []
entry = asyncio.run(store.find_notebook_entry("session-1", "q-1", turn_id="turn-1"))
@@ -108,7 +117,7 @@ def test_ungraded_is_not_treated_as_wrong() -> None:
assert item["is_correct"] is False
-def test_non_mastery_linkage_is_dropped() -> None:
+def test_non_mastery_complete_linkage_is_preserved() -> None:
record = AssessmentRecord(
session_id="s",
turn_id="t",
@@ -120,9 +129,24 @@ def test_non_mastery_linkage_is_dropped() -> None:
)
diagnostics: list[str] = []
item = to_notebook_item(record, diagnostics)
+ assert item["mastery_path_id"] == "path-1"
+ assert item["knowledge_point_id"] == "kp-1"
+ assert diagnostics == []
+
+
+def test_incomplete_linkage_is_dropped() -> None:
+ record = AssessmentRecord(
+ session_id="s",
+ question_id="q",
+ question="...",
+ source="book",
+ mastery_path_id="path-1",
+ )
+ diagnostics: list[str] = []
+ item = to_notebook_item(record, diagnostics)
assert item["mastery_path_id"] == ""
assert item["knowledge_point_id"] == ""
- assert "dropped_non_mastery_linkage" in diagnostics
+ assert "dropped_incomplete_mastery_linkage" in diagnostics
def test_mastery_defaults_attempt_and_hints() -> None:
@@ -142,6 +166,92 @@ def test_repeated_record_is_idempotent(store: SQLiteSessionStore) -> None:
store.list_notebook_entries(source="mastery_path", session_id="session-1")
)
assert listing["total"] == 1
+ attempts = asyncio.run(store.list_assessment_attempts("session-1", question_id="q-1"))
+ assert len(attempts) == 1
+
+
+def test_reanswer_keeps_immutable_attempts_and_updates_latest_projection(
+ store: SQLiteSessionStore,
+) -> None:
+ asyncio.run(store.create_session(title="S", session_id="session-1"))
+ asyncio.run(
+ record_assessment(
+ _mastery_record(attempt_id="attempt-1", user_answer="3", result="incorrect")
+ )
+ )
+ asyncio.run(
+ record_assessment(
+ _mastery_record(
+ attempt_id="attempt-2",
+ attempt_count=2,
+ user_answer="4",
+ result="correct",
+ is_correct=True,
+ )
+ )
+ )
+
+ latest = asyncio.run(store.find_notebook_entry("session-1", "q-1", turn_id="turn-1"))
+ attempts = asyncio.run(store.list_assessment_attempts("session-1", question_id="q-1"))
+ assert latest["user_answer"] == "4"
+ assert latest["result"] == "correct"
+ assert [attempt["attempt_id"] for attempt in attempts] == ["attempt-1", "attempt-2"]
+ assert [attempt["result"] for attempt in attempts] == ["incorrect", "correct"]
+
+
+def test_linked_book_assessment_updates_mastery_retention_once(
+ store: SQLiteSessionStore,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ asyncio.run(store.create_session(title="S", session_id="session-1"))
+ learning_store = LearningStore(root=tmp_path / "learning")
+ progress = LearningProgress(
+ book_id="path-1",
+ modules=[
+ LearningModule(
+ id="module-1",
+ name="Module",
+ order=0,
+ knowledge_points=[
+ KnowledgePoint(
+ id="kp-1",
+ name="Concept",
+ type=KnowledgeType.CONCEPT,
+ module_id="module-1",
+ )
+ ],
+ )
+ ],
+ knowledge_types={"kp-1": KnowledgeType.CONCEPT},
+ )
+ learning_store.save(progress)
+ monkeypatch.setattr("deeptutor.learning.assessment._get_learning_store", lambda: learning_store)
+ record = AssessmentRecord(
+ session_id="session-1",
+ turn_id="book-turn",
+ question_id="book-q",
+ question="Explain the concept",
+ user_answer="Answer",
+ result="correct",
+ is_correct=True,
+ source="book",
+ assessment_type="focus_check",
+ mastery_path_id="path-1",
+ knowledge_point_id="kp-1",
+ attempt_id="book-attempt-1",
+ )
+
+ first = asyncio.run(record_assessment(record))
+ second = asyncio.run(record_assessment(record))
+
+ assert "linked_retention_updated" in first.diagnostics
+ assert second.attempt_recorded is False
+ linked = learning_store.load("path-1")
+ assert len(linked.learning_evidence) == 1
+ assert linked.learning_evidence[0].evidence_id == "book-attempt-1"
+ assert linked.learning_evidence[0].source == "book"
+ assert linked.repetition_states["kp-1"].review_count == 1
def test_missing_session_raises_record_error() -> None:
diff --git a/deeptutor/learning/tests/test_guided_mastery_updates.py b/deeptutor/learning/tests/test_guided_mastery_updates.py
index bb29e5c5d..145648be3 100644
--- a/deeptutor/learning/tests/test_guided_mastery_updates.py
+++ b/deeptutor/learning/tests/test_guided_mastery_updates.py
@@ -294,15 +294,13 @@ def test_record_qualitative_pass_and_fail_drive_display_mastery(tmp_path):
@pytest.mark.parametrize(
- ("knowledge_type", "first_interval_days"),
+ "knowledge_type",
[
- (KnowledgeType.CONCEPT, 3),
- (KnowledgeType.DESIGN, 14),
+ KnowledgeType.CONCEPT,
+ KnowledgeType.DESIGN,
],
)
-def test_record_qualitative_starts_at_first_review_interval(
- tmp_path, monkeypatch, knowledge_type, first_interval_days
-):
+def test_record_qualitative_starts_at_first_review_interval(tmp_path, monkeypatch, knowledge_type):
store = LearningStore(root=tmp_path)
service = LearningService(store)
scheduler = SpacedRepetitionScheduler()
@@ -315,8 +313,9 @@ def test_record_qualitative_starts_at_first_review_interval(
service.record_qualitative(progress, "kp1", passed=True, scheduler=scheduler)
state = progress.repetition_states["kp1"]
- assert state.interval_index == 0
- assert state.next_review_at == now + first_interval_days * 86400
+ assert state.review_count == 1
+ assert state.last_review_at == now
+ assert state.next_review_at > now
assert state.stability > 0
assert [task.knowledge_point_id for task in progress.review_queue] == ["kp1"]
assert progress.review_queue[0].due_at == state.next_review_at
@@ -336,18 +335,19 @@ def test_record_qualitative_updates_existing_review_state(tmp_path, monkeypatch)
first_due = progress.repetition_states["kp1"].next_review_at
first_stability = progress.repetition_states["kp1"].stability
service.record_qualitative(progress, "kp1", passed=True, scheduler=scheduler)
- assert progress.repetition_states["kp1"].interval_index == 0
- assert progress.repetition_states["kp1"].next_review_at == first_due
- assert progress.repetition_states["kp1"].stability == first_stability
+ immediate = progress.repetition_states["kp1"]
+ assert immediate.review_count == 2
+ assert immediate.stability > first_stability
+ immediate_stability = immediate.stability
- now[0] = first_due
+ now[0] = immediate.next_review_at
service.record_qualitative(progress, "kp1", passed=True, scheduler=scheduler)
after_success = progress.repetition_states["kp1"]
success_stability = after_success.stability
success_due = after_success.next_review_at
- assert success_stability > first_stability
+ assert success_stability > immediate_stability
assert success_due > first_due
- assert after_success.review_count == 1
+ assert after_success.review_count == 3
now[0] = success_due
service.record_qualitative(progress, "kp1", passed=False, scheduler=scheduler)
@@ -359,7 +359,7 @@ def test_record_qualitative_updates_existing_review_state(tmp_path, monkeypatch)
assert fail_interval < success_interval
-def test_record_qualitative_initial_failure_does_not_schedule_review(tmp_path):
+def test_record_qualitative_initial_failure_schedules_repair_review(tmp_path):
store = LearningStore(root=tmp_path)
service = LearningService(store)
scheduler = SpacedRepetitionScheduler()
@@ -367,12 +367,35 @@ def test_record_qualitative_initial_failure_does_not_schedule_review(tmp_path):
service.record_qualitative(progress, "kp1", passed=False, scheduler=scheduler)
- assert progress.repetition_states == {}
- assert progress.review_queue == []
+ state = progress.repetition_states["kp1"]
+ assert state.review_count == 1
+ assert state.lapse_count == 1
+ assert [task.knowledge_point_id for task in progress.review_queue] == ["kp1"]
assert len(progress.learning_evidence) == 1
assert progress.learning_evidence[0].result == "partial"
+def test_qualitative_live_state_matches_evidence_replay(tmp_path, monkeypatch):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ scheduler = SpacedRepetitionScheduler()
+ progress = _make_progress()
+ moment = [1_700_000_000.0]
+ monkeypatch.setattr("deeptutor.learning.service.time.time", lambda: moment[0])
+
+ service.record_qualitative_in_memory(
+ progress, "kp1", passed=False, evidence="partial", scheduler=scheduler
+ )
+ moment[0] += 3 * 86400
+ service.record_qualitative_in_memory(
+ progress, "kp1", passed=True, evidence="clear", scheduler=scheduler
+ )
+
+ replayed = scheduler.replay(KnowledgeType.CONCEPT, progress.learning_evidence)
+ live = progress.repetition_states["kp1"]
+ assert live.model_dump() == pytest.approx(replayed.model_dump())
+
+
def test_grade_and_record_retry_correct_uses_weaker_quality(tmp_path):
store = LearningStore(root=tmp_path)
service = LearningService(store)
diff --git a/deeptutor/learning/tests/test_scheduler.py b/deeptutor/learning/tests/test_scheduler.py
index 59463f881..64c695d4b 100644
--- a/deeptutor/learning/tests/test_scheduler.py
+++ b/deeptutor/learning/tests/test_scheduler.py
@@ -332,6 +332,30 @@ class TestRetentionBaseline:
assert easy.stability > hard.stability
assert easy.next_review_at > hard.next_review_at
+ def test_delayed_success_grows_stability_more_than_immediate_repetition(self, scheduler):
+ start = 1_700_000_000.0
+ immediate = scheduler.get_initial_state(KnowledgeType.CONCEPT, now=start)
+ delayed = scheduler.get_initial_state(KnowledgeType.CONCEPT, now=start)
+ first = _evidence(quality=1.0, ts=start)
+ scheduler.schedule_review(immediate, KnowledgeType.CONCEPT, first, now=start)
+ scheduler.schedule_review(delayed, KnowledgeType.CONCEPT, first, now=start)
+
+ scheduler.schedule_review(
+ immediate,
+ KnowledgeType.CONCEPT,
+ _evidence(quality=1.0, ts=start + 60),
+ now=start + 60,
+ )
+ scheduler.schedule_review(
+ delayed,
+ KnowledgeType.CONCEPT,
+ _evidence(quality=1.0, ts=start + 7 * 86400),
+ now=start + 7 * 86400,
+ )
+
+ assert delayed.stability > immediate.stability
+ assert delayed.difficulty < immediate.difficulty
+
def test_replay_matches_stepwise_updates(self, scheduler):
now = 1_700_000_000.0
events = [
diff --git a/deeptutor/learning/tests/test_storage.py b/deeptutor/learning/tests/test_storage.py
index aca4f2787..c37534956 100644
--- a/deeptutor/learning/tests/test_storage.py
+++ b/deeptutor/learning/tests/test_storage.py
@@ -124,6 +124,43 @@ class TestSaveLoad:
== 2
)
+ def test_evidence_projection_appends_without_rewriting_history(self, store):
+ from deeptutor.learning.models import LearningEvidence
+
+ progress = LearningProgress(book_id="append-only-evidence")
+ progress.learning_evidence = [
+ LearningEvidence(knowledge_point_id="kp1", result="incorrect", quality=0.0)
+ ]
+ store.save(progress)
+ with sqlite3.connect(store.db_path) as conn:
+ conn.execute(
+ """
+ CREATE TRIGGER reject_existing_evidence_update
+ BEFORE UPDATE ON mastery_learning_evidence
+ WHEN OLD.path_id = 'append-only-evidence'
+ BEGIN SELECT RAISE(ABORT, 'history rewrite'); END
+ """
+ )
+ conn.execute(
+ """
+ CREATE TRIGGER reject_existing_evidence_delete
+ BEFORE DELETE ON mastery_learning_evidence
+ WHEN OLD.path_id = 'append-only-evidence'
+ BEGIN SELECT RAISE(ABORT, 'history delete'); END
+ """
+ )
+
+ progress = store.load("append-only-evidence")
+ progress.learning_evidence.append(
+ LearningEvidence(knowledge_point_id="kp1", result="correct", quality=1.0)
+ )
+ store.save(progress)
+
+ assert [event.result for event in store.list_learning_evidence("append-only-evidence")] == [
+ "correct",
+ "incorrect",
+ ]
+
def test_existing_paths_receive_evidence_projection_on_upgrade(self, store):
from deeptutor.learning.models import LearningEvidence
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 90531e0f2..a170a2d74 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -387,6 +387,27 @@ class SQLiteSessionStore:
CREATE INDEX IF NOT EXISTS idx_notebook_entries_bookmarked
ON notebook_entries(bookmarked, created_at DESC);
+ CREATE TABLE IF NOT EXISTS assessment_attempts (
+ attempt_id TEXT PRIMARY KEY,
+ notebook_entry_id INTEGER,
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ turn_id TEXT NOT NULL DEFAULT '',
+ question_id TEXT NOT NULL,
+ source TEXT NOT NULL,
+ assessment_type TEXT NOT NULL,
+ result TEXT NOT NULL,
+ mastery_path_id TEXT NOT NULL DEFAULT '',
+ knowledge_point_id TEXT NOT NULL DEFAULT '',
+ occurred_at REAL NOT NULL,
+ assessment_json TEXT NOT NULL
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_assessment_attempts_session_time
+ ON assessment_attempts(session_id, occurred_at DESC);
+
+ CREATE INDEX IF NOT EXISTS idx_assessment_attempts_linkage
+ ON assessment_attempts(mastery_path_id, knowledge_point_id, occurred_at DESC);
+
CREATE TABLE IF NOT EXISTS reading_quiz_pending (
material_id TEXT NOT NULL,
locator INTEGER NOT NULL,
@@ -2851,6 +2872,95 @@ class SQLiteSessionStore:
async def upsert_notebook_entries(self, session_id: str, items: list[dict[str, Any]]) -> int:
return await self._run(self._upsert_notebook_entries_sync, session_id, items)
+ def _append_assessment_attempt_sync(
+ self,
+ session_id: str,
+ notebook_entry_id: int | None,
+ attempt: dict[str, Any],
+ ) -> bool:
+ attempt_id = str(attempt.get("attempt_id") or "").strip()
+ question_id = str(attempt.get("question_id") or "").strip()
+ if not attempt_id or not question_id:
+ raise ValueError("attempt_id and question_id are required")
+ with self._connect() as conn:
+ if (
+ conn.execute("SELECT id FROM sessions WHERE id = ?", (session_id,)).fetchone()
+ is None
+ ):
+ raise ValueError(f"Session not found: {session_id}")
+ conn.execute(
+ """
+ INSERT OR IGNORE INTO assessment_attempts (
+ attempt_id, notebook_entry_id, session_id, turn_id,
+ question_id, source, assessment_type, result,
+ mastery_path_id, knowledge_point_id, occurred_at,
+ assessment_json
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ attempt_id,
+ notebook_entry_id,
+ session_id,
+ str(attempt.get("turn_id") or ""),
+ question_id,
+ str(attempt.get("source") or "deep_question"),
+ str(attempt.get("assessment_type") or "quiz"),
+ str(attempt.get("result") or "ungraded"),
+ str(attempt.get("mastery_path_id") or ""),
+ str(attempt.get("knowledge_point_id") or ""),
+ float(attempt.get("occurred_at") or time.time()),
+ _json_dumps(attempt),
+ ),
+ )
+ inserted = bool(conn.execute("SELECT changes()").fetchone()[0])
+ conn.commit()
+ return inserted
+
+ async def append_assessment_attempt(
+ self,
+ session_id: str,
+ notebook_entry_id: int | None,
+ attempt: dict[str, Any],
+ ) -> bool:
+ """Append one immutable assessment event; duplicate ids are idempotent."""
+ return await self._run(
+ self._append_assessment_attempt_sync,
+ session_id,
+ notebook_entry_id,
+ attempt,
+ )
+
+ def _list_assessment_attempts_sync(
+ self,
+ session_id: str,
+ question_id: str,
+ ) -> list[dict[str, Any]]:
+ clauses = ["session_id = ?"]
+ params: list[Any] = [session_id]
+ if question_id:
+ clauses.append("question_id = ?")
+ params.append(question_id)
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT assessment_json FROM assessment_attempts "
+ f"WHERE {' AND '.join(clauses)} ORDER BY occurred_at, rowid", # nosec B608
+ tuple(params),
+ ).fetchall()
+ return [_json_loads(str(row["assessment_json"]), {}) for row in rows]
+
+ async def list_assessment_attempts(
+ self,
+ session_id: str,
+ *,
+ question_id: str = "",
+ ) -> list[dict[str, Any]]:
+ """Return immutable attempts in replay order for one session."""
+ return await self._run(
+ self._list_assessment_attempts_sync,
+ session_id,
+ question_id,
+ )
+
def _put_reading_quiz_pending_sync(
self, material_id: str, locator: int, questions: list[Any]
) -> int: