Conversation
_on_turn fires after every agent turn and called _persist() inline — a synchronous open()+json.dump() over the full history/display_history/ workflow_turns. As a session grows this write grows with it, and being awaited directly in run_agent_loop it stalls the event loop on every single turn (TUI freezes, no other coroutine gets to run). Move it to asyncio.to_thread, awaited so writes stay ordered turn to turn and the resume checkpoint can't be overwritten out of order. Benchmarked with a 2000-message history + a concurrent heartbeat coroutine: sync persist blocks the loop for ~139ms with 0 heartbeat ticks; to_thread lets ~4558 ticks through with a 0.85ms max stall.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Persistence must remain serialized and safe during cancellation.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (1)
What changed in this PR
Moves per-turn session persistence off the asyncio event loop to keep the TUI and streaming responsive.
Changes:
- Runs
_persist()viaasyncio.to_thread. - Keeps persistence awaited between turns.
| File | Summary |
|---|---|
apodex/session.py |
Offloads checkpoint writes; cancellation can allow concurrent persistence and risk checkpoint corruption. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| # _persist() does synchronous file I/O over the full history; run it | ||
| # off the event loop so long sessions don't stall on every turn. | ||
| # Awaited (not fire-and-forget) so writes stay ordered turn-to-turn. | ||
| await asyncio.to_thread(self._persist) |
There was a problem hiding this comment.
Fixed in c61ff52.
The write lock and atomic replacement prevented interleaved JSON writes, but the payload was still built before acquiring the lock. Cancelling _on_turn leaves the asyncio.to_thread worker running, so that worker could capture old state, let a subsequent save finish, then overwrite it with the stale payload.
The lock now covers the full checkpoint operation: TUI snapshot, session/path and payload capture, temporary-file write, and atomic replacement. A waiting writer therefore captures current state only after acquiring the lock; an in-progress snapshot finishes writing before a newer save can proceed. Per-turn persistence remains off the event loop. The comment on _on_turn now also makes the cancellation behavior explicit.
Added a deterministic regression test that pauses the old snapshot, cancels _on_turn, updates history and renames the session, then lets the background worker finish. It verifies that the newest name and both histories remain on disk. This test fails on the previous PR head and passes with the fix.
Validation: 137 tests passed in apodex/tests/test_changes.py and apodex/tests/test_features.py; Ruff passed for both changed files.
_persist() now runs on both the main thread (start_new_session, rename_session) and a to_thread worker (_on_turn), so overlapping writers could interleave and corrupt session.json. Serialize writes with a threading.Lock and write via tmp file + os.replace so a torn write is never observable on disk.

Summary
TerminalSession._on_turnfires after every agent turn (run_agent_loopawaitson_turn_completedirectly) and called_persist()inline — a synchronousopen()+json.dump()over the fullhistory,display_history, andworkflow_turns.asyncio.to_thread, still awaited so writes stay ordered turn-to-turn (no risk of an out-of-order write corrupting the--resumecheckpoint).Benchmark
2000-message history, 10 persists, with a concurrent heartbeat coroutine standing in for other async work:
Sync blocks the loop completely (0 heartbeat ticks in 139ms).
to_threadcosts a bit more wall time (thread dispatch + GIL handoff) but lets everything else keep running concurrently — the actual user-visible win, since the write itself isn't the bottleneck, the freeze is.Test plan
uv run pytest apodex/tests/test_changes.py apodex/tests/test_features.py— 136 passeduv run ruff check apodex/session.py— clean