Skip to content

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

fix(quiz): scope streaming quiz cards to their turn (#677)

Bingxi Zhao (Frank)5d315a271db2
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index d0d52b39b..3f7d4d72c 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -1712,36 +1712,24 @@ class SQLiteSessionStore:
question_id: str,
turn_id: str | None = None,
) -> dict[str, Any] | None:
+ # A missing turn_id only ever matches the legacy namespace (rows
+ # persisted before turn scoping, migrated with turn_id=''). It must
+ # never fall back to other turns' rows: positional question ids
+ # (``q_1``..``q_N``) repeat across quizzes in one session, so a
+ # cross-turn match would leak a previous quiz's answers into a new
+ # quiz (issues #487 / #677).
with self._connect() as conn:
- if turn_id is not None:
- row = conn.execute(
- """
- SELECT n.*, COALESCE(s.title, '') AS session_title
- FROM notebook_entries n
- LEFT JOIN sessions s ON s.id = n.session_id
- WHERE n.session_id = ?
- AND n.turn_id = ?
- AND n.question_id = ?
- """,
- (session_id, turn_id, question_id),
- ).fetchone()
- else:
- # Legacy lookup: return the most recent matching entry across
- # turns. Two quizzes in the same session can share a question_id
- # (positional IDs like ``q_1``), so we explicitly pick the
- # newest one to keep behavior deterministic for callers that
- # don't yet pass a turn_id.
- row = conn.execute(
- """
- SELECT n.*, COALESCE(s.title, '') AS session_title
- FROM notebook_entries n
- LEFT JOIN sessions s ON s.id = n.session_id
- WHERE n.session_id = ? AND n.question_id = ?
- ORDER BY n.updated_at DESC, n.id DESC
- LIMIT 1
- """,
- (session_id, question_id),
- ).fetchone()
+ row = conn.execute(
+ """
+ SELECT n.*, COALESCE(s.title, '') AS session_title
+ FROM notebook_entries n
+ LEFT JOIN sessions s ON s.id = n.session_id
+ WHERE n.session_id = ?
+ AND n.turn_id = ?
+ AND n.question_id = ?
+ """,
+ (session_id, turn_id if turn_id is not None else "", question_id),
+ ).fetchone()
if row is None:
return None
return self._serialize_notebook_entry(row)
diff --git a/tests/api/test_notebook_router.py b/tests/api/test_notebook_router.py
index e95951744..7e709da4e 100644
--- a/tests/api/test_notebook_router.py
+++ b/tests/api/test_notebook_router.py
@@ -290,12 +290,13 @@ def test_quiz_state_isolated_per_turn(store: SQLiteSessionStore) -> None:
assert scoped_b.json()["turn_id"] == "turn_B"
-def test_lookup_without_turn_id_falls_back_to_latest(
+def test_lookup_without_turn_id_only_matches_legacy_namespace(
store: SQLiteSessionStore,
) -> None:
- """Callers that don't pass turn_id (legacy entries / external API) get the
- most recently updated matching entry — deterministic even when multiple
- turns share a question_id."""
+ """Regression test for #677 — a lookup that doesn't pass turn_id must
+ never see turn-scoped rows (positional ids like ``q_1`` repeat across
+ quizzes, so a cross-turn fallback leaks the previous quiz's answers into
+ a new quiz). It only matches the legacy namespace (turn_id='')."""
session = asyncio.run(store.create_session())
sid = session["id"]
@@ -304,7 +305,7 @@ def test_lookup_without_turn_id_falls_back_to_latest(
sid,
[
{
- "turn_id": "turn_old",
+ "turn_id": "turn_A",
"question_id": "q1",
"question": "Q?",
"user_answer": "A",
@@ -313,30 +314,37 @@ def test_lookup_without_turn_id_falls_back_to_latest(
],
)
)
- asyncio.run(
- store.upsert_notebook_entries(
- sid,
- [
- {
- "turn_id": "turn_new",
- "question_id": "q1",
- "question": "Q?",
- "user_answer": "B",
- "is_correct": True,
- }
- ],
- )
- )
with TestClient(_build_app(store)) as client:
+ # Turn-scoped rows are invisible without their turn_id.
resp = client.get(
"/api/v1/question-notebook/entries/lookup/by-question",
params={"session_id": sid, "question_id": "q1"},
)
- assert resp.status_code == 200
- body = resp.json()
- assert body["turn_id"] == "turn_new"
- assert body["user_answer"] == "B"
+ assert resp.status_code == 404
+
+ # Pre-turn-scoping rows (migrated with turn_id='') stay reachable.
+ asyncio.run(
+ store.upsert_notebook_entries(
+ sid,
+ [
+ {
+ "turn_id": "",
+ "question_id": "q1",
+ "question": "Q?",
+ "user_answer": "B",
+ "is_correct": True,
+ }
+ ],
+ )
+ )
+ legacy = client.get(
+ "/api/v1/question-notebook/entries/lookup/by-question",
+ params={"session_id": sid, "question_id": "q1"},
+ )
+ assert legacy.status_code == 200
+ assert legacy.json()["turn_id"] == ""
+ assert legacy.json()["user_answer"] == "B"
def test_lookup_missing_entry_returns_404_by_default(store: SQLiteSessionStore) -> None:
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 68fe074c3..b8c1ea154 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -44,6 +44,7 @@ import { useVoiceAutoplay } from "@/hooks/useVoiceAutoplay";
import { extractMathAnimatorResult } from "@/lib/math-animator-types";
import {
extractQuizQuestions,
+ extractQuizTurnId,
extractStreamingQuizQuestions,
} from "@/lib/quiz-types";
import { extractVisualizeResult } from "@/lib/visualize-types";
@@ -346,6 +347,15 @@ const AssistantMessage = memo(function AssistantMessage({
return extractStreamingQuizQuestions(msg.events ?? []);
}, [msg.capability, msg.events, resultEvent]);
+ // Turn identity for the quiz card. Derived from the streamed events, not
+ // just the final result event — during generation the result hasn't landed
+ // yet, and a null turn id would let the QuizViewer fall back to
+ // session-wide notebook state from a previous quiz (issue #677).
+ const quizTurnId = useMemo(() => {
+ if (msg.capability !== "deep_question") return null;
+ return extractQuizTurnId(msg.events);
+ }, [msg.capability, msg.events]);
+
const mathAnimatorResult = useMemo(() => {
if (msg.capability !== "math_animator" || !resultEvent) return null;
return extractMathAnimatorResult(resultEvent.metadata);
@@ -465,7 +475,7 @@ const AssistantMessage = memo(function AssistantMessage({
<QuizViewer
questions={quizQuestions}
sessionId={sessionId}
- turnId={resultEvent?.turn_id ?? null}
+ turnId={quizTurnId}
language={language}
/>
</>
diff --git a/web/components/quiz/QuizViewer.tsx b/web/components/quiz/QuizViewer.tsx
index dd6fd6a22..e15752441 100644
--- a/web/components/quiz/QuizViewer.tsx
+++ b/web/components/quiz/QuizViewer.tsx
@@ -69,9 +69,11 @@ interface QuizViewerProps {
/**
* The ``turn_id`` of the assistant turn that produced this quiz. Scopes
* notebook lookups/upserts so two quizzes generated in the same chat
- * session don't share answer state (see issue #487). When absent, the
- * component falls back to legacy session-wide scoping for backward
- * compatibility with already-persisted entries.
+ * session don't share answer state — positional question ids
+ * (``q_1``..``q_N``) repeat across quizzes (issues #487 / #677). When
+ * absent (only legacy turns persisted before turn ids existed), the card
+ * is local-only: answers grade client-side but the notebook is never
+ * read or written, so state can't leak across quizzes.
*/
turnId?: string | null;
language?: string;
@@ -260,6 +262,10 @@ export default function QuizViewer({
const refreshEntryId = useCallback(
async (qKey: string, sId: string, questionIndex?: number) => {
+ // No turn identity → no notebook reads. A turn-less lookup can only
+ // resolve against another turn's rows (question ids are positional),
+ // which is exactly the cross-quiz answer inheritance of #677.
+ if (!turnId) return;
try {
const entry = await lookupNotebookEntry(sId, qKey, turnId);
if (entry) {
@@ -438,7 +444,11 @@ export default function QuizViewer({
);
useEffect(() => {
- if (!sessionId || total === 0 || completedCount !== total) return;
+ // Reporting requires a turn identity: an empty ``turn_id`` write lands
+ // in the shared legacy namespace, where the next quiz's identically
+ // numbered questions would pick it up as their own answers (#677).
+ if (!sessionId || !turnId || total === 0 || completedCount !== total)
+ return;
const signature = JSON.stringify(submittedResults);
if (!signature || signature === lastReportedSignatureRef.current) return;
lastReportedSignatureRef.current = signature;
@@ -470,7 +480,7 @@ export default function QuizViewer({
answer: AnswerState,
questionIndex: number,
) => {
- if (!sessionId) return;
+ if (!sessionId || !turnId) return;
const key = getQuestionKey(question, questionIndex);
try {
const imagePayload = answer.images.map((image) => ({
@@ -482,7 +492,7 @@ export default function QuizViewer({
}));
const entry = await upsertNotebookEntry({
session_id: sessionId,
- turn_id: turnId || "",
+ turn_id: turnId,
question_id: question.question_id,
question: question.question,
question_type: question.question_type,
diff --git a/web/lib/quiz-types.ts b/web/lib/quiz-types.ts
index 8760af98f..634ed0c21 100644
--- a/web/lib/quiz-types.ts
+++ b/web/lib/quiz-types.ts
@@ -129,6 +129,32 @@ export function extractStreamingQuizQuestions(
.map((entry) => entry.qa);
}
+/**
+ * Resolve the turn identity of a quiz message from its event stream.
+ *
+ * Quiz answer state is scoped per turn: the notebook unique key is
+ * ``(session_id, turn_id, question_id)`` and positional question ids
+ * (``q_1``..``q_N``) repeat across quizzes in one session. During
+ * generation the final ``result`` event hasn't landed yet, so the turn id
+ * must come from the streamed events themselves — every unified-WS event
+ * carries ``turn_id``. The ``result`` event stays authoritative when
+ * present so the settled/persisted path is unchanged (issues #487 / #677).
+ *
+ * Returns ``null`` only for legacy persisted turns whose events predate
+ * ``turn_id``; QuizViewer renders those cards local-only (no notebook
+ * reads or writes), so they can never inherit another turn's answers.
+ */
+export function extractQuizTurnId(
+ events: Array<{ type?: string; turn_id?: string }> | undefined,
+): string | null {
+ if (!Array.isArray(events)) return null;
+ const result = events.find(
+ (event) => event.type === "result" && event.turn_id,
+ );
+ if (result?.turn_id) return result.turn_id;
+ return events.find((event) => event.turn_id)?.turn_id ?? null;
+}
+
/**
* Extract QuizQuestion[] from the raw `result` event metadata returned by
* the deep_question capability.
diff --git a/web/tests/quiz-turn-id.test.ts b/web/tests/quiz-turn-id.test.ts
new file mode 100644
index 000000000..efbe752d4
--- /dev/null
+++ b/web/tests/quiz-turn-id.test.ts
@@ -0,0 +1,44 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { extractQuizTurnId } from "../lib/quiz-types";
+
+// Regression tests for issue #677: during streaming generation the final
+// ``result`` event hasn't landed yet, but the quiz card still needs its turn
+// identity so notebook lookups/writes stay scoped to this quiz instead of
+// falling back to the previous quiz's session-wide state.
+
+test("extractQuizTurnId reads the turn id from streamed events before result", () => {
+ const events = [
+ { type: "stage_start", turn_id: "turn_B" },
+ {
+ type: "content",
+ turn_id: "turn_B",
+ metadata: { call_kind: "quiz_question_emitted" },
+ },
+ ];
+ assert.equal(extractQuizTurnId(events), "turn_B");
+});
+
+test("extractQuizTurnId prefers the result event's turn id", () => {
+ const events = [
+ { type: "content", turn_id: "turn_stream" },
+ { type: "result", turn_id: "turn_result" },
+ ];
+ assert.equal(extractQuizTurnId(events), "turn_result");
+});
+
+test("extractQuizTurnId skips events without a turn id", () => {
+ const events = [
+ { type: "session" },
+ { type: "content", turn_id: "" },
+ { type: "content", turn_id: "turn_C" },
+ ];
+ assert.equal(extractQuizTurnId(events), "turn_C");
+});
+
+test("extractQuizTurnId returns null for legacy turn-less events", () => {
+ assert.equal(extractQuizTurnId(undefined), null);
+ assert.equal(extractQuizTurnId([]), null);
+ assert.equal(extractQuizTurnId([{ type: "content" }]), null);
+});