perf(dashboard): recursive-CTE descendant lookup in _session_latest_descendant

_session_latest_descendant fetched EVERY sessions row and built the
parent->children tree in Python on each call. Replace with a recursive
CTE that loads only the target session's descendant branch.

Hand-applied from PR #39140 (the schema-init cache and Rust PTY bridge
parts of that PR are intentionally NOT salvaged here); main's function
signature gained a db parameter since the PR was cut.

(cherry picked from commit 8ed5e54f65)
This commit is contained in:
sebastianlutycz 2026-07-08 17:31:34 +05:30 committed by kshitij
parent 492be28e50
commit d7e4d94e2f

View file

@ -9303,7 +9303,17 @@ def _session_latest_descendant(session_id: str, db):
rows = []
if conn is not None:
raw_rows = conn.execute(
"SELECT id, parent_session_id, started_at FROM sessions"
"""
WITH RECURSIVE descendants(id, parent_session_id, started_at) AS (
SELECT id, parent_session_id, started_at FROM sessions WHERE id = ?
UNION ALL
SELECT s.id, s.parent_session_id, s.started_at
FROM sessions s
JOIN descendants d ON s.parent_session_id = d.id
)
SELECT id, parent_session_id, started_at FROM descendants
""",
(sid,),
).fetchall()
for row in raw_rows:
rows.append({