Skip to content

Commit 10a38eb

Browse files
fix: a web release spares a newcomer's files, keeps the saved state, tears the adapter down
Review 2026-10-21, remediation plan 5, larger #1 (lane 2's found-not-fixed #1, #3, #4). ``session/active.py`` ``release()`` ran ``clear_session_files()`` unconditionally, so three things went wrong on every web ending: (a) The reaper's ``state_file_replaced`` release of session A deleted the state, topics and parking files a later session B had just written. ``release()`` now reads the state file first and touches nothing when it names another session. (b) The ``mode=ended`` state the end paths write (``persist_session_end``) was deleted with the rest, so ``/api/session/state`` answered ``{}`` and the SSE summary view (``_render.py`` ``mode == "ended"``) was unreachable for browser sessions. ``release()`` keeps a saved (``mode=ended``) state file; an unsaved or id-less one still goes, so a live-looking claim owned by this process's pid never outlives the slot. The marker is never written by ``release()``: it means "persisted" and only the code that persisted may say so. (c) Stop, agent exit, grace expiry, the reaper and shutdown saved the session (F-WEB-02) but never ran ``teardown_session``, so Kiro's agent-JSON restore and the persona-file unlink happened only on End. ``_grace._end_before_release`` (was ``_persist_before_release``) now runs ``end_session_common(raise_if_not_persisted=False)``: the same persist-then-teardown, in the same order, the End route and the CLI's ``cleanup_on_exit`` already run. A later End on the kept ended file is now idempotent (200 after an idempotent teardown) rather than 404, which the End dialog reads as "could not end, try again" and keeps open; lane 2's repeated-end test pins the new answer and that nothing is persisted twice.
1 parent 137ccad commit 10a38eb

4 files changed

Lines changed: 349 additions & 12 deletions

File tree

‎packages/studyloop/src/studyloop/session/active.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,5 +140,41 @@ async def release() -> None:
140140
)
141141

142142
loop = asyncio.get_running_loop()
143-
await loop.run_in_executor(None, session_state.clear_session_files)
143+
await loop.run_in_executor(None, _clear_files_of, session.study_session_id)
144144
logger.info("active session released id=%s", session.study_session_id)
145+
146+
147+
def _clear_files_of(study_session_id: str) -> None:
148+
"""Clear the IPC files the released session owned -- and only those.
149+
150+
Until review 2026-10-21 (plan 5, larger #1) this was an unconditional
151+
``clear_session_files()``, which deleted files the released session did not
152+
own in two ways. The state file names its owner, so read it first:
153+
154+
- **Another session's.** The reaper releases a slot whose state file no
155+
longer names it (``state_file_replaced``: a later start has written its
156+
claim, and its topics and parking files are its own). Nothing here is
157+
that session's to delete; touch nothing.
158+
- **Ours, saved.** Every end path writes ``mode=ended`` after persisting
159+
the session (``cleanup.persist_session_end``), and the dashboard's
160+
summary view renders from that file. Deleting it here is why a browser
161+
session never showed its summary. Keep the state file; the topics and
162+
parking files have been persisted and go. An ended claim blocks no
163+
start (``_claim_exists``), and the next start replaces the file.
164+
- **Ours, unsaved** (no ``mode=ended``: the marker write failed, or a
165+
caller released without ending) and **nobody's** (no id): as before,
166+
everything goes. A kept file would read as a live claim owned by this
167+
process's pid and refuse the next ``studyloop study``, and there is no
168+
saved summary for it to show. The marker is NOT written here: it means
169+
"persisted", and only the code that persisted may say so.
170+
171+
Runs on an executor thread (``write_session_state``'s flock would block the
172+
loop). Reading, then unlinking, is not atomic against a start landing in
173+
between on the loop; that window is the read-to-unlink gap of the unsaved
174+
case only, where it used to be the whole release.
175+
"""
176+
state = session_state.read_session_state()
177+
owner = state.get("study_session_id")
178+
if owner and owner != study_session_id:
179+
return
180+
session_state.clear_session_files(keep_state=bool(owner) and state.get("mode") == "ended")

