From 6b71a5975b6d6fe4c567e8ad77a4e9acf3ff081d Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 11:39:37 -0800 Subject: [PATCH 01/15] Node attribute store; CSR: from_arrays, read_block, step_edges, digest - graphs.node_arrays: NodeArrays, NodeArraysWriter, write_node_arrays keep one value or vector per node in memory-mapped arrays keyed by node id, beside the graph they were computed on. - CSRGraphDataBase.from_arrays creates a database from a whole graph held in arrays. - CSRGraphDataBase.read_block reads a block with its surroundings (by distance, by edge steps or both) and marks the block's own nodes. - read_arrays(step_edges=...) follows only edges that carry one of the named attributes. - CSRGraphDataBase.is_database and .digest. Co-Authored-By: Claude Fable 5.2 --- docs/source/api.md | 12 + docs/source/graphs.md | 67 +++++ src/funlib/persistence/graphs/__init__.py | 1 + .../persistence/graphs/csr_graph_database.py | 152 +++++++++- src/funlib/persistence/graphs/node_arrays.py | 277 ++++++++++++++++++ tests/test_csr_graph_database.py | 153 ++++++++++ tests/test_node_arrays.py | 133 +++++++++ 7 files changed, 793 insertions(+), 2 deletions(-) create mode 100644 src/funlib/persistence/graphs/node_arrays.py create mode 100644 tests/test_node_arrays.py diff --git a/docs/source/api.md b/docs/source/api.md index d329fa4..0cc20a2 100644 --- a/docs/source/api.md +++ b/docs/source/api.md @@ -58,4 +58,16 @@ The graph databases are importable from `funlib.persistence.graphs`. .. autoclass:: funlib.persistence.graphs.pgsql_graph_database.PgSQLGraphDatabase :members: :show-inheritance: + +.. autoclass:: funlib.persistence.graphs.csr_graph_database.CSRGraphDataBase + :members: + :show-inheritance: + +.. autoclass:: funlib.persistence.graphs.node_arrays.NodeArrays + :members: + +.. autoclass:: funlib.persistence.graphs.node_arrays.NodeArraysWriter + :members: + +.. autofunction:: funlib.persistence.graphs.node_arrays.write_node_arrays ``` diff --git a/docs/source/graphs.md b/docs/source/graphs.md index 77b5828..349af64 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -41,3 +41,70 @@ the nodes inside the ROI and the edges whose `u` is inside it, which is how a block sees the edges that leave it; `fetch_on_v=True` adds the edges whose `v` is inside as well. A ROI that is unbounded on every axis, or no ROI, reads the whole graph. + +## A graph in memory-mapped arrays + +`CSRGraphDataBase` keeps a graph as plain `.npy` arrays under a directory, +sorted so that the nodes of a region are a few runs of consecutive rows. It +is read by memory mapping and suits graphs that are written once and then +read block by block. Attributes are numbers or vectors of numbers. + +A whole graph held in arrays is written in one call, and read back as +arrays: + +```python +import numpy as np +from funlib.geometry import Roi +from funlib.persistence.graphs import CSRGraphDataBase + +db = CSRGraphDataBase.from_arrays( + "fragments.csr", + ids, # (N,) node ids + {"position": positions, "size": sizes}, # (N, 3) and (N,) + u, v, # (M,) endpoint ids + {"merge_score": scores}, # (M,) + cell_size=3000.0, +) +nodes, edges = db.read_arrays(Roi((0, 0, 0), (100, 100, 100)), num_steps=1) +``` + +`read_arrays` returns the nodes in the ROI, every node within `num_steps` +edges of them, and the edges among the nodes read. `step_edges` names the +edge attributes that make an edge a step. + +`read_block` is the read of a computation that writes one value per node of +a block: the nodes of the ROI, marked `own`, with the nodes within a +distance `context` of it and within `num_steps` edges of those. + +```python +nodes, edges = db.read_block(roi, context=500, num_steps=2) +values = compute(nodes, edges)[nodes["own"]] +``` + +`CSRGraphDataBase.is_database(path)` tells such a directory from any other, +and `db.digest` identifies the content of the database. + +## Values on the nodes of a graph + +Values computed on a graph, such as an embedding per node, can be kept +beside the graph without rewriting it. A node attribute store is a +directory of memory-mapped arrays keyed by node id, and records the digest +of the graph the values belong to: + +```python +from funlib.persistence.graphs import NodeArrays, NodeArraysWriter + +with NodeArraysWriter( + "embedding.nodes", {"embedding": 64}, graph_digest=db.digest +) as out: + for roi in blocks: + nodes, edges = db.read_block(roi, num_steps=2) + own = nodes["own"] + out.append(nodes["id"][own], embedding=model(nodes, edges)[own]) + +found, values = NodeArrays("embedding.nodes").read(nodes["id"]) +``` + +A node belongs to one block: a node id written twice is refused. A node +that was never written is not `found` and reads as NaN (0 for an integer). +`write_node_arrays` writes values that are already in memory in one call. diff --git a/src/funlib/persistence/graphs/__init__.py b/src/funlib/persistence/graphs/__init__.py index 3a270f9..da92634 100644 --- a/src/funlib/persistence/graphs/__init__.py +++ b/src/funlib/persistence/graphs/__init__.py @@ -1,3 +1,4 @@ from .sqlite_graph_database import SQLiteGraphDataBase # noqa from .pgsql_graph_database import PgSQLGraphDatabase # noqa from .csr_graph_database import CSRGraphDataBase # noqa +from .node_arrays import NodeArrays, NodeArraysWriter, write_node_arrays # noqa diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index c810dcf..573fd16 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -23,18 +23,19 @@ from __future__ import annotations import fcntl +import hashlib import json import logging import os import shutil import uuid -from collections.abc import Iterable +from collections.abc import Iterable, Mapping, Sequence from contextlib import contextmanager from pathlib import Path from typing import Any import numpy as np -from funlib.geometry import Roi +from funlib.geometry import Coordinate, Roi from networkx import Graph from ..types import Vec @@ -290,6 +291,80 @@ def __init__( stored_roi = self.meta.get("total_roi") self.total_roi = None if stored_roi is None else Roi(*stored_roi) + @staticmethod + def is_database(path: Path | str) -> bool: + """Whether ``path`` is the directory of a CSR graph database.""" + meta = Path(path) / "meta.json" + if not meta.is_file(): + return False + try: + stored = json.loads(meta.read_text()) + except ValueError: + return False + return isinstance(stored, dict) and "generation" in stored + + @classmethod + def from_arrays( + cls, + path: Path | str, + ids: np.ndarray, + node_attrs: Mapping[str, np.ndarray], + u: np.ndarray | None = None, + v: np.ndarray | None = None, + edge_attrs: Mapping[str, np.ndarray] | None = None, + *, + cell_size: float | Iterable[float], + position_attribute: str = "position", + node_types: Mapping[str, AttributeType] | None = None, + edge_types: Mapping[str, AttributeType] | None = None, + total_roi: Roi | None = None, + ) -> CSRGraphDataBase: + """Create a database at ``path`` from a whole graph held in arrays, + replacing what is there, and return it open for reading and writing. + + ``ids`` are the node ids, ``node_attrs`` one array per node attribute + (the position among them), ``u`` and ``v`` the endpoint ids of the + edges and ``edge_attrs`` one array per edge attribute. + + An attribute is stored in the dtype of its array, a 2-D array as a + vector, unless ``node_types`` or ``edge_types`` names another type + for it; the array is cast to that type. + """ + edge_attrs = dict(edge_attrs or {}) + if (u is None) != (v is None): + raise ValueError("edges need both u and v") + if u is None and edge_attrs: + raise ValueError("edge attributes were given without edges") + + def types(columns, given) -> dict[str, AttributeType]: + unknown = sorted(set(given or {}) - set(columns)) + if unknown: + raise ValueError(f"types were given for {unknown}, which have no array") + out: dict[str, AttributeType] = {} + for name, column in columns.items(): + if given and name in given: + out[name] = given[name] + continue + column = np.asarray(column) + dtype = column.dtype.name + out[name] = dtype if column.ndim == 1 else Vec(dtype, column.shape[1]) + return out + + db = cls( + path, + position_attribute=position_attribute, + mode="w", + total_roi=total_roi, + node_attrs=types(node_attrs, node_types), + edge_attrs=types(edge_attrs, edge_types), + cell_size=cell_size, + ) + with db.bulk_write_mode(): + db.write_node_arrays(np.asarray(ids), **node_attrs) + if u is not None and v is not None: + db.write_edge_arrays(u, v, **edge_attrs) + return db + # -- metadata ----------------------------------------------------------- def _write_meta(self) -> None: @@ -323,6 +398,14 @@ def num_nodes(self) -> int: def num_edges(self) -> int: return self.meta["num_edges"] + @property + def digest(self) -> str: + """What identifies the content of the database: the sha256 of its + ``meta.json``, which names the set of arrays last built. It changes + with every :meth:`finalize` that had something to merge, and is the + same for every copy of the directory.""" + return hashlib.sha256((self.path / "meta.json").read_bytes()).hexdigest() + def close(self) -> None: for segment in self._segments.values(): segment.close() @@ -859,10 +942,16 @@ def read_arrays( num_steps: int = 0, node_attrs: list[str] | None = None, edge_attrs: list[str] | None = None, + step_edges: Sequence[str] | None = None, ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: """The nodes in ``roi``, every node within ``num_steps`` edges of them, and the edges among those nodes, as arrays. + ``step_edges`` names the edge attributes that make an edge a step: + an edge is followed when any of them is set on it (not NaN). Left + out, every edge is followed. The edges returned are all those among + the nodes read, whichever were followed. + Returns ``(nodes, edges)``. ``nodes`` has ``id``, ``step`` (0 for a node in the region, else the step that first reached it) and the requested attributes; ``edges`` has ``u``, ``v`` (ids, ``u < v``, @@ -873,6 +962,9 @@ def read_arrays( edge_attrs = list(self.meta["edge_attrs"]) if edge_attrs is None else edge_attrs if arrays is None: arrays = self._empty() + for name in step_edges or (): + if name not in self.meta["edge_attrs"]: + raise ValueError(f"unknown edge attribute {name!r}") indptr, nbr = arrays["indptr"], arrays["nbr"] selected = self._rows_in(arrays, roi) step = np.zeros(len(selected), dtype=np.int16) @@ -881,6 +973,11 @@ def read_arrays( if len(frontier) == 0: break at, _ = _gather(indptr, frontier) + if step_edges: + followed = np.zeros(len(at), dtype=bool) + for name in step_edges: + followed |= self._present(np.asarray(arrays[f"edge_{name}"][at])) + at = at[followed] reached = np.unique(np.asarray(nbr[at])) frontier = reached[~np.isin(reached, selected, assume_unique=True)] if len(frontier) == 0: @@ -906,6 +1003,57 @@ def read_arrays( edges[name] = np.asarray(arrays[f"edge_{name}"][at[once]]) return nodes, edges + def read_block( + self, + roi: Roi, + context: Sequence[float] | float | None = None, + num_steps: int = 0, + node_attrs: list[str] | None = None, + edge_attrs: list[str] | None = None, + step_edges: Sequence[str] | None = None, + ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: + """A block with its surroundings, as arrays: what a computation that + writes one value per node of ``roi`` reads. + + The block's own nodes are those inside ``roi``. The surroundings + are every node within ``context`` of the box (one distance or one + per dimension, rounded up to whole units), and every node within + ``num_steps`` edges of any of those, wherever it lies. + + Returns ``(nodes, edges)`` as :meth:`read_arrays` does, with one more + array in ``nodes``: ``own``, true for the nodes inside ``roi``. + """ + if num_steps < 0: + raise ValueError("num_steps must be >= 0") + wanted = list(self.meta["node_attrs"]) if node_attrs is None else node_attrs + if context is None: + nodes, edges = self.read_arrays( + roi, num_steps, wanted, edge_attrs, step_edges + ) + nodes["own"] = nodes["step"] == 0 + return nodes, edges + grow = np.ceil(np.broadcast_to(np.asarray(context, dtype=float), (self.ndims,))) + if (grow < 0).any(): + raise ValueError("context must be >= 0") + amount = Coordinate(int(g) for g in grow) + position = self.position_attribute + nodes, edges = self.read_arrays( + roi.grow(amount, amount), + num_steps, + list(dict.fromkeys([*wanted, position])), + edge_attrs, + step_edges, + ) + at = np.asarray(nodes[position], dtype=float).reshape(len(nodes["id"]), -1) + own = nodes["step"] == 0 + bounds = self._bounds(roi) + if bounds is not None: + own &= ((at >= bounds[0]) & (at < bounds[1])).all(axis=1) + nodes["own"] = own + if position not in wanted: + del nodes[position] + return nodes, edges + def _empty(self) -> dict[str, np.ndarray]: out = { "ids": np.zeros(0, dtype=ID_DTYPE), diff --git a/src/funlib/persistence/graphs/node_arrays.py b/src/funlib/persistence/graphs/node_arrays.py new file mode 100644 index 0000000..696263f --- /dev/null +++ b/src/funlib/persistence/graphs/node_arrays.py @@ -0,0 +1,277 @@ +"""Node attributes in plain arrays beside the graph they belong to. + +Values computed on a graph (an embedding, a score, a label per node) do not +have to go into the graph database: the graph stays as it is, and a +64-vector per node would outweigh the graph it describes. They are stored +on their own, as memory-mapped arrays keyed by node id, and name the graph +they were computed on by its digest +(:attr:`~funlib.persistence.graphs.CSRGraphDataBase.digest`):: + + /meta.json version, num_nodes, attrs, graph_digest, source + /ids.npy uint64 (N,) node ids, in stored order + /order.npy int64 (N,) argsort of ids + /node_.npy (N,) or (N, k) + +``attrs`` maps each attribute to ``{"dtype": " str: + return f"node_{name}.npy" + + +class NodeArrays: + """Stored node attributes, memory-mapped and read by node id.""" + + def __init__(self, path: Path | str): + self.path = Path(path) + meta = self.path / META + if not meta.is_file(): + raise FileNotFoundError( + f"{self.path} holds no {META}: not a node attribute store" + ) + self.meta: dict[str, Any] = json.loads(meta.read_text()) + if self.meta.get("version") != FORMAT_VERSION: + raise ValueError( + f"{self.path}: node attribute store version " + f"{self.meta.get('version')!r}, this reader knows {FORMAT_VERSION}" + ) + self._arrays: dict[str, np.ndarray] = {} + + @property + def num_nodes(self) -> int: + return int(self.meta["num_nodes"]) + + @property + def attrs(self) -> dict[str, int | None]: + """Attribute name to vector length (None for a scalar).""" + return { + name: (spec["size"] or None) for name, spec in self.meta["attrs"].items() + } + + @property + def graph_digest(self) -> str | None: + """The digest of the graph the values were computed on.""" + return self.meta.get("graph_digest") + + @property + def source(self) -> str | None: + return self.meta.get("source") + + def _load(self, file: str) -> np.ndarray: + if file not in self._arrays: + self._arrays[file] = np.load(self.path / file, mmap_mode="r") + return self._arrays[file] + + @property + def ids(self) -> np.ndarray: + """Every stored node id, in stored order.""" + return self._load("ids.npy") + + def array(self, name: str) -> np.ndarray: + """One attribute of every node, memory-mapped, aligned with + :attr:`ids`.""" + if name not in self.meta["attrs"]: + raise KeyError( + f"{self.path} holds no attribute {name!r}; it holds " + f"{sorted(self.meta['attrs'])}" + ) + return self._load(_file(name)) + + def rows(self, ids: Any) -> tuple[np.ndarray, np.ndarray]: + """Where each of ``ids`` is stored: ``(found, rows)``; a row is + only meaningful where ``found``.""" + ids = np.asarray(ids, dtype=np.uint64) + order = self._load("order.npy") + stored = self.ids + if len(order) == 0: + return np.zeros(len(ids), dtype=bool), np.zeros(len(ids), dtype=np.int64) + # ``order`` sorts the stored ids, so the search probes log(N) of + # them per id and never reads the whole array + lo = np.searchsorted(stored, ids, sorter=order) + at = np.minimum(lo, len(order) - 1) + rows = np.asarray(order[at], dtype=np.int64) + found = (lo < len(order)) & (np.asarray(stored[rows]) == ids) + return found, rows + + def read( + self, ids: Any, attrs: Sequence[str] | None = None + ) -> tuple[np.ndarray, dict[str, np.ndarray]]: + """The attributes of the nodes ``ids``, in their order. + + Returns ``(found, values)``. A node that was never written is not + ``found`` and reads as NaN (0 for an integer attribute). + """ + names = list(self.meta["attrs"]) if attrs is None else list(attrs) + found, rows = self.rows(ids) + # gather in row order, so a block's read walks the file forwards + where = np.flatnonzero(found) + walk = where[np.argsort(rows[where], kind="stable")] + values: dict[str, np.ndarray] = {} + for name in names: + stored = self.array(name) + fill = np.nan if stored.dtype.kind == "f" else 0 + out = np.full((len(found), *stored.shape[1:]), fill, dtype=stored.dtype) + out[walk] = stored[rows[walk]] + values[name] = out + return found, values + + +class NodeArraysWriter: + """Writes a node attribute store a block at a time. + + :: + + with NodeArraysWriter(path, {"embedding": 64}, graph_digest=d) as out: + for ids, embedding in blocks: + out.append(ids, embedding=embedding) + + The store appears at ``path`` only when the block is left without an + error; until then it is a ``.partial`` directory beside it, which an + error leaves behind for inspection and the next writer removes. + """ + + def __init__( + self, + path: Path | str, + attrs: Mapping[str, int | None], + *, + dtypes: Mapping[str, Any] | None = None, + graph_digest: str | None = None, + source: str | None = None, + ): + self.path = Path(path) + self.attrs = dict(attrs) + if not self.attrs: + raise ValueError("a node attribute store holds at least one attribute") + self.dtypes = { + name: np.dtype((dtypes or {}).get(name, "float32")).newbyteorder("<") + for name in self.attrs + } + for name, dtype in self.dtypes.items(): + if dtype.kind not in "fiub": + raise ValueError(f"attribute {name!r}: {dtype} is not a number type") + self.graph_digest = graph_digest + self.source = source + self.num_nodes = 0 + self._partial = self.path.with_name(self.path.name + ".partial") + self._files: dict[str, Any] = {} + + def __enter__(self) -> NodeArraysWriter: + if self._partial.exists(): + shutil.rmtree(self._partial) + self._partial.mkdir(parents=True) + for name in ("ids", *self.attrs): + self._files[name] = open(self._partial / f"{name}.raw", "wb") + return self + + def append(self, ids: Any, **values: Any) -> None: + """Add nodes: their ids and one array per attribute, aligned.""" + ids = np.ascontiguousarray(ids, dtype=" None: + for file in self._files.values(): + file.close() + if kind is not None: + return + self._finish("ids", "ids.npy", np.dtype(" 1 and (np.diff(np.asarray(ids)[order]) == 0).any(): + raise ValueError( + f"{self.path}: a node id was written twice; a node belongs to one block" + ) + np.save(self._partial / "order.npy", order) + meta = { + "version": FORMAT_VERSION, + "num_nodes": self.num_nodes, + "attrs": { + name: {"dtype": self.dtypes[name].str, "size": length or 0} + for name, length in self.attrs.items() + }, + "graph_digest": self.graph_digest, + "source": self.source, + } + (self._partial / META).write_text(json.dumps(meta, indent=2) + "\n") + if self.path.exists(): + shutil.rmtree(self.path) + os.replace(self._partial, self.path) + + +def write_node_arrays( + path: Path | str, + ids: Any, + values: Mapping[str, Any], + *, + graph_digest: str | None = None, + source: str | None = None, +) -> Path: + """Write node attributes that are in memory as one store.""" + arrays = {name: np.asarray(value) for name, value in values.items()} + attrs = { + name: (None if value.ndim == 1 else int(value.shape[1])) + for name, value in arrays.items() + } + dtypes = {name: value.dtype for name, value in arrays.items()} + with NodeArraysWriter( + path, attrs, dtypes=dtypes, graph_digest=graph_digest, source=source + ) as out: + out.append(ids, **arrays) + return Path(path) diff --git a/tests/test_csr_graph_database.py b/tests/test_csr_graph_database.py index 127a58a..9a24600 100644 --- a/tests/test_csr_graph_database.py +++ b/tests/test_csr_graph_database.py @@ -261,3 +261,156 @@ def test_a_region_of_empty_cells_inside_the_graph_holds_nothing(tmp_path, steps) assert len(nodes["id"]) == 0 assert nodes["position"].shape == (0, 3) assert len(edges["u"]) == 0 + + +def test_from_arrays_writes_a_whole_graph_in_the_dtypes_of_its_arrays(tmp_path): + ids, pos, size, u, v, adj, lr = random_graph() + vectors = np.arange(len(ids) * 2, dtype=np.float32).reshape(-1, 2) + db = CSRGraphDataBase.from_arrays( + tmp_path / "g.csr", + ids, + {"position": pos, "size": size, "vec": vectors}, + u, + v, + {"adj": adj, "lr": lr}, + cell_size=40.0, + ) + assert (db.num_nodes, db.num_edges) == (len(ids), len(u)) + assert db.node_attrs == { + "position": Vec("float64", 3), + "size": "int64", + "vec": Vec("float32", 2), + } + assert db.edge_attrs == {"adj": "float32", "lr": "float32"} + nodes, edges = CSRGraphDataBase(tmp_path / "g.csr").read_arrays() + order = np.argsort(ids) + back = np.argsort(nodes["id"]) + assert nodes["id"][back].tolist() == ids[order].tolist() + assert nodes["vec"][back].tolist() == vectors[order].tolist() + assert sorted(zip(edges["u"].tolist(), edges["v"].tolist(), strict=True)) == sorted( + zip(u.tolist(), v.tolist(), strict=True) + ) + + +def test_from_arrays_stores_an_attribute_in_the_type_named_for_it(tmp_path): + ids, pos, size, u, v, adj, _ = random_graph(n=50, m=100) + db = CSRGraphDataBase.from_arrays( + tmp_path / "g.csr", + ids, + {"position": pos, "size": size}, + u, + v, + {"adj": adj.astype(np.float64)}, + cell_size=40.0, + node_types={"size": "int32"}, + edge_types={"adj": "float32"}, + ) + assert db.node_attrs["size"] == "int32" and db.edge_attrs == {"adj": "float32"} + # written again, it replaces what was there + again = CSRGraphDataBase.from_arrays( + tmp_path / "g.csr", ids[:5], {"position": pos[:5]}, cell_size=40.0 + ) + assert (again.num_nodes, again.num_edges) == (5, 0) + + +@pytest.mark.parametrize( + "kwargs, match", + [ + ({"u": np.array([1], dtype=np.uint64)}, "both u and v"), + ({"edge_attrs": {"adj": np.zeros(1)}}, "without edges"), + ({"node_types": {"nope": "int32"}}, r"types were given for \['nope'\]"), + ], +) +def test_from_arrays_refuses_arguments_that_do_not_fit(tmp_path, kwargs, match): + ids, pos, *_ = random_graph(n=10, m=10) + with pytest.raises(ValueError, match=match): + CSRGraphDataBase.from_arrays( + tmp_path / "g.csr", ids, {"position": pos}, cell_size=40.0, **kwargs + ) + + +def chain(tmp_path): + """Nodes 1..6 on a line, 10 apart; 1-2-3-4-5-6 joined by ``adj``, and a + long edge 1-6 that carries only ``lr``.""" + ids = np.arange(1, 7, dtype=np.uint64) + pos = np.stack([np.zeros(6), np.zeros(6), np.arange(6) * 10.0 + 5], axis=1) + u = np.array([1, 2, 3, 4, 5, 1], dtype=np.uint64) + v = np.array([2, 3, 4, 5, 6, 6], dtype=np.uint64) + adj = np.array([0.1, 0.2, 0.3, 0.4, 0.5, np.nan], dtype=np.float32) + lr = np.array([np.nan] * 5 + [0.9], dtype=np.float32) + return CSRGraphDataBase.from_arrays( + tmp_path / "chain.csr", + ids, + {"position": pos}, + u, + v, + {"adj": adj, "lr": lr}, + cell_size=10.0, + ) + + +def test_steps_follow_only_the_edges_named(tmp_path): + db = chain(tmp_path) + first = Roi((-5, -5, 0), (10, 10, 10)) # node 1 alone + every, _ = db.read_arrays(first, num_steps=1) + assert sorted(every["id"].tolist()) == [1, 2, 6] + adj, edges = db.read_arrays(first, num_steps=1, step_edges=["adj"]) + assert sorted(adj["id"].tolist()) == [1, 2] + lr, _ = db.read_arrays(first, num_steps=1, step_edges=["lr"]) + assert sorted(lr["id"].tolist()) == [1, 6] + either, edges = db.read_arrays(first, num_steps=1, step_edges=["adj", "lr"]) + assert sorted(either["id"].tolist()) == [1, 2, 6] + # the edges among the nodes read are returned, followed or not + two, edges = db.read_arrays(first, num_steps=5, step_edges=["adj"]) + assert len(two["id"]) == 6 and len(edges["u"]) == 6 + with pytest.raises(ValueError, match="unknown edge attribute 'nope'"): + db.read_arrays(first, num_steps=1, step_edges=["nope"]) + + +def test_read_block_marks_the_nodes_of_the_block_among_its_surroundings(tmp_path): + db = chain(tmp_path) + block = Roi((-5, -5, 20), (10, 10, 20)) # nodes 3 and 4 + + def own(nodes): + return sorted(nodes["id"][nodes["own"]].tolist()) + + alone, edges = db.read_block(block) + assert sorted(alone["id"].tolist()) == own(alone) == [3, 4] + assert len(edges["u"]) == 1 + + near, edges = db.read_block(block, context=[0, 0, 10], node_attrs=[]) + assert sorted(near["id"].tolist()) == [2, 3, 4, 5] and own(near) == [3, 4] + assert "position" not in near and len(edges["u"]) == 3 + + stepped, _ = db.read_block(block, num_steps=1, step_edges=["adj"]) + assert sorted(stepped["id"].tolist()) == [2, 3, 4, 5] and own(stepped) == [3, 4] + + # steps start from the nodes the context reached + both, _ = db.read_block(block, context=10.0, num_steps=1) + assert sorted(both["id"].tolist()) == [1, 2, 3, 4, 5, 6] and own(both) == [3, 4] + assert both["step"][both["id"] == 2].tolist() == [0] + + with pytest.raises(ValueError, match="num_steps must be >= 0"): + db.read_block(block, num_steps=-1) + with pytest.raises(ValueError, match="context must be >= 0"): + db.read_block(block, context=-1) + + +def test_a_database_is_told_from_other_directories_and_names_its_content(tmp_path): + db = chain(tmp_path) + assert CSRGraphDataBase.is_database(db.path) + assert not CSRGraphDataBase.is_database(tmp_path) + assert not CSRGraphDataBase.is_database(tmp_path / "missing") + other = tmp_path / "other" + other.mkdir() + (other / "meta.json").write_text('{"version": 1}') + assert not CSRGraphDataBase.is_database(other) + (other / "meta.json").write_text("not json") + assert not CSRGraphDataBase.is_database(other) + + before = db.digest + assert CSRGraphDataBase(db.path).digest == before + db.write_node_arrays( + np.array([7], dtype=np.uint64), position=np.array([[0.0, 0.0, 65.0]]) + ) + assert db.digest != before diff --git a/tests/test_node_arrays.py b/tests/test_node_arrays.py new file mode 100644 index 0000000..4060a4f --- /dev/null +++ b/tests/test_node_arrays.py @@ -0,0 +1,133 @@ +"""Node attributes stored in arrays beside the graph they were computed on.""" + +import json + +import numpy as np +import pytest + +from funlib.persistence.graphs import NodeArrays, NodeArraysWriter, write_node_arrays + +IDS = np.array([40, 7, 19, 3, 88], dtype=np.uint64) +VECTORS = np.arange(15, dtype=np.float32).reshape(5, 3) +SCORES = np.array([0.5, 0.25, 0.75, 1.0, 0.0], dtype=np.float32) + + +def stored(tmp_path, **kwargs): + return NodeArrays( + write_node_arrays( + tmp_path / "out.nodes", IDS, {"vec": VECTORS, "score": SCORES}, **kwargs + ) + ) + + +def test_values_read_back_in_the_order_the_ids_are_asked_for(tmp_path): + found, values = stored(tmp_path).read([3, 88, 40]) + assert found.tolist() == [True, True, True] + assert values["vec"].tolist() == VECTORS[[3, 4, 0]].tolist() + assert values["score"].tolist() == [1.0, 0.0, 0.5] + + +def test_a_node_that_was_never_written_is_not_found_and_reads_as_nan(tmp_path): + found, values = stored(tmp_path).read([7, 5, 1000], attrs=["score"]) + assert found.tolist() == [True, False, False] + assert values["score"][0] == 0.25 + assert np.isnan(values["score"][1:]).all() + + +def test_a_read_names_the_attributes_it_wants(tmp_path): + _, values = stored(tmp_path).read([7], attrs=["vec"]) + assert list(values) == ["vec"] + + +def test_an_unknown_attribute_is_refused_with_the_ones_stored(tmp_path): + with pytest.raises(KeyError, match=r"no attribute 'nope'.*\['score', 'vec'\]"): + stored(tmp_path).read([7], attrs=["nope"]) + + +def test_the_store_says_what_it_holds_and_which_graph_it_belongs_to(tmp_path): + arrays = stored(tmp_path, graph_digest="abc", source="fragments") + assert arrays.num_nodes == 5 + assert arrays.attrs == {"vec": 3, "score": None} + assert arrays.graph_digest == "abc" + assert arrays.source == "fragments" + assert arrays.ids.tolist() == IDS.tolist() + + +def test_the_layout_on_disk_is_plain_npy_files_and_a_meta_json(tmp_path): + path = stored(tmp_path).path + assert sorted(p.name for p in path.iterdir()) == [ + "ids.npy", + "meta.json", + "node_score.npy", + "node_vec.npy", + "order.npy", + ] + assert np.load(path / "order.npy").tolist() == np.argsort(IDS).tolist() + assert np.load(path / "node_vec.npy").shape == (5, 3) + assert json.loads((path / "meta.json").read_text())["attrs"] == { + "vec": {"dtype": " Date: Wed, 25 Nov 2026 11:39:37 -0800 Subject: [PATCH 02/15] Bump version to 0.9.3 Co-Authored-By: Claude Fable 5.2 --- src/funlib/persistence/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/funlib/persistence/__init__.py b/src/funlib/persistence/__init__.py index 591af6d..49d80b7 100644 --- a/src/funlib/persistence/__init__.py +++ b/src/funlib/persistence/__init__.py @@ -1,4 +1,4 @@ from .arrays import Array, open_ds, prepare_ds, open_ome_ds, prepare_ome_ds # noqa -__version__ = "0.9.1" +__version__ = "0.9.3" __version_info__ = tuple(int(i) for i in __version__.split(".")) From ac1a2decbc8dfd87cd5197925c6dc6f628f1302b Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 13:17:14 -0800 Subject: [PATCH 03/15] Version 0.9.2, not 0.9.3 No 0.9.2 was released; this is the next release after 0.9.1. Co-Authored-By: Claude Fable 5.2 --- src/funlib/persistence/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/funlib/persistence/__init__.py b/src/funlib/persistence/__init__.py index 49d80b7..fc84ff8 100644 --- a/src/funlib/persistence/__init__.py +++ b/src/funlib/persistence/__init__.py @@ -1,4 +1,4 @@ from .arrays import Array, open_ds, prepare_ds, open_ome_ds, prepare_ome_ds # noqa -__version__ = "0.9.3" +__version__ = "0.9.2" __version_info__ = tuple(int(i) for i in __version__.split(".")) From a23476d9126a9a2fa60247ee58702894e295678e Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 13:17:36 -0800 Subject: [PATCH 04/15] Drop CSRGraphDataBase.digest and the store's graph_digest The digest was the sha256 of meta.json: it named one build, not the content, and nothing compared a recorded graph_digest with a database. The identity of a graph is its entry in the consumer's registry, which does not change once registered. The node attribute store keeps its free-form source metadata; a meta.json that still carries a graph_digest key reads as before. Co-Authored-By: Claude Fable 5.2 --- docs/source/graphs.md | 10 +++----- .../persistence/graphs/csr_graph_database.py | 9 ------- src/funlib/persistence/graphs/node_arrays.py | 25 ++++++------------- tests/test_csr_graph_database.py | 9 +------ tests/test_node_arrays.py | 6 ++--- 5 files changed, 14 insertions(+), 45 deletions(-) diff --git a/docs/source/graphs.md b/docs/source/graphs.md index 349af64..fd9e172 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -81,22 +81,18 @@ nodes, edges = db.read_block(roi, context=500, num_steps=2) values = compute(nodes, edges)[nodes["own"]] ``` -`CSRGraphDataBase.is_database(path)` tells such a directory from any other, -and `db.digest` identifies the content of the database. +`CSRGraphDataBase.is_database(path)` tells such a directory from any other. ## Values on the nodes of a graph Values computed on a graph, such as an embedding per node, can be kept beside the graph without rewriting it. A node attribute store is a -directory of memory-mapped arrays keyed by node id, and records the digest -of the graph the values belong to: +directory of memory-mapped arrays keyed by node id: ```python from funlib.persistence.graphs import NodeArrays, NodeArraysWriter -with NodeArraysWriter( - "embedding.nodes", {"embedding": 64}, graph_digest=db.digest -) as out: +with NodeArraysWriter("embedding.nodes", {"embedding": 64}) as out: for roi in blocks: nodes, edges = db.read_block(roi, num_steps=2) own = nodes["own"] diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 573fd16..23aaae2 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -23,7 +23,6 @@ from __future__ import annotations import fcntl -import hashlib import json import logging import os @@ -398,14 +397,6 @@ def num_nodes(self) -> int: def num_edges(self) -> int: return self.meta["num_edges"] - @property - def digest(self) -> str: - """What identifies the content of the database: the sha256 of its - ``meta.json``, which names the set of arrays last built. It changes - with every :meth:`finalize` that had something to merge, and is the - same for every copy of the directory.""" - return hashlib.sha256((self.path / "meta.json").read_bytes()).hexdigest() - def close(self) -> None: for segment in self._segments.values(): segment.close() diff --git a/src/funlib/persistence/graphs/node_arrays.py b/src/funlib/persistence/graphs/node_arrays.py index 696263f..13b76a6 100644 --- a/src/funlib/persistence/graphs/node_arrays.py +++ b/src/funlib/persistence/graphs/node_arrays.py @@ -3,11 +3,9 @@ Values computed on a graph (an embedding, a score, a label per node) do not have to go into the graph database: the graph stays as it is, and a 64-vector per node would outweigh the graph it describes. They are stored -on their own, as memory-mapped arrays keyed by node id, and name the graph -they were computed on by its digest -(:attr:`~funlib.persistence.graphs.CSRGraphDataBase.digest`):: +on their own, as memory-mapped arrays keyed by node id:: - /meta.json version, num_nodes, attrs, graph_digest, source + /meta.json version, num_nodes, attrs, source /ids.npy uint64 (N,) node ids, in stored order /order.npy int64 (N,) argsort of ids /node_.npy (N,) or (N, k) @@ -16,7 +14,8 @@ 0 for a scalar. Rows are in the order they were written: a writer that goes block by block over a spatially sorted graph leaves neighbours near each other on disk, so the read of a block touches few pages. A read is by -node id, through ``order``. +node id, through ``order``. ``source`` is free text that says where the +values come from; the store does not interpret it. """ from __future__ import annotations @@ -70,13 +69,9 @@ def attrs(self) -> dict[str, int | None]: name: (spec["size"] or None) for name, spec in self.meta["attrs"].items() } - @property - def graph_digest(self) -> str | None: - """The digest of the graph the values were computed on.""" - return self.meta.get("graph_digest") - @property def source(self) -> str | None: + """What the writer recorded about where the values come from.""" return self.meta.get("source") def _load(self, file: str) -> np.ndarray: @@ -143,7 +138,7 @@ class NodeArraysWriter: :: - with NodeArraysWriter(path, {"embedding": 64}, graph_digest=d) as out: + with NodeArraysWriter(path, {"embedding": 64}) as out: for ids, embedding in blocks: out.append(ids, embedding=embedding) @@ -158,7 +153,6 @@ def __init__( attrs: Mapping[str, int | None], *, dtypes: Mapping[str, Any] | None = None, - graph_digest: str | None = None, source: str | None = None, ): self.path = Path(path) @@ -172,7 +166,6 @@ def __init__( for name, dtype in self.dtypes.items(): if dtype.kind not in "fiub": raise ValueError(f"attribute {name!r}: {dtype} is not a number type") - self.graph_digest = graph_digest self.source = source self.num_nodes = 0 self._partial = self.path.with_name(self.path.name + ".partial") @@ -246,7 +239,6 @@ def __exit__(self, kind: Any, *_: Any) -> None: name: {"dtype": self.dtypes[name].str, "size": length or 0} for name, length in self.attrs.items() }, - "graph_digest": self.graph_digest, "source": self.source, } (self._partial / META).write_text(json.dumps(meta, indent=2) + "\n") @@ -260,7 +252,6 @@ def write_node_arrays( ids: Any, values: Mapping[str, Any], *, - graph_digest: str | None = None, source: str | None = None, ) -> Path: """Write node attributes that are in memory as one store.""" @@ -270,8 +261,6 @@ def write_node_arrays( for name, value in arrays.items() } dtypes = {name: value.dtype for name, value in arrays.items()} - with NodeArraysWriter( - path, attrs, dtypes=dtypes, graph_digest=graph_digest, source=source - ) as out: + with NodeArraysWriter(path, attrs, dtypes=dtypes, source=source) as out: out.append(ids, **arrays) return Path(path) diff --git a/tests/test_csr_graph_database.py b/tests/test_csr_graph_database.py index 9a24600..f2e6285 100644 --- a/tests/test_csr_graph_database.py +++ b/tests/test_csr_graph_database.py @@ -396,7 +396,7 @@ def own(nodes): db.read_block(block, context=-1) -def test_a_database_is_told_from_other_directories_and_names_its_content(tmp_path): +def test_a_database_is_told_from_other_directories(tmp_path): db = chain(tmp_path) assert CSRGraphDataBase.is_database(db.path) assert not CSRGraphDataBase.is_database(tmp_path) @@ -407,10 +407,3 @@ def test_a_database_is_told_from_other_directories_and_names_its_content(tmp_pat assert not CSRGraphDataBase.is_database(other) (other / "meta.json").write_text("not json") assert not CSRGraphDataBase.is_database(other) - - before = db.digest - assert CSRGraphDataBase(db.path).digest == before - db.write_node_arrays( - np.array([7], dtype=np.uint64), position=np.array([[0.0, 0.0, 65.0]]) - ) - assert db.digest != before diff --git a/tests/test_node_arrays.py b/tests/test_node_arrays.py index 4060a4f..26ce384 100644 --- a/tests/test_node_arrays.py +++ b/tests/test_node_arrays.py @@ -44,12 +44,12 @@ def test_an_unknown_attribute_is_refused_with_the_ones_stored(tmp_path): stored(tmp_path).read([7], attrs=["nope"]) -def test_the_store_says_what_it_holds_and_which_graph_it_belongs_to(tmp_path): - arrays = stored(tmp_path, graph_digest="abc", source="fragments") +def test_the_store_says_what_it_holds_and_where_it_comes_from(tmp_path): + arrays = stored(tmp_path, source="fragments") assert arrays.num_nodes == 5 assert arrays.attrs == {"vec": 3, "score": None} - assert arrays.graph_digest == "abc" assert arrays.source == "fragments" + assert "graph_digest" not in arrays.meta assert arrays.ids.tolist() == IDS.tolist() From 0862d3591a2431949ac701ae70fda3ba728f7628 Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 13:19:13 -0800 Subject: [PATCH 05/15] from_arrays: check the arrays first, build beside the path, replace at the end A call that failed left the database that was at the path empty or gone: mode 'w' removed it before the attribute types were converted, and before any array was looked at. Now every array is checked against the node or edge count before anything is written (an array of length 1 was broadcast over the whole graph), the database is built in a scratch directory beside the path, and it replaces the path only when complete. The constructor in mode 'w' converts every attribute type before it removes what is there. A text array raises NotImplementedError, as the constructor does, not numpy's TypeError. Review findings 2 and 3. Co-Authored-By: Claude Fable 5.2 --- src/funlib/persistence/graphs/_files.py | 40 +++++++ .../persistence/graphs/csr_graph_database.py | 109 +++++++++++++----- tests/test_csr_graph_database.py | 105 +++++++++++++++++ 3 files changed, 224 insertions(+), 30 deletions(-) create mode 100644 src/funlib/persistence/graphs/_files.py diff --git a/src/funlib/persistence/graphs/_files.py b/src/funlib/persistence/graphs/_files.py new file mode 100644 index 0000000..92c89f8 --- /dev/null +++ b/src/funlib/persistence/graphs/_files.py @@ -0,0 +1,40 @@ +"""File system steps shared by the stores that are directories of arrays.""" + +from __future__ import annotations + +import errno +import os +import shutil +import uuid +from pathlib import Path + + +def scratch_beside(path: Path, what: str) -> Path: + """A directory name beside ``path`` that no other writer uses.""" + return path.with_name(f"{path.name}.{what}-{uuid.uuid4().hex}") + + +def replace_directory(new: Path, path: Path) -> None: + """Put the directory ``new`` at ``path``, removing what is there. + + What was at ``path`` is moved aside before ``new`` is moved in, so + ``path`` never holds a mix of the two; for the instant between the two + moves it does not exist. Several processes may replace one path at + once: each of them succeeds in turn and the last one stays. + """ + while True: + try: + os.rename(new, path) # succeeds onto nothing or an empty directory + return + except OSError as error: + if error.errno not in (errno.ENOTEMPTY, errno.EEXIST, errno.ENOTDIR): + raise + old = scratch_beside(path, "old") + try: + os.rename(path, old) + except FileNotFoundError: + continue # another process moved it aside first + if old.is_dir() and not old.is_symlink(): + shutil.rmtree(old, ignore_errors=True) + else: + old.unlink() diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 23aaae2..3991cbe 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -38,6 +38,7 @@ from networkx import Graph from ..types import Vec +from ._files import replace_directory, scratch_beside from .graph_database import AttributeType, GraphDataBase logger = logging.getLogger(__name__) @@ -238,6 +239,9 @@ def __init__( if cell_size is None: raise ValueError("cell_size is required to create a CSR database") sizes = np.broadcast_to(np.asarray(cell_size, dtype=float), (ndims,)) + # every argument is checked before what is at the path is removed + node_specs = {k: _spec(v) for k, v in node_attrs.items()} + edge_specs = {k: _spec(v) for k, v in (edge_attrs or {}).items()} if self.path.exists(): shutil.rmtree(self.path) self.path.mkdir(parents=True) @@ -245,8 +249,8 @@ def __init__( "version": FORMAT_VERSION, "position_attribute": position_attribute, "ndims": ndims, - "node_attrs": {k: _spec(v) for k, v in node_attrs.items()}, - "edge_attrs": {k: _spec(v) for k, v in (edge_attrs or {}).items()}, + "node_attrs": node_specs, + "edge_attrs": edge_specs, "cell_size": sizes.tolist(), "total_roi": None if total_roi is None @@ -323,46 +327,91 @@ def from_arrays( ``ids`` are the node ids, ``node_attrs`` one array per node attribute (the position among them), ``u`` and ``v`` the endpoint ids of the - edges and ``edge_attrs`` one array per edge attribute. + edges and ``edge_attrs`` one array per edge attribute. Every array + has one entry per node, or per edge: an array of another length is + refused, a single value is not spread over the graph. An attribute is stored in the dtype of its array, a 2-D array as a vector, unless ``node_types`` or ``edge_types`` names another type for it; the array is cast to that type. + + The database is built in a directory beside ``path`` and moved to + ``path`` when it is complete. A call that fails, for whatever + reason, leaves what was at ``path`` as it was. """ - edge_attrs = dict(edge_attrs or {}) + path = Path(path) + ids = np.asarray(ids) + if ids.ndim != 1: + raise ValueError(f"ids has shape {ids.shape}; expected one id per node") if (u is None) != (v is None): raise ValueError("edges need both u and v") if u is None and edge_attrs: raise ValueError("edge attributes were given without edges") + num_edges = 0 + if u is not None and v is not None: + u, v = np.asarray(u), np.asarray(v) + if u.ndim != 1 or u.shape != v.shape: + raise ValueError( + f"u and v have shapes {u.shape} and {v.shape}; expected one " + "entry per edge in each" + ) + num_edges = len(u) - def types(columns, given) -> dict[str, AttributeType]: - unknown = sorted(set(given or {}) - set(columns)) + def columns(what, given, count, named) -> tuple[dict, dict]: + arrays = {name: np.asarray(a) for name, a in (given or {}).items()} + unknown = sorted(set(named or {}) - set(arrays)) if unknown: raise ValueError(f"types were given for {unknown}, which have no array") - out: dict[str, AttributeType] = {} - for name, column in columns.items(): - if given and name in given: - out[name] = given[name] - continue - column = np.asarray(column) - dtype = column.dtype.name - out[name] = dtype if column.ndim == 1 else Vec(dtype, column.shape[1]) - return out - - db = cls( - path, - position_attribute=position_attribute, - mode="w", - total_roi=total_roi, - node_attrs=types(node_attrs, node_types), - edge_attrs=types(edge_attrs, edge_types), - cell_size=cell_size, - ) - with db.bulk_write_mode(): - db.write_node_arrays(np.asarray(ids), **node_attrs) - if u is not None and v is not None: - db.write_edge_arrays(u, v, **edge_attrs) - return db + types: dict[str, AttributeType] = {} + for name, array in arrays.items(): + if array.ndim not in (1, 2) or len(array) != count: + raise ValueError( + f"{what} attribute {name!r} has shape {array.shape}; " + f"expected one entry for each of the {count} {what}s" + ) + if named and name in named: + types[name] = named[name] + elif array.dtype.kind not in "fiub": + raise NotImplementedError( + f"{what} attribute {name!r}: attributes of type " + f"{array.dtype} are not supported by the CSR backend" + ) + elif array.ndim == 1: + types[name] = array.dtype.name + else: + types[name] = Vec(array.dtype.name, array.shape[1]) + size = _spec(types[name])["size"] + if (array.shape[1] if array.ndim == 2 else 0) != size: + raise ValueError( + f"{what} attribute {name!r} has shape {array.shape}, which " + f"does not fit its type {types[name]}" + ) + return arrays, types + + node_arrays, node_kinds = columns("node", node_attrs, len(ids), node_types) + edge_arrays, edge_kinds = columns("edge", edge_attrs, num_edges, edge_types) + + scratch = scratch_beside(path, "writing") + try: + db = cls( + scratch, + position_attribute=position_attribute, + mode="w", + total_roi=total_roi, + node_attrs=node_kinds, + edge_attrs=edge_kinds, + cell_size=cell_size, + ) + with db.bulk_write_mode(): + db.write_node_arrays(ids, **node_arrays) + if u is not None and v is not None: + db.write_edge_arrays(u, v, **edge_arrays) + db.close() + except BaseException: + shutil.rmtree(scratch, ignore_errors=True) + raise + replace_directory(scratch, path) + return cls(path, mode="r+") # -- metadata ----------------------------------------------------------- diff --git a/tests/test_csr_graph_database.py b/tests/test_csr_graph_database.py index f2e6285..aebe36a 100644 --- a/tests/test_csr_graph_database.py +++ b/tests/test_csr_graph_database.py @@ -329,6 +329,111 @@ def test_from_arrays_refuses_arguments_that_do_not_fit(tmp_path, kwargs, match): ) +def one_per(n, dtype=np.float32): + return np.ones(n, dtype=dtype) + + +@pytest.mark.parametrize( + "change, error, match", + [ + # a text attribute cannot be stored (was a TypeError from numpy) + ( + {"node_attrs": {"name": np.array(["a"] * 10)}}, + NotImplementedError, + "node attribute 'name'.*not supported by the CSR backend", + ), + ({"node_types": {"size": str}}, NotImplementedError, "not supported"), + # an array that is not one entry per node or edge is not spread + ( + {"node_attrs": {"size": np.array([9])}}, + ValueError, + r"node attribute 'size' has shape \(1,\).*each of the 10 nodes", + ), + ( + {"node_attrs": {"size": np.arange(3)}}, + ValueError, + r"node attribute 'size' has shape \(3,\)", + ), + ( + {"edge_attrs": {"adj": one_per(1)}}, + ValueError, + r"edge attribute 'adj' has shape \(1,\).*each of the 9 edges", + ), + ({"node_attrs": {"size": np.int64(9)}}, ValueError, r"has shape \(\)"), + ({"v": np.arange(2, 5)}, ValueError, "u and v have shapes"), + ({"ids": np.ones((10, 1))}, ValueError, "ids has shape"), + ( + {"node_types": {"size": Vec(int, 2)}}, + ValueError, + "does not fit its type", + ), + # one that only fails while the arrays are built + ({"cell_size": 1e-6}, ValueError, "more grid cells than a Morton code"), + ], +) +def test_from_arrays_that_fails_keeps_the_database_that_was_there( + tmp_path, change, error, match +): + path = tmp_path / "g.csr" + ids = np.arange(1, 11, dtype=np.uint64) + pos = np.stack([np.zeros(10), np.zeros(10), np.arange(10) * 10.0], axis=1) + given = { + "ids": ids, + "node_attrs": {"position": pos, "size": np.arange(10)}, + "u": ids[:-1], + "v": ids[1:], + "edge_attrs": {"adj": one_per(9)}, + "cell_size": 10.0, + } + CSRGraphDataBase.from_arrays(path, **given) + for name, value in change.items(): + if name in ("node_attrs", "edge_attrs"): + given[name] = {**given[name], **value} + else: + given[name] = value + with pytest.raises(error, match=match): + CSRGraphDataBase.from_arrays(path, **given) + # the earlier graph is whole, and nothing is left beside it + before = CSRGraphDataBase(path) + assert (before.num_nodes, before.num_edges) == (10, 9) + nodes, edges = before.read_arrays() + assert sorted(nodes["size"].tolist()) == list(range(10)) + assert edges["adj"].tolist() == [1.0] * 9 + assert [p.name for p in tmp_path.iterdir()] == ["g.csr"] + + +def test_from_arrays_replaces_a_database_only_when_the_new_one_is_complete(tmp_path): + path = tmp_path / "deep" / "g.csr" + ids, pos, size, u, v, adj, _ = random_graph(n=50, m=100) + first = CSRGraphDataBase.from_arrays( + path, ids, {"position": pos, "size": size}, u, v, {"adj": adj}, cell_size=40.0 + ) + held = first.read_arrays()[0]["id"] + second = CSRGraphDataBase.from_arrays( + path, ids[:5], {"position": pos[:5]}, cell_size=40.0 + ) + assert second.path == path and second.mode == "r+" + assert (second.num_nodes, second.num_edges) == (5, 0) + assert second.node_attrs == {"position": Vec("float64", 3)} + assert len(held) == 50 # a read taken before the replacement stays valid + # the handle returned accepts further writes + second.write_node_arrays(ids[5:6], position=pos[5:6]) + assert CSRGraphDataBase(path).num_nodes == 6 + assert [p.name for p in path.parent.iterdir()] == ["g.csr"] + + +def test_a_database_is_not_removed_by_a_constructor_that_refuses_its_types(tmp_path): + db = chain(tmp_path) + with pytest.raises(NotImplementedError, match="not supported by the CSR backend"): + CSRGraphDataBase( + db.path, + mode="w", + node_attrs={"position": Vec(float, 3), "name": str}, + cell_size=10.0, + ) + assert CSRGraphDataBase(db.path).num_nodes == 6 + + def chain(tmp_path): """Nodes 1..6 on a line, 10 apart; 1-2-3-4-5-6 joined by ``adj``, and a long edge 1-6 that carries only ``lr``.""" From 235a049b21de4bc48d56baa098521312726ba078 Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 13:19:21 -0800 Subject: [PATCH 06/15] step_edges: an empty sequence follows no edge, a non-float attribute is refused; a negative context is refused before rounding step_edges=[] took the branch for None and followed every edge. An integer or bool attribute is present on every edge (0 is its unwritten value), so naming one also followed every edge: it now raises ValueError. read_block tested the sign of context after np.ceil, so -0.5 passed as 0. The read_block docstring says that step is 0 for the nodes the context reached. Review findings 4, 5 and 7, question 8. Co-Authored-By: Claude Fable 5.2 --- .../persistence/graphs/csr_graph_database.py | 24 ++++++++++---- tests/test_csr_graph_database.py | 32 +++++++++++++++++-- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 3991cbe..4996ce1 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -988,9 +988,12 @@ def read_arrays( them, and the edges among those nodes, as arrays. ``step_edges`` names the edge attributes that make an edge a step: - an edge is followed when any of them is set on it (not NaN). Left - out, every edge is followed. The edges returned are all those among - the nodes read, whichever were followed. + an edge is followed when any of them is set on it (not NaN). They + are float attributes: an integer or bool attribute has no unset + value and is refused. ``None`` follows every edge; an empty + sequence names no attribute, so no edge is followed. The edges + returned are all those among the nodes read, whichever were + followed. Returns ``(nodes, edges)``. ``nodes`` has ``id``, ``step`` (0 for a node in the region, else the step that first reached it) and the @@ -1005,6 +1008,12 @@ def read_arrays( for name in step_edges or (): if name not in self.meta["edge_attrs"]: raise ValueError(f"unknown edge attribute {name!r}") + dtype = np.dtype(self.meta["edge_attrs"][name]["dtype"]) + if dtype.kind != "f": + raise ValueError( + f"step_edges: edge attribute {name!r} is {dtype.name}; only " + "a float attribute can be unset on an edge" + ) indptr, nbr = arrays["indptr"], arrays["nbr"] selected = self._rows_in(arrays, roi) step = np.zeros(len(selected), dtype=np.int16) @@ -1013,7 +1022,7 @@ def read_arrays( if len(frontier) == 0: break at, _ = _gather(indptr, frontier) - if step_edges: + if step_edges is not None: followed = np.zeros(len(at), dtype=bool) for name in step_edges: followed |= self._present(np.asarray(arrays[f"edge_{name}"][at])) @@ -1062,6 +1071,8 @@ def read_block( Returns ``(nodes, edges)`` as :meth:`read_arrays` does, with one more array in ``nodes``: ``own``, true for the nodes inside ``roi``. + ``step`` is 0 for the block's own nodes and for those the context + reached; the steps are counted from there. """ if num_steps < 0: raise ValueError("num_steps must be >= 0") @@ -1072,9 +1083,10 @@ def read_block( ) nodes["own"] = nodes["step"] == 0 return nodes, edges - grow = np.ceil(np.broadcast_to(np.asarray(context, dtype=float), (self.ndims,))) - if (grow < 0).any(): + distance = np.broadcast_to(np.asarray(context, dtype=float), (self.ndims,)) + if not (distance >= 0).all(): # before rounding: ceil(-0.5) is -0 raise ValueError("context must be >= 0") + grow = np.ceil(distance) amount = Coordinate(int(g) for g in grow) position = self.position_attribute nodes, edges = self.read_arrays( diff --git a/tests/test_csr_graph_database.py b/tests/test_csr_graph_database.py index aebe36a..24fc290 100644 --- a/tests/test_csr_graph_database.py +++ b/tests/test_csr_graph_database.py @@ -470,6 +470,33 @@ def test_steps_follow_only_the_edges_named(tmp_path): assert len(two["id"]) == 6 and len(edges["u"]) == 6 with pytest.raises(ValueError, match="unknown edge attribute 'nope'"): db.read_arrays(first, num_steps=1, step_edges=["nope"]) + # no attribute named: no edge is a step (None is what follows every edge) + none, edges = db.read_arrays(first, num_steps=3, step_edges=[]) + assert none["id"].tolist() == [1] and len(edges["u"]) == 0 + none, _ = db.read_block(first, num_steps=3, step_edges=()) + assert none["id"].tolist() == [1] + + +def test_steps_cannot_be_named_by_an_attribute_that_is_never_unset(tmp_path): + # an integer reads 0 where it was never written, which is a value like + # any other: following "the edges that have it" would follow every edge + ids = np.arange(1, 4, dtype=np.uint64) + pos = np.stack([np.zeros(3), np.zeros(3), np.arange(3) * 10.0 + 5], axis=1) + db = CSRGraphDataBase.from_arrays( + tmp_path / "g.csr", + ids, + {"position": pos}, + ids[:-1], + ids[1:], + {"kind": np.array([1, 0], dtype=np.int8), "flag": np.array([True, False])}, + cell_size=10.0, + ) + first = Roi((-5, -5, 0), (10, 10, 10)) + for name, dtype in (("kind", "int8"), ("flag", "bool")): + with pytest.raises(ValueError, match=f"'{name}' is {dtype}; only a float"): + db.read_arrays(first, num_steps=1, step_edges=[name]) + with pytest.raises(ValueError, match="only a float"): + db.read_block(first, num_steps=1, step_edges=[name]) def test_read_block_marks_the_nodes_of_the_block_among_its_surroundings(tmp_path): @@ -497,8 +524,9 @@ def own(nodes): with pytest.raises(ValueError, match="num_steps must be >= 0"): db.read_block(block, num_steps=-1) - with pytest.raises(ValueError, match="context must be >= 0"): - db.read_block(block, context=-1) + for negative in (-1, -0.5, [0, 0, -0.25], float("nan")): + with pytest.raises(ValueError, match="context must be >= 0"): + db.read_block(block, context=negative) def test_a_database_is_told_from_other_directories(tmp_path): From 5514db92d3ef95d1d8b4f1ea85a463f0214fd1ac Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 13:20:38 -0800 Subject: [PATCH 07/15] read_arrays, read_block: edge_ends selects the edge rule of read_edges read_edges and read_graph return an edge when its smaller-id end is in the region (with fetch_on_v, when either end is), on every backend. read_arrays returned only the edges with both ends among the nodes read, so a caller that read a CSR database as arrays and a SQLite database through read_graph got different edges for one roi (e11bio/volara#111, finding 1). edge_ends='u' and edge_ends='either' give the array read the two rules of read_edges. The default, 'both', is the behaviour until now: callers index the node arrays by the edges returned, and an edge that names a node that was not read would break them. Co-Authored-By: Claude Fable 5.2 --- docs/source/graphs.md | 18 +++- .../persistence/graphs/csr_graph_database.py | 48 ++++++++-- tests/test_csr_graph_database.py | 96 +++++++++++++++++++ 3 files changed, 155 insertions(+), 7 deletions(-) diff --git a/docs/source/graphs.md b/docs/source/graphs.md index fd9e172..e6b3b0f 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -70,7 +70,23 @@ nodes, edges = db.read_arrays(Roi((0, 0, 0), (100, 100, 100)), num_steps=1) `read_arrays` returns the nodes in the ROI, every node within `num_steps` edges of them, and the edges among the nodes read. `step_edges` names the -edge attributes that make an edge a step. +float edge attributes that make an edge a step: an edge is followed when +one of them is set on it. + +By default an edge is returned when both of its ends are among the nodes +read, so the arrays are a graph on their own. That is not the rule of +`read_graph`, which also returns the edges that leave the ROI. +`edge_ends` selects the rule: + +| `edge_ends` | an edge is returned when | same edges as | +|---|---|---| +| `"both"` (default) | both ends are among the nodes read | | +| `"u"` | its smaller-id end is among the nodes read | `read_graph(roi)`, `read_edges(roi)` on every backend | +| `"either"` | at least one end is among the nodes read | `read_graph(roi, fetch_on_v=True)` | + +With `"u"` or `"either"` an edge can name a node whose attributes were not +read. Code that reads one backend as arrays and another through +`read_graph` asks for `edge_ends="u"` to get the same edges from both. `read_block` is the read of a computation that writes one value per node of a block: the nodes of the ROI, marked `own`, with the nodes within a diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 4996ce1..669a235 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -983,23 +983,48 @@ def read_arrays( node_attrs: list[str] | None = None, edge_attrs: list[str] | None = None, step_edges: Sequence[str] | None = None, + edge_ends: str = "both", ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: """The nodes in ``roi``, every node within ``num_steps`` edges of them, and the edges among those nodes, as arrays. + ``edge_ends`` says which ends of an edge have to be among the nodes + read for the edge to be returned: + + ``"both"`` (the default) + The edges among the nodes read. Every ``u`` and ``v`` is an + ``id`` in ``nodes``, so the result is a graph on its own. An + edge that leaves the nodes read is not returned. + ``"u"`` + The edges whose smaller-id end is among the nodes read: the + rule of :meth:`read_edges` and :meth:`read_graph`, here and in + the SQL backends. With ``num_steps=0`` the edges are those of + ``read_edges(roi)``. A block sees the edges that leave it, and + blocks that tile a graph see every edge once. + ``"either"`` + The edges with at least one end among the nodes read: the + rule of ``read_edges(roi, fetch_on_v=True)``. + + With ``"u"`` and ``"either"`` an edge can name a node that is not in + ``nodes``; its attributes were not read. + ``step_edges`` names the edge attributes that make an edge a step: an edge is followed when any of them is set on it (not NaN). They are float attributes: an integer or bool attribute has no unset value and is refused. ``None`` follows every edge; an empty - sequence names no attribute, so no edge is followed. The edges - returned are all those among the nodes read, whichever were - followed. + sequence names no attribute, so no edge is followed. Which edges + are returned is the matter of ``edge_ends`` alone, not of which + were followed. Returns ``(nodes, edges)``. ``nodes`` has ``id``, ``step`` (0 for a node in the region, else the step that first reached it) and the requested attributes; ``edges`` has ``u``, ``v`` (ids, ``u < v``, each edge once) and the requested attributes. All attributes are returned when none are named.""" + if edge_ends not in ("both", "u", "either"): + raise ValueError( + f"edge_ends is {edge_ends!r}; it is one of 'both', 'u', 'either'" + ) arrays = self._readable() node_attrs = list(self.meta["node_attrs"]) if node_attrs is None else node_attrs edge_attrs = list(self.meta["edge_attrs"]) if edge_attrs is None else edge_attrs @@ -1039,6 +1064,11 @@ def read_arrays( ] nodes = self._node_columns(arrays, selected, node_attrs) nodes["step"] = step + if edge_ends != "both": + # the rule of read_edges, applied to the nodes read + return nodes, self._edge_columns( + arrays, selected, edge_ends == "either", edge_attrs + ) at, owner = _gather(indptr, selected) other = np.asarray(nbr[at]) where = np.searchsorted(selected, other) @@ -1060,6 +1090,7 @@ def read_block( node_attrs: list[str] | None = None, edge_attrs: list[str] | None = None, step_edges: Sequence[str] | None = None, + edge_ends: str = "both", ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: """A block with its surroundings, as arrays: what a computation that writes one value per node of ``roi`` reads. @@ -1072,14 +1103,16 @@ def read_block( Returns ``(nodes, edges)`` as :meth:`read_arrays` does, with one more array in ``nodes``: ``own``, true for the nodes inside ``roi``. ``step`` is 0 for the block's own nodes and for those the context - reached; the steps are counted from there. + reached; the steps are counted from there. ``edge_ends`` is that of + :meth:`read_arrays`: it applies to all the nodes read, the + surroundings included. """ if num_steps < 0: raise ValueError("num_steps must be >= 0") wanted = list(self.meta["node_attrs"]) if node_attrs is None else node_attrs if context is None: nodes, edges = self.read_arrays( - roi, num_steps, wanted, edge_attrs, step_edges + roi, num_steps, wanted, edge_attrs, step_edges, edge_ends ) nodes["own"] = nodes["step"] == 0 return nodes, edges @@ -1095,6 +1128,7 @@ def read_block( list(dict.fromkeys([*wanted, position])), edge_attrs, step_edges, + edge_ends, ) at = np.asarray(nodes[position], dtype=float).reshape(len(nodes["id"]), -1) own = nodes["step"] == 0 @@ -1197,7 +1231,9 @@ def read_edges( fetch_on_v: bool = False, ) -> list[dict[str, Any]]: """Edges whose smaller endpoint (``u``) is in ``roi`` or in - ``nodes``; with ``fetch_on_v`` also those whose larger one is.""" + ``nodes``; with ``fetch_on_v`` also those whose larger one is. + :meth:`read_arrays` returns the same edges as arrays with + ``edge_ends="u"`` and ``edge_ends="either"``.""" if roi is not None and nodes is not None: raise ValueError( "read_edges does not support both roi and nodes at the same time. " diff --git a/tests/test_csr_graph_database.py b/tests/test_csr_graph_database.py index 24fc290..f6a512e 100644 --- a/tests/test_csr_graph_database.py +++ b/tests/test_csr_graph_database.py @@ -540,3 +540,99 @@ def test_a_database_is_told_from_other_directories(tmp_path): assert not CSRGraphDataBase.is_database(other) (other / "meta.json").write_text("not json") assert not CSRGraphDataBase.is_database(other) + + +def pairs(edges): + return sorted(zip(edges["u"].tolist(), edges["v"].tolist(), strict=True)) + + +@pytest.mark.parametrize( + "edge_ends, fetch_on_v", [("u", False), ("either", True)], ids=["u", "either"] +) +def test_an_array_read_returns_the_edges_read_graph_returns_from_sqlite( + tmp_path, edge_ends, fetch_on_v +): + """The scenario of volara#111: nodes 1 and 2 inside the roi, node 3 + outside, edges (1, 3) and (2, 3).""" + ids = np.array([1, 2, 3], dtype=np.uint64) + pos = np.array([[10.0, 10, 10], [30, 30, 30], [90, 90, 90]]) + u, v = np.array([1, 2], dtype=np.uint64), np.array([3, 3], dtype=np.uint64) + score = np.array([0.5, 0.75], dtype=np.float32) + roi = Roi((0, 0, 0), (50, 50, 50)) + + sqlite = SQLiteGraphDataBase( + tmp_path / "g.db", + position_attribute="position", + mode="w", + node_attrs={"position": Vec(float, 3)}, + edge_attrs={"score": float}, + ) + graph = nx.Graph() + graph.add_nodes_from( + (int(i), {"position": tuple(p)}) for i, p in zip(ids, pos.tolist(), strict=True) + ) + graph.add_edges_from( + (int(a), int(b), {"score": float(s)}) + for a, b, s in zip(u, v, score, strict=True) + ) + sqlite.write_graph(graph) + csr = CSRGraphDataBase.from_arrays( + tmp_path / "g.csr", ids, {"position": pos}, u, v, {"score": score}, cell_size=20 + ) + + def listed(db, region): + graph = db.read_graph(region, fetch_on_v=fetch_on_v) + return sorted((min(e), max(e)) for e in graph.edges) + + expected = listed(sqlite, roi) + assert expected == [(1, 3), (2, 3)] + assert listed(csr, roi) == expected + + nodes, edges = csr.read_arrays(roi, edge_ends=edge_ends) + assert sorted(nodes["id"].tolist()) == [1, 2] # node 3 is named, not read + assert pairs(edges) == expected + assert sorted(edges["score"].tolist()) == [0.5, 0.75] + nodes, edges = csr.read_block(roi, edge_ends=edge_ends) + assert pairs(edges) == expected and nodes["own"].all() + + # the default is unchanged: only the edges among the nodes read + assert pairs(csr.read_arrays(roi)[1]) == pairs(csr.read_block(roi)[1]) == [] + + # from the other side, node 3 is the larger end of both edges + outside = Roi((50, 50, 50), (50, 50, 50)) + expected = [(1, 3), (2, 3)] if fetch_on_v else [] + assert listed(sqlite, outside) == listed(csr, outside) == expected + assert pairs(csr.read_arrays(outside, edge_ends=edge_ends)[1]) == expected + + +@pytest.mark.parametrize("fetch_on_v", [False, True]) +def test_edge_ends_is_the_rule_of_read_edges_on_any_region(filled, fetch_on_v): + db, _ = filled + edge_ends = "either" if fetch_on_v else "u" + + def scored(edges): + order = np.lexsort((edges["v"], edges["u"])) + return dict(zip(pairs(edges), edges["adj"][order].tolist(), strict=True)) + + for roi in ( + Roi((0, 0, 0), (120, 120, 120)), + Roi((100, -50, 37), (33, 400, 80)), + Roi((1000, 1000, 1000), (10, 10, 10)), + None, + ): + listed = db.read_edges(roi, fetch_on_v=fetch_on_v) + _, edges = db.read_arrays(roi, edge_ends=edge_ends) + assert scored(edges) == {(e["u"], e["v"]): e["adj"] for e in listed} + # with steps, the rule applies to every node read + roi = Roi((0, 0, 0), (120, 120, 120)) + nodes, edges = db.read_arrays(roi, num_steps=1, edge_ends=edge_ends) + listed = db.read_edges( + nodes=[{"id": i} for i in nodes["id"].tolist()], fetch_on_v=fetch_on_v + ) + assert pairs(edges) == sorted((e["u"], e["v"]) for e in listed) + assert set(pairs(db.read_arrays(roi, num_steps=1)[1])) < set(pairs(edges)) + + +def test_an_unknown_edge_ends_is_refused(tmp_path): + with pytest.raises(ValueError, match="edge_ends is 'v'; it is one of"): + chain(tmp_path).read_arrays(edge_ends="v") From 5cfcf1d8e2d7966e0c8dc1d4b6828418287b99d0 Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 13:26:16 -0800 Subject: [PATCH 08/15] Node attribute store: several processes write one store; a writer's scratch is its own Two writers to one path shared .partial and destroyed each other's output (review finding 1). A scratch directory per writer fixes that, and is not enough for a blockwise task in which every worker writes the nodes of its own blocks, so the store takes the model of CSRGraphDataBase: segments, then a finalize. - A write is a segment, an append-only file of records, one record per append. The single writer keeps its segment in a scratch directory of its own and builds the store when its block is left; the store replaces the path whole, by rename. - NodeArraysWriter(..., worker=True) appends to a segment of its own in .segments/. finalize_node_arrays(path) merges the store that is there with every segment under a lock, into a new store, and removes the segments. duplicates='last' keeps the last value of a node that was written twice; the default refuses it and changes nothing. - NodeArrays maps every array when it is opened and checks that the directory was not replaced meanwhile, so a reader holds one whole store. - The attribute name 'ids' and a vector length below 1 are refused (review finding 6). The layout on disk and format version 1 are unchanged. The limits are in the module docstring and in docs/source/graphs.md. Co-Authored-By: Claude Fable 5.2 --- docs/source/api.md | 4 + docs/source/graphs.md | 59 +- src/funlib/persistence/graphs/__init__.py | 7 +- src/funlib/persistence/graphs/node_arrays.py | 550 ++++++++++++++++--- tests/test_node_arrays.py | 288 +++++++++- 5 files changed, 818 insertions(+), 90 deletions(-) diff --git a/docs/source/api.md b/docs/source/api.md index 0cc20a2..491b593 100644 --- a/docs/source/api.md +++ b/docs/source/api.md @@ -63,6 +63,8 @@ The graph databases are importable from `funlib.persistence.graphs`. :members: :show-inheritance: +.. automodule:: funlib.persistence.graphs.node_arrays + .. autoclass:: funlib.persistence.graphs.node_arrays.NodeArrays :members: @@ -70,4 +72,6 @@ The graph databases are importable from `funlib.persistence.graphs`. :members: .. autofunction:: funlib.persistence.graphs.node_arrays.write_node_arrays + +.. autofunction:: funlib.persistence.graphs.node_arrays.finalize_node_arrays ``` diff --git a/docs/source/graphs.md b/docs/source/graphs.md index e6b3b0f..c692a0e 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -108,7 +108,7 @@ directory of memory-mapped arrays keyed by node id: ```python from funlib.persistence.graphs import NodeArrays, NodeArraysWriter -with NodeArraysWriter("embedding.nodes", {"embedding": 64}) as out: +with NodeArraysWriter("embedding.nodes", {"embedding": 64}, source="model 3") as out: for roi in blocks: nodes, edges = db.read_block(roi, num_steps=2) own = nodes["own"] @@ -120,3 +120,60 @@ found, values = NodeArrays("embedding.nodes").read(nodes["id"]) A node belongs to one block: a node id written twice is refused. A node that was never written is not `found` and reads as NaN (0 for an integer). `write_node_arrays` writes values that are already in memory in one call. +`source` is free text about where the values come from; the store does not +interpret it. Which graph a store belongs to is for the caller to record, +for example in the registry that names both. + +The store appears at its path when the `with` block is left without an +error, whole, and replaces what was there. It is built in a scratch +directory of its own beside the path, so a writer that fails changes +nothing, and two writers to one path cannot damage each other: the one that +finishes last stays. + +### Several writers + +In a blockwise task each worker process writes the nodes of its own blocks. +The store follows the model of `CSRGraphDataBase` for this: a writer opened +with `worker=True` appends to a segment file of its own, and one call +merges the segments into the store when the workers are done. + +```python +from funlib.persistence.graphs import NodeArraysWriter, finalize_node_arrays + +# in each worker process +with NodeArraysWriter("embedding.nodes", {"embedding": 64}, worker=True) as out: + for roi in my_blocks: + nodes, edges = db.read_block(roi, num_steps=2) + own = nodes["own"] + out.append(nodes["id"][own], embedding=model(nodes, edges)[own]) + +# in one process, when the workers are done +finalize_node_arrays("embedding.nodes", source="model 3") +``` + +The segments are in `embedding.nodes.segments/`, beside the store. Each +`append` is one record there, complete when `append` returns; a worker that +fails or is killed later keeps the blocks it had appended. Nothing changes +at the store's path until `finalize_node_arrays`, which builds a new store +from the one that is there and every segment, moves it into place, and +removes the segments. A run that is taken up again therefore adds to what +the earlier run finalized, and a reader sees the store of the last finalize, +whole, or none. + +What to know about this mode: + +- Finalize when the writers are done. A record appended to a segment while + that segment is being merged is lost. Several finalizes at once are safe; + they run one after the other. +- A block that ran twice wrote its nodes twice. By default the finalize + refuses that with `ValueError` and changes nothing; + `finalize_node_arrays(path, duplicates="last")` keeps the value written + last instead. +- Every writer of one store declares the same attributes and dtypes; the + finalize refuses segments that disagree. `source` is given to the + finalize, not to a worker. +- Segments left behind by a run that was given up are merged by the next + finalize. Remove `.segments` to discard them. +- The finalize copies every value once and sorts the node ids in memory. +- An open `NodeArrays` keeps reading the store it opened; open it again + after a finalize to see the new one. diff --git a/src/funlib/persistence/graphs/__init__.py b/src/funlib/persistence/graphs/__init__.py index da92634..cfe9c13 100644 --- a/src/funlib/persistence/graphs/__init__.py +++ b/src/funlib/persistence/graphs/__init__.py @@ -1,4 +1,9 @@ from .sqlite_graph_database import SQLiteGraphDataBase # noqa from .pgsql_graph_database import PgSQLGraphDatabase # noqa from .csr_graph_database import CSRGraphDataBase # noqa -from .node_arrays import NodeArrays, NodeArraysWriter, write_node_arrays # noqa +from .node_arrays import ( # noqa + NodeArrays, + NodeArraysWriter, + finalize_node_arrays, + write_node_arrays, +) diff --git a/src/funlib/persistence/graphs/node_arrays.py b/src/funlib/persistence/graphs/node_arrays.py index 13b76a6..f9abacf 100644 --- a/src/funlib/persistence/graphs/node_arrays.py +++ b/src/funlib/persistence/graphs/node_arrays.py @@ -16,32 +16,105 @@ each other on disk, so the read of a block touches few pages. A read is by node id, through ``order``. ``source`` is free text that says where the values come from; the store does not interpret it. + +**Writing.** The arrays of a store are never changed in place. A write is +a *segment*: an append-only file of records, one record per +:meth:`NodeArraysWriter.append`. A store is built from segments in a +scratch directory beside ``path`` and moved to ``path`` when it is +complete, so ``path`` holds a whole store or none. This is the model of +:class:`~funlib.persistence.graphs.CSRGraphDataBase`: segments, then a +finalize. + +One writer + ``with NodeArraysWriter(path, attrs) as out`` keeps its segment in a + scratch directory of its own and builds the store when the block is + left without an error. The store then holds what this writer appended + and replaces what was at ``path``. Two such writers to one path do not + touch each other's files; the one that finishes last stays. + +Several writers + ``NodeArraysWriter(path, attrs, worker=True)`` appends to a segment of + its own in ``.segments/``, in any number of processes at once, + on any machine that sees the directory. Each ``append`` is one record, + flushed before it returns. :func:`finalize_node_arrays`, called once + the writers are done, merges the store at ``path`` (if there is one) + with every segment into a new store and removes the segments. Until + then a reader sees the store of the last finalize, or none. + +Limits of the several-writers mode: + +* Call :func:`finalize_node_arrays` when the writers are done. A record + appended to a segment while that segment is being merged is lost with + it. Two finalizes at once are safe: the second waits for the first. +* A writer that is killed leaves the records it had completed. A record + cut short is ignored, with a warning; the block it belonged to has to + be written again. +* A node id written twice is refused at finalize by default, and the + segments stay. ``duplicates="last"`` keeps the last value instead, for + a block that was run again after its first write had landed. +* Finalize copies every value once more and sorts the ids in memory + (16 bytes per node); the values themselves are streamed. +* ``path`` is replaced by two renames. A reader that opens the store in + the instant between them can find nothing there. A :class:`NodeArrays` + that is open keeps reading the store it opened, whole, and has to be + opened again to see the new one. Do not replace a store with a single + writer while workers write to it or a finalize runs. +* Segments left by a run that was given up are merged by the next + finalize. Remove ``.segments`` to discard them. """ from __future__ import annotations +import fcntl import json +import logging import os import shutil -from collections.abc import Mapping, Sequence +import time +import uuid +from collections.abc import Generator, Iterable, Iterator, Mapping, Sequence +from contextlib import contextmanager from pathlib import Path from typing import Any import numpy as np -__all__ = ["FORMAT_VERSION", "NodeArrays", "NodeArraysWriter", "write_node_arrays"] +from ._files import replace_directory, scratch_beside + +__all__ = [ + "FORMAT_VERSION", + "NodeArrays", + "NodeArraysWriter", + "finalize_node_arrays", + "write_node_arrays", +] + +logger = logging.getLogger(__name__) FORMAT_VERSION = 1 META = "meta.json" -_COPY = 1 << 26 +_ID = "ids" # the id field of a record; not an attribute name +_ID_DTYPE = np.dtype(" str: return f"node_{name}.npy" +def _segments_dir(path: Path) -> Path: + return path.with_name(path.name + ".segments") + + class NodeArrays: - """Stored node attributes, memory-mapped and read by node id.""" + """Stored node attributes, memory-mapped and read by node id. + + Every array is mapped when the reader is opened, so a reader holds + one whole store: the one that was at ``path`` then. A store that + replaces it later (a new write, a finalize) is seen by opening a + reader again; this one keeps reading the store it opened.""" def __init__(self, path: Path | str): self.path = Path(path) @@ -50,13 +123,33 @@ def __init__(self, path: Path | str): raise FileNotFoundError( f"{self.path} holds no {META}: not a node attribute store" ) - self.meta: dict[str, Any] = json.loads(meta.read_text()) - if self.meta.get("version") != FORMAT_VERSION: - raise ValueError( - f"{self.path}: node attribute store version " - f"{self.meta.get('version')!r}, this reader knows {FORMAT_VERSION}" - ) - self._arrays: dict[str, np.ndarray] = {} + for attempt in range(_OPEN_ATTEMPTS): + try: + before = os.stat(self.path) + self.meta: dict[str, Any] = json.loads(meta.read_text()) + if self.meta.get("version") != FORMAT_VERSION: + raise ValueError( + f"{self.path}: node attribute store version " + f"{self.meta.get('version')!r}, this reader knows " + f"{FORMAT_VERSION}" + ) + files = ["ids.npy", "order.npy", *map(_file, self.meta["attrs"])] + self._arrays: dict[str, np.ndarray] = { + file: np.load(self.path / file, mmap_mode="r") for file in files + } + after = os.stat(self.path) + except FileNotFoundError: + # the store is being replaced: its directory was moved away + # between two of the steps above + if attempt == _OPEN_ATTEMPTS - 1: + raise + time.sleep(0.01) + continue + # the same directory before and after: one store, not the + # meta.json of one and the arrays of the next + if (before.st_ino, before.st_mtime_ns) == (after.st_ino, after.st_mtime_ns): + return + raise RuntimeError(f"{self.path} kept being replaced while it was opened") @property def num_nodes(self) -> int: @@ -74,15 +167,10 @@ def source(self) -> str | None: """What the writer recorded about where the values come from.""" return self.meta.get("source") - def _load(self, file: str) -> np.ndarray: - if file not in self._arrays: - self._arrays[file] = np.load(self.path / file, mmap_mode="r") - return self._arrays[file] - @property def ids(self) -> np.ndarray: """Every stored node id, in stored order.""" - return self._load("ids.npy") + return self._arrays["ids.npy"] def array(self, name: str) -> np.ndarray: """One attribute of every node, memory-mapped, aligned with @@ -92,13 +180,13 @@ def array(self, name: str) -> np.ndarray: f"{self.path} holds no attribute {name!r}; it holds " f"{sorted(self.meta['attrs'])}" ) - return self._load(_file(name)) + return self._arrays[_file(name)] def rows(self, ids: Any) -> tuple[np.ndarray, np.ndarray]: """Where each of ``ids`` is stored: ``(found, rows)``; a row is only meaningful where ``found``.""" ids = np.asarray(ids, dtype=np.uint64) - order = self._load("order.npy") + order = self._arrays["order.npy"] stored = self.ids if len(order) == 0: return np.zeros(len(ids), dtype=bool), np.zeros(len(ids), dtype=np.int64) @@ -133,6 +221,258 @@ def read( return found, values +# -- segments and the build of a store --------------------------------------- + + +def _specs(record: np.dtype) -> dict[str, dict[str, Any]]: + """The attributes a record dtype declares, as ``meta.json`` states them.""" + out = {} + for name, (field, *_) in (record.fields or {}).items(): + if name != _ID: + out[name] = { + "dtype": field.base.str, + "size": field.shape[0] if field.shape else 0, + } + return out + + +def _scan(path: Path) -> tuple[np.dtype | None, list[tuple[int, int]]]: + """The whole records of a segment: their dtype and, for each, where + its rows start in the file and how many there are.""" + size = path.stat().st_size + record: np.dtype | None = None + found: list[tuple[int, int]] = [] + with open(path, "rb") as f: + while f.tell() < size: + try: + np.lib.format.read_magic(f) + shape, _, dtype = np.lib.format.read_array_header_1_0(f) + end = f.tell() + shape[0] * dtype.itemsize + except (ValueError, EOFError, OSError): + end = size + 1 + if end > size: + # a writer that died mid-record leaves a short tail + logger.warning("ignoring a truncated record in %s", path) + break + if record is None: + record = dtype + elif dtype != record: + raise ValueError(f"{path} holds records of two kinds") + found.append((f.tell(), shape[0])) + f.seek(end) + return record, found + + +_Scanned = list[tuple[Path, np.dtype, list[tuple[int, int]]]] + + +def _chunks(existing: NodeArrays | None, segments: _Scanned) -> Iterator[Any]: + """Everything to store, a bounded number of rows at a time: the store + that is there first, then the segments in the order given.""" + if existing is not None: + columns = {_ID: existing.ids} + columns.update({name: existing.array(name) for name in existing.meta["attrs"]}) + for start in range(0, existing.num_nodes, _ROWS): + yield {k: np.asarray(v[start : start + _ROWS]) for k, v in columns.items()} + for path, record, found in segments: + with open(path, "rb") as f: + for start, count in found: + f.seek(start) + yield np.fromfile(f, dtype=record, count=count) + + +def _build( + path: Path, + out: Path, + existing: NodeArrays | None, + segments: list[Path], + source: str | None, + duplicates: str, +) -> None: + """Write the store of ``existing`` and ``segments`` to the new directory + ``out`` and move it to ``path``.""" + scanned: _Scanned = [] + attrs: dict[str, dict[str, Any]] | None = ( + None if existing is None else existing.meta["attrs"] + ) + for segment in segments: + record, found = _scan(segment) + if record is None: + continue + if attrs is None: + attrs = _specs(record) + elif _specs(record) != attrs: + raise ValueError( + f"{segment} was written with the attributes {_specs(record)}, " + f"the rest of {path} with {attrs}" + ) + scanned.append((segment, record, found)) + if attrs is None: + raise FileNotFoundError(f"nothing was written to {path}") + total = (existing.num_nodes if existing is not None else 0) + sum( + count for _, _, found in scanned for _, count in found + ) + + out.mkdir(parents=True) + files = {_ID: "ids.npy", **{name: _file(name) for name in attrs}} + dtypes = {_ID: _ID_DTYPE, **{k: np.dtype(v["dtype"]) for k, v in attrs.items()}} + tails = { + _ID: (), + **{k: (v["size"],) if v["size"] else () for k, v in attrs.items()}, + } + + def write(rows: int, chunks: Iterable[Any]) -> None: + handles = {name: open(out / file, "wb") for name, file in files.items()} + try: + for name, handle in handles.items(): + np.lib.format.write_array_header_1_0( + handle, + { + "descr": np.lib.format.dtype_to_descr(dtypes[name]), + "fortran_order": False, + "shape": (rows, *tails[name]), + }, + ) + for chunk in chunks: + for name, handle in handles.items(): + np.ascontiguousarray(chunk[name], dtype=dtypes[name]).tofile(handle) + finally: + for handle in handles.values(): + handle.close() + + write(total, _chunks(existing, scanned)) + ids = np.load(out / "ids.npy") + order = np.argsort(ids, kind="stable") + again = np.flatnonzero(ids[order][1:] == ids[order][:-1]) + if len(again): + if duplicates != "last": + some = np.unique(ids[order][again])[:5].tolist() + raise ValueError( + f"{path}: a node id was written twice (for example {some}); a " + "node belongs to one block" + ) + # of the rows with one id the last written stays; the sort is + # stable, so that is the last of each run of equal ids + last = np.ones(total, dtype=bool) + last[again] = False + keep = np.zeros(total, dtype=bool) + keep[order[last]] = True + for file in files.values(): + os.rename(out / file, out / f"{file}.all") + every = { + name: np.load(out / f"{file}.all", mmap_mode="r") + for name, file in files.items() + } + total = int(keep.sum()) + write( + total, + ( + { + name: np.asarray(values[start : start + _ROWS])[ + keep[start : start + _ROWS] + ] + for name, values in every.items() + } + for start in range(0, len(keep), _ROWS) + ), + ) + del every + for file in files.values(): + (out / f"{file}.all").unlink() + ids = np.load(out / "ids.npy") + order = np.argsort(ids, kind="stable") + np.save(out / "order.npy", order.astype(" Generator[bool]: + """One finalize at a time. Yields False when ``folder`` is not there: + no worker wrote, or another finalize merged everything in it.""" + name = folder / _LOCK + fd = None + while fd is None: + try: + fd = os.open(name, os.O_RDWR | os.O_CREAT, 0o666) + except FileNotFoundError: + break + fcntl.flock(fd, fcntl.LOCK_EX) + try: + # the finalize waited for removes the lock file it held + current = os.fstat(fd).st_ino == os.stat(name).st_ino + except FileNotFoundError: + current = False + if not current: + os.close(fd) + fd = None + try: + yield fd is not None + finally: + if fd is not None: + os.close(fd) + + +def finalize_node_arrays( + path: Path | str, *, source: str | None = None, duplicates: str = "raise" +) -> Path: + """Merge what the worker writers of ``path`` appended into the store. + + The new store holds the nodes of the store at ``path``, if there is + one, and of every segment in ``.segments``; it replaces the + store, and the segments are removed. Call it in one process when the + writers are done (the limits are in the module documentation). With + nothing to merge it leaves the store as it is. + + ``source`` is recorded in the new store; left out, the store keeps + the ``source`` it had. + + ``duplicates`` says what a node id written more than once is: + ``"raise"`` (the default) refuses it with ``ValueError`` and leaves + the store and the segments as they were; ``"last"`` keeps the value + written last. Segments are taken in the order their writers were + opened, by the clocks of the machines that opened them, after the + store that is already there. + """ + path = Path(path) + if duplicates not in ("raise", "last"): + raise ValueError(f"duplicates is {duplicates!r}; it is 'raise' or 'last'") + folder = _segments_dir(path) + with _finalize_lock(folder) as pending: + segments = sorted(folder.glob("*.npys")) if pending else [] + stored = (path / META).is_file() + if not segments and not stored: + raise FileNotFoundError( + f"nothing was written to {path}: there is no store and no " + f"segment in {folder}" + ) + if segments: + existing = NodeArrays(path) if stored else None + if source is None and existing is not None: + source = existing.source + out = scratch_beside(path, "building") + try: + _build(path, out, existing, segments, source, duplicates) + finally: + shutil.rmtree(out, ignore_errors=True) + for segment in segments: + segment.unlink(missing_ok=True) + if pending: + # leave nothing beside the store, unless a writer is still there + try: + (folder / _LOCK).unlink() + folder.rmdir() + except OSError: + pass + return path + + class NodeArraysWriter: """Writes a node attribute store a block at a time. @@ -142,9 +482,33 @@ class NodeArraysWriter: for ids, embedding in blocks: out.append(ids, embedding=embedding) - The store appears at ``path`` only when the block is left without an - error; until then it is a ``.partial`` directory beside it, which an - error leaves behind for inspection and the next writer removes. + ``attrs`` maps each attribute to its vector length, ``None`` for a + scalar; ``dtypes`` names a dtype for those that are not ``float32``. + ``ids`` is not an attribute name. + + As above, with one writer, the store appears at ``path`` only when the + block is left without an error, and it replaces what was there. An + error leaves ``path`` as it was and nothing beside it. + + With ``worker=True`` the writer is one of several, in as many + processes:: + + # in each worker + with NodeArraysWriter(path, {"embedding": 64}, worker=True) as out: + for ids, embedding in my_blocks: + out.append(ids, embedding=embedding) + + # in one process, when the workers are done + finalize_node_arrays(path, source="model 3") + + Every ``append`` is then a record in a segment file of this writer in + ``.segments``, complete when ``append`` returns, and it stays + whatever happens to the writer afterwards. Nothing changes at ``path`` + before :func:`finalize_node_arrays`, which adds the segments to the + store that is there. Every writer of a store declares the same + attributes. Open the writer in the process that appends to it. The + design and its limits are in the documentation of + :mod:`funlib.persistence.graphs.node_arrays`. """ def __init__( @@ -154,11 +518,22 @@ def __init__( *, dtypes: Mapping[str, Any] | None = None, source: str | None = None, + worker: bool = False, ): self.path = Path(path) self.attrs = dict(attrs) if not self.attrs: raise ValueError("a node attribute store holds at least one attribute") + if _ID in self.attrs: + raise ValueError( + f"{_ID!r} is not an attribute name: it names the node ids of a store" + ) + for name, length in self.attrs.items(): + if length is not None and (isinstance(length, bool) or length < 1): + raise ValueError( + f"attribute {name!r}: a vector has a length of 1 or more and " + f"a scalar has None, not {length!r}" + ) self.dtypes = { name: np.dtype((dtypes or {}).get(name, "float32")).newbyteorder("<") for name in self.attrs @@ -166,85 +541,95 @@ def __init__( for name, dtype in self.dtypes.items(): if dtype.kind not in "fiub": raise ValueError(f"attribute {name!r}: {dtype} is not a number type") + if worker and source is not None: + raise ValueError( + "source belongs to the store, not to one of its writers: give " + "it to finalize_node_arrays" + ) self.source = source + self.worker = worker self.num_nodes = 0 - self._partial = self.path.with_name(self.path.name + ".partial") - self._files: dict[str, Any] = {} + self._record = np.dtype( + [(_ID, _ID_DTYPE)] + + [ + (name, self.dtypes[name], () if length is None else (length,)) + for name, length in self.attrs.items() + ] + ) + self._scratch: Path | None = None + self._segment: Path | None = None + self._file: Any = None def __enter__(self) -> NodeArraysWriter: - if self._partial.exists(): - shutil.rmtree(self._partial) - self._partial.mkdir(parents=True) - for name in ("ids", *self.attrs): - self._files[name] = open(self._partial / f"{name}.raw", "wb") + if self.worker: + meta = self.path / META + if meta.is_file(): + stored = json.loads(meta.read_text()).get("attrs") + if stored != _specs(self._record): + raise ValueError( + f"{self.path} holds the attributes {stored}; this writer " + f"declares {_specs(self._record)}" + ) + folder = _segments_dir(self.path) + else: + # a directory no other writer has: two writers to one path + # never see each other's files + folder = self._scratch = scratch_beside(self.path, "writing") + folder.mkdir(parents=True, exist_ok=True) + name = f"{time.time_ns():020d}-{os.getpid()}-{uuid.uuid4().hex}.npys" + self._segment = folder / name + self._file = open(self._segment, "ab") + # a record of no rows states the attributes, so that writers with + # no node to write still leave a store, an empty one + self._write(np.zeros(0, dtype=self._record)) return self + def _write(self, records: np.ndarray) -> None: + np.lib.format.write_array( + self._file, records, version=(1, 0), allow_pickle=False + ) + self._file.flush() + def append(self, ids: Any, **values: Any) -> None: """Add nodes: their ids and one array per attribute, aligned.""" - ids = np.ascontiguousarray(ids, dtype=" None: - for file in self._files.values(): - file.close() - if kind is not None: - return - self._finish("ids", "ids.npy", np.dtype(" 1 and (np.diff(np.asarray(ids)[order]) == 0).any(): - raise ValueError( - f"{self.path}: a node id was written twice; a node belongs to one block" - ) - np.save(self._partial / "order.npy", order) - meta = { - "version": FORMAT_VERSION, - "num_nodes": self.num_nodes, - "attrs": { - name: {"dtype": self.dtypes[name].str, "size": length or 0} - for name, length in self.attrs.items() - }, - "source": self.source, - } - (self._partial / META).write_text(json.dumps(meta, indent=2) + "\n") - if self.path.exists(): - shutil.rmtree(self.path) - os.replace(self._partial, self.path) + self._file.close() + self._file = None + if self._scratch is None or self._segment is None: + return # a worker: its records wait for finalize_node_arrays + try: + if kind is None: + _build( + self.path, + self._scratch / "store", + None, + [self._segment], + self.source, + "raise", + ) + finally: + shutil.rmtree(self._scratch, ignore_errors=True) def write_node_arrays( @@ -254,10 +639,11 @@ def write_node_arrays( *, source: str | None = None, ) -> Path: - """Write node attributes that are in memory as one store.""" + """Write node attributes that are in memory as one store, replacing + what is at ``path``.""" arrays = {name: np.asarray(value) for name, value in values.items()} attrs = { - name: (None if value.ndim == 1 else int(value.shape[1])) + name: (int(value.shape[1]) if value.ndim == 2 else None) for name, value in arrays.items() } dtypes = {name: value.dtype for name, value in arrays.items()} diff --git a/tests/test_node_arrays.py b/tests/test_node_arrays.py index 26ce384..724415d 100644 --- a/tests/test_node_arrays.py +++ b/tests/test_node_arrays.py @@ -1,11 +1,17 @@ """Node attributes stored in arrays beside the graph they were computed on.""" import json +import multiprocessing as mp import numpy as np import pytest -from funlib.persistence.graphs import NodeArrays, NodeArraysWriter, write_node_arrays +from funlib.persistence.graphs import ( + NodeArrays, + NodeArraysWriter, + finalize_node_arrays, + write_node_arrays, +) IDS = np.array([40, 7, 19, 3, 88], dtype=np.uint64) VECTORS = np.arange(15, dtype=np.float32).reshape(5, 3) @@ -30,15 +36,11 @@ def test_values_read_back_in_the_order_the_ids_are_asked_for(tmp_path): def test_a_node_that_was_never_written_is_not_found_and_reads_as_nan(tmp_path): found, values = stored(tmp_path).read([7, 5, 1000], attrs=["score"]) assert found.tolist() == [True, False, False] + assert list(values) == ["score"] # a read names the attributes it wants assert values["score"][0] == 0.25 assert np.isnan(values["score"][1:]).all() -def test_a_read_names_the_attributes_it_wants(tmp_path): - _, values = stored(tmp_path).read([7], attrs=["vec"]) - assert list(values) == ["vec"] - - def test_an_unknown_attribute_is_refused_with_the_ones_stored(tmp_path): with pytest.raises(KeyError, match=r"no attribute 'nope'.*\['score', 'vec'\]"): stored(tmp_path).read([7], attrs=["nope"]) @@ -96,6 +98,17 @@ def test_a_writer_that_fails_leaves_no_store(tmp_path): out.append(IDS, vec=VECTORS) raise RuntimeError("stop") assert not path.exists() + assert list(tmp_path.iterdir()) == [] # and nothing beside it + + +def test_a_writer_that_fails_leaves_the_store_that_was_there(tmp_path): + path = write_node_arrays(tmp_path / "out.nodes", IDS, {"vec": VECTORS}) + with pytest.raises(ValueError, match="written twice"): + with NodeArraysWriter(path, {"vec": 3}) as out: + out.append(IDS[:2], vec=VECTORS[:2]) + out.append(IDS[:1], vec=VECTORS[:1]) + assert NodeArrays(path).num_nodes == 5 + assert [p.name for p in tmp_path.iterdir()] == ["out.nodes"] def test_a_second_write_replaces_the_store(tmp_path): @@ -131,3 +144,266 @@ def test_an_append_that_does_not_fit_the_declared_attributes_is_refused( def test_a_directory_that_is_not_a_store_is_refused(tmp_path): with pytest.raises(FileNotFoundError, match="not a node attribute store"): NodeArrays(tmp_path) + + +@pytest.mark.parametrize( + "attrs, match", + [ + ({"ids": None}, "'ids' is not an attribute name"), + ({"vec": 0}, "'vec': a vector has a length of 1 or more"), + ({"vec": -2}, "'vec': a vector has a length of 1 or more"), + ({}, "at least one attribute"), + ], +) +def test_a_declaration_the_store_cannot_hold_is_refused(tmp_path, attrs, match): + with pytest.raises(ValueError, match=match): + NodeArraysWriter(tmp_path / "out.nodes", attrs) + assert list(tmp_path.iterdir()) == [] + + +def test_values_in_memory_that_the_store_cannot_hold_are_refused(tmp_path): + with pytest.raises(ValueError, match="'ids' is not an attribute name"): + write_node_arrays(tmp_path / "out.nodes", [1, 2], {"ids": np.zeros(2)}) + with pytest.raises(ValueError, match="a vector has a length of 1 or more"): + write_node_arrays(tmp_path / "out.nodes", [1, 2], {"s": np.zeros((2, 0))}) + + +# -- several writers --------------------------------------------------------- + + +def test_two_writers_to_one_path_do_not_touch_each_others_files(tmp_path): + """Both orders of leaving: the store is that of the writer that left + last, whole, and no scratch directory stays.""" + path = tmp_path / "out.nodes" + for first_out in ("a", "b"): + a = NodeArraysWriter(path, {"vec": 3}) + b = NodeArraysWriter(path, {"vec": 3}) + a.__enter__() + a.append(IDS[:3], vec=VECTORS[:3]) + b.__enter__() + b.append(IDS[3:], vec=VECTORS[3:]) + first, second = (a, b) if first_out == "a" else (b, a) + first.__exit__(None, None, None) + assert NodeArrays(path).num_nodes == first.num_nodes + second.__exit__(None, None, None) + last = NodeArrays(path) + wanted = IDS[:3] if second is a else IDS[3:] + assert last.ids.tolist() == wanted.tolist() + found, values = last.read(IDS) + assert found.tolist() == np.isin(IDS, wanted).tolist() + assert values["vec"][found].tolist() == VECTORS[found].tolist() + assert [p.name for p in tmp_path.iterdir()] == ["out.nodes"] + + +BLOCK = 500 + + +def _block(k): + ids = np.arange(k * BLOCK, (k + 1) * BLOCK, dtype=np.uint64)[::-1] + vec = np.stack([ids, ids * 2, ids * 3], axis=1).astype(np.float32) + return ids, vec, (ids % 7).astype(np.int16) + + +def _worker(path, part, parts, blocks, start): + start.wait() + with NodeArraysWriter( + path, {"vec": 3, "label": None}, dtypes={"label": "int16"}, worker=True + ) as out: + for k in range(part, blocks, parts): + ids, vec, label = _block(k) + out.append(ids, vec=vec, label=label) + + +def _write_in_processes(path, parts, blocks): + ctx = mp.get_context("spawn") + start = ctx.Barrier(parts) + procs = [ + ctx.Process(target=_worker, args=(path, part, parts, blocks, start)) + for part in range(parts) + ] + for p in procs: + p.start() + for p in procs: + p.join() + assert [p.exitcode for p in procs] == [0] * parts + + +def test_several_processes_write_one_store(tmp_path): + path = tmp_path / "out.nodes" + parts, blocks = 4, 40 + _write_in_processes(path, parts, blocks) + # nothing is at the path before the finalize; the segments are beside it + assert not path.exists() + assert len(list((tmp_path / "out.nodes.segments").glob("*.npys"))) == parts + with pytest.raises(FileNotFoundError, match="not a node attribute store"): + NodeArrays(path) + + assert finalize_node_arrays(path, source="four workers") == path + store = NodeArrays(path) + assert store.num_nodes == blocks * BLOCK and store.source == "four workers" + assert store.attrs == {"vec": 3, "label": None} + assert store.array("label").dtype == np.int16 + ids = np.arange(blocks * BLOCK + 3, dtype=np.uint64) + found, values = store.read(ids) + assert found.tolist() == [True] * (blocks * BLOCK) + [False] * 3 + known = ids[found] + assert values["vec"][found].tolist() == ( + np.stack([known, known * 2, known * 3], axis=1).astype(np.float32).tolist() + ) + assert values["label"][found].tolist() == (known % 7).tolist() + # a block stays together on disk, in the order it was appended + stored = np.asarray(store.ids).reshape(blocks, BLOCK) + assert (np.diff(stored.astype(np.int64), axis=1) == -1).all() + # nothing is left beside the store + assert [p.name for p in tmp_path.iterdir()] == ["out.nodes"] + assert sorted(p.name for p in path.iterdir()) == [ + "ids.npy", + "meta.json", + "node_label.npy", + "node_vec.npy", + "order.npy", + ] + + +def _finalizer(path): + finalize_node_arrays(path) + + +def test_finalizes_at_once_wait_for_each_other(tmp_path): + path = tmp_path / "out.nodes" + _write_in_processes(path, 2, 20) + ctx = mp.get_context("spawn") + procs = [ctx.Process(target=_finalizer, args=(path,)) for _ in range(4)] + for p in procs: + p.start() + for p in procs: + p.join() + assert [p.exitcode for p in procs] == [0] * 4 + store = NodeArrays(path) + assert store.num_nodes == 20 * BLOCK + assert len(np.unique(store.ids)) == 20 * BLOCK + assert [p.name for p in tmp_path.iterdir()] == ["out.nodes"] + + +def worker(path, **kwargs): + return NodeArraysWriter(path, {"vec": 3}, worker=True, **kwargs) + + +def test_a_finalize_adds_to_the_store_that_is_there(tmp_path): + """A run that is taken up again: the nodes of the first finalize stay.""" + path = tmp_path / "out.nodes" + with worker(path) as out: + out.append(IDS[:2], vec=VECTORS[:2]) + finalize_node_arrays(path, source="run") + assert NodeArrays(path).ids.tolist() == IDS[:2].tolist() + + before = NodeArrays(path) + with worker(path) as out: + out.append(IDS[2:4], vec=VECTORS[2:4]) + # until the finalize, a reader sees the store of the last one + assert NodeArrays(path).num_nodes == 2 + with worker(path) as out: + out.append(IDS[4:], vec=VECTORS[4:]) + finalize_node_arrays(path) + store = NodeArrays(path) + assert store.ids.tolist() == IDS.tolist() and store.source == "run" + found, values = store.read(IDS) + assert found.all() and values["vec"].tolist() == VECTORS.tolist() + # a reader opened before reads what it opened + assert before.read(IDS)[0].tolist() == [True, True, False, False, False] + + # with nothing new, the store is left as it is + stamp = (path / "meta.json").stat().st_mtime_ns + finalize_node_arrays(path, source="ignored") + assert (path / "meta.json").stat().st_mtime_ns == stamp + assert [p.name for p in tmp_path.iterdir()] == ["out.nodes"] + + +def test_a_worker_that_fails_keeps_the_blocks_it_had_written(tmp_path): + path = tmp_path / "out.nodes" + with pytest.raises(RuntimeError, match="stop"): + with worker(path) as out: + out.append(IDS[:2], vec=VECTORS[:2]) + raise RuntimeError("stop") + finalize_node_arrays(path) + assert NodeArrays(path).ids.tolist() == IDS[:2].tolist() + + +@pytest.mark.parametrize("cut", [10, 3 * 20 + 30], ids=["rows", "header"]) +def test_a_record_cut_short_is_left_out(tmp_path, caplog, cut): + """What a writer killed inside an append leaves: the last record lacks + some of its rows (3 rows of 20 bytes), or part of its header.""" + path = tmp_path / "out.nodes" + with worker(path) as out: + out.append(IDS[:2], vec=VECTORS[:2]) + out.append(IDS[2:], vec=VECTORS[2:]) + (segment,) = (tmp_path / "out.nodes.segments").glob("*.npys") + segment.write_bytes(segment.read_bytes()[:-cut]) + finalize_node_arrays(path) + assert "truncated record" in caplog.text + assert NodeArrays(path).ids.tolist() == IDS[:2].tolist() + + +def test_a_node_written_by_two_workers_is_refused_or_keeps_its_last_value(tmp_path): + path = write_node_arrays(tmp_path / "out.nodes", IDS[:1], {"vec": VECTORS[:1]}) + with worker(path) as out: + out.append(IDS[:3], vec=VECTORS[:3] + 100) + with worker(path) as out: + out.append(IDS[1:], vec=VECTORS[1:] + 200) + out.append(IDS[4:], vec=VECTORS[4:] + 300) + with pytest.raises(ValueError, match="written twice"): + finalize_node_arrays(path) + # refused: the store and the segments are as they were + assert NodeArrays(path).ids.tolist() == IDS[:1].tolist() + assert len(list((tmp_path / "out.nodes.segments").glob("*.npys"))) == 2 + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "out.nodes", + "out.nodes.segments", + ] + + finalize_node_arrays(path, duplicates="last") + store = NodeArrays(path) + assert sorted(store.ids.tolist()) == sorted(IDS.tolist()) + found, values = store.read(IDS) + assert found.all() + assert (values["vec"] - VECTORS)[:, 0].tolist() == [100, 200, 200, 200, 300] + assert np.load(path / "order.npy").tolist() == np.argsort(store.ids).tolist() + assert sorted(p.name for p in path.iterdir()) == [ + "ids.npy", + "meta.json", + "node_vec.npy", + "order.npy", + ] + with pytest.raises(ValueError, match="duplicates is 'first'"): + finalize_node_arrays(path, duplicates="first") + + +def test_writers_that_declare_other_attributes_are_refused(tmp_path): + path = tmp_path / "out.nodes" + with worker(path) as out: + out.append(IDS[:2], vec=VECTORS[:2]) + with NodeArraysWriter(path, {"vec": 2}, worker=True) as out: + out.append(IDS[2:], vec=VECTORS[2:, :2]) + with pytest.raises(ValueError, match="was written with the attributes"): + finalize_node_arrays(path) + assert not path.exists() + + # against a store that is there, the writer is refused when it opens + path = write_node_arrays(tmp_path / "other.nodes", IDS, {"vec": VECTORS}) + with pytest.raises(ValueError, match="holds the attributes"): + with NodeArraysWriter(path, {"vec": 3}, dtypes={"vec": "f8"}, worker=True): + pass + with pytest.raises(ValueError, match="give it to finalize_node_arrays"): + worker(path, source="mine") + + +def test_workers_with_no_node_to_write_leave_an_empty_store(tmp_path): + path = tmp_path / "out.nodes" + with pytest.raises(FileNotFoundError, match="nothing was written"): + finalize_node_arrays(path) + with worker(path) as out: + out.append(IDS[:0], vec=VECTORS[:0]) + finalize_node_arrays(path) + store = NodeArrays(path) + assert store.num_nodes == 0 and store.attrs == {"vec": 3} + assert store.read([1])[0].tolist() == [False] From a8b6de2926f1be4163bc199040c10156478713e1 Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 14:32:22 -0800 Subject: [PATCH 09/15] Remove the separate node attribute store NodeArrays, NodeArraysWriter, write_node_arrays and finalize_node_arrays were a second implementation of segments-then-finalize beside CSRGraphDataBase. Values on the nodes of a graph are to be written and read through the database, in directories of their own (next commit). The format was never released. Co-Authored-By: Claude Fable 5.2 --- docs/source/api.md | 12 - docs/source/graphs.md | 79 --- src/funlib/persistence/graphs/__init__.py | 6 - src/funlib/persistence/graphs/node_arrays.py | 652 ------------------- tests/test_node_arrays.py | 409 ------------ 5 files changed, 1158 deletions(-) delete mode 100644 src/funlib/persistence/graphs/node_arrays.py delete mode 100644 tests/test_node_arrays.py diff --git a/docs/source/api.md b/docs/source/api.md index 491b593..8e97415 100644 --- a/docs/source/api.md +++ b/docs/source/api.md @@ -62,16 +62,4 @@ The graph databases are importable from `funlib.persistence.graphs`. .. autoclass:: funlib.persistence.graphs.csr_graph_database.CSRGraphDataBase :members: :show-inheritance: - -.. automodule:: funlib.persistence.graphs.node_arrays - -.. autoclass:: funlib.persistence.graphs.node_arrays.NodeArrays - :members: - -.. autoclass:: funlib.persistence.graphs.node_arrays.NodeArraysWriter - :members: - -.. autofunction:: funlib.persistence.graphs.node_arrays.write_node_arrays - -.. autofunction:: funlib.persistence.graphs.node_arrays.finalize_node_arrays ``` diff --git a/docs/source/graphs.md b/docs/source/graphs.md index c692a0e..187d238 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -98,82 +98,3 @@ values = compute(nodes, edges)[nodes["own"]] ``` `CSRGraphDataBase.is_database(path)` tells such a directory from any other. - -## Values on the nodes of a graph - -Values computed on a graph, such as an embedding per node, can be kept -beside the graph without rewriting it. A node attribute store is a -directory of memory-mapped arrays keyed by node id: - -```python -from funlib.persistence.graphs import NodeArrays, NodeArraysWriter - -with NodeArraysWriter("embedding.nodes", {"embedding": 64}, source="model 3") as out: - for roi in blocks: - nodes, edges = db.read_block(roi, num_steps=2) - own = nodes["own"] - out.append(nodes["id"][own], embedding=model(nodes, edges)[own]) - -found, values = NodeArrays("embedding.nodes").read(nodes["id"]) -``` - -A node belongs to one block: a node id written twice is refused. A node -that was never written is not `found` and reads as NaN (0 for an integer). -`write_node_arrays` writes values that are already in memory in one call. -`source` is free text about where the values come from; the store does not -interpret it. Which graph a store belongs to is for the caller to record, -for example in the registry that names both. - -The store appears at its path when the `with` block is left without an -error, whole, and replaces what was there. It is built in a scratch -directory of its own beside the path, so a writer that fails changes -nothing, and two writers to one path cannot damage each other: the one that -finishes last stays. - -### Several writers - -In a blockwise task each worker process writes the nodes of its own blocks. -The store follows the model of `CSRGraphDataBase` for this: a writer opened -with `worker=True` appends to a segment file of its own, and one call -merges the segments into the store when the workers are done. - -```python -from funlib.persistence.graphs import NodeArraysWriter, finalize_node_arrays - -# in each worker process -with NodeArraysWriter("embedding.nodes", {"embedding": 64}, worker=True) as out: - for roi in my_blocks: - nodes, edges = db.read_block(roi, num_steps=2) - own = nodes["own"] - out.append(nodes["id"][own], embedding=model(nodes, edges)[own]) - -# in one process, when the workers are done -finalize_node_arrays("embedding.nodes", source="model 3") -``` - -The segments are in `embedding.nodes.segments/`, beside the store. Each -`append` is one record there, complete when `append` returns; a worker that -fails or is killed later keeps the blocks it had appended. Nothing changes -at the store's path until `finalize_node_arrays`, which builds a new store -from the one that is there and every segment, moves it into place, and -removes the segments. A run that is taken up again therefore adds to what -the earlier run finalized, and a reader sees the store of the last finalize, -whole, or none. - -What to know about this mode: - -- Finalize when the writers are done. A record appended to a segment while - that segment is being merged is lost. Several finalizes at once are safe; - they run one after the other. -- A block that ran twice wrote its nodes twice. By default the finalize - refuses that with `ValueError` and changes nothing; - `finalize_node_arrays(path, duplicates="last")` keeps the value written - last instead. -- Every writer of one store declares the same attributes and dtypes; the - finalize refuses segments that disagree. `source` is given to the - finalize, not to a worker. -- Segments left behind by a run that was given up are merged by the next - finalize. Remove `.segments` to discard them. -- The finalize copies every value once and sorts the node ids in memory. -- An open `NodeArrays` keeps reading the store it opened; open it again - after a finalize to see the new one. diff --git a/src/funlib/persistence/graphs/__init__.py b/src/funlib/persistence/graphs/__init__.py index cfe9c13..3a270f9 100644 --- a/src/funlib/persistence/graphs/__init__.py +++ b/src/funlib/persistence/graphs/__init__.py @@ -1,9 +1,3 @@ from .sqlite_graph_database import SQLiteGraphDataBase # noqa from .pgsql_graph_database import PgSQLGraphDatabase # noqa from .csr_graph_database import CSRGraphDataBase # noqa -from .node_arrays import ( # noqa - NodeArrays, - NodeArraysWriter, - finalize_node_arrays, - write_node_arrays, -) diff --git a/src/funlib/persistence/graphs/node_arrays.py b/src/funlib/persistence/graphs/node_arrays.py deleted file mode 100644 index f9abacf..0000000 --- a/src/funlib/persistence/graphs/node_arrays.py +++ /dev/null @@ -1,652 +0,0 @@ -"""Node attributes in plain arrays beside the graph they belong to. - -Values computed on a graph (an embedding, a score, a label per node) do not -have to go into the graph database: the graph stays as it is, and a -64-vector per node would outweigh the graph it describes. They are stored -on their own, as memory-mapped arrays keyed by node id:: - - /meta.json version, num_nodes, attrs, source - /ids.npy uint64 (N,) node ids, in stored order - /order.npy int64 (N,) argsort of ids - /node_.npy (N,) or (N, k) - -``attrs`` maps each attribute to ``{"dtype": ".segments/``, in any number of processes at once, - on any machine that sees the directory. Each ``append`` is one record, - flushed before it returns. :func:`finalize_node_arrays`, called once - the writers are done, merges the store at ``path`` (if there is one) - with every segment into a new store and removes the segments. Until - then a reader sees the store of the last finalize, or none. - -Limits of the several-writers mode: - -* Call :func:`finalize_node_arrays` when the writers are done. A record - appended to a segment while that segment is being merged is lost with - it. Two finalizes at once are safe: the second waits for the first. -* A writer that is killed leaves the records it had completed. A record - cut short is ignored, with a warning; the block it belonged to has to - be written again. -* A node id written twice is refused at finalize by default, and the - segments stay. ``duplicates="last"`` keeps the last value instead, for - a block that was run again after its first write had landed. -* Finalize copies every value once more and sorts the ids in memory - (16 bytes per node); the values themselves are streamed. -* ``path`` is replaced by two renames. A reader that opens the store in - the instant between them can find nothing there. A :class:`NodeArrays` - that is open keeps reading the store it opened, whole, and has to be - opened again to see the new one. Do not replace a store with a single - writer while workers write to it or a finalize runs. -* Segments left by a run that was given up are merged by the next - finalize. Remove ``.segments`` to discard them. -""" - -from __future__ import annotations - -import fcntl -import json -import logging -import os -import shutil -import time -import uuid -from collections.abc import Generator, Iterable, Iterator, Mapping, Sequence -from contextlib import contextmanager -from pathlib import Path -from typing import Any - -import numpy as np - -from ._files import replace_directory, scratch_beside - -__all__ = [ - "FORMAT_VERSION", - "NodeArrays", - "NodeArraysWriter", - "finalize_node_arrays", - "write_node_arrays", -] - -logger = logging.getLogger(__name__) - -FORMAT_VERSION = 1 -META = "meta.json" -_ID = "ids" # the id field of a record; not an attribute name -_ID_DTYPE = np.dtype(" str: - return f"node_{name}.npy" - - -def _segments_dir(path: Path) -> Path: - return path.with_name(path.name + ".segments") - - -class NodeArrays: - """Stored node attributes, memory-mapped and read by node id. - - Every array is mapped when the reader is opened, so a reader holds - one whole store: the one that was at ``path`` then. A store that - replaces it later (a new write, a finalize) is seen by opening a - reader again; this one keeps reading the store it opened.""" - - def __init__(self, path: Path | str): - self.path = Path(path) - meta = self.path / META - if not meta.is_file(): - raise FileNotFoundError( - f"{self.path} holds no {META}: not a node attribute store" - ) - for attempt in range(_OPEN_ATTEMPTS): - try: - before = os.stat(self.path) - self.meta: dict[str, Any] = json.loads(meta.read_text()) - if self.meta.get("version") != FORMAT_VERSION: - raise ValueError( - f"{self.path}: node attribute store version " - f"{self.meta.get('version')!r}, this reader knows " - f"{FORMAT_VERSION}" - ) - files = ["ids.npy", "order.npy", *map(_file, self.meta["attrs"])] - self._arrays: dict[str, np.ndarray] = { - file: np.load(self.path / file, mmap_mode="r") for file in files - } - after = os.stat(self.path) - except FileNotFoundError: - # the store is being replaced: its directory was moved away - # between two of the steps above - if attempt == _OPEN_ATTEMPTS - 1: - raise - time.sleep(0.01) - continue - # the same directory before and after: one store, not the - # meta.json of one and the arrays of the next - if (before.st_ino, before.st_mtime_ns) == (after.st_ino, after.st_mtime_ns): - return - raise RuntimeError(f"{self.path} kept being replaced while it was opened") - - @property - def num_nodes(self) -> int: - return int(self.meta["num_nodes"]) - - @property - def attrs(self) -> dict[str, int | None]: - """Attribute name to vector length (None for a scalar).""" - return { - name: (spec["size"] or None) for name, spec in self.meta["attrs"].items() - } - - @property - def source(self) -> str | None: - """What the writer recorded about where the values come from.""" - return self.meta.get("source") - - @property - def ids(self) -> np.ndarray: - """Every stored node id, in stored order.""" - return self._arrays["ids.npy"] - - def array(self, name: str) -> np.ndarray: - """One attribute of every node, memory-mapped, aligned with - :attr:`ids`.""" - if name not in self.meta["attrs"]: - raise KeyError( - f"{self.path} holds no attribute {name!r}; it holds " - f"{sorted(self.meta['attrs'])}" - ) - return self._arrays[_file(name)] - - def rows(self, ids: Any) -> tuple[np.ndarray, np.ndarray]: - """Where each of ``ids`` is stored: ``(found, rows)``; a row is - only meaningful where ``found``.""" - ids = np.asarray(ids, dtype=np.uint64) - order = self._arrays["order.npy"] - stored = self.ids - if len(order) == 0: - return np.zeros(len(ids), dtype=bool), np.zeros(len(ids), dtype=np.int64) - # ``order`` sorts the stored ids, so the search probes log(N) of - # them per id and never reads the whole array - lo = np.searchsorted(stored, ids, sorter=order) - at = np.minimum(lo, len(order) - 1) - rows = np.asarray(order[at], dtype=np.int64) - found = (lo < len(order)) & (np.asarray(stored[rows]) == ids) - return found, rows - - def read( - self, ids: Any, attrs: Sequence[str] | None = None - ) -> tuple[np.ndarray, dict[str, np.ndarray]]: - """The attributes of the nodes ``ids``, in their order. - - Returns ``(found, values)``. A node that was never written is not - ``found`` and reads as NaN (0 for an integer attribute). - """ - names = list(self.meta["attrs"]) if attrs is None else list(attrs) - found, rows = self.rows(ids) - # gather in row order, so a block's read walks the file forwards - where = np.flatnonzero(found) - walk = where[np.argsort(rows[where], kind="stable")] - values: dict[str, np.ndarray] = {} - for name in names: - stored = self.array(name) - fill = np.nan if stored.dtype.kind == "f" else 0 - out = np.full((len(found), *stored.shape[1:]), fill, dtype=stored.dtype) - out[walk] = stored[rows[walk]] - values[name] = out - return found, values - - -# -- segments and the build of a store --------------------------------------- - - -def _specs(record: np.dtype) -> dict[str, dict[str, Any]]: - """The attributes a record dtype declares, as ``meta.json`` states them.""" - out = {} - for name, (field, *_) in (record.fields or {}).items(): - if name != _ID: - out[name] = { - "dtype": field.base.str, - "size": field.shape[0] if field.shape else 0, - } - return out - - -def _scan(path: Path) -> tuple[np.dtype | None, list[tuple[int, int]]]: - """The whole records of a segment: their dtype and, for each, where - its rows start in the file and how many there are.""" - size = path.stat().st_size - record: np.dtype | None = None - found: list[tuple[int, int]] = [] - with open(path, "rb") as f: - while f.tell() < size: - try: - np.lib.format.read_magic(f) - shape, _, dtype = np.lib.format.read_array_header_1_0(f) - end = f.tell() + shape[0] * dtype.itemsize - except (ValueError, EOFError, OSError): - end = size + 1 - if end > size: - # a writer that died mid-record leaves a short tail - logger.warning("ignoring a truncated record in %s", path) - break - if record is None: - record = dtype - elif dtype != record: - raise ValueError(f"{path} holds records of two kinds") - found.append((f.tell(), shape[0])) - f.seek(end) - return record, found - - -_Scanned = list[tuple[Path, np.dtype, list[tuple[int, int]]]] - - -def _chunks(existing: NodeArrays | None, segments: _Scanned) -> Iterator[Any]: - """Everything to store, a bounded number of rows at a time: the store - that is there first, then the segments in the order given.""" - if existing is not None: - columns = {_ID: existing.ids} - columns.update({name: existing.array(name) for name in existing.meta["attrs"]}) - for start in range(0, existing.num_nodes, _ROWS): - yield {k: np.asarray(v[start : start + _ROWS]) for k, v in columns.items()} - for path, record, found in segments: - with open(path, "rb") as f: - for start, count in found: - f.seek(start) - yield np.fromfile(f, dtype=record, count=count) - - -def _build( - path: Path, - out: Path, - existing: NodeArrays | None, - segments: list[Path], - source: str | None, - duplicates: str, -) -> None: - """Write the store of ``existing`` and ``segments`` to the new directory - ``out`` and move it to ``path``.""" - scanned: _Scanned = [] - attrs: dict[str, dict[str, Any]] | None = ( - None if existing is None else existing.meta["attrs"] - ) - for segment in segments: - record, found = _scan(segment) - if record is None: - continue - if attrs is None: - attrs = _specs(record) - elif _specs(record) != attrs: - raise ValueError( - f"{segment} was written with the attributes {_specs(record)}, " - f"the rest of {path} with {attrs}" - ) - scanned.append((segment, record, found)) - if attrs is None: - raise FileNotFoundError(f"nothing was written to {path}") - total = (existing.num_nodes if existing is not None else 0) + sum( - count for _, _, found in scanned for _, count in found - ) - - out.mkdir(parents=True) - files = {_ID: "ids.npy", **{name: _file(name) for name in attrs}} - dtypes = {_ID: _ID_DTYPE, **{k: np.dtype(v["dtype"]) for k, v in attrs.items()}} - tails = { - _ID: (), - **{k: (v["size"],) if v["size"] else () for k, v in attrs.items()}, - } - - def write(rows: int, chunks: Iterable[Any]) -> None: - handles = {name: open(out / file, "wb") for name, file in files.items()} - try: - for name, handle in handles.items(): - np.lib.format.write_array_header_1_0( - handle, - { - "descr": np.lib.format.dtype_to_descr(dtypes[name]), - "fortran_order": False, - "shape": (rows, *tails[name]), - }, - ) - for chunk in chunks: - for name, handle in handles.items(): - np.ascontiguousarray(chunk[name], dtype=dtypes[name]).tofile(handle) - finally: - for handle in handles.values(): - handle.close() - - write(total, _chunks(existing, scanned)) - ids = np.load(out / "ids.npy") - order = np.argsort(ids, kind="stable") - again = np.flatnonzero(ids[order][1:] == ids[order][:-1]) - if len(again): - if duplicates != "last": - some = np.unique(ids[order][again])[:5].tolist() - raise ValueError( - f"{path}: a node id was written twice (for example {some}); a " - "node belongs to one block" - ) - # of the rows with one id the last written stays; the sort is - # stable, so that is the last of each run of equal ids - last = np.ones(total, dtype=bool) - last[again] = False - keep = np.zeros(total, dtype=bool) - keep[order[last]] = True - for file in files.values(): - os.rename(out / file, out / f"{file}.all") - every = { - name: np.load(out / f"{file}.all", mmap_mode="r") - for name, file in files.items() - } - total = int(keep.sum()) - write( - total, - ( - { - name: np.asarray(values[start : start + _ROWS])[ - keep[start : start + _ROWS] - ] - for name, values in every.items() - } - for start in range(0, len(keep), _ROWS) - ), - ) - del every - for file in files.values(): - (out / f"{file}.all").unlink() - ids = np.load(out / "ids.npy") - order = np.argsort(ids, kind="stable") - np.save(out / "order.npy", order.astype(" Generator[bool]: - """One finalize at a time. Yields False when ``folder`` is not there: - no worker wrote, or another finalize merged everything in it.""" - name = folder / _LOCK - fd = None - while fd is None: - try: - fd = os.open(name, os.O_RDWR | os.O_CREAT, 0o666) - except FileNotFoundError: - break - fcntl.flock(fd, fcntl.LOCK_EX) - try: - # the finalize waited for removes the lock file it held - current = os.fstat(fd).st_ino == os.stat(name).st_ino - except FileNotFoundError: - current = False - if not current: - os.close(fd) - fd = None - try: - yield fd is not None - finally: - if fd is not None: - os.close(fd) - - -def finalize_node_arrays( - path: Path | str, *, source: str | None = None, duplicates: str = "raise" -) -> Path: - """Merge what the worker writers of ``path`` appended into the store. - - The new store holds the nodes of the store at ``path``, if there is - one, and of every segment in ``.segments``; it replaces the - store, and the segments are removed. Call it in one process when the - writers are done (the limits are in the module documentation). With - nothing to merge it leaves the store as it is. - - ``source`` is recorded in the new store; left out, the store keeps - the ``source`` it had. - - ``duplicates`` says what a node id written more than once is: - ``"raise"`` (the default) refuses it with ``ValueError`` and leaves - the store and the segments as they were; ``"last"`` keeps the value - written last. Segments are taken in the order their writers were - opened, by the clocks of the machines that opened them, after the - store that is already there. - """ - path = Path(path) - if duplicates not in ("raise", "last"): - raise ValueError(f"duplicates is {duplicates!r}; it is 'raise' or 'last'") - folder = _segments_dir(path) - with _finalize_lock(folder) as pending: - segments = sorted(folder.glob("*.npys")) if pending else [] - stored = (path / META).is_file() - if not segments and not stored: - raise FileNotFoundError( - f"nothing was written to {path}: there is no store and no " - f"segment in {folder}" - ) - if segments: - existing = NodeArrays(path) if stored else None - if source is None and existing is not None: - source = existing.source - out = scratch_beside(path, "building") - try: - _build(path, out, existing, segments, source, duplicates) - finally: - shutil.rmtree(out, ignore_errors=True) - for segment in segments: - segment.unlink(missing_ok=True) - if pending: - # leave nothing beside the store, unless a writer is still there - try: - (folder / _LOCK).unlink() - folder.rmdir() - except OSError: - pass - return path - - -class NodeArraysWriter: - """Writes a node attribute store a block at a time. - - :: - - with NodeArraysWriter(path, {"embedding": 64}) as out: - for ids, embedding in blocks: - out.append(ids, embedding=embedding) - - ``attrs`` maps each attribute to its vector length, ``None`` for a - scalar; ``dtypes`` names a dtype for those that are not ``float32``. - ``ids`` is not an attribute name. - - As above, with one writer, the store appears at ``path`` only when the - block is left without an error, and it replaces what was there. An - error leaves ``path`` as it was and nothing beside it. - - With ``worker=True`` the writer is one of several, in as many - processes:: - - # in each worker - with NodeArraysWriter(path, {"embedding": 64}, worker=True) as out: - for ids, embedding in my_blocks: - out.append(ids, embedding=embedding) - - # in one process, when the workers are done - finalize_node_arrays(path, source="model 3") - - Every ``append`` is then a record in a segment file of this writer in - ``.segments``, complete when ``append`` returns, and it stays - whatever happens to the writer afterwards. Nothing changes at ``path`` - before :func:`finalize_node_arrays`, which adds the segments to the - store that is there. Every writer of a store declares the same - attributes. Open the writer in the process that appends to it. The - design and its limits are in the documentation of - :mod:`funlib.persistence.graphs.node_arrays`. - """ - - def __init__( - self, - path: Path | str, - attrs: Mapping[str, int | None], - *, - dtypes: Mapping[str, Any] | None = None, - source: str | None = None, - worker: bool = False, - ): - self.path = Path(path) - self.attrs = dict(attrs) - if not self.attrs: - raise ValueError("a node attribute store holds at least one attribute") - if _ID in self.attrs: - raise ValueError( - f"{_ID!r} is not an attribute name: it names the node ids of a store" - ) - for name, length in self.attrs.items(): - if length is not None and (isinstance(length, bool) or length < 1): - raise ValueError( - f"attribute {name!r}: a vector has a length of 1 or more and " - f"a scalar has None, not {length!r}" - ) - self.dtypes = { - name: np.dtype((dtypes or {}).get(name, "float32")).newbyteorder("<") - for name in self.attrs - } - for name, dtype in self.dtypes.items(): - if dtype.kind not in "fiub": - raise ValueError(f"attribute {name!r}: {dtype} is not a number type") - if worker and source is not None: - raise ValueError( - "source belongs to the store, not to one of its writers: give " - "it to finalize_node_arrays" - ) - self.source = source - self.worker = worker - self.num_nodes = 0 - self._record = np.dtype( - [(_ID, _ID_DTYPE)] - + [ - (name, self.dtypes[name], () if length is None else (length,)) - for name, length in self.attrs.items() - ] - ) - self._scratch: Path | None = None - self._segment: Path | None = None - self._file: Any = None - - def __enter__(self) -> NodeArraysWriter: - if self.worker: - meta = self.path / META - if meta.is_file(): - stored = json.loads(meta.read_text()).get("attrs") - if stored != _specs(self._record): - raise ValueError( - f"{self.path} holds the attributes {stored}; this writer " - f"declares {_specs(self._record)}" - ) - folder = _segments_dir(self.path) - else: - # a directory no other writer has: two writers to one path - # never see each other's files - folder = self._scratch = scratch_beside(self.path, "writing") - folder.mkdir(parents=True, exist_ok=True) - name = f"{time.time_ns():020d}-{os.getpid()}-{uuid.uuid4().hex}.npys" - self._segment = folder / name - self._file = open(self._segment, "ab") - # a record of no rows states the attributes, so that writers with - # no node to write still leave a store, an empty one - self._write(np.zeros(0, dtype=self._record)) - return self - - def _write(self, records: np.ndarray) -> None: - np.lib.format.write_array( - self._file, records, version=(1, 0), allow_pickle=False - ) - self._file.flush() - - def append(self, ids: Any, **values: Any) -> None: - """Add nodes: their ids and one array per attribute, aligned.""" - if self._file is None: - raise RuntimeError("append belongs inside the writer's with block") - ids = np.ascontiguousarray(ids, dtype=_ID_DTYPE) - if set(values) != set(self.attrs): - raise ValueError( - f"expected the attributes {sorted(self.attrs)}, got {sorted(values)}" - ) - records = np.empty(len(ids), dtype=self._record) - records[_ID] = ids - for name, length in self.attrs.items(): - block = np.asarray(values[name], dtype=self.dtypes[name]) - shape = (len(ids),) if length is None else (len(ids), length) - if block.shape != shape: - raise ValueError( - f"attribute {name!r} has shape {block.shape}, expected {shape}" - ) - records[name] = block - if len(records): - self._write(records) - self.num_nodes += len(ids) - - def __exit__(self, kind: Any, *_: Any) -> None: - self._file.close() - self._file = None - if self._scratch is None or self._segment is None: - return # a worker: its records wait for finalize_node_arrays - try: - if kind is None: - _build( - self.path, - self._scratch / "store", - None, - [self._segment], - self.source, - "raise", - ) - finally: - shutil.rmtree(self._scratch, ignore_errors=True) - - -def write_node_arrays( - path: Path | str, - ids: Any, - values: Mapping[str, Any], - *, - source: str | None = None, -) -> Path: - """Write node attributes that are in memory as one store, replacing - what is at ``path``.""" - arrays = {name: np.asarray(value) for name, value in values.items()} - attrs = { - name: (int(value.shape[1]) if value.ndim == 2 else None) - for name, value in arrays.items() - } - dtypes = {name: value.dtype for name, value in arrays.items()} - with NodeArraysWriter(path, attrs, dtypes=dtypes, source=source) as out: - out.append(ids, **arrays) - return Path(path) diff --git a/tests/test_node_arrays.py b/tests/test_node_arrays.py deleted file mode 100644 index 724415d..0000000 --- a/tests/test_node_arrays.py +++ /dev/null @@ -1,409 +0,0 @@ -"""Node attributes stored in arrays beside the graph they were computed on.""" - -import json -import multiprocessing as mp - -import numpy as np -import pytest - -from funlib.persistence.graphs import ( - NodeArrays, - NodeArraysWriter, - finalize_node_arrays, - write_node_arrays, -) - -IDS = np.array([40, 7, 19, 3, 88], dtype=np.uint64) -VECTORS = np.arange(15, dtype=np.float32).reshape(5, 3) -SCORES = np.array([0.5, 0.25, 0.75, 1.0, 0.0], dtype=np.float32) - - -def stored(tmp_path, **kwargs): - return NodeArrays( - write_node_arrays( - tmp_path / "out.nodes", IDS, {"vec": VECTORS, "score": SCORES}, **kwargs - ) - ) - - -def test_values_read_back_in_the_order_the_ids_are_asked_for(tmp_path): - found, values = stored(tmp_path).read([3, 88, 40]) - assert found.tolist() == [True, True, True] - assert values["vec"].tolist() == VECTORS[[3, 4, 0]].tolist() - assert values["score"].tolist() == [1.0, 0.0, 0.5] - - -def test_a_node_that_was_never_written_is_not_found_and_reads_as_nan(tmp_path): - found, values = stored(tmp_path).read([7, 5, 1000], attrs=["score"]) - assert found.tolist() == [True, False, False] - assert list(values) == ["score"] # a read names the attributes it wants - assert values["score"][0] == 0.25 - assert np.isnan(values["score"][1:]).all() - - -def test_an_unknown_attribute_is_refused_with_the_ones_stored(tmp_path): - with pytest.raises(KeyError, match=r"no attribute 'nope'.*\['score', 'vec'\]"): - stored(tmp_path).read([7], attrs=["nope"]) - - -def test_the_store_says_what_it_holds_and_where_it_comes_from(tmp_path): - arrays = stored(tmp_path, source="fragments") - assert arrays.num_nodes == 5 - assert arrays.attrs == {"vec": 3, "score": None} - assert arrays.source == "fragments" - assert "graph_digest" not in arrays.meta - assert arrays.ids.tolist() == IDS.tolist() - - -def test_the_layout_on_disk_is_plain_npy_files_and_a_meta_json(tmp_path): - path = stored(tmp_path).path - assert sorted(p.name for p in path.iterdir()) == [ - "ids.npy", - "meta.json", - "node_score.npy", - "node_vec.npy", - "order.npy", - ] - assert np.load(path / "order.npy").tolist() == np.argsort(IDS).tolist() - assert np.load(path / "node_vec.npy").shape == (5, 3) - assert json.loads((path / "meta.json").read_text())["attrs"] == { - "vec": {"dtype": " Date: Wed, 25 Nov 2026 14:36:37 -0800 Subject: [PATCH 10/15] CSRGraphDataBase: extra node attributes in directories of their own (extra_fields) Values computed on a finished graph are written and read through the database, and kept outside the graph's directory: g = CSRGraphDataBase(path, mode='r+', extra_fields={'embedding': 'pred/model_a'}, node_attrs={'embedding': Vec('float32', 64)}) g.write_node_arrays(ids, embedding=values) - An extra directory holds one array per attribute in the graph's row order, its own segments and its own lock. Writes append to segments from any number of processes; finalize merges them into the arrays of the attributes that were written and reads only the graph's node ids. A later finalize adds to what is there; the last value written stays. - The graph is read-only through such a handle: edge writes, writes of stored node attributes and drop_edges raise GraphIsReadOnly, and nothing in the graph's directory is created, changed or locked. - read_arrays, read_block, read_nodes and read_graph return the extra attributes by name; node_attrs lists them. A node without a value reads as NaN, or 0 for an integer or bool. - The directory records the graph's node count, the name of its arrays and a crc32 of its node ids in row order. Another node count, other ids or another order is refused at open; added edges or a rebuild from the same nodes are accepted. - A value for an id that is not a node raises at finalize, which then changes nothing. The lock of the graph's finalize is now the helper the extra directories use as well. Co-Authored-By: Claude Fable 5.2 --- docs/source/api.md | 4 + docs/source/graphs.md | 93 ++++ .../persistence/graphs/csr_graph_database.py | 474 ++++++++++++++++- tests/test_csr_extra_fields.py | 492 ++++++++++++++++++ 4 files changed, 1046 insertions(+), 17 deletions(-) create mode 100644 tests/test_csr_extra_fields.py diff --git a/docs/source/api.md b/docs/source/api.md index 8e97415..169360a 100644 --- a/docs/source/api.md +++ b/docs/source/api.md @@ -62,4 +62,8 @@ The graph databases are importable from `funlib.persistence.graphs`. .. autoclass:: funlib.persistence.graphs.csr_graph_database.CSRGraphDataBase :members: :show-inheritance: + +.. autoexception:: funlib.persistence.graphs.csr_graph_database.UnfinalizedWrites + +.. autoexception:: funlib.persistence.graphs.csr_graph_database.GraphIsReadOnly ``` diff --git a/docs/source/graphs.md b/docs/source/graphs.md index 187d238..e380c11 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -98,3 +98,96 @@ values = compute(nodes, edges)[nodes["own"]] ``` `CSRGraphDataBase.is_database(path)` tells such a directory from any other. + +## Values on the nodes of a graph: extra fields + +Values computed on a finished graph, such as an embedding per node, do not +have to go into the graph's directory. The graph is opened with +`extra_fields`, a mapping from attribute name to the directory that holds +it, and the extra attributes are written and read through the database +like stored ones: + +```python +from funlib.persistence.graphs import CSRGraphDataBase +from funlib.persistence.types import Vec + +g = CSRGraphDataBase( + "fragments.csr", + mode="r+", + extra_fields={"embedding": "pred/model_a", "label": "pred/model_a"}, + node_attrs={"embedding": Vec("float32", 64), "label": "int32"}, +) +with g.bulk_write_mode(): + for roi in blocks: + nodes, edges = g.read_block(roi, num_steps=2, node_attrs=["position"]) + own = nodes["own"] + e, l = model(nodes, edges) + g.write_node_arrays(nodes["id"][own], embedding=e[own], label=l[own]) + +nodes, edges = g.read_arrays(roi, node_attrs=["position", "embedding"]) +``` + +A directory holds any number of attributes, and a handle can name +attributes from several directories. An attribute its directory does not +hold yet is created when the graph is opened with mode `"r+"`, with the +type `node_attrs` gives it; later the type may be left out. `g.node_attrs` +lists the extra attributes after the stored ones, and `read_arrays`, +`read_block`, `read_nodes` and `read_graph` return them by name, for the +same regions and steps. + +**The graph is read-only through such a handle.** Nothing in the graph's +directory is created, changed or locked. Writing edges, writing nodes with +stored attributes, and `drop_edges` raise `GraphIsReadOnly`. The node +writes (`write_node_arrays`, `write_attrs`, `write_nodes`, +`bulk_write_nodes`) take extra attributes only, for nodes that exist, and +need no position. + +Writing is the database's: each handle appends to a segment file of its own +in the extra directory, and `finalize()`, or leaving `bulk_write_mode` in +the main process, merges the segments into the arrays. In a blockwise task +each worker opens the graph with the same `extra_fields` and writes inside +`bulk_write_mode(worker=True)`; the main process finalizes at the end. The +finalize rebuilds the arrays of the attributes that were written and reads +the graph's node ids, nothing else of the graph. A later finalize adds to +the values that are there, so a run can be taken up again; a node written +twice keeps its last value. + +The values are stored in the graph's row order, one array per attribute, so +a region read has the graph's locality and there is no lookup by id. This +ties a directory to one graph. It records the graph's node count, the name +of the graph's arrays, and a checksum of its node ids in row order, and +opening it with a graph of another node count, other ids or another row +order raises `ValueError`. Adding edges to the graph, or building it again +from the same nodes, keeps the extra fields valid; adding nodes does not. + +``` +pred/model_a/meta.json version, extends, node_attrs, arrays +pred/model_a/node_embedding-.npy (N, 64), in the graph's row order +pred/model_a/node_label-.npy (N,) +pred/model_a/segments/ writes not yet in the arrays +pred/model_a/finalize.lock +``` + +What to know: + +- A node that was never written reads as NaN, and as 0 for an integer or a + bool, which cannot be told from a written 0. Use a float, or a value + other than 0, where the difference matters. A written NaN counts as not + written. +- A value for an id that is not a node of the graph is found at the + finalize, which raises `ValueError` and changes nothing. The segments + stay; remove the one named in the error to go on. +- Finalize when the writers are done: a record appended to a segment while + it is being merged is lost. Several finalizes at once run one after the + other. A record cut short by a killed writer is ignored with a warning, + and its block has to be written again. +- Which of two processes wrote a node "last" is decided by the names of + their segment files, not by time. Within one process it is the order of + the writes. +- A read that returns an extra attribute raises `UnfinalizedWrites` while + its directory has segments. A read that names other attributes does not, + so a worker reads the graph (`node_attrs=[...]` without the attribute it + is writing) while the run is under way. +- Finalize holds the node ids and the attributes it rebuilds in memory. +- A handle sees the arrays of the finalize it last loaded; open the graph + again to see what another process finalized since. diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 669a235..eb78efe 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -18,6 +18,12 @@ :meth:`CSRGraphDataBase.finalize` merges the segments into a new set of arrays; leaving :meth:`CSRGraphDataBase.bulk_write_mode` in the main process does that. Reads see the arrays of the last finalize. + +Node attributes that are computed on a finished graph (an embedding, a +label per node) can be kept outside the graph's directory, as *extra +fields*: see ``extra_fields`` of :class:`CSRGraphDataBase`. They are +written and finalized the same way, into a directory of their own, and the +graph's directory is not touched. """ from __future__ import annotations @@ -28,7 +34,8 @@ import os import shutil import uuid -from collections.abc import Iterable, Mapping, Sequence +import zlib +from collections.abc import Generator, Iterable, Mapping, Sequence from contextlib import contextmanager from pathlib import Path from typing import Any @@ -44,6 +51,7 @@ logger = logging.getLogger(__name__) FORMAT_VERSION = 1 +EXTRA_FORMAT_VERSION = 1 ID_DTYPE = np.dtype(" Generator[None]: + """Hold the lock of a directory of arrays: one finalize, or one change + of its ``meta.json``, at a time. A second process waits.""" + with open(folder / "finalize.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + yield + + def _spec(attr_type: AttributeType) -> dict[str, Any]: """An attribute type as JSON: a numpy dtype name and a vector size.""" size = 0 @@ -173,6 +195,60 @@ def read(path: Path) -> list[np.ndarray]: return records +class _ExtraFields: + """A directory of extra node attributes of one graph:: + + meta.json version, extends, node_attrs, arrays + node_-.npy one array per attribute, in the graph's row order + segments/ writes that are not in the arrays yet + finalize.lock + + ``extends`` says which graph the rows are those of: its node count, + the name of the set of arrays it was last built into, and a checksum + of its node ids in row order. ``arrays`` names the file of each + attribute, or nothing for one that was declared and never finalized. + """ + + def __init__(self, path: Path): + self.path = path + self.meta: dict[str, Any] | None = None + self.reload() + + def reload(self) -> None: + file = self.path / "meta.json" + if not file.exists(): + self.meta = None + return + meta = json.loads(file.read_text()) + if not isinstance(meta, dict) or "extends" not in meta: + raise ValueError(f"{self.path} is not a directory of extra node attributes") + if meta["version"] != EXTRA_FORMAT_VERSION: + raise RuntimeError( + f"{self.path} is extra-fields format version {meta['version']}, " + f"this library reads version {EXTRA_FORMAT_VERSION}" + ) + self.meta = meta + + @property + def stored(self) -> dict[str, Any]: + if self.meta is None: + raise RuntimeError(f"{self.path} holds no extra node attributes") + return self.meta + + def write(self) -> None: + tmp = self.path / f"meta.json.{uuid.uuid4().hex}" + tmp.write_text(json.dumps(self.meta, indent=2) + "\n") + os.replace(tmp, self.path / "meta.json") + + def pending(self) -> list[Path]: + folder = self.path / "segments" + return sorted(folder.glob("*.npys")) if folder.exists() else [] + + def record_dtype(self, attrs: Iterable[str]) -> np.dtype: + specs = self.stored["node_attrs"] + return np.dtype([("id", ID_DTYPE)] + [(a, *_field(specs[a])) for a in attrs]) + + class CSRGraphDataBase(GraphDataBase): """A graph in memory-mapped CSR arrays under a directory. @@ -203,6 +279,67 @@ class CSRGraphDataBase(GraphDataBase): Edge length of a grid cell, in the units of the positions: one number or one per dimension. Pick it a few times smaller than the regions that will be read. + + extra_fields: + + Node attributes of this graph that are kept in other + directories: attribute name to directory. The graph is opened + as it is (mode ``"r"`` or ``"r+"``) and the extra attributes + are read with it and written through it:: + + g = CSRGraphDataBase(path, mode="r+", extra_fields={ + "embedding": "pred/modelA", "label": "pred/modelA"}, + node_attrs={"embedding": Vec("float32", 64), "label": "int32"}) + g.write_node_arrays(ids, embedding=e, label=l) # in bulk_write_mode + g.read_arrays(roi, node_attrs=["position", "embedding"]) + + A directory holds any number of attributes; a handle sees those + it names. An attribute that its directory does not hold yet is + created, in mode ``"r+"``, with the type ``node_attrs`` gives + it. Extra attributes are read like stored ones (same regions, + steps, filters) and listed by :attr:`node_attrs`. + + **The graph is read-only through such a handle.** Writes of + edges, of nodes with stored attributes, and ``drop_edges`` + raise :class:`GraphIsReadOnly`; nothing in the graph's + directory is created, changed or locked. The node writes + (``write_node_arrays``, ``write_attrs``, ``write_nodes``, + ``bulk_write_nodes``) take extra attributes only and need no + position. + + Writing works as for the graph: each handle appends to a + segment file of its own in the extra directory, from any + number of processes, and :meth:`finalize` (or leaving + :meth:`bulk_write_mode` in the main process) merges the + segments into the arrays of the attributes that were written. + It reads the graph's node ids and nothing else of the graph. A + later finalize adds to the values that are there; a node + written twice keeps its last value. + + Values are stored in the graph's row order, so they belong to + one graph. The directory records that graph's node count, the + name of its arrays and a checksum of its node ids in row order; + opening it with a graph of another node count, or of other ids + or another row order, raises ``ValueError``. Adding edges to + the graph, or rebuilding it from the same nodes, keeps its + extra fields valid. + + Limits. A node that was never written reads as NaN (0 for an + integer or a bool, which cannot be told from a written 0). A + written NaN counts as not written. Writing an id that is not a + node of the graph is found at finalize, which then raises + ``ValueError`` and changes nothing; the segments stay until + they are removed. Finalize holds the node ids and every + attribute it rebuilds in memory. As for the graph: finalize + when the writers are done (a record appended to a segment while + it is merged is lost), a record cut short by a killed writer is + ignored with a warning, and which of two processes wrote "last" + is decided by the names of their segment files, not by time. A + read that returns an extra attribute raises + :class:`UnfinalizedWrites` while its directory has segments; + reads of other attributes do not. A handle sees the arrays of + the finalize it last loaded: open the graph again to see what + another process finalized since. """ read_modes = ("r", "r+") @@ -218,14 +355,22 @@ def __init__( node_attrs: dict[str, AttributeType] | None = None, edge_attrs: dict[str, AttributeType] | None = None, cell_size: float | Iterable[float] | None = None, + extra_fields: Mapping[str, Path | str] | None = None, ): if directed: raise NotImplementedError("the CSR backend stores undirected graphs") self.path = Path(path) self.mode = mode self.directed = False + self.extra_fields = {k: Path(v) for k, v in (extra_fields or {}).items()} + self._extra: dict[str, _ExtraFields] = {} + if self.extra_fields and mode not in self.read_modes: + raise ValueError( + f"mode {mode!r} creates the graph; extra_fields belong to a " + "graph that exists and are opened with mode 'r' or 'r+'" + ) self._arrays: dict[str, np.ndarray] | None = None - self._segments: dict[str, _Segment] = {} + self._segments: dict[Any, _Segment] = {} self._bulk_depth = 0 self.meta: dict[str, Any] = {} if mode in self.create_modes: @@ -276,6 +421,8 @@ def __init__( (edge_attrs, self.meta["edge_attrs"], "edge"), ): for name, attr_type in (given or {}).items(): + if what == "node" and name in self.extra_fields: + continue # checked against its own directory below if name not in stored: raise ValueError( f"{what} attribute {name!r} is not in {self.path}; " @@ -293,6 +440,250 @@ def __init__( self.cell_size = np.asarray(self.meta["cell_size"], dtype=float) stored_roi = self.meta.get("total_roi") self.total_roi = None if stored_roi is None else Roi(*stored_roi) + if self.extra_fields: + self._open_extra_fields(node_attrs or {}) + + # -- extra fields ------------------------------------------------------- + + @staticmethod + def stored_extra_fields(path: Path | str) -> dict[str, AttributeType]: + """The node attributes a directory of extra fields holds, with their + types; empty when ``path`` is not such a directory.""" + try: + extra = _ExtraFields(Path(path)) + except (ValueError, NotADirectoryError): + return {} + if extra.meta is None: + return {} + return CSRGraphDataBase._types(extra.meta["node_attrs"]) + + def _extends(self) -> dict[str, Any]: + """What an extra directory records of this graph.""" + ids = np.load(self.path / self.meta["generation"] / "ids.npy", mmap_mode="r") + checksum = 0 + for start in range(0, len(ids), 1 << 22): + checksum = zlib.crc32(np.asarray(ids[start : start + (1 << 22)]), checksum) + return { + "num_nodes": self.meta["num_nodes"], + "generation": self.meta["generation"], + "ids_crc32": checksum, + } + + def _check_extends(self, extra: _ExtraFields) -> None: + of = extra.stored["extends"] + if of["num_nodes"] != self.meta["num_nodes"]: + raise ValueError( + f"{extra.path} holds attributes of a graph of {of['num_nodes']} " + f"nodes; {self.path} has {self.meta['num_nodes']}" + ) + # the same set of arrays is the same rows; another set (edges were + # added, the graph was built again) is compared by its node ids + if of["generation"] != self.meta["generation"]: + if of["ids_crc32"] != self._extends()["ids_crc32"]: + raise ValueError( + f"{extra.path} holds attributes of a graph with other nodes, " + f"or the same nodes in another order, than {self.path}" + ) + + def _open_extra_fields(self, given: Mapping[str, AttributeType]) -> None: + if self.meta["generation"] is None: + raise ValueError( + f"{self.path} was never finalized; extra fields belong to a " + "graph whose nodes are written" + ) + taken = sorted(set(self.extra_fields) & set(self.meta["node_attrs"])) + if taken: + raise ValueError( + f"{taken} are node attributes of {self.path} itself and cannot " + "be extra fields" + ) + folders: dict[Path, _ExtraFields] = {} + for name, folder in self.extra_fields.items(): + key = folder.resolve() + if key == self.path.resolve(): + raise ValueError("extra fields are kept outside the graph's directory") + if key not in folders: + folders[key] = _ExtraFields(folder) + self._extra[name] = folders[key] + for extra in folders.values(): + names = [n for n, e in self._extra.items() if e is extra] + specs = {n: _spec(given[n]) for n in names if n in given} + held = {} if extra.meta is None else extra.meta["node_attrs"] + new = [n for n in names if n not in held] + if new and self.mode == "r": + raise ValueError( + f"node attributes {new} are not in {extra.path}; it has " + f"{sorted(held)}. Open with mode 'r+' to create them" + ) + untyped = [n for n in new if n not in specs] + if untyped: + raise ValueError( + f"{untyped} are new in {extra.path}: give their types in node_attrs" + ) + if new: + extra.path.mkdir(parents=True, exist_ok=True) + with _locked(extra.path): + extra.reload() # another process may have declared them + if extra.meta is None: + extra.meta = { + "version": EXTRA_FORMAT_VERSION, + "extends": self._extends(), + "node_attrs": {}, + "arrays": {}, + } + for name in new: + extra.meta["node_attrs"].setdefault(name, specs[name]) + extra.write() + self._check_extends(extra) + for name, spec in specs.items(): + if spec != extra.stored["node_attrs"][name]: + raise ValueError( + f"node attribute {name!r} is {extra.stored['node_attrs'][name]} " + f"in {extra.path}, not {spec}" + ) + + def _extra_folders(self) -> list[_ExtraFields]: + return list({id(e): e for e in self._extra.values()}.values()) + + def _node_specs(self) -> dict[str, dict[str, Any]]: + """Every node attribute this handle reads: stored, then extra.""" + specs = dict(self.meta["node_attrs"]) + for name, extra in self._extra.items(): + specs[name] = extra.stored["node_attrs"][name] + return specs + + def _refuse(self, what: str) -> None: + if self._extra: + raise GraphIsReadOnly( + f"{what}: {self.path} is read-only through a handle opened with " + "extra_fields; only the extra node attributes " + f"{sorted(self._extra)} are written. Open the graph without " + "extra_fields to change it" + ) + + def _split_extra( + self, attrs: Iterable[str] + ) -> list[tuple[_ExtraFields, list[str]]]: + """Extra attribute names by the directory that holds them.""" + attrs = list(attrs) + stored = [a for a in attrs if a in self.meta["node_attrs"]] + if stored: + self._refuse(f"cannot write the node attributes {stored}") + unknown = [a for a in attrs if a not in self._extra] + if unknown: + raise ValueError(f"unknown node attributes {unknown}") + return [ + (extra, [a for a in attrs if self._extra[a] is extra]) + for extra in self._extra_folders() + if any(self._extra[a] is extra for a in attrs) + ] + + def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None: + ids = np.asarray(ids) + for extra, names in self._split_extra(attrs): + records = np.empty(len(ids), dtype=extra.record_dtype(names)) + records["id"] = ids + for name in names: + values = np.asarray(attrs[name]) + if values.ndim == 0 or len(values) != len(ids): + raise ValueError( + f"node attribute {name!r} has shape {values.shape}; " + f"expected one entry for each of the {len(ids)} ids" + ) + records[name] = values + self._segment("nodes", extra.path).append(records) + + def _write_extra_rows(self, nodes, roi: Roi | None, attributes) -> None: + names = list(self._extra) if attributes is None else list(attributes) + for extra, own in self._split_extra(names): + groups: dict[tuple[str, ...], list[tuple]] = {} + for node_id, data in nodes.items(): + if roi is not None: + position = self._position(data) + if position is None or not roi.contains(tuple(position)): + continue + present = tuple(a for a in own if data.get(a) is not None) + if not present: + continue + values = [ + tuple(data[a]) if np.ndim(data[a]) else data[a] for a in present + ] + groups.setdefault(present, []).append((node_id, *values)) + for present, rows in groups.items(): + self._segment("nodes", extra.path).append( + np.array(rows, dtype=extra.record_dtype(present)) + ) + + def _finalize_extra(self, extra: _ExtraFields) -> None: + paths = extra.pending() + if not paths: + return + extra.reload() + self._reload_meta() + self._check_extends(extra) + # the node ids are all that is read of the graph + ids = np.load(self.path / self.meta["generation"] / "ids.npy") + n = len(ids) + by_id = np.argsort(ids, kind="stable") + sorted_ids = ids[by_id] + specs = extra.stored["node_attrs"] + files = extra.stored["arrays"] + values: dict[str, np.ndarray] = {} + for path in paths: + for batch in _Segment.read(path): + at = np.searchsorted(sorted_ids, batch["id"]) + at[at == n] = 0 + known = ( + sorted_ids[at] == batch["id"] + if n + else np.zeros(len(batch), dtype=bool) + ) + if not known.all(): + some = np.unique(batch["id"][~known])[:5].tolist() + raise ValueError( + f"{path} holds values for {int((~known).sum())} ids that " + f"are not nodes of {self.path} (for example {some}); " + f"nothing was finalized in {extra.path}" + ) + rows = by_id[at] + for name in (batch.dtype.names or ())[1:]: + if name not in specs: + raise ValueError( + f"{path} holds {name!r}, unknown to {extra.path}" + ) + if name not in values: + values[name] = self._extra_array(extra, name, n, copy=True) + written = self._present(batch[name]) + values[name][rows[written]] = batch[name][written] + previous = [files.get(name) for name in values] + for name, array in values.items(): + file = f"node_{name}-{uuid.uuid4().hex[:12]}.npy" + np.save(extra.path / file, array) + files[name] = file + extra.stored["extends"] = { + "num_nodes": n, + "generation": self.meta["generation"], + "ids_crc32": zlib.crc32(ids), + } + extra.write() + for file in previous: + if file is not None: + (extra.path / file).unlink(missing_ok=True) + for path in paths: + path.unlink(missing_ok=True) + + @staticmethod + def _extra_array(extra: _ExtraFields, name: str, n: int, copy: bool = False): + """One extra attribute of every node, in row order. One that was + never finalized is all missing values.""" + file = extra.stored["arrays"].get(name) + if file is not None: + return np.load(extra.path / file, mmap_mode=None if copy else "r") + dtype, *shape = _field(extra.stored["node_attrs"][name]) + full = (n, *(shape[0] if shape else ())) + if copy: + return np.full(full, _missing(dtype), dtype=dtype) + return np.broadcast_to(np.asarray(_missing(dtype), dtype=dtype), full) @staticmethod def is_database(path: Path | str) -> bool: @@ -423,7 +814,8 @@ def _write_meta(self) -> None: def _reload_meta(self) -> None: self.meta = json.loads((self.path / "meta.json").read_text()) - def _types(self, specs: dict[str, dict]) -> dict[str, AttributeType]: + @staticmethod + def _types(specs: dict[str, dict]) -> dict[str, AttributeType]: out: dict[str, AttributeType] = {} for name, spec in specs.items(): dtype = np.dtype(spec["dtype"]).name @@ -432,7 +824,9 @@ def _types(self, specs: dict[str, dict]) -> dict[str, AttributeType]: @property def node_attrs(self) -> dict[str, AttributeType]: - return self._types(self.meta["node_attrs"]) + """The node attributes and their types: those stored in the graph, + then the extra fields this handle was opened with.""" + return self._types(self._node_specs()) @property def edge_attrs(self) -> dict[str, AttributeType]: @@ -473,10 +867,16 @@ def _open_arrays(self) -> dict[str, np.ndarray] | None: if self.meta["generation"] is None: return None folder = self.path / self.meta["generation"] - self._arrays = { + arrays = { name: np.load(folder / f"{name}.npy", mmap_mode="r") for name in self._array_names() } + for extra in self._extra_folders(): + extra.reload() + self._check_extends(extra) + for name, extra in self._extra.items(): + arrays[f"node_{name}"] = self._extra_array(extra, name, len(arrays["ids"])) + self._arrays = arrays return self._arrays def _readable(self) -> dict[str, np.ndarray] | None: @@ -489,13 +889,18 @@ def _readable(self) -> dict[str, np.ndarray] | None: # -- writing ------------------------------------------------------------ - def _segment(self, kind: str) -> _Segment: + def _segment(self, kind: str, folder: Path | None = None) -> _Segment: + """This handle's segment of ``kind`` in the graph's directory, or in + ``folder``, a directory of extra fields.""" if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") - if kind not in self._segments: + if folder is None: + self._refuse(f"cannot write {kind}") + key = (kind, folder) + if key not in self._segments: name = f"{kind}-{os.getpid()}-{uuid.uuid4().hex}.npys" - self._segments[kind] = _Segment(self.path / "segments" / name) - return self._segments[kind] + self._segments[key] = _Segment((folder or self.path) / "segments" / name) + return self._segments[key] def _record_dtype(self, kind: str, attrs: list[str]) -> np.dtype: specs = self.meta[f"{kind}_attrs"] @@ -509,7 +914,12 @@ def _record_dtype(self, kind: str, attrs: list[str]) -> np.dtype: def write_node_arrays(self, ids: np.ndarray, **attrs: np.ndarray) -> None: """Append nodes given as arrays: ``ids`` and one array per attribute - (the position among them).""" + (the position among them). Through a handle with ``extra_fields``: + values of extra attributes for nodes of the graph, no position.""" + if self._extra: + self._write_extra_arrays(ids, attrs) + self._after_write() + return if self.position_attribute not in attrs: raise ValueError(f"nodes need their {self.position_attribute!r}") records = np.empty(len(ids), dtype=self._record_dtype("node", list(attrs))) @@ -524,6 +934,7 @@ def write_edge_arrays( ) -> None: """Append edges given as arrays: endpoint ids and one array per attribute. The order of an edge's endpoints does not matter.""" + self._refuse("cannot write edges") records = np.empty(len(u), dtype=self._record_dtype("edge", list(attrs))) u, v = np.asarray(u, dtype=ID_DTYPE), np.asarray(v, dtype=ID_DTYPE) records["u"], records["v"] = np.minimum(u, v), np.maximum(u, v) @@ -559,6 +970,10 @@ def _append_rows( ) def bulk_write_nodes(self, nodes, roi: Roi | None = None, attributes=None) -> None: + if self._extra: + self._write_extra_rows(nodes, roi, attributes) + self._after_write() + return attrs = ( list(attributes) if attributes is not None @@ -580,6 +995,7 @@ def bulk_write_nodes(self, nodes, roi: Roi | None = None, attributes=None) -> No def bulk_write_edges( self, nodes, edges, roi: Roi | None = None, attributes=None ) -> None: + self._refuse("cannot write edges") attrs = ( list(attributes) if attributes is not None @@ -605,6 +1021,8 @@ def bulk_write_graph( node_attrs: list[str] | None = None, edge_attrs: list[str] | None = None, ) -> None: + if write_edges: + self._refuse("cannot write edges (pass write_edges=False)") with self.bulk_write_mode(worker=self._bulk_depth > 0): if write_nodes: self.bulk_write_nodes(graph.nodes, roi=roi, attributes=node_attrs) @@ -668,6 +1086,8 @@ def write_attrs( ) -> None: """Write attribute values of nodes and edges that exist. Values are merged at finalize: an attribute keeps its last written value.""" + if edge_attrs: + self._refuse("cannot write edge attributes") with self.bulk_write_mode(worker=self._bulk_depth > 0): if node_attrs: self.bulk_write_nodes(graph.nodes, roi=roi, attributes=node_attrs) @@ -695,6 +1115,7 @@ def drop_edges(self) -> None: """Remove every edge, keeping the nodes.""" if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") + self._refuse("cannot drop edges") for path in self._pending(): if path.name.startswith("edges-"): path.unlink() @@ -777,7 +1198,11 @@ def finalize(self) -> None: A node or edge written more than once keeps, per attribute, its last written value. An edge with an endpoint that is not a node is - dropped. Holds the whole graph in memory.""" + dropped. Holds the whole graph in memory. + + Through a handle with ``extra_fields`` it merges the segments of + the extra directories instead, into the arrays of the attributes + that were written, and leaves the graph alone.""" if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") for segment in self._segments.values(): @@ -785,8 +1210,13 @@ def finalize(self) -> None: self._segments = {} # one finalize at a time: a second process waits, then finds the # segments the first one merged gone - with open(self.path / "finalize.lock", "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + if self._extra: + for extra in self._extra_folders(): + with _locked(extra.path): + self._finalize_extra(extra) + self._arrays = None + return + with _locked(self.path): self._finalize() def _finalize(self) -> None: @@ -970,9 +1400,19 @@ def _rows_in(self, arrays: dict[str, np.ndarray], roi: Roi | None) -> np.ndarray def _node_columns(self, arrays, rows, attrs: list[str]) -> dict[str, np.ndarray]: out = {"id": np.asarray(arrays["ids"][rows])} + specs = self._node_specs() for name in attrs: - if name not in self.meta["node_attrs"]: + if name not in specs: raise ValueError(f"unknown node attribute {name!r}") + for extra in { + id(self._extra[a]): self._extra[a] for a in attrs if a in self._extra + }.values(): + if extra.pending(): + raise UnfinalizedWrites( + f"{extra.path} has writes that are not in its arrays yet; " + "call finalize(), or read without its attributes" + ) + for name in attrs: out[name] = np.asarray(arrays[f"node_{name}"][rows]) return out @@ -1026,7 +1466,7 @@ def read_arrays( f"edge_ends is {edge_ends!r}; it is one of 'both', 'u', 'either'" ) arrays = self._readable() - node_attrs = list(self.meta["node_attrs"]) if node_attrs is None else node_attrs + node_attrs = list(self._node_specs()) if node_attrs is None else node_attrs edge_attrs = list(self.meta["edge_attrs"]) if edge_attrs is None else edge_attrs if arrays is None: arrays = self._empty() @@ -1109,7 +1549,7 @@ def read_block( """ if num_steps < 0: raise ValueError("num_steps must be >= 0") - wanted = list(self.meta["node_attrs"]) if node_attrs is None else node_attrs + wanted = list(self._node_specs()) if node_attrs is None else node_attrs if context is None: nodes, edges = self.read_arrays( roi, num_steps, wanted, edge_attrs, step_edges, edge_ends @@ -1191,7 +1631,7 @@ def read_nodes( ) -> list[dict[str, Any]]: """The nodes in ``roi`` as dictionaries, as the SQL backends do.""" arrays = self._readable() or self._empty() - read_attrs = list(self.meta["node_attrs"]) if read_attrs is None else read_attrs + read_attrs = list(self._node_specs()) if read_attrs is None else read_attrs needed = list(dict.fromkeys(read_attrs + list(attr_filter or {}))) columns = self._node_columns(arrays, self._rows_in(arrays, roi), needed) mask = self._filter(columns, attr_filter) diff --git a/tests/test_csr_extra_fields.py b/tests/test_csr_extra_fields.py new file mode 100644 index 0000000..d8d5827 --- /dev/null +++ b/tests/test_csr_extra_fields.py @@ -0,0 +1,492 @@ +"""Extra node attributes of a CSR graph, kept in directories of their own.""" + +import hashlib +import multiprocessing as mp +from typing import Any + +import networkx as nx +import numpy as np +import pytest +from funlib.geometry import Roi + +from funlib.persistence.graphs import CSRGraphDataBase +from funlib.persistence.graphs.csr_graph_database import ( + GraphIsReadOnly, + UnfinalizedWrites, +) +from funlib.persistence.graphs.graph_database import AttributeType +from funlib.persistence.types import Vec + +N = 600 +TYPES: dict[str, AttributeType] = { + "vec": Vec("float32", 3), + "label": "int32", + "seen": bool, + "score": float, +} + + +def graph_arrays(n=N, seed=0): + rng = np.random.default_rng(seed) + ids = rng.choice(10 * n, size=n, replace=False).astype(np.uint64) + 1 + pos = rng.uniform(0, 100, size=(n, 3)) + u, v = ids[:-1], ids[1:] # a path through the nodes in the order given + return ids, pos, u, v + + +def make_graph(path, n=N, seed=0): + ids, pos, u, v = graph_arrays(n, seed) + weight = np.ones(len(u), dtype=np.float32) + CSRGraphDataBase.from_arrays( + path, ids, {"position": pos}, u, v, {"weight": weight}, cell_size=20.0 + ).close() + return ids, pos + + +def vec_of(ids): + ids = np.asarray(ids, dtype=np.float32) + return np.stack([ids, ids * 2, ids * 3], axis=1) + + +def expanded(tmp_path, mode="r+", names=("vec", "label", "seen", "score"), **kwargs): + return CSRGraphDataBase( + tmp_path / "g.csr", + mode=mode, + node_attrs={k: TYPES[k] for k in names} if mode == "r+" else None, + extra_fields={k: tmp_path / "pred" for k in names}, + **kwargs, + ) + + +def snapshot(folder): + """Every file under a directory with the sha256 of its bytes.""" + return { + str(p.relative_to(folder)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(folder.rglob("*")) + if p.is_file() + } + + +def by_id(nodes, name): + return dict(zip(nodes["id"].tolist(), nodes[name].tolist(), strict=True)) + + +def test_extra_attributes_are_written_and_read_through_the_graph(tmp_path): + ids, pos = make_graph(tmp_path / "g.csr") + before = snapshot(tmp_path / "g.csr") + db = expanded(tmp_path) + assert db.node_attrs == { + "position": Vec("float64", 3), + "vec": Vec("float32", 3), + "label": "int32", + "seen": "bool", + "score": "float64", + } + half = ids[: N // 2] + with db.bulk_write_mode(): + db.write_node_arrays( + half, + vec=vec_of(half), + label=(half % 5 + 1).astype(np.int32), + seen=np.ones(len(half), dtype=bool), + score=half / 7, + ) + + # the graph's own directory: no file added, removed or changed + assert snapshot(tmp_path / "g.csr") == before + # the extra directory: meta.json, the lock, one array per attribute + names = sorted(p.name.split("-")[0] for p in (tmp_path / "pred").iterdir()) + assert names == [ + "finalize.lock", + "meta.json", + "node_label", + "node_score", + "node_seen", + "node_vec", + "segments", + ] + assert list((tmp_path / "pred" / "segments").iterdir()) == [] + + # read back, by a new handle that names what it wants + db = expanded(tmp_path, mode="r") + nodes, edges = db.read_arrays() + assert len(nodes["id"]) == N and len(edges["u"]) == N - 1 + written = np.isin(nodes["id"], half) + assert nodes["vec"][written].tolist() == vec_of(nodes["id"][written]).tolist() + assert nodes["label"][written].tolist() == (nodes["id"][written] % 5 + 1).tolist() + assert nodes["seen"][written].all() + assert nodes["score"][written].tolist() == (nodes["id"][written] / 7).tolist() + # a node that was never written: NaN for a float, 0 for an integer or bool + assert np.isnan(nodes["vec"][~written]).all() + assert np.isnan(nodes["score"][~written]).all() + assert not nodes["label"][~written].any() and not nodes["seen"][~written].any() + # values are in the graph's row order: the arrays line up with its ids + rows = np.load(tmp_path / "g.csr" / db.meta["generation"] / "ids.npy") + (file,) = (tmp_path / "pred").glob("node_label-*.npy") + stored = np.load(file) + assert stored.shape == (N,) + assert stored.tolist() == np.where(np.isin(rows, half), rows % 5 + 1, 0).tolist() + + +def test_region_and_step_reads_return_extra_attributes(tmp_path): + ids, pos = make_graph(tmp_path / "g.csr") + db = expanded(tmp_path, names=("vec", "label")) + with db.bulk_write_mode(): + db.write_node_arrays(ids, vec=vec_of(ids), label=(ids % 9).astype(np.int32)) + plain = CSRGraphDataBase(tmp_path / "g.csr") + roi = Roi((0, 0, 0), (50, 60, 70)) + + for steps in (0, 2): + wanted, wanted_edges = plain.read_arrays(roi, num_steps=steps) + nodes, edges = db.read_arrays(roi, num_steps=steps) + assert ( + nodes["id"].tolist() == wanted["id"].tolist() and 0 < len(nodes["id"]) < N + ) + assert nodes["step"].tolist() == wanted["step"].tolist() + assert edges["u"].tolist() == wanted_edges["u"].tolist() + assert nodes["vec"].tolist() == vec_of(nodes["id"]).tolist() + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + + nodes, _ = db.read_block(roi, context=10, num_steps=1, node_attrs=["label"]) + assert set(nodes) == {"id", "label", "step", "own"} + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + assert 0 < nodes["own"].sum() < len(nodes["id"]) + + listed = db.read_nodes(roi, read_attrs=["label", "vec"]) + assert sorted(n["id"] for n in listed) == sorted(plain.read_arrays(roi)[0]["id"]) + assert all(n["label"] == n["id"] % 9 for n in listed) + assert all(n["vec"] == (n["id"], n["id"] * 2, n["id"] * 3) for n in listed) + only = db.read_nodes(roi, attr_filter={"label": 4}, read_attrs=["label"]) + assert only and all(n["id"] % 9 == 4 for n in only) + + graph = db.read_graph(roi) + inside = [n for n, d in graph.nodes(data=True) if "position" in d] + assert all(graph.nodes[n]["label"] == n % 9 for n in inside) + assert graph.number_of_edges() == plain.read_graph(roi).number_of_edges() + + with pytest.raises(ValueError, match="unknown node attribute 'nope'"): + db.read_arrays(roi, node_attrs=["nope"]) + # the plain handle does not know the extra attributes + with pytest.raises(ValueError, match="unknown node attribute 'label'"): + plain.read_arrays(roi, node_attrs=["label"]) + + +def _worker(root, part, parts, start): + ids, _, _, _ = graph_arrays() + db = CSRGraphDataBase( + root / "g.csr", + mode="r+", + node_attrs={"vec": TYPES["vec"], "label": TYPES["label"]}, + extra_fields={"vec": root / "pred", "label": root / "pred"}, + ) + start.wait() + with db.bulk_write_mode(worker=True): + for block in np.array_split(ids[part::parts], 10): + db.write_node_arrays( + block, vec=vec_of(block), label=(block % 9).astype(np.int32) + ) + + +def test_several_processes_write_one_extra_directory(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + before = snapshot(tmp_path / "g.csr") + parts = 4 + ctx = mp.get_context("spawn") + start = ctx.Barrier(parts) + procs = [ + ctx.Process(target=_worker, args=(tmp_path, part, parts, start)) + for part in range(parts) + ] + for p in procs: + p.start() + for p in procs: + p.join() + assert [p.exitcode for p in procs] == [0] * parts + assert len(list((tmp_path / "pred" / "segments").glob("*.npys"))) == parts + + db = expanded(tmp_path, names=("vec", "label")) + # until the finalize a read of the extra attributes is refused, a read + # of the graph's own is not + with pytest.raises(UnfinalizedWrites, match="pred has writes"): + db.read_arrays() + assert len(db.read_arrays(node_attrs=["position"])[0]["id"]) == N + db.finalize() + nodes, _ = db.read_arrays() + assert sorted(nodes["id"].tolist()) == sorted(ids.tolist()) + assert nodes["vec"].tolist() == vec_of(nodes["id"]).tolist() + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + assert list((tmp_path / "pred" / "segments").iterdir()) == [] + assert snapshot(tmp_path / "g.csr") == before + + +def test_a_later_finalize_adds_to_the_values_that_are_there(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + db = expanded(tmp_path, names=("score", "label")) + a, b, c = ids[:200], ids[150:400], ids[400:] + with db.bulk_write_mode(): + db.write_node_arrays(a, score=np.full(len(a), 1.0)) + files = sorted(p.name for p in (tmp_path / "pred").glob("node_*")) + with db.bulk_write_mode(): + # written twice: the last value stays; a NaN is not a value + db.write_node_arrays(b, score=np.full(len(b), 2.0)) + db.write_node_arrays(a[:10], score=np.full(10, np.nan)) + db.write_node_arrays(b[:5], score=np.full(5, 3.0)) + # one array per attribute: the one before is gone, label was never built + again = sorted(p.name for p in (tmp_path / "pred").glob("node_*")) + assert len(files) == len(again) == 1 and files != again + score = by_id(db.read_arrays(node_attrs=["score", "label"])[0], "score") + assert all(score[i] == 1.0 for i in a[:150].tolist()) + assert all(score[i] == 3.0 for i in b[:5].tolist()) + assert all(score[i] == 2.0 for i in b[5:].tolist()) + assert all(np.isnan(score[i]) for i in c.tolist()) + labels = db.read_arrays(node_attrs=["label"])[0]["label"] + assert labels.shape == (N,) and not labels.any() + + # a run taken up again by another handle + other = expanded(tmp_path, names=("score",)) + other.write_node_arrays(c, score=np.full(len(c), 4.0)) # finalizes on its own + score = by_id(expanded(tmp_path, "r", ("score",)).read_arrays()[0], "score") + assert not np.isnan(list(score.values())).any() + assert all(score[i] == 4.0 for i in c.tolist()) + + +def test_the_graph_is_read_only_through_a_handle_with_extra_fields(tmp_path): + ids, pos = make_graph(tmp_path / "g.csr") + before = snapshot(tmp_path / "g.csr") + db = expanded(tmp_path, names=("label",)) + graph = nx.Graph() + graph.add_node(int(ids[0]), position=tuple(pos[0]), label=3) + graph.add_edge(int(ids[0]), int(ids[1]), weight=2.0) + one = ids[:1] + refused = [ + lambda: db.write_node_arrays(one, position=pos[:1]), + lambda: db.write_node_arrays(one, position=pos[:1], label=[1]), + lambda: db.write_edge_arrays(ids[:1], ids[2:3], weight=[1.0]), + lambda: db.write_nodes(graph.nodes, attributes=["position"]), + lambda: db.write_edges(graph.nodes, graph.edges), + lambda: db.bulk_write_edges(graph.nodes, graph.edges), + lambda: db.write_graph(graph), + lambda: db.bulk_write_graph(graph), + lambda: db.write_attrs(graph, edge_attrs=["weight"]), + lambda: db.write_attrs(graph, node_attrs=["position"]), + lambda: db.drop_edges(), + ] + for write in refused: + with pytest.raises(GraphIsReadOnly, match="read-only through a handle"): + write() + with pytest.raises(ValueError, match="unknown node attributes"): + db.write_node_arrays(one, nope=[1]) + db.finalize() + assert snapshot(tmp_path / "g.csr") == before + assert list((tmp_path / "pred" / "segments").glob("*.npys")) == [] + assert not db.read_arrays()[0]["label"].any() + # a handle that only reads refuses every write + with pytest.raises(RuntimeError, match="read-only DB"): + expanded(tmp_path, mode="r", names=("label",)).write_node_arrays(one, label=[1]) + + +def test_nodes_given_as_dictionaries_write_their_extra_attributes(tmp_path): + ids, pos = make_graph(tmp_path / "g.csr") + db = expanded(tmp_path, names=("label", "vec")) + roi = Roi((0, 0, 0), (50, 100, 100)) + graph = db.read_graph(node_attrs=["position"]) + for node, data in graph.nodes(data=True): + data["label"] = node % 9 + 1 + if node % 2: + data["vec"] = (node, 0.0, 0.0) + db.write_attrs(graph, roi=roi, node_attrs=["label", "vec"]) + nodes, _ = db.read_arrays() + inside = (nodes["position"][:, 0] < 50).tolist() + for node, label, vec, here in zip( + nodes["id"].tolist(), nodes["label"], nodes["vec"], inside, strict=True + ): + assert label == (node % 9 + 1 if here else 0) + assert (vec[0] == node) if here and node % 2 else np.isnan(vec).all() + + # without a region no position is needed; every extra attribute is taken + values = {int(i): {"label": 77} for i in ids[:3]} + db.write_nodes(values) + assert by_id(db.read_arrays()[0], "label")[int(ids[0])] == 77 + db.write_graph(nx.Graph([(int(ids[3]), int(ids[4]))]), write_edges=False) + nx_graph = nx.Graph() + nx_graph.add_node(int(ids[5]), label=78) + db.write_graph(nx_graph, write_edges=False, node_attrs=["label"]) + assert by_id(db.read_arrays()[0], "label")[int(ids[5])] == 78 + + +def test_extra_fields_of_another_graph_are_refused(tmp_path): + ids, pos = make_graph(tmp_path / "g.csr") + db = expanded(tmp_path, names=("label",)) + db.write_node_arrays(ids, label=(ids % 9).astype(np.int32)) + fields = {"label": tmp_path / "pred"} + + make_graph(tmp_path / "fewer.csr", n=N - 1) + with pytest.raises(ValueError, match=f"a graph of {N} nodes; .* has {N - 1}"): + CSRGraphDataBase(tmp_path / "fewer.csr", extra_fields=fields) + make_graph(tmp_path / "other.csr", seed=1) # as many nodes, other ids + with pytest.raises(ValueError, match="a graph with other nodes"): + CSRGraphDataBase(tmp_path / "other.csr", extra_fields=fields) + with pytest.raises(ValueError, match="a graph with other nodes"): + CSRGraphDataBase(tmp_path / "other.csr", mode="r+", extra_fields=fields) + + # the same nodes built again, or edges added, are the same rows + make_graph(tmp_path / "again.csr") + again = CSRGraphDataBase(tmp_path / "again.csr", extra_fields=fields) + nodes, _ = again.read_arrays() + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + plain = CSRGraphDataBase(tmp_path / "g.csr", mode="r+") + plain.write_edge_arrays(ids[:1], ids[5:6], weight=np.ones(1, np.float32)) + assert plain.num_edges == N + nodes, edges = expanded(tmp_path, mode="r", names=("label",)).read_arrays() + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + assert len(edges["u"]) == N + # a graph that changed under an open handle is noticed at the next write + plain.write_node_arrays(np.array([10**9], dtype=np.uint64), position=pos[:1]) + with pytest.raises(ValueError, match=f"a graph of {N} nodes"): + db.write_node_arrays(ids[:1], label=[1]) + + +def test_a_value_for_an_id_that_is_not_a_node_stops_the_finalize(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + db = expanded(tmp_path, names=("label",)) + db.write_node_arrays(ids[:5], label=np.full(5, 1, np.int32)) + stranger = np.array([ids[5], 10**12], dtype=np.uint64) + with pytest.raises(ValueError, match=r"1 ids that are not nodes.*1000000000000"): + db.write_node_arrays(stranger, label=[2, 2]) + # nothing was finalized: the arrays are as they were, the segment stays + assert len(list((tmp_path / "pred" / "segments").glob("*.npys"))) == 1 + reader = expanded(tmp_path, mode="r", names=("label",)) + assert reader.read_arrays(node_attrs=["position"])[0]["id"].shape == (N,) + with pytest.raises(UnfinalizedWrites): + reader.read_arrays() + for segment in (tmp_path / "pred" / "segments").glob("*.npys"): + segment.unlink() + assert int(reader.read_arrays()[0]["label"].sum()) == 5 + + +@pytest.mark.parametrize( + "kwargs, error, match", + [ + ({"mode": "w", "cell_size": 1.0}, ValueError, "mode 'w' creates the graph"), + ({"mode": "r"}, ValueError, r"\['label'\] are not in .*Open with mode 'r\+'"), + ({"mode": "r+"}, ValueError, r"\['label'\] are new in .*types in node_attrs"), + ( + {"mode": "r+", "node_attrs": {"label": str}}, + NotImplementedError, + "not supported by the CSR backend", + ), + ( + {"mode": "r+", "extra_fields": {"position": "x"}}, + ValueError, + r"\['position'\] are node attributes of .* itself", + ), + ( + {"mode": "r+", "extra_fields": {"label": "g.csr"}}, + ValueError, + "outside the graph's directory", + ), + ], +) +def test_extra_fields_that_cannot_be_opened_are_refused( + tmp_path, monkeypatch, kwargs, error, match +): + make_graph(tmp_path / "g.csr") + before = snapshot(tmp_path / "g.csr") + monkeypatch.chdir(tmp_path) + given: dict[str, Any] = {"extra_fields": {"label": "pred"}, **kwargs} + with pytest.raises(error, match=match): + CSRGraphDataBase("g.csr", **given) + assert snapshot(tmp_path / "g.csr") == before + assert not (tmp_path / "pred" / "meta.json").exists() + + +def test_a_declared_type_has_to_be_the_stored_one(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + expanded(tmp_path, names=("vec", "label")).close() + fields = {"vec": tmp_path / "pred", "label": tmp_path / "pred"} + other: list[dict[str, AttributeType]] = [ + {"vec": Vec("float32", 4)}, + {"label": "int64"}, + ] + for types in other: + with pytest.raises(ValueError, match="in .*pred, not"): + CSRGraphDataBase(tmp_path / "g.csr", node_attrs=types, extra_fields=fields) + # stored attributes are still checked against the graph + with pytest.raises(ValueError, match="node attribute 'nope' is not in"): + CSRGraphDataBase( + tmp_path / "g.csr", node_attrs={"nope": int}, extra_fields=fields + ) + db = CSRGraphDataBase( + tmp_path / "g.csr", + node_attrs={"position": Vec(float, 3), **{k: TYPES[k] for k in fields}}, + extra_fields=fields, + ) + assert list(db.node_attrs) == ["position", "vec", "label"] + with pytest.raises(ValueError, match=r"'label' has shape \(1,\).*each of the 3"): + expanded(tmp_path, names=("label",)).write_node_arrays(ids[:3], label=[1]) + + +def test_a_graph_that_was_never_finalized_takes_no_extra_fields(tmp_path): + CSRGraphDataBase( + tmp_path / "g.csr", + mode="w", + node_attrs={"position": Vec(float, 3)}, + cell_size=10.0, + ) + with pytest.raises(ValueError, match="was never finalized"): + expanded(tmp_path, names=("label",)) + + +def test_a_directory_that_holds_something_else_is_not_taken_for_extra_fields(tmp_path): + make_graph(tmp_path / "g.csr") + make_graph(tmp_path / "h.csr") + (tmp_path / "other").mkdir() + (tmp_path / "other" / "meta.json").write_text('{"version": 1}') + for folder in (tmp_path / "h.csr", tmp_path / "other"): + before = snapshot(folder) + with pytest.raises(ValueError, match="not a directory of extra node attr"): + CSRGraphDataBase( + tmp_path / "g.csr", + mode="r+", + node_attrs={"label": int}, + extra_fields={"label": folder}, + ) + assert snapshot(folder) == before + + +def test_attributes_in_several_directories_and_several_in_one(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + a, b = tmp_path / "model_a", tmp_path / "deep" / "model_b" + db = CSRGraphDataBase( + tmp_path / "g.csr", + mode="r+", + node_attrs={"vec": TYPES["vec"], "label": "int32", "score": float}, + extra_fields={"vec": a, "label": a, "score": b}, + ) + with db.bulk_write_mode(): + db.write_node_arrays(ids, vec=vec_of(ids), score=ids / 2) + db.write_node_arrays(ids, label=(ids % 9).astype(np.int32)) + assert CSRGraphDataBase.stored_extra_fields(a) == { + "vec": Vec("float32", 3), + "label": "int32", + } + assert CSRGraphDataBase.stored_extra_fields(b) == {"score": "float64"} + assert CSRGraphDataBase.stored_extra_fields(tmp_path / "g.csr") == {} + assert CSRGraphDataBase.stored_extra_fields(tmp_path / "missing") == {} + assert not CSRGraphDataBase.is_database(a) + + # a handle sees the attributes it names, under the directory it names + one = CSRGraphDataBase(tmp_path / "g.csr", extra_fields={"label": a, "score": b}) + assert list(one.node_attrs) == ["position", "label", "score"] + nodes, _ = one.read_arrays() + assert "vec" not in nodes + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + assert nodes["score"].tolist() == (nodes["id"] / 2).tolist() + # pending writes in one directory do not stop a read of the other + with db.bulk_write_mode(worker=True): + db.write_node_arrays(ids[:1], score=np.array([0.5])) + assert len(db.read_arrays(node_attrs=["vec", "label"])[0]["id"]) == N + with pytest.raises(UnfinalizedWrites, match="model_b"): + db.read_block(Roi((0, 0, 0), (100, 100, 100))) + db.finalize() + assert by_id(db.read_arrays()[0], "score")[int(ids[0])] == 0.5 From ef562e6c9b83de742e44c8275df303fcb97be42c Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 15:13:24 -0800 Subject: [PATCH 11/15] extra_fields takes directories; attributes and types come from each directory The path is enough to open the extra node attributes of a graph: every attribute a directory holds is exposed with the type its meta.json records. extra_fields is one directory or a sequence of them; the {name: directory} mapping is gone (TypeError). - A new attribute is created by the first write that names it, with the dtype and vector size of the values written, recorded in the directory's meta.json under its lock, so that processes creating one attribute at once agree. A later array of another dtype or size raises; nothing is cast. - The dictionary writes create an attribute named in attributes from the nodes' values when they are numbers of one kind and one length, and raise otherwise. Left out, attributes are the extra ones that exist. - node_attrs is never needed for an extra attribute; it may declare one up front in mode r+, or have the recorded type checked. - A new attribute goes into the one directory that is open; with several open, creating one raises. - An attribute held by two directories, or also stored in the graph, is refused at open. A directory that is empty or missing is created by the first write in mode r+ and is an error in mode r. Co-Authored-By: Claude Fable 5.2 --- docs/source/graphs.md | 60 ++- .../persistence/graphs/csr_graph_database.py | 328 ++++++++++---- tests/test_csr_extra_fields.py | 403 ++++++++++++------ 3 files changed, 556 insertions(+), 235 deletions(-) diff --git a/docs/source/graphs.md b/docs/source/graphs.md index e380c11..64f049f 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -103,37 +103,61 @@ values = compute(nodes, edges)[nodes["own"]] Values computed on a finished graph, such as an embedding per node, do not have to go into the graph's directory. The graph is opened with -`extra_fields`, a mapping from attribute name to the directory that holds -it, and the extra attributes are written and read through the database -like stored ones: +`extra_fields`, the directory that holds them, and the extra attributes are +written and read through the database like stored ones: ```python from funlib.persistence.graphs import CSRGraphDataBase -from funlib.persistence.types import Vec -g = CSRGraphDataBase( - "fragments.csr", - mode="r+", - extra_fields={"embedding": "pred/model_a", "label": "pred/model_a"}, - node_attrs={"embedding": Vec("float32", 64), "label": "int32"}, -) +g = CSRGraphDataBase("fragments.csr", mode="r+", extra_fields="pred/model_a") with g.bulk_write_mode(): for roi in blocks: nodes, edges = g.read_block(roi, num_steps=2, node_attrs=["position"]) own = nodes["own"] - e, l = model(nodes, edges) + e, l = model(nodes, edges) # float32 (N, 64) and int32 (N,) g.write_node_arrays(nodes["id"][own], embedding=e[own], label=l[own]) +g = CSRGraphDataBase("fragments.csr", extra_fields="pred/model_a") nodes, edges = g.read_arrays(roi, node_attrs=["position", "embedding"]) ``` -A directory holds any number of attributes, and a handle can name -attributes from several directories. An attribute its directory does not -hold yet is created when the graph is opened with mode `"r+"`, with the -type `node_attrs` gives it; later the type may be left out. `g.node_attrs` -lists the extra attributes after the stored ones, and `read_arrays`, -`read_block`, `read_nodes` and `read_graph` return them by name, for the -same regions and steps. +The path is enough. No attribute is named and no type is given: `meta.json` +in the directory records what it holds, and opening the graph with it +exposes every attribute there with its recorded type. `g.node_attrs` lists +the extra attributes after the stored ones, and `read_arrays`, `read_block`, +`read_nodes` and `read_graph` return them by name, for the same regions and +steps. `CSRGraphDataBase.stored_extra_fields(path)` tells what a directory +holds without opening a graph. + +`extra_fields` also takes several directories, +`extra_fields=["pred/model_a", "pred/model_b"]`, and exposes the attributes +of all of them. An attribute that two of them hold, or that the graph itself +stores, is refused when the graph is opened. A directory that is empty or +does not exist yet is created by the first write in mode `"r+"`; in mode +`"r"` it is an error. + +**A new attribute is created by the first write that names it**, with the +type of the values written: `embedding=e` with `e` a float32 array of shape +`(N, 64)` declares a float32 vector of 64. The declaration is recorded in the +directory's `meta.json` under the directory's lock, so worker processes that +create the same attribute at the same moment agree on it. From then on an +array written to the attribute has that dtype and vector size, or the write +raises `ValueError`; nothing is cast. The writes that take nodes as +dictionaries (`write_nodes`, `bulk_write_nodes`, `write_attrs`) create an +attribute named in `attributes` from the values the nodes carry, when those +are numbers of one kind (bool, int or float, stored as bool, int64 or +float64) and one length; otherwise they raise and ask for a type. Values for +an attribute that exists are cast to its type. + +`node_attrs` is never needed for an extra attribute. It may name one with a +type, `node_attrs={"score": "float32"}`, to create it up front in mode +`"r+"`, for example float32 where Python numbers would give float64, or to +have the recorded type checked. + +**A new attribute goes into the one directory that is open.** With several +directories open, a write that names an attribute none of them holds raises: +open the graph with the directory it is to go into. Attributes that exist +are written into the directory that holds them. **The graph is read-only through such a handle.** Nothing in the graph's directory is created, changed or locked. Writing edges, writing nodes with diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index eb78efe..3830582 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -282,22 +282,48 @@ class CSRGraphDataBase(GraphDataBase): extra_fields: - Node attributes of this graph that are kept in other - directories: attribute name to directory. The graph is opened - as it is (mode ``"r"`` or ``"r+"``) and the extra attributes - are read with it and written through it:: - - g = CSRGraphDataBase(path, mode="r+", extra_fields={ - "embedding": "pred/modelA", "label": "pred/modelA"}, - node_attrs={"embedding": Vec("float32", 64), "label": "int32"}) + One directory, or several, that hold node attributes of this + graph outside the graph's own directory. The graph is opened as + it is (mode ``"r"`` or ``"r+"``); every attribute the + directories hold is read with it, with the type its directory + records, and written through it:: + + g = CSRGraphDataBase(path, mode="r+", extra_fields="pred/modelA") g.write_node_arrays(ids, embedding=e, label=l) # in bulk_write_mode g.read_arrays(roi, node_attrs=["position", "embedding"]) - A directory holds any number of attributes; a handle sees those - it names. An attribute that its directory does not hold yet is - created, in mode ``"r+"``, with the type ``node_attrs`` gives - it. Extra attributes are read like stored ones (same regions, - steps, filters) and listed by :attr:`node_attrs`. + The path is enough: no attribute is named and no type is given. + ``meta.json`` in each directory says what it holds. Extra + attributes are read like stored ones (same regions, steps, + filters) and listed by :attr:`node_attrs`. An attribute that + two of the directories hold, or that the graph itself stores, + is refused when the graph is opened. A directory that is empty + or does not exist is created by the first write in mode + ``"r+"`` and is an error in mode ``"r"``. + + **A new attribute is created by the first write that names + it**, with the type of the values written: + ``write_node_arrays(ids, embedding=e)`` with ``e`` a float32 + array of shape ``(N, 64)`` declares a float32 vector of 64. The + declaration is recorded in the directory's ``meta.json`` under + its lock, so processes that create one attribute at once agree + on it. From then on an array written to it has that dtype and + vector size, or the write raises; nothing is cast. The writes + that take nodes as dictionaries (``write_nodes``, + ``bulk_write_nodes``, ``write_attrs``) create an attribute that + ``attributes`` names from the values the nodes carry: numbers + of one kind (bool, int or float, stored as bool, int64 or + float64) and one length; anything else raises. Values for an + attribute that exists are cast to its type. ``node_attrs`` is + never needed for an extra attribute. It may name one with a + type, to create it up front in mode ``"r+"`` (float32 rather + than the float64 Python numbers give), or to have the type that + is recorded checked. + + **A new attribute goes into the one directory that is open.** + With several directories open, a write that names an attribute + none of them holds raises: open the graph with the directory it + is to go into. **The graph is read-only through such a handle.** Writes of edges, of nodes with stored attributes, and ``drop_edges`` @@ -355,14 +381,22 @@ def __init__( node_attrs: dict[str, AttributeType] | None = None, edge_attrs: dict[str, AttributeType] | None = None, cell_size: float | Iterable[float] | None = None, - extra_fields: Mapping[str, Path | str] | None = None, + extra_fields: Path | str | Sequence[Path | str] | None = None, ): if directed: raise NotImplementedError("the CSR backend stores undirected graphs") self.path = Path(path) self.mode = mode self.directed = False - self.extra_fields = {k: Path(v) for k, v in (extra_fields or {}).items()} + if isinstance(extra_fields, Mapping): + raise TypeError( + "extra_fields is a directory or a sequence of directories; the " + "attributes and their types are read from each directory" + ) + if isinstance(extra_fields, str | Path): + extra_fields = [extra_fields] + self.extra_fields = [Path(folder) for folder in extra_fields or ()] + self._extra_dirs: list[_ExtraFields] = [] self._extra: dict[str, _ExtraFields] = {} if self.extra_fields and mode not in self.read_modes: raise ValueError( @@ -421,8 +455,8 @@ def __init__( (edge_attrs, self.meta["edge_attrs"], "edge"), ): for name, attr_type in (given or {}).items(): - if what == "node" and name in self.extra_fields: - continue # checked against its own directory below + if what == "node" and self.extra_fields and name not in stored: + continue # an extra attribute: see _open_extra_fields if name not in stored: raise ValueError( f"{what} attribute {name!r} is not in {self.path}; " @@ -491,59 +525,108 @@ def _open_extra_fields(self, given: Mapping[str, AttributeType]) -> None: f"{self.path} was never finalized; extra fields belong to a " "graph whose nodes are written" ) - taken = sorted(set(self.extra_fields) & set(self.meta["node_attrs"])) - if taken: - raise ValueError( - f"{taken} are node attributes of {self.path} itself and cannot " - "be extra fields" - ) - folders: dict[Path, _ExtraFields] = {} - for name, folder in self.extra_fields.items(): + seen: set[Path] = set() + for folder in self.extra_fields: key = folder.resolve() if key == self.path.resolve(): raise ValueError("extra fields are kept outside the graph's directory") - if key not in folders: - folders[key] = _ExtraFields(folder) - self._extra[name] = folders[key] - for extra in folders.values(): - names = [n for n, e in self._extra.items() if e is extra] - specs = {n: _spec(given[n]) for n in names if n in given} - held = {} if extra.meta is None else extra.meta["node_attrs"] - new = [n for n in names if n not in held] - if new and self.mode == "r": + if key in seen: + raise ValueError(f"{folder} is given twice in extra_fields") + seen.add(key) + extra = _ExtraFields(folder) + if extra.meta is None and self.mode == "r": raise ValueError( - f"node attributes {new} are not in {extra.path}; it has " - f"{sorted(held)}. Open with mode 'r+' to create them" + f"{folder} holds no extra node attributes. Open the graph " + "with mode 'r+' to write the first" ) - untyped = [n for n in new if n not in specs] - if untyped: - raise ValueError( - f"{untyped} are new in {extra.path}: give their types in node_attrs" - ) - if new: - extra.path.mkdir(parents=True, exist_ok=True) - with _locked(extra.path): - extra.reload() # another process may have declared them - if extra.meta is None: - extra.meta = { - "version": EXTRA_FORMAT_VERSION, - "extends": self._extends(), - "node_attrs": {}, - "arrays": {}, - } - for name in new: - extra.meta["node_attrs"].setdefault(name, specs[name]) - extra.write() + self._extra_dirs.append(extra) + self._map_extra_fields() + # node_attrs may name extra attributes: to create them up front, or + # to have the recorded type checked + named = { + name: _spec(attr_type) + for name, attr_type in given.items() + if name not in self.meta["node_attrs"] + } + new = {name: spec for name, spec in named.items() if name not in self._extra} + if new and self.mode == "r": + raise ValueError( + f"node attributes {sorted(new)} are neither in {self.path} nor " + f"in its extra fields, which hold {sorted(self._extra)}" + ) + if new: + self._declare_extra(new) + for name, spec in named.items(): + self._same_spec(name, spec) + + def _map_extra_fields(self) -> None: + """Which directory holds each extra attribute, from what the + directories say now. A name held twice is refused.""" + found: dict[str, _ExtraFields] = {} + for extra in self._extra_dirs: + if extra.meta is None: + continue self._check_extends(extra) - for name, spec in specs.items(): - if spec != extra.stored["node_attrs"][name]: + for name in extra.meta["node_attrs"]: + if name in self.meta["node_attrs"]: raise ValueError( - f"node attribute {name!r} is {extra.stored['node_attrs'][name]} " - f"in {extra.path}, not {spec}" + f"node attribute {name!r} of {extra.path} is also stored " + f"in {self.path} itself" ) + if name in found: + raise ValueError( + f"node attribute {name!r} is held by {found[name].path} " + f"and by {extra.path}" + ) + found[name] = extra + self._extra = found + + def _same_spec(self, name: str, spec: dict[str, Any]) -> None: + extra = self._extra[name] + recorded = extra.stored["node_attrs"][name] + if spec != recorded: + raise ValueError( + f"node attribute {name!r} is {self._types({name: recorded})[name]} " + f"in {extra.path}, not {self._types({name: spec})[name]}" + ) + + def _declare_extra(self, specs: Mapping[str, dict[str, Any]]) -> None: + """Record new extra attributes in the one directory that is open. + Another process may declare the same ones at the same time: the + first to hold the lock writes them, the others find them.""" + if self.mode == "r": + raise RuntimeError("Trying to write to read-only DB") + if len(self._extra_dirs) != 1: + raise ValueError( + f"{sorted(specs)} are new node attributes and " + f"{len(self._extra_dirs)} extra directories are open: open the " + "graph with the one directory they are to go into" + ) + (extra,) = self._extra_dirs + extra.path.mkdir(parents=True, exist_ok=True) + with _locked(extra.path): + extra.reload() + if extra.meta is None: + extra.meta = { + "version": EXTRA_FORMAT_VERSION, + "extends": self._extends(), + "node_attrs": {}, + "arrays": {}, + } + added = False + for name, spec in specs.items(): + if name not in extra.meta["node_attrs"]: + extra.meta["node_attrs"][name] = spec + added = True + if added: + extra.write() + self._map_extra_fields() + self._arrays = None + for name, spec in specs.items(): + self._same_spec(name, spec) def _extra_folders(self) -> list[_ExtraFields]: - return list({id(e): e for e in self._extra.values()}.values()) + return self._extra_dirs def _node_specs(self) -> dict[str, dict[str, Any]]: """Every node attribute this handle reads: stored, then extra.""" @@ -553,12 +636,12 @@ def _node_specs(self) -> dict[str, dict[str, Any]]: return specs def _refuse(self, what: str) -> None: - if self._extra: + if self._extra_dirs: raise GraphIsReadOnly( f"{what}: {self.path} is read-only through a handle opened with " - "extra_fields; only the extra node attributes " - f"{sorted(self._extra)} are written. Open the graph without " - "extra_fields to change it" + "extra_fields; only extra node attributes are written, into " + f"{[str(e.path) for e in self._extra_dirs]}. Open the graph " + "without extra_fields to change it" ) def _split_extra( @@ -566,42 +649,107 @@ def _split_extra( ) -> list[tuple[_ExtraFields, list[str]]]: """Extra attribute names by the directory that holds them.""" attrs = list(attrs) - stored = [a for a in attrs if a in self.meta["node_attrs"]] - if stored: - self._refuse(f"cannot write the node attributes {stored}") - unknown = [a for a in attrs if a not in self._extra] - if unknown: - raise ValueError(f"unknown node attributes {unknown}") return [ (extra, [a for a in attrs if self._extra[a] is extra]) - for extra in self._extra_folders() + for extra in self._extra_dirs if any(self._extra[a] is extra for a in attrs) ] + def _extra_names(self, attrs: Iterable[str], specs) -> None: + """Refuse stored attributes; create the extra ones that are new, + with ``specs(names)`` giving the types of those; check the rest.""" + attrs = list(attrs) + stored = [a for a in attrs if a in self.meta["node_attrs"]] + if stored: + self._refuse(f"cannot write the node attributes {stored}") + new = [a for a in attrs if a not in self._extra] + if new: + for extra in self._extra_dirs: + extra.reload() # another process may have created them + self._map_extra_fields() + new = [a for a in attrs if a not in self._extra] + if new: + self._declare_extra(specs(new)) + + @staticmethod + def _spec_of_values(name: str, values: np.ndarray) -> dict[str, Any]: + """The type an array of values, one entry per node, declares.""" + if values.dtype.kind not in "fiub": + raise NotImplementedError( + f"node attribute {name!r}: attributes of type {values.dtype} are " + "not supported by the CSR backend" + ) + if values.ndim not in (1, 2) or (values.ndim == 2 and values.shape[1] < 1): + raise ValueError( + f"node attribute {name!r} has shape {values.shape}; expected " + "(N,) for a scalar or (N, k) for a vector" + ) + size = values.shape[1] if values.ndim == 2 else 0 + return {"dtype": values.dtype.newbyteorder("<").str, "size": size} + def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None: ids = np.asarray(ids) - for extra, names in self._split_extra(attrs): + arrays = {name: np.asarray(values) for name, values in attrs.items()} + for name, values in arrays.items(): + if values.ndim == 0 or len(values) != len(ids): + raise ValueError( + f"node attribute {name!r} has shape {values.shape}; " + f"expected one entry for each of the {len(ids)} ids" + ) + given = { + name: self._spec_of_values(name, values) + for name, values in arrays.items() + if name not in self.meta["node_attrs"] + } + self._extra_names(arrays, lambda new: {name: given[name] for name in new}) + for name, spec in given.items(): + self._same_spec(name, spec) + for extra, names in self._split_extra(arrays): records = np.empty(len(ids), dtype=extra.record_dtype(names)) records["id"] = ids for name in names: - values = np.asarray(attrs[name]) - if values.ndim == 0 or len(values) != len(ids): - raise ValueError( - f"node attribute {name!r} has shape {values.shape}; " - f"expected one entry for each of the {len(ids)} ids" - ) - records[name] = values + records[name] = arrays[name] self._segment("nodes", extra.path).append(records) def _write_extra_rows(self, nodes, roi: Roi | None, attributes) -> None: + # left out, the extra attributes that exist are written; a new one + # is named names = list(self._extra) if attributes is None else list(attributes) + kept = [] + for node_id, data in nodes.items(): + if roi is not None: + position = self._position(data) + if position is None or not roi.contains(tuple(position)): + continue + kept.append((node_id, data)) + + def infer(new: list[str]) -> dict[str, dict[str, Any]]: + specs = {} + for name in new: + values = [ + np.asarray(d[name]) for _, d in kept if d.get(name) is not None + ] + kinds = {v.dtype.kind for v in values} + shapes = {v.shape for v in values} + if ( + len(kinds) != 1 + or len(shapes) != 1 + or not kinds <= set("fiub") + or len(next(iter(shapes))) > 1 + ): + raise ValueError( + f"node attribute {name!r} is new and its type cannot be " + f"told from the values of the nodes ({len(values)} " + f"values, kinds {sorted(kinds)}, shapes {sorted(shapes)}): " + "give its type in node_attrs when the graph is opened" + ) + specs[name] = self._spec_of_values(name, np.stack(values)) + return specs + + self._extra_names(names, infer) for extra, own in self._split_extra(names): groups: dict[tuple[str, ...], list[tuple]] = {} - for node_id, data in nodes.items(): - if roi is not None: - position = self._position(data) - if position is None or not roi.contains(tuple(position)): - continue + for node_id, data in kept: present = tuple(a for a in own if data.get(a) is not None) if not present: continue @@ -871,9 +1019,9 @@ def _open_arrays(self) -> dict[str, np.ndarray] | None: name: np.load(folder / f"{name}.npy", mmap_mode="r") for name in self._array_names() } - for extra in self._extra_folders(): + for extra in self._extra_dirs: extra.reload() - self._check_extends(extra) + self._map_extra_fields() for name, extra in self._extra.items(): arrays[f"node_{name}"] = self._extra_array(extra, name, len(arrays["ids"])) self._arrays = arrays @@ -916,7 +1064,7 @@ def write_node_arrays(self, ids: np.ndarray, **attrs: np.ndarray) -> None: """Append nodes given as arrays: ``ids`` and one array per attribute (the position among them). Through a handle with ``extra_fields``: values of extra attributes for nodes of the graph, no position.""" - if self._extra: + if self._extra_dirs: self._write_extra_arrays(ids, attrs) self._after_write() return @@ -970,7 +1118,7 @@ def _append_rows( ) def bulk_write_nodes(self, nodes, roi: Roi | None = None, attributes=None) -> None: - if self._extra: + if self._extra_dirs: self._write_extra_rows(nodes, roi, attributes) self._after_write() return @@ -1210,8 +1358,8 @@ def finalize(self) -> None: self._segments = {} # one finalize at a time: a second process waits, then finds the # segments the first one merged gone - if self._extra: - for extra in self._extra_folders(): + if self._extra_dirs: + for extra in self._extra_dirs: with _locked(extra.path): self._finalize_extra(extra) self._arrays = None diff --git a/tests/test_csr_extra_fields.py b/tests/test_csr_extra_fields.py index d8d5827..eb894c7 100644 --- a/tests/test_csr_extra_fields.py +++ b/tests/test_csr_extra_fields.py @@ -1,6 +1,7 @@ """Extra node attributes of a CSR graph, kept in directories of their own.""" import hashlib +import json import multiprocessing as mp from typing import Any @@ -48,13 +49,21 @@ def vec_of(ids): return np.stack([ids, ids * 2, ids * 3], axis=1) -def expanded(tmp_path, mode="r+", names=("vec", "label", "seen", "score"), **kwargs): +def expanded(tmp_path, mode="r+", names=("vec", "label", "seen", "score")): + """The graph with the directory ``pred``; in mode r+ the attributes + ``names`` are declared up front, with the types of ``TYPES``.""" return CSRGraphDataBase( tmp_path / "g.csr", mode=mode, node_attrs={k: TYPES[k] for k in names} if mode == "r+" else None, - extra_fields={k: tmp_path / "pred" for k in names}, - **kwargs, + extra_fields=tmp_path / "pred", + ) + + +def opened(tmp_path, mode="r", folder="pred"): + """The graph opened with a directory, by its path alone.""" + return CSRGraphDataBase( + tmp_path / "g.csr", mode=mode, extra_fields=tmp_path / folder ) @@ -173,12 +182,8 @@ def test_region_and_step_reads_return_extra_attributes(tmp_path): def _worker(root, part, parts, start): ids, _, _, _ = graph_arrays() - db = CSRGraphDataBase( - root / "g.csr", - mode="r+", - node_attrs={"vec": TYPES["vec"], "label": TYPES["label"]}, - extra_fields={"vec": root / "pred", "label": root / "pred"}, - ) + # the path alone: every worker creates the attributes with its first write + db = CSRGraphDataBase(root / "g.csr", mode="r+", extra_fields=root / "pred") start.wait() with db.bulk_write_mode(worker=True): for block in np.array_split(ids[part::parts], 10): @@ -187,9 +192,10 @@ def _worker(root, part, parts, start): ) -def test_several_processes_write_one_extra_directory(tmp_path): +def test_several_processes_create_and_write_the_same_attributes(tmp_path): ids, _ = make_graph(tmp_path / "g.csr") before = snapshot(tmp_path / "g.csr") + assert not (tmp_path / "pred").exists() parts = 4 ctx = mp.get_context("spawn") start = ctx.Barrier(parts) @@ -203,8 +209,13 @@ def test_several_processes_write_one_extra_directory(tmp_path): p.join() assert [p.exitcode for p in procs] == [0] * parts assert len(list((tmp_path / "pred" / "segments").glob("*.npys"))) == parts + # they agreed on one declaration, the type of the values written + assert CSRGraphDataBase.stored_extra_fields(tmp_path / "pred") == { + "vec": Vec("float32", 3), + "label": "int32", + } - db = expanded(tmp_path, names=("vec", "label")) + db = opened(tmp_path, "r+") # until the finalize a read of the extra attributes is refused, a read # of the graph's own is not with pytest.raises(UnfinalizedWrites, match="pred has writes"): @@ -219,6 +230,120 @@ def test_several_processes_write_one_extra_directory(tmp_path): assert snapshot(tmp_path / "g.csr") == before +def test_the_path_alone_opens_what_a_directory_holds(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + with pytest.raises(ValueError, match="holds no extra node attributes.*'r\\+'"): + opened(tmp_path) + (tmp_path / "empty").mkdir() + with pytest.raises(ValueError, match="holds no extra node attributes"): + opened(tmp_path, folder="empty") + db = opened(tmp_path, "r+") # a directory that does not exist yet + assert not (tmp_path / "pred").exists() + assert db.node_attrs == {"position": Vec("float64", 3)} + assert len(db.read_arrays()[0]["id"]) == N + + # the first write of a name creates it, with the type of its values + with db.bulk_write_mode(): + db.write_node_arrays( + ids, + vec=vec_of(ids), + label=(ids % 9).astype(np.int16), + seen=ids % 2 == 0, + ) + types: dict[str, AttributeType] = { + "vec": Vec("float32", 3), + "label": "int16", + "seen": "bool", + } + assert CSRGraphDataBase.stored_extra_fields(tmp_path / "pred") == types + assert db.node_attrs == {"position": Vec("float64", 3), **types} + stored = json.loads((tmp_path / "pred" / "meta.json").read_text()) + assert stored["node_attrs"]["vec"] == {"dtype": " Date: Wed, 25 Nov 2026 15:51:41 -0800 Subject: [PATCH 12/15] Extra fields: check a write whole before recording anything; refuse what would change a value Review of ef562e6, findings U1 to U5 and questions 2 and 3. - U1: a write recorded its new attributes in meta.json before it was known to be storable. Every check of a call now comes first, and a declaration records all of its attributes or none. The names id, step and own, which the reads use for arrays of their own, are refused on write, in node_attrs, and in a directory that holds one. - U2: finalize, and leaving bulk_write_mode, raised FileNotFoundError for an extra directory that did not exist yet. A directory with nothing to merge is left alone. An error raised inside bulk_write_mode is the one raised; a failing finalize after it is logged. - U3: a dictionary write in which no node carries a value for a new attribute writes nothing and creates nothing, instead of raising. - U4: a dictionary value is stored in the recorded type or refused: a float for an integer or a bool, an integer for a bool, and a sequence of another length than the vector raise. - U5: a dictionary write with a roi raises for a node that carries no position, instead of leaving it out. - finalize merges every extra directory and raises the errors together (one as it is, several as an ExceptionGroup). - finalize removes node_-*.npy files that meta.json does not name. Co-Authored-By: Claude Fable 5.2 --- docs/source/graphs.md | 24 +- .../persistence/graphs/csr_graph_database.py | 227 +++++++++++++----- tests/test_csr_extra_fields.py | 163 ++++++++++++- 3 files changed, 349 insertions(+), 65 deletions(-) diff --git a/docs/source/graphs.md b/docs/source/graphs.md index 64f049f..ee86b43 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -146,8 +146,17 @@ raises `ValueError`; nothing is cast. The writes that take nodes as dictionaries (`write_nodes`, `bulk_write_nodes`, `write_attrs`) create an attribute named in `attributes` from the values the nodes carry, when those are numbers of one kind (bool, int or float, stored as bool, int64 or -float64) and one length; otherwise they raise and ask for a type. Values for -an attribute that exists are cast to its type. +float64) and one length; otherwise they raise and ask for a type. When no +node carries a value (an empty block) nothing is written and nothing is +created. A value for an attribute that exists is stored in the recorded type +or refused, never changed: a float for an integer or a bool, an integer for +a bool, and a sequence of another length than the vector raise. A Python +float takes the recorded float width and an integer the recorded integer +width, or becomes a float. + +A write that is refused records nothing: none of the attributes it names is +created. `id`, `step` and `own` are not names of attributes, because the +reads return arrays of those names. `node_attrs` is never needed for an extra attribute. It may name one with a type, `node_attrs={"score": "float32"}`, to create it up front in mode @@ -164,7 +173,8 @@ directory is created, changed or locked. Writing edges, writing nodes with stored attributes, and `drop_edges` raise `GraphIsReadOnly`. The node writes (`write_node_arrays`, `write_attrs`, `write_nodes`, `bulk_write_nodes`) take extra attributes only, for nodes that exist, and -need no position. +need no position, unless a `roi` is given: then every node carries its +position (read the graph with it), and a node without one raises. Writing is the database's: each handle appends to a segment file of its own in the extra directory, and `finalize()`, or leaving `bulk_write_mode` in @@ -212,6 +222,14 @@ What to know: its directory has segments. A read that names other attributes does not, so a worker reads the graph (`node_attrs=[...]` without the attribute it is writing) while the run is under way. +- With several directories open, `finalize()` merges every one. A directory + that fails does not keep the others from being merged; one error is raised + as it is, several as an `ExceptionGroup`. A directory with nothing to + merge, or that does not exist yet, is left alone. +- A finalize removes `node_-*.npy` files in the directory that its + `meta.json` does not name, which a finalize that was killed can leave. +- An error raised inside `bulk_write_mode` is the one that reaches the + caller; what was written before it is still merged. - Finalize holds the node ids and the attributes it rebuilds in memory. - A handle sees the arrays of the finalize it last loaded; open the graph again to see what another process finalized since. diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 3830582..74d271f 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -52,6 +52,9 @@ FORMAT_VERSION = 1 EXTRA_FORMAT_VERSION = 1 +RESERVED_NODE_NAMES = ("id", "step", "own") +"""Names the reads give to arrays of their own (the node id, the step that +reached a node, the block's own nodes): not names of extra attributes.""" ID_DTYPE = np.dtype(" None: continue self._check_extends(extra) for name in extra.meta["node_attrs"]: + if name in RESERVED_NODE_NAMES: + raise ValueError( + f"{extra.path} holds a node attribute named {name!r}, " + "which the reads use for an array of their own" + ) if name in self.meta["node_attrs"]: raise ValueError( f"node attribute {name!r} of {extra.path} is also stored " @@ -590,18 +613,35 @@ def _same_spec(self, name: str, spec: dict[str, Any]) -> None: f"in {extra.path}, not {self._types({name: spec})[name]}" ) - def _declare_extra(self, specs: Mapping[str, dict[str, Any]]) -> None: - """Record new extra attributes in the one directory that is open. - Another process may declare the same ones at the same time: the - first to hold the lock writes them, the others find them.""" + def _check_new_extra(self, names: Iterable[str]) -> None: + """Whether attributes of these names may be created by this handle.""" + names = sorted(names) + if not names: + return if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") + reserved = [n for n in names if n in RESERVED_NODE_NAMES] + if reserved: + raise ValueError( + f"{reserved} are not names of node attributes: the reads use " + f"{list(RESERVED_NODE_NAMES)} for arrays of their own" + ) if len(self._extra_dirs) != 1: raise ValueError( - f"{sorted(specs)} are new node attributes and " + f"{names} are new node attributes and " f"{len(self._extra_dirs)} extra directories are open: open the " "graph with the one directory they are to go into" ) + + def _declare_extra(self, specs: Mapping[str, dict[str, Any]]) -> None: + """Record new extra attributes in the one directory that is open. + Another process may declare the same ones at the same time: the + first to hold the lock writes them, the others find them. Either + all of ``specs`` are recorded or, when one disagrees with what is + recorded, none.""" + if not specs: + return + self._check_new_extra(specs) (extra,) = self._extra_dirs extra.path.mkdir(parents=True, exist_ok=True) with _locked(extra.path): @@ -613,17 +653,18 @@ def _declare_extra(self, specs: Mapping[str, dict[str, Any]]) -> None: "node_attrs": {}, "arrays": {}, } - added = False + held = extra.meta["node_attrs"] for name, spec in specs.items(): - if name not in extra.meta["node_attrs"]: - extra.meta["node_attrs"][name] = spec - added = True - if added: + if name in held and held[name] != spec: + extra.reload() + self._map_extra_fields() + self._same_spec(name, spec) + new = {name: spec for name, spec in specs.items() if name not in held} + if new: + held.update(new) extra.write() self._map_extra_fields() self._arrays = None - for name, spec in specs.items(): - self._same_spec(name, spec) def _extra_folders(self) -> list[_ExtraFields]: return self._extra_dirs @@ -655,21 +696,20 @@ def _split_extra( if any(self._extra[a] is extra for a in attrs) ] - def _extra_names(self, attrs: Iterable[str], specs) -> None: - """Refuse stored attributes; create the extra ones that are new, - with ``specs(names)`` giving the types of those; check the rest.""" + def _new_extra_names(self, attrs: Iterable[str]) -> list[str]: + """Refuse stored attributes and give the names that no directory + holds yet. Nothing is recorded.""" attrs = list(attrs) stored = [a for a in attrs if a in self.meta["node_attrs"]] if stored: self._refuse(f"cannot write the node attributes {stored}") - new = [a for a in attrs if a not in self._extra] - if new: + if any(a not in self._extra for a in attrs): for extra in self._extra_dirs: extra.reload() # another process may have created them self._map_extra_fields() - new = [a for a in attrs if a not in self._extra] - if new: - self._declare_extra(specs(new)) + new = [a for a in attrs if a not in self._extra] + self._check_new_extra(new) + return new @staticmethod def _spec_of_values(name: str, values: np.ndarray) -> dict[str, Any]: @@ -690,6 +730,9 @@ def _spec_of_values(name: str, values: np.ndarray) -> dict[str, Any]: def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None: ids = np.asarray(ids) arrays = {name: np.asarray(values) for name, values in attrs.items()} + # every check of the call comes before anything is recorded: a write + # that is refused declares no attribute + new = self._new_extra_names(arrays) for name, values in arrays.items(): if values.ndim == 0 or len(values) != len(ids): raise ValueError( @@ -697,13 +740,12 @@ def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None f"expected one entry for each of the {len(ids)} ids" ) given = { - name: self._spec_of_values(name, values) - for name, values in arrays.items() - if name not in self.meta["node_attrs"] + name: self._spec_of_values(name, values) for name, values in arrays.items() } - self._extra_names(arrays, lambda new: {name: given[name] for name in new}) for name, spec in given.items(): - self._same_spec(name, spec) + if name not in new: + self._same_spec(name, spec) + self._declare_extra({name: given[name] for name in new}) for extra, names in self._split_extra(arrays): records = np.empty(len(ids), dtype=extra.record_dtype(names)) records["id"] = ids @@ -711,6 +753,25 @@ def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None records[name] = arrays[name] self._segment("nodes", extra.path).append(records) + @staticmethod + def _fits(name: str, value: Any, spec: dict[str, Any]) -> None: + """Refuse a value of a node given as a dictionary that the recorded + type would have to change: a float for an integer or a bool, an + integer for a bool, anything that is not a number, and a sequence + of another length than the vector. A Python number has no width, so + a float is stored in the recorded float type and an integer in the + recorded integer type (numpy refuses one that is out of range).""" + given = np.asarray(value) + dtype = np.dtype(spec["dtype"]) + allowed = {"f": "fiub", "i": "iub", "u": "iub", "b": "b"}[dtype.kind] + shape = (spec["size"],) if spec["size"] else () + if given.dtype.kind not in allowed or given.shape != shape: + wanted = f"a vector of {spec['size']}" if spec["size"] else "one value" + raise ValueError( + f"node attribute {name!r} is {dtype.name}, {wanted}; " + f"{value!r} is not stored as that without changing it" + ) + def _write_extra_rows(self, nodes, roi: Roi | None, attributes) -> None: # left out, the extra attributes that exist are written; a new one # is named @@ -719,34 +780,47 @@ def _write_extra_rows(self, nodes, roi: Roi | None, attributes) -> None: for node_id, data in nodes.items(): if roi is not None: position = self._position(data) - if position is None or not roi.contains(tuple(position)): - continue - kept.append((node_id, data)) - - def infer(new: list[str]) -> dict[str, dict[str, Any]]: - specs = {} - for name in new: - values = [ - np.asarray(d[name]) for _, d in kept if d.get(name) is not None - ] - kinds = {v.dtype.kind for v in values} - shapes = {v.shape for v in values} - if ( - len(kinds) != 1 - or len(shapes) != 1 - or not kinds <= set("fiub") - or len(next(iter(shapes))) > 1 - ): + if position is None: raise ValueError( - f"node attribute {name!r} is new and its type cannot be " - f"told from the values of the nodes ({len(values)} " - f"values, kinds {sorted(kinds)}, shapes {sorted(shapes)}): " - "give its type in node_attrs when the graph is opened" + f"node {node_id} carries no {self.position_attribute!r}: " + "with a roi, the nodes carry their position (read them " + "with it, or write without a roi)" ) - specs[name] = self._spec_of_values(name, np.stack(values)) - return specs + if not roi.contains(tuple(position)): + continue + kept.append((node_id, data)) - self._extra_names(names, infer) + # every check of the call comes before anything is recorded + new = self._new_extra_names(names) + specs: dict[str, dict[str, Any]] = {} + for name in new: + values = [np.asarray(d[name]) for _, d in kept if d.get(name) is not None] + if not values: + # no node carries it (an empty block): nothing to write, and + # nothing to tell a type from + continue + kinds = {v.dtype.kind for v in values} + shapes = {v.shape for v in values} + if ( + len(kinds) != 1 + or len(shapes) != 1 + or not kinds <= set("fiub") + or len(next(iter(shapes))) > 1 + ): + raise ValueError( + f"node attribute {name!r} is new and its type cannot be " + f"told from the values of the nodes ({len(values)} " + f"values, kinds {sorted(kinds)}, shapes {sorted(shapes)}): " + "give its type in node_attrs when the graph is opened" + ) + specs[name] = self._spec_of_values(name, np.stack(values)) + names = [a for a in names if a in self._extra or a in specs] + for name in names: + spec = specs.get(name) or self._extra[name].stored["node_attrs"][name] + for _, data in kept: + if data.get(name) is not None: + self._fits(name, data[name], spec) + self._declare_extra(specs) for extra, own in self._split_extra(names): groups: dict[tuple[str, ...], list[tuple]] = {} for node_id, data in kept: @@ -803,7 +877,6 @@ def _finalize_extra(self, extra: _ExtraFields) -> None: values[name] = self._extra_array(extra, name, n, copy=True) written = self._present(batch[name]) values[name][rows[written]] = batch[name][written] - previous = [files.get(name) for name in values] for name, array in values.items(): file = f"node_{name}-{uuid.uuid4().hex[:12]}.npy" np.save(extra.path / file, array) @@ -814,9 +887,12 @@ def _finalize_extra(self, extra: _ExtraFields) -> None: "ids_crc32": zlib.crc32(ids), } extra.write() - for file in previous: - if file is not None: - (extra.path / file).unlink(missing_ok=True) + # the arrays that were replaced, and any that a finalize which was + # killed before it recorded them left behind + named = set(files.values()) + for file in extra.path.glob("node_*-*.npy"): + if file.name not in named: + file.unlink(missing_ok=True) for path in paths: path.unlink(missing_ok=True) @@ -1252,7 +1328,22 @@ def bulk_write_mode(self, worker=False, node_writes=True, edge_writes=True): self._bulk_depth += 1 try: yield - finally: + except BaseException: + # what was written is merged; the error of the block is the one + # that is raised, whatever the finalize has to say + self._bulk_depth -= 1 + for segment in self._segments.values(): + segment.close() + if not worker and self._bulk_depth == 0: + try: + self.finalize() + except Exception: + logger.exception( + "finalize of %s failed after an error in bulk_write_mode", + self.path, + ) + raise + else: self._bulk_depth -= 1 for segment in self._segments.values(): segment.close() @@ -1359,10 +1450,24 @@ def finalize(self) -> None: # one finalize at a time: a second process waits, then finds the # segments the first one merged gone if self._extra_dirs: + # every directory is finalized; one that fails does not keep + # the others from being merged + errors: list[Exception] = [] for extra in self._extra_dirs: - with _locked(extra.path): - self._finalize_extra(extra) + if not extra.pending(): + continue # nothing to merge; the directory may not exist + try: + with _locked(extra.path): + self._finalize_extra(extra) + except Exception as error: + errors.append(error) self._arrays = None + if len(errors) == 1: + raise errors[0] + if errors: + raise ExceptionGroup( + f"finalize failed in {len(errors)} extra directories", errors + ) return with _locked(self.path): self._finalize() diff --git a/tests/test_csr_extra_fields.py b/tests/test_csr_extra_fields.py index eb894c7..3d34dca 100644 --- a/tests/test_csr_extra_fields.py +++ b/tests/test_csr_extra_fields.py @@ -295,11 +295,47 @@ def test_a_later_write_has_the_type_that_was_recorded(tmp_path): db.write_node_arrays(few, cube=np.zeros((4, 2, 2))) with pytest.raises(ValueError, match=r"'label' has shape \(1,\).*each of the 4"): db.write_node_arrays(few, label=np.ones(1, np.int32)) + # the names the reads use for arrays of their own + for name in ("id", "step", "own"): + with pytest.raises(ValueError, match=f"'{name}'.* are not names of node attr"): + db.write_node_arrays(few, **{name: np.ones(4, np.float32)}) + with pytest.raises(ValueError, match="are not names of node attr"): + db.write_nodes({int(few[0]): {name: 1}}, attributes=[name]) + with pytest.raises(ValueError, match="are not names of node attr"): + CSRGraphDataBase( + tmp_path / "g.csr", + mode="r+", + node_attrs={name: "float32"}, + extra_fields=tmp_path / "pred", + ) + # a call that is refused for one attribute declares none of the others + with pytest.raises(ValueError, match="'label' is int32 in .*pred, not int64"): + db.write_node_arrays(few, fresh=np.ones(4), label=np.ones(4, np.int64)) + with pytest.raises(ValueError, match="'cube' has shape"): + db.write_node_arrays(few, fresh=np.ones(4), cube=np.zeros((4, 2, 2))) + with pytest.raises(ValueError, match="each of the 4"): + db.write_node_arrays(few, fresh=np.ones(4), short=np.ones(1)) + with pytest.raises(ValueError, match="'label' is int32"): + db.write_nodes( + {int(few[0]): {"fresh": 1, "label": 0.5}}, attributes=["fresh", "label"] + ) assert list((tmp_path / "pred" / "segments").glob("*.npys")) == [] assert sorted(CSRGraphDataBase.stored_extra_fields(tmp_path / "pred")) == [ "label", "vec", ] + nodes, _ = opened(tmp_path).read_arrays() + assert sorted(nodes) == ["id", "label", "position", "step", "vec"] + assert nodes["id"].dtype == np.uint64 and sorted(nodes["id"]) == sorted(ids) + # a directory that holds such a name (written by an earlier version) is + # refused when it is opened, not read with the node ids overwritten + meta = json.loads((tmp_path / "pred" / "meta.json").read_text()) + poisoned = tmp_path / "poisoned" + poisoned.mkdir() + meta["node_attrs"]["id"] = {"dtype": " Date: Wed, 25 Nov 2026 16:12:02 -0800 Subject: [PATCH 13/15] Extra fields: findings V1 to V8 of the review of 6ecb0bb - V1: a dictionary write with a roi leaves out a node that carries neither a value nor a position (read_graph(roi) adds one for an edge leaving the roi) and raises only for a node with a value and no position, so a block read with its region can be written back. - V2: the name of an extra attribute is letters, digits, '_', '.' and '-', not starting with '.' or '-'; any other is refused before anything is recorded, on every path. - V3: an extra directory inside the graph's directory, or one that holds it, is refused. - V4: a handle that finds an attribute another handle created drops the arrays it had loaded, so a read of it no longer raises KeyError. - V5: a dictionary value out of the range of the recorded type is refused in the check of the call (ValueError, was numpy's OverflowError after the declaration), as is a finite float that the recorded float width turns into inf. - V6: from_arrays builds the arrays of a graph without nodes, so it is a finalized graph and takes extra fields. - V7: node ids that are not integers are refused on the extra-fields writes. The graph's own writes are unchanged. - V8: ty passes under Python 3.11: crc32 is given a memoryview, and _present returns an array. Co-Authored-By: Claude Fable 5.2 --- docs/source/graphs.md | 18 ++- .../persistence/graphs/csr_graph_database.py | 104 ++++++++++++++--- tests/test_csr_extra_fields.py | 106 +++++++++++++++++- 3 files changed, 201 insertions(+), 27 deletions(-) diff --git a/docs/source/graphs.md b/docs/source/graphs.md index ee86b43..feef620 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -134,7 +134,8 @@ holds without opening a graph. of all of them. An attribute that two of them hold, or that the graph itself stores, is refused when the graph is opened. A directory that is empty or does not exist yet is created by the first write in mode `"r+"`; in mode -`"r"` it is an error. +`"r"` it is an error. An extra directory is never inside the graph's +directory, nor the other way round: both are refused. **A new attribute is created by the first write that names it**, with the type of the values written: `embedding=e` with `e` a float32 array of shape @@ -155,8 +156,11 @@ float takes the recorded float width and an integer the recorded integer width, or becomes a float. A write that is refused records nothing: none of the attributes it names is -created. `id`, `step` and `own` are not names of attributes, because the -reads return arrays of those names. +created. The name of an extra attribute is made of letters, digits, `_`, +`.` and `-`, and does not start with `.` or `-`, because it is part of the +name of a file. `id`, `step` and `own` are not names of attributes, because +the reads return arrays of those names. Node ids are integers, and a value +has to be in the range of the recorded type. `node_attrs` is never needed for an extra attribute. It may name one with a type, `node_attrs={"score": "float32"}`, to create it up front in mode @@ -173,8 +177,12 @@ directory is created, changed or locked. Writing edges, writing nodes with stored attributes, and `drop_edges` raise `GraphIsReadOnly`. The node writes (`write_node_arrays`, `write_attrs`, `write_nodes`, `bulk_write_nodes`) take extra attributes only, for nodes that exist, and -need no position, unless a `roi` is given: then every node carries its -position (read the graph with it), and a node without one raises. +need no position, unless a `roi` is given: then a node with a value to write +carries its position (read the graph with it), and one without raises. A +node that carries neither a value nor a position is left out. `read_graph(roi)` +adds such a node for every edge that leaves the region, so +`g.write_attrs(g.read_graph(roi), roi=roi, node_attrs=[...])` writes the +nodes inside the region. Writing is the database's: each handle appends to a segment file of its own in the extra directory, and `finalize()`, or leaving `bulk_write_mode` in diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 74d271f..824ec47 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -32,6 +32,7 @@ import json import logging import os +import re import shutil import uuid import zlib @@ -55,6 +56,9 @@ RESERVED_NODE_NAMES = ("id", "step", "own") """Names the reads give to arrays of their own (the node id, the step that reached a node, the block's own nodes): not names of extra attributes.""" +_EXTRA_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.\-]*") +"""The name of an extra attribute: letters, digits, ``_``, ``.`` and ``-``, +not starting with ``.`` or ``-``. It is part of the name of a file.""" ID_DTYPE = np.dtype(" dict[str, Any]: ids = np.load(self.path / self.meta["generation"] / "ids.npy", mmap_mode="r") checksum = 0 for start in range(0, len(ids), 1 << 22): - checksum = zlib.crc32(np.asarray(ids[start : start + (1 << 22)]), checksum) + chunk = np.ascontiguousarray(ids[start : start + (1 << 22)]) + checksum = zlib.crc32(memoryview(chunk), checksum) return { "num_nodes": self.meta["num_nodes"], "generation": self.meta["generation"], @@ -545,9 +558,17 @@ def _open_extra_fields(self, given: Mapping[str, AttributeType]) -> None: ) seen: set[Path] = set() for folder in self.extra_fields: - key = folder.resolve() - if key == self.path.resolve(): - raise ValueError("extra fields are kept outside the graph's directory") + key, graph = folder.resolve(), self.path.resolve() + if key == graph or key.is_relative_to(graph): + raise ValueError( + f"{folder}: extra fields are kept outside the graph's " + f"directory {self.path}, which they never change" + ) + if graph.is_relative_to(key): + raise ValueError( + f"{folder} holds the graph's directory {self.path}: extra " + "fields are kept in a directory of their own" + ) if key in seen: raise ValueError(f"{folder} is given twice in extra_fields") seen.add(key) @@ -615,9 +636,11 @@ def _same_spec(self, name: str, spec: dict[str, Any]) -> None: def _check_new_extra(self, names: Iterable[str]) -> None: """Whether attributes of these names may be created by this handle.""" - names = sorted(names) + names = sorted(names, key=str) if not names: return + if any(not isinstance(n, str) for n in names): + raise ValueError(f"{names} are not all names: an attribute name is a str") if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") reserved = [n for n in names if n in RESERVED_NODE_NAMES] @@ -626,6 +649,13 @@ def _check_new_extra(self, names: Iterable[str]) -> None: f"{reserved} are not names of node attributes: the reads use " f"{list(RESERVED_NODE_NAMES)} for arrays of their own" ) + unfit = [n for n in names if not _EXTRA_NAME.fullmatch(n)] + if unfit: + raise ValueError( + f"{unfit} are not names of extra node attributes: a name is " + "made of letters, digits, '_', '.' and '-', and does not start " + "with '.' or '-' (it is part of the name of a file)" + ) if len(self._extra_dirs) != 1: raise ValueError( f"{names} are new node attributes and " @@ -707,6 +737,8 @@ def _new_extra_names(self, attrs: Iterable[str]) -> list[str]: for extra in self._extra_dirs: extra.reload() # another process may have created them self._map_extra_fields() + # the arrays this handle loaded do not hold what was found + self._arrays = None new = [a for a in attrs if a not in self._extra] self._check_new_extra(new) return new @@ -729,6 +761,11 @@ def _spec_of_values(name: str, values: np.ndarray) -> dict[str, Any]: def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None: ids = np.asarray(ids) + if ids.ndim != 1 or (len(ids) and ids.dtype.kind not in "iu"): + raise ValueError( + f"ids are {ids.dtype} of shape {ids.shape}; node ids are " + "integers, one per node" + ) arrays = {name: np.asarray(values) for name, values in attrs.items()} # every check of the call comes before anything is recorded: a write # that is refused declares no attribute @@ -760,12 +797,22 @@ def _fits(name: str, value: Any, spec: dict[str, Any]) -> None: integer for a bool, anything that is not a number, and a sequence of another length than the vector. A Python number has no width, so a float is stored in the recorded float type and an integer in the - recorded integer type (numpy refuses one that is out of range).""" + recorded integer type, when it is in the range of that type.""" given = np.asarray(value) dtype = np.dtype(spec["dtype"]) allowed = {"f": "fiub", "i": "iub", "u": "iub", "b": "b"}[dtype.kind] shape = (spec["size"],) if spec["size"] else () - if given.dtype.kind not in allowed or given.shape != shape: + fits = given.dtype.kind in allowed and given.shape == shape + if fits and dtype.kind in "iu": + # exact Python integers: a value past int64 has dtype object + # and was refused above + bounds = np.iinfo(dtype.name) + fits = all(bounds.min <= int(x) <= bounds.max for x in given.flat) + elif fits and dtype.kind == "f": + with np.errstate(over="ignore"): + stored = given.astype(dtype) + fits = bool((np.isfinite(stored) | ~np.isfinite(given)).all()) + if not fits: wanted = f"a vector of {spec['size']}" if spec["size"] else "one value" raise ValueError( f"node attribute {name!r} is {dtype.name}, {wanted}; " @@ -778,13 +825,21 @@ def _write_extra_rows(self, nodes, roi: Roi | None, attributes) -> None: names = list(self._extra) if attributes is None else list(attributes) kept = [] for node_id, data in nodes.items(): + if isinstance(node_id, bool) or not isinstance(node_id, int | np.integer): + raise ValueError(f"{node_id!r} is not a node id: an id is an integer") if roi is not None: position = self._position(data) if position is None: + # a node that read_graph(roi) added for an edge leaving + # the roi carries nothing; one with a value to write and + # no position cannot be placed and is not left out + if all(data.get(a) is None for a in names): + continue raise ValueError( - f"node {node_id} carries no {self.position_attribute!r}: " - "with a roi, the nodes carry their position (read them " - "with it, or write without a roi)" + f"node {node_id} carries values and no " + f"{self.position_attribute!r}: with a roi, the nodes " + "carry their position (read them with it, or write " + "without a roi)" ) if not roi.contains(tuple(position)): continue @@ -884,7 +939,7 @@ def _finalize_extra(self, extra: _ExtraFields) -> None: extra.stored["extends"] = { "num_nodes": n, "generation": self.meta["generation"], - "ids_crc32": zlib.crc32(ids), + "ids_crc32": zlib.crc32(memoryview(np.ascontiguousarray(ids))), } extra.write() # the arrays that were replaced, and any that a finalize which was @@ -1021,6 +1076,17 @@ def columns(what, given, count, named) -> tuple[dict, dict]: db.write_node_arrays(ids, **node_arrays) if u is not None and v is not None: db.write_edge_arrays(u, v, **edge_arrays) + if db.meta["generation"] is None: + # no node: nothing was appended, so nothing was merged. The + # arrays of an empty graph are built all the same, so that + # it is a finalized graph like any other + empty = db._empty() + db._build( + empty["ids"], + {k: empty[f"node_{k}"] for k in db.meta["node_attrs"]}, + None, + sort_nodes=True, + ) db.close() except BaseException: shutil.rmtree(scratch, ignore_errors=True) @@ -1418,7 +1484,7 @@ def _present(values: np.ndarray) -> np.ndarray: if values.dtype.kind != "f": return np.ones(len(values), dtype=bool) missing = np.isnan(values) - return ~(missing.all(axis=1) if values.ndim > 1 else missing) + return np.asarray(~(missing.all(axis=1) if values.ndim > 1 else missing)) def _edge_list(self, arrays: dict[str, np.ndarray]): """Every edge of the arrays once, as ids, from its smaller end.""" @@ -1508,7 +1574,9 @@ def _finalize(self) -> None: path.unlink(missing_ok=True) def _build(self, ids, nodes, edges, sort_nodes: bool) -> None: - position = nodes[self.position_attribute].reshape(len(ids), -1).astype(float) + position = ( + nodes[self.position_attribute].reshape(len(ids), self.ndims).astype(float) + ) if sort_nodes or self.meta.get("origin") is None: lowest = position.min(axis=0) if len(ids) else np.zeros(self.ndims) origin = np.floor(lowest / self.cell_size) * self.cell_size diff --git a/tests/test_csr_extra_fields.py b/tests/test_csr_extra_fields.py index 3d34dca..e953b6b 100644 --- a/tests/test_csr_extra_fields.py +++ b/tests/test_csr_extra_fields.py @@ -308,6 +308,26 @@ def test_a_later_write_has_the_type_that_was_recorded(tmp_path): node_attrs={name: "float32"}, extra_fields=tmp_path / "pred", ) + # a name is part of the name of a file + for name in ("a/b", "..", ".hidden", "-x", "", "a b", "a\\b"): + with pytest.raises(ValueError, match="are not names of extra node attr"): + db.write_node_arrays(few, **{name: np.ones(4, np.float32)}) + with pytest.raises(ValueError, match="are not names of extra node attr"): + db.write_nodes({int(few[0]): {name: 1}}, attributes=[name]) + with pytest.raises(ValueError, match="are not names of extra node attr"): + CSRGraphDataBase( + tmp_path / "g.csr", + mode="r+", + node_attrs={name: "float32"}, + extra_fields=tmp_path / "pred", + ) + db.write_node_arrays(few[:0], **{"ok-1.b_2": np.ones(0, np.float32)}) + assert "ok-1.b_2" in db.node_attrs + # node ids are integers: 2.5 is not node 2 + for bad in (few.astype(np.float64), few.reshape(2, 2), np.array(["1"] * 4)): + with pytest.raises(ValueError, match="node ids are integers, one per node"): + db.write_node_arrays(bad, late=np.ones(4)) + assert "late" not in db.node_attrs # a call that is refused for one attribute declares none of the others with pytest.raises(ValueError, match="'label' is int32 in .*pred, not int64"): db.write_node_arrays(few, fresh=np.ones(4), label=np.ones(4, np.int64)) @@ -322,10 +342,11 @@ def test_a_later_write_has_the_type_that_was_recorded(tmp_path): assert list((tmp_path / "pred" / "segments").glob("*.npys")) == [] assert sorted(CSRGraphDataBase.stored_extra_fields(tmp_path / "pred")) == [ "label", + "ok-1.b_2", "vec", ] nodes, _ = opened(tmp_path).read_arrays() - assert sorted(nodes) == ["id", "label", "position", "step", "vec"] + assert sorted(nodes) == ["id", "label", "ok-1.b_2", "position", "step", "vec"] assert nodes["id"].dtype == np.uint64 and sorted(nodes["id"]) == sorted(ids) # a directory that holds such a name (written by an earlier version) is # refused when it is opened, not read with the node ids overwritten @@ -467,9 +488,26 @@ def test_nodes_given_as_dictionaries_write_their_extra_attributes(tmp_path): # with a region the nodes carry their position: one that has none is not # silently left out bare = db.read_graph(roi, node_attrs=["label"]) - with pytest.raises(ValueError, match="carries no 'position'.*without a roi"): + with pytest.raises(ValueError, match="values and no 'position'.*without a roi"): db.write_attrs(bare, roi=roi, node_attrs=["label"]) assert list((tmp_path / "pred" / "segments").glob("*.npys")) == [] + # a block read with its region and written back: read_graph adds the far + # end of an edge that leaves the region as a node that carries nothing, + # and that node is not a reason to refuse the block + block = db.read_graph(roi, node_attrs=["position", "label"]) + outside = [n for n, d in block.nodes(data=True) if "position" not in d] + assert outside and all(not block.nodes[n] for n in outside) + for _, data in block.nodes(data=True): + if "position" in data: + data["label"] = 55 + db.write_attrs(block, roi=roi, node_attrs=["label"]) + labels = by_id(db.read_arrays()[0], "label") + written = sorted(n for n, label in labels.items() if label == 55) + assert written == sorted(n for n in block.nodes if n not in outside) + assert written == sorted(db.read_arrays(roi)[0]["id"].tolist()) + for node, data in block.nodes(data=True): + data["label"] = node % 9 + 1 # as it was, for what follows + db.write_attrs(block, node_attrs=["label"]) # a value is stored in the recorded type or refused, never changed: # label is int32, vec a float32 vector of 3 @@ -488,8 +526,24 @@ def test_nodes_given_as_dictionaries_write_their_extra_attributes(tmp_path): for values in changed: with pytest.raises(ValueError, match="is not stored as that without chang"): db.write_nodes({one: values}, attributes=list(values)) - with pytest.raises(OverflowError): - db.write_nodes({one: {"label": 2**40}}, attributes=["label"]) + # out of the range of the recorded type; with it, an attribute of the + # same call that would have been new is not created + out_of_range: list[dict[str, Any]] = [ + {"label": 2**40}, + {"label": -(2**31) - 1}, + {"label": 2**70}, + {"vec": (1e300, 0.0, 0.0)}, + ] + for values in out_of_range: + with pytest.raises(ValueError, match="is not stored as that without chang"): + db.write_nodes({one: {"znew": 1.0, **values}}, attributes=["znew", *values]) + assert "znew" not in CSRGraphDataBase.stored_extra_fields(tmp_path / "pred") + two = int(ids[1]) + db.write_nodes({two: {"vec": (float("inf"), 0.0, 1e30)}}) # inf is a value + assert by_id(db.read_arrays()[0], "vec")[two][0] == float("inf") + for key in (1.5, "7", True): + with pytest.raises(ValueError, match="is not a node id"): + db.write_nodes({key: {"label": 1}}) after = {k: by_id(db.read_arrays()[0], k)[one] for k in before} np.testing.assert_equal(after, before) assert list((tmp_path / "pred" / "segments").glob("*.npys")) == [] @@ -625,6 +679,9 @@ def test_extra_fields_that_cannot_be_opened_are_refused(tmp_path): refused: list[tuple[dict[str, Any], str]] = [ ({"mode": "w", "cell_size": 1.0}, "mode 'w' creates the graph"), ({"extra_fields": graph}, "outside the graph's directory"), + ({"extra_fields": graph / "pred"}, "outside the graph's directory"), + ({"extra_fields": graph / "segments" / ".." / "a" / "b"}, "outside the graph"), + ({"extra_fields": [pred, tmp_path]}, "holds the graph's directory"), ({"extra_fields": [pred, tmp_path / "x" / ".." / "pred"]}, "is given twice"), # a directory that holds something else ({"extra_fields": tmp_path / "h.csr"}, "not a directory of extra node attr"), @@ -800,3 +857,44 @@ def test_an_array_that_no_record_names_is_removed_by_the_next_finalize(tmp_path) assert now.name.startswith("node_label-") and now != kept assert (pred / "notes.npy").exists() assert int(opened(tmp_path).read_arrays()[0]["label"].sum()) == 3 + + +def test_a_handle_reads_an_attribute_it_found_another_handle_had_created(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + first, second = opened(tmp_path, "r+"), opened(tmp_path, "r+") + assert len(first.read_arrays()[0]["id"]) == N # its arrays are loaded + with second.bulk_write_mode(worker=True): + second.write_node_arrays(ids[:2], b=np.ones(2, np.float32)) + with first.bulk_write_mode(worker=True): + first.write_node_arrays(ids[2:4], b=np.full(2, 2, np.float32)) + opened(tmp_path, "r+").finalize() + assert "b" in first.node_attrs + for nodes in (first.read_arrays()[0], first.read_arrays(node_attrs=["b"])[0]): + b = by_id(nodes, "b") + assert [b[int(i)] for i in ids[:4]] == [1.0, 1.0, 2.0, 2.0] + + +def test_a_graph_without_nodes_takes_extra_fields(tmp_path): + none = np.zeros(0, dtype=np.uint64) + db = CSRGraphDataBase.from_arrays( + tmp_path / "g.csr", none, {"position": np.zeros((0, 3))}, cell_size=10.0 + ) + assert db.num_nodes == 0 and len(db.read_arrays()[0]["id"]) == 0 + assert db.read_graph(Roi((0, 0, 0), (10, 10, 10))).number_of_nodes() == 0 + # it is a graph like any other: nodes can still be written to it + more = CSRGraphDataBase.from_arrays( + tmp_path / "h.csr", none, {"position": np.zeros((0, 3))}, cell_size=10.0 + ) + more.write_node_arrays(np.array([4], dtype=np.uint64), position=np.ones((1, 3))) + assert CSRGraphDataBase(tmp_path / "h.csr").read_arrays()[0]["id"].tolist() == [4] + + extended = opened(tmp_path, "r+") + with extended.bulk_write_mode(): + extended.write_node_arrays(none, vec=np.zeros((0, 3), np.float32)) + assert extended.node_attrs["vec"] == Vec("float32", 3) + nodes, edges = opened(tmp_path).read_arrays() + assert nodes["vec"].shape == (0, 3) and len(edges["u"]) == 0 + with pytest.raises(ValueError, match="ids that are not nodes"): + extended.write_node_arrays( + np.array([1], dtype=np.uint64), vec=np.zeros((1, 3), np.float32) + ) From 2981e7f801f3110fad77999aecc70078c824689c Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 16:13:26 -0800 Subject: [PATCH 14/15] crc32 of the node ids from bytes, so ty passes under Python 3.11 An ndarray is not a Buffer for the type checker before Python 3.12, with or without memoryview. The checksum is the same. Co-Authored-By: Claude Fable 5.2 --- .../persistence/graphs/csr_graph_database.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 824ec47..455432c 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -202,6 +202,15 @@ def read(path: Path) -> list[np.ndarray]: return records +def _ids_crc32(ids: np.ndarray) -> int: + """The crc32 of node ids in row order, a few million at a time.""" + checksum = 0 + for start in range(0, len(ids), 1 << 22): + chunk = np.asarray(ids[start : start + (1 << 22)], dtype=ID_DTYPE) + checksum = zlib.crc32(chunk.tobytes(), checksum) + return checksum + + class _ExtraFields: """A directory of extra node attributes of one graph:: @@ -524,14 +533,10 @@ def stored_extra_fields(path: Path | str) -> dict[str, AttributeType]: def _extends(self) -> dict[str, Any]: """What an extra directory records of this graph.""" ids = np.load(self.path / self.meta["generation"] / "ids.npy", mmap_mode="r") - checksum = 0 - for start in range(0, len(ids), 1 << 22): - chunk = np.ascontiguousarray(ids[start : start + (1 << 22)]) - checksum = zlib.crc32(memoryview(chunk), checksum) return { "num_nodes": self.meta["num_nodes"], "generation": self.meta["generation"], - "ids_crc32": checksum, + "ids_crc32": _ids_crc32(ids), } def _check_extends(self, extra: _ExtraFields) -> None: @@ -939,7 +944,7 @@ def _finalize_extra(self, extra: _ExtraFields) -> None: extra.stored["extends"] = { "num_nodes": n, "generation": self.meta["generation"], - "ids_crc32": zlib.crc32(memoryview(np.ascontiguousarray(ids))), + "ids_crc32": _ids_crc32(ids), } extra.write() # the arrays that were replaced, and any that a finalize which was From f46adddaaa890eddf08ea0c439dc593ac1dc3023 Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 25 Nov 2026 16:27:41 -0800 Subject: [PATCH 15/15] read_block with a context on a region without nodes; bound the length of an attribute name - W1: read_block with any context raised 'cannot reshape array of size 0' when the grown region held no node: the positions of no node were reshaped to (0, -1). The number of dimensions is given. A new test drives read_arrays, read_block, read_nodes, read_edges, read_graph, has_edges, from_arrays and the extra-fields writes and finalize through a region with no node, a region with nodes and no edge, a graph with no edge and a graph with no node, with and without extra fields, and through a database that was never written. - W2: the name of an extra attribute has at most 233 characters, so that node_-<12 characters>.npy is a file name of at most 255. - A negative node id is refused on the extra-fields writes, as a float id is: it would be stored as an id near 2^64 and block the finalize. Co-Authored-By: Claude Fable 5.2 --- docs/source/graphs.md | 6 +- .../persistence/graphs/csr_graph_database.py | 37 ++- tests/test_csr_empty_cases.py | 221 ++++++++++++++++++ tests/test_csr_extra_fields.py | 16 ++ tests/test_csr_graph_database.py | 6 + 5 files changed, 274 insertions(+), 12 deletions(-) create mode 100644 tests/test_csr_empty_cases.py diff --git a/docs/source/graphs.md b/docs/source/graphs.md index feef620..8fe087c 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -157,9 +157,11 @@ width, or becomes a float. A write that is refused records nothing: none of the attributes it names is created. The name of an extra attribute is made of letters, digits, `_`, -`.` and `-`, and does not start with `.` or `-`, because it is part of the +`.` and `-`, does not start with `.` or `-`, and has at most 233 +characters, because it is part of the name of a file. `id`, `step` and `own` are not names of attributes, because -the reads return arrays of those names. Node ids are integers, and a value +the reads return arrays of those names. Node ids are integers that are not +negative, and a value has to be in the range of the recorded type. `node_attrs` is never needed for an extra attribute. It may name one with a diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index 455432c..2b36f82 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -56,9 +56,11 @@ RESERVED_NODE_NAMES = ("id", "step", "own") """Names the reads give to arrays of their own (the node id, the step that reached a node, the block's own nodes): not names of extra attributes.""" -_EXTRA_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.\-]*") +_EXTRA_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.\-]{0,232}") """The name of an extra attribute: letters, digits, ``_``, ``.`` and ``-``, -not starting with ``.`` or ``-``. It is part of the name of a file.""" +not starting with ``.`` or ``-``, at most 233 characters. It is part of the +name of a file, ``node_-<12 characters>.npy``, which a file system +commonly limits to 255 bytes.""" ID_DTYPE = np.dtype(" None: if unfit: raise ValueError( f"{unfit} are not names of extra node attributes: a name is " - "made of letters, digits, '_', '.' and '-', and does not start " - "with '.' or '-' (it is part of the name of a file)" + "made of letters, digits, '_', '.' and '-', does not start " + "with '.' or '-' and has at most 233 characters (it is part of " + "the name of a file)" ) if len(self._extra_dirs) != 1: raise ValueError( @@ -771,6 +775,10 @@ def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None f"ids are {ids.dtype} of shape {ids.shape}; node ids are " "integers, one per node" ) + if ids.dtype.kind == "i" and len(ids) and int(ids.min()) < 0: + raise ValueError( + f"{int(ids.min())} is not a node id: an id is not negative" + ) arrays = {name: np.asarray(values) for name, values in attrs.items()} # every check of the call comes before anything is recorded: a write # that is refused declares no attribute @@ -830,8 +838,14 @@ def _write_extra_rows(self, nodes, roi: Roi | None, attributes) -> None: names = list(self._extra) if attributes is None else list(attributes) kept = [] for node_id, data in nodes.items(): - if isinstance(node_id, bool) or not isinstance(node_id, int | np.integer): - raise ValueError(f"{node_id!r} is not a node id: an id is an integer") + if ( + isinstance(node_id, bool) + or not isinstance(node_id, int | np.integer) + or node_id < 0 + ): + raise ValueError( + f"{node_id!r} is not a node id: an id is an integer, not negative" + ) if roi is not None: position = self._position(data) if position is None: @@ -1896,7 +1910,10 @@ def read_block( step_edges, edge_ends, ) - at = np.asarray(nodes[position], dtype=float).reshape(len(nodes["id"]), -1) + # the number of dimensions is given: no node leaves nothing to infer + at = np.asarray(nodes[position], dtype=float).reshape( + len(nodes["id"]), self.ndims + ) own = nodes["step"] == 0 bounds = self._bounds(roi) if bounds is not None: diff --git a/tests/test_csr_empty_cases.py b/tests/test_csr_empty_cases.py new file mode 100644 index 0000000..943a564 --- /dev/null +++ b/tests/test_csr_empty_cases.py @@ -0,0 +1,221 @@ +"""Every read and write of the CSR graph database on the four ways a result +can be empty: a region with no node, a region with nodes and no edge, a +graph with no edge at all, and a graph with no node.""" + +import itertools + +import networkx as nx +import numpy as np +import pytest +from funlib.geometry import Roi + +from funlib.persistence.graphs import CSRGraphDataBase +from funlib.persistence.types import Vec + +NONE = np.zeros(0, dtype=np.uint64) +WHOLE = Roi((0, 0, 0), (1000, 1000, 1000)) + + +def build(path, case): + """The graph of a case, the region to read, and the ids of the nodes in + that region and of those within reach of it.""" + if case == "no node in the graph": + ids, pos = NONE, np.zeros((0, 3)) + u = v = NONE + else: + # 1-2-3 joined near the origin; 7 and 8 on their own, far away + ids = np.array([1, 2, 3, 7, 8], dtype=np.uint64) + pos = np.array( + [[5, 5, 5], [5, 5, 15], [5, 5, 25], [505, 505, 505], [505, 505, 515]], + dtype=np.float64, + ) + u, v = ids[:2], ids[1:3] + if case == "no edge in the graph": + u = v = NONE + weight = np.full(len(u), 0.5, dtype=np.float32) + kind = np.ones(len(u), dtype=np.int8) + if case == "no edge in the graph, none given": + db = CSRGraphDataBase.from_arrays( + path, ids, {"position": pos, "size": np.arange(len(ids))}, cell_size=20.0 + ) + else: + db = CSRGraphDataBase.from_arrays( + path, + ids, + {"position": pos, "size": np.arange(len(ids))}, + u, + v, + {"weight": weight, "kind": kind}, + cell_size=20.0, + ) + db.close() + roi = { + "no node in the region": Roi((800, 800, 800), (10, 10, 10)), + "nodes and no edge in the region": Roi((500, 500, 500), (20, 20, 20)), + }.get(case, WHOLE) + lo, hi = np.array(roi.begin), np.array(roi.end) + inside = ids[((pos >= lo) & (pos < hi)).all(axis=1)] if len(ids) else NONE + return roi, sorted(inside.tolist()) + + +CASES = [ + "no node in the region", + "nodes and no edge in the region", + "no edge in the graph", + "no edge in the graph, none given", + "no node in the graph", +] + + +def check(db, nodes, edges, expected_ids, extras, own=False, node_attrs=None): + """A result of the documented shape, whatever it holds.""" + n = len(nodes["id"]) + assert nodes["id"].dtype == np.uint64 and nodes["id"].ndim == 1 + assert nodes["step"].dtype == np.int16 and nodes["step"].shape == (n,) + if expected_ids is not None: + assert sorted(nodes["id"].tolist()) == expected_ids + names = list(db.node_attrs) if node_attrs is None else node_attrs + assert set(nodes) == {"id", "step", *names, *(["own"] if own else [])} + if "position" in names: + assert nodes["position"].shape == (n, 3) + assert nodes["position"].dtype == np.float64 + if "size" in names: + assert nodes["size"].shape == (n,) and nodes["size"].dtype == np.int64 + if extras and node_attrs is None: + assert nodes["vec"].shape == (n, 3) and nodes["vec"].dtype == np.float32 + assert nodes["label"].shape == (n,) and nodes["label"].dtype == np.int32 + if own: + assert nodes["own"].dtype == bool and nodes["own"].shape == (n,) + m = len(edges["u"]) + assert edges["u"].dtype == edges["v"].dtype == np.uint64 + assert edges["v"].shape == (m,) + assert set(edges) == {"u", "v", *db.edge_attrs} + for name, dtype in (("weight", np.float32), ("kind", np.int8)): + if name in edges: + assert edges[name].shape == (m,) and edges[name].dtype == dtype + return n, m + + +@pytest.mark.parametrize("extras", [False, True], ids=["plain", "extra fields"]) +@pytest.mark.parametrize("case", CASES) +def test_every_read_and_write_on_an_empty_result(tmp_path, case, extras): + path = tmp_path / "g.csr" + roi, inside = build(path, case) + ids_all = sorted(CSRGraphDataBase(path).read_arrays()[0]["id"].tolist()) + has_weight = "weight" in CSRGraphDataBase(path).edge_attrs + + if extras: + # -- the extra-fields writes and their finalize --------------------- + db = CSRGraphDataBase(path, mode="r+", extra_fields=tmp_path / "pred") + db.finalize() # nothing written yet + with db.bulk_write_mode(): + pass + nodes_in, _ = db.read_arrays(roi) + with db.bulk_write_mode(): + # the nodes of the region, which may be none + db.write_node_arrays( + nodes_in["id"], + vec=np.ones((len(nodes_in["id"]), 3), np.float32), + label=np.full(len(nodes_in["id"]), 4, np.int32), + ) + assert db.node_attrs["vec"] == Vec("float32", 3) + graph = db.read_graph(roi, node_attrs=["position", "label"]) + for _, data in graph.nodes(data=True): + if "position" in data: + data["label"] = 9 + db.write_attrs(graph, roi=roi, node_attrs=["label"]) + db.write_nodes({}, attributes=["label", "another"]) + db.write_nodes({int(i): {"label": 9} for i in inside}) + db.finalize() + db = CSRGraphDataBase(path, extra_fields=tmp_path / "pred") + labels = db.read_arrays()[0] + written = sorted(labels["id"][labels["label"] == 9].tolist()) + assert written == inside + else: + db = CSRGraphDataBase(path) + + # -- read_arrays ------------------------------------------------------- + step_choices = [None, [], *([["weight"]] if has_weight else [])] + for steps, step_edges, edge_ends in itertools.product( + (0, 1, 3), step_choices, ("both", "u", "either") + ): + nodes, edges = db.read_arrays( + roi, num_steps=steps, step_edges=step_edges, edge_ends=edge_ends + ) + n, m = check(db, nodes, edges, inside if steps == 0 else None, extras) + assert set(inside) <= set(nodes["id"].tolist()) <= set(ids_all) + if edge_ends == "both": + assert set(edges["u"].tolist()) | set(edges["v"].tolist()) <= set( + nodes["id"].tolist() + ) + nodes, edges = db.read_arrays(roi, node_attrs=[], edge_attrs=[]) + assert set(nodes) == {"id", "step"} and set(edges) == {"u", "v"} + nodes, edges = db.read_arrays() + assert check(db, nodes, edges, ids_all, extras)[0] == len(ids_all) + + # -- read_block -------------------------------------------------------- + contexts = (None, 0, 5, 2.5, [0, 0, 30], 2000) + for context, steps, edge_ends in itertools.product( + contexts, (0, 2), ("both", "u", "either") + ): + for step_edges in step_choices: + for node_attrs in (None, [], ["size"]): + nodes, edges = db.read_block( + roi, + context=context, + num_steps=steps, + node_attrs=node_attrs, + step_edges=step_edges, + edge_ends=edge_ends, + ) + check(db, nodes, edges, None, extras, own=True, node_attrs=node_attrs) + assert sorted(nodes["id"][nodes["own"]].tolist()) == inside + if context is None and steps == 0: + assert nodes["own"].all() + + # -- the reads that give dictionaries and a networkx graph ------------- + listed = db.read_nodes(roi) + assert sorted(n["id"] for n in listed) == inside + assert db.read_nodes(roi, attr_filter={"size": 10**6}) == [] + for fetch_on_v in (False, True): + from_roi = db.read_edges(roi, fetch_on_v=fetch_on_v) + from_nodes = db.read_edges(nodes=listed, fetch_on_v=fetch_on_v) + assert sorted((e["u"], e["v"]) for e in from_roi) == sorted( + (e["u"], e["v"]) for e in from_nodes + ) + assert db.read_edges(nodes=[], fetch_on_v=fetch_on_v) == [] + graph = db.read_graph(roi, fetch_on_v=fetch_on_v) + assert set(inside) <= set(graph.nodes) + assert graph.number_of_edges() == len(from_roi) + _, edges = db.read_arrays(roi, edge_ends="either" if fetch_on_v else "u") + assert len(edges["u"]) == len(from_roi) + assert db.read_graph(roi, read_edges=False).number_of_edges() == 0 + assert db.read_graph(roi, nodes_filter={"size": 10**6}).number_of_nodes() == 0 + assert isinstance(db.read_graph(), nx.Graph) + assert db.has_edges(roi) is bool(db.read_edges(roi, fetch_on_v=True)) + assert db.num_nodes == len(ids_all) + + +def test_a_database_that_was_created_and_never_written_reads_as_empty(tmp_path): + db = CSRGraphDataBase( + tmp_path / "g.csr", + mode="w", + node_attrs={"position": Vec(float, 3), "size": int}, + edge_attrs={"weight": "float32", "kind": "int8"}, + cell_size=20.0, + ) + for handle in (db, CSRGraphDataBase(tmp_path / "g.csr")): + for context, steps, edge_ends in itertools.product( + (None, 0, 5), (0, 2), ("both", "u", "either") + ): + nodes, edges = handle.read_block( + WHOLE, context=context, num_steps=steps, edge_ends=edge_ends + ) + assert check(handle, nodes, edges, [], False, own=True) == (0, 0) + nodes, edges = handle.read_arrays(num_steps=1, step_edges=["weight"]) + assert check(handle, nodes, edges, [], False) == (0, 0) + assert handle.read_nodes(WHOLE) == [] and handle.read_edges(WHOLE) == [] + assert handle.read_graph(WHOLE).number_of_nodes() == 0 + assert handle.has_edges(WHOLE) is False + db.finalize() # nothing to merge + assert db.num_nodes == 0 diff --git a/tests/test_csr_extra_fields.py b/tests/test_csr_extra_fields.py index e953b6b..636b6bb 100644 --- a/tests/test_csr_extra_fields.py +++ b/tests/test_csr_extra_fields.py @@ -321,6 +321,22 @@ def test_a_later_write_has_the_type_that_was_recorded(tmp_path): node_attrs={name: "float32"}, extra_fields=tmp_path / "pred", ) + # and the file is node_-<12 characters>.npy, of at most 255 bytes + for name in ("x" * 234, "x" * 300): + with pytest.raises(ValueError, match="at most 233 characters"): + db.write_node_arrays(few, **{name: np.ones(4, np.float32)}) + longest = CSRGraphDataBase( + tmp_path / "g.csr", mode="r+", extra_fields=tmp_path / "l" + ) + longest.write_node_arrays(few, **{"x" * 233: np.ones(4, np.float32)}) + (stored,) = (tmp_path / "l").glob("node_*.npy") + assert len(stored.name) == 255 + assert np.nansum(opened(tmp_path, folder="l").read_arrays()[0]["x" * 233]) == 4 + # an id is not negative + with pytest.raises(ValueError, match="-1 is not a node id"): + db.write_node_arrays(np.array([-1, 2, 3, 4]), late=np.ones(4)) + with pytest.raises(ValueError, match="-1 is not a node id"): + db.write_nodes({-1: {"label": 1}}) db.write_node_arrays(few[:0], **{"ok-1.b_2": np.ones(0, np.float32)}) assert "ok-1.b_2" in db.node_attrs # node ids are integers: 2.5 is not node 2 diff --git a/tests/test_csr_graph_database.py b/tests/test_csr_graph_database.py index f6a512e..25e7c83 100644 --- a/tests/test_csr_graph_database.py +++ b/tests/test_csr_graph_database.py @@ -524,6 +524,12 @@ def own(nodes): with pytest.raises(ValueError, match="num_steps must be >= 0"): db.read_block(block, num_steps=-1) + # a block whose surroundings hold no node, with a context or without + far = Roi((500, 500, 500), (10, 10, 10)) + for context in (None, 0, 5, [1, 2, 3]): + nodes, edges = db.read_block(far, context=context, num_steps=1) + assert nodes["position"].shape == (0, 3) and nodes["own"].shape == (0,) + assert nodes["own"].dtype == bool and len(edges["u"]) == 0 for negative in (-1, -0.5, [0, 0, -0.25], float("nan")): with pytest.raises(ValueError, match="context must be >= 0"): db.read_block(block, context=negative)