diff --git a/src/polystore/__init__.py b/src/polystore/__init__.py index 9bc26a2..a9dbd6e 100644 --- a/src/polystore/__init__.py +++ b/src/polystore/__init__.py @@ -80,6 +80,8 @@ "NapariShapeType": ".streaming_constants", "StreamingDataType": ".streaming_constants", "SourcePixelRef": ".virtual_workspace", + "GitBackend": ".git", + "GitCommit": ".git", "DiskBackend": ".disk", "DiskStorageBackend": ".disk", } diff --git a/src/polystore/backend_registry.py b/src/polystore/backend_registry.py index e2fa29b..d230d92 100644 --- a/src/polystore/backend_registry.py +++ b/src/polystore/backend_registry.py @@ -74,14 +74,11 @@ def create_storage_registry() -> dict[str, DataSink]: STORAGE_BACKENDS._discover() logger.debug("Triggered backend discovery via LazyDiscoveryDict") - # Backends that require context-specific initialization (e.g., plate_root) - # These are registered lazily when needed, not at startup - SKIP_BACKENDS = {"virtual_workspace", "omero_local", "bioformats"} - registry = {} - for backend_type in STORAGE_BACKENDS.keys(): - # Skip backends that need context-specific initialization - if backend_type in SKIP_BACKENDS: + for backend_type, backend_class in STORAGE_BACKENDS.items(): + # A backend that declares it needs application context (a plate root, a + # repository) is built by the application, not here. + if backend_class.requires_context: logger.debug( f"Skipping backend '{backend_type}' - requires context-specific initialization" ) diff --git a/src/polystore/base.py b/src/polystore/base.py index 921c13f..54fa462 100644 --- a/src/polystore/base.py +++ b/src/polystore/base.py @@ -192,6 +192,13 @@ def requires_filesystem_validation(self) -> bool: """ pass + requires_context: bool = False + """ + Whether constructing this backend needs application context (a plate root, a server + connection, a repository): the application builds it and adds it to its registry. A + context-free backend is built by ``create_storage_registry``. + """ + # Class attribute: can be accessed without instantiation supports_arbitrary_files: bool = True """ diff --git a/src/polystore/bioformats_storage.py b/src/polystore/bioformats_storage.py index 180c783..deb4956 100644 --- a/src/polystore/bioformats_storage.py +++ b/src/polystore/bioformats_storage.py @@ -79,6 +79,7 @@ class BioFormatsStorageBackend(ReadOnlyBackend, PicklableBackend): """Load planes addressed directly by ``BioFormatsPlaneRef`` values.""" _backend_type = Backend.BIOFORMATS.value + requires_context = True def get_connection_params(self) -> dict[str, Any] | None: return None diff --git a/src/polystore/constants.py b/src/polystore/constants.py index f56fdf2..41a5ce8 100644 --- a/src/polystore/constants.py +++ b/src/polystore/constants.py @@ -14,6 +14,7 @@ class Backend(Enum): DISK = "disk" MEMORY = "memory" ZARR = "zarr" + GIT = "git" OME_ZARR = "ome_zarr" STREAMING = "streaming" NAPARI_STREAM = "napari_stream" diff --git a/src/polystore/git.py b/src/polystore/git.py new file mode 100644 index 0000000..3b30b4f --- /dev/null +++ b/src/polystore/git.py @@ -0,0 +1,369 @@ +"""A git repository as a storage backend: versioned, content-addressed, durable text. + +Each backend instance is one branch of a bare repository. Writes stage into the instance's +own index; :meth:`GitBackend.checkpoint` records the staged tree as a commit and moves the +branch to it atomically, which is the durability point. Identical content is stored once +(by hash) and packed with deltas, so many revisions of a mostly unchanged document cost +about one copy plus its differences. + +Everything here is git plumbing run against the repository: no working tree, no user +configuration, no hooks. The result is an ordinary repository any git tool can read. + +The backend stores bytes and text. Arrays belong in an array backend (zarr); what belongs +here is the state whose history matters and the identity of anything derived from it: +:meth:`GitBackend.blob_id` and :meth:`GitBackend.tree_id` name content, so a cache keyed +by them is valid exactly while the content it was computed from is unchanged. +""" + +from __future__ import annotations + +import fnmatch +import os +import subprocess +import tempfile +import weakref +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from typing import Any + +from .base import PicklableBackend, StorageBackend +from .constants import Backend +from .exceptions import StorageResolutionError + +_FILE_MODE = "100644" +_NO_OBJECT = "0" * 40 + + +@dataclass(frozen=True) +class GitCommit: + """One checkpoint: its id, the tree it recorded, when, and why.""" + + id: str + tree: str + timestamp: int + message: str + + +class GitBackend(StorageBackend, PicklableBackend): + """One branch of a bare git repository, written through its own staging index.""" + + _backend_type = Backend.GIT.value + requires_context = True + + def __init__(self, repository: str | Path, ref: str = "refs/heads/main") -> None: + self.repository = Path(repository) + self.ref = ref + if not (self.repository / "HEAD").is_file(): + self.repository.mkdir(parents=True, exist_ok=True) + self._run("init", "--bare", "--quiet", str(self.repository), bound=False) + # A checkpoint that returned is on disk: objects and the ref are fsynced. + self._run(f"--git-dir={self.repository}", "config", "core.fsync", "all", bound=False) + staging = self.repository / "polystore-index" + staging.mkdir(exist_ok=True) + handle, index = tempfile.mkstemp(dir=staging, suffix=".index") + os.close(handle) + os.unlink(index) # git creates it; a zero-byte file is not a valid index + self._index = index + self._finalizer = weakref.finalize(self, _discard, index) + # The checkpoint this instance's staged tree is based on: the only head its own + # checkpoint may replace. + self._base = self.head() + self._git("read-tree", self._base.id if self._base else "--empty") + + # -- git plumbing ------------------------------------------------------- + + def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) -> bytes: + environment = { + "PATH": os.environ.get("PATH", os.defpath), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_TERMINAL_PROMPT": "0", + "GIT_AUTHOR_NAME": "polystore", + "GIT_AUTHOR_EMAIL": "polystore@localhost", + "GIT_COMMITTER_NAME": "polystore", + "GIT_COMMITTER_EMAIL": "polystore@localhost", + } + command = ["git"] + if bound: + command.append(f"--git-dir={self.repository}") + environment["GIT_INDEX_FILE"] = self._index + completed = subprocess.run( + [*command, *arguments], input=input, env=environment, capture_output=True, check=False, + ) + if completed.returncode != 0: + raise StorageResolutionError( + f"git {' '.join(arguments)} failed: {completed.stderr.decode(errors='replace').strip()}" + ) + return completed.stdout + + def _git(self, *arguments: str, input: bytes | None = None) -> str: + return self._run(*arguments, input=input).decode().strip() + + @staticmethod + def _path(identifier: str | Path, *, directory: bool = False) -> str: + """The repository-relative POSIX path an identifier names; ``""`` is the root.""" + path = PurePosixPath(str(identifier)) + if path.is_absolute() or ".." in path.parts: + raise StorageResolutionError(f"Git paths are relative to the repository root: {identifier}") + text = "" if str(path) == "." else str(path) + if not text and not directory: + raise StorageResolutionError("A git file path cannot be the repository root") + return text + + def _entries(self, ref: str | None = None) -> dict[str, str]: + """Every file path and its blob id: the staged tree, or the tree at ``ref``.""" + if ref is None: + listing = self._run("ls-files", "--stage", "-z").decode() + rows = (row.split("\t", 1) for row in listing.split("\0") if row) + return {path: meta.split()[1] for meta, path in rows} + listing = self._run("ls-tree", "-r", "-z", ref).decode() + rows = (row.split("\t", 1) for row in listing.split("\0") if row) + return {path: meta.split()[2] for meta, path in rows} + + @staticmethod + def _under(entries: dict[str, str], directory: str) -> dict[str, str]: + prefix = f"{directory}/" if directory else "" + return {path: blob for path, blob in entries.items() if path.startswith(prefix)} + + # -- DataSink ----------------------------------------------------------- + + def accepts_payload(self, data: Any, identifier: str | Path) -> bool: + del identifier + return isinstance(data, (bytes, str)) + + def save(self, data: Any, identifier: str | Path, **kwargs) -> None: + """Stage ``data`` (bytes, or text as UTF-8) at ``identifier``, replacing what was there; + the previous content stays in every checkpoint that recorded it.""" + del kwargs + if isinstance(data, str): + data = data.encode("utf-8") + if not isinstance(data, bytes): + raise TypeError(f"GitBackend stores bytes or text, not {type(data).__name__}") + path = self._path(identifier) + blob = self._git("hash-object", "-w", "--stdin", input=data) + self._git("update-index", "--add", "--cacheinfo", f"{_FILE_MODE},{blob},{path}") + + def save_batch(self, data_list: list[Any], identifiers: list[str | Path], **kwargs) -> None: + if len(data_list) != len(identifiers): + raise ValueError("data_list and identifiers must have the same length") + for data, identifier in zip(data_list, identifiers, strict=True): + self.save(data, identifier, **kwargs) + + # -- DataSource --------------------------------------------------------- + + def load(self, file_path: str | Path, **kwargs) -> bytes: + """The bytes at ``file_path``: staged, or as recorded at ``ref=``.""" + path = self._path(file_path) + blob = self._entries(kwargs.get("ref")).get(path) + if blob is None: + raise FileNotFoundError(f"No such git file: {path}") + return self._run("cat-file", "blob", blob) + + def load_text(self, file_path: str | Path, **kwargs) -> str: + return self.load(file_path, **kwargs).decode("utf-8") + + def load_batch(self, file_paths: list[str | Path], **kwargs) -> list[bytes]: + return [self.load(path, **kwargs) for path in file_paths] + + def list_files( + self, + directory: str | Path, + pattern: str | None = None, + extensions: set[str] | None = None, + recursive: bool = False, + **kwargs, + ) -> list[str]: + base = self._path(directory, directory=True) + self.is_dir(base, **kwargs) + prefix = f"{base}/" if base else "" + files = [] + for path in self._under(self._entries(kwargs.get("ref")), base): + relative = path[len(prefix):] + if not recursive and "/" in relative: + continue + name = PurePosixPath(path).name + if pattern is not None and not fnmatch.fnmatch(name, pattern): + continue + if extensions is not None and PurePosixPath(name).suffix.lower() not in extensions: + continue + files.append(path) + return sorted(files) + + def is_file(self, path: str | Path, **kwargs) -> bool: + entries = self._entries(kwargs.get("ref")) + target = self._path(path, directory=True) + if target in entries: + return True + if not target or self._under(entries, target): + raise IsADirectoryError(f"Git path is a directory: {target or '.'}") + raise FileNotFoundError(f"No such git path: {target}") + + def is_dir(self, path: str | Path, **kwargs) -> bool: + entries = self._entries(kwargs.get("ref")) + target = self._path(path, directory=True) + if not target or self._under(entries, target): + return True + if target in entries: + raise NotADirectoryError(f"Git path is a file: {target}") + raise FileNotFoundError(f"No such git path: {target}") + + def list_dir(self, path: str | Path, **kwargs) -> list[str]: + base = self._path(path, directory=True) + self.is_dir(base, **kwargs) + prefix = f"{base}/" if base else "" + entries = self._under(self._entries(kwargs.get("ref")), base) + return sorted({name[len(prefix):].split("/", 1)[0] for name in entries}) + + # -- file operations ---------------------------------------------------- + + @property + def requires_filesystem_validation(self) -> bool: + return False + + def ensure_directory(self, directory: str | Path) -> str | Path: + """Git has no empty directories: one exists as soon as a file is saved under it.""" + self._path(directory, directory=True) + return directory + + def _unstage(self, paths: list[str]) -> None: + """Remove entries from the index. Mode 0 through --index-info is the removal that + needs no work tree, which a bare repository does not have.""" + self._run( + "update-index", "-z", "--index-info", + input="".join(f"0 {_NO_OBJECT}\t{path}\0" for path in paths).encode(), + ) + + def delete(self, path: str | Path) -> None: + self.is_file(path) + self._unstage([self._path(path)]) + + def delete_all(self, path: str | Path) -> None: + target = self._path(path, directory=True) + entries = self._entries() + doomed = [target] if target in entries else list(self._under(entries, target)) + if not doomed: + raise FileNotFoundError(f"No such git path: {target}") + self._unstage(doomed) + + def copy(self, src: str | Path, dst: str | Path) -> None: + """Stage ``src``'s content at ``dst``: a file, or every file under a directory.""" + source, destination = self._path(src), self._path(dst) + entries = self._entries() + moved = ( + {destination: entries[source]} if source in entries + else {destination + path[len(source):]: blob + for path, blob in self._under(entries, source).items()} + ) + if not moved: + raise FileNotFoundError(f"No such git path: {source}") + for path, blob in moved.items(): + self._git("update-index", "--add", "--cacheinfo", f"{_FILE_MODE},{blob},{path}") + + def move(self, src: str | Path, dst: str | Path) -> None: + self.copy(src, dst) + self.delete_all(src) + + # -- versions ----------------------------------------------------------- + + def head(self) -> GitCommit | None: + """The branch's latest checkpoint, or ``None`` before the first.""" + try: + commit = self._git("rev-parse", "--quiet", "--verify", f"{self.ref}^{{commit}}") + except StorageResolutionError: + return None + return self.history(limit=1, ref=commit)[0] + + def checkpoint(self, message: str) -> GitCommit: + """Record the staged tree as a commit and move the branch to it. Durable on return. + + A tree identical to the head's records nothing and returns the head. The branch moves + only from the head this instance saw: another writer's checkpoint in between is a + conflict, raised rather than overwritten. + """ + tree = self._git("write-tree") + parent = self._base + if parent is not None and parent.tree == tree: + return parent + lineage = ("-p", parent.id) if parent else () + commit = self._git("commit-tree", tree, *lineage, "-m", message) + self._git("update-ref", self.ref, commit, parent.id if parent else _NO_OBJECT) + self._base = self.history(limit=1, ref=commit)[0] + return self._base + + def history( + self, path: str | Path | None = None, *, limit: int | None = None, ref: str | None = None, + ) -> tuple[GitCommit, ...]: + """Checkpoints newest first; with ``path``, only those that changed it.""" + start = ref or self.ref + try: + self._git("rev-parse", "--quiet", "--verify", f"{start}^{{commit}}") + except StorageResolutionError: + return () + arguments = ["log", "--format=%H%x1f%T%x1f%ct%x1f%B%x1e"] + if limit is not None: + arguments.append(f"--max-count={limit}") + arguments.append(start) + if path is not None: + arguments += ["--", self._path(path, directory=True)] + records = (record.strip("\n") for record in self._run(*arguments).decode().split("\x1e")) + return tuple( + GitCommit(commit, tree, int(timestamp), message.rstrip("\n")) + for commit, tree, timestamp, message in ( + record.split("\x1f", 3) for record in records if record + ) + ) + + def restore(self, ref: str) -> None: + """Stage the tree recorded at ``ref``. The next checkpoint records the return as a + new commit; history is never rewritten.""" + self._git("read-tree", ref) + + def fork(self, ref: str) -> GitBackend: + """A new branch starting at this branch's head; staged changes are not carried.""" + head = self.head() + if head is None: + raise StorageResolutionError("A branch with no checkpoint cannot be forked") + self._git("update-ref", ref, head.id, _NO_OBJECT) + return type(self)(self.repository, ref) + + def blob_id(self, path: str | Path, **kwargs) -> str: + """The content hash of one file: equal ids are equal bytes.""" + target = self._path(path) + blob = self._entries(kwargs.get("ref")).get(target) + if blob is None: + raise FileNotFoundError(f"No such git file: {target}") + return blob + + def tree_id(self, directory: str | Path = "") -> str: + """The content hash of the staged files under ``directory``: equal ids are equal + names and bytes, whatever their history.""" + base = self._path(directory, directory=True) + self.is_dir(base) + return self._git("write-tree", *([f"--prefix={base}/"] if base else [])) + + def compact(self) -> None: + """Pack loose objects with deltas.""" + self._git("gc", "--quiet") + + # -- PicklableBackend --------------------------------------------------- + + def get_connection_params(self) -> dict[str, Any]: + return {"repository": str(self.repository), "ref": self.ref} + + def set_connection_params(self, params: dict[str, Any] | None) -> None: + if params and (params["repository"], params["ref"]) != (str(self.repository), self.ref): + raise StorageResolutionError("A git backend cannot be rebound to another branch") + + @classmethod + def from_connection_params(cls, params: dict[str, Any] | None) -> GitBackend: + if not params: + raise StorageResolutionError("A git backend needs its repository and branch") + return cls(params["repository"], params["ref"]) + + +def _discard(index: str) -> None: + for path in (index, f"{index}.lock"): + try: + os.unlink(path) + except FileNotFoundError: + pass diff --git a/src/polystore/omero_local.py b/src/polystore/omero_local.py index 0d8bf80..048647d 100644 --- a/src/polystore/omero_local.py +++ b/src/polystore/omero_local.py @@ -145,6 +145,7 @@ class OMEROLocalBackend(VirtualBackend, PicklableBackend): """ _backend_type = "omero_local" + requires_context = True def resolve_listed_address( self, diff --git a/src/polystore/virtual_workspace.py b/src/polystore/virtual_workspace.py index d3fb4ce..d7bef9a 100644 --- a/src/polystore/virtual_workspace.py +++ b/src/polystore/virtual_workspace.py @@ -203,6 +203,7 @@ class VirtualWorkspaceBackend(ReadOnlyBackend, PicklableBackend): """Read-only virtual paths dispatched through an execution-local registry.""" _backend_type = Backend.VIRTUAL_WORKSPACE.value + requires_context = True def __init__( self, diff --git a/tests/test_git_backend.py b/tests/test_git_backend.py new file mode 100644 index 0000000..5bc467e --- /dev/null +++ b/tests/test_git_backend.py @@ -0,0 +1,190 @@ +"""GitBackend: versioned, content-addressed text through git plumbing.""" + +from __future__ import annotations + +import pickle +import subprocess + +import pytest + +from polystore import FileManager, GitBackend, MemoryBackend +from polystore.backend_registry import create_storage_registry +from polystore.exceptions import StorageResolutionError + + +@pytest.fixture +def backend(tmp_path): + return GitBackend(tmp_path / "store.git") + + +def test_saved_files_are_read_back_and_listed_like_a_filesystem(backend): + backend.save("turn one", "ctx/0001-user.txt") + backend.save(b"\x00raw", "ctx/0002-tool.bin") + backend.save("a note", "ctx/notes/plan.md") + + assert backend.load_text("ctx/0001-user.txt") == "turn one" + assert backend.load("ctx/0002-tool.bin") == b"\x00raw" + assert backend.list_files("ctx") == ["ctx/0001-user.txt", "ctx/0002-tool.bin"] + assert backend.list_files("ctx", recursive=True, extensions={".md"}) == ["ctx/notes/plan.md"] + assert backend.list_files("", pattern="*.txt", recursive=True) == ["ctx/0001-user.txt"] + assert backend.list_dir("ctx") == ["0001-user.txt", "0002-tool.bin", "notes"] + assert backend.exists("ctx/notes") and backend.exists("ctx/0001-user.txt") + assert not backend.exists("ctx/missing") + with pytest.raises(IsADirectoryError): + backend.is_file("ctx") + with pytest.raises(NotADirectoryError): + backend.is_dir("ctx/0001-user.txt") + with pytest.raises(FileNotFoundError): + backend.load("ctx/missing") + + +def test_a_checkpoint_is_a_commit_any_git_reads_and_a_reopened_branch_resumes_from(tmp_path): + first = GitBackend(tmp_path / "store.git") + assert first.head() is None + first.save("v1", "doc.txt") + one = first.checkpoint("write v1") + first.save("v2", "doc.txt") + two = first.checkpoint("write v2") + + assert first.checkpoint("nothing changed") == two + assert [commit.message for commit in first.history()] == ["write v2", "write v1"] + assert first.load_text("doc.txt", ref=one.id) == "v1" + shown = subprocess.run( + ["git", f"--git-dir={tmp_path / 'store.git'}", "show", "refs/heads/main:doc.txt"], + capture_output=True, check=True, + ) + assert shown.stdout == b"v2" + reopened = GitBackend(tmp_path / "store.git") + assert reopened.head() == two + assert reopened.load_text("doc.txt") == "v2" + + +def test_writes_that_were_never_checkpointed_are_not_on_the_branch(tmp_path): + first = GitBackend(tmp_path / "store.git") + first.save("kept", "kept.txt") + first.checkpoint("keep") + first.save("staged only", "lost.txt") + + assert GitBackend(tmp_path / "store.git").list_files("") == ["kept.txt"] + + +def test_history_of_one_path_names_only_the_checkpoints_that_changed_it(backend): + backend.save("a1", "a.txt") + backend.checkpoint("a1") + backend.save("b1", "b.txt") + backend.checkpoint("b1") + backend.save("a2", "a.txt") + backend.checkpoint("a2") + + assert [commit.message for commit in backend.history("a.txt")] == ["a2", "a1"] + assert [commit.message for commit in backend.history(limit=1)] == ["a2"] + + +def test_delete_move_and_copy_change_the_staged_tree_only(backend): + backend.save("one", "ctx/0001.txt") + backend.save("two", "ctx/0002.txt") + before = backend.checkpoint("two turns") + + backend.move("ctx/0002.txt", "store/0002.txt") + backend.copy("ctx", "backup") + backend.delete("ctx/0001.txt") + + assert backend.list_files("", recursive=True) == ["backup/0001.txt", "store/0002.txt"] + assert backend.load_text("ctx/0001.txt", ref=before.id) == "one" + backend.delete_all("backup") + assert backend.list_dir("") == ["store"] + with pytest.raises(FileNotFoundError): + backend.delete("ctx/0001.txt") + + +def test_content_ids_are_equal_exactly_when_content_is_equal(backend): + backend.save("same", "a/x.txt") + backend.save("same", "b/x.txt") + backend.save("other", "c/x.txt") + + assert backend.blob_id("a/x.txt") == backend.blob_id("b/x.txt") != backend.blob_id("c/x.txt") + assert backend.tree_id("a") == backend.tree_id("b") != backend.tree_id("c") + whole = backend.tree_id() + backend.save("changed", "c/x.txt") + assert backend.tree_id("a") == backend.tree_id("b") + assert backend.tree_id() != whole + + +def test_restore_stages_a_past_tree_and_records_the_return_as_a_new_commit(backend): + backend.save("v1", "doc.txt") + one = backend.checkpoint("v1") + backend.save("v2", "doc.txt") + backend.save("extra", "extra.txt") + backend.checkpoint("v2") + + backend.restore(one.id) + assert backend.list_files("") == ["doc.txt"] + back = backend.checkpoint("back to v1") + assert back.tree == one.tree and back.id != one.id + assert [commit.message for commit in backend.history()] == ["back to v1", "v2", "v1"] + + +def test_a_fork_starts_at_the_head_and_diverges(backend): + backend.save("shared", "doc.txt") + backend.checkpoint("shared") + branch = backend.fork("refs/heads/branch") + branch.save("branch only", "doc.txt") + branch.checkpoint("diverge") + + assert backend.load_text("doc.txt") == "shared" + assert [commit.message for commit in branch.history()] == ["diverge", "shared"] + with pytest.raises(StorageResolutionError): + backend.fork("refs/heads/branch") + + +def test_a_checkpoint_never_overwrites_another_writers(tmp_path): + first = GitBackend(tmp_path / "store.git") + first.save("base", "doc.txt") + first.checkpoint("base") + second = GitBackend(tmp_path / "store.git") + first.save("first", "doc.txt") + second.save("second", "doc.txt") + second.checkpoint("second wins the race") + + with pytest.raises(StorageResolutionError): + first.checkpoint("first lost") + assert GitBackend(tmp_path / "store.git").load_text("doc.txt") == "second" + + +def test_paths_stay_inside_the_repository_and_payloads_are_bytes_or_text(backend): + for escape in ("/abs.txt", "../up.txt", "a/../../up.txt"): + with pytest.raises(StorageResolutionError): + backend.save("x", escape) + with pytest.raises(TypeError): + backend.save([1, 2, 3], "list.txt") + assert backend.accepts_payload("text", "a.txt") and not backend.accepts_payload(3, "a.txt") + + +def test_many_revisions_of_one_document_pack_to_about_one_copy(backend): + lines = [f"line {number}: " + "x" * 60 for number in range(400)] + for revision in range(40): + lines[revision] = f"edited in revision {revision}" + backend.save("\n".join(lines), "ctx/LIVE.txt") + backend.checkpoint(f"revision {revision}") + backend.compact() + + packed = sum(file.stat().st_size for file in (backend.repository / "objects").rglob("*") if file.is_file()) + assert packed < 2 * len("\n".join(lines)) + assert backend.load_text("ctx/LIVE.txt", ref=backend.history()[-1].id).startswith("edited in revision 0\nline 1:") + + +def test_it_routes_through_a_file_manager_and_survives_pickling(tmp_path): + backend = GitBackend(tmp_path / "store.git") + files = FileManager({"git": backend, "memory": MemoryBackend()}) + files.save("routed", "ctx/a.txt", backend="git") + assert files.load("ctx/a.txt", backend="git") == b"routed" + backend.checkpoint("routed") + + clone = pickle.loads(pickle.dumps(backend.get_connection_params())) + assert GitBackend.from_connection_params(clone).load_text("ctx/a.txt") == "routed" + + +def test_the_default_registry_builds_no_backend_that_needs_context(): + registry = create_storage_registry() + assert "git" not in registry and "virtual_workspace" not in registry + assert {"disk", "memory", "zarr"} <= set(registry)