flow-semantics 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1952 @@
1
+ """flowsemantics.configuration.flow - Flow builder and FlowContract.
2
+
3
+ Layer: Composition
4
+ Module: flowsemantics.configuration.flow
5
+ Since: 0.1.0
6
+ Implements: SPEC.md sections 4.1 (two-stage lifecycle), 10.1-10.6, 10.9
7
+ Depends on: flowsemantics.configuration.rule, flowsemantics.errors,
8
+ flowsemantics.execution.{clock,context,outcome}
9
+ Used by: consumers, conformance runner, samples
10
+ See also: SPEC.md section 10
11
+
12
+ Notes:
13
+ - Flow is the mutable construction-stage builder. It MUST NOT execute any
14
+ condition, transformation, or effect during construction (SPEC 4.1.1).
15
+ - FlowContract is the immutable execution-stage artifact produced by
16
+ compile(). It is reusable and safe to share across concurrent
17
+ invocations; user callbacks are NOT guaranteed thread-safe (SPEC 4.2).
18
+ - Implemented here: when, when_not, then, otherwise,
19
+ default/default_if_no_match, EvaluationMode (all three modes),
20
+ compile(), execute(), try_execute(). Merge, DecisionTable, catch
21
+ rules, finalizers, hooks, trace, and portability export arrive in
22
+ their own sub-phases.
23
+ - SPEC.md v0.1 does not define how a rule declares REJECTED polarity;
24
+ a matched rule therefore yields APPROVED. REJECTED arrives with the
25
+ API that defines it (tracked as a spec gap, not silently invented).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import asyncio
31
+ import datetime
32
+ import hashlib
33
+ import inspect
34
+ import json
35
+ from collections.abc import Callable, Iterable
36
+ from dataclasses import dataclass, field, replace
37
+ from enum import StrEnum
38
+ from typing import Any, cast
39
+
40
+ from flowsemantics._spec import SPEC_VERSION
41
+ from flowsemantics.configuration.catch import (
42
+ CatchRule,
43
+ ExceptionHandler,
44
+ ExceptionPredicate,
45
+ )
46
+ from flowsemantics.configuration.finalization import (
47
+ FinallyCancellationToken,
48
+ FinallyContext,
49
+ FinallyFailurePolicy,
50
+ )
51
+ from flowsemantics.configuration.portable import (
52
+ PExpr,
53
+ PortableFlow,
54
+ PortableRule,
55
+ _parse_dt,
56
+ eval_expr,
57
+ )
58
+ from flowsemantics.configuration.rule import (
59
+ ActionFn,
60
+ ConditionFn,
61
+ GuardFn,
62
+ Rule,
63
+ RuleId,
64
+ RuleKind,
65
+ )
66
+ from flowsemantics.errors import (
67
+ AsyncOnlyContractError,
68
+ PortabilityError,
69
+ StructureError,
70
+ )
71
+ from flowsemantics.execution.clock import Clock, SystemClock
72
+ from flowsemantics.execution.context import FlowContext
73
+ from flowsemantics.execution.outcome import (
74
+ DecisionStatus,
75
+ Effect,
76
+ ExecutionStatus,
77
+ FinalizationInfo,
78
+ FlowOutcome,
79
+ InterruptionInfo,
80
+ RecoveryInfo,
81
+ )
82
+ from flowsemantics.execution.trace import ExecutionTrace, TraceRecorder
83
+
84
+
85
+ class EvaluationMode(StrEnum):
86
+ """Multiple-match behavior. Exactly three members (SPEC 10.6)."""
87
+
88
+ FIRST_MATCH = "FirstMatch"
89
+ ALL_MATCH = "AllMatch"
90
+ PRIORITY = "Priority"
91
+
92
+
93
+ class FlowPortability(StrEnum):
94
+ """Whole-contract portability classification (SPEC 4.4, feature 47)."""
95
+
96
+ PORTABLE = "portable"
97
+ NATIVE = "native"
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class Fallback:
102
+ """No-match fallback configuration (SPEC 10.4)."""
103
+
104
+ kind: str # "otherwise" | "default_if_no_match"
105
+ action: ActionFn | None = None
106
+ value: Any = None
107
+
108
+
109
+ class Flow:
110
+ """Mutable builder for a flow. Construction performs no execution."""
111
+
112
+ def __init__(self) -> None:
113
+ """Create an empty flow builder in FirstMatch mode."""
114
+ self._rules: list[Rule] = []
115
+ self._fallback: Fallback | None = None
116
+ self._mode: EvaluationMode = EvaluationMode.FIRST_MATCH
117
+ self._clock: Clock | None = None
118
+ self._catches: list[CatchRule] = []
119
+ self._hooks: list[Callable[[Any, str, Any], Any]] = []
120
+ self._finalizers: list[Callable[[FinallyContext], None]] = []
121
+ self._finally_policy: FinallyFailurePolicy = FinallyFailurePolicy.PRESERVE_PRIMARY
122
+ self._finally_timeout_ms: int | None = None
123
+ self._trace_enabled: bool = False
124
+ self._trace_hook: Callable[[Any], dict[str, Any] | None] | None = None
125
+ self._portable_rules: list[PortableRule] = []
126
+ self._flow_id: str = ""
127
+ self._cancel_check: Callable[[], bool] | None = None
128
+
129
+ # -- rule registration -------------------------------------------------
130
+
131
+ def when(
132
+ self,
133
+ condition: ConditionFn,
134
+ *,
135
+ then: ActionFn,
136
+ id: str | RuleId,
137
+ guard: GuardFn | None = None,
138
+ priority: int = 0,
139
+ effective_from: datetime.datetime | None = None,
140
+ effective_until: datetime.datetime | None = None,
141
+ effects: Iterable[Effect] = (),
142
+ ) -> Flow:
143
+ """Register a positive condition rule (SPEC 10.2, 12.9).
144
+
145
+ effects are proposed (never applied) in evaluation order when the
146
+ rule matches (SPEC 5, 6.4, 14.2).
147
+ """
148
+ self._rules.append(
149
+ Rule(
150
+ id=self._coerce_id(id),
151
+ kind="when",
152
+ condition=condition,
153
+ guard=guard,
154
+ action=then,
155
+ priority=priority,
156
+ effective_from=effective_from,
157
+ effective_until=effective_until,
158
+ effects=tuple(effects),
159
+ )
160
+ )
161
+ return self
162
+
163
+ def when_not(
164
+ self,
165
+ condition: ConditionFn,
166
+ *,
167
+ then: ActionFn,
168
+ id: str | RuleId,
169
+ guard: GuardFn | None = None,
170
+ priority: int = 0,
171
+ effective_from: datetime.datetime | None = None,
172
+ effective_until: datetime.datetime | None = None,
173
+ effects: Iterable[Effect] = (),
174
+ ) -> Flow:
175
+ """Register a negative condition rule (SPEC 10.2, 12.9)."""
176
+ self._rules.append(
177
+ Rule(
178
+ id=self._coerce_id(id),
179
+ kind="when_not",
180
+ condition=condition,
181
+ guard=guard,
182
+ action=then,
183
+ priority=priority,
184
+ effective_from=effective_from,
185
+ effective_until=effective_until,
186
+ effects=tuple(effects),
187
+ )
188
+ )
189
+ return self
190
+
191
+ def when_expr(
192
+ self,
193
+ condition: PExpr,
194
+ *,
195
+ then: PExpr,
196
+ id: str | RuleId,
197
+ guard: PExpr | None = None,
198
+ priority: int = 0,
199
+ effective_from: datetime.datetime | None = None,
200
+ effective_until: datetime.datetime | None = None,
201
+ effects: Iterable[Effect] = (),
202
+ ) -> Flow:
203
+ """Register a portable rule (SPEC 14.2).
204
+
205
+ Condition, guard, and transform are declarative expressions from
206
+ the portable subset; no host lambdas are involved. Effects are
207
+ proposed data carried in the IR (SPEC 14.2).
208
+ """
209
+ self._portable_rules.append(
210
+ PortableRule(
211
+ rule_id=str(self._coerce_id(id)),
212
+ kind="when",
213
+ condition=condition,
214
+ guard=guard,
215
+ transform=then,
216
+ priority=priority,
217
+ effective_from=(effective_from.isoformat() if effective_from else None),
218
+ effective_until=(effective_until.isoformat() if effective_until else None),
219
+ effects=tuple({"name": e.name, "payload": e.payload} for e in effects),
220
+ )
221
+ )
222
+ return self
223
+
224
+ def when_not_expr(
225
+ self,
226
+ condition: PExpr,
227
+ *,
228
+ then: PExpr,
229
+ id: str | RuleId,
230
+ guard: PExpr | None = None,
231
+ priority: int = 0,
232
+ effective_from: datetime.datetime | None = None,
233
+ effective_until: datetime.datetime | None = None,
234
+ effects: Iterable[Effect] = (),
235
+ ) -> Flow:
236
+ """Register a negated portable rule (SPEC 14.2)."""
237
+ self._portable_rules.append(
238
+ PortableRule(
239
+ rule_id=str(self._coerce_id(id)),
240
+ kind="when_not",
241
+ condition=condition,
242
+ guard=guard,
243
+ transform=then,
244
+ priority=priority,
245
+ effective_from=(effective_from.isoformat() if effective_from else None),
246
+ effective_until=(effective_until.isoformat() if effective_until else None),
247
+ effects=tuple({"name": e.name, "payload": e.payload} for e in effects),
248
+ )
249
+ )
250
+ return self
251
+
252
+ def with_flow_id(self, flow_id: str) -> Flow:
253
+ """Set the flow identifier carried in the Portable IR (SPEC 14.2)."""
254
+ self._flow_id = flow_id
255
+ return self
256
+
257
+ @classmethod
258
+ def from_ir(cls, data: dict[str, Any] | str) -> Flow:
259
+ """Build a Flow from a Portable IR document (SPEC 14.2).
260
+
261
+ Accepts a dict or JSON string produced by PortableFlow.to_dict/
262
+ to_json. Only when/when_not rules with declarative expressions
263
+ are supported; 'then' stages and dynamic fallbacks are rejected.
264
+ """
265
+ ir = PortableFlow.from_json(data) if isinstance(data, str) else PortableFlow.from_dict(data)
266
+ if ir.portability != "PORTABLE":
267
+ raise StructureError("IR portability must be PORTABLE")
268
+ flow = cls().with_flow_id(ir.flow_id).with_mode(ir.mode)
269
+ for r in ir.rules:
270
+ if r.kind not in ("when", "when_not"):
271
+ raise StructureError(f"portable IR kind {r.kind!r} not supported in from_ir")
272
+ if r.condition is None or r.transform is None:
273
+ raise StructureError("portable rule requires condition+transform")
274
+ method = flow.when_expr if r.kind == "when" else flow.when_not_expr
275
+ method(
276
+ r.condition,
277
+ then=r.transform,
278
+ id=r.rule_id,
279
+ guard=r.guard,
280
+ priority=r.priority,
281
+ effective_from=_parse_dt(r.effective_from),
282
+ effective_until=_parse_dt(r.effective_until),
283
+ effects=tuple(Effect(name=e["name"], payload=e.get("payload")) for e in r.effects),
284
+ )
285
+ if ir.fallback is not None:
286
+ fb = ir.fallback
287
+ if fb.get("kind") == "default_if_no_match":
288
+ flow.default(fb.get("value"))
289
+ elif fb.get("kind") == "otherwise" and "value" in fb:
290
+ flow.default(fb["value"])
291
+ else:
292
+ raise StructureError(f"unsupported portable fallback kind: {fb.get('kind')!r}")
293
+ return flow
294
+
295
+ def then(
296
+ self,
297
+ stage: Callable[[Any, Any], Any],
298
+ *,
299
+ id: str | RuleId,
300
+ effects: Iterable[Effect] = (),
301
+ ) -> Flow:
302
+ """Register a sequential stage (SPEC 10.5).
303
+
304
+ The stage receives (input, previous_output) and runs only when the
305
+ preceding rule matched. It cannot be the first element of a flow;
306
+ compile() enforces that.
307
+ """
308
+ self._rules.append(
309
+ Rule(
310
+ id=self._coerce_id(id),
311
+ kind="then",
312
+ condition=None,
313
+ guard=None,
314
+ action=stage,
315
+ effects=tuple(effects),
316
+ )
317
+ )
318
+ return self
319
+
320
+ # -- fallbacks ---------------------------------------------------------
321
+
322
+ def otherwise(self, action: ActionFn) -> Flow:
323
+ """Register a dynamic no-match fallback (SPEC 10.4)."""
324
+ self._set_fallback(Fallback(kind="otherwise", action=action))
325
+ return self
326
+
327
+ def default_if_no_match(self, value: Any) -> Flow:
328
+ """Register a constant no-match fallback (SPEC 10.4)."""
329
+ self._set_fallback(Fallback(kind="default_if_no_match", value=value))
330
+ return self
331
+
332
+ def default(self, value: Any) -> Flow:
333
+ """Alias of default_if_no_match (SPEC 10.4)."""
334
+ return self.default_if_no_match(value)
335
+
336
+ # -- exception handling (SPEC 11.1-11.4) ---------------------------------
337
+
338
+ def catch(
339
+ self,
340
+ exc_type: type[Exception],
341
+ handler: ExceptionHandler,
342
+ *,
343
+ id: str | None = None,
344
+ ) -> Flow:
345
+ """Register a typed exception handler (SPEC 11.1).
346
+
347
+ The handler receives (input, exception) and returns the outcome
348
+ value. Matching follows host-language inheritance: a handler for a
349
+ base type catches subclasses.
350
+ """
351
+ self._catches.append(CatchRule(kind="typed", exc_type=exc_type, handler=handler, id=id))
352
+ return self
353
+
354
+ def catch_when(
355
+ self,
356
+ exc_type: type[Exception],
357
+ predicate: ExceptionPredicate,
358
+ handler: ExceptionHandler,
359
+ *,
360
+ id: str | None = None,
361
+ ) -> Flow:
362
+ """Register a typed handler with a predicate (SPEC 11.2).
363
+
364
+ The predicate receives (input, exception) and is evaluated only
365
+ after the type check passes.
366
+ """
367
+ self._catches.append(
368
+ CatchRule(
369
+ kind="when",
370
+ exc_type=exc_type,
371
+ predicate=predicate,
372
+ handler=handler,
373
+ id=id,
374
+ )
375
+ )
376
+ return self
377
+
378
+ def catch_any(self, handler: ExceptionHandler, *, id: str | None = None) -> Flow:
379
+ """Register a broad handler for otherwise-uncaught exceptions (SPEC 11.3).
380
+
381
+ MUST be registered after all typed catch/catch_when rules;
382
+ compile() enforces the ordering.
383
+ """
384
+ self._catches.append(CatchRule(kind="any", handler=handler, id=id))
385
+ return self
386
+
387
+ def rethrow(self) -> Flow:
388
+ """Register explicit propagation of the current exception (SPEC 11.4)."""
389
+ self._catches.append(CatchRule(kind="rethrow"))
390
+ return self
391
+
392
+ def on_match(self, hook: Callable[[Any, str, Any], Any]) -> Flow:
393
+ """Register an observable hook (SPEC 11.5).
394
+
395
+ The hook receives (input, RuleId, value) after a when/when_not
396
+ rule's action produces its value. Hook failures are isolated into
397
+ secondary_exceptions and never trigger catch rules.
398
+ """
399
+ self._hooks.append(hook)
400
+ return self
401
+
402
+ def finally_(self, cleanup: Callable[[FinallyContext], None]) -> Flow:
403
+ """Register a finalizer that runs after primary execution (SPEC 11.8).
404
+
405
+ The finalizer receives a FinallyContext and runs for every outcome
406
+ status, including CANCELLED and TIMED_OUT. Finalizers run in LIFO
407
+ order and are isolated: a failure in one does not skip the rest.
408
+ """
409
+ self._finalizers.append(cleanup)
410
+ return self
411
+
412
+ def finally_async(self, cleanup: Callable[[FinallyContext], Any]) -> Flow:
413
+ """Register an asynchronous finalizer (SPEC 11.8, 16.7).
414
+
415
+ A flow with async finalizers is async-only: every finalizer must
416
+ be async, and the contract can only run via execute_async()
417
+ (SPEC 11.7, FR8).
418
+ """
419
+ self._finalizers.append(cleanup)
420
+ return self
421
+
422
+ def with_finally_policy(self, policy: FinallyFailurePolicy | str) -> Flow:
423
+ """Set the finally failure policy (SPEC 11.8.3, 16.4)."""
424
+ self._finally_policy = FinallyFailurePolicy(policy)
425
+ return self
426
+
427
+ def with_finally_timeout(self, ms: int) -> Flow:
428
+ """Bound each finalizer's budget in milliseconds (SPEC 16.7)."""
429
+ if ms < 1:
430
+ raise StructureError("finally timeout must be >= 1ms (SPEC 16.7)")
431
+ self._finally_timeout_ms = ms
432
+ return self
433
+
434
+ def with_trace(
435
+ self,
436
+ diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None,
437
+ ) -> Flow:
438
+ """Enable tracing for executions of this flow (SPEC 12.3, 12.2).
439
+
440
+ diagnostic_hook is the application-supplied redaction-aware hook:
441
+ it receives each TraceEvent and may return extra diagnostic fields.
442
+ """
443
+ self._trace_enabled = True
444
+ self._trace_hook = diagnostic_hook
445
+ return self
446
+
447
+ # -- configuration -----------------------------------------------------
448
+
449
+ def with_cancel_check(self, check: Callable[[], bool]) -> Flow:
450
+ """Register a cooperative cancellation predicate (SPEC 11.6).
451
+
452
+ The predicate is polled before each rule evaluation; when it
453
+ returns True the contract produces a CANCELLED outcome via an
454
+ interruption, bypassing catch rules entirely.
455
+ """
456
+ self._cancel_check = check
457
+ return self
458
+
459
+ def with_mode(self, mode: EvaluationMode | str) -> Flow:
460
+ """Set the evaluation mode (SPEC 10.6)."""
461
+ self._mode = EvaluationMode(mode)
462
+ return self
463
+
464
+ def with_clock(self, clock: Clock) -> Flow:
465
+ """Inject a deterministic clock (SPEC 6.2)."""
466
+ self._clock = clock
467
+ return self
468
+
469
+ def merge(self, other: Flow | FlowContract) -> Flow:
470
+ """Splice another flow's rules and fallback at the call site (SPEC 10.7).
471
+
472
+ Rules:
473
+ - Both flows MUST share the same EvaluationMode; mismatch raises
474
+ StructureError.
475
+ - RuleIds MUST be unique across the combined flow.
476
+ - If both flows have a fallback, the outer (self) fallback wins
477
+ and the inner fallback is discarded.
478
+ - Catch scoping and LIFO finalizer ordering complete in Phase 2.5.
479
+ """
480
+ other_catches: list[CatchRule]
481
+ other_finalizers: list[Callable[[FinallyContext], None]]
482
+ if isinstance(other, FlowContract):
483
+ other_rules = list(other.rules)
484
+ other_fallback = other.fallback
485
+ other_mode = other.mode
486
+ other_catches = list(other.catches)
487
+ other_finalizers = list(other.finalizers)
488
+ else:
489
+ other_rules = list(other._rules)
490
+ other_fallback = other._fallback
491
+ other_mode = other._mode
492
+ other_catches = list(other._catches)
493
+ other_finalizers = list(other._finalizers)
494
+
495
+ if other_mode is not self._mode:
496
+ raise StructureError(
497
+ f"cannot merge flows with different EvaluationMode: "
498
+ f"{self._mode} vs {other_mode} (SPEC 10.7)"
499
+ )
500
+
501
+ existing = {str(rule.id) for rule in self._rules}
502
+ for rule in other_rules:
503
+ if str(rule.id) in existing:
504
+ raise StructureError(f"merge would produce duplicate RuleId: {rule.id} (SPEC 10.7)")
505
+ existing.add(str(rule.id))
506
+
507
+ self._rules.extend(other_rules)
508
+ self._catches.extend(other_catches)
509
+ self._finalizers.extend(other_finalizers)
510
+ if self._fallback is None and other_fallback is not None:
511
+ self._fallback = other_fallback
512
+ return self
513
+
514
+ # -- compilation -------------------------------------------------------
515
+
516
+ def compile(self) -> FlowContract:
517
+ """Validate and produce an immutable FlowContract (SPEC 10.9)."""
518
+ if self._portable_rules and self._rules:
519
+ raise StructureError(
520
+ "cannot mix portable (when_expr) and native (when) rules "
521
+ "in one flow; a contract is either PORTABLE or NATIVE"
522
+ )
523
+ portable_ir: PortableFlow | None = None
524
+ portability = FlowPortability.NATIVE
525
+ if self._portable_rules:
526
+ rules = self._compile_portable_rules()
527
+ # The IR carries rules, mode, fallback, and dates only
528
+ # (SPEC 14.2). Catches, finalizers, and hooks are not
529
+ # representable, so their presence makes the contract NATIVE
530
+ # (SPEC 4.4, D3) rather than silently dropping them.
531
+ if not (self._catches or self._finalizers or self._hooks):
532
+ portability = FlowPortability.PORTABLE
533
+ portable_ir = self._build_ir()
534
+ else:
535
+ rules = self._normalized_rules()
536
+ self._validate(rules)
537
+ self._validate_finalizer_forms()
538
+ async_only = _compute_async_only(
539
+ rules=rules,
540
+ catches=self._catches,
541
+ hooks=self._hooks,
542
+ finalizers=self._finalizers,
543
+ )
544
+ return FlowContract(
545
+ rules=tuple(rules),
546
+ fallback=self._fallback,
547
+ mode=self._mode,
548
+ clock=self._clock if self._clock is not None else SystemClock(),
549
+ spec_version=SPEC_VERSION,
550
+ portability=portability,
551
+ portable_ir=portable_ir,
552
+ catches=tuple(self._catches),
553
+ hooks=tuple(self._hooks),
554
+ finalizers=tuple(self._finalizers),
555
+ finally_policy=self._finally_policy,
556
+ finally_timeout_ms=self._finally_timeout_ms,
557
+ trace_enabled=self._trace_enabled,
558
+ trace_diagnostic_hook=self._trace_hook,
559
+ async_only=async_only,
560
+ cancel_check=self._cancel_check,
561
+ contract_version=_compute_contract_version(
562
+ rules=rules,
563
+ fallback=self._fallback,
564
+ mode=self._mode,
565
+ catches=self._catches,
566
+ finalizers=self._finalizers,
567
+ finally_policy=self._finally_policy,
568
+ finally_timeout_ms=self._finally_timeout_ms,
569
+ trace_enabled=self._trace_enabled,
570
+ ),
571
+ )
572
+
573
+ def _compile_portable_rules(self) -> list[Rule]:
574
+ """Convert portable rules to executable Rules (SPEC 14.2)."""
575
+ rules: list[Rule] = []
576
+ for pr in self._portable_rules:
577
+ assert pr.condition is not None and pr.transform is not None
578
+ for eff in pr.effects:
579
+ try:
580
+ json.dumps(eff.get("payload"))
581
+ except (TypeError, ValueError) as exc:
582
+ raise StructureError(
583
+ f"portable rule {pr.rule_id}: effect payload must be "
584
+ "JSON-serializable to be carried in the IR (SPEC 14.2)"
585
+ ) from exc
586
+ cond = pr.condition
587
+ guard = pr.guard
588
+ transform = pr.transform
589
+
590
+ # kind="when_not" is negated by the engine (_condition_holds);
591
+ # the compiled condition stays positive.
592
+ def _cond(i: Any, c: PExpr = cond) -> bool:
593
+ return bool(eval_expr(c, i))
594
+
595
+ def _guard_fn(i: Any, g: PExpr | None = guard) -> bool:
596
+ assert g is not None
597
+ return bool(eval_expr(g, i))
598
+
599
+ def _action(i: Any, t: PExpr = transform) -> Any:
600
+ return eval_expr(t, i)
601
+
602
+ rules.append(
603
+ Rule(
604
+ id=RuleId(pr.rule_id),
605
+ kind=cast(RuleKind, pr.kind),
606
+ condition=_cond,
607
+ guard=_guard_fn if guard is not None else None,
608
+ action=_action,
609
+ priority=pr.priority,
610
+ effective_from=_parse_dt(pr.effective_from),
611
+ effective_until=_parse_dt(pr.effective_until),
612
+ effects=tuple(
613
+ Effect(name=e["name"], payload=e.get("payload")) for e in pr.effects
614
+ ),
615
+ )
616
+ )
617
+ return rules
618
+
619
+ def _build_ir(self) -> PortableFlow:
620
+ """Build the PortableFlow IR for this contract (SPEC 14.2)."""
621
+ ir_rules = tuple(self._portable_rules)
622
+ fallback_dict: dict[str, Any] | None = None
623
+ if self._fallback is not None:
624
+ fb = self._fallback
625
+ fallback_dict = {"kind": fb.kind}
626
+ if fb.kind == "default_if_no_match":
627
+ fallback_dict["value"] = fb.value
628
+ return PortableFlow(
629
+ spec_version=SPEC_VERSION,
630
+ flow_id=self._flow_id,
631
+ portability="PORTABLE",
632
+ mode=str(self._mode),
633
+ rules=ir_rules,
634
+ fallback=fallback_dict,
635
+ )
636
+
637
+ def _validate_finalizer_forms(self) -> None:
638
+ """A flow MUST NOT mix sync and async finalizers (SPEC 11.8, FR8)."""
639
+ if not self._finalizers:
640
+ return
641
+ forms = {_is_async_callable(f) for f in self._finalizers}
642
+ if len(forms) > 1:
643
+ raise StructureError(
644
+ "cannot mix synchronous and asynchronous finalizers; "
645
+ "a flow with finally_async must register only async "
646
+ "finalizers (SPEC 11.8, FR8)"
647
+ )
648
+
649
+ def _normalized_rules(self) -> list[Rule]:
650
+ """Return rules with then-stages inheriting the preceding priority."""
651
+ rules = list(self._rules)
652
+ previous_priority = 0
653
+ for index, rule in enumerate(rules):
654
+ if rule.kind == "then":
655
+ rules[index] = replace(rule, priority=previous_priority)
656
+ else:
657
+ previous_priority = rule.priority
658
+ return rules
659
+
660
+ def _validate(self, rules: list[Rule]) -> None:
661
+ seen: set[str] = set()
662
+ for rule in rules:
663
+ key = str(rule.id)
664
+ if key in seen:
665
+ raise StructureError(f"duplicate RuleId: {key!r}")
666
+ seen.add(key)
667
+ if not rules and self._fallback is None:
668
+ raise StructureError(
669
+ "flow has neither rules nor a fallback; at least one is required (SPEC 4.3)"
670
+ )
671
+ for index, rule in enumerate(rules):
672
+ if rule.kind != "then":
673
+ continue
674
+ if index == 0:
675
+ raise StructureError("then cannot be the first element of a flow (SPEC 10.5)")
676
+ if rules[index - 1].kind not in ("when", "when_not", "then"):
677
+ raise StructureError(f"then at index {index} does not follow a rule (SPEC 10.5)")
678
+ for rule in rules:
679
+ if (
680
+ rule.effective_from is not None
681
+ and rule.effective_until is not None
682
+ and rule.effective_from >= rule.effective_until
683
+ ):
684
+ raise StructureError(
685
+ f"rule {rule.id}: effective_from must be before effective_until (SPEC 12.9)"
686
+ )
687
+ self._validate_catches()
688
+
689
+ def _validate_catches(self) -> None:
690
+ """Enforce catch ordering rules (SPEC 11.3, 4.3)."""
691
+ seen_any = False
692
+ for catch in self._catches:
693
+ if catch.kind == "any":
694
+ seen_any = True
695
+ elif seen_any and catch.kind in ("typed", "when"):
696
+ raise StructureError(
697
+ "catch_any MUST be registered after all typed catch "
698
+ "and catch_when rules (SPEC 11.3)"
699
+ )
700
+
701
+ @classmethod
702
+ def from_table(cls, table: Any) -> Flow:
703
+ """Build a Flow from a DecisionTable (SPEC 10.8).
704
+
705
+ Accepts a DecisionTable; compiles each row to an equivalent when
706
+ rule. Hit policy maps to EvaluationMode per SPEC 10.8.
707
+ """
708
+ from flowsemantics.configuration.table import table_to_flow
709
+
710
+ return table_to_flow(table)
711
+
712
+ # -- internals ---------------------------------------------------------
713
+
714
+ @staticmethod
715
+ def _coerce_id(id: str | RuleId) -> RuleId:
716
+ return id if isinstance(id, RuleId) else RuleId(id)
717
+
718
+ def _set_fallback(self, fallback: Fallback) -> None:
719
+ if self._fallback is not None:
720
+ raise StructureError(
721
+ "at most one of otherwise, default, default_if_no_match "
722
+ "may be configured per flow (SPEC 10.4)"
723
+ )
724
+ self._fallback = fallback
725
+
726
+
727
+ @dataclass(frozen=True)
728
+ class FlowContract:
729
+ """Immutable, reusable execution definition produced by compile()."""
730
+
731
+ rules: tuple[Rule, ...]
732
+ fallback: Fallback | None
733
+ mode: EvaluationMode
734
+ clock: Clock
735
+ spec_version: str
736
+ portability: FlowPortability
737
+ catches: tuple[CatchRule, ...] = ()
738
+ hooks: tuple[Callable[[Any, str, Any], Any], ...] = ()
739
+ finalizers: tuple[Callable[[FinallyContext], Any], ...] = ()
740
+ finally_policy: FinallyFailurePolicy = FinallyFailurePolicy.PRESERVE_PRIMARY
741
+ finally_timeout_ms: int | None = None
742
+ trace_enabled: bool = False
743
+ trace_diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None
744
+ portable_ir: PortableFlow | None = None
745
+ async_only: bool = False
746
+ cancel_check: Callable[[], bool] | None = None
747
+ contract_version: str = field(default="1")
748
+
749
+ # -- portable IR (SPEC 14.2) -------------------------------------------
750
+
751
+ def to_ir(self) -> PortableFlow:
752
+ """Export the contract as a PortableFlow IR document.
753
+
754
+ Only PORTABLE contracts carry an IR; NATIVE contracts raise
755
+ PortabilityError (SPEC 4.4, 14.2).
756
+ """
757
+ if self.portable_ir is None:
758
+ raise PortabilityError(
759
+ "contract is NATIVE; only PORTABLE contracts can be "
760
+ "exported to the Portable IR (SPEC 14.2)"
761
+ )
762
+ return replace(self.portable_ir, contract_version=self.contract_version)
763
+
764
+ def to_ir_json(self) -> str:
765
+ """Export the contract as canonical Portable IR JSON."""
766
+ return self.to_ir().to_json()
767
+
768
+ # -- trust layer (SPEC section 12) -------------------------------------
769
+
770
+ def simulate(self, input: Any, *, clock: Clock | None = None) -> FlowOutcome:
771
+ """Evaluate without effects, hooks, or finalizers (SPEC 12.5).
772
+
773
+ Produces the same decision semantics as a real execution for the
774
+ same input and clock, except finalization is not performed and
775
+ on_match hooks are suppressed.
776
+ """
777
+ sim_contract = replace(self, hooks=())
778
+ ctx = FlowContext(input=input, clock=clock if clock is not None else self.clock)
779
+ return sim_contract._primary(ctx, None)
780
+
781
+ def simulate_batch(
782
+ self, inputs: Iterable[Any], *, clock: Clock | None = None
783
+ ) -> dict[str, Any]:
784
+ """Batch simulation with firing distribution (SPEC 12.5).
785
+
786
+ Runs simulate() over each input and aggregates outcomes by
787
+ execution status, decision status, and produced value.
788
+ """
789
+ by_status: dict[str, int] = {}
790
+ by_decision: dict[str, int] = {}
791
+ by_value: dict[str, int] = {}
792
+ outcomes: list[FlowOutcome] = []
793
+ for inp in inputs:
794
+ outcome = self.simulate(inp, clock=clock)
795
+ outcomes.append(outcome)
796
+ by_status[outcome.execution_status.value] = (
797
+ by_status.get(outcome.execution_status.value, 0) + 1
798
+ )
799
+ dkey = outcome.decision_status.value if outcome.decision_status else "null"
800
+ by_decision[dkey] = by_decision.get(dkey, 0) + 1
801
+ vkey = json.dumps(outcome.value, default=str, sort_keys=True)
802
+ by_value[vkey] = by_value.get(vkey, 0) + 1
803
+ return {
804
+ "total": len(outcomes),
805
+ "by_status": by_status,
806
+ "by_decision": by_decision,
807
+ "by_value": by_value,
808
+ "outcomes": outcomes,
809
+ }
810
+
811
+ def portability_report(self) -> dict[str, Any]:
812
+ """Portability classification + offending components (SPEC 4.4)."""
813
+ if self.portable_ir is None:
814
+ return {"classification": "NATIVE", "offenders": ["native rules"]}
815
+ offenders: list[str] = []
816
+ if self.catches:
817
+ offenders.append("catches")
818
+ if self.finalizers:
819
+ offenders.append("finalizers")
820
+ if self.hooks:
821
+ offenders.append("hooks")
822
+ return {
823
+ "classification": "PORTABLE" if not offenders else "NATIVE",
824
+ "offenders": offenders,
825
+ }
826
+
827
+ def explain(self, trace: ExecutionTrace) -> str:
828
+ """Render a trace as human-readable lines (SPEC 12.4).
829
+
830
+ The rationale is derived only from trace events and registered
831
+ rule ids; no reasons are invented.
832
+ """
833
+ lines = [f"FlowContract {trace.contract_version}: {len(trace.events)} event(s)"]
834
+ for event in trace.events:
835
+ lines.append(_explain_event(event))
836
+ return "\n".join(lines)
837
+
838
+ def validate(self) -> tuple[ValidationIssue, ...]:
839
+ """Static analysis without execution (SPEC 12.8).
840
+
841
+ Returns issues distinguishing errors (block compilation) from
842
+ warnings (should investigate). A compiled contract is expected to
843
+ have no errors; warnings may remain.
844
+ """
845
+ issues: list[ValidationIssue] = []
846
+ if not self.rules and self.fallback is None:
847
+ issues.append(
848
+ ValidationIssue(
849
+ severity="error",
850
+ code="empty_flow",
851
+ message="flow has neither rules nor a fallback",
852
+ )
853
+ )
854
+ seen: set[str] = set()
855
+ for rule in self.rules:
856
+ rid = str(rule.id)
857
+ if rid in seen:
858
+ issues.append(
859
+ ValidationIssue(
860
+ severity="error",
861
+ code="duplicate_rule_id",
862
+ message=f"duplicate RuleId: {rid}",
863
+ rule_id=rid,
864
+ )
865
+ )
866
+ seen.add(rid)
867
+ seen_any = False
868
+ for catch in self.catches:
869
+ if catch.kind == "any":
870
+ seen_any = True
871
+ elif seen_any and catch.kind in ("typed", "when"):
872
+ issues.append(
873
+ ValidationIssue(
874
+ severity="error",
875
+ code="catch_any_ordering",
876
+ message="typed catch registered after catch_any",
877
+ )
878
+ )
879
+ for rule in self.rules:
880
+ if (
881
+ rule.effective_from is not None
882
+ and rule.effective_until is not None
883
+ and rule.effective_from >= rule.effective_until
884
+ ):
885
+ issues.append(
886
+ ValidationIssue(
887
+ severity="error",
888
+ code="invalid_effective_window",
889
+ message="effective_from must be before effective_until",
890
+ rule_id=str(rule.id),
891
+ )
892
+ )
893
+ # Unreachable / overlap analysis is only provable for portable
894
+ # const-true and structurally identical conditions (SPEC 12.8).
895
+ if self.portable_ir is not None:
896
+ prs = [r for r in self.portable_ir.rules if r.kind != "then"]
897
+ if self.mode is not EvaluationMode.ALL_MATCH:
898
+ unconditional = False
899
+ for pr in prs:
900
+ rid = str(pr.rule_id)
901
+ if unconditional:
902
+ issues.append(
903
+ ValidationIssue(
904
+ severity="warning",
905
+ code="unreachable_rule",
906
+ message=(
907
+ "rule cannot match: an earlier unconditional "
908
+ "rule always matches first"
909
+ ),
910
+ rule_id=rid,
911
+ )
912
+ )
913
+ continue
914
+ cond = pr.condition
915
+ if cond is not None and cond.op == "const" and cond.value is True:
916
+ unconditional = True
917
+ for i, a in enumerate(prs):
918
+ for b in prs[i + 1 :]:
919
+ if a.kind == b.kind and a.condition == b.condition:
920
+ issues.append(
921
+ ValidationIssue(
922
+ severity="warning",
923
+ code="overlapping_rules",
924
+ message=("rules have structurally identical conditions"),
925
+ rule_id=str(b.rule_id),
926
+ )
927
+ )
928
+ if self.fallback is None and self.rules:
929
+ issues.append(
930
+ ValidationIssue(
931
+ severity="warning",
932
+ code="possible_gap",
933
+ message="no fallback configured; some inputs may produce NO_MATCH",
934
+ )
935
+ )
936
+ return tuple(issues)
937
+
938
+ # -- execution ---------------------------------------------------------
939
+
940
+ def execute(self, input: Any, *, clock: Clock | None = None) -> FlowOutcome:
941
+ """Execute and propagate an unrecovered exception (SPEC 11.4, D13)."""
942
+ if self.async_only:
943
+ raise AsyncOnlyContractError(
944
+ "contract is async-only; use execute_async() (SPEC 11.7, FR8)"
945
+ )
946
+ outcome = self.try_execute(input, clock=clock)
947
+ if (
948
+ outcome.execution_status is ExecutionStatus.FAILED
949
+ and outcome.primary_exception is not None
950
+ ):
951
+ raise outcome.primary_exception
952
+ return outcome
953
+
954
+ def try_execute(
955
+ self,
956
+ input: Any,
957
+ *,
958
+ clock: Clock | None = None,
959
+ trace: bool | None = None,
960
+ diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None,
961
+ ) -> FlowOutcome:
962
+ """Execute and always return a FlowOutcome (SPEC 11.4, D13).
963
+
964
+ trace=True enables trace collection for this execution even when
965
+ the contract was not built with_trace() (SPEC 12.3).
966
+ diagnostic_hook overrides the contract-level hook for this call.
967
+ """
968
+ ctx = FlowContext(input=input, clock=clock if clock is not None else self.clock)
969
+ if self.async_only:
970
+ raise AsyncOnlyContractError(
971
+ "contract is async-only; use try_execute_async() (SPEC 11.7)"
972
+ )
973
+ enabled = self.trace_enabled if trace is None else trace
974
+ hook = diagnostic_hook if diagnostic_hook is not None else self.trace_diagnostic_hook
975
+ rec = TraceRecorder(self.contract_version, hook) if enabled else None
976
+ primary = self._primary(ctx, rec)
977
+ outcome = _finalize(self, ctx, primary, rec)
978
+ if rec is not None:
979
+ outcome = replace(outcome, trace=rec.build())
980
+ return outcome
981
+
982
+ async def execute_async(self, input: Any, *, clock: Clock | None = None) -> FlowOutcome:
983
+ """Async execution; propagates an unrecovered exception (SPEC 11.7)."""
984
+ outcome = await self.try_execute_async(input, clock=clock)
985
+ if (
986
+ outcome.execution_status is ExecutionStatus.FAILED
987
+ and outcome.primary_exception is not None
988
+ ):
989
+ raise outcome.primary_exception
990
+ return outcome
991
+
992
+ async def try_execute_async(
993
+ self,
994
+ input: Any,
995
+ *,
996
+ clock: Clock | None = None,
997
+ trace: bool | None = None,
998
+ diagnostic_hook: Callable[[Any], dict[str, Any] | None] | None = None,
999
+ ) -> FlowOutcome:
1000
+ """Async execution returning a FlowOutcome (SPEC 11.7).
1001
+
1002
+ Awaits every user-supplied callback that returns an awaitable;
1003
+ sync and async paths produce identical outcomes for the same
1004
+ contract and input.
1005
+ """
1006
+ ctx = FlowContext(input=input, clock=clock if clock is not None else self.clock)
1007
+ enabled = self.trace_enabled if trace is None else trace
1008
+ hook = diagnostic_hook if diagnostic_hook is not None else self.trace_diagnostic_hook
1009
+ rec = TraceRecorder(self.contract_version, hook) if enabled else None
1010
+ primary = await self._primary_async(ctx, rec)
1011
+ outcome = await _finalize_async(self, ctx, primary, rec)
1012
+ if rec is not None:
1013
+ outcome = replace(outcome, trace=rec.build())
1014
+ return outcome
1015
+
1016
+ async def _primary_async(self, ctx: FlowContext, rec: TraceRecorder | None) -> FlowOutcome:
1017
+ """Async primary outcome before finalization (SPEC 7.3.1, 11.7)."""
1018
+ try:
1019
+ return await _evaluate_async(self, ctx, rec)
1020
+ except asyncio.CancelledError as exc:
1021
+ if rec is not None:
1022
+ rec.emit("cancelled_observed", timestamp=ctx.clock.wall())
1023
+ return FlowOutcome(
1024
+ execution_status=ExecutionStatus.CANCELLED,
1025
+ interruption=InterruptionInfo(
1026
+ kind="cancelled",
1027
+ source="host",
1028
+ timestamp=ctx.clock.wall(),
1029
+ ),
1030
+ primary_exception=exc,
1031
+ )
1032
+ except TimeoutError as exc:
1033
+ if rec is not None:
1034
+ rec.emit("timed_out_observed", timestamp=ctx.clock.wall())
1035
+ return FlowOutcome(
1036
+ execution_status=ExecutionStatus.TIMED_OUT,
1037
+ interruption=InterruptionInfo(
1038
+ kind="timed_out",
1039
+ source="external",
1040
+ timestamp=ctx.clock.wall(),
1041
+ ),
1042
+ primary_exception=exc,
1043
+ )
1044
+ except Exception as exc:
1045
+ try:
1046
+ return await _route_exception_async(self, ctx, exc, rec)
1047
+ except Exception as route_exc:
1048
+ return FlowOutcome(
1049
+ execution_status=ExecutionStatus.FAILED,
1050
+ primary_exception=route_exc,
1051
+ )
1052
+ except BaseException as exc:
1053
+ return FlowOutcome(
1054
+ execution_status=ExecutionStatus.FAILED,
1055
+ primary_exception=exc,
1056
+ )
1057
+
1058
+ def _primary(self, ctx: FlowContext, rec: TraceRecorder | None) -> FlowOutcome:
1059
+ """Compute the primary outcome before finalization (SPEC 7.3.1)."""
1060
+ try:
1061
+ return _evaluate(self, ctx, rec)
1062
+ except asyncio.CancelledError as exc:
1063
+ if rec is not None:
1064
+ rec.emit(
1065
+ "cancelled_observed",
1066
+ timestamp=ctx.clock.wall(),
1067
+ )
1068
+ # Cooperative cancellation: an interruption, not an exception.
1069
+ # It bypasses catch rules entirely (SPEC 11.6.1, 11.6.3).
1070
+ return FlowOutcome(
1071
+ execution_status=ExecutionStatus.CANCELLED,
1072
+ interruption=InterruptionInfo(
1073
+ kind="cancelled",
1074
+ source="host",
1075
+ timestamp=ctx.clock.wall(),
1076
+ ),
1077
+ primary_exception=exc,
1078
+ )
1079
+ except TimeoutError as exc:
1080
+ # Externally-imposed timeout: an interruption, not an exception.
1081
+ # The library does not enforce timeouts; it recognizes them
1082
+ # (SPEC 11.6.2). Catch rules MUST NOT catch it (11.6.3).
1083
+ if rec is not None:
1084
+ rec.emit(
1085
+ "timed_out_observed",
1086
+ timestamp=ctx.clock.wall(),
1087
+ )
1088
+ return FlowOutcome(
1089
+ execution_status=ExecutionStatus.TIMED_OUT,
1090
+ interruption=InterruptionInfo(
1091
+ kind="timed_out",
1092
+ source="external",
1093
+ timestamp=ctx.clock.wall(),
1094
+ ),
1095
+ primary_exception=exc,
1096
+ )
1097
+ except Exception as exc:
1098
+ try:
1099
+ return _route_exception(self, ctx, exc, rec)
1100
+ except Exception as route_exc:
1101
+ return FlowOutcome(
1102
+ execution_status=ExecutionStatus.FAILED,
1103
+ primary_exception=route_exc,
1104
+ )
1105
+ except BaseException as exc:
1106
+ # Non-Exception BaseExceptions (e.g. SystemExit, KeyboardInterrupt)
1107
+ # are ordinary failures, not interruptions (SPEC 11.6.3).
1108
+ return FlowOutcome(
1109
+ execution_status=ExecutionStatus.FAILED,
1110
+ primary_exception=exc,
1111
+ )
1112
+
1113
+
1114
+ def _finalize(
1115
+ contract: FlowContract,
1116
+ ctx: FlowContext,
1117
+ outcome: FlowOutcome,
1118
+ rec: TraceRecorder | None,
1119
+ ) -> FlowOutcome:
1120
+ """Run finalizers and apply the finally failure policy (SPEC 11.8, 16.4).
1121
+
1122
+ Finalizers run in LIFO order (innermost first), each isolated with a
1123
+ fresh cancellation token. Cleanup exceptions never trigger catch rules
1124
+ and never re-enter evaluation (FR3). is_clean is false iff any
1125
+ finalizer raised, was cancelled, or exceeded its budget.
1126
+ """
1127
+ if not contract.finalizers:
1128
+ return outcome
1129
+
1130
+ cleanup_excs: list[BaseException] = []
1131
+ budget_exceeded = False
1132
+ for fin in reversed(contract.finalizers):
1133
+ fctx = FinallyContext(
1134
+ result=outcome,
1135
+ status=outcome.execution_status,
1136
+ value=outcome.value,
1137
+ exception=outcome.primary_exception,
1138
+ context=ctx.input,
1139
+ cancellation_token=FinallyCancellationToken(),
1140
+ )
1141
+ start = ctx.clock.monotonic()
1142
+ if rec is not None:
1143
+ rec.emit("finally_started", timestamp=ctx.clock.wall())
1144
+ try:
1145
+ fin_result = fin(fctx)
1146
+ _reject_awaitable(fin_result)
1147
+ except Exception as exc:
1148
+ cleanup_excs.append(exc)
1149
+ if rec is not None:
1150
+ rec.emit("finally_raised", timestamp=ctx.clock.wall())
1151
+ else:
1152
+ if rec is not None:
1153
+ rec.emit("finally_completed", timestamp=ctx.clock.wall())
1154
+ if contract.finally_timeout_ms is not None:
1155
+ elapsed_ms = (ctx.clock.monotonic() - start) * 1000.0
1156
+ if elapsed_ms > contract.finally_timeout_ms:
1157
+ budget_exceeded = True
1158
+
1159
+ is_clean = not cleanup_excs and not budget_exceeded
1160
+ finfo = FinalizationInfo(
1161
+ is_clean=is_clean,
1162
+ cleanup_exceptions=tuple(cleanup_excs),
1163
+ cleanup_budget_exceeded=budget_exceeded,
1164
+ )
1165
+ result = replace(outcome, finalization=finfo)
1166
+
1167
+ if not cleanup_excs:
1168
+ return result
1169
+
1170
+ secondary = list(outcome.secondary_exceptions) + cleanup_excs
1171
+ if (
1172
+ contract.finally_policy is FinallyFailurePolicy.REPLACE_PRIMARY
1173
+ and outcome.execution_status is ExecutionStatus.FAILED
1174
+ and outcome.primary_exception is not None
1175
+ ):
1176
+ # ReplacePrimary on FAILED: cleanup exception becomes primary,
1177
+ # original primary moves to secondary (SPEC 16.4 matrix).
1178
+ secondary.append(outcome.primary_exception)
1179
+ return replace(
1180
+ result,
1181
+ primary_exception=cleanup_excs[0],
1182
+ secondary_exceptions=tuple(secondary),
1183
+ )
1184
+ # PreservePrimary and Attach: outcome unchanged; cleanup exceptions
1185
+ # recorded in secondary_exceptions (FR2). ReplacePrimary on
1186
+ # COMPLETED/CANCELLED/TIMED_OUT also lands here (B3-a).
1187
+ return replace(result, secondary_exceptions=tuple(secondary))
1188
+
1189
+
1190
+ def _ordered_rules(contract: FlowContract) -> list[Rule]:
1191
+ if contract.mode is EvaluationMode.PRIORITY:
1192
+ # Stable sort: higher priority first, ties keep registration order.
1193
+ return sorted(contract.rules, key=lambda r: -r.priority)
1194
+ return list(contract.rules)
1195
+
1196
+
1197
+ def _evaluate(contract: FlowContract, ctx: FlowContext, rec: TraceRecorder | None) -> FlowOutcome:
1198
+ """Evaluate the contract against the context (SPEC sections 7, 10)."""
1199
+ secondary: list[BaseException] = []
1200
+ effects: list[Effect] = []
1201
+ outcome = _run_rules(contract, ctx, secondary, effects, rec)
1202
+ if secondary:
1203
+ outcome = replace(outcome, secondary_exceptions=tuple(secondary))
1204
+ if effects:
1205
+ outcome = replace(outcome, effects=tuple(effects))
1206
+ return outcome
1207
+
1208
+
1209
+ def _run_rules(
1210
+ contract: FlowContract,
1211
+ ctx: FlowContext,
1212
+ secondary: list[BaseException],
1213
+ effects: list[Effect],
1214
+ rec: TraceRecorder | None,
1215
+ ) -> FlowOutcome:
1216
+ """Core rule evaluation; hook failures append to secondary (SPEC 11.5)."""
1217
+ rules = _ordered_rules(contract)
1218
+ matched = False
1219
+ value: Any = None
1220
+ index = 0
1221
+ total = len(rules)
1222
+
1223
+ while index < total:
1224
+ rule = rules[index]
1225
+ if contract.cancel_check is not None and contract.cancel_check():
1226
+ raise asyncio.CancelledError()
1227
+ if rule.kind == "then":
1228
+ # then-stage with no active match: skipped (SPEC 10.5).
1229
+ index += 1
1230
+ continue
1231
+
1232
+ if not _is_effective(rule, ctx):
1233
+ if rec is not None:
1234
+ rec.emit(
1235
+ "rule_skipped",
1236
+ rule_id=str(rule.id),
1237
+ timestamp=ctx.clock.wall(),
1238
+ reason="not_effective",
1239
+ )
1240
+ index += 1
1241
+ continue
1242
+
1243
+ holds, skip_reason = _condition_holds(rule, ctx, rec)
1244
+ if not holds:
1245
+ if rec is not None and skip_reason is not None:
1246
+ rec.emit(
1247
+ "rule_skipped",
1248
+ rule_id=str(rule.id),
1249
+ timestamp=ctx.clock.wall(),
1250
+ reason=skip_reason,
1251
+ )
1252
+ index += 1
1253
+ continue
1254
+
1255
+ matched = True
1256
+ try:
1257
+ value = rule.action(ctx.input)
1258
+ _reject_awaitable(value)
1259
+ except Exception:
1260
+ if rec is not None:
1261
+ rec.emit(
1262
+ "action_raised",
1263
+ rule_id=str(rule.id),
1264
+ timestamp=ctx.clock.wall(),
1265
+ )
1266
+ raise
1267
+ if rec is not None:
1268
+ rec.emit(
1269
+ "action_executed",
1270
+ rule_id=str(rule.id),
1271
+ timestamp=ctx.clock.wall(),
1272
+ )
1273
+ _propose_effects(rule, effects, rec, ctx)
1274
+ _fire_hooks(contract, ctx, str(rule.id), value, secondary, rec)
1275
+
1276
+ # Run the then-chain immediately following this rule (SPEC 10.5).
1277
+ chain_index = index + 1
1278
+ while chain_index < total and rules[chain_index].kind == "then":
1279
+ stage = rules[chain_index]
1280
+ value = stage.action(ctx.input, value)
1281
+ _reject_awaitable(value)
1282
+ _propose_effects(stage, effects, rec, ctx)
1283
+ chain_index += 1
1284
+
1285
+ if contract.mode is not EvaluationMode.ALL_MATCH:
1286
+ # FirstMatch/Priority: remaining rules skipped by short-circuit.
1287
+ if rec is not None:
1288
+ for skipped in rules[chain_index:]:
1289
+ if skipped.kind == "then":
1290
+ continue
1291
+ rec.emit(
1292
+ "skipped_by_short_circuit",
1293
+ rule_id=str(skipped.id),
1294
+ timestamp=ctx.clock.wall(),
1295
+ reason="earlier_match",
1296
+ )
1297
+ break
1298
+ index = chain_index
1299
+
1300
+ if matched:
1301
+ return FlowOutcome(
1302
+ execution_status=ExecutionStatus.COMPLETED,
1303
+ decision_status=DecisionStatus.APPROVED,
1304
+ value=value,
1305
+ )
1306
+
1307
+ # No rule matched: apply fallback if configured (SPEC 10.4, 3.2).
1308
+ if contract.fallback is not None:
1309
+ if contract.fallback.kind == "otherwise":
1310
+ assert contract.fallback.action is not None
1311
+ fb_value = contract.fallback.action(ctx.input)
1312
+ _reject_awaitable(fb_value)
1313
+ return FlowOutcome(
1314
+ execution_status=ExecutionStatus.COMPLETED,
1315
+ decision_status=DecisionStatus.NO_MATCH,
1316
+ value=fb_value,
1317
+ )
1318
+ return FlowOutcome(
1319
+ execution_status=ExecutionStatus.COMPLETED,
1320
+ decision_status=DecisionStatus.NO_MATCH,
1321
+ value=contract.fallback.value,
1322
+ )
1323
+
1324
+ return FlowOutcome(
1325
+ execution_status=ExecutionStatus.COMPLETED,
1326
+ decision_status=DecisionStatus.NO_MATCH,
1327
+ value=None,
1328
+ )
1329
+
1330
+
1331
+ def _propose_effects(
1332
+ rule: Rule,
1333
+ effects: list[Effect],
1334
+ rec: TraceRecorder | None,
1335
+ ctx: FlowContext,
1336
+ ) -> None:
1337
+ """Append a rule's proposed effects in deterministic order (SPEC 5, 6.4)."""
1338
+ for effect in rule.effects:
1339
+ effects.append(effect)
1340
+ if rec is not None:
1341
+ rec.emit(
1342
+ "effect_proposed",
1343
+ rule_id=str(rule.id),
1344
+ timestamp=ctx.clock.wall(),
1345
+ )
1346
+
1347
+
1348
+ def _is_effective(rule: Rule, ctx: FlowContext) -> bool:
1349
+ """Check effective window against injected wall clock (SPEC 12.9).
1350
+
1351
+ Inclusive of effective_from, exclusive of effective_until.
1352
+ """
1353
+ now = ctx.clock.wall()
1354
+ if rule.effective_from is not None and now < rule.effective_from:
1355
+ return False
1356
+ return not (rule.effective_until is not None and now >= rule.effective_until)
1357
+
1358
+
1359
+ def _condition_holds(
1360
+ rule: Rule, ctx: FlowContext, rec: TraceRecorder | None
1361
+ ) -> tuple[bool, str | None]:
1362
+ """Evaluate condition + guard; emit trace events (SPEC 10.1-10.2, 12.1).
1363
+
1364
+ Returns (holds, skip_reason) where skip_reason is a closed-enum reason
1365
+ for rule_skipped events, or None when the rule holds.
1366
+ """
1367
+ assert rule.condition is not None
1368
+ rid = str(rule.id)
1369
+ try:
1370
+ cond_raw = rule.condition(ctx.input)
1371
+ _reject_awaitable(cond_raw)
1372
+ result = bool(cond_raw)
1373
+ except Exception:
1374
+ if rec is not None:
1375
+ rec.emit(
1376
+ "condition_raised",
1377
+ rule_id=rid,
1378
+ timestamp=ctx.clock.wall(),
1379
+ )
1380
+ raise
1381
+ if rec is not None:
1382
+ rec.emit(
1383
+ "condition_evaluated",
1384
+ rule_id=rid,
1385
+ timestamp=ctx.clock.wall(),
1386
+ )
1387
+ if rule.kind == "when_not":
1388
+ result = not result
1389
+ if not result:
1390
+ return False, "condition_false"
1391
+ if rule.guard is not None:
1392
+ try:
1393
+ guard_raw = rule.guard(ctx.input)
1394
+ _reject_awaitable(guard_raw)
1395
+ guard_ok = bool(guard_raw)
1396
+ except Exception:
1397
+ raise
1398
+ if rec is not None:
1399
+ rec.emit(
1400
+ "guard_evaluated",
1401
+ rule_id=rid,
1402
+ timestamp=ctx.clock.wall(),
1403
+ )
1404
+ if not guard_ok:
1405
+ return False, "guard_blocked"
1406
+ return True, None
1407
+
1408
+
1409
+ def _fire_hooks(
1410
+ contract: FlowContract,
1411
+ ctx: FlowContext,
1412
+ rule_id: str,
1413
+ value: Any,
1414
+ secondary: list[BaseException],
1415
+ rec: TraceRecorder | None,
1416
+ ) -> None:
1417
+ """Invoke on_match hooks; failures are isolated (SPEC 11.5)."""
1418
+ for hook in contract.hooks:
1419
+ if rec is not None:
1420
+ rec.emit("hook_invoked", rule_id=rule_id, timestamp=ctx.clock.wall())
1421
+ try:
1422
+ hook_result = hook(ctx.input, rule_id, value)
1423
+ _reject_awaitable(hook_result)
1424
+ except Exception as exc:
1425
+ secondary.append(exc)
1426
+ if rec is not None:
1427
+ rec.emit("hook_raised", rule_id=rule_id, timestamp=ctx.clock.wall())
1428
+
1429
+
1430
+ def _route_exception(
1431
+ contract: FlowContract,
1432
+ ctx: FlowContext,
1433
+ exc: Exception,
1434
+ rec: TraceRecorder | None,
1435
+ ) -> FlowOutcome:
1436
+ """Route an exception through the catch chain (SPEC 11.1-11.4, 7.3.1).
1437
+
1438
+ The first matching catch handles the exception. A handler that raises
1439
+ propagates the NEW exception through the remaining catches. rethrow
1440
+ stops evaluation and fails with the current exception. If no catch
1441
+ matches, the outcome is FAILED with the current exception as primary.
1442
+ """
1443
+ current: Exception = exc
1444
+ for index, catch in enumerate(contract.catches):
1445
+ if catch.kind == "rethrow":
1446
+ if rec is not None:
1447
+ rec.emit("rethrow_reached", timestamp=ctx.clock.wall())
1448
+ return FlowOutcome(
1449
+ execution_status=ExecutionStatus.FAILED,
1450
+ primary_exception=current,
1451
+ )
1452
+ if catch.kind == "any":
1453
+ type_matched = True
1454
+ else:
1455
+ assert catch.exc_type is not None
1456
+ type_matched = isinstance(current, catch.exc_type)
1457
+ if not type_matched:
1458
+ continue
1459
+ if rec is not None and catch.kind != "any":
1460
+ rec.emit("catch_matched", timestamp=ctx.clock.wall())
1461
+ if catch.kind == "when" and catch.predicate is not None:
1462
+ if rec is not None:
1463
+ rec.emit("catch_predicate_evaluated", timestamp=ctx.clock.wall())
1464
+ try:
1465
+ pred_raw = catch.predicate(ctx.input, current)
1466
+ _reject_awaitable(pred_raw)
1467
+ pred_ok = bool(pred_raw)
1468
+ except Exception as pred_exc:
1469
+ if rec is not None:
1470
+ rec.emit("catch_predicate_raised", timestamp=ctx.clock.wall())
1471
+ # A failing predicate is an explicit failure: the predicate
1472
+ # exception becomes the new primary candidate (SPEC 11.2).
1473
+ current = pred_exc
1474
+ continue
1475
+ if not pred_ok:
1476
+ if rec is not None:
1477
+ rec.emit("catch_declined", timestamp=ctx.clock.wall())
1478
+ continue
1479
+ assert catch.handler is not None
1480
+ try:
1481
+ value = catch.handler(ctx.input, current)
1482
+ _reject_awaitable(value)
1483
+ except Exception as new_exc:
1484
+ # Handler failure propagates the new exception through the
1485
+ # remaining catches (SPEC 11.1, 11.2, 11.3).
1486
+ current = new_exc
1487
+ continue
1488
+ if rec is not None:
1489
+ rec.emit("catch_handled", timestamp=ctx.clock.wall())
1490
+ handler_id = catch.id if catch.id is not None else f"catch[{index}]"
1491
+ return FlowOutcome(
1492
+ execution_status=ExecutionStatus.COMPLETED,
1493
+ value=value,
1494
+ recovery=RecoveryInfo(
1495
+ original_exception=current,
1496
+ handler_rule_id=handler_id,
1497
+ recovered_at=ctx.clock.wall(),
1498
+ ),
1499
+ )
1500
+ return FlowOutcome(
1501
+ execution_status=ExecutionStatus.FAILED,
1502
+ primary_exception=current,
1503
+ )
1504
+
1505
+
1506
+ # -- async execution parity (SPEC 11.7) ---------------------------------------
1507
+
1508
+
1509
+ def _is_async_callable(fn: Callable[..., Any]) -> bool:
1510
+ """Detect async callables including partials and async __call__."""
1511
+ if inspect.iscoroutinefunction(fn):
1512
+ return True
1513
+ try:
1514
+ return inspect.iscoroutinefunction(type(fn).__call__)
1515
+ except AttributeError:
1516
+ return False
1517
+
1518
+
1519
+ def _compute_async_only(
1520
+ *,
1521
+ rules: list[Rule],
1522
+ catches: list[CatchRule],
1523
+ hooks: list[Callable[[Any, str, Any], None]],
1524
+ finalizers: list[Callable[[FinallyContext], Any]],
1525
+ ) -> bool:
1526
+ """Classify the contract as async-only (SPEC 11.7, FR8)."""
1527
+ for rule in rules:
1528
+ for fn in (rule.condition, rule.guard, rule.action):
1529
+ if fn is not None and _is_async_callable(fn):
1530
+ return True
1531
+ for catch in catches:
1532
+ for fn in (catch.handler, catch.predicate):
1533
+ if fn is not None and _is_async_callable(fn):
1534
+ return True
1535
+ for hook in hooks:
1536
+ if _is_async_callable(hook):
1537
+ return True
1538
+ return any(_is_async_callable(fin) for fin in finalizers)
1539
+
1540
+
1541
+ def _reject_awaitable(result: Any) -> None:
1542
+ """Sync path must never silently skip awaiting (SPEC 11.7)."""
1543
+ if inspect.isawaitable(result):
1544
+ raise AsyncOnlyContractError(
1545
+ "a user callback returned an awaitable on the sync path; "
1546
+ "use execute_async() (SPEC 11.7)"
1547
+ )
1548
+
1549
+
1550
+ async def _resolve(value: Any) -> Any:
1551
+ """Await the value if it is awaitable, else return it (SPEC 11.7)."""
1552
+ if inspect.isawaitable(value):
1553
+ return await value
1554
+ return value
1555
+
1556
+
1557
+ async def _evaluate_async(
1558
+ contract: FlowContract, ctx: FlowContext, rec: TraceRecorder | None
1559
+ ) -> FlowOutcome:
1560
+ """Async rule evaluation; hook failures append to secondary."""
1561
+ secondary: list[BaseException] = []
1562
+ effects: list[Effect] = []
1563
+ outcome = await _run_rules_async(contract, ctx, secondary, effects, rec)
1564
+ if secondary:
1565
+ outcome = replace(outcome, secondary_exceptions=tuple(secondary))
1566
+ if effects:
1567
+ outcome = replace(outcome, effects=tuple(effects))
1568
+ return outcome
1569
+
1570
+
1571
+ async def _run_rules_async(
1572
+ contract: FlowContract,
1573
+ ctx: FlowContext,
1574
+ secondary: list[BaseException],
1575
+ effects: list[Effect],
1576
+ rec: TraceRecorder | None,
1577
+ ) -> FlowOutcome:
1578
+ """Async core rule evaluation (SPEC 10, 11.7)."""
1579
+ rules = _ordered_rules(contract)
1580
+ matched = False
1581
+ value: Any = None
1582
+ index = 0
1583
+ total = len(rules)
1584
+
1585
+ while index < total:
1586
+ rule = rules[index]
1587
+ if contract.cancel_check is not None and contract.cancel_check():
1588
+ raise asyncio.CancelledError()
1589
+ if rule.kind == "then":
1590
+ index += 1
1591
+ continue
1592
+
1593
+ if not _is_effective(rule, ctx):
1594
+ if rec is not None:
1595
+ rec.emit(
1596
+ "rule_skipped",
1597
+ rule_id=str(rule.id),
1598
+ timestamp=ctx.clock.wall(),
1599
+ reason="not_effective",
1600
+ )
1601
+ index += 1
1602
+ continue
1603
+
1604
+ holds, skip_reason = await _condition_holds_async(rule, ctx, rec)
1605
+ if not holds:
1606
+ if rec is not None and skip_reason is not None:
1607
+ rec.emit(
1608
+ "rule_skipped",
1609
+ rule_id=str(rule.id),
1610
+ timestamp=ctx.clock.wall(),
1611
+ reason=skip_reason,
1612
+ )
1613
+ index += 1
1614
+ continue
1615
+
1616
+ matched = True
1617
+ try:
1618
+ value = await _resolve(rule.action(ctx.input))
1619
+ except Exception:
1620
+ if rec is not None:
1621
+ rec.emit(
1622
+ "action_raised",
1623
+ rule_id=str(rule.id),
1624
+ timestamp=ctx.clock.wall(),
1625
+ )
1626
+ raise
1627
+ if rec is not None:
1628
+ rec.emit(
1629
+ "action_executed",
1630
+ rule_id=str(rule.id),
1631
+ timestamp=ctx.clock.wall(),
1632
+ )
1633
+ _propose_effects(rule, effects, rec, ctx)
1634
+ await _fire_hooks_async(contract, ctx, str(rule.id), value, secondary, rec)
1635
+
1636
+ chain_index = index + 1
1637
+ while chain_index < total and rules[chain_index].kind == "then":
1638
+ stage = rules[chain_index]
1639
+ value = await _resolve(stage.action(ctx.input, value))
1640
+ _propose_effects(stage, effects, rec, ctx)
1641
+ chain_index += 1
1642
+
1643
+ if contract.mode is not EvaluationMode.ALL_MATCH:
1644
+ if rec is not None:
1645
+ for skipped in rules[chain_index:]:
1646
+ if skipped.kind == "then":
1647
+ continue
1648
+ rec.emit(
1649
+ "skipped_by_short_circuit",
1650
+ rule_id=str(skipped.id),
1651
+ timestamp=ctx.clock.wall(),
1652
+ reason="earlier_match",
1653
+ )
1654
+ break
1655
+ index = chain_index
1656
+
1657
+ if matched:
1658
+ return FlowOutcome(
1659
+ execution_status=ExecutionStatus.COMPLETED,
1660
+ decision_status=DecisionStatus.APPROVED,
1661
+ value=value,
1662
+ )
1663
+
1664
+ if contract.fallback is not None:
1665
+ if contract.fallback.kind == "otherwise":
1666
+ assert contract.fallback.action is not None
1667
+ return FlowOutcome(
1668
+ execution_status=ExecutionStatus.COMPLETED,
1669
+ decision_status=DecisionStatus.NO_MATCH,
1670
+ value=await _resolve(contract.fallback.action(ctx.input)),
1671
+ )
1672
+ return FlowOutcome(
1673
+ execution_status=ExecutionStatus.COMPLETED,
1674
+ decision_status=DecisionStatus.NO_MATCH,
1675
+ value=contract.fallback.value,
1676
+ )
1677
+
1678
+ return FlowOutcome(
1679
+ execution_status=ExecutionStatus.COMPLETED,
1680
+ decision_status=DecisionStatus.NO_MATCH,
1681
+ value=None,
1682
+ )
1683
+
1684
+
1685
+ async def _condition_holds_async(
1686
+ rule: Rule, ctx: FlowContext, rec: TraceRecorder | None
1687
+ ) -> tuple[bool, str | None]:
1688
+ """Async condition + guard evaluation (SPEC 10.1-10.2, 11.7)."""
1689
+ assert rule.condition is not None
1690
+ rid = str(rule.id)
1691
+ try:
1692
+ result = bool(await _resolve(rule.condition(ctx.input)))
1693
+ except Exception:
1694
+ if rec is not None:
1695
+ rec.emit(
1696
+ "condition_raised",
1697
+ rule_id=rid,
1698
+ timestamp=ctx.clock.wall(),
1699
+ )
1700
+ raise
1701
+ if rec is not None:
1702
+ rec.emit(
1703
+ "condition_evaluated",
1704
+ rule_id=rid,
1705
+ timestamp=ctx.clock.wall(),
1706
+ )
1707
+ if rule.kind == "when_not":
1708
+ result = not result
1709
+ if not result:
1710
+ return False, "condition_false"
1711
+ if rule.guard is not None:
1712
+ try:
1713
+ guard_ok = bool(await _resolve(rule.guard(ctx.input)))
1714
+ except Exception:
1715
+ raise
1716
+ if rec is not None:
1717
+ rec.emit(
1718
+ "guard_evaluated",
1719
+ rule_id=rid,
1720
+ timestamp=ctx.clock.wall(),
1721
+ )
1722
+ if not guard_ok:
1723
+ return False, "guard_blocked"
1724
+ return True, None
1725
+
1726
+
1727
+ async def _fire_hooks_async(
1728
+ contract: FlowContract,
1729
+ ctx: FlowContext,
1730
+ rule_id: str,
1731
+ value: Any,
1732
+ secondary: list[BaseException],
1733
+ rec: TraceRecorder | None,
1734
+ ) -> None:
1735
+ """Async on_match hooks; failures isolated (SPEC 11.5, 11.7)."""
1736
+ for hook in contract.hooks:
1737
+ if rec is not None:
1738
+ rec.emit("hook_invoked", rule_id=rule_id, timestamp=ctx.clock.wall())
1739
+ try:
1740
+ await _resolve(hook(ctx.input, rule_id, value))
1741
+ except Exception as exc:
1742
+ secondary.append(exc)
1743
+ if rec is not None:
1744
+ rec.emit("hook_raised", rule_id=rule_id, timestamp=ctx.clock.wall())
1745
+
1746
+
1747
+ async def _route_exception_async(
1748
+ contract: FlowContract,
1749
+ ctx: FlowContext,
1750
+ exc: Exception,
1751
+ rec: TraceRecorder | None,
1752
+ ) -> FlowOutcome:
1753
+ """Async catch-chain routing (SPEC 11.1-11.4, 11.7)."""
1754
+ current: Exception = exc
1755
+ for index, catch in enumerate(contract.catches):
1756
+ if catch.kind == "rethrow":
1757
+ if rec is not None:
1758
+ rec.emit("rethrow_reached", timestamp=ctx.clock.wall())
1759
+ return FlowOutcome(
1760
+ execution_status=ExecutionStatus.FAILED,
1761
+ primary_exception=current,
1762
+ )
1763
+ if catch.kind == "any":
1764
+ type_matched = True
1765
+ else:
1766
+ assert catch.exc_type is not None
1767
+ type_matched = isinstance(current, catch.exc_type)
1768
+ if not type_matched:
1769
+ continue
1770
+ if rec is not None and catch.kind != "any":
1771
+ rec.emit("catch_matched", timestamp=ctx.clock.wall())
1772
+ if catch.kind == "when" and catch.predicate is not None:
1773
+ if rec is not None:
1774
+ rec.emit("catch_predicate_evaluated", timestamp=ctx.clock.wall())
1775
+ try:
1776
+ pred_ok = bool(await _resolve(catch.predicate(ctx.input, current)))
1777
+ except Exception as pred_exc:
1778
+ if rec is not None:
1779
+ rec.emit("catch_predicate_raised", timestamp=ctx.clock.wall())
1780
+ current = pred_exc
1781
+ continue
1782
+ if not pred_ok:
1783
+ if rec is not None:
1784
+ rec.emit("catch_declined", timestamp=ctx.clock.wall())
1785
+ continue
1786
+ assert catch.handler is not None
1787
+ try:
1788
+ value = await _resolve(catch.handler(ctx.input, current))
1789
+ except Exception as new_exc:
1790
+ current = new_exc
1791
+ continue
1792
+ if rec is not None:
1793
+ rec.emit("catch_handled", timestamp=ctx.clock.wall())
1794
+ handler_id = catch.id if catch.id is not None else f"catch[{index}]"
1795
+ return FlowOutcome(
1796
+ execution_status=ExecutionStatus.COMPLETED,
1797
+ value=value,
1798
+ recovery=RecoveryInfo(
1799
+ original_exception=current,
1800
+ handler_rule_id=handler_id,
1801
+ recovered_at=ctx.clock.wall(),
1802
+ ),
1803
+ )
1804
+ return FlowOutcome(
1805
+ execution_status=ExecutionStatus.FAILED,
1806
+ primary_exception=current,
1807
+ )
1808
+
1809
+
1810
+ async def _finalize_async(
1811
+ contract: FlowContract,
1812
+ ctx: FlowContext,
1813
+ outcome: FlowOutcome,
1814
+ rec: TraceRecorder | None,
1815
+ ) -> FlowOutcome:
1816
+ """Async finalization with the same failure policy (SPEC 11.8, 16.4)."""
1817
+ if not contract.finalizers:
1818
+ return outcome
1819
+
1820
+ cleanup_excs: list[BaseException] = []
1821
+ budget_exceeded = False
1822
+ for fin in reversed(contract.finalizers):
1823
+ fctx = FinallyContext(
1824
+ result=outcome,
1825
+ status=outcome.execution_status,
1826
+ value=outcome.value,
1827
+ exception=outcome.primary_exception,
1828
+ context=ctx.input,
1829
+ cancellation_token=FinallyCancellationToken(),
1830
+ )
1831
+ start = ctx.clock.monotonic()
1832
+ if rec is not None:
1833
+ rec.emit("finally_started", timestamp=ctx.clock.wall())
1834
+ try:
1835
+ call = fin(fctx)
1836
+ if contract.finally_timeout_ms is not None and inspect.isawaitable(call):
1837
+ await asyncio.wait_for(_resolve(call), timeout=contract.finally_timeout_ms / 1000.0)
1838
+ else:
1839
+ await _resolve(call)
1840
+ except Exception as exc:
1841
+ cleanup_excs.append(exc)
1842
+ if rec is not None:
1843
+ rec.emit("finally_raised", timestamp=ctx.clock.wall())
1844
+ else:
1845
+ if rec is not None:
1846
+ rec.emit("finally_completed", timestamp=ctx.clock.wall())
1847
+ if contract.finally_timeout_ms is not None:
1848
+ elapsed_ms = (ctx.clock.monotonic() - start) * 1000.0
1849
+ if elapsed_ms > contract.finally_timeout_ms:
1850
+ budget_exceeded = True
1851
+
1852
+ is_clean = not cleanup_excs and not budget_exceeded
1853
+ finfo = FinalizationInfo(
1854
+ is_clean=is_clean,
1855
+ cleanup_exceptions=tuple(cleanup_excs),
1856
+ cleanup_budget_exceeded=budget_exceeded,
1857
+ )
1858
+ result = replace(outcome, finalization=finfo)
1859
+
1860
+ if not cleanup_excs:
1861
+ return result
1862
+
1863
+ secondary = list(outcome.secondary_exceptions) + cleanup_excs
1864
+ if (
1865
+ contract.finally_policy is FinallyFailurePolicy.REPLACE_PRIMARY
1866
+ and outcome.execution_status is ExecutionStatus.FAILED
1867
+ and outcome.primary_exception is not None
1868
+ ):
1869
+ secondary.append(outcome.primary_exception)
1870
+ return replace(
1871
+ result,
1872
+ primary_exception=cleanup_excs[0],
1873
+ secondary_exceptions=tuple(secondary),
1874
+ )
1875
+ return replace(result, secondary_exceptions=tuple(secondary))
1876
+
1877
+
1878
+ @dataclass(frozen=True)
1879
+ class ValidationIssue:
1880
+ """A static-analysis finding (SPEC 12.8).
1881
+
1882
+ severity "error" blocks compilation; "warning" should be investigated
1883
+ but does not block.
1884
+ """
1885
+
1886
+ severity: str # "error" | "warning"
1887
+ code: str
1888
+ message: str
1889
+ rule_id: str | None = None
1890
+
1891
+
1892
+ def _compute_contract_version(
1893
+ *,
1894
+ rules: list[Rule],
1895
+ fallback: Fallback | None,
1896
+ mode: EvaluationMode,
1897
+ catches: list[CatchRule],
1898
+ finalizers: list[Callable[[FinallyContext], Any]],
1899
+ finally_policy: FinallyFailurePolicy,
1900
+ finally_timeout_ms: int | None,
1901
+ trace_enabled: bool,
1902
+ ) -> str:
1903
+ """Structural contract version: SHA-256 of canonical content (SPEC 12.9).
1904
+
1905
+ Algorithm v1: JSON-canonical serialization of rule ids/kinds/
1906
+ priorities, fallback kind, mode, catch kinds, finalizer count,
1907
+ policy, timeout, and trace flag; SHA-256 hex digest truncated to 32
1908
+ chars. Callables are represented by identity-free metadata only.
1909
+ """
1910
+ payload = {
1911
+ "algorithm": "flowsemantics-contract-v1",
1912
+ "rules": [
1913
+ {
1914
+ "id": str(r.id),
1915
+ "kind": r.kind,
1916
+ "priority": r.priority,
1917
+ "effective_from": (
1918
+ r.effective_from.isoformat() if r.effective_from is not None else None
1919
+ ),
1920
+ "effective_until": (
1921
+ r.effective_until.isoformat() if r.effective_until is not None else None
1922
+ ),
1923
+ }
1924
+ for r in rules
1925
+ ],
1926
+ "fallback": None if fallback is None else fallback.kind,
1927
+ "mode": str(mode),
1928
+ "catches": [c.kind for c in catches],
1929
+ "finalizer_count": len(finalizers),
1930
+ "finally_policy": str(finally_policy),
1931
+ "finally_timeout_ms": finally_timeout_ms,
1932
+ "trace_enabled": trace_enabled,
1933
+ }
1934
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
1935
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:32]
1936
+
1937
+
1938
+ def _explain_event(event: Any) -> str:
1939
+ """Render one trace event as a line (SPEC 12.4)."""
1940
+ rid = event.rule_id if event.rule_id is not None else "-"
1941
+ reason = f" ({event.reason})" if event.reason else ""
1942
+ return f" [{event.type}] rule={rid}{reason}"
1943
+
1944
+
1945
+ __all__: list[str] = [
1946
+ "EvaluationMode",
1947
+ "Fallback",
1948
+ "Flow",
1949
+ "FlowContract",
1950
+ "FlowPortability",
1951
+ "ValidationIssue",
1952
+ ]