Skip to content

Commit 2b2de36

Browse files
Merge lane R web-session-lifecycle (plan 5): release() lifecycle, pi export check, --show-url pid check
Lane review5/web-session-lifecycle, four commits on 137ccad, verified by the coordinator: 332 lane/adjacent tests + 331 active/grace/cleanup tests green under an independent run; ruff/format/pyright 0; RED proven -- 19 of the 21 new lifecycle/export-check tests fail against 137ccad's source. Repeated-End pin 404->200 accepted: the End route already answers 200 on mode=ended and the dialog (R-70) keeps itself open on any non-OK.
2 parents 137ccad + 6dab3b7 commit 2b2de36

12 files changed

Lines changed: 825 additions & 20 deletions

‎packages/studyloop/src/studyloop/cli/_web.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,12 +141,22 @@ def _show_url() -> None:
141141
practice_check capability (same file, same threat model), and the address is
142142
printed only when something answers on the recorded port -- a dead server's
143143
token is nobody's credential and is not handed out.
144+
145+
Something answering is not enough (plan 5 item E, pass 4): a port can be
146+
reused, and then the probe would vouch for a stranger. The launcher records
147+
the server's ``web_pid`` beside the port; ``os.kill(pid, 0)`` asks the kernel
148+
whether that process still exists without signalling it. Gone (``ESRCH``)
149+
means whatever answers is not our server, so refuse; alive -- including
150+
``EPERM``, a real process we may not signal -- means the answer is ours.
144151
"""
152+
import os
153+
145154
from studyloop.session_state import read_session_state
146155
from studyloop.web.ws_origin import BOOTSTRAP_QUERY
147156

148157
state = read_session_state()
149158
port = state.get("web_port")
159+
pid = state.get("web_pid")
150160
token = state.get("web_sign_in_token")
151161
host = str(state.get("web_bind_host") or LOOPBACK)
152162
none_up = (
@@ -161,6 +171,16 @@ def _show_url() -> None:
161171
raise click.ClickException(none_up)
162172
if not _answers(LOOPBACK, port_number):
163173
raise click.ClickException(none_up)
174+
if isinstance(pid, int) and not isinstance(pid, bool):
175+
try:
176+
os.kill(pid, 0)
177+
except ProcessLookupError:
178+
raise click.ClickException(
179+
f"the recorded server (pid {pid}) is gone; something else answers on port "
180+
f"{port_number}. Start a new one with `studyloop study --web`."
181+
) from None
182+
except PermissionError:
183+
pass # alive, owned by someone else: still a real process on that pid
164184
if not token:
165185
raise click.ClickException(
166186
f"A server answers on port {port_number} but this session recorded no sign-in "

‎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/session/cleanup.py‎

Lines changed: 109 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -410,21 +410,127 @@ def auto_clean_zombies() -> None:
410410
)
411411

412412

413+
def record_harness_export_check(state: dict) -> None:
414+
"""Record whether pi exported this session to the sessions database.
415+
416+
pi exports its own transcript from a ``session_shutdown`` extension
417+
(``agents/pi/extensions/studyloop-session-export.ts`` runs
418+
``session-export --pi-only``), and pi 1.1.0 awaits that handler before its
419+
process exits -- so when the tmux wrapper runs :func:`cleanup_on_exit` the
420+
export has either landed or failed, and this is the one moment StudyLoop
421+
can tell which (review 2026-10-21, lane O's design for F#5 / plan-5 D).
422+
423+
No-op unless ``state["agent"] == "pi"``. The database is opened read-only
424+
(``mode=ro``): a missing file, a database without a ``sessions`` table or
425+
any other read failure is a ``missing`` verdict, never an exception -- the
426+
caller is about to tear the session down and must not be stopped. A row
427+
counts when ``source='pi'``, its ``project_path`` resolves to the same
428+
directory as the session's ``session_dir`` (node's ``process.cwd()`` is the
429+
physical path; the sessions dir may be a symlink) and its ``updated_at`` --
430+
the last message's stamp, in ``Z`` -- is not before this session's
431+
``started_at`` (a row for the same directory from an earlier run is last
432+
time's export). An empty session the exporter wrote no row for reads as
433+
``missing`` too; the line the dashboard shows is advice, not an error.
434+
435+
Writes ``export_check`` into the session state, which survives the tmux
436+
kill and is what the dashboard's ended view reads.
437+
"""
438+
if state.get("agent") != "pi":
439+
return
440+
import contextlib
441+
from datetime import UTC, datetime
442+
443+
from studyloop.session_state import write_session_state
444+
445+
status = "ok" if _pi_export_row_exists(state) else "missing"
446+
with contextlib.suppress(Exception):
447+
write_session_state(
448+
{
449+
"export_check": {
450+
"harness": "pi",
451+
"status": status,
452+
"checked_at": datetime.now(UTC).isoformat(),
453+
}
454+
}
455+
)
456+
457+
458+
def _pi_export_row_exists(state: dict) -> bool:
459+
"""Whether the sessions database holds pi's export of this session. Never raises."""
460+
import sqlite3
461+
from datetime import UTC, datetime
462+
from pathlib import Path
463+
464+
from studyloop.settings import get_db_path
465+
466+
def _utc(stamp: str) -> datetime:
467+
# Both writers stamp UTC: StudyLoop as ``+00:00``, pi (node's
468+
# ``toISOString``) as ``Z``. A naive stamp is read as UTC too.
469+
parsed = datetime.fromisoformat(stamp)
470+
return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)
471+
472+
session_dir = state.get("session_dir")
473+
started_at = state.get("started_at")
474+
if not session_dir or not isinstance(started_at, str):
475+
return False
476+
try:
477+
started = _utc(started_at)
478+
wanted = Path(session_dir).resolve()
479+
except (ValueError, OSError):
480+
return False
481+
482+
# The SQL bound is a conservative prefix -- ``started_at`` in UTC to the
483+
# second, no offset -- which compares correctly as text against both
484+
# ``...Z`` and ``...+00:00`` stamps. The exact comparison is Python's.
485+
lower_bound = started.strftime("%Y-%m-%dT%H:%M:%S")
486+
try:
487+
conn = sqlite3.connect(f"file:{get_db_path()}?mode=ro", uri=True)
488+
except sqlite3.Error:
489+
return False
490+
try:
491+
rows = conn.execute(
492+
"SELECT project_path, updated_at FROM sessions "
493+
"WHERE source = 'pi' AND updated_at IS NOT NULL AND updated_at >= ?",
494+
(lower_bound,),
495+
).fetchall()
496+
except sqlite3.Error:
497+
return False
498+
finally:
499+
conn.close()
500+
501+
for project_path, updated_at in rows:
502+
if not project_path or not isinstance(updated_at, str):
503+
continue
504+
try:
505+
if Path(project_path).resolve() == wanted and _utc(updated_at) >= started:
506+
return True
507+
except (ValueError, OSError):
508+
continue
509+
return False
510+
511+
413512
def cleanup_on_exit() -> None:
414513
"""Auto-cleanup when the agent process exits.
415514
416515
Called by the wrapper shell command in the main tmux pane. This runs
417516
inside the tmux session, so tmux will SIGHUP us when sessions are
418-
killed -- all operations are wrapped in contextlib.suppress via
419-
end_session_common().
517+
killed -- all operations are wrapped in contextlib.suppress.
518+
519+
Order matters: :func:`teardown_session` kills this pane's own tmux
520+
session, so anything after it never executes. The session is saved first,
521+
then the harness export check is recorded, then the teardown runs.
420522
"""
421523
import contextlib
422524

