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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
repos:
- repo: https://github.com/psf/black
rev: 26.1.0
rev: 26.10.1
hooks:
- id: black
2 changes: 2 additions & 0 deletions pychunkedgraph/app/meshing/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions pychunkedgraph/app/meshing/v1/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/<table_id>/remeshing", methods=["POST"])
@auth_requires_permission("edit")
@remap_public(edit=True)
Expand Down
32 changes: 31 additions & 1 deletion pychunkedgraph/app/segmentation/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -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 -------------------------------------------------------------


Expand Down
16 changes: 16 additions & 0 deletions pychunkedgraph/app/segmentation/v1/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,22 @@ def handle_rollback(table_id):
return jsonify_with_kwargs(resp, int64_as_str=int64_as_str)


### FORK -----------------------------------------------------------------------


@bp.route("/table/<table_id>/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 -------------------------------------------------------------


Expand Down
1 change: 1 addition & 0 deletions pychunkedgraph/fork/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Graph forks: tables that read their source's history up to a fork point."""
95 changes: 95 additions & 0 deletions pychunkedgraph/fork/create.py
Original file line number Diff line number Diff line change
@@ -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)
17 changes: 17 additions & 0 deletions pychunkedgraph/fork/guard.py
Original file line number Diff line number Diff line change
@@ -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_<fork>`: 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"
)
1 change: 1 addition & 0 deletions pychunkedgraph/graph/chunkedgraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 10 additions & 5 deletions pychunkedgraph/graph/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``<ws>/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
Expand All @@ -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
Expand Down
Loading
Loading