flux-sim-engine 0.2.0__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.
Files changed (165) hide show
  1. flux_engine/__init__.py +22 -0
  2. flux_engine/_links.py +55 -0
  3. flux_engine/_vendor/__init__.py +5 -0
  4. flux_engine/_vendor/flux_spec/NOTICE +19 -0
  5. flux_engine/_vendor/flux_spec/VENDOR-NOTES.md +104 -0
  6. flux_engine/_vendor/flux_spec/__init__.py +9 -0
  7. flux_engine/_vendor/flux_spec/bundle.py +410 -0
  8. flux_engine/_vendor/flux_spec/enforce.py +316 -0
  9. flux_engine/_vendor/flux_spec/schema/flux-enforcement-0.5.0.json +121 -0
  10. flux_engine/_vendor/flux_spec/schema/flux-manifest-0.5.0.json +153 -0
  11. flux_engine/_vendor/flux_spec/schema/flux-schema-0.2.0.json +465 -0
  12. flux_engine/_vendor/flux_spec/schema/flux-schema-0.3.0.json +876 -0
  13. flux_engine/_vendor/flux_spec/schema/flux-schema-0.4.0.json +1601 -0
  14. flux_engine/_vendor/flux_spec/schema/flux-schema-0.4.1.json +1668 -0
  15. flux_engine/_vendor/flux_spec/schema/flux-schema-0.5.0.json +1669 -0
  16. flux_engine/_vendor/flux_spec/schema/flux-schema-latest.json +1669 -0
  17. flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.4.0.json +795 -0
  18. flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.4.1.json +852 -0
  19. flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.5.0.json +852 -0
  20. flux_engine/_vendor/flux_spec/validate.py +537 -0
  21. flux_engine/_vendor/flux_spec/vectors/enforcement-vectors.json +935 -0
  22. flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.3.json +5234 -0
  23. flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.4.json +5437 -0
  24. flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.5.json +5498 -0
  25. flux_engine/_vocabulary.py +141 -0
  26. flux_engine/accuracy/__init__.py +5 -0
  27. flux_engine/accuracy/_scoring/__init__.py +24 -0
  28. flux_engine/accuracy/accuracy_record.py +96 -0
  29. flux_engine/accuracy/policy.py +158 -0
  30. flux_engine/accuracy/records.py +264 -0
  31. flux_engine/accuracy/store.py +169 -0
  32. flux_engine/api/__init__.py +163 -0
  33. flux_engine/api/accuracy.py +209 -0
  34. flux_engine/api/agentic.py +134 -0
  35. flux_engine/api/calibration.py +125 -0
  36. flux_engine/api/claims.py +93 -0
  37. flux_engine/api/digests.py +73 -0
  38. flux_engine/api/emit.py +78 -0
  39. flux_engine/api/expressions.py +72 -0
  40. flux_engine/api/fidelity.py +110 -0
  41. flux_engine/api/lineage.py +78 -0
  42. flux_engine/api/stages.py +242 -0
  43. flux_engine/api/verdict.py +108 -0
  44. flux_engine/calibrate/__init__.py +5 -0
  45. flux_engine/calibrate/declared.py +253 -0
  46. flux_engine/calibrate/provenance.py +113 -0
  47. flux_engine/cli/__init__.py +2146 -0
  48. flux_engine/cli/__main__.py +17 -0
  49. flux_engine/cli/_documents.py +226 -0
  50. flux_engine/cli/_hints.py +118 -0
  51. flux_engine/cli/_init.py +152 -0
  52. flux_engine/cli/_progress.py +124 -0
  53. flux_engine/concordance/__init__.py +127 -0
  54. flux_engine/concordance/boundary/__init__.py +78 -0
  55. flux_engine/concordance/boundary/merkle.py +287 -0
  56. flux_engine/concordance/boundary/slice.py +429 -0
  57. flux_engine/concordance/boundary/statistic.py +561 -0
  58. flux_engine/concordance/boundary/store.py +334 -0
  59. flux_engine/concordance/boundary/vault.py +357 -0
  60. flux_engine/concordance/compiler.py +542 -0
  61. flux_engine/concordance/errors.py +189 -0
  62. flux_engine/concordance/gate.py +525 -0
  63. flux_engine/concordance/predicate.py +1217 -0
  64. flux_engine/concordance/record.py +554 -0
  65. flux_engine/concordance/verifier.py +583 -0
  66. flux_engine/core/__init__.py +5 -0
  67. flux_engine/core/artifact.py +99 -0
  68. flux_engine/core/canonical.py +369 -0
  69. flux_engine/core/clock.py +437 -0
  70. flux_engine/core/digest.py +288 -0
  71. flux_engine/core/errors.py +277 -0
  72. flux_engine/core/fixedpoint.py +929 -0
  73. flux_engine/core/lrm.py +158 -0
  74. flux_engine/core/rng.py +736 -0
  75. flux_engine/core/seedtree.py +891 -0
  76. flux_engine/core/trace.py +423 -0
  77. flux_engine/describe.py +207 -0
  78. flux_engine/engine.py +257 -0
  79. flux_engine/evidence/__init__.py +5 -0
  80. flux_engine/evidence/pack.py +411 -0
  81. flux_engine/evidence/report.py +243 -0
  82. flux_engine/expr/__init__.py +133 -0
  83. flux_engine/expr/ast.py +312 -0
  84. flux_engine/expr/attrs.py +386 -0
  85. flux_engine/expr/check.py +278 -0
  86. flux_engine/expr/compile.py +322 -0
  87. flux_engine/expr/errors.py +256 -0
  88. flux_engine/expr/lexer.py +297 -0
  89. flux_engine/expr/parser.py +313 -0
  90. flux_engine/expr/types.py +177 -0
  91. flux_engine/generator/__init__.py +97 -0
  92. flux_engine/generator/families.py +325 -0
  93. flux_engine/generator/paths.py +227 -0
  94. flux_engine/generator/rows.py +918 -0
  95. flux_engine/generator/statistics.py +524 -0
  96. flux_engine/governance/__init__.py +87 -0
  97. flux_engine/governance/audit.py +307 -0
  98. flux_engine/governance/gate.py +334 -0
  99. flux_engine/governance/skills.py +220 -0
  100. flux_engine/governance/sovereignty.py +251 -0
  101. flux_engine/lineage/__init__.py +5 -0
  102. flux_engine/lineage/emitter.py +398 -0
  103. flux_engine/py.typed +0 -0
  104. flux_engine/runtime/__init__.py +153 -0
  105. flux_engine/runtime/campaign.py +407 -0
  106. flux_engine/runtime/cast.py +283 -0
  107. flux_engine/runtime/detector.py +222 -0
  108. flux_engine/runtime/errors.py +58 -0
  109. flux_engine/runtime/experiment.py +311 -0
  110. flux_engine/runtime/journey.py +383 -0
  111. flux_engine/runtime/jurisdiction.py +72 -0
  112. flux_engine/runtime/payloads.py +124 -0
  113. flux_engine/runtime/signals.py +334 -0
  114. flux_engine/runtime/temperature.py +156 -0
  115. flux_engine/seam/__init__.py +5 -0
  116. flux_engine/seam/attest.py +290 -0
  117. flux_engine/seam/conform.py +448 -0
  118. flux_engine/seam/contract.py +605 -0
  119. flux_engine/seam/emit.py +488 -0
  120. flux_engine/seam/mapping.py +299 -0
  121. flux_engine/seam/resolve.py +1087 -0
  122. flux_engine/seam/sinks.py +157 -0
  123. flux_engine/spec/__init__.py +134 -0
  124. flux_engine/spec/bundle.py +25 -0
  125. flux_engine/spec/enforce.py +31 -0
  126. flux_engine/spec/validate.py +28 -0
  127. flux_engine/stages/__init__.py +30 -0
  128. flux_engine/stages/apply.py +447 -0
  129. flux_engine/stages/errors.py +315 -0
  130. flux_engine/stages/layout.py +292 -0
  131. flux_engine/stages/pipeline.py +600 -0
  132. flux_engine/stages/plan.py +241 -0
  133. flux_engine/stages/replay.py +83 -0
  134. flux_engine/stages/run.py +208 -0
  135. flux_engine/stages/ship.py +934 -0
  136. flux_engine/stages/validate.py +93 -0
  137. flux_engine/stages/verify.py +1129 -0
  138. flux_engine/starter/__init__.py +161 -0
  139. flux_engine/starter/bundle/detector.flux.yml +15 -0
  140. flux_engine/starter/bundle/journey.flux.yml +23 -0
  141. flux_engine/starter/bundle/module.flux.yml +16 -0
  142. flux_engine/starter/bundle/payment-recovery.fluid.yml +30 -0
  143. flux_engine/starter/bundle/persona.flux.yml +26 -0
  144. flux_engine/starter/bundle/signal.flux.yml +13 -0
  145. flux_engine/starter/bundle/simulation.flux.yml +29 -0
  146. flux_engine/starter/bundle/taxonomy.flux.yml +17 -0
  147. flux_engine/starter/bundle/treatment.flux.yml +13 -0
  148. flux_engine/starter/bundle/world.flux.yml +20 -0
  149. flux_engine/verticals/__init__.py +85 -0
  150. flux_engine/verticals/telco.py +89 -0
  151. flux_engine/world/__init__.py +89 -0
  152. flux_engine/world/derived.py +195 -0
  153. flux_engine/world/errors.py +41 -0
  154. flux_engine/world/families.py +260 -0
  155. flux_engine/world/population.py +602 -0
  156. flux_engine/world/tracing.py +66 -0
  157. flux_engine/world/values.py +121 -0
  158. flux_sim_engine-0.2.0.dist-info/METADATA +108 -0
  159. flux_sim_engine-0.2.0.dist-info/RECORD +165 -0
  160. flux_sim_engine-0.2.0.dist-info/WHEEL +5 -0
  161. flux_sim_engine-0.2.0.dist-info/entry_points.txt +2 -0
  162. flux_sim_engine-0.2.0.dist-info/licenses/LICENSE +202 -0
  163. flux_sim_engine-0.2.0.dist-info/licenses/NOTICE +10 -0
  164. flux_sim_engine-0.2.0.dist-info/licenses/flux_engine/_vendor/flux_spec/NOTICE +19 -0
  165. flux_sim_engine-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,220 @@
