Skip to content

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

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

Ray0907 wants to merge 1 commit 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.
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.

1 participant