From 768038f53ad472344a6bbcc578df17ff97c09c37 Mon Sep 17 00:00:00 2001 From: Mahesh VAIKRI Date: Thu, 5 Nov 2026 15:07:40 -0600 Subject: [PATCH 1/2] Bring Rust, C# and C++ in line on undirected graphs and non-finite floats The identity patch (#1) fixed Python, JS and TS. These three ports had the same two gaps where their string ids allow a fix, plus a worse one: any file carrying a meta.graph block - every undirected graph the other ports now write, and every Python MultiGraph file - was refused outright as an "unknown block kind". - An undirected graph writes meta.graph / directed false and reads it back, skipping the mirror row it has already reconstructed. The Python-written undirected fixture is now byte-identical in all six ports and loads back undirected in each. Directed output is unchanged. - A Python MultiGraph document is refused with a message naming it, since these ports have no multigraph and would silently drop parallel edges. - NaN and infinity are refused as property values on add_node, add_edge and update_node, and update_node validates property names as the other ports do. Rust 69 -> 76 tests, C# 377 -> 384, C++ 57 -> 64; the cross-port golden still agrees. Node ids remain strings in these ports - the one parity gap left, and a breaking one for a later release. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 31 ++- ison-graph-cpp/include/ison_graph.hpp | 84 +++++++- ison-graph-cpp/tests/test_ison_graph.cpp | 103 ++++++++++ ison-graph-cs/src/IsonGraph/IsonGraph.cs | 27 +++ ison-graph-cs/src/IsonGraph/Serialization.cs | 53 ++++- .../IsonGraph.Tests/SerializationTests.cs | 96 +++++++++ ison-graph-rs/src/lib.rs | 191 +++++++++++++++++- 7 files changed, 555 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b450b5..13d9f18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,10 +10,9 @@ and the project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Four ways a graph's meaning changed between `dump` and `load`, found while auditing Core as the identity base for ISONGraphExt. Each is fixed in -Python, JavaScript and TypeScript, with the same tests in all three. A -directed graph's serialized bytes are unchanged, so the cross-port golden -still holds; only the cases that were already broken produce different -output. +every port where it applies, with the same tests in each. A directed +graph's serialized bytes are unchanged, so the cross-port golden still +holds; only the cases that were already broken produce different output. ### Fixed @@ -53,13 +52,23 @@ output. graph. `update_node` also validates property *names* now, closing a gap that let a dotted or `#`-prefixed name in through the back door. -### Not yet in Rust, C# and C++ - -Those ports store every node id as a string, so the negative-id and -id-type changes have no equivalent there yet, and they do not emit -`meta.graph` for an undirected graph. An undirected graph written by -Python/JS/TS and read by Rust/C#/C++ loads as directed, as it did before -this change. Aligning them is the next parity item. +### Rust, C# and C++ + +These three ports now agree with the others on everything above that +their ids allow. An undirected graph writes and reads `meta.graph`, so +the Python-written undirected fixture is byte-identical in all six +ports and loads back undirected in each. A document written by the +Python `MultiGraph` is refused with a message naming it - it used to +fail as an "unknown block kind", as did any file carrying `meta.graph`. +Non-finite floats are refused on `add_node`, `add_edge` and +`update_node` (`InvalidPropertyValue` in Rust, `ArgumentException` in +C#, `std::invalid_argument` in C++), and `update_node` validates +property names as the other ports do. + +What remains is that node ids are strings in these ports, so `1` and +`"1"` are one node there and two elsewhere, and the negative-id and +id-type changes have no equivalent. That is the next parity item, and +a breaking one. ## [1.4.0] — 2026-09-05 diff --git a/ison-graph-cpp/include/ison_graph.hpp b/ison-graph-cpp/include/ison_graph.hpp index 225fc47..df29302 100644 --- a/ison-graph-cpp/include/ison_graph.hpp +++ b/ison-graph-cpp/include/ison_graph.hpp @@ -67,6 +67,7 @@ #include #include #include +#include namespace ison_graph { @@ -113,6 +114,13 @@ struct NodeRefHash { /// parser already models exactly the types the format has, so it owns them. using Properties = std::map; +/** + * Written into meta.graph by the Python MultiGraph. This port has no + * multigraph, so loading such a document would silently drop its parallel + * edges; it is refused instead. + */ +inline constexpr const char* MULTIGRAPH_FORMAT = "ison-graph-multigraph-v1"; + /// Render a property as text - the form every value had before properties /// carried types. Query string operators, schema validation and the /// visualiser use it so their behaviour is unchanged by typing the storage. @@ -288,6 +296,7 @@ class ISONGraph { checkIdentifier("Node type", nodeType); checkIdentifier("Node id", nodeId); checkPropertyNames("Node property", properties); + checkPropertyValues("Node property", properties); auto& typeNodes = nodes_[nodeType]; if (typeNodes.find(nodeId) != typeNodes.end()) { throw DuplicateNodeError(NodeRef(nodeType, nodeId)); @@ -384,6 +393,8 @@ class ISONGraph { /** Update node properties */ void updateNode(const std::string& nodeType, const std::string& nodeId, const Properties& properties) { + checkPropertyNames("Node property", properties); + checkPropertyValues("Node property", properties); Node& node = getNode(nodeType, nodeId); for (const auto& [k, v] : properties) { node.properties[k] = v; @@ -451,6 +462,7 @@ class ISONGraph { const Properties& properties = {}) { checkIdentifier("Relationship type", relType); checkPropertyNames("Edge property", properties); + checkPropertyValues("Edge property", properties); if (!hasNode(source)) { throw NodeNotFoundError(source); @@ -914,6 +926,20 @@ class ISONGraph { ison::Document buildDocument() const { ison::Document doc; + // Directedness is graph semantics: an undirected graph that reloads + // as directed silently changes traversal, degree and cycle results, + // and its two mirror rows become two distinct edges. Written only + // when it departs from the default so every directed graph keeps + // its bytes. + if (!directed) { + ison::Block meta("meta", "graph"); + meta.fields.push_back("directed"); + ison::Row row; + row["directed"] = ison::Value(false); + meta.rows.push_back(row); + doc.blocks.push_back(meta); + } + std::vector nodeTypes; for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { nodeTypes.push_back(it->first); @@ -1239,18 +1265,54 @@ class ISONGraph { return false; } + /** + * Reject property values that change type on a round trip. ISON has no + * spelling for a non-finite float: NaN and infinity are written bare and + * read back as the *strings* "nan" / "inf". + */ + static void checkPropertyValues(const std::string& kind, const Properties& properties) { + for (const auto& [name, value] : properties) { + if (value.is_float() && !std::isfinite(value.as_float())) { + throw std::invalid_argument( + kind + " '" + name + "' cannot be encoded: a float must be finite " + "(NaN and infinity are read back as strings)."); + } + } + } + static ISONGraph buildFromDocument(const ison::Document& doc, const std::string& graphName) { - ISONGraph graph(graphName); - + // meta.graph carries graph semantics: 'directed' (written by every + // port for an undirected graph) and 'format' (written by the Python + // MultiGraph, which this port cannot represent). + bool directed = true; for (size_t b = 0; b < doc.blocks.size(); ++b) { const ison::Block& block = doc.blocks[b]; - if (block.kind != "nodes" && block.kind != "edges") { - throw GraphError("unknown block kind '" + block.kind + - "' (expected 'nodes' or 'edges')"); + if (block.kind == "nodes" || block.kind == "edges") continue; + if (block.kind == "meta" && block.name == "graph") { + for (size_t r = 0; r < block.rows.size(); ++r) { + const ison::Row& row = block.rows[r]; + ison::Row::const_iterator f = row.find("format"); + if (f != row.end() && f->second.is_string() && + f->second.as_string() == MULTIGRAPH_FORMAT) { + throw GraphError(std::string("This is a ") + MULTIGRAPH_FORMAT + + " document, which may contain multiple edges per " + "(relType, source, target) triple; this port has no " + "MultiGraph and would silently drop them."); + } + ison::Row::const_iterator d = row.find("directed"); + if (d != row.end() && d->second.is_bool()) { + directed = d->second.as_bool(); + } + } + continue; } + throw GraphError("unknown block kind '" + block.kind + + "' (expected 'nodes', 'edges' or 'meta')"); } + ISONGraph graph(graphName, directed); + // Nodes first regardless of block order - the canonical writer sorts // blocks by name, which puts 'edges' ahead of 'nodes'. for (size_t b = 0; b < doc.blocks.size(); ++b) { @@ -1299,8 +1361,16 @@ class ISONGraph { throw GraphError( "fromIson: Invalid node reference: edge endpoint has no type"); } - graph.addEdge(block.name, NodeRef(sref.type.value(), sref.id), - NodeRef(tref.type.value(), tref.id), props); + NodeRef sourceRef(sref.type.value(), sref.id); + NodeRef targetRef(tref.type.value(), tref.id); + // An undirected graph serializes both an edge and the mirror + // it auto-created; re-adding the mirror would collide, so + // skip what is already reconstructed. A directed graph still + // throws on a genuine duplicate. + if (!graph.directed && graph.hasEdge(block.name, sourceRef, targetRef)) { + continue; + } + graph.addEdge(block.name, sourceRef, targetRef, props); } } diff --git a/ison-graph-cpp/tests/test_ison_graph.cpp b/ison-graph-cpp/tests/test_ison_graph.cpp index 3d0c33b..37856fe 100644 --- a/ison-graph-cpp/tests/test_ison_graph.cpp +++ b/ison-graph-cpp/tests/test_ison_graph.cpp @@ -946,6 +946,100 @@ TEST(roundtrip_preserves_canonical_form) { assert(reloaded.toIson() == g.toIson()); } + +// ============================================================================= +// Identity contract: directedness survives dump -> load, a Python MultiGraph +// document is refused rather than silently flattened, and a value the wire +// format cannot spell is refused before it enters the graph. +// UNDIRECTED_FIXTURE is the exact bytes the Python port writes for the same +// graph (string ids, so every port can represent it). +// ============================================================================= + +static const char* UNDIRECTED_FIXTURE = + "edges.R\nsource target w\n:p:1 :p:2 1\n:p:2 :p:1 1\n\n" + "meta.graph\ndirected\nfalse\n\n" + "nodes.p\nid name\n\"1\" A\n\"2\" null"; + +static ISONGraph buildUndirected() { + ISONGraph g("u", false); + g.addNode("p", "1", {{"name", ison::Value("A")}}); + g.addNode("p", "2"); + g.addEdge("R", {"p", "1"}, {"p", "2"}, {{"w", ison::Value(1)}}); + return g; +} + +TEST(undirected_writes_meta_and_matches_python_bytes) { + assert(buildUndirected().toIson() == UNDIRECTED_FIXTURE); +} + +TEST(directed_output_has_no_meta_block) { + assert(buildCanonicalFixture(0).toIson().find("meta.graph") == std::string::npos); + assert(buildCanonicalFixture(0).toIsonl().find("meta.graph") == std::string::npos); +} + +TEST(undirected_roundtrip) { + ISONGraph g = buildUndirected(); + ISONGraph r = ISONGraph::fromIson(g.toIson()); + assert(!r.directed); + assert(r.edgeCount() == g.edgeCount()); + assert(r.hasEdge("R", {"p", "1"}, {"p", "2"})); + assert(r.hasEdge("R", {"p", "2"}, {"p", "1"})); + assert(r.toIson() == g.toIson()); + + ISONGraph rl = ISONGraph::fromIsonl(g.toIsonl()); + assert(!rl.directed); + assert(rl.toIsonl() == g.toIsonl()); +} + +TEST(directed_duplicate_row_still_throws) { + bool thrown = false; + try { + ISONGraph::fromIson("edges.R\nsource target\n:p:1 :p:2\n:p:1 :p:2\n\nnodes.p\nid\n\"1\"\n\"2\""); + } catch (const DuplicateEdgeError&) { + thrown = true; + } + assert(thrown); +} + +TEST(explicit_directed_true_is_honoured) { + assert(ISONGraph::fromIson("meta.graph\ndirected\ntrue\n\nnodes.p\nid\n\"1\"").directed); +} + +TEST(multigraph_document_is_refused) { + bool refused = false; + try { + ISONGraph::fromIson("meta.graph\ndirected format version\ntrue ison-graph-multigraph-v1 1\n\nnodes.p\nid\n\"1\""); + } catch (const GraphError& e) { + refused = std::string(e.what()).find("MultiGraph") != std::string::npos; + } + assert(refused); +} + +TEST(non_finite_float_properties_are_refused) { + ISONGraph g("t"); + bool thrown = false; + try { g.addNode("p", "1", {{"x", ison::Value(std::nan(""))}}); } + catch (const std::invalid_argument&) { thrown = true; } + assert(thrown); + + g.addNode("p", "1"); + g.addNode("p", "2"); + thrown = false; + try { g.updateNode("p", "1", {{"x", ison::Value(static_cast(INFINITY))}}); } + catch (const std::invalid_argument&) { thrown = true; } + assert(thrown); + assert(g.getNode("p", "1").properties.empty()); + + thrown = false; + try { g.addEdge("R", {"p", "1"}, {"p", "2"}, {{"w", ison::Value(static_cast(-INFINITY))}}); } + catch (const std::invalid_argument&) { thrown = true; } + assert(thrown); + assert(g.edgeCount() == 0); + + // Finite floats are untouched. + g.addEdge("R", {"p", "1"}, {"p", "2"}, {{"w", ison::Value(1.5)}}); +} + // ============================================================================= // Main // ============================================================================= @@ -1035,6 +1129,15 @@ int main() { RUN_TEST(ordinal_not_numeric_sort); RUN_TEST(roundtrip_preserves_canonical_form); + // Identity contract + RUN_TEST(undirected_writes_meta_and_matches_python_bytes); + RUN_TEST(directed_output_has_no_meta_block); + RUN_TEST(undirected_roundtrip); + RUN_TEST(directed_duplicate_row_still_throws); + RUN_TEST(explicit_directed_true_is_honoured); + RUN_TEST(multigraph_document_is_refused); + RUN_TEST(non_finite_float_properties_are_refused); + std::cout << "\n=== Results ===\n"; std::cout << "Total: " << total << ", Passed: " << (total - failed) << ", Failed: " << failed << std::endl; diff --git a/ison-graph-cs/src/IsonGraph/IsonGraph.cs b/ison-graph-cs/src/IsonGraph/IsonGraph.cs index fb765b6..a951630 100644 --- a/ison-graph-cs/src/IsonGraph/IsonGraph.cs +++ b/ison-graph-cs/src/IsonGraph/IsonGraph.cs @@ -283,6 +283,30 @@ private static void CheckIdentifier(string kind, string value) throw new ArgumentException($"{kind} must not contain ':' or '|': '{value}'"); } + /// + /// Reject property values that change type on a round trip. ISON has no + /// spelling for a non-finite float: NaN and infinity are written bare and + /// read back as the strings "nan" / "inf", so the value changes + /// type silently. Refused here, where the mistake is still visible. + /// + private static void CheckPropertyValues(string kind, IDictionary? properties) + { + if (properties is null) return; + foreach (var (key, value) in properties) + { + var nonFinite = value switch + { + double d => !double.IsFinite(d), + float f => !float.IsFinite(f), + _ => false, + }; + if (nonFinite) + throw new ArgumentException( + $"{kind} '{key}' = {value} cannot be encoded: a float must be finite " + + "(NaN and infinity are read back as strings)."); + } + } + /// /// Add a node to the graph. /// Throws if the type or id contains ':' or '|', @@ -293,6 +317,7 @@ public Node AddNode(string nodeType, string nodeId, { CheckIdentifier("Node type", nodeType); CheckIdentifier("Node id", nodeId); + CheckPropertyValues("Node property", properties); if (!_nodesByType.TryGetValue(nodeType, out var typeNodes)) { @@ -365,6 +390,7 @@ public void RemoveNode(string nodeType, string nodeId) public Node UpdateNode(string nodeType, string nodeId, IDictionary properties) { + CheckPropertyValues("Node property", properties); var node = GetNode(nodeType, nodeId); foreach (var (key, value) in properties) node.Properties[key] = value; @@ -420,6 +446,7 @@ public Edge AddEdge(string relType, NodeRef source, NodeRef target, IDictionary? properties = null) { CheckIdentifier("Relationship type", relType); + CheckPropertyValues("Edge property", properties); if (!HasNode(source)) throw new NodeNotFoundError(source); diff --git a/ison-graph-cs/src/IsonGraph/Serialization.cs b/ison-graph-cs/src/IsonGraph/Serialization.cs index fc61273..a4e07d4 100644 --- a/ison-graph-cs/src/IsonGraph/Serialization.cs +++ b/ison-graph-cs/src/IsonGraph/Serialization.cs @@ -221,10 +221,29 @@ private static List SortedEdges(List edges) /// the id column was written unquoted, so a node id containing a space /// produced output that would not reparse. /// + /// + /// Written into meta.graph by the Python MultiGraph. This + /// port has no multigraph, so loading such a document would silently drop + /// its parallel edges; it is refused instead. + /// + public const string MultigraphFormat = "ison-graph-multigraph-v1"; + private Document BuildDocument() { var doc = new Document(); + // Directedness is graph semantics: an undirected graph that reloads as + // directed silently changes traversal, degree and cycle results, and + // its two mirror rows become two distinct edges. Written only when it + // departs from the default so every directed graph keeps its bytes. + if (!Directed) + { + var meta = new Block("meta", "graph"); + meta.Fields.Add("directed"); + meta.Rows.Add(new Dictionary { ["directed"] = false }); + doc.Blocks.Add(meta); + } + var nodeTypes = new List(_nodeTypeOrder); nodeTypes.Sort(OrdinalComparer); foreach (var nodeType in nodeTypes) @@ -311,15 +330,33 @@ private Document BuildDocument() private static ISONGraph BuildFromDocument(Document doc, string name) { - var graph = new ISONGraph(name); - + // meta.graph carries graph semantics: 'directed' (written by every + // port for an undirected graph) and 'format' (written by the Python + // MultiGraph, which this port cannot represent). + var directed = true; foreach (var block in doc.Blocks) { - if (block.Kind != "nodes" && block.Kind != "edges") - throw new GraphError( - $"unknown block kind '{block.Kind}' (expected 'nodes' or 'edges')"); + if (block.Kind == "nodes" || block.Kind == "edges") continue; + if (block.Kind == "meta" && block.Name == "graph") + { + foreach (var row in block.Rows) + { + if (row.TryGetValue("format", out var format) && format is string f && f == MultigraphFormat) + throw new GraphError( + $"This is a {MultigraphFormat} document, which may contain multiple edges " + + "per (relType, source, target) triple; this port has no MultiGraph and " + + "would silently drop them."); + if (row.TryGetValue("directed", out var d) && d is bool b) + directed = b; + } + continue; + } + throw new GraphError( + $"unknown block kind '{block.Kind}' (expected 'nodes', 'edges' or 'meta')"); } + var graph = new ISONGraph(name, directed); + // Nodes first regardless of block order - the canonical writer sorts // blocks by name, which puts 'edges' ahead of 'nodes'. foreach (var block in doc.Blocks) @@ -373,6 +410,12 @@ private static ISONGraph BuildFromDocument(Document doc, string name) throw new GraphError( $"Invalid node reference: :{end.Type}:{end.Id} has not been defined"); } + // An undirected graph serializes both an edge and the mirror it + // auto-created; re-adding the mirror would collide, so skip what + // is already reconstructed. A directed graph still fails on a + // genuine duplicate. + if (!graph.Directed && graph.HasEdge(block.Name, sourceRef, targetRef)) + continue; try { graph.AddEdge(block.Name, sourceRef, targetRef, props); diff --git a/ison-graph-cs/tests/IsonGraph.Tests/SerializationTests.cs b/ison-graph-cs/tests/IsonGraph.Tests/SerializationTests.cs index 9f4e4c8..ab98d59 100644 --- a/ison-graph-cs/tests/IsonGraph.Tests/SerializationTests.cs +++ b/ison-graph-cs/tests/IsonGraph.Tests/SerializationTests.cs @@ -634,3 +634,99 @@ public void RoundtripPreservesCanonicalForm() Assert.Equal(g.ToIson(), reloaded.ToIson()); } } + +// ============================================================================= +// Identity contract: directedness survives dump -> load, a Python MultiGraph +// document is refused rather than silently flattened, and a value the wire +// format cannot spell is refused before it enters the graph. +// UndirectedFixture is the exact bytes the Python port writes for the same +// graph (string ids, so every port can represent it). +// ============================================================================= + +public class IdentityContractTests +{ + private const string UndirectedFixture = + "edges.R\nsource target w\n:p:1 :p:2 1\n:p:2 :p:1 1\n\n" + + "meta.graph\ndirected\nfalse\n\n" + + "nodes.p\nid name\n\"1\" A\n\"2\" null"; + + private static ISONGraph BuildUndirected() + { + var g = new ISONGraph("u", directed: false); + g.AddNode("p", "1", new Dictionary { ["name"] = "A" }); + g.AddNode("p", "2"); + g.AddEdge("R", new("p", "1"), new("p", "2"), new Dictionary { ["w"] = 1L }); + return g; + } + + [Fact] + public void UndirectedWritesMetaAndMatchesPythonBytes() + { + Assert.Equal(UndirectedFixture, BuildUndirected().ToIson()); + } + + [Fact] + public void DirectedOutputHasNoMetaBlock() + { + var g = new ISONGraph(); + g.AddNode("p", "1"); + Assert.DoesNotContain("meta.graph", g.ToIson()); + Assert.DoesNotContain("meta.graph", g.ToIsonl()); + } + + [Fact] + public void UndirectedRoundTrip() + { + var g = BuildUndirected(); + var r = ISONGraph.FromIson(g.ToIson()); + Assert.False(r.Directed); + Assert.Equal(g.EdgeCount(), r.EdgeCount()); + Assert.True(r.HasEdge("R", new("p", "1"), new("p", "2"))); + Assert.True(r.HasEdge("R", new("p", "2"), new("p", "1"))); + Assert.Equal(g.ToIson(), r.ToIson()); + + var rl = ISONGraph.FromIsonl(g.ToIsonl()); + Assert.False(rl.Directed); + Assert.Equal(g.ToIsonl(), rl.ToIsonl()); + } + + [Fact] + public void DirectedDuplicateRowStillThrows() + { + const string text = "edges.R\nsource target\n:p:1 :p:2\n:p:1 :p:2\n\nnodes.p\nid\n\"1\"\n\"2\""; + var ex = Assert.Throws(() => ISONGraph.FromIson(text)); + Assert.Contains("duplicate edge", ex.Message); + } + + [Fact] + public void ExplicitDirectedTrueIsHonoured() + { + Assert.True(ISONGraph.FromIson("meta.graph\ndirected\ntrue\n\nnodes.p\nid\n\"1\"").Directed); + } + + [Fact] + public void MultigraphDocumentIsRefused() + { + const string text = "meta.graph\ndirected format version\ntrue ison-graph-multigraph-v1 1\n\nnodes.p\nid\n\"1\""; + var ex = Assert.Throws(() => ISONGraph.FromIson(text)); + Assert.Contains("MultiGraph", ex.Message); + } + + [Fact] + public void NonFiniteFloatPropertiesAreRefused() + { + var g = new ISONGraph(); + Assert.Throws(() => + g.AddNode("p", "1", new Dictionary { ["x"] = double.NaN })); + g.AddNode("p", "1"); + g.AddNode("p", "2"); + Assert.Throws(() => + g.UpdateNode("p", "1", new Dictionary { ["x"] = double.PositiveInfinity })); + Assert.Empty(g.GetNode("p", "1").Properties); + Assert.Throws(() => + g.AddEdge("R", new("p", "1"), new("p", "2"), new Dictionary { ["w"] = double.NegativeInfinity })); + Assert.Equal(0, g.EdgeCount()); + // Finite floats are untouched. + g.AddEdge("R", new("p", "1"), new("p", "2"), new Dictionary { ["w"] = 1.5 }); + } +} diff --git a/ison-graph-rs/src/lib.rs b/ison-graph-rs/src/lib.rs index 02188be..1f1329c 100644 --- a/ison-graph-rs/src/lib.rs +++ b/ison-graph-rs/src/lib.rs @@ -286,12 +286,23 @@ pub enum GraphError { #[error("{0}")] InvalidIdentifier(String), + /// A property value cannot survive a serialization round trip. ISON has + /// no spelling for a non-finite float: NaN and infinity are written bare + /// and read back as the *strings* "nan" / "inf". + #[error("{0}")] + InvalidPropertyValue(String), + #[error("I/O error: {0}")] Io(#[from] std::io::Error), } pub type Result = std::result::Result; +/// Written into `meta.graph` by the Python `MultiGraph`. This port has no +/// multigraph, so loading such a document would silently drop its parallel +/// edges; it is refused instead. +pub const MULTIGRAPH_FORMAT: &str = "ison-graph-multigraph-v1"; + // ============================================================================= // ISONGraph - Main Graph Structure // ============================================================================= @@ -512,6 +523,26 @@ impl ISONGraph { Ok(()) } + /// Reject property values that change type on a round trip; see + /// [`GraphError::InvalidPropertyValue`]. + fn check_property_values<'a>( + kind: &str, + properties: impl Iterator, + ) -> Result<()> { + for (name, value) in properties { + if let Value::Float(f) = value { + if !f.is_finite() { + return Err(GraphError::InvalidPropertyValue(format!( + "{} {:?} = {} cannot be encoded: a float must be finite \ + (NaN and infinity are read back as strings).", + kind, name, f + ))); + } + } + } + Ok(()) + } + pub fn add_node( &mut self, node_type: &str, @@ -521,6 +552,7 @@ impl ISONGraph { Self::check_identifier("Node type", node_type)?; Self::check_identifier("Node id", node_id)?; Self::check_property_names("Node property", properties.iter().map(|(k, _)| *k))?; + Self::check_property_values("Node property", properties.iter().map(|(k, v)| (*k, v)))?; let type_nodes = self.nodes.entry(node_type.to_string()).or_default(); @@ -594,6 +626,8 @@ impl ISONGraph { node_id: &str, properties: Vec<(&str, Value)>, ) -> Result<()> { + Self::check_property_names("Node property", properties.iter().map(|(k, _)| *k))?; + Self::check_property_values("Node property", properties.iter().map(|(k, v)| (*k, v)))?; let node = self .nodes .get_mut(node_type) @@ -648,6 +682,7 @@ impl ISONGraph { ) -> Result<()> { Self::check_identifier("Relationship type", rel_type)?; Self::check_property_names("Edge property", properties.iter().map(|(k, _)| *k))?; + Self::check_property_values("Edge property", properties.iter().map(|(k, v)| (*k, v)))?; // Validate nodes exist if !self.has_node(source.0, source.1) { @@ -1250,6 +1285,20 @@ impl ISONGraph { fn document(&self) -> IsonDocument { let mut doc = IsonDocument::new(); + // Directedness is graph semantics: an undirected graph that reloads + // as directed silently changes traversal, degree and cycle results, + // and its two mirror rows become two distinct edges. Written only + // when it departs from the default so every directed graph keeps + // its bytes. + if !self.directed { + let mut block = IsonBlock::new("meta", "graph"); + block.fields = vec!["directed".to_string()]; + let mut row: HashMap = HashMap::new(); + row.insert("directed".to_string(), IsonValue::Bool(false)); + block.rows.push(row); + doc.blocks.push(block); + } + let mut node_types: Vec<_> = self.nodes.keys().collect(); node_types.sort(); for node_type in node_types { @@ -1368,17 +1417,42 @@ impl ISONGraph { } fn build_from_document(doc: &IsonDocument, name: &str) -> Result { - let mut graph = ISONGraph::new(name); - + // `meta.graph` carries graph semantics: `directed` (written by every + // port for an undirected graph) and `format` (written by the Python + // MultiGraph, which this port cannot represent). + let mut directed = true; for block in &doc.blocks { - if block.kind != "nodes" && block.kind != "edges" { - return Err(GraphError::ParseError(format!( - "unknown block kind {:?} (expected 'nodes' or 'edges')", - block.kind - ))); + match block.kind.as_str() { + "nodes" | "edges" => {} + "meta" if block.name == "graph" => { + for row in &block.rows { + if let Some(IsonValue::String(format)) = row.get("format") { + if format == MULTIGRAPH_FORMAT { + return Err(GraphError::ParseError(format!( + "This is a {} document, which may contain multiple \ + edges per (rel_type, source, target) triple; this \ + port has no MultiGraph and would silently drop them.", + MULTIGRAPH_FORMAT + ))); + } + } + if let Some(IsonValue::Bool(b)) = row.get("directed") { + directed = *b; + } + } + } + other => { + return Err(GraphError::ParseError(format!( + "unknown block kind {:?} (expected 'nodes', 'edges' or 'meta')", + other + ))) + } } } + let mut graph = ISONGraph::new(name); + graph.directed = directed; + // Nodes first regardless of block order - the canonical writer sorts // blocks by name, which puts 'edges' ahead of 'nodes'. for block in &doc.blocks { @@ -1426,6 +1500,15 @@ impl ISONGraph { .collect(); let borrowed: Vec<(&str, Value)> = props.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(); + // An undirected graph serializes both an edge and the mirror + // it auto-created; re-adding the mirror would collide, so + // skip what is already reconstructed. A directed graph still + // fails on a genuine duplicate. + if !graph.directed + && graph.has_edge(&block.name, (&source.0, &source.1), (&target.0, &target.1)) + { + continue; + } graph.add_edge( &block.name, (&source.0, &source.1), @@ -2742,4 +2825,98 @@ nodes.project|id budget name tag|p1 1250 Alpha "a\|b""#; let reloaded = ISONGraph::from_ison(&g.to_ison(), None).unwrap(); assert_eq!(reloaded.to_ison(), g.to_ison()); } + + // ========================================================================= + // Identity contract: directedness survives dump -> load, a Python + // MultiGraph document is refused rather than silently flattened, and a + // value the wire format cannot spell is refused before it enters the + // graph. UNDIRECTED_FIXTURE is the exact bytes the Python port writes + // for the same graph (string ids, so every port can represent it). + // ========================================================================= + + const UNDIRECTED_FIXTURE: &str = "edges.R\nsource target w\n:p:1 :p:2 1\n:p:2 :p:1 1\n\n\ + meta.graph\ndirected\nfalse\n\n\ + nodes.p\nid name\n\"1\" A\n\"2\" null"; + + fn build_undirected() -> ISONGraph { + let mut g = ISONGraph::undirected("u"); + g.add_node("p", "1", props![("name", "A")]).unwrap(); + g.add_node("p", "2", props![]).unwrap(); + g.add_edge("R", ("p", "1"), ("p", "2"), props![("w", 1i64)]).unwrap(); + g + } + + #[test] + fn test_undirected_writes_meta_and_matches_python_bytes() { + assert_eq!(build_undirected().to_ison(), UNDIRECTED_FIXTURE); + } + + #[test] + fn test_directed_output_has_no_meta_block() { + assert!(!build_canonical_fixture(0).to_ison().contains("meta.graph")); + assert!(!build_canonical_fixture(0).to_isonl().contains("meta.graph")); + } + + #[test] + fn test_undirected_roundtrip() { + let g = build_undirected(); + let r = ISONGraph::from_ison(&g.to_ison(), None).unwrap(); + assert!(!r.directed); + assert_eq!(r.edge_count(), g.edge_count()); + assert!(r.has_edge("R", ("p", "1"), ("p", "2"))); + assert!(r.has_edge("R", ("p", "2"), ("p", "1"))); + assert_eq!(r.to_ison(), g.to_ison()); + + let rl = ISONGraph::from_isonl(&g.to_isonl(), None).unwrap(); + assert!(!rl.directed); + assert_eq!(rl.to_isonl(), g.to_isonl()); + } + + #[test] + fn test_directed_duplicate_row_still_fails() { + let text = "edges.R\nsource target\n:p:1 :p:2\n:p:1 :p:2\n\nnodes.p\nid\n\"1\"\n\"2\""; + assert!(matches!( + ISONGraph::from_ison(text, None), + Err(GraphError::DuplicateEdge(_)) + )); + } + + #[test] + fn test_explicit_directed_true_is_honoured() { + let g = ISONGraph::from_ison("meta.graph\ndirected\ntrue\n\nnodes.p\nid\n\"1\"", None).unwrap(); + assert!(g.directed); + } + + #[test] + fn test_multigraph_document_is_refused() { + let text = "meta.graph\ndirected format version\ntrue ison-graph-multigraph-v1 1\n\n\ + nodes.p\nid\n\"1\""; + match ISONGraph::from_ison(text, None) { + Err(GraphError::ParseError(msg)) => assert!(msg.contains("MultiGraph"), "{}", msg), + other => panic!("expected ParseError, got {:?}", other.map(|_| ())), + } + } + + #[test] + fn test_non_finite_float_properties_are_refused() { + let mut g = ISONGraph::new("t"); + assert!(matches!( + g.add_node("p", "1", props![("x", f64::NAN)]), + Err(GraphError::InvalidPropertyValue(_)) + )); + g.add_node("p", "1", props![]).unwrap(); + g.add_node("p", "2", props![]).unwrap(); + assert!(matches!( + g.update_node("p", "1", props![("x", f64::INFINITY)]), + Err(GraphError::InvalidPropertyValue(_)) + )); + assert!(g.get_node("p", "1").unwrap().properties.is_empty()); + assert!(matches!( + g.add_edge("R", ("p", "1"), ("p", "2"), props![("w", f64::NEG_INFINITY)]), + Err(GraphError::InvalidPropertyValue(_)) + )); + assert_eq!(g.edge_count(), 0); + // Finite floats are untouched. + g.add_edge("R", ("p", "1"), ("p", "2"), props![("w", 1.5f64)]).unwrap(); + } } From 8a283d0a0d6c0f786f4e34887195b59dbd1a429a Mon Sep 17 00:00:00 2001 From: Mahesh VAIKRI Date: Thu, 5 Nov 2026 15:08:46 -0600 Subject: [PATCH 2/2] Release 1.4.1: version bump and dated changelog All six ports move to 1.4.1 together, per the release convention in CONTRIBUTING.md: pyproject.toml and both __version__ strings, both package.json files and their lockfiles, Cargo.toml and Cargo.lock, IsonGraph.csproj, CMakeLists.txt, and the two README install snippets that quote the crate version. A patch rather than a minor because nothing that round-tripped correctly on 1.4.0 changes: a directed graph's bytes are identical, and the inputs now refused were all silently corrupted on reload before. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 2 +- README.md | 2 +- ison-graph-cpp/CMakeLists.txt | 2 +- ison-graph-cs/src/IsonGraph/IsonGraph.csproj | 2 +- ison-graph-js/package-lock.json | 4 ++-- ison-graph-js/package.json | 2 +- ison-graph-rs/Cargo.lock | 2 +- ison-graph-rs/Cargo.toml | 2 +- ison-graph-rs/README.md | 2 +- ison-graph-ts/package-lock.json | 4 ++-- ison-graph-ts/package.json | 2 +- ison-graph/pyproject.toml | 2 +- ison-graph/src/ison_graph/__init__.py | 4 ++-- ison-graph/src/ison_graph/query.py | 4 ++-- 14 files changed, 18 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13d9f18..f7f623a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ share this file and, from 1.3.0, a single version number. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.4.1] — 2026-11-05 Four ways a graph's meaning changed between `dump` and `load`, found while auditing Core as the identity base for ISONGraphExt. Each is fixed in diff --git a/README.md b/README.md index cee81d0..3947945 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ npm install ison-graph-ts ```toml [dependencies] -ison-graph = "1.4.0" +ison-graph = "1.4.1" ``` ### C++ diff --git a/ison-graph-cpp/CMakeLists.txt b/ison-graph-cpp/CMakeLists.txt index bd98d62..29f6565 100644 --- a/ison-graph-cpp/CMakeLists.txt +++ b/ison-graph-cpp/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.14) -project(ison_graph_cpp VERSION 1.4.0 LANGUAGES CXX) +project(ison_graph_cpp VERSION 1.4.1 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/ison-graph-cs/src/IsonGraph/IsonGraph.csproj b/ison-graph-cs/src/IsonGraph/IsonGraph.csproj index 378a60f..c30f9ee 100644 --- a/ison-graph-cs/src/IsonGraph/IsonGraph.csproj +++ b/ison-graph-cs/src/IsonGraph/IsonGraph.csproj @@ -19,7 +19,7 @@ IsonGraph - 1.4.0 + 1.4.1 Mahesh Vaikri MIT https://github.com/ISON-format/isongraph diff --git a/ison-graph-js/package-lock.json b/ison-graph-js/package-lock.json index e8f2aef..0f2171b 100644 --- a/ison-graph-js/package-lock.json +++ b/ison-graph-js/package-lock.json @@ -1,12 +1,12 @@ { "name": "ison-graph-js", - "version": "1.4.0", + "version": "1.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ison-graph-js", - "version": "1.4.0", + "version": "1.4.1", "license": "MIT", "dependencies": { "ison-parser": "^1.2.0" diff --git a/ison-graph-js/package.json b/ison-graph-js/package.json index 1e93908..7402a17 100644 --- a/ison-graph-js/package.json +++ b/ison-graph-js/package.json @@ -1,6 +1,6 @@ { "name": "ison-graph-js", - "version": "1.4.0", + "version": "1.4.1", "description": "ISONGraph - Token-efficient property graph store with ISON persistence, ISONQL queries, schema validation, and deterministic graph visualization", "main": "src/index.js", "type": "module", diff --git a/ison-graph-rs/Cargo.lock b/ison-graph-rs/Cargo.lock index 852ff5a..3b32186 100644 --- a/ison-graph-rs/Cargo.lock +++ b/ison-graph-rs/Cargo.lock @@ -19,7 +19,7 @@ checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "ison-graph" -version = "1.4.0" +version = "1.4.1" dependencies = [ "ison-rs", "pretty_assertions", diff --git a/ison-graph-rs/Cargo.toml b/ison-graph-rs/Cargo.toml index 14a764b..f6c684f 100644 --- a/ison-graph-rs/Cargo.toml +++ b/ison-graph-rs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ison-graph" -version = "1.4.0" +version = "1.4.1" edition = "2021" rust-version = "1.70" authors = ["Mahesh Vaikri"] diff --git a/ison-graph-rs/README.md b/ison-graph-rs/README.md index 180c2d1..0223561 100644 --- a/ison-graph-rs/README.md +++ b/ison-graph-rs/README.md @@ -25,7 +25,7 @@ ```toml [dependencies] -ison-graph = "1.4.0" +ison-graph = "1.4.1" ``` ## Quick Start diff --git a/ison-graph-ts/package-lock.json b/ison-graph-ts/package-lock.json index 3d6013b..9c6332d 100644 --- a/ison-graph-ts/package-lock.json +++ b/ison-graph-ts/package-lock.json @@ -1,12 +1,12 @@ { "name": "ison-graph-ts", - "version": "1.4.0", + "version": "1.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ison-graph-ts", - "version": "1.4.0", + "version": "1.4.1", "license": "MIT", "dependencies": { "ison-ts": "^1.2.0" diff --git a/ison-graph-ts/package.json b/ison-graph-ts/package.json index 076cd23..eeeab1b 100644 --- a/ison-graph-ts/package.json +++ b/ison-graph-ts/package.json @@ -1,6 +1,6 @@ { "name": "ison-graph-ts", - "version": "1.4.0", + "version": "1.4.1", "description": "ISONGraph - Token-efficient property graph store with ISON persistence, ISONQL queries, schema validation, and deterministic graph visualization", "main": "dist/index.js", "module": "dist/index.mjs", diff --git a/ison-graph/pyproject.toml b/ison-graph/pyproject.toml index 3dee5fd..7e0df68 100644 --- a/ison-graph/pyproject.toml +++ b/ison-graph/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "ison-graph" -version = "1.4.0" +version = "1.4.1" description = "ISONGraph - A token-efficient graph store format built on ISON" readme = "README.md" license = {text = "MIT"} diff --git a/ison-graph/src/ison_graph/__init__.py b/ison-graph/src/ison_graph/__init__.py index b5145ea..137a4d6 100644 --- a/ison-graph/src/ison_graph/__init__.py +++ b/ison-graph/src/ison_graph/__init__.py @@ -32,7 +32,7 @@ graph = ISONGraph.load('social.isong') Author: Mahesh Vaikri -Version: 1.4.0 +Version: 1.4.1 """ from __future__ import annotations @@ -57,7 +57,7 @@ dumps_canonical, dumps_canonical_isonl ) -__version__ = "1.4.0" +__version__ = "1.4.1" __author__ = "Mahesh Vaikri" diff --git a/ison-graph/src/ison_graph/query.py b/ison-graph/src/ison_graph/query.py index fe73c6a..7290260 100644 --- a/ison-graph/src/ison_graph/query.py +++ b/ison-graph/src/ison_graph/query.py @@ -38,7 +38,7 @@ .execute()) Author: Mahesh Vaikri -Version: 1.4.0 +Version: 1.4.1 """ from __future__ import annotations @@ -59,7 +59,7 @@ # Fallback for standalone testing from ison_graph import ISONGraph, Node, Edge, NodeRef, Direction, Path -__version__ = "1.4.0" +__version__ = "1.4.1" __author__ = "Mahesh Vaikri"