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 摘要。