Skip to content
Open
141 changes: 132 additions & 9 deletions src/datajoint/gc.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,31 @@
**per-schema**: each schema is scanned against its own subtree only. Orphan
detection is therefore confined to the collector's schemas — any subset of the
schemas sharing a store may be collected safely, and GC never touches another
schema's objects or user-managed content elsewhere in the store.
schema's objects or user-managed content elsewhere in the store. The root-level
layout, below, is the exception.

Root-level layout (``schema_prefix=""``). Files migrated from DataJoint 0.14
stay where 0.14 stored them, ``{database}/...``, which is then inside the schema
section, and ``<filepath@>`` files may lie there too. In this layout only, GC
keeps these files:

- a file that a hash reference (such as a migrated ``<blob@>`` or ``<attach@>``
value) or a ``<filepath@>`` reference points to counts as referenced;
- a file named as 0.14 named blobs and attachments (32 hex digits, optionally
followed by ``.`` and a name) is never an orphan;
- a file directly under ``{schema}/``, with no subfolder, is never an orphan.
2.x schema-addressed paths are ``{schema}/{table}/...``, so such a file is a
0.14 file stored without subfolding or a blob that 0.14 had migrated from 0.11;
- the section of a schema that still has 0.14 ``~external_*`` tracking tables is
not listed at all, and the schema is reported under ``skipped_schemas``.

GC reads references only from the schemas it collects, in the store it
collects. A file in a subfolder of ``{schema}/`` that is not named as 0.14
named its files, and that only rows of other schemas reference (for example a
``<filepath@>`` file referenced from another schema), is still listed as an
orphan. Pass every schema whose rows reference files in the store, such as a
copy migrated with ``legacy_database``, to the same collector, and preview
with ``dry_run=True`` before deleting.

See Also
--------
Expand All @@ -44,6 +68,7 @@
from __future__ import annotations

import logging
import posixpath
import re
from typing import TYPE_CHECKING, Any

Expand All @@ -58,6 +83,34 @@
# Base32 content-hash filename: 26 lowercase alphanumeric chars.
_BASE32_HASH = re.compile(r"^[a-z2-7]{26}$")

# DataJoint 0.14 named an in-store blob by the hex MD5 digest of its contents,
# and an attachment by that digest, a dot, and the attachment's name, under
# ``{database}/``. These files can sit inside the root-level schema section.
_LEGACY_014_NAME = re.compile(r"^[0-9a-f]{32}(\..+)?$")


def _kept_in_root_level_layout(path: str) -> bool:
"""
Return True for a root-level schema-section file that GC never treats as an orphan.

That is a file named as 0.14 named its blobs and attachments, or a file
directly under ``{schema}/`` (``{schema}/{name}``). 2.x schema-addressed
paths are ``{schema}/{table}/...``, so a file with no subfolder is a 0.14
file stored without subfolding, or a blob that 0.14 had migrated from 0.11.
"""
return path.count("/") == 1 or bool(_LEGACY_014_NAME.match(path.rsplit("/", 1)[-1]))


def _normalized(paths: set[str]) -> set[str]:
"""
Return reference paths in the form the store listing uses.

A ``<filepath@>`` value is stored as written, so it may hold ``./``, ``//``
or backslashes (``./{schema}/sub/a.txt``) and still read. The store listing
returns clean relative paths (``{schema}/sub/a.txt``).
"""
return {posixpath.normpath(p.replace("\\", "/")).lstrip("/") for p in paths}


def _is_covered(path: str, referenced: set[str]) -> bool:
"""
Expand Down Expand Up @@ -101,7 +154,11 @@ class GarbageCollector:
The schemas to collect. At least one is required. Every managed path
embeds its schema, so collection is per-schema and confined to these
schemas: objects of any other schema sharing the store are never listed
and never at risk — pass any subset safely.
and never at risk — pass any subset safely. The root-level layout
(``schema_prefix=""``) is the exception: there a file in a subfolder of
``{schema}/`` that only other schemas reference is listed as an orphan,
so pass every schema that references files in the store (see the
module docstring).
store : str, optional
Store name (None = the default store), keyword-only.
config : Config, optional
Expand Down Expand Up @@ -159,6 +216,27 @@ def schema_references(self, verbose: bool = False) -> set[str]:
"""
return self._references("schema_objects", verbose)

