railtracks.middleware
1from railtracks.middleware.after import after_node 2from railtracks.middleware.core import ( 3 Middleware, 4 wrap_node, 5) 6from railtracks.middleware.post import post_node 7from railtracks.middleware.verdict import ( 8 Verdict, 9 VerifierAction, 10 VerifierDecision, 11 VerifierRejectedError, 12) 13 14__all__ = [ 15 "post_node", 16 "after_node", 17 "Middleware", 18 "wrap_node", 19 "Verdict", 20 "VerifierRejectedError", 21 "VerifierAction", 22 "VerifierDecision", 23]
31def post_node( 32 fn: Callable[[_R], Awaitable[_R]] | Callable[[_R], _R] | None = None, 33 /, 34 *, 35 name: str | None = None, 36) -> ( 37 Middleware[..., _R] 38 | Callable[ 39 [Callable[[_R], Awaitable[_R]] | Callable[[_R], _R]], Middleware[..., _R] 40 ] 41): 42 """ 43 Special decorator to create a middleware that runs after the node completes. The wrapped function will run and then your post function will be called upon successful completion of the function. 44 45 NOTE: This middleware will not run if the node raises an exception. 46 """ 47 48 if fn is None: 49 return lambda f: wrap_node(_wrapper(f), name=name) 50 51 return wrap_node(_wrapper(fn), name=name)
Special decorator to create a middleware that runs after the node completes. The wrapped function will run and then your post function will be called upon successful completion of the function.
NOTE: This middleware will not run if the node raises an exception.
28def after_node( 29 fn: Callable[[_R], Awaitable[_R]] | Callable[[_R], _R] | None = None, 30 /, 31 *, 32 name: str | None = None, 33) -> Any: 34 """Deprecated: Use ``rt.post_node`` instead.""" 35 warn_pending_change( 36 "rt.after_node", 37 change="is renamed", 38 instead="rt.post_node", 39 detail="The function itself is unchanged.", 40 ) 41 if fn is None: 42 return post_node(name=name) 43 return post_node(fn, name=name)
Deprecated: Use rt.post_node instead.
62class Middleware(Generic[_P, _R, _Constraint]): 63 """Execution-control middleware: wraps a callable to control how it is invoked. 64 65 Built from an async call-style function ``fn(call, *args, **kwargs)`` where 66 ``call`` is the next callable in the chain:: 67 68 @wrap_node 69 async def retry(call, *args, **kwargs): 70 for _ in range(3): 71 try: 72 return await call(*args, **kwargs) 73 except Exception: 74 pass 75 raise RuntimeError("All retries exhausted") 76 77 ``fn`` must be ``async``; passing a plain ``def`` raises ``TypeError``. 78 """ 79 80 def __init__( 81 self, 82 fn: Callable[Concatenate[Callable[_P, Awaitable[_R]], _P], Awaitable[_R]], 83 name: str | None = None, 84 ) -> None: 85 _require_async(fn, "Middleware function") 86 self._fn = fn 87 if name is None: 88 bound_to_self = getattr(fn, "__self__", None) is self 89 name = type(self).__name__ if bound_to_self else fn.__name__ 90 self.name = name 91 self.type_id = str( 92 uuid.uuid4() 93 ) # identifies this middleware definition, shared by every invocation 94 95 async def start_creation_task(self): 96 # instances are shared across runs, so announce once per session, not once ever 97 if not claim_middleware_registration(self.type_id): 98 return 99 100 event = MiddlewareCreationEvent( 101 middleware_type_id=self.type_id, 102 middleware_name=self.name, 103 ) 104 return await emit(event) 105 106 def wrap(self, inner: Callable[_P, Awaitable[_R]]) -> Callable[_P, Awaitable[_R]]: 107 """Compose this middleware onto ``inner``, returning a new callable with the same signature.""" 108 fn = self._fn 109 110 async def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: 111 return await fn(inner, *args, **kwargs) 112 113 return wrapped 114 115 def __repr__(self) -> str: 116 return f"Middleware({self._fn.__name__})" 117 118 def middleware_type(self) -> str: 119 return "General"
Execution-control middleware: wraps a callable to control how it is invoked.
Built from an async call-style function fn(call, *args, **kwargs) where
call is the next callable in the chain::
@wrap_node
async def retry(call, *args, **kwargs):
for _ in range(3):
try:
return await call(*args, **kwargs)
except Exception:
pass
raise RuntimeError("All retries exhausted")
fn must be async; passing a plain def raises TypeError.
80 def __init__( 81 self, 82 fn: Callable[Concatenate[Callable[_P, Awaitable[_R]], _P], Awaitable[_R]], 83 name: str | None = None, 84 ) -> None: 85 _require_async(fn, "Middleware function") 86 self._fn = fn 87 if name is None: 88 bound_to_self = getattr(fn, "__self__", None) is self 89 name = type(self).__name__ if bound_to_self else fn.__name__ 90 self.name = name 91 self.type_id = str( 92 uuid.uuid4() 93 ) # identifies this middleware definition, shared by every invocation
95 async def start_creation_task(self): 96 # instances are shared across runs, so announce once per session, not once ever 97 if not claim_middleware_registration(self.type_id): 98 return 99 100 event = MiddlewareCreationEvent( 101 middleware_type_id=self.type_id, 102 middleware_name=self.name, 103 ) 104 return await emit(event)
106 def wrap(self, inner: Callable[_P, Awaitable[_R]]) -> Callable[_P, Awaitable[_R]]: 107 """Compose this middleware onto ``inner``, returning a new callable with the same signature.""" 108 fn = self._fn 109 110 async def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: 111 return await fn(inner, *args, **kwargs) 112 113 return wrapped
Compose this middleware onto inner, returning a new callable with the same signature.
13@dataclass 14class Verdict(Generic[_R]): 15 """The result of an approve callable's review of a node call. 16 17 - accept: ``accepted=True``, ``comment=None`` 18 - accept with comments: ``accepted=True``, ``comment=<str>``, optionally 19 ``args``/``kwargs`` (pre-call) or ``result`` (post-call) set to override 20 what gets forwarded. 21 - decline: ``accepted=False``, ``comment=None`` 22 - decline with comments: ``accepted=False``, ``comment=<str>`` 23 24 ``args``/``kwargs`` mean "forward these into the call instead" — used by 25 pre-call verifiers, which review before the node runs. ``result`` means 26 "propagate this instead of what the call produced" — used by post-call 27 verifiers, which review after the node has already run and can no longer 28 change what was passed in, only what continues onward. 29 30 ``Verdict`` is generic over ``result``'s type, matching the wrapped 31 node's return type, so a ``result=`` override of the wrong type is a 32 type-checker error rather than a silent runtime mismatch. There is no 33 runtime validation of ``args``/``kwargs`` overrides against the node's 34 signature — a bad override surfaces as a ``TypeError`` from the call 35 itself. 36 """ 37 38 accepted: bool 39 comment: str | None = None 40 args: tuple | None = None 41 kwargs: dict | None = None 42 result: _R | None = None
The result of an approve callable's review of a node call.
- accept:
accepted=True,comment=None - accept with comments:
accepted=True,comment=<str>, optionallyargs/kwargs(pre-call) orresult(post-call) set to override what gets forwarded. - decline:
accepted=False,comment=None - decline with comments:
accepted=False,comment=<str>
args/kwargs mean "forward these into the call instead" — used by
pre-call verifiers, which review before the node runs. result means
"propagate this instead of what the call produced" — used by post-call
verifiers, which review after the node has already run and can no longer
change what was passed in, only what continues onward.
Verdict is generic over result's type, matching the wrapped
node's return type, so a result= override of the wrong type is a
type-checker error rather than a silent runtime mismatch. There is no
runtime validation of args/kwargs overrides against the node's
signature — a bad override surfaces as a TypeError from the call
itself.
45class VerifierRejectedError(Exception): 46 """Raised when a verifier's approve callable declines a node call."""
Raised when a verifier's approve callable declines a node call.
49class VerifierAction(str, Enum): 50 """What a verifier's review concluded. 51 52 Members: 53 ACCEPT: The call (or its output) may proceed. 54 DECLINE: The call (or its output) is rejected. 55 """ 56 57 ACCEPT = "accept" 58 DECLINE = "decline"
What a verifier's review concluded.
Members:
ACCEPT: The call (or its output) may proceed. DECLINE: The call (or its output) is rejected.
61class VerifierDecision(BaseModel): 62 """Structured, observable summary of a `Verdict`, carried on verifier events. 63 64 Mirrors `GuardrailDecision`'s shape so verifier decisions are tagged in the 65 trace the same way guardrail decisions are. 66 67 Attributes: 68 action: Whether the verdict accepted or declined the call. 69 reason: The verdict's comment, if any. 70 overridden: Whether the verdict replaced args/kwargs (pre-call) or the 71 result (post-call) instead of forwarding them unchanged. 72 timeout: Whether this decision was synthesized because `approve_fn` 73 didn't respond within the configured timeout, rather than an 74 actual verdict from `approve_fn` itself. 75 """ 76 77 action: VerifierAction 78 reason: str | None = None 79 overridden: bool = False 80 timeout: bool = False 81 82 @classmethod 83 def from_verdict( 84 cls, verdict: Verdict, *, overridden: bool, timeout: bool = False 85 ) -> "VerifierDecision": 86 """Build a `VerifierDecision` summarizing `verdict`.""" 87 return cls( 88 action=VerifierAction.ACCEPT 89 if verdict.accepted 90 else VerifierAction.DECLINE, 91 reason=verdict.comment, 92 overridden=overridden, 93 timeout=timeout, 94 )
Structured, observable summary of a Verdict, carried on verifier events.
Mirrors GuardrailDecision's shape so verifier decisions are tagged in the
trace the same way guardrail decisions are.
Attributes:
- action: Whether the verdict accepted or declined the call.
- reason: The verdict's comment, if any.
- overridden: Whether the verdict replaced args/kwargs (pre-call) or the result (post-call) instead of forwarding them unchanged.
- timeout: Whether this decision was synthesized because
approve_fndidn't respond within the configured timeout, rather than an actual verdict fromapprove_fnitself.
82 @classmethod 83 def from_verdict( 84 cls, verdict: Verdict, *, overridden: bool, timeout: bool = False 85 ) -> "VerifierDecision": 86 """Build a `VerifierDecision` summarizing `verdict`.""" 87 return cls( 88 action=VerifierAction.ACCEPT 89 if verdict.accepted 90 else VerifierAction.DECLINE, 91 reason=verdict.comment, 92 overridden=overridden, 93 timeout=timeout, 94 )
Build a VerifierDecision summarizing verdict.