Repository navigation
Conversation
persistence, stream.get) are closures recreated every turn. Each subscribe built a fast_depends/pydantic model for them, and each event ran through asolve, although their arguments are always (event, context). Wrap them in EventHandler; MemoryStream calls those directly. User subscribers and tools keep dependency injection. Other Stream implementations still work: EventHandler is a plain (event, context) callable. Framework overhead per turn: 1.55 -> 0.09 ms (plain reply), 2.90 -> 0.27 ms (tool call + reply); stream build_model per turn 7/9 -> 0.
4 of 6 tasks
vvlrff
marked this pull request as draft
November 24, 2026 04:37
vvlrff
marked this pull request as ready for review
November 24, 2026 19:46
Codecov Report✅ All modified and coverable lines are covered by tests.
... and 10 files with indirect coverage changes 🚀 New features to boost your workflow:
|
marklysze
approved these changes
Nov 26, 2026
marklysze
left a comment
Collaborator
There was a problem hiding this comment.
I checked each wrapped subscriber. All of them are async (event, context) callables with no Inject/Variable/Depends, so skipping DI is safe. User code keeps DI where it matters: wrap_hitl still builds its own model for the user's HITL hook, and middleware on_human_input is a plain (call_next, event, context) chain. A non-MemoryStream still works via EventHandler.__call__'s AnnotatedContext, and AuditedStream covers that. Verified locally: the offline suite passes (9100 passed, 73 skipped; live-provider/redis markers deselected).
Before merging, please fix the description:
- The "Full
pytest test" bullet still has the<!-- fill in after the run: N passed, … -->placeholder. test/acp/test_remote_transport.py(sock.listen()beforeserve()) is in the diff but not in the description. A line on why it's needed (a flaky connection-refused race?) would help.- All checks are green, so the auto-checks box can be ticked.
Nits (non-blocking):
- A small test asserting that
MemoryStream.subscribe(EventHandler(...))doesn't callbuild_modelwould stop the speedup from silently regressing. Right now nothing would fail if a wrapper stopped being recognised. - When squashing, use a short subject: the first commit's message is one long paragraph.
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 27, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why are these changes needed?
Every agent turn subscribes the agent-loop handlers to the stream: model call, tool dispatch, tool-not-found fallback, the HITL hook / delegation bridge, history persistence and
stream.get(). They are closures created anew each turn, soMemoryStream.subscribebuilt a fast_depends call model — a pydantic model generated from the signature — for each of them every turn, and every event they received went throughasolvewith its ownAsyncExitStack. Their arguments are always(event, context): there is nothing to resolve or validate.This showed up while auditing what blocks the event loop: model building was most of the framework's own work per turn.
This PR adds
EventHandlerinag2/stream.py, a marker for framework handlers.MemoryStream.subscribecalls anEventHandlerdirectly asfunc(event, context); anything else still goes through dependency injection. The agent-loop subscriptions wrap their handlers in it:ag2/agent.py:_call_client, the HITL hook (configured and default),delegation.bridgeag2/tools/executor.py:execute_tools,_tool_not_foundag2/tools/final/function_tool.py: the per-toolexecuteag2/stream.py: default history persistence (_FilteredStorage.save_event) andstream.get()'s waiterWhat does not change:
Inject,Variable,Depends). So does a userStorage.save_eventsubscribed withpersist_all=True.ContextisAnnotated[ConversationContext, ContextField(cast=False)], so fast_depends passed the stream'sConversationContextthrough unchanged.Streamimplementations need no change.EventHandleris an ordinary(event, context: Context)callable, so a stream that does not know the type runs it through dependency injection as before.EventHandleris not exported in__all__; it is an internal mechanism, not public API._Subscriptionnow holds aruncallable (EventHandler.funcor_InjectedCall(model)), so subscriber timeouts work identically on both paths.The same split exists elsewhere: FastAPI passes
Request/Response/BackgroundTasksparameters directly instead of validating them (fastapi/dependencies/utils.py,add_non_field_param_to_dependency), Starlette'sRoutecallsendpoint(request)with FastAPI's DI layered on top inAPIRoute, and Litestar skips validation forSKIP_VALIDATION_NAMES(request,socket,scope, …).Evidence
Framework overhead per
ask(TestConfig, one tool, median of 300 turns, GC off):build_modelcalls per turntest/stream/test_wrapped_subscribers.py: aMemoryStreamsubclass that wraps every subscriber (instrumentation-style) still runs a full turn with a tool call and persists history. This is the path where a stream doesn't recogniseEventHandlerand runs it through dependency injection; annotating itscontextas a bareConversationContextmakes the test fail.ag2/stream.pyis fully covered by the existing tests plus the one above; the timeout branch is shared with user subscribers and covered bytest/stream/test_timeout.py.ruff checkandmypyclean on the changed files.pytest test: The only failures are two live-provider tests that also fail onmain:test_thinking_budget_reports_thinking_tokens(Gemini) andtest_token_budget_policy_clamps_history[mistral](the model recalls the trimmed history).Merge danger
EventHandler. That is visible at the subscription site, and would fail in tests as an argument error.Related issue number
None.
Checks
AI assistance