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.
- flux_engine/__init__.py +22 -0
- flux_engine/_links.py +55 -0
- flux_engine/_vendor/__init__.py +5 -0
- flux_engine/_vendor/flux_spec/NOTICE +19 -0
- flux_engine/_vendor/flux_spec/VENDOR-NOTES.md +104 -0
- flux_engine/_vendor/flux_spec/__init__.py +9 -0
- flux_engine/_vendor/flux_spec/bundle.py +410 -0
- flux_engine/_vendor/flux_spec/enforce.py +316 -0
- flux_engine/_vendor/flux_spec/schema/flux-enforcement-0.5.0.json +121 -0
- flux_engine/_vendor/flux_spec/schema/flux-manifest-0.5.0.json +153 -0
- flux_engine/_vendor/flux_spec/schema/flux-schema-0.2.0.json +465 -0
- flux_engine/_vendor/flux_spec/schema/flux-schema-0.3.0.json +876 -0
- flux_engine/_vendor/flux_spec/schema/flux-schema-0.4.0.json +1601 -0
- flux_engine/_vendor/flux_spec/schema/flux-schema-0.4.1.json +1668 -0
- flux_engine/_vendor/flux_spec/schema/flux-schema-0.5.0.json +1669 -0
- flux_engine/_vendor/flux_spec/schema/flux-schema-latest.json +1669 -0
- flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.4.0.json +795 -0
- flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.4.1.json +852 -0
- flux_engine/_vendor/flux_spec/schema/flux-ui-hints-0.5.0.json +852 -0
- flux_engine/_vendor/flux_spec/validate.py +537 -0
- flux_engine/_vendor/flux_spec/vectors/enforcement-vectors.json +935 -0
- flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.3.json +5234 -0
- flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.4.json +5437 -0
- flux_engine/_vendor/flux_spec/vendor/fluid/fluid-schema-0.7.5.json +5498 -0
- flux_engine/_vocabulary.py +141 -0
- flux_engine/accuracy/__init__.py +5 -0
- flux_engine/accuracy/_scoring/__init__.py +24 -0
- flux_engine/accuracy/accuracy_record.py +96 -0
- flux_engine/accuracy/policy.py +158 -0
- flux_engine/accuracy/records.py +264 -0
- flux_engine/accuracy/store.py +169 -0
- flux_engine/api/__init__.py +163 -0
- flux_engine/api/accuracy.py +209 -0
- flux_engine/api/agentic.py +134 -0
- flux_engine/api/calibration.py +125 -0
- flux_engine/api/claims.py +93 -0
- flux_engine/api/digests.py +73 -0
- flux_engine/api/emit.py +78 -0
- flux_engine/api/expressions.py +72 -0
- flux_engine/api/fidelity.py +110 -0
- flux_engine/api/lineage.py +78 -0
- flux_engine/api/stages.py +242 -0
- flux_engine/api/verdict.py +108 -0
- flux_engine/calibrate/__init__.py +5 -0
- flux_engine/calibrate/declared.py +253 -0
- flux_engine/calibrate/provenance.py +113 -0
- flux_engine/cli/__init__.py +2146 -0
- flux_engine/cli/__main__.py +17 -0
- flux_engine/cli/_documents.py +226 -0
- flux_engine/cli/_hints.py +118 -0
- flux_engine/cli/_init.py +152 -0
- flux_engine/cli/_progress.py +124 -0
- flux_engine/concordance/__init__.py +127 -0
- flux_engine/concordance/boundary/__init__.py +78 -0
- flux_engine/concordance/boundary/merkle.py +287 -0
- flux_engine/concordance/boundary/slice.py +429 -0
- flux_engine/concordance/boundary/statistic.py +561 -0
- flux_engine/concordance/boundary/store.py +334 -0
- flux_engine/concordance/boundary/vault.py +357 -0
- flux_engine/concordance/compiler.py +542 -0
- flux_engine/concordance/errors.py +189 -0
- flux_engine/concordance/gate.py +525 -0
- flux_engine/concordance/predicate.py +1217 -0
- flux_engine/concordance/record.py +554 -0
- flux_engine/concordance/verifier.py +583 -0
- flux_engine/core/__init__.py +5 -0
- flux_engine/core/artifact.py +99 -0
- flux_engine/core/canonical.py +369 -0
- flux_engine/core/clock.py +437 -0
- flux_engine/core/digest.py +288 -0
- flux_engine/core/errors.py +277 -0
- flux_engine/core/fixedpoint.py +929 -0
- flux_engine/core/lrm.py +158 -0
- flux_engine/core/rng.py +736 -0
- flux_engine/core/seedtree.py +891 -0
- flux_engine/core/trace.py +423 -0
- flux_engine/describe.py +207 -0
- flux_engine/engine.py +257 -0
- flux_engine/evidence/__init__.py +5 -0
- flux_engine/evidence/pack.py +411 -0
- flux_engine/evidence/report.py +243 -0
- flux_engine/expr/__init__.py +133 -0
- flux_engine/expr/ast.py +312 -0
- flux_engine/expr/attrs.py +386 -0
- flux_engine/expr/check.py +278 -0
- flux_engine/expr/compile.py +322 -0
- flux_engine/expr/errors.py +256 -0
- flux_engine/expr/lexer.py +297 -0
- flux_engine/expr/parser.py +313 -0
- flux_engine/expr/types.py +177 -0
- flux_engine/generator/__init__.py +97 -0
- flux_engine/generator/families.py +325 -0
- flux_engine/generator/paths.py +227 -0
- flux_engine/generator/rows.py +918 -0
- flux_engine/generator/statistics.py +524 -0
- flux_engine/governance/__init__.py +87 -0
- flux_engine/governance/audit.py +307 -0
- flux_engine/governance/gate.py +334 -0
- flux_engine/governance/skills.py +220 -0
- flux_engine/governance/sovereignty.py +251 -0
- flux_engine/lineage/__init__.py +5 -0
- flux_engine/lineage/emitter.py +398 -0
- flux_engine/py.typed +0 -0
- flux_engine/runtime/__init__.py +153 -0
- flux_engine/runtime/campaign.py +407 -0
- flux_engine/runtime/cast.py +283 -0
- flux_engine/runtime/detector.py +222 -0
- flux_engine/runtime/errors.py +58 -0
- flux_engine/runtime/experiment.py +311 -0
- flux_engine/runtime/journey.py +383 -0
- flux_engine/runtime/jurisdiction.py +72 -0
- flux_engine/runtime/payloads.py +124 -0
- flux_engine/runtime/signals.py +334 -0
- flux_engine/runtime/temperature.py +156 -0
- flux_engine/seam/__init__.py +5 -0
- flux_engine/seam/attest.py +290 -0
- flux_engine/seam/conform.py +448 -0
- flux_engine/seam/contract.py +605 -0
- flux_engine/seam/emit.py +488 -0
- flux_engine/seam/mapping.py +299 -0
- flux_engine/seam/resolve.py +1087 -0
- flux_engine/seam/sinks.py +157 -0
- flux_engine/spec/__init__.py +134 -0
- flux_engine/spec/bundle.py +25 -0
- flux_engine/spec/enforce.py +31 -0
- flux_engine/spec/validate.py +28 -0
- flux_engine/stages/__init__.py +30 -0
- flux_engine/stages/apply.py +447 -0
- flux_engine/stages/errors.py +315 -0
- flux_engine/stages/layout.py +292 -0
- flux_engine/stages/pipeline.py +600 -0
- flux_engine/stages/plan.py +241 -0
- flux_engine/stages/replay.py +83 -0
- flux_engine/stages/run.py +208 -0
- flux_engine/stages/ship.py +934 -0
- flux_engine/stages/validate.py +93 -0
- flux_engine/stages/verify.py +1129 -0
- flux_engine/starter/__init__.py +161 -0
- flux_engine/starter/bundle/detector.flux.yml +15 -0
- flux_engine/starter/bundle/journey.flux.yml +23 -0
- flux_engine/starter/bundle/module.flux.yml +16 -0
- flux_engine/starter/bundle/payment-recovery.fluid.yml +30 -0
- flux_engine/starter/bundle/persona.flux.yml +26 -0
- flux_engine/starter/bundle/signal.flux.yml +13 -0
- flux_engine/starter/bundle/simulation.flux.yml +29 -0
- flux_engine/starter/bundle/taxonomy.flux.yml +17 -0
- flux_engine/starter/bundle/treatment.flux.yml +13 -0
- flux_engine/starter/bundle/world.flux.yml +20 -0
- flux_engine/verticals/__init__.py +85 -0
- flux_engine/verticals/telco.py +89 -0
- flux_engine/world/__init__.py +89 -0
- flux_engine/world/derived.py +195 -0
- flux_engine/world/errors.py +41 -0
- flux_engine/world/families.py +260 -0
- flux_engine/world/population.py +602 -0
- flux_engine/world/tracing.py +66 -0
- flux_engine/world/values.py +121 -0
- flux_sim_engine-0.2.0.dist-info/METADATA +108 -0
- flux_sim_engine-0.2.0.dist-info/RECORD +165 -0
- flux_sim_engine-0.2.0.dist-info/WHEEL +5 -0
- flux_sim_engine-0.2.0.dist-info/entry_points.txt +2 -0
- flux_sim_engine-0.2.0.dist-info/licenses/LICENSE +202 -0
- flux_sim_engine-0.2.0.dist-info/licenses/NOTICE +10 -0
- flux_sim_engine-0.2.0.dist-info/licenses/flux_engine/_vendor/flux_spec/NOTICE +19 -0
- flux_sim_engine-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# Copyright 2026 Agentics Transformation Limited
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
"""Vertical-pack derived subject attributes (KERNEL-SPEC §3, ``...,"products"``).
|
|
6
|
+
|
|
7
|
+
The seed-tree table gives one stream per subject to "vertical-pack derived
|
|
8
|
+
attributes", and EXPR-SPEC §3 gives the vertical pack the *types* of those
|
|
9
|
+
attributes -- telco's ``products: set<string>``, ``tenureMonths: number``,
|
|
10
|
+
``latePaymentCount: number``, ``arpu: number``. What the pack deliberately does
|
|
11
|
+
not carry is the shapes those values are drawn from: "a pack never carries a
|
|
12
|
+
value, a rate or a distribution, so nothing in this module can put a number
|
|
13
|
+
into a hashed document" (``flux_engine/verticals/telco.py``).
|
|
14
|
+
|
|
15
|
+
This module carries them, and is the **v0.1 stopgap** that the pack's own
|
|
16
|
+
docstring anticipates: "FLUX 0.6 RFC moves the declaration into the spec". Until
|
|
17
|
+
it does, the shapes are engine-owned, exactly as ``tickMs`` is engine-owned in
|
|
18
|
+
KERNEL-SPEC §7 -- declared in one table, written as exact decimal strings, and
|
|
19
|
+
therefore part of ``kernelVersion``: changing a number here moves the goldens on
|
|
20
|
+
purpose and needs a ``GOLDEN-CHANGELOG.md`` row like any other kernel change.
|
|
21
|
+
|
|
22
|
+
Two determinism rules the table must keep, both pinned by tests:
|
|
23
|
+
|
|
24
|
+
* every attribute is drawn on **one** stream, in NFC-sorted attribute order, so
|
|
25
|
+
adding an attribute changes only the values after it in that order;
|
|
26
|
+
* the word cost of a subject's derivation does **not** depend on that subject's
|
|
27
|
+
lifecycle, even though the ``latePaymentCount`` rate does -- a lifecycle-
|
|
28
|
+
dependent cost would make one subject's stream position depend on another
|
|
29
|
+
document's cohort allocation.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from decimal import Decimal
|
|
36
|
+
from typing import Any, Dict, Mapping, Tuple
|
|
37
|
+
|
|
38
|
+
from flux_engine.core.errors import FluxError
|
|
39
|
+
from flux_engine.expr.attrs import VerticalPack
|
|
40
|
+
from flux_engine.expr.types import Type, nfc
|
|
41
|
+
from flux_engine.world.errors import FLX_5040
|
|
42
|
+
from flux_engine.world.families import (
|
|
43
|
+
BoundedNormal,
|
|
44
|
+
Family,
|
|
45
|
+
RateCount,
|
|
46
|
+
SetOf,
|
|
47
|
+
StreamFactory,
|
|
48
|
+
drawn_type_satisfies,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__all__ = ["DERIVATIONS", "Derivation", "derivation_for", "TELCO_DERIVATION"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Derivation:
|
|
56
|
+
"""How one vertical's derived subject attributes are drawn.
|
|
57
|
+
|
|
58
|
+
``attributes`` is the base family per attribute name. ``by_lifecycle``
|
|
59
|
+
overrides a family for subjects in one lifecycle cohort; an override must
|
|
60
|
+
keep the base family's :attr:`~flux_engine.world.families.Family.word_cost`,
|
|
61
|
+
which :meth:`__post_init__` checks, so the cohort a subject landed in can
|
|
62
|
+
change the *value* it draws but never the *position* the stream is left in.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
vertical: str
|
|
66
|
+
attributes: Mapping[str, Family]
|
|
67
|
+
by_lifecycle: Mapping[str, Mapping[str, Family]] = field(default_factory=dict)
|
|
68
|
+
|
|
69
|
+
def __post_init__(self) -> None:
|
|
70
|
+
for lifecycle, overrides in self.by_lifecycle.items():
|
|
71
|
+
for name, family in overrides.items():
|
|
72
|
+
base = self.attributes.get(name)
|
|
73
|
+
if base is None:
|
|
74
|
+
raise ValueError(
|
|
75
|
+
f"{self.vertical}: lifecycle {lifecycle!r} overrides unknown "
|
|
76
|
+
f"attribute {name!r}"
|
|
77
|
+
)
|
|
78
|
+
if base.word_cost != family.word_cost:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
f"{self.vertical}: the {lifecycle!r} override of {name!r} costs "
|
|
81
|
+
f"{family.word_cost} words, the base family costs {base.word_cost}; "
|
|
82
|
+
"a lifecycle must not move the stream position"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def names(self) -> Tuple[str, ...]:
|
|
87
|
+
"""The derived attribute names in the NFC-sorted order :meth:`draw` uses."""
|
|
88
|
+
return tuple(sorted(self.attributes, key=nfc))
|
|
89
|
+
|
|
90
|
+
def families_for(self, lifecycle: str) -> Mapping[str, Family]:
|
|
91
|
+
"""The family per attribute for a subject in *lifecycle*."""
|
|
92
|
+
overrides = self.by_lifecycle.get(nfc(lifecycle), {})
|
|
93
|
+
return {name: overrides.get(name, self.attributes[name]) for name in self.names}
|
|
94
|
+
|
|
95
|
+
def word_cost(self) -> int:
|
|
96
|
+
"""Raw words one subject's derivation consumes. Lifecycle-independent."""
|
|
97
|
+
return sum(self.attributes[name].word_cost for name in self.names)
|
|
98
|
+
|
|
99
|
+
def draw(self, open_stream: StreamFactory, *, lifecycle: str) -> Dict[str, Any]:
|
|
100
|
+
"""Draw every derived attribute for one subject, in NFC-sorted name order.
|
|
101
|
+
|
|
102
|
+
Every attribute draws on the one stream *open_stream* yields, so the
|
|
103
|
+
factory is expected to be memoised by path -- which
|
|
104
|
+
:meth:`flux_engine.core.seedtree.SeedTree.stream` is.
|
|
105
|
+
"""
|
|
106
|
+
families = self.families_for(lifecycle)
|
|
107
|
+
return {name: families[name].draw(open_stream) for name in self.names}
|
|
108
|
+
|
|
109
|
+
def types(self) -> Mapping[str, Type]:
|
|
110
|
+
"""The ``flux-expr/1`` type of each derived attribute, for cross-checking a pack."""
|
|
111
|
+
return {name: self.attributes[name].expr_type for name in self.names}
|
|
112
|
+
|
|
113
|
+
def check_against(self, pack: VerticalPack) -> None:
|
|
114
|
+
"""Fail (``FLX-5040``) unless this table draws exactly what *pack* declares.
|
|
115
|
+
|
|
116
|
+
The pack owns the names and types the expression language type-checks
|
|
117
|
+
against; this table owns the shapes. If the two disagree, a segment
|
|
118
|
+
query would type-check against an attribute no subject carries (or a
|
|
119
|
+
subject would carry an attribute typed as something else), so the two
|
|
120
|
+
are compared once, at plan time, rather than diverging silently.
|
|
121
|
+
"""
|
|
122
|
+
declared = {nfc(name): t for name, t in pack.subject_attributes.items()}
|
|
123
|
+
drawn = self.types()
|
|
124
|
+
missing = sorted(set(declared) - set(drawn))
|
|
125
|
+
extra = sorted(set(drawn) - set(declared))
|
|
126
|
+
if missing or extra:
|
|
127
|
+
raise FluxError(
|
|
128
|
+
FLX_5040,
|
|
129
|
+
f"vertical {pack.name!r}: the pack declares {missing or []} that no "
|
|
130
|
+
f"derivation draws, and the derivation draws {extra or []} the pack does "
|
|
131
|
+
"not declare",
|
|
132
|
+
)
|
|
133
|
+
for name in sorted(declared):
|
|
134
|
+
if not drawn_type_satisfies(declared[name], drawn[name]):
|
|
135
|
+
raise FluxError(
|
|
136
|
+
FLX_5040,
|
|
137
|
+
f"vertical {pack.name!r}: attribute {name!r} is declared "
|
|
138
|
+
f"{declared[name].name} by the pack and drawn as {drawn[name].name}",
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _d(literal: str) -> Decimal:
|
|
143
|
+
"""An engine-owned constant, written as an exact decimal string (never a float)."""
|
|
144
|
+
return Decimal(literal)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
#: The telco table. Every number is a string literal; every family is one of
|
|
148
|
+
#: SEAM-FIDELITY-SPEC §1's four. ``latePaymentCount`` is the only
|
|
149
|
+
#: lifecycle-conditioned attribute: an at-risk subscriber is at risk *because*
|
|
150
|
+
#: of missed payments, and a table that drew the same rate for every cohort
|
|
151
|
+
#: would make ``seg-atrisk-tv`` and ``pb-billing-history``'s
|
|
152
|
+
#: ``late_payment_count >= 2`` describe unrelated populations.
|
|
153
|
+
TELCO_DERIVATION = Derivation(
|
|
154
|
+
vertical="telco",
|
|
155
|
+
attributes={
|
|
156
|
+
"arpu": BoundedNormal(
|
|
157
|
+
mean=_d("42.00"), stddev=_d("12.00"), lo=_d("5.00"), hi=_d("250.00"), scale=2
|
|
158
|
+
),
|
|
159
|
+
"latePaymentCount": RateCount(mean=_d("0.30")),
|
|
160
|
+
"products": SetOf(
|
|
161
|
+
{"broadband": _d("0.70"), "mobile": _d("0.50"), "tv": _d("0.35")},
|
|
162
|
+
),
|
|
163
|
+
"tenureMonths": BoundedNormal(
|
|
164
|
+
mean=_d("36"), stddev=_d("18"), lo=_d("0"), hi=_d("240"), scale=0
|
|
165
|
+
),
|
|
166
|
+
},
|
|
167
|
+
by_lifecycle={
|
|
168
|
+
"new": {"latePaymentCount": RateCount(mean=_d("0.10"))},
|
|
169
|
+
"active": {"latePaymentCount": RateCount(mean=_d("0.20"))},
|
|
170
|
+
"atrisk": {"latePaymentCount": RateCount(mean=_d("2.50"))},
|
|
171
|
+
"churned": {"latePaymentCount": RateCount(mean=_d("1.50"))},
|
|
172
|
+
},
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
#: Every vertical this engine can materialise, keyed the way
|
|
176
|
+
#: :data:`flux_engine.verticals.PACKS` is keyed.
|
|
177
|
+
DERIVATIONS: Mapping[str, Derivation] = {TELCO_DERIVATION.vertical: TELCO_DERIVATION}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def derivation_for(vertical: str) -> Derivation:
|
|
181
|
+
"""Return the derivation table for *vertical*; ``FLX-5040`` when there is none.
|
|
182
|
+
|
|
183
|
+
A missing table is a hard failure rather than an empty derivation: an empty
|
|
184
|
+
one would leave every vertical attribute null, which makes
|
|
185
|
+
``products.has('tv')`` quietly false for the whole population instead of
|
|
186
|
+
naming the vertical the engine cannot materialise.
|
|
187
|
+
"""
|
|
188
|
+
key = nfc(vertical)
|
|
189
|
+
if key not in DERIVATIONS:
|
|
190
|
+
raise FluxError(
|
|
191
|
+
FLX_5040,
|
|
192
|
+
f"no derivation table for vertical {vertical!r}; this engine materialises "
|
|
193
|
+
f"{', '.join(sorted(DERIVATIONS))}",
|
|
194
|
+
)
|
|
195
|
+
return DERIVATIONS[key]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Copyright 2026 Agentics Transformation Limited
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
"""Error codes raised while materialising a world (the ``FLX-5040`` block).
|
|
6
|
+
|
|
7
|
+
KERNEL-SPEC §13 gives band 5000 to numerics. Population materialisation is
|
|
8
|
+
where a declared distribution becomes a drawn value, so a declaration this
|
|
9
|
+
engine cannot sample -- an unknown ``dist``, a weight that is not a number, a
|
|
10
|
+
normal whose bounds cross -- fails here with a 5000-band code rather than
|
|
11
|
+
travelling into a digest as a silently substituted default.
|
|
12
|
+
|
|
13
|
+
Registered at import time so ``fluxsim explain FLX-5040`` works without a
|
|
14
|
+
population having been materialised first (see
|
|
15
|
+
:func:`flux_engine.core.errors.ensure_core_codes_loaded`).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from flux_engine.core.errors import ErrorCode, register
|
|
21
|
+
|
|
22
|
+
__all__ = ["FLX_5040", "FLX_5041"]
|
|
23
|
+
|
|
24
|
+
FLX_5040: ErrorCode = register(
|
|
25
|
+
"FLX-5040",
|
|
26
|
+
"population declaration cannot be materialised",
|
|
27
|
+
"A World or Persona declaration reached the sampler in a shape it cannot draw from: "
|
|
28
|
+
"an unknown trait 'dist', a non-numeric weight or bound, a normal whose 'min' exceeds "
|
|
29
|
+
"its 'max', or a market list the assignment cannot index. Fix the declaration; the "
|
|
30
|
+
"engine will not substitute a default, because a substituted default would change the "
|
|
31
|
+
"population digest without changing the documents.",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
FLX_5041: ErrorCode = register(
|
|
35
|
+
"FLX-5041",
|
|
36
|
+
"value is outside the domain the kernel can hash",
|
|
37
|
+
"A schema-declared JSON number could not be converted to the exact Decimal the kernel "
|
|
38
|
+
"hashes (KERNEL-SPEC §2.1 keeps float out of every hashed value), or a probability "
|
|
39
|
+
"landed outside [0, 1]. The offending value's class and path are named; the value "
|
|
40
|
+
"itself is not, so a diagnostic never leaks a population value.",
|
|
41
|
+
)
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
# Copyright 2026 Agentics Transformation Limited
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
"""Sampling families: a declared shape plus the §4 kernel sampler that draws it.
|
|
6
|
+
|
|
7
|
+
SEAM-FIDELITY-SPEC §1 names four families a generator may pick from
|
|
8
|
+
("categorical, bounded-normal, rate, uniform/empirical") and requires that
|
|
9
|
+
"every draw uses the §4 kernel samplers". This module is that vocabulary,
|
|
10
|
+
factored out of the two places that need it: the vertical-derived subject
|
|
11
|
+
attributes of :mod:`flux_engine.world.derived` and the signal payload fields of
|
|
12
|
+
:mod:`flux_engine.runtime.payloads`.
|
|
13
|
+
|
|
14
|
+
Three rules hold of every family here:
|
|
15
|
+
|
|
16
|
+
* **Every parameter is an exact ``Decimal`` built from a string.** No family
|
|
17
|
+
ever holds a ``float``, so a drawn value is safe to put in a traced op
|
|
18
|
+
(KERNEL-SPEC §2.1).
|
|
19
|
+
* **Every draw has a fixed word cost** that depends on the family and not on
|
|
20
|
+
the value drawn (:attr:`Family.word_cost`), so a stream's position after a
|
|
21
|
+
draw is data-independent -- the property KERNEL-SPEC §4 buys with its fixed
|
|
22
|
+
draw budgets, and the reason a family may not branch on a drawn value to
|
|
23
|
+
decide whether to draw again.
|
|
24
|
+
* **Draw order inside a composite family is NFC-sorted key order**
|
|
25
|
+
(KERNEL-SPEC §7), so a family declared in a different mapping order draws the
|
|
26
|
+
same values.
|
|
27
|
+
|
|
28
|
+
:meth:`Family.draw` takes a *factory* rather than a stream, and a zero-cost
|
|
29
|
+
family never calls it. That is the type-level statement of KERNEL-SPEC §3's
|
|
30
|
+
insertion-stability property: a constant trait materialises no seed path, so it
|
|
31
|
+
cannot appear in ``seedTreeDigest`` and cannot move any other stream.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
from abc import ABC, abstractmethod
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
from decimal import Decimal
|
|
39
|
+
from typing import Any, Callable, FrozenSet, Mapping, Tuple
|
|
40
|
+
|
|
41
|
+
from flux_engine.core.rng import (
|
|
42
|
+
RAW_WORDS_PER_DRAW,
|
|
43
|
+
DrawStream,
|
|
44
|
+
bernoulli,
|
|
45
|
+
categorical,
|
|
46
|
+
poisson,
|
|
47
|
+
truncated_normal,
|
|
48
|
+
)
|
|
49
|
+
from flux_engine.expr.types import BOOL, NUMBER, SET_STRING, Type, TypeKind, enum_of
|
|
50
|
+
from flux_engine.world.values import nfc_sorted_items
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"Bernoulli",
|
|
54
|
+
"BoundedNormal",
|
|
55
|
+
"Categorical",
|
|
56
|
+
"Constant",
|
|
57
|
+
"Family",
|
|
58
|
+
"RateCount",
|
|
59
|
+
"SetOf",
|
|
60
|
+
"StreamFactory",
|
|
61
|
+
"drawn_type_satisfies",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
#: How a family asks for the stream it draws on. Called at most once per draw,
|
|
65
|
+
#: and not at all by a zero-cost family.
|
|
66
|
+
StreamFactory = Callable[[], DrawStream]
|
|
67
|
+
|
|
68
|
+
_UNIFORM_WORDS = RAW_WORDS_PER_DRAW["uniform53"]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Family(ABC):
|
|
72
|
+
"""One declared sampling family. Frozen, ``Decimal``-parameterised, total."""
|
|
73
|
+
|
|
74
|
+
@abstractmethod
|
|
75
|
+
def draw(self, open_stream: "StreamFactory") -> Any:
|
|
76
|
+
"""Draw one value, consuming exactly :attr:`word_cost` words of the stream.
|
|
77
|
+
|
|
78
|
+
*open_stream* is called once, and only when :attr:`word_cost` is
|
|
79
|
+
non-zero -- see the module docstring.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
@abstractmethod
|
|
84
|
+
def word_cost(self) -> int:
|
|
85
|
+
"""Raw words this family consumes per draw. Independent of the value drawn."""
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
@abstractmethod
|
|
89
|
+
def expr_type(self) -> Type:
|
|
90
|
+
"""The ``flux-expr/1`` type the drawn value inhabits (EXPR-SPEC §2)."""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class Constant(Family):
|
|
95
|
+
"""A declared value, drawn without touching the stream.
|
|
96
|
+
|
|
97
|
+
The 0.3.0-compatible scalar trait (``digitalFluency: 0.6``) is this family:
|
|
98
|
+
every subject carries the declared number, and the stream for that trait is
|
|
99
|
+
never materialised -- which is what makes adding a scalar trait leave every
|
|
100
|
+
other stream untouched (KERNEL-SPEC §3, insertion stability).
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
value: Any
|
|
104
|
+
declared_type: Type = NUMBER
|
|
105
|
+
|
|
106
|
+
def draw(self, open_stream: StreamFactory) -> Any:
|
|
107
|
+
return self.value
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def word_cost(self) -> int:
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def expr_type(self) -> Type:
|
|
115
|
+
return self.declared_type
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class Categorical(Family):
|
|
120
|
+
"""One level from a closed weighted set -- KERNEL-SPEC §4's ``categorical``."""
|
|
121
|
+
|
|
122
|
+
levels: Mapping[str, Decimal]
|
|
123
|
+
|
|
124
|
+
def draw(self, open_stream: StreamFactory) -> str:
|
|
125
|
+
return categorical(open_stream(), self.levels)
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def word_cost(self) -> int:
|
|
129
|
+
return _UNIFORM_WORDS
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def expr_type(self) -> Type:
|
|
133
|
+
return enum_of(self.levels)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class BoundedNormal(Family):
|
|
138
|
+
"""KERNEL-SPEC §4's ``truncated_normal``: one uniform through the inverse CDF."""
|
|
139
|
+
|
|
140
|
+
mean: Decimal
|
|
141
|
+
stddev: Decimal
|
|
142
|
+
lo: Decimal
|
|
143
|
+
hi: Decimal
|
|
144
|
+
scale: int = 6
|
|
145
|
+
|
|
146
|
+
def draw(self, open_stream: StreamFactory) -> Decimal:
|
|
147
|
+
return truncated_normal(
|
|
148
|
+
open_stream(),
|
|
149
|
+
mean=self.mean,
|
|
150
|
+
stddev=self.stddev,
|
|
151
|
+
lo=self.lo,
|
|
152
|
+
hi=self.hi,
|
|
153
|
+
scale=self.scale,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def word_cost(self) -> int:
|
|
158
|
+
return _UNIFORM_WORDS
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def expr_type(self) -> Type:
|
|
162
|
+
return NUMBER
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@dataclass(frozen=True)
|
|
166
|
+
class RateCount(Family):
|
|
167
|
+
"""A count: KERNEL-SPEC §4's ``poisson`` shifted by a declared *offset*.
|
|
168
|
+
|
|
169
|
+
*offset* exists so a field whose smallest legal value is 1 (a payment
|
|
170
|
+
*attempts* counter) is declared as ``RateCount(mean, offset=1)`` rather than
|
|
171
|
+
drawn and then clamped -- clamping would put a spike of probability mass on
|
|
172
|
+
the bound and would make the drawn value's distribution depend on a
|
|
173
|
+
correction the declaration does not state.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
mean: Decimal
|
|
177
|
+
offset: int = 0
|
|
178
|
+
|
|
179
|
+
def draw(self, open_stream: StreamFactory) -> Decimal:
|
|
180
|
+
return Decimal(poisson(open_stream(), mean=self.mean) + self.offset)
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def word_cost(self) -> int:
|
|
184
|
+
return _UNIFORM_WORDS
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
def expr_type(self) -> Type:
|
|
188
|
+
return NUMBER
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(frozen=True)
|
|
192
|
+
class Bernoulli(Family):
|
|
193
|
+
"""A boolean at declared rate *p* -- KERNEL-SPEC §4's integer comparison."""
|
|
194
|
+
|
|
195
|
+
p: Decimal
|
|
196
|
+
|
|
197
|
+
def draw(self, open_stream: StreamFactory) -> bool:
|
|
198
|
+
return bernoulli(open_stream(), self.p)
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def word_cost(self) -> int:
|
|
202
|
+
return _UNIFORM_WORDS
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def expr_type(self) -> Type:
|
|
206
|
+
return BOOL
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@dataclass(frozen=True)
|
|
210
|
+
class SetOf(Family):
|
|
211
|
+
"""A ``set<string>``: one independent Bernoulli per declared member.
|
|
212
|
+
|
|
213
|
+
Members are drawn in NFC-sorted order and **every** member is drawn, so the
|
|
214
|
+
word cost is the member count and not the size of the set produced. A
|
|
215
|
+
subject that draws false on every member carries the empty set, which is a
|
|
216
|
+
legal ``set<string>``; ``products.has('tv')`` is simply false for it.
|
|
217
|
+
"""
|
|
218
|
+
|
|
219
|
+
members: Mapping[str, Decimal]
|
|
220
|
+
|
|
221
|
+
def draw(self, open_stream: StreamFactory) -> FrozenSet[str]:
|
|
222
|
+
stream = open_stream()
|
|
223
|
+
chosen = [name for name, rate in nfc_sorted_items(self.members) if bernoulli(stream, rate)]
|
|
224
|
+
return frozenset(chosen)
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def word_cost(self) -> int:
|
|
228
|
+
return _UNIFORM_WORDS * len(self.members)
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def expr_type(self) -> Type:
|
|
232
|
+
return SET_STRING
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def member_names(self) -> Tuple[str, ...]:
|
|
236
|
+
"""The declared members, NFC-sorted -- the order :meth:`draw` uses."""
|
|
237
|
+
return tuple(name for name, _ in nfc_sorted_items(self.members))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def drawn_type_satisfies(declared: Type, drawn: Type) -> bool:
|
|
241
|
+
"""Whether a family drawing *drawn* may fill a path declared as *declared*.
|
|
242
|
+
|
|
243
|
+
Equal kinds satisfy each other, with one refinement and one widening, both
|
|
244
|
+
read straight off EXPR-SPEC §2's "``enum<...>`` (a string drawn from a
|
|
245
|
+
declared closed set; compares as string)":
|
|
246
|
+
|
|
247
|
+
* an ``enum`` may fill a ``string`` -- every enum value *is* a string, and a
|
|
248
|
+
predicate written against the path compares it as one;
|
|
249
|
+
* an ``enum`` may fill an ``enum`` only when its levels are a subset of the
|
|
250
|
+
declared ones, because a level outside the declared set would make a
|
|
251
|
+
literal that is ``FLX-6003`` at plan time match at run time.
|
|
252
|
+
|
|
253
|
+
A ``string`` may **not** fill an ``enum``: the drawn value could be outside
|
|
254
|
+
the closed set the checker validated literals against.
|
|
255
|
+
"""
|
|
256
|
+
if declared.kind is drawn.kind:
|
|
257
|
+
if declared.kind is TypeKind.ENUM:
|
|
258
|
+
return set(drawn.levels) <= set(declared.levels)
|
|
259
|
+
return True
|
|
260
|
+
return declared.kind is TypeKind.STRING and drawn.kind is TypeKind.ENUM
|