adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

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

Open Fruiterer333 opened this issue 1 week ago • 5 comments

🔴 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.

Fruiterer333 avatar Nov 21 '26 18:11 Fruiterer333

I reproduced this on current main (2b90353, ADK 2.15.0, Python 3.12.13) using the offline script in this issue. For case_a, I got:

Evaluation Results for repetitions 0–2
A alone, parallelism 1 FAILED, FAILED, OK
A alone again, parallelism 1 FAILED, FAILED, OK
A + B, parallelism 1 OK, OK, FAILED
B + A, parallelism 1 OK, FAILED, FAILED
A + B, parallelism 4 OK, FAILED, FAILED

Both existing seed tests in test_environment_simulation_engine.py pass; they exercise repeatability within a fresh engine rather than isolation between eval runs.

@Fruiterer333, thanks for the reproduction and seed-key analysis. Since you offered to implement this, are you already working on it? If the scope is available, I would be happy to contribute a focused fix with this approach:

  • Derive each stream from a stable encoding of (seed, app_name, eval_set_id, eval_case_id, repetition_index, tool_name, injection_config_index), using SHA-256 rather than Python's process-dependent hash().
  • Establish a private, task-local eval-run context around inference. Keep the generator cache within that run so a shared plugin cannot mix cases or retain sequences across subsequent eval invocations. Child tasks and successive turns of the same run share that context.
  • Preserve the documented behavior outside eval for this PR, and discuss per-session fallback separately. Avoid putting case identifiers in client headers or persisted session state.
  • Add offline regression coverage for case selection/order, parallelism, repeated evaluation with the same plugin, multi-turn stream continuity, and context cleanup. Update the random_seed description.

The guarantee would cover the same ordered matching calls within a case; a changed agent trajectory can still consume different draws.

Would maintainers support this seed key and eval-only scope? If implementation is already underway, I can help with regression coverage instead.

paulraj avatar Nov 21 '26 23:11 paulraj

Thanks @paulraj for reproducing this and for the detailed seed-key proposal.

Yes, I planned to implement this and will start on a PR shortly. Your approach matches what I had in mind: a stable SHA-256 seed key over (seed, app_name, eval_set_id, eval_case_id, repetition_index, tool_name, injection_config_index), a task-local eval-run context so a shared plugin cannot mix cases or leak sequences across runs, and leaving non-eval behavior unchanged for this PR. This will build on #8041, which touches the same part of environment_simulation_engine.py.

I'd be glad to have your help on the regression coverage you outlined (case order, parallelism, repeated evaluation with the same plugin, multi-turn stream continuity, and context cleanup). I'll open a draft PR once the core change is in place so we can iterate on the tests together.

Fruiterer333 avatar Nov 22 '26 16:11 Fruiterer333

Thanks—I'd be happy to take the regression coverage. Please tag me when the draft PR is available.

I'll prepare offline tests for case selection/order, parallelism, repeated evaluations using the same plugin, multi-turn stream continuity, and context cleanup on failure or cancellation. I'll verify that they reproduce the problem on main and pass on your branch.

paulraj avatar Nov 22 '26 23:11 paulraj

Thanks @Fruiterer333 for the detailed report and repro, and for opening a PR to address it.

The diagnosis looks right: the seeded generator lives on the engine, so all eval cases and repetitions served by one plugin share a single sequence, and results depend on case set, order, and parallelism.

Since #8307 is still a draft, please mark it ready for review once it is complete. We'll review it then.

sanketpatil06 avatar Nov 25 '26 08:11 sanketpatil06

Thanks @sanketpatil06! I've marked #8307 ready for review. It is stacked on #8041 (environment simulation state per session), so its diff currently includes that commit; the change for this issue is e07629e, plus @paulraj's regression tests in 071dd98. Once #8041 lands I'll rebase so only those remain.

Fruiterer333 avatar Nov 25 '26 11:11 Fruiterer333