Preserve structured serialization of routing snapshots

Allow dataclass and JSON conversion to traverse seed and result mappings while keeping the public snapshot mutation methods read-only.
This commit is contained in:
Jan Petykiewicz 2026-11-29 16:37:28 -08:00
commit 725f385ba3
3 changed files with 38 additions and 17 deletions

View file

@ -53,6 +53,8 @@ The fields below appear in constructor order. Use one layout unit for coordinate
Check `is_valid` and keep the effective net and geometry settings with each placement recipe. [Placement workflow](route-a-layout.md#save-a-placement-recipe)
For structured logging, `dataclasses.asdict(run)` preserves the per-net fields. Choose how to encode the Shapely polygons when writing JSON.
## Options and defaults
`RoutingOptions` accepts six option groups. Each group uses the defaults in its table when omitted.

View file

@ -2,34 +2,36 @@
from __future__ import annotations
from collections.abc import Iterator, Mapping
from types import MappingProxyType
from typing import TypeVar
from typing import Never, Self, TYPE_CHECKING, TypeVar
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
_K = TypeVar("_K")
_V = TypeVar("_V")
class _Snapshot(Mapping[_K, _V]):
__slots__ = ("_data",)
class _Snapshot(dict[_K, _V]):
"""A read-only dict that dataclasses.asdict can traverse."""
def __init__(self, source: Mapping[_K, _V]) -> None:
self._data = MappingProxyType(dict(source))
__slots__ = ()
def __getitem__(self, key: _K) -> _V:
return self._data[key]
def __new__(cls, source: Mapping[_K, _V] | Iterable[tuple[_K, _V]]) -> Self:
result = super().__new__(cls)
dict.update(result, source)
return result
def __iter__(self) -> Iterator[_K]:
return iter(self._data)
def __init__(self, _source: Mapping[_K, _V] | Iterable[tuple[_K, _V]]) -> None:
# Populate only at allocation so reinitialization cannot change a snapshot.
pass
def __len__(self) -> int:
return len(self._data)
def _read_only(self, *_args: object, **_kwargs: object) -> Never:
raise TypeError("Snapshot mappings are read-only")
def __repr__(self) -> str:
return repr(self._data.copy())
__setitem__ = __delitem__ = __ior__ = clear = pop = popitem = setdefault = update = _read_only
def __reduce__(self) -> tuple[type[_Snapshot[_K, _V]], tuple[dict[_K, _V]]]:
return type(self), (self._data.copy(),)
return type(self), (dict(self),)
def snapshot(source: Mapping[_K, _V]) -> Mapping[_K, _V]:

View file

@ -1,6 +1,7 @@
import pickle
from copy import deepcopy
from dataclasses import replace
from dataclasses import asdict, replace
from json import dumps, loads
import pytest
from shapely import set_precision, union_all
@ -241,6 +242,8 @@ def test_routing_inputs_and_results_are_detached_snapshots() -> None:
problem.initial_paths["track"] = PathSeed(())
with pytest.raises(TypeError):
del run.results_by_net["track"]
with pytest.raises(TypeError):
run.results_by_net.clear()
assert run.results_by_net["track"].is_valid
@ -258,3 +261,17 @@ def test_read_only_snapshots_survive_python_copy_and_pickle() -> None:
replacement = replace(run, results_by_net=source)
source.clear()
assert replacement.results_by_net == run.results_by_net
def test_asdict_serializes_snapshot_entries_as_structured_data() -> None:
net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0))
seed = PathSeed((StraightSeed(80),))
problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={net.net_id: seed})
run = route(problem, options=_REPLAY)
problem_data = loads(dumps(asdict(problem), default=str))
result_data = loads(dumps(asdict(run), default=str))
assert problem_data["initial_paths"]["track"]["segments"] == [{"length": 80}]
assert result_data["results_by_net"]["track"]["report"]["total_length"] == 80
assert result_data["results_by_net"]["track"]["path"][0]["move_spec"] == {"length": 80}