agent-chaos-engineering 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of agent-chaos-engineering might be problematic. Click here for more details.
- agent_chaos/__init__.py +157 -0
- agent_chaos/_version.py +2 -0
- agent_chaos/adapters/__init__.py +8 -0
- agent_chaos/adapters/langchain.py +34 -0
- agent_chaos/adapters/langgraph.py +223 -0
- agent_chaos/adapters/ma_trace.py +51 -0
- agent_chaos/checkpoint.py +137 -0
- agent_chaos/cli.py +173 -0
- agent_chaos/consensus.py +228 -0
- agent_chaos/detection.py +321 -0
- agent_chaos/faults.py +504 -0
- agent_chaos/healer.py +338 -0
- agent_chaos/injector.py +398 -0
- agent_chaos/patterns.py +263 -0
- agent_chaos/plan.py +166 -0
- agent_chaos/py.typed +0 -0
- agent_chaos/runner.py +240 -0
- agent_chaos/scorecard.py +238 -0
- agent_chaos/sim.py +175 -0
- agent_chaos/zones.py +208 -0
- agent_chaos_engineering-0.1.0.dist-info/METADATA +305 -0
- agent_chaos_engineering-0.1.0.dist-info/RECORD +25 -0
- agent_chaos_engineering-0.1.0.dist-info/WHEEL +4 -0
- agent_chaos_engineering-0.1.0.dist-info/entry_points.txt +2 -0
- agent_chaos_engineering-0.1.0.dist-info/licenses/LICENSE +201 -0
agent_chaos/__init__.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""agent-chaos: chaos engineering and self-healing recovery patterns for multi-agent systems.
|
|
3
|
+
|
|
4
|
+
Break things::
|
|
5
|
+
|
|
6
|
+
from agent_chaos import ChaosInjector, ChaosPlan
|
|
7
|
+
chaos = ChaosInjector(ChaosPlan.standard(seed=1), agents=["planner", "executor"])
|
|
8
|
+
|
|
9
|
+
@chaos.tool("search", agent="executor") # 5 % of calls raise, some are delayed
|
|
10
|
+
def search(q): ...
|
|
11
|
+
|
|
12
|
+
@chaos.reasoning_step("planner") # 3 % of outputs become hallucinations
|
|
13
|
+
def plan(goal): ...
|
|
14
|
+
|
|
15
|
+
delivery = chaos.message("planner", "executor", plan) # may be dropped / rerouted / delayed
|
|
16
|
+
|
|
17
|
+
Heal them::
|
|
18
|
+
|
|
19
|
+
from agent_chaos import SelfHealer
|
|
20
|
+
healer = SelfHealer(agents=["planner", "executor"], dependencies={"executor": ["planner"]})
|
|
21
|
+
healer.checkpoint("planner", state, coherence=1.0)
|
|
22
|
+
signal, action = healer.heal("planner", task="t1", output=answer, constraints=[...])
|
|
23
|
+
|
|
24
|
+
Measure::
|
|
25
|
+
|
|
26
|
+
from agent_chaos import ScenarioRunner
|
|
27
|
+
runner = ScenarioRunner(my_scenario, plan=ChaosPlan.standard(), episodes=30)
|
|
28
|
+
print(runner.run().scorecard.to_markdown())
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
from ._version import __version__
|
|
34
|
+
from .checkpoint import CheckpointStore, SemanticCheckpoint
|
|
35
|
+
from .consensus import (
|
|
36
|
+
ConsensusWeights,
|
|
37
|
+
FusedDecision,
|
|
38
|
+
TrustWeightedDecision,
|
|
39
|
+
cross_path_consistency,
|
|
40
|
+
weighted_consensus,
|
|
41
|
+
weighted_vote,
|
|
42
|
+
)
|
|
43
|
+
from .detection import (
|
|
44
|
+
AnomalyDetector,
|
|
45
|
+
AnomalySignal,
|
|
46
|
+
CoherenceMonitor,
|
|
47
|
+
PathDiscrepancyDetector,
|
|
48
|
+
ReasoningVarianceMonitor,
|
|
49
|
+
)
|
|
50
|
+
from .faults import (
|
|
51
|
+
FAULT_TYPES,
|
|
52
|
+
ChaosToolError,
|
|
53
|
+
CyclicDependency,
|
|
54
|
+
DataPoisoning,
|
|
55
|
+
Fault,
|
|
56
|
+
FaultContext,
|
|
57
|
+
FaultKind,
|
|
58
|
+
HallucinationLoop,
|
|
59
|
+
InjectionRecord,
|
|
60
|
+
InputPerturbation,
|
|
61
|
+
Miscoordination,
|
|
62
|
+
NetworkDelay,
|
|
63
|
+
Outcome,
|
|
64
|
+
PerceptionSpoofing,
|
|
65
|
+
StaleMemory,
|
|
66
|
+
Surface,
|
|
67
|
+
ToolError,
|
|
68
|
+
describe_faults,
|
|
69
|
+
)
|
|
70
|
+
from .healer import HealingConfig, Incident, SelfHealer
|
|
71
|
+
from .injector import ChaosInjector, ChaosMemory, Delivery
|
|
72
|
+
from .patterns import (
|
|
73
|
+
DEFAULT_PATTERNS,
|
|
74
|
+
AdaptiveConsensusReset,
|
|
75
|
+
CognitiveRollback,
|
|
76
|
+
FailureContext,
|
|
77
|
+
PatternProfile,
|
|
78
|
+
PatternSelector,
|
|
79
|
+
QuarantineIsolation,
|
|
80
|
+
RecoveryAction,
|
|
81
|
+
RecoveryPattern,
|
|
82
|
+
SemanticCheckpointing,
|
|
83
|
+
)
|
|
84
|
+
from .plan import PRESETS, ChaosPlan, ScheduleMode
|
|
85
|
+
from .runner import RunResult, ScenarioContext, ScenarioOutcome, ScenarioRunner, VirtualClock
|
|
86
|
+
from .scorecard import ARMS, ArmSummary, EpisodeResult, Scorecard, build_scorecard, summarise_arm
|
|
87
|
+
from .zones import AuditRecord, ResilienceZone, ZoneAction, ZoneStatus, ZoneSupervisor
|
|
88
|
+
|
|
89
|
+
__all__ = [
|
|
90
|
+
"ARMS",
|
|
91
|
+
"DEFAULT_PATTERNS",
|
|
92
|
+
"FAULT_TYPES",
|
|
93
|
+
"PRESETS",
|
|
94
|
+
"AdaptiveConsensusReset",
|
|
95
|
+
"AnomalyDetector",
|
|
96
|
+
"AnomalySignal",
|
|
97
|
+
"ArmSummary",
|
|
98
|
+
"AuditRecord",
|
|
99
|
+
"ChaosInjector",
|
|
100
|
+
"ChaosMemory",
|
|
101
|
+
"ChaosPlan",
|
|
102
|
+
"ChaosToolError",
|
|
103
|
+
"CheckpointStore",
|
|
104
|
+
"CognitiveRollback",
|
|
105
|
+
"CoherenceMonitor",
|
|
106
|
+
"ConsensusWeights",
|
|
107
|
+
"CyclicDependency",
|
|
108
|
+
"DataPoisoning",
|
|
109
|
+
"Delivery",
|
|
110
|
+
"EpisodeResult",
|
|
111
|
+
"FailureContext",
|
|
112
|
+
"Fault",
|
|
113
|
+
"FaultContext",
|
|
114
|
+
"FaultKind",
|
|
115
|
+
"FusedDecision",
|
|
116
|
+
"HallucinationLoop",
|
|
117
|
+
"HealingConfig",
|
|
118
|
+
"Incident",
|
|
119
|
+
"InjectionRecord",
|
|
120
|
+
"InputPerturbation",
|
|
121
|
+
"Miscoordination",
|
|
122
|
+
"NetworkDelay",
|
|
123
|
+
"Outcome",
|
|
124
|
+
"PathDiscrepancyDetector",
|
|
125
|
+
"PatternProfile",
|
|
126
|
+
"PatternSelector",
|
|
127
|
+
"PerceptionSpoofing",
|
|
128
|
+
"QuarantineIsolation",
|
|
129
|
+
"ReasoningVarianceMonitor",
|
|
130
|
+
"RecoveryAction",
|
|
131
|
+
"RecoveryPattern",
|
|
132
|
+
"ResilienceZone",
|
|
133
|
+
"RunResult",
|
|
134
|
+
"ScenarioContext",
|
|
135
|
+
"ScenarioOutcome",
|
|
136
|
+
"ScenarioRunner",
|
|
137
|
+
"ScheduleMode",
|
|
138
|
+
"Scorecard",
|
|
139
|
+
"SelfHealer",
|
|
140
|
+
"SemanticCheckpoint",
|
|
141
|
+
"SemanticCheckpointing",
|
|
142
|
+
"StaleMemory",
|
|
143
|
+
"Surface",
|
|
144
|
+
"ToolError",
|
|
145
|
+
"TrustWeightedDecision",
|
|
146
|
+
"VirtualClock",
|
|
147
|
+
"ZoneAction",
|
|
148
|
+
"ZoneStatus",
|
|
149
|
+
"ZoneSupervisor",
|
|
150
|
+
"__version__",
|
|
151
|
+
"build_scorecard",
|
|
152
|
+
"cross_path_consistency",
|
|
153
|
+
"describe_faults",
|
|
154
|
+
"summarise_arm",
|
|
155
|
+
"weighted_consensus",
|
|
156
|
+
"weighted_vote",
|
|
157
|
+
]
|
agent_chaos/_version.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Optional integrations (each imports its dependency lazily):
|
|
3
|
+
|
|
4
|
+
* :mod:`agent_chaos.adapters.langgraph` - chaos node wrappers, ``heal_node`` and the
|
|
5
|
+
``SelfHealingCheckpointSaver`` checkpointer extension;
|
|
6
|
+
* :mod:`agent_chaos.adapters.langchain` - ``chaos_tool`` for LangChain tools;
|
|
7
|
+
* :mod:`agent_chaos.adapters.ma_trace` - log injections and recoveries into ma-trace episodes.
|
|
8
|
+
"""
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""LangChain integration: wrap tools so tool-error / delay / perturbation faults apply."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ..injector import ChaosInjector
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def chaos_tool(tool: Any, injector: ChaosInjector, *, agent: str | None = None) -> Any:
|
|
13
|
+
"""Return a chaos-wrapped copy of a LangChain ``BaseTool`` (or a plain callable)."""
|
|
14
|
+
try:
|
|
15
|
+
from langchain_core.tools import BaseTool, StructuredTool
|
|
16
|
+
except ImportError as e: # pragma: no cover - only without the extra
|
|
17
|
+
raise ImportError(
|
|
18
|
+
"chaos_tool needs langchain-core: pip install 'agent-chaos-engineering[langgraph]'"
|
|
19
|
+
) from e
|
|
20
|
+
|
|
21
|
+
if isinstance(tool, BaseTool):
|
|
22
|
+
original = tool
|
|
23
|
+
|
|
24
|
+
def call(**kwargs: Any) -> Any:
|
|
25
|
+
return original.invoke(kwargs)
|
|
26
|
+
|
|
27
|
+
wrapped: Callable[..., Any] = injector.tool(original.name, agent)(call)
|
|
28
|
+
return StructuredTool.from_function(
|
|
29
|
+
func=wrapped,
|
|
30
|
+
name=original.name,
|
|
31
|
+
description=original.description,
|
|
32
|
+
args_schema=original.args_schema,
|
|
33
|
+
)
|
|
34
|
+
return injector.tool(getattr(tool, "__name__", "tool"), agent)(tool)
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""LangGraph integration.
|
|
3
|
+
|
|
4
|
+
* :func:`chaos_node` - wrap a node so hallucination-loop faults can corrupt its output;
|
|
5
|
+
* :func:`heal_node` - wrap a node with checkpoint / detect / restore (cognitive rollback at
|
|
6
|
+
node granularity);
|
|
7
|
+
* :class:`SelfHealingCheckpointSaver` - wrap any LangGraph checkpointer so every checkpoint
|
|
8
|
+
carries a *coherence* score, and ask it for the best valid checkpoint to resume from.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import builtins
|
|
14
|
+
import functools
|
|
15
|
+
import inspect
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import AsyncIterator, Callable, Iterator
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from ..healer import SelfHealer
|
|
21
|
+
from ..injector import ChaosInjector
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from langgraph.checkpoint.base import BaseCheckpointSaver
|
|
25
|
+
except ImportError as e: # pragma: no cover - only without the extra
|
|
26
|
+
raise ImportError(
|
|
27
|
+
"the LangGraph adapter needs langgraph: pip install 'agent-chaos-engineering[langgraph]'"
|
|
28
|
+
) from e
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def chaos_node(
|
|
32
|
+
fn: Callable[..., Any], injector: ChaosInjector, *, agent: str | None = None
|
|
33
|
+
) -> Callable[..., Any]:
|
|
34
|
+
"""Return a node whose state update passes through the injector's reasoning surface."""
|
|
35
|
+
name: str = agent or str(getattr(fn, "__name__", "node"))
|
|
36
|
+
if inspect.iscoroutinefunction(fn):
|
|
37
|
+
|
|
38
|
+
@functools.wraps(fn)
|
|
39
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
40
|
+
return injector.reason(name, await fn(*args, **kwargs), name)
|
|
41
|
+
|
|
42
|
+
return async_wrapper
|
|
43
|
+
|
|
44
|
+
@functools.wraps(fn)
|
|
45
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
46
|
+
return injector.reason(name, fn(*args, **kwargs), name)
|
|
47
|
+
|
|
48
|
+
return wrapper
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def heal_node(
|
|
52
|
+
fn: Callable[..., Any],
|
|
53
|
+
healer: SelfHealer,
|
|
54
|
+
*,
|
|
55
|
+
agent: str | None = None,
|
|
56
|
+
coherence: Callable[[Any], float | list[bool] | tuple[bool, ...]],
|
|
57
|
+
task: str | None = None,
|
|
58
|
+
) -> Callable[..., Any]:
|
|
59
|
+
"""Wrap a node with the self-healing loop.
|
|
60
|
+
|
|
61
|
+
``coherence(update)`` returns either a ratio in ``[0, 1]`` or a list of constraint
|
|
62
|
+
booleans. Healthy updates are checkpointed; a confirmed anomaly triggers recovery and,
|
|
63
|
+
when the chosen pattern restores a checkpoint, the restored state update is returned
|
|
64
|
+
in place of the node's output.
|
|
65
|
+
"""
|
|
66
|
+
name: str = agent or str(getattr(fn, "__name__", "node"))
|
|
67
|
+
|
|
68
|
+
def _after(update: Any) -> Any:
|
|
69
|
+
score = coherence(update)
|
|
70
|
+
kwargs: dict[str, Any]
|
|
71
|
+
if isinstance(score, (list, tuple)):
|
|
72
|
+
kwargs = {"constraints": list(score)}
|
|
73
|
+
else:
|
|
74
|
+
kwargs = {"coherence": float(score)}
|
|
75
|
+
signal, action = healer.heal(name, task=task or name, output=None, **kwargs)
|
|
76
|
+
if action is not None and action.kind == "restore" and action.state is not None:
|
|
77
|
+
return action.state
|
|
78
|
+
if not signal.anomalous:
|
|
79
|
+
c = kwargs.get("coherence")
|
|
80
|
+
if c is None:
|
|
81
|
+
cons = kwargs["constraints"]
|
|
82
|
+
c = sum(1 for x in cons if x) / len(cons) if cons else 1.0
|
|
83
|
+
healer.checkpoint(name, update, c)
|
|
84
|
+
return update
|
|
85
|
+
|
|
86
|
+
if inspect.iscoroutinefunction(fn):
|
|
87
|
+
|
|
88
|
+
@functools.wraps(fn)
|
|
89
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
90
|
+
return _after(await fn(*args, **kwargs))
|
|
91
|
+
|
|
92
|
+
return async_wrapper
|
|
93
|
+
|
|
94
|
+
@functools.wraps(fn)
|
|
95
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
96
|
+
return _after(fn(*args, **kwargs))
|
|
97
|
+
|
|
98
|
+
return wrapper
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class SelfHealingCheckpointSaver(BaseCheckpointSaver): # type: ignore[misc]
|
|
102
|
+
"""Checkpointer extension: tags every checkpoint with a coherence score.
|
|
103
|
+
|
|
104
|
+
Wrap any saver (``InMemorySaver``, ``SqliteSaver``, ``PostgresSaver`` ...)::
|
|
105
|
+
|
|
106
|
+
saver = SelfHealingCheckpointSaver(InMemorySaver(), coherence=score_state)
|
|
107
|
+
graph = builder.compile(checkpointer=saver)
|
|
108
|
+
|
|
109
|
+
After a run, ``saver.best_valid_config(thread_id)`` returns the config of the checkpoint
|
|
110
|
+
maximising ``coherence − λ·age`` among those above the validity threshold. Pass it to
|
|
111
|
+
``graph.invoke(None, config=...)`` / ``graph.update_state`` to resume from that state
|
|
112
|
+
(LangGraph time travel).
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
def __init__(
|
|
116
|
+
self,
|
|
117
|
+
inner: Any,
|
|
118
|
+
*,
|
|
119
|
+
coherence: Callable[[dict[str, Any]], float],
|
|
120
|
+
threshold: float = 0.85,
|
|
121
|
+
decay_lambda: float = 0.001,
|
|
122
|
+
clock: Callable[[], float] = time.time,
|
|
123
|
+
) -> None:
|
|
124
|
+
super().__init__(serde=getattr(inner, "serde", None))
|
|
125
|
+
self.inner = inner
|
|
126
|
+
self.coherence_fn = coherence
|
|
127
|
+
self.threshold = threshold
|
|
128
|
+
self.decay_lambda = decay_lambda
|
|
129
|
+
self._clock = clock
|
|
130
|
+
|
|
131
|
+
# -- delegation -----------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def config_specs(self) -> Any:
|
|
135
|
+
return self.inner.config_specs
|
|
136
|
+
|
|
137
|
+
def get_tuple(self, config: Any) -> Any:
|
|
138
|
+
return self.inner.get_tuple(config)
|
|
139
|
+
|
|
140
|
+
def list(
|
|
141
|
+
self, config: Any, *, filter: Any = None, before: Any = None, limit: Any = None
|
|
142
|
+
) -> Iterator[Any]:
|
|
143
|
+
return self.inner.list(config, filter=filter, before=before, limit=limit)
|
|
144
|
+
|
|
145
|
+
def put(self, config: Any, checkpoint: Any, metadata: Any, new_versions: Any) -> Any:
|
|
146
|
+
return self.inner.put(config, checkpoint, self._tag(checkpoint, metadata), new_versions)
|
|
147
|
+
|
|
148
|
+
def put_writes(self, config: Any, writes: Any, task_id: str, task_path: str = "") -> None:
|
|
149
|
+
return self.inner.put_writes(config, writes, task_id, task_path)
|
|
150
|
+
|
|
151
|
+
def delete_thread(self, thread_id: str) -> None:
|
|
152
|
+
return self.inner.delete_thread(thread_id)
|
|
153
|
+
|
|
154
|
+
async def aget_tuple(self, config: Any) -> Any:
|
|
155
|
+
return await self.inner.aget_tuple(config)
|
|
156
|
+
|
|
157
|
+
async def alist(
|
|
158
|
+
self, config: Any, *, filter: Any = None, before: Any = None, limit: Any = None
|
|
159
|
+
) -> AsyncIterator[Any]:
|
|
160
|
+
async for item in self.inner.alist(config, filter=filter, before=before, limit=limit):
|
|
161
|
+
yield item
|
|
162
|
+
|
|
163
|
+
async def aput(self, config: Any, checkpoint: Any, metadata: Any, new_versions: Any) -> Any:
|
|
164
|
+
return await self.inner.aput(config, checkpoint, self._tag(checkpoint, metadata), new_versions)
|
|
165
|
+
|
|
166
|
+
async def aput_writes(self, config: Any, writes: Any, task_id: str, task_path: str = "") -> None:
|
|
167
|
+
return await self.inner.aput_writes(config, writes, task_id, task_path)
|
|
168
|
+
|
|
169
|
+
async def adelete_thread(self, thread_id: str) -> None:
|
|
170
|
+
return await self.inner.adelete_thread(thread_id)
|
|
171
|
+
|
|
172
|
+
def get_next_version(self, current: Any, channel: Any = None) -> Any:
|
|
173
|
+
return self.inner.get_next_version(current, channel)
|
|
174
|
+
|
|
175
|
+
# -- coherence -------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
def _tag(self, checkpoint: Any, metadata: Any) -> Any:
|
|
178
|
+
values = checkpoint.get("channel_values", {}) if isinstance(checkpoint, dict) else {}
|
|
179
|
+
try:
|
|
180
|
+
score = float(self.coherence_fn(values))
|
|
181
|
+
except Exception:
|
|
182
|
+
score = 1.0
|
|
183
|
+
tagged = dict(metadata or {})
|
|
184
|
+
tagged["coherence"] = score
|
|
185
|
+
tagged["coherence_t"] = self._clock()
|
|
186
|
+
return tagged
|
|
187
|
+
|
|
188
|
+
def coherence_history(self, thread_id: str) -> builtins.list[tuple[str, float, float]]:
|
|
189
|
+
"""``[(checkpoint_id, coherence, timestamp)]`` newest first."""
|
|
190
|
+
out: builtins.list[tuple[str, float, float]] = []
|
|
191
|
+
for t in self.inner.list({"configurable": {"thread_id": thread_id}}):
|
|
192
|
+
md = t.metadata or {}
|
|
193
|
+
if "coherence" in md:
|
|
194
|
+
out.append(
|
|
195
|
+
(
|
|
196
|
+
t.config["configurable"]["checkpoint_id"],
|
|
197
|
+
float(md["coherence"]),
|
|
198
|
+
float(md.get("coherence_t", 0.0)),
|
|
199
|
+
)
|
|
200
|
+
)
|
|
201
|
+
return out
|
|
202
|
+
|
|
203
|
+
def latest_coherence(self, thread_id: str) -> float | None:
|
|
204
|
+
hist = self.coherence_history(thread_id)
|
|
205
|
+
return hist[0][1] if hist else None
|
|
206
|
+
|
|
207
|
+
def needs_rollback(self, thread_id: str) -> bool:
|
|
208
|
+
c = self.latest_coherence(thread_id)
|
|
209
|
+
return c is not None and c < self.threshold
|
|
210
|
+
|
|
211
|
+
def best_valid_config(self, thread_id: str) -> Any:
|
|
212
|
+
best = None
|
|
213
|
+
best_score = float("-inf")
|
|
214
|
+
now = self._clock()
|
|
215
|
+
for t in self.inner.list({"configurable": {"thread_id": thread_id}}):
|
|
216
|
+
md = t.metadata or {}
|
|
217
|
+
c = md.get("coherence")
|
|
218
|
+
if c is None or float(c) < self.threshold:
|
|
219
|
+
continue
|
|
220
|
+
score = float(c) - self.decay_lambda * max(0.0, now - float(md.get("coherence_t", now)))
|
|
221
|
+
if score > best_score:
|
|
222
|
+
best, best_score = t, score
|
|
223
|
+
return best.config if best is not None else None
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Record injections and recoveries into the current `MA-Trace <https://pypi.org/project/multi-agent-observability/>`_
|
|
3
|
+
episode (requires ``pip install multi-agent-observability``)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from ..healer import SelfHealer
|
|
11
|
+
from ..injector import ChaosInjector
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _chain(previous: Callable[[Any], None] | None, new: Callable[[Any], None]) -> Callable[[Any], None]:
|
|
15
|
+
def both(item: Any) -> None:
|
|
16
|
+
if previous is not None:
|
|
17
|
+
previous(item)
|
|
18
|
+
new(item)
|
|
19
|
+
|
|
20
|
+
return both
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def bind_ma_trace(injector: ChaosInjector | None = None, healer: SelfHealer | None = None) -> None:
|
|
24
|
+
"""Log every injection (warning) and recovery action (info) as ma-trace log events."""
|
|
25
|
+
try:
|
|
26
|
+
import ma_trace as mt
|
|
27
|
+
except ImportError as e: # pragma: no cover
|
|
28
|
+
raise ImportError("bind_ma_trace needs ma-trace: pip install multi-agent-observability") from e
|
|
29
|
+
|
|
30
|
+
if injector is not None:
|
|
31
|
+
|
|
32
|
+
def on_injection(rec: Any) -> None:
|
|
33
|
+
data = {k: v for k, v in rec.to_dict().items() if k != "agent"}
|
|
34
|
+
mt.log(
|
|
35
|
+
f"chaos: {rec.fault.value} on {rec.surface.value}", level="warning", agent=rec.agent, **data
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
injector.on_injection = _chain(injector.on_injection, on_injection)
|
|
39
|
+
if healer is not None:
|
|
40
|
+
|
|
41
|
+
def on_recovery(action: Any) -> None:
|
|
42
|
+
agent = action.agents[0] if action.agents else None
|
|
43
|
+
mt.log(
|
|
44
|
+
f"recovery: {action.describe()}",
|
|
45
|
+
level="info",
|
|
46
|
+
agent=agent,
|
|
47
|
+
pattern=action.pattern,
|
|
48
|
+
kind=action.kind,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
healer.on_recovery = _chain(healer.on_recovery, on_recovery)
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Semantic checkpoints: reasoning states captured at decision points, each tagged with a
|
|
3
|
+
coherence score, plus the restoration objective used by cognitive rollback."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import copy
|
|
8
|
+
import itertools
|
|
9
|
+
import time
|
|
10
|
+
from collections import defaultdict, deque
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class SemanticCheckpoint:
|
|
18
|
+
id: int
|
|
19
|
+
agent: str
|
|
20
|
+
state: Any
|
|
21
|
+
coherence: float
|
|
22
|
+
t: float
|
|
23
|
+
step: int = 0
|
|
24
|
+
label: str | None = None
|
|
25
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
26
|
+
|
|
27
|
+
def score(self, now: float, decay_lambda: float) -> float:
|
|
28
|
+
"""Restoration score ``coherence − λ · seconds_since_checkpoint``."""
|
|
29
|
+
return self.coherence - decay_lambda * max(0.0, now - self.t)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CheckpointStore:
|
|
33
|
+
"""Bounded per-agent history of :class:`SemanticCheckpoint` objects.
|
|
34
|
+
|
|
35
|
+
* :meth:`latest_valid` - the most recent checkpoint whose coherence meets
|
|
36
|
+
``validity_threshold`` (semantic checkpointing);
|
|
37
|
+
* :meth:`best` - ``argmax(coherence − λ·age)`` over the history (cognitive rollback),
|
|
38
|
+
balancing semantic validity against the progress lost by going back further.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
*,
|
|
44
|
+
capacity_per_agent: int = 20,
|
|
45
|
+
validity_threshold: float = 0.85,
|
|
46
|
+
decay_lambda: float = 0.001,
|
|
47
|
+
clock: Callable[[], float] = time.time,
|
|
48
|
+
) -> None:
|
|
49
|
+
self.capacity = capacity_per_agent
|
|
50
|
+
self.validity_threshold = validity_threshold
|
|
51
|
+
self.decay_lambda = decay_lambda
|
|
52
|
+
self._clock = clock
|
|
53
|
+
self._ids = itertools.count(1)
|
|
54
|
+
self._store: dict[str, deque[SemanticCheckpoint]] = defaultdict(
|
|
55
|
+
lambda: deque(maxlen=capacity_per_agent)
|
|
56
|
+
)
|
|
57
|
+
self.restorations = 0
|
|
58
|
+
|
|
59
|
+
def save(
|
|
60
|
+
self,
|
|
61
|
+
agent: str,
|
|
62
|
+
state: Any,
|
|
63
|
+
coherence: float,
|
|
64
|
+
*,
|
|
65
|
+
step: int = 0,
|
|
66
|
+
label: str | None = None,
|
|
67
|
+
**metadata: Any,
|
|
68
|
+
) -> SemanticCheckpoint:
|
|
69
|
+
cp = SemanticCheckpoint(
|
|
70
|
+
id=next(self._ids),
|
|
71
|
+
agent=agent,
|
|
72
|
+
state=copy.deepcopy(state),
|
|
73
|
+
coherence=float(coherence),
|
|
74
|
+
t=self._clock(),
|
|
75
|
+
step=step,
|
|
76
|
+
label=label,
|
|
77
|
+
metadata=dict(metadata),
|
|
78
|
+
)
|
|
79
|
+
self._store[agent].append(cp)
|
|
80
|
+
return cp
|
|
81
|
+
|
|
82
|
+
def history(self, agent: str) -> list[SemanticCheckpoint]:
|
|
83
|
+
return list(self._store.get(agent, ()))
|
|
84
|
+
|
|
85
|
+
def latest(self, agent: str) -> SemanticCheckpoint | None:
|
|
86
|
+
hist = self._store.get(agent)
|
|
87
|
+
return hist[-1] if hist else None
|
|
88
|
+
|
|
89
|
+
def latest_valid(self, agent: str) -> SemanticCheckpoint | None:
|
|
90
|
+
for cp in reversed(self._store.get(agent, ())):
|
|
91
|
+
if cp.coherence >= self.validity_threshold:
|
|
92
|
+
return cp
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
def best(
|
|
96
|
+
self, agent: str, now: float | None = None, *, valid_only: bool = True
|
|
97
|
+
) -> SemanticCheckpoint | None:
|
|
98
|
+
hist = self._store.get(agent)
|
|
99
|
+
if not hist:
|
|
100
|
+
return None
|
|
101
|
+
candidates = (
|
|
102
|
+
[cp for cp in hist if cp.coherence >= self.validity_threshold] if valid_only else list(hist)
|
|
103
|
+
)
|
|
104
|
+
if not candidates:
|
|
105
|
+
return None
|
|
106
|
+
t = self._clock() if now is None else now
|
|
107
|
+
return max(candidates, key=lambda cp: (cp.score(t, self.decay_lambda), cp.id))
|
|
108
|
+
|
|
109
|
+
def validity(self, agent: str) -> float:
|
|
110
|
+
"""Coherence of the best valid checkpoint (0 when none exists)."""
|
|
111
|
+
cp = self.best(agent)
|
|
112
|
+
return cp.coherence if cp is not None else 0.0
|
|
113
|
+
|
|
114
|
+
def restore(self, checkpoint: SemanticCheckpoint) -> Any:
|
|
115
|
+
"""Return a deep copy of the checkpoint's state (so the caller can mutate it)."""
|
|
116
|
+
self.restorations += 1
|
|
117
|
+
return copy.deepcopy(checkpoint.state)
|
|
118
|
+
|
|
119
|
+
def prune(self, agent: str, *, before_step: int | None = None, keep_last: int | None = None) -> int:
|
|
120
|
+
hist = self._store.get(agent)
|
|
121
|
+
if not hist:
|
|
122
|
+
return 0
|
|
123
|
+
items = list(hist)
|
|
124
|
+
if before_step is not None:
|
|
125
|
+
items = [cp for cp in items if cp.step >= before_step]
|
|
126
|
+
if keep_last is not None:
|
|
127
|
+
items = items[-keep_last:]
|
|
128
|
+
removed = len(hist) - len(items)
|
|
129
|
+
hist.clear()
|
|
130
|
+
hist.extend(items)
|
|
131
|
+
return removed
|
|
132
|
+
|
|
133
|
+
def agents(self) -> list[str]:
|
|
134
|
+
return [a for a, h in self._store.items() if h]
|
|
135
|
+
|
|
136
|
+
def __len__(self) -> int:
|
|
137
|
+
return sum(len(h) for h in self._store.values())
|