-
Notifications
You must be signed in to change notification settings - Fork 36
feat: add chaos testing module for fault injection #224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
36e431c
first implement of chaos module
ybdarrenwang b6211f1
fix tool output corruption
ybdarrenwang 1bc20f3
refactor with contextvar
ybdarrenwang 68db60c
improve style
ybdarrenwang 28a0679
add tests
ybdarrenwang bb023d6
address review bot's comments
ybdarrenwang 61dd7d7
replace chaos scenario with chaos case
ybdarrenwang 46a49ed
update chaos effect type and map; fix pydantic serialization and asyn…
ybdarrenwang d5bcd6e
remove apply rate; limit 1 effect per tool
ybdarrenwang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| """Chaos testing module for Strands Evals. | ||
|
|
||
| Provides deterministic fault injection for evaluating agent resilience | ||
| under tool failures and response corruption scenarios. | ||
| """ | ||
|
|
||
| from .case import ChaosCase | ||
| from .effects import ( | ||
| ChaosEffect, | ||
| CorruptValues, | ||
| ExecutionError, | ||
| NetworkError, | ||
| RemoveFields, | ||
| Timeout, | ||
| ToolEffect, | ||
| ToolEffectUnion, | ||
| TruncateFields, | ||
| ValidationError, | ||
| ) | ||
| from .experiment import ChaosExperiment | ||
| from .plugin import ChaosPlugin | ||
|
|
||
| __all__ = [ | ||
| # Core classes | ||
| "ChaosCase", | ||
| "ChaosExperiment", | ||
| "ChaosPlugin", | ||
| # Effect hierarchy | ||
| "ChaosEffect", | ||
| "ToolEffect", | ||
| "ToolEffectUnion", | ||
| # Pre-hook effects (tool call failures) | ||
| "Timeout", | ||
| "NetworkError", | ||
| "ExecutionError", | ||
| "ValidationError", | ||
| # Post-hook effects (response corruption) | ||
| "TruncateFields", | ||
| "RemoveFields", | ||
| "CorruptValues", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| """Internal context variable for tracking the active chaos case. | ||
|
|
||
| The ChaosPlugin reads from this ContextVar at hook time. | ||
| The ChaosExperiment sets and resets it around each case's task invocation. | ||
|
|
||
| Using a ContextVar ensures correct behavior under: | ||
| - Sequential execution (trivially correct) | ||
| - Async execution (each asyncio.Task inherits the var from its parent) | ||
| - Threaded execution (each thread gets its own copy) | ||
| """ | ||
|
|
||
| from contextvars import ContextVar | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| if TYPE_CHECKING: | ||
| from .case import ChaosCase | ||
|
|
||
| _current_chaos_case: ContextVar["ChaosCase | None"] = ContextVar( | ||
| "chaos_current_case", | ||
| default=None, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| """Chaos case definition. | ||
|
|
||
| A ChaosCase extends Case with chaos-specific fields, providing a stable | ||
| extension point for failure injection configuration without modifying the | ||
| base Case class. | ||
| """ | ||
|
|
||
| import uuid | ||
|
|
||
| from pydantic import Field, model_validator | ||
| from typing_extensions import Generic | ||
|
|
||
| from ..case import Case | ||
| from ..types.evaluation import InputT, OutputT | ||
| from .effects import ToolEffectUnion | ||
|
|
||
|
|
||
| class ChaosCase(Case, Generic[InputT, OutputT]): | ||
| """A test case with associated chaos effects. | ||
|
|
||
| Extends Case to carry the effects mapping that the ChaosPlugin reads | ||
| at hook time. A ChaosCase with empty effects is a baseline run. | ||
|
|
||
| The ``expand`` class method provides the Cartesian product of cases × | ||
| effect maps, producing a flat list of ChaosCase objects ready for | ||
| ChaosExperiment. | ||
|
|
||
| Attributes: | ||
| effects: A dict keyed by effect category. Currently supports | ||
| ``"tool_effects"`` mapping tool_name -> list of effects. | ||
|
|
||
| Example:: | ||
|
|
||
| from strands_evals import Case | ||
| from strands_evals.chaos import ChaosCase | ||
| from strands_evals.chaos.effects import Timeout, TruncateFields | ||
|
|
||
| # Direct construction | ||
| chaos_case = ChaosCase( | ||
| name="search_timeout", | ||
| input="Find flights to Tokyo", | ||
| effects={"tool_effects": {"search_tool": [Timeout()]}}, | ||
| ) | ||
|
|
||
| # Expansion from base cases × named effect maps | ||
| cases = [ | ||
| Case(name="flight_search", input="Find flights to Tokyo"), | ||
| Case(name="hotel_search", input="Find hotels in Tokyo"), | ||
| ] | ||
| effect_maps = { | ||
| "search_timeout": {"tool_effects": {"search_tool": [Timeout()]}}, | ||
| "search_truncated": {"tool_effects": {"search_tool": [TruncateFields(max_length=5)]}}, | ||
| } | ||
| chaos_cases = ChaosCase.expand(cases, effect_maps, include_no_effect_baseline=True) | ||
| # Produces 6 ChaosCase objects: 2 cases × (2 effect maps + 1 baseline) | ||
| """ | ||
|
|
||
| effects: dict[str, dict[str, list[ToolEffectUnion]]] = Field( | ||
| default_factory=dict, | ||
| description="Effect categories. Currently supports 'tool_effects' mapping " | ||
| "tool_name -> list of effects. Empty dict means baseline (no chaos).", | ||
| ) | ||
|
|
||
| @model_validator(mode="after") | ||
| def _validate_tool_effects(self) -> "ChaosCase": | ||
| """Validate tool effects configuration.""" | ||
| for tool_name, effects_list in self.tool_effects.items(): | ||
| if len(effects_list) > 1: | ||
| raise ValueError( | ||
| f"Tool '{tool_name}' has {len(effects_list)} effects — only 1 is allowed per " | ||
| f"ChaosCase. Use separate ChaosCase instances to test effects independently." | ||
| ) | ||
| return self | ||
|
|
||
| @classmethod | ||
| def expand( | ||
| cls, | ||
| cases: list[Case], | ||
| effect_maps: dict[str, dict[str, dict[str, list[ToolEffectUnion]]]], | ||
| include_no_effect_baseline: bool = False, | ||
| ) -> list["ChaosCase"]: | ||
| """Generate the Cartesian product of cases × named effect maps. | ||
|
|
||
| Produces a flat list of ChaosCase objects, one for each (case, effect_map) | ||
| combination. Each ChaosCase gets a fresh session_id and a composite name | ||
| built from the case name and the effect map key. | ||
|
|
||
| Args: | ||
| cases: Base test cases to expand. | ||
| effect_maps: Named effect configurations. Keys are short human-readable | ||
| names (used in the composite case name); values are dicts keyed by | ||
| effect category (e.g. ``"tool_effects"``) mapping tool_name -> list | ||
| of effect instances. | ||
| Example:: | ||
|
|
||
| { | ||
| "search_timeout": { | ||
| "tool_effects": {"search_tool": [Timeout()]} | ||
| }, | ||
| } | ||
| include_no_effect_baseline: If True, includes a baseline (no chaos) | ||
| variant for each case. Defaults to False. | ||
|
|
||
| Returns: | ||
| Flat list of ChaosCase objects with composite names like | ||
| "flight_search|baseline" or "flight_search|search_timeout". | ||
| """ | ||
| all_entries: list[tuple[str, dict[str, dict[str, list[ToolEffectUnion]]]]] = [] | ||
|
|
||
| if include_no_effect_baseline: | ||
| all_entries.append(("baseline", {})) | ||
|
|
||
| for name, effects_config in effect_maps.items(): | ||
| all_entries.append((name, effects_config)) | ||
|
|
||
| expanded: list[ChaosCase] = [] | ||
| for case in cases: | ||
| for condition_name, effects_config in all_entries: | ||
| session_id = str(uuid.uuid4()) | ||
| expanded_name = f"{case.name}|{condition_name}" if case.name else condition_name | ||
|
|
||
| expanded.append( | ||
| cls( | ||
| name=expanded_name, | ||
| session_id=session_id, | ||
| input=case.input, | ||
| expected_output=case.expected_output, | ||
| expected_assertion=case.expected_assertion, | ||
| expected_trajectory=case.expected_trajectory, | ||
| expected_interactions=case.expected_interactions, | ||
| expected_environment_state=case.expected_environment_state, | ||
| metadata=case.metadata, | ||
| effects=effects_config, | ||
| ) | ||
| ) | ||
|
|
||
| return expanded | ||
|
|
||
| @property | ||
| def tool_effects(self) -> dict[str, list[ToolEffectUnion]]: | ||
| """Convenience accessor for effects['tool_effects'].""" | ||
| return self.effects.get("tool_effects", {}) | ||
|
|
||
| def __repr__(self) -> str: | ||
| effects_str = ", ".join( | ||
| f"{target}: [{', '.join(type(e).__name__ for e in effs)}]" for target, effs in self.tool_effects.items() | ||
| ) | ||
| return f"ChaosCase(name='{self.name}', effects={{{effects_str}}})" | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.