Repository navigation
perf(core): keep un-iterated events short and pace streams by deltas - #94
Conversation
gopaljigaur
left a comment
There was a problem hiding this comment.
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-filesanduv run mypy cyclopspass 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_eventsis 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()failstest_run_waits_for_the_stream_consumer, removing the nested drop failstest_awaited_run_keeps_no_subagent_events, an unboundedaheadfailstest_paced_run_reads_a_bounded_number_of_chunks_ahead, and not settinglisteninghangs the suite (thejoin()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()andRunFinishedis emitted withput_nowait; hooks and telemetry do not read the queue. - The
_init/_put/_gethooks are marked "overridable in subclasses" inasyncio/queues.pyand are identical from 3.10 to 3.14 (3.13'sshutdowngoes 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-implementget,task_doneandjoin.
Should fix
- The sync batch lets a run start tool calls a caller has not reached (inline on
sync.py). - 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.
e28e438 to
6359693
Compare
gopaljigaur
left a comment
There was a problem hiding this comment.
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-filesanduv run mypy cyclopspass. 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=1and 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_runfails on the previous batched bridge and passes on main; the same probe withstream()runs 0 tools.- Bench on the merged tree against a794618:
astream_events2.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 forastream_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.
6359693 to
88a235f
Compare
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
left a comment
There was a problem hiding this comment.
No findings.
Re-reviewed 0772e5a (rebased onto 3619796).
Checked
uv run pytestpasses on the default Python and on 3.10.19 (403 passed each); pre-commit anduv run mypy cyclopspass; CI is green.- The rebase matches 6359693 except for the conflict in
_streamed_completion. The per-chunktaken(ahead=_READ_AHEAD)is inside #95's retry loop, and the fulltaken()runs only in theelse:of a completed stream, beforestream_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_completionis suspended atyield, outside the timeout around__anext__.test_consumer_slower_than_the_idle_timeout_keeps_the_streamcovers it. - A retry cannot repeat a delta: both retry paths require
emittedto 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_streamhangs on 3 of 3 runs. An async probe (astream_events, one event,aclose()) shows the mechanism: afterhandle.cancel()the run kept reading chunks, becausewait_forreturned the chunk and dropped the cancel, and it then waited forever in the finaltaken()for a caller that had gone. With 0772e5a it closes cleanly. The same path (closingastream_eventscallshandle.cancel()) is covered on 3.10 by that test in CI, so no extra test is needed. async-timeoutis the right choice before 3.11. It is the aio-libs libraryasyncio.timeoutwas taken from, it is the usual backport, and it is already installed on those versions as a dependency ofaiohttp(via LiteLLM; seeuv.lock). Declaring it is correct because cyclops now imports it.- The bench and probes match the earlier review:
astream_events0.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.
What changed
Un-iterated handles (#81). A run's events go into
_Events, anasyncio.Queuesubclass (through the_init/_put/_gethooksLifoQueueuses). Until the handle is iterated it keeps consecutive deltas of one kind as one event (their text in aStringIO) and_Run.emitdrops 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 asastream_eventsdoes, 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_consumeris 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_completionis suspended atyield, outside theasyncio.timeoutaround 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 finaltaken()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_forbefore 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 finaltaken()(test_closing_sync_stream_early_closes_the_completion_streamhung on 3.10). Before 3.11_nextnow usesasync_timeout, the libraryasyncio.timeoutcame from, added as a dependency for those versions likeexceptiongroup. It also drops the task per chunk thatwait_forran.emit(event)keeps its signature; nested runs share the root's_Events, so forwarded events follow the same rules.Decisions
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 throughemit(), andput_nowaitinto a full bounded queue raises.taken(ahead)gives the same bound with the existingjoin().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.acompletionwith a 3,000 chunk stream and counts calls to the loop selector'sselect(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.astream_events, loop iterations per tokenastream_eventswith I/Ostream()/stream_events(), iterations per tokenWith 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-filesanduv run mypy cyclopspass.Closes #81
Closes #82