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,104 @@
1
+ """flowsemantics.execution.clock - Injected wall and monotonic clocks.
2
+
3
+ Layer: Domain
4
+ Module: flowsemantics.execution.clock
5
+ Since: 0.1.0
6
+ Implements: SPEC.md section 6.2 (injected clocks), section 6.3 (default clock)
7
+ Depends on: stdlib only (datetime, time)
8
+ Used by: FlowContext, FlowOutcome timestamps, finalization budgets
9
+ See also: SPEC.md section 6
10
+
11
+ Notes:
12
+ - Every time read in Core routes through a Clock. Ambient clock APIs are
13
+ banned in Core by audit.py; SystemClock is the single sanctioned reader,
14
+ permitted by SPEC.md section 6.3 and clearly replaceable via with_clock.
15
+ - SystemClock reads the host clocks through the datetime and time modules.
16
+ It is the documented default; deterministic replay requires FakeClock.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import datetime
22
+ import time
23
+ from typing import Protocol
24
+
25
+ _EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.UTC)
26
+
27
+
28
+ class Clock(Protocol):
29
+ """Two-concept clock: wall time for timestamps, monotonic for durations.
30
+
31
+ SPEC.md section 6.2 makes the wall/monotonic distinction normative.
32
+ """
33
+
34
+ def wall(self) -> datetime.datetime:
35
+ """Return the current wall-clock time as a timezone-aware datetime."""
36
+ ...
37
+
38
+ def monotonic(self) -> float:
39
+ """Return the current monotonic time in seconds."""
40
+ ...
41
+
42
+
43
+ class SystemClock:
44
+ """Default clock reading the host's real clocks (SPEC.md section 6.3).
45
+
46
+ This is the only Core component permitted to read ambient time. It is
47
+ replaceable: pass any Clock implementation via Flow.with_clock() or the
48
+ execute() clock parameter. Deterministic replay and tests MUST use
49
+ FakeClock instead.
50
+ """
51
+
52
+ def wall(self) -> datetime.datetime:
53
+ """Return the host wall-clock time in UTC."""
54
+ return datetime.datetime.now(datetime.UTC)
55
+
56
+ def monotonic(self) -> float:
57
+ """Return the host monotonic clock in seconds."""
58
+ return time.monotonic()
59
+
60
+
61
+ class FakeClock:
62
+ """Deterministic clock for tests, replay, and conformance vectors.
63
+
64
+ Wall and monotonic values advance only when advance() or advance_wall()
65
+ is called. Two FakeClocks constructed with the same values behave
66
+ identically, which is what SPEC.md section 6.1 determinism requires.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ wall: datetime.datetime | None = None,
72
+ monotonic: float = 0.0,
73
+ ) -> None:
74
+ """Create a FakeClock at the given wall time and monotonic offset."""
75
+ self._wall = wall if wall is not None else _EPOCH
76
+ self._monotonic = monotonic
77
+
78
+ def wall(self) -> datetime.datetime:
79
+ """Return the current fake wall-clock time."""
80
+ return self._wall
81
+
82
+ def monotonic(self) -> float:
83
+ """Return the current fake monotonic time in seconds."""
84
+ return self._monotonic
85
+
86
+ def advance(self, seconds: float) -> None:
87
+ """Advance both wall and monotonic time by the same duration."""
88
+ self._wall += datetime.timedelta(seconds=seconds)
89
+ self._monotonic += seconds
90
+
91
+ def advance_wall(self, seconds: float) -> None:
92
+ """Advance only the wall clock (monotonic time is unaffected)."""
93
+ self._wall += datetime.timedelta(seconds=seconds)
94
+
95
+ def set_wall(self, value: datetime.datetime) -> None:
96
+ """Set the wall clock to an absolute value."""
97
+ self._wall = value
98
+
99
+
100
+ __all__: list[str] = [
101
+ "Clock",
102
+ "FakeClock",
103
+ "SystemClock",
104
+ ]
@@ -0,0 +1,46 @@
1
+ """flowsemantics.execution.context - Per-invocation execution context.
2
+
3
+ Layer: Domain
4
+ Module: flowsemantics.execution.context
5
+ Since: 0.1.0
6
+ Implements: SPEC.md section 4.1.3 (isolated execution context), section 6.2
7
+ Depends on: flowsemantics.execution.clock
8
+ Used by: FlowContract.execute / execute_async
9
+ See also: SPEC.md section 4.2 (qualified thread safety)
10
+
11
+ Notes:
12
+ - A fresh FlowContext is created per invocation. No mutable state is shared
13
+ between invocations of the same contract (SPEC.md section 4.1.3).
14
+ - The context carries the input, the injected clock, and (from Phase 2.3)
15
+ the cancellation token. User callbacks receive the input, not the whole
16
+ context, so they cannot accidentally mutate shared state.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+ from typing import Any
23
+
24
+ from flowsemantics.execution.clock import Clock, SystemClock
25
+
26
+
27
+ @dataclass
28
+ class FlowContext:
29
+ """Isolated per-invocation state for one flow execution.
30
+
31
+ Attributes:
32
+ input: The input value passed to execute().
33
+ clock: The injected clock. Defaults to SystemClock when the caller
34
+ does not supply one; deterministic replay MUST inject FakeClock.
35
+ state: Per-invocation mutable state for engine bookkeeping. Never
36
+ shared between invocations.
37
+ """
38
+
39
+ input: Any
40
+ clock: Clock = field(default_factory=SystemClock)
41
+ state: dict[str, Any] = field(default_factory=dict)
42
+
43
+
44
+ __all__: list[str] = [
45
+ "FlowContext",
46
+ ]
@@ -0,0 +1,118 @@
1
+ """flowsemantics.execution.outcome - Canonical outcome model (SPEC.md section 3).
2
+
3
+ Layer: Domain
4
+ Module: flowsemantics.execution.outcome
5
+ Since: 0.1.0
6
+ Implements: SPEC.md sections 3.1-3.8 (corrected v5 outcome model)
7
+ Depends on: stdlib only (dataclasses, enum, datetime)
8
+ Used by: execution engine, trace, simulation, conformance runner
9
+ See also: SPEC.md section 3, section 7
10
+
11
+ Notes:
12
+ - The v5 corrections are encoded here: interruption is separate from
13
+ recovery (B5), is_clean is finalization metadata not a status (B6),
14
+ secondary_exceptions includes cleanup exceptions even when the primary
15
+ succeeded (B7).
16
+ - All dataclasses are frozen: a FlowOutcome MUST be immutable after
17
+ construction (SPEC.md section 3.6).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import datetime
23
+ from dataclasses import dataclass, field
24
+ from enum import StrEnum
25
+ from typing import TYPE_CHECKING, Any, Literal
26
+
27
+ if TYPE_CHECKING:
28
+ from flowsemantics.execution.trace import ExecutionTrace
29
+
30
+
31
+ class ExecutionStatus(StrEnum):
32
+ """What happened while running. Exactly four members (SPEC 3.1)."""
33
+
34
+ COMPLETED = "completed"
35
+ FAILED = "failed"
36
+ CANCELLED = "cancelled"
37
+ TIMED_OUT = "timed_out"
38
+
39
+
40
+ class DecisionStatus(StrEnum):
41
+ """What the flow concluded. Exactly three members (SPEC 3.2)."""
42
+
43
+ APPROVED = "approved"
44
+ REJECTED = "rejected"
45
+ NO_MATCH = "no_match"
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class InterruptionInfo:
50
+ """Cancellation/timeout metadata. Never an exception (SPEC 3.3, B5)."""
51
+
52
+ kind: Literal["cancelled", "timed_out"]
53
+ source: str
54
+ timestamp: datetime.datetime
55
+ deadline: datetime.datetime | None = None
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class RecoveryInfo:
60
+ """Exception-recovery metadata only (SPEC 3.4, O1)."""
61
+
62
+ original_exception: BaseException
63
+ handler_rule_id: str
64
+ recovered_at: datetime.datetime
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class FinalizationInfo:
69
+ """Finalization metadata including is_clean (SPEC 3.5, B6, B8)."""
70
+
71
+ is_clean: bool
72
+ cleanup_exceptions: tuple[BaseException, ...] = ()
73
+ cleanup_budget_used: datetime.timedelta = datetime.timedelta(0)
74
+ cleanup_budget_exceeded: bool = False
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Effect:
79
+ """A proposed side effect. Data, not code (SPEC 3.7)."""
80
+
81
+ name: str
82
+ payload: Any = None
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class FlowOutcome:
87
+ """The structured result of one execution (SPEC 3.6).
88
+
89
+ Invariants enforced by construction in the engine:
90
+ - decision_status is absent unless execution_status is COMPLETED.
91
+ - primary_exception is absent unless execution_status is FAILED.
92
+ - interruption is populated only for CANCELLED and TIMED_OUT.
93
+ - recovery is populated only when an exception was recovered.
94
+ - secondary_exceptions includes cleanup exceptions even when the
95
+ primary execution succeeded (B7).
96
+ """
97
+
98
+ execution_status: ExecutionStatus
99
+ decision_status: DecisionStatus | None = None
100
+ value: Any = None
101
+ recovery: RecoveryInfo | None = None
102
+ interruption: InterruptionInfo | None = None
103
+ finalization: FinalizationInfo | None = None
104
+ primary_exception: BaseException | None = None
105
+ secondary_exceptions: tuple[BaseException, ...] = ()
106
+ effects: tuple[Effect, ...] = ()
107
+ trace: ExecutionTrace | None = field(default=None, compare=False)
108
+
109
+
110
+ __all__: list[str] = [
111
+ "DecisionStatus",
112
+ "Effect",
113
+ "ExecutionStatus",
114
+ "FinalizationInfo",
115
+ "FlowOutcome",
116
+ "InterruptionInfo",
117
+ "RecoveryInfo",
118
+ ]
@@ -0,0 +1,160 @@
1
+ """flowsemantics.execution.trace - ExecutionTrace, TraceEvent, TraceRecorder.
2
+
3
+ Layer: Domain
4
+ Module: flowsemantics.execution.trace
5
+ Since: 0.3.0
6
+ Implements: SPEC.md sections 3.8, 12.1, 12.3
7
+ Depends on: stdlib only
8
+ Used by: FlowContract.try_execute (when tracing enabled), explain()
9
+ See also: SPEC.md sections 3.8, 12.1-12.4
10
+
11
+ Notes:
12
+ - The event-type vocabulary is closed (SPEC 12.1): exactly the 22 types
13
+ listed there. TraceRecorder.emit validates against it.
14
+ - reason values are a closed enumeration (SPEC 12.1.1).
15
+ - Tracing is zero-cost when disabled: no recorder is created and no
16
+ clock reads happen (SPEC 12.3).
17
+ - Trace events MUST NOT contain input values, secrets, or exception
18
+ messages (SPEC 12.2).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import datetime
24
+ from collections.abc import Callable
25
+ from dataclasses import dataclass, field
26
+ from typing import Any
27
+
28
+ # Canonical event vocabulary (SPEC 12.1) - closed set, no others.
29
+ EVENT_TYPES: frozenset[str] = frozenset(
30
+ {
31
+ "condition_evaluated",
32
+ "condition_raised",
33
+ "guard_evaluated",
34
+ "action_executed",
35
+ "action_raised",
36
+ "catch_matched",
37
+ "catch_predicate_evaluated",
38
+ "catch_predicate_raised",
39
+ "catch_handled",
40
+ "catch_declined",
41
+ "rethrow_reached",
42
+ "hook_invoked",
43
+ "hook_raised",
44
+ "effect_proposed",
45
+ "skipped_by_short_circuit",
46
+ "skipped_by_mode",
47
+ "finally_started",
48
+ "finally_completed",
49
+ "finally_raised",
50
+ "cancelled_observed",
51
+ "timed_out_observed",
52
+ "rule_skipped",
53
+ }
54
+ )
55
+
56
+ # Closed reason enumeration (SPEC 12.1.1).
57
+ REASONS: frozenset[str] = frozenset(
58
+ {
59
+ "condition_false",
60
+ "guard_blocked",
61
+ "not_effective",
62
+ "earlier_match",
63
+ "mode_excluded",
64
+ }
65
+ )
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class TraceEvent:
70
+ """A single trace event (SPEC 3.8)."""
71
+
72
+ type: str
73
+ rule_id: str | None = None
74
+ timestamp: datetime.datetime | None = None
75
+ reason: str | None = None
76
+ contract_version: str | None = None
77
+ diagnostics: dict[str, Any] | None = None
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class ExecutionTrace:
82
+ """Ordered trace events plus contract version (SPEC 3.8)."""
83
+
84
+ contract_version: str
85
+ events: tuple[TraceEvent, ...] = field(default_factory=tuple)
86
+
87
+
88
+ class TraceRecorder:
89
+ """Collects trace events during one execution (SPEC 12.1, 12.3).
90
+
91
+ Created only when tracing is enabled; when disabled, no recorder
92
+ exists and evaluation pays zero tracing cost.
93
+ """
94
+
95
+ __slots__ = ("_contract_version", "_diagnostic_hook", "_events")
96
+
97
+ def __init__(
98
+ self,
99
+ contract_version: str,
100
+ diagnostic_hook: Callable[[TraceEvent], dict[str, Any] | None] | None = None,
101
+ ) -> None:
102
+ """Create an empty recorder for the given contract version.
103
+
104
+ diagnostic_hook is the application-supplied redaction-aware hook
105
+ (SPEC 12.2): it receives each event and may return a dict of
106
+ additional diagnostic fields. The library defers entirely to the
107
+ application's policy; absent a hook, no diagnostic data is added.
108
+ """
109
+ self._contract_version = contract_version
110
+ self._diagnostic_hook = diagnostic_hook
111
+ self._events: list[TraceEvent] = []
112
+
113
+ def emit(
114
+ self,
115
+ event_type: str,
116
+ *,
117
+ rule_id: str | None = None,
118
+ timestamp: datetime.datetime | None = None,
119
+ reason: str | None = None,
120
+ ) -> None:
121
+ """Append an event. Validates type and reason against the closed sets."""
122
+ if event_type not in EVENT_TYPES:
123
+ raise ValueError(f"unknown trace event type: {event_type!r}")
124
+ if reason is not None and reason not in REASONS:
125
+ raise ValueError(f"unknown trace reason: {reason!r}")
126
+ event = TraceEvent(
127
+ type=event_type,
128
+ rule_id=rule_id,
129
+ timestamp=timestamp,
130
+ reason=reason,
131
+ contract_version=self._contract_version,
132
+ )
133
+ if self._diagnostic_hook is not None:
134
+ extra = self._diagnostic_hook(event)
135
+ if extra:
136
+ event = TraceEvent(
137
+ type=event.type,
138
+ rule_id=event.rule_id,
139
+ timestamp=event.timestamp,
140
+ reason=event.reason,
141
+ contract_version=event.contract_version,
142
+ diagnostics=dict(extra),
143
+ )
144
+ self._events.append(event)
145
+
146
+ def build(self) -> ExecutionTrace:
147
+ """Produce the immutable ExecutionTrace."""
148
+ return ExecutionTrace(
149
+ contract_version=self._contract_version,
150
+ events=tuple(self._events),
151
+ )
152
+
153
+
154
+ __all__: list[str] = [
155
+ "EVENT_TYPES",
156
+ "REASONS",
157
+ "ExecutionTrace",
158
+ "TraceEvent",
159
+ "TraceRecorder",
160
+ ]
@@ -0,0 +1,18 @@
1
+ """flowsemantics.finalization - finally_ semantics and policies (Phase 2.5+).
2
+
3
+ Layer: Domain
4
+ Module: flowsemantics.finalization
5
+ Since: 0.0.0
6
+ Implements: n/a (subpackage marker)
7
+ Depends on: n/a (empty in Phase 0.0)
8
+ Used by: parent package; populated in Phase 2.5
9
+ See also: SPEC.md section 16, docs/finalization.md (Phase 2)
10
+
11
+ Notes:
12
+ - __all__ is empty in Phase 0.0. It grows as features are implemented.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ __all__: list[str] = []
18
+
@@ -0,0 +1,20 @@
1
+ """flowsemantics.portable - Declarative conditions and IR (v0.2).
2
+
3
+ Layer: Contracts
4
+ Module: flowsemantics.portable
5
+ Since: 0.0.0
6
+ Implements: n/a (subpackage marker)
7
+ Depends on: n/a (empty in Phase 0.0)
8
+ Used by: parent package; populated in v0.2
9
+ See also: SPEC.md section 14.2, spec/ir.schema.json
10
+
11
+ Notes:
12
+ - __all__ is empty in Phase 0.0. It grows as features are implemented.
13
+ - The declarative expression language is small and inspectable.
14
+ - Portable IR never carries host-language lambdas or serialized code.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ __all__: list[str] = []
20
+
flowsemantics/py.typed ADDED
File without changes
@@ -0,0 +1,23 @@
1
+ """flowsemantics.testing - Shipped pytest plugin and assertion helpers (Phase 1.8).
2
+
3
+ Layer: Tests
4
+ Module: flowsemantics.testing
5
+ Since: 0.0.0
6
+ Implements: n/a (subpackage marker)
7
+ Depends on: n/a (empty in Phase 0.0; pytest in Phase 1.8)
8
+ Used by: consumers who want the FlowSemantics pytest plugin
9
+ See also: docs/getting-started.md (Phase 1), pytest.ini markers
10
+
11
+ Notes:
12
+ - __all__ is empty in Phase 0.0. It grows in Phase 1.8 when the plugin
13
+ and assertion helpers are implemented.
14
+ - The plugin registers markers (conformance, flowsemantics_scenario,
15
+ slow, fuzz) and provides fixtures for downstream tests.
16
+ - pytest is a development dependency of the *test suite*, not of this
17
+ subpackage. This subpackage itself has no runtime dependency.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ __all__: list[str] = []
23
+
@@ -0,0 +1,22 @@
1
+ """flowsemantics.testing.conformance - Language-agnostic conformance runner.
2
+
3
+ Layer: Tests
4
+ Module: flowsemantics.testing.conformance
5
+ Since: 0.1.0
6
+ Implements: conformance/runner-protocol.md, spec/fixtures.md,
7
+ spec/vector.schema.json
8
+ Depends on: flowsemantics (public API), stdlib only
9
+ Used by: python -m flowsemantics.testing.conformance.runner
10
+ See also: SPEC.md section 14.3, 14.4
11
+
12
+ Notes:
13
+ - This subpackage is exempt from the zero-third-party audit rule
14
+ (ALLOWLISTED_SOURCE_DIRS includes "testing"), but it uses stdlib only
15
+ anyway.
16
+ - The runner executes vectors through the real public API. It never
17
+ reaches into private modules.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ __all__: list[str] = []