Skip to content

perf(core): keep un-iterated events short and pace streams by deltas - #94

Merged
gopaljigaur merged 3 commits into
mainfrom
perf/event-buffering
Oct 15, 2026
Merged

gopaljigaur merged 3 commits into
mainfrom
perf/event-buffering

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

What changed

Un-iterated handles (#81). A run's events go into _Events, an asyncio.Queue subclass (through the _init/_put/_get hooks LifoQueue uses). Until the handle is iterated it keeps consecutive deltas of one kind as one event (their text in a StringIO) and _Run.emit drops nested runs' events, so a run that is only awaited (an awaited handle, run, arun, arun_with_response) holds a few events per step instead of one per token or per subagent event. A handle iterated from the start, as the docs show and as astream_events does, gets every event as before; one iterated late gets the run's own events with the deltas merged.

Pacing (#82). A paced run now waits for its caller only once more than 16 events are left to take, instead of queue.join() after every chunk, and joins once at the end of each streamed completion. So it still starts no tool call and no completion until the caller has taken every event before it, and a consumer that stops reading holds the run (test_run_waits_for_the_stream_consumer is unchanged); within a completion it gets at most 16 deltas (text or reasoning) ahead.

Sync bridge. Unchanged: it still fetches one event per request, so a sync caller that stops reading holds the run the same way (test_sync_events_caller_that_stops_reading_holds_the_run). Batching it would count unread events as taken and let tool calls run. Sync streaming gains from the pacing change alone.

With stream retries and the idle timeout. The pacing waits happen while _astream_completion is suspended at yield, outside the asyncio.timeout around each chunk's __anext__, so a slow caller never counts as an idle stream (test_consumer_slower_than_the_idle_timeout_keeps_the_stream). The final taken() runs only after a stream completes, and a stream is retried only before its first delta, so nothing is emitted twice.

Python 3.10. Reading ahead exposed a lost cancellation in the stream idle timeout: asyncio.wait_for before 3.11 drops a cancellation that comes as the chunk arrives, so a sync stream closed after one chunk left the run waiting at its final taken() (test_closing_sync_stream_early_closes_the_completion_stream hung on 3.10). Before 3.11 _next now uses async_timeout, the library asyncio.timeout came from, added as a dependency for those versions like exceptiongroup. It also drops the task per chunk that wait_for ran.

emit(event) keeps its signature; nested runs share the root's _Events, so forwarded events follow the same rules.

Decisions

  • Pacing is not a bounded queue with await put(), as Streaming pays extra event loop turns and a thread hop per token #82 proposed: tool, step and nested run events are emitted from sync code through emit(), and put_nowait into a full bounded queue raises. taken(ahead) gives the same bound with the existing join().
  • Deltas are merged, not dropped, before iteration, so a handle iterated late (for example from a task created after await handle) still sees the run's text and every other event of the run.

Measurements

Before is main at 3619796; numbers from a script that patches litellm.acompletion with a 3,000 chunk stream and counts calls to the loop selector's select (one per loop iteration) and to _write_to_self (the cross thread wakeup). "I/O" yields to the loop once per chunk, like a socket read.

before after
astream_events, loop iterations per token 2.00 0.12
astream_events with I/O 3.00 1.00
sync stream() / stream_events(), iterations per token 4.00 2.12
sync with I/O 5.00 2.10
sync wakeups per token 1.00 1.00
memory held by an awaited, un-iterated 5,000 chunk run (tracemalloc) 2,729 KB, 5,002 events 70 KB, 3 events

With 20 subagent calls, an awaited lead run now keeps 44 events, none of them from the subagents (test_awaited_run_keeps_no_subagent_events).

Tests

New: deltas of a handle iterated from the start, merging before iteration, no subagent events in an awaited run, a paced stream reads 17 chunks ahead of a stopped consumer, a sync caller that stops after one event keeps tools from running. uv run pytest (358 passed), uv run pre-commit run --all-files and uv run mypy cyclops pass.

Closes #81
Closes #82

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Two should-fix findings and two nits; the rest checks out.

Checked and fine

  • uv run pytest (358 passed), uv run pre-commit run --all-files and uv run mypy cyclops pass on e28e438.
  • The bench reproduces the table exactly on 2ea729b and e28e438: 2.00 to 0.12 and 3.00 to 1.00 for astream_events, 4.00 to 0.25 and 5.00 to 1.00 for sync, 1.00 to 0.06 wakeups per token, 2,729 KB / 5,002 events to 70 KB / 3 events.
  • No memory regression for iterated streams: peak for a 5,000 chunk astream_events is 70,811 KB on both; an iterated handle is 19,552 KB on main and 19,865 KB here.
  • Each new line is covered: removing the end of completion taken() fails test_run_waits_for_the_stream_consumer, removing the nested drop fails test_awaited_run_keeps_no_subagent_events, an unbounded ahead fails test_paced_run_reads_a_bounded_number_of_chunks_ahead, and not setting listening hangs the suite (the join() argument holds only because a paced run is iterated before it starts). The new tests fail on main and passed 25 of 25 repeated runs.
  • A handle iterated mid run from another task gets the merged tail, then every later delta, in order. Cancellation still raises at join() and RunFinished is emitted with put_nowait; hooks and telemetry do not read the queue.
  • The _init/_put/_get hooks are marked "overridable in subclasses" in asyncio/queues.py and are identical from 3.10 to 3.14 (3.13's shutdown goes through _get). Merging has to touch the tail of the storage, so a subclass is the smallest structure; a deque plus an Event would re-implement get, task_done and join.

Should fix

  1. The sync batch lets a run start tool calls a caller has not reached (inline on sync.py).
  2. The docs and commit message say 16 chunks; the bound counts events (inline on streaming.md).

Nits
3. _continues and its TypeGuard can be one condition in _put.
4. The join() invariant comment sits in RunHandle; it describes _Events.

Comment thread cyclops/core/sync.py Resolved
Comment thread docs/guide/streaming.md Resolved
Comment thread cyclops/core/run_state.py Resolved
Comment thread cyclops/core/run_state.py Resolved
@gopaljigaur gopaljigaur changed the title perf(core): keep un-iterated events short and pace streams in batches perf(core): keep un-iterated events short and pace streams by deltas Oct 15, 2026

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

No findings.

Re-reviewed 6359693. All four points from the last review are fixed: the sync bridge is identical to main, the docs and commit say 16 text or reasoning deltas, the merge check is inline in _put without TypeGuard, and the join() invariant is in the _Events docstring.

Checked

  • At 6359693: uv run pytest (358 passed), uv run pre-commit run --all-files and uv run mypy cyclops pass. CI is green (lint, type-check, test 3.10 to 3.12, CodeQL, build).
  • The branch is still based on 2ea729b, not on main. Merged locally onto a794618 (with #93) it merges without conflicts, and the full suite passes there (376 passed), with mypy clean.
  • With #93: a paced consumer that stops after the first event holds the run before two tool calls under max_parallel_tool_calls=1 and a tool timeout (0 calls, then both run in order once it reads on). An awaited lead whose subagent call times out completes with the timeout error result and keeps no subagent events.
  • test_sync_events_caller_that_stops_reading_holds_the_run fails on the previous batched bridge and passes on main; the same probe with stream() runs 0 tools.
  • Bench on the merged tree against a794618: astream_events 2.00 to 0.12 iterations per token (3.00 to 1.00 with I/O), sync 4.00 to 2.12 (5.00 to 2.10), 1.00 wakeups per token on both, an awaited 5,000 chunk run 2,729 KB / 5,002 events to 70 KB / 3 events. This matches the PR table. Peak memory of iterated streams is unchanged (70,811 KB for astream_events; 19,553 KB and 19,865 KB for an iterated handle).
  • Confidentiality and prose: nothing in the title, body, commit, added lines or replies, and no dashes used as punctuation.

A handle that is not iterated yet keeps consecutive deltas as one event
and drops nested runs' events, so a run that is only awaited holds a few
events per step instead of one per token.

A paced run now waits for its caller only once more than 16 events are
left to take, instead of after every chunk, and waits for every event
to be taken once a streamed completion ends, before tool calls or the
next completion.
asyncio.wait_for before 3.11 drops a cancellation that comes as the
awaited chunk arrives, so a stream closed while the run read ahead of
its caller left the run waiting for a caller that was gone. Use
async_timeout there, the library asyncio.timeout came from.

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

No findings.

Re-reviewed 0772e5a (rebased onto 3619796).

Checked

  • uv run pytest passes on the default Python and on 3.10.19 (403 passed each); pre-commit and uv run mypy cyclops pass; CI is green.
  • The rebase matches 6359693 except for the conflict in _streamed_completion. The per-chunk taken(ahead=_READ_AHEAD) is inside #95's retry loop, and the full taken() runs only in the else: of a completed stream, before stream_chunk_builder. A failed stream raises or retries without it, which is correct.
  • Pacing waits never count toward stream_idle_timeout: taken() runs while _astream_completion is suspended at yield, outside the timeout around __anext__. test_consumer_slower_than_the_idle_timeout_keeps_the_stream covers it.
  • A retry cannot repeat a delta: both retry paths require emitted to be false, and a stream that emitted anything raises.
  • The 3.10 diagnosis is right. With 0772e5a reverted on 3.10.19, test_closing_sync_stream_early_closes_the_completion_stream hangs on 3 of 3 runs. An async probe (astream_events, one event, aclose()) shows the mechanism: after handle.cancel() the run kept reading chunks, because wait_for returned the chunk and dropped the cancel, and it then waited forever in the final taken() for a caller that had gone. With 0772e5a it closes cleanly. The same path (closing astream_events calls handle.cancel()) is covered on 3.10 by that test in CI, so no extra test is needed.
  • async-timeout is the right choice before 3.11. It is the aio-libs library asyncio.timeout was taken from, it is the usual backport, and it is already installed on those versions as a dependency of aiohttp (via LiteLLM; see uv.lock). Declaring it is correct because cyclops now imports it.
  • The bench and probes match the earlier review: astream_events 0.12 iterations per token, sync 2.12, an awaited 5,000 chunk run 70 KB / 3 events. A sync or paced caller that stops reading still keeps tools from running.
  • Confidentiality and prose: nothing in the title, body, commits, added lines or replies, and no dashes used as punctuation.

Outside this PR: tool_execution.py (from #93) still runs tools under asyncio.wait_for, which loses a cancel the same way before 3.12. I did not reproduce it there.

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.

Streaming pays extra event loop turns and a thread hop per token Events of a handle that is never iterated stay buffered

1 participant