fix(sessions): deleting or expiring a session drops its held routes too

A held route (its platform's plugin not registered yet) is written back by
every full routing save, but remove_by_session_id, release_route, the
stale-entry prune, routing expiry and canonical-delete retirement only
looked at the live index. Deleting session S left S's held row in memory and
in sessions.json/state.db; with a live and a held route for S only the live
one went. One helper now finds a session's live and held keys (deduped) and
one drops a key from both, so a shadowed held copy cannot reappear either;
an idle held row expires on the same clock as a live one.
This commit is contained in:
Teknium
2026-11-25 18:53:09 -08:00
parent fd312a3682
commit 5d3c913320
4 changed files with 126 additions and 28 deletions

View File

@@ -1074,7 +1074,7 @@ class SessionStore(
# Honour an explicit suspension/reset decision instead of silently reopening via recovery.
if reset_reason:
decision.schedule_reset(reset_reason, entry, entry.last_prompt_tokens > 0)
self._entries.pop(session_key, None)
self._drop_routes_locked([session_key])
decision.needs_recover = True
else:
# Internal/system events preserve the user-activity clock.
@@ -1298,10 +1298,8 @@ class SessionStore(
with self._lock:
held = getattr(self, "_unparsed_routes", None) or {}
dropped = [key for key in self._entries if key.startswith(ns)]
dropped += [key for key in held if key.startswith(ns)] # else the save below writes them back
for key in dropped:
self._entries.pop(key, None)
held.pop(key, None)
dropped += [key for key in held if key.startswith(ns) and key not in self._entries]
self._drop_routes_locked(dropped)
if dropped:
self._save()
return len(dropped)
@@ -1312,16 +1310,16 @@ class SessionStore(
The routing index is written back by THIS process, so removing only the state.db rows
elsewhere in a delete flow is undone by the next whole-index save: the surviving entry
hands the same id to the next inbound message and run_agent's INSERT OR IGNORE
re-creates the row — the deleted conversation comes back (#42422). Idempotent; returns
the number of entries dropped.
re-creates the row — the deleted conversation comes back (#42422). A held route (its
platform's plugin not registered yet) goes too, or that save writes it back. Idempotent;
returns the number of routes dropped.
"""
if not session_id:
return 0
with self._lock:
self._ensure_loaded_locked()
dropped = [key for key, entry in self._entries.items() if entry.session_id == session_id]
for key in dropped:
self._entries.pop(key, None)
dropped = self._route_keys_for_sessions_locked({session_id})
self._drop_routes_locked(dropped)
if dropped:
hints = getattr(self, "_session_owner_hints", None)
if hints is not None:
@@ -1340,7 +1338,7 @@ class SessionStore(
entry = self._entry_locked(session_key)
if entry is None or entry.session_id != session_id:
return False
self._entries.pop(session_key, None)
self._drop_routes_locked([session_key])
self._save()
return True

View File

@@ -9,7 +9,7 @@ import uuid
from datetime import datetime, timedelta, timezone, UTC
from typing import TYPE_CHECKING, Optional
from gateway.session_persistence import _apply_to_held_row
from gateway.session_persistence import _apply_to_held_row, _held_row_entry
from session_rules.session_ids import new_session_id
if TYPE_CHECKING:
@@ -305,17 +305,19 @@ class SessionLifecycleMixin:
if max_age_days is None or max_age_days <= 0:
return 0
cutoff = _now() - timedelta(days=max_age_days)
def _idle(key: str, entry: SessionEntry) -> bool:
# The callback is keyed by session_key, NOT session_id.
return (not entry.suspended and entry.updated_at < cutoff
and not self._has_active_processes_safe(key, context="prune"))
with self._lock:
self._ensure_loaded_locked()
removed_keys = [
key for key, entry in list(self._entries.items())
if not entry.suspended
# The callback is keyed by session_key, NOT session_id.
and not self._has_active_processes_safe(entry.session_key, context="prune")
and entry.updated_at < cutoff
]
for key in removed_keys:
self._entries.pop(key, None)
held = getattr(self, "_unparsed_routes", None) or {}
removed_keys = [key for key, entry in list(self._entries.items()) if _idle(entry.session_key, entry)]
# A held route (platform not registered yet) expires on the same clock, or it outlives every peer.
removed_keys += [key for key, data in held.items()
if key not in self._entries and _idle(key, _held_row_entry(data))]
self._drop_routes_locked(removed_keys)
if removed_keys:
self._save()
if removed_keys:

View File

@@ -87,12 +87,17 @@ def _with_platform(data: dict, name: str) -> dict:
return {**data, "platform": name, "origin": {**data["origin"], "platform": name}}
def _held_row_entry(data: dict):
"""A held row as a ``SessionEntry`` under a stand-in platform, for platform-independent checks."""
from gateway.session import SessionEntry
return SessionEntry.from_dict(_with_platform(data, "local"))
def _apply_to_held_row(data: dict, mutate) -> Optional[dict]:
"""Run a platform-independent whole-index verdict (turn-marker recovery or discard) on a held row now,
through a stand-in platform, so it reaches the row on disk even if the process exits before the
plugin registers. The new row, or None when *mutate* left it unchanged."""
from gateway.session import SessionEntry
entry = SessionEntry.from_dict(_with_platform(data, "local"))
entry = _held_row_entry(data)
if not mutate(entry):
return None
return _with_platform({**data, **entry.to_dict()}, data["origin"]["platform"])
@@ -105,12 +110,25 @@ class SessionPersistenceMixin:
"""Publish committed retirement; durable fences reject delayed saves."""
with self._lock:
targets = set(session_ids)
for key, entry in list(self._entries.items()):
if entry.session_id in targets:
del self._entries[key]
self._drop_routes_locked(self._route_keys_for_sessions_locked(targets))
for sid in targets:
self._session_owner_hints.pop(sid, None)
def _route_keys_for_sessions_locked(self, session_ids) -> list[str]:
"""Every key routing to one of *session_ids*, live or held (platform not registered yet), once
each. Lock held."""
held = getattr(self, "_unparsed_routes", None) or {}
live = [key for key, entry in self._entries.items() if entry.session_id in session_ids]
return list(dict.fromkeys(live + [key for key, data in held.items() if data["session_id"] in session_ids]))
def _drop_routes_locked(self, keys) -> None:
"""Drop *keys* from the live index AND the held rows: a held copy left behind is written back by
the next full save, so the route outlives its removal. Lock held."""
held = getattr(self, "_unparsed_routes", None) or {}
for key in keys:
self._entries.pop(key, None)
held.pop(key, None)
def fence_retired_routes(self, session_ids, *, namespace, expiring=()) -> None:
"""Durably retire *session_ids* in the routing index's own database (fences + route
drop in one transaction). A delete committed in another profile's store fences only that
@@ -578,8 +596,7 @@ class SessionPersistenceMixin:
except Exception as exc:
logger.warning("gateway.session: stale-entry pruning skipped due to DB error: %s", exc)
return
for key in stale_keys:
del self._entries[key]
self._drop_routes_locked(stale_keys)
if stale_keys or recovered_keys:
self._save()

View File

@@ -287,3 +287,84 @@ def test_a_plugin_registering_before_the_db_recovers_keeps_the_newer_db_route(tm
_unregister("yuanbao")
monkeypatch.setattr(type(db.routing), "load_routing_entries", real_load)
assert json.loads(db.routing.load_routing_entries(routing_scope=scope)[key])["resume_pending"] is True
def _durable_keys(store, db):
"""Route keys in both durable copies: state.db's routing table and the sessions.json mirror."""
mirror = json.loads((store.sessions_dir / "sessions.json").read_text(encoding="utf-8"))
return set(db.routing.load_routing_entries(routing_scope=store._routing_scope())), set(mirror) - {"_README"}
def _seed_two_held(tmp_path):
"""Two saved yuanbao routes (a run with the plugin wrote them) and a live telegram one; the restarted
store has no yuanbao plugin, so both yuanbao routes are held."""
store = SessionStore(tmp_path / "sessions", GatewayConfig())
Platform._add_pseudo_member("yuanbao")
try:
doomed = store.get_or_create_session(_yb_source())
kept = store.get_or_create_session(SessionSource(platform=Platform("yuanbao"), chat_id="U2", chat_type="dm"))
finally:
_unregister("yuanbao")
live = store.get_or_create_session(SessionSource(platform=Platform.TELEGRAM, chat_id="t1"))
restarted = SessionStore(store.sessions_dir, GatewayConfig())
with restarted._lock:
restarted._ensure_loaded_locked()
return restarted, doomed, kept, live
def test_hard_deleting_a_session_drops_its_held_route_from_both_durable_copies(tmp_path):
"""The delete endpoint's removal (#42422) covers a held route: gone at once and after an unrelated save,
other routes stay, a repeat is a no-op, and the plugin registering later starts a fresh session."""
from persistence_assembly import open_persistence, profile_scope
with open_persistence(profile_scope()) as db:
from gateway.platforms.api_server_store import delete_session
store, doomed, kept, live = _seed_two_held(tmp_path)
assert delete_session(db, doomed.session_id, store.sessions_dir) # the endpoint's order: rows, then routes
assert store.remove_by_session_id(doomed.session_id) == 1
for keys in _durable_keys(store, db):
assert doomed.session_key not in keys and {kept.session_key, live.session_key} <= keys
store.get_or_create_session(SessionSource(platform=Platform.TELEGRAM, chat_id="t2")) # unrelated full save
for keys in _durable_keys(store, db):
assert doomed.session_key not in keys and {kept.session_key, live.session_key} <= keys
assert store.remove_by_session_id(doomed.session_id) == 0
Platform._add_pseudo_member("yuanbao")
try:
assert store.get_or_create_session(_yb_source()).session_id != doomed.session_id
assert store.get_or_create_session(
SessionSource(platform=Platform("yuanbao"), chat_id="U2", chat_type="dm")).session_id == kept.session_id
finally:
_unregister("yuanbao")
def _rewrite_held_row(store, db, key, **fields):
"""Change a held route's saved row, then restart so the new store holds that copy."""
scope = store._routing_scope()
row = json.loads(db.routing.load_routing_entries(routing_scope=scope)[key])
db.routing.upsert_routing_entry(key, json.dumps({**row, **fields}), routing_scope=scope)
restarted = SessionStore(store.sessions_dir, GatewayConfig())
with restarted._lock:
restarted._ensure_loaded_locked()
return restarted
def test_hard_deleting_a_session_drops_its_live_and_held_routes_together(tmp_path):
"""Session S has a live telegram route and a held yuanbao route: both go in one delete, counted once each."""
from persistence_assembly import open_persistence, profile_scope
with open_persistence(profile_scope()) as db:
store, held, _kept, live = _seed_two_held(tmp_path)
store = _rewrite_held_row(store, db, held.session_key, session_id=live.session_id)
assert store.remove_by_session_id(live.session_id) == 2
store.get_or_create_session(SessionSource(platform=Platform.TELEGRAM, chat_id="t2"))
for keys in _durable_keys(store, db):
assert not {held.session_key, live.session_key} & keys
def test_expiring_an_idle_route_drops_an_idle_held_route_too(tmp_path):
"""Routing expiry covers a held route: an idle one is pruned like a live one, a fresh one stays."""
from persistence_assembly import open_persistence, profile_scope
with open_persistence(profile_scope()) as db:
store, idle, fresh, _live = _seed_two_held(tmp_path)
store = _rewrite_held_row(store, db, idle.session_key, updated_at="2001-01-01T00:00:00")
assert store.prune_old_entries(30) == 1
for keys in _durable_keys(store, db):
assert idle.session_key not in keys and fresh.session_key in keys