From d902c78248660fabef45ca87fdad442ef2daf341 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 11 Nov 2026 01:36:36 +0000 Subject: [PATCH 01/11] feat(meshing): read a table's mesh locations from its mesh block - `MeshMeta` resolves `dir`, `initial_mesh_dir` and `dynamic_mesh_dir` from `custom_data["mesh"]`; either mesh dir may be a cloud URL. - Setup writes the shard spec and the mesh block, never the watershed's info. - `dataset_info` and the graphene info take mesh keys from the mesh block alone. Co-Authored-By: Claude --- pychunkedgraph/app/segmentation/common.py | 12 +- pychunkedgraph/graph/meta.py | 15 ++- pychunkedgraph/meshing/mesh_meta/README.md | 76 +++++++++++++ pychunkedgraph/meshing/mesh_meta/__init__.py | 5 + pychunkedgraph/meshing/mesh_meta/core.py | 107 ++++++++++++++++++ pychunkedgraph/meshing/meshgen_utils.py | 6 +- pychunkedgraph/pipeline/meshing/setup.py | 37 +++--- .../tests/meshing/test_mesh_meta.py | 35 ++++++ 8 files changed, 261 insertions(+), 32 deletions(-) create mode 100644 pychunkedgraph/meshing/mesh_meta/README.md create mode 100644 pychunkedgraph/meshing/mesh_meta/__init__.py create mode 100644 pychunkedgraph/meshing/mesh_meta/core.py create mode 100644 pychunkedgraph/tests/meshing/test_mesh_meta.py diff --git a/pychunkedgraph/app/segmentation/common.py b/pychunkedgraph/app/segmentation/common.py index b07a284eb..c19fb6bc2 100644 --- a/pychunkedgraph/app/segmentation/common.py +++ b/pychunkedgraph/app/segmentation/common.py @@ -14,6 +14,7 @@ from pychunkedgraph import __version__ from pychunkedgraph.app import app_utils +from pychunkedgraph.meshing.mesh_meta import MeshMeta from pychunkedgraph.graph import ( attributes, cutting, @@ -106,11 +107,12 @@ def handle_info(table_id): combined_info["verify_mesh"] = cg.meta.custom_data.get("mesh", {}).get( "verify", False ) - mesh_dir = cg.meta.custom_data.get("mesh", {}).get("dir", None) - if mesh_dir is not None: - combined_info["mesh_dir"] = mesh_dir - elif combined_info.get("mesh_dir", None) is not None: - combined_info["mesh_dir"] = "graphene_meshes" + # A table without a mesh dir has no meshes, so it advertises none. + if cg.meta.custom_data.get("mesh", {}).get("dir") is not None: + mm = MeshMeta(cg) + combined_info["mesh_dir"] = mm.dir + combined_info["dynamic_mesh_dir"] = mm.dynamic_mesh_dir + combined_info["mesh_metadata"] = mm.client_metadata return jsonify(combined_info) diff --git a/pychunkedgraph/graph/meta.py b/pychunkedgraph/graph/meta.py index 83d670ffe..37e922b6f 100644 --- a/pychunkedgraph/graph/meta.py +++ b/pychunkedgraph/graph/meta.py @@ -100,6 +100,11 @@ def ws_cv(self): ... return self._ws_cv + @property + def ws_info(self) -> dict[str, object]: + """The watershed's own ``info``; its mesh keys belong to no table in particular.""" + return self.ws_cv.info # pylint: disable=no-member + @property def resolution(self): return self.ws_cv.resolution # pylint: disable=no-member @@ -233,9 +238,13 @@ def split_bounding_offset(self): ) @property - def dataset_info(self) -> Dict: - info = self.ws_cv.info # pylint: disable=no-member - + def dataset_info(self) -> dict[str, object]: + # Mesh keys come from this table's mesh block alone; the watershed's are not its own. + info = { + key: value + for key, value in self.ws_info.items() + if key not in ("mesh", "mesh_dir", "mesh_metadata") + } info.update( { "chunks_start_at_voxel_offset": True, diff --git a/pychunkedgraph/meshing/mesh_meta/README.md b/pychunkedgraph/meshing/mesh_meta/README.md new file mode 100644 index 000000000..4270e852a --- /dev/null +++ b/pychunkedgraph/meshing/mesh_meta/README.md @@ -0,0 +1,76 @@ +# mesh_meta + +Single, branch-agnostic home for **graphene mesh metadata**. Every value comes +from **`custom_data["mesh"]`, the single source of truth**. `MeshMeta(cg)` wraps a +ChunkedGraph and exposes, as properties, the mesh dir/bucket locations and the +per-dataset mesh params used by the v2 manifest and by remeshing; multi-resolution +(LOD) mesh meta will live here too as it lands, so this is the module to grow +rather than scattering mesh-meta reads across the code. + +## Why it exists + +Supervoxels (watershed) can move to a cheap, egress-waived bucket while meshes +stay put. The v2 graphene manifest therefore carries **absolute mesh bucket +paths** rather than paths composed relative to the watershed `data_dir`, so a +client fetches meshes straight from wherever they live. This module is the one +place that decides where meshes live, and what the mesh params are, for a given +ChunkedGraph. + +## Two mesh locations + +- **initial** — the sharded meshes produced at ingest. **Shared / graph-independent**: + several ChunkedGraphs (e.g. copies) point at the *same* initial meshes, so this + location is never namespaced by graph id. +- **dynamic** — the unsharded meshes produced by proofreading edits. + **Per-graph**: each graph keeps its own, so on the pcgv3 line it defaults to a + graph-id-derived dir (`dynamic_`) and stays isolated even while + sharing initial meshes; on the pcgv2 line it is a plain subdir. + +## Configuration + +All read from `custom_data["mesh"]`: + +- `dir` — the mesh root under the watershed. No default: setup always writes it, and a + table without it has no meshes, so reading it raises `KeyError`. +- `initial_mesh_dir` — the initial location (default `initial`). +- `dynamic_mesh_dir` — the dynamic location (default `dynamic`; pcgv3 setup fills + `dynamic_`). +- `max_layer`, `mip`, `max_error` — mesh params (start layer for manifests, and + the mip / max-error used by remeshing). +- `uniform_draco_grid_size` — the draco grid clients deduplicate on, written by setup. + Deprecated shim: a table whose block lacks it, or `max_meshed_layer` / + `draco_grid_sizes`, gets the watershed info's value in `client_metadata` until its + block is rewritten. Nothing else reads the watershed info for meshes. +- `initial_ts` — the ingest timestamp boundary that splits initial (sharded) node + ids from proofread (dynamic) ones. + +Resolution rule for the two location values: a value containing a cloud scheme +(`gs://`, `s3://`, …) is treated as an **absolute** bucket and used as-is; +otherwise it is joined under `/`. This lets a dataset move +initial and/or dynamic meshes to different buckets without touching anything else. + +Branch-agnostic on purpose: this module reads only `custom_data["mesh"]` and the +watershed path — accessors identical on the pcgv2 and pcgv3 lines — so it +cherry-picks clean between them. How that config gets *populated* (e.g. pcgv3's +setup-time `MeshConfig` from the dataset yaml) is branch-specific and lives +upstream; this module only reads the result. + +## API + +`MeshMeta(cg)` exposes these properties: + +- `initial_path` → absolute dir of the initial (sharded) meshes. +- `dynamic_path` → absolute dir of the dynamic (unsharded) meshes. +- `dir` → the sharded mesh dir name under the watershed. +- `dynamic_mesh_dir` → the dynamic dir as configured, a name or a cloud URL. +- `client_metadata` → the graphene info's `mesh_metadata` for this table. +- `max_layer`, `mip`, `max_error`, `initial_ts` → the mesh params. +- `needs_v2` → true when either location falls **outside** the watershed dir, + i.e. meshes are not co-located with the watershed. Old clients compose paths + relative to the watershed, so they cannot reach such meshes: the v2 manifest + serves them correctly, and the v1 path must fail loudly rather than return + unreachable paths. +- `reader_anchor` → the `(data_dir, mesh)` pair to hand a CloudVolume mesh reader. + The reader appends `initial/` internally, so it must be anchored at the + **parent** of the initial dir; this yields shard byte-ranges from the right + bucket even for a migrated graph. diff --git a/pychunkedgraph/meshing/mesh_meta/__init__.py b/pychunkedgraph/meshing/mesh_meta/__init__.py new file mode 100644 index 000000000..33b6c72fd --- /dev/null +++ b/pychunkedgraph/meshing/mesh_meta/__init__.py @@ -0,0 +1,5 @@ +"""Branch-agnostic graphene mesh metadata. See README.md.""" + +from .core import MeshMeta + +__all__ = ["MeshMeta"] diff --git a/pychunkedgraph/meshing/mesh_meta/core.py b/pychunkedgraph/meshing/mesh_meta/core.py new file mode 100644 index 000000000..daf4d13f6 --- /dev/null +++ b/pychunkedgraph/meshing/mesh_meta/core.py @@ -0,0 +1,107 @@ +"""MeshMeta — mesh dir locations and per-dataset params for a ChunkedGraph. + +``custom_data["mesh"]`` is the single source of truth. See README.md. +""" + +import posixpath + +#: DEPRECATED shim: client mesh keys older setups wrote into the watershed info only. A key +#: the table's mesh block lacks is copied from there at read time; drop this once every +#: table's block carries them. +_WATERSHED_FALLBACK_KEYS = ( + "uniform_draco_grid_size", + "max_meshed_layer", + "draco_grid_sizes", +) + + +def _resolve(root: str, value: str) -> str: + """Absolute ``value`` (a cloud URL) as-is, else joined under ``root``.""" + return value.rstrip("/") if "://" in value else posixpath.join(root, value) + + +class MeshMeta: + """Mesh metadata for a ChunkedGraph, read from ``custom_data["mesh"]``.""" + + def __init__(self, cg): + self._mesh = cg.meta.custom_data.get("mesh", {}) + self._watershed = cg.meta.data_source.WATERSHED + self._meta = cg.meta + + @property + def dir(self) -> str: + """Sharded mesh dir name under the watershed; setup writes it, so a table without + one has no meshes and this raises ``KeyError``.""" + return self._mesh["dir"] + + @property + def _root(self) -> str: + return posixpath.join(self._watershed, self.dir) + + @property + def initial_path(self) -> str: + """Absolute dir of the shared initial (sharded) meshes.""" + return _resolve(self._root, self._mesh.get("initial_mesh_dir", "initial")) + + @property + def dynamic_mesh_dir(self) -> str: + """The dynamic dir as configured: a name under ``dir``, or a cloud URL.""" + return self._mesh.get("dynamic_mesh_dir", "dynamic") + + @property + def dynamic_path(self) -> str: + """Absolute dir of the per-graph dynamic (unsharded) meshes.""" + return _resolve(self._root, self.dynamic_mesh_dir) + + @property + def client_metadata(self) -> dict[str, object]: + """``mesh_metadata`` for a graphene info. cloud-volume reads the dynamic dir as + ``unsharded_mesh_dir``, and a v2 client reads the two absolute paths.""" + ws_mesh = self._meta.ws_info.get("mesh_metadata", {}) + fallback = { + key: ws_mesh[key] + for key in _WATERSHED_FALLBACK_KEYS + if key in ws_mesh and key not in self._mesh + } + own = { + key: self._mesh[key] + for key in _WATERSHED_FALLBACK_KEYS + if key in self._mesh + } + return { + **fallback, + **own, + "unsharded_mesh_dir": self.dynamic_mesh_dir, + "initial_mesh_path": self.initial_path, + "dynamic_mesh_path": self.dynamic_path, + } + + @property + def needs_v2(self) -> bool: + """True when meshes live outside the watershed dir (old clients can't reach).""" + root = self._root + return not ( + self.initial_path.startswith(root) and self.dynamic_path.startswith(root) + ) + + @property + def reader_anchor(self): + """``(data_dir, mesh)`` so a CloudVolume that appends ``initial/`` lands at + ``initial_path`` — points the shard reader at a migrated bucket.""" + return posixpath.split(posixpath.dirname(self.initial_path)) + + @property + def max_layer(self) -> int: + return self._mesh.get("max_layer", 2) + + @property + def mip(self) -> int: + return self._mesh["mip"] + + @property + def max_error(self): + return self._mesh["max_error"] + + @property + def initial_ts(self): + return self._mesh["initial_ts"] diff --git a/pychunkedgraph/meshing/meshgen_utils.py b/pychunkedgraph/meshing/meshgen_utils.py index 711c09322..2c54baa8c 100644 --- a/pychunkedgraph/meshing/meshgen_utils.py +++ b/pychunkedgraph/meshing/meshgen_utils.py @@ -14,6 +14,7 @@ from pychunkedgraph.graph.utils.basetypes import NODE_ID # noqa from ..graph.types import empty_1d +from .mesh_meta import MeshMeta def str_to_slice(slice_str: str): @@ -145,7 +146,10 @@ def get_json_info(cg): dataset_info = cg.meta.dataset_info dummy_app_info = {"app": {"supported_api_versions": [0, 1]}} info = {**dataset_info, **dummy_app_info} - info["mesh"] = cg.meta.custom_data.get("mesh", {}).get("dir", "graphene_meshes") + mm = MeshMeta(cg) + info["mesh"] = mm.dir + info["dynamic_mesh_dir"] = mm.dynamic_mesh_dir + info["mesh_metadata"] = mm.client_metadata info_str = dumps(info) return loads(info_str) diff --git a/pychunkedgraph/pipeline/meshing/setup.py b/pychunkedgraph/pipeline/meshing/setup.py index 8753e9000..83582876a 100644 --- a/pychunkedgraph/pipeline/meshing/setup.py +++ b/pychunkedgraph/pipeline/meshing/setup.py @@ -3,10 +3,10 @@ Writes every mesh-related field a new or freshly-copied graph needs before any mesh fragment can be served: - 1. ``cg.meta.ws_cv.info["mesh"]`` (mesh dir in the watershed cv info.json) - 2. ``cg.meta.ws_cv.mesh.meta.info`` (per-layer sharded mesh spec) - 3. ``cg.meta.ws_cv.info["mesh_metadata"]`` (uniform draco grid + dynamic dir) - 4. ``cg.meta.custom_data["mesh"]`` (CG bigtable meta block) + 1. ``//info`` (per-layer sharded mesh spec) + 2. ``cg.meta.custom_data["mesh"]`` (CG bigtable meta block, draco grid size included) + +The watershed's own info is not written: the CG meta block is the only mesh source. Idempotent: re-running overwrites the same fields with the current inputs, with one exception — ``initial_ts`` is preserved if already @@ -22,10 +22,12 @@ import argparse import logging +import posixpath from datetime import datetime, timezone from os import environ import yaml +from cloudfiles import CloudFiles from ...graph.chunkedgraph import ChunkedGraph from ...meshing.meshgen import get_draco_encoding_settings_for_chunk @@ -62,9 +64,8 @@ def setup_mesh_meta( ) -> dict: """Write every mesh.* metadata field this graph needs to serve meshes. - Writes go to two places: the watershed CloudVolume (steps 1-3, via - ``info.json`` / ``mesh/info`` on GCS) and the CG's bigtable meta - block (step 4). + Writes go to two places: the mesh dir's sharding ``info`` on GCS (step 1) + and the CG's bigtable meta block (step 2). ``initial_ts`` is set once and never overwritten — if the existing bigtable mesh meta already has one, it is reused as-is. Otherwise @@ -84,12 +85,7 @@ def setup_mesh_meta( if existing_ts is not None: logger.info("preserving existing initial_ts=%d", initial_ts) - # 1. watershed CV info — mesh dir. - cg.meta.ws_cv.info["mesh"] = cfg.dir - cg.meta.ws_cv.commit_info() - logger.info("wrote ws_cv.info['mesh']=%r", cfg.dir) - - # 2. sharded mesh spec — same template per layer, layer-specific bits. + # 1. sharded mesh spec — same template per layer, layer-specific bits. layer_shard_spec = { "@type": "neuroglancer_uint64_sharded_v1", "preshift_bits": 0, @@ -111,24 +107,19 @@ def setup_mesh_meta( "chunk_size": [int(x) for x in mesh_chunk_size], "sharding": sharding, } - cg.meta.ws_cv.mesh.meta.info = mesh_spec - cg.meta.ws_cv.mesh.meta.commit_info() + mesh_root = posixpath.join(cg.meta.data_source.WATERSHED, cfg.dir) + CloudFiles(mesh_root).put_json("info", mesh_spec, cache_control="no-cache") logger.info("wrote sharded mesh spec for layers %s", sorted(sharding.keys())) - # 3. uniform draco grid size, derived from layer-2 draco settings. + # uniform draco grid size, derived from layer-2 draco settings. draco = get_draco_encoding_settings_for_chunk( cg, cg.get_chunk_id(layer=2, x=0, y=0, z=0), mip=cfg.mip ) grid_size = draco["quantization_range"] / (2 ** draco["quantization_bits"] - 1) - cg.meta.ws_cv.info["mesh_metadata"] = { - "uniform_draco_grid_size": grid_size, - "unsharded_mesh_dir": "dynamic", - } - cg.meta.ws_cv.commit_info() - logger.info("wrote mesh_metadata uniform_draco_grid_size=%s", grid_size) - # 4. CG-side bigtable meta block. + # 2. CG-side bigtable meta block. mesh_meta = { + "uniform_draco_grid_size": grid_size, "max_layer": int(cfg.max_layer), "dynamic_mesh_dir": cfg.dynamic_mesh_dir, "mip": int(cfg.mip), diff --git a/pychunkedgraph/tests/meshing/test_mesh_meta.py b/pychunkedgraph/tests/meshing/test_mesh_meta.py new file mode 100644 index 000000000..46a76c762 --- /dev/null +++ b/pychunkedgraph/tests/meshing/test_mesh_meta.py @@ -0,0 +1,35 @@ +"""Tests for pychunkedgraph.meshing.mesh_meta.MeshMeta.""" + +import posixpath +from types import SimpleNamespace + +from pychunkedgraph.meshing.mesh_meta import MeshMeta + + +def _cg(watershed, mesh): + meta = SimpleNamespace( + custom_data={"mesh": mesh}, + data_source=SimpleNamespace(WATERSHED=watershed), + ) + return SimpleNamespace(meta=meta) + + +class TestReaderAnchor: + """reader_anchor must recompose to initial_path via cloud-volume's hardcoded + ``initial`` subdir, so the verified shard reader reads the real bucket.""" + + def test_colocated_anchor_is_watershed_dir(self): + mm = MeshMeta(_cg("gs://ws/seg", {"dir": "graphene_meshes"})) + assert mm.reader_anchor == ("gs://ws/seg", "graphene_meshes") + assert posixpath.join(*mm.reader_anchor, "initial") == mm.initial_path + assert mm.needs_v2 is False + + def test_migrated_initial_anchor_recomposes(self): + mesh = { + "dir": "graphene_meshes", + "initial_mesh_dir": "gs://old/graphene_meshes/initial", + } + mm = MeshMeta(_cg("gs://cheap/seg", mesh)) + assert mm.initial_path == "gs://old/graphene_meshes/initial" + assert posixpath.join(*mm.reader_anchor, "initial") == mm.initial_path + assert mm.needs_v2 is True From f5b8d3383cb37a754af09a3cfed2d2cde1dd9d37 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 11 Nov 2026 01:39:04 +0000 Subject: [PATCH 02/11] fix(meshing): read and write meshes in the table's own dirs - Stitching, remeshing and find-path read node meshes through `NodeMeshReader`, from `initial_path` and `dynamic_path`. - The manifest's shard readers resolve `initial_path` through `shard_mesh_source`, a cloud-URL dir included. - `remeshing()` drops `cv_sharded_mesh_dir`; its callers pass `MeshMeta`'s values. Co-Authored-By: Claude --- pychunkedgraph/app/meshing/common.py | 19 ++---- pychunkedgraph/app/meshing/tasks.py | 23 ++----- pychunkedgraph/graph/basetypes.py | 6 ++ pychunkedgraph/meshing/manifest/sharded.py | 7 +- pychunkedgraph/meshing/manifest/utils.py | 76 ++++++++++++++++++---- pychunkedgraph/meshing/mesh_analysis.py | 20 +----- pychunkedgraph/meshing/meshgen.py | 23 ++----- workers/mesh_worker.py | 23 ++++--- 8 files changed, 107 insertions(+), 90 deletions(-) create mode 100644 pychunkedgraph/graph/basetypes.py diff --git a/pychunkedgraph/app/meshing/common.py b/pychunkedgraph/app/meshing/common.py index 8f1a0c20a..4c7731081 100644 --- a/pychunkedgraph/app/meshing/common.py +++ b/pychunkedgraph/app/meshing/common.py @@ -13,6 +13,7 @@ from pychunkedgraph.graph import chunkedgraph from pychunkedgraph.app.meshing import tasks as meshing_tasks from pychunkedgraph.meshing import meshgen +from pychunkedgraph.meshing.mesh_meta import MeshMeta from pychunkedgraph.meshing.manifest import get_highest_child_nodes_with_meshes from pychunkedgraph.meshing.manifest import get_children_before_start_layer from pychunkedgraph.meshing.manifest import ManifestCache @@ -180,22 +181,14 @@ def handle_remesh(table_id): def _remeshing(serialized_cg_info, lvl2_nodes): cg = chunkedgraph.ChunkedGraph(**serialized_cg_info) - cv_mesh_dir = cg.meta.dataset_info["mesh"] - cv_unsharded_mesh_dir = cg.meta.dataset_info["mesh_metadata"]["unsharded_mesh_dir"] - cv_unsharded_mesh_path = os.path.join( - cg.meta.data_source.WATERSHED, cv_mesh_dir, cv_unsharded_mesh_dir - ) - mesh_data = cg.meta.custom_data["mesh"] - - # TODO: stop_layer and mip should be configurable by dataset + mm = MeshMeta(cg) meshgen.remeshing( cg, lvl2_nodes, - stop_layer=mesh_data["max_layer"], - mip=mesh_data["mip"], - max_err=mesh_data["max_error"], - cv_sharded_mesh_dir=cv_mesh_dir, - cv_unsharded_mesh_path=cv_unsharded_mesh_path, + stop_layer=mm.max_layer, + mip=mm.mip, + max_err=mm.max_error, + cv_unsharded_mesh_path=mm.dynamic_path, ) return Response(status=200) diff --git a/pychunkedgraph/app/meshing/tasks.py b/pychunkedgraph/app/meshing/tasks.py index a1f11ca68..5f0a39871 100644 --- a/pychunkedgraph/app/meshing/tasks.py +++ b/pychunkedgraph/app/meshing/tasks.py @@ -1,27 +1,18 @@ from pychunkedgraph.app import app_utils -from pychunkedgraph.meshing import meshgen, meshgen_utils +from pychunkedgraph.meshing import meshgen +from pychunkedgraph.meshing.mesh_meta import MeshMeta import numpy as np -import os def remeshing(table_id, lvl2_nodes): lvl2_nodes = np.array(lvl2_nodes, dtype=np.uint64) cg = app_utils.get_cg(table_id, skip_cache=True) - - cv_mesh_dir = cg.meta.dataset_info["mesh"] - cv_unsharded_mesh_dir = cg.meta.dataset_info["mesh_metadata"]["unsharded_mesh_dir"] - cv_unsharded_mesh_path = os.path.join( - cg.meta.data_source.WATERSHED, cv_mesh_dir, cv_unsharded_mesh_dir - ) - mesh_data = cg.meta.custom_data["mesh"] - - # TODO: stop_layer and mip should be configurable by dataset + mm = MeshMeta(cg) meshgen.remeshing( cg, lvl2_nodes, - stop_layer=mesh_data["max_layer"], - mip=mesh_data["mip"], - max_err=mesh_data["max_error"], - cv_sharded_mesh_dir=cv_mesh_dir, - cv_unsharded_mesh_path=cv_unsharded_mesh_path, + stop_layer=mm.max_layer, + mip=mm.mip, + max_err=mm.max_error, + cv_unsharded_mesh_path=mm.dynamic_path, ) \ No newline at end of file diff --git a/pychunkedgraph/graph/basetypes.py b/pychunkedgraph/graph/basetypes.py new file mode 100644 index 000000000..25195a6c7 --- /dev/null +++ b/pychunkedgraph/graph/basetypes.py @@ -0,0 +1,6 @@ +"""Compat shim: ``basetypes`` lives at ``graph/utils/basetypes.py`` on this line +but at ``graph/basetypes.py`` on the pcgv3 line. Re-export so the shorter import +path resolves identically on both, keeping meshing code branch-agnostic. +""" + +from .utils.basetypes import * # noqa: F401,F403 diff --git a/pychunkedgraph/meshing/manifest/sharded.py b/pychunkedgraph/meshing/manifest/sharded.py index 2576fcb2f..afb41189a 100644 --- a/pychunkedgraph/meshing/manifest/sharded.py +++ b/pychunkedgraph/meshing/manifest/sharded.py @@ -8,8 +8,9 @@ from .utils import get_children_before_start_layer from ...graph import ChunkedGraph from ...graph.types import empty_1d -from ...graph.utils.basetypes import NODE_ID +from ...graph.basetypes import NODE_ID from ...graph.chunks import utils as chunk_utils +from ..mesh_meta import MeshMeta def verified_manifest( @@ -61,7 +62,7 @@ def speculative_manifest( from ..meshgen_utils import get_json_info if start_layer is None: - start_layer = cg.meta.custom_data.get("mesh", {}).get("max_layer", 2) + start_layer = MeshMeta(cg).max_layer start = time() bounding_box = chunk_utils.normalize_bounding_box( @@ -89,7 +90,7 @@ def speculative_manifest( readers = CloudVolume( # pylint: disable=no-member "graphene://https://localhost/segmentation/table/dummy", - mesh_dir=cg.meta.custom_data.get("mesh", {}).get("dir", "graphene_meshes"), + mesh_dir=MeshMeta(cg).dir, info=get_json_info(cg), ).mesh.readers diff --git a/pychunkedgraph/meshing/manifest/utils.py b/pychunkedgraph/meshing/manifest/utils.py index 67e600653..aab723068 100644 --- a/pychunkedgraph/meshing/manifest/utils.py +++ b/pychunkedgraph/meshing/manifest/utils.py @@ -10,13 +10,15 @@ import numpy as np from cloudfiles import CloudFiles from cloudvolume import CloudVolume +from cloudvolume import Mesh from .cache import ManifestCache from ..meshgen_utils import get_mesh_name from ..meshgen_utils import get_json_info +from ..mesh_meta import MeshMeta from ...graph import ChunkedGraph from ...graph.types import empty_1d -from ...graph.utils.basetypes import NODE_ID +from ...graph.basetypes import NODE_ID from ...graph.utils import generic as misc_utils @@ -40,7 +42,7 @@ def _get_children(cg, node_ids: Sequence[np.uint64], children_cache: Dict): if len(node_ids) == 0: return empty_1d.copy() node_ids = np.array(node_ids, dtype=NODE_ID) - mask = np.in1d(node_ids, np.fromiter(children_cache.keys(), dtype=NODE_ID)) + mask = np.isin(node_ids, np.fromiter(children_cache.keys(), dtype=NODE_ID)) children_d = cg.get_children(node_ids[~mask]) children_cache.update(children_d) @@ -105,8 +107,7 @@ def _get_dynamic_meshes(cg, node_ids: Sequence[np.uint64]) -> Tuple[Dict, List]: if len(node_ids) == 0: return result, not_existing - mesh_dir = cg.meta.custom_data.get("mesh", {}).get("dir", "graphene_meshes") - mesh_path = f"{cg.meta.data_source.WATERSHED}/{mesh_dir}/dynamic" + mesh_path = MeshMeta(cg).dynamic_path cf = CloudFiles(mesh_path) manifest_cache = ManifestCache(cg.graph_id, initial=False) @@ -180,7 +181,7 @@ def segregate_node_ids(cg, node_ids): new = created by proofreading edit operations """ - initial_ts = cg.meta.custom_data["mesh"]["initial_ts"] + initial_ts = MeshMeta(cg).initial_ts initial_mesh_dt = np.datetime64(datetime.fromtimestamp(initial_ts)) node_ids_ts = cg.get_node_timestamps(node_ids) initial_mesh_mask = node_ids_ts < initial_mesh_dt @@ -189,16 +190,69 @@ def segregate_node_ids(cg, node_ids): return initial_ids, new_ids +def shard_mesh_source(cg): + """A cloud-volume mesh source whose shard readers read this table's ``initial_path``.""" + # cloud-volume resolves shards at join(info["data_dir"], info["mesh"], "initial"), so + # reader_anchor splits initial_path into that (data_dir, mesh) pair, a migrated bucket too. + info = get_json_info(cg) + data_dir, mesh_dir = MeshMeta(cg).reader_anchor + info["data_dir"] = data_dir + info["mesh"] = mesh_dir + return CloudVolume( # pylint: disable=no-member + "graphene://https://localhost/segmentation/table/dummy", + mesh_dir=mesh_dir, + info=info, + ).mesh + + +class NodeMeshReader: + """Reads node meshes from this table's own mesh dirs, a cloud-URL dir included. + + Built once per task so the shard readers keep their index caches across reads. + """ + + def __init__(self, cg): + self._cg = cg + self._dynamic = CloudFiles(MeshMeta(cg).dynamic_path) + self._source = shard_mesh_source(cg) + + def get(self, node_ids: Sequence[np.uint64]) -> Dict[int, Mesh]: + """Each node's draco mesh; a node with none is absent. + + Split by ``initial_ts`` as the manifest does, so a node is read only from the + store that holds it: new ones as files, initial ones from their shards. + """ + node_ids = np.asarray(node_ids, dtype=NODE_ID) + if node_ids.size == 0: + return {} + initial_ids, new_ids = segregate_node_ids(self._cg, node_ids) + result = {} + names = {get_mesh_name(self._cg, id_): int(id_) for id_ in new_ids} + for res in self._dynamic.get(list(names)): + if res["error"]: + raise res["error"] + if res["content"] is not None: + label = names[res["path"]] + result[label] = Mesh.from_draco(res["content"], segid=label) + meta = self._source.meta + layers = self._cg.get_chunk_layers(initial_ids) + for layer in np.unique(layers): + path = meta.join(meta.mesh_path, meta.sharded_mesh_dir, str(layer)) + found = self._source.readers[int(layer)].get_data( + initial_ids[layers == layer], path=path + ) + for label, binary in found.items(): + if binary is not None: + result[int(label)] = Mesh.from_draco(binary, segid=int(label)) + return result + + def get_mesh_paths( cg, node_ids: Sequence[np.uint64], stop_layer: int = 2, -) -> Dict: - shard_readers = CloudVolume( # pylint: disable=no-member - "graphene://https://localhost/segmentation/table/dummy", - mesh_dir=cg.meta.custom_data.get("mesh", {}).get("dir", "graphene_meshes"), - info=get_json_info(cg), - ).mesh +) -> Dict[np.uint64, object]: + shard_readers = shard_mesh_source(cg) result = {} node_layers = cg.get_chunk_layers(node_ids) diff --git a/pychunkedgraph/meshing/mesh_analysis.py b/pychunkedgraph/meshing/mesh_analysis.py index 97bb28f5b..6f735772c 100644 --- a/pychunkedgraph/meshing/mesh_analysis.py +++ b/pychunkedgraph/meshing/mesh_analysis.py @@ -1,7 +1,5 @@ -from cloudvolume import CloudVolume import numpy as np -import os -from pychunkedgraph.meshing import meshgen, meshgen_utils +from pychunkedgraph.meshing.manifest.utils import NodeMeshReader def compute_centroid_by_range(vertices): @@ -58,21 +56,7 @@ def compute_mesh_centroids_of_l2_ids(cg, l2_ids, flatten=False): :param l2_ids: Sequence[np.uint64] :return: Union[Dict[np.uint64, np.ndarray], [np.uint64], [np.uint64]] """ - cv_sharded_mesh_dir = cg.meta.dataset_info["mesh"] - cv_unsharded_mesh_dir = cg.meta.dataset_info["mesh_metadata"][ - "unsharded_mesh_dir" - ] - cv_unsharded_mesh_path = os.path.join( - cg.meta.data_source.WATERSHED, - cv_sharded_mesh_dir, - cv_unsharded_mesh_dir, - ) - cv = CloudVolume( - f"graphene://https://localhost/segmentation/table/dummy", - mesh_dir=cv_sharded_mesh_dir, - info=meshgen_utils.get_json_info(cg), - ) - meshes = cv.mesh.get_meshes_on_bypass(l2_ids, allow_missing=True) + meshes = NodeMeshReader(cg).get(l2_ids) if flatten: centroids_with_chunk_boundary_points = [] else: diff --git a/pychunkedgraph/meshing/meshgen.py b/pychunkedgraph/meshing/meshgen.py index a8da89b1f..4263d7bce 100644 --- a/pychunkedgraph/meshing/meshgen.py +++ b/pychunkedgraph/meshing/meshgen.py @@ -22,6 +22,7 @@ from pychunkedgraph.graph import attributes # noqa from pychunkedgraph.meshing import meshgen_utils # noqa from pychunkedgraph.meshing.manifest.cache import ManifestCache +from pychunkedgraph.meshing.manifest.utils import NodeMeshReader UTC = pytz.UTC @@ -822,7 +823,6 @@ def _get_timestamp_from_node_ids(cg, node_ids): def remeshing( cg, l2_node_ids: Sequence[np.uint64], - cv_sharded_mesh_dir: str, cv_unsharded_mesh_path: str, stop_layer: int = None, mip: int = 2, @@ -899,7 +899,6 @@ def add_nodes_to_l2_chunk_dict(ids): fragment_batch_size=40, node_id_subset=node_ids, cg=cg, - cv_sharded_mesh_dir=cv_sharded_mesh_dir, cv_unsharded_mesh_path=cv_unsharded_mesh_path, ) @@ -1086,7 +1085,6 @@ def get_multi_child_nodes(cg, chunk_id, node_id_subset=None, chunk_bbox_string=F def chunk_stitch_remeshing_task( cg_name, chunk_id, - cv_sharded_mesh_dir, cv_unsharded_mesh_path, mip=2, lod=0, @@ -1119,11 +1117,7 @@ def chunk_stitch_remeshing_task( print("Nothing to do", cx, cy, cz) return ", ".join(str(x) for x in result) - cv = CloudVolume( - f"graphene://https://localhost/segmentation/table/dummy", - mesh_dir=cv_sharded_mesh_dir, - info=meshgen_utils.get_json_info(cg), - ) + reader = NodeMeshReader(cg) fragments_in_batch_processed = 0 batches_processed = 0 @@ -1135,13 +1129,9 @@ def chunk_stitch_remeshing_task( ] cf = CloudFiles(cv_unsharded_mesh_path) if fragment_batch_size is None: - fragment_map = cv.mesh.get_meshes_on_bypass( - fragment_to_fetch, allow_missing=True - ) + fragment_map = reader.get(fragment_to_fetch) else: - fragment_map = cv.mesh.get_meshes_on_bypass( - fragment_to_fetch[0:fragment_batch_size], allow_missing=True - ) + fragment_map = reader.get(fragment_to_fetch[0:fragment_batch_size]) i = 0 fragments_d = {} for new_fragment_id, fragment_ids_to_fetch in multi_child_nodes.items(): @@ -1158,12 +1148,11 @@ def chunk_stitch_remeshing_task( fragments_in_batch_processed = 1 batches_processed += 1 num_fragments_processed = batches_processed * fragment_batch_size - fragment_map = cv.mesh.get_meshes_on_bypass( + fragment_map = reader.get( fragment_to_fetch[ num_fragments_processed : num_fragments_processed + fragment_batch_size - ], - allow_missing=True, + ] ) if fragment_id in fragment_map: old_frag = fragment_map[fragment_id] diff --git a/workers/mesh_worker.py b/workers/mesh_worker.py index b8f1e0024..422bf0bd7 100644 --- a/workers/mesh_worker.py +++ b/workers/mesh_worker.py @@ -3,15 +3,16 @@ import gc import pickle import logging -from os import path from os import getenv import numpy as np +from cloudfiles import CloudFiles from messagingclient import MessagingClient from pychunkedgraph.graph import ChunkedGraph from pychunkedgraph.graph.utils import basetypes from pychunkedgraph.meshing import meshgen +from pychunkedgraph.meshing.mesh_meta import MeshMeta PCG_CACHE = {} @@ -41,20 +42,19 @@ def callback(payload): ) try: - mesh_meta = cg.meta.custom_data["mesh"] - mesh_dir = mesh_meta["dir"] - layer = mesh_meta["max_layer"] - mip = mesh_meta["mip"] - err = mesh_meta["max_error"] - cv_unsharded_mesh_dir = mesh_meta.get("dynamic_mesh_dir", "dynamic") + mm = MeshMeta(cg) + layer = mm.max_layer + mip = mm.mip + err = mm.max_error + mesh_dir = mm.dir + mesh_path = mm.dynamic_path except KeyError: logging.warning(f"No metadata found for {cg.graph_id}; ignoring...") return - mesh_path = path.join( - cg.meta.data_source.WATERSHED, mesh_dir, cv_unsharded_mesh_dir - ) - + if not CloudFiles(cg.meta.data_source.WATERSHED).exists(f"{mesh_dir}/info"): + logging.warning(f"No meshes at {mesh_dir} for {cg.graph_id}; ignoring...") + return logging.log(INFO_HIGH, f"remeshing {l2ids}; graph {table_id} operation {op_id}.") meshgen.remeshing( @@ -63,7 +63,6 @@ def callback(payload): stop_layer=layer, mip=mip, max_err=err, - cv_sharded_mesh_dir=mesh_dir, cv_unsharded_mesh_path=mesh_path, ) logging.log(INFO_HIGH, f"remeshing complete; graph {table_id} operation {op_id}.") From 91bcd917c60f3e3066640f20451e5dd4263b56f2 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 11 Nov 2026 01:41:39 +0000 Subject: [PATCH 03/11] feat(meshing): negotiate a v2 manifest through the Accept header - `Accept: application/x.cave;manifest_version=2` gets fragments grouped by absolute bucket, with one seg id per row. - A v1 request for a table that `needs_v2` gets `406`, naming the v2 header; responses carry `Vary: Accept` and `X-Manifest-Version`. - Manifest flags merge the query string and the body through `_flag`. Co-Authored-By: Claude --- pychunkedgraph/app/common.py | 2 +- pychunkedgraph/app/meshing/common.py | 64 ++++++++++------ pychunkedgraph/graph/exceptions.py | 5 ++ .../meshing/manifest/sharded_format.md | 21 +++++- pychunkedgraph/meshing/manifest/v2.py | 73 +++++++++++++++++++ .../tests/meshing/test_manifest_endpoint.py | 42 +++++++++++ .../tests/meshing/test_manifest_v2.py | 64 ++++++++++++++++ 7 files changed, 248 insertions(+), 23 deletions(-) create mode 100644 pychunkedgraph/meshing/manifest/v2.py create mode 100644 pychunkedgraph/tests/meshing/test_manifest_endpoint.py create mode 100644 pychunkedgraph/tests/meshing/test_manifest_v2.py diff --git a/pychunkedgraph/app/common.py b/pychunkedgraph/app/common.py index 802a600dc..9b602c0f1 100644 --- a/pychunkedgraph/app/common.py +++ b/pychunkedgraph/app/common.py @@ -84,7 +84,7 @@ def after_request(response): # for 9% fewer bytes. response.data = compression.gzip_compress(response.data, compresslevel=1) response.headers["Content-Encoding"] = "gzip" - response.headers["Vary"] = "Accept-Encoding" + response.vary.add("Accept-Encoding") response.headers["Content-Length"] = len(response.data) return response diff --git a/pychunkedgraph/app/meshing/common.py b/pychunkedgraph/app/meshing/common.py index 4c7731081..d353541f7 100644 --- a/pychunkedgraph/app/meshing/common.py +++ b/pychunkedgraph/app/meshing/common.py @@ -11,9 +11,11 @@ from pychunkedgraph import __version__ from pychunkedgraph.app import app_utils from pychunkedgraph.graph import chunkedgraph +from pychunkedgraph.graph import exceptions as cg_exceptions from pychunkedgraph.app.meshing import tasks as meshing_tasks from pychunkedgraph.meshing import meshgen from pychunkedgraph.meshing.mesh_meta import MeshMeta +from pychunkedgraph.meshing.manifest import v2 from pychunkedgraph.meshing.manifest import get_highest_child_nodes_with_meshes from pychunkedgraph.meshing.manifest import get_children_before_start_layer from pychunkedgraph.meshing.manifest import ManifestCache @@ -55,6 +57,11 @@ def handle_valid_frags(table_id, node_id): ## MANIFEST -------------------------------------------------------------------- +def _flag(name: str, data: dict[str, object]) -> bool: + """A manifest request flag, from the query string or the body, false when absent.""" + return app_utils.toboolean(request.args.get(name) or data.get(name) or "false") + + def handle_get_manifest(table_id, node_id): current_app.request_type = "manifest" current_app.table_id = table_id @@ -69,13 +76,18 @@ def handle_get_manifest(table_id, node_id): bounding_box = np.array([b.split("-") for b in bounds.split("_")], dtype=int).T cg = app_utils.get_cg(table_id) - verify = request.args.get("verify", False) - verify = verify in ["True", "true", "1", True] - return_seg_ids = request.args.get("return_seg_ids", False) - prepend_seg_ids = request.args.get("prepend_seg_ids", False) - return_seg_ids = return_seg_ids in ["True", "true", "1", True] - prepend_seg_ids = prepend_seg_ids in ["True", "true", "1", True] - start_layer = cg.meta.custom_data.get("mesh", {}).get("max_layer", 2) + mm = MeshMeta(cg) + manifest_version = v2.served_manifest_version(request.headers.get("Accept")) + if manifest_version < 2 and mm.needs_v2: + raise cg_exceptions.NotAcceptable( + "This dataset serves meshes from an absolute path; upgrade your " + "client to one that requests " + "'Accept: application/x.cave;manifest_version=2'." + ) + verify = _flag("verify", data) + return_seg_ids = _flag("return_seg_ids", data) + prepend_seg_ids = _flag("prepend_seg_ids", data) + start_layer = mm.max_layer start_layer = int(request.args.get("start_layer", start_layer)) if "start_layer" in data: start_layer = int(data["start_layer"]) @@ -92,8 +104,12 @@ def handle_get_manifest(table_id, node_id): flexible_start_layer, bounding_box, data, + manifest_version, ) - return manifest_response(cg, args) + response = make_response(jsonify(manifest_response(cg, args))) + response.headers["X-Manifest-Version"] = str(manifest_version) + response.headers["Vary"] = "Accept" + return response def manifest_response(cg, args): @@ -108,34 +124,40 @@ def manifest_response(cg, args): flexible_start_layer, bounding_box, data, + manifest_version, ) = args - resp = {} - seg_ids = [] if not verify: - seg_ids, resp["fragments"] = speculative_manifest_sharded( + seg_ids, fragments = speculative_manifest_sharded( cg, node_id, start_layer=start_layer, bounding_box=bounding_box ) - else: - seg_ids, resp["fragments"] = get_highest_child_nodes_with_meshes( + seg_ids, fragments = get_highest_child_nodes_with_meshes( cg, np.uint64(node_id), start_layer=start_layer, bounding_box=bounding_box, ) - if prepend_seg_ids: - resp["fragments"] = [f"~{i}:{f}" for i, f in zip(seg_ids, resp["fragments"])] - if return_seg_ids: - resp["seg_ids"] = seg_ids + + if manifest_version >= 2: + # Seg ids travel on the fragments and nowhere else: a top level list cannot be lined up + # with fragments split across buckets, and duplicates what the prefix already carries. + # Every row carries its seg id, so neither seg id flag changes a v2 response. + mm = MeshMeta(cg) + initial, dynamic = v2.to_v2_groups(seg_ids, fragments, verified=verify) + resp = v2.assemble(mm.initial_path, mm.dynamic_path, initial, dynamic) + else: + resp = {"fragments": fragments} + if prepend_seg_ids: + resp["fragments"] = [f"~{i}:{f}" for i, f in zip(seg_ids, fragments)] + if return_seg_ids: + resp["seg_ids"] = seg_ids return _check_post_options(cg, resp, data, seg_ids) def _check_post_options(cg, resp, data, seg_ids): - if app_utils.toboolean(data.get("return_seg_ids", "false")): - resp["seg_ids"] = seg_ids - if app_utils.toboolean(data.get("return_seg_id_layers", "false")): + if _flag("return_seg_id_layers", data): resp["seg_id_layers"] = cg.get_chunk_layers(seg_ids) - if app_utils.toboolean(data.get("return_seg_chunk_coordinates", "false")): + if _flag("return_seg_chunk_coordinates", data): resp["seg_chunk_coordinates"] = [ cg.get_chunk_coordinates(seg_id) for seg_id in seg_ids ] diff --git a/pychunkedgraph/graph/exceptions.py b/pychunkedgraph/graph/exceptions.py index 45aa57fc7..5ca56d8a2 100644 --- a/pychunkedgraph/graph/exceptions.py +++ b/pychunkedgraph/graph/exceptions.py @@ -64,6 +64,11 @@ class Forbidden(ClientError): status_code = http_client.FORBIDDEN +class NotAcceptable(ClientError): + """Exception mapping a ``406 Not Acceptable`` response.""" + status_code = http_client.NOT_ACCEPTABLE + + class Conflict(ClientError): """Exception mapping a ``409 Conflict`` response.""" status_code = http_client.CONFLICT diff --git a/pychunkedgraph/meshing/manifest/sharded_format.md b/pychunkedgraph/meshing/manifest/sharded_format.md index 828c84cc2..c86b4a452 100644 --- a/pychunkedgraph/meshing/manifest/sharded_format.md +++ b/pychunkedgraph/meshing/manifest/sharded_format.md @@ -26,4 +26,23 @@ There can be two types of mesh fragments in a manifest: `initial` and `dynamic`. For segment IDs generated by edit operations during proofreading, legacy format is used to name mesh fragments. -For all formats, `prepend_seg_ids=true` query parameter can be used to add `~{segment_id}:` as prefix to fragment ID in the manifest. This can be used in neuroglancer to map segment ID to mesh fragment in cache, this helps avoid redownloading unaffected fragments after an edit operation. +In a v1 manifest, for all formats, `prepend_seg_ids=true` query parameter can be used to add `~{segment_id}:` as prefix to fragment ID in the manifest. This can be used in neuroglancer to map segment ID to mesh fragment in cache, this helps avoid redownloading unaffected fragments after an edit operation. + +In a v2 manifest, requested with `Accept: application/x.cave;manifest_version=2`, every fragment opens with its segment ID exactly once, so neither `return_seg_ids` nor `prepend_seg_ids` changes it. A v2 manifest carries no top level `seg_ids` list: fragments are grouped by bucket, so a flat list cannot be lined up with them, and each fragment already names its segment. + +``` +{ + "manifest_version": 2, + "fragments": { + "gs://bucket/graphene_meshes/initial": [":/.shard::"], + "gs://bucket/graphene_meshes/dynamic": [":0:"] + } +} +``` + +Each bucket maps straight to its fragment list, and a group with no fragments is omitted. The bucket says which kind a fragment is, so v2 rows carry no `~`. Initial fragments are spelled: + +* With verification, `{segment_id}:{layer}/{shard_file}:{offset}:{size}`, the v1 fragment with its segment ID in front. +* Without verification, `{segment_id}:{layer}:{chunk_id}:{shard_name}:{minishard_number}`, the v1 fragment with `.shard` left off its shard file name, so only a fragment carrying its byte range names a `.shard` file. + + eg: `173395595644372020:2:173395595644370944:425884686-0:1` diff --git a/pychunkedgraph/meshing/manifest/v2.py b/pychunkedgraph/meshing/manifest/v2.py new file mode 100644 index 000000000..effaa178b --- /dev/null +++ b/pychunkedgraph/meshing/manifest/v2.py @@ -0,0 +1,73 @@ +"""v2 graphene manifest: Accept-header negotiation + format assembly. + +Branch-agnostic, pure-stdlib. The v2 format keys ``fragments`` by absolute mesh +bucket path so mesh location travels in the manifest itself; a client advertises +support via ``Accept: application/x.cave;manifest_version=2``. +""" + +ACCEPT_MEDIA_TYPE = "application/x.cave" +MANIFEST_VERSION = 2 # highest manifest version this server produces + + +def requested_manifest_version(accept_header, default: int = 1) -> int: + """Manifest version the client advertised via + ``Accept: application/x.cave;manifest_version=N``. + + Parsed with stdlib — werkzeug's ``MIMEAccept`` mangles media-type params. + """ + if not accept_header: + return default + for part in accept_header.split(","): + params = [p.strip() for p in part.split(";")] + if params[0].lower() != ACCEPT_MEDIA_TYPE: + continue + for param in params[1:]: + key, _, value = param.partition("=") + if key.strip().lower() == "manifest_version": + try: + return int(value.strip()) + except ValueError: + return default + return default + + +def served_manifest_version(accept_header) -> int: + """Manifest version a request with this ``Accept`` is answered in, one of the two + this server builds: ``MANIFEST_VERSION`` when it asks for that or newer, else v1.""" + asked = requested_manifest_version(accept_header) + return MANIFEST_VERSION if asked >= MANIFEST_VERSION else 1 + + +def to_v2_groups(node_ids, fragments, *, verified): + """Group v1 fragments into ``(initial, dynamic)``, every row opening with its one segid. + + A verified row gains the segid its v1 form lacks. A speculative row already opens with it + and drops its file name's constant ``.shard``: a row names a shard only with its byte range. + """ + initial, dynamic = [], [] + for node_id, frag in zip(node_ids, fragments): + if not frag.startswith("~"): + dynamic.append(frag) + elif verified: + initial.append(f"{node_id}:{frag[1:]}") + else: + segid, layer, chunk_id, fname, minishard = frag[1:].split(":") + stem = fname.removesuffix(".shard") + initial.append(f"{segid}:{layer}:{chunk_id}:{stem}:{minishard}") + return initial, dynamic + + +def assemble( + initial_path: str, dynamic_path: str, initial_frags, dynamic_frags +) -> dict[str, object]: + """v2 manifest: fragment lists grouped by absolute bucket path. + + Empty groups are omitted. Metadata is added beside ``fragments`` at the top + level, so a bucket maps straight to its list. + """ + fragments: dict[str, list[str]] = {} + if len(initial_frags): + fragments[initial_path] = list(initial_frags) + if len(dynamic_frags): + fragments[dynamic_path] = list(dynamic_frags) + return {"manifest_version": MANIFEST_VERSION, "fragments": fragments} diff --git a/pychunkedgraph/tests/meshing/test_manifest_endpoint.py b/pychunkedgraph/tests/meshing/test_manifest_endpoint.py new file mode 100644 index 000000000..389973cdf --- /dev/null +++ b/pychunkedgraph/tests/meshing/test_manifest_endpoint.py @@ -0,0 +1,42 @@ +"""Manifest endpoint tests: pychunkedgraph.app.meshing.common.handle_get_manifest.""" + +from types import SimpleNamespace + +import flask +import pytest + +from pychunkedgraph.app import app_utils +from pychunkedgraph.app.meshing import common +from pychunkedgraph.meshing import manifest +from pychunkedgraph.meshing.manifest.v2 import MANIFEST_VERSION + +#: A graph whose meshes lie under its watershed, so either version may serve it. +GRAPH = SimpleNamespace( + meta=SimpleNamespace( + custom_data={"mesh": {"dir": "graphene_meshes"}}, + data_source=SimpleNamespace(WATERSHED="gs://bucket/ws"), + ) +) + + +@pytest.fixture +def get_manifest(monkeypatch): + """The endpoint's response to one ``Accept``, its graph load and shard reads + stubbed: the I/O boundaries, so negotiation, assembly and headers run for real.""" + monkeypatch.setattr(app_utils, "get_cg", lambda table_id: GRAPH) + monkeypatch.setattr( + manifest, "speculative_manifest_sharded", lambda cg, node_id, **kw: ([], []) + ) + + def respond(accept: str): + with flask.Flask(__name__).test_request_context(headers={"Accept": accept}): + return common.handle_get_manifest("g", "1") + + return respond + + +def test_a_request_past_the_newest_is_told_the_newest(get_manifest): + newest = MANIFEST_VERSION + response = get_manifest(f"application/x.cave;manifest_version={newest + 1}") + told = (response.headers["X-Manifest-Version"], response.json["manifest_version"]) + assert told == (str(newest), newest) diff --git a/pychunkedgraph/tests/meshing/test_manifest_v2.py b/pychunkedgraph/tests/meshing/test_manifest_v2.py new file mode 100644 index 000000000..3f048540e --- /dev/null +++ b/pychunkedgraph/tests/meshing/test_manifest_v2.py @@ -0,0 +1,64 @@ +"""Tests for pychunkedgraph.meshing.manifest.v2.""" + +import pytest + +from pychunkedgraph.meshing.manifest.v2 import ( + MANIFEST_VERSION, + assemble, + served_manifest_version, + to_v2_groups, +) + +ASK = "application/x.cave;manifest_version={}" + + +class TestServedManifestVersion: + @pytest.mark.parametrize( + "accept, served", + [ + (None, 1), + ("application/json", 1), + (ASK.format("x"), 1), + (ASK.format(0), 1), + (ASK.format(1), 1), + (ASK.format(MANIFEST_VERSION), MANIFEST_VERSION), + (ASK.format(MANIFEST_VERSION + 1), MANIFEST_VERSION), + (f"application/json, {ASK.format(MANIFEST_VERSION)}", MANIFEST_VERSION), + ], + ) + def test_an_ask_for_the_newest_or_past_it_gets_the_newest_and_any_other_v1( + self, accept, served + ): + """No ask, an unparseable one or one below the newest gets v1.""" + assert served_manifest_version(accept) == served + + +class TestToV2Groups: + def test_a_verified_row_gains_its_seg_id(self): + """A verified v1 row names no segment, so v2 puts its seg id in front; a dynamic + fragment already opens with its own and passes through.""" + frags = ["~5/774017-0.shard:74809813:4532", "529:0:90112-98304"] + ini, dyn = to_v2_groups([386, 529], frags, verified=True) + assert ini == ["386:5/774017-0.shard:74809813:4532"] + assert dyn == ["529:0:90112-98304"] + + def test_a_speculative_row_keeps_one_seg_id_and_drops_the_shard_extension(self): + """Only a row carrying its byte range names a ``.shard`` file.""" + segid = 458522737061959004 + frags = [f"~{segid}:6:458522737061658624:95232-0.shard:85", "529:0:90112-98304"] + ini, dyn = to_v2_groups([segid, 529], frags, verified=False) + assert ini == [f"{segid}:6:458522737061658624:95232-0:85"] + assert dyn == ["529:0:90112-98304"] + + def test_assemble_maps_each_bucket_to_its_list(self): + """A bucket maps straight to its fragments; metadata sits at the top level.""" + resp = assemble( + "gs://b/initial", "gs://b/dynamic", ["386:a.shard:1:2"], ["529:0:y"] + ) + assert resp["fragments"]["gs://b/initial"] == ["386:a.shard:1:2"] + assert resp["fragments"]["gs://b/dynamic"] == ["529:0:y"] + assert resp["manifest_version"] == 2 + + def test_assemble_omits_a_group_with_no_fragments(self): + resp = assemble("gs://b/initial", "gs://b/dynamic", [], ["529:0:y"]) + assert list(resp["fragments"]) == ["gs://b/dynamic"] From e529620396b968cefe16e37c62f451021a62b343 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 11 Nov 2026 01:44:03 +0000 Subject: [PATCH 04/11] feat(meshing): expire manifest cache entries after 3 days - Every cached fragment and absence expires after `MANIFEST_TTL_SECONDS`, 3 days. - `ManifestCache.clear_namespace` deletes a graph's keys by SCAN. Co-Authored-By: Claude --- pychunkedgraph/meshing/manifest/cache.py | 43 +++++++++++++++++++++--- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/pychunkedgraph/meshing/manifest/cache.py b/pychunkedgraph/meshing/manifest/cache.py index f38a830c2..0decc3a65 100644 --- a/pychunkedgraph/meshing/manifest/cache.py +++ b/pychunkedgraph/meshing/manifest/cache.py @@ -12,6 +12,8 @@ DOES_NOT_EXIST = "X" INITIAL_PATH_PREFIX = "initial_path_prefix" +MANIFEST_TTL_SECONDS = 3 * 24 * 3600 + REDIS_HOST = os.environ.get("MANIFEST_CACHE_REDIS_HOST", "localhost") REDIS_PORT = os.environ.get("MANIFEST_CACHE_REDIS_PORT", "6379") REDIS_PASSWORD = os.environ.get("MANIFEST_CACHE_REDIS_PASSWORD", "") @@ -74,6 +76,27 @@ def clear_fragments(self, node_ids) -> None: keys = [f"{self.namespace}:{n}" for n in node_ids] REDIS.delete(*keys) + def clear_namespace(self, batch_size: int = 1000) -> int: + """Delete every key under this graph_id's namespace. + + SCAN-based pattern delete (non-blocking on the redis side). + Returns the number of keys deleted. + """ + if REDIS is None: + return 0 + + pattern = f"{self.namespace}:*" + deleted = 0 + batch = [] + for key in REDIS.scan_iter(match=pattern, count=batch_size): + batch.append(key) + if len(batch) >= batch_size: + deleted += REDIS.delete(*batch) + batch.clear() + if batch: + deleted += REDIS.delete(*batch) + return deleted + def _get_cached_initial_fragments(self, node_ids: List[np.uint64]): if REDIS is None: return {}, node_ids, [] @@ -140,10 +163,16 @@ def _set_cached_initial_fragments( for node_id, fragment_info in fragments_d.items(): path, offset, size = fragment_info key = f"{self.namespace}:{node_id}" - pipeline.set(key, f"{path[prefix_idx:]}:{offset}:{size}") + pipeline.set( + key, f"{path[prefix_idx:]}:{offset}:{size}", ex=MANIFEST_TTL_SECONDS + ) for node_id in not_existing: - pipeline.set(f"{self.namespace}:{node_id}", DOES_NOT_EXIST) + pipeline.set( + f"{self.namespace}:{node_id}", + DOES_NOT_EXIST, + ex=MANIFEST_TTL_SECONDS, + ) pipeline.execute() @@ -155,9 +184,15 @@ def _set_cached_dynamic_fragments( pipeline = REDIS.pipeline() for node_id, fragment in fragments_d.items(): - pipeline.set(f"{self.namespace}:{node_id}", fragment) + pipeline.set( + f"{self.namespace}:{node_id}", fragment, ex=MANIFEST_TTL_SECONDS + ) for node_id in not_existing: - pipeline.set(f"{self.namespace}:{node_id}", DOES_NOT_EXIST) + pipeline.set( + f"{self.namespace}:{node_id}", + DOES_NOT_EXIST, + ex=MANIFEST_TTL_SECONDS, + ) pipeline.execute() From 94d92f40a1c6f88d7ebefb6afb5bb2a04f112603 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 11 Nov 2026 02:30:47 +0000 Subject: [PATCH 05/11] fix(meshing): read the shard spec beside the initial meshes - `MeshMeta.spec_dir` names the spec's dir, the parent of `initial_path`; `reader_anchor` derives from it. - `verify=0` builds its shard readers through `shard_mesh_source`. - The remesh worker looks for the spec in `spec_dir`, so a table whose watershed lives elsewhere still remeshes. Co-Authored-By: Claude --- pychunkedgraph/meshing/manifest/sharded.py | 9 ++------- pychunkedgraph/meshing/mesh_meta/core.py | 8 +++++++- pychunkedgraph/tests/meshing/test_mesh_meta.py | 13 +++++++++++++ workers/mesh_worker.py | 7 +++---- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/pychunkedgraph/meshing/manifest/sharded.py b/pychunkedgraph/meshing/manifest/sharded.py index afb41189a..56519100f 100644 --- a/pychunkedgraph/meshing/manifest/sharded.py +++ b/pychunkedgraph/meshing/manifest/sharded.py @@ -3,9 +3,9 @@ from time import time import numpy as np -from cloudvolume import CloudVolume from .utils import get_children_before_start_layer +from .utils import shard_mesh_source from ...graph import ChunkedGraph from ...graph.types import empty_1d from ...graph.basetypes import NODE_ID @@ -59,7 +59,6 @@ def speculative_manifest( from .utils import check_skips from .utils import segregate_node_ids from ..meshgen_utils import get_mesh_name - from ..meshgen_utils import get_json_info if start_layer is None: start_layer = MeshMeta(cg).max_layer @@ -88,11 +87,7 @@ def speculative_manifest( result.append(node_ids[node_layers == stop_layer]) print("chilren IDs", len(result), time() - start) - readers = CloudVolume( # pylint: disable=no-member - "graphene://https://localhost/segmentation/table/dummy", - mesh_dir=MeshMeta(cg).dir, - info=get_json_info(cg), - ).mesh.readers + readers = shard_mesh_source(cg).readers node_ids = np.concatenate(result) initial_ids, new_ids = segregate_node_ids(cg, node_ids) diff --git a/pychunkedgraph/meshing/mesh_meta/core.py b/pychunkedgraph/meshing/mesh_meta/core.py index daf4d13f6..ef501cec1 100644 --- a/pychunkedgraph/meshing/mesh_meta/core.py +++ b/pychunkedgraph/meshing/mesh_meta/core.py @@ -84,11 +84,17 @@ def needs_v2(self) -> bool: self.initial_path.startswith(root) and self.dynamic_path.startswith(root) ) + @property + def spec_dir(self) -> str: + """Dir of the shard spec ``info``: the parent of ``initial_path``, wherever that + lives, so a watershed elsewhere never hides it.""" + return posixpath.dirname(self.initial_path) + @property def reader_anchor(self): """``(data_dir, mesh)`` so a CloudVolume that appends ``initial/`` lands at ``initial_path`` — points the shard reader at a migrated bucket.""" - return posixpath.split(posixpath.dirname(self.initial_path)) + return posixpath.split(self.spec_dir) @property def max_layer(self) -> int: diff --git a/pychunkedgraph/tests/meshing/test_mesh_meta.py b/pychunkedgraph/tests/meshing/test_mesh_meta.py index 46a76c762..f0c7e422b 100644 --- a/pychunkedgraph/tests/meshing/test_mesh_meta.py +++ b/pychunkedgraph/tests/meshing/test_mesh_meta.py @@ -33,3 +33,16 @@ def test_migrated_initial_anchor_recomposes(self): assert mm.initial_path == "gs://old/graphene_meshes/initial" assert posixpath.join(*mm.reader_anchor, "initial") == mm.initial_path assert mm.needs_v2 is True + + +class TestSpecDir: + """The shard spec is read beside the initial meshes, which a watershed elsewhere + does not hold.""" + + def test_watershed_elsewhere_keeps_spec_beside_initial(self): + mesh = { + "dir": "graphene_meshes", + "initial_mesh_dir": "gs://old/graphene_meshes/initial", + } + mm = MeshMeta(_cg("gs://cheap/seg", mesh)) + assert mm.spec_dir == "gs://old/graphene_meshes" diff --git a/workers/mesh_worker.py b/workers/mesh_worker.py index 422bf0bd7..b2b484ec5 100644 --- a/workers/mesh_worker.py +++ b/workers/mesh_worker.py @@ -14,7 +14,6 @@ from pychunkedgraph.meshing import meshgen from pychunkedgraph.meshing.mesh_meta import MeshMeta - PCG_CACHE = {} @@ -46,14 +45,14 @@ def callback(payload): layer = mm.max_layer mip = mm.mip err = mm.max_error - mesh_dir = mm.dir + spec_dir = mm.spec_dir mesh_path = mm.dynamic_path except KeyError: logging.warning(f"No metadata found for {cg.graph_id}; ignoring...") return - if not CloudFiles(cg.meta.data_source.WATERSHED).exists(f"{mesh_dir}/info"): - logging.warning(f"No meshes at {mesh_dir} for {cg.graph_id}; ignoring...") + if not CloudFiles(spec_dir).exists("info"): + logging.warning(f"No meshes at {spec_dir} for {cg.graph_id}; ignoring...") return logging.log(INFO_HIGH, f"remeshing {l2ids}; graph {table_id} operation {op_id}.") From 15ed474131022f05645db4f46d2514ff76c3d024 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 11 Nov 2026 03:05:30 +0000 Subject: [PATCH 06/11] fix(meshing): keep mesh block keys a setup re-run cannot set - `setup_mesh_meta` merges its seven keys over the existing block, so `initial_mesh_dir` and other keys survive a re-run. - The shard spec is written in `MeshMeta.spec_dir`, beside the initial meshes, never under a watershed that holds none. Co-Authored-By: Claude --- pychunkedgraph/meshing/mesh_meta/__init__.py | 4 +- pychunkedgraph/meshing/mesh_meta/core.py | 7 +- pychunkedgraph/pipeline/meshing/setup.py | 61 +++++++------ pychunkedgraph/tests/meshing/test_setup.py | 91 ++++++++++++++++++++ 4 files changed, 135 insertions(+), 28 deletions(-) create mode 100644 pychunkedgraph/tests/meshing/test_setup.py diff --git a/pychunkedgraph/meshing/mesh_meta/__init__.py b/pychunkedgraph/meshing/mesh_meta/__init__.py index 33b6c72fd..4d777312a 100644 --- a/pychunkedgraph/meshing/mesh_meta/__init__.py +++ b/pychunkedgraph/meshing/mesh_meta/__init__.py @@ -1,5 +1,5 @@ """Branch-agnostic graphene mesh metadata. See README.md.""" -from .core import MeshMeta +from .core import MeshMeta, is_absolute -__all__ = ["MeshMeta"] +__all__ = ["MeshMeta", "is_absolute"] diff --git a/pychunkedgraph/meshing/mesh_meta/core.py b/pychunkedgraph/meshing/mesh_meta/core.py index ef501cec1..03f391dc8 100644 --- a/pychunkedgraph/meshing/mesh_meta/core.py +++ b/pychunkedgraph/meshing/mesh_meta/core.py @@ -15,9 +15,14 @@ ) +def is_absolute(value: str) -> bool: + """Whether mesh dir is cloud URL used as-is, rather than name under root.""" + return "://" in value + + def _resolve(root: str, value: str) -> str: """Absolute ``value`` (a cloud URL) as-is, else joined under ``root``.""" - return value.rstrip("/") if "://" in value else posixpath.join(root, value) + return value.rstrip("/") if is_absolute(value) else posixpath.join(root, value) class MeshMeta: diff --git a/pychunkedgraph/pipeline/meshing/setup.py b/pychunkedgraph/pipeline/meshing/setup.py index 83582876a..5dee92f7b 100644 --- a/pychunkedgraph/pipeline/meshing/setup.py +++ b/pychunkedgraph/pipeline/meshing/setup.py @@ -3,15 +3,15 @@ Writes every mesh-related field a new or freshly-copied graph needs before any mesh fragment can be served: - 1. ``//info`` (per-layer sharded mesh spec) + 1. the shard spec ``info`` in ``MeshMeta.spec_dir`` (per-layer sharded mesh spec) 2. ``cg.meta.custom_data["mesh"]`` (CG bigtable meta block, draco grid size included) The watershed's own info is not written: the CG meta block is the only mesh source. -Idempotent: re-running overwrites the same fields with the current -inputs, with one exception — ``initial_ts`` is preserved if already -set, because changing it after the fact would reclassify every node -id and silently break served manifests. +Idempotent: re-running overwrites the fields the config sets and keeps the rest of +the block, so ``initial_mesh_dir`` and a pinned mesh path survive, and ``initial_ts`` is +never reset, since changing it would reclassify every node id and silently break served +manifests. Also the container entrypoint, run once per graph after root-layer ingest: @@ -22,7 +22,6 @@ import argparse import logging -import posixpath from datetime import datetime, timezone from os import environ @@ -32,6 +31,7 @@ from ...graph.chunkedgraph import ChunkedGraph from ...meshing.meshgen import get_draco_encoding_settings_for_chunk from ...meshing.meshgen_utils import get_mesh_block_shape_for_mip +from ...meshing.mesh_meta import MeshMeta, is_absolute from .. import run_and_exit from .meta import MeshConfig @@ -58,6 +58,32 @@ def derive_initial_ts(cg: ChunkedGraph) -> int: return int(earliest.timestamp()) + 1 +def _mesh_block( + cg: ChunkedGraph, cfg: MeshConfig, grid_size: float +) -> dict[str, object]: + """The config's keys over the table's existing block, keeping what a re-run must not + change: keys the config cannot set, such as ``initial_mesh_dir``, ``initial_ts`` once + set, and a pinned mesh path the config's relative dynamic dir would move.""" + existing = cg.meta.custom_data.get("mesh", {}) + initial_ts = existing.get("initial_ts") + if initial_ts is not None: + logger.info("preserving existing initial_ts=%d", int(initial_ts)) + pinned = existing.get("dynamic_mesh_dir", "") + keep = is_absolute(pinned) and not is_absolute(cfg.dynamic_mesh_dir) + return { + **existing, + "uniform_draco_grid_size": grid_size, + "max_layer": int(cfg.max_layer), + "dynamic_mesh_dir": pinned if keep else cfg.dynamic_mesh_dir, + "mip": int(cfg.mip), + "max_error": int(cfg.max_error), + "dir": cfg.dir, + "initial_ts": ( + int(initial_ts) if initial_ts is not None else derive_initial_ts(cg) + ), + } + + def setup_mesh_meta( cg: ChunkedGraph, mesh_config: MeshConfig, @@ -79,12 +105,6 @@ def setup_mesh_meta( raise ValueError( f"mesh_config.mip {cfg.mip} exceeds watershed scales (available 0..{n_scales - 1})" ) - existing_mesh = cg.meta.custom_data.get("mesh", {}) - existing_ts = existing_mesh.get("initial_ts") - initial_ts = int(existing_ts) if existing_ts is not None else derive_initial_ts(cg) - if existing_ts is not None: - logger.info("preserving existing initial_ts=%d", initial_ts) - # 1. sharded mesh spec — same template per layer, layer-specific bits. layer_shard_spec = { "@type": "neuroglancer_uint64_sharded_v1", @@ -107,10 +127,6 @@ def setup_mesh_meta( "chunk_size": [int(x) for x in mesh_chunk_size], "sharding": sharding, } - mesh_root = posixpath.join(cg.meta.data_source.WATERSHED, cfg.dir) - CloudFiles(mesh_root).put_json("info", mesh_spec, cache_control="no-cache") - logger.info("wrote sharded mesh spec for layers %s", sorted(sharding.keys())) - # uniform draco grid size, derived from layer-2 draco settings. draco = get_draco_encoding_settings_for_chunk( cg, cg.get_chunk_id(layer=2, x=0, y=0, z=0), mip=cfg.mip @@ -118,16 +134,11 @@ def setup_mesh_meta( grid_size = draco["quantization_range"] / (2 ** draco["quantization_bits"] - 1) # 2. CG-side bigtable meta block. - mesh_meta = { - "uniform_draco_grid_size": grid_size, - "max_layer": int(cfg.max_layer), - "dynamic_mesh_dir": cfg.dynamic_mesh_dir, - "mip": int(cfg.mip), - "max_error": int(cfg.max_error), - "dir": cfg.dir, - "initial_ts": int(initial_ts), - } + mesh_meta = _mesh_block(cg, cfg, grid_size) cg.meta.custom_data["mesh"] = mesh_meta + spec_dir = MeshMeta(cg).spec_dir + CloudFiles(spec_dir).put_json("info", mesh_spec, cache_control="no-cache") + logger.info("wrote mesh spec for layers %s in %s", sorted(sharding), spec_dir) cg.update_meta(cg.meta, overwrite=True) logger.info("wrote cg.meta.custom_data['mesh']=%r", mesh_meta) return mesh_meta diff --git a/pychunkedgraph/tests/meshing/test_setup.py b/pychunkedgraph/tests/meshing/test_setup.py new file mode 100644 index 000000000..8e6715b1d --- /dev/null +++ b/pychunkedgraph/tests/meshing/test_setup.py @@ -0,0 +1,91 @@ +"""Tests for pychunkedgraph.pipeline.meshing.setup.setup_mesh_meta.""" + +from types import SimpleNamespace + +import pytest + +from pychunkedgraph.pipeline.meshing import setup +from pychunkedgraph.pipeline.meshing.meta import MeshConfig + + +@pytest.fixture +def written(monkeypatch): + """Spec writes by path, with draco and block-shape lookups stubbed.""" + specs = {} + + class Files: + def __init__(self, root): + self.root = root + + def put_json(self, name, data, cache_control=None): + specs[f"{self.root}/{name}"] = data + + monkeypatch.setattr(setup, "CloudFiles", Files) + monkeypatch.setattr( + setup, "get_mesh_block_shape_for_mip", lambda *_: (256, 256, 128) + ) + monkeypatch.setattr( + setup, + "get_draco_encoding_settings_for_chunk", + lambda *_, **__: {"quantization_range": 1023.0, "quantization_bits": 10}, + ) + return specs + + +def _migrated_cg(dynamic_mesh_dir="gs://old/graphene_meshes/dynamic"): + """A table whose watershed lives apart from its meshes.""" + mesh = { + "dir": "graphene_meshes", + "initial_mesh_dir": "gs://old/graphene_meshes/initial", + "dynamic_mesh_dir": dynamic_mesh_dir, + "initial_ts": 1700000000, + "verify": True, + } + meta = SimpleNamespace( + custom_data={"mesh": mesh}, + data_source=SimpleNamespace(WATERSHED="gs://cheap/seg"), + ws_cv=SimpleNamespace(info={"scales": [{}, {}, {}]}), + ) + return SimpleNamespace( + graph_id="g", + meta=meta, + get_chunk_id=lambda **_: 0, + update_meta=lambda *_, **__: None, + ) + + +def _config(dynamic_mesh_dir=None): + return MeshConfig( + dir="graphene_meshes", + mip=2, + max_layer=6, + max_error=40, + minishard_bits={2: 3}, + dynamic_mesh_dir=dynamic_mesh_dir, + ) + + +def test_rerun_keeps_keys_the_config_cannot_set(written): + mesh = setup.setup_mesh_meta(_migrated_cg(), _config()) + assert mesh["initial_mesh_dir"] == "gs://old/graphene_meshes/initial" + assert mesh["verify"] is True + + +def test_rerun_writes_the_spec_beside_the_initial_meshes(written): + setup.setup_mesh_meta(_migrated_cg(), _config()) + assert list(written) == ["gs://old/graphene_meshes/info"] + + +def test_rerun_keeps_a_pinned_mesh_path_over_a_relative_dynamic_dir(written): + mesh = setup.setup_mesh_meta(_migrated_cg(), _config("dynamic")) + assert mesh["dynamic_mesh_dir"] == "gs://old/graphene_meshes/dynamic" + + +def test_rerun_takes_an_absolute_dynamic_dir_the_config_names(written): + mesh = setup.setup_mesh_meta(_migrated_cg(), _config("gs://new/dynamic")) + assert mesh["dynamic_mesh_dir"] == "gs://new/dynamic" + + +def test_rerun_replaces_a_relative_dynamic_dir_with_the_configs(written): + mesh = setup.setup_mesh_meta(_migrated_cg("dynamic"), _config()) + assert mesh["dynamic_mesh_dir"] == "dynamic_g" From 0abf0343e1edf60941b17ecf4da9d8ec25999281 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 11 Nov 2026 21:14:18 +0000 Subject: [PATCH 07/11] feat(meshing): repoint a table's watershed on its graph meta - ChunkedGraphMeta.repoint_watershed pins the mesh block first - it persists nothing; ChunkedGraph.update_meta saves it - ws_cv reads its watershed's info directly, with no Redis cache Co-Authored-By: Claude --- pychunkedgraph/graph/meta.py | 31 +++++------- pychunkedgraph/meshing/mesh_meta/README.md | 5 +- pychunkedgraph/meshing/mesh_meta/core.py | 46 ++++++++++------- pychunkedgraph/tests/graph/test_meta.py | 57 ++++++++++++++++++++++ 4 files changed, 102 insertions(+), 37 deletions(-) create mode 100644 pychunkedgraph/tests/graph/test_meta.py diff --git a/pychunkedgraph/graph/meta.py b/pychunkedgraph/graph/meta.py index 37e922b6f..6ae5b23f9 100644 --- a/pychunkedgraph/graph/meta.py +++ b/pychunkedgraph/graph/meta.py @@ -1,4 +1,3 @@ -import json from datetime import timedelta from typing import Dict from typing import List @@ -11,10 +10,7 @@ from .utils.generic import compute_bitmasks from .chunks.utils import get_chunks_boundary -from ..utils.redis import keys as r_keys -from ..utils.redis import get_rq_queue -from ..utils.redis import get_redis_connection - +from ..meshing.mesh_meta import MeshMeta _datasource_fields = ("EDGES", "COMPONENTS", "WATERSHED", "DATA_VERSION", "CV_MIP") _datasource_defaults = (None, None, None, None, 0) @@ -80,24 +76,21 @@ def data_source(self): def custom_data(self): return self._custom_data + def repoint_watershed(self, watershed: str) -> "ChunkedGraphMeta": + """Point this meta at ``watershed`` in place, the mesh block pinned first so + meshes stay where they are. Persists nothing: save the returned self with + ``cg.update_meta(meta, overwrite=True)``.""" + if "mesh" in self._custom_data: + self._custom_data["mesh"] = MeshMeta(self).pinned_block + self._data_source = self._data_source._replace(WATERSHED=watershed) + self._ws_cv = None + return self + @property def ws_cv(self): if self._ws_cv: return self._ws_cv - - cache_key = f"{self.graph_config.ID}:ws_cv_info_cached" - try: - # try reading a cached info file for distributed workers - # useful to avoid md5 errors on high gcs load - redis = get_redis_connection() - cached_info = json.loads(redis.get(cache_key)) - self._ws_cv = CloudVolume(self._data_source.WATERSHED, info=cached_info) - except Exception: - self._ws_cv = CloudVolume(self._data_source.WATERSHED) - try: - redis.set(cache_key, json.dumps(self._ws_cv.info)) - except Exception: - ... + self._ws_cv = CloudVolume(self._data_source.WATERSHED) return self._ws_cv @property diff --git a/pychunkedgraph/meshing/mesh_meta/README.md b/pychunkedgraph/meshing/mesh_meta/README.md index 4270e852a..6aedac606 100644 --- a/pychunkedgraph/meshing/mesh_meta/README.md +++ b/pychunkedgraph/meshing/mesh_meta/README.md @@ -57,13 +57,16 @@ upstream; this module only reads the result. ## API -`MeshMeta(cg)` exposes these properties: +`MeshMeta(cg)`, or `MeshMeta(meta)` for a graph meta alone, exposes these properties: - `initial_path` → absolute dir of the initial (sharded) meshes. - `dynamic_path` → absolute dir of the dynamic (unsharded) meshes. +- `spec_dir` → the dir of the shard spec `info`, the parent of `initial_path`. - `dir` → the sharded mesh dir name under the watershed. - `dynamic_mesh_dir` → the dynamic dir as configured, a name or a cloud URL. - `client_metadata` → the graphene info's `mesh_metadata` for this table. +- `pinned_block` → the block with both dirs absolute and its grid keys written in, so it + reads the same under any watershed; `ChunkedGraphMeta.repoint_watershed` stores it. - `max_layer`, `mip`, `max_error`, `initial_ts` → the mesh params. - `needs_v2` → true when either location falls **outside** the watershed dir, i.e. meshes are not co-located with the watershed. Old clients compose paths diff --git a/pychunkedgraph/meshing/mesh_meta/core.py b/pychunkedgraph/meshing/mesh_meta/core.py index 03f391dc8..fcf8e0bcf 100644 --- a/pychunkedgraph/meshing/mesh_meta/core.py +++ b/pychunkedgraph/meshing/mesh_meta/core.py @@ -26,12 +26,13 @@ def _resolve(root: str, value: str) -> str: class MeshMeta: - """Mesh metadata for a ChunkedGraph, read from ``custom_data["mesh"]``.""" + """Mesh metadata of a ChunkedGraph or its meta alone, from ``custom_data["mesh"]``.""" def __init__(self, cg): - self._mesh = cg.meta.custom_data.get("mesh", {}) - self._watershed = cg.meta.data_source.WATERSHED - self._meta = cg.meta + meta = getattr(cg, "meta", cg) + self._mesh = meta.custom_data.get("mesh", {}) + self._watershed = meta.data_source.WATERSHED + self._meta = meta @property def dir(self) -> str: @@ -59,28 +60,39 @@ def dynamic_path(self) -> str: return _resolve(self._root, self.dynamic_mesh_dir) @property - def client_metadata(self) -> dict[str, object]: - """``mesh_metadata`` for a graphene info. cloud-volume reads the dynamic dir as - ``unsharded_mesh_dir``, and a v2 client reads the two absolute paths.""" + def _grid_keys(self) -> dict[str, object]: + """The client grid keys: the block's own, else the watershed info's (the shim).""" ws_mesh = self._meta.ws_info.get("mesh_metadata", {}) - fallback = { - key: ws_mesh[key] - for key in _WATERSHED_FALLBACK_KEYS - if key in ws_mesh and key not in self._mesh - } - own = { - key: self._mesh[key] + return { + key: self._mesh[key] if key in self._mesh else ws_mesh[key] for key in _WATERSHED_FALLBACK_KEYS - if key in self._mesh + if key in self._mesh or key in ws_mesh } + + @property + def client_metadata(self) -> dict[str, object]: + """``mesh_metadata`` for a graphene info. cloud-volume reads the dynamic dir as + ``unsharded_mesh_dir``, and a v2 client reads the two absolute paths.""" return { - **fallback, - **own, + **self._grid_keys, "unsharded_mesh_dir": self.dynamic_mesh_dir, "initial_mesh_path": self.initial_path, "dynamic_mesh_path": self.dynamic_path, } + @property + def pinned_block(self) -> dict[str, object]: + """The block with every value it takes from the watershed written in, so it reads + the same under any watershed; a block without ``dir`` takes none.""" + if "dir" not in self._mesh: + return dict(self._mesh) + return { + **self._mesh, + **self._grid_keys, + "initial_mesh_dir": self.initial_path, + "dynamic_mesh_dir": self.dynamic_path, + } + @property def needs_v2(self) -> bool: """True when meshes live outside the watershed dir (old clients can't reach).""" diff --git a/pychunkedgraph/tests/graph/test_meta.py b/pychunkedgraph/tests/graph/test_meta.py new file mode 100644 index 000000000..24795b96d --- /dev/null +++ b/pychunkedgraph/tests/graph/test_meta.py @@ -0,0 +1,57 @@ +"""Tests for pychunkedgraph.graph.meta.ChunkedGraphMeta.repoint_watershed.""" + +import pytest + +from pychunkedgraph.graph import meta as meta_module +from pychunkedgraph.graph.meta import ChunkedGraphMeta, DataSource, GraphConfig +from pychunkedgraph.meshing.mesh_meta import MeshMeta + +OLD, NEW = "gs://old/seg", "gs://new/seg" + + +@pytest.fixture +def infos(monkeypatch): + """Watershed infos by path, served by a stub volume.""" + by_path = {OLD: {"at": OLD}, NEW: {"at": NEW}} + + class Volume: + def __init__(self, path): + self.info = by_path[path] + + monkeypatch.setattr(meta_module, "CloudVolume", Volume) + return by_path + + +def _meta(custom_data): + return ChunkedGraphMeta(GraphConfig(ID="g"), DataSource(WATERSHED=OLD), custom_data) + + +def test_repoint_reads_the_new_watershed(infos): + meta = _meta({}) + assert meta.ws_info == {"at": OLD} + assert meta.repoint_watershed(NEW) is meta + assert meta.data_source.WATERSHED == NEW + assert meta.ws_info == {"at": NEW} + + +def test_repoint_keeps_meshes_where_they_resolved(infos): + mm = MeshMeta(_meta({"mesh": {"dir": "graphene_meshes"}}).repoint_watershed(NEW)) + assert mm.initial_path == f"{OLD}/graphene_meshes/initial" + assert mm.dynamic_path == f"{OLD}/graphene_meshes/dynamic" + + +def test_repoint_keeps_the_old_watershed_grid_keys(infos): + infos[OLD] = { + "mesh_metadata": {"uniform_draco_grid_size": 7.0, "max_meshed_layer": 9} + } + infos[NEW] = {"mesh_metadata": {"max_meshed_layer": 3}} + meta = _meta({"mesh": {"dir": "graphene_meshes", "max_meshed_layer": 5}}) + client = MeshMeta(meta.repoint_watershed(NEW)).client_metadata + assert client["uniform_draco_grid_size"] == 7.0 + assert client["max_meshed_layer"] == 5 + + +@pytest.mark.parametrize("custom_data", [{"READ_ONLY": True}, {"mesh": {"mip": 2}}]) +def test_repoint_of_a_table_without_meshes_keeps_its_custom_data(infos, custom_data): + meta = _meta(dict(custom_data)).repoint_watershed(NEW) + assert meta.custom_data == custom_data From 9bdd4d174a7250da85d34ad6d78dd2ed79ad71b2 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Thu, 12 Nov 2026 15:49:39 +0000 Subject: [PATCH 08/11] temp(meshing): serve minnie3_v1 from its new watershed until merge - every load of its meta repoints it in memory to the iarpa_microns path - it pickles as stored, so no write changes its row; revert before merge Co-Authored-By: Claude --- pychunkedgraph/graph/meta.py | 19 ++++++++++++++++--- pychunkedgraph/tests/graph/test_meta.py | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/pychunkedgraph/graph/meta.py b/pychunkedgraph/graph/meta.py index 6ae5b23f9..9161611f2 100644 --- a/pychunkedgraph/graph/meta.py +++ b/pychunkedgraph/graph/meta.py @@ -12,6 +12,10 @@ from .chunks.utils import get_chunks_boundary from ..meshing.mesh_meta import MeshMeta +#: TEMPORARY, revert before merge: tables a test cluster serves from another watershed, +#: repointed in memory each time their stored meta loads. +TEST_WATERSHEDS = {"minnie3_v1": "gs://iarpa_microns/minnie/minnie65/ws"} + _datasource_fields = ("EDGES", "COMPONENTS", "WATERSHED", "DATA_VERSION", "CV_MIP") _datasource_defaults = (None, None, None, None, 0) DataSource = namedtuple( @@ -63,6 +67,7 @@ def __init__( self._layer_bounds_d = None self._layer_count = None self._bitmasks = None + self._stored = None @property def graph_config(self): @@ -261,16 +266,24 @@ def __getnewargs__(self): return (self.graph_config, self.data_source) def __getstate__(self): + # A test table pickles as stored, so a write never persists its in-memory repoint. + source = self._stored or self return { - "graph_config": self.graph_config, - "data_source": self.data_source, - "custom_data": self.custom_data, + "graph_config": source.graph_config, + "data_source": source.data_source, + "custom_data": source.custom_data, } def __setstate__(self, state): self.__init__( state["graph_config"], state["data_source"], state.get("custom_data", {}) ) + graph_id = self._graph_config.ID_PREFIX + self._graph_config.ID + if graph_id in TEST_WATERSHEDS: + self._stored = ChunkedGraphMeta( + self._graph_config, self._data_source, dict(self._custom_data) + ) + self.repoint_watershed(TEST_WATERSHEDS[graph_id]) def __str__(self): from json import dumps diff --git a/pychunkedgraph/tests/graph/test_meta.py b/pychunkedgraph/tests/graph/test_meta.py index 24795b96d..7ca646a4f 100644 --- a/pychunkedgraph/tests/graph/test_meta.py +++ b/pychunkedgraph/tests/graph/test_meta.py @@ -1,5 +1,7 @@ """Tests for pychunkedgraph.graph.meta.ChunkedGraphMeta.repoint_watershed.""" +import pickle + import pytest from pychunkedgraph.graph import meta as meta_module @@ -55,3 +57,25 @@ def test_repoint_keeps_the_old_watershed_grid_keys(infos): def test_repoint_of_a_table_without_meshes_keeps_its_custom_data(infos, custom_data): meta = _meta(dict(custom_data)).repoint_watershed(NEW) assert meta.custom_data == custom_data + + +def test_a_test_table_loads_repointed_and_others_load_as_stored(infos, monkeypatch): + monkeypatch.setattr(meta_module, "TEST_WATERSHEDS", {"minnie3_v1": NEW}) + test = ChunkedGraphMeta(GraphConfig(ID="minnie3_v1"), DataSource(WATERSHED=OLD), {}) + other = ChunkedGraphMeta(GraphConfig(ID="other"), DataSource(WATERSHED=OLD), {}) + assert pickle.loads(pickle.dumps(test)).data_source.WATERSHED == NEW + assert pickle.loads(pickle.dumps(other)).data_source.WATERSHED == OLD + + +def test_a_loaded_test_table_writes_back_as_stored(infos, monkeypatch): + monkeypatch.setattr(meta_module, "TEST_WATERSHEDS", {"minnie3_v1": NEW}) + block = {"mesh": {"dir": "graphene_meshes"}} + stored = ChunkedGraphMeta( + GraphConfig(ID="minnie3_v1"), DataSource(WATERSHED=OLD), dict(block) + ) + loaded = pickle.loads(pickle.dumps(stored)) + assert MeshMeta(loaded).initial_path == f"{OLD}/graphene_meshes/initial" + written = pickle.dumps(loaded) + monkeypatch.setattr(meta_module, "TEST_WATERSHEDS", {}) + row = pickle.loads(written) + assert (row.data_source.WATERSHED, row.custom_data) == (OLD, block) From cb05ea7c0205cd1f7f53747bb7eb4b93aceb843d Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Mon, 16 Nov 2026 18:53:15 +0000 Subject: [PATCH 09/11] feat(meshing): copies read their source's dynamic meshes - A copy reuses its source's initial meshes and writes its own dynamic dir. - Its first open lists the source's dynamic dir as an inherited layer. - A new node's creation time hints at the dir holding its mesh. - A probe checks the hint, and a miss searches the own dir first. - After the own dir, a miss searches inherited dirs newest first. - Inside the server, a mesh found outside the own dir carries that dir. - v2 groups rows by that dir, so clients see the same row format. - Tables without inherited dirs read and cache exactly as before. Co-Authored-By: Claude --- pychunkedgraph/app/meshing/common.py | 4 +- pychunkedgraph/graph/chunkedgraph.py | 33 +++-- pychunkedgraph/graph/meta.py | 22 +++- pychunkedgraph/meshing/manifest/dynamic.py | 110 ++++++++++++++++ pychunkedgraph/meshing/manifest/sharded.py | 4 +- pychunkedgraph/meshing/manifest/utils.py | 35 ++--- pychunkedgraph/meshing/manifest/v2.py | 7 +- pychunkedgraph/meshing/mesh_meta/README.md | 27 +++- pychunkedgraph/meshing/mesh_meta/__init__.py | 4 +- pychunkedgraph/meshing/mesh_meta/core.py | 52 +++++++- pychunkedgraph/tests/graph/test_meta.py | 28 ++++ .../tests/meshing/test_manifest_dynamic.py | 122 ++++++++++++++++++ .../tests/meshing/test_manifest_v2.py | 12 +- .../tests/meshing/test_mesh_meta.py | 53 ++++++++ 14 files changed, 460 insertions(+), 53 deletions(-) create mode 100644 pychunkedgraph/meshing/manifest/dynamic.py create mode 100644 pychunkedgraph/tests/meshing/test_manifest_dynamic.py diff --git a/pychunkedgraph/app/meshing/common.py b/pychunkedgraph/app/meshing/common.py index d353541f7..e4f40c1b9 100644 --- a/pychunkedgraph/app/meshing/common.py +++ b/pychunkedgraph/app/meshing/common.py @@ -19,7 +19,7 @@ from pychunkedgraph.meshing.manifest import get_highest_child_nodes_with_meshes from pychunkedgraph.meshing.manifest import get_children_before_start_layer from pychunkedgraph.meshing.manifest import ManifestCache - +from pychunkedgraph.meshing.manifest.dynamic import dynamic_buckets __meshing_url_prefix__ = os.environ.get("MESHING_URL_PREFIX", "meshing") @@ -144,7 +144,7 @@ def manifest_response(cg, args): # Every row carries its seg id, so neither seg id flag changes a v2 response. mm = MeshMeta(cg) initial, dynamic = v2.to_v2_groups(seg_ids, fragments, verified=verify) - resp = v2.assemble(mm.initial_path, mm.dynamic_path, initial, dynamic) + resp = v2.assemble(mm.initial_path, initial, dynamic_buckets(cg, dynamic)) else: resp = {"fragments": fragments} if prepend_seg_ids: diff --git a/pychunkedgraph/graph/chunkedgraph.py b/pychunkedgraph/graph/chunkedgraph.py index 3916fc94e..98931ceae 100644 --- a/pychunkedgraph/graph/chunkedgraph.py +++ b/pychunkedgraph/graph/chunkedgraph.py @@ -61,6 +61,11 @@ def __init__( self._cache_service = None self.mock_edges = None # hack for unit tests + # A copied table carries its source's meta; its first open under the new id + # rewrites and saves it once, and a later open matches the id. + if graph_id != self.graph_id: + self.update_meta(self.meta.for_copied_graph(graph_id), overwrite=True) + @property def meta(self) -> ChunkedGraphMeta: return self._meta @@ -112,9 +117,13 @@ def range_read_chunk( """Read all nodes in a chunk.""" layer = self.get_chunk_layer(chunk_id) root_chunk = layer == self.meta.layer_count - max_node_id = self.id_client.get_max_node_id(chunk_id=chunk_id, root_chunk=root_chunk) + max_node_id = self.id_client.get_max_node_id( + chunk_id=chunk_id, root_chunk=root_chunk + ) if layer == 1: - max_node_id = chunk_id | self.get_segment_id_limit(chunk_id) # pylint: disable=unsupported-binary-operation + max_node_id = chunk_id | self.get_segment_id_limit( + chunk_id + ) # pylint: disable=unsupported-binary-operation return self.client.read_nodes( start_id=self.get_node_id(np.uint64(0), chunk_id=chunk_id), @@ -283,9 +292,11 @@ def _get_children_multiple( node_ids=node_ids, properties=attributes.Hierarchy.Child ) return { - x: node_children_d[x][0].value - if x in node_children_d - else types.empty_1d.copy() + x: ( + node_children_d[x][0].value + if x in node_children_d + else types.empty_1d.copy() + ) for x in node_ids } return self.cache.children_multiple(node_ids) @@ -692,9 +703,7 @@ def get_l2_agglomerations( sv_parent_d.update(dict(zip(svs.tolist(), [l2id] * len(svs)))) in_edges, out_edges, cross_edges = edge_utils.categorize_edges_v2( - self.meta, - all_chunk_edges, - sv_parent_d + self.meta, all_chunk_edges, sv_parent_d ) agglomeration_d = get_agglomerations( @@ -702,9 +711,11 @@ def get_l2_agglomerations( ) return ( agglomeration_d, - (self.mock_edges,) - if self.mock_edges is not None - else (in_edges, out_edges, cross_edges), + ( + (self.mock_edges,) + if self.mock_edges is not None + else (in_edges, out_edges, cross_edges) + ), ) def get_node_timestamps( diff --git a/pychunkedgraph/graph/meta.py b/pychunkedgraph/graph/meta.py index 9161611f2..9c875d4c4 100644 --- a/pychunkedgraph/graph/meta.py +++ b/pychunkedgraph/graph/meta.py @@ -1,3 +1,4 @@ +import time from datetime import timedelta from typing import Dict from typing import List @@ -10,7 +11,7 @@ from .utils.generic import compute_bitmasks from .chunks.utils import get_chunks_boundary -from ..meshing.mesh_meta import MeshMeta +from ..meshing.mesh_meta import INHERITED, MeshMeta #: TEMPORARY, revert before merge: tables a test cluster serves from another watershed, #: repointed in memory each time their stored meta loads. @@ -81,6 +82,25 @@ def data_source(self): def custom_data(self): return self._custom_data + def for_copied_graph(self, graph_id: str) -> "ChunkedGraphMeta": + """Rewrite this meta for a table copied under ``graph_id``: its id, and a mesh + block keeping the source's meshes, reading the source's dynamic dir for nodes + made before now while writing its own. Returns self, for ``update_meta``.""" + gc = self._graph_config._asdict() + gc["ID"] = graph_id + self._graph_config = GraphConfig(**gc) + mesh = self._custom_data.get("mesh") + if not mesh or "dir" not in mesh: + return self + source = MeshMeta(self) + layer = {"path": source.dynamic_path, "until": int(time.time())} + block = {**source.pinned_block, "dynamic_mesh_dir": f"dynamic_{graph_id}"} + block[INHERITED] = [*mesh.get(INHERITED, ()), layer] + self._custom_data["mesh"] = block + # Pinned again, so the copy's own dir is absolute and a setup re-run keeps it. + self._custom_data["mesh"] = MeshMeta(self).pinned_block + return self + def repoint_watershed(self, watershed: str) -> "ChunkedGraphMeta": """Point this meta at ``watershed`` in place, the mesh block pinned first so meshes stay where they are. Persists nothing: save the returned self with diff --git a/pychunkedgraph/meshing/manifest/dynamic.py b/pychunkedgraph/meshing/manifest/dynamic.py new file mode 100644 index 000000000..e84083fc7 --- /dev/null +++ b/pychunkedgraph/meshing/manifest/dynamic.py @@ -0,0 +1,110 @@ +"""Where a dynamic mesh lives, across a table's own dynamic dir and the dirs it inherits. + +A node's creation time hints at its dir; a probe checks the hint, and a miss searches the +rest of the stack, own dir first, so a table finds every mesh it wrote whatever the hint says. +""" + +import posixpath +from functools import lru_cache +from typing import Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple + +import numpy as np +from cloudfiles import CloudFiles + +from ..meshgen_utils import get_mesh_name +from ..mesh_meta import MeshMeta +from ...graph.basetypes import NODE_ID + +#: What ``search_dynamic`` asks of a dir: each name it holds, mapped to a truthy value. +Probe = Callable[[str, List[str]], Dict[str, object]] + + +class Found(NamedTuple): + """A dynamic mesh as found: its dir, its file name, and what the probe read.""" + + path: str + name: str + value: object + + +def dynamic_groups(cg, new_ids) -> Dict[str, np.ndarray]: + """``new_ids`` grouped by the dynamic dir their creation time hints at; node timestamps + are read only for a copy, the one table with inherited dirs.""" + mm = MeshMeta(cg) + new_ids = np.asarray(new_ids, dtype=NODE_ID) + created = cg.get_node_timestamps(new_ids) if mm.inherited and new_ids.size else None + return mm.by_dynamic_dir(new_ids, created) + + +@lru_cache(maxsize=None) +def dynamic_store(path: str) -> CloudFiles: + """One store of a dynamic dir, made once per process and shared by every reader.""" + return CloudFiles(path) + + +def probe_exists(path: str, names: List[str]) -> Dict[str, bool]: + """Whether ``path`` holds each named mesh.""" + return dynamic_store(path).exists(names) + + +def probe_read(path: str, names: List[str]) -> Dict[str, Optional[bytes]]: + """Each named mesh's content in ``path``, ``None`` where it holds none.""" + contents = {} + for res in dynamic_store(path).get(names): + if res["error"]: + raise res["error"] + contents[res["path"]] = res["content"] + return contents + + +def search_dynamic(cg, new_ids, probe: Probe) -> Dict[int, Found]: + """Each new node's dynamic mesh, probed first in its creation-time dir, then on a + miss in each other dir of ``dynamic_stack`` once, in order; a node in none is absent. + """ + names = {int(i): get_mesh_name(cg, i) for i in new_ids} + hint, found = {}, {} + + def run(path: str, ids: List[int]) -> None: + got = probe(path, [names[i] for i in ids]) + found.update( + {i: Found(path, names[i], got[names[i]]) for i in ids if got.get(names[i])} + ) + + for path, ids in dynamic_groups(cg, list(names)).items(): + hint.update({int(i): path for i in ids}) + run(path, [int(i) for i in ids]) + for path in MeshMeta(cg).dynamic_stack: + rest = [i for i in names if i not in found and hint[i] != path] + if rest: + run(path, rest) + return found + + +def dynamic_row(own: str, path: str, name: str) -> str: + """A dynamic mesh's row: its file name, under its dir unless that dir is ``own``.""" + return name if path == own else posixpath.join(path, name) + + +def row_location(own: str, row: str) -> Tuple[str, str]: + """A dynamic row's dir and file name, the inverse of ``dynamic_row``.""" + path, name = posixpath.split(row) + return path or own, name + + +def hinted_rows(cg, new_ids) -> List[str]: + """Unprobed rows for ``new_ids``, in order, each under its creation-time hint dir.""" + own = MeshMeta(cg).dynamic_path + hint = { + int(i): path for path, ids in dynamic_groups(cg, new_ids).items() for i in ids + } + return [dynamic_row(own, hint[int(i)], get_mesh_name(cg, i)) for i in new_ids] + + +def dynamic_buckets(cg, rows: Sequence[str]) -> Dict[str, List[str]]: + """v2 dynamic rows grouped by the dir holding each, read off the row: no timestamp.""" + own = MeshMeta(cg).dynamic_path + buckets: Dict[str, List[str]] = {} + for row in rows: + path, name = row_location(own, row) + buckets.setdefault(path, []).append(name) + return buckets diff --git a/pychunkedgraph/meshing/manifest/sharded.py b/pychunkedgraph/meshing/manifest/sharded.py index 56519100f..108269947 100644 --- a/pychunkedgraph/meshing/manifest/sharded.py +++ b/pychunkedgraph/meshing/manifest/sharded.py @@ -58,7 +58,7 @@ def speculative_manifest( """ from .utils import check_skips from .utils import segregate_node_ids - from ..meshgen_utils import get_mesh_name + from .dynamic import hinted_rows if start_layer is None: start_layer = MeshMeta(cg).max_layer @@ -101,5 +101,5 @@ def speculative_manifest( mesh_shards.append(f"~{id_}:{layer}:{chunk_id}:{fname}:{minishard}") # get mesh files for new IDs - mesh_files = [f"{get_mesh_name(cg, id_)}" for id_ in new_ids] + mesh_files = hinted_rows(cg, new_ids) return np.concatenate([initial_ids, new_ids]), mesh_shards + mesh_files diff --git a/pychunkedgraph/meshing/manifest/utils.py b/pychunkedgraph/meshing/manifest/utils.py index aab723068..c78b4f656 100644 --- a/pychunkedgraph/meshing/manifest/utils.py +++ b/pychunkedgraph/meshing/manifest/utils.py @@ -8,12 +8,14 @@ from typing import Sequence import numpy as np -from cloudfiles import CloudFiles from cloudvolume import CloudVolume from cloudvolume import Mesh from .cache import ManifestCache -from ..meshgen_utils import get_mesh_name +from .dynamic import dynamic_row +from .dynamic import probe_exists +from .dynamic import probe_read +from .dynamic import search_dynamic from ..meshgen_utils import get_json_info from ..mesh_meta import MeshMeta from ...graph import ChunkedGraph @@ -107,24 +109,21 @@ def _get_dynamic_meshes(cg, node_ids: Sequence[np.uint64]) -> Tuple[Dict, List]: if len(node_ids) == 0: return result, not_existing - mesh_path = MeshMeta(cg).dynamic_path - cf = CloudFiles(mesh_path) manifest_cache = ManifestCache(cg.graph_id, initial=False) result_, not_cached, not_existing_ = manifest_cache.get_fragments(node_ids) not_existing.extend(not_existing_) result.update(result_) - filenames = [get_mesh_name(cg, id_) for id_ in not_cached] - existence_dict = cf.exists(filenames) - + own = MeshMeta(cg).dynamic_path + found = search_dynamic(cg, not_cached, probe_exists) result_ = {} - for mesh_key in existence_dict: - node_id = np.uint64(mesh_key.split(":")[0]) - if existence_dict[mesh_key]: - result_[node_id] = mesh_key + for node_id in not_cached: + hit = found.get(int(node_id)) + if hit is None: + not_existing.append(node_id) continue - not_existing.append(node_id) + result_[node_id] = dynamic_row(own, hit.path, hit.name) manifest_cache.set_fragments(result_) result.update(result_) @@ -206,14 +205,13 @@ def shard_mesh_source(cg): class NodeMeshReader: - """Reads node meshes from this table's own mesh dirs, a cloud-URL dir included. + """Reads node meshes from the dirs holding them, a copy's inherited dirs included. Built once per task so the shard readers keep their index caches across reads. """ def __init__(self, cg): self._cg = cg - self._dynamic = CloudFiles(MeshMeta(cg).dynamic_path) self._source = shard_mesh_source(cg) def get(self, node_ids: Sequence[np.uint64]) -> Dict[int, Mesh]: @@ -227,13 +225,8 @@ def get(self, node_ids: Sequence[np.uint64]) -> Dict[int, Mesh]: return {} initial_ids, new_ids = segregate_node_ids(self._cg, node_ids) result = {} - names = {get_mesh_name(self._cg, id_): int(id_) for id_ in new_ids} - for res in self._dynamic.get(list(names)): - if res["error"]: - raise res["error"] - if res["content"] is not None: - label = names[res["path"]] - result[label] = Mesh.from_draco(res["content"], segid=label) + for node_id, hit in search_dynamic(self._cg, new_ids, probe_read).items(): + result[node_id] = Mesh.from_draco(hit.value, segid=node_id) meta = self._source.meta layers = self._cg.get_chunk_layers(initial_ids) for layer in np.unique(layers): diff --git a/pychunkedgraph/meshing/manifest/v2.py b/pychunkedgraph/meshing/manifest/v2.py index effaa178b..1af17fee2 100644 --- a/pychunkedgraph/meshing/manifest/v2.py +++ b/pychunkedgraph/meshing/manifest/v2.py @@ -58,9 +58,9 @@ def to_v2_groups(node_ids, fragments, *, verified): def assemble( - initial_path: str, dynamic_path: str, initial_frags, dynamic_frags + initial_path: str, initial_frags, dynamic: dict[str, list[str]] ) -> dict[str, object]: - """v2 manifest: fragment lists grouped by absolute bucket path. + """v2 manifest: fragment lists grouped by absolute bucket path, one per dynamic dir. Empty groups are omitted. Metadata is added beside ``fragments`` at the top level, so a bucket maps straight to its list. @@ -68,6 +68,5 @@ def assemble( fragments: dict[str, list[str]] = {} if len(initial_frags): fragments[initial_path] = list(initial_frags) - if len(dynamic_frags): - fragments[dynamic_path] = list(dynamic_frags) + fragments.update({path: list(rows) for path, rows in dynamic.items() if len(rows)}) return {"manifest_version": MANIFEST_VERSION, "fragments": fragments} diff --git a/pychunkedgraph/meshing/mesh_meta/README.md b/pychunkedgraph/meshing/mesh_meta/README.md index 6aedac606..c9ad2e288 100644 --- a/pychunkedgraph/meshing/mesh_meta/README.md +++ b/pychunkedgraph/meshing/mesh_meta/README.md @@ -24,7 +24,9 @@ ChunkedGraph. - **dynamic** — the unsharded meshes produced by proofreading edits. **Per-graph**: each graph keeps its own, so on the pcgv3 line it defaults to a graph-id-derived dir (`dynamic_`) and stays isolated even while - sharing initial meshes; on the pcgv2 line it is a plain subdir. + sharing initial meshes; on the pcgv2 line it is a plain subdir. A copy writes + only its own, and also reads the dynamic dirs it inherits, for meshes its + sources wrote before it was copied. ## Configuration @@ -35,6 +37,11 @@ All read from `custom_data["mesh"]`: - `initial_mesh_dir` — the initial location (default `initial`). - `dynamic_mesh_dir` — the dynamic location (default `dynamic`; pcgv3 setup fills `dynamic_`). +- `inherited_dynamic` — a copy's sources' dynamic dirs, oldest first, each + `{"path", "until"}`: an absolute dir, and the Unix second of the copy's first + open, before which its source made a node. Only a copy's first open writes it, + through `ChunkedGraphMeta.for_copied_graph`; any other table has none and reads + as before. - `max_layer`, `mip`, `max_error` — mesh params (start layer for manifests, and the mip / max-error used by remeshing). - `uniform_draco_grid_size` — the draco grid clients deduplicate on, written by setup. @@ -61,6 +68,14 @@ upstream; this module only reads the result. - `initial_path` → absolute dir of the initial (sharded) meshes. - `dynamic_path` → absolute dir of the dynamic (unsharded) meshes. +- `inherited` → a copy's inherited dynamic dirs as `Layer(path, until)`, oldest + first; empty for any other table. +- `dynamic_stack` → every dynamic dir a node's mesh may be in, the table's own first, + then inherited dirs newest first: the order a missed lookup searches. +- `by_dynamic_dir(node_ids, created)` → new node ids grouped by the dynamic dir their + creation times hint at. `manifest/dynamic.py` checks each hint with a probe and + searches `dynamic_stack` on a miss, so a copy finds every mesh it or its sources + wrote. - `spec_dir` → the dir of the shard spec `info`, the parent of `initial_path`. - `dir` → the sharded mesh dir name under the watershed. - `dynamic_mesh_dir` → the dynamic dir as configured, a name or a cloud URL. @@ -68,11 +83,11 @@ upstream; this module only reads the result. - `pinned_block` → the block with both dirs absolute and its grid keys written in, so it reads the same under any watershed; `ChunkedGraphMeta.repoint_watershed` stores it. - `max_layer`, `mip`, `max_error`, `initial_ts` → the mesh params. -- `needs_v2` → true when either location falls **outside** the watershed dir, - i.e. meshes are not co-located with the watershed. Old clients compose paths - relative to the watershed, so they cannot reach such meshes: the v2 manifest - serves them correctly, and the v1 path must fail loudly rather than return - unreachable paths. +- `needs_v2` → true when either location falls **outside** the watershed dir, or the + table inherits dynamic dirs, i.e. meshes are not all co-located with the + watershed. Old clients compose paths relative to the watershed, so they cannot + reach such meshes: the v2 manifest serves them correctly, and the v1 path must + fail loudly rather than return unreachable paths. - `reader_anchor` → the `(data_dir, mesh)` pair to hand a CloudVolume mesh reader. The reader appends `initial/` internally, so it must be anchored at the **parent** of the initial dir; this yields shard byte-ranges from the right diff --git a/pychunkedgraph/meshing/mesh_meta/__init__.py b/pychunkedgraph/meshing/mesh_meta/__init__.py index 4d777312a..1f0b1d4cc 100644 --- a/pychunkedgraph/meshing/mesh_meta/__init__.py +++ b/pychunkedgraph/meshing/mesh_meta/__init__.py @@ -1,5 +1,5 @@ """Branch-agnostic graphene mesh metadata. See README.md.""" -from .core import MeshMeta, is_absolute +from .core import INHERITED, MeshMeta, is_absolute -__all__ = ["MeshMeta", "is_absolute"] +__all__ = ["INHERITED", "MeshMeta", "is_absolute"] diff --git a/pychunkedgraph/meshing/mesh_meta/core.py b/pychunkedgraph/meshing/mesh_meta/core.py index fcf8e0bcf..18f559139 100644 --- a/pychunkedgraph/meshing/mesh_meta/core.py +++ b/pychunkedgraph/meshing/mesh_meta/core.py @@ -4,6 +4,9 @@ """ import posixpath +from typing import NamedTuple + +import numpy as np #: DEPRECATED shim: client mesh keys older setups wrote into the watershed info only. A key #: the table's mesh block lacks is copied from there at read time; drop this once every @@ -25,6 +28,18 @@ def _resolve(root: str, value: str) -> str: return value.rstrip("/") if is_absolute(value) else posixpath.join(root, value) +#: The block key a copy's rewrite fills: its sources' dynamic dirs, oldest first. +INHERITED = "inherited_dynamic" + + +class Layer(NamedTuple): + """A source's dynamic dir, holding the meshes of nodes made before ``until``.""" + + path: str + #: Unix seconds: the copy's first open, before which the source made the node. + until: int + + class MeshMeta: """Mesh metadata of a ChunkedGraph or its meta alone, from ``custom_data["mesh"]``.""" @@ -59,6 +74,38 @@ def dynamic_path(self) -> str: """Absolute dir of the per-graph dynamic (unsharded) meshes.""" return _resolve(self._root, self.dynamic_mesh_dir) + @property + def inherited(self) -> tuple[Layer, ...]: + """Dynamic dirs inherited as a copy, oldest first; none for any other table.""" + return tuple( + Layer(str(one["path"]), int(one["until"])) + for one in self._mesh.get(INHERITED, ()) + ) + + @property + def dynamic_stack(self) -> tuple[str, ...]: + """Every dynamic dir a node's mesh may be in, in the order a miss searches them: + the table's own first, then inherited dirs newest first.""" + return (self.dynamic_path, *(one.path for one in reversed(self.inherited))) + + def by_dynamic_dir(self, node_ids, created) -> dict[str, np.ndarray]: + """New node ids grouped by the dynamic dir their creation time hints at, each dir + once: the first inherited dir a node's ``created`` (datetime64) predates, else + ``dynamic_path``. ``created`` must hold one time per id; this is not checked, + since every caller reads the times of nodes that exist.""" + node_ids = np.asarray(node_ids) + if not node_ids.size: + return {} + layers = self.inherited + if not layers: + return {self.dynamic_path: node_ids} + untils = np.array([np.datetime64(one.until, "s") for one in layers]) + at = np.searchsorted( + untils, np.asarray(created, dtype="datetime64[s]"), side="right" + ) + paths = [one.path for one in layers] + [self.dynamic_path] + return {paths[i]: node_ids[at == i] for i in np.unique(at)} + @property def _grid_keys(self) -> dict[str, object]: """The client grid keys: the block's own, else the watershed info's (the shim).""" @@ -95,9 +142,10 @@ def pinned_block(self) -> dict[str, object]: @property def needs_v2(self) -> bool: - """True when meshes live outside the watershed dir (old clients can't reach).""" + """True when meshes live outside the watershed dir, or across inherited dynamic + dirs: old clients reach neither.""" root = self._root - return not ( + return bool(self.inherited) or not ( self.initial_path.startswith(root) and self.dynamic_path.startswith(root) ) diff --git a/pychunkedgraph/tests/graph/test_meta.py b/pychunkedgraph/tests/graph/test_meta.py index 7ca646a4f..784c3b839 100644 --- a/pychunkedgraph/tests/graph/test_meta.py +++ b/pychunkedgraph/tests/graph/test_meta.py @@ -28,6 +28,34 @@ def _meta(custom_data): return ChunkedGraphMeta(GraphConfig(ID="g"), DataSource(WATERSHED=OLD), custom_data) +def test_a_copy_keeps_its_sources_initial_meshes(infos): + meta = _meta({"mesh": {"dir": "graphene_meshes"}}).for_copied_graph("c") + assert meta.graph_config.ID == "c" + assert MeshMeta(meta).initial_path == f"{OLD}/graphene_meshes/initial" + + +def test_a_copy_reads_its_sources_dynamic_dir_and_writes_its_own(infos): + meta = _meta({"mesh": {"dir": "graphene_meshes"}}).for_copied_graph("c") + mm = MeshMeta(meta) + assert mm.dynamic_path == f"{OLD}/graphene_meshes/dynamic_c" + assert [one.path for one in mm.inherited] == [f"{OLD}/graphene_meshes/dynamic"] + + +def test_a_copy_of_a_copy_reads_both_sources_oldest_first(infos): + root = f"{OLD}/graphene_meshes" + meta = _meta({"mesh": {"dir": "graphene_meshes"}}) + mm = MeshMeta(meta.for_copied_graph("c").for_copied_graph("d")) + assert [one.path for one in mm.inherited] == [ + f"{root}/dynamic", + f"{root}/dynamic_c", + ] + assert mm.dynamic_path == f"{root}/dynamic_d" + + +def test_a_copy_without_meshes_keeps_its_custom_data(infos): + assert _meta({"other": 1}).for_copied_graph("c").custom_data == {"other": 1} + + def test_repoint_reads_the_new_watershed(infos): meta = _meta({}) assert meta.ws_info == {"at": OLD} diff --git a/pychunkedgraph/tests/meshing/test_manifest_dynamic.py b/pychunkedgraph/tests/meshing/test_manifest_dynamic.py new file mode 100644 index 000000000..dc8bfa979 --- /dev/null +++ b/pychunkedgraph/tests/meshing/test_manifest_dynamic.py @@ -0,0 +1,122 @@ +"""Tests for pychunkedgraph.meshing.manifest.dynamic, over real files in a copy's dirs.""" + +from pathlib import Path +from types import SimpleNamespace +from typing import NamedTuple + +import numpy as np +import pytest + +from pychunkedgraph.meshing.manifest import dynamic +from pychunkedgraph.meshing.manifest.dynamic import ( + dynamic_buckets, + hinted_rows, + probe_exists, + probe_read, + search_dynamic, +) + +#: Unix seconds of the copy's first open: a node made before it is the source's. +UNTIL = 100 + + +class Dirs(NamedTuple): + """A copy's watershed, its source's dynamic dir and its own, as cloud URLs.""" + + watershed: str + source: str + own: str + + +def _cg(watershed, mesh, created=None): + """A table stub; with ``created``, node id to Unix seconds, it reads timestamps.""" + meta = SimpleNamespace( + custom_data={"mesh": mesh}, + data_source=SimpleNamespace(WATERSHED=watershed), + ) + if created is None: + return SimpleNamespace(meta=meta) + + def get_node_timestamps(node_ids): + seconds = [created[int(i)] for i in node_ids] + return np.array(seconds, dtype="datetime64[s]").astype("datetime64[us]") + + return SimpleNamespace(meta=meta, get_node_timestamps=get_node_timestamps) + + +def _copy(dirs, created): + """A copy reading its source's dynamic dir for nodes made before ``UNTIL``.""" + layer = {"path": dirs.source, "until": UNTIL} + mesh = {"dir": "graphene_meshes", "inherited_dynamic": [layer]} + return _cg(dirs.watershed, mesh, created) + + +def _write(url, name, content=b"mesh"): + """A mesh file ``name`` in the local dir ``url`` names.""" + (Path(url.removeprefix("file://")) / name).write_bytes(content) + + +@pytest.fixture(autouse=True) +def _names(monkeypatch): + """File names from the node id alone; the chunk's box plays no part here.""" + monkeypatch.setattr( + dynamic, "get_mesh_name", lambda cg, node_id: f"{int(node_id)}:0:x" + ) + + +@pytest.fixture +def dirs(tmp_path): + source = tmp_path / "src" / "dynamic" + own = tmp_path / "ws" / "graphene_meshes" / "dynamic" + source.mkdir(parents=True) + own.mkdir(parents=True) + return Dirs(f"file://{tmp_path / 'ws'}", f"file://{source}", f"file://{own}") + + +class TestSearchDynamic: + def test_a_node_its_source_made_is_found_in_the_sources_dir(self, dirs): + _write(dirs.source, "5:0:x") + found = search_dynamic(_copy(dirs, {5: 99}), [5], probe_exists) + assert found[5].path == dirs.source + + def test_a_node_the_copy_made_is_found_in_its_own_dir(self, dirs): + _write(dirs.own, "6:0:x") + found = search_dynamic(_copy(dirs, {6: 101}), [6], probe_exists) + assert found[6].path == dirs.own + + def test_a_mesh_the_copy_wrote_for_a_source_made_node_is_found_in_its_own_dir( + self, dirs + ): + """The hint names the source, which lacks it, as after a remesh in the copy.""" + _write(dirs.own, "5:0:x") + found = search_dynamic(_copy(dirs, {5: 99}), [5], probe_exists) + assert found[5].path == dirs.own + + def test_a_node_in_no_dir_is_absent(self, dirs): + assert search_dynamic(_copy(dirs, {7: 99}), [7], probe_exists) == {} + + def test_a_read_returns_the_mesh_bytes(self, dirs): + _write(dirs.source, "5:0:x", b"draco") + found = search_dynamic(_copy(dirs, {5: 99}), [5], probe_read) + assert found[5].value == b"draco" + + def test_a_table_without_inherited_dirs_reads_no_timestamp(self, dirs): + """The stub has no timestamp reader, so reading one would raise.""" + _write(dirs.own, "6:0:x") + cg = _cg(dirs.watershed, {"dir": "graphene_meshes"}) + assert search_dynamic(cg, [6], probe_exists)[6].path == dirs.own + + +class TestRows: + def test_a_speculative_row_names_the_sources_dir_for_a_node_it_made(self, dirs): + rows = hinted_rows(_copy(dirs, {5: 99, 6: 101}), [5, 6]) + assert rows == [f"{dirs.source}/5:0:x", "6:0:x"] + + def test_a_row_lands_in_the_dir_it_names_and_a_bare_one_in_the_tables_own( + self, dirs + ): + buckets = dynamic_buckets(_copy(dirs, {}), [f"{dirs.source}/5:0:x", "6:0:x"]) + assert buckets == {dirs.source: ["5:0:x"], dirs.own: ["6:0:x"]} + + def test_no_rows_have_no_buckets(self, dirs): + assert dynamic_buckets(_copy(dirs, {}), []) == {} diff --git a/pychunkedgraph/tests/meshing/test_manifest_v2.py b/pychunkedgraph/tests/meshing/test_manifest_v2.py index 3f048540e..bf4d39ce0 100644 --- a/pychunkedgraph/tests/meshing/test_manifest_v2.py +++ b/pychunkedgraph/tests/meshing/test_manifest_v2.py @@ -53,12 +53,20 @@ def test_a_speculative_row_keeps_one_seg_id_and_drops_the_shard_extension(self): def test_assemble_maps_each_bucket_to_its_list(self): """A bucket maps straight to its fragments; metadata sits at the top level.""" resp = assemble( - "gs://b/initial", "gs://b/dynamic", ["386:a.shard:1:2"], ["529:0:y"] + "gs://b/initial", ["386:a.shard:1:2"], {"gs://b/dynamic": ["529:0:y"]} ) assert resp["fragments"]["gs://b/initial"] == ["386:a.shard:1:2"] assert resp["fragments"]["gs://b/dynamic"] == ["529:0:y"] assert resp["manifest_version"] == 2 + def test_assemble_keeps_each_dynamic_dir_under_its_own_bucket(self): + """A copy's rows from its source's dir stay apart from its own.""" + dynamic = {"gs://src/dynamic": ["529:0:y"], "gs://b/dynamic": ["530:0:z"]} + resp = assemble("gs://b/initial", [], dynamic) + assert resp["fragments"]["gs://src/dynamic"] == ["529:0:y"] + assert resp["fragments"]["gs://b/dynamic"] == ["530:0:z"] + def test_assemble_omits_a_group_with_no_fragments(self): - resp = assemble("gs://b/initial", "gs://b/dynamic", [], ["529:0:y"]) + dynamic = {"gs://src/dynamic": [], "gs://b/dynamic": ["529:0:y"]} + resp = assemble("gs://b/initial", [], dynamic) assert list(resp["fragments"]) == ["gs://b/dynamic"] diff --git a/pychunkedgraph/tests/meshing/test_mesh_meta.py b/pychunkedgraph/tests/meshing/test_mesh_meta.py index f0c7e422b..e40265dba 100644 --- a/pychunkedgraph/tests/meshing/test_mesh_meta.py +++ b/pychunkedgraph/tests/meshing/test_mesh_meta.py @@ -3,6 +3,8 @@ import posixpath from types import SimpleNamespace +import numpy as np + from pychunkedgraph.meshing.mesh_meta import MeshMeta @@ -14,6 +16,57 @@ def _cg(watershed, mesh): return SimpleNamespace(meta=meta) +def _created(*seconds): + return np.array([np.datetime64(one, "s") for one in seconds], dtype="datetime64[s]") + + +class TestByDynamicDir: + """New node is read from dir its creation time falls in; each dir grouped once.""" + + SOURCE = "gs://src/graphene_meshes/dynamic" + COPY = { + "dir": "graphene_meshes", + "inherited_dynamic": [{"path": SOURCE, "until": 100}], + } + + def test_a_table_without_layers_reads_every_node_from_its_own_dir(self): + mm = MeshMeta(_cg("gs://ws/seg", {"dir": "graphene_meshes"})) + groups = mm.by_dynamic_dir([5, 6], _created(1, 2)) + assert list(groups) == [mm.dynamic_path] + assert list(groups[mm.dynamic_path]) == [5, 6] + + def test_a_copy_reads_nodes_its_source_made_from_the_source(self): + mm = MeshMeta(_cg("gs://ws/seg", self.COPY)) + groups = mm.by_dynamic_dir([5, 6, 7], _created(99, 100, 101)) + assert list(groups[self.SOURCE]) == [5] + assert list(groups[mm.dynamic_path]) == [6, 7] + + def test_a_copy_of_a_copy_reads_each_node_from_the_table_that_made_it(self): + older = "gs://src/graphene_meshes/dynamic_a" + layers = [{"path": older, "until": 100}, {"path": self.SOURCE, "until": 200}] + mesh = {"dir": "graphene_meshes", "inherited_dynamic": layers} + mm = MeshMeta(_cg("gs://ws/seg", mesh)) + groups = mm.by_dynamic_dir([5, 6, 7], _created(99, 150, 200)) + assert list(groups[older]) == [5] + assert list(groups[self.SOURCE]) == [6] + assert list(groups[mm.dynamic_path]) == [7] + + def test_a_miss_searches_the_own_dir_then_inherited_dirs_newest_first(self): + older = "gs://src/graphene_meshes/dynamic_a" + layers = [{"path": older, "until": 100}, {"path": self.SOURCE, "until": 200}] + mesh = {"dir": "graphene_meshes", "inherited_dynamic": layers} + mm = MeshMeta(_cg("gs://ws/seg", mesh)) + assert mm.dynamic_stack == (mm.dynamic_path, self.SOURCE, older) + + def test_no_nodes_group_to_nothing(self): + """A copy given no nodes reads no creation times, as its caller passes none.""" + mm = MeshMeta(_cg("gs://ws/seg", self.COPY)) + assert mm.by_dynamic_dir([], None) == {} + + def test_a_copy_needs_v2(self): + assert MeshMeta(_cg("gs://ws/seg", self.COPY)).needs_v2 is True + + class TestReaderAnchor: """reader_anchor must recompose to initial_path via cloud-volume's hardcoded ``initial`` subdir, so the verified shard reader reads the real bucket.""" From ef159f4061e81498e43fe311b0fbde8a639e4a74 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Tue, 17 Nov 2026 03:26:22 +0000 Subject: [PATCH 10/11] fix(meshing): search a copy's misses only where the node can be - A copy's restored id counters reuse its source's ids, so an older dir may hold another node's mesh. - A miss now searches the own dir and the inherited dirs newer than the hint. - The copy's block is built beside its layer record, and its dir name has one home. Co-Authored-By: Claude --- pychunkedgraph/graph/meta.py | 20 +++--------- pychunkedgraph/meshing/manifest/dynamic.py | 16 ++++++---- pychunkedgraph/meshing/mesh_meta/README.md | 18 ++++++++--- pychunkedgraph/meshing/mesh_meta/__init__.py | 4 +-- pychunkedgraph/meshing/mesh_meta/core.py | 31 ++++++++++++++++++- pychunkedgraph/pipeline/meshing/meta.py | 4 ++- pychunkedgraph/tests/graph/test_meta.py | 20 +++++++++--- .../tests/meshing/test_manifest_dynamic.py | 25 +++++++++++++++ .../tests/meshing/test_mesh_meta.py | 18 +++++++++++ 9 files changed, 122 insertions(+), 34 deletions(-) diff --git a/pychunkedgraph/graph/meta.py b/pychunkedgraph/graph/meta.py index 9c875d4c4..ce3b49585 100644 --- a/pychunkedgraph/graph/meta.py +++ b/pychunkedgraph/graph/meta.py @@ -1,4 +1,3 @@ -import time from datetime import timedelta from typing import Dict from typing import List @@ -11,7 +10,7 @@ from .utils.generic import compute_bitmasks from .chunks.utils import get_chunks_boundary -from ..meshing.mesh_meta import INHERITED, MeshMeta +from ..meshing.mesh_meta import MeshMeta #: TEMPORARY, revert before merge: tables a test cluster serves from another watershed, #: repointed in memory each time their stored meta loads. @@ -83,22 +82,13 @@ def custom_data(self): return self._custom_data def for_copied_graph(self, graph_id: str) -> "ChunkedGraphMeta": - """Rewrite this meta for a table copied under ``graph_id``: its id, and a mesh - block keeping the source's meshes, reading the source's dynamic dir for nodes - made before now while writing its own. Returns self, for ``update_meta``.""" + """Rewrite this meta for a table copied under ``graph_id``: its id, and the mesh + block ``MeshMeta.copied_block`` gives it. Returns self, for ``update_meta``.""" gc = self._graph_config._asdict() gc["ID"] = graph_id self._graph_config = GraphConfig(**gc) - mesh = self._custom_data.get("mesh") - if not mesh or "dir" not in mesh: - return self - source = MeshMeta(self) - layer = {"path": source.dynamic_path, "until": int(time.time())} - block = {**source.pinned_block, "dynamic_mesh_dir": f"dynamic_{graph_id}"} - block[INHERITED] = [*mesh.get(INHERITED, ()), layer] - self._custom_data["mesh"] = block - # Pinned again, so the copy's own dir is absolute and a setup re-run keeps it. - self._custom_data["mesh"] = MeshMeta(self).pinned_block + if "mesh" in self._custom_data: + self._custom_data["mesh"] = MeshMeta(self).copied_block(graph_id) return self def repoint_watershed(self, watershed: str) -> "ChunkedGraphMeta": diff --git a/pychunkedgraph/meshing/manifest/dynamic.py b/pychunkedgraph/meshing/manifest/dynamic.py index e84083fc7..a45262f52 100644 --- a/pychunkedgraph/meshing/manifest/dynamic.py +++ b/pychunkedgraph/meshing/manifest/dynamic.py @@ -1,7 +1,8 @@ """Where a dynamic mesh lives, across a table's own dynamic dir and the dirs it inherits. A node's creation time hints at its dir; a probe checks the hint, and a miss searches the -rest of the stack, own dir first, so a table finds every mesh it wrote whatever the hint says. +other dirs that can hold the node, own dir first, so a table finds every mesh it wrote +whatever the hint says, and never another node's under a reused id. """ import posixpath @@ -28,8 +29,8 @@ class Found(NamedTuple): def dynamic_groups(cg, new_ids) -> Dict[str, np.ndarray]: - """``new_ids`` grouped by the dynamic dir their creation time hints at; node timestamps - are read only for a copy, the one table with inherited dirs.""" + """``new_ids`` grouped by the dynamic dir their creation time hints at; node + timestamps are read only for a copy, the one table with inherited dirs.""" mm = MeshMeta(cg) new_ids = np.asarray(new_ids, dtype=NODE_ID) created = cg.get_node_timestamps(new_ids) if mm.inherited and new_ids.size else None @@ -59,8 +60,10 @@ def probe_read(path: str, names: List[str]) -> Dict[str, Optional[bytes]]: def search_dynamic(cg, new_ids, probe: Probe) -> Dict[int, Found]: """Each new node's dynamic mesh, probed first in its creation-time dir, then on a - miss in each other dir of ``dynamic_stack`` once, in order; a node in none is absent. + miss in each of that hint's ``fallback_dirs``, each dir probed once, in + ``dynamic_stack`` order; a node in none is absent. """ + mm = MeshMeta(cg) names = {int(i): get_mesh_name(cg, i) for i in new_ids} hint, found = {}, {} @@ -73,8 +76,9 @@ def run(path: str, ids: List[int]) -> None: for path, ids in dynamic_groups(cg, list(names)).items(): hint.update({int(i): path for i in ids}) run(path, [int(i) for i in ids]) - for path in MeshMeta(cg).dynamic_stack: - rest = [i for i in names if i not in found and hint[i] != path] + fallbacks = {path: mm.fallback_dirs(path) for path in set(hint.values())} + for path in mm.dynamic_stack: + rest = [i for i in names if i not in found and path in fallbacks[hint[i]]] if rest: run(path, rest) return found diff --git a/pychunkedgraph/meshing/mesh_meta/README.md b/pychunkedgraph/meshing/mesh_meta/README.md index c9ad2e288..3af2cca30 100644 --- a/pychunkedgraph/meshing/mesh_meta/README.md +++ b/pychunkedgraph/meshing/mesh_meta/README.md @@ -40,8 +40,8 @@ All read from `custom_data["mesh"]`: - `inherited_dynamic` — a copy's sources' dynamic dirs, oldest first, each `{"path", "until"}`: an absolute dir, and the Unix second of the copy's first open, before which its source made a node. Only a copy's first open writes it, - through `ChunkedGraphMeta.for_copied_graph`; any other table has none and reads - as before. + storing `copied_block` through `ChunkedGraphMeta.for_copied_graph`; any other + table has none and reads as before. - `max_layer`, `mip`, `max_error` — mesh params (start layer for manifests, and the mip / max-error used by remeshing). - `uniform_draco_grid_size` — the draco grid clients deduplicate on, written by setup. @@ -73,15 +73,23 @@ upstream; this module only reads the result. - `dynamic_stack` → every dynamic dir a node's mesh may be in, the table's own first, then inherited dirs newest first: the order a missed lookup searches. - `by_dynamic_dir(node_ids, created)` → new node ids grouped by the dynamic dir their - creation times hint at. `manifest/dynamic.py` checks each hint with a probe and - searches `dynamic_stack` on a miss, so a copy finds every mesh it or its sources - wrote. + creation times hint at. `manifest/dynamic.py` checks each hint with a probe and, + on a miss, searches the hint's `fallback_dirs`, so a copy finds every mesh it or + its sources wrote for a node, and never another node's under a reused id. +- `fallback_dirs(hint)` → the dirs a node hinted at `hint` may also be in: the + table's own, then inherited dirs newer than `hint`. An older dir's source never + had the node, and its id counter may have given that id to a node of its own. - `spec_dir` → the dir of the shard spec `info`, the parent of `initial_path`. - `dir` → the sharded mesh dir name under the watershed. - `dynamic_mesh_dir` → the dynamic dir as configured, a name or a cloud URL. - `client_metadata` → the graphene info's `mesh_metadata` for this table. - `pinned_block` → the block with both dirs absolute and its grid keys written in, so it reads the same under any watershed; `ChunkedGraphMeta.repoint_watershed` stores it. +- `copied_block(graph_id)` → the pinned block a copy under `graph_id` stores, its own + dynamic dir `dynamic_dir_name(graph_id)`, this table's appended to + `inherited_dynamic`; `ChunkedGraphMeta.for_copied_graph` stores it. +- `dynamic_dir_name(graph_id)`, a module function → `dynamic_`, a graph's own + dynamic dir name: setup's default, and a copy's. - `max_layer`, `mip`, `max_error`, `initial_ts` → the mesh params. - `needs_v2` → true when either location falls **outside** the watershed dir, or the table inherits dynamic dirs, i.e. meshes are not all co-located with the diff --git a/pychunkedgraph/meshing/mesh_meta/__init__.py b/pychunkedgraph/meshing/mesh_meta/__init__.py index 1f0b1d4cc..2d91eaf86 100644 --- a/pychunkedgraph/meshing/mesh_meta/__init__.py +++ b/pychunkedgraph/meshing/mesh_meta/__init__.py @@ -1,5 +1,5 @@ """Branch-agnostic graphene mesh metadata. See README.md.""" -from .core import INHERITED, MeshMeta, is_absolute +from .core import MeshMeta, dynamic_dir_name, is_absolute -__all__ = ["INHERITED", "MeshMeta", "is_absolute"] +__all__ = ["MeshMeta", "dynamic_dir_name", "is_absolute"] diff --git a/pychunkedgraph/meshing/mesh_meta/core.py b/pychunkedgraph/meshing/mesh_meta/core.py index 18f559139..320b4d491 100644 --- a/pychunkedgraph/meshing/mesh_meta/core.py +++ b/pychunkedgraph/meshing/mesh_meta/core.py @@ -4,6 +4,7 @@ """ import posixpath +import time from typing import NamedTuple import numpy as np @@ -28,6 +29,11 @@ def _resolve(root: str, value: str) -> str: return value.rstrip("/") if is_absolute(value) else posixpath.join(root, value) +def dynamic_dir_name(graph_id: str) -> str: + """A graph's own dynamic dir name: setup's default, and a copy's.""" + return f"dynamic_{graph_id}" + + #: The block key a copy's rewrite fills: its sources' dynamic dirs, oldest first. INHERITED = "inherited_dynamic" @@ -36,7 +42,8 @@ class Layer(NamedTuple): """A source's dynamic dir, holding the meshes of nodes made before ``until``.""" path: str - #: Unix seconds: the copy's first open, before which the source made the node. + #: Unix seconds of the copy's first open: of the copy's nodes, the source made every + #: older one and no newer one, while the opener's clock agrees with node timestamps. until: int @@ -88,6 +95,15 @@ def dynamic_stack(self) -> tuple[str, ...]: the table's own first, then inherited dirs newest first.""" return (self.dynamic_path, *(one.path for one in reversed(self.inherited))) + def fallback_dirs(self, hint: str) -> tuple[str, ...]: + """Dirs a node hinted at ``hint`` may also be in, in search order: the table's + own, then inherited dirs newer than ``hint``. An older dir's source never had + the node, and its id counter may have given that id to a node of its own.""" + if hint == self.dynamic_path: + return () + paths = [one.path for one in self.inherited] + return self.dynamic_stack[: len(paths) - paths.index(hint)] + def by_dynamic_dir(self, node_ids, created) -> dict[str, np.ndarray]: """New node ids grouped by the dynamic dir their creation time hints at, each dir once: the first inherited dir a node's ``created`` (datetime64) predates, else @@ -140,6 +156,19 @@ def pinned_block(self) -> dict[str, object]: "dynamic_mesh_dir": self.dynamic_path, } + def copied_block(self, graph_id: str) -> dict[str, object]: + """The block a copy under ``graph_id`` stores: this table's meshes pinned, a + dynamic dir of its own, and this table's dynamic dir inherited for the nodes + made before now. A block without ``dir`` is copied as it is.""" + if "dir" not in self._mesh: + return dict(self._mesh) + layer = Layer(self.dynamic_path, int(time.time()))._asdict() + return { + **self.pinned_block, + "dynamic_mesh_dir": _resolve(self._root, dynamic_dir_name(graph_id)), + INHERITED: [*self._mesh.get(INHERITED, ()), layer], + } + @property def needs_v2(self) -> bool: """True when meshes live outside the watershed dir, or across inherited dynamic diff --git a/pychunkedgraph/pipeline/meshing/meta.py b/pychunkedgraph/pipeline/meshing/meta.py index fe9052a5e..347ef4921 100644 --- a/pychunkedgraph/pipeline/meshing/meta.py +++ b/pychunkedgraph/pipeline/meshing/meta.py @@ -22,6 +22,8 @@ from dataclasses import asdict, dataclass, replace from typing import Dict, Optional +from ...meshing.mesh_meta import dynamic_dir_name + @dataclass class MeshConfig: @@ -59,7 +61,7 @@ def with_graph_id(self, graph_id: str) -> "MeshConfig": """Return a copy with ``dynamic_mesh_dir`` filled in if unset.""" if self.dynamic_mesh_dir is not None: return self - return replace(self, dynamic_mesh_dir=f"dynamic_{graph_id}") + return replace(self, dynamic_mesh_dir=dynamic_dir_name(graph_id)) def to_dict(self) -> Dict: return asdict(self) diff --git a/pychunkedgraph/tests/graph/test_meta.py b/pychunkedgraph/tests/graph/test_meta.py index 784c3b839..87bb5fe11 100644 --- a/pychunkedgraph/tests/graph/test_meta.py +++ b/pychunkedgraph/tests/graph/test_meta.py @@ -1,6 +1,7 @@ """Tests for pychunkedgraph.graph.meta.ChunkedGraphMeta.repoint_watershed.""" import pickle +import time import pytest @@ -34,11 +35,20 @@ def test_a_copy_keeps_its_sources_initial_meshes(infos): assert MeshMeta(meta).initial_path == f"{OLD}/graphene_meshes/initial" -def test_a_copy_reads_its_sources_dynamic_dir_and_writes_its_own(infos): +def test_a_copy_reads_its_sources_dynamic_dir_and_writes_its_own(infos, monkeypatch): + monkeypatch.setattr(time, "time", lambda: 1234.5) meta = _meta({"mesh": {"dir": "graphene_meshes"}}).for_copied_graph("c") mm = MeshMeta(meta) assert mm.dynamic_path == f"{OLD}/graphene_meshes/dynamic_c" - assert [one.path for one in mm.inherited] == [f"{OLD}/graphene_meshes/dynamic"] + assert [(one.path, one.until) for one in mm.inherited] == [ + (f"{OLD}/graphene_meshes/dynamic", 1234) + ] + + +def test_a_copy_stores_its_own_dir_absolute(infos): + meta = _meta({"mesh": {"dir": "graphene_meshes"}}).for_copied_graph("c") + own = f"{OLD}/graphene_meshes/dynamic_c" + assert meta.custom_data["mesh"]["dynamic_mesh_dir"] == own def test_a_copy_of_a_copy_reads_both_sources_oldest_first(infos): @@ -52,8 +62,10 @@ def test_a_copy_of_a_copy_reads_both_sources_oldest_first(infos): assert mm.dynamic_path == f"{root}/dynamic_d" -def test_a_copy_without_meshes_keeps_its_custom_data(infos): - assert _meta({"other": 1}).for_copied_graph("c").custom_data == {"other": 1} +@pytest.mark.parametrize("custom_data", [{"other": 1}, {"mesh": {"mip": 2}}]) +def test_a_copy_of_a_table_without_meshes_keeps_its_custom_data(infos, custom_data): + meta = _meta(dict(custom_data)).for_copied_graph("c") + assert meta.custom_data == custom_data def test_repoint_reads_the_new_watershed(infos): diff --git a/pychunkedgraph/tests/meshing/test_manifest_dynamic.py b/pychunkedgraph/tests/meshing/test_manifest_dynamic.py index dc8bfa979..0a2fb41df 100644 --- a/pychunkedgraph/tests/meshing/test_manifest_dynamic.py +++ b/pychunkedgraph/tests/meshing/test_manifest_dynamic.py @@ -95,6 +95,31 @@ def test_a_mesh_the_copy_wrote_for_a_source_made_node_is_found_in_its_own_dir( def test_a_node_in_no_dir_is_absent(self, dirs): assert search_dynamic(_copy(dirs, {7: 99}), [7], probe_exists) == {} + def test_a_node_the_copy_made_never_takes_its_sources_mesh_of_its_id(self, dirs): + """The restored id counter gave the source's own later node this id too.""" + _write(dirs.source, "8:0:x") + assert search_dynamic(_copy(dirs, {8: 101}), [8], probe_exists) == {} + + def test_a_copy_of_a_copy_searches_only_dirs_newer_than_the_hint( + self, dirs, tmp_path + ): + """Nodes 4 and 5, the first source's, sit where this copy and the middle one + remeshed them; the middle copy's node 9 is never read from the first source.""" + middle = tmp_path / "mid" / "dynamic" + middle.mkdir(parents=True) + layers = [ + {"path": dirs.source, "until": UNTIL}, + {"path": f"file://{middle}", "until": 2 * UNTIL}, + ] + mesh = {"dir": "graphene_meshes", "inherited_dynamic": layers} + cg = _cg(dirs.watershed, mesh, {4: UNTIL - 1, 5: UNTIL - 1, 9: UNTIL + 1}) + _write(dirs.own, "4:0:x") + _write(f"file://{middle}", "5:0:x") + _write(dirs.source, "9:0:x") + found = search_dynamic(cg, [4, 5, 9], probe_exists) + paths = {i: hit.path for i, hit in found.items()} + assert paths == {4: dirs.own, 5: f"file://{middle}"} + def test_a_read_returns_the_mesh_bytes(self, dirs): _write(dirs.source, "5:0:x", b"draco") found = search_dynamic(_copy(dirs, {5: 99}), [5], probe_read) diff --git a/pychunkedgraph/tests/meshing/test_mesh_meta.py b/pychunkedgraph/tests/meshing/test_mesh_meta.py index e40265dba..abc06eec7 100644 --- a/pychunkedgraph/tests/meshing/test_mesh_meta.py +++ b/pychunkedgraph/tests/meshing/test_mesh_meta.py @@ -4,6 +4,7 @@ from types import SimpleNamespace import numpy as np +import pytest from pychunkedgraph.meshing.mesh_meta import MeshMeta @@ -58,6 +59,23 @@ def test_a_miss_searches_the_own_dir_then_inherited_dirs_newest_first(self): mm = MeshMeta(_cg("gs://ws/seg", mesh)) assert mm.dynamic_stack == (mm.dynamic_path, self.SOURCE, older) + def test_a_miss_searches_only_dirs_newer_than_its_hint(self): + """An older dir's source never had the node, and may have given its id away.""" + oldest, middle = "gs://src/meshes/dynamic_a", "gs://src/meshes/dynamic_b" + layers = [ + {"path": oldest, "until": 100}, + {"path": middle, "until": 200}, + {"path": self.SOURCE, "until": 300}, + ] + mesh = {"dir": "graphene_meshes", "inherited_dynamic": layers} + mm = MeshMeta(_cg("gs://ws/seg", mesh)) + own = mm.dynamic_path + assert mm.fallback_dirs(oldest) == (own, self.SOURCE, middle) + assert mm.fallback_dirs(self.SOURCE) == (own,) + assert mm.fallback_dirs(own) == () + with pytest.raises(ValueError): + mm.fallback_dirs("gs://elsewhere/dynamic") + def test_no_nodes_group_to_nothing(self): """A copy given no nodes reads no creation times, as its caller passes none.""" mm = MeshMeta(_cg("gs://ws/seg", self.COPY)) From 6c4c4c5fa0ad88666f8e6210c8a53be85bb8df3a Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Thu, 19 Nov 2026 01:52:57 +0000 Subject: [PATCH 11/11] fix(meshing): publish a repointed table's dynamic dir by name - Publish the dynamic dir relative to the mesh root when it lies there. - Share one whole-segment test of the mesh root with `needs_v2`. - Refuse v1 for a sibling dir that only shares the root's prefix. Co-Authored-By: Claude --- pychunkedgraph/app/segmentation/common.py | 2 +- pychunkedgraph/meshing/mesh_meta/core.py | 21 ++++++++-- pychunkedgraph/meshing/meshgen_utils.py | 4 +- pychunkedgraph/tests/graph/test_meta.py | 12 ++++++ .../tests/meshing/test_mesh_meta.py | 40 +++++++++++++++++++ 5 files changed, 72 insertions(+), 7 deletions(-) diff --git a/pychunkedgraph/app/segmentation/common.py b/pychunkedgraph/app/segmentation/common.py index c19fb6bc2..035359ac3 100644 --- a/pychunkedgraph/app/segmentation/common.py +++ b/pychunkedgraph/app/segmentation/common.py @@ -111,7 +111,7 @@ def handle_info(table_id): if cg.meta.custom_data.get("mesh", {}).get("dir") is not None: mm = MeshMeta(cg) combined_info["mesh_dir"] = mm.dir - combined_info["dynamic_mesh_dir"] = mm.dynamic_mesh_dir + combined_info["dynamic_mesh_dir"] = mm.client_dynamic_dir combined_info["mesh_metadata"] = mm.client_metadata return jsonify(combined_info) diff --git a/pychunkedgraph/meshing/mesh_meta/core.py b/pychunkedgraph/meshing/mesh_meta/core.py index 320b4d491..f3b38a57f 100644 --- a/pychunkedgraph/meshing/mesh_meta/core.py +++ b/pychunkedgraph/meshing/mesh_meta/core.py @@ -64,7 +64,7 @@ def dir(self) -> str: @property def _root(self) -> str: - return posixpath.join(self._watershed, self.dir) + return posixpath.join(self._watershed, self.dir).rstrip("/") @property def initial_path(self) -> str: @@ -81,6 +81,20 @@ def dynamic_path(self) -> str: """Absolute dir of the per-graph dynamic (unsharded) meshes.""" return _resolve(self._root, self.dynamic_mesh_dir) + def _under_root(self, path: str) -> bool: + """Whether ``path`` is ``/`` or lies under it, by whole segments, + so a sibling sharing its prefix, such as ``_v2``, does not.""" + return path == self._root or path.startswith(f"{self._root}/") + + @property + def client_dynamic_dir(self) -> str: + """The dynamic dir as v1 clients join it under ``/``: relative + when it lies there, a repoint's pinned URL included, else its URL.""" + path = self.dynamic_path + if not self._under_root(path): + return path + return path.removeprefix(self._root).lstrip("/") + @property def inherited(self) -> tuple[Layer, ...]: """Dynamic dirs inherited as a copy, oldest first; none for any other table.""" @@ -138,7 +152,7 @@ def client_metadata(self) -> dict[str, object]: ``unsharded_mesh_dir``, and a v2 client reads the two absolute paths.""" return { **self._grid_keys, - "unsharded_mesh_dir": self.dynamic_mesh_dir, + "unsharded_mesh_dir": self.client_dynamic_dir, "initial_mesh_path": self.initial_path, "dynamic_mesh_path": self.dynamic_path, } @@ -173,9 +187,8 @@ def copied_block(self, graph_id: str) -> dict[str, object]: def needs_v2(self) -> bool: """True when meshes live outside the watershed dir, or across inherited dynamic dirs: old clients reach neither.""" - root = self._root return bool(self.inherited) or not ( - self.initial_path.startswith(root) and self.dynamic_path.startswith(root) + self._under_root(self.initial_path) and self._under_root(self.dynamic_path) ) @property diff --git a/pychunkedgraph/meshing/meshgen_utils.py b/pychunkedgraph/meshing/meshgen_utils.py index 2c54baa8c..f23a24723 100644 --- a/pychunkedgraph/meshing/meshgen_utils.py +++ b/pychunkedgraph/meshing/meshgen_utils.py @@ -148,7 +148,7 @@ def get_json_info(cg): info = {**dataset_info, **dummy_app_info} mm = MeshMeta(cg) info["mesh"] = mm.dir - info["dynamic_mesh_dir"] = mm.dynamic_mesh_dir + info["dynamic_mesh_dir"] = mm.client_dynamic_dir info["mesh_metadata"] = mm.client_metadata info_str = dumps(info) return loads(info_str) @@ -159,7 +159,7 @@ def get_ws_seg_for_chunk(cg, chunk_id, mip, overlap_vx=1): mip_diff = mip - cg.meta.cv.mip mip_chunk_size = np.array(cg.meta.graph_config.CHUNK_SIZE, dtype=int) / np.array( - [2 ** mip_diff, 2 ** mip_diff, 1] + [2**mip_diff, 2**mip_diff, 1] ) mip_chunk_size = mip_chunk_size.astype(int) diff --git a/pychunkedgraph/tests/graph/test_meta.py b/pychunkedgraph/tests/graph/test_meta.py index 87bb5fe11..991fa452e 100644 --- a/pychunkedgraph/tests/graph/test_meta.py +++ b/pychunkedgraph/tests/graph/test_meta.py @@ -93,6 +93,18 @@ def test_repoint_keeps_the_old_watershed_grid_keys(infos): assert client["max_meshed_layer"] == 5 +def test_a_table_repointed_away_and_back_publishes_its_dynamic_dir_by_name(infos): + meta = _meta({"mesh": {"dir": "graphene_meshes", "dynamic_mesh_dir": "dynamic_g"}}) + meta.repoint_watershed(NEW).repoint_watershed(OLD) + assert MeshMeta(meta).client_metadata["unsharded_mesh_dir"] == "dynamic_g" + + +def test_a_moved_table_publishes_its_dynamic_dir_url(infos): + meta = _meta({"mesh": {"dir": "graphene_meshes"}}).repoint_watershed(NEW) + published = MeshMeta(meta).client_metadata["unsharded_mesh_dir"] + assert published == f"{OLD}/graphene_meshes/dynamic" + + @pytest.mark.parametrize("custom_data", [{"READ_ONLY": True}, {"mesh": {"mip": 2}}]) def test_repoint_of_a_table_without_meshes_keeps_its_custom_data(infos, custom_data): meta = _meta(dict(custom_data)).repoint_watershed(NEW) diff --git a/pychunkedgraph/tests/meshing/test_mesh_meta.py b/pychunkedgraph/tests/meshing/test_mesh_meta.py index abc06eec7..fcf03306a 100644 --- a/pychunkedgraph/tests/meshing/test_mesh_meta.py +++ b/pychunkedgraph/tests/meshing/test_mesh_meta.py @@ -117,3 +117,43 @@ def test_watershed_elsewhere_keeps_spec_beside_initial(self): } mm = MeshMeta(_cg("gs://cheap/seg", mesh)) assert mm.spec_dir == "gs://old/graphene_meshes" + + +class TestClientDynamicDir: + """v1 clients join the published dynamic dir under ``/``.""" + + @pytest.mark.parametrize( + "mesh_dir, dynamic, published", + [ + ("graphene_meshes", "dynamic_g", "dynamic_g"), + ("graphene_meshes/", "dynamic_g", "dynamic_g"), + ("graphene_meshes", "gs://ws/seg/graphene_meshes/dynamic_g", "dynamic_g"), + ("graphene_meshes", "gs://ws/seg/graphene_meshes", ""), + ( + "graphene_meshes", + "gs://ws/seg/graphene_meshes_v2/dynamic", + "gs://ws/seg/graphene_meshes_v2/dynamic", + ), + ], + ) + def test_a_dir_under_the_root_is_published_by_name_any_other_by_url( + self, mesh_dir, dynamic, published + ): + mesh = {"dir": mesh_dir, "dynamic_mesh_dir": dynamic} + assert MeshMeta(_cg("gs://ws/seg", mesh)).client_dynamic_dir == published + + +class TestNeedsV2: + """v1 clients join every row under ``/``, so a dir anywhere else, + a sibling sharing the root's prefix included, needs v2.""" + + @pytest.mark.parametrize( + "key, path", + [ + ("initial_mesh_dir", "gs://ws/seg/graphene_meshes_v2/initial"), + ("dynamic_mesh_dir", "gs://ws/seg/graphene_meshes_v2/dynamic"), + ], + ) + def test_a_sibling_sharing_the_roots_prefix_needs_v2(self, key, path): + mesh = {"dir": "graphene_meshes", key: path} + assert MeshMeta(_cg("gs://ws/seg", mesh)).needs_v2 is True