From 006a3cf72a0a055251f640414f7911af15a52323 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Sat, 31 Oct 2026 20:32:20 +0000 Subject: [PATCH 01/11] refactor(edit): fold execute's failure handling into one helper - `GraphEditOperation._raise_failure` clears the cache, records and re-raises by kind, as the four except blocks did. - Pre-commit's black moves to 26.10.1. Co-Authored-By: Claude --- .pre-commit-config.yaml | 2 +- pychunkedgraph/graph/operation.py | 79 +++++++++++++------------------ 2 files changed, 35 insertions(+), 46 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70ceaed90..2545c7734 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,5 +1,5 @@ repos: - repo: https://github.com/psf/black - rev: 26.1.0 + rev: 26.10.1 hooks: - id: black diff --git a/pychunkedgraph/graph/operation.py b/pychunkedgraph/graph/operation.py index d226b2eef..8930ea374 100644 --- a/pychunkedgraph/graph/operation.py +++ b/pychunkedgraph/graph/operation.py @@ -11,6 +11,7 @@ from typing import Tuple from typing import Union from typing import Any +from typing import NoReturn from typing import Optional from typing import Sequence from functools import reduce @@ -452,20 +453,20 @@ def execute( ) if timestamp is None: timestamp = get_valid_timestamp(timestamp) + operation_ts = override_ts if override_ts else timestamp log_record_before_edit = self._create_log_record( operation_id=lock.operation_id, new_root_ids=types.empty_1d, timestamp=timestamp, - operation_ts=override_ts if override_ts else timestamp, + operation_ts=operation_ts, status=attributes.OperationLogs.StatusCodes.CREATED.value, ) self._persist_rows([log_record_before_edit]) try: new_root_ids, new_lvl2_ids, affected_records = self._apply( - operation_id=lock.operation_id, - timestamp=override_ts if override_ts else timestamp, + operation_id=lock.operation_id, timestamp=operation_ts ) if is_dry_run(): # return without persisting changes @@ -475,52 +476,12 @@ def execute( new_lvl2_ids=new_lvl2_ids, old_root_ids=root_ids, ) - except PreconditionError as err: - self.cg.cache = None - raise PreconditionError(err) from err - except PostconditionError as err: - self.cg.cache = None - raise PostconditionError(err) from err - except (AssertionError, RuntimeError) as err: - self.cg.cache = None - dump_url = err_dump.dump_err_artifact( - self.cg, - lock.operation_id, - err_dump.build_err_payload(self, lock.operation_id, err), - ) - logger.error( - f"<{lock.operation_id}> {type(self).__name__} failed: " - f"{type(err).__name__}: {err}" - f"{err_dump.payload_summary(self)} dump={dump_url}" - ) - raise RuntimeError(err) from err except Exception as err: - # unknown exception, update log record with error - self.cg.cache = None - dump_url = err_dump.dump_err_artifact( - self.cg, - lock.operation_id, - err_dump.build_err_payload(self, lock.operation_id, err), - ) - logger.error( - f"<{lock.operation_id}> {type(self).__name__} failed: " - f"{type(err).__name__}: {err}" - f"{err_dump.payload_summary(self)} dump={dump_url}" - ) - log_record_error = self._create_log_record( - operation_id=lock.operation_id, - new_root_ids=types.empty_1d, - timestamp=None, - operation_ts=override_ts if override_ts else timestamp, - status=attributes.OperationLogs.StatusCodes.EXCEPTION.value, - exception=repr(err), - ) - self._persist_rows([log_record_error]) - raise Exception(err) from err + self._raise_failure(err, lock.operation_id, operation_ts) result = self._write( lock, - override_ts if override_ts else timestamp, + operation_ts, new_root_ids, new_lvl2_ids, affected_records, @@ -592,6 +553,34 @@ def _persist_rows(self, rows): return self.cg.client.write(rows) + def _raise_failure( + self, err: Exception, operation_id: np.uint64, operation_ts: datetime + ) -> NoReturn: + """Re-raise `err` from applying this edit, recorded as its kind requires.""" + self.cg.cache = None + for expected in (PreconditionError, PostconditionError): + if isinstance(err, expected): + raise expected(err) from err + payload = err_dump.build_err_payload(self, operation_id, err) + dump_url = err_dump.dump_err_artifact(self.cg, operation_id, payload) + logger.error( + f"<{operation_id}> {type(self).__name__} failed: " + f"{type(err).__name__}: {err}" + f"{err_dump.payload_summary(self)} dump={dump_url}" + ) + if isinstance(err, (AssertionError, RuntimeError)): + raise RuntimeError(err) from err + log_record_error = self._create_log_record( + operation_id=operation_id, + new_root_ids=types.empty_1d, + timestamp=None, + operation_ts=operation_ts, + status=attributes.OperationLogs.StatusCodes.EXCEPTION.value, + exception=repr(err), + ) + self._persist_rows([log_record_error]) + raise Exception(err) from err + class MergeOperation(GraphEditOperation): """Merge Operation: Connect *known* pairs of supervoxels by adding a (weighted) edge. From b06ecb1f94907a46ab7b4f434e74491fb090f8a9 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Sat, 31 Oct 2026 20:36:27 +0000 Subject: [PATCH 02/11] feat(edit): cap graph writes at an edit's op time plus 21 minutes - An edit with under 30 s left is refused before its indefinite locks, raising `EditDeadlineError`, a 504. - Graph writes, the supervoxel-split write included, pass the cap on as kvdbclient's write deadline. - Needs kvdbclient's `write(deadline=)`. Co-Authored-By: Claude --- pychunkedgraph/graph/exceptions.py | 4 ++ pychunkedgraph/graph/operation.py | 39 ++++++++++++++++--- .../tests/graph/edits/test_operation.py | 25 ++++++++++++ 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/pychunkedgraph/graph/exceptions.py b/pychunkedgraph/graph/exceptions.py index cee7348b9..9f7ab0023 100644 --- a/pychunkedgraph/graph/exceptions.py +++ b/pychunkedgraph/graph/exceptions.py @@ -91,6 +91,10 @@ class GatewayTimeout(ServerError): status_code = http_client.GATEWAY_TIMEOUT +class EditDeadlineError(GatewayTimeout): + """An edit too close to its op time plus `MAX_EDIT_AGE` to start a graph write.""" + + class SupervoxelSplitRequiredError(ChunkedGraphError): """ Raised when supervoxel splitting is necessary. diff --git a/pychunkedgraph/graph/operation.py b/pychunkedgraph/graph/operation.py index 8930ea374..6b62840d0 100644 --- a/pychunkedgraph/graph/operation.py +++ b/pychunkedgraph/graph/operation.py @@ -3,7 +3,7 @@ import time from abc import ABC, abstractmethod from collections import namedtuple -from datetime import datetime +from datetime import datetime, timedelta from typing import TYPE_CHECKING from typing import Dict from typing import List @@ -17,6 +17,8 @@ from functools import reduce import numpy as np +from kvdbclient.exceptions import WriteDeadlineError +from kvdbclient.utils import require_before from pychunkedgraph import get_logger from . import err_dump @@ -35,6 +37,7 @@ from .cutting import Cut, SvSplitRequired, run_multicut from .exceptions import PreconditionError from .exceptions import PostconditionError +from .exceptions import EditDeadlineError from .utils.generic import get_bounding_box as get_bbox, assert_same_root from pychunkedgraph.graph import get_valid_timestamp @@ -43,6 +46,11 @@ logger = get_logger(__name__) +# No edit lands a graph cell past its op time plus this; older source state is settled. +MAX_EDIT_AGE = timedelta(minutes=21) +# A graph write starts only with this much time left, so a refusal lands no cell. +WRITE_MARGIN = timedelta(seconds=30) + def _log_edit_done(result, op_type, elapsed): new_roots = list(map(int, np.asarray(result.new_root_ids).tolist())) @@ -476,6 +484,7 @@ def execute( new_lvl2_ids=new_lvl2_ids, old_root_ids=root_ids, ) + deadline = self._write_deadline(operation_ts) except Exception as err: self._raise_failure(err, lock.operation_id, operation_ts) @@ -486,6 +495,7 @@ def execute( new_lvl2_ids, affected_records, root_ids, + deadline, ) _log_edit_done(result, op_type, time.time() - t_edit_start) return result @@ -498,8 +508,9 @@ def _write( new_lvl2_ids: np.ndarray, affected_records: list, old_root_ids: np.ndarray, + deadline: datetime, ): - """Helper to persist changes after an edit.""" + """Persist an edit's changes, its graph cells landing by `deadline`.""" new_root_ids = np.array(new_root_ids, dtype=basetypes.NODE_ID) new_lvl2_ids = np.array(new_lvl2_ids, dtype=basetypes.NODE_ID) @@ -526,6 +537,7 @@ def _write( lock.locked_root_ids, operation_id=lock.operation_id, slow_retry=False, + deadline=deadline, ) log_record_success = self._create_log_record( operation_id=lock.operation_id, @@ -547,11 +559,22 @@ def _write( seg_bbox=getattr(self, "seg_bboxes", None) or None, ) - def _persist_rows(self, rows): - """Persist BT mutation rows; no-op under ``PCG_DRY_RUN=1``.""" + def _persist_rows(self, rows, deadline: Optional[datetime] = None): + """Persist BT mutation rows by `deadline`; no-op under ``PCG_DRY_RUN=1``.""" if is_dry_run(): return - self.cg.client.write(rows) + self.cg.client.write(rows, deadline=deadline) + + def _write_deadline(self, timestamp: datetime) -> datetime: + """When graph cells stamped `timestamp` must have landed; refused near it.""" + deadline = timestamp + MAX_EDIT_AGE + try: + require_before(deadline - WRITE_MARGIN) + except WriteDeadlineError as err: + raise EditDeadlineError( + f"edit stamped {timestamp} cannot land by {deadline}" + ) from err + return deadline def _raise_failure( self, err: Exception, operation_id: np.uint64, operation_ts: datetime @@ -579,6 +602,9 @@ def _raise_failure( exception=repr(err), ) self._persist_rows([log_record_error]) + if isinstance(err, EditDeadlineError): + # Kept typed, so the API answers with its 504. + raise err raise Exception(err) from err @@ -969,6 +995,7 @@ def _apply( timestamp=timestamp, parent_ts=self.parent_ts, ) + deadline = self._write_deadline(timestamp) with locks.IndefiniteL2ChunkLock( self.cg, chunk_ids, @@ -976,7 +1003,7 @@ def _apply( privileged_mode=self.privileged_mode, ): write_seg_chunks(self.cg.meta, sv_result.seg_writes) - self._persist_rows(sv_result.bigtable_rows) + self._persist_rows(sv_result.bigtable_rows, deadline=deadline) self.seg_bboxes = sv_result.seg_bboxes self.source_ids = sv_result.source_ids_fresh self.sink_ids = sv_result.sink_ids_fresh diff --git a/pychunkedgraph/tests/graph/edits/test_operation.py b/pychunkedgraph/tests/graph/edits/test_operation.py index ff7cacd21..5e9b019d9 100644 --- a/pychunkedgraph/tests/graph/edits/test_operation.py +++ b/pychunkedgraph/tests/graph/edits/test_operation.py @@ -5,6 +5,7 @@ -- all using real graph operations through the BigTable emulator. """ +from datetime import UTC, datetime from math import inf import numpy as np @@ -13,6 +14,7 @@ from ...helpers import SV, build_graph from ....graph import attributes from ....graph.operation import ( + MAX_EDIT_AGE, GraphEditOperation, MergeOperation, MulticutOperation, @@ -21,6 +23,7 @@ UndoOperation, ) from ....graph.exceptions import ( + EditDeadlineError, PreconditionError, PostconditionError, SupervoxelSplitRequiredError, @@ -694,6 +697,28 @@ def test_execute_assertion_error_clears_cache(self, gen_graph): assert cg.cache is None + @pytest.mark.timeout(30) + def test_execute_refuses_a_write_past_the_edit_deadline(self, gen_graph): + """A stale op time writes nothing, logs EXCEPTION and frees its roots.""" + from unittest.mock import patch + + cg, sv = _build_two_sv_disconnected(gen_graph) + sv0, sv1 = sv["a0"], sv["a1"] + stale = datetime.now(UTC).replace(microsecond=0) - MAX_EDIT_AGE + with patch.object( + type(cg.client), "get_consolidated_lock_timestamp", return_value=stale + ), patch("pychunkedgraph.graph.err_dump.dump_err_artifact", return_value=None): + with pytest.raises(EditDeadlineError, match="cannot land") as refused: + cg.add_edges("test_user", [sv0, sv1], affinities=[0.3]) + assert refused.value.status_code == 504 + + assert cg.get_root(sv0) != cg.get_root(sv1) + op = cg.client.get_max_operation_id() + status = cg.client.read_node(op, properties=attributes.OperationLogs.Status) + assert status[0].value == attributes.OperationLogs.StatusCodes.EXCEPTION.value + cg.add_edges("test_user", [sv0, sv1], affinities=[0.3]) + assert cg.get_root(sv0) == cg.get_root(sv1) + # =========================================================================== # NEW: UndoOperation.execute() edge validation (lines 1245-1267) From daf2c9883194cc5b7545f1d9c93a1840b7563697 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Sat, 31 Oct 2026 20:37:38 +0000 Subject: [PATCH 03/11] feat(fork): open fork tables and create forks at a past time - `ChunkedGraph` opens a Bigtable graph through kvdbclient's `ForkClient`. - `pychunkedgraph.fork.create.create_fork` forks at the requested time, stepped back past the edit cap. - Needs kvdbclient's fork package. Co-Authored-By: Claude --- pychunkedgraph/fork/__init__.py | 1 + pychunkedgraph/fork/create.py | 44 +++++++++++++++ pychunkedgraph/graph/chunkedgraph.py | 5 +- pychunkedgraph/tests/fork/__init__.py | 0 pychunkedgraph/tests/fork/test_reads.py | 73 +++++++++++++++++++++++++ 5 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 pychunkedgraph/fork/__init__.py create mode 100644 pychunkedgraph/fork/create.py create mode 100644 pychunkedgraph/tests/fork/__init__.py create mode 100644 pychunkedgraph/tests/fork/test_reads.py diff --git a/pychunkedgraph/fork/__init__.py b/pychunkedgraph/fork/__init__.py new file mode 100644 index 000000000..075868185 --- /dev/null +++ b/pychunkedgraph/fork/__init__.py @@ -0,0 +1 @@ +"""Graph forks: tables that read their source's history up to a fork point.""" diff --git a/pychunkedgraph/fork/create.py b/pychunkedgraph/fork/create.py new file mode 100644 index 000000000..182034dd7 --- /dev/null +++ b/pychunkedgraph/fork/create.py @@ -0,0 +1,44 @@ +"""Fork a graph at the requested time, stepped back to where every edit has landed.""" + +import uuid +from copy import deepcopy +from datetime import datetime + +from kvdbclient.fork.client import ForkClient, create_fork_table +from kvdbclient.fork.marker import ForkMarker, Hop, MarkerState + +from pychunkedgraph.graph import BackendClientInfo, ChunkedGraph +from pychunkedgraph.graph import get_default_client_info, get_valid_timestamp +from pychunkedgraph.graph.meta import ChunkedGraphMeta +from pychunkedgraph.graph.operation import MAX_EDIT_AGE + + +def create_fork( + source: str, + fork: str, + at: datetime, + *, + client_info: BackendClientInfo = get_default_client_info(), +) -> ChunkedGraph: + """Fork `source` into the new table `fork` at `at`, or `MAX_EDIT_AGE` ago if later.""" + upstream = ForkClient(source, config=client_info.CONFIG) + meta = upstream.read_table_meta() + # A source that is itself a fork passes on its chain, read beyond this hop. + inherited = upstream.marker.chain if upstream.marker else () + requested = get_valid_timestamp(at) + tf = min(requested, get_valid_timestamp(None) - MAX_EDIT_AGE) + marker = ForkMarker( + chain=(Hop(source, tf),) + inherited, + state=MarkerState.READY, + generation=uuid.uuid4().hex, + source_max_op_id=int(upstream.get_max_operation_id()), + requested_at=requested, + ) + config = meta.graph_config._replace(ID=fork, ID_PREFIX="") + fork_meta = ChunkedGraphMeta(config, meta.data_source, deepcopy(meta.custom_data)) + version = upstream.read_table_version() + upstream.close() + create_fork_table( + fork, marker, fork_meta, version, config=client_info.CONFIG + ).close() + return ChunkedGraph(graph_id=fork, client_info=client_info) diff --git a/pychunkedgraph/graph/chunkedgraph.py b/pychunkedgraph/graph/chunkedgraph.py index 02bac55c9..0a08ec952 100644 --- a/pychunkedgraph/graph/chunkedgraph.py +++ b/pychunkedgraph/graph/chunkedgraph.py @@ -7,6 +7,7 @@ from functools import reduce import numpy as np +from kvdbclient.fork.client import ForkClient from pychunkedgraph import __version__ from . import types @@ -57,7 +58,9 @@ def __init__( ) self._meta = meta else: - _client = ClientClass(graph_id, config=client_info.CONFIG) + # A bigtable graph may be a fork; its meta read attaches the fork chain. + OpenClass = ForkClient if client_info.TYPE == "bigtable" else ClientClass + _client = OpenClass(graph_id, config=client_info.CONFIG) self._meta = _client.read_table_meta() _client._lock_expiry = self._meta.graph_config.ROOT_LOCK_EXPIRY diff --git a/pychunkedgraph/tests/fork/__init__.py b/pychunkedgraph/tests/fork/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/pychunkedgraph/tests/fork/test_reads.py b/pychunkedgraph/tests/fork/test_reads.py new file mode 100644 index 000000000..9b03facdc --- /dev/null +++ b/pychunkedgraph/tests/fork/test_reads.py @@ -0,0 +1,73 @@ +"""A fork reads its source as of the fork point, and so does a fork of that fork.""" + +from datetime import UTC, datetime, timedelta + +import numpy as np +import pytest + +from ...fork.create import create_fork +from ...graph import BackendClientInfo +from ...graph.operation import MAX_EDIT_AGE +from ..helpers import SV, build_graph, fake_timestamp + + +def _forked(source, name, at, request): + """`create_fork` on a test graph, given the test mocks its stored meta lacks.""" + info = BackendClientInfo(TYPE="bigtable", CONFIG=source.client._config) + graph = create_fork(source.graph_id, name, at, client_info=info) + request.addfinalizer(graph.client._admin_table.delete) + for attr in ("_ws_cv", "_ws_info_d", "ws_ts_scale"): + setattr(graph.meta, attr, getattr(source.meta, attr)) + graph.meta.layer_count = source.meta.layer_count + graph.meta.layer_chunk_bounds = source.meta.layer_chunk_bounds + return graph + + +@pytest.fixture() +def split_pair(gen_graph): + """Two joined supervoxels split now; returns (graph, ids, an earlier time).""" + cg, sv = build_graph( + gen_graph, + n_layers=3, + supervoxels={"a": SV(), "b": SV(x=1)}, + edges=[("a", "b", 0.5)], + ) + if cg.client.backend_name != "bigtable": + pytest.skip("forks read through the bigtable fork client only") + # The graph is built at fake_timestamp(), ten days back; the split runs now. + before = fake_timestamp() + timedelta(days=1) + cg.remove_edges("test_user", source_ids=sv["a"], sink_ids=sv["b"], mincut=False) + return cg, np.array([sv["a"], sv["b"]], dtype=np.uint64), before + + +def test_a_fork_reads_its_source_as_of_the_fork_point(split_pair, request): + cg, ids, before = split_pair + fork = _forked(cg, "test_fork", before, request) + roots = fork.get_roots(ids) + assert roots[0] == roots[1] + assert np.array_equal(roots, cg.get_roots(ids, time_stamp=before)) + assert not np.array_equal(roots, cg.get_roots(ids)) + + +def test_a_fork_of_a_fork_reads_the_source_at_the_first_fork_point(split_pair, request): + cg, ids, before = split_pair + first = _forked(cg, "test_fork", before, request) + second = _forked(first, "test_fork2", datetime.now(UTC), request) + assert np.array_equal(second.get_roots(ids), cg.get_roots(ids, time_stamp=before)) + + +def test_a_past_request_forks_at_exactly_that_time(split_pair, request): + cg, _, before = split_pair + marker = _forked(cg, "test_fork", before, request).client.marker + assert marker.tf == marker.requested_at + + +def test_a_recent_request_steps_back_past_the_edit_cap(split_pair, request): + cg, ids, _ = split_pair + requested = datetime.now(UTC).replace(microsecond=0) + fork = _forked(cg, "test_fork", requested, request) + assert fork.client.marker.tf <= datetime.now(UTC) - MAX_EDIT_AGE + assert fork.client.marker.requested_at == requested + # The split ran seconds ago, after the stepped-back fork point. + roots = fork.get_roots(ids) + assert roots[0] == roots[1] From 0c9d79b45f41c7114f02cf21ae517068ba2841f9 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Thu, 5 Nov 2026 03:56:50 +0000 Subject: [PATCH 04/11] feat(fork): refuse remeshing a fork and pin the fork-aware kvdbclient refuse_on_fork raises Forbidden in remeshing and handle_remesh. kvdbclient installs from KVDbClient@da067c7 until its PR releases. tests/fork/test_meshes.py covers fork manifests and the refusal. Co-Authored-By: Claude --- pychunkedgraph/app/meshing/common.py | 2 + pychunkedgraph/app/meshing/v1/routes.py | 2 + pychunkedgraph/fork/guard.py | 14 +++ pychunkedgraph/meshing/meshgen.py | 2 + pychunkedgraph/tests/fork/test_meshes.py | 108 +++++++++++++++++++++++ requirements.in | 4 +- requirements.txt | 2 +- 7 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 pychunkedgraph/fork/guard.py create mode 100644 pychunkedgraph/tests/fork/test_meshes.py diff --git a/pychunkedgraph/app/meshing/common.py b/pychunkedgraph/app/meshing/common.py index 52edcc40f..af6ca6ac7 100644 --- a/pychunkedgraph/app/meshing/common.py +++ b/pychunkedgraph/app/meshing/common.py @@ -8,6 +8,7 @@ from pychunkedgraph import __version__ from pychunkedgraph.app import app_utils +from pychunkedgraph.fork.guard import refuse_on_fork from pychunkedgraph.graph import chunkedgraph from pychunkedgraph.graph import exceptions as cg_exceptions @@ -171,6 +172,7 @@ def handle_remesh(table_id): new_lvl2_ids = json.loads(request.data)["new_lvl2_ids"] new_lvl2_ids = np.array(new_lvl2_ids, dtype=np.uint64) cg = app_utils.get_cg(table_id) + refuse_on_fork(cg, "remeshing") if len(new_lvl2_ids) > 0: t = threading.Thread( target=_remeshing, args=(cg.get_serialized_info(), new_lvl2_ids) diff --git a/pychunkedgraph/app/meshing/v1/routes.py b/pychunkedgraph/app/meshing/v1/routes.py index 14b286e3a..93db98cf9 100644 --- a/pychunkedgraph/app/meshing/v1/routes.py +++ b/pychunkedgraph/app/meshing/v1/routes.py @@ -85,6 +85,8 @@ def handle_get_manifest(table_id, node_id): ## ENQUE MESHING JOBS ---------------------------------------------------------- +# TODO: remove with CAVEclient's `remesh_level2_chunks`, its one known caller, once usage +# logs show no calls; edits already remesh through the pub/sub mesh workers. @bp.route("/table//remeshing", methods=["POST"]) @auth_requires_permission("edit") @remap_public(edit=True) diff --git a/pychunkedgraph/fork/guard.py b/pychunkedgraph/fork/guard.py new file mode 100644 index 000000000..9bfa07880 --- /dev/null +++ b/pychunkedgraph/fork/guard.py @@ -0,0 +1,14 @@ +"""Refusals for a read-only fork's writes that land outside its table.""" + +from kvdbclient.fork.client import ForkClient + +from ..graph.exceptions import Forbidden + + +def refuse_on_fork(cg, action: str) -> None: + """Raise `Forbidden` when `cg` is a fork. + + A fork writes nothing until fork edits land; its client refuses only table writes. + """ + if isinstance(cg.client, ForkClient) and cg.client.marker is not None: + raise Forbidden(f"{cg.graph_id} is a read-only fork: {action} is refused") diff --git a/pychunkedgraph/meshing/meshgen.py b/pychunkedgraph/meshing/meshgen.py index 3f72dee78..cfc44c987 100644 --- a/pychunkedgraph/meshing/meshgen.py +++ b/pychunkedgraph/meshing/meshgen.py @@ -18,6 +18,7 @@ import zmesh import fastremap +from pychunkedgraph.fork.guard import refuse_on_fork from pychunkedgraph.graph.chunkedgraph import ChunkedGraph # noqa from pychunkedgraph.graph import attributes # noqa from pychunkedgraph.meshing import meshgen_utils # noqa @@ -861,6 +862,7 @@ def remeshing( :param max_err: int :return: """ + refuse_on_fork(cg, "remeshing") l2_chunk_dict = collections.defaultdict(set) # Find the chunk_ids of the l2_node_ids diff --git a/pychunkedgraph/tests/fork/test_meshes.py b/pychunkedgraph/tests/fork/test_meshes.py new file mode 100644 index 000000000..da23961a5 --- /dev/null +++ b/pychunkedgraph/tests/fork/test_meshes.py @@ -0,0 +1,108 @@ +"""A fork finds its source's meshes as of the fork point, and refuses to remesh.""" + +import json +from types import SimpleNamespace + +import pytest +from flask import Flask + +from ...app import app_utils +from ...app.meshing import common +from ...fork.guard import refuse_on_fork +from ...graph.exceptions import Forbidden +from ...meshing import meshgen +from ...meshing.manifest import sharded +from ...meshing.manifest.utils import ( + _get_dynamic_meshes, + get_children_before_start_layer, +) +from ...meshing.mesh_meta import MeshMeta +from ...meshing.meshgen_utils import get_mesh_name +from .test_reads import _forked, split_pair # noqa: F401 -- `split_pair` is a fixture + + +def _meshed(cg, dynamic_mesh_dir="dynamic"): + """`cg` with a mesh block in its meta row; every node is newer than `initial_ts`.""" + block = {"dir": "mesh", "dynamic_mesh_dir": dynamic_mesh_dir, "initial_ts": 0} + cg.meta._custom_data = {**cg.meta.custom_data, "mesh": block} + cg.update_meta(cg.meta, overwrite=True) + + +def _manifest(cg, node_id, accept): + """The meshing API's manifest for `node_id`, as `cg` answers it.""" + headers = {"Accept": accept} if accept else {} + with Flask(__name__).test_request_context(headers=headers): + return common.handle_get_manifest(cg.graph_id, str(node_id)).get_json() + + +def _never_started(*args, **kwargs): + raise AssertionError("a refused remesh queued its thread") + + +def test_a_fork_finds_its_source_meshes_as_of_the_fork_point( + split_pair, request, tmp_path +): + cg, ids, before = split_pair + dynamic = tmp_path / "dynamic" + dynamic.mkdir() + _meshed(cg, dynamic.as_uri()) + fork = _forked(cg, "test_fork", before, request) + assert MeshMeta(fork).dynamic_path == MeshMeta(cg).dynamic_path == dynamic.as_uri() + assert MeshMeta(fork).initial_path == MeshMeta(cg).initial_path + root = cg.get_root(ids[0], time_stamp=before) + assert fork.get_root(ids[0]) == root + nodes = get_children_before_start_layer(fork, root, start_layer=2) + for node in nodes: + (dynamic / get_mesh_name(cg, node)).touch() + found, missing = _get_dynamic_meshes(fork, nodes) + assert set(found) == set(nodes) and missing.size == 0 + assert found == _get_dynamic_meshes(cg, nodes)[0] + + +@pytest.mark.parametrize("accept", [None, "application/x.cave;manifest_version=2"]) +def test_a_fork_answers_its_source_manifest_as_of_the_fork_point( + split_pair, request, monkeypatch, accept +): + cg, ids, before = split_pair + _meshed(cg) + fork = _forked(cg, "test_fork", before, request) + graphs = {cg.graph_id: cg, fork.graph_id: fork} + monkeypatch.setattr(app_utils, "get_cg", lambda table_id, **_: graphs[table_id]) + # Shard readers place only nodes older than `initial_ts`, and none are; the emulator + # graph has no segmentation info to build them from. + monkeypatch.setattr( + sharded, "shard_mesh_source", lambda cg: SimpleNamespace(readers={}) + ) + root = cg.get_root(ids[0], time_stamp=before) + assert fork.get_root(ids[0]) == root + assert _manifest(fork, root, accept) == _manifest(cg, root, accept) + + +def test_remeshing_a_fork_is_refused_and_writes_nothing(split_pair, request, tmp_path): + cg, ids, before = split_pair + fork = _forked(cg, "test_fork", before, request) + out = tmp_path / "out" + with pytest.raises(Forbidden, match="read-only fork"): + meshgen.remeshing( + fork, fork.get_parents(ids), cv_unsharded_mesh_path=out.as_uri() + ) + assert not out.exists() + + +def test_a_remesh_request_for_a_fork_answers_403_before_queueing( + split_pair, request, monkeypatch +): + cg, ids, before = split_pair + fork = _forked(cg, "test_fork", before, request) + monkeypatch.setattr(app_utils, "get_cg", lambda table_id, **_: fork) + monkeypatch.setattr(common, "threading", SimpleNamespace(Thread=_never_started)) + body = json.dumps({"new_lvl2_ids": [int(i) for i in fork.get_parents(ids)]}) + with Flask(__name__).test_request_context(data=body): + with pytest.raises(Forbidden) as refused: + common.handle_remesh(fork.graph_id) + assert refused.value.status_code == 403 + + +def test_the_source_itself_is_not_refused(split_pair): + cg, _, _ = split_pair + refuse_on_fork(cg, "remeshing") diff --git a/requirements.in b/requirements.in index f36cf492c..e3acf79e7 100644 --- a/requirements.in +++ b/requirements.in @@ -26,13 +26,15 @@ task-queue>=2.14.0 messagingclient>0.3.0 dracopy>=1.5.0 datastoreflex>=0.5.0 -kvdbclient>=0.8.0 zstandard>=0.23.0 tinybrain>=1.7.0 pykdtree>=1.4.3 supervoxel-splitter[fast]>=0.1.0 cave-pipeline[distribution]>=0.0.3,<0.1 +# TODO: back to a PyPI release once KVDbClient's table-forks PR merges and ships. +kvdbclient @ git+https://github.com/seung-lab/KVDbClient@da067c7759c14f7347fe7ce277b507fdc9db6772 + # Conda only - use requirements.yml (or install manually): # graph-tool # numpy (graph-tool ABI; kept out of this lock via [tool.pip-tools] unsafe-package) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 8778a754a..79f767cd0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -196,7 +196,7 @@ jsonschema==4.26.0 # python-jsonschema-objects jsonschema-specifications==2025.9.1 # via jsonschema -kvdbclient==0.8.0 +kvdbclient @ git+https://github.com/seung-lab/KVDbClient@da067c7759c14f7347fe7ce277b507fdc9db6772 # via # -r requirements.in # cave-pipeline From f114eac4104a5d0f3512128bd26b4e7cf39abaf7 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Thu, 5 Nov 2026 15:16:37 +0000 Subject: [PATCH 05/11] fix(build): install kvdbclient from its GitHub archive, not git The image has no git, so pip could not clone the git+https pin. The archive zip of KVDbClient@da067c7 installs with no git. Co-Authored-By: Claude Opus 5.5 --- requirements.in | 2 +- requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.in b/requirements.in index e3acf79e7..4e9b8d081 100644 --- a/requirements.in +++ b/requirements.in @@ -33,7 +33,7 @@ supervoxel-splitter[fast]>=0.1.0 cave-pipeline[distribution]>=0.0.3,<0.1 # TODO: back to a PyPI release once KVDbClient's table-forks PR merges and ships. -kvdbclient @ git+https://github.com/seung-lab/KVDbClient@da067c7759c14f7347fe7ce277b507fdc9db6772 +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/da067c7759c14f7347fe7ce277b507fdc9db6772.zip # Conda only - use requirements.yml (or install manually): # graph-tool diff --git a/requirements.txt b/requirements.txt index 79f767cd0..93622da04 100644 --- a/requirements.txt +++ b/requirements.txt @@ -196,7 +196,7 @@ jsonschema==4.26.0 # python-jsonschema-objects jsonschema-specifications==2025.9.1 # via jsonschema -kvdbclient @ git+https://github.com/seung-lab/KVDbClient@da067c7759c14f7347fe7ce277b507fdc9db6772 +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/da067c7759c14f7347fe7ce277b507fdc9db6772.zip # via # -r requirements.in # cave-pipeline From d2aae00c7ad222d15077a1d37caaae6937157b18 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Thu, 5 Nov 2026 23:46:05 +0000 Subject: [PATCH 06/11] build: move the temporary kvdbclient pin to KVDbClient 276883f Same code as da067c7, which no branch holds now, plus coverage tests. Temporary: dropped with the other pin commits before merge. Co-Authored-By: Claude --- requirements.in | 5 +++-- requirements.txt | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/requirements.in b/requirements.in index 4e9b8d081..62ef91ef1 100644 --- a/requirements.in +++ b/requirements.in @@ -32,8 +32,9 @@ pykdtree>=1.4.3 supervoxel-splitter[fast]>=0.1.0 cave-pipeline[distribution]>=0.0.3,<0.1 -# TODO: back to a PyPI release once KVDbClient's table-forks PR merges and ships. -kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/da067c7759c14f7347fe7ce277b507fdc9db6772.zip +# TODO: temporary, for test images. Drop this pin and every commit carrying it before +# merge, then pin the KVDbClient release. +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/276883f1270b766abb261b41c299d96bb7c195cb.zip # Conda only - use requirements.yml (or install manually): # graph-tool diff --git a/requirements.txt b/requirements.txt index 93622da04..a91d1a9d2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -196,7 +196,7 @@ jsonschema==4.26.0 # python-jsonschema-objects jsonschema-specifications==2025.9.1 # via jsonschema -kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/da067c7759c14f7347fe7ce277b507fdc9db6772.zip +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/276883f1270b766abb261b41c299d96bb7c195cb.zip # via # -r requirements.in # cave-pipeline From 90418cd5a293c1dddce5f8f2647cd30d479be319 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Tue, 10 Nov 2026 01:37:34 +0000 Subject: [PATCH 07/11] feat(fork): open forks through kvdbclient's registry at a safe time - `ChunkedGraph`, `create_fork` and the fork guard name no backend; the registered client opens forks. - `create_fork` forks at kvdbclient's `safe_time`, stepping back, or with `wait` waiting. - The edit write deadline is gone, and kvdbclient pins its fork-reads commit `83ba037`. Co-Authored-By: Claude --- pychunkedgraph/fork/create.py | 24 +++++++++---- pychunkedgraph/fork/guard.py | 11 ++---- pychunkedgraph/graph/chunkedgraph.py | 6 ++-- pychunkedgraph/graph/exceptions.py | 4 --- pychunkedgraph/graph/operation.py | 36 ++++--------------- pychunkedgraph/tests/fork/test_reads.py | 29 +++++++++++---- .../tests/graph/edits/test_operation.py | 13 +++---- requirements.in | 2 +- requirements.txt | 2 +- 9 files changed, 57 insertions(+), 70 deletions(-) diff --git a/pychunkedgraph/fork/create.py b/pychunkedgraph/fork/create.py index 182034dd7..3e601e039 100644 --- a/pychunkedgraph/fork/create.py +++ b/pychunkedgraph/fork/create.py @@ -1,14 +1,16 @@ -"""Fork a graph at the requested time, stepped back to where every edit has landed.""" +"""Fork a graph at the newest safe time at or before the request.""" import uuid from copy import deepcopy from datetime import datetime -from kvdbclient.fork.client import ForkClient, create_fork_table from kvdbclient.fork.marker import ForkMarker, Hop, MarkerState +from kvdbclient.safe_time import safe_time from pychunkedgraph.graph import BackendClientInfo, ChunkedGraph -from pychunkedgraph.graph import get_default_client_info, get_valid_timestamp +from pychunkedgraph.graph import get_client_class, get_default_client_info +from pychunkedgraph.graph import get_valid_timestamp +from pychunkedgraph.graph.exceptions import ChunkedGraphError from pychunkedgraph.graph.meta import ChunkedGraphMeta from pychunkedgraph.graph.operation import MAX_EDIT_AGE @@ -18,15 +20,23 @@ def create_fork( fork: str, at: datetime, *, + wait: bool = False, client_info: BackendClientInfo = get_default_client_info(), ) -> ChunkedGraph: - """Fork `source` into the new table `fork` at `at`, or `MAX_EDIT_AGE` ago if later.""" - upstream = ForkClient(source, config=client_info.CONFIG) + """Fork `source` into the new table `fork` at the newest safe time at or before `at`. + + An edit that may still write holds that time back: the fork steps below it, or with + `wait` waits for it to finish. + """ + ClientClass = get_client_class(client_info.TYPE) + if not ClientClass.opens_forks: + raise ChunkedGraphError(f"{client_info.TYPE} tables cannot be forked") + upstream = ClientClass(source, config=client_info.CONFIG) meta = upstream.read_table_meta() # A source that is itself a fork passes on its chain, read beyond this hop. inherited = upstream.marker.chain if upstream.marker else () requested = get_valid_timestamp(at) - tf = min(requested, get_valid_timestamp(None) - MAX_EDIT_AGE) + tf = safe_time(upstream, requested, MAX_EDIT_AGE, wait=wait) marker = ForkMarker( chain=(Hop(source, tf),) + inherited, state=MarkerState.READY, @@ -38,7 +48,7 @@ def create_fork( fork_meta = ChunkedGraphMeta(config, meta.data_source, deepcopy(meta.custom_data)) version = upstream.read_table_version() upstream.close() - create_fork_table( + ClientClass.create_fork_table( fork, marker, fork_meta, version, config=client_info.CONFIG ).close() return ChunkedGraph(graph_id=fork, client_info=client_info) diff --git a/pychunkedgraph/fork/guard.py b/pychunkedgraph/fork/guard.py index 9bfa07880..820d23ca5 100644 --- a/pychunkedgraph/fork/guard.py +++ b/pychunkedgraph/fork/guard.py @@ -1,14 +1,9 @@ -"""Refusals for a read-only fork's writes that land outside its table.""" - -from kvdbclient.fork.client import ForkClient +"""Refusals for a fork's writes that land outside its table.""" from ..graph.exceptions import Forbidden def refuse_on_fork(cg, action: str) -> None: - """Raise `Forbidden` when `cg` is a fork. - - A fork writes nothing until fork edits land; its client refuses only table writes. - """ - if isinstance(cg.client, ForkClient) and cg.client.marker is not None: + """Raise `Forbidden` when `cg` is a fork, which writes nothing outside its table.""" + if cg.client.marker is not None: raise Forbidden(f"{cg.graph_id} is a read-only fork: {action} is refused") diff --git a/pychunkedgraph/graph/chunkedgraph.py b/pychunkedgraph/graph/chunkedgraph.py index 0a08ec952..c2ad9bba2 100644 --- a/pychunkedgraph/graph/chunkedgraph.py +++ b/pychunkedgraph/graph/chunkedgraph.py @@ -7,7 +7,6 @@ from functools import reduce import numpy as np -from kvdbclient.fork.client import ForkClient from pychunkedgraph import __version__ from . import types @@ -58,9 +57,8 @@ def __init__( ) self._meta = meta else: - # A bigtable graph may be a fork; its meta read attaches the fork chain. - OpenClass = ForkClient if client_info.TYPE == "bigtable" else ClientClass - _client = OpenClass(graph_id, config=client_info.CONFIG) + # A fork's meta read attaches the chain of tables it reads through. + _client = ClientClass(graph_id, config=client_info.CONFIG) self._meta = _client.read_table_meta() _client._lock_expiry = self._meta.graph_config.ROOT_LOCK_EXPIRY diff --git a/pychunkedgraph/graph/exceptions.py b/pychunkedgraph/graph/exceptions.py index 9f7ab0023..cee7348b9 100644 --- a/pychunkedgraph/graph/exceptions.py +++ b/pychunkedgraph/graph/exceptions.py @@ -91,10 +91,6 @@ class GatewayTimeout(ServerError): status_code = http_client.GATEWAY_TIMEOUT -class EditDeadlineError(GatewayTimeout): - """An edit too close to its op time plus `MAX_EDIT_AGE` to start a graph write.""" - - class SupervoxelSplitRequiredError(ChunkedGraphError): """ Raised when supervoxel splitting is necessary. diff --git a/pychunkedgraph/graph/operation.py b/pychunkedgraph/graph/operation.py index 6b62840d0..290badce0 100644 --- a/pychunkedgraph/graph/operation.py +++ b/pychunkedgraph/graph/operation.py @@ -17,8 +17,6 @@ from functools import reduce import numpy as np -from kvdbclient.exceptions import WriteDeadlineError -from kvdbclient.utils import require_before from pychunkedgraph import get_logger from . import err_dump @@ -37,7 +35,6 @@ from .cutting import Cut, SvSplitRequired, run_multicut from .exceptions import PreconditionError from .exceptions import PostconditionError -from .exceptions import EditDeadlineError from .utils.generic import get_bounding_box as get_bbox, assert_same_root from pychunkedgraph.graph import get_valid_timestamp @@ -46,10 +43,8 @@ logger = get_logger(__name__) -# No edit lands a graph cell past its op time plus this; older source state is settled. +# Edits finish within this of their op time, a known bound nothing enforces. MAX_EDIT_AGE = timedelta(minutes=21) -# A graph write starts only with this much time left, so a refusal lands no cell. -WRITE_MARGIN = timedelta(seconds=30) def _log_edit_done(result, op_type, elapsed): @@ -484,7 +479,6 @@ def execute( new_lvl2_ids=new_lvl2_ids, old_root_ids=root_ids, ) - deadline = self._write_deadline(operation_ts) except Exception as err: self._raise_failure(err, lock.operation_id, operation_ts) @@ -495,7 +489,6 @@ def execute( new_lvl2_ids, affected_records, root_ids, - deadline, ) _log_edit_done(result, op_type, time.time() - t_edit_start) return result @@ -508,9 +501,8 @@ def _write( new_lvl2_ids: np.ndarray, affected_records: list, old_root_ids: np.ndarray, - deadline: datetime, ): - """Persist an edit's changes, its graph cells landing by `deadline`.""" + """Persist an edit's changes.""" new_root_ids = np.array(new_root_ids, dtype=basetypes.NODE_ID) new_lvl2_ids = np.array(new_lvl2_ids, dtype=basetypes.NODE_ID) @@ -537,7 +529,6 @@ def _write( lock.locked_root_ids, operation_id=lock.operation_id, slow_retry=False, - deadline=deadline, ) log_record_success = self._create_log_record( operation_id=lock.operation_id, @@ -559,22 +550,11 @@ def _write( seg_bbox=getattr(self, "seg_bboxes", None) or None, ) - def _persist_rows(self, rows, deadline: Optional[datetime] = None): - """Persist BT mutation rows by `deadline`; no-op under ``PCG_DRY_RUN=1``.""" + def _persist_rows(self, rows): + """Persist BT mutation rows; no-op under ``PCG_DRY_RUN=1``.""" if is_dry_run(): return - self.cg.client.write(rows, deadline=deadline) - - def _write_deadline(self, timestamp: datetime) -> datetime: - """When graph cells stamped `timestamp` must have landed; refused near it.""" - deadline = timestamp + MAX_EDIT_AGE - try: - require_before(deadline - WRITE_MARGIN) - except WriteDeadlineError as err: - raise EditDeadlineError( - f"edit stamped {timestamp} cannot land by {deadline}" - ) from err - return deadline + self.cg.client.write(rows) def _raise_failure( self, err: Exception, operation_id: np.uint64, operation_ts: datetime @@ -602,9 +582,6 @@ def _raise_failure( exception=repr(err), ) self._persist_rows([log_record_error]) - if isinstance(err, EditDeadlineError): - # Kept typed, so the API answers with its 504. - raise err raise Exception(err) from err @@ -995,7 +972,6 @@ def _apply( timestamp=timestamp, parent_ts=self.parent_ts, ) - deadline = self._write_deadline(timestamp) with locks.IndefiniteL2ChunkLock( self.cg, chunk_ids, @@ -1003,7 +979,7 @@ def _apply( privileged_mode=self.privileged_mode, ): write_seg_chunks(self.cg.meta, sv_result.seg_writes) - self._persist_rows(sv_result.bigtable_rows, deadline=deadline) + self._persist_rows(sv_result.bigtable_rows) self.seg_bboxes = sv_result.seg_bboxes self.source_ids = sv_result.source_ids_fresh self.sink_ids = sv_result.sink_ids_fresh diff --git a/pychunkedgraph/tests/fork/test_reads.py b/pychunkedgraph/tests/fork/test_reads.py index 9b03facdc..fa44db452 100644 --- a/pychunkedgraph/tests/fork/test_reads.py +++ b/pychunkedgraph/tests/fork/test_reads.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from kvdbclient.safe_time import SETTLE from ...fork.create import create_fork from ...graph import BackendClientInfo @@ -11,10 +12,10 @@ from ..helpers import SV, build_graph, fake_timestamp -def _forked(source, name, at, request): +def _forked(source, name, at, request, **options): """`create_fork` on a test graph, given the test mocks its stored meta lacks.""" info = BackendClientInfo(TYPE="bigtable", CONFIG=source.client._config) - graph = create_fork(source.graph_id, name, at, client_info=info) + graph = create_fork(source.graph_id, name, at, client_info=info, **options) request.addfinalizer(graph.client._admin_table.delete) for attr in ("_ws_cv", "_ws_info_d", "ws_ts_scale"): setattr(graph.meta, attr, getattr(source.meta, attr)) @@ -32,8 +33,8 @@ def split_pair(gen_graph): supervoxels={"a": SV(), "b": SV(x=1)}, edges=[("a", "b", 0.5)], ) - if cg.client.backend_name != "bigtable": - pytest.skip("forks read through the bigtable fork client only") + if not cg.client.opens_forks: + pytest.skip("this backend's client opens no forks") # The graph is built at fake_timestamp(), ten days back; the split runs now. before = fake_timestamp() + timedelta(days=1) cg.remove_edges("test_user", source_ids=sv["a"], sink_ids=sv["b"], mincut=False) @@ -62,12 +63,28 @@ def test_a_past_request_forks_at_exactly_that_time(split_pair, request): assert marker.tf == marker.requested_at -def test_a_recent_request_steps_back_past_the_edit_cap(split_pair, request): +def test_a_recent_request_steps_back_past_the_settle_window(split_pair, request): cg, ids, _ = split_pair requested = datetime.now(UTC).replace(microsecond=0) fork = _forked(cg, "test_fork", requested, request) - assert fork.client.marker.tf <= datetime.now(UTC) - MAX_EDIT_AGE + now = datetime.now(UTC) + assert now - MAX_EDIT_AGE < fork.client.marker.tf <= now - SETTLE assert fork.client.marker.requested_at == requested # The split ran seconds ago, after the stepped-back fork point. roots = fork.get_roots(ids) assert roots[0] == roots[1] + + +def test_the_admins_wait_choice_reaches_the_safe_time_search( + split_pair, request, monkeypatch +): + cg, _, before = split_pair + waits = [] + + def searched(client, requested, longest_edit, wait=False): + waits.append(wait) + return requested + + monkeypatch.setattr("pychunkedgraph.fork.create.safe_time", searched) + _forked(cg, "test_fork", before, request, wait=True) + assert waits == [True] diff --git a/pychunkedgraph/tests/graph/edits/test_operation.py b/pychunkedgraph/tests/graph/edits/test_operation.py index 5e9b019d9..e940c3068 100644 --- a/pychunkedgraph/tests/graph/edits/test_operation.py +++ b/pychunkedgraph/tests/graph/edits/test_operation.py @@ -5,7 +5,6 @@ -- all using real graph operations through the BigTable emulator. """ -from datetime import UTC, datetime from math import inf import numpy as np @@ -14,7 +13,6 @@ from ...helpers import SV, build_graph from ....graph import attributes from ....graph.operation import ( - MAX_EDIT_AGE, GraphEditOperation, MergeOperation, MulticutOperation, @@ -23,7 +21,6 @@ UndoOperation, ) from ....graph.exceptions import ( - EditDeadlineError, PreconditionError, PostconditionError, SupervoxelSplitRequiredError, @@ -698,19 +695,17 @@ def test_execute_assertion_error_clears_cache(self, gen_graph): assert cg.cache is None @pytest.mark.timeout(30) - def test_execute_refuses_a_write_past_the_edit_deadline(self, gen_graph): - """A stale op time writes nothing, logs EXCEPTION and frees its roots.""" + def test_a_failed_edit_logs_exception_and_frees_its_roots(self, gen_graph): + """A failure after locking leaves the graph untouched, so a retry lands.""" from unittest.mock import patch cg, sv = _build_two_sv_disconnected(gen_graph) sv0, sv1 = sv["a0"], sv["a1"] - stale = datetime.now(UTC).replace(microsecond=0) - MAX_EDIT_AGE with patch.object( - type(cg.client), "get_consolidated_lock_timestamp", return_value=stale + MergeOperation, "_apply", side_effect=ValueError("test failure") ), patch("pychunkedgraph.graph.err_dump.dump_err_artifact", return_value=None): - with pytest.raises(EditDeadlineError, match="cannot land") as refused: + with pytest.raises(Exception, match="test failure"): cg.add_edges("test_user", [sv0, sv1], affinities=[0.3]) - assert refused.value.status_code == 504 assert cg.get_root(sv0) != cg.get_root(sv1) op = cg.client.get_max_operation_id() diff --git a/requirements.in b/requirements.in index 62ef91ef1..1f933d653 100644 --- a/requirements.in +++ b/requirements.in @@ -34,7 +34,7 @@ cave-pipeline[distribution]>=0.0.3,<0.1 # TODO: temporary, for test images. Drop this pin and every commit carrying it before # merge, then pin the KVDbClient release. -kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/276883f1270b766abb261b41c299d96bb7c195cb.zip +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/83ba0370cb6f586453fa670352e334832e1d401e.zip # Conda only - use requirements.yml (or install manually): # graph-tool diff --git a/requirements.txt b/requirements.txt index a91d1a9d2..2f3c85e90 100644 --- a/requirements.txt +++ b/requirements.txt @@ -196,7 +196,7 @@ jsonschema==4.26.0 # python-jsonschema-objects jsonschema-specifications==2025.9.1 # via jsonschema -kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/276883f1270b766abb261b41c299d96bb7c195cb.zip +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/83ba0370cb6f586453fa670352e334832e1d401e.zip # via # -r requirements.in # cave-pipeline From 605469e20954c88a4f3d53c9544da7f0bc0ef67b Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Tue, 10 Nov 2026 21:32:07 +0000 Subject: [PATCH 08/11] test(fork): rebuild fork edit tests on the fork-edits kvdbclient - Move the temporary kvdbclient pin to KVDbClient c528caf. - Fork fixtures move to a conftest the read, mesh and edit tests share. - Fork edits change only fork roots, minted above every source root. Co-Authored-By: Claude --- pychunkedgraph/tests/fork/conftest.py | 63 ++++++++++++++++++++++++ pychunkedgraph/tests/fork/test_edits.py | 31 ++++++++++++ pychunkedgraph/tests/fork/test_meshes.py | 17 +++---- pychunkedgraph/tests/fork/test_reads.py | 57 +++++---------------- requirements.in | 2 +- requirements.txt | 2 +- 6 files changed, 116 insertions(+), 56 deletions(-) create mode 100644 pychunkedgraph/tests/fork/conftest.py create mode 100644 pychunkedgraph/tests/fork/test_edits.py diff --git a/pychunkedgraph/tests/fork/conftest.py b/pychunkedgraph/tests/fork/conftest.py new file mode 100644 index 000000000..dc8dbfcc7 --- /dev/null +++ b/pychunkedgraph/tests/fork/conftest.py @@ -0,0 +1,63 @@ +"""Fork test graphs, and forks of them carrying the mocks their stored meta lacks.""" + +from datetime import timedelta + +import numpy as np +import pytest + +from ...fork.create import create_fork +from ...graph import BackendClientInfo +from ..helpers import SV, build_graph, fake_timestamp + + +def _pair(gen_graph, edges): + """Two supervoxels in neighbouring chunks; returns (graph, their ids).""" + cg, sv = build_graph( + gen_graph, + n_layers=3, + supervoxels={"a": SV(), "b": SV(x=1)}, + edges=edges, + ) + if not cg.client.opens_forks: + pytest.skip("this backend's client opens no forks") + return cg, np.array([sv["a"], sv["b"]], dtype=np.uint64) + + +@pytest.fixture() +def joined(gen_graph): + """Two supervoxels one edge joins into one root.""" + return _pair(gen_graph, [("a", "b", 0.5)]) + + +@pytest.fixture() +def apart(gen_graph): + """Two supervoxels with no edge, so two roots.""" + return _pair(gen_graph, []) + + +@pytest.fixture() +def split_pair(joined): + """The joined pair, split now; returns (graph, ids, an earlier time).""" + cg, ids = joined + # The graph is built at fake_timestamp(), ten days back; the split runs now. + before = fake_timestamp() + timedelta(days=1) + cg.remove_edges("test_user", source_ids=ids[0], sink_ids=ids[1], mincut=False) + return cg, ids, before + + +@pytest.fixture() +def fork_of(request): + """Forks a test graph at a time; each fork's table is deleted after the test.""" + + def forked(source, name, at, **options): + info = BackendClientInfo(TYPE="bigtable", CONFIG=source.client._config) + graph = create_fork(source.graph_id, name, at, client_info=info, **options) + request.addfinalizer(graph.client._admin_table.delete) + graph.mock_edges = source.mock_edges + for attr in ("_ws_cv", "_ws_info_d", "ws_ts_scale"): + setattr(graph.meta, attr, getattr(source.meta, attr)) + graph.meta.layer_count = source.meta.layer_count + graph.meta.layer_chunk_bounds = source.meta.layer_chunk_bounds + return graph + + return forked diff --git a/pychunkedgraph/tests/fork/test_edits.py b/pychunkedgraph/tests/fork/test_edits.py new file mode 100644 index 000000000..21a9d1475 --- /dev/null +++ b/pychunkedgraph/tests/fork/test_edits.py @@ -0,0 +1,31 @@ +"""A fork's edits change its own roots alone, minting ids above its source's.""" + +from datetime import UTC, datetime + + +def _roots(graph, ids) -> int: + """How many roots `ids` climb to in `graph`.""" + return len(set(graph.get_roots(ids))) + + +def test_a_merge_on_a_fork_joins_its_roots_and_not_the_source_s(apart, fork_of): + cg, ids = apart + fork = fork_of(cg, "test_fork", datetime.now(UTC)) + fork.add_edges("test_user", list(ids), affinities=[0.5]) + assert (_roots(fork, ids), _roots(cg, ids)) == (1, 2) + + +def test_a_split_on_a_fork_parts_its_roots_and_not_the_source_s(joined, fork_of): + cg, ids = joined + fork = fork_of(cg, "test_fork", datetime.now(UTC)) + fork.remove_edges("test_user", source_ids=ids[0], sink_ids=ids[1], mincut=False) + assert (_roots(fork, ids), _roots(cg, ids)) == (2, 1) + + +def test_a_fork_edit_mints_roots_above_every_root_its_source_minted(joined, fork_of): + cg, ids = joined + fork = fork_of(cg, "test_fork", datetime.now(UTC)) + # The source's split mints roots from its counters after the fork point. + cg.remove_edges("test_user", source_ids=ids[0], sink_ids=ids[1], mincut=False) + fork.remove_edges("test_user", source_ids=ids[0], sink_ids=ids[1], mincut=False) + assert fork.get_roots(ids).min() > cg.get_roots(ids).max() diff --git a/pychunkedgraph/tests/fork/test_meshes.py b/pychunkedgraph/tests/fork/test_meshes.py index da23961a5..674a12aca 100644 --- a/pychunkedgraph/tests/fork/test_meshes.py +++ b/pychunkedgraph/tests/fork/test_meshes.py @@ -18,7 +18,6 @@ ) from ...meshing.mesh_meta import MeshMeta from ...meshing.meshgen_utils import get_mesh_name -from .test_reads import _forked, split_pair # noqa: F401 -- `split_pair` is a fixture def _meshed(cg, dynamic_mesh_dir="dynamic"): @@ -40,13 +39,13 @@ def _never_started(*args, **kwargs): def test_a_fork_finds_its_source_meshes_as_of_the_fork_point( - split_pair, request, tmp_path + split_pair, fork_of, tmp_path ): cg, ids, before = split_pair dynamic = tmp_path / "dynamic" dynamic.mkdir() _meshed(cg, dynamic.as_uri()) - fork = _forked(cg, "test_fork", before, request) + fork = fork_of(cg, "test_fork", before) assert MeshMeta(fork).dynamic_path == MeshMeta(cg).dynamic_path == dynamic.as_uri() assert MeshMeta(fork).initial_path == MeshMeta(cg).initial_path root = cg.get_root(ids[0], time_stamp=before) @@ -61,11 +60,11 @@ def test_a_fork_finds_its_source_meshes_as_of_the_fork_point( @pytest.mark.parametrize("accept", [None, "application/x.cave;manifest_version=2"]) def test_a_fork_answers_its_source_manifest_as_of_the_fork_point( - split_pair, request, monkeypatch, accept + split_pair, fork_of, monkeypatch, accept ): cg, ids, before = split_pair _meshed(cg) - fork = _forked(cg, "test_fork", before, request) + fork = fork_of(cg, "test_fork", before) graphs = {cg.graph_id: cg, fork.graph_id: fork} monkeypatch.setattr(app_utils, "get_cg", lambda table_id, **_: graphs[table_id]) # Shard readers place only nodes older than `initial_ts`, and none are; the emulator @@ -78,9 +77,9 @@ def test_a_fork_answers_its_source_manifest_as_of_the_fork_point( assert _manifest(fork, root, accept) == _manifest(cg, root, accept) -def test_remeshing_a_fork_is_refused_and_writes_nothing(split_pair, request, tmp_path): +def test_remeshing_a_fork_is_refused_and_writes_nothing(split_pair, fork_of, tmp_path): cg, ids, before = split_pair - fork = _forked(cg, "test_fork", before, request) + fork = fork_of(cg, "test_fork", before) out = tmp_path / "out" with pytest.raises(Forbidden, match="read-only fork"): meshgen.remeshing( @@ -90,10 +89,10 @@ def test_remeshing_a_fork_is_refused_and_writes_nothing(split_pair, request, tmp def test_a_remesh_request_for_a_fork_answers_403_before_queueing( - split_pair, request, monkeypatch + split_pair, fork_of, monkeypatch ): cg, ids, before = split_pair - fork = _forked(cg, "test_fork", before, request) + fork = fork_of(cg, "test_fork", before) monkeypatch.setattr(app_utils, "get_cg", lambda table_id, **_: fork) monkeypatch.setattr(common, "threading", SimpleNamespace(Thread=_never_started)) body = json.dumps({"new_lvl2_ids": [int(i) for i in fork.get_parents(ids)]}) diff --git a/pychunkedgraph/tests/fork/test_reads.py b/pychunkedgraph/tests/fork/test_reads.py index fa44db452..35e5a3122 100644 --- a/pychunkedgraph/tests/fork/test_reads.py +++ b/pychunkedgraph/tests/fork/test_reads.py @@ -1,72 +1,39 @@ """A fork reads its source as of the fork point, and so does a fork of that fork.""" -from datetime import UTC, datetime, timedelta +from datetime import UTC, datetime import numpy as np -import pytest from kvdbclient.safe_time import SETTLE -from ...fork.create import create_fork -from ...graph import BackendClientInfo from ...graph.operation import MAX_EDIT_AGE -from ..helpers import SV, build_graph, fake_timestamp -def _forked(source, name, at, request, **options): - """`create_fork` on a test graph, given the test mocks its stored meta lacks.""" - info = BackendClientInfo(TYPE="bigtable", CONFIG=source.client._config) - graph = create_fork(source.graph_id, name, at, client_info=info, **options) - request.addfinalizer(graph.client._admin_table.delete) - for attr in ("_ws_cv", "_ws_info_d", "ws_ts_scale"): - setattr(graph.meta, attr, getattr(source.meta, attr)) - graph.meta.layer_count = source.meta.layer_count - graph.meta.layer_chunk_bounds = source.meta.layer_chunk_bounds - return graph - - -@pytest.fixture() -def split_pair(gen_graph): - """Two joined supervoxels split now; returns (graph, ids, an earlier time).""" - cg, sv = build_graph( - gen_graph, - n_layers=3, - supervoxels={"a": SV(), "b": SV(x=1)}, - edges=[("a", "b", 0.5)], - ) - if not cg.client.opens_forks: - pytest.skip("this backend's client opens no forks") - # The graph is built at fake_timestamp(), ten days back; the split runs now. - before = fake_timestamp() + timedelta(days=1) - cg.remove_edges("test_user", source_ids=sv["a"], sink_ids=sv["b"], mincut=False) - return cg, np.array([sv["a"], sv["b"]], dtype=np.uint64), before - - -def test_a_fork_reads_its_source_as_of_the_fork_point(split_pair, request): +def test_a_fork_reads_its_source_as_of_the_fork_point(split_pair, fork_of): cg, ids, before = split_pair - fork = _forked(cg, "test_fork", before, request) + fork = fork_of(cg, "test_fork", before) roots = fork.get_roots(ids) assert roots[0] == roots[1] assert np.array_equal(roots, cg.get_roots(ids, time_stamp=before)) assert not np.array_equal(roots, cg.get_roots(ids)) -def test_a_fork_of_a_fork_reads_the_source_at_the_first_fork_point(split_pair, request): +def test_a_fork_of_a_fork_reads_the_source_at_the_first_fork_point(split_pair, fork_of): cg, ids, before = split_pair - first = _forked(cg, "test_fork", before, request) - second = _forked(first, "test_fork2", datetime.now(UTC), request) + first = fork_of(cg, "test_fork", before) + second = fork_of(first, "test_fork2", datetime.now(UTC)) assert np.array_equal(second.get_roots(ids), cg.get_roots(ids, time_stamp=before)) -def test_a_past_request_forks_at_exactly_that_time(split_pair, request): +def test_a_past_request_forks_at_exactly_that_time(split_pair, fork_of): cg, _, before = split_pair - marker = _forked(cg, "test_fork", before, request).client.marker + marker = fork_of(cg, "test_fork", before).client.marker assert marker.tf == marker.requested_at -def test_a_recent_request_steps_back_past_the_settle_window(split_pair, request): +def test_a_recent_request_steps_back_past_the_settle_window(split_pair, fork_of): cg, ids, _ = split_pair requested = datetime.now(UTC).replace(microsecond=0) - fork = _forked(cg, "test_fork", requested, request) + fork = fork_of(cg, "test_fork", requested) now = datetime.now(UTC) assert now - MAX_EDIT_AGE < fork.client.marker.tf <= now - SETTLE assert fork.client.marker.requested_at == requested @@ -76,7 +43,7 @@ def test_a_recent_request_steps_back_past_the_settle_window(split_pair, request) def test_the_admins_wait_choice_reaches_the_safe_time_search( - split_pair, request, monkeypatch + split_pair, fork_of, monkeypatch ): cg, _, before = split_pair waits = [] @@ -86,5 +53,5 @@ def searched(client, requested, longest_edit, wait=False): return requested monkeypatch.setattr("pychunkedgraph.fork.create.safe_time", searched) - _forked(cg, "test_fork", before, request, wait=True) + fork_of(cg, "test_fork", before, wait=True) assert waits == [True] diff --git a/requirements.in b/requirements.in index 1f933d653..64a6078b1 100644 --- a/requirements.in +++ b/requirements.in @@ -34,7 +34,7 @@ cave-pipeline[distribution]>=0.0.3,<0.1 # TODO: temporary, for test images. Drop this pin and every commit carrying it before # merge, then pin the KVDbClient release. -kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/83ba0370cb6f586453fa670352e334832e1d401e.zip +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/c528cafd3b291b12ade21bc6433d8f2f724fb53c.zip # Conda only - use requirements.yml (or install manually): # graph-tool diff --git a/requirements.txt b/requirements.txt index 2f3c85e90..cc4529c2c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -196,7 +196,7 @@ jsonschema==4.26.0 # python-jsonschema-objects jsonschema-specifications==2025.9.1 # via jsonschema -kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/83ba0370cb6f586453fa670352e334832e1d401e.zip +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/c528cafd3b291b12ade21bc6433d8f2f724fb53c.zip # via # -r requirements.in # cave-pipeline From df197ac1228e521d9e71d4364a24ce7335e23e15 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 25 Nov 2026 01:09:25 +0000 Subject: [PATCH 09/11] fix(meta): let a table's stored OCDBT flag beat the watershed marker - A watershed's populate marker no longer turns OCDBT on for a table storing enabled false. - A table storing no flag still takes the marker's. Co-Authored-By: Claude --- pychunkedgraph/graph/meta.py | 15 ++++++++++----- pychunkedgraph/tests/graph/test_meta.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/pychunkedgraph/graph/meta.py b/pychunkedgraph/graph/meta.py index d2c94119c..168ec3d4b 100644 --- a/pychunkedgraph/graph/meta.py +++ b/pychunkedgraph/graph/meta.py @@ -172,13 +172,14 @@ def ws_info(self) -> dict[str, object]: @property def ocdbt_config(self) -> OcdbtConfig: - """Per-CG OCDBT settings with precedence info-file > custom_data > defaults. + """Per-CG OCDBT settings with precedence info-file > custom_data > defaults, + save a table's stored ``enabled``, which beats the info file. The watershed's ``/ocdbt/.populated/meta.json`` is the authoritative on-disk source for fields that affect the OCDBT format (compression, - max_inline_value_bytes, populate_layer). custom_data fills per-CG - fields (enabled, sv_split_threshold) and anything the info file - doesn't pin. Both layers fall through to dataclass defaults. + max_inline_value_bytes, populate_layer). custom_data fills anything the + info file doesn't pin, and its stored flag alone decides whether this table + reads OCDBT. Both layers fall through to dataclass defaults. The result is cached in instance state after first access. Legacy ``custom_data["seg"]`` shape is read when ``"ocdbt_config"`` is @@ -194,13 +195,17 @@ def ocdbt_config(self) -> OcdbtConfig: "enabled": bool(seg.get("ocdbt", False)), "sv_split_threshold": int(seg.get("sv_split_threshold", 10)), } + stored = "ocdbt" in seg + else: + stored = "enabled" in meta_d + flag = {"enabled": meta_d["enabled"]} if stored else {} info_d = None ws = self._data_source.WATERSHED if ws: info_d = read_populate_meta(ws) - self._ocdbt_config_cached = OcdbtConfig.resolve(meta_d, info_d) + self._ocdbt_config_cached = OcdbtConfig.resolve(meta_d, info_d, flag) return self._ocdbt_config_cached @property diff --git a/pychunkedgraph/tests/graph/test_meta.py b/pychunkedgraph/tests/graph/test_meta.py index 7ad5f3e5a..a74d4be17 100644 --- a/pychunkedgraph/tests/graph/test_meta.py +++ b/pychunkedgraph/tests/graph/test_meta.py @@ -516,6 +516,25 @@ def test_ocdbt_seg_cached(self): val2 = meta.ocdbt_seg assert val1 is val2 + @pytest.mark.parametrize( + "custom_data", [{"ocdbt_config": {"enabled": False}}, {"seg": {"ocdbt": False}}] + ) + @patch( + "pychunkedgraph.graph.meta.read_populate_meta", return_value={"enabled": True} + ) + def test_a_stored_flag_beats_the_populate_marker(self, _marker, custom_data): + ds = DataSource(WATERSHED="gs://bucket/ws", DATA_VERSION=4) + meta = ChunkedGraphMeta(GraphConfig(CHUNK_SIZE=[64, 64, 64]), ds, custom_data) + assert meta.ocdbt_seg is False + + @patch( + "pychunkedgraph.graph.meta.read_populate_meta", return_value={"enabled": True} + ) + def test_a_table_storing_no_flag_takes_the_marker_s(self, _marker): + ds = DataSource(WATERSHED="gs://bucket/ws", DATA_VERSION=4) + meta = ChunkedGraphMeta(GraphConfig(CHUNK_SIZE=[64, 64, 64]), ds) + assert meta.ocdbt_seg is True + def test_ws_ocdbt_asserts_when_not_ocdbt(self): gc = GraphConfig(CHUNK_SIZE=[64, 64, 64]) ds = DataSource(DATA_VERSION=4) From 39495940f18422387dd14eb685e60485b9f28672 Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Wed, 25 Nov 2026 01:10:57 +0000 Subject: [PATCH 10/11] feat(fork): remesh a fork into its own dynamic dir - create_fork stores a copy's mesh block: its own dynamic dir, its source's inherited. - Remeshing refuses only a fork whose dynamic dir is not its own. Co-Authored-By: Claude --- pychunkedgraph/fork/create.py | 5 ++- pychunkedgraph/fork/guard.py | 16 ++++++-- pychunkedgraph/tests/fork/conftest.py | 9 ++++- pychunkedgraph/tests/fork/test_meshes.py | 51 ++++++++++++++++++------ 4 files changed, 62 insertions(+), 19 deletions(-) diff --git a/pychunkedgraph/fork/create.py b/pychunkedgraph/fork/create.py index 3e601e039..4a9dac56a 100644 --- a/pychunkedgraph/fork/create.py +++ b/pychunkedgraph/fork/create.py @@ -45,7 +45,10 @@ def create_fork( requested_at=requested, ) config = meta.graph_config._replace(ID=fork, ID_PREFIX="") - fork_meta = ChunkedGraphMeta(config, meta.data_source, deepcopy(meta.custom_data)) + # A copy's mesh block: own dynamic dir, source's dirs read for what it inherits. + fork_meta = ChunkedGraphMeta( + config, meta.data_source, deepcopy(meta.custom_data) + ).for_copied_graph(fork) version = upstream.read_table_version() upstream.close() ClientClass.create_fork_table( diff --git a/pychunkedgraph/fork/guard.py b/pychunkedgraph/fork/guard.py index 820d23ca5..66c4f42fc 100644 --- a/pychunkedgraph/fork/guard.py +++ b/pychunkedgraph/fork/guard.py @@ -1,9 +1,17 @@ -"""Refusals for a fork's writes that land outside its table.""" +"""Refusals for a fork's writes that would land in its source's storage.""" from ..graph.exceptions import Forbidden +from ..meshing.mesh_meta import MeshMeta, dynamic_dir_name def refuse_on_fork(cg, action: str) -> None: - """Raise `Forbidden` when `cg` is a fork, which writes nothing outside its table.""" - if cg.client.marker is not None: - raise Forbidden(f"{cg.graph_id} is a read-only fork: {action} is refused") + """Raise `Forbidden` when `cg` is a fork whose dynamic dir is not its own + `dynamic_`: a fork made before its block was copied names its source's.""" + if cg.client.marker is None: + return + own = "/" + dynamic_dir_name(cg.graph_id) + meshed = "dir" in cg.meta.custom_data.get("mesh", {}) + if not (meshed and MeshMeta(cg).dynamic_path.endswith(own)): + raise Forbidden( + f"{cg.graph_id} is a fork with no mesh dir of its own: {action} is refused" + ) diff --git a/pychunkedgraph/tests/fork/conftest.py b/pychunkedgraph/tests/fork/conftest.py index dc8dbfcc7..9d40736bf 100644 --- a/pychunkedgraph/tests/fork/conftest.py +++ b/pychunkedgraph/tests/fork/conftest.py @@ -7,6 +7,7 @@ from ...fork.create import create_fork from ...graph import BackendClientInfo +from ...graph.meta import ChunkedGraphMeta from ..helpers import SV, build_graph, fake_timestamp @@ -46,12 +47,16 @@ def split_pair(joined): @pytest.fixture() -def fork_of(request): +def fork_of(request, monkeypatch): """Forks a test graph at a time; each fork's table is deleted after the test.""" def forked(source, name, at, **options): info = BackendClientInfo(TYPE="bigtable", CONFIG=source.client._config) - graph = create_fork(source.graph_id, name, at, client_info=info, **options) + # The fork's fresh meta copies its mesh block from the source's mocked watershed. + ws_info = source.meta.ws_info + with monkeypatch.context() as patch: + patch.setattr(ChunkedGraphMeta, "ws_info", property(lambda _: ws_info)) + graph = create_fork(source.graph_id, name, at, client_info=info, **options) request.addfinalizer(graph.client._admin_table.delete) graph.mock_edges = source.mock_edges for attr in ("_ws_cv", "_ws_info_d", "ws_ts_scale"): diff --git a/pychunkedgraph/tests/fork/test_meshes.py b/pychunkedgraph/tests/fork/test_meshes.py index 674a12aca..bede5a55a 100644 --- a/pychunkedgraph/tests/fork/test_meshes.py +++ b/pychunkedgraph/tests/fork/test_meshes.py @@ -1,4 +1,4 @@ -"""A fork finds its source's meshes as of the fork point, and refuses to remesh.""" +"""A fork reads its source's meshes from the source's dir, and remeshes only into its own.""" import json from types import SimpleNamespace @@ -9,7 +9,7 @@ from ...app import app_utils from ...app.meshing import common from ...fork.guard import refuse_on_fork -from ...graph.exceptions import Forbidden +from ...graph.exceptions import Forbidden, NotAcceptable from ...meshing import meshgen from ...meshing.manifest import sharded from ...meshing.manifest.utils import ( @@ -19,6 +19,9 @@ from ...meshing.mesh_meta import MeshMeta from ...meshing.meshgen_utils import get_mesh_name +#: A v2 client's Accept header; a fork answers no other manifest. +V2 = "application/x.cave;manifest_version=2" + def _meshed(cg, dynamic_mesh_dir="dynamic"): """`cg` with a mesh block in its meta row; every node is newer than `initial_ts`.""" @@ -38,7 +41,7 @@ def _never_started(*args, **kwargs): raise AssertionError("a refused remesh queued its thread") -def test_a_fork_finds_its_source_meshes_as_of_the_fork_point( +def test_a_fork_reads_its_source_meshes_from_the_source_s_dir( split_pair, fork_of, tmp_path ): cg, ids, before = split_pair @@ -46,8 +49,10 @@ def test_a_fork_finds_its_source_meshes_as_of_the_fork_point( dynamic.mkdir() _meshed(cg, dynamic.as_uri()) fork = fork_of(cg, "test_fork", before) - assert MeshMeta(fork).dynamic_path == MeshMeta(cg).dynamic_path == dynamic.as_uri() - assert MeshMeta(fork).initial_path == MeshMeta(cg).initial_path + mm = MeshMeta(fork) + assert mm.dynamic_path.endswith("/dynamic_test_fork") + assert [one.path for one in mm.inherited] == [dynamic.as_uri()] + assert mm.initial_path == MeshMeta(cg).initial_path root = cg.get_root(ids[0], time_stamp=before) assert fork.get_root(ids[0]) == root nodes = get_children_before_start_layer(fork, root, start_layer=2) @@ -55,12 +60,11 @@ def test_a_fork_finds_its_source_meshes_as_of_the_fork_point( (dynamic / get_mesh_name(cg, node)).touch() found, missing = _get_dynamic_meshes(fork, nodes) assert set(found) == set(nodes) and missing.size == 0 - assert found == _get_dynamic_meshes(cg, nodes)[0] + assert all(row.startswith(dynamic.as_uri()) for row in found.values()) -@pytest.mark.parametrize("accept", [None, "application/x.cave;manifest_version=2"]) -def test_a_fork_answers_its_source_manifest_as_of_the_fork_point( - split_pair, fork_of, monkeypatch, accept +def test_a_fork_answers_only_v2_manifests_with_its_source_s_rows( + split_pair, fork_of, monkeypatch ): cg, ids, before = split_pair _meshed(cg) @@ -73,15 +77,38 @@ def test_a_fork_answers_its_source_manifest_as_of_the_fork_point( sharded, "shard_mesh_source", lambda cg: SimpleNamespace(readers={}) ) root = cg.get_root(ids[0], time_stamp=before) - assert fork.get_root(ids[0]) == root - assert _manifest(fork, root, accept) == _manifest(cg, root, accept) + with pytest.raises(NotAcceptable): + _manifest(fork, root, None) + assert _manifest(fork, root, V2) == _manifest(cg, root, V2) + + +def test_a_fork_inheriting_its_source_s_dir_is_not_refused(split_pair, fork_of): + cg, _, before = split_pair + _meshed(cg) + refuse_on_fork(fork_of(cg, "test_fork", before), "remeshing") + + +def test_a_fork_naming_its_source_s_dir_is_refused_though_it_inherits( + split_pair, fork_of +): + cg, _, before = split_pair + _meshed(cg) + fork = fork_of(cg, "test_fork", before) + block = { + **fork.meta.custom_data["mesh"], + "dynamic_mesh_dir": MeshMeta(cg).dynamic_path, + } + fork.meta._custom_data = {**fork.meta.custom_data, "mesh": block} + assert MeshMeta(fork).inherited + with pytest.raises(Forbidden, match="no mesh dir of its own"): + refuse_on_fork(fork, "remeshing") def test_remeshing_a_fork_is_refused_and_writes_nothing(split_pair, fork_of, tmp_path): cg, ids, before = split_pair fork = fork_of(cg, "test_fork", before) out = tmp_path / "out" - with pytest.raises(Forbidden, match="read-only fork"): + with pytest.raises(Forbidden, match="no mesh dir of its own"): meshgen.remeshing( fork, fork.get_parents(ids), cv_unsharded_mesh_path=out.as_uri() ) From 23f4ad4e88a05d124ace8eda8b5124141b8e8b2c Mon Sep 17 00:00:00 2001 From: Akhilesh Halageri Date: Thu, 26 Nov 2026 00:40:53 +0000 Subject: [PATCH 11/11] feat(fork): create a fork through an admin endpoint - `POST /table//fork` wraps `create_fork`, admin only, answering the fork time. - `create_fork` refuses an existing table, an OCDBT-splitting source and a used fork mesh dir, before writing. Co-Authored-By: Claude --- pychunkedgraph/app/segmentation/common.py | 32 +++++- pychunkedgraph/app/segmentation/v1/routes.py | 16 +++ pychunkedgraph/fork/create.py | 78 +++++++++---- pychunkedgraph/tests/fork/conftest.py | 8 ++ pychunkedgraph/tests/fork/test_create.py | 110 +++++++++++++++++++ pychunkedgraph/tests/fork/test_meshes.py | 17 ++- 6 files changed, 239 insertions(+), 22 deletions(-) create mode 100644 pychunkedgraph/tests/fork/test_create.py diff --git a/pychunkedgraph/app/segmentation/common.py b/pychunkedgraph/app/segmentation/common.py index d7a049f81..00973a9fb 100644 --- a/pychunkedgraph/app/segmentation/common.py +++ b/pychunkedgraph/app/segmentation/common.py @@ -7,6 +7,7 @@ from datetime import datetime, timezone from functools import reduce from collections import deque, defaultdict +from typing import NamedTuple import numpy as np import pandas as pd @@ -29,7 +30,8 @@ from pychunkedgraph.graph.analysis import pathing from pychunkedgraph.graph.misc import get_contact_sites from pychunkedgraph.graph.operation import GraphEditOperation -from pychunkedgraph.graph import basetypes +from pychunkedgraph.graph import basetypes, get_default_client_info +from pychunkedgraph.fork.create import create_fork __api_versions__ = [0, 1] __segmentation_url_prefix__ = os.environ.get("SEGMENTATION_URL_PREFIX", "segmentation") @@ -589,6 +591,34 @@ def handle_rollback(table_id): return user_operations +### FORK ----------------------------------------------------------------------- + + +class CreatedFork(NamedTuple): + """A fork the endpoint made: its table id and the fork time its marker holds.""" + + fork_id: str + fork_time: datetime + + +def handle_fork(table_id: str) -> CreatedFork: + """Forks `table_id` into the JSON body's `fork_id` at the `timestamp` arg, else now; a + fork `create_fork` refuses answers 400, and the fork it opens is closed.""" + current_app.table_id = table_id + fork_id = (request.get_json(silent=True) or {}).get("fork_id") + if not fork_id: + raise cg_exceptions.BadRequest("a fork needs a `fork_id` in the request body") + at = _parse_timestamp("timestamp", time.time(), return_datetime=True) + try: + fork = create_fork(table_id, fork_id, at, client_info=get_default_client_info()) + except cg_exceptions.PreconditionError as err: + raise cg_exceptions.BadRequest(str(err)) from err + try: + return CreatedFork(fork.graph_id, fork.client.marker.chain[0].tf) + finally: + fork.client.close() + + ### USER OPERATIONS ------------------------------------------------------------- diff --git a/pychunkedgraph/app/segmentation/v1/routes.py b/pychunkedgraph/app/segmentation/v1/routes.py index dffd502c4..efdb05154 100644 --- a/pychunkedgraph/app/segmentation/v1/routes.py +++ b/pychunkedgraph/app/segmentation/v1/routes.py @@ -178,6 +178,22 @@ def handle_rollback(table_id): return jsonify_with_kwargs(resp, int64_as_str=int64_as_str) +### FORK ----------------------------------------------------------------------- + + +@bp.route("/table//fork", methods=["POST"]) +@auth_requires_admin +@remap_public(edit=True) +def handle_fork(table_id): + created = common.handle_fork(table_id) + resp = { + "fork_id": created.fork_id, + "source": table_id, + "fork_time": created.fork_time.timestamp(), + } + return jsonify_with_kwargs(resp) + + ### USER OPERATIONS ------------------------------------------------------------- diff --git a/pychunkedgraph/fork/create.py b/pychunkedgraph/fork/create.py index 4a9dac56a..e7adf50b7 100644 --- a/pychunkedgraph/fork/create.py +++ b/pychunkedgraph/fork/create.py @@ -4,6 +4,8 @@ from copy import deepcopy from datetime import datetime +from cloudfiles import CloudFiles +from kvdbclient.exceptions import PreconditionError from kvdbclient.fork.marker import ForkMarker, Hop, MarkerState from kvdbclient.safe_time import safe_time @@ -13,6 +15,36 @@ from pychunkedgraph.graph.exceptions import ChunkedGraphError from pychunkedgraph.graph.meta import ChunkedGraphMeta from pychunkedgraph.graph.operation import MAX_EDIT_AGE +from pychunkedgraph.meshing.mesh_meta import MeshMeta + + +def holds_files(path: str) -> bool: + """Whether the cloud dir at `path` holds any file; the first one listed answers.""" + return next(iter(CloudFiles(path).list()), None) is not None + + +def _table_exists(client_class: type, table_id: str, config) -> bool: + """Whether `table_id`'s storage exists, asked of a client opened and closed for it.""" + client = client_class(table_id, config=config) + try: + return client._table_exists() + finally: + client.close() + + +def _refuse(source: str, meta: ChunkedGraphMeta, fork_meta: ChunkedGraphMeta) -> None: + """Raises `PreconditionError` for a source splitting supervoxels in OCDBT, which a fork + cannot follow, or a fork whose own dynamic dir holds a deleted namesake's meshes.""" + if meta.ocdbt_seg: + raise PreconditionError( + f"{source} splits supervoxels in OCDBT, which forks cannot" + ) + if "dir" in fork_meta.custom_data.get("mesh", {}): + path = MeshMeta(fork_meta).dynamic_path + if holds_files(path): + raise PreconditionError( + f"{path} already holds meshes; clear it to reuse the name" + ) def create_fork( @@ -26,31 +58,37 @@ def create_fork( """Fork `source` into the new table `fork` at the newest safe time at or before `at`. An edit that may still write holds that time back: the fork steps below it, or with - `wait` waits for it to finish. + `wait` waits for it to finish. A fork `_refuse` names, or an existing table, raises + `PreconditionError` before anything is written. """ ClientClass = get_client_class(client_info.TYPE) if not ClientClass.opens_forks: raise ChunkedGraphError(f"{client_info.TYPE} tables cannot be forked") + if _table_exists(ClientClass, fork, client_info.CONFIG): + raise PreconditionError(f"{fork} already exists") upstream = ClientClass(source, config=client_info.CONFIG) - meta = upstream.read_table_meta() - # A source that is itself a fork passes on its chain, read beyond this hop. - inherited = upstream.marker.chain if upstream.marker else () - requested = get_valid_timestamp(at) - tf = safe_time(upstream, requested, MAX_EDIT_AGE, wait=wait) - marker = ForkMarker( - chain=(Hop(source, tf),) + inherited, - state=MarkerState.READY, - generation=uuid.uuid4().hex, - source_max_op_id=int(upstream.get_max_operation_id()), - requested_at=requested, - ) - config = meta.graph_config._replace(ID=fork, ID_PREFIX="") - # A copy's mesh block: own dynamic dir, source's dirs read for what it inherits. - fork_meta = ChunkedGraphMeta( - config, meta.data_source, deepcopy(meta.custom_data) - ).for_copied_graph(fork) - version = upstream.read_table_version() - upstream.close() + try: + meta = upstream.read_table_meta() + config = meta.graph_config._replace(ID=fork, ID_PREFIX="") + # A copy's mesh block: own dynamic dir, source's dirs read for what it inherits. + fork_meta = ChunkedGraphMeta( + config, meta.data_source, deepcopy(meta.custom_data) + ).for_copied_graph(fork) + _refuse(source, meta, fork_meta) + # A source that is itself a fork passes on its chain, read beyond this hop. + inherited = upstream.marker.chain if upstream.marker else () + requested = get_valid_timestamp(at) + tf = safe_time(upstream, requested, MAX_EDIT_AGE, wait=wait) + marker = ForkMarker( + chain=(Hop(source, tf),) + inherited, + state=MarkerState.READY, + generation=uuid.uuid4().hex, + source_max_op_id=int(upstream.get_max_operation_id()), + requested_at=requested, + ) + version = upstream.read_table_version() + finally: + upstream.close() ClientClass.create_fork_table( fork, marker, fork_meta, version, config=client_info.CONFIG ).close() diff --git a/pychunkedgraph/tests/fork/conftest.py b/pychunkedgraph/tests/fork/conftest.py index 9d40736bf..8518a7b1f 100644 --- a/pychunkedgraph/tests/fork/conftest.py +++ b/pychunkedgraph/tests/fork/conftest.py @@ -24,6 +24,14 @@ def _pair(gen_graph, edges): return cg, np.array([sv["a"], sv["b"]], dtype=np.uint64) +@pytest.fixture(autouse=True) +def offline_creation(monkeypatch): + """Creation reads the watershed's OCDBT marker and lists the fork's mesh dir, both in + cloud storage the test graphs only name; here neither holds anything.""" + monkeypatch.setattr("pychunkedgraph.graph.meta.read_populate_meta", lambda ws: None) + monkeypatch.setattr("pychunkedgraph.fork.create.holds_files", lambda path: False) + + @pytest.fixture() def joined(gen_graph): """Two supervoxels one edge joins into one root.""" diff --git a/pychunkedgraph/tests/fork/test_create.py b/pychunkedgraph/tests/fork/test_create.py new file mode 100644 index 000000000..f9eae126d --- /dev/null +++ b/pychunkedgraph/tests/fork/test_create.py @@ -0,0 +1,110 @@ +"""A fork that cannot be made is refused before any write, and the admin endpoint forks a +table at the requested time.""" + +import inspect +from datetime import UTC, datetime +from types import SimpleNamespace + +import pytest +from flask import Flask +from kvdbclient.fork.marker import Hop + +from ...app.segmentation import common +from ...app.segmentation.v1 import routes +from ...graph.exceptions import BadRequest, PreconditionError +from ...graph.meta import ChunkedGraphMeta + +#: The fork time the stand-in fork's marker holds. +TF = datetime(2026, 11, 25, tzinfo=UTC) + + +def _opened() -> SimpleNamespace: + """A stand-in for the fork `create_fork` opens, its client recording its close.""" + client = SimpleNamespace(marker=SimpleNamespace(chain=(Hop("source", TF),))) + client.closed = False + client.close = lambda: setattr(client, "closed", True) + return SimpleNamespace(graph_id="fork", client=client) + + +def _handle(body, query=""): + """The fork handler's answer to one POST of `body`, with `query` as its args.""" + with Flask(__name__).test_request_context(f"/?{query}", method="POST", json=body): + return common.handle_fork("source") + + +def _recorded(monkeypatch) -> list[tuple[str, str, datetime]]: + """The calls the handler makes to `create_fork`, stubbed at that boundary.""" + calls = [] + + def created(*args, **_): + calls.append(args) + return _opened() + + monkeypatch.setattr(common, "create_fork", created) + return calls + + +def test_a_second_fork_under_one_name_is_refused(joined, fork_of): + cg, _ = joined + fork_of(cg, "test_fork", datetime.now(UTC)) + with pytest.raises(PreconditionError, match="test_fork already exists"): + fork_of(cg, "test_fork", datetime.now(UTC)) + + +def test_a_source_splitting_supervoxels_in_ocdbt_is_refused_writing_nothing( + joined, fork_of, monkeypatch +): + cg, _ = joined + monkeypatch.setattr(ChunkedGraphMeta, "ocdbt_seg", property(lambda _: True)) + with pytest.raises(PreconditionError, match="splits supervoxels in OCDBT"): + fork_of(cg, "test_fork", datetime.now(UTC)) + monkeypatch.setattr(ChunkedGraphMeta, "ocdbt_seg", property(lambda _: False)) + assert fork_of(cg, "test_fork", datetime.now(UTC)).graph_id == "test_fork" + + +def test_the_endpoint_forks_at_the_requested_time(monkeypatch): + calls = _recorded(monkeypatch) + _handle({"fork_id": "fork"}, "timestamp=1700000000") + assert calls == [("source", "fork", datetime.fromtimestamp(1700000000, UTC))] + + +def test_the_endpoint_forks_now_without_a_timestamp(monkeypatch): + calls = _recorded(monkeypatch) + before = datetime.now(UTC) + _handle({"fork_id": "fork"}) + assert before <= calls[0][2] <= datetime.now(UTC) + + +def test_the_endpoint_answers_the_fork_time_and_closes_the_fork(monkeypatch): + fork = _opened() + monkeypatch.setattr(common, "create_fork", lambda *args, **_: fork) + assert _handle({"fork_id": "fork"}) == common.CreatedFork("fork", TF) + assert fork.client.closed + + +def test_the_endpoint_needs_a_fork_id(monkeypatch): + calls = _recorded(monkeypatch) + with pytest.raises(BadRequest, match="fork_id"): + _handle({}) + assert calls == [] + + +def test_a_refused_fork_answers_400_with_its_reason(monkeypatch): + def refuse(*args, **kwargs): + raise PreconditionError( + "source splits supervoxels in OCDBT, which forks cannot" + ) + + monkeypatch.setattr(common, "create_fork", refuse) + with pytest.raises(BadRequest, match="splits supervoxels in OCDBT") as refused: + _handle({"fork_id": "fork"}) + assert refused.value.status_code == 400 + + +def test_the_route_answers_the_fork_its_source_and_its_time(monkeypatch): + created = common.CreatedFork("fork", TF) + monkeypatch.setattr(common, "handle_fork", lambda table_id: created) + with Flask(__name__).test_request_context(method="POST"): + answer = inspect.unwrap(routes.handle_fork)("source") + expected = {"fork_id": "fork", "source": "source", "fork_time": TF.timestamp()} + assert answer.get_json() == expected diff --git a/pychunkedgraph/tests/fork/test_meshes.py b/pychunkedgraph/tests/fork/test_meshes.py index bede5a55a..4b33baa94 100644 --- a/pychunkedgraph/tests/fork/test_meshes.py +++ b/pychunkedgraph/tests/fork/test_meshes.py @@ -8,8 +8,9 @@ from ...app import app_utils from ...app.meshing import common +from ...fork import create from ...fork.guard import refuse_on_fork -from ...graph.exceptions import Forbidden, NotAcceptable +from ...graph.exceptions import Forbidden, NotAcceptable, PreconditionError from ...meshing import meshgen from ...meshing.manifest import sharded from ...meshing.manifest.utils import ( @@ -104,6 +105,20 @@ def test_a_fork_naming_its_source_s_dir_is_refused_though_it_inherits( refuse_on_fork(fork, "remeshing") +def test_a_fork_whose_own_dynamic_dir_holds_meshes_is_refused_writing_nothing( + split_pair, fork_of, monkeypatch +): + cg, _, before = split_pair + _meshed(cg) + listed = [] + monkeypatch.setattr(create, "holds_files", lambda path: listed.append(path) or True) + with pytest.raises(PreconditionError, match="already holds meshes"): + fork_of(cg, "test_fork", before) + assert listed[0].endswith("/mesh/dynamic_test_fork") + monkeypatch.setattr(create, "holds_files", lambda path: False) + assert fork_of(cg, "test_fork", before).graph_id == "test_fork" + + def test_remeshing_a_fork_is_refused_and_writes_nothing(split_pair, fork_of, tmp_path): cg, ids, before = split_pair fork = fork_of(cg, "test_fork", before)