fix(state): chain-aware dashboard session deletes; stats exclude compression children

Dashboard sessions endpoints treated compression-continuation children as
independent rows in two places:

- /api/sessions/stats counted every physical row, so total/active_store/
  archived were inflated by the hidden chain links while the paired
  list_sessions_rich page collapses each chain to one row (#54298).
- The bulk and single delete endpoints removed only the selected physical
  row. A list row carries the chain tip's id, so the root survived and the
  next list reload re-projected it onto the previous link — deleted
  conversations reappeared (#57543).

delete_session/delete_sessions gain include_compression_chain (opt-in; the
dashboard endpoints pass True). Lineage expansion walks compression edges in
both directions with the same edge definition as get_compression_tip and the
list-projection CTE (branch/reset/delegate/tool children excluded), collects
stale sibling continuations, threads the write-guard pass through the
expanded lineage, sweeps transcript files of every chain member, and keeps
the returned count equal to the selected rows. The default stays chain-blind
for existing callers (CLI /exit --delete, ACP, gateway API).

Fixes #54298, Fixes #57543

Salvaged from #54300 (stats exclude_children; @liuhao1024) and #57996
(lineage expansion; @draix), adapted onto the web_routers split and the
guard-aware delete paths.

Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
Co-authored-by: draix <draixagent@gmail.com>
This commit is contained in:
Austin Pickett
2026-10-06 10:59:27 -04:00
parent 535f2161dc
commit aaf7f199d5
4 changed files with 506 additions and 18 deletions

View File

@@ -441,6 +441,12 @@ async def bulk_delete_sessions_endpoint(body: BulkDeleteSessions):
Per :meth:`SessionDB.delete_sessions`: unknown ids are skipped (``deleted``
reports what really happened), children are orphaned, active/archived rows
ARE deleted (hand-picked), on-disk cleanup is left to the next prune.
Compression chains are deleted whole: the sessions list shows one row per
logical conversation carrying the chain *tip's* id, so deleting only that
row would leave the root to resurface as the previous chain link on the
next reload (#57543). ``deleted`` still counts the selected rows, not the
expanded chain links.
"""
# Hard cap so a runaway selection can't lock the writer for long.
if len(body.ids) > 500:
@@ -448,7 +454,8 @@ async def bulk_delete_sessions_endpoint(body: BulkDeleteSessions):
profile = destructive_profile(body.profile, "POST /api/sessions/bulk-delete")
skipped: list[str] = [] # rows a live turn/compression still owns; the UI must keep them listed
deleted = await asyncio.to_thread(_with_db, profile, lambda db: db.delete_sessions(
body.ids, exclude_active_write_guards=True, skipped_ids=skipped), read_only=False)
body.ids, exclude_active_write_guards=True, skipped_ids=skipped,
include_compression_chain=True), read_only=False)
return {"ok": True, "deleted": deleted, "skipped_active": skipped}
@@ -507,9 +514,12 @@ async def get_session_stats(profile: Optional[str] = None):
"""Session-store statistics (mirrors `hermes sessions stats`)."""
def _stats(db):
out = {
"total": db.session_count(include_archived=True),
"active_store": db.session_count(include_archived=False),
"archived": db.session_count(archived_only=True), "messages": db.message_count(),
# exclude_children=True: the dashboard Sessions page pairs these counts with
# list_sessions_rich rows, which collapse compression chains to one row carrying
# the tip's id — the raw row count is inflated by the hidden chain links (#54298).
"total": db.session_count(include_archived=True, exclude_children=True),
"active_store": db.session_count(include_archived=False, exclude_children=True),
"archived": db.session_count(archived_only=True, exclude_children=True), "messages": db.message_count(),
"by_source": {}}
try:
out["by_source"] = db.session_count_by_source(
@@ -799,7 +809,12 @@ async def delete_session_endpoint(session_id: str, profile: Optional[str] = None
if not sid:
return {"ok": True, "already_absent": True}
try:
db.delete_session(sid, sessions_dir=_session_files_dir(profile), exclude_active_write_guards=True)
# Chain-aware like bulk-delete: the list row the user clicked represents the
# whole compression chain (and carries the tip's id), so deleting just this
# physical row would resurface the conversation as the previous chain link
# on reload (#57543).
db.delete_session(sid, sessions_dir=_session_files_dir(profile),
exclude_active_write_guards=True, include_compression_chain=True)
except SessionActiveWriteGuardError as exc:
raise HTTPException(status_code=409, detail=str(exc))
return {"ok": True}

View File

@@ -23,6 +23,7 @@ from hermes_state_common import (
_sql_in_window, _sql_json_extract, _sql_session_last_active, _sql_session_last_active_by_id,
escape_like as _escape_like, _SQL_IN_CHUNK, _id_chunks, _placeholders as _session_ids_placeholders,
)
from hermes_state_compression import _CHAIN_CAP
# caplog tests pin the "hermes_state" logger name.
logger = logging.getLogger("hermes_state")
@@ -150,6 +151,42 @@ def _session_filter_where(
return where, params
def _expand_compression_lineage_ids(conn, frontier: List[str]) -> List[str]:
"""One both-direction compression-edge step from *frontier*: forward through every
continuation child and backward through the compression parent, using the SAME edge
definition as ``_CHAIN_STEP_SQL`` / the list-projection CTE (parent ended with
``reason='compression'``, child is not a branch / reset / delegate / tool session).
Branch/reset children are NOT continuations — they are their own conversations."""
ids = [sid for sid in frontier if sid]
if not ids:
return []
out: List[str] = []
for chunk in _id_chunks(ids, _SQL_IN_CHUNK // 4): # each id bound 4x below
ph = _session_ids_placeholders(chunk)
child_filter = (
f"{_sql_json_extract('child.model_config', '$._branched_from')} IS NULL "
f"AND {_sql_json_extract('child.model_config', '$._delegate_from')} IS NULL "
f"AND NOT ({_RESET_CHILD_SQL.format(a='child')}) "
"AND COALESCE(child.source, '') != 'tool'"
)
out.extend(row["id"] for row in conn.execute(
# forward: every continuation of a compression-ended frontier row
f"SELECT child.id FROM sessions parent "
f"JOIN sessions child ON child.parent_session_id = parent.id "
f"WHERE parent.id IN ({ph}) AND parent.end_reason = 'compression' AND {child_filter}",
chunk,
).fetchall())
out.extend(row["id"] for row in conn.execute(
# backward: the compression parent of a frontier row
f"SELECT parent.id FROM sessions child "
f"JOIN sessions parent ON parent.id = child.parent_session_id "
f"WHERE child.id IN ({ph}) AND parent.end_reason = 'compression' "
f"AND {child_filter}",
chunk,
).fetchall())
return out
def _collect_delegate_child_ids(conn, parent_ids: List[str]) -> List[str]:
"""Delegate-subagent ids (``_delegate_from`` marker, walked recursively) to cascade-delete with
*parent_ids*; untagged children stay orphaned, not deleted."""
@@ -1618,17 +1655,65 @@ class SessionSessionsMixin:
delegate_ids = _collect_delegate_child_ids(conn, [session_id])
return [session_id, *sorted(delegate_ids)]
def _expand_compression_lineage(self, conn, session_ids: List[str]) -> List[str]:
"""Expand *session_ids* to every member of their compression chains.
The dashboard sessions list surfaces one row per logical conversation: compression
roots are projected forward to their latest continuation, and the surfaced row
carries the *tip's* id (see :meth:`list_sessions_rich`). Deleting only that tip row
leaves the root behind, and the next list re-projects the root onto the previous
link — the "deleted" conversation reappears (#57543).
Walks compression-continuation edges in BOTH directions from the given ids:
backward to the chain root, and forward through every continuation — including
stale sibling continuations (e.g. ``ws_orphan_reap`` leftovers), which would
otherwise be orphaned into brand-new visible top-level rows by the delete itself.
The edge definition matches ``_CHAIN_STEP_SQL`` / ``get_compression_tip`` and the
list-projection CTE: parent ended with ``reason='compression'``, child is not a
branch / reset / delegate / tool session. Branch, reset and delegate children are
deliberately NOT pulled in — a branch/reset is its own conversation, and delegates
are handled by the existing cascade in the delete paths.
Runs inside the caller's write transaction (*conn*). The walk is defensively
bounded like ``get_compression_chain`` — ``seen`` guards cycles.
"""
seen = set(session_ids)
frontier = list(session_ids)
for _ in range(_CHAIN_CAP):
if not frontier:
break
targets = _expand_compression_lineage_ids(conn, frontier)
frontier = [sid for sid in targets if sid not in seen]
seen.update(frontier)
return list(seen)
def delete_session(
self, session_id: str, sessions_dir: Optional[Path] = None,
expected_delete_ids: Optional[List[str]] = None,
expected_display_messages: Optional[Dict[str, List[Dict[str, Any]]]] = None,
exclude_active_write_guards: bool = False,
include_compression_chain: bool = False,
) -> bool:
"""Delete a session and its messages; delegate children cascade, branch/compression children
are orphaned. Optional expected ids fence delegate drift; expected display snapshots fence
transcript drift. Both checks run inside the same write transaction as deletion.
With ``exclude_active_write_guards``, raises :class:`SessionActiveWriteGuardError` if the row
is protected by an active turn lease or compression lock."""
is protected by an active turn lease or compression lock.
With ``include_compression_chain=True`` the whole compression chain the session belongs to
is deleted with it (root and every continuation) — the dashboard delete endpoints use this
variant because their list rows carry chain-*tip* ids; deleting only that physical row
would leave the rest of the chain to resurface on the next list (#57543). Default False so
callers that operate on a single physical session keep the historic contract. Routing
through :meth:`delete_sessions` keeps the chain-aware guard/counting semantics in one
place; its return value counts the *requested* ids that existed, so ``> 0`` is exactly
"the session was found"."""
if include_compression_chain:
return self.delete_sessions(
[session_id], sessions_dir=sessions_dir,
exclude_active_write_guards=exclude_active_write_guards,
include_compression_chain=True,
) > 0
removed_ids: List[str] = []
expected_ids = set(expected_delete_ids) if expected_delete_ids is not None else None
def _do(conn):
@@ -1699,11 +1784,19 @@ class SessionSessionsMixin:
def delete_sessions(
self, session_ids: List[str], sessions_dir: Optional[Path] = None,
exclude_active_write_guards: bool = False, skipped_ids: Optional[List[str]] = None,
include_compression_chain: bool = False,
) -> int:
"""Bulk delete with :meth:`delete_session` semantics per row, in ONE transaction. Unknown ids
are skipped (UI selection can race another tab's delete). With ``exclude_active_write_guards``,
rows protected by an active turn lease or compression lock are skipped and, when given, appended
to ``skipped_ids`` so callers can tell the user. Returns the number deleted."""
are skipped (UI selection can race another tab's delete). With ``exclude_active_write_guards``, rows
protected by an active turn lease or compression lock are skipped and, when given, appended
to ``skipped_ids`` so callers can tell the user. Returns the number deleted.
With ``include_compression_chain=True``, each selected id is expanded to its full
compression chain (root + every continuation, including stale sibling continuations)
via :meth:`_expand_compression_lineage` — the dashboard rows carry chain-tip ids, so
without the expansion a "deleted" conversation resurfaces as the previous chain link on
the next list reload (#57543). The returned count still reflects the *requested* rows,
not the expanded chain links, so the caller's toast matches the user's selection."""
unique_ids = list({sid for sid in session_ids or () if isinstance(sid, str) and sid})
if not unique_ids:
return 0
@@ -1714,23 +1807,44 @@ class SessionSessionsMixin:
).fetchall()]
if not existing:
return 0
if include_compression_chain:
# Expand BEFORE the guard pass so a guarded chain member (active turn lease /
# compression lock anywhere in the lineage) keeps its selected root listed too.
expanded = self._expand_compression_lineage(conn, existing)
else:
expanded = existing
guard_pool = [*expanded, *_collect_delegate_child_ids(conn, expanded)]
if exclude_active_write_guards:
# A root is skipped when it or any delegate child it would cascade is guarded, so the
# cascade below never deletes a guarded row reported back as kept.
# cascade below never deletes a guarded row reported back as kept. When the chain
# expansion is on, a guard on ANY lineage member keeps its selected root: deleting
# a torn chain would re-surface it (the root re-projects onto a surviving link).
# One batched check first; per-root attribution only when something is guarded.
active_ids: set = set()
if self._guarded_ids(conn, [*existing, *_collect_delegate_child_ids(conn, existing)]):
active_ids = {
sid for sid in existing
if self._guarded_ids(conn, [sid, *_collect_delegate_child_ids(conn, [sid])])
}
if self._guarded_ids(conn, guard_pool):
if include_compression_chain:
for sid in existing:
member_lineage = set(self._expand_compression_lineage(conn, [sid]))
member_lineage.add(sid)
if self._guarded_ids(conn, [*member_lineage,
*_collect_delegate_child_ids(conn, list(member_lineage))]):
active_ids.add(sid)
else:
active_ids = {
sid for sid in existing
if self._guarded_ids(conn, [sid, *_collect_delegate_child_ids(conn, [sid])])
}
existing = [sid for sid in existing if sid not in active_ids]
if skipped_ids is not None:
skipped_ids.extend(sorted(active_ids))
if not existing:
return 0
removed_ids.extend(_delete_delegate_children(conn, existing))
for chunk in _id_chunks(existing):
if include_compression_chain:
expanded = self._expand_compression_lineage(conn, existing)
else:
expanded = existing
removed_ids.extend(_delete_delegate_children(conn, expanded))
for chunk in _id_chunks(expanded):
ph = _session_ids_placeholders(chunk)
conn.execute( # orphan children whose parent is in the kill list (FK)
f"UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id IN ({ph})", chunk,
@@ -1738,7 +1852,10 @@ class SessionSessionsMixin:
conn.execute(f"DELETE FROM messages WHERE session_id IN ({ph})", chunk)
conn.execute(f"DELETE FROM sessions WHERE id IN ({ph})", chunk)
self._delete_unreferenced_system_prompts(conn)
removed_ids.extend(existing)
removed_ids.extend(expanded)
# Count the ids the CALLER asked for, not the expanded chain links —
# the dashboard toast should say "3 deleted" when the user selected
# 3 rows, however many physical links those rows had.
return len(existing)
count = self._execute_write(_do)
for sid in removed_ids:

View File

@@ -0,0 +1,152 @@
"""Dashboard sessions endpoints vs compression-continuation children (#54298, #57543).
The sessions list collapses each compression chain to one row carrying the *tip's*
id; these tests pin the paired stats count and both delete endpoints to that
projection. Kept in a topical sibling (not ``test_web_server.py``, which is over
its file-lines ratchet cap and may only go down).
"""
import pytest
class _SessionsCompressionEndpoints:
"""Shared harness: TestClient pair against the isolated HERMES_HOME store."""
@pytest.fixture(autouse=True)
def _setup_test_client(self, monkeypatch, _isolate_hermes_home):
try:
from starlette.testclient import TestClient
except ImportError:
pytest.skip("fastapi/starlette not installed")
import hermes_state
from hermes_constants import get_hermes_home
from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
monkeypatch.setattr(
hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db"
)
self.client = TestClient(app)
self.auth_client = TestClient(app)
self.auth_client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
class TestSessionStatsCompressionChildren(_SessionsCompressionEndpoints):
"""``GET /api/sessions/stats`` must pair with the list (#54298)."""
def test_session_stats_excludes_compression_children(self):
"""Stats counts every physical row while the paired list collapses each
chain to one row — total/active_store/archived were inflated by the
hidden chain links and never matched the listed rows."""
from hermes_state import SessionDB
db = SessionDB()
try:
# compression chain: root -> child1 -> child2 -> live tip
db.create_session(session_id="comp-root", source="cli")
db.append_message("comp-root", role="user", content="root")
db.end_session("comp-root", end_reason="compression")
db.create_session(session_id="comp-child1", source="cli", parent_session_id="comp-root")
db.append_message("comp-child1", role="user", content="child1")
db.end_session("comp-child1", end_reason="compression")
db.create_session(session_id="comp-child2", source="cli", parent_session_id="comp-child1")
db.append_message("comp-child2", role="user", content="child2")
db.end_session("comp-child2", end_reason="compression")
db.create_session(session_id="comp-tip", source="cli", parent_session_id="comp-child2")
db.append_message("comp-tip", role="user", content="tip")
# an archived standalone session
db.create_session(session_id="archived", source="cli")
db.append_message("archived", role="user", content="old")
db.set_session_archived("archived", True)
# an active standalone session
db.create_session(session_id="standalone", source="cli")
db.append_message("standalone", role="user", content="solo")
finally:
db.close()
stats = self.auth_client.get("/api/sessions/stats").json()
# 6 rows in the DB; the list surfaces 3 conversations: the compression
# chain (collapsed to its tip, counted once at the root), the archived
# standalone, and the active standalone.
assert stats["total"] == 3, stats
assert stats["active_store"] == 2, stats
assert stats["archived"] == 1, stats
class TestDeleteSessionCompressionChain(_SessionsCompressionEndpoints):
"""``DELETE /api/sessions/{session_id}`` — single-row flavour of #57543."""
def test_delete_removes_whole_compression_chain(self):
"""The list row the user clicked carries the chain tip's id; deleting it
must take the root with it, or the conversation resurfaces as the
previous chain link on the next reload."""
from hermes_state import SessionDB
db = SessionDB()
try:
db.create_session("conv_root", source="tui")
db.end_session("conv_root", end_reason="compression")
db.create_session(
session_id="conv_tip", source="tui", parent_session_id="conv_root"
)
finally:
db.close()
resp = self.auth_client.delete("/api/sessions/conv_tip")
assert resp.status_code == 200
assert resp.json().get("ok") is True
db = SessionDB()
try:
assert db.get_session("conv_tip") is None
assert db.get_session("conv_root") is None
finally:
db.close()
class TestBulkDeleteCompressionChain(_SessionsCompressionEndpoints):
"""``POST /api/sessions/bulk-delete`` — the #57543 multi-select repro."""
def test_deletes_whole_compression_chain_of_each_selected_root(self):
"""The sessions list surfaces a compressed conversation as ONE row
carrying the chain tip's id. Bulk-deleting that id must remove the whole
chain — otherwise the root resurfaces as the previous link on the next
reload and the user sees the delete "not work". ``deleted`` counts
selected rows, and other lineages / standalone rows survive untouched."""
from hermes_state import SessionDB
db = SessionDB()
try:
# chain A (selected): a_root -> a_tip
db.create_session("a_root", source="tui")
db.end_session("a_root", end_reason="compression")
db.create_session("a_tip", source="tui", parent_session_id="a_root")
# chain B (selected): b_root -> b_mid -> b_tip
db.create_session("b_root", source="tui")
db.end_session("b_root", end_reason="compression")
db.create_session("b_mid", source="tui", parent_session_id="b_root")
db.end_session("b_mid", end_reason="compression")
db.create_session("b_tip", source="tui", parent_session_id="b_mid")
# chain C — NOT selected
db.create_session("c_root", source="tui")
db.end_session("c_root", end_reason="compression")
db.create_session("c_tip", source="tui", parent_session_id="c_root")
# standalones — NOT selected
db.create_session("solo", source="tui")
finally:
db.close()
resp = self.auth_client.post(
"/api/sessions/bulk-delete", json={"ids": ["a_tip", "b_tip"]}
)
assert resp.status_code == 200
assert resp.json() == {"ok": True, "deleted": 2, "skipped_active": []}
db = SessionDB()
try:
for gone in ("a_root", "a_tip", "b_root", "b_mid", "b_tip"):
assert db.get_session(gone) is None, gone
for kept in ("c_root", "c_tip", "solo"):
assert db.get_session(kept) is not None, kept
finally:
db.close()

View File

@@ -0,0 +1,204 @@
"""Chain-aware deletion invariants for the dashboard delete endpoints (#57543).
``list_sessions_rich`` surfaces one row per logical conversation: compression roots
are projected forward and the row carries the chain *tip's* id. Deleting only that
physical row leaves the root behind, and the next list re-projects it onto the
previous link — the user sees the "deleted" conversation reappear ("deletes some
of them, but not all"). Invariants this module locks in:
1. Deleting a tip removes the whole chain (backward walk to root).
2. Deleting a root removes every continuation — including stale sibling
continuations, which orphaning would otherwise promote into visible
top-level rows.
3. Branch / reset / delegate children of chain members keep the plain
contract (orphaned, not deleted); delegate children are cascade-deleted.
4. The returned count reflects the *selected* rows, not the expanded chain
links, so the dashboard toast matches what the user picked.
5. The default stays chain-blind — existing callers (CLI ``/exit --delete``,
ACP, gateway API) are behaviour-identical.
6. Deletion is EXACT: only the selected roots' own compression chains die;
every other lineage and standalone row survives untouched.
"""
from hermes_state import SessionDB
def _make_chain(db, root="root", mid="mid", tip="tip"):
"""root --compression--> mid --compression--> tip (live)."""
db.create_session(root, source="tui")
db.append_message(root, role="user", content="the start")
db.end_session(root, "compression")
db.create_session(mid, source="tui", parent_session_id=root)
db.append_message(mid, role="user", content="continued once")
db.end_session(mid, "compression")
db.create_session(tip, source="tui", parent_session_id=mid)
db.append_message(tip, role="user", content="continued twice")
def _seeded_db(tmp_path):
return SessionDB(tmp_path / "state.db")
def test_deleting_tip_removes_whole_chain(tmp_path):
"""The exact #57543 repro: the dashboard row carries the tip id; bulk-deleting
it must not leave the root to resurface on the next list reload."""
db = _seeded_db(tmp_path)
_make_chain(db)
assert [r["id"] for r in db.list_sessions_rich(limit=20)] == ["tip"]
assert db.delete_sessions(["tip"], include_compression_chain=True) == 1
assert db.get_session("root") is None
assert db.get_session("mid") is None
assert db.get_session("tip") is None
assert db.list_sessions_rich(limit=20) == []
db.close()
def test_bulk_delete_removes_whole_chain_of_each_selected_root_and_nothing_else(tmp_path):
"""EXACTNESS (#57543 sweeper risk): two selected roots with their own chains —
both chains vanish whole, and every other lineage / standalone row survives."""
db = _seeded_db(tmp_path)
# chain A (selected)
_make_chain(db, root="a_root", mid="a_mid", tip="a_tip")
# chain B (selected)
db.create_session("b_root", source="tui")
db.append_message("b_root", role="user", content="b start")
db.end_session("b_root", "compression")
db.create_session("b_tip", source="tui", parent_session_id="b_root")
# chain C — NOT selected, must survive whole
db.create_session("c_root", source="tui")
db.end_session("c_root", "compression")
db.create_session("c_tip", source="tui", parent_session_id="c_root")
# standalone rows — must survive
db.create_session("solo1", source="tui")
db.create_session("solo2", source="tui")
deleted = db.delete_sessions(["a_tip", "b_tip"], include_compression_chain=True)
assert deleted == 2 # counts selected rows, not the 5 physical links
for gone in ("a_root", "a_mid", "a_tip", "b_root", "b_tip"):
assert db.get_session(gone) is None, gone
for kept in ("c_root", "c_tip", "solo1", "solo2"):
assert db.get_session(kept) is not None, kept
# chain C stays a single projected row; standalones still listed
assert {r["id"] for r in db.list_sessions_rich(limit=20)} == {"c_tip", "solo2", "solo1"}
db.close()
def test_deleting_root_removes_continuations_and_stale_siblings(tmp_path):
"""Forward direction: every compression child dies with the chain — including a
stale sibling continuation, which orphaning would otherwise promote into a
visible top-level row."""
db = _seeded_db(tmp_path)
db.create_session("root", source="tui")
db.end_session("root", "compression")
db.create_session("tip", source="tui", parent_session_id="root")
db.create_session("stale", source="tui", parent_session_id="root")
db.end_session("stale", "ws_orphan_reap")
assert db.delete_sessions(["root"], include_compression_chain=True) == 1
assert db.get_session("root") is None
assert db.get_session("tip") is None
assert db.get_session("stale") is None
db.close()
def test_chain_delete_orphans_branches_and_cascades_delegates(tmp_path):
"""Branch / reset / delegate children of chain members keep the plain per-row
contract: a branch (or reset fork) is its own conversation and survives
(orphaned); a delegate subagent run is cascade-deleted."""
db = _seeded_db(tmp_path)
_make_chain(db)
db.create_session("branch", source="tui", parent_session_id="root",
model_config={"_branched_from": "root"})
db.create_session("reset", source="tui", parent_session_id="mid",
model_config={"_reset_from": "mid"})
db.create_session("delegate", source="tui", parent_session_id="tip",
model_config={"_delegate_from": "tip"})
assert db.delete_sessions(["tip"], include_compression_chain=True) == 1
branch = db.get_session("branch")
assert branch is not None and branch["parent_session_id"] is None
reset = db.get_session("reset")
assert reset is not None and reset["parent_session_id"] is None
assert db.get_session("delegate") is None
db.close()
def test_count_reflects_selected_rows_not_chain_links(tmp_path):
"""Selecting 2 rows deletes 5 physical sessions but reports 2 — the toast
matches the user's selection."""
db = _seeded_db(tmp_path)
_make_chain(db)
db.create_session("plain", source="tui")
assert db.delete_sessions(["tip", "plain"], include_compression_chain=True) == 2
db.close()
def test_default_remains_chain_blind(tmp_path):
"""Without the flag, only the listed row is deleted — pins the historic
contract for non-dashboard callers."""
db = _seeded_db(tmp_path)
_make_chain(db)
assert db.delete_sessions(["tip"]) == 1
assert db.get_session("tip") is None
assert db.get_session("mid") is not None
assert db.get_session("root") is not None
db.close()
def test_single_delete_session_chain_variant(tmp_path):
"""``delete_session(..., include_compression_chain=True)`` — the single-row
dashboard endpoint has the same reappearing-conversation bug, so it routes
through the same expansion."""
db = _seeded_db(tmp_path)
_make_chain(db)
assert db.delete_session("tip", include_compression_chain=True) is True
assert db.get_session("root") is None
assert db.get_session("mid") is None
assert db.get_session("tip") is None
# Missing sessions still report False.
assert db.delete_session("ghost", include_compression_chain=True) is False
db.close()
def test_chain_transcript_files_cleaned(tmp_path):
"""On-disk transcripts of every expanded chain member are swept, not just the
selected row's."""
db = _seeded_db(tmp_path)
_make_chain(db)
sessions_dir = tmp_path / "sessions"
sessions_dir.mkdir()
(sessions_dir / "root.jsonl").write_text("")
(sessions_dir / "tip.json").write_text("{}")
# Another session's artifacts must survive.
(sessions_dir / "session_other.json").write_text("{}")
assert db.delete_sessions(["tip"], sessions_dir=sessions_dir,
include_compression_chain=True) == 1
assert not (sessions_dir / "root.jsonl").exists()
assert not (sessions_dir / "tip.json").exists()
assert (sessions_dir / "session_other.json").exists()
db.close()
def test_chain_delete_skips_guarded_lineage(tmp_path):
"""A live turn lease anywhere in the chain keeps the selected root: a torn
delete would re-surface the conversation, worse than skipping it."""
import os
db = _seeded_db(tmp_path)
_make_chain(db)
holder = f"pid={os.getpid()}:turn=1"
assert db.try_acquire_session_turn_lease("mid", holder, ttl_seconds=300.0) is True
skipped: list[str] = []
assert db.delete_sessions(["tip"], exclude_active_write_guards=True,
skipped_ids=skipped, include_compression_chain=True) == 0
assert skipped == ["tip"]
# whole chain survives
for kept in ("root", "mid", "tip"):
assert db.get_session(kept) is not None, kept
db.close()