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,329 @@
1
+ """Python implementations of the fixture vocabulary (spec/fixtures.md).
2
+
3
+ Each fixture name resolves to a factory that produces the host-language
4
+ callable or value the conformance runner binds into a Flow pipeline.
5
+
6
+ Callable signatures used by the engine:
7
+ - condition / guard : (input) -> bool
8
+ - action : (input) -> value
9
+ - then stage : (input, previous_output) -> value
10
+ - catch handler : (input, exception) -> value
11
+ - hook : (input, rule_id, value) -> None
12
+ - cleanup : (FinallyContext) -> None (Phase 2.5)
13
+
14
+ Abstract error kinds (fixtures.md) map to concrete Python exceptions:
15
+ Kind.Timeout -> TimeoutError
16
+ Kind.Cancelled -> asyncio.CancelledError
17
+ Kind.ValueError-> ValueError
18
+ Kind.Any -> FixtureAnyError (a plain Exception subclass)
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import time
25
+ from collections.abc import Callable
26
+ from typing import Any
27
+
28
+
29
+ class FixtureAnyError(Exception):
30
+ """Concrete mapping for the abstract kind Kind.Any."""
31
+
32
+
33
+ KIND_MAP: dict[str, type[BaseException]] = {
34
+ "Kind.Timeout": TimeoutError,
35
+ "Kind.Cancelled": asyncio.CancelledError,
36
+ "Kind.ValueError": ValueError,
37
+ "Kind.Any": FixtureAnyError,
38
+ }
39
+
40
+
41
+ def exception_for_kind(kind: str) -> BaseException:
42
+ """Instantiate the concrete exception for an abstract error kind."""
43
+ exc_type = KIND_MAP.get(kind)
44
+ if exc_type is None:
45
+ raise KeyError(f"unknown abstract error kind: {kind!r}")
46
+ return exc_type(f"fixture error: {kind}")
47
+
48
+
49
+ def kind_of_exception(exc: BaseException) -> str:
50
+ """Reverse-map a concrete exception to its abstract kind."""
51
+ if isinstance(exc, TimeoutError):
52
+ return "Kind.Timeout"
53
+ if isinstance(exc, asyncio.CancelledError):
54
+ return "Kind.Cancelled"
55
+ if isinstance(exc, ValueError):
56
+ return "Kind.ValueError"
57
+ if isinstance(exc, FixtureAnyError):
58
+ return "Kind.Any"
59
+ return "Kind.Any"
60
+
61
+
62
+ def _param(params: dict[str, Any], *names: str, default: Any = None) -> Any:
63
+ for name in names:
64
+ if name in params:
65
+ return params[name]
66
+ return default
67
+
68
+
69
+ def _require_param(params: dict[str, Any], *names: str) -> Any:
70
+ value = _param(params, *names, default=_MISSING)
71
+ if value is _MISSING:
72
+ raise KeyError(f"missing required fixture parameter: {names[0]!r}")
73
+ return value
74
+
75
+
76
+ _MISSING = object()
77
+
78
+
79
+ # -- condition fixtures ----------------------------------------------------
80
+
81
+
82
+ def _cond_true(_input: Any) -> bool:
83
+ return True
84
+
85
+
86
+ def _cond_false(_input: Any) -> bool:
87
+ return False
88
+
89
+
90
+ def _make_cond_returns(value: bool) -> Callable[[Any], bool]:
91
+ def _cond(_input: Any) -> bool:
92
+ return value
93
+
94
+ return _cond
95
+
96
+
97
+ def _make_cond_throws(kind: str) -> Callable[[Any], bool]:
98
+ def _cond(_input: Any) -> bool:
99
+ raise exception_for_kind(kind)
100
+
101
+ return _cond
102
+
103
+
104
+ def _make_cond_returns_per_call(values: list[bool]) -> Callable[[Any], bool]:
105
+ state = {"index": 0}
106
+
107
+ def _cond(_input: Any) -> bool:
108
+ index = state["index"]
109
+ state["index"] = index + 1
110
+ if index >= len(values):
111
+ return values[-1]
112
+ return values[index]
113
+
114
+ return _cond
115
+
116
+
117
+ # -- action fixtures -------------------------------------------------------
118
+
119
+
120
+ def _make_action_const(value: Any) -> Callable[..., Any]:
121
+ def _action(_input: Any, *_args: Any) -> Any:
122
+ return value
123
+
124
+ return _action
125
+
126
+
127
+ def _make_action_throws(kind: str) -> Callable[..., Any]:
128
+ def _action(_input: Any, *_args: Any) -> Any:
129
+ raise exception_for_kind(kind)
130
+
131
+ return _action
132
+
133
+
134
+ def _make_action_prev() -> Callable[..., Any]:
135
+ def _action(_input: Any, previous: Any = None, *_args: Any) -> Any:
136
+ return previous
137
+
138
+ return _action
139
+
140
+
141
+ # -- guard fixtures --------------------------------------------------------
142
+
143
+
144
+ def _guard_true(_input: Any) -> bool:
145
+ return True
146
+
147
+
148
+ def _guard_false(_input: Any) -> bool:
149
+ return False
150
+
151
+
152
+ # -- catch fixtures --------------------------------------------------------
153
+
154
+
155
+ def _make_catch_handles(value: Any) -> Callable[[Any, BaseException], Any]:
156
+ def _handler(_input: Any, _exc: BaseException) -> Any:
157
+ return value
158
+
159
+ return _handler
160
+
161
+
162
+ def _make_catch_throws(kind: str) -> Callable[[Any, BaseException], Any]:
163
+ def _handler(_input: Any, _exc: BaseException) -> Any:
164
+ raise exception_for_kind(kind)
165
+
166
+ return _handler
167
+
168
+
169
+ # -- hook fixtures ---------------------------------------------------------
170
+
171
+
172
+ def _make_hook_records(records: list[dict[str, Any]]) -> Callable[[Any, str, Any], None]:
173
+ def _hook(_input: Any, rule_id: str, value: Any) -> None:
174
+ records.append({"rule_id": rule_id, "value": value})
175
+
176
+ return _hook
177
+
178
+
179
+ def _make_hook_throws(kind: str) -> Callable[[Any, str, Any], None]:
180
+ def _hook(_input: Any, _rule_id: str, _value: Any) -> None:
181
+ raise exception_for_kind(kind)
182
+
183
+ return _hook
184
+
185
+
186
+ # -- cleanup fixtures ------------------------------------------------------
187
+
188
+
189
+ def _cleanup_succeeds(_ctx: Any) -> None:
190
+ return None
191
+
192
+
193
+ def _make_cleanup_throws(kind: str) -> Callable[[Any], None]:
194
+ def _cleanup(_ctx: Any) -> None:
195
+ raise exception_for_kind(kind)
196
+
197
+ return _cleanup
198
+
199
+
200
+ def _cleanup_cooperative(ctx: Any) -> None:
201
+ token = getattr(ctx, "cancellation_token", None)
202
+ if token is not None and getattr(token, "cancelled", False):
203
+ return
204
+ return None
205
+
206
+
207
+ def _cleanup_ignores_token(_ctx: Any) -> None:
208
+ return None
209
+
210
+
211
+ def _make_cleanup_delays(ms: int) -> Callable[[Any], None]:
212
+ def _cleanup(_ctx: Any) -> None:
213
+ time.sleep(ms / 1000.0)
214
+
215
+ return _cleanup
216
+
217
+
218
+ # -- enrichment fixtures ---------------------------------------------------
219
+
220
+
221
+ def _make_enrichment_delayed(ms: int) -> Callable[[Any], Any]:
222
+ def _enrichment(_input: Any) -> Any:
223
+ time.sleep(ms / 1000.0)
224
+ return {"delayed_ms": ms}
225
+
226
+ return _enrichment
227
+
228
+
229
+ # -- input fixtures --------------------------------------------------------
230
+
231
+ _INPUTS: dict[str, Any] = {
232
+ "input.empty": {},
233
+ "input.order_50": {"total": 50},
234
+ "input.order_0": {"total": 0},
235
+ "input.order_large": {"total": 10000},
236
+ }
237
+
238
+
239
+ # -- registry --------------------------------------------------------------
240
+
241
+
242
+ class FixtureContext:
243
+ """Per-vector resolution context shared by fixtures in one vector."""
244
+
245
+ def __init__(self) -> None:
246
+ """Create an empty per-vector fixture context."""
247
+ self.records: list[dict[str, Any]] = []
248
+ self.hooks: list[Callable[..., Any]] = []
249
+
250
+
251
+ FixtureFactory = Callable[[dict[str, Any], FixtureContext], Any]
252
+
253
+
254
+ def _resolve_action_returns(params: dict[str, Any], ctx: FixtureContext) -> Any:
255
+ ref = _require_param(params, "ref", "fixture_ref")
256
+ return resolve_fixture(ref, ctx)
257
+
258
+
259
+ def _build_registry(ctx: FixtureContext) -> dict[str, FixtureFactory]:
260
+ return {
261
+ "cond.true": lambda p, c: _cond_true,
262
+ "cond.false": lambda p, c: _cond_false,
263
+ "cond.returns": lambda p, c: _make_cond_returns(bool(_require_param(p, "value", "v"))),
264
+ "cond.throws": lambda p, c: _make_cond_throws(str(_require_param(p, "kind"))),
265
+ "cond.returns_per_call": lambda p, c: _make_cond_returns_per_call(
266
+ list(_require_param(p, "values"))
267
+ ),
268
+ "action.const": lambda p, c: _make_action_const(_require_param(p, "v", "value")),
269
+ "action.throws": lambda p, c: _make_action_throws(str(_require_param(p, "kind"))),
270
+ "action.returns": _resolve_action_returns,
271
+ "action.prev": lambda p, c: _make_action_prev(),
272
+ "guard.true": lambda p, c: _guard_true,
273
+ "guard.false": lambda p, c: _guard_false,
274
+ "catch.handles": lambda p, c: _make_catch_handles(_param(p, "v", "value", default=None)),
275
+ "catch.throws": lambda p, c: _make_catch_throws(str(_require_param(p, "kind"))),
276
+ "hook.records": lambda p, c: _make_hook_records(ctx.records),
277
+ "hook.throws": lambda p, c: _make_hook_throws(str(_require_param(p, "kind"))),
278
+ "cleanup.succeeds": lambda p, c: _cleanup_succeeds,
279
+ "cleanup.throws": lambda p, c: _make_cleanup_throws(str(_require_param(p, "kind"))),
280
+ "cleanup.cooperative": lambda p, c: _cleanup_cooperative,
281
+ "cleanup.ignores_token": lambda p, c: _cleanup_ignores_token,
282
+ "cleanup.delays": lambda p, c: _make_cleanup_delays(int(_require_param(p, "ms"))),
283
+ "enrichment.delayed": lambda p, c: _make_enrichment_delayed(int(_require_param(p, "ms"))),
284
+ }
285
+
286
+
287
+ def resolve_fixture(ref: dict[str, Any], ctx: FixtureContext | None = None) -> Any:
288
+ """Resolve a FixtureRef ({fixture, params}) to a callable or value.
289
+
290
+ Raises:
291
+ KeyError: unknown fixture name or missing required parameter.
292
+ ValueError: invalid parameter type or value.
293
+ """
294
+ if ctx is None:
295
+ ctx = FixtureContext()
296
+ name = ref.get("fixture")
297
+ if not isinstance(name, str):
298
+ raise ValueError("fixture reference must have a string 'fixture' name")
299
+ params = ref.get("params") or {}
300
+ if not isinstance(params, dict):
301
+ raise ValueError("fixture 'params' must be an object")
302
+
303
+ if name in _INPUTS:
304
+ return _INPUTS[name]
305
+
306
+ registry = _build_registry(ctx)
307
+ factory = registry.get(name)
308
+ if factory is None:
309
+ raise KeyError(f"unknown fixture: {name!r}")
310
+ return factory(params, ctx)
311
+
312
+
313
+ def list_fixture_names() -> list[str]:
314
+ """Return all known fixture names (for coverage and diagnostics)."""
315
+ ctx = FixtureContext()
316
+ names = sorted(_build_registry(ctx).keys())
317
+ names.extend(sorted(_INPUTS.keys()))
318
+ return names
319
+
320
+
321
+ __all__: list[str] = [
322
+ "KIND_MAP",
323
+ "FixtureAnyError",
324
+ "FixtureContext",
325
+ "exception_for_kind",
326
+ "kind_of_exception",
327
+ "list_fixture_names",
328
+ "resolve_fixture",
329
+ ]