From 676330d74475efaf4c20b59ddfc64b6d0403ffc1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 14:57:46 +0000 Subject: [PATCH] Keep subgraph node order independent of hash seed Graph.subgraph iterated a set of node ids, so the order of nodes in a subgraph, and in its JSON and Mermaid output, changed with PYTHONHASHSEED. Regenerating docs/img/pbpk_elimination_subgraph.mmd reordered its node lines on every run, with no change in content. Subgraphs now keep the parent graph's insertion order and raise KeyError naming any unknown ids. A new test renders the PBPK elimination subgraph under four hash seeds and requires identical output; the test fails on the previous implementation. The regenerated Mermaid source is committed; the graph JSON and validation outputs are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CoFhtFtE7wJgvHKAzNB3xD --- docs/img/pbpk_elimination_subgraph.mmd | 10 ++++---- tests/test_graph.py | 33 ++++++++++++++++++++++++++ vh/graph/core.py | 14 +++++++---- 3 files changed, 48 insertions(+), 9 deletions(-) diff --git a/docs/img/pbpk_elimination_subgraph.mmd b/docs/img/pbpk_elimination_subgraph.mmd index 1d67173..18fece9 100644 --- a/docs/img/pbpk_elimination_subgraph.mmd +++ b/docs/img/pbpk_elimination_subgraph.mmd @@ -1,12 +1,12 @@ %% Elimination subgraph (plasma-referenced reporting parameters) flowchart LR + arterial(["arterial blood"]) venous(["venous blood"]) - spleen["spleen"] eliminated[("eliminated")] - arterial(["arterial blood"]) kidney["kidney"] - gut["gut"] liver["liver"] + gut["gut"] + spleen["spleen"] pancreas["pancreas"] arterial -->|"74.1 L/h"| kidney kidney -->|"74.1 L/h"| venous @@ -21,8 +21,8 @@ flowchart LR liver -->|"CL 16.86 L/h (plasma)"| eliminated kidney -->|"CL 0.24 L/h (plasma)"| eliminated classDef c_blood fill:#C2373A,stroke:#222,color:#ffffff; - class venous,arterial c_blood; + class arterial,venous c_blood; classDef c_compartment fill:#2B44C4,stroke:#222,color:#ffffff; - class spleen,kidney,gut,liver,pancreas c_compartment; + class kidney,liver,gut,spleen,pancreas c_compartment; classDef c_sink fill:#586379,stroke:#222,color:#ffffff; class eliminated c_sink; \ No newline at end of file diff --git a/tests/test_graph.py b/tests/test_graph.py index 62cb133..cae44de 100644 --- a/tests/test_graph.py +++ b/tests/test_graph.py @@ -70,6 +70,39 @@ def test_connected_components_and_subgraph(): assert set(sub.nodes) == {"a", "b"} and len(sub.edges) == 1 +def test_subgraph_order_is_reproducible_across_hash_seeds(): + # String-set iteration order changes with PYTHONHASHSEED; a subgraph must + # follow the parent graph's order so its JSON and Mermaid are byte-stable. + import os + import subprocess + import sys + + g = Graph("ordered") + for n in "fedcba": + g.add_node(n, "x") + g.add_edge("f", "a", "e") + assert list(g.subgraph(["a", "c", "f"]).nodes) == ["f", "c", "a"] + assert list(g.subgraph(reversed(["a", "c", "f"])).nodes) == ["f", "c", "a"] + with pytest.raises(KeyError, match="unknown nodes"): + g.subgraph(["a", "missing"]) + + code = ("from vh.body import PBPKModel, MIDAZOLAM\n" + "from vh.graph.physiology_graph import build_pbpk_graph\n" + "from vh.graph.render import to_mermaid\n" + "g, _ = build_pbpk_graph(PBPKModel(MIDAZOLAM))\n" + "ids = ['arterial', 'liver', 'kidney', 'venous', 'gut', 'spleen', 'pancreas', 'eliminated']\n" + "print(to_mermaid(g.subgraph(set(ids))))\n") + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + outputs = set() + for seed in ("0", "1", "2", "3"): + env = {**os.environ, "PYTHONHASHSEED": seed, + "PYTHONPATH": os.pathsep.join(filter(None, [root, os.environ.get("PYTHONPATH")]))} + run = subprocess.run([sys.executable, "-c", code], env=env, cwd=root, + capture_output=True, text=True, check=True, timeout=120) + outputs.add(run.stdout) + assert len(outputs) == 1 + + def test_schema_validation_catches_bad_edges(): schema = Schema(node_types={"blood": set(), "organ": {"volume"}}, edge_rules=[EdgeRule("flow", {"blood", "organ"}, {"blood", "organ"}, {"flow"})]) diff --git a/vh/graph/core.py b/vh/graph/core.py index 4f93e31..2088b9d 100644 --- a/vh/graph/core.py +++ b/vh/graph/core.py @@ -120,12 +120,18 @@ def degree(self, nid: str) -> int: # --- subgraphs ----------------------------------------------------------- def subgraph(self, node_ids: Iterable[str], name: str | None = None) -> "Graph": - """Induced subgraph on the given nodes (all edges with both ends inside).""" + """Induced subgraph on the given nodes (all edges with both ends inside). + + Nodes keep this graph's insertion order, not the order (or set-iteration + order) of `node_ids`, so serialization and rendering are reproducible.""" keep = set(node_ids) + unknown = keep - self.nodes.keys() + if unknown: + raise KeyError(f"subgraph references unknown nodes {sorted(unknown)!r}") g = Graph(name or f"{self.name}:sub") - for nid in keep: - n = self.nodes[nid] - g.add_node(n.id, n.type, n.scale, n.label, **dict(n.attrs)) + for n in self.nodes.values(): + if n.id in keep: + g.add_node(n.id, n.type, n.scale, n.label, **dict(n.attrs)) for e in self.edges: if e.src in keep and e.dst in keep: g.add_edge(e.src, e.dst, e.type, e.directed, e.model, **dict(e.attrs))