Skip to content

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

Resolve objective relations against final learning identities

Bingxi Zhao (Frank)c8887f2a8924
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index 09ccbd56c..9b53209de 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -27,6 +27,7 @@ from deeptutor.learning.models import (
TopicSource,
)
from deeptutor.learning.objective_relations import (
+ ObjectiveRelationError,
RelationRefs,
resolve_relation_refs,
validate_objective_relations,
@@ -280,14 +281,6 @@ class LearningService:
"""Initialize the runnable module set (replace semantics)."""
self.replace_modules(progress, modules)
- @staticmethod
- def _new_entity_id(prefix: str, reserved: set[str]) -> str:
- while True:
- candidate = f"{prefix}_{uuid.uuid4().hex[:12]}"
- if candidate not in reserved:
- reserved.add(candidate)
- return candidate
-
@staticmethod
def _resolve_final_relations(
applied: list[LearningModule],
@@ -334,77 +327,6 @@ class LearningService:
sources=sources,
)
- @classmethod
- def _finalize_modules(
- cls,
- progress: LearningProgress,
- modules: list[LearningModule],
- *,
- append: bool,
- fresh_identity: bool,
- relation_refs: dict[str, RelationRefs],
- source_aliases: dict[str, str],
- sources: list[TopicSource],
- ) -> list[LearningModule]:
- applied = [module.model_copy(deep=True) for module in modules]
- existing_kp_ids = {
- point.id for module in progress.modules for point in module.knowledge_points
- }
- prerequisite_aliases = {key: key for key in existing_kp_ids}
- old_to_new: dict[str, str] = {}
-
- if append:
- offset = len(progress.modules)
- for index, module in enumerate(applied, start=offset):
- module.id = f"{progress.book_id}_m{index}"
- module.order = index
- for kp_index, point in enumerate(module.knowledge_points):
- old_id = point.id
- point.module_id = module.id
- point.id = f"{module.id}_kp{kp_index}"
- old_to_new[old_id] = point.id
- elif fresh_identity and existing_kp_ids:
- reserved_modules = set(module.id for module in progress.modules) | set(
- module.id for module in applied
- )
- reserved_points = set(existing_kp_ids) | set(
- point.id for module in applied for point in module.knowledge_points
- )
- for index, module in enumerate(applied):
- module.id = cls._new_entity_id(f"{progress.book_id}_m", reserved_modules)
- module.order = index
- for point in module.knowledge_points:
- old_id = point.id
- point.module_id = module.id
- point.id = cls._new_entity_id(f"{module.id}_kp", reserved_points)
- old_to_new[old_id] = point.id
- else:
- for module in applied:
- for point in module.knowledge_points:
- old_to_new[point.id] = point.id
-
- final_refs: dict[str, RelationRefs] = {}
- for module in applied:
- for point in module.knowledge_points:
- final_id = point.id
- for old_id, new_id in old_to_new.items():
- if new_id == final_id:
- specs = relation_refs.get(old_id)
- if specs is not None:
- final_refs[final_id] = specs
- if specs.client_ref:
- prerequisite_aliases[specs.client_ref] = final_id
- break
-
- resolve_relation_refs(
- applied,
- final_refs,
- prerequisite_aliases=prerequisite_aliases,
- source_aliases=source_aliases,
- sources=sources,
- )
- return applied
-
def replace_modules(self, progress: LearningProgress, modules: list[LearningModule]) -> None:
"""Replace all modules and clean stale KP state."""
new_kp_ids = {kp.id for m in modules for kp in m.knowledge_points}
@@ -1251,14 +1173,13 @@ class LearningService:
def create(tx):
tx.progress.name = str(name or "").strip()[:_MAX_PATH_NAME_LEN]
tx.put_topic(metadata, sources)
- applied_modules = self._finalize_modules(
- tx.progress,
+ applied_modules = [module.model_copy(deep=True) for module in modules]
+ self._resolve_final_relations(
+ applied_modules,
modules,
- append=False,
- fresh_identity=False,
- relation_refs=relation_refs or {},
- source_aliases=source_aliases or {},
- sources=sources,
+ relation_refs or {},
+ source_aliases or {},
+ sources,
)
validate_objective_relations(applied_modules, sources)
self.replace_modules(tx.progress, applied_modules)
diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.py
index bb3c32b5e..fe1d3896a 100644
--- a/deeptutor/learning/tests/test_api_endpoints.py
+++ b/deeptutor/learning/tests/test_api_endpoints.py
@@ -232,7 +232,10 @@ class TestTopicProductApi:
assert response.status_code == 200
edited = response.json()["map"]["modules"][0]["knowledge_points"]
- assert [point["id"] for point in edited] == [second["id"], first["id"]]
+ # A renamed objective gets fresh identity so previous mastery evidence
+ # cannot silently follow a changed learning target.
+ assert edited[0]["id"] != second["id"]
+ assert edited[1]["id"] == first["id"]
assert edited[0]["name"] == "Second objective, renamed"
assert edited[0]["prerequisite_ids"] == [first["id"]]
assert edited[0]["topic_source_ids"] == [source_id]
diff --git a/deeptutor/learning/tests/test_objective_relations.py b/deeptutor/learning/tests/test_objective_relations.py
index 818709065..1645bc62a 100644
--- a/deeptutor/learning/tests/test_objective_relations.py
+++ b/deeptutor/learning/tests/test_objective_relations.py
@@ -142,6 +142,27 @@ def test_resolve_maps_client_refs_and_source_aliases_to_final_ids():
assert second.topic_source_ids == ["source_notes"]
+def test_duplicate_client_refs_reject_topic_creation_without_persisting(tmp_path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ modules = [_module(_kp("draft_a"), _kp("draft_b"))]
+
+ with pytest.raises(ObjectiveRelationError, match="ambiguous"):
+ service.create_topic(
+ "topic",
+ name="Relations",
+ modules=modules,
+ metadata=TopicMetadata(path_id="topic", goal="Learn relations"),
+ sources=[],
+ relation_refs={
+ "draft_a": RelationRefs(client_ref="same"),
+ "draft_b": RelationRefs(client_ref="same"),
+ },
+ )
+
+ assert store.load("topic") is None
+
+
def test_append_resolves_refs_after_final_ids_are_assigned(tmp_path):
store = LearningStore(root=tmp_path)
service = LearningService(store)