after_model_callback: a replacement LlmResponse silently loses `partial` during SSE streaming - every delta is persisted to the session as a final event
Describe the Bug:
The documented contract for after_model_callback says a callback may return a replacement response ("When present, the actual model response will be ignored and the provided content will be returned to user" - agents/llm_agent.py). During SSE streaming, however, the callback is invoked on every streamedLlmResponse, including partial=True deltas (flows/llm_flows/base_llm_flow.py:1833-1840 on main), and the returned replacement is used wholesale:
if altered := (await self._handle_after_model_callback(...)):
llm_response = altered
LlmResponse.partial defaults to None (models/llm_response.py), and per the streaming protocol described in LlmResponse's own docstring, a response with partial "false or unset" is a final response. So any callback that rebuilds an LlmResponse, exactly what the contract suggests, silently converts every streaming delta into a final response. Neither _handle_after_model_callback (module level, base_llm_flow.py:295) nor the call sites carry partial (or turn_complete) over from the response being replaced.
Downstream, Runner persists every non-partial event (runners.py: if not event.partial: await self.session_service.append_event(...)), so each delta fragment is appended to the session as a separate complete model event - the conversation history is corrupted for all subsequent turns.
To Reproduce:
Self-contained repro, no API key required (fake model follows the partial-deltas-then-aggregated-final protocol from LlmResponse's docstring):
# repro_partial_loss.py - run: pip install google-adk==2.8.0 && python repro_partial_loss.py
"""Repro: after_model_callback silently drops `partial` on streamed responses.
A fake streaming model yields 3 partial deltas + 1 final aggregated response (the protocol described in LlmResponse's own docstring). The
after_model_callback follows the documented contract ("When present, the actual model response will be ignored and the provided content will be returned to user") and returns a rebuilt LlmResponse.
Result: every streamed chunk loses partial=True, so (a) clients see N "final" responses instead of deltas, and (b) Runner persists every delta
into the session as a separate complete event (runners.py: `if not event.partial: append_event(...)`).
"""
import asyncio
from typing import AsyncGenerator
from google.adk.agents import LlmAgent
from google.adk.agents.run_config import RunConfig, StreamingMode
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.adk.runners import InMemoryRunner
from google.genai import types
def _text_response(text: str, partial: bool | None = None) -> LlmResponse:
return LlmResponse(
content=types.Content(role="model", parts=[types.Part(text=text)]),
partial=partial,
)
class FakeStreamingLlm(BaseLlm):
"""Emits: 'Hello ' / 'brave ' / 'world.' as partials, then the full text."""
@classmethod
def supported_models(cls) -> list[str]:
return [".*"]
async def generate_content_async(
self, llm_request: LlmRequest, stream: bool = False
) -> AsyncGenerator[LlmResponse, None]:
deltas = ["Hello ", "brave ", "world."]
if stream:
for d in deltas:
yield _text_response(d, partial=True)
yield _text_response("".join(deltas)) # aggregated final (partial unset)
def scrub_callback(callback_context, llm_response: LlmResponse):
"""A guardrail-style callback written exactly per the documented contract:
build and return a replacement LlmResponse."""
if not (llm_response.content and llm_response.content.parts):
return None
text = llm_response.content.parts[0].text or ""
return _text_response(text.replace("brave", "[REDACTED]"))
async def run(label: str, callback):
agent = LlmAgent(
name="repro_agent",
model=FakeStreamingLlm(model="fake-streaming"),
after_model_callback=callback,
)
runner = InMemoryRunner(agent=agent, app_name="repro")
session = await runner.session_service.create_session(
app_name="repro", user_id="u"
)
print(f"\n=== {label} ===")
n = 0
async for event in runner.run_async(
user_id="u",
session_id=session.id,
new_message=types.Content(role="user", parts=[types.Part(text="hi")]),
run_config=RunConfig(streaming_mode=StreamingMode.SSE),
):
n += 1
text = ""
if event.content and event.content.parts and event.content.parts[0].text:
text = event.content.parts[0].text
print(f" event {n}: partial={event.partial!r:6} "
f"final={event.is_final_response()!s:5} text={text!r}")
stored = await runner.session_service.get_session(
app_name="repro", user_id="u", session_id=session.id
)
model_events = [e for e in stored.events if e.author == "repro_agent"]
print(f" session now holds {len(model_events)} persisted model event(s):")
for e in model_events:
t = e.content.parts[0].text if (e.content and e.content.parts) else ""
print(f" - {t!r}")
async def main():
await run("CONTROL: no after_model_callback", None)
await run("BUG: doc-contract callback (rebuilds LlmResponse)", scrub_callback)
asyncio.run(main())
def scrub_callback_copy(callback_context, llm_response: LlmResponse):
"""Workaround: model_copy(update=...) preserves partial/turn_complete."""
if not (llm_response.content and llm_response.content.parts):
return None
text = llm_response.content.parts[0].text or ""
new_content = types.Content(
role="model", parts=[types.Part(text=text.replace("brave", "[REDACTED]"))])
return llm_response.model_copy(update={"content": new_content})
asyncio.run(run("WORKAROUND: model_copy(update=...)", scrub_callback_copy))
Actual output on google-adk 2.8.0:
=== CONTROL: no after_model_callback ===
event 1: partial=True final=False text='Hello '
event 2: partial=True final=False text='brave '
event 3: partial=True final=False text='world.'
event 4: partial=None final=True text='Hello brave world.'
session now holds 1 persisted model event(s):
- 'Hello brave world.'
=== BUG: doc-contract callback (rebuilds LlmResponse) ===
event 1: partial=None final=True text='Hello '
event 2: partial=None final=True text='[REDACTED] '
event 3: partial=None final=True text='world.'
event 4: partial=None final=True text='Hello [REDACTED] world.'
session now holds 4 persisted model event(s):
- 'Hello '
- '[REDACTED] '
- 'world.'
- 'Hello [REDACTED] world.'
=== WORKAROUND: model_copy(update=...) ===
event 1: partial=True final=False text='Hello '
event 2: partial=True final=False text='[REDACTED] '
event 3: partial=True final=False text='world.'
event 4: partial=None final=True text='Hello [REDACTED] world.'
session now holds 1 persisted model event(s):
- 'Hello [REDACTED] world.'
Expected behavior:
A callback replacement that does not explicitly set streaming-control fields should not change the streaming semantics of the response it replaces: deltas stay partial=True, exactly one final event is persisted to the session (the WORKAROUND run in the output above shows the expected shape).
Impact:
- Session corruption: every delta is appended to the session as a complete model event; later turns see N fragment messages as context.
- Clients in SSE mode receive N "final" responses (
is_final_response() == Truefor every delta) - duplicated/mangled rendering. - Same field-loss class affects
turn_complete(live path checksevent.turn_completeto close the live request queue - a rebuilt response loses it) andusage_metadata(token accounting silently dropped).
Workaround:
Rebuild via model_copy instead of the constructor:
return llm_response.model_copy(update={"content": new_content})
Verified (third run in the repro/output above): deltas stay partial, session gets exactly 1 event. But nothing in the docs points users to this, and the natural reading of the contract produces the broken version.
Suggested fix (happy to send a PR):
Treat None as "unset" and inherit streaming-control fields from the response being replaced, at both call sites (live: base_llm_flow.py:1791-1798, SSE: 1833-1840):
def _inherit_unset_streaming_fields(original, replacement):
if replacement.partial is None and original.partial is not None:
replacement.partial = original.partial
if replacement.turn_complete is None and original.turn_complete is not None:
replacement.turn_complete = original.turn_complete
return replacement
An explicit partial=False set by a callback is still respected.
Alternatively (or additionally): document the model_copy requirement in the after_model_callback contract.
Desktop:
- OS: macOS 15 (Darwin 25.6)
- Python: 3.13.12
- google-adk: 2.8.0 (also present in 1.18.0 — call sites at
base_llm_flow.py:757-760and796-799there; the pattern is unchanged across the 1.x→2.x line)
Additional context:
Found running a production multi-agent HR assistant where a guardrail-style after_model_callback (PII scrubbing) rebuilt responses per the documented contract; symptom was mid-stream output mangling plus duplicated assistant messages accumulating in session history.
I reproduced this on current main (b018062) with the exact script from the report: control run persists 1 model event, the doc-contract callback run persists 4 (every delta stored as a final event). Root cause confirmed at both after_model_callback call sites in base_llm_flow.py (run_live SSE branch and the non-support_cfc branch): the replacement is used wholesale, so an unset partial/turn_complete silently flips every streamed delta to final, and Runner then persists each one.
Planned fix: in the module-level _handle_after_model_callback (the single choke point for plugin + agent callbacks), inherit partial/turn_complete from the replaced response when the replacement leaves them unset; an explicitly set value is still respected. Regression tests will cover inherit-partial, inherit-turn_complete, explicit-False-respected, and an SSE flow-level run asserting deltas stay partial with exactly one persisted final event.
If that direction looks right, I'll open the focused PR shortly.
@zhuhongd The wholesale replacement at both after_model_callback call sites does flip every delta to final, confirmed with your script (4 persisted events instead of 1). The inherit-unset-fields approach checks out on my end too, ran it against both #7038 and #7036 and deltas stay partial with only one event landing in the session either way. Since you and Bruce-Yii arrived at basically the same fix independently might be worth syncing on which PR to carry forward so we're not reviewing duplicate work.
#7036 and #7038 independently converged on the same inherit-unset-streaming-fields fix, and @surajksharma07 has confirmed both resolve the repro.
For coordination: #7036 was opened first and applies the inheritance at "_handle_after_model_callback", the shared choke point for plugin and agent callbacks. It also uses "model_copy()" only when inheritance is needed, so the callback-owned replacement object is not mutated.
Happy for maintainers to choose whichever implementation they prefer; I’ll avoid duplicating further work until that decision is made.
Thanks @surajksharma07 for verifying both, and @Bruce-Yii for the quick confirmation - glad the suggested fix from the report held up under independent implementation.
Happy either way on consolidation; deferring to maintainers on which PR carries forward. Two notes to make the decision easy:
- #7036's copy-on-inherit (not mutating the callback-owned replacement) is a nice refinement, if #7038 is carried, I'm happy to fold that and the choke-point placement in with one commit.
- What #7038 currently adds: a flow-level SSE test asserting the event-stream shape end to end ([True, True, True, None] + exactly one persisted session event), explicit-False regression, and a documented full-directory regression run (716 passed).
If #7036 is preferred, no objection a Co-authored-by given the fix design originated in this report would be appreciated, and I'll review #7036 instead.
4 comments in, sounds like this took some back-and-forth to pin down. Did every delta getting persisted as final actually corrupt session state in a way you noticed downstream, or did you catch it before it caused real damage?
@anythingoah Not just theoretical. Per the original report zhuhongd hit this in a production multi-agent HR assistant where a PII-scrubbing after_model_callback caused mid-stream output mangling plus duplicated assistant messages piling up in session history that later turns then saw as context. Re-verified it's still reproducible on current main. #7036 and #7038 both fix it just waiting on a maintainer pick between the two before merge.
Appreciate the detail, mid-stream corruption silently poisoning later-turn context is a nasty failure mode. Once #7036/#7038 lands, is there anything currently watching for this class of regression recurring (e.g. in a different callback or provider), or was this caught purely by someone noticing bad output downstream? Curious how you'd catch the next one of these before it reaches a user.
@anythingoah Short answer: this incident was caught from downstream/production behavior, not by a generic lifecycle monitor. One update since the earlier comments: #7036 has now landed on main via Copybara as 39e4538, so the exact callback-replacement regression does have a real guard now.
That guard is reasonably strong for this specific path: the shared after_model_callback finalizer now inherits unset partial / turn_complete for both plugin- and agent-provided replacements, while still respecting an explicit override. The regression suite also includes a flow-level fake-model SSE case, so this protection is not tied to one provider adapter: a rebuilding callback must leave intermediate deltas partial and the final aggregate final.
I would not call the broader failure class covered yet, though. What failed here was really an invariant crossing several ownership boundaries: provider/model stream -> ADK flow -> callback transformation -> event persistence. Adjacent issues show that the same lifecycle contract can be broken somewhere other than the callback finalizer. For example, #6583 traces a task-agent wrapper consuming a partial=True task-delegation FunctionCall before the non-partial aggregate is reached, which can leave persisted FC/FR history unbalanced; #5342 is another example of provider-adapter streaming behavior not matching the progressive streaming surface. So #7036 closes one hole, but it is not a general detector for "lifecycle metadata became semantically wrong before somebody consumed or persisted the event."
If the goal is to catch the next one before it becomes another user report, I would probably use two layers rather than one global assertion:
-
Capability-aware streaming conformance tests at the model-adapter boundary. Feed deterministic/canned provider streams through each adapter and assert the contract that matters downstream: intermediate emissions remain partial=True; terminal output is the complete logical model turn; partial FunctionCall/tool data cannot become executable/persistable as a completed call; IDs stay correlated across partial -> final assembly. I say capability-aware because adapters do not all expose the same granularity, so requiring identical chunk counts would be the wrong invariant.
-
Transformation + persistence invariant tests above providers. A small matrix across plugin vs agent callback, pass-through vs replacement, SSE vs live where applicable, and explicit vs unset lifecycle fields. The important assertion is not just the emitted UI stream; it is the resulting session/event history -- a normal streamed model call should not turn chunk fragments into independently persistable completed responses merely because an intermediate layer rebuilt an object.
For production/runtime defense, I would lean toward telemetry or warnings rather than a hard reject. ADK intentionally allows a callback to set partial=False explicitly, and one invocation can legitimately contain multiple model calls, so rules like "more than one final model event per invocation is invalid" would create false positives and potentially change API semantics. But a trace/event at the transformation boundary for an explicit lifecycle transition such as original.partial=True -> replacement.partial=False, or an early turn_complete, correlated to the individual model call/turn, would make this class queryable. That would turn a silent semantic transition into something observable without forbidding intentional overrides.
Longer term I think there is also a contract-design question here. LlmResponse carries both callback-owned payload and framework/protocol lifecycle metadata in the same replaceable object. #7036 now has an explicit inheritance policy for two control fields, which is the right minimal fix. But I would prefer an explicit field-ownership/inheritance policy over discovering each important control field one incident at a time. I would not blindly copy every metadata field -- usage, grounding, finish semantics, etc. have different ownership/merge rules -- but making that distinction explicit would reduce this whole class of bugs.
If that direction sounds useful to maintainers, I would be interested in turning the first piece into a focused streaming-lifecycle conformance harness/proposal rather than broadening this already-fixed issue. That seems like a better next step than adding another provider-specific regression after the next incident.
On Fri, 11 Sep 2026 06:26:40 -0700, anythingoah @.***> wrote:
anythingoah left a comment (google/adk-python#7035)
Appreciate the detail, mid-stream corruption silently poisoning later-turn context is a nasty failure mode. Once #7036/#7038 lands, is there anything currently watching for this class of regression recurring (e.g. in a different callback or provider), or was this caught purely by someone noticing bad output downstream? Curious how you'd catch the next one of these before it reaches a user.
— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you were mentioned.
Good question. I checked current main rather than assuming the fix
itself gives us broad protection.
Short version: this instance was user-discovered, not caught by an existing watchdog. The production symptom in the original report led us to the invariant violation. #7036 now gives ADK strong regression coverage for this exact path, but I don't think it is accurate to say ADK currently has a general detector for this whole class of callback/provider lifecycle corruption.
What is protected now:
- The landed fix sits in the shared
handle_after_model_callbackfinalization path and applies to both plugin and canonical agentafter_model_callbackreplacements. - It preserves the framework-owned streaming control fields
partialandturn_completewhen a replacement leaves them unset, while still respecting an explicit override. - There is a flow-level SSE regression using a streaming fake model, so the important externally visible invariant is exercised: partial deltas remain partial and the turn ends with one terminal response instead of every delta becoming terminal.
- Because this repair is above the provider adapter boundary, the
specific replacement bug is not tied to one model provider as long
as that provider has already produced a valid
LlmResponselifecycle.
What I do not see today is a broader contract gate such as “every
callback replacement must preserve all framework-owned
lifecycle/correlation/accounting semantics unless that field is
explicitly overridable”, or a runtime signal that would flag an
impossible event shape before a user notices it. I also don't see a
callback-source × streaming-mode × provider contract matrix. And there
is already a concrete residual example of the same structural risk:
#7036 deliberately left usage_metadata out of scope, so a callback
that rebuilds an LlmResponse can still lose token/accounting
metadata even though the streaming lifecycle is now safe.
If we want to catch the next version of this class before it reaches a user, I'd probably harden the invariant rather than add a provider-specific test for every backend:
- Define the model-call lifecycle contract at the shared flow boundary. For a single completed model call in SSE, pre-terminal deltas must remain partial, and there should be one terminal model response/persisted model event for that model call. Scope this per model call/span, not per whole agent invocation, because tool loops can legitimately cause multiple model calls.
- Parameterize replacement tests across callback sources/modes. At minimum: plugin vs agent callback, SSE vs live/non-streaming, replacement-with-unset-fields vs explicit overrides. Provider-specific cases are useful only where an adapter has distinct lifecycle semantics; the main invariant belongs above adapters.
- Add a diagnostic signal before making it a hard runtime
assertion. For example, in debug/test telemetry, count terminal
responses and persisted model events per model call, and record when a
callback replacement drops framework-owned non-content metadata. A
sudden
N > 1terminal/persisted-event shape for one streaming model call would have made #7035 visible immediately. I'd start with a metric/warning because there may be legitimate edge cases we should audit before turning it into an exception. - Audit the replacement contract beyond
partial/turn_complete.usage_metadatais the obvious next candidate, but I'd first classify fields into (a) framework-owned invariants that should normally inherit, (b) callback-owned content that may replace freely, and (c) fields whose override semantics must stay explicit. That avoids blindly copying every field and accidentally freezing the wrong API semantics.
So my answer is: we now have a good regression fence around the bug that happened, but not yet a systemic early-warning fence around the bug class. I think a small follow-up focused on the replacement invariant + diagnostic coverage would be more valuable than a large provider matrix. If maintainers think that direction is useful, I'm happy to scope it narrowly before proposing code.
On Fri, 11 Sep 2026 06:26:40 -0700, anythingoah @.***> wrote:
anythingoah left a comment (google/adk-python#7035)
Appreciate the detail, mid-stream corruption silently poisoning later-turn context is a nasty failure mode. Once #7036/#7038 lands, is there anything currently watching for this class of regression recurring (e.g. in a different callback or provider), or was this caught purely by someone noticing bad output downstream? Curious how you'd catch the next one of these before it reaches a user.
— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you were mentioned.
Bruce-Yii's breakdown is right @anythingoah. #7036 landed as 39e4538 and shipped in v2.10.0. Checked the 2.11.0 source too: _inherit_unset_streaming_fields runs on both the plugin and agent after_model_callback paths so @zhuhongdu upgrading to 2.10.0 or later should be all that's needed. Your workaround from the report still works fine but it's no longer required.
@Bruce-Yii the conformance harness and field-ownership idea is worth pursuing but it's broader than this bug. Could you open it as a separate proposal issue so maintainers can weigh in? The same goes for the usage_metadata gap GWeale mentioned on #7038. A rebuilt response still drops token counts so that one needs its own issue. Leaving this one closed since the fix is released.