|
| 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