423525
from studyloop.session_state import read_session_state
424526

425527
with contextlib.suppress(Exception):
426528
state = read_session_state()
529+
if not state.get("study_session_id"):
530+
return
427531
# Best effort, as before: the agent has already exited and nothing is
428532
# left to retry the end, so a failed DB write must not leave the tmux
429533
# session and IPC files behind.
430-
end_session_common(state, raise_if_not_persisted=False)
534+
persist_session_end(state, raise_if_not_persisted=False)
535+
record_harness_export_check(state) # BEFORE teardown: it kills this pane
536+
teardown_session(state)

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def _mtime_or_zero(f: Path) -> float:
164164
"""This file's mtime, or 0.0 if it can't be stat()'d.
165165
166166
Read first and handle failure, rather than checking exists() and then
167-
stat()-ing: clear_session_files() (session release, active.py:130-131)
167+
stat()-ing: clear_session_files() (session release, ``active._clear_files_of``)
168168
unlinks these same files from an executor thread. 28a431b fixed the
169169
exact race for parse_topics_file/parse_parking_file's read(); the SSE
170170
loop below is the client its own commit message named as reachable

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

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,12 +138,29 @@ def _render_summary(state: dict) -> str:
138138
)
139139
parked_html = f"<h3>\u25cb Parked Topics</h3><ul>{parked_items}</ul>"
140140

141+
# One line, only when pi's own export is known to be missing
142+
# (``cleanup.record_harness_export_check``, plan-5 D). Advice, not an error:
143+
# an empty pi session the exporter wrote no row for gets the same line, and
144+
# the command it names is idempotent. Only pi exports itself, so only pi is
145+
# checked; another harness would need its own command here.
146+
export_html = ""
147+
export_check = state.get("export_check")
148+
if (
149+
isinstance(export_check, dict)
150+
and export_check.get("harness") == "pi"
151+
and export_check.get("status") == "missing"
152+
):
153+
export_html = (
154+
'<p class="summary-export-missing">This pi session was not exported to '
155+
"the session database \u2014 run `session-export --pi-only`.</p>"
156+
)
157+
141158
return (
142159
f'<div class="session-summary">'
143160
f'<div class="summary-header">'
144161
f"<h2>Session Complete: {topic}</h2>"
145162
f"</div>"
146-
f"{wins_html}{struggles_html}{parked_html}"
163+
f"{wins_html}{struggles_html}{parked_html}{export_html}"
147164
f'<p class="summary-cta">'
148165
f"Stand up. Walk to the kitchen. Your brain needs a break.</p>"
149166
f"</div>"

‎packages/studyloop/tests/test_no_exists_then_read_race.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
session file-IO modules.
33
44
Session release (``active.release()``) unlinks the IPC files from an
5-
executor thread (``active.py:130-131``), so a request reading them concurrently
5+
executor thread (``active.py``, ``_clear_files_of``), so a request reading them concurrently
66
races that unlink. ``28a431b`` fixed this shape for
77
``parse_topics_file``/``parse_parking_file`` (checked ``exists()`` then called
88
``read_text()`` as a separate step); R-06 and R-08 (this lane) fixed the two

0 commit comments

Comments
 (0)