Environment simulation: a seeded fault injection is not reproducible per eval case; adding an unrelated case or changing parallelism changes which runs fail

Aberta
#8,288 5 comentários 0 reações 1 responsável Ver no GitHub

Mantenedores costumam responder em até 3 dias

@sanketpatil06 já está trabalhando nisso.

Desde 23/11/2026.

  • #8307 de @Fruiterer333 — aberto

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
30/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Ativa
Stack de tecnologia
python
Domínio
ai-infra-agents

Direção de pesquisa

Start with EnvironmentSimulationEngine.init and its _seeded_generators and _draw helpers, which hold one shared seeded sequence per plugin. Run the repro script with case_a alone and with case_a plus case_b at parallelism 1 and 4 to confirm the outcomes differ. Done means each eval case sees the same injection decisions regardless of other cases, order or parallelism, with a regression test covering those three variants; the key choice is still undecided, so maintainer input is needed first.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

eval

🔴 Required Information

Describe the Bug:

InjectionConfig.random_seed is meant to make probabilistic fault injection (injection_probability < 1) repeatable. Today the seeded generator is created once per plugin/engine (EnvironmentSimulationEngine.__init__, self._seeded_generators) and every session the plugin serves draws from the same sequence (_draw). The docstring says so: "one plugin's sequence is shared by every session it serves".

In an eval, one plugin serves every eval case and every num_runs repetition. So whether a given case/run gets the injected error depends on how many draws other cases made before it, which depends on:

  • which other eval cases are in the eval set (or selected with eval_case_ids),
  • the order of the cases,
  • parallelism, because concurrent runs interleave their draws.

The seed therefore makes the whole eval invocation repeatable only when nothing else changes, but it does not make an eval case's result repeatable. Adding one unrelated case to the eval set flips results of existing cases, which is exactly the kind of noise a seed is supposed to remove from a regression gate.

Steps to Reproduce:

Offline, no API key: a fake agent model calls charge_card once and replies OK or FAILED depending on whether the tool returned an injected 503. The injection has injection_probability=0.5, random_seed=42. case_a is run with num_runs=3 alone, with an unrelated case_b, in the other order, and with parallelism=4.

$ python repro.py
case_a alone,          parallelism=1: case_a runs 0..2 -> ['OK', 'FAILED', 'FAILED']
case_a alone,          parallelism=1 (again): case_a runs 0..2 -> ['OK', 'FAILED', 'FAILED']
case_a + case_b,       parallelism=1: case_a runs 0..2 -> ['FAILED', 'OK', 'OK']
case_b + case_a order, parallelism=1: case_a runs 0..2 -> ['FAILED', 'FAILED', 'OK']
case_a + case_b,       parallelism=4: case_a runs 0..2 -> ['OK', 'OK', 'OK']

Same seed, same case_a, four different outcomes. With parallelism > 1 the outcome also depends on scheduling.

Expected Behavior:

With a fixed random_seed, the injection decisions an eval case's run sees should be the same no matter which other cases run with it, in what order, or with what parallelism.

Observed Behavior:

They depend on the other cases and on scheduling (output above).

Environment Details:

  • ADK: main at 2b90353 (2.15.0)
  • Python 3.12.16, Linux

Model Information: fake BaseLlm registered in the script; no external model.

🟡 Optional Information

Proposed fix (open to discussion):

This is the same root cause as #8040 (fixed for the simulated state store in #8041): per-session data lives on the engine. The natural fix is to give each session its own seeded generator, derived from the seed plus a stable key, e.g. random.Random(hash((seed, tool_name, config_index, key))) or a random.Random(seed) per key.

The open question is the key:

  1. Session key (app_name, user_id, session_id), as in #8041. Isolates sessions, but eval session ids are random UUIDs, so the sequence a run sees is still not repeatable across eval invocations unless every session simply restarts the same sequence from seed.
  2. Restart the sequence per session (every session draws Random(seed) from the start). Fully repeatable and simple, but every num_runs repetition of a case then sees identical injections, so repetitions no longer sample different fault patterns.
  3. Eval case id + repetition index. Repeatable and varies across repetitions, but the plugin does not know them today. LocalEvalService could expose them to the run (for example through the eval client labels it already sets, or a reserved session state key).

