> ## Documentation Index
> Fetch the complete documentation index at: https://b01t.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Serialization: Save and Load Exact Programs

> Reference for b01t's exact program serialization: convert ExactProgram to JSON or dict and restore it with full structural validation on load.

b01t provides four functions for serializing and deserializing `ExactProgram` values. The format is `exact-oracle-v1` — a JSON schema that captures the full program structure including certification level, register layout, and every op. On deserialization, b01t re-validates the structural invariants, so a corrupted or tampered file is rejected rather than silently accepted.

```python theme={null}
from b01t import (
    exact_program_to_json,
    exact_program_from_json,
    exact_program_to_dict,
    exact_program_from_dict,
)
```

***

## exact\_program\_to\_json

```python theme={null}
exact_program_to_json(prog: ExactProgram) -> str
```

Serializes an `ExactProgram` to a deterministic JSON string. Keys are sorted alphabetically and the output is indented with two spaces, making the format suitable for version control.

<ParamField path="prog" type="ExactProgram" required>
  The exact program to serialize. Obtain one from `.build_exact()` on a `@coherent` or `@primitive` function.
</ParamField>

**Returns:** a UTF-8 JSON string in `exact-oracle-v1` format.

```python theme={null}
from b01t import coherent, QReg, h, cx, exact_program_to_json

@coherent
def bell(a: QReg, b: QReg) -> None:
    h(a[0])
    cx(a[0], b[0])

prog = bell.build_exact(("a", 1), ("b", 1))
json_str = exact_program_to_json(prog)
print(json_str)
```

***

## exact\_program\_from\_json

```python theme={null}
exact_program_from_json(s: str) -> ExactProgram
```

Deserializes an `ExactProgram` from a JSON string. Validates the format version, then re-checks all structural invariants before returning.

<ParamField path="s" type="str" required>
  A JSON string previously produced by `exact_program_to_json`.
</ParamField>

**Returns:** a fully validated `ExactProgram`.

**Raises:** `DSLValidationError` if the format version is not `exact-oracle-v1`, or if any structural invariant is violated.

```python theme={null}
from b01t import exact_program_from_json

restored = exact_program_from_json(json_str)
print(restored.name)           # "bell"
print(restored.certification)  # Certification.SAFE
```

***

## exact\_program\_to\_dict

```python theme={null}
exact_program_to_dict(prog: ExactProgram) -> dict
```

Serializes an `ExactProgram` to a plain Python dict. Use this when you want to embed the program in a larger data structure (such as a registry entry) without converting to a string first.

<ParamField path="prog" type="ExactProgram" required>
  The exact program to serialize.
</ParamField>

**Returns:** a `dict` with the same structure as the JSON schema below.

```python theme={null}
from b01t import exact_program_to_dict

d = exact_program_to_dict(prog)
print(d["format"])        # "exact-oracle-v1"
print(d["certification"]) # "safe"
```

***

## exact\_program\_from\_dict

```python theme={null}
exact_program_from_dict(d: dict) -> ExactProgram
```

Deserializes an `ExactProgram` from a plain Python dict. Validates the format version and structural invariants.

<ParamField path="d" type="dict" required>
  A dict previously produced by `exact_program_to_dict`, or parsed from a JSON file in `exact-oracle-v1` format.
</ParamField>

**Returns:** a fully validated `ExactProgram`.

**Raises:** `DSLValidationError` if the format version is wrong or any invariant is violated.

```python theme={null}
from b01t import exact_program_from_dict

restored = exact_program_from_dict(d)
```

***

## JSON schema

The `exact-oracle-v1` format has the following top-level structure:

```json theme={null}
{
  "format": "exact-oracle-v1",
  "name": "bell",
  "certification": "safe",
  "regs": [
    { "name": "a", "size": 1, "kind": "sys" },
    { "name": "b", "size": 1, "kind": "sys" }
  ],
  "ops": [
    {
      "op": "gate",
      "gate": "H",
      "wires": [{ "reg": "a", "index": 0, "kind": "sys" }]
    },
    {
      "op": "gate",
      "gate": "CX",
      "wires": [
        { "reg": "a", "index": 0, "kind": "sys" },
        { "reg": "b", "index": 0, "kind": "sys" }
      ]
    }
  ]
}
```

### Op types

Each entry in `"ops"` has an `"op"` field that is one of:

| `"op"` value | Description                                                                                            |
| ------------ | ------------------------------------------------------------------------------------------------------ |
| `"gate"`     | A single gate application. Has `"gate"` (enum value) and `"wires"`.                                    |
| `"ancilla"`  | An ancilla block. Has `"ancilla"` (reg dict), `"compute"`, `"middle"`, `"middle_kind"`, `"uncompute"`. |
| `"par"`      | Parallel composition. Has `"left"` and `"right"` (lists of ops).                                       |

### Certification values

| `"certification"` | Decorator    |
| ----------------- | ------------ |
| `"safe"`          | `@coherent`  |
| `"primitive"`     | `@primitive` |

***

## Round-trip example

```python theme={null}
from b01t import (
    coherent, QReg, h, cx,
    exact_program_to_json,
    exact_program_from_json,
    Certification,
)

@coherent
def bell(a: QReg, b: QReg) -> None:
    h(a[0])
    cx(a[0], b[0])

# Build
original = bell.build_exact(("a", 1), ("b", 1))
assert original.certification == Certification.SAFE

# Serialize
json_str = exact_program_to_json(original)

# Deserialize and verify
restored = exact_program_from_json(json_str)
assert restored.name == original.name
assert restored.certification == original.certification
assert len(restored.regs) == len(original.regs)
assert len(restored.ops) == len(original.ops)
```

***

## Saving to a file

```python theme={null}
import pathlib
from b01t import exact_program_to_json, exact_program_from_json

# Write
pathlib.Path("bell.json").write_text(exact_program_to_json(original))

# Read
text = pathlib.Path("bell.json").read_text()
restored = exact_program_from_json(text)
```
