flowsemantics package¶
Subpackages¶
- flowsemantics.abstractions package
- flowsemantics.configuration package
- Submodules
- flowsemantics.configuration.catch module
- flowsemantics.configuration.finalization module
FinallyCancellationTokenFinallyContextFinallyContext.resultFinallyContext.statusFinallyContext.valueFinallyContext.exceptionFinallyContext.contextFinallyContext.cancellation_tokenFinallyContext.resultFinallyContext.statusFinallyContext.valueFinallyContext.exceptionFinallyContext.contextFinallyContext.cancellation_tokenFinallyContext.__init__()
FinallyFailurePolicy
- flowsemantics.configuration.flow module
EvaluationModeFallbackFlowFlow.__init__()Flow.when()Flow.when_not()Flow.when_expr()Flow.when_not_expr()Flow.with_flow_id()Flow.from_ir()Flow.then()Flow.otherwise()Flow.default_if_no_match()Flow.default()Flow.catch()Flow.catch_when()Flow.catch_any()Flow.rethrow()Flow.on_match()Flow.finally_()Flow.finally_async()Flow.with_finally_policy()Flow.with_finally_timeout()Flow.with_trace()Flow.with_cancel_check()Flow.with_mode()Flow.with_clock()Flow.merge()Flow.compile()Flow.from_table()
FlowContractFlowContract.rulesFlowContract.fallbackFlowContract.modeFlowContract.clockFlowContract.spec_versionFlowContract.portabilityFlowContract.catchesFlowContract.hooksFlowContract.finalizersFlowContract.finally_policyFlowContract.finally_timeout_msFlowContract.trace_enabledFlowContract.trace_diagnostic_hookFlowContract.portable_irFlowContract.async_onlyFlowContract.cancel_checkFlowContract.contract_versionFlowContract.to_ir()FlowContract.to_ir_json()FlowContract.simulate()FlowContract.simulate_batch()FlowContract.portability_report()FlowContract.explain()FlowContract.validate()FlowContract.execute()FlowContract.try_execute()FlowContract.execute_async()FlowContract.try_execute_async()FlowContract.__init__()
FlowPortabilityValidationIssue
- flowsemantics.configuration.portable module
- flowsemantics.configuration.rule module
- flowsemantics.configuration.table module
- Module contents
CatchRuleDecisionTableDecisionTableRowEvaluationModeFallbackFinallyCancellationTokenFinallyContextFinallyContext.resultFinallyContext.statusFinallyContext.valueFinallyContext.exceptionFinallyContext.contextFinallyContext.cancellation_tokenFinallyContext.resultFinallyContext.statusFinallyContext.valueFinallyContext.exceptionFinallyContext.contextFinallyContext.cancellation_tokenFinallyContext.__init__()
FinallyFailurePolicyFlowFlow.__init__()Flow.when()Flow.when_not()Flow.when_expr()Flow.when_not_expr()Flow.with_flow_id()Flow.from_ir()Flow.then()Flow.otherwise()Flow.default_if_no_match()Flow.default()Flow.catch()Flow.catch_when()Flow.catch_any()Flow.rethrow()Flow.on_match()Flow.finally_()Flow.finally_async()Flow.with_finally_policy()Flow.with_finally_timeout()Flow.with_trace()Flow.with_cancel_check()Flow.with_mode()Flow.with_clock()Flow.merge()Flow.compile()Flow.from_table()
FlowContractFlowContract.rulesFlowContract.fallbackFlowContract.modeFlowContract.clockFlowContract.spec_versionFlowContract.portabilityFlowContract.catchesFlowContract.hooksFlowContract.finalizersFlowContract.finally_policyFlowContract.finally_timeout_msFlowContract.trace_enabledFlowContract.trace_diagnostic_hookFlowContract.portable_irFlowContract.async_onlyFlowContract.cancel_checkFlowContract.contract_versionFlowContract.to_ir()FlowContract.to_ir_json()FlowContract.simulate()FlowContract.simulate_batch()FlowContract.portability_report()FlowContract.explain()FlowContract.validate()FlowContract.execute()FlowContract.try_execute()FlowContract.execute_async()FlowContract.try_execute_async()FlowContract.__init__()
FlowPortabilityPExprPortableFlowPortableRuleRuleRuleIdValidationIssueeval_expr()expr_from_dict()expr_to_dict()pand()pconst()peq()pfield()pge()pgt()pin()pis_not_null()pis_null()ple()plt()pne()pnot()pnot_in()por()table_to_flow()
- flowsemantics.errors package
- flowsemantics.execution package
- Submodules
- flowsemantics.execution.clock module
- flowsemantics.execution.context module
- flowsemantics.execution.outcome module
- flowsemantics.execution.trace module
- Module contents
- flowsemantics.finalization package
- flowsemantics.portable package
- flowsemantics.testing package
- flowsemantics.trace package
- flowsemantics.trust package
- Submodules
- flowsemantics.trust.replay module
ReplayErrorReplayModeReplayRecordReplayRecord.spec_versionReplayRecord.contract_versionReplayRecord.inputReplayRecord.clock_wallReplayRecord.clock_monotonicReplayRecord.outcomeReplayRecord.traceReplayRecord.effectsReplayRecord.integrityReplayRecord.spec_versionReplayRecord.contract_versionReplayRecord.inputReplayRecord.clock_wallReplayRecord.clock_monotonicReplayRecord.outcomeReplayRecord.traceReplayRecord.effectsReplayRecord.integrityReplayRecord.__init__()
ReplayResultrecord()replay()sign()
- flowsemantics.trust.shadow module
- Module contents
ReplayErrorReplayModeReplayRecordReplayRecord.spec_versionReplayRecord.contract_versionReplayRecord.inputReplayRecord.clock_wallReplayRecord.clock_monotonicReplayRecord.outcomeReplayRecord.traceReplayRecord.effectsReplayRecord.integrityReplayRecord.spec_versionReplayRecord.contract_versionReplayRecord.inputReplayRecord.clock_wallReplayRecord.clock_monotonicReplayRecord.outcomeReplayRecord.traceReplayRecord.effectsReplayRecord.integrityReplayRecord.__init__()
ReplayResultShadowEntryShadowReportrecord()replay()shadow()sign()
- flowsemantics.validation package
Module contents¶
FlowSemantics: zero-runtime-dependency, language-neutral execution-semantics library.
This package is the Python reference implementation of the FlowSemantics specification (SPEC.md v0.1, frozen). The specification is authoritative; this package is a conforming implementation, not the definition.
Layer: Contracts Module: flowsemantics Since: 0.0.0 Implements: n/a (public package surface) Depends on: flowsemantics._version (re-exported as __version__) Used by: consumers, tests, samples, conformance runner See also: SPEC.md, docs/getting-started.md (Phase 1)
Notes
__all__ grows as features are implemented in Phases 1-3.
_version is re-exported for the smoke test and for pip-show consistency.
- exception flowsemantics.AsyncOnlyContractError[source]¶
Bases:
FlowSemanticsErrorRaised when execute() is called on an async-only contract (SPEC 11.7).
- class flowsemantics.CatchRule(kind: Literal['typed', 'when', 'any', 'rethrow'], exc_type: type[Exception] | None = None, predicate: Callable[[Any, BaseException], bool] | None = None, handler: Callable[[Any, BaseException], Any] | None = None, id: str | None = None)[source]¶
Bases:
objectOne exception handler in the catch chain (SPEC 11.1-11.4).
- kind¶
“typed” (isinstance match), “when” (isinstance + predicate), “any” (matches any Exception), or “rethrow” (always propagates).
- Type:
Literal[‘typed’, ‘when’, ‘any’, ‘rethrow’]
- predicate¶
Optional predicate for “when” kind; receives (input, exception) and must return bool.
- Type:
collections.abc.Callable[[Any, BaseException], bool] | None
- handler¶
Receives (input, exception), returns the outcome value. Absent for “rethrow”.
- Type:
collections.abc.Callable[[Any, BaseException], Any] | None
- id¶
Optional stable identifier recorded in RecoveryInfo.
- Type:
str | None
- kind: Literal['typed', 'when', 'any', 'rethrow']¶
- predicate: Callable[[Any, BaseException], bool] | None = None¶
- handler: Callable[[Any, BaseException], Any] | None = None¶
- id: str | None = None¶
- class flowsemantics.Clock(*args, **kwargs)[source]¶
Bases:
ProtocolTwo-concept clock: wall time for timestamps, monotonic for durations.
SPEC.md section 6.2 makes the wall/monotonic distinction normative.
- __init__(*args, **kwargs)¶
- class flowsemantics.DecisionStatus(value)[source]¶
Bases:
StrEnumWhat the flow concluded. Exactly three members (SPEC 3.2).
- APPROVED = 'approved'¶
- REJECTED = 'rejected'¶
- NO_MATCH = 'no_match'¶
- class flowsemantics.DecisionTable(rows: tuple[~flowsemantics.configuration.table.DecisionTableRow, ...], hit_policy: str = 'FIRST', input_fields: tuple[str, ...] = <factory>, warnings: tuple[str, ...] = <factory>)[source]¶
Bases:
objectA column-based decision table that compiles to a rule list.
- rows: tuple[DecisionTableRow, ...]¶
- hit_policy: str = 'FIRST'¶
- input_fields: tuple[str, ...]¶
- warnings: tuple[str, ...]¶
- property evaluation_mode: EvaluationMode¶
The EvaluationMode this hit policy maps to (SPEC 10.8).
- __init__(rows: tuple[~flowsemantics.configuration.table.DecisionTableRow, ...], hit_policy: str = 'FIRST', input_fields: tuple[str, ...] = <factory>, warnings: tuple[str, ...] = <factory>) None¶
- class flowsemantics.DecisionTableRow(id: str, conditions: tuple[Callable[[Any], bool | Awaitable[bool]], ...], action: Callable[[...], Any], priority: int = 0)[source]¶
Bases:
objectOne row of a decision table.
- id¶
Stable RuleId for the compiled rule.
- Type:
str
- conditions¶
Predicates that must ALL be true for the row to match.
- Type:
tuple[collections.abc.Callable[[Any], bool | collections.abc.Awaitable[bool]], …]
- action¶
The transformation executed on match.
- Type:
collections.abc.Callable[[…], Any]
- priority¶
Priority for PRIORITY hit policy (higher first).
- Type:
int
- id: str¶
- conditions: tuple[Callable[[Any], bool | Awaitable[bool]], ...]¶
- action: Callable[[...], Any]¶
- priority: int = 0¶
- __init__(id: str, conditions: tuple[Callable[[Any], bool | Awaitable[bool]], ...], action: Callable[[...], Any], priority: int = 0) None¶
- class flowsemantics.Effect(name: str, payload: Any = None)[source]¶
Bases:
objectA proposed side effect. Data, not code (SPEC 3.7).
- name: str¶
- payload: Any = None¶
- __init__(name: str, payload: Any = None) None¶
- exception flowsemantics.EvaluationError[source]¶
Bases:
FlowSemanticsErrorRaised for an evaluation-time failure not otherwise classified.
- class flowsemantics.EvaluationMode(value)[source]¶
Bases:
StrEnumMultiple-match behavior. Exactly three members (SPEC 10.6).
- FIRST_MATCH = 'FirstMatch'¶
- ALL_MATCH = 'AllMatch'¶
- PRIORITY = 'Priority'¶
- class flowsemantics.ExecutionStatus(value)[source]¶
Bases:
StrEnumWhat happened while running. Exactly four members (SPEC 3.1).
- COMPLETED = 'completed'¶
- FAILED = 'failed'¶
- CANCELLED = 'cancelled'¶
- TIMED_OUT = 'timed_out'¶
- class flowsemantics.ExecutionTrace(contract_version: str, events: tuple[~flowsemantics.execution.trace.TraceEvent, ...]=<factory>)[source]¶
Bases:
objectOrdered trace events plus contract version (SPEC 3.8).
- contract_version: str¶
- events: tuple[TraceEvent, ...]¶
- __init__(contract_version: str, events: tuple[~flowsemantics.execution.trace.TraceEvent, ...]=<factory>) None¶
- class flowsemantics.FakeClock(wall: datetime | None = None, monotonic: float = 0.0)[source]¶
Bases:
objectDeterministic clock for tests, replay, and conformance vectors.
Wall and monotonic values advance only when advance() or advance_wall() is called. Two FakeClocks constructed with the same values behave identically, which is what SPEC.md section 6.1 determinism requires.
- __init__(wall: datetime | None = None, monotonic: float = 0.0) None[source]¶
Create a FakeClock at the given wall time and monotonic offset.
- class flowsemantics.Fallback(kind: str, action: Callable[[...], Any] | None = None, value: Any = None)[source]¶
Bases:
objectNo-match fallback configuration (SPEC 10.4).
- kind: str¶
- action: Callable[[...], Any] | None = None¶
- value: Any = None¶
- __init__(kind: str, action: Callable[[...], Any] | None = None, value: Any = None) None¶
- exception flowsemantics.FinalizationBudgetExceeded[source]¶
Bases:
FlowSemanticsErrorRecorded when cleanup exceeds its WithFinallyTimeout budget (SPEC 16.7).
- class flowsemantics.FinalizationInfo(is_clean: bool, cleanup_exceptions: tuple[BaseException, ...] = (), cleanup_budget_used: timedelta = datetime.timedelta(0), cleanup_budget_exceeded: bool = False)[source]¶
Bases:
objectFinalization metadata including is_clean (SPEC 3.5, B6, B8).
- is_clean: bool¶
- cleanup_exceptions: tuple[BaseException, ...] = ()¶
- cleanup_budget_used: timedelta = datetime.timedelta(0)¶
- cleanup_budget_exceeded: bool = False¶
- __init__(is_clean: bool, cleanup_exceptions: tuple[BaseException, ...] = (), cleanup_budget_used: timedelta = datetime.timedelta(0), cleanup_budget_exceeded: bool = False) None¶
- class flowsemantics.FinallyCancellationToken(cancelled: bool = False)[source]¶
Bases:
objectFresh per-finalizer cancellation token (SPEC 11.8.1, 11.8.5).
Bounded by WithFinallyTimeout where configured. One finalizer cancelling its token MUST NOT cancel the tokens of the others.
- cancelled: bool = False¶
- __init__(cancelled: bool = False) None¶
- class flowsemantics.FinallyContext(result: FlowOutcome, status: ExecutionStatus, value: Any, exception: BaseException | None, context: Any, cancellation_token: FinallyCancellationToken)[source]¶
Bases:
objectContext passed to each finalizer (SPEC 11.8.1).
- result¶
The sealed primary outcome.
- status¶
The ExecutionStatus of the primary outcome.
- value¶
The outcome value, read-only. Finally MUST NOT change it.
- Type:
Any
- exception¶
The primary exception, if any.
- Type:
BaseException | None
- context¶
The typed input from the flow.
- Type:
Any
- cancellation_token¶
A fresh token for this finalizer.
- result: FlowOutcome¶
- status: ExecutionStatus¶
- value: Any¶
- exception: BaseException | None¶
- context: Any¶
- cancellation_token: FinallyCancellationToken¶
- __init__(result: FlowOutcome, status: ExecutionStatus, value: Any, exception: BaseException | None, context: Any, cancellation_token: FinallyCancellationToken) None¶
- class flowsemantics.FinallyFailurePolicy(value)[source]¶
Bases:
StrEnumWhat happens to the primary outcome when cleanup fails (SPEC 16.4).
- PRESERVE_PRIMARY = 'PreservePrimary'¶
- ATTACH = 'Attach'¶
- REPLACE_PRIMARY = 'ReplacePrimary'¶
- class flowsemantics.Flow[source]¶
Bases:
objectMutable builder for a flow. Construction performs no execution.
- when(condition: Callable[[Any], bool | Awaitable[bool]], *, then: Callable[[...], Any], id: str | RuleId, guard: Callable[[Any], bool | Awaitable[bool]] | None = None, priority: int = 0, effective_from: datetime | None = None, effective_until: datetime | None = None, effects: Iterable[Effect] = ()) Flow[source]¶
Register a positive condition rule (SPEC 10.2, 12.9).
effects are proposed (never applied) in evaluation order when the rule matches (SPEC 5, 6.4, 14.2).
- when_not(condition: Callable[[Any], bool | Awaitable[bool]], *, then: Callable[[...], Any], id: str | RuleId, guard: Callable[[Any], bool | Awaitable[bool]] | None = None, priority: int = 0, effective_from: datetime | None = None, effective_until: datetime | None = None, effects: Iterable[Effect] = ()) Flow[source]¶
Register a negative condition rule (SPEC 10.2, 12.9).
- when_expr(condition: PExpr, *, then: PExpr, id: str | RuleId, guard: PExpr | None = None, priority: int = 0, effective_from: datetime | None = None, effective_until: datetime | None = None, effects: Iterable[Effect] = ()) Flow[source]¶
Register a portable rule (SPEC 14.2).
Condition, guard, and transform are declarative expressions from the portable subset; no host lambdas are involved. Effects are proposed data carried in the IR (SPEC 14.2).
- when_not_expr(condition: PExpr, *, then: PExpr, id: str | RuleId, guard: PExpr | None = None, priority: int = 0, effective_from: datetime | None = None, effective_until: datetime | None = None, effects: Iterable[Effect] = ()) Flow[source]¶
Register a negated portable rule (SPEC 14.2).
- with_flow_id(flow_id: str) Flow[source]¶
Set the flow identifier carried in the Portable IR (SPEC 14.2).
- classmethod from_ir(data: dict[str, Any] | str) Flow[source]¶
Build a Flow from a Portable IR document (SPEC 14.2).
Accepts a dict or JSON string produced by PortableFlow.to_dict/ to_json. Only when/when_not rules with declarative expressions are supported; ‘then’ stages and dynamic fallbacks are rejected.
- then(stage: Callable[[Any, Any], Any], *, id: str | RuleId, effects: Iterable[Effect] = ()) Flow[source]¶
Register a sequential stage (SPEC 10.5).
The stage receives (input, previous_output) and runs only when the preceding rule matched. It cannot be the first element of a flow; compile() enforces that.
- otherwise(action: Callable[[...], Any]) Flow[source]¶
Register a dynamic no-match fallback (SPEC 10.4).
- catch(exc_type: type[Exception], handler: Callable[[Any, BaseException], Any], *, id: str | None = None) Flow[source]¶
Register a typed exception handler (SPEC 11.1).
The handler receives (input, exception) and returns the outcome value. Matching follows host-language inheritance: a handler for a base type catches subclasses.
- catch_when(exc_type: type[Exception], predicate: Callable[[Any, BaseException], bool], handler: Callable[[Any, BaseException], Any], *, id: str | None = None) Flow[source]¶
Register a typed handler with a predicate (SPEC 11.2).
The predicate receives (input, exception) and is evaluated only after the type check passes.
- catch_any(handler: Callable[[Any, BaseException], Any], *, id: str | None = None) Flow[source]¶
Register a broad handler for otherwise-uncaught exceptions (SPEC 11.3).
MUST be registered after all typed catch/catch_when rules; compile() enforces the ordering.
- on_match(hook: Callable[[Any, str, Any], Any]) Flow[source]¶
Register an observable hook (SPEC 11.5).
The hook receives (input, RuleId, value) after a when/when_not rule’s action produces its value. Hook failures are isolated into secondary_exceptions and never trigger catch rules.
- finally_(cleanup: Callable[[FinallyContext], None]) Flow[source]¶
Register a finalizer that runs after primary execution (SPEC 11.8).
The finalizer receives a FinallyContext and runs for every outcome status, including CANCELLED and TIMED_OUT. Finalizers run in LIFO order and are isolated: a failure in one does not skip the rest.
- finally_async(cleanup: Callable[[FinallyContext], Any]) Flow[source]¶
Register an asynchronous finalizer (SPEC 11.8, 16.7).
A flow with async finalizers is async-only: every finalizer must be async, and the contract can only run via execute_async() (SPEC 11.7, FR8).
- with_finally_policy(policy: FinallyFailurePolicy | str) Flow[source]¶
Set the finally failure policy (SPEC 11.8.3, 16.4).
- with_finally_timeout(ms: int) Flow[source]¶
Bound each finalizer’s budget in milliseconds (SPEC 16.7).
- with_trace(diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None) Flow[source]¶
Enable tracing for executions of this flow (SPEC 12.3, 12.2).
diagnostic_hook is the application-supplied redaction-aware hook: it receives each TraceEvent and may return extra diagnostic fields.
- with_cancel_check(check: Callable[[], bool]) Flow[source]¶
Register a cooperative cancellation predicate (SPEC 11.6).
The predicate is polled before each rule evaluation; when it returns True the contract produces a CANCELLED outcome via an interruption, bypassing catch rules entirely.
- with_mode(mode: EvaluationMode | str) Flow[source]¶
Set the evaluation mode (SPEC 10.6).
- merge(other: Flow | FlowContract) Flow[source]¶
Splice another flow’s rules and fallback at the call site (SPEC 10.7).
- Rules:
Both flows MUST share the same EvaluationMode; mismatch raises StructureError.
RuleIds MUST be unique across the combined flow.
If both flows have a fallback, the outer (self) fallback wins and the inner fallback is discarded.
Catch scoping and LIFO finalizer ordering complete in Phase 2.5.
- compile() FlowContract[source]¶
Validate and produce an immutable FlowContract (SPEC 10.9).
- class flowsemantics.FlowContext(input: Any, clock: Clock = <factory>, state: dict[str, ~typing.Any]=<factory>)[source]¶
Bases:
objectIsolated per-invocation state for one flow execution.
- input¶
The input value passed to execute().
- Type:
Any
- clock¶
The injected clock. Defaults to SystemClock when the caller does not supply one; deterministic replay MUST inject FakeClock.
- state¶
Per-invocation mutable state for engine bookkeeping. Never shared between invocations.
- Type:
dict[str, Any]
- input: Any¶
- state: dict[str, Any]¶
- class flowsemantics.FlowContract(rules: tuple[Rule, ...], fallback: Fallback | None, mode: EvaluationMode, clock: Clock, spec_version: str, portability: FlowPortability, catches: tuple[CatchRule, ...] = (), hooks: tuple[Callable[[Any, str, Any], Any], ...] = (), finalizers: tuple[Callable[[FinallyContext], Any], ...] = (), finally_policy: FinallyFailurePolicy = FinallyFailurePolicy.PRESERVE_PRIMARY, finally_timeout_ms: int | None = None, trace_enabled: bool = False, trace_diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None, portable_ir: PortableFlow | None = None, async_only: bool = False, cancel_check: Callable[[], bool] | None = None, contract_version: str = '1')[source]¶
Bases:
objectImmutable, reusable execution definition produced by compile().
- mode: EvaluationMode¶
- spec_version: str¶
- portability: FlowPortability¶
- hooks: tuple[Callable[[Any, str, Any], Any], ...] = ()¶
- finalizers: tuple[Callable[[FinallyContext], Any], ...] = ()¶
- finally_policy: FinallyFailurePolicy = 'PreservePrimary'¶
- finally_timeout_ms: int | None = None¶
- trace_enabled: bool = False¶
- trace_diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None¶
- portable_ir: PortableFlow | None = None¶
- async_only: bool = False¶
- cancel_check: Callable[[], bool] | None = None¶
- contract_version: str = '1'¶
- to_ir() PortableFlow[source]¶
Export the contract as a PortableFlow IR document.
Only PORTABLE contracts carry an IR; NATIVE contracts raise PortabilityError (SPEC 4.4, 14.2).
- simulate(input: Any, *, clock: Clock | None = None) FlowOutcome[source]¶
Evaluate without effects, hooks, or finalizers (SPEC 12.5).
Produces the same decision semantics as a real execution for the same input and clock, except finalization is not performed and on_match hooks are suppressed.
- simulate_batch(inputs: Iterable[Any], *, clock: Clock | None = None) dict[str, Any][source]¶
Batch simulation with firing distribution (SPEC 12.5).
Runs simulate() over each input and aggregates outcomes by execution status, decision status, and produced value.
- portability_report() dict[str, Any][source]¶
Portability classification + offending components (SPEC 4.4).
- explain(trace: ExecutionTrace) str[source]¶
Render a trace as human-readable lines (SPEC 12.4).
The rationale is derived only from trace events and registered rule ids; no reasons are invented.
- validate() tuple[ValidationIssue, ...][source]¶
Static analysis without execution (SPEC 12.8).
Returns issues distinguishing errors (block compilation) from warnings (should investigate). A compiled contract is expected to have no errors; warnings may remain.
- execute(input: Any, *, clock: Clock | None = None) FlowOutcome[source]¶
Execute and propagate an unrecovered exception (SPEC 11.4, D13).
- try_execute(input: Any, *, clock: Clock | None = None, trace: bool | None = None, diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None) FlowOutcome[source]¶
Execute and always return a FlowOutcome (SPEC 11.4, D13).
trace=True enables trace collection for this execution even when the contract was not built with_trace() (SPEC 12.3). diagnostic_hook overrides the contract-level hook for this call.
- async execute_async(input: Any, *, clock: Clock | None = None) FlowOutcome[source]¶
Async execution; propagates an unrecovered exception (SPEC 11.7).
- async try_execute_async(input: Any, *, clock: Clock | None = None, trace: bool | None = None, diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None) FlowOutcome[source]¶
Async execution returning a FlowOutcome (SPEC 11.7).
Awaits every user-supplied callback that returns an awaitable; sync and async paths produce identical outcomes for the same contract and input.
- __init__(rules: tuple[Rule, ...], fallback: Fallback | None, mode: EvaluationMode, clock: Clock, spec_version: str, portability: FlowPortability, catches: tuple[CatchRule, ...] = (), hooks: tuple[Callable[[Any, str, Any], Any], ...] = (), finalizers: tuple[Callable[[FinallyContext], Any], ...] = (), finally_policy: FinallyFailurePolicy = FinallyFailurePolicy.PRESERVE_PRIMARY, finally_timeout_ms: int | None = None, trace_enabled: bool = False, trace_diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None, portable_ir: PortableFlow | None = None, async_only: bool = False, cancel_check: Callable[[], bool] | None = None, contract_version: str = '1') None¶
- class flowsemantics.FlowOutcome(execution_status: ExecutionStatus, decision_status: DecisionStatus | None = None, value: Any = None, recovery: RecoveryInfo | None = None, interruption: InterruptionInfo | None = None, finalization: FinalizationInfo | None = None, primary_exception: BaseException | None = None, secondary_exceptions: tuple[BaseException, ...] = (), effects: tuple[Effect, ...] = (), trace: ExecutionTrace | None = None)[source]¶
Bases:
objectThe structured result of one execution (SPEC 3.6).
- Invariants enforced by construction in the engine:
decision_status is absent unless execution_status is COMPLETED.
primary_exception is absent unless execution_status is FAILED.
interruption is populated only for CANCELLED and TIMED_OUT.
recovery is populated only when an exception was recovered.
secondary_exceptions includes cleanup exceptions even when the primary execution succeeded (B7).
- execution_status: ExecutionStatus¶
- decision_status: DecisionStatus | None = None¶
- value: Any = None¶
- recovery: RecoveryInfo | None = None¶
- interruption: InterruptionInfo | None = None¶
- finalization: FinalizationInfo | None = None¶
- primary_exception: BaseException | None = None¶
- secondary_exceptions: tuple[BaseException, ...] = ()¶
- trace: ExecutionTrace | None = None¶
- __init__(execution_status: ExecutionStatus, decision_status: DecisionStatus | None = None, value: Any = None, recovery: RecoveryInfo | None = None, interruption: InterruptionInfo | None = None, finalization: FinalizationInfo | None = None, primary_exception: BaseException | None = None, secondary_exceptions: tuple[BaseException, ...] = (), effects: tuple[Effect, ...] = (), trace: ExecutionTrace | None = None) None¶
- class flowsemantics.FlowPortability(value)[source]¶
Bases:
StrEnumWhole-contract portability classification (SPEC 4.4, feature 47).
- PORTABLE = 'portable'¶
- NATIVE = 'native'¶
- exception flowsemantics.FlowSemanticsError[source]¶
Bases:
ExceptionBase class for every exception raised by the FlowSemantics library.
- class flowsemantics.InterruptionInfo(kind: Literal['cancelled', 'timed_out'], source: str, timestamp: datetime, deadline: datetime | None = None)[source]¶
Bases:
objectCancellation/timeout metadata. Never an exception (SPEC 3.3, B5).
- kind: Literal['cancelled', 'timed_out']¶
- source: str¶
- timestamp: datetime¶
- deadline: datetime | None = None¶
- __init__(kind: Literal['cancelled', 'timed_out'], source: str, timestamp: datetime, deadline: datetime | None = None) None¶
- class flowsemantics.PExpr(op: str, args: tuple[Any, ...] = (), value: Any = None)[source]¶
Bases:
objectA node in the portable expression subset (SPEC 14.2).
op is one of: field, const, eq, ne, lt, le, gt, ge, and, or, not, is_null, is_not_null, in, not_in.
- op: str¶
- args: tuple[Any, ...] = ()¶
- value: Any = None¶
- __init__(op: str, args: tuple[Any, ...] = (), value: Any = None) None¶
- exception flowsemantics.PortabilityError[source]¶
Bases:
FlowSemanticsErrorRaised by export_portable() on a NATIVE contract (SPEC 4.4).
- class flowsemantics.PortableFlow(spec_version: str, flow_id: str, portability: str, mode: str, rules: tuple[PortableRule, ...], fallback: dict[str, Any] | None = None, contract_version: str = '')[source]¶
Bases:
objectCanonical Portable IR document (SPEC 14.2).
- spec_version: str¶
- flow_id: str¶
- portability: str¶
- mode: str¶
- rules: tuple[PortableRule, ...]¶
- fallback: dict[str, Any] | None = None¶
- contract_version: str = ''¶
- classmethod from_dict(data: dict[str, Any]) PortableFlow[source]¶
Deserialize from a dict.
Enforces SPEC 9.2 hardening: maximum rule count and duplicate RuleId rejection at deserialization time.
- classmethod from_json(text: str) PortableFlow[source]¶
Deserialize from a JSON string.
Rejects payloads larger than MAX_IR_BYTES (SPEC 9.2).
- __init__(spec_version: str, flow_id: str, portability: str, mode: str, rules: tuple[PortableRule, ...], fallback: dict[str, Any] | None = None, contract_version: str = '') None¶
- class flowsemantics.PortableRule(rule_id: str, kind: str, condition: PExpr | None = None, guard: PExpr | None = None, transform: PExpr | None = None, priority: int = 0, effective_from: str | None = None, effective_until: str | None = None, effects: tuple[dict[str, Any], ...] = ())[source]¶
Bases:
objectOne rule in the Portable IR (SPEC 14.2).
- rule_id: str¶
- kind: str¶
- priority: int = 0¶
- effective_from: str | None = None¶
- effective_until: str | None = None¶
- effects: tuple[dict[str, Any], ...] = ()¶
- class flowsemantics.RecoveryInfo(original_exception: BaseException, handler_rule_id: str, recovered_at: datetime)[source]¶
Bases:
objectException-recovery metadata only (SPEC 3.4, O1).
- original_exception: BaseException¶
- handler_rule_id: str¶
- recovered_at: datetime¶
- __init__(original_exception: BaseException, handler_rule_id: str, recovered_at: datetime) None¶
- exception flowsemantics.ReplayError[source]¶
Bases:
FlowSemanticsErrorRaised when a replay record cannot be safely replayed.
- class flowsemantics.ReplayMode(value)[source]¶
Bases:
StrEnumThe four replay operations (SPEC 12.6).
- SIMULATION = 'simulation'¶
- HISTORICAL = 'historical'¶
- DECISION = 'decision'¶
- EFFECTS = 'effects'¶
- class flowsemantics.ReplayRecord(spec_version: str, contract_version: str, input: Any, clock_wall: datetime, clock_monotonic: float, outcome: FlowOutcome, trace: ExecutionTrace | None = None, effects: tuple[Any, ...] = (), integrity: str | None = None)[source]¶
Bases:
objectA recorded decision tuple (SPEC 12.6, 12.10).
- spec_version¶
SPEC.md version that produced the record.
- Type:
str
- contract_version¶
Structural hash of the FlowContract.
- Type:
str
- input¶
The recorded input (application data; handle per 12.2).
- Type:
Any
- clock_wall¶
Recorded wall-clock value.
- Type:
datetime.datetime
- clock_monotonic¶
Recorded monotonic value.
- Type:
float
- outcome¶
The recorded FlowOutcome.
- trace¶
The recorded trace, if collected.
- Type:
- effects¶
Recorded proposed effects.
- Type:
tuple[Any, …]
- integrity¶
Optional HMAC-SHA256 hex digest (see sign()).
- Type:
str | None
- spec_version: str¶
- contract_version: str¶
- input: Any¶
- clock_wall: datetime¶
- clock_monotonic: float¶
- outcome: FlowOutcome¶
- trace: ExecutionTrace | None = None¶
- effects: tuple[Any, ...] = ()¶
- integrity: str | None = None¶
- __init__(spec_version: str, contract_version: str, input: Any, clock_wall: datetime, clock_monotonic: float, outcome: FlowOutcome, trace: ExecutionTrace | None = None, effects: tuple[Any, ...] = (), integrity: str | None = None) None¶
- class flowsemantics.ReplayResult(mode: ReplayMode, outcome: FlowOutcome | None = None, equivalent: bool | None = None, effects_applied: int = 0)[source]¶
Bases:
objectResult of a replay operation.
- mode: ReplayMode¶
- outcome: FlowOutcome | None = None¶
- equivalent: bool | None = None¶
- effects_applied: int = 0¶
- __init__(mode: ReplayMode, outcome: FlowOutcome | None = None, equivalent: bool | None = None, effects_applied: int = 0) None¶
- class flowsemantics.Rule(id: RuleId, kind: Literal['when', 'when_not', 'then'], condition: Callable[[Any], bool | Awaitable[bool]] | None, guard: Callable[[Any], bool | Awaitable[bool]] | None, action: Callable[[...], Any], priority: int = 0, effective_from: datetime | None = None, effective_until: datetime | None = None, effects: tuple[Effect, ...] = ())[source]¶
Bases:
objectOne rule in a flow: identity, kind, condition, guard, action.
kind is “when” (match on true), “when_not” (match on false), or “then” (sequential stage; condition is None and action receives (input, previous_output)).
- kind: Literal['when', 'when_not', 'then']¶
- condition: Callable[[Any], bool | Awaitable[bool]] | None¶
- guard: Callable[[Any], bool | Awaitable[bool]] | None¶
- action: Callable[[...], Any]¶
- priority: int = 0¶
- effective_from: datetime | None = None¶
- effective_until: datetime | None = None¶
- __init__(id: RuleId, kind: Literal['when', 'when_not', 'then'], condition: Callable[[Any], bool | Awaitable[bool]] | None, guard: Callable[[Any], bool | Awaitable[bool]] | None, action: Callable[[...], Any], priority: int = 0, effective_from: datetime | None = None, effective_until: datetime | None = None, effects: tuple[Effect, ...] = ()) None¶
- class flowsemantics.RuleId(value: str)[source]¶
Bases:
objectStable, readonly rule identity with implicit string conversion.
Feature 8 of the v5 baseline. The value is validated non-empty at construction; compile() additionally enforces uniqueness (SPEC 4.3).
- value: str¶
- __init__(value: str) None¶
- class flowsemantics.ShadowEntry(index: int, input: Any, current: FlowOutcome, candidate: FlowOutcome, differs: bool, differing_fields: tuple[str, ...])[source]¶
Bases:
objectOne input’s current-vs-candidate comparison.
- index: int¶
- input: Any¶
- current: FlowOutcome¶
- candidate: FlowOutcome¶
- differs: bool¶
- differing_fields: tuple[str, ...]¶
- __init__(index: int, input: Any, current: FlowOutcome, candidate: FlowOutcome, differs: bool, differing_fields: tuple[str, ...]) None¶
- class flowsemantics.ShadowReport(entries: tuple[ShadowEntry, ...], total: int, differences: int)[source]¶
Bases:
objectAggregate shadow comparison report (SPEC 12.7).
- entries: tuple[ShadowEntry, ...]¶
- total: int¶
- differences: int¶
- __init__(entries: tuple[ShadowEntry, ...], total: int, differences: int) None¶
- exception flowsemantics.StructureError[source]¶
Bases:
FlowSemanticsErrorRaised by compile() when the flow structure is invalid (SPEC 4.3).
- class flowsemantics.SystemClock[source]¶
Bases:
objectDefault clock reading the host’s real clocks (SPEC.md section 6.3).
This is the only Core component permitted to read ambient time. It is replaceable: pass any Clock implementation via Flow.with_clock() or the execute() clock parameter. Deterministic replay and tests MUST use FakeClock instead.
- class flowsemantics.TraceEvent(type: str, rule_id: str | None = None, timestamp: datetime | None = None, reason: str | None = None, contract_version: str | None = None, diagnostics: dict[str, Any] | None = None)[source]¶
Bases:
objectA single trace event (SPEC 3.8).
- type: str¶
- rule_id: str | None = None¶
- timestamp: datetime | None = None¶
- reason: str | None = None¶
- contract_version: str | None = None¶
- diagnostics: dict[str, Any] | None = None¶
- __init__(type: str, rule_id: str | None = None, timestamp: datetime | None = None, reason: str | None = None, contract_version: str | None = None, diagnostics: dict[str, Any] | None = None) None¶
- class flowsemantics.TraceRecorder(contract_version: str, diagnostic_hook: Callable[[TraceEvent], dict[str, Any] | None] | None = None)[source]¶
Bases:
objectCollects trace events during one execution (SPEC 12.1, 12.3).
Created only when tracing is enabled; when disabled, no recorder exists and evaluation pays zero tracing cost.
- __init__(contract_version: str, diagnostic_hook: Callable[[TraceEvent], dict[str, Any] | None] | None = None) None[source]¶
Create an empty recorder for the given contract version.
diagnostic_hook is the application-supplied redaction-aware hook (SPEC 12.2): it receives each event and may return a dict of additional diagnostic fields. The library defers entirely to the application’s policy; absent a hook, no diagnostic data is added.
- emit(event_type: str, *, rule_id: str | None = None, timestamp: datetime | None = None, reason: str | None = None) None[source]¶
Append an event. Validates type and reason against the closed sets.
- build() ExecutionTrace[source]¶
Produce the immutable ExecutionTrace.
- class flowsemantics.ValidationIssue(severity: str, code: str, message: str, rule_id: str | None = None)[source]¶
Bases:
objectA static-analysis finding (SPEC 12.8).
severity “error” blocks compilation; “warning” should be investigated but does not block.
- severity: str¶
- code: str¶
- message: str¶
- rule_id: str | None = None¶
- __init__(severity: str, code: str, message: str, rule_id: str | None = None) None¶
- flowsemantics.eval_expr(expr: PExpr, input: Any) Any[source]¶
Evaluate a portable expression against the input (SPEC 14.2).
Field access requires the input to be a mapping; anything else raises StructureError at evaluation time.
- flowsemantics.expr_from_dict(data: dict[str, Any], _depth: int = 0) PExpr[source]¶
Deserialize a PExpr from its dict form.
Rejects nesting deeper than MAX_EXPR_DEPTH (SPEC 9.2).
- flowsemantics.expr_to_dict(expr: PExpr) dict[str, Any][source]¶
Serialize a PExpr to a JSON-safe dict.
- flowsemantics.record(contract: FlowContract, input: Any, *, clock: Any | None = None) ReplayRecord[source]¶
Execute with tracing and capture a ReplayRecord (SPEC 12.6).
- flowsemantics.replay(record: ReplayRecord, contract: FlowContract, *, mode: ReplayMode = ReplayMode.SIMULATION, integrity_key: bytes | None = None, effect_executor: Any | None = None, authorize_effects: bool = False) ReplayResult[source]¶
Replay a recorded decision (SPEC 12.6).
- Parameters:
record – The recorded tuple.
contract – The current FlowContract to replay against.
mode – One of the four replay operations.
integrity_key – HMAC key when the record is integrity-tagged.
effect_executor – Callable(Effect) for EFFECTS mode only.
authorize_effects – Must be True for EFFECTS mode; never default.
- flowsemantics.shadow(current: FlowContract, candidate: FlowContract, inputs: Iterable[Any], *, clock: Clock | None = None) ShadowReport[source]¶
Compare a candidate flow against the current flow (SPEC 12.7).
Both flows are simulated (no effects, no hooks, no finalizers).
- flowsemantics.sign(record: ReplayRecord, key: bytes) ReplayRecord[source]¶
Return a copy of the record with an HMAC-SHA256 integrity tag.
- flowsemantics.table_to_flow(table: DecisionTable) Flow[source]¶
Compile a DecisionTable into a Flow builder (SPEC 10.8).
The resulting flow is equivalent to one built with the fluent API: each row becomes a when rule whose condition is the conjunction of the row’s column predicates.