Skip to content

Identity

identity

Versioned structural content identity for compiler artifacts.

Downstream forward and artifact provenance consume this manifest. It records compiler structure, not fitted values, solver settings, runtime versions or proof of numerical equivalence. It never changes Python object equality or hashing.

StructuralModelIdentity(schema_version, digest) dataclass

Validate a portable reference to a structural manifest.

Attributes:

Name Type Description
schema_version int

Canonical manifest and reference format, currently 1.

digest str

SHA-256 of the exact canonical manifest's UTF-8 bytes.

Examples:

>>> from op_system import compile_spec
>>> model = compile_spec({
...     "kind": "expr",
...     "state": ["x"],
...     "equations": {"x": "-k*x"},
... })
>>> identity = StructuralModelIdentity.from_compiled(model)
>>> StructuralModelIdentity.from_json(identity.to_json()) == identity
True
>>> identity.digest.startswith("sha256:")
True

__post_init__()

Refuse unknown formats and malformed content references.

Raises:

Type Description
ValueError

Version or digest is missing, malformed or unsupported.

Source code in src/op_system/identity.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __post_init__(self) -> None:
    """Refuse unknown formats and malformed content references.

    Raises:
        ValueError: Version or digest is missing, malformed or unsupported.
    """
    if type(self.schema_version) is not int or self.schema_version != 1:
        msg = "Unsupported structural model identity schema version (expected 1)"
        raise ValueError(msg)
    if (
        not isinstance(self.digest, str)
        or re.fullmatch(r"sha256:[0-9a-f]{64}", self.digest) is None
    ):
        msg = "Structural model identity requires a lowercase SHA-256 digest"
        raise ValueError(msg)

from_compiled(compiled) classmethod

Identify compiler structure without binding runtime parameters.

Parameters:

Name Type Description Default
compiled CompiledRhs

An unmodified artifact produced by the compiler.

required

Returns:

Type Description
StructuralModelIdentity

Reference to :func:structural_model_json's canonical bytes.

Source code in src/op_system/identity.py
75
76
77
78
79
80
81
82
83
84
85
86
@classmethod
def from_compiled(cls, compiled: CompiledRhs) -> StructuralModelIdentity:
    """Identify compiler structure without binding runtime parameters.

    Args:
        compiled: An unmodified artifact produced by the compiler.

    Returns:
        Reference to :func:`structural_model_json`'s canonical bytes.
    """
    payload = structural_model_json(compiled).encode("utf-8")
    return cls(1, f"sha256:{hashlib.sha256(payload).hexdigest()}")

from_json(payload) classmethod

Read a reference without treating it as an independently expected identity.

Parameters:

Name Type Description Default
payload str

Exact two-field reference JSON.

required

Returns:

Type Description
StructuralModelIdentity

Validated reference. Downstream guarded loaders must additionally

StructuralModelIdentity

compare an independently supplied expected identity.

Raises:

Type Description
ValueError

The reference is malformed or uses an unknown schema.

Source code in src/op_system/identity.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@classmethod
def from_json(cls, payload: str) -> StructuralModelIdentity:
    """Read a reference without treating it as an independently expected identity.

    Args:
        payload: Exact two-field reference JSON.

    Returns:
        Validated reference. Downstream guarded loaders must additionally
        compare an independently supplied expected identity.

    Raises:
        ValueError: The reference is malformed or uses an unknown schema.
    """
    value = json.loads(payload)
    if not isinstance(value, dict) or set(value) != {"schema_version", "digest"}:
        msg = "Structural model identity requires schema_version and digest only"
        raise ValueError(msg)
    return cls(value["schema_version"], value["digest"])

to_json()

Serialize the small reference, excluding the model manifest.

Returns:

Type Description
str

Versioned reference JSON; this does not serialize a runnable model.

Source code in src/op_system/identity.py
88
89
90
91
92
93
94
def to_json(self) -> str:
    """Serialize the small reference, excluding the model manifest.

    Returns:
        Versioned reference JSON; this does not serialize a runnable model.
    """
    return _json({"schema_version": self.schema_version, "digest": self.digest})

structural_model_json(compiled)

Serialize typed normalized IR and ordered compiler layouts as a canonical DAG.

Parameters:

Name Type Description Default
compiled CompiledRhs

An unmodified compiler-produced artifact with retained source IR.

required

Returns:

Type Description
str

Canonical schema-1 UTF-8/ASCII JSON text. Mapping keys are sorted;

str

state, parameter, axis, coordinate, operation and observable sequences

str

retain their semantic order. Scalars have explicit type tags and floats

str

use exact hexadecimal strings. Shared typed trees are content-interned.

str

The manifest includes normalized declarations/constants/operators and

str

gauge/coordinate options, but never bound runtime values or closures.

str

This is an identity manifest, not the external executable IR export.

Raises:

Type Description
ValueError

The artifact has no typed normalized source.

Source code in src/op_system/identity.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def structural_model_json(compiled: CompiledRhs) -> str:
    """Serialize typed normalized IR and ordered compiler layouts as a canonical DAG.

    Args:
        compiled: An unmodified compiler-produced artifact with retained source IR.

    Returns:
        Canonical schema-1 UTF-8/ASCII JSON text. Mapping keys are sorted;
        state, parameter, axis, coordinate, operation and observable sequences
        retain their semantic order. Scalars have explicit type tags and floats
        use exact hexadecimal strings. Shared typed trees are content-interned.
        The manifest includes normalized declarations/constants/operators and
        gauge/coordinate options, but never bound runtime values or closures.
        This is an identity manifest, not the external executable IR export.

    Raises:
        ValueError: The artifact has no typed normalized source.
    """
    rhs = compiled._rhs  # ruff: ignore[private-member-access]
    if (
        rhs is None
        or not rhs.equations_ir_reduce
        or any(expr is None for expr in rhs.equations_ir_reduce)
    ):
        msg = "Structural identity requires compiler-produced typed normalized IR"
        raise ValueError(msg)
    source = {
        "kind": type(rhs).__name__,
        "state_names": compiled.state_names,
        "param_names": compiled.param_names,
        "state_templates": rhs.state_templates,
        "shaped_params": rhs.shaped_params,
        "time_varying_params": rhs.time_varying_params,
        "alias_templates": rhs.alias_templates,
        "aliases_ir": rhs.aliases_ir_reduce,
        "equations_ir": rhs.equations_ir_reduce,
        "metadata": rhs.meta,
        "reactions_ir": getattr(rhs, "reactions_ir", ()),
        "reaction_gaps": getattr(rhs, "reaction_gaps_ir", ()),
        "observables": tuple(compiled.observables),
        "template_shapes": compiled.template_shapes,
        "block_template_shapes": compiled.block_template_shapes,
    }
    encoder = _ManifestEncoder()
    root = encoder.encode(source)
    return _json({
        "format": "op-system-structural-model",
        "schema_version": 1,
        "nodes": encoder.nodes,
        "root": root,
    })