Skip to content

fix(apodex): offload per-turn session persist off the event loop - #45

Open
Ray0907 wants to merge 3 commits into
ApodexAI:mainfrom
Ray0907:fix/session-persist-blocking-io
Open

Ray0907 wants to merge 3 commits into
ApodexAI:mainfrom
Ray0907:fix/session-persist-blocking-io

Conversation

@Ray0907

@Ray0907 Ray0907 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Summary

  • TerminalSession._on_turn fires after every agent turn (run_agent_loop awaits on_turn_complete directly) and called _persist() inline — a synchronous open() + json.dump() over the full history, display_history, and workflow_turns.
  • As a session grows, this write grows with it, and being awaited directly on the hot per-turn path it stalls the event loop every single turn — no other coroutine (TUI redraw, streaming, etc.) gets to run during the write.
  • Moved it to asyncio.to_thread, still awaited so writes stay ordered turn-to-turn (no risk of an out-of-order write corrupting the --resume checkpoint).

Benchmark

2000-message history, 10 persists, with a concurrent heartbeat coroutine standing in for other async work:

sync (current)         elapsed=139.1ms  heartbeat_ticks=   0  max_stall=0.00ms
asyncio.to_thread      elapsed=195.4ms  heartbeat_ticks=4558  max_stall=0.85ms

Sync blocks the loop completely (0 heartbeat ticks in 139ms). to_thread costs 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 passed
  • uv run ruff check apodex/session.py — clean

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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() via asyncio.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.

Comment thread apodex/session.py
# _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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Ray0907 and others added 2 commits September 21, 2026 20:51
_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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants