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/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/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/__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..e7adf50b7 --- /dev/null +++ b/pychunkedgraph/fork/create.py @@ -0,0 +1,95 @@ +"""Fork a graph at the newest safe time at or before the request.""" + +import uuid +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 + +from pychunkedgraph.graph import BackendClientInfo, ChunkedGraph +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 +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( + source: str, + fork: str, + at: datetime, + *, + wait: bool = False, + client_info: BackendClientInfo = get_default_client_info(), +) -> ChunkedGraph: + """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. 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) + 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() + return ChunkedGraph(graph_id=fork, client_info=client_info) diff --git a/pychunkedgraph/fork/guard.py b/pychunkedgraph/fork/guard.py new file mode 100644 index 000000000..66c4f42fc --- /dev/null +++ b/pychunkedgraph/fork/guard.py @@ -0,0 +1,17 @@ +"""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 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/graph/chunkedgraph.py b/pychunkedgraph/graph/chunkedgraph.py index 02bac55c9..c2ad9bba2 100644 --- a/pychunkedgraph/graph/chunkedgraph.py +++ b/pychunkedgraph/graph/chunkedgraph.py @@ -57,6 +57,7 @@ def __init__( ) self._meta = meta else: + # 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/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/graph/operation.py b/pychunkedgraph/graph/operation.py index d226b2eef..290badce0 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 @@ -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 @@ -42,6 +43,9 @@ logger = get_logger(__name__) +# Edits finish within this of their op time, a known bound nothing enforces. +MAX_EDIT_AGE = timedelta(minutes=21) + def _log_edit_done(result, op_type, elapsed): new_roots = list(map(int, np.asarray(result.new_root_ids).tolist())) @@ -452,20 +456,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 +479,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, @@ -538,7 +502,7 @@ def _write( affected_records: list, old_root_ids: np.ndarray, ): - """Helper to persist changes after an edit.""" + """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) @@ -592,6 +556,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. 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/__init__.py b/pychunkedgraph/tests/fork/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/pychunkedgraph/tests/fork/conftest.py b/pychunkedgraph/tests/fork/conftest.py new file mode 100644 index 000000000..8518a7b1f --- /dev/null +++ b/pychunkedgraph/tests/fork/conftest.py @@ -0,0 +1,76 @@ +"""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 ...graph.meta import ChunkedGraphMeta +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(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.""" + 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, 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) + # 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"): + 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_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_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 new file mode 100644 index 000000000..4b33baa94 --- /dev/null +++ b/pychunkedgraph/tests/fork/test_meshes.py @@ -0,0 +1,149 @@ +"""A fork reads its source's meshes from the source's dir, and remeshes only into its own.""" + +import json +from types import SimpleNamespace + +import pytest +from flask import Flask + +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, PreconditionError +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 + +#: 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`.""" + 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_reads_its_source_meshes_from_the_source_s_dir( + split_pair, fork_of, tmp_path +): + cg, ids, before = split_pair + dynamic = tmp_path / "dynamic" + dynamic.mkdir() + _meshed(cg, dynamic.as_uri()) + fork = fork_of(cg, "test_fork", before) + 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) + 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 all(row.startswith(dynamic.as_uri()) for row in found.values()) + + +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) + 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 + # 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) + 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_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) + out = tmp_path / "out" + 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() + ) + assert not out.exists() + + +def test_a_remesh_request_for_a_fork_answers_403_before_queueing( + split_pair, fork_of, monkeypatch +): + cg, ids, before = split_pair + 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)]}) + 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/pychunkedgraph/tests/fork/test_reads.py b/pychunkedgraph/tests/fork/test_reads.py new file mode 100644 index 000000000..35e5a3122 --- /dev/null +++ b/pychunkedgraph/tests/fork/test_reads.py @@ -0,0 +1,57 @@ +"""A fork reads its source as of the fork point, and so does a fork of that fork.""" + +from datetime import UTC, datetime + +import numpy as np +from kvdbclient.safe_time import SETTLE + +from ...graph.operation import MAX_EDIT_AGE + + +def test_a_fork_reads_its_source_as_of_the_fork_point(split_pair, fork_of): + cg, ids, before = split_pair + 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, fork_of): + cg, ids, before = split_pair + 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, fork_of): + cg, _, before = split_pair + 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, fork_of): + cg, ids, _ = split_pair + requested = datetime.now(UTC).replace(microsecond=0) + 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 + # 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, fork_of, 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) + fork_of(cg, "test_fork", before, wait=True) + assert waits == [True] diff --git a/pychunkedgraph/tests/graph/edits/test_operation.py b/pychunkedgraph/tests/graph/edits/test_operation.py index ff7cacd21..e940c3068 100644 --- a/pychunkedgraph/tests/graph/edits/test_operation.py +++ b/pychunkedgraph/tests/graph/edits/test_operation.py @@ -694,6 +694,26 @@ def test_execute_assertion_error_clears_cache(self, gen_graph): assert cg.cache is None + @pytest.mark.timeout(30) + 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"] + with patch.object( + MergeOperation, "_apply", side_effect=ValueError("test failure") + ), patch("pychunkedgraph.graph.err_dump.dump_err_artifact", return_value=None): + with pytest.raises(Exception, match="test failure"): + cg.add_edges("test_user", [sv0, sv1], affinities=[0.3]) + + 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) 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) diff --git a/requirements.in b/requirements.in index f36cf492c..64a6078b1 100644 --- a/requirements.in +++ b/requirements.in @@ -26,13 +26,16 @@ 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: 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/c528cafd3b291b12ade21bc6433d8f2f724fb53c.zip + # 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..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==0.8.0 +kvdbclient @ https://github.com/seung-lab/KVDbClient/archive/c528cafd3b291b12ade21bc6433d8f2f724fb53c.zip # via # -r requirements.in # cave-pipeline