Skip to content

perf(stream): call framework handlers without dependency injection - #3718

Open
vvlrff wants to merge 6 commits into
mainfrom
perf/stream-direct-framework-handlers
Open

vvlrff wants to merge 6 commits into
mainfrom
perf/stream-direct-framework-handlers

Conversation

@vvlrff

@vvlrff vvlrff commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

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, so MemoryStream.subscribe built a fast_depends call model — a pydantic model generated from the signature — for each of them every turn, and every event they received went through asolve with its own AsyncExitStack. 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 EventHandler in ag2/stream.py, a marker for framework handlers. MemoryStream.subscribe calls an EventHandler directly as func(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.bridge
  • ag2/tools/executor.py: execute_tools, _tool_not_found
  • ag2/tools/final/function_tool.py: the per-tool execute
  • ag2/stream.py: default history persistence (_FilteredStorage.save_event) and stream.get()'s waiter

What does not change:

  • User subscribers, observers and tools keep dependency injection (Inject, Variable, Depends). So does a user Storage.save_event subscribed with persist_all=True.
  • The handler receives the same context object as before: Context is Annotated[ConversationContext, ContextField(cast=False)], so fast_depends passed the stream's ConversationContext through unchanged.
  • Other Stream implementations need no change. EventHandler is an ordinary (event, context: Context) callable, so a stream that does not know the type runs it through dependency injection as before.
  • EventHandler is not exported in __all__; it is an internal mechanism, not public API.

_Subscription now holds a run callable (EventHandler.func or _InjectedCall(model)), so subscriber timeouts work identically on both paths.

The same split exists elsewhere: FastAPI passes Request / Response / BackgroundTasks parameters directly instead of validating them (fastapi/dependencies/utils.py, add_non_field_param_to_dependency), Starlette's Route calls endpoint(request) with FastAPI's DI layered on top in APIRoute, and Litestar skips validation for SKIP_VALIDATION_NAMES (request, socket, scope, …).

Evidence

Framework overhead per ask (TestConfig, one tool, median of 300 turns, GC off):

Turn Before After build_model calls per turn
plain reply 1.55 ms 0.09 ms 7 → 0
tool call + reply 2.90 ms 0.27 ms 9 → 0
  • New test/stream/test_wrapped_subscribers.py: a MemoryStream subclass 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 recognise EventHandler and runs it through dependency injection; annotating its context as a bare ConversationContext makes the test fail.
  • New code in ag2/stream.py is fully covered by the existing tests plus the one above; the timeout branch is shared with user subscribers and covered by test/stream/test_timeout.py.
  • ruff check and mypy clean on the changed files.
  • Full pytest test: The only failures are two live-provider tests that also fail on main: test_thinking_budget_reports_thinking_tokens (Gemini) and test_token_budget_policy_clamps_history[mistral] (the model recalls the trimmed history).

Merge danger

  • Door: two-way. No public API, wire format or persisted data changes; reverting restores the previous dispatch.
  • Blast radius: agent-loop event dispatch. A framework handler that starts relying on dependency injection must not be wrapped in EventHandler. That is visible at the subscription site, and would fail in tests as an argument error.

Related issue number

None.

Checks

AI assistance

  • I understand the changes in this PR and can explain them in my own words.
  • I have verified that the PR description accurately reflects the actual diff.
  • If AI assistance was used, I reviewed, tested, and validated the generated code/text before submitting.

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.
@github-actions github-actions Bot added area:core Agent runtime core: ag2/*.py, ag2/events, ag2/response, ag2/streams area:tools Tool system, builtin tools, subagents (ag2/tools) labels Nov 23, 2026
@github-actions github-actions Bot added the area:deps Python dependency updates (pyproject.toml, uv.lock) label Nov 23, 2026
@vvlrff
vvlrff marked this pull request as draft November 24, 2026 04:37
@github-actions github-actions Bot added the area:acp ACP support for CLI coding agents (ag2/acp) label Nov 24, 2026
@vvlrff
vvlrff marked this pull request as ready for review November 24, 2026 19:46
@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
ag2/agent.py 97.86% <100.00%> (ø)
ag2/stream.py 97.64% <100.00%> (-0.46%) ⬇️
ag2/tools/executor.py 96.38% <100.00%> (+0.04%) ⬆️
ag2/tools/final/function_tool.py 100.00% <100.00%> (ø)

... and 10 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@marklysze marklysze left a comment

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.

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() before serve()) 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 call build_model would 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.

@vvlrff
vvlrff added this pull request to the merge queue Nov 27, 2026
@github-merge-queue
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

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

Labels

area:acp ACP support for CLI coding agents (ag2/acp) area:core Agent runtime core: ag2/*.py, ag2/events, ag2/response, ag2/streams area:deps Python dependency updates (pyproject.toml, uv.lock) area:tools Tool system, builtin tools, subagents (ag2/tools)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants