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,472 @@
1
+ """FlowSemantics conformance runner (conformance/runner-protocol.md).
2
+
3
+ Discovers *.json vectors recursively, resolves fixtures, builds a Flow
4
+ pipeline through the public API, executes it, and compares the observed
5
+ FlowOutcome against the vector's expected block.
6
+
7
+ Usage:
8
+ python -m flowsemantics.testing.conformance.runner --vectors <dir>
9
+
10
+ Exit code 0 iff every discovered vector passes.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import asyncio
17
+ import json
18
+ import sys
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from flowsemantics import (
24
+ Effect,
25
+ EvaluationMode,
26
+ Flow,
27
+ FlowOutcome,
28
+ )
29
+ from flowsemantics._spec import SPEC_VERSION
30
+ from flowsemantics.execution import FakeClock
31
+ from flowsemantics.testing.conformance.fixtures import (
32
+ KIND_MAP,
33
+ FixtureContext,
34
+ kind_of_exception,
35
+ resolve_fixture,
36
+ )
37
+
38
+ _SUPPORTED_SPEC = SPEC_VERSION
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class VectorResult:
43
+ """Outcome of running one conformance vector."""
44
+
45
+ vector_id: str
46
+ passed: bool
47
+ reason: str = ""
48
+
49
+
50
+ def _parse_version(text: str) -> tuple[int, int, int]:
51
+ parts = text.split(".")
52
+ if len(parts) != 3:
53
+ raise ValueError(f"bad spec_version: {text!r}")
54
+ return (int(parts[0]), int(parts[1]), int(parts[2]))
55
+
56
+
57
+ def _check_spec_version(vector: dict[str, Any]) -> str | None:
58
+ """Return an error string if the vector spec_version is incompatible."""
59
+ raw = vector.get("spec_version")
60
+ if not isinstance(raw, str):
61
+ return "missing or non-string spec_version"
62
+ try:
63
+ vec_v = _parse_version(raw)
64
+ sup_v = _parse_version(_SUPPORTED_SPEC)
65
+ except ValueError as exc:
66
+ return str(exc)
67
+ if vec_v > sup_v:
68
+ return f"spec_version {raw} is newer than supported {_SUPPORTED_SPEC}"
69
+ return None
70
+
71
+
72
+ def _validate_vector_shape(vector: dict[str, Any]) -> str | None:
73
+ """Minimal structural validation (full JSON-Schema check is Phase 6+)."""
74
+ for key in ("id", "spec_version", "spec_section", "pipeline", "input", "expected"):
75
+ if key not in vector:
76
+ return f"missing required key: {key!r}"
77
+ pipeline = vector["pipeline"]
78
+ if not isinstance(pipeline, dict):
79
+ return "pipeline must be an object"
80
+ if "portable_ir" not in pipeline and "rules" not in pipeline:
81
+ return "pipeline.rules or pipeline.portable_ir missing"
82
+ if "portable_ir" in pipeline:
83
+ return None
84
+ rules = pipeline["rules"]
85
+ if not isinstance(rules, list):
86
+ return "pipeline.rules must be an array"
87
+ for i, rule in enumerate(rules):
88
+ if not isinstance(rule, dict):
89
+ return f"rules[{i}] must be an object"
90
+ kind = rule.get("kind", "when")
91
+ if kind not in ("when", "when_not", "then"):
92
+ return f"rules[{i}] unknown kind: {kind!r}"
93
+ if "id" not in rule or "action" not in rule:
94
+ return f"rules[{i}] missing 'id' or 'action'"
95
+ if kind != "then" and "condition" not in rule:
96
+ return f"rules[{i}] missing 'condition'"
97
+ expected = vector["expected"]
98
+ if not isinstance(expected, dict):
99
+ return "expected must be an object"
100
+ if "execution_status" not in expected or "has_finalization" not in expected:
101
+ return "expected missing execution_status or has_finalization"
102
+ return None
103
+
104
+
105
+ def _build_flow(vector: dict[str, Any], ctx: FixtureContext) -> Flow | str:
106
+ """Build a Flow from the vector pipeline. Returns error string on failure."""
107
+ pipeline = vector["pipeline"]
108
+
109
+ # Portable IR pipeline: the vector carries a canonical IR document
110
+ # (SPEC 14.2) and the runner rebuilds an executable flow from it.
111
+ if "portable_ir" in pipeline:
112
+ try:
113
+ return Flow.from_ir(pipeline["portable_ir"])
114
+ except Exception as exc:
115
+ return f"portable_ir rejected: {exc}"
116
+
117
+ mode_raw = pipeline.get("mode", "FirstMatch")
118
+ try:
119
+ mode = EvaluationMode(mode_raw)
120
+ except ValueError:
121
+ return f"unknown evaluation mode: {mode_raw!r}"
122
+
123
+ flow = Flow().with_mode(mode)
124
+
125
+ for rule in pipeline["rules"]:
126
+ kind = rule.get("kind", "when")
127
+ try:
128
+ action = resolve_fixture(rule["action"], ctx)
129
+ except (KeyError, ValueError) as exc:
130
+ return f"fixture resolution failed: {exc}"
131
+ rule_effects = tuple(
132
+ Effect(name=str(e["name"]), payload=e.get("payload")) for e in rule.get("effects", [])
133
+ )
134
+ if kind == "then":
135
+ flow.then(action, id=str(rule["id"]), effects=rule_effects)
136
+ continue
137
+ try:
138
+ condition = resolve_fixture(rule["condition"], ctx)
139
+ except (KeyError, ValueError) as exc:
140
+ return f"fixture resolution failed: {exc}"
141
+ guard = None
142
+ if rule.get("guard") is not None:
143
+ try:
144
+ guard = resolve_fixture(rule["guard"], ctx)
145
+ except (KeyError, ValueError) as exc:
146
+ return f"fixture resolution failed: {exc}"
147
+ if kind == "when_not":
148
+ flow.when_not(
149
+ condition,
150
+ then=action,
151
+ id=str(rule["id"]),
152
+ guard=guard,
153
+ priority=int(rule.get("priority", 0)),
154
+ effects=rule_effects,
155
+ )
156
+ else:
157
+ flow.when(
158
+ condition,
159
+ then=action,
160
+ id=str(rule["id"]),
161
+ guard=guard,
162
+ priority=int(rule.get("priority", 0)),
163
+ effects=rule_effects,
164
+ )
165
+
166
+ # Exception handlers (SPEC 11.1-11.4). exc_kind names an abstract
167
+ # error kind; the adapter maps it to the concrete exception type.
168
+ for catch in pipeline.get("catches", []):
169
+ ckind = catch.get("kind")
170
+ if ckind == "rethrow":
171
+ flow.rethrow()
172
+ continue
173
+ if ckind == "any":
174
+ try:
175
+ handler = resolve_fixture(catch["handler"], ctx)
176
+ except (KeyError, ValueError) as exc:
177
+ return f"fixture resolution failed: {exc}"
178
+ flow.catch_any(handler, id=catch.get("id"))
179
+ continue
180
+ exc_kind = catch.get("exc_kind")
181
+ exc_type = KIND_MAP.get(exc_kind or "")
182
+ if exc_type is None or not issubclass(exc_type, Exception):
183
+ return f"unknown or uncatchable exc_kind: {exc_kind!r}"
184
+ try:
185
+ handler = resolve_fixture(catch["handler"], ctx)
186
+ except (KeyError, ValueError) as exc:
187
+ return f"fixture resolution failed: {exc}"
188
+ if ckind == "typed":
189
+ flow.catch(exc_type, handler, id=catch.get("id"))
190
+ elif ckind == "when":
191
+ try:
192
+ pred = resolve_fixture(catch["predicate"], ctx)
193
+ except (KeyError, ValueError) as exc:
194
+ return f"fixture resolution failed: {exc}"
195
+
196
+ def _predicate(i: Any, e: BaseException, f: Any = pred) -> bool:
197
+ return bool(f(i))
198
+
199
+ flow.catch_when(exc_type, _predicate, handler, id=catch.get("id"))
200
+ else:
201
+ return f"unknown catch kind: {ckind!r}"
202
+
203
+ # Observable hooks (SPEC 11.5).
204
+ for hook_ref in pipeline.get("on_match", []):
205
+ try:
206
+ hook = resolve_fixture(hook_ref, ctx)
207
+ except (KeyError, ValueError) as exc:
208
+ return f"fixture resolution failed: {exc}"
209
+ flow.on_match(hook)
210
+
211
+ # Finalizer (SPEC 11.8): a named cleanup fixture.
212
+ finally_ref = pipeline.get("finally")
213
+ if finally_ref is not None:
214
+ ref = finally_ref if isinstance(finally_ref, dict) else {"fixture": finally_ref}
215
+ try:
216
+ cleanup = resolve_fixture(ref, ctx)
217
+ except (KeyError, ValueError) as exc:
218
+ return f"fixture resolution failed: {exc}"
219
+ flow.finally_(cleanup)
220
+ if pipeline.get("finally_policy") is not None:
221
+ flow.with_finally_policy(str(pipeline["finally_policy"]))
222
+ if pipeline.get("finally_timeout_ms") is not None:
223
+ flow.with_finally_timeout(int(pipeline["finally_timeout_ms"]))
224
+
225
+ fallback = pipeline.get("fallback")
226
+ if fallback is not None:
227
+ fkind = fallback.get("kind")
228
+ if fkind == "otherwise":
229
+ try:
230
+ action = resolve_fixture(fallback["action"], ctx)
231
+ except (KeyError, ValueError) as exc:
232
+ return f"fixture resolution failed: {exc}"
233
+ flow.otherwise(action)
234
+ elif fkind == "default_if_no_match":
235
+ flow.default_if_no_match(fallback.get("value"))
236
+ else:
237
+ return f"unknown fallback kind: {fkind!r}"
238
+ return flow
239
+
240
+
241
+ def _resolve_input(vector: dict[str, Any], ctx: FixtureContext) -> tuple[Any, str | None]:
242
+ try:
243
+ return resolve_fixture(vector["input"], ctx), None
244
+ except (KeyError, ValueError) as exc:
245
+ return None, f"fixture resolution failed: {exc}"
246
+
247
+
248
+ def _compare_expected(outcome: FlowOutcome, expected: dict[str, Any]) -> str | None:
249
+ """Compare observed outcome against expected per runner-protocol.md."""
250
+ if outcome.execution_status.name != expected["execution_status"]:
251
+ return (
252
+ f"execution_status: expected {expected['execution_status']}, "
253
+ f"got {outcome.execution_status.name}"
254
+ )
255
+
256
+ exp_decision = expected.get("decision_status")
257
+ got_decision = outcome.decision_status.name if outcome.decision_status is not None else None
258
+ if exp_decision != got_decision:
259
+ return f"decision_status: expected {exp_decision}, got {got_decision}"
260
+
261
+ if "value" in expected and outcome.value != expected["value"]:
262
+ return f"value: expected {expected['value']!r}, got {outcome.value!r}"
263
+
264
+ if expected.get("has_recovery", False) != (outcome.recovery is not None):
265
+ return "has_recovery mismatch"
266
+
267
+ if expected.get("has_interruption", False) != (outcome.interruption is not None):
268
+ return "has_interruption mismatch"
269
+
270
+ exp_kind = expected.get("interruption_kind")
271
+ got_kind = outcome.interruption.kind if outcome.interruption is not None else None
272
+ if exp_kind != got_kind:
273
+ return f"interruption_kind: expected {exp_kind}, got {got_kind}"
274
+
275
+ if expected["has_finalization"] != (outcome.finalization is not None):
276
+ return "has_finalization mismatch"
277
+
278
+ exp_clean = expected.get("is_clean")
279
+ got_clean = outcome.finalization.is_clean if outcome.finalization is not None else None
280
+ if exp_clean != got_clean:
281
+ return f"is_clean: expected {exp_clean}, got {got_clean}"
282
+
283
+ exp_sec = expected.get("secondary_exceptions_count", 0)
284
+ if exp_sec != len(outcome.secondary_exceptions):
285
+ return (
286
+ f"secondary_exceptions_count: expected {exp_sec}, "
287
+ f"got {len(outcome.secondary_exceptions)}"
288
+ )
289
+
290
+ exp_primary = expected.get("primary_exception_kind")
291
+ got_primary = (
292
+ kind_of_exception(outcome.primary_exception)
293
+ if outcome.primary_exception is not None
294
+ else None
295
+ )
296
+ if exp_primary != got_primary:
297
+ return f"primary_exception_kind: expected {exp_primary}, got {got_primary}"
298
+
299
+ exp_effects = expected.get("effects")
300
+ if exp_effects is not None:
301
+ got_effects = [{"name": e.name, "payload": e.payload} for e in outcome.effects]
302
+ normalized = [{"name": e.get("name"), "payload": e.get("payload")} for e in exp_effects]
303
+ if got_effects != normalized:
304
+ return f"effects: expected {normalized!r}, got {got_effects!r}"
305
+
306
+ return None
307
+
308
+
309
+ def _compare_trace(vector: dict[str, Any], outcome: FlowOutcome) -> str | None:
310
+ """Compare observed trace per runner-protocol.md trace rules."""
311
+ expected_events = vector.get("trace")
312
+ if expected_events is None:
313
+ return None
314
+ if outcome.trace is None:
315
+ return "trace expected but trace was not collected"
316
+ observed = [
317
+ {"type": e.type, "rule_id": e.rule_id, "reason": e.reason} for e in outcome.trace.events
318
+ ]
319
+ expected = [
320
+ {"type": e.get("type"), "rule_id": e.get("rule_id"), "reason": e.get("reason")}
321
+ for e in expected_events
322
+ ]
323
+
324
+ def _matches(obs: dict[str, Any], exp: dict[str, Any]) -> bool:
325
+ if obs["type"] != exp["type"]:
326
+ return False
327
+ if exp.get("rule_id") is not None and obs["rule_id"] != exp["rule_id"]:
328
+ return False
329
+ return exp.get("reason") is None or obs["reason"] == exp["reason"]
330
+
331
+ if vector.get("trace_subset"):
332
+ # Every expected event must appear in order; extras allowed.
333
+ pos = 0
334
+ for exp in expected:
335
+ found = False
336
+ while pos < len(observed):
337
+ if _matches(observed[pos], exp):
338
+ found = True
339
+ pos += 1
340
+ break
341
+ pos += 1
342
+ if not found:
343
+ return f"trace subset: missing event {exp!r}"
344
+ return None
345
+
346
+ if len(observed) != len(expected):
347
+ return f"trace length: expected {len(expected)}, got {len(observed)}"
348
+ for i, (obs, exp) in enumerate(zip(observed, expected, strict=True)):
349
+ if not _matches(obs, exp):
350
+ return f"trace[{i}]: expected {exp!r}, got {obs!r}"
351
+ return None
352
+
353
+
354
+ def run_vector(path: Path) -> VectorResult:
355
+ """Run a single vector file. Never raises; returns PASS/FAIL result."""
356
+ vector_id = path.stem
357
+ try:
358
+ vector = json.loads(path.read_text(encoding="utf-8"))
359
+ except (OSError, json.JSONDecodeError) as exc:
360
+ return VectorResult(vector_id, False, f"runner failure: cannot parse: {exc}")
361
+ if not isinstance(vector, dict):
362
+ return VectorResult(vector_id, False, "runner failure: vector is not an object")
363
+
364
+ vector_id = str(vector.get("id", vector_id))
365
+
366
+ version_error = _check_spec_version(vector)
367
+ if version_error is not None:
368
+ return VectorResult(vector_id, False, f"runner failure: {version_error}")
369
+
370
+ shape_error = _validate_vector_shape(vector)
371
+ if shape_error is not None:
372
+ return VectorResult(vector_id, False, f"runner failure: {shape_error}")
373
+
374
+ ctx = FixtureContext()
375
+ expected_error = vector.get("expected_error")
376
+
377
+ built = _build_flow(vector, ctx)
378
+ if isinstance(built, str):
379
+ if expected_error is not None:
380
+ return VectorResult(vector_id, expected_error in built, built)
381
+ return VectorResult(vector_id, False, built)
382
+
383
+ input_value, input_error = _resolve_input(vector, ctx)
384
+ if input_error is not None:
385
+ if expected_error is not None:
386
+ return VectorResult(vector_id, expected_error in input_error, input_error)
387
+ return VectorResult(vector_id, False, input_error)
388
+
389
+ try:
390
+ contract = built.compile()
391
+ except Exception as exc: # StructureError and friends
392
+ if expected_error is not None:
393
+ return VectorResult(vector_id, expected_error in str(exc), f"compile failed: {exc}")
394
+ return VectorResult(vector_id, False, f"compile failed: {exc}")
395
+
396
+ clock = FakeClock()
397
+ trace_enabled = "trace" in vector
398
+ try:
399
+ if vector["pipeline"].get("execution") == "async":
400
+ outcome = asyncio.run(
401
+ contract.try_execute_async(input_value, clock=clock, trace=trace_enabled)
402
+ )
403
+ else:
404
+ outcome = contract.try_execute(input_value, clock=clock, trace=trace_enabled)
405
+ except Exception as exc:
406
+ if expected_error is not None:
407
+ return VectorResult(vector_id, expected_error in str(exc), f"execution raised: {exc}")
408
+ raise
409
+
410
+ if expected_error is not None:
411
+ return VectorResult(
412
+ vector_id,
413
+ False,
414
+ f"expected rejection containing {expected_error!r} but execution completed",
415
+ )
416
+
417
+ mismatch = _compare_expected(outcome, vector["expected"])
418
+ if mismatch is not None:
419
+ return VectorResult(vector_id, False, mismatch)
420
+
421
+ trace_error = _compare_trace(vector, outcome)
422
+ if trace_error is not None:
423
+ return VectorResult(vector_id, False, trace_error)
424
+
425
+ return VectorResult(vector_id, True)
426
+
427
+
428
+ def discover_vectors(vectors_dir: Path) -> list[Path]:
429
+ """Recursively discover *.json vector files (runner-protocol.md)."""
430
+ return sorted(vectors_dir.rglob("*.json"))
431
+
432
+
433
+ def main(argv: list[str] | None = None) -> int:
434
+ """CLI entry point. Returns 0 iff all discovered vectors pass."""
435
+ parser = argparse.ArgumentParser(
436
+ prog="flowsemantics-conformance",
437
+ description="Run FlowSemantics conformance vectors.",
438
+ )
439
+ parser.add_argument(
440
+ "--vectors",
441
+ type=Path,
442
+ required=True,
443
+ help="Directory containing vector JSON files (searched recursively).",
444
+ )
445
+ args = parser.parse_args(argv)
446
+
447
+ vectors_dir: Path = args.vectors
448
+ if not vectors_dir.is_dir():
449
+ print(f"ERROR: vectors directory not found: {vectors_dir}", file=sys.stderr)
450
+ return 2
451
+
452
+ paths = discover_vectors(vectors_dir)
453
+ if not paths:
454
+ print("RESULT: 0/0 passed (no vectors discovered)")
455
+ return 0
456
+
457
+ passed = 0
458
+ for path in paths:
459
+ result = run_vector(path)
460
+ if result.passed:
461
+ passed += 1
462
+ print(f"PASS {result.vector_id}")
463
+ else:
464
+ print(f"FAIL {result.vector_id}: {result.reason}")
465
+
466
+ total = len(paths)
467
+ print(f"RESULT: {passed}/{total} passed")
468
+ return 0 if passed == total else 1
469
+
470
+
471
+ if __name__ == "__main__":
472
+ sys.exit(main())
File without changes
@@ -0,0 +1,18 @@
1
+ """flowsemantics.trace - ExecutionTrace, TraceEvent, explain (Phase 3.0+).
2
+
3
+ Layer: Domain
4
+ Module: flowsemantics.trace
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 3.0
9
+ See also: SPEC.md section 12.1, docs/tracing.md (Phase 3)
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,36 @@
1
+ """flowsemantics.trust - Trust layer: replay, shadow, explain helpers.
2
+
3
+ Layer: Trust
4
+ Module: flowsemantics.trust
5
+ Since: 0.3.0
6
+ Implements: SPEC.md section 12
7
+ Depends on: flowsemantics.configuration, flowsemantics.execution
8
+ Used by: consumers needing replay/shadow/audit capabilities
9
+ See also: SPEC.md sections 12.5-12.7, 9.5
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from flowsemantics.trust.replay import (
15
+ ReplayError,
16
+ ReplayMode,
17
+ ReplayRecord,
18
+ ReplayResult,
19
+ record,
20
+ replay,
21
+ sign,
22
+ )
23
+ from flowsemantics.trust.shadow import ShadowEntry, ShadowReport, shadow
24
+
25
+ __all__: list[str] = [
26
+ "ReplayError",
27
+ "ReplayMode",
28
+ "ReplayRecord",
29
+ "ReplayResult",
30
+ "ShadowEntry",
31
+ "ShadowReport",
32
+ "record",
33
+ "replay",
34
+ "shadow",
35
+ "sign",
36
+ ]