def filepath_references(self, verbose: bool = False) -> set[str]:
"""
Store paths that ``<filepath@>`` columns of live rows across this
collector's schemas point to, filtered to this collector's store.

GC reads these references only in the root-level layout
(``schema_prefix=""``), where a ``<filepath@>`` file may lie inside a
schema section. There GC does not delete a ``<filepath@>`` file it reads
a reference to; a file that only schemas outside this collector
reference is listed as an orphan (see the module docstring). Outside
that layout, ``<filepath@>`` files lie outside the scanned sections.
"""
return self._references("filepath_objects", verbose)

@staticmethod
def _attribute_names(heading, heading_attr: str) -> list[str]:
if heading_attr == "filepath_objects":
return [k for k, v in heading.attributes.items() if getattr(v.codec, "name", "") == "filepath"]
# Classification lives on the heading — one source of truth.
return getattr(heading, heading_attr)

def _references(self, heading_attr: str, verbose: bool) -> set[str]:
referenced: set[str] = set()
for schema in self.schemas:
Expand All @@ -167,8 +245,7 @@ def _references(self, heading_attr: str, verbose: bool) -> set[str]:
for table_name in schema.list_tables():
try:
table = schema.get_table(table_name)
# Classification lives on the heading — one source of truth.
for attr_name in getattr(table.heading, heading_attr):
for attr_name in self._attribute_names(table.heading, heading_attr):
attr = table.heading.attributes[attr_name]
if verbose:
logger.info(f" Scanning {table_name}.{attr_name}")
Expand Down Expand Up @@ -249,7 +326,9 @@ def list_schema_paths(self, schema_name: str) -> dict[str, int]:
datajoint/datajoint-python#1487). Such a store should set
``schema_prefix=""`` so writes and this walk use the root-level layout
consistently; otherwise those objects remain readable but outside the
scanned section.
scanned section. In that layout the section ``{schema}/`` can also hold
files migrated from DataJoint 0.14 and ``<filepath@>`` files;
:meth:`collect` keeps the ones the module docstring lists.

Returns a dict mapping each object file's relative path to size.
"""
Expand Down Expand Up @@ -277,6 +356,18 @@ def list_schema_paths(self, schema_name: str) -> dict[str, int]:
self._scan_errors.append(f"list_schema_paths({schema_name}): {e}")
return stored

@staticmethod
def _has_legacy_tracking_tables(schema: "Schema") -> bool:
"""Return True if the schema has DataJoint 0.14 ``~external_<store>`` tracking tables."""
if schema.connection.adapter.backend != "mysql":
return False # DataJoint 0.14 ran on MySQL only
return bool(
schema.connection.query(
"SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME LIKE %s",
args=(schema.database, "~external\\_%"),
).fetchone()[0]
)

# ------------------------------------------------------------------ #
# Deletion
# ------------------------------------------------------------------ #
Expand Down Expand Up @@ -340,24 +431,55 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any]
- orphaned_schema_paths: orphaned schema files as full relative store paths
- hash_paths_deleted / schema_paths_deleted / deleted / bytes_freed (0 when
dry_run) / errors / dry_run
- skipped_schemas: schemas whose root-level section was not listed
because they still have DataJoint 0.14 tracking tables

In the root-level layout (``schema_prefix=""``), files migrated from
DataJoint 0.14 and ``<filepath@>`` files can lie in a schema section;
the module docstring lists the files GC keeps there and the case it
does not cover. Preview with ``dry_run=True`` before deleting.
"""
self._scan_errors = [] # reset per-call; populated by list_*_paths below
# References can be gathered across all schemas at once: because paths
# embed the schema, a file under schema X is only ever covered by an X
# reference, so combined coverage equals per-schema coverage.
# References are gathered across all schemas at once, so a file that any
# collected schema references is kept. 2.x paths embed their schema, so
# for them combined coverage equals per-schema coverage.
hash_paths_referenced = self.hash_references(verbose=verbose)
schema_paths_referenced = self.schema_references(verbose=verbose)
root_level = not self._schema_prefix
filepath_paths_referenced = self.filepath_references(verbose=verbose) if root_level else set()

