Skip to main content

Serialization & diffing

A GraphLens round-trips through JSON losslessly, so you can compute a graph once and reuse it everywhere — a CI artifact, an agent's input, a cache, a baseline to diff against.

To and from JSON

# Serialize
text = graph.to_json(indent=2) # str
data = graph.to_dict() # JSON-compatible dict

# Deserialize
from graphlens import GraphLens
graph = GraphLens.from_json(text)
graph = GraphLens.from_dict(data)

The payload contains the nodes, the relations, and the graph metadata (including the resolver status).

Schema version

Serialized payloads carry a schema version. Loading a payload produced by an incompatible schema raises SerializationError, so you find out immediately rather than silently misreading old data. Keep producers and consumers on compatible graphlens versions, or regenerate the graph after an upgrade.

Diffing

Because node IDs are deterministic, two scans line up by identity and a structural diff is meaningful:

diff = old_graph.diff(new_graph)

GraphDiff exposes:

FieldTypeMeaning
added_nodeslist[Node]present only in the new graph
removed_nodeslist[Node]present only in the old graph
changed_nodeslist[tuple[Node, Node]]same id, different content (old, new)
added_relationslist[Relation]edges only in the new graph
removed_relationslist[Relation]edges only in the old graph
is_emptybool (property)True when the graphs are structurally identical

A "what changed in this PR" report is then a few lines:

diff = old.diff(new)
if not diff.is_empty:
print(f"nodes: +{len(diff.added_nodes)} -{len(diff.removed_nodes)}")
print(f"relations: +{len(diff.added_relations)} -{len(diff.removed_relations)}")

See CI integration for using a cached graph as a diff baseline.

Merging

merge combines another graph into this one (in place):

combined = python_graph
combined.merge(typescript_graph, allow_shared=True)

allow_shared=True permits identical nodes to coincide rather than raising — essential for cross-language BOUNDARY nodes, which are meant to be shared across the graphs being merged.