Parallel scalar state updates roll back when tool completion order differs from call order

未关闭
#8,325 4 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

维护者通常 3 天内回复

@surajksharma07 已经在做这个了。

开始于 2026年11月24日。

  • #8343 来自 @linye157 —— 未关闭

评估

这个 Issue 还没有评估数据。

描述

Required Information

Describe the Bug:
Two async tool calls in one model turn can successfully increment a shared scalar state key to 2, but the merged response event persists 1 when completion order differs from function-call order. The read/increment/write section contains no await; an asyncio.Event deliberately makes B finish before A. Both function responses are present, so this is state loss rather than a missing tool execution.

Steps to Reproduce:

  1. Install the source revision tested below: pip install "google-adk @ git+https://github.com/google/adk-python.git@e3dbdc1726bed0bfc3d2e3f335fc7c0dcdf6b9c5".
  2. Save the code below as parallel_counter_repro.py and run python parallel_counter_repro.py.
  3. Compare the tool-observed write sequence with a fresh get_session() after Runner completes.

Expected Behavior:
For this explicitly ordered read-modify-write, the stored counter remains 2, matching the latest value observed through ToolContext.state. The example does not require the framework to provide atomicity across awaited read-modify-write sections or concurrent invocations.

Observed Behavior:

reverse=True, scalar: writes=[B:1, A:2], stored counter=1, both responses present
reverse=False, scalar: writes=[A:1, B:2], stored counter=2
reverse=True, list: stored counter=['b','a']
reverse=True, dict: stored counter={'b':True,'a':True}

The affected scalar case repeats 3/3. The normal-order scalar and reversed-order list/dict controls pass 9/9.

Environment Details:

  • ADK: source main at e3dbdc1726bed0bfc3d2e3f335fc7c0dcdf6b9c5; source reports 2.15.0.
  • OS: Windows 11, build 26300.
  • Python: 3.12.13.
  • Session service: real InMemorySessionService, fresh get_session after each run.

Model Information:

  • LiteLLM: No.
  • Model: deterministic local BaseLlm that returns two function calls, then text. No network, API key, paid model, or replacement of the Runner/tool/state/persistence code.

Optional Information

Root-cause observation:
_batch_executor.deep_merge_dicts() merges scalar deltas in function-call order. _apply_latest_state_writes() re-applies current session values for list/dict keys only, skipping scalars. For call order [A,B] but writes B=1 then A=2, the later merge of B's delta overwrites the current value with 1.

Related work checked:
#5190/#5191 and commit d42a3beb address list writes; #7661/#7703 concern dictionary removals and retain list/dict-specific bookkeeping. This report is about a scalar read-modify-write through ToolContext.state, not blind conflicting deltas written directly to actions.state_delta, dict-union semantics, or separate session writers as in #6236. No implementation direction is assumed here; please let me know if the scalar result above is intentional.

Impact:
A tool-maintained completed-item count or progress scalar can move backward when the batch is persisted, despite both tools succeeding and seeing the incremented value. A subsequent turn reads the stale count. No claim of a particular production outage or validation on other backends/platforms.

Regression:
N/A; older versions were not tested in this report.

Minimal Reproduction Code:

import sys, asyncio, json, platform
from pathlib import Path
import google.adk
from google.adk.agents import LlmAgent
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools.tool_context import ToolContext
from google.genai import types
class OfflineModel(BaseLlm):
    model: str = 'offline'
    async def generate_content_async(self,llm_request,stream=False):
        has_response=any(p.function_response for c in llm_request.contents for p in c.parts or [])
        if has_response:
            yield LlmResponse(content=types.Content(role='model',parts=[types.Part(text='done')]))
        else:
            yield LlmResponse(content=types.Content(role='model',parts=[types.Part(function_call=types.FunctionCall(id=v,name='increment',args={'item':v})) for v in ['a','b']]))
async def run(reverse,kind):
    gate=asyncio.Event(); writes=[]
    async def increment(item:str,tool_context:ToolContext)->str:
        if reverse and item=='a': await asyncio.wait_for(gate.wait(),2)
        if kind=='scalar': tool_context.state['counter']=tool_context.state.get('counter',0)+1
        elif kind=='list':tool_context.state['counter']=tool_context.state.get('counter',[])+[item]
        else:
            obj=dict(tool_context.state.get('counter',{}));obj[item]=True;tool_context.state['counter']=obj
        writes.append({"item":item,"seen":tool_context.state["counter"]})
        gate.set()
        return item
    sessions=InMemorySessionService();agent=LlmAgent(name='agent',model=OfflineModel(),tools=[increment]);runner=Runner(app_name='probe',agent=agent,session_service=sessions)
    session=await sessions.create_session(app_name='probe',user_id='u');events=[]
    async for e in runner.run_async(user_id='u',session_id=session.id,new_message=types.Content(role='user',parts=[types.Part(text='go')])):events.append(e)
    stored=await sessions.get_session(app_name='probe',user_id='u',session_id=session.id)
    result={'reverse':reverse,'kind':kind,'value':stored.state.get('counter'),'writes':writes,'responses':[r.name for e in events for r in e.get_function_responses()]}
    print(json.dumps(result),flush=True);return result
async def main():
    print(json.dumps({'source':google.adk.__file__,'version':google.adk.__version__,'python':platform.python_version(),'os':platform.platform()}),flush=True)
    results=[]
    for repeat in range(3):
        for reverse,kind in [(True,'scalar'),(False,'scalar'),(True,'list'),(True,'dict')]:results.append(await run(reverse,kind))
    Path(__file__).with_name('counter-results.json').write_text(json.dumps(results,indent=2),encoding='utf-8')
    failures=[r for r in results if r['reverse'] and r['kind']=='scalar'];controls=[r for r in results if r not in failures]
    assert all(r['value']==1 and len(r['responses'])==2 for r in failures),failures
    assert all(r['value']==({'a':True,'b':True} if r['kind']=='dict' else ['b','a'] if r['kind']=='list' else 2) for r in controls),controls
    print('3/3 lost scalar updates; 9/9 controls pass')
asyncio.run(main())

How often has this issue occurred?: Always for the controlled B-before-A ordering (3/3).

AI assistance: OpenAI Codex was used to inspect source, prepare and execute this offline reproducer, check related reports, and draft this issue. No production patch or PR is included.

主要语言
Python
星标
22.3k
派生
4.4k
平均合并
1 天 2 小时
30 天内合并 PR
6

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

google/adk-python 的其他 Issue

查看 google/adk-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。