operon-langgraph-gates 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.
- operon_langgraph_gates/__init__.py +33 -0
- operon_langgraph_gates/_common.py +79 -0
- operon_langgraph_gates/embedders.py +65 -0
- operon_langgraph_gates/integrity.py +229 -0
- operon_langgraph_gates/py.typed +0 -0
- operon_langgraph_gates/stagnation.py +337 -0
- operon_langgraph_gates-0.1.0.dist-info/METADATA +202 -0
- operon_langgraph_gates-0.1.0.dist-info/RECORD +10 -0
- operon_langgraph_gates-0.1.0.dist-info/WHEEL +4 -0
- operon_langgraph_gates-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Reliability primitives for LangGraph.
|
|
2
|
+
|
|
3
|
+
Two gates, both thin wrappers over Operon's certificate framework:
|
|
4
|
+
|
|
5
|
+
- ``StagnationGate``: Bayesian stagnation detection on conditional edges or
|
|
6
|
+
node outputs. Emits ``behavioral_stability_windowed`` certificates.
|
|
7
|
+
- ``IntegrityGate``: runtime invariant check on checkpointer writes. Emits
|
|
8
|
+
``langgraph_state_integrity`` certificates.
|
|
9
|
+
|
|
10
|
+
Backed by Paper 4 §4.3 (stagnation, 96% real-embedding accuracy) and §4.1
|
|
11
|
+
(DNA-repair integrity, 3/3 benchmarks) + Paper 5 §3 (certificate preservation
|
|
12
|
+
under compilation).
|
|
13
|
+
|
|
14
|
+
The theorem names emitted by each gate are also exposed as public
|
|
15
|
+
constants — ``STAGNATION_THEOREM`` and ``INTEGRITY_THEOREM`` — so
|
|
16
|
+
downstream consumers can key on them without hard-coding strings that
|
|
17
|
+
might drift if the underlying theorem is renamed in ``operon-ai``.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from .integrity import _THEOREM as INTEGRITY_THEOREM
|
|
21
|
+
from .integrity import IntegrityGate
|
|
22
|
+
from .stagnation import _WINDOWED_THEOREM as STAGNATION_THEOREM
|
|
23
|
+
from .stagnation import StagnationGate
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"INTEGRITY_THEOREM",
|
|
29
|
+
"IntegrityGate",
|
|
30
|
+
"STAGNATION_THEOREM",
|
|
31
|
+
"StagnationGate",
|
|
32
|
+
"__version__",
|
|
33
|
+
]
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Shared internals for both gates.
|
|
2
|
+
|
|
3
|
+
Keep this tiny — only things that both ``stagnation`` and ``integrity``
|
|
4
|
+
genuinely need. Any growth beyond a handful of helpers should trigger a
|
|
5
|
+
rethink of the abstraction rather than accretion here.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import inspect
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
EPHEMERAL_THREAD = "__ephemeral__"
|
|
15
|
+
|
|
16
|
+
# Kwarg names LangGraph is known to use when injecting a RunnableConfig
|
|
17
|
+
# dict or a Runtime object into a node. Only these names are trusted for
|
|
18
|
+
# dict-shaped extraction, so a business kwarg whose dict happens to have
|
|
19
|
+
# a ``configurable.thread_id`` key doesn't hijack thread routing.
|
|
20
|
+
_LANGGRAPH_KWARG_NAMES: tuple[str, ...] = ("config", "runtime")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def thread_id(args: tuple[Any, ...], kwargs: dict[str, Any]) -> str:
|
|
24
|
+
"""Extract ``thread_id`` from a LangGraph config/runtime passed to a node.
|
|
25
|
+
|
|
26
|
+
Resolution is explicit to avoid hijack by unrelated business payloads:
|
|
27
|
+
|
|
28
|
+
1. Positional args (LangGraph invocation protocol slots: ``state`` plus
|
|
29
|
+
an optional ``config`` dict or ``runtime`` object).
|
|
30
|
+
2. Known LangGraph kwarg names — ``config``, ``runtime``. Any shape
|
|
31
|
+
(dict RunnableConfig or Runtime-like object) is accepted.
|
|
32
|
+
|
|
33
|
+
Arbitrary kwargs are *not* scanned, so a business dict/object shaped
|
|
34
|
+
like a RunnableConfig cannot hijack per-thread routing. If a new
|
|
35
|
+
LangGraph version adds another kwarg name for config/runtime, add it
|
|
36
|
+
to :data:`_LANGGRAPH_KWARG_NAMES` rather than widening the match.
|
|
37
|
+
|
|
38
|
+
Falls back to :data:`EPHEMERAL_THREAD` when no thread id is present.
|
|
39
|
+
"""
|
|
40
|
+
for c in args:
|
|
41
|
+
tid = _extract_thread_id(c)
|
|
42
|
+
if tid is not None:
|
|
43
|
+
return tid
|
|
44
|
+
for name in _LANGGRAPH_KWARG_NAMES:
|
|
45
|
+
if name in kwargs:
|
|
46
|
+
tid = _extract_thread_id(kwargs[name])
|
|
47
|
+
if tid is not None:
|
|
48
|
+
return tid
|
|
49
|
+
return EPHEMERAL_THREAD
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _extract_thread_id(value: Any) -> str | None:
|
|
53
|
+
if isinstance(value, dict):
|
|
54
|
+
return _from_config_dict(value)
|
|
55
|
+
# Runtime-like object: unwrap via .config (LangGraph 1.x Runtime).
|
|
56
|
+
inner = getattr(value, "config", None)
|
|
57
|
+
if isinstance(inner, dict):
|
|
58
|
+
return _from_config_dict(inner)
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _from_config_dict(cfg: dict[str, Any]) -> str | None:
|
|
63
|
+
configurable = cfg.get("configurable")
|
|
64
|
+
if isinstance(configurable, dict):
|
|
65
|
+
tid = configurable.get("thread_id")
|
|
66
|
+
if tid is not None:
|
|
67
|
+
return str(tid)
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def is_async_callable(fn: Callable[..., Any]) -> bool:
|
|
72
|
+
"""Detect async callables including callable classes with ``async __call__``."""
|
|
73
|
+
if inspect.iscoroutinefunction(fn):
|
|
74
|
+
return True
|
|
75
|
+
# Callable instance of a class with ``async def __call__``: inspect the
|
|
76
|
+
# class-level attribute so ``iscoroutinefunction`` sees the unbound method.
|
|
77
|
+
if callable(fn):
|
|
78
|
+
return inspect.iscoroutinefunction(type(fn).__call__)
|
|
79
|
+
return False
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Zero-dependency character-n-gram embedder.
|
|
2
|
+
|
|
3
|
+
Default for ``StagnationGate`` so users can adopt the gate without installing
|
|
4
|
+
a neural embedding model. Accuracy is lower than a real sentence encoder but
|
|
5
|
+
sufficient to detect the most common stagnation pathology: an agent repeating
|
|
6
|
+
itself verbatim or with trivial edits.
|
|
7
|
+
|
|
8
|
+
Power users can swap in any callable ``(text: str) -> list[float]`` via the
|
|
9
|
+
``embedder=`` parameter on the gate.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import math
|
|
16
|
+
|
|
17
|
+
_DEFAULT_NGRAM = 3
|
|
18
|
+
_DEFAULT_DIM = 512
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class NGramEmbedder:
|
|
22
|
+
"""Character n-gram embedder using hashed-bag-of-n-grams.
|
|
23
|
+
|
|
24
|
+
Produces a fixed-dimension L2-normalized vector; cosine similarity equals
|
|
25
|
+
the dot product. Not as expressive as a neural embedder but deterministic,
|
|
26
|
+
dependency-free, and good enough to catch verbatim-repeat stagnation.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, n: int = _DEFAULT_NGRAM, dim: int = _DEFAULT_DIM) -> None:
|
|
30
|
+
if n < 1:
|
|
31
|
+
raise ValueError(f"n must be >= 1, got {n}")
|
|
32
|
+
if dim < 1:
|
|
33
|
+
raise ValueError(f"dim must be >= 1, got {dim}")
|
|
34
|
+
self.n = n
|
|
35
|
+
self.dim = dim
|
|
36
|
+
|
|
37
|
+
def embed(self, text: str) -> list[float]:
|
|
38
|
+
counts = [0.0] * self.dim
|
|
39
|
+
for gram in _ngrams(text, self.n):
|
|
40
|
+
bucket = _hash_to_bucket(gram, self.dim)
|
|
41
|
+
counts[bucket] += 1.0
|
|
42
|
+
norm = math.sqrt(sum(x * x for x in counts))
|
|
43
|
+
if norm == 0.0:
|
|
44
|
+
return counts
|
|
45
|
+
return [x / norm for x in counts]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def cosine(a: list[float], b: list[float]) -> float:
|
|
49
|
+
"""Cosine similarity in [-1, 1]. Assumes equal dim; zero vectors -> 0.0."""
|
|
50
|
+
if len(a) != len(b):
|
|
51
|
+
raise ValueError(f"dim mismatch: {len(a)} vs {len(b)}")
|
|
52
|
+
return sum(x * y for x, y in zip(a, b, strict=True))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _ngrams(text: str, n: int) -> list[str]:
|
|
56
|
+
if len(text) < n:
|
|
57
|
+
return []
|
|
58
|
+
return [text[i : i + n] for i in range(len(text) - n + 1)]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _hash_to_bucket(gram: str, dim: int) -> int:
|
|
62
|
+
# MD5 is fine here: not cryptographic use, just stable hashing across
|
|
63
|
+
# Python processes (unlike hash(), which is salted per interpreter).
|
|
64
|
+
digest = hashlib.md5(gram.encode("utf-8")).digest()
|
|
65
|
+
return int.from_bytes(digest[:8], "little") % dim
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""IntegrityGate — runtime invariant checks on LangGraph node output.
|
|
2
|
+
|
|
3
|
+
Backed by Operon Paper 4 §4 (Results, "State integrity: clear structural
|
|
4
|
+
value"). In the paper's canonical state-integrity task with four
|
|
5
|
+
corruption sites (three gene drifts + one checksum failure) injected
|
|
6
|
+
between agent stages, the ``DNARepair`` pre/post-flight integrity check
|
|
7
|
+
achieves:
|
|
8
|
+
|
|
9
|
+
- **FULL** variant (with ``DNARepair``): **100%** detection, **100%**
|
|
10
|
+
repair across all repetitions.
|
|
11
|
+
- **RAW** and **GUARDED** variants (no integrity check): **0%**
|
|
12
|
+
detection, **0%** repair — blind to the corruption.
|
|
13
|
+
|
|
14
|
+
Paper 4 calls this "the strongest structural guarantee in the evaluated
|
|
15
|
+
stack" (§4, Table 3, Integrity row). Paper 5 §3 proves preservation of
|
|
16
|
+
certificate-bearing morphisms under compilation in general; this module
|
|
17
|
+
registers a distinct LangGraph-flavored theorem
|
|
18
|
+
(``langgraph_state_integrity``) that is structurally analogous but not
|
|
19
|
+
itself the subject of a preservation proof in the paper. The 100/100
|
|
20
|
+
numbers above apply to the paper's ``DNARepair`` setup on ``Genome``
|
|
21
|
+
objects, not to this package's detection-only reformulation.
|
|
22
|
+
|
|
23
|
+
A full citation record with verbatim paper quotes and a pointer to the
|
|
24
|
+
archived benchmark data is at ``docs/paper-citations.md``.
|
|
25
|
+
|
|
26
|
+
This module is conceptually a thin LangGraph adapter over the same
|
|
27
|
+
*state-integrity* idea Operon uses for DNA-repair checkpoints — but the
|
|
28
|
+
public API uses LangGraph terms (``invariants``, ``thread_id``) and a
|
|
29
|
+
fresh theorem (``langgraph_state_integrity``) with clean evidence
|
|
30
|
+
fields, not the biology vocabulary of the upstream implementation.
|
|
31
|
+
|
|
32
|
+
Usage::
|
|
33
|
+
|
|
34
|
+
gate = IntegrityGate(invariants=[has_required_user, budget_not_exceeded])
|
|
35
|
+
graph.add_node("tool_call", gate.wrap(tool_call_fn))
|
|
36
|
+
graph.add_conditional_edges(
|
|
37
|
+
"tool_call",
|
|
38
|
+
gate.edge(forward="process", break_to="recover"),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
A certificate with theorem ``langgraph_state_integrity`` is emitted once
|
|
42
|
+
per thread on the first violation. ``cert.verify()`` replays the frozen
|
|
43
|
+
invariant-result evidence and returns (False, details) on replay.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import inspect
|
|
49
|
+
from collections.abc import Callable, Mapping
|
|
50
|
+
from dataclasses import dataclass, field
|
|
51
|
+
from types import MappingProxyType
|
|
52
|
+
from typing import Any
|
|
53
|
+
|
|
54
|
+
from operon_ai.core.certificate import Certificate, register_verify_fn
|
|
55
|
+
|
|
56
|
+
from ._common import EPHEMERAL_THREAD, is_async_callable, thread_id
|
|
57
|
+
|
|
58
|
+
_NodeIn = Any
|
|
59
|
+
_NodeOut = Any
|
|
60
|
+
NodeFn = Callable[..., _NodeOut]
|
|
61
|
+
Invariant = Callable[[Mapping[str, Any]], bool]
|
|
62
|
+
|
|
63
|
+
_THEOREM = "langgraph_state_integrity"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _verify_state_integrity(params: Mapping[str, Any]) -> tuple[bool, dict[str, Any]]:
|
|
67
|
+
"""Replay: all invariants recorded in ``invariant_results`` must hold."""
|
|
68
|
+
results = tuple(params.get("invariant_results", ()))
|
|
69
|
+
all_passed = all(passed for _, passed in results)
|
|
70
|
+
return all_passed, {
|
|
71
|
+
"invariant_results": tuple((name, bool(passed)) for name, passed in results),
|
|
72
|
+
"failed_invariants": tuple(name for name, passed in results if not passed),
|
|
73
|
+
"n": len(results),
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Register our theorem so Certificate.verify() can find the function when
|
|
78
|
+
# replaying a cert that was serialized and reloaded (Paper 5 §3 — preservation
|
|
79
|
+
# under compilation relies on the verify-function registry).
|
|
80
|
+
register_verify_fn(_THEOREM, _verify_state_integrity)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class _ThreadState:
|
|
85
|
+
"""Per-thread integrity state."""
|
|
86
|
+
|
|
87
|
+
is_violated: bool = False
|
|
88
|
+
certificates: list[Certificate] = field(default_factory=list)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class IntegrityGate:
|
|
92
|
+
"""Checks state invariants at node output boundaries.
|
|
93
|
+
|
|
94
|
+
Parameters
|
|
95
|
+
----------
|
|
96
|
+
invariants:
|
|
97
|
+
Iterable of callables ``(state) -> bool``. Each is run after every
|
|
98
|
+
wrapped-node invocation; a ``False`` return counts as a violation.
|
|
99
|
+
Callables are identified in certificates by their ``__name__``.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__(self, invariants: list[Invariant] | tuple[Invariant, ...]) -> None:
|
|
103
|
+
if not invariants:
|
|
104
|
+
raise ValueError("IntegrityGate requires at least one invariant")
|
|
105
|
+
self._invariants: tuple[Invariant, ...] = tuple(invariants)
|
|
106
|
+
self._threads: dict[str, _ThreadState] = {}
|
|
107
|
+
|
|
108
|
+
# -- public API ---------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def is_violated(self) -> bool:
|
|
112
|
+
"""True if the ephemeral (default-thread) state has been violated.
|
|
113
|
+
|
|
114
|
+
For per-thread checks inside a LangGraph run, use :meth:`edge` or
|
|
115
|
+
:meth:`is_violated_for`.
|
|
116
|
+
"""
|
|
117
|
+
state = self._threads.get(EPHEMERAL_THREAD)
|
|
118
|
+
return state is not None and state.is_violated
|
|
119
|
+
|
|
120
|
+
def is_violated_for(self, thread_id_: str) -> bool:
|
|
121
|
+
"""Whether a specific LangGraph thread has been violated."""
|
|
122
|
+
state = self._threads.get(thread_id_)
|
|
123
|
+
return state is not None and state.is_violated
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def certificates(self) -> list[Certificate]:
|
|
127
|
+
"""All integrity certificates emitted across all threads."""
|
|
128
|
+
return [c for s in self._threads.values() for c in s.certificates]
|
|
129
|
+
|
|
130
|
+
def reset(self, thread_id_: str | None = None) -> None:
|
|
131
|
+
"""Reset integrity state. ``None`` clears all threads."""
|
|
132
|
+
if thread_id_ is None:
|
|
133
|
+
self._threads.clear()
|
|
134
|
+
else:
|
|
135
|
+
self._threads.pop(thread_id_, None)
|
|
136
|
+
|
|
137
|
+
def wrap(self, fn: NodeFn) -> NodeFn:
|
|
138
|
+
"""Wrap a LangGraph node function with invariant checking.
|
|
139
|
+
|
|
140
|
+
Supports sync and async ``fn``; forwards ``*args, **kwargs`` so
|
|
141
|
+
LangGraph's ``config`` / ``runtime`` are preserved and the gate can
|
|
142
|
+
scope state per ``thread_id``.
|
|
143
|
+
"""
|
|
144
|
+
if is_async_callable(fn):
|
|
145
|
+
|
|
146
|
+
async def async_wrapped(state: _NodeIn, *args: Any, **kwargs: Any) -> _NodeOut:
|
|
147
|
+
output = await fn(state, *args, **kwargs)
|
|
148
|
+
self._check(output, thread_id(args, kwargs))
|
|
149
|
+
return output
|
|
150
|
+
|
|
151
|
+
return async_wrapped
|
|
152
|
+
|
|
153
|
+
def sync_wrapped(state: _NodeIn, *args: Any, **kwargs: Any) -> _NodeOut:
|
|
154
|
+
output = fn(state, *args, **kwargs)
|
|
155
|
+
if inspect.isawaitable(output):
|
|
156
|
+
# Close the coroutine before raising so we don't leak a
|
|
157
|
+
# "coroutine was never awaited" RuntimeWarning on top of the
|
|
158
|
+
# error we're already surfacing.
|
|
159
|
+
if inspect.iscoroutine(output):
|
|
160
|
+
output.close()
|
|
161
|
+
raise TypeError(
|
|
162
|
+
f"{fn!r} returned an awaitable but was not detected as async. "
|
|
163
|
+
"Declare it as ``async def`` or call it via the ainvoke path; "
|
|
164
|
+
"the sync gate wrapper cannot measure an unawaited coroutine."
|
|
165
|
+
)
|
|
166
|
+
self._check(output, thread_id(args, kwargs))
|
|
167
|
+
return output
|
|
168
|
+
|
|
169
|
+
return sync_wrapped
|
|
170
|
+
|
|
171
|
+
def edge(self, forward: str, break_to: str) -> Callable[..., str]:
|
|
172
|
+
"""Conditional-edge router: returns ``break_to`` after a violation."""
|
|
173
|
+
|
|
174
|
+
def route(_state: _NodeIn, *args: Any, **kwargs: Any) -> str:
|
|
175
|
+
tid = thread_id(args, kwargs)
|
|
176
|
+
state = self._threads.get(tid)
|
|
177
|
+
return break_to if state is not None and state.is_violated else forward
|
|
178
|
+
|
|
179
|
+
return route
|
|
180
|
+
|
|
181
|
+
# -- internals ----------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
def _thread_state(self, tid: str) -> _ThreadState:
|
|
184
|
+
state = self._threads.get(tid)
|
|
185
|
+
if state is None:
|
|
186
|
+
state = _ThreadState()
|
|
187
|
+
self._threads[tid] = state
|
|
188
|
+
return state
|
|
189
|
+
|
|
190
|
+
def _check(self, output: _NodeOut, tid: str) -> None:
|
|
191
|
+
state = self._thread_state(tid)
|
|
192
|
+
# Don't re-emit after the first violation — the cert carries the full
|
|
193
|
+
# evidence snapshot, subsequent calls would just duplicate it.
|
|
194
|
+
if state.is_violated:
|
|
195
|
+
return
|
|
196
|
+
|
|
197
|
+
results: list[tuple[str, bool]] = []
|
|
198
|
+
for inv in self._invariants:
|
|
199
|
+
try:
|
|
200
|
+
passed = bool(inv(output))
|
|
201
|
+
except Exception:
|
|
202
|
+
# A raising invariant is as much a violation as returning False.
|
|
203
|
+
passed = False
|
|
204
|
+
results.append((inv.__name__, passed))
|
|
205
|
+
|
|
206
|
+
all_passed = all(p for _, p in results)
|
|
207
|
+
if not all_passed:
|
|
208
|
+
state.is_violated = True
|
|
209
|
+
state.certificates.append(_make_certificate(results))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _make_certificate(results: list[tuple[str, bool]]) -> Certificate:
|
|
213
|
+
params = MappingProxyType(
|
|
214
|
+
{
|
|
215
|
+
"invariant_results": tuple(results),
|
|
216
|
+
"all_passed": False,
|
|
217
|
+
}
|
|
218
|
+
)
|
|
219
|
+
failed = [name for name, passed in results if not passed]
|
|
220
|
+
return Certificate(
|
|
221
|
+
theorem=_THEOREM,
|
|
222
|
+
parameters=params,
|
|
223
|
+
conclusion=(
|
|
224
|
+
f"State-integrity violation: {len(failed)} of {len(results)} "
|
|
225
|
+
f"invariants failed ({', '.join(failed)})."
|
|
226
|
+
),
|
|
227
|
+
source="operon_langgraph_gates.integrity",
|
|
228
|
+
_verify_fn=_verify_state_integrity,
|
|
229
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""StagnationGate — Bayesian stagnation detection for LangGraph nodes and edges.
|
|
2
|
+
|
|
3
|
+
Backed by Operon Paper 4 §4.3 "Epiplexity: Embedding Quality Determines
|
|
4
|
+
Outcome". With real sentence embeddings (all-MiniLM-L6-v2, N = 3 seeds
|
|
5
|
+
× 100 trials = 300), the biological two-signal monitor achieves:
|
|
6
|
+
|
|
7
|
+
- **convergence discrimination**: 0.960 accuracy (vs 0.401 naive baseline)
|
|
8
|
+
- **false-stagnation rejection**: 0.960 accuracy, 0.000 FP rate
|
|
9
|
+
(vs 0.020 accuracy, 0.980 FP rate for the naive baseline)
|
|
10
|
+
- **loop detection**: 0.631 accuracy (the naive detector scores 0.940
|
|
11
|
+
here, so the strength of this gate is in convergence/false-stagnation
|
|
12
|
+
rather than loop detection per se)
|
|
13
|
+
|
|
14
|
+
Authoritative source for these numbers (path relative to the Operon
|
|
15
|
+
repo root, commit ``339875e``):
|
|
16
|
+
``eval/results/benchmarks_real_embeddings/multi_model_summary.json`` at
|
|
17
|
+
``github.com/coredipper/operon``. A full citation record with verbatim
|
|
18
|
+
paper quotes and reproduction commands is at ``docs/paper-citations.md``.
|
|
19
|
+
|
|
20
|
+
In practice the gate is effective at breaking stuck loops (see
|
|
21
|
+
``tests/integration/test_loop_break.py``) because most real-world
|
|
22
|
+
stagnation presents as identical or near-identical outputs that trip the
|
|
23
|
+
epiplexic integral rather than the classifier's loop scenario. Using
|
|
24
|
+
``epiplexic_integral`` directly — rather than the monitor's status
|
|
25
|
+
classifier — gives the gate its stable detection signal.
|
|
26
|
+
|
|
27
|
+
This module is a thin LangGraph-friendly wrapper over
|
|
28
|
+
``operon_ai.health.epiplexity.EpiplexityMonitor``. It adds:
|
|
29
|
+
|
|
30
|
+
- A text-extraction step (LangGraph node outputs are typically dicts, not
|
|
31
|
+
text).
|
|
32
|
+
- A zero-dep default embedder (``NGramEmbedder``) so the gate works
|
|
33
|
+
without a neural model install. Pass ``embedder=...`` for a real one;
|
|
34
|
+
the Paper 4 numbers above were measured with ``all-MiniLM-L6-v2``.
|
|
35
|
+
- Per-thread state scoping keyed on
|
|
36
|
+
``config["configurable"]["thread_id"]`` so reusing a compiled graph
|
|
37
|
+
across invocations or running concurrent threads doesn't leak state.
|
|
38
|
+
- Async node support via ``_common.is_async_callable`` (also catches
|
|
39
|
+
classes with ``async def __call__``).
|
|
40
|
+
- ``behavioral_stability_windowed`` certificate emission on first detection
|
|
41
|
+
per thread.
|
|
42
|
+
|
|
43
|
+
Usage::
|
|
44
|
+
|
|
45
|
+
gate = StagnationGate(threshold=0.2, critical_duration=3)
|
|
46
|
+
graph.add_node("think", gate.wrap(think_fn))
|
|
47
|
+
graph.add_conditional_edges("think", gate.edge(forward="answer", break_to="escalate"))
|
|
48
|
+
# after graph.invoke(...)
|
|
49
|
+
if gate.certificates:
|
|
50
|
+
# stagnation was detected during the run
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
from __future__ import annotations
|
|
54
|
+
|
|
55
|
+
import inspect
|
|
56
|
+
from collections.abc import Callable
|
|
57
|
+
from dataclasses import dataclass, field
|
|
58
|
+
from types import MappingProxyType
|
|
59
|
+
from typing import Any
|
|
60
|
+
|
|
61
|
+
from operon_ai.core.certificate import Certificate
|
|
62
|
+
from operon_ai.health.epiplexity import EmbeddingProvider, EpiplexityMonitor
|
|
63
|
+
|
|
64
|
+
from ._common import EPHEMERAL_THREAD, is_async_callable, thread_id
|
|
65
|
+
from .embedders import NGramEmbedder
|
|
66
|
+
|
|
67
|
+
# LangGraph node functions consume and return arbitrary mappings (TypedDict,
|
|
68
|
+
# dict, or dataclass). We keep the typing loose on purpose — the gate does not
|
|
69
|
+
# care about the schema, only the extracted text.
|
|
70
|
+
_NodeIn = Any
|
|
71
|
+
_NodeOut = Any
|
|
72
|
+
NodeFn = Callable[..., _NodeOut]
|
|
73
|
+
TextExtractor = Callable[[_NodeOut], str]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class _ThreadState:
|
|
78
|
+
"""Per-thread state holder — one per LangGraph ``thread_id``."""
|
|
79
|
+
|
|
80
|
+
monitor: EpiplexityMonitor
|
|
81
|
+
severities: list[float] = field(default_factory=list)
|
|
82
|
+
# ``integrals[i]`` is the ``EpiplexityResult.epiplexic_integral`` the
|
|
83
|
+
# monitor produced on turn ``i``. This is the exact signal the gate's
|
|
84
|
+
# detection logic routes on — surfacing it lets UI clients (e.g. the
|
|
85
|
+
# demo Space) render the same number the gate acted on, rather than
|
|
86
|
+
# re-deriving something that can drift (e.g. ``1 - mean(severity)``
|
|
87
|
+
# does not match the α-mixed formula once perplexity is in play).
|
|
88
|
+
integrals: list[float] = field(default_factory=list)
|
|
89
|
+
certificates: list[Certificate] = field(default_factory=list)
|
|
90
|
+
is_stagnant: bool = False
|
|
91
|
+
low_integral_streak: int = 0
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class StagnationGate:
|
|
95
|
+
"""Detects stagnation on a per-node basis and routes conditional edges.
|
|
96
|
+
|
|
97
|
+
Parameters mirror :class:`operon_ai.health.epiplexity.EpiplexityMonitor`
|
|
98
|
+
but with LangGraph-friendly defaults:
|
|
99
|
+
|
|
100
|
+
- ``threshold``: epiplexic integral below this counts toward stagnation.
|
|
101
|
+
- ``window_size``: sliding-window size for the epiplexity calculation.
|
|
102
|
+
- ``critical_duration``: consecutive sub-threshold readings required.
|
|
103
|
+
- ``embedder``: any object with ``embed(text) -> list[float]``. Defaults to
|
|
104
|
+
:class:`NGramEmbedder` — zero-dependency, deterministic, good enough to
|
|
105
|
+
catch verbatim-repeat pathologies.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
def __init__(
|
|
109
|
+
self,
|
|
110
|
+
threshold: float = 0.2,
|
|
111
|
+
critical_duration: int = 2,
|
|
112
|
+
window_size: int = 10,
|
|
113
|
+
*,
|
|
114
|
+
alpha: float = 0.5,
|
|
115
|
+
embedder: EmbeddingProvider | None = None,
|
|
116
|
+
) -> None:
|
|
117
|
+
self._threshold = threshold
|
|
118
|
+
self._critical_duration = critical_duration
|
|
119
|
+
self._window_size = window_size
|
|
120
|
+
self._alpha = alpha
|
|
121
|
+
self._embedder: EmbeddingProvider = embedder or NGramEmbedder()
|
|
122
|
+
self._threads: dict[str, _ThreadState] = {}
|
|
123
|
+
|
|
124
|
+
# -- public API ---------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def is_stagnant(self) -> bool:
|
|
128
|
+
"""Whether the ephemeral (default-thread) measurement is stagnant.
|
|
129
|
+
|
|
130
|
+
For per-thread checks inside a LangGraph run, use :meth:`edge` (which
|
|
131
|
+
extracts thread_id from config automatically) or
|
|
132
|
+
:meth:`is_stagnant_for`.
|
|
133
|
+
"""
|
|
134
|
+
state = self._threads.get(EPHEMERAL_THREAD)
|
|
135
|
+
return state is not None and state.is_stagnant
|
|
136
|
+
|
|
137
|
+
def is_stagnant_for(self, thread_id_: str) -> bool:
|
|
138
|
+
"""Whether a specific LangGraph thread is currently stagnant."""
|
|
139
|
+
state = self._threads.get(thread_id_)
|
|
140
|
+
return state is not None and state.is_stagnant
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def certificates(self) -> list[Certificate]:
|
|
144
|
+
"""All certificates emitted across all threads during this gate's life."""
|
|
145
|
+
return [c for s in self._threads.values() for c in s.certificates]
|
|
146
|
+
|
|
147
|
+
def integrals_for(self, thread_id_: str | None = None) -> list[float]:
|
|
148
|
+
"""Per-turn ``epiplexic_integral`` values observed on a thread.
|
|
149
|
+
|
|
150
|
+
Returns the exact integral sequence the detection logic routed on,
|
|
151
|
+
so UI clients (e.g. the demo Space) can render the same number the
|
|
152
|
+
gate acted on rather than re-deriving one that may not match the
|
|
153
|
+
monitor's α-mixed formula.
|
|
154
|
+
|
|
155
|
+
``thread_id_ is None`` returns the ephemeral thread's history —
|
|
156
|
+
matching :attr:`is_stagnant` semantics for single-thread callers.
|
|
157
|
+
"""
|
|
158
|
+
key = EPHEMERAL_THREAD if thread_id_ is None else thread_id_
|
|
159
|
+
state = self._threads.get(key)
|
|
160
|
+
return list(state.integrals) if state is not None else []
|
|
161
|
+
|
|
162
|
+
def reset(self, thread_id: str | None = None) -> None:
|
|
163
|
+
"""Reset stagnation state. ``None`` clears all threads."""
|
|
164
|
+
if thread_id is None:
|
|
165
|
+
self._threads.clear()
|
|
166
|
+
else:
|
|
167
|
+
self._threads.pop(thread_id, None)
|
|
168
|
+
|
|
169
|
+
def wrap(self, fn: NodeFn, *, text_extractor: TextExtractor | None = None) -> NodeFn:
|
|
170
|
+
"""Wrap a LangGraph node function with stagnation measurement.
|
|
171
|
+
|
|
172
|
+
Supports both sync and async ``fn``. Forwards all positional and
|
|
173
|
+
keyword arguments to ``fn`` so LangGraph's ``config`` / ``runtime``
|
|
174
|
+
are preserved. Uses the same arg list to scope state per thread.
|
|
175
|
+
"""
|
|
176
|
+
extract = text_extractor or (lambda out: str(out))
|
|
177
|
+
|
|
178
|
+
if is_async_callable(fn):
|
|
179
|
+
|
|
180
|
+
async def async_wrapped(state: _NodeIn, *args: Any, **kwargs: Any) -> _NodeOut:
|
|
181
|
+
output = await fn(state, *args, **kwargs)
|
|
182
|
+
self._observe(extract(output), thread_id(args, kwargs))
|
|
183
|
+
return output
|
|
184
|
+
|
|
185
|
+
return async_wrapped
|
|
186
|
+
|
|
187
|
+
def sync_wrapped(state: _NodeIn, *args: Any, **kwargs: Any) -> _NodeOut:
|
|
188
|
+
output = fn(state, *args, **kwargs)
|
|
189
|
+
if inspect.isawaitable(output):
|
|
190
|
+
# Close the coroutine before raising so we don't leak a
|
|
191
|
+
# "coroutine was never awaited" RuntimeWarning on top of the
|
|
192
|
+
# error we're already surfacing.
|
|
193
|
+
if inspect.iscoroutine(output):
|
|
194
|
+
output.close()
|
|
195
|
+
raise TypeError(
|
|
196
|
+
f"{fn!r} returned an awaitable but was not detected as async. "
|
|
197
|
+
"Declare it as ``async def`` or call it via the ainvoke path; "
|
|
198
|
+
"the sync gate wrapper cannot measure an unawaited coroutine."
|
|
199
|
+
)
|
|
200
|
+
self._observe(extract(output), thread_id(args, kwargs))
|
|
201
|
+
return output
|
|
202
|
+
|
|
203
|
+
return sync_wrapped
|
|
204
|
+
|
|
205
|
+
def edge(self, forward: str, break_to: str) -> Callable[..., str]:
|
|
206
|
+
"""Conditional-edge router: returns ``break_to`` when stagnant."""
|
|
207
|
+
|
|
208
|
+
def route(_state: _NodeIn, *args: Any, **kwargs: Any) -> str:
|
|
209
|
+
tid = thread_id(args, kwargs)
|
|
210
|
+
state = self._threads.get(tid)
|
|
211
|
+
return break_to if state is not None and state.is_stagnant else forward
|
|
212
|
+
|
|
213
|
+
return route
|
|
214
|
+
|
|
215
|
+
# -- internals ----------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
def _thread_state(self, thread_id: str) -> _ThreadState:
|
|
218
|
+
state = self._threads.get(thread_id)
|
|
219
|
+
if state is None:
|
|
220
|
+
state = _ThreadState(
|
|
221
|
+
monitor=EpiplexityMonitor(
|
|
222
|
+
embedding_provider=self._embedder,
|
|
223
|
+
alpha=self._alpha,
|
|
224
|
+
window_size=self._window_size,
|
|
225
|
+
threshold=self._threshold,
|
|
226
|
+
critical_duration=self._critical_duration,
|
|
227
|
+
),
|
|
228
|
+
)
|
|
229
|
+
self._threads[thread_id] = state
|
|
230
|
+
return state
|
|
231
|
+
|
|
232
|
+
def _observe(self, text: str, thread_id: str) -> None:
|
|
233
|
+
state = self._thread_state(thread_id)
|
|
234
|
+
result = state.monitor.measure(text)
|
|
235
|
+
|
|
236
|
+
# severity = 1 - epiplexity so "mean < threshold" means healthy; large
|
|
237
|
+
# values flag stagnation pathology (matches the operon_ai severity-domain
|
|
238
|
+
# convention shared by both ``behavioral_stability`` and the windowed
|
|
239
|
+
# variant ``behavioral_stability_windowed`` this gate emits).
|
|
240
|
+
severity = max(0.0, min(1.0, 1.0 - float(result.epiplexity)))
|
|
241
|
+
state.severities.append(severity)
|
|
242
|
+
# Record the exact integral the detection logic routes on, so
|
|
243
|
+
# callers rendering the gate's decision see the same number.
|
|
244
|
+
integral = float(result.epiplexic_integral)
|
|
245
|
+
state.integrals.append(integral)
|
|
246
|
+
|
|
247
|
+
# Detect on sustained low epiplexic_integral rather than the monitor's
|
|
248
|
+
# built-in status classifier, which depends on a perplexity
|
|
249
|
+
# approximation that varies with text shape and can mask stagnation
|
|
250
|
+
# as CONVERGING. The integral is a direct, stable signal.
|
|
251
|
+
if integral < self._threshold:
|
|
252
|
+
state.low_integral_streak += 1
|
|
253
|
+
else:
|
|
254
|
+
state.low_integral_streak = 0
|
|
255
|
+
|
|
256
|
+
was_stagnant = state.is_stagnant
|
|
257
|
+
should_be_stagnant = state.low_integral_streak >= self._critical_duration
|
|
258
|
+
|
|
259
|
+
if should_be_stagnant and not was_stagnant:
|
|
260
|
+
# Emit the certificate *before* flipping ``state.is_stagnant`` so a
|
|
261
|
+
# failure (e.g. unregistered theorem) leaves the thread in its
|
|
262
|
+
# prior non-stagnant state and a later call can retry emission
|
|
263
|
+
# once the underlying problem is corrected. If we flipped state
|
|
264
|
+
# first, the ``was_stagnant/not was_stagnant`` guard above would
|
|
265
|
+
# suppress retry and the thread would be permanently stuck in
|
|
266
|
+
# ``is_stagnant=True`` without a corresponding certificate.
|
|
267
|
+
violating_integrals = state.integrals[-self._critical_duration :]
|
|
268
|
+
window_severity_means = tuple(1.0 - i for i in violating_integrals)
|
|
269
|
+
cert = _emit_certificate(
|
|
270
|
+
window_severity_means=window_severity_means,
|
|
271
|
+
threshold=1.0 - self._threshold,
|
|
272
|
+
detection_index=len(state.severities),
|
|
273
|
+
source="operon_langgraph_gates.stagnation",
|
|
274
|
+
)
|
|
275
|
+
state.certificates.append(cert)
|
|
276
|
+
state.is_stagnant = should_be_stagnant
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# A theorem name distinct from the shared ``behavioral_stability`` (which is
|
|
280
|
+
# flat-mean-based). Upstream ``operon_ai.core.certificate`` registers this
|
|
281
|
+
# theorem in its theorem registry, so ``Certificate.from_theorem`` resolves
|
|
282
|
+
# the correct verifier without this package binding to any upstream symbol
|
|
283
|
+
# beyond the public ``Certificate`` class itself.
|
|
284
|
+
_WINDOWED_THEOREM = "behavioral_stability_windowed"
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _emit_certificate(
|
|
288
|
+
*,
|
|
289
|
+
window_severity_means: tuple[float, ...],
|
|
290
|
+
threshold: float,
|
|
291
|
+
detection_index: int,
|
|
292
|
+
source: str,
|
|
293
|
+
) -> Certificate:
|
|
294
|
+
"""Emit a ``behavioral_stability_windowed`` certificate backed by per-window means.
|
|
295
|
+
|
|
296
|
+
``signal_values`` is the sequence of mean severities over each violating
|
|
297
|
+
rolling window — one value per window, ``critical_duration`` values total.
|
|
298
|
+
The replay check is ``max(signal_values) <= threshold``, which mirrors
|
|
299
|
+
detection's "every one of the last ``critical_duration`` rolling windows
|
|
300
|
+
was violating" predicate.
|
|
301
|
+
|
|
302
|
+
``threshold`` is the stability threshold in the severity domain (the
|
|
303
|
+
complement of the detection threshold, ``1 - τ_detect``). This makes the
|
|
304
|
+
verifier agree with detection at every τ in [0, 1] — the severity-domain
|
|
305
|
+
and epiplexity-domain predicates are equivalent only when the threshold
|
|
306
|
+
is translated.
|
|
307
|
+
|
|
308
|
+
``detection_index`` is the total number of evaluations the critic had
|
|
309
|
+
performed when stagnation was detected (``len(state.severities)`` at emit
|
|
310
|
+
time). Used only in the human-readable conclusion text so "after N
|
|
311
|
+
measurements" remains accurate after a long healthy prefix — the
|
|
312
|
+
evidence slice is narrower than total history.
|
|
313
|
+
|
|
314
|
+
Raises ``ValueError`` if ``window_severity_means`` is empty: a stagnation
|
|
315
|
+
certificate without evidence is a contradiction in terms, and the Pydantic
|
|
316
|
+
``critical_duration >= 1`` guarantee makes this unreachable from the gate.
|
|
317
|
+
"""
|
|
318
|
+
if not window_severity_means:
|
|
319
|
+
raise ValueError(
|
|
320
|
+
"window_severity_means must be non-empty; "
|
|
321
|
+
"a stagnation certificate requires at least one violating window"
|
|
322
|
+
)
|
|
323
|
+
return Certificate.from_theorem(
|
|
324
|
+
theorem=_WINDOWED_THEOREM,
|
|
325
|
+
parameters=MappingProxyType(
|
|
326
|
+
{
|
|
327
|
+
"signal_values": tuple(window_severity_means),
|
|
328
|
+
"threshold": float(threshold),
|
|
329
|
+
}
|
|
330
|
+
),
|
|
331
|
+
conclusion=(
|
|
332
|
+
f"Stagnation detected after {detection_index} measurements; "
|
|
333
|
+
f"{len(window_severity_means)} violating rolling windows "
|
|
334
|
+
f"captured for replay verification."
|
|
335
|
+
),
|
|
336
|
+
source=source,
|
|
337
|
+
)
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: operon-langgraph-gates
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reliability primitives for LangGraph — certified stagnation and integrity gates, backed by the Operon categorical framework.
|
|
5
|
+
Project-URL: Homepage, https://github.com/coredipper/operon-langgraph-gates
|
|
6
|
+
Project-URL: Documentation, https://banu.be/operon/
|
|
7
|
+
Project-URL: Issues, https://github.com/coredipper/operon-langgraph-gates/issues
|
|
8
|
+
Project-URL: Paper 4, https://github.com/coredipper/operon/blob/main/article/paper4/main.pdf
|
|
9
|
+
Project-URL: Paper 5, https://github.com/coredipper/operon/blob/main/article/paper5/main.pdf
|
|
10
|
+
Author-email: Bogdan Banu <bogdan@banu.be>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: agents,certificates,integrity,langgraph,llm,reliability,stagnation
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Requires-Dist: langgraph<2.0,>=1.0.0
|
|
24
|
+
Requires-Dist: operon-ai<0.40,>=0.36.1
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: ipykernel>=6.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: jupyter>=1.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: mypy>=1.11; extra == 'dev'
|
|
29
|
+
Requires-Dist: nbconvert>=7.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: nbformat>=5.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
33
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# operon-langgraph-gates
|
|
37
|
+
|
|
38
|
+
> **In-graph** reliability gates for LangGraph — drop-in, cert-emitting.
|
|
39
|
+
|
|
40
|
+
[LangGraph issue #6731](https://github.com/langchain-ai/langgraph/issues/6731) — *"agent infinite-loops until recursion limit, burns tokens invisibly"* — was closed as **NOT_PLANNED**. LangChain's answer: *"use tool-call limits in middleware."*
|
|
41
|
+
|
|
42
|
+
This package ships that missing native gate, plus a second one for checkpointer-write integrity. Two primitives. No framework adoption. ~10-line diff on an existing `StateGraph`.
|
|
43
|
+
|
|
44
|
+
Both gates run **inside** the graph: they route conditional edges and can short-circuit the next step. This is a deliberate contrast to post-hoc observability tools — an observer tells you an agent looped after the fact; a gate stops the loop mid-run and emits a replayable certificate of what fired it.
|
|
45
|
+
|
|
46
|
+
**At a glance:**
|
|
47
|
+
|
|
48
|
+
- `StagnationGate` — Bayesian stagnation detection (Paper 4 §4.3, 0.960 on convergence / false-stagnation scenarios) with per-thread state, async + class-callable aware. [See it live.](https://huggingface.co/spaces/coredipper/operon-stagnation-gate)
|
|
49
|
+
- `IntegrityGate` — user-defined invariants checked on every wrapped node's output; violations emit a `langgraph_state_integrity` certificate with replayable evidence. Detection-and-certification only; does not repair state.
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install operon-langgraph-gates
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Requires `operon-ai>=0.36.1,<0.40` and `langgraph>=1.0,<2.0`.
|
|
58
|
+
|
|
59
|
+
## Quickstart
|
|
60
|
+
|
|
61
|
+
### Break infinite loops (`StagnationGate`)
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from langgraph.graph import StateGraph
|
|
65
|
+
from operon_langgraph_gates import StagnationGate
|
|
66
|
+
|
|
67
|
+
graph = StateGraph(State)
|
|
68
|
+
gate = StagnationGate(threshold=0.2, critical_duration=3)
|
|
69
|
+
graph.add_node("think", gate.wrap(think_fn))
|
|
70
|
+
|
|
71
|
+
# Or attach to a conditional edge (route loop-detected runs elsewhere)
|
|
72
|
+
graph.add_conditional_edges(
|
|
73
|
+
"think",
|
|
74
|
+
gate.edge(forward="answer", break_to="escalate"),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# All certificates the gate has emitted (across all threads)
|
|
78
|
+
certs = gate.certificates
|
|
79
|
+
# For thread-scoped views use gate.is_stagnant_for(thread_id_) /
|
|
80
|
+
# gate.integrals_for(thread_id_). The gate falls back to an internal
|
|
81
|
+
# ephemeral-thread id (__ephemeral__) whenever no thread_id can be
|
|
82
|
+
# extracted from the LangGraph config/runtime at the wrapped node
|
|
83
|
+
# (e.g. no config argument, or a config with no configurable.thread_id);
|
|
84
|
+
# this id is an implementation detail, not part of the public API.
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Backed by [Paper 4 §4.3](https://github.com/coredipper/operon/blob/main/article/paper4/main.pdf): convergence/false-stagnation accuracy **0.960** with real sentence embeddings (all-MiniLM-L6-v2, N = 300 trials). See [`docs/paper-citations.md`](./docs/paper-citations.md) for the full citation record, including the loop-detection caveat and a pointer to the archived benchmark data.
|
|
88
|
+
|
|
89
|
+
### Catch state drift (`IntegrityGate`)
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from langgraph.graph import StateGraph
|
|
93
|
+
from operon_langgraph_gates import IntegrityGate
|
|
94
|
+
|
|
95
|
+
gate = IntegrityGate(invariants=[has_required_user, budget_not_exceeded])
|
|
96
|
+
|
|
97
|
+
graph = StateGraph(State)
|
|
98
|
+
graph.add_node("tool_call", gate.wrap(tool_call_fn))
|
|
99
|
+
|
|
100
|
+
# Route runs that violated an invariant to a recovery node
|
|
101
|
+
graph.add_conditional_edges(
|
|
102
|
+
"tool_call",
|
|
103
|
+
gate.edge(forward="process", break_to="recover"),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# Certificates (one per thread, on first violation) are on the gate
|
|
107
|
+
certs = gate.certificates
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Backed by [Paper 4 §4, Table 3](https://github.com/coredipper/operon/blob/main/article/paper4/main.pdf): *in the paper's setup*, the FULL variant (with `DNARepair`) achieves 100% detection and 100% repair of injected state corruption, vs 0%/0% for RAW and GUARDED. **This package is detection-and-certification only — it does not repair state.** It reformulates the idea as a LangGraph-native invariant gate. [Paper 5 §3](https://github.com/coredipper/operon/blob/main/article/paper5/main.pdf) establishes the preservation-under-compilation framework that the gate's certificate follows. See [`docs/paper-citations.md`](./docs/paper-citations.md) for verbatim quotes and the honest caveat.
|
|
111
|
+
|
|
112
|
+
## Theoretical basis
|
|
113
|
+
|
|
114
|
+
Both gates are a discrete-state port of the rolling-past reliability loop that has been standard in robotics state estimation since [Kaess et al. 2012](https://dspace.mit.edu/handle/1721.1/71582) (iSAM2) and is formalised in [Dellaert & Kaess 2017](https://www.cs.cmu.edu/~kaess/pub/Dellaert17fnt.pdf) (*Factor Graphs for Robot Perception*). A recent [GTSAM blog post](https://gtsam.org/2026/04/21/factor-graphs-and-world-models.html) frames that loop — **STAG**: Sense-Think-Act with Graphs — as a concrete structured instance of an energy-based world model.
|
|
115
|
+
|
|
116
|
+
### Scope (normative for this package)
|
|
117
|
+
|
|
118
|
+
What this repository actually commits to under the factor-graph framing:
|
|
119
|
+
|
|
120
|
+
- **Binding**: `StagnationGate` replay equivalence — a `behavioral_stability_windowed` certificate emitted by the gate must verify identically offline when passed its own parameters. The emitted certificate parameters are in the **severity domain**, not the integral domain: `signal_values = tuple(1.0 - i for i in state.integrals[-critical_duration:])` and `threshold = 1.0 - detection_threshold` (see `src/operon_langgraph_gates/stagnation.py:266-269`), which keeps the replay predicate aligned with `operon_ai`'s shared `behavioral_stability_windowed` verifier semantics (`max(signal_values) ≤ threshold`).
|
|
121
|
+
- **Binding**: `IntegrityGate` frozen-result replay — a `langgraph_state_integrity` certificate's parameters are exactly `invariant_results: tuple[(str, bool), ...]` and `all_passed: False` (see `_make_certificate` in `src/operon_langgraph_gates/integrity.py`); replay must reproduce the same boolean vector. Node output is **not** captured in the certificate payload. Two notes on the `name` field in `(name, passed)`: (i) names are **descriptive labels only**, derived from `inv.__name__` at emit time; replay never resolves them back to live invariants, so lambdas (`<lambda>`) and duplicate names do not break replay correctness — they just collapse to lossy labels in logs and UIs. Treat them as descriptive, not as stable identifiers. (ii) exceptions raised inside an invariant are coerced to `False`, and neither the certificate nor the replay surfaces the offending state or the exception detail.
|
|
122
|
+
- **Binding**: A2A round-trip equivalence — under the pinned `operon-ai` range in `pyproject.toml` (`>=0.36.1,<0.40`), a certificate emitted by either gate must round-trip through `operon_ai.convergence.a2a_certificate.{certificate_to_a2a_part, certificate_from_a2a_part}` such that `Certificate.verify()` returns the same result and the parameter dict is preserved exactly. Enforced by `tests/test_a2a_round_trip.py`. Tightening the upper bound on the `operon-ai` pin requires re-running this test against the new range.
|
|
123
|
+
- **Non-binding**: no cross-agent inference or factor-graph joining is implemented in this package. Nothing below promises any behaviour beyond what is replayable from the emitted certificates.
|
|
124
|
+
- **Non-binding**: the factor-graph vocabulary is explanatory. Any analogy mapping in the next subsection can be re-tagged as *analogy only* without breaking any contract in this repository.
|
|
125
|
+
|
|
126
|
+
### Mapping (explanatory, not normative)
|
|
127
|
+
|
|
128
|
+
- `StagnationGate` is the discrete-state analogue of a **past-graph fixed-lag smoother**. Concretely: on each turn, `EpiplexityMonitor.measure()` emits a scalar `epiplexic_integral` that is stored in `state.integrals`; the detector fires when the last `critical_duration` integrals fall below `detection_threshold` (`src/operon_langgraph_gates/stagnation.py:250-256`). At emission, that integral slice is converted to the severity domain via `1.0 - integral` and shipped in the certificate as `signal_values`, with the threshold also translated to `1.0 - detection_threshold` (`stagnation.py:266-269`). The offline replay predicate `max(signal_values) ≤ threshold` is therefore a translated, not raw, replay of the gate's decision — the translation is part of the replay contract and is required to match `operon_ai`'s shared `behavioral_stability_windowed` verifier semantics.
|
|
129
|
+
- `IntegrityGate` is a **dynamics-residual check**: user-defined invariants play the role of the dynamics model's consistency factors, and a violation at a wrapped node is a positive residual routed onto a conditional edge. The certificate is the replayable record of that residual — specifically the `(name, passed)` vector over invariants and the `all_passed` flag, as emitted by `_make_certificate`. Capturing the offending node output is a deliberate non-goal in the current schema (privacy/redaction would need a separate design); the cert fixes *which* invariants failed, not *what* triggered them.
|
|
130
|
+
|
|
131
|
+
### Ecosystem note (A2A round-trip is enforced)
|
|
132
|
+
|
|
133
|
+
Operon's A2A certificate codec (in the [operon repo](https://github.com/coredipper/operon), `operon_ai/convergence/a2a_certificate.py`) transports certificates as `DataPart` payloads and handles graceful degradation for unknown theorems. Under the STAG framing that is a transport-layer analogy of factor joining along shared theorem variables, but the codec does *not* maintain an internal factor graph or perform joint inference.
|
|
134
|
+
|
|
135
|
+
The `Certificate` objects this package emits are guaranteed to round-trip through that codec under the pinned `operon-ai` range in `pyproject.toml` (`>=0.36.1,<0.40`). The guarantee is enforced by `tests/test_a2a_round_trip.py`, which drives both gates to emission, encodes their certificates via `certificate_to_a2a_part`, decodes via `certificate_from_a2a_part`, and asserts that `Certificate.verify()` returns the same result and that `parameters` are preserved exactly. The same test verifies that `safe_certificate_from_a2a_part` recovers the cert (not `None`) for both gate-emitted theorem names — i.e., the round-trip works even when the receiver opts into graceful-degradation mode.
|
|
136
|
+
|
|
137
|
+
This was previously informational; promoted to a binding claim in `0.1.0` per the maintainer checklist. If the upper bound on the `operon-ai` pin is widened, the round-trip test must be re-run against the new range before merging.
|
|
138
|
+
|
|
139
|
+
### Follow-up checklist for maintainers
|
|
140
|
+
|
|
141
|
+
If the code changes, the bindings in *Scope (normative for this package)* above must be re-verified. Checklist items are keyed to stable symbols, not line numbers, so they survive ordinary refactors:
|
|
142
|
+
|
|
143
|
+
1. `StagnationGate` — if *either* `_emit_certificate` (the integral-to-severity translation and emitted parameter names `signal_values`, `threshold`) *or* `_observe` (the detection predicate `integral < threshold`, the streak counting, and the `critical_duration` slice at emission) changes, update the *StagnationGate replay equivalence* scope entry and add or update an end-to-end test that exercises both the detection path and the replay predicate so detection changes cannot silently drift past the checklist.
|
|
144
|
+
2. `IntegrityGate` — if `_make_certificate` (in `integrity.py`) changes the shape of `invariant_results` or `all_passed`, update the *IntegrityGate frozen-result replay* scope entry; and in the same change, update or add tests that cover: (a) label derivation from `inv.__name__` including the lambda / duplicate-name cases (treated as lossy labels, not identifiers); (b) exception-coerced-to-`False` behaviour; (c) serialization round-trip of `(name, passed)` pairs. If callers ever start round-tripping `name` back to a callable (e.g. an executable replay), introduce an explicit caller-supplied identifier and upgrade the binding before merging.
|
|
145
|
+
3. A2A — the round-trip is binding under the current pinned `operon-ai` range (`>=0.36.1,<0.40`) and is enforced by `tests/test_a2a_round_trip.py`. If `certificate_to_a2a_part` / `certificate_from_a2a_part` change shape upstream, re-run the test against the new range; if the upper bound on the pin is widened, the test must be re-run against the new range before merging. If the `safe_certificate_from_a2a_part` graceful-degradation behaviour is removed upstream, the corresponding sub-test must be removed in lockstep with the pin update.
|
|
146
|
+
4. Theorem-name changes are **repo-wide**, not README-only. If either `behavioral_stability_windowed` or `langgraph_state_integrity` is renamed in `operon-ai`, the following surfaces must all change in lockstep: this README (the quickstart text and the *Certificate theorem name and verification* section), `src/operon_langgraph_gates/__init__.py` and `stagnation.py` / `integrity.py` (emission sites), `scripts/build_examples.py` (currently references `langgraph_state_integrity` at 3 places), and `huggingface/space-stagnation-gate/app.py` (currently still references the pre-0.36 `behavioral_stability` name — known drift, fix when the theorem-rename PR next touches it). Prefer a single source of truth (e.g. a `_THEOREM` constant re-exported from the package) to prevent this list from growing.
|
|
147
|
+
|
|
148
|
+
### Honest scope
|
|
149
|
+
|
|
150
|
+
This is a porting exercise, not new math. What is new is running the loop over symbolic LLM-agent state with a fixed verifier instead of gradient-based smoothing; see [paper 6 appendix §8](https://github.com/coredipper/operon/blob/main/article/paper6/sections/08-factor-graphs.tex) for the full term-by-term mapping, the worked example, and an explicit record of where the analogy stops. The scope-discipline rule inherited from the framing: **factors and topology are fixed; only the theorem set grows** — no learned factors, no horizon > 1 planning graphs.
|
|
151
|
+
|
|
152
|
+
## Certificate theorem name and verification
|
|
153
|
+
|
|
154
|
+
`StagnationGate` emits certificates with theorem name `behavioral_stability_windowed` (not the core's shared `behavioral_stability`). The two differ in how they verify:
|
|
155
|
+
|
|
156
|
+
- `behavioral_stability` (shared core): `mean(severities) < threshold`. Loses the per-window structure rolling-integral detection operates on.
|
|
157
|
+
- `behavioral_stability_windowed` (shared core, since operon-ai 0.36.0): `max(per_window_severity_means) <= stability_threshold`. Mirrors detection exactly.
|
|
158
|
+
|
|
159
|
+
Both verifiers are registered in `operon_ai.core.certificate._THEOREM_FN_PATHS`, so deserialized certificates resolve through `_resolve_verify_fn` without this package needing to be imported. Any consumer with `operon-ai>=0.36.0` can round-trip a `behavioral_stability_windowed` certificate correctly.
|
|
160
|
+
|
|
161
|
+
### Breaking change from pre-alpha prototypes
|
|
162
|
+
|
|
163
|
+
Earlier builds emitted certificates with theorem name `behavioral_stability`, bound to a locally-attached `_verify_fn`. That shape was semantically wrong — the shared verifier is flat-mean-based, so any cert round-tripped through serialization would silently revert to the wrong replay logic. Consumers that key on `certificate.theorem == "behavioral_stability"` must update to `"behavioral_stability_windowed"`. No migration path; alpha.
|
|
164
|
+
|
|
165
|
+
## Try it — HuggingFace Space
|
|
166
|
+
|
|
167
|
+
[**Operon StagnationGate Demo**](https://huggingface.co/spaces/coredipper/operon-stagnation-gate) — interactive page: pick a preset (identical, diverse, noisy, slow drift), tune the gate parameters, watch `is_stagnant` flip and the certificate appear. Deterministic text trajectories — no LLM calls.
|
|
168
|
+
|
|
169
|
+
## Examples
|
|
170
|
+
|
|
171
|
+
- [`examples/01_stagnation_breaks_loop.ipynb`](./examples/01_stagnation_breaks_loop.ipynb) — reproduces issue #6731 pathology, then fixes it with a ten-line diff.
|
|
172
|
+
- [`examples/02_integrity_catches_drift.ipynb`](./examples/02_integrity_catches_drift.ipynb) — a three-node graph silently corrupts state; `IntegrityGate` catches it with replayable evidence.
|
|
173
|
+
|
|
174
|
+
## Public API
|
|
175
|
+
|
|
176
|
+
The committed surface for `0.1.x` is small and explicit:
|
|
177
|
+
|
|
178
|
+
- **Classes:** `StagnationGate`, `IntegrityGate`.
|
|
179
|
+
- **Methods on each gate:** `wrap(node_fn)`, `edge(forward, break_to)`, `certificates`, `reset()`. `StagnationGate` additionally exposes the global property `is_stagnant`, the per-thread methods `is_stagnant_for(thread_id)` and `integrals_for(thread_id)`. `IntegrityGate` exposes the global property `is_violated` and the per-thread method `is_violated_for(thread_id)`.
|
|
180
|
+
- **Theorem-name constants:** `STAGNATION_THEOREM` (`"behavioral_stability_windowed"`), `INTEGRITY_THEOREM` (`"langgraph_state_integrity"`). Use these instead of hard-coding strings; the underlying private constants `_THEOREM` / `_WINDOWED_THEOREM` are the SSoT and the public re-exports forward to them.
|
|
181
|
+
- **Module attributes:** `__version__`, `__all__`.
|
|
182
|
+
|
|
183
|
+
Anything underscore-prefixed is **internal** and may change without notice within `0.1.x`. Notable internals callers sometimes touch:
|
|
184
|
+
|
|
185
|
+
- `_THEOREM` / `_WINDOWED_THEOREM` — module-internal SSoT for theorem names; use `STAGNATION_THEOREM` / `INTEGRITY_THEOREM` instead.
|
|
186
|
+
- `EPHEMERAL_THREAD` (in `_common.py`) — the internal fallback thread-id used whenever no `thread_id` can be extracted from the LangGraph config or runtime at the wrapped node. Confirmed internal in `0.1.0a2` (Roborev #903); see `_common.py:thread_id()` for exact semantics.
|
|
187
|
+
- `_observe`, `_emit_certificate`, `_make_certificate`, `_thread_state` — internal gate machinery; touching these from a caller breaks the binding contract in *Scope (normative)*.
|
|
188
|
+
|
|
189
|
+
**Stability commitment:**
|
|
190
|
+
|
|
191
|
+
- `0.1.x` is an alpha series — **breaking changes are still possible**. Each will be documented in `CHANGELOG.md` and (for renamed theorem names) will go through a deprecation cycle wired through `operon-ai`'s theorem registry.
|
|
192
|
+
- The first non-breaking promise lands at `0.1.0` stable. Patches above that (`0.1.1`, `0.1.2`, ...) preserve the public surface above.
|
|
193
|
+
- Breaking changes thereafter increment to `0.2.0` per [SemVer](https://semver.org/).
|
|
194
|
+
- The cross-repo binding to `operon-ai`'s A2A codec is enforced by `tests/test_a2a_round_trip.py` against the pinned range in `pyproject.toml`; widening that pin requires re-running the test against the new range.
|
|
195
|
+
|
|
196
|
+
## Status
|
|
197
|
+
|
|
198
|
+
**Beta — `0.1.0`.** First stable release. Public surface is documented in the section above; `0.1.x` patches preserve it, breaking changes increment to `0.2.0` per [SemVer](https://semver.org/). The cross-repo A2A binding is enforced under the pinned `operon-ai>=0.36.1,<0.40` range. Feedback welcome via Issues.
|
|
199
|
+
|
|
200
|
+
## License
|
|
201
|
+
|
|
202
|
+
MIT — see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
operon_langgraph_gates/__init__.py,sha256=O4xJb8-BhBH85vw07EJHWPRCsaj2Na2kpWGMo2bqYiI,1176
|
|
2
|
+
operon_langgraph_gates/_common.py,sha256=TYafSSJmP_xXhQBHBv8qHf70vLrEuk2tNqWzJlyPrIs,2961
|
|
3
|
+
operon_langgraph_gates/embedders.py,sha256=VxVRZEOlp9g72udxujfvigYygcjGOxYvoDHZLCQzH4A,2242
|
|
4
|
+
operon_langgraph_gates/integrity.py,sha256=jAkEtIqZGcaN6PlvDcILOkSmOMpyC8I9VxBv96lCyEk,8929
|
|
5
|
+
operon_langgraph_gates/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
operon_langgraph_gates/stagnation.py,sha256=G8ctkmGx4riPc3o5LDly1oSDLw6D_tNawgCsmFkB1gM,14970
|
|
7
|
+
operon_langgraph_gates-0.1.0.dist-info/METADATA,sha256=dsI9L8fLfkNdPWQ0K0KEfc31GiXjI_2HdwAYciamNaI,19804
|
|
8
|
+
operon_langgraph_gates-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
9
|
+
operon_langgraph_gates-0.1.0.dist-info/licenses/LICENSE,sha256=kSlbfr4PkGoa5n1a4hxlwvIn8n2TsfFRJIKZ4jJkMNI,1068
|
|
10
|
+
operon_langgraph_gates-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bogdan Banu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|