‎packages/studyloop/src/studyloop/web/routes/session/_grace.py‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -657,18 +657,25 @@ def _read_topic(session_id: str) -> str | None:
657657
return topic if isinstance(topic, str) else None
658658

659659

660-
def _persist_before_release(session_id: str) -> None:
661-
"""Save ``session_id``'s evidence before ``active.release()`` deletes it.
660+
def _end_before_release(session_id: str) -> None:
661+
"""End ``session_id`` -- save it and tear it down -- before ``active.release()``.
662662
663663
Stop, agent exit, grace expiry, the reaper and shutdown all end a session
664664
through :func:`_release_if_current` alone. Before review 2026-10-21
665665
(F-WEB-02) that released the slot, which unlinks the topics and parking
666666
files, and never wrote the ``study_sessions`` row: the row stayed open with
667-
no notes and the evidence was unrecoverable.
667+
no notes and the evidence was unrecoverable. F-WEB-02 added the save; plan 5
668+
(larger #1 c) added the teardown half too, because only the End route ran
669+
it: a Kiro learner's swapped agent definitions and the persona file stayed
670+
behind on every other kind of ending until the next session started.
671+
``end_session_common`` runs the same persist-then-teardown the End route and
672+
the CLI's ``cleanup_on_exit`` run, in the same order -- teardown while the
673+
agent is still alive is the order every end path already uses.
668674
669675
Skips a state file that is not this session's (cleared or replaced from
670676
another process; its files are not this session's evidence) and one
671-
already marked ``mode=ended`` (saved by whoever wrote the marker).
677+
already marked ``mode=ended`` (saved, and torn down, by whoever wrote the
678+
marker).
672679
673680
Synchronous for the reason :func:`_read_topic` gives: no new yield point
674681
in the WS route's ``finally``. Best effort, because none of these paths can
@@ -682,12 +689,12 @@ def _persist_before_release(session_id: str) -> None:
682689
return
683690
if state.get("study_session_id") != session_id or state.get("mode") == "ended":
684691
return
685-
from studyloop.session.cleanup import persist_session_end
692+
from studyloop.session.cleanup import end_session_common
686693

687694
try:
688-
persist_session_end(state, raise_if_not_persisted=False)
695+
end_session_common(state, raise_if_not_persisted=False)
689696
except Exception: # pragma: no cover — defensive; must not wedge the slot
690-
logger.exception("saving session %s before release failed", session_id)
697+
logger.exception("ending session %s before release failed", session_id)
691698

692699

693700
def _transport_alive(transport: AgentSessionTransport) -> bool:
@@ -709,8 +716,11 @@ async def _release_if_current(session_id: str, *, reason: str, persist: bool = T
709716
own.
710717
711718
With ``persist`` (every caller except the End route, which has already
712-
saved the session) the session's evidence is saved first, because
713-
``active.release()`` deletes the topics and parking files.
719+
ended the session) the session is ended first -- saved and torn down --
720+
because ``active.release()`` deletes the topics and parking files, and
721+
nothing after it can reach the adapter. ``release()`` keeps the
722+
``mode=ended`` state file the save leaves, so the dashboard's summary view
723+
has something to render.
714724
"""
715725
from studyloop.session import active as session_active
716726

@@ -720,7 +730,7 @@ async def _release_if_current(session_id: str, *, reason: str, persist: bool = T
720730
topic = _read_topic(session_id)
721731
_record_release(session_id, reason, topic, current.config.agent)
722732
if persist:
723-
_persist_before_release(session_id)
733+
_end_before_release(session_id)
724734
# Free the consumer slot with the session it belonged to. Leaving it to the
725735
# WS handler's ``finally`` is what let "refresh → End → Start" refuse the
726736
# next session's first WebSocket with a handshake 403.
Lines changed: 286 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
1+
"""What ``active.release()`` leaves on disk, for every way a web session ends.
2+
3+
Review 2026-10-21, remediation plan 5 (larger #1; lane 2's found-not-fixed #1, #3
4+
and #4). ``session/active.py``'s ``release()`` ran ``clear_session_files()``
5+
unconditionally, which deleted three files it did not own in three ways:
6+
7+
- the reaper's ``state_file_replaced`` release of session A deleted session B's
8+
freshly written state, topics and parking files;
9+
- every web release deleted the ``mode=ended`` state the dashboard's summary view
10+
renders from, so a browser session never showed its summary;
11+
- and none of the non-End releases (Stop, agent exit, grace expiry, the reaper,
12+
shutdown) ran the adapter teardown, so a Kiro learner's swapped agent definitions
13+
and the persona file stayed behind until the next session.
14+
15+
These tests drive the real ``_grace`` release paths, the real writers and a real
16+
per-test ``sessions.db``; only the agent transport is a stub.
17+
"""
18+
19+
from __future__ import annotations
20+
21+
import asyncio
22+
import dataclasses
23+
import json
24+
import sys
25+
from pathlib import Path
26+
27+
import pytest
28+
from _helpers import run_async
29+
from _sessions_db_template import seed_sessions_db
30+
31+
pytest.importorskip("fastapi")
32+
33+
from fastapi.testclient import TestClient # pyright: ignore[reportMissingImports]
34+
35+
from studyloop import session_state
36+
from studyloop.session import active
37+
from studyloop.session.transport import SessionConfig
38+
from studyloop.web.app import create_app
39+
from studyloop.web.routes.session import _grace
40+
41+
_tests_dir = str(Path(__file__).parent)
42+
if _tests_dir not in sys.path:
43+
sys.path.insert(0, _tests_dir)
44+
45+
from _stub_transport import StubTransport # noqa: E402
46+
47+
_TOPIC = "Python decorators"
48+
_PARKED = "Why does asyncio need an event loop?"
49+
50+
51+
@pytest.fixture(autouse=True)
52+
def _reset_active_state():
53+
run_async(active.release())
54+
_grace.reset_for_tests()
55+
yield
56+
run_async(active.release())
57+
_grace.reset_for_tests()
58+
59+
60+
@pytest.fixture()
61+
def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
62+
return seed_sessions_db(tmp_path / "sessions.db", monkeypatch)
63+
64+
65+
class _LiveTransport(StubTransport):
66+
"""Stub with the duck-typed liveness probe the reaper and grace timer poll."""
67+
68+
def __init__(self) -> None:
69+
super().__init__()
70+
self.alive = True
71+
72+
def is_running(self) -> bool:
73+
return self.alive
74+
75+
76+
def _start_live_session(
77+
tmp_path: Path, transport: StubTransport, *, agent: str = "claude"
78+
) -> tuple[str, Path]:
79+
"""A live web session as ``_start.py`` leaves it: DB row, slot, state file.
80+
81+
Returns the study id and the persona file the state names.
82+
"""
83+
from studyloop.history import start_study_session
84+
85+
study_id = start_study_session(_TOPIC, "medium")
86+
assert study_id, "the seeded sessions.db refused to start a study session"
87+
persona_file = tmp_path / "persona.md"
88+
persona_file.write_text("# persona\n")
89+
session_dir = tmp_path / "session-dir"
90+
session_dir.mkdir()
91+
config = SessionConfig(
92+
study_session_id=study_id,
93+
agent=agent,
94+
persona_file=str(persona_file),
95+
cwd=str(session_dir),
96+
env={},
97+
cols=80,
98+
rows=24,
99+
)
100+
run_async(active.acquire(config, lambda: transport))
101+
session_state.write_session_state(
102+
{
103+
"study_session_id": study_id,
104+
"agent": agent,
105+
"topic": _TOPIC,
106+
"transport": "pty",
107+
"mode": "focus",
108+
"session_dir": str(session_dir),
109+
"persona_file": str(persona_file),
110+
}
111+
)
112+
return study_id, persona_file
113+
114+
115+
def _record_evidence() -> None:
116+
session_state.append_topic("10:00", "Closures", "win", "free variables clicked")
117+
session_state.append_topic("10:20", "GIL", "struggling", "still fuzzy")
118+
session_state.append_parking(_PARKED)
119+
120+
121+
# ---------------------------------------------------------------------------
122+
# (a) the reaper's state_file_replaced release touches nothing of the newcomer's
123+
# ---------------------------------------------------------------------------
124+
125+
126+
@pytest.mark.asyncio
127+
async def test_reaper_state_file_replaced_release_leaves_the_replacing_session_files_intact(
128+
db: Path, tmp_path: Path
129+
) -> None:
130+
"""Releasing A because B now owns the state file must not alter B's files.
131+
132+
B's start path wrote its claim with ``try_claim_session`` (REPLACE) and
133+
recorded its own topics and parking. The reaper notices the file no longer
134+
names A, releases A's slot -- and that release used to unlink all three of
135+
B's files.
136+
"""
137+
transport = _LiveTransport()
138+
study_id_a, _ = _start_live_session(tmp_path, transport)
139+
140+
b_state = {
141+
"study_session_id": "session-b",
142+
"topic": "Tries",
143+
"mode": "focus",
144+
"agent": "codex",
145+
"started_at": "2026-10-23T10:00:00+00:00",
146+
}
147+
session_state.STATE_FILE.write_text(json.dumps(b_state, indent=2))
148+
session_state.TOPICS_FILE.write_text("- [10:05] Tries | status:win | prefix trees clicked\n")
149+
session_state.PARKING_FILE.write_text("- How do radix trees differ?\n")
150+
state_before = session_state.STATE_FILE.read_bytes()
151+
topics_before = session_state.TOPICS_FILE.read_bytes()
152+
parking_before = session_state.PARKING_FILE.read_bytes()
153+
154+
assert await _grace.reap_once(min_age=0.0) == "state_file_replaced"
155+
156+
assert await active.current() is None, f"session {study_id_a} still holds the slot"
157+
assert session_state.STATE_FILE.exists(), "B's state file was deleted by A's release"
158+
assert session_state.STATE_FILE.read_bytes() == state_before, "B's state file was altered"
159+
assert session_state.TOPICS_FILE.read_bytes() == topics_before, "B's topics file was touched"
160+
assert session_state.PARKING_FILE.read_bytes() == parking_before, "B's parking file was touched"
161+
162+
163+
# ---------------------------------------------------------------------------
164+
# (b) a non-End web release leaves mode=ended for the dashboard summary
165+
# ---------------------------------------------------------------------------
166+
167+
168+
async def _until_released(timeout: float = 5.0) -> None:
169+
deadline = asyncio.get_running_loop().time() + timeout
170+
while await active.current() is not None:
171+
if asyncio.get_running_loop().time() > deadline:
172+
raise AssertionError("the session was never released")
173+
await asyncio.sleep(0.02)
174+
175+
176+
async def _stop_or_agent_exit(sid: str, _transport: _LiveTransport) -> None:
177+
await _grace.release_now(sid, reason="session ended")
178+
179+
180+
async def _grace_expiry(sid: str, _transport: _LiveTransport) -> None:
181+
_grace.schedule_release(sid, grace=0.01)
182+
await _until_released()
183+
184+
185+
async def _reaper_sees_agent_gone(sid: str, transport: _LiveTransport) -> None:
186+
transport.alive = False
187+
assert await _grace.reap_once() == "agent_exited"
188+
189+
190+
async def _server_shutdown(_sid: str, _transport: _LiveTransport) -> None:
191+
await _grace.shutdown()
192+
193+
194+
_RELEASE_PATHS = pytest.mark.parametrize(
195+
"release",
196+
[_stop_or_agent_exit, _grace_expiry, _reaper_sees_agent_gone, _server_shutdown],
197+
ids=["stop-or-agent-exit", "grace-expiry", "reaper-agent-exited", "server-shutdown"],
198+
)
199+
200+
201+
@pytest.mark.asyncio
202+
@_RELEASE_PATHS
203+
async def test_a_web_release_leaves_a_state_file_that_reads_ended(
204+
release, db: Path, tmp_path: Path
205+
) -> None:
206+
"""The summary view renders from a ``mode=ended`` state file; keep it.
207+
208+
``persist_session_end`` writes the marker, then ``release()`` deleted the
209+
file, so ``/api/session/state`` answered ``{}`` and the summary branch of the
210+
SSE renderer was unreachable for every browser session.
211+
"""
212+
transport = _LiveTransport()
213+
study_id, _ = _start_live_session(tmp_path, transport)
214+
_record_evidence()
215+
216+
await release(study_id, transport)
217+
218+
assert await active.current() is None
219+
state = session_state.read_session_state()
220+
assert state.get("study_session_id") == study_id, f"state file lost: {state!r}"
221+
assert state.get("mode") == "ended"
222+
# The evidence files were persisted and go; only the state stays.
223+
assert not session_state.TOPICS_FILE.exists()
224+
assert not session_state.PARKING_FILE.exists()
225+
226+
227+
def test_the_dashboard_reads_the_ended_session_after_a_stop(db: Path, tmp_path: Path) -> None:
228+
"""End to end for the learner: after a Stop, the endpoint says ``ended``."""
229+
transport = _LiveTransport()
230+
study_id, _ = _start_live_session(tmp_path, transport)
231+
_record_evidence()
232+
run_async(_grace.release_now(study_id, reason="session ended"))
233+
234+
resp = TestClient(create_app()).get("/api/session/state")
235+
236+
assert resp.status_code == 200, resp.text
237+
body = resp.json()
238+
assert body.get("study_session_id") == study_id, body
239+
assert body.get("mode") == "ended", body
240+
241+
242+
@pytest.mark.asyncio
243+
async def test_a_kept_ended_state_never_blocks_the_next_start(db: Path, tmp_path: Path) -> None:
244+
"""Keeping the file must not keep the claim: both start paths read it as free."""
245+
transport = _LiveTransport()
246+
study_id, _ = _start_live_session(tmp_path, transport)
247+
248+
await _grace.release_now(study_id, reason="session ended")
249+
250+
state = session_state.read_session_state()
251+
assert state, "the state file is gone, so nothing can render the summary"
252+
assert not session_state.claim_blocks_web_start(state)
253+
assert not session_state.claim_blocks_cli_start(state)
254+
assert not session_state.is_session_active()
255+
256+
257+
# ---------------------------------------------------------------------------
258+
# (c) a non-End web release runs the adapter teardown
259+
# ---------------------------------------------------------------------------
260+
261+
262+
@pytest.mark.asyncio
263+
@_RELEASE_PATHS
264+
async def test_a_web_release_runs_the_adapter_teardown(
265+
release, db: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
266+
) -> None:
267+
"""Stop, agent exit, grace expiry, the reaper and shutdown tear the adapter down.
268+
269+
Only the End route ran ``teardown_session``; the other releases saved the
270+
session (F-WEB-02) and stopped there, so Kiro's agent-JSON restore and the
271+
persona-file unlink happened only when the learner pressed End.
272+
"""
273+
from studyloop.agent_launcher import AGENTS
274+
275+
torn_down: list[Path] = []
276+
adapter = AGENTS["claude"]
277+
monkeypatch.setitem(AGENTS, "claude", dataclasses.replace(adapter, teardown=torn_down.append))
278+
transport = _LiveTransport()
279+
study_id, persona_file = _start_live_session(tmp_path, transport)
280+
assert persona_file.exists()
281+
282+
await release(study_id, transport)
283+
284+
assert await active.current() is None, f"session {study_id} still holds the slot"
285+
assert torn_down == [tmp_path / "session-dir"], "the adapter teardown did not run"
286+
assert not persona_file.exists(), "the persona file outlived the session"

0 commit comments

Comments
 (0)