Skip to content

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

fix: re-parent descendants on turn delete and render orphaned message trees (#923)

zhouraym6c1dcca0ecfa
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 8ef2ebab8..daf8e30c4 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -1140,6 +1140,22 @@ class SQLiteSessionStore:
ids_to_delete = [int(message_id)]
if paired_msg is not None:
ids_to_delete.append(int(paired_msg["id"]))
+
+ # Splice the deleted rows out of the parent-pointer tree: children
+ # of a deleted row inherit its parent, in descending id order so a
+ # pair's subtree rides up to the pair's parent in one pass (#912).
+ for mid in sorted(ids_to_delete, reverse=True):
+ conn.execute(
+ """
+ UPDATE messages
+ SET parent_message_id = (
+ SELECT parent_message_id FROM messages WHERE id = ?
+ )
+ WHERE session_id = ? AND parent_message_id = ?
+ """,
+ (mid, session_id, mid),
+ )
+
conn.execute(
f"DELETE FROM messages WHERE id IN ({','.join('?' * len(ids_to_delete))})", # nosec B608
tuple(ids_to_delete),
diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.py
index 80984fd3f..1941935a9 100644
--- a/tests/services/session/test_sqlite_store.py
+++ b/tests/services/session/test_sqlite_store.py
@@ -265,3 +265,71 @@ def test_category_cascade_on_entry_delete(store: SQLiteSessionStore) -> None:
asyncio.run(store.delete_notebook_entry(eid))
cats = asyncio.run(store.list_categories())
assert cats[0]["entry_count"] == 0
+
+
+# ── Turn deletion / parent-pointer splicing ───────────────────────
+
+
+def _seed_chat(store: SQLiteSessionStore, turns: int) -> tuple[str, list[int]]:
+ """Seed a linear multi-turn chat; returns (session_id, message_ids) where
+ message_ids alternate user/assistant per turn."""
+ session = asyncio.run(store.create_session())
+ sid = session["id"]
+ ids: list[int] = []
+ parent: int | None = None
+ for i in range(turns):
+ uid = asyncio.run(store.add_message(sid, "user", f"q{i + 1}", parent_message_id=parent))
+ ids.append(uid)
+ aid = asyncio.run(store.add_message(sid, "assistant", f"a{i + 1}", parent_message_id=uid))
+ ids.append(aid)
+ parent = aid
+ return sid, ids
+
+
+def test_delete_first_turn_reparents_descendants(store: SQLiteSessionStore) -> None:
+ sid, ids = _seed_chat(store, turns=2)
+ u1, _a1, u2, a2 = ids
+
+ result = asyncio.run(store.delete_turn_by_message(sid, u1))
+ assert result["deleted"] is True
+
+ remaining = asyncio.run(store.get_messages(sid))
+ assert [m["content"] for m in remaining] == ["q2", "a2"]
+ assert remaining[0]["parent_message_id"] is None
+ assert remaining[1]["parent_message_id"] == u2
+ # The surviving chain is fully connected root → leaf.
+ path = asyncio.run(store.get_message_path(sid, a2))
+ assert [m["content"] for m in path] == ["q2", "a2"]
+
+
+def test_delete_middle_turn_keeps_chain_connected(store: SQLiteSessionStore) -> None:
+ sid, ids = _seed_chat(store, turns=3)
+ u1, a1, u2, _a2, u3, a3 = ids
+
+ result = asyncio.run(store.delete_turn_by_message(sid, u2))
+ assert result["deleted"] is True
+
+ remaining = asyncio.run(store.get_messages(sid))
+ assert [m["content"] for m in remaining] == ["q1", "a1", "q3", "a3"]
+ by_content = {m["content"]: m for m in remaining}
+ assert by_content["q3"]["parent_message_id"] == a1
+
+ path = asyncio.run(store.get_message_path(sid, a3))
+ assert [m["content"] for m in path] == ["q1", "a1", "q3", "a3"]
+ # u1 stays the session root.
+ assert by_content["q1"]["parent_message_id"] is None
+ assert by_content["q1"]["id"] == u1
+
+
+def test_delete_last_turn_leaves_prefix_intact(store: SQLiteSessionStore) -> None:
+ sid, ids = _seed_chat(store, turns=2)
+ _u1, a1, u2, _a2 = ids
+
+ result = asyncio.run(store.delete_turn_by_message(sid, u2))
+ assert result["deleted"] is True
+
+ remaining = asyncio.run(store.get_messages(sid))
+ assert [m["content"] for m in remaining] == ["q1", "a1"]
+ assert remaining[0]["parent_message_id"] is None
+ assert remaining[1]["parent_message_id"] == remaining[0]["id"]
+ assert remaining[1]["id"] == a1
diff --git a/web/lib/message-branches.ts b/web/lib/message-branches.ts
index 56dc2da76..bd079deda 100644
--- a/web/lib/message-branches.ts
+++ b/web/lib/message-branches.ts
@@ -80,6 +80,31 @@ export function buildVisiblePath(
const siblingsByMessageId = new Map<number, SiblingInfo>();
const guard = new Set<string>();
let currentParent = ROOT_KEY;
+ if ((childrenByParent.get(ROOT_KEY)?.length ?? 0) === 0) {
+ // Orphaned tree (no root message): legacy rows whose parent was deleted,
+ // or local state right after DELETE_TURN. Seed from the oldest orphan.
+ const ids = new Set<number>();
+ for (const msg of allMessages) {
+ if (msg.id !== undefined) ids.add(msg.id);
+ }
+ let seeds = allMessages.filter(
+ (m) =>
+ m.id !== undefined &&
+ m.parentMessageId != null &&
+ !ids.has(m.parentMessageId),
+ );
+ // Pure cycles have no orphan entry; fall back to the oldest message.
+ if (seeds.length === 0) {
+ seeds = allMessages.filter((m) => m.id !== undefined);
+ }
+ if (seeds.length > 0) {
+ let oldest = seeds[0];
+ for (const s of seeds) {
+ if (siblingRank(s) < siblingRank(oldest)) oldest = s;
+ }
+ currentParent = parentKey(oldest.parentMessageId);
+ }
+ }
// Bound the walk defensively against pathological data (loops).
let safety = 10_000;
while (safety > 0) {
diff --git a/web/tests/orphaned-tree.test.ts b/web/tests/orphaned-tree.test.ts
new file mode 100644
index 000000000..d22129efe
--- /dev/null
+++ b/web/tests/orphaned-tree.test.ts
@@ -0,0 +1,39 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { buildVisiblePath } from "../lib/message-branches";
+import type { MessageItem } from "../context/UnifiedChatContext";
+
+// Issue #912: deleting a turn left descendants pointing at deleted rows, so
+// buildVisiblePath found no root message and rendered a blank chat while
+// markdown export still worked. The walk must fall back to the oldest orphan.
+test("an orphaned tree (no root message) still renders from its oldest orphan", () => {
+ const messages = [
+ { id: 3, role: "user" as const, content: "q2", parentMessageId: 2 },
+ { id: 4, role: "assistant" as const, content: "a2", parentMessageId: 3 },
+ ];
+ const visible = buildVisiblePath(messages as unknown as MessageItem[], {});
+ assert.deepEqual(
+ visible.messages.map((m) => m.content),
+ ["q2", "a2"],
+ );
+});
+
+test("a healthy root always wins over orphaned subtrees", () => {
+ const messages = [
+ { id: 1, role: "user" as const, content: "q1", parentMessageId: null },
+ { id: 2, role: "assistant" as const, content: "a1", parentMessageId: 1 },
+ // Orphaned tail from a later deleted turn (parent 99 doesn't exist).
+ { id: 5, role: "user" as const, content: "q3", parentMessageId: 99 },
+ { id: 6, role: "assistant" as const, content: "a3", parentMessageId: 5 },
+ ];
+ const visible = buildVisiblePath(messages as unknown as MessageItem[], {});
+ assert.deepEqual(
+ visible.messages.map((m) => m.content),
+ ["q1", "a1"],
+ );
+});
+
+test("empty message list still yields an empty path", () => {
+ const visible = buildVisiblePath([], {});
+ assert.deepEqual(visible.messages, []);
+});