Skip to content

Portable

portable

Versioned typed IR interchange bound to the compiler's structural identity.

The envelope contains data, never pickled objects or executable source. The canonical typed DAG retains axes, ordered layouts, aliases, observables, constants, known time-varying inputs and declaration metadata without eager cell expansion.

IRRecord(type_name, fields) dataclass

Readonly compiler record as a portable type name and ordered fields.

Decoding does not import or instantiate the named Python class. Consumers explicitly select supported record/operation types before evaluation.

field(name)

Return one declared field.

Returns:

Type Description
object

The readonly decoded field value.

Raises:

Type Description
KeyError

The record has no such field.

Source code in src/op_system/portable.py
39
40
41
42
43
44
45
46
47
48
49
50
51
def field(self, name: str) -> object:
    """Return one declared field.

    Returns:
        The readonly decoded field value.

    Raises:
        KeyError: The record has no such field.
    """
    for key, value in self.fields:
        if key == name:
            return value
    raise KeyError(name)

PortableIR(manifest, identity) dataclass

Immutable canonical IR data with independently checkable source identity.

manifest is the canonical structural DAG. Its hash is the exact existing StructuralModelIdentity, not a hash of fitted values or emitted code. Use :meth:from_json with an independently expected model identity on import. A digest detects changes against that expectation; it is not authentication.

__post_init__()

Validate canonical format, bounds and a non-executable typed DAG.

Raises:

Type Description
ValueError

Format, bounds or identity disagree.

Source code in src/op_system/portable.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __post_init__(self) -> None:
    """Validate canonical format, bounds and a non-executable typed DAG.

    Raises:
        ValueError: Format, bounds or identity disagree.
    """
    if (
        not isinstance(self.manifest, str)
        or len(self.manifest.encode()) > _MAX_PAYLOAD_BYTES
    ):
        msg = "Portable IR manifest must be bounded UTF-8 JSON text"
        raise ValueError(msg)
    source = _load_json(self.manifest)
    canonical = _json(source)
    expected = f"sha256:{hashlib.sha256(canonical.encode()).hexdigest()}"
    if canonical != self.manifest or expected != self.identity.digest:
        msg = "Portable IR canonical bytes differ from structural model identity"
        raise ValueError(msg)
    _decode(source)

decode()

Return fresh readonly data without executing or instantiating records.

Source code in src/op_system/portable.py
87
88
89
def decode(self) -> Mapping[str, object]:
    """Return fresh readonly data without executing or instantiating records."""
    return _decode(_load_json(self.manifest))

from_json(payload, *, expected) classmethod

Read bounded data only when its source matches an independent identity.

Unsupported versions, extra envelope fields and changed IR fail before the consumer gets decoded data. No arbitrary Python/Julia source runs.

Returns:

Type Description
PortableIR

Validated canonical interchange with the expected source identity.

Raises:

Type Description
ValueError

Payload, version or source identity differs.

Source code in src/op_system/portable.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
@classmethod
def from_json(
    cls, payload: str, *, expected: StructuralModelIdentity
) -> PortableIR:
    """Read bounded data only when its source matches an independent identity.

    Unsupported versions, extra envelope fields and changed IR fail before
    the consumer gets decoded data. No arbitrary Python/Julia source runs.

    Returns:
        Validated canonical interchange with the expected source identity.

    Raises:
        ValueError: Payload, version or source identity differs.
    """
    if not isinstance(payload, str) or len(payload.encode()) > _MAX_PAYLOAD_BYTES:
        msg = "Portable IR payload exceeds its UTF-8 byte limit"
        raise ValueError(msg)
    data = _load_json(payload)
    if (
        not isinstance(data, dict)
        or set(data) != {"format", "schema_version", "source", "manifest"}
        or data["format"] != _FORMAT
        or type(data["schema_version"]) is not int
        or data["schema_version"] != 1
    ):
        msg = "Unsupported portable IR envelope/schema"
        raise ValueError(msg)
    source = StructuralModelIdentity.from_json(_json(data["source"]))
    if source != expected:
        msg = "Portable IR source differs from independently expected identity"
        raise ValueError(msg)
    return cls(_json(data["manifest"]), source)

to_json()

Return canonical schema-1 external interchange JSON.

Source code in src/op_system/portable.py
91
92
93
94
95
96
97
98
def to_json(self) -> str:
    """Return canonical schema-1 external interchange JSON."""
    return _json({
        "format": _FORMAT,
        "schema_version": 1,
        "source": _load_json(self.identity.to_json()),
        "manifest": _load_json(self.manifest),
    })

export_ir(compiled)

Export retained compiler IR without materializing lazy scalar equations.

Source metadata and ordering are those of :func:structural_model_json. This interchange does not establish that every external tool can evaluate every IR operation or that different tools use the same rank definition.

Returns:

Type Description
PortableIR

Canonical schema-1 IR data bound to the source model identity.

Source code in src/op_system/portable.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def export_ir(compiled: CompiledRhs) -> PortableIR:
    """Export retained compiler IR without materializing lazy scalar equations.

    Source metadata and ordering are those of :func:`structural_model_json`.
    This interchange does not establish that every external tool can evaluate
    every IR operation or that different tools use the same rank definition.

    Returns:
        Canonical schema-1 IR data bound to the source model identity.
    """
    manifest = structural_model_json(compiled)
    return PortableIR(
        manifest,
        StructuralModelIdentity(
            1, f"sha256:{hashlib.sha256(manifest.encode()).hexdigest()}"
        ),
    )