Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ 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
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

Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ npm install ison-graph-ts

```toml
[dependencies]
ison-graph = "1.4.0"
ison-graph = "1.4.1"
```

### C++
Expand Down
2 changes: 1 addition & 1 deletion ison-graph-cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
84 changes: 77 additions & 7 deletions ison-graph-cpp/include/ison_graph.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
#include <fstream>
#include <tuple>
#include <regex>
#include <cmath>

namespace ison_graph {

Expand Down Expand Up @@ -113,6 +114,13 @@ struct NodeRefHash {
/// parser already models exactly the types the format has, so it owns them.
using Properties = std::map<std::string, ison::Value>;

/**
* 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.
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<std::string> nodeTypes;
for (auto it = nodes_.begin(); it != nodes_.end(); ++it) {
nodeTypes.push_back(it->first);
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
}

Expand Down
103 changes: 103 additions & 0 deletions ison-graph-cpp/tests/test_ison_graph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<double>(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<double>(-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
// =============================================================================
Expand Down Expand Up @@ -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;
Expand Down
27 changes: 27 additions & 0 deletions ison-graph-cs/src/IsonGraph/IsonGraph.cs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,30 @@ private static void CheckIdentifier(string kind, string value)
throw new ArgumentException($"{kind} must not contain ':' or '|': '{value}'");
}

/// <summary>
/// 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 <em>strings</em> "nan" / "inf", so the value changes
/// type silently. Refused here, where the mistake is still visible.
/// </summary>
private static void CheckPropertyValues(string kind, IDictionary<string, object?>? 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).");
}
}

/// <summary>
/// Add a node to the graph.
/// Throws <see cref="ArgumentException"/> if the type or id contains ':' or '|',
Expand All @@ -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))
{
Expand Down Expand Up @@ -365,6 +390,7 @@ public void RemoveNode(string nodeType, string nodeId)
public Node UpdateNode(string nodeType, string nodeId,
IDictionary<string, object?> properties)
{
CheckPropertyValues("Node property", properties);
var node = GetNode(nodeType, nodeId);
foreach (var (key, value) in properties)
node.Properties[key] = value;
Expand Down Expand Up @@ -420,6 +446,7 @@ public Edge AddEdge(string relType, NodeRef source, NodeRef target,
IDictionary<string, object?>? properties = null)
{
CheckIdentifier("Relationship type", relType);
CheckPropertyValues("Edge property", properties);

if (!HasNode(source))
throw new NodeNotFoundError(source);
Expand Down
2 changes: 1 addition & 1 deletion ison-graph-cs/src/IsonGraph/IsonGraph.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

<PropertyGroup>
<PackageId>IsonGraph</PackageId>
<Version>1.4.0</Version>
<Version>1.4.1</Version>
<Authors>Mahesh Vaikri</Authors>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryUrl>https://github.com/ISON-format/isongraph</RepositoryUrl>
Expand Down
Loading
Loading