gebra 0.0.1__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.
- gebra/__init__.py +114 -0
- gebra/annotations/__init__.py +154 -0
- gebra/annotations/contract.py +1036 -0
- gebra/annotations/errors.py +93 -0
- gebra/annotations/inference.py +1426 -0
- gebra/annotations/resolve.py +676 -0
- gebra/annotations/sidecar.py +776 -0
- gebra/annotations/slots.py +105 -0
- gebra/audit/__init__.py +79 -0
- gebra/audit/export.py +332 -0
- gebra/audit/freshness.py +128 -0
- gebra/audit/models.py +258 -0
- gebra/cli/__init__.py +47 -0
- gebra/cli/__main__.py +8 -0
- gebra/cli/app.py +681 -0
- gebra/cli/common.py +148 -0
- gebra/cli/diff.py +556 -0
- gebra/cli/display.py +307 -0
- gebra/cli/history.py +353 -0
- gebra/cli/invocation.py +192 -0
- gebra/cli/render.py +126 -0
- gebra/cli/resolve.py +378 -0
- gebra/cli/snapshot.py +343 -0
- gebra/cli/verify.py +357 -0
- gebra/diff/__init__.py +118 -0
- gebra/diff/contracts.py +375 -0
- gebra/diff/graph.py +190 -0
- gebra/diff/models.py +338 -0
- gebra/diff/state.py +260 -0
- gebra/diff/topology.py +367 -0
- gebra/diff/workflow.py +220 -0
- gebra/display/__init__.py +26 -0
- gebra/display/mermaid.py +240 -0
- gebra/display/overlay.py +349 -0
- gebra/extraction/__init__.py +231 -0
- gebra/extraction/base.py +83 -0
- gebra/extraction/builder.py +1229 -0
- gebra/extraction/compat.py +392 -0
- gebra/extraction/compiled.py +1330 -0
- gebra/extraction/contracts.py +616 -0
- gebra/extraction/digests.py +813 -0
- gebra/extraction/dispatch.py +320 -0
- gebra/extraction/envelope.py +297 -0
- gebra/extraction/errors.py +127 -0
- gebra/extraction/inference.py +82 -0
- gebra/extraction/lcel.py +1192 -0
- gebra/extraction/routing.py +309 -0
- gebra/extraction/sidecar.py +104 -0
- gebra/extraction/state.py +693 -0
- gebra/extraction/stock.py +121 -0
- gebra/extraction/warnings.py +368 -0
- gebra/ir/__init__.py +181 -0
- gebra/ir/base.py +59 -0
- gebra/ir/canonical.py +791 -0
- gebra/ir/identity.py +590 -0
- gebra/ir/models.py +515 -0
- gebra/ir/serialization.py +617 -0
- gebra/lineage/__init__.py +72 -0
- gebra/lineage/document.py +138 -0
- gebra/lineage/engine.py +265 -0
- gebra/lineage/models.py +244 -0
- gebra/naming.py +84 -0
- gebra/py.typed +0 -0
- gebra/pytest_plugin.py +2279 -0
- gebra/report/__init__.py +164 -0
- gebra/report/anchors.py +300 -0
- gebra/report/evidence.py +373 -0
- gebra/report/findings.py +149 -0
- gebra/report/human.py +465 -0
- gebra/report/native.py +38 -0
- gebra/report/rules.py +293 -0
- gebra/report/sarif.py +257 -0
- gebra/report/suggestions.py +82 -0
- gebra/snapshot/__init__.py +72 -0
- gebra/snapshot/engine.py +524 -0
- gebra/snapshot/models.py +164 -0
- gebra/store/__init__.py +121 -0
- gebra/store/atomic.py +124 -0
- gebra/store/base.py +63 -0
- gebra/store/models.py +361 -0
- gebra/store/serialization.py +198 -0
- gebra/store/store.py +507 -0
- gebra/testing/__init__.py +122 -0
- gebra/testing/fixtures.py +808 -0
- gebra/testing/harness.py +894 -0
- gebra/testing/mutations.py +2172 -0
- gebra/testing/strategies.py +1027 -0
- gebra/verify/__init__.py +422 -0
- gebra/verify/base.py +358 -0
- gebra/verify/conditions.py +741 -0
- gebra/verify/graph.py +898 -0
- gebra/verify/guards.py +657 -0
- gebra/verify/locations.py +245 -0
- gebra/verify/properties/__init__.py +37 -0
- gebra/verify/properties/dataflow_completeness.py +673 -0
- gebra/verify/properties/determinism_replay.py +334 -0
- gebra/verify/properties/effect_safety.py +489 -0
- gebra/verify/properties/graph_well_formed.py +351 -0
- gebra/verify/properties/termination_witness.py +1023 -0
- gebra/verify/registry.py +477 -0
- gebra/verify/report.py +242 -0
- gebra/verify/run.py +863 -0
- gebra/verify/witnesses.py +430 -0
- gebra/versioning/__init__.py +85 -0
- gebra/versioning/classify.py +289 -0
- gebra/versioning/models.py +301 -0
- gebra-0.0.1.dist-info/METADATA +453 -0
- gebra-0.0.1.dist-info/RECORD +112 -0
- gebra-0.0.1.dist-info/WHEEL +4 -0
- gebra-0.0.1.dist-info/entry_points.txt +5 -0
- gebra-0.0.1.dist-info/licenses/LICENSE +201 -0
- gebra-0.0.1.dist-info/licenses/NOTICE +2 -0
|
@@ -0,0 +1,1036 @@
|
|
|
1
|
+
"""The decorator declaration surface — ANNOTATION-API-SPEC §1.
|
|
2
|
+
|
|
3
|
+
``@gebra.contract`` and its six shorthands are how an author declares a node contract next to
|
|
4
|
+
the node. §1 fixes what they do in one sentence: they "attach metadata under one namespaced
|
|
5
|
+
attribute (``__gebra_contract__``) and return the function unchanged — they never wrap,
|
|
6
|
+
reorder, or invoke it".
|
|
7
|
+
|
|
8
|
+
Three properties carry the whole surface, and each is enforced rather than documented.
|
|
9
|
+
|
|
10
|
+
**Identity.** Every decorator here returns the object it was given — the *same* object, not
|
|
11
|
+
an equal one. This is not tidiness: §6 requires annotations to survive ``.compile()``, and
|
|
12
|
+
they do so precisely because gebra adds no wrapper for LangGraph's own wrapping to replace.
|
|
13
|
+
It also settles the never-invokes question at this surface by construction (WA-07): a
|
|
14
|
+
decorator that builds no callable has nothing to call, and one that returns its input
|
|
15
|
+
unchanged cannot have run that input's body.
|
|
16
|
+
|
|
17
|
+
**One attribute, in IR spellings.** The attached value is a :class:`NodeContract` — a frozen
|
|
18
|
+
model whose members are exactly the nine annotatable slots of
|
|
19
|
+
:data:`~gebra.annotations.slots.ANNOTATION_SLOTS`, named as the IR names the slots rather
|
|
20
|
+
than as the decorator arguments spell them (``reads``→``input``, ``writes``→``output``,
|
|
21
|
+
``effects``→``effect``). That is the vocabulary §5's (node id, slot) grade lookup and §3's
|
|
22
|
+
per-slot precedence chain are written in, so the carrier speaks it directly, and
|
|
23
|
+
``extra="forbid"`` makes the nine-slot closure structural rather than a convention.
|
|
24
|
+
|
|
25
|
+
**Errors at import time, and only these four.** §1's consistency rules raise
|
|
26
|
+
:class:`~gebra.annotations.errors.GebraContractError` "at import time — cheap, early, never
|
|
27
|
+
at extraction". Exactly four rules live here: the at-most-once slot rule, ``pure``/``effects``
|
|
28
|
+
exclusivity, the closed effect vocabulary, and the ``deterministic`` object form's required
|
|
29
|
+
``seed``. The two decision D-012 checks §1 states in the same list — an idempotency key that
|
|
30
|
+
must appear in the resolved ``input``, and ``irreversible`` together with ``idempotent=True``
|
|
31
|
+
— are deliberately **not** here: §1 says both "need the *resolved* contract, so they run at
|
|
32
|
+
extraction, not decoration — warning-grade, never an error". Enforcing either here would turn
|
|
33
|
+
a warning into an import failure and would judge a stack against an ``input`` set that does
|
|
34
|
+
not exist yet.
|
|
35
|
+
|
|
36
|
+
**No decorator argument is rendered before it is checked.** Error messages name a rejected
|
|
37
|
+
value's *type* (:func:`~gebra.naming.type_identity`) and show its value only once it is known
|
|
38
|
+
to be a plain string, number or bool. A message built with ``{value!r}`` would run the
|
|
39
|
+
value's own ``__repr__``, which would let a decorator argument replace gebra's error with an
|
|
40
|
+
exception of its own — the same hazard EX-02's pre-review found on the extraction path, in
|
|
41
|
+
the one other place this package reads user-supplied values. Foreign containers are read
|
|
42
|
+
through unbound built-in accessors for the same reason (:mod:`gebra.ir.canonical` established
|
|
43
|
+
the pattern), and a ``**kwargs`` key is copied into a plain ``str`` before anything looks at
|
|
44
|
+
it, since CPython admits a ``str`` subclass there.
|
|
45
|
+
|
|
46
|
+
Nothing here imports langgraph or opens a socket, and no decoration path calls the object it
|
|
47
|
+
decorates. **Two residuals, stated rather than implied**, because "executes nothing" would be
|
|
48
|
+
too strong a claim for a surface whose whole job is to accept caller-supplied values:
|
|
49
|
+
|
|
50
|
+
* §1 types ``reads``/``writes``/``effects`` as ``Iterable[str]``, and an iterable has to be
|
|
51
|
+
iterated to be read. ``list``/``tuple`` go through the unbound accessors, but anything else
|
|
52
|
+
— a generator, a ``set``, a custom container — runs its own ``__iter__``/``__next__``. That
|
|
53
|
+
is the caller's own value in the caller's own import, not a node being invoked, and there
|
|
54
|
+
is no way to accept §1's declared type without it. Nothing re-iterates afterwards:
|
|
55
|
+
extraction reads the already-materialized tuple. The bound is stated, not enforced — a
|
|
56
|
+
generator that never stops would hang decoration, and capping the length would be inventing
|
|
57
|
+
a limit §1 does not have.
|
|
58
|
+
* Attachment is a ``setattr``, so a target's own ``__setattr__`` or a data descriptor on its
|
|
59
|
+
metaclass runs. That is inherent to §1's "attach metadata under one namespaced attribute",
|
|
60
|
+
and the failure case is handled: a target that cannot carry one is pointed at §6's sidecar.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
from __future__ import annotations
|
|
64
|
+
|
|
65
|
+
import difflib
|
|
66
|
+
import math
|
|
67
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
68
|
+
from types import MappingProxyType
|
|
69
|
+
from typing import Any, Final, TypeVar, overload
|
|
70
|
+
|
|
71
|
+
from pydantic import BaseModel, ConfigDict
|
|
72
|
+
|
|
73
|
+
from gebra.annotations.errors import ContractErrorReason, GebraContractError
|
|
74
|
+
from gebra.annotations.slots import ANNOTATION_SLOTS, EFFECT_TAGS, AnnotationSlot
|
|
75
|
+
from gebra.ir.canonical import I_JSON_MAX_INT, I_JSON_MIN_INT
|
|
76
|
+
from gebra.ir.models import Compensation, DeterministicSpec, IdempotentKey, Variant
|
|
77
|
+
from gebra.naming import type_identity
|
|
78
|
+
|
|
79
|
+
__all__ = [
|
|
80
|
+
"CONTRACT_ATTRIBUTE",
|
|
81
|
+
"SLOT_KEYWORDS",
|
|
82
|
+
"NodeContract",
|
|
83
|
+
"compensation",
|
|
84
|
+
"contract",
|
|
85
|
+
"deterministic",
|
|
86
|
+
"effect",
|
|
87
|
+
"idempotent",
|
|
88
|
+
"normalize_declared_value",
|
|
89
|
+
"normalize_effect_members",
|
|
90
|
+
"pure",
|
|
91
|
+
"read_contract",
|
|
92
|
+
"variant",
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
#: The one namespaced attribute §1 and §6 fix for the carrier. Normative, not a convention:
|
|
96
|
+
#: §6 relies on the name being gebra's own, so that LangGraph's wrapping of a node callable
|
|
97
|
+
#: "cannot strip it by replacing a wrapper Gebra never added", and INTROSPECTION §3 reads it
|
|
98
|
+
#: back under this spelling.
|
|
99
|
+
CONTRACT_ATTRIBUTE: Final = "__gebra_contract__"
|
|
100
|
+
|
|
101
|
+
#: The decorated callable, always returned unchanged (§1's own ``F``).
|
|
102
|
+
F = TypeVar("F", bound=Callable[..., object])
|
|
103
|
+
|
|
104
|
+
#: How deep an ``args_schema`` may nest. Set far above anything a JSON Schema needs; it
|
|
105
|
+
#: exists so a self-referential mapping becomes a message rather than a ``RecursionError``.
|
|
106
|
+
_MAX_SCHEMA_DEPTH: Final = 64
|
|
107
|
+
|
|
108
|
+
#: The keywords :func:`contract` accepts, in signature order — the seven of the nine slots
|
|
109
|
+
#: that have a ``contract()`` route. ``variant`` and ``compensation`` are annotatable too,
|
|
110
|
+
#: but only through their own decorators (§1).
|
|
111
|
+
_CONTRACT_KEYWORDS: Final[tuple[str, ...]] = (
|
|
112
|
+
"reads",
|
|
113
|
+
"writes",
|
|
114
|
+
"effects",
|
|
115
|
+
"pure",
|
|
116
|
+
"idempotent",
|
|
117
|
+
"deterministic",
|
|
118
|
+
"args_schema",
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
#: Ledger slots §1 puts "out of annotation reach", each with why. Reaching for one is a
|
|
122
|
+
#: specific misunderstanding, so it gets a specific answer rather than "unknown keyword".
|
|
123
|
+
_OUT_OF_REACH: Final[Mapping[str, str]] = MappingProxyType(
|
|
124
|
+
{
|
|
125
|
+
"retry_policy": (
|
|
126
|
+
"extracted, never annotated: it is projected from the builder's "
|
|
127
|
+
"StateNodeSpec.retry_policy (INTROSPECTION-SPEC §3)"
|
|
128
|
+
),
|
|
129
|
+
"prompt_digest": (
|
|
130
|
+
"computed, never annotated: the extractor digests the node's prompt template "
|
|
131
|
+
"(ir-field-ledger §3)"
|
|
132
|
+
),
|
|
133
|
+
"config_digest": (
|
|
134
|
+
"computed, never annotated: the extractor digests the node's generation config "
|
|
135
|
+
"(ir-field-ledger §3)"
|
|
136
|
+
),
|
|
137
|
+
"interrupts": (
|
|
138
|
+
"extracted, never annotated: interrupt gates are a compile() kwarg, read into "
|
|
139
|
+
"runtime.interrupts (INTROSPECTION-SPEC §4)"
|
|
140
|
+
),
|
|
141
|
+
"checkpointer": (
|
|
142
|
+
"extracted, never annotated: checkpointing is a compile() kwarg, read into "
|
|
143
|
+
"runtime.checkpointer (INTROSPECTION-SPEC §4)"
|
|
144
|
+
),
|
|
145
|
+
"recursion_limit": (
|
|
146
|
+
"a graph-level runtime slot rather than a node contract (IR-SPEC §3.5)"
|
|
147
|
+
),
|
|
148
|
+
"source": "part of the parked data-isolation track (D-017), with no surface in this spec",
|
|
149
|
+
"map": "part of the parked data-isolation track (D-017), with no surface in this spec",
|
|
150
|
+
}
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
#: The IR names of the three slots whose ``contract()`` keyword is spelled differently. A
|
|
154
|
+
#: caller who reaches for the IR spelling has the right slot and the wrong word, which is a
|
|
155
|
+
#: different mistake from a typo and gets a different answer.
|
|
156
|
+
_IR_SPELLINGS: Final[Mapping[str, str]] = MappingProxyType(
|
|
157
|
+
{"input": "reads", "output": "writes", "effect": "effects"}
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
#: The declaration spelling of each annotatable slot → the IR slot it fills. §1 states the
|
|
161
|
+
#: nine as pairs (``reads``→``input``, ``writes``→``output``, ``effects``→``effect``) and §2's
|
|
162
|
+
#: sidecar example writes the left-hand side, so this table is the *one* vocabulary both
|
|
163
|
+
#: declaration surfaces are keyed by — "the decorator (§1) and sidecar (§2) share the set
|
|
164
|
+
#: byte-for-byte" (§1).
|
|
165
|
+
SLOT_KEYWORDS: Final[Mapping[str, AnnotationSlot]] = MappingProxyType(
|
|
166
|
+
{
|
|
167
|
+
"reads": "input",
|
|
168
|
+
"writes": "output",
|
|
169
|
+
"effects": "effect",
|
|
170
|
+
"pure": "pure",
|
|
171
|
+
"idempotent": "idempotent",
|
|
172
|
+
"deterministic": "deterministic",
|
|
173
|
+
"args_schema": "args_schema",
|
|
174
|
+
"variant": "variant",
|
|
175
|
+
"compensation": "compensation",
|
|
176
|
+
}
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class NodeContract(BaseModel):
|
|
181
|
+
"""A declared node contract — what ``__gebra_contract__`` holds (ANNOTATION §1).
|
|
182
|
+
|
|
183
|
+
Exactly the nine annotatable slots, in their IR spellings and IR shapes, so that §3's
|
|
184
|
+
precedence chain and §5's grade lookup read it without translating. A slot is **declared
|
|
185
|
+
iff its value is not** ``None`` — §3's "Set means not-``None``" rule, which is why an
|
|
186
|
+
explicit ``pure=False`` occupies its slot and an omitted one does not, and why no
|
|
187
|
+
separate record of "which slots were set" is needed.
|
|
188
|
+
|
|
189
|
+
Frozen, ``extra="forbid"`` and ``strict=True``, following the A6 conventions the IR and
|
|
190
|
+
envelope bases carry: the value reaches ``graph_version`` through the §3 resolution, so
|
|
191
|
+
an unknown member has to be an error rather than silently-dropped content, and a slot
|
|
192
|
+
that could be *rebound* after attachment could move a digest with no re-decoration in
|
|
193
|
+
sight. One residual, stated because ``frozen`` is easy to over-read: freezing prevents
|
|
194
|
+
rebinding a slot, not mutation *inside* one, and ``args_schema`` is the one slot whose
|
|
195
|
+
value has an interior. Its arrays are frozen into tuples, but its objects stay ordinary
|
|
196
|
+
``dict``s — a read-only proxy could not be canonicalized, since
|
|
197
|
+
:func:`gebra.ir.canonical.graph_version` reads foreign content with ``isinstance(...,
|
|
198
|
+
dict)``. So a holder of the carrier can still edit the schema in place.
|
|
199
|
+
|
|
200
|
+
Values arrive here already normalized by this module's decorators — plain strings, bools,
|
|
201
|
+
ints, floats, tuples, JSON data, and the four IR sub-models — so this model never
|
|
202
|
+
validates a raw user value and never renders one.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
206
|
+
|
|
207
|
+
input: tuple[str, ...] | None = None
|
|
208
|
+
"""Declared state-key reads (``reads=``) — IR ``input`` (decision D-010 @INPUT)."""
|
|
209
|
+
output: tuple[str, ...] | None = None
|
|
210
|
+
"""Declared state-key writes (``writes=``) — IR ``output`` (decision D-010 @OUTPUT)."""
|
|
211
|
+
effect: tuple[str, ...] | None = None
|
|
212
|
+
"""Declared effect tags (``effects=``), each from :data:`EFFECT_TAGS` (decision D-011)."""
|
|
213
|
+
pure: bool | None = None
|
|
214
|
+
idempotent: bool | IdempotentKey | None = None
|
|
215
|
+
deterministic: bool | DeterministicSpec | None = None
|
|
216
|
+
args_schema: dict[str, Any] | None = None
|
|
217
|
+
"""A JSON Schema object; 1.0 imposes no schema algebra on its contents (ledger §3)."""
|
|
218
|
+
variant: Variant | None = None
|
|
219
|
+
compensation: Compensation | None = None
|
|
220
|
+
|
|
221
|
+
@classmethod
|
|
222
|
+
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Any:
|
|
223
|
+
"""Refuse construction that skips validation (A6 PC-6).
|
|
224
|
+
|
|
225
|
+
Raises:
|
|
226
|
+
NotImplementedError: always. A contract built without validation would carry an
|
|
227
|
+
unchecked value into the §3 resolution and from there into ``graph_version``.
|
|
228
|
+
"""
|
|
229
|
+
raise NotImplementedError(
|
|
230
|
+
f"{cls.__name__}.model_construct() is banned (A6 PC-6): it skips validation, and a "
|
|
231
|
+
"declared contract is resolved into the IR and digested. Use the decorators of "
|
|
232
|
+
"gebra.annotations, or the constructor."
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
def declared_slots(self) -> tuple[AnnotationSlot, ...]:
|
|
236
|
+
"""The slots this contract declares, in :data:`ANNOTATION_SLOTS` order.
|
|
237
|
+
|
|
238
|
+
"Declared" is §3's test — not ``None``. An explicit negative (``pure=False``) is a
|
|
239
|
+
declaration and appears here; an omitted slot does not.
|
|
240
|
+
"""
|
|
241
|
+
return tuple(slot for slot in ANNOTATION_SLOTS if getattr(self, slot) is not None)
|
|
242
|
+
|
|
243
|
+
def slot_value(self, slot: AnnotationSlot) -> object:
|
|
244
|
+
"""The value of ``slot``, or ``None`` when it is not declared."""
|
|
245
|
+
return getattr(self, slot)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def read_contract(target: object) -> NodeContract | None:
|
|
249
|
+
"""The contract ``target`` itself carries, or ``None``.
|
|
250
|
+
|
|
251
|
+
Reads the object's **own** namespace rather than using ``getattr``, so a class that
|
|
252
|
+
inherits a decorated base is not reported as carrying its base's contract. This answers
|
|
253
|
+
the single-object question only: §6's walk along ``functools.wraps`` chains, and its
|
|
254
|
+
outermost-carrier rule for a chain with several carriers, belong to the extraction-time
|
|
255
|
+
resolution, not here.
|
|
256
|
+
|
|
257
|
+
The namespace is read through the unbound built-in accessor, because an instance
|
|
258
|
+
``__dict__`` may be *assigned* a ``dict`` subclass — so ``namespace.get(...)`` would run
|
|
259
|
+
that subclass's own ``get`` on a target gebra was merely asked to decorate (WA-07).
|
|
260
|
+
``mappingproxy``, which a class carries, cannot be subclassed, but is read the same way
|
|
261
|
+
so the two branches say the same thing.
|
|
262
|
+
|
|
263
|
+
Raises:
|
|
264
|
+
GebraContractError: if ``target`` carries a ``__gebra_contract__`` that is not a
|
|
265
|
+
:class:`NodeContract`. Overwriting it silently would discard whatever set it.
|
|
266
|
+
"""
|
|
267
|
+
namespace = getattr(target, "__dict__", None)
|
|
268
|
+
if isinstance(namespace, dict):
|
|
269
|
+
carried = dict.get(namespace, CONTRACT_ATTRIBUTE)
|
|
270
|
+
elif isinstance(namespace, MappingProxyType):
|
|
271
|
+
carried = MappingProxyType.get(namespace, CONTRACT_ATTRIBUTE)
|
|
272
|
+
else:
|
|
273
|
+
return None
|
|
274
|
+
if carried is None:
|
|
275
|
+
return None
|
|
276
|
+
if not isinstance(carried, NodeContract):
|
|
277
|
+
raise GebraContractError(
|
|
278
|
+
f"{CONTRACT_ATTRIBUTE} is already set to a {type_identity(carried)}, which is not a "
|
|
279
|
+
"NodeContract; gebra owns this attribute (ANNOTATION-API-SPEC §1) and will not "
|
|
280
|
+
"overwrite something it did not attach",
|
|
281
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
282
|
+
)
|
|
283
|
+
return carried
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def normalize_declared_value(keyword: str, value: object) -> object:
|
|
287
|
+
"""One declared slot value in its carrier form — the shape :class:`NodeContract` holds.
|
|
288
|
+
|
|
289
|
+
The normalization seam the two declaration surfaces share. §1 fixes the shapes; §2 says
|
|
290
|
+
the sidecar carries "the same slot vocabulary (the §1 closed annotatable-slot set,
|
|
291
|
+
byte-for-byte)"; and §3 decides "identical values are not a conflict" **structurally** —
|
|
292
|
+
by byte-equality of the two canonicalizations. So the sidecar loader must land on the same
|
|
293
|
+
value the decorator does, down to the type: a TOML ``temperature = 0`` and a decorator
|
|
294
|
+
``temperature=0.0`` have to become one value, or §3's rule reports a conflict between two
|
|
295
|
+
spellings of the same declaration. Sharing the code is what makes that true by
|
|
296
|
+
construction rather than by two implementations agreeing today.
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
keyword: The declaration spelling — a key of :data:`SLOT_KEYWORDS`.
|
|
300
|
+
value: The authored value, unchecked.
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
The normalized value for the slot ``SLOT_KEYWORDS[keyword]``.
|
|
304
|
+
|
|
305
|
+
Raises:
|
|
306
|
+
GebraContractError: if ``value`` is not of its slot's kind. On the decorator surface
|
|
307
|
+
that is §1's import-time error; the sidecar loader catches it and degrades to an
|
|
308
|
+
``annotation-invalid`` warning (§2), which is why the reason code and ``slot`` are
|
|
309
|
+
carried rather than only a message.
|
|
310
|
+
KeyError: if ``keyword`` is not one of the nine. Callers check membership first —
|
|
311
|
+
both surfaces have their own answer for an unknown key.
|
|
312
|
+
"""
|
|
313
|
+
slot = SLOT_KEYWORDS[keyword]
|
|
314
|
+
if keyword in ("reads", "writes"):
|
|
315
|
+
return _state_keys(value, slot=slot, argument=keyword)
|
|
316
|
+
if keyword == "effects":
|
|
317
|
+
return _effect_tags(value)
|
|
318
|
+
if keyword == "pure":
|
|
319
|
+
return _flag(value, slot=slot, argument=keyword)
|
|
320
|
+
if keyword == "idempotent":
|
|
321
|
+
return _idempotent_value(value)
|
|
322
|
+
if keyword == "deterministic":
|
|
323
|
+
return _deterministic_value(value)
|
|
324
|
+
if keyword == "args_schema":
|
|
325
|
+
return _args_schema_value(value)
|
|
326
|
+
if keyword == "variant":
|
|
327
|
+
return _variant_value(value)
|
|
328
|
+
return _compensation_value(value)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def normalize_effect_members(tags: object) -> tuple[str, ...]:
|
|
332
|
+
"""The declared effect tags as plain strings, **without** the D-011 vocabulary check.
|
|
333
|
+
|
|
334
|
+
Split out because the two surfaces reject an unknown tag at different granularities: §1
|
|
335
|
+
makes it an error for the whole decoration, while §2 rejects "the tag" and keeps the
|
|
336
|
+
entry. Both need the same reading of the container first — a bare string refused, members
|
|
337
|
+
checked rather than coerced — so that half lives here and each surface applies the closed
|
|
338
|
+
:data:`~gebra.annotations.slots.EFFECT_TAGS` set in its own way.
|
|
339
|
+
|
|
340
|
+
Raises:
|
|
341
|
+
GebraContractError: if ``tags`` is not a non-string iterable of strings.
|
|
342
|
+
"""
|
|
343
|
+
members = _sequence(tags, slot="effect", argument="effects", unit="effect tag")
|
|
344
|
+
return _strings(members, slot="effect", argument="effects", unit="effect tag")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# ── The decorators ───────────────────────────────────────────────────────────────────────
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def contract(
|
|
351
|
+
*,
|
|
352
|
+
reads: Iterable[str] | None = None,
|
|
353
|
+
writes: Iterable[str] | None = None,
|
|
354
|
+
effects: Iterable[str] | None = None,
|
|
355
|
+
pure: bool | None = None,
|
|
356
|
+
idempotent: bool | dict[str, str] | None = None,
|
|
357
|
+
deterministic: bool | dict[str, int | float] | None = None,
|
|
358
|
+
args_schema: dict[str, object] | None = None,
|
|
359
|
+
**unknown: object,
|
|
360
|
+
) -> Callable[[F], F]:
|
|
361
|
+
"""Declare a node contract, and return the decorated callable unchanged (§1).
|
|
362
|
+
|
|
363
|
+
Every argument is optional, and every omitted one leaves its slot open for the lower
|
|
364
|
+
precedence tiers of §3 (tool-carried schema, sidecar, inference). An explicit negative is
|
|
365
|
+
a declaration and closes its slot: ``pure=False`` says "not pure", not "unstated".
|
|
366
|
+
|
|
367
|
+
Args:
|
|
368
|
+
reads: State keys the node reads — IR ``input``. Any iterable of strings *except* a
|
|
369
|
+
bare string, which is refused: a string is an iterable of characters, and
|
|
370
|
+
silently reading ``"budget"`` as six state keys would land in the digest.
|
|
371
|
+
writes: State keys the node writes — IR ``output``. Same rule.
|
|
372
|
+
effects: Effect tags, each from the closed decision D-011 vocabulary
|
|
373
|
+
:data:`~gebra.annotations.slots.EFFECT_TAGS`.
|
|
374
|
+
pure: Whether the node is pure. Mutually exclusive with a non-empty ``effects``.
|
|
375
|
+
idempotent: ``True``/``False``, or ``{"key": "<state key>"}``. Whether the key is a
|
|
376
|
+
member of the node's resolved ``input`` is checked at *extraction*, warning-grade
|
|
377
|
+
(§1) — a decorator cannot know the resolved input set.
|
|
378
|
+
deterministic: ``True``/``False``, or ``{"seed": <int>}`` with an optional
|
|
379
|
+
``"temperature"``. The object form requires ``seed``.
|
|
380
|
+
args_schema: A JSON Schema object for the node/tool argument shape. JSON data
|
|
381
|
+
throughout, since it is serialized into the IR and digested.
|
|
382
|
+
**unknown: Accepted only in order to be refused, with a message saying why. No
|
|
383
|
+
keyword here is ever attached: the surface is the nine slots and nothing else.
|
|
384
|
+
|
|
385
|
+
Returns:
|
|
386
|
+
A decorator that attaches the declared slots and returns its argument unchanged.
|
|
387
|
+
|
|
388
|
+
Raises:
|
|
389
|
+
GebraContractError: on any §1 consistency violation, on a keyword outside the nine
|
|
390
|
+
annotatable slots, or on a value that is not of its slot's kind.
|
|
391
|
+
"""
|
|
392
|
+
if unknown:
|
|
393
|
+
_refuse_unknown_keywords(unknown)
|
|
394
|
+
|
|
395
|
+
declared: dict[str, object] = {}
|
|
396
|
+
if reads is not None:
|
|
397
|
+
declared["input"] = _state_keys(reads, slot="input", argument="reads")
|
|
398
|
+
if writes is not None:
|
|
399
|
+
declared["output"] = _state_keys(writes, slot="output", argument="writes")
|
|
400
|
+
if effects is not None:
|
|
401
|
+
declared["effect"] = _effect_tags(effects)
|
|
402
|
+
if pure is not None:
|
|
403
|
+
declared["pure"] = _flag(pure, slot="pure", argument="pure")
|
|
404
|
+
if idempotent is not None:
|
|
405
|
+
declared["idempotent"] = _idempotent_value(idempotent)
|
|
406
|
+
if deterministic is not None:
|
|
407
|
+
declared["deterministic"] = _deterministic_value(deterministic)
|
|
408
|
+
if args_schema is not None:
|
|
409
|
+
declared["args_schema"] = _args_schema_value(args_schema)
|
|
410
|
+
|
|
411
|
+
def decorate(fn: F) -> F:
|
|
412
|
+
return _attach(fn, declared, surface="@gebra.contract")
|
|
413
|
+
|
|
414
|
+
return decorate
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def pure(fn: F) -> F:
|
|
418
|
+
"""Declare the node pure — ``@gebra.pure``, sugar for ``contract(pure=True)`` (§1).
|
|
419
|
+
|
|
420
|
+
The bare form is the only one §1 gives this shorthand; ``contract(pure=False)`` is how a
|
|
421
|
+
node is declared explicitly *not* pure.
|
|
422
|
+
"""
|
|
423
|
+
return _attach(fn, {"pure": True}, surface="@gebra.pure")
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def effect(*tags: str) -> Callable[[F], F]:
|
|
427
|
+
"""Declare effect tags — ``@gebra.effect("irreversible", "billable")`` (§1).
|
|
428
|
+
|
|
429
|
+
Raises:
|
|
430
|
+
GebraContractError: if any tag is outside the closed decision D-011 vocabulary, or if
|
|
431
|
+
the decorator was applied bare (``@gebra.effect``), which would otherwise read
|
|
432
|
+
the decorated function itself as a tag.
|
|
433
|
+
"""
|
|
434
|
+
# Typed `object` on purpose: the declared parameter is `str`, so a type checker reads
|
|
435
|
+
# `tags[0]` as one and would call the guard below dead — but `@gebra.effect` written bare
|
|
436
|
+
# puts the decorated function here at runtime, which is exactly what this catches.
|
|
437
|
+
sole: object = tags[0] if len(tags) == 1 else None
|
|
438
|
+
if sole is not None and not isinstance(sole, str) and callable(sole):
|
|
439
|
+
raise GebraContractError(
|
|
440
|
+
"@gebra.effect takes its tags and has no bare form: write "
|
|
441
|
+
'@gebra.effect("network") rather than @gebra.effect',
|
|
442
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
443
|
+
slot="effect",
|
|
444
|
+
)
|
|
445
|
+
declared: dict[str, object] = {"effect": _effect_tags(tags)}
|
|
446
|
+
|
|
447
|
+
def decorate(fn: F) -> F:
|
|
448
|
+
return _attach(fn, declared, surface="@gebra.effect")
|
|
449
|
+
|
|
450
|
+
return decorate
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
@overload
|
|
454
|
+
def idempotent(fn: F) -> F: ...
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
@overload
|
|
458
|
+
def idempotent(fn: None = None, *, key: str | None = None) -> Callable[[F], F]: ...
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def idempotent(fn: Any = None, *, key: str | None = None) -> Any:
|
|
462
|
+
"""Declare idempotence — ``@gebra.idempotent`` or ``@gebra.idempotent(key="...")`` (§1).
|
|
463
|
+
|
|
464
|
+
The bare form declares ``idempotent: true``; the keyed form declares
|
|
465
|
+
``{"key": "<state key>"}``. Whether the key is a member of the node's resolved ``input``
|
|
466
|
+
is an *extraction*-time check and warning-grade (§1), because the resolved input set does
|
|
467
|
+
not exist at decoration time.
|
|
468
|
+
"""
|
|
469
|
+
declared: dict[str, object] = {
|
|
470
|
+
"idempotent": True if key is None else IdempotentKey(key=_reference(key, argument="key"))
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
def decorate(inner: F) -> F:
|
|
474
|
+
return _attach(inner, declared, surface="@gebra.idempotent")
|
|
475
|
+
|
|
476
|
+
return decorate if fn is None else decorate(fn)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
@overload
|
|
480
|
+
def deterministic(fn: F) -> F: ...
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
@overload
|
|
484
|
+
def deterministic(
|
|
485
|
+
fn: None = None, *, seed: int | None = None, temperature: float | None = None
|
|
486
|
+
) -> Callable[[F], F]: ...
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def deterministic(
|
|
490
|
+
fn: Any = None, *, seed: int | None = None, temperature: float | None = None
|
|
491
|
+
) -> Any:
|
|
492
|
+
"""Declare determinism — ``@gebra.deterministic`` or ``(seed=42, temperature=0.0)`` (§1).
|
|
493
|
+
|
|
494
|
+
Raises:
|
|
495
|
+
GebraContractError: if ``temperature`` is given without ``seed``. §1 names this case
|
|
496
|
+
outright; the frozen ledger §3 shape ``{seed: int, temperature?: number}`` is
|
|
497
|
+
what owns the ruling, since the dict type hint cannot express requiredness.
|
|
498
|
+
"""
|
|
499
|
+
declared: dict[str, object] = {"deterministic": _deterministic_form(seed, temperature)}
|
|
500
|
+
|
|
501
|
+
def decorate(inner: F) -> F:
|
|
502
|
+
return _attach(inner, declared, surface="@gebra.deterministic")
|
|
503
|
+
|
|
504
|
+
return decorate if fn is None else decorate(fn)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def variant(*, key: str, measure: str) -> Callable[[F], F]:
|
|
508
|
+
"""Declare a loop variant — ``@gebra.variant(key="remaining", measure="len")`` (§1).
|
|
509
|
+
|
|
510
|
+
The P-02 witness form (c) carrier. What measures are admissible, and what discharge
|
|
511
|
+
requires, are owned by R-05's TERMINATION-WITNESS-SPEC; §1 and the ledger fix only the
|
|
512
|
+
two field names, so nothing here interprets either value.
|
|
513
|
+
"""
|
|
514
|
+
declared: dict[str, object] = {
|
|
515
|
+
"variant": Variant(
|
|
516
|
+
key=_reference(key, argument="key"),
|
|
517
|
+
measure=_reference(measure, argument="measure"),
|
|
518
|
+
)
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
def decorate(fn: F) -> F:
|
|
522
|
+
return _attach(fn, declared, surface="@gebra.variant")
|
|
523
|
+
|
|
524
|
+
return decorate
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def compensation(*, hook: str) -> Callable[[F], F]:
|
|
528
|
+
"""Declare a compensation hook — ``@gebra.compensation(hook="cancel_booking")`` (§1).
|
|
529
|
+
|
|
530
|
+
``hook`` is a node id under the ledger §5 grammar. It is stored as written and not
|
|
531
|
+
checked against that grammar here, for the reason :mod:`gebra.ir.models` records for
|
|
532
|
+
every reference-role string: whether a reference *resolves* is the reporting stage's
|
|
533
|
+
question, and §1's consistency rules — the closed list this module enforces — do not
|
|
534
|
+
include it.
|
|
535
|
+
"""
|
|
536
|
+
declared: dict[str, object] = {
|
|
537
|
+
"compensation": Compensation(hook=_reference(hook, argument="hook"))
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
def decorate(fn: F) -> F:
|
|
541
|
+
return _attach(fn, declared, surface="@gebra.compensation")
|
|
542
|
+
|
|
543
|
+
return decorate
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
# ── Attachment ───────────────────────────────────────────────────────────────────────────
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _attach(fn: F, declared: Mapping[str, object], *, surface: str) -> F:
|
|
550
|
+
"""Merge ``declared`` into ``fn``'s contract and return ``fn`` — the same object (§1).
|
|
551
|
+
|
|
552
|
+
The merge is where §1's at-most-once rule lives, because a decorator *stack* applies
|
|
553
|
+
bottom-up to one object: each decorator sees what the ones below it attached.
|
|
554
|
+
"""
|
|
555
|
+
existing = read_contract(fn)
|
|
556
|
+
_refuse_duplicate_slots(existing, declared, surface=surface)
|
|
557
|
+
|
|
558
|
+
merged: dict[str, object] = (
|
|
559
|
+
{slot: existing.slot_value(slot) for slot in existing.declared_slots()}
|
|
560
|
+
if existing is not None
|
|
561
|
+
else {}
|
|
562
|
+
)
|
|
563
|
+
merged.update(declared)
|
|
564
|
+
# Validated rather than constructed positionally: the merge is a mapping of slot name to
|
|
565
|
+
# already-normalized value, and `model_validate` is the one path that keeps `extra="forbid"`
|
|
566
|
+
# meaningful for it — a key that is not a slot is an error here rather than a silent drop.
|
|
567
|
+
declaration = NodeContract.model_validate(merged)
|
|
568
|
+
_refuse_pure_with_effects(declaration, surface=surface)
|
|
569
|
+
|
|
570
|
+
try:
|
|
571
|
+
setattr(fn, CONTRACT_ATTRIBUTE, declaration)
|
|
572
|
+
except (AttributeError, TypeError) as exc:
|
|
573
|
+
raise GebraContractError(
|
|
574
|
+
# The raw exception text is interpreter-dependent (CPython 3.13 enriched the
|
|
575
|
+
# slotted-object AttributeError message), and this diagnostic is stable
|
|
576
|
+
# user-facing copy that documented examples print verbatim (DOC-20) — so it
|
|
577
|
+
# names the exception TYPE and chains the original rather than quoting it.
|
|
578
|
+
f"{surface} cannot attach {CONTRACT_ATTRIBUTE} to a {type_identity(fn)} "
|
|
579
|
+
f"(the write raised {type(exc).__name__}; the original is chained); "
|
|
580
|
+
"for a target that cannot carry attributes — a slotted or frozen object, a bound "
|
|
581
|
+
"method of one, a remote tool — the gebra.toml sidecar is the designated fallback "
|
|
582
|
+
"(ANNOTATION-API-SPEC §6)",
|
|
583
|
+
reason=ContractErrorReason.ATTACHMENT_IMPOSSIBLE,
|
|
584
|
+
) from exc
|
|
585
|
+
return fn
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _refuse_duplicate_slots(
|
|
589
|
+
existing: NodeContract | None, declared: Mapping[str, object], *, surface: str
|
|
590
|
+
) -> None:
|
|
591
|
+
"""§1's at-most-once rule: a duplicate is an error, identical values included.
|
|
592
|
+
|
|
593
|
+
Both values are safe to render: each has already been through this module's
|
|
594
|
+
normalization, so neither is a raw decorator argument.
|
|
595
|
+
"""
|
|
596
|
+
if existing is None:
|
|
597
|
+
return
|
|
598
|
+
for slot in ANNOTATION_SLOTS:
|
|
599
|
+
if slot not in declared:
|
|
600
|
+
continue
|
|
601
|
+
held = existing.slot_value(slot)
|
|
602
|
+
if held is None:
|
|
603
|
+
continue
|
|
604
|
+
raise GebraContractError(
|
|
605
|
+
f"{surface} sets {slot!r} to {declared[slot]!r}, but a decorator below it in this "
|
|
606
|
+
f"stack already set it to {held!r}. A slot is settable at most once across a "
|
|
607
|
+
"decorator stack, and a duplicate is an error rather than a merge — identical "
|
|
608
|
+
"values included, because one author's stack has no drift to excuse "
|
|
609
|
+
"(ANNOTATION-API-SPEC §1). Declare the slot once.",
|
|
610
|
+
reason=ContractErrorReason.DUPLICATE_SLOT,
|
|
611
|
+
slot=slot,
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _refuse_pure_with_effects(declaration: NodeContract, *, surface: str) -> None:
|
|
616
|
+
"""Decision D-011 exclusivity, over the whole stack rather than one decorator call."""
|
|
617
|
+
if declaration.pure is True and declaration.effect:
|
|
618
|
+
raise GebraContractError(
|
|
619
|
+
f"this stack declares pure=True together with the effects "
|
|
620
|
+
f"{list(declaration.effect)!r}; the two are mutually exclusive (decision D-011, "
|
|
621
|
+
"ANNOTATION-API-SPEC §1). A node that touches the world is not pure — drop "
|
|
622
|
+
f"whichever of the two is not true of it (reached at {surface})",
|
|
623
|
+
reason=ContractErrorReason.PURE_EFFECT_EXCLUSIVE,
|
|
624
|
+
slot="pure",
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
# ── Value normalization ──────────────────────────────────────────────────────────────────
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _refuse_unknown_keywords(unknown: Mapping[str, object]) -> None:
|
|
632
|
+
"""Refuse everything outside the nine annotatable slots, saying which kind of outside.
|
|
633
|
+
|
|
634
|
+
The keyword is copied into a plain ``str`` before anything else touches it. CPython
|
|
635
|
+
admits a ``str`` *subclass* as a ``**kwargs`` key, and every operation below would
|
|
636
|
+
otherwise resolve through that subclass's own hooks — ``__eq__`` and ``__hash__`` on the
|
|
637
|
+
membership tests, ``__iter__`` on the close-match search, ``__str__`` and ``__repr__`` on
|
|
638
|
+
the message — which is the module's own no-rendering-before-checking rule broken on the
|
|
639
|
+
one value that never goes through slot normalization (WA-07). The copy also keeps
|
|
640
|
+
:attr:`GebraContractError.slot` a plain string, as its type says.
|
|
641
|
+
"""
|
|
642
|
+
name = str.__str__(next(iter(unknown)))
|
|
643
|
+
suggestion = ""
|
|
644
|
+
if name in ("variant", "compensation"):
|
|
645
|
+
arguments = "key=..., measure=..." if name == "variant" else "hook=..."
|
|
646
|
+
detail = "an annotatable slot, but one with its own decorator"
|
|
647
|
+
suggestion = f" Write @gebra.{name}({arguments})."
|
|
648
|
+
elif name in _OUT_OF_REACH:
|
|
649
|
+
detail = _OUT_OF_REACH[name]
|
|
650
|
+
elif name in _IR_SPELLINGS:
|
|
651
|
+
detail = "an annotatable slot under its IR name rather than its keyword"
|
|
652
|
+
suggestion = f" Write {_IR_SPELLINGS[name]}=."
|
|
653
|
+
else:
|
|
654
|
+
detail = "not one of the nine annotatable slots"
|
|
655
|
+
close = difflib.get_close_matches(name, _CONTRACT_KEYWORDS, n=1, cutoff=0.6)
|
|
656
|
+
if close:
|
|
657
|
+
suggestion = f" Did you mean {close[0]!r}?"
|
|
658
|
+
raise GebraContractError(
|
|
659
|
+
f"@gebra.contract() got {name!r}, which is {detail}. It accepts "
|
|
660
|
+
f"{', '.join(_CONTRACT_KEYWORDS)}; the annotatable-slot set is closed at nine "
|
|
661
|
+
f"(ANNOTATION-API-SPEC §1).{suggestion}",
|
|
662
|
+
reason=ContractErrorReason.UNKNOWN_SLOT,
|
|
663
|
+
slot=name,
|
|
664
|
+
)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _sequence(value: object, *, slot: str, argument: str, unit: str) -> tuple[Any, ...]:
|
|
668
|
+
"""A declared repeated slot as a tuple, refusing the bare-string reading of it.
|
|
669
|
+
|
|
670
|
+
A bare ``str``/``bytes`` is refused rather than iterated, and nothing else would catch
|
|
671
|
+
it: ``str`` satisfies ``Iterable[str]``, so a type checker passes ``reads="budget"``, and
|
|
672
|
+
reading it as six one-character state keys would reach canonical bytes and the digest.
|
|
673
|
+
"""
|
|
674
|
+
if isinstance(value, (str, bytes)):
|
|
675
|
+
raise GebraContractError(
|
|
676
|
+
f"{argument}= is a single {type_identity(value)}, which would be read as one "
|
|
677
|
+
f"{unit} per character; pass a sequence instead, e.g. {argument}=[...]",
|
|
678
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
679
|
+
slot=slot,
|
|
680
|
+
)
|
|
681
|
+
if not isinstance(value, Iterable):
|
|
682
|
+
raise GebraContractError(
|
|
683
|
+
f"{argument}= is a {type_identity(value)}, which is not iterable; it declares "
|
|
684
|
+
f"{unit}s, so it is a sequence of strings",
|
|
685
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
686
|
+
slot=slot,
|
|
687
|
+
)
|
|
688
|
+
# The two shapes an author actually writes are read through unbound built-in accessors,
|
|
689
|
+
# so a `list`/`tuple` subclass cannot interpose its own `__iter__` (WA-07). Anything else
|
|
690
|
+
# is iterated normally: §1 types the argument `Iterable[str]`, and materializing an
|
|
691
|
+
# arbitrary iterable is the one thing this surface cannot do without touching it.
|
|
692
|
+
if isinstance(value, list):
|
|
693
|
+
return tuple(list.__iter__(value))
|
|
694
|
+
if isinstance(value, tuple):
|
|
695
|
+
return tuple(tuple.__iter__(value))
|
|
696
|
+
return tuple(value)
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _strings(members: tuple[Any, ...], *, slot: str, argument: str, unit: str) -> tuple[str, ...]:
|
|
700
|
+
"""Every member as a plain ``str``; a non-string member is refused, never coerced."""
|
|
701
|
+
checked: list[str] = []
|
|
702
|
+
for index, member in enumerate(members):
|
|
703
|
+
if not isinstance(member, str):
|
|
704
|
+
raise GebraContractError(
|
|
705
|
+
f"{argument}=[{index}] is a {type_identity(member)}; each {unit} is a string",
|
|
706
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
707
|
+
slot=slot,
|
|
708
|
+
)
|
|
709
|
+
checked.append(str.__str__(member))
|
|
710
|
+
return tuple(checked)
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def _state_keys(value: object, *, slot: str, argument: str) -> tuple[str, ...]:
|
|
714
|
+
"""A declared state-key set as a tuple of plain strings, in the order authored."""
|
|
715
|
+
members = _sequence(value, slot=slot, argument=argument, unit="state key")
|
|
716
|
+
return _strings(members, slot=slot, argument=argument, unit="state key")
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def _effect_tags(tags: object) -> tuple[str, ...]:
|
|
720
|
+
"""The declared effect tags, each checked against the closed D-011 vocabulary.
|
|
721
|
+
|
|
722
|
+
Order and multiplicity are kept as authored: §1 closes the *vocabulary* and says nothing
|
|
723
|
+
about either, and canonical serialization is where the IR's own ordering rules apply.
|
|
724
|
+
"""
|
|
725
|
+
checked = normalize_effect_members(tags)
|
|
726
|
+
for tag in checked:
|
|
727
|
+
if tag not in EFFECT_TAGS:
|
|
728
|
+
raise GebraContractError(
|
|
729
|
+
f"{tag!r} is not an effect tag. The decision D-011 vocabulary is closed: "
|
|
730
|
+
f"{', '.join(sorted(EFFECT_TAGS))} (ANNOTATION-API-SPEC §1)",
|
|
731
|
+
reason=ContractErrorReason.UNKNOWN_EFFECT_TAG,
|
|
732
|
+
slot="effect",
|
|
733
|
+
)
|
|
734
|
+
return checked
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _flag(value: object, *, slot: str, argument: str) -> bool:
|
|
738
|
+
"""A boolean slot. ``1``/``0`` are refused rather than read as ``True``/``False``."""
|
|
739
|
+
if not isinstance(value, bool):
|
|
740
|
+
raise GebraContractError(
|
|
741
|
+
f"{argument}= is a {type_identity(value)}; it is a boolean declaration",
|
|
742
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
743
|
+
slot=slot,
|
|
744
|
+
)
|
|
745
|
+
return bool(value)
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _reference(value: object, *, argument: str) -> str:
|
|
749
|
+
"""A declared reference-role string — a state key, a measure name, a node id."""
|
|
750
|
+
if not isinstance(value, str):
|
|
751
|
+
raise GebraContractError(
|
|
752
|
+
f"{argument}= is a {type_identity(value)}; it is a string",
|
|
753
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
754
|
+
)
|
|
755
|
+
return str.__str__(value)
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def _idempotent_value(value: object) -> bool | IdempotentKey:
|
|
759
|
+
"""``idempotent=`` as ``True``/``False`` or the ledger §3 ``{key: string}`` object."""
|
|
760
|
+
if isinstance(value, bool):
|
|
761
|
+
return bool(value)
|
|
762
|
+
if not isinstance(value, dict):
|
|
763
|
+
raise GebraContractError(
|
|
764
|
+
f"idempotent= is a {type_identity(value)}; it is True, False, or "
|
|
765
|
+
'{"key": "<state key>"} (ir-field-ledger §3)',
|
|
766
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
767
|
+
slot="idempotent",
|
|
768
|
+
)
|
|
769
|
+
members = _object_members(value, slot="idempotent", known=("key",))
|
|
770
|
+
if "key" not in members:
|
|
771
|
+
raise GebraContractError(
|
|
772
|
+
'idempotent= is an object without "key"; the ledger §3 shape is {"key": "<state key>"}',
|
|
773
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
774
|
+
slot="idempotent",
|
|
775
|
+
)
|
|
776
|
+
return IdempotentKey(key=_reference(members["key"], argument="idempotent key"))
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def _deterministic_value(value: object) -> bool | DeterministicSpec:
|
|
780
|
+
"""``deterministic=`` as ``True``/``False`` or the ledger §3 ``{seed, temperature?}``."""
|
|
781
|
+
if isinstance(value, bool):
|
|
782
|
+
return bool(value)
|
|
783
|
+
if not isinstance(value, dict):
|
|
784
|
+
raise GebraContractError(
|
|
785
|
+
f"deterministic= is a {type_identity(value)}; it is True, False, or "
|
|
786
|
+
'{"seed": <int>, "temperature"?: <number>} (ir-field-ledger §3)',
|
|
787
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
788
|
+
slot="deterministic",
|
|
789
|
+
)
|
|
790
|
+
members = _object_members(value, slot="deterministic", known=("seed", "temperature"))
|
|
791
|
+
if "seed" not in members:
|
|
792
|
+
raise GebraContractError(
|
|
793
|
+
'deterministic= is an object without "seed". The object form requires it: the '
|
|
794
|
+
'frozen ledger §3 shape is {"seed": <int>, "temperature"?: <number>} '
|
|
795
|
+
"(ANNOTATION-API-SPEC §1, DEC-09)",
|
|
796
|
+
reason=ContractErrorReason.DETERMINISTIC_SEED_REQUIRED,
|
|
797
|
+
slot="deterministic",
|
|
798
|
+
)
|
|
799
|
+
return _deterministic_spec(members["seed"], members.get("temperature"))
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _deterministic_form(seed: object, temperature: object) -> bool | DeterministicSpec:
|
|
803
|
+
"""The ``@gebra.deterministic`` shorthand's forms, and the one §1 names as an error."""
|
|
804
|
+
if seed is None:
|
|
805
|
+
if temperature is None:
|
|
806
|
+
return True
|
|
807
|
+
raise GebraContractError(
|
|
808
|
+
"@gebra.deterministic(temperature=...) without seed= declares nothing replayable: "
|
|
809
|
+
"the object form requires seed (ANNOTATION-API-SPEC §1; the frozen ledger §3 shape "
|
|
810
|
+
'is {"seed": <int>, "temperature"?: <number>})',
|
|
811
|
+
reason=ContractErrorReason.DETERMINISTIC_SEED_REQUIRED,
|
|
812
|
+
slot="deterministic",
|
|
813
|
+
)
|
|
814
|
+
return _deterministic_spec(seed, temperature)
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def _deterministic_spec(seed: object, temperature: object) -> DeterministicSpec:
|
|
818
|
+
"""The ledger §3 object, from a checked seed and an optional checked temperature."""
|
|
819
|
+
if isinstance(seed, bool) or not isinstance(seed, int):
|
|
820
|
+
raise GebraContractError(
|
|
821
|
+
f"seed is a {type_identity(seed)}; the ledger §3 shape types it as an integer",
|
|
822
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
823
|
+
slot="deterministic",
|
|
824
|
+
)
|
|
825
|
+
if temperature is None:
|
|
826
|
+
return DeterministicSpec(seed=_exact_integer(seed, path="seed"))
|
|
827
|
+
if isinstance(temperature, bool) or not isinstance(temperature, (int, float)):
|
|
828
|
+
raise GebraContractError(
|
|
829
|
+
f"temperature is a {type_identity(temperature)}; the ledger §3 shape types it as a "
|
|
830
|
+
"number",
|
|
831
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
832
|
+
slot="deterministic",
|
|
833
|
+
)
|
|
834
|
+
# An integer *is* a JSON number and the ledger shape reads `temperature?: number`, while
|
|
835
|
+
# the model types it `float`; widening here is what keeps `temperature=0` from being a
|
|
836
|
+
# strict-mode error at the one place a reader would not expect one.
|
|
837
|
+
number = float(temperature)
|
|
838
|
+
if not math.isfinite(number):
|
|
839
|
+
# Refused where it is written, for the reason `args_schema` is: the slot is
|
|
840
|
+
# serialized into the IR and digested, and JSON has no form for an infinity or a NaN.
|
|
841
|
+
# Left to canonicalization it would surface as a `CanonicalizationError` at
|
|
842
|
+
# `graph_version()` time, with nothing pointing back at the declaration that
|
|
843
|
+
# introduced it — extraction total in name only. (TOML has a literal `nan`, so the
|
|
844
|
+
# §2 sidecar surface can reach this too, where it degrades to a warning instead.)
|
|
845
|
+
raise GebraContractError(
|
|
846
|
+
f"temperature is {number!r}; JSON has no form for it, so it could not be "
|
|
847
|
+
"serialized into the IR or digested",
|
|
848
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
849
|
+
slot="deterministic",
|
|
850
|
+
)
|
|
851
|
+
return DeterministicSpec(seed=_exact_integer(seed, path="seed"), temperature=number)
|
|
852
|
+
|
|
853
|
+
|
|
854
|
+
def _variant_value(value: object) -> Variant:
|
|
855
|
+
"""``variant`` in its object form — ``{key, measure}``, both required (§1, §2).
|
|
856
|
+
|
|
857
|
+
The decorator spells the slot as two keywords (``@gebra.variant(key=…, measure=…)``) and
|
|
858
|
+
the sidecar as one inline table (``variant = { key = "...", measure = "..." }``, §2). Both
|
|
859
|
+
build the same :class:`~gebra.ir.models.Variant` out of :func:`_reference`, so neither
|
|
860
|
+
surface can drift into accepting a value the other refuses.
|
|
861
|
+
"""
|
|
862
|
+
if not isinstance(value, dict):
|
|
863
|
+
raise GebraContractError(
|
|
864
|
+
f"variant is a {type_identity(value)}; it is an object with a state key and a "
|
|
865
|
+
'measure — { key = "...", measure = "..." } (ANNOTATION-API-SPEC §1/§2)',
|
|
866
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
867
|
+
slot="variant",
|
|
868
|
+
)
|
|
869
|
+
members = _object_members(value, slot="variant", known=("key", "measure"))
|
|
870
|
+
missing = tuple(name for name in ("key", "measure") if name not in members)
|
|
871
|
+
if missing:
|
|
872
|
+
raise GebraContractError(
|
|
873
|
+
f"variant is an object without {', '.join(repr(name) for name in missing)}; the "
|
|
874
|
+
"P-02 witness form (c) carries both a key and a measure",
|
|
875
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
876
|
+
slot="variant",
|
|
877
|
+
)
|
|
878
|
+
return Variant(
|
|
879
|
+
key=_reference(members["key"], argument="variant key"),
|
|
880
|
+
measure=_reference(members["measure"], argument="variant measure"),
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def _compensation_value(value: object) -> Compensation:
|
|
885
|
+
"""``compensation`` in its object form — ``{hook}``, a node id (§1, §2)."""
|
|
886
|
+
if not isinstance(value, dict):
|
|
887
|
+
raise GebraContractError(
|
|
888
|
+
f"compensation is a {type_identity(value)}; it is an object naming the hook — "
|
|
889
|
+
'{ hook = "<node id>" } (ANNOTATION-API-SPEC §1/§2)',
|
|
890
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
891
|
+
slot="compensation",
|
|
892
|
+
)
|
|
893
|
+
members = _object_members(value, slot="compensation", known=("hook",))
|
|
894
|
+
if "hook" not in members:
|
|
895
|
+
raise GebraContractError(
|
|
896
|
+
'compensation is an object without "hook"; the slot carries the compensating '
|
|
897
|
+
"node's id (ir-field-ledger §3/§5)",
|
|
898
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
899
|
+
slot="compensation",
|
|
900
|
+
)
|
|
901
|
+
return Compensation(hook=_reference(members["hook"], argument="compensation hook"))
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def _exact_integer(value: int, *, path: str) -> int:
|
|
905
|
+
"""An integer the canonical form can carry — the I-JSON exact range (IR-SPEC §6.3).
|
|
906
|
+
|
|
907
|
+
The twin of the non-finite ``temperature`` refusal, and refused for the same reason at the
|
|
908
|
+
same place: §6.3 fixes both scalar constraints *before* the hash, so a value outside them
|
|
909
|
+
can never be valid IR. Left through, it would reach the §3 resolution, land in a slot, and
|
|
910
|
+
surface as a :class:`~gebra.ir.canonical.CanonicalizationError` the moment anyone asked for
|
|
911
|
+
a ``graph_version`` — with nothing pointing back at the declaration that introduced it.
|
|
912
|
+
Checked where it is written, so the message names the slot instead.
|
|
913
|
+
|
|
914
|
+
The bound is imported from the canonicalizer rather than restated: two copies of ±(2**53−1)
|
|
915
|
+
is one copy too many, and this check exists precisely to agree with that one.
|
|
916
|
+
"""
|
|
917
|
+
number = int.__index__(value)
|
|
918
|
+
if not I_JSON_MIN_INT <= number <= I_JSON_MAX_INT:
|
|
919
|
+
raise GebraContractError(
|
|
920
|
+
f"{path} is {number}, outside the I-JSON exact integer range ±(2**53−1) "
|
|
921
|
+
"(IR-SPEC §6.3; PD-004). The value is serialized into the IR and digested, so a "
|
|
922
|
+
"number JSON cannot round-trip exactly could not be carried",
|
|
923
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
924
|
+
slot="deterministic" if path == "seed" else "args_schema",
|
|
925
|
+
)
|
|
926
|
+
return number
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def _object_members(value: dict[Any, Any], *, slot: str, known: tuple[str, ...]) -> dict[str, Any]:
|
|
930
|
+
"""A declared object's members, with its keys checked against the slot's closed shape.
|
|
931
|
+
|
|
932
|
+
Read through ``dict.items`` rather than ``value.items()`` so a ``dict`` subclass cannot
|
|
933
|
+
interpose its own accessor — the pattern :mod:`gebra.ir.canonical` uses on foreign
|
|
934
|
+
content, for the same WA-07 reason.
|
|
935
|
+
"""
|
|
936
|
+
members: dict[str, Any] = {}
|
|
937
|
+
for key, member in dict.items(value):
|
|
938
|
+
name = _json_key(key, path=f"{slot}=", slot=slot)
|
|
939
|
+
if name not in known:
|
|
940
|
+
raise GebraContractError(
|
|
941
|
+
f"{slot}= has the member {name!r}, which its shape does not carry; the ledger "
|
|
942
|
+
f"§3 shape has {', '.join(known)}",
|
|
943
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
944
|
+
slot=slot,
|
|
945
|
+
)
|
|
946
|
+
members[name] = member
|
|
947
|
+
return members
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def _args_schema_value(value: object) -> dict[str, Any]:
|
|
951
|
+
"""``args_schema=`` as JSON data, checked where it was written.
|
|
952
|
+
|
|
953
|
+
Checked here rather than left to canonicalization because the value is serialized into
|
|
954
|
+
the IR and digested: something JSON cannot carry would otherwise surface as a
|
|
955
|
+
``CanonicalizationError`` at ``graph_version()`` time, with nothing pointing back at the
|
|
956
|
+
decorator that introduced it. §1 is silent on the interior — "a JSON Schema object" — so
|
|
957
|
+
nothing here reads the schema's *meaning*; only that it is data.
|
|
958
|
+
"""
|
|
959
|
+
if not isinstance(value, dict):
|
|
960
|
+
raise GebraContractError(
|
|
961
|
+
f"args_schema= is a {type_identity(value)}; it is a JSON Schema object "
|
|
962
|
+
"(ir-field-ledger §3)",
|
|
963
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
964
|
+
slot="args_schema",
|
|
965
|
+
)
|
|
966
|
+
members: dict[str, Any] = {}
|
|
967
|
+
for key, member in dict.items(value):
|
|
968
|
+
name = _json_key(key, path="args_schema", slot="args_schema")
|
|
969
|
+
members[name] = _json_data(member, path=f"args_schema.{name}", depth=1)
|
|
970
|
+
return members
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def _json_key(key: object, *, path: str, slot: str) -> str:
|
|
974
|
+
"""A JSON object member name — a string, read without running a subclass's accessor."""
|
|
975
|
+
if not isinstance(key, str):
|
|
976
|
+
raise GebraContractError(
|
|
977
|
+
f"{path} has a {type_identity(key)} key; a JSON object member name is a string",
|
|
978
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
979
|
+
slot=slot,
|
|
980
|
+
)
|
|
981
|
+
return str.__str__(key)
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
def _json_data(value: object, *, path: str, depth: int) -> Any:
|
|
985
|
+
"""``value`` as JSON data, with sequences as tuples; raise if it is not.
|
|
986
|
+
|
|
987
|
+
Containers and scalars are read through unbound built-in accessors so no subclass hook
|
|
988
|
+
runs on a value this module was handed (WA-07). Sequences become tuples for two reasons:
|
|
989
|
+
the authored container is not aliased into the carrier, so editing it afterwards does not
|
|
990
|
+
reach the declared contract; and a list and a tuple of the same items compare equal, which
|
|
991
|
+
keeps two spellings of one schema from reading as two contracts. It is digest-neutral —
|
|
992
|
+
:func:`gebra.ir.canonical.graph_version` emits both as JSON arrays, in the order given.
|
|
993
|
+
Object members are *not* frozen; see :class:`NodeContract` for why and what that leaves
|
|
994
|
+
open.
|
|
995
|
+
"""
|
|
996
|
+
if depth > _MAX_SCHEMA_DEPTH:
|
|
997
|
+
raise GebraContractError(
|
|
998
|
+
f"{path} nests deeper than {_MAX_SCHEMA_DEPTH} levels; a JSON Schema that deep is "
|
|
999
|
+
"more likely to be a cycle than a shape",
|
|
1000
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
1001
|
+
slot="args_schema",
|
|
1002
|
+
)
|
|
1003
|
+
if value is None or isinstance(value, bool):
|
|
1004
|
+
return value
|
|
1005
|
+
if isinstance(value, int):
|
|
1006
|
+
return _exact_integer(value, path=path)
|
|
1007
|
+
if isinstance(value, float):
|
|
1008
|
+
number = float.__float__(value)
|
|
1009
|
+
if not math.isfinite(number):
|
|
1010
|
+
raise GebraContractError(
|
|
1011
|
+
f"{path} is {number!r}; JSON has no form for it, so it could not be serialized "
|
|
1012
|
+
"into the IR",
|
|
1013
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
1014
|
+
slot="args_schema",
|
|
1015
|
+
)
|
|
1016
|
+
return number
|
|
1017
|
+
if isinstance(value, str):
|
|
1018
|
+
return str.__str__(value)
|
|
1019
|
+
if isinstance(value, dict):
|
|
1020
|
+
members: dict[str, Any] = {}
|
|
1021
|
+
for key, member in dict.items(value):
|
|
1022
|
+
name = _json_key(key, path=path, slot="args_schema")
|
|
1023
|
+
members[name] = _json_data(member, path=f"{path}.{name}", depth=depth + 1)
|
|
1024
|
+
return members
|
|
1025
|
+
if isinstance(value, (list, tuple)):
|
|
1026
|
+
items = list.__iter__(value) if isinstance(value, list) else tuple.__iter__(value)
|
|
1027
|
+
return tuple(
|
|
1028
|
+
_json_data(item, path=f"{path}[{index}]", depth=depth + 1)
|
|
1029
|
+
for index, item in enumerate(items)
|
|
1030
|
+
)
|
|
1031
|
+
raise GebraContractError(
|
|
1032
|
+
f"{path} holds a {type_identity(value)}, which JSON cannot carry; args_schema is "
|
|
1033
|
+
"serialized into the IR and digested, so every value in it has to be data",
|
|
1034
|
+
reason=ContractErrorReason.SLOT_VALUE_INVALID,
|
|
1035
|
+
slot="args_schema",
|
|
1036
|
+
)
|