flowsemantics.configuration package¶
Submodules¶
flowsemantics.configuration.catch module¶
flowsemantics.configuration.catch - CatchRule (SPEC.md sections 11.1-11.4).
Layer: Composition Module: flowsemantics.configuration.catch Since: 0.2.0 Implements: SPEC.md sections 11.1 (catch), 11.2 (catch_when),
11.3 (catch_any), 11.4 (rethrow)
Depends on: stdlib only Used by: Flow builder, FlowContract, exception router See also: SPEC.md section 11, section 7.3.1
Notes
Catch evaluation is ordered: the first matching catch wins.
catch_any MUST be registered after all typed catch/catch_when rules; compile() enforces this (SPEC 11.3, 4.3).
rethrow stops catch evaluation and propagates the current exception.
- class flowsemantics.configuration.catch.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¶
flowsemantics.configuration.finalization module¶
flowsemantics.configuration.finalization - FinallyContext and policies.
Layer: Composition Module: flowsemantics.configuration.finalization Since: 0.2.0 Implements: SPEC.md sections 11.8, 16.4, 16.7 Depends on: flowsemantics.execution.outcome, stdlib only Used by: Flow.finally_, FlowContract, finalization engine See also: SPEC.md sections 11.8, 16.4, 16.7
Notes
Exactly three failure policies exist (SPEC 11.8.3): PreservePrimary (default), Attach, ReplacePrimary. No others.
is_clean is orthogonal to policy: false iff any finalizer raised, was cancelled, or exceeded its budget (SPEC 11.8.3, 3.5).
- class flowsemantics.configuration.finalization.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.configuration.finalization.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¶
flowsemantics.configuration.flow module¶
flowsemantics.configuration.flow - Flow builder and FlowContract.
Layer: Composition Module: flowsemantics.configuration.flow Since: 0.1.0 Implements: SPEC.md sections 4.1 (two-stage lifecycle), 10.1-10.6, 10.9 Depends on: flowsemantics.configuration.rule, flowsemantics.errors,
flowsemantics.execution.{clock,context,outcome}
Used by: consumers, conformance runner, samples See also: SPEC.md section 10
Notes
Flow is the mutable construction-stage builder. It MUST NOT execute any condition, transformation, or effect during construction (SPEC 4.1.1).
FlowContract is the immutable execution-stage artifact produced by compile(). It is reusable and safe to share across concurrent invocations; user callbacks are NOT guaranteed thread-safe (SPEC 4.2).
Implemented here: when, when_not, then, otherwise, default/default_if_no_match, EvaluationMode (all three modes), compile(), execute(), try_execute(). Merge, DecisionTable, catch rules, finalizers, hooks, trace, and portability export arrive in their own sub-phases.
SPEC.md v0.1 does not define how a rule declares REJECTED polarity; a matched rule therefore yields APPROVED. REJECTED arrives with the API that defines it (tracked as a spec gap, not silently invented).
- class flowsemantics.configuration.flow.EvaluationMode(value)[source]¶
Bases:
StrEnumMultiple-match behavior. Exactly three members (SPEC 10.6).
- FIRST_MATCH = 'FirstMatch'¶
- ALL_MATCH = 'AllMatch'¶
- PRIORITY = 'Priority'¶
- class flowsemantics.configuration.flow.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¶
- class flowsemantics.configuration.flow.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.configuration.flow.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.configuration.flow.FlowPortability(value)[source]¶
Bases:
StrEnumWhole-contract portability classification (SPEC 4.4, feature 47).
- PORTABLE = 'portable'¶
- NATIVE = 'native'¶
- class flowsemantics.configuration.flow.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.configuration.portable module¶
flowsemantics.configuration.portable - Portable IR and expression subset.
Layer: Composition Module: flowsemantics.configuration.portable Since: 0.4.0 Implements: SPEC.md section 14.2 (Portable IR), 5.1 (pure conditions) Depends on: stdlib only Used by: Flow.when_expr, FlowContract.to_ir/from_ir, conformance See also: SPEC.md sections 14.2, 5.1
Notes
The portable expression subset is deliberately small and inspectable (SPEC 14.2): named field access, six comparisons, and/or/not, is-null/is-not-null, in/not-in. Nothing else.
The IR MUST NOT carry host-language lambdas, serialized code, or host types outside the subset.
Schema: spec/ir.schema.json.
- class flowsemantics.configuration.portable.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¶
- class flowsemantics.configuration.portable.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.configuration.portable.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], ...] = ()¶
- flowsemantics.configuration.portable.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.configuration.portable.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.configuration.portable.expr_to_dict(expr: PExpr) dict[str, Any][source]¶
Serialize a PExpr to a JSON-safe dict.
- flowsemantics.configuration.portable.pand(*args: PExpr) PExpr[source]¶
Boolean AND over all arguments.
- flowsemantics.configuration.portable.pfield(name: str) PExpr[source]¶
Named field access (read-only).
- flowsemantics.configuration.portable.pge(a: PExpr, b: PExpr) PExpr[source]¶
Greater-than-or-equal comparison.
- flowsemantics.configuration.portable.pgt(a: PExpr, b: PExpr) PExpr[source]¶
Greater-than comparison.
- flowsemantics.configuration.portable.pin(a: PExpr, values: list[Any]) PExpr[source]¶
Enum membership (in).
- flowsemantics.configuration.portable.ple(a: PExpr, b: PExpr) PExpr[source]¶
Less-than-or-equal comparison.
flowsemantics.configuration.rule module¶
flowsemantics.configuration.rule - RuleId and Rule (SPEC.md sections 2.1, 10.1).
Layer: Composition Module: flowsemantics.configuration.rule Since: 0.1.0 Implements: SPEC.md section 10.1 (rule is a 4-tuple plus identity) Depends on: stdlib only Used by: Flow builder, FlowContract, conformance runner See also: SPEC.md section 10
Notes
RuleId is readonly and has implicit string conversion via __str__.
A Rule is immutable once registered: the builder stores it in a tuple inside the compiled FlowContract.
- class flowsemantics.configuration.rule.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¶
- class flowsemantics.configuration.rule.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.configuration.rule.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¶
flowsemantics.configuration.table module¶
flowsemantics.configuration.table - DecisionTable (SPEC.md section 10.8).
Layer: Composition Module: flowsemantics.configuration.table Since: 0.1.0 Implements: SPEC.md section 10.8 (column-based, DMN-aligned hit policies) Depends on: flowsemantics.configuration.{flow,rule}, stdlib only Used by: Flow.from_table, consumers authoring rules as tables See also: SPEC.md section 10.8
Notes
A decision table compiles to the same rule list as the fluent API.
Hit policies map to EvaluationMode: FIRST->FirstMatch, COLLECT->AllMatch, PRIORITY->Priority, UNIQUE->FirstMatch plus a compile-time exclusivity check where statically provable.
For opaque callables, UNIQUE exclusivity cannot be proven; the table records a validation warning rather than claiming a guarantee (SPEC 10.8).
- class flowsemantics.configuration.table.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.configuration.table.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¶
- flowsemantics.configuration.table.HitPolicy¶
alias of
str
- flowsemantics.configuration.table.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.
Module contents¶
flowsemantics.configuration - Flow builder, options, registry.
Layer: Composition Module: flowsemantics.configuration Since: 0.0.0 Implements: SPEC.md sections 4.1, 10 Depends on: flowsemantics.configuration.{rule,flow}, flowsemantics.errors,
flowsemantics.execution
Used by: parent package; populated from Phase 1.0 See also: SPEC.md section 10
Notes
__all__ grows as features are implemented. Currently exports the decision-layer primitives (Flow, FlowContract, Rule, RuleId, EvaluationMode, Fallback, FlowPortability).
- class flowsemantics.configuration.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.configuration.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.configuration.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.configuration.EvaluationMode(value)[source]¶
Bases:
StrEnumMultiple-match behavior. Exactly three members (SPEC 10.6).
- FIRST_MATCH = 'FirstMatch'¶
- ALL_MATCH = 'AllMatch'¶
- PRIORITY = 'Priority'¶
- class flowsemantics.configuration.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¶
- class flowsemantics.configuration.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.configuration.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.configuration.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.configuration.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.configuration.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.configuration.FlowPortability(value)[source]¶
Bases:
StrEnumWhole-contract portability classification (SPEC 4.4, feature 47).
- PORTABLE = 'portable'¶
- NATIVE = 'native'¶
- class flowsemantics.configuration.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¶
- class flowsemantics.configuration.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.configuration.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.configuration.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.configuration.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.configuration.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.configuration.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.configuration.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.configuration.expr_to_dict(expr: PExpr) dict[str, Any][source]¶
Serialize a PExpr to a JSON-safe dict.
- flowsemantics.configuration.pge(a: PExpr, b: PExpr) PExpr[source]¶
Greater-than-or-equal comparison.
- flowsemantics.configuration.pnot_in(a: PExpr, values: list[Any]) PExpr[source]¶
Enum non-membership (not in).
- flowsemantics.configuration.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.