hash_paths_stored: dict[str, int] = {}
schema_paths_stored: dict[str, int] = {}
skipped_schemas: list[str] = []
for schema in self.schemas:
hash_paths_stored.update(self.list_hash_paths(schema.database))
if root_level and self._has_legacy_tracking_tables(schema):
# Root-level layout: {schema}/ is also where DataJoint 0.14 kept
# this schema's files. Their references are in 0.14 tables that
# GC does not read, so the section is not listed at all.
logger.warning(
f"Not listing {schema.database}/ in store {self.store or 'default'}: the schema has "
f"DataJoint 0.14 tracking tables (~external_*), and its 0.14 files share this folder."
)
skipped_schemas.append(schema.database)
continue
schema_paths_stored.update(self.list_schema_paths(schema.database))

orphaned_hash_paths = sorted(set(hash_paths_stored.keys()) - hash_paths_referenced)
# Coverage, not exact set difference: a referenced path may be a
# directory-valued object (many files + a manifest sidecar).
orphaned_schema_paths = sorted(p for p in schema_paths_stored if not _is_covered(p, schema_paths_referenced))
if root_level:
# The schema section is {schema}/, where DataJoint 0.14 stored its
# files and where <filepath@> files may lie. Hash and filepath
# references count too, and files named as 0.14 named them, or
# directly under {schema}/, are never orphans. A <filepath@> value
# is stored as written, so references are normalized before matching.
covering = _normalized(schema_paths_referenced | hash_paths_referenced | filepath_paths_referenced)
orphaned_schema_paths = sorted(
p for p in schema_paths_stored if not _is_covered(p, covering) and not _kept_in_root_level_layout(p)
)
else:
orphaned_schema_paths = sorted(p for p in schema_paths_stored if not _is_covered(p, schema_paths_referenced))

hash_paths_deleted = 0
schema_paths_deleted = 0
Expand Down Expand Up @@ -415,5 +537,6 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any]
"bytes_freed": bytes_freed,
"errors": errors,
"scan_errors": list(self._scan_errors),
"skipped_schemas": skipped_schemas,
"dry_run": dry_run,
}
13 changes: 12 additions & 1 deletion src/datajoint/hash_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ def get_hash(metadata: dict[str, Any], config: Config | None = None) -> bytes:
Parameters
----------
metadata : dict
Metadata dict with keys: path, hash, store (optional).
Metadata dict with keys: path, hash, store (optional), and
attachment_name (only on attachments migrated from DataJoint 0.14).
config : Config, optional
Config instance. If None, falls back to global settings.config.

Expand All @@ -280,13 +281,23 @@ def get_hash(metadata: dict[str, Any], config: Config | None = None) -> bytes:
If content is not found at the stored path.
DataJointError
If hash verification fails (data corruption).

Notes
-----
DataJoint 0.14 stored an attachment's contents alone in its file, and hashed
the attachment name, a NUL byte, and the contents. Those are the bytes that
``<attach>`` stores, so for a migrated attachment the name is put back in
front of the contents before the hash is checked.
"""
path = metadata["path"]
expected_hash = metadata["hash"]
store_name = metadata.get("store")

backend = get_store_backend(store_name, config=config)
data = backend.get_buffer(path)
attachment_name = metadata.get("attachment_name")
if attachment_name is not None:
data = attachment_name.encode("utf-8") + b"\x00" + data

# Verify hash for integrity
actual_hash = compute_hash(data)
Expand Down
Loading
Loading