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

Đang mở
#8,325 4 bình luận 0 reaction 1 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 3 ngày

@surajksharma07 đang làm issue này rồi.

Từ ngày 24/11/2026.

  • #8343 của @linye157 — đang mở

Đánh giá

Issue này chưa được đánh giá.

Mô tả

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.

Ngôn ngữ chính
Python
Star
22.3k
Fork
4.4k
Merge trung bình
1 ngày 2 giờ
Pull request đã merge (30 ngày)
6

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của google/adk-python

Tất cả issue của google/adk-python

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.