I lean towards (3) with (2) as the fallback outside of eval, but would like maintainers' view before implementing. I'd also update the random_seed docstring and add a regression test like the repro (alone vs. with another case vs. parallelism).

Willingness to contribute: Yes, after agreeing on the key. I'd base it on #8041 if that lands first, since both change the same per-session bookkeeping in the engine.

Minimal Reproduction Code:

"""A seeded fault injection is not reproducible per eval case (offline)."""
import argparse, asyncio, logging
from typing import ClassVar
from google.adk.agents.llm_agent import LlmAgent
from google.adk.apps.app import App
from google.adk.evaluation import eval_case as ec
from google.adk.evaluation.base_eval_service import InferenceConfig, InferenceRequest
from google.adk.evaluation.in_memory_eval_sets_manager import InMemoryEvalSetsManager
from google.adk.evaluation.local_eval_service import LocalEvalService
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.models.registry import LLMRegistry
from google.adk.tools.environment_simulation import EnvironmentSimulationFactory
from google.adk.tools.environment_simulation.environment_simulation_config import (
    EnvironmentSimulationConfig, InjectedError, InjectionConfig, ToolSimulationConfig)
from google.genai import types

logging.disable(logging.CRITICAL)

class FakeAgentModel(BaseLlm):
  """Calls charge_card once, then replies with what the tool returned."""
  @classmethod
  def supported_models(cls): return [r"^fake-agent$"]
  async def generate_content_async(self, llm_request, stream=False):
    last = llm_request.contents[-1].parts[0]
    if last.function_response:
      r = last.function_response.response
      text = "FAILED" if "error_code" in r else "OK"
      yield LlmResponse(content=types.ModelContent(text))
    else:
      yield LlmResponse(content=types.ModelContent(
          [types.Part.from_function_call(name="charge_card", args={})]))
LLMRegistry.register(FakeAgentModel)

def charge_card() -> dict:
  """Charges the card."""
  return {"status": "charged"}

async def run(case_ids, parallelism, num_runs):
  plugin = EnvironmentSimulationFactory.create_plugin(EnvironmentSimulationConfig(
      tool_simulation_configs=[ToolSimulationConfig(
          tool_name="charge_card",
          injection_configs=[InjectionConfig(
              injection_probability=0.5, random_seed=42,
              injected_error=InjectedError(injected_http_error_code=503,
                                           error_message="unavailable"))])]))
  agent = LlmAgent(name="agent", model="fake-agent", tools=[charge_card])
  app = App(name="app", root_agent=agent, plugins=[plugin])
  manager = InMemoryEvalSetsManager()
  manager.create_eval_set("app", "set")
  for cid in case_ids:
    manager.add_eval_case("app", "set", ec.EvalCase(eval_id=cid, conversation=[
        ec.Invocation(user_content=types.UserContent("Pay my bill."))]))
  service = LocalEvalService(root_agent=agent, eval_sets_manager=manager, app=app)
  out = {}
  async for r in service.perform_inference(InferenceRequest(
      app_name="app", eval_set_id="set", eval_case_ids=case_ids,
      inference_config=InferenceConfig(parallelism=parallelism, num_runs=num_runs))):
    out[(r.eval_case_id, r.repetition_index)] = r.inferences[-1].final_response.parts[0].text
  return out

async def main():
  for label, ids, par in [
      ("case_a alone,          parallelism=1", ["case_a"], 1),
      ("case_a alone,          parallelism=1 (again)", ["case_a"], 1),
      ("case_a + case_b,       parallelism=1", ["case_a", "case_b"], 1),
      ("case_b + case_a order, parallelism=1", ["case_b", "case_a"], 1),
      ("case_a + case_b,       parallelism=4", ["case_a", "case_b"], 4),
  ]:
    out = await run(ids, par, num_runs=3)
    a = [out[("case_a", i)] for i in range(3)]
    print(f"{label}: case_a runs 0..2 -> {a}")

asyncio.run(main())

Additional context: I used Grok Bot to help find the issue and draft this report; I reproduced the bug and checked the output locally.

Linguagem predominante
Python
Estrelas
22.3k
Forks
4.4k
Merge médio
1d 2h
PRs com merge (30d)
6

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de google/adk-python

Todas as issues de google/adk-python

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.