1
+ # Copyright 2026 Agentics Transformation Limited
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """Skill bindings: static validation at plan time, and the v0.3 fidelity gate.
6
+
7
+ Two independent checks, both named in the schema.
8
+
9
+ **Static validation** (``validate_skill_bindings`` / ``require_valid_skill_bindings``)
10
+ mirrors the FLUX offline reference validator's cross-document check --
11
+ schema ``$defs/skillBinding``: "``model``: Must be a member of
12
+ agentPolicy.allowedModels (validator-enforced)" and "``tokenBudget``:
13
+ Per-skill budget; must not exceed agentPolicy.tokenBudget
14
+ (validator-enforced)". This module runs the identical rule inside
15
+ flux_engine, at plan time, before any call the binding would authorize is
16
+ ever made -- it does not re-derive the rule from the RFC-04 decision
17
+ contract in :mod:`flux_engine.spec.enforce`, because a skill binding is a
18
+ document-shape question (does this binding fit inside the policy that
19
+ governs its document?), not a runtime enforcement decision (may this one
20
+ call proceed?). :func:`flux_engine.governance.gate.decide` answers the
21
+ second question, at call time, using the actual narrowed budget.
22
+
23
+ **The v0.3 fidelity gate** (``require_supported_fidelity``) is
24
+ independent of skill bindings: ``Simulation.spec.fidelity: agentic``
25
+ (schema, escalating: deterministic / stochastic / agentic) requires the
26
+ ``flux_engine_agentic`` extension package, which is the only thing in
27
+ this engine that reaches a real language model (see
28
+ :mod:`flux_engine.api.agentic`'s module docstring: "the agentic tier
29
+ ships separately and can be uninstalled without touching anything
30
+ else"). The runtime skill registry itself is out of scope for v0.3 -- this
31
+ module's whole contribution to it is refusing to proceed when the
32
+ extension the registry would need is not installed.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import importlib.util
38
+ from dataclasses import dataclass
39
+ from typing import Any, Iterable, Mapping, Optional, Tuple
40
+
41
+ from flux_engine.core.errors import FluxError, register
42
+
43
+ __all__ = [
44
+ "AGENTIC_EXTENSION_MODULE",
45
+ "FLX_4101",
46
+ "FLX_4102",
47
+ "SkillBindingCheck",
48
+ "SkillBindingViolation",
49
+ "UnsupportedFidelity",
50
+ "agentic_extension_available",
51
+ "require_supported_fidelity",
52
+ "require_valid_skill_bindings",
53
+ "validate_skill_bindings",
54
+ ]
55
+
56
+ FLX_4101 = register(
57
+ "FLX-4101",
58
+ "fidelity: agentic declared without the agentic extension installed",
59
+ "Simulation.spec.fidelity: agentic (schema-declared) requires the "
60
+ "flux_engine_agentic extension package -- the only thing in this "
61
+ "engine that reaches a real language model. It is not installed in "
62
+ "this environment. deterministic and stochastic fidelity need nothing "
63
+ "beyond the core engine and are unaffected.",
64
+ )
65
+
66
+ FLX_4102 = register(
67
+ "FLX-4102",
68
+ "skill binding is not permitted by the document's agentPolicy",
69
+ "A skill's declared model is not a member of agentPolicy.allowedModels, or "
70
+ "its declared tokenBudget exceeds agentPolicy.tokenBudget (schema "
71
+ "$defs/skillBinding: both are validator-enforced). This mirrors the FLUX "
72
+ "offline validator's cross-document check and runs at plan time, before any "
73
+ "call the binding would authorize is ever made.",
74
+ )
75
+
76
+ #: The extension package name checked by :func:`agentic_extension_available`.
77
+ #: A plain string, not an import, so checking for it never imports it.
78
+ AGENTIC_EXTENSION_MODULE = "flux_engine_agentic"
79
+
80
+
81
+ class UnsupportedFidelity(FluxError):
82
+ """Raised for ``fidelity: agentic`` when the agentic extension is absent."""
83
+
84
+ def __init__(self, fidelity: str) -> None:
85
+ super().__init__(
86
+ FLX_4101,
87
+ f"fidelity {fidelity!r} requires the {AGENTIC_EXTENSION_MODULE!r} "
88
+ "extension, which is not installed",
89
+ )
90
+ self.fidelity = fidelity
91
+
92
+
93
+ class SkillBindingViolation(FluxError):
94
+ """Raised by :func:`require_valid_skill_bindings` for one failing binding."""
95
+
96
+ def __init__(self, skill_name: str, detail: str) -> None:
97
+ super().__init__(FLX_4102, f"skill {skill_name!r}: {detail}")
98
+ self.skill_name = skill_name
99
+ self.detail = detail
100
+
101
+
102
+ def agentic_extension_available(*, module_name: str = AGENTIC_EXTENSION_MODULE) -> bool:
103
+ """Whether *module_name* can be imported, without importing it.
104
+
105
+ ``importlib.util.find_spec`` answers "is this importable" by searching
106
+ the same finders ``import`` would use, but does not execute the
107
+ module -- checking availability never has the side effects of loading
108
+ the agentic extension.
109
+ """
110
+ return importlib.util.find_spec(module_name) is not None
111
+
112
+
113
+ def require_supported_fidelity(fidelity: str, *, available: Optional[bool] = None) -> None:
114
+ """Raise :class:`UnsupportedFidelity` for ``"agentic"`` without the extension.
115
+
116
+ ``deterministic`` and ``stochastic`` (the schema's other two fidelity
117
+ values) always pass -- this function does not validate that *fidelity*
118
+ is one of the three; that is the schema's job. *available* overrides
119
+ the live :func:`agentic_extension_available` check, for a caller (or a
120
+ test) that wants to force either branch deterministically.
121
+ """
122
+ if fidelity != "agentic":
123
+ return
124
+ is_available = agentic_extension_available() if available is None else available
125
+ if not is_available:
126
+ raise UnsupportedFidelity(fidelity)
127
+
128
+
129
+ def _as_json_int(value: Any) -> Optional[int]:
130
+ """The JSON notion of an integer (RFC-04's ``as_int``), duplicated narrowly.
131
+
132
+ A budget is compared here the same way :mod:`flux_engine.spec.enforce`
133
+ compares one -- ``200000.0`` is the integer 200000, a bool is never an
134
+ integer -- but this module does not import that one's private helper
135
+ (only ``decide``, ``run_vectors`` and ``DEFAULT_VECTORS`` are
136
+ re-exported through the shim, and only
137
+ :mod:`flux_engine.governance.gate` may reach the module underneath).
138
+ Returns ``None`` for anything that is not a JSON integer.
139
+ """
140
+ if isinstance(value, bool):
141
+ return None
142
+ if isinstance(value, int):
143
+ return value
144
+ if isinstance(value, float) and value.is_integer():
145
+ return int(value)
146
+ return None
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class SkillBindingCheck:
151
+ """The outcome of validating one skill binding against an ``agentPolicy``."""
152
+
153
+ skill_name: str
154
+ ok: bool
155
+ detail: Optional[str] = None
156
+
157
+
158
+ def validate_skill_bindings(
159
+ agent_policy: Mapping[str, Any], skills: Iterable[Mapping[str, Any]]
160
+ ) -> Tuple[SkillBindingCheck, ...]:
161
+ """Check every binding in *skills* against *agent_policy*. Never raises.
162
+
163
+ Mirrors the FLUX offline validator's rule exactly: a binding with no
164
+ declared ``model`` or ``tokenBudget`` passes (those fields are
165
+ optional on ``skillBinding`` -- a skill that declares neither takes
166
+ whatever the document's own default call site would use); a
167
+ non-integer ``tokenBudget`` fails, since the schema declares it an
168
+ integer and a caller that supplied something else is off-spec here
169
+ too, not merely inside a request.
170
+ """
171
+ allowed_models = {str(model) for model in agent_policy.get("allowedModels", [])}
172
+ policy_budget = _as_json_int(agent_policy.get("tokenBudget"))
173
+
174
+ checks = []
175
+ for skill in skills:
176
+ name = str(skill.get("name", "<unnamed>"))
177
+ model = skill.get("model")
178
+ if model is not None and str(model) not in allowed_models:
179
+ checks.append(
180
+ SkillBindingCheck(
181
+ name, False, f"model {model!r} is not in agentPolicy.allowedModels"
182
+ )
183
+ )
184
+ continue
185
+
186
+ declared_budget = skill.get("tokenBudget")
187
+ if declared_budget is None:
188
+ checks.append(SkillBindingCheck(name, True))
189
+ continue
190
+
191
+ budget = _as_json_int(declared_budget)
192
+ if budget is None:
193
+ checks.append(
194
+ SkillBindingCheck(
195
+ name, False, f"tokenBudget must be an integer, got {declared_budget!r}"
196
+ )
197
+ )
198
+ continue
199
+ if policy_budget is not None and budget > policy_budget:
200
+ checks.append(
201
+ SkillBindingCheck(
202
+ name,
203
+ False,
204
+ f"tokenBudget {budget} exceeds agentPolicy.tokenBudget {policy_budget}",
205
+ )
206
+ )
207
+ continue
208
+ checks.append(SkillBindingCheck(name, True))
209
+
210
+ return tuple(checks)
211
+
212
+
213
+ def require_valid_skill_bindings(
214
+ agent_policy: Mapping[str, Any], skills: Iterable[Mapping[str, Any]]
215
+ ) -> None:
216
+ """:func:`validate_skill_bindings`, raising :class:`SkillBindingViolation`
217
+ on the first failing binding (bindings are checked in *skills* order)."""
218
+ for check in validate_skill_bindings(agent_policy, skills):
219
+ if not check.ok:
220
+ raise SkillBindingViolation(check.skill_name, check.detail or "binding rejected")
@@ -0,0 +1,251 @@
1
+ # Copyright 2026 Agentics Transformation Limited
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """World/Simulation sovereignty enforcement (schema ``$defs/sovereignty``).
6
+
7
+ The FLUX schema declares sovereignty on both ``World.spec.sovereignty`` and
8
+ ``Simulation.spec.sovereignty`` as ``{"allowedZones": [...], "enforcement":
9
+ "block" | "audit"}`` (default ``"block"``), with the schema's own
10
+ description of the two modes: *block* -- execution refuses to start outside
11
+ the allowed zones; *audit* -- a violation is recorded instead of stopping
12
+ the run.
13
+
14
+ This module is the boundary that turns that declaration into an action. It
15
+ resolves the run's own declared zone from ``--zone``/``FLUX_ZONE`` (whoever
16
+ invokes the CLI passes ``--zone``; :func:`declared_zone` is the same
17
+ precedence, callable directly for a caller that never goes through the
18
+ CLI), checks it against the policy, and either raises
19
+ :class:`SovereigntyViolation` (``FLX-4001``, block mode) or returns a
20
+ :class:`SovereigntyAuditRow` for the caller to hand to a lineage emitter
21
+ (audit mode).
22
+
23
+ **Ambiguity resolved.** The schema does not say what happens when no zone
24
+ is declared at all (no ``--zone``, no ``FLUX_ZONE``) against a document
25
+ that *does* declare ``allowedZones``. Read literally, KERNEL-SPEC's
26
+ governance band exists to stop a run executing somewhere it should not --
27
+ an *absent* declaration is not a claim about where the run is executing,
28
+ so :func:`enforce_sovereignty` does not refuse the run in that case, in
29
+ any enforcement mode, rather than treating it as a
30
+ zone-outside-allowedZones violation by default. A deployment that wants
31
+ "no zone declared" to be a hard failure enforces that separately, before
32
+ calling this module -- KERNEL-SPEC does not require every deployment to
33
+ declare one.
34
+
35
+ **But it is written down.** Not refusing is not the same as saying
36
+ nothing. The zone is resolved from a value the runner supplies about
37
+ itself, so "no zone declared" is the one case where an ``enforcement:
38
+ block`` policy did not actually run -- and it used to leave the receipt
39
+ and the evidence pack byte-identical to a run that had been checked and
40
+ passed. :func:`enforce_sovereignty` now returns a
41
+ :class:`SovereigntyAuditRow` with :attr:`~SovereigntyAuditRow.enforced`
42
+ false and no zone for that case, so a reader of the artifacts can tell
43
+ "checked, inside the allow-list" from "never checked".
44
+
45
+ No wall clock is read here: :attr:`SovereigntyAuditRow.event_time` is
46
+ caller-supplied, the same discipline
47
+ :class:`flux_engine.api.lineage.LineageEvent` uses and for the same
48
+ reason -- KERNEL-SPEC keeps the read at the facade, never in a governed
49
+ decision.
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import os
55
+ from dataclasses import dataclass
56
+ from typing import Any, Dict, Mapping, Optional, Sequence, Tuple
57
+
58
+ from flux_engine.core.errors import FluxError, register
59
+
60
+ __all__ = [
61
+ "FLUX_ZONE_ENV_VAR",
62
+ "FLX_4001",
63
+ "SovereigntyAuditRow",
64
+ "SovereigntyPolicy",
65
+ "SovereigntyViolation",
66
+ "declared_zone",
67
+ "enforce_sovereignty",
68
+ ]
69
+
70
+ FLX_4001 = register(
71
+ "FLX-4001",
72
+ "declared zone is outside the document's allowed zones",
73
+ "World.spec.sovereignty / Simulation.spec.sovereignty (schema $defs/sovereignty) "
74
+ "declares the zones a run may execute in. The run's own declared zone -- the "
75
+ "--zone flag, falling back to FLUX_ZONE -- was resolved and it is not a member "
76
+ "of allowedZones. Under enforcement: block (the default) the run refuses to "
77
+ "start; under enforcement: audit it does not, and a lineage-style row is "
78
+ "recorded instead.",
79
+ )
80
+
81
+ #: The one environment variable this module ever reads, and the fallback
82
+ #: named in the schema's own vocabulary alongside ``--zone``. A deployment
83
+ #: switch, not a value that reaches a digest.
84
+ FLUX_ZONE_ENV_VAR = "FLUX_ZONE"
85
+
86
+
87
+ class SovereigntyViolation(FluxError):
88
+ """Raised in ``enforcement: block`` when the declared zone is not allowed.
89
+
90
+ Carries the offending zone and the policy's allow-list so a caller can
91
+ report both without re-deriving them from the document.
92
+ """
93
+
94
+ def __init__(self, zone: str, allowed_zones: Sequence[str]) -> None:
95
+ allowed = tuple(allowed_zones)
96
+ super().__init__(
97
+ FLX_4001,
98
+ f"zone {zone!r} is not one of the allowed zones {sorted(allowed)!r}",
99
+ )
100
+ self.zone = zone
101
+ self.allowed_zones = allowed
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class SovereigntyPolicy:
106
+ """One document's resolved ``sovereignty`` block.
107
+
108
+ ``enforcement`` mirrors the schema's own default: absent means
109
+ ``"block"``, never an unenforced policy by omission.
110
+ """
111
+
112
+ allowed_zones: Tuple[str, ...]
113
+ enforcement: str = "block"
114
+
115
+ def __post_init__(self) -> None:
116
+ if not self.allowed_zones:
117
+ raise ValueError("sovereignty.allowedZones must not be empty")
118
+ if self.enforcement not in ("block", "audit"):
119
+ raise ValueError(
120
+ f"sovereignty.enforcement must be 'block' or 'audit', got {self.enforcement!r}"
121
+ )
122
+
123
+ @classmethod
124
+ def from_document(
125
+ cls, sovereignty: Optional[Mapping[str, Any]]
126
+ ) -> Optional["SovereigntyPolicy"]:
127
+ """Build a policy from a document's ``spec.sovereignty`` block, or ``None``.
128
+
129
+ Returns ``None`` for a document that declares no sovereignty block at
130
+ all -- there is nothing to enforce, which is different from a
131
+ declared-but-empty ``allowedZones`` (schema-invalid; the dataclass
132
+ itself refuses that).
133
+ """
134
+ if sovereignty is None:
135
+ return None
136
+ zones = tuple(str(zone) for zone in sovereignty["allowedZones"])
137
+ enforcement = sovereignty.get("enforcement", "block")
138
+ return cls(allowed_zones=zones, enforcement=enforcement)
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class SovereigntyAuditRow:
143
+ """A lineage-style record of a sovereignty check that did not come out clean.
144
+
145
+ Two cases produce one: a zone that fell outside the declared allow-list
146
+ under ``enforcement: audit`` (:attr:`enforced` true, :attr:`zone` set),
147
+ and a policy that was never checked because the run declared no zone at
148
+ all (:attr:`enforced` false, :attr:`zone` ``None``). Deliberately
149
+ shaped close to :class:`flux_engine.api.lineage.LineageEvent` (job
150
+ identity, a facets mapping) so :meth:`as_lineage_facets` slots straight
151
+ into one without this module importing the port itself -- sovereignty
152
+ is a governance decision; where the row travels afterward is
153
+ deployment plumbing.
154
+ """
155
+
156
+ zone: Optional[str]
157
+ allowed_zones: Tuple[str, ...]
158
+ document_id: str
159
+ document_kind: str
160
+ event_time: str
161
+ run_id: Optional[str] = None
162
+ #: False only for the "no zone was declared, so nothing was checked"
163
+ #: row. A consumer that treats every row as a violation would be
164
+ #: reading the second case wrongly, which is why the facet it renders
165
+ #: under is a different name too.
166
+ enforced: bool = True
167
+
168
+ def as_lineage_facets(self) -> Dict[str, Any]:
169
+ """This row's content as a ``facets`` mapping for a lineage event.
170
+
171
+ ``sovereigntyViolation`` for a zone outside the allow-list;
172
+ ``sovereigntyNotEnforced`` for a policy that never ran. Two names,
173
+ because "this run was somewhere it should not have been" and "we do
174
+ not know where this run was" are different facts.
175
+ """
176
+ facet = "sovereigntyViolation" if self.enforced else "sovereigntyNotEnforced"
177
+ return {
178
+ facet: {
179
+ "zone": self.zone,
180
+ "allowedZones": list(self.allowed_zones),
181
+ "documentId": self.document_id,
182
+ "documentKind": self.document_kind,
183
+ "runId": self.run_id,
184
+ }
185
+ }
186
+
187
+
188
+ def declared_zone(
189
+ *, cli_zone: Optional[str] = None, env: Optional[Mapping[str, str]] = None
190
+ ) -> Optional[str]:
191
+ """Resolve the run's declared zone: ``--zone`` first, then ``FLUX_ZONE``.
192
+
193
+ ``env`` defaults to ``os.environ`` -- the one environment read in this
194
+ module, isolated to this function so a caller (or a test) can supply
195
+ an explicit mapping instead. Returns ``None`` when neither is set (or
196
+ both are blank), which :func:`enforce_sovereignty` treats as nothing to
197
+ check.
198
+ """
199
+ if cli_zone is not None and cli_zone.strip():
200
+ return cli_zone.strip()
201
+ source: Mapping[str, str] = os.environ if env is None else env
202
+ value = source.get(FLUX_ZONE_ENV_VAR)
203
+ if value is not None and value.strip():
204
+ return value.strip()
205
+ return None
206
+
207
+
208
+ def enforce_sovereignty(
209
+ policy: Optional[SovereigntyPolicy],
210
+ *,
211
+ zone: Optional[str],
212
+ document_id: str,
213
+ document_kind: str,
214
+ event_time: str,
215
+ run_id: Optional[str] = None,
216
+ ) -> Optional[SovereigntyAuditRow]:
217
+ """Apply *policy* to *zone*.
218
+
219
+ Returns ``None`` when there is nothing to report: no policy declared,
220
+ or the declared zone is allowed. Returns a
221
+ :class:`SovereigntyAuditRow` in ``enforcement: audit`` when the zone is
222
+ not allowed, and one with :attr:`SovereigntyAuditRow.enforced` false
223
+ when a policy exists but the run declared no zone -- the case where the
224
+ control did not run at all, in any enforcement mode. Raises
225
+ :class:`SovereigntyViolation` in ``enforcement: block`` (the default)
226
+ when the zone is not allowed.
227
+ """
228
+ if policy is None:
229
+ return None
230
+ if zone is None:
231
+ return SovereigntyAuditRow(
232
+ zone=None,
233
+ allowed_zones=policy.allowed_zones,
234
+ document_id=document_id,
235
+ document_kind=document_kind,
236
+ event_time=event_time,
237
+ run_id=run_id,
238
+ enforced=False,
239
+ )
240
+ if zone in policy.allowed_zones:
241
+ return None
242
+ if policy.enforcement == "block":
243
+ raise SovereigntyViolation(zone, policy.allowed_zones)
244
+ return SovereigntyAuditRow(
245
+ zone=zone,
246
+ allowed_zones=policy.allowed_zones,
247
+ document_id=document_id,
248
+ document_kind=document_kind,
249
+ event_time=event_time,
250
+ run_id=run_id,
251
+ )
@@ -0,0 +1,5 @@
1
+ # Copyright 2026 Agentics Transformation Limited
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """OpenLineage RunEvent emission for twin and production runs."""