diff --git a/src/polystore/__init__.py b/src/polystore/__init__.py index a9dbd6e..cff74d5 100644 --- a/src/polystore/__init__.py +++ b/src/polystore/__init__.py @@ -81,6 +81,7 @@ "StreamingDataType": ".streaming_constants", "SourcePixelRef": ".virtual_workspace", "GitBackend": ".git", + "GitStreamBackend": ".git_stream", "GitCommit": ".git", "DiskBackend": ".disk", "DiskStorageBackend": ".disk", diff --git a/src/polystore/constants.py b/src/polystore/constants.py index 41a5ce8..8f0d0fb 100644 --- a/src/polystore/constants.py +++ b/src/polystore/constants.py @@ -15,6 +15,7 @@ class Backend(Enum): MEMORY = "memory" ZARR = "zarr" GIT = "git" + GIT_STREAM = "git_stream" OME_ZARR = "ome_zarr" STREAMING = "streaming" NAPARI_STREAM = "napari_stream" diff --git a/src/polystore/git.py b/src/polystore/git.py index 3b30b4f..810601a 100644 --- a/src/polystore/git.py +++ b/src/polystore/git.py @@ -58,6 +58,16 @@ def __init__(self, repository: str | Path, ref: str = "refs/heads/main") -> None 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) + self._open_staging() + # The checkpoint this instance's staged tree is based on: the only head its own + # checkpoint may replace. + self._base = self.head() + self._stage_tree_at(self._base.id if self._base else None) + + # -- where the staged tree is kept --------------------------------------- + + def _open_staging(self) -> None: + """Somewhere of this instance's own to stage in: a git index file.""" staging = self.repository / "polystore-index" staging.mkdir(exist_ok=True) handle, index = tempfile.mkstemp(dir=staging, suffix=".index") @@ -65,15 +75,28 @@ def __init__(self, repository: str | Path, ref: str = "refs/heads/main") -> None 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") + + def _staging_environment(self) -> dict[str, str]: + """What a git started for this instance is told about where it stages.""" + return {"GIT_INDEX_FILE": self._index} + + def _stage_tree_at(self, ref: str | None) -> None: + """Make the staged tree the one recorded at ``ref``; the empty tree for ``None``.""" + self._git("read-tree", ref or "--empty") + + def _stage_blobs(self, staged: dict[str, str]) -> None: + """Stage blobs git already holds, each at its path.""" + self._run( + "update-index", "--add", "-z", "--index-info", + input="".join(f"{_FILE_MODE} {blob}\t{path}\0" for path, blob in staged.items()).encode(), + ) # -- git plumbing ------------------------------------------------------- - def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) -> bytes: - environment = { + def _environment(self, bound: bool = True) -> dict[str, str]: + """What a git started here runs under: this user's and this machine's configuration + play no part, and a git bound to the repository stages where this instance does.""" + return { "PATH": os.environ.get("PATH", os.defpath), "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, @@ -82,13 +105,14 @@ def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) "GIT_AUTHOR_EMAIL": "polystore@localhost", "GIT_COMMITTER_NAME": "polystore", "GIT_COMMITTER_EMAIL": "polystore@localhost", + **(self._staging_environment() if bound else {}), } - command = ["git"] - if bound: - command.append(f"--git-dir={self.repository}") - environment["GIT_INDEX_FILE"] = self._index + + def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) -> bytes: + command = ["git", *([f"--git-dir={self.repository}"] if bound else [])] completed = subprocess.run( - [*command, *arguments], input=input, env=environment, capture_output=True, check=False, + [*command, *arguments], input=input, env=self._environment(bound), + capture_output=True, check=False, ) if completed.returncode != 0: raise StorageResolutionError( @@ -110,15 +134,18 @@ def _path(identifier: str | Path, *, directory: bool = False) -> str: raise StorageResolutionError("A git file path cannot be the repository root") return text + def _rows(self, ref: str | None = None) -> list[tuple[str, str, str]]: + """Every file's mode, blob id and path: of the staged tree, or of the tree at ``ref``.""" + listing = self._run(*(("ls-files", "--stage", "-z") if ref is None + else ("ls-tree", "-r", "-z", ref))).decode() + rows = (row.split("\t", 1) for row in listing.split("\0") if row) + # "mode blob stage" for the index, "mode type blob" for a tree. + return [(meta.split()[0], meta.split()[1 if ref is None else 2], path) + for meta, path in rows] + 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} + return {path: blob for _mode, blob, path in self._rows(ref)} @staticmethod def _under(entries: dict[str, str], directory: str) -> dict[str, str]: @@ -134,20 +161,30 @@ def accepts_payload(self, data: Any, identifier: str | Path) -> bool: 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}") + self.save_batch([data], [identifier], **kwargs) def save_batch(self, data_list: list[Any], identifiers: list[str | Path], **kwargs) -> None: + """Stage each of ``data_list`` at its identifier. Git is started twice whatever the + number of files: once to store every blob, once to stage every path.""" + del kwargs 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) + payloads = [data.encode("utf-8") if isinstance(data, str) else data for data in data_list] + for payload in payloads: + if not isinstance(payload, bytes): + raise TypeError(f"GitBackend stores bytes or text, not {type(payload).__name__}") + paths = [self._path(identifier) for identifier in identifiers] + if not paths: + return + with tempfile.TemporaryDirectory(dir=Path(self._index).parent) as folder: + files = [Path(folder) / str(number) for number in range(len(payloads))] + for file, payload in zip(files, payloads, strict=True): + file.write_bytes(payload) + blobs = self._git( + "hash-object", "-w", "--stdin-paths", + input="".join(f"{file}\n" for file in files).encode(), + ).split() + self._stage_blobs(dict(zip(paths, blobs, strict=True))) # -- DataSource --------------------------------------------------------- @@ -256,8 +293,7 @@ def copy(self, src: str | Path, dst: str | Path) -> None: ) 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}") + self._stage_blobs(moved) def move(self, src: str | Path, dst: str | Path) -> None: self.copy(src, dst) @@ -316,7 +352,7 @@ def history( 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) + self._stage_tree_at(ref) def fork(self, ref: str) -> GitBackend: """A new branch starting at this branch's head; staged changes are not carried.""" diff --git a/src/polystore/git_stream.py b/src/polystore/git_stream.py new file mode 100644 index 0000000..32753c0 --- /dev/null +++ b/src/polystore/git_stream.py @@ -0,0 +1,365 @@ +"""A git branch written through one long-lived git process. + +``GitBackend`` starts git for every operation: about a dozen processes to stage a few files and +checkpoint them. ``GitStreamBackend`` keeps its staged tree in memory, names every blob and tree +itself (a git id is a hash of the content), and writes checkpoints down one ``git fast-import`` +that stays open while any branch of the repository is open here. A checkpoint starts no +process; a ``flush`` of fewer than a hundred objects starts one. + +What the base promises when ``checkpoint`` returns, this member promises at ``flush``: the +checkpoint is on disk, and the branch moved only from the head this instance saw. A branch +another writer moved is a conflict raised by the checkpoint that can see it, or by the flush +that git refuses it at. Reading anything this instance has not staged flushes first. It holds +plain files only, and a ref that holds anything else is refused when it is opened. +""" + +from __future__ import annotations + +import atexit +import hashlib +import os +import subprocess +import tempfile +import threading +import time +import weakref +from collections import deque +from pathlib import Path +from typing import Any, ClassVar + +from polystore.constants import Backend +from polystore.exceptions import StorageResolutionError +from polystore.git import _FILE_MODE, GitBackend, GitCommit + +_TREE_MODE = "40000" + + +def blob_id(data: bytes) -> str: + """The id git gives these bytes as a file.""" + return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() # noqa: S324 - git's id + + +def tree_id(entries: dict[str, str]) -> str: + """The id git gives the tree of ``entries``: each plain file's path, relative to the tree, + and its blob id.""" + files: dict[str, str] = {} + folders: dict[str, dict[str, str]] = {} + for path, blob in entries.items(): + name, _, rest = path.partition("/") + if rest: + folders.setdefault(name, {})[rest] = blob + else: + files[name] = blob + # Git orders a tree's entries by name, a directory's name ending in a slash. + rows = sorted( + [(name.encode(), _FILE_MODE, blob) for name, blob in files.items()] + + [(f"{name}/".encode(), _TREE_MODE, tree_id(under)) for name, under in folders.items()] + ) + body = b"".join(mode.encode() + b" " + name.rstrip(b"/") + b"\0" + bytes.fromhex(identity) + for name, mode, identity in rows) + return hashlib.sha1(b"tree %d\0" % len(body) + body).hexdigest() # noqa: S324 - git's id + + +def _quoted(path: str) -> str: + """A path as fast-import reads it: as it is, or C-quoted when it could be misread.""" + if not path.startswith('"') and "\n" not in path: + return path + return '"' + path.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"' + + +class GitStream: + """One ``git fast-import`` on a repository, shared by every stream branch of it this + process has open, and closed when the last of them goes.""" + + #: The open stream of each repository, per process: a forked child opens its own. + open_streams: ClassVar[dict[tuple[int, Path], GitStream]] = {} + opening: ClassVar[threading.Lock] = threading.Lock() + #: The stream of each branch that has gone. A branch's finalizer runs at any line of any + #: thread, the one holding ``opening`` included, so it takes no lock: it only notes this. + departures: ClassVar[deque[GitStream]] = deque() + + def __init__(self, backend: GitStreamBackend, key: tuple[int, Path]) -> None: + self.key = key + self.turn = threading.RLock() + self.branches = 0 + self.unflushed = False + self.refused_a_branch = False + self.marks = 0 + #: Each branch's newest commit made here and the mark git knows it by: a commit git + #: has only in the stream is named to it by mark, one on disk by its id. + self.tips: dict[str, tuple[str, int]] = {} + environment = backend._environment(bound=True) + self.committer = (f"{environment['GIT_COMMITTER_NAME']} " + f"<{environment['GIT_COMMITTER_EMAIL']}>") + # What git says of a branch it would not move goes to a file read at every flush: a + # pipe nobody drains is read by nobody, and blocks git once it fills. The file has no + # name, so it outlives a repository deleted under it and leaves nothing behind. + self.said = tempfile.TemporaryFile() + self.heard = 0 + self.process = subprocess.Popen( # noqa: S603 - git, with this backend's own arguments + ["git", f"--git-dir={backend.repository}", "fast-import", "--quiet", "--done"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.said, env=environment, + ) + + @classmethod + def reap(cls) -> None: + """Close every stream whose branches have all gone. What a closing stream raises is + raised here, after the rest are closed: the branch it belonged to is no longer there + to be told.""" + over = [] + with cls.opening: + while cls.departures: + stream = cls.departures.popleft() + stream.branches -= 1 + # A forked process inherits its parent's notes; the parent's streams are not + # its to close. + if (not stream.branches and stream.key[0] == os.getpid() + and cls.open_streams.get(stream.key) is stream): + del cls.open_streams[stream.key] + over.append(stream) + failures = [] + for stream in over: + try: + stream.close() + except StorageResolutionError as failure: + failures.append(failure) + if failures: + for other in failures[1:]: + failures[0].add_note(str(other)) + raise failures[0] + + @classmethod + def close_all(cls) -> None: + """At exit: close the streams this process opened.""" + for stream in [stream for (pid, _), stream in cls.open_streams.items() + if pid == os.getpid()]: + stream.close() + + @classmethod + def joined(cls, backend: GitStreamBackend) -> GitStream: + """The repository's open stream, with one more branch on it.""" + cls.reap() + key = (os.getpid(), backend.repository.resolve()) + with cls.opening: + if key not in cls.open_streams: + cls.open_streams[key] = cls(backend, key) + stream = cls.open_streams[key] + stream.branches += 1 + return stream + + @classmethod + def settle(cls, repository: Path) -> None: + """Put on disk whatever this process has streamed to ``repository``.""" + stream = cls.open_streams.get((os.getpid(), repository.resolve())) + if stream is not None: + stream.flush() + + def usable(self) -> None: + """A stream is written by the process that opened it, until it ends.""" + if self.key[0] != os.getpid(): + raise StorageResolutionError( + f"this stream is process {self.key[0]}'s: a forked process opens the branch again") + if self.said.closed: + raise StorageResolutionError("this stream ended: open the branch again") + + def refused(self) -> str: + """What git has said since it was last asked: it is quiet unless something is wrong.""" + # Read beside git's place in the file: git writes through the same open file. + descriptor = self.said.fileno() + text = os.pread(descriptor, os.fstat(descriptor).st_size - self.heard, self.heard) + self.heard += len(text) + return text.decode(errors="replace").strip() + + def told(self, text: bytes, answers: int) -> list[str]: + """Write ``text`` to git and read the ``answers`` lines git answers it with.""" + try: + self.process.stdin.write(text) + self.process.stdin.flush() + lines = [self.process.stdout.readline().decode().rstrip("\n") for _ in range(answers)] + except BrokenPipeError: + lines = [""] + if not all(lines): + self.process.wait() + raise StorageResolutionError(f"git fast-import stopped: {self.ended()}") + return lines + + def commit(self, ref: str, parent: str | None, tree: str, message: str, + fresh: dict[str, bytes], removed: list[str], staged: dict[str, str], + timestamp: int) -> str: + """One checkpoint: the blobs git has not seen, then the commit that removes and stages + paths on top of ``parent``. Answers the commit's id. A branch this stream has moved + past ``parent`` is another writer's, and a tree git names otherwise than ``tree`` is + a tree this member cannot name: both raise.""" + with self.turn: + self.usable() + tip, mark = self.tips.get(ref, (parent, 0)) + if parent != tip: + raise StorageResolutionError( + f"{ref} moved to {tip} since this branch was at {parent}: " + "another writer's checkpoint is not overwritten") + self.marks += 1 + said = message.encode() + lines = [b"".join((b"blob\ndata %d\n" % len(data), data, b"\n")) + for data in fresh.values()] + lines.append( + f"commit {ref}\nmark :{self.marks}\n" + f"committer {self.committer} {timestamp} +0000\n".encode() + + b"data %d\n" % len(said) + said + b"\n") + lines.append(b"" if parent is None + else f"from {f':{mark}' if mark else parent}\n".encode()) + lines.extend(f"D {_quoted(path)}\n".encode() for path in removed) + lines.extend(f"M {_FILE_MODE} {blob} {_quoted(path)}\n".encode() + for path, blob in staged.items()) + self.unflushed = True + commit, root = self.told( + b"".join(lines) + f'\nget-mark :{self.marks}\nls :{self.marks} ""\n'.encode(), 2) + named = root.split("\t")[0].split()[-1] + if named != tree: + raise StorageResolutionError( + f"git names the tree of {commit} {named}; it was computed as {tree}") + self.tips[ref] = (commit, self.marks) + return commit + + def flush(self) -> None: + """Have git put every checkpoint so far on disk and move the branches to them. A + branch git would not move, because another writer moved it first, raises.""" + self.reap() + with self.turn: + self.usable() + if self.unflushed: + self.unflushed = False + self.told(b"checkpoint\nprogress flushed\n", 1) + refused = self.refused() + if refused: + # Said once: git forgets where the stream had each branch, so it asks again + # only for a branch that is checkpointed again from a head it does not hold. + self.process.stdin.write(b"".join(f"reset {ref}\n".encode() for ref in self.tips)) + self.tips.clear() + self.refused_a_branch = True + raise StorageResolutionError(f"git did not take a checkpoint: {refused}") + + def ended(self) -> str: + """This stream is over and no longer the repository's, so the next branch opens a new + one. Answers git's last words.""" + with self.opening: + if self.open_streams.get(self.key) is self: + del self.open_streams[self.key] + refused = self.refused() + self.said.close() + return refused + + def close(self) -> None: + """Finish the stream: what it holds goes to disk, and git's last word is heard. A + stream that already stopped has said its last.""" + with self.turn: + if self.said.closed: + return + self.process.communicate(b"done\n") + refused = self.ended() + # Git ends with 1 for a branch it refused earlier; that was raised when it did. + if refused or (self.process.returncode and not self.refused_a_branch): + raise StorageResolutionError( + f"git fast-import ended with {self.process.returncode}: {refused}") + + +class GitStreamBackend(GitBackend): + """A branch whose checkpoints are written through the repository's one open git.""" + + _backend_type = Backend.GIT_STREAM.value + + def _open_staging(self) -> None: + """The staged tree is kept here: every path and its blob id, and the bytes of each + blob git has not been given yet.""" + self._tree: dict[str, str] = {} + self._recorded: dict[str, str] = {} + self._fresh: dict[str, bytes] = {} + self._stream = GitStream.joined(self) + self._finalizer = weakref.finalize(self, GitStream.departures.append, self._stream) + + def _staging_environment(self) -> dict[str, str]: + return {} + + def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) -> bytes: + """A git started beside the stream reads what is on disk, so the stream is put there + first.""" + GitStream.settle(self.repository) + return super()._run(*arguments, input=input, bound=bound) + + def _stage_tree_at(self, ref: str | None) -> None: + rows = self._rows(ref) if ref else [] + other = sorted(path for mode, _blob, path in rows if mode != _FILE_MODE) + if other: + raise StorageResolutionError( + f"{ref} holds more than plain files ({', '.join(other[:3])}): " + "a stream branch names its own trees and knows only plain files") + self._tree = {path: blob for _mode, blob, path in rows} + if self._base is not None and ref == self._base.id: + self._recorded = dict(self._tree) + + def _stage_blobs(self, staged: dict[str, str]) -> None: + self._tree.update(staged) + + def _unstage(self, paths: list[str]) -> None: + for path in paths: + del self._tree[path] + + def _entries(self, ref: str | None = None) -> dict[str, str]: + return dict(self._tree) if ref is None else super()._entries(ref) + + def save_batch(self, data_list: list[Any], identifiers: list[str | Path], **kwargs) -> None: + """Stage each of ``data_list`` at its identifier. Nothing is started and nothing is + written: git is given the bytes with the checkpoint that records them.""" + del kwargs + if len(data_list) != len(identifiers): + raise ValueError("data_list and identifiers must have the same length") + payloads = [data.encode("utf-8") if isinstance(data, str) else data for data in data_list] + for payload in payloads: + if not isinstance(payload, bytes): + raise TypeError(f"GitBackend stores bytes or text, not {type(payload).__name__}") + for identifier, payload in zip(identifiers, payloads, strict=True): + path, blob = self._path(identifier), blob_id(payload) + if self._tree.get(path) != blob: + self._tree[path] = blob + self._fresh[blob] = payload + + def load(self, file_path: str | Path, **kwargs) -> bytes: + 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._fresh[blob] if blob in self._fresh else self._run("cat-file", "blob", blob) + + def checkpoint(self, message: str) -> GitCommit: + """Record the staged tree as a commit on the branch, through the open git. A tree + identical to the head's records nothing and returns the head. The branch moves only + from the head this instance saw, on disk at ``flush``.""" + tree = tree_id(self._tree) + parent = self._base + staged = {path: blob for path, blob in self._tree.items() if self._recorded.get(path) != blob} + fresh = {blob: self._fresh[blob] for blob in set(staged.values()) if blob in self._fresh} + # The bytes are let go only once nothing needs them: a checkpoint that raises still + # holds what it staged. + if parent is not None and parent.tree == tree: + self._fresh.clear() + return parent + timestamp = int(time.time()) + commit = self._stream.commit( + self.ref, parent.id if parent else None, tree, message, fresh, + [path for path in self._recorded if path not in self._tree], staged, timestamp) + self._fresh.clear() + self._recorded = dict(self._tree) + self._base = GitCommit(commit, tree, timestamp, message) + return self._base + + def flush(self) -> None: + """Put this repository's streamed checkpoints on disk.""" + self._stream.flush() + + def tree_id(self, directory: str | Path = "") -> str: + base = self._path(directory, directory=True) + self.is_dir(base) + prefix = f"{base}/" if base else "" + return tree_id({path[len(prefix):]: blob for path, blob in self._under(self._tree, base).items()}) + + +atexit.register(GitStream.close_all) diff --git a/tests/test_git_backend.py b/tests/test_git_backend.py index 5bc467e..f4162cb 100644 --- a/tests/test_git_backend.py +++ b/tests/test_git_backend.py @@ -10,11 +10,13 @@ from polystore import FileManager, GitBackend, MemoryBackend from polystore.backend_registry import create_storage_registry from polystore.exceptions import StorageResolutionError +from polystore.git_stream import GitStreamBackend -@pytest.fixture -def backend(tmp_path): - return GitBackend(tmp_path / "store.git") +@pytest.fixture(params=[GitBackend, GitStreamBackend]) +def backend(request, tmp_path): + """A branch of each kind: whatever a caller does to a branch, both answer alike.""" + return request.param(tmp_path / "store.git") def test_saved_files_are_read_back_and_listed_like_a_filesystem(backend): @@ -188,3 +190,167 @@ 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) + + +def test_a_batch_is_stored_by_two_git_processes_whatever_its_size(tmp_path, monkeypatch): + import subprocess + + backend = GitBackend(tmp_path / "store.git") + started: list[list[str]] = [] + run = subprocess.run + + def counted(command, *arguments, **keywords): + started.append(command) + return run(command, *arguments, **keywords) + + monkeypatch.setattr(subprocess, "run", counted) + names = [f"ctx/{number:04d} turn.txt" for number in range(60)] + backend.save_batch([f"text {number}\n" for number in range(59)] + [b"\x00bytes"], names) + assert len(started) == 2 + monkeypatch.setattr(subprocess, "run", run) + + assert backend.list_files("ctx") == names + assert backend.load_text(names[7]) == "text 7\n" and backend.load(names[-1]) == b"\x00bytes" + backend.save("replaced\n", names[7]) + backend.checkpoint("batch") + assert GitBackend(tmp_path / "store.git").load_text(names[7]) == "replaced\n" + + +def test_a_streamed_checkpoint_starts_no_process_and_any_git_reads_it_once_flushed( + tmp_path, monkeypatch): + stream = GitStreamBackend(tmp_path / "store.git") + started = [] + real_run, real_popen = subprocess.run, subprocess.Popen + monkeypatch.setattr(subprocess, "run", lambda *a, **k: started.append(a) or real_run(*a, **k)) + monkeypatch.setattr(subprocess, "Popen", lambda *a, **k: started.append(a) or real_popen(*a, **k)) + made = [] + for revision in range(20): + stream.save_batch([f"turn {revision}", "told"], [f"ctx/{revision:04d}-user.txt", "system.txt"]) + if revision == 10: + stream.delete_all("ctx/0003-user.txt") + made.append((stream.checkpoint(f"context: {revision}"), stream.tree_id("ctx"))) + assert stream.checkpoint("nothing changed") == made[-1][0] + assert not started + + stream.flush() + monkeypatch.undo() + + def git(*arguments: str) -> str: + return subprocess.run(["git", f"--git-dir={tmp_path / 'store.git'}", *arguments], + capture_output=True, check=True).stdout.decode().strip() + + # The ids it named itself are the ids git gives the same content. + for commit, context in (made[0], made[10], made[-1]): + assert git("rev-parse", f"{commit.id}^{{tree}}") == commit.tree + assert git("rev-parse", f"{commit.id}:ctx") == context + assert git("rev-parse", "refs/heads/main") == made[-1][0].id + assert git("rev-list", "--count", "refs/heads/main") == "20" + assert "ctx/0003-user.txt" not in git("ls-tree", "-r", "--name-only", made[10][0].id) + reopened = GitBackend(tmp_path / "store.git") + assert reopened.head().id == made[-1][0].id and reopened.tree_id("ctx") == made[-1][1] + resumed = GitStreamBackend(tmp_path / "store.git") + resumed.save("more", "ctx/0020-user.txt") + assert [one.message for one in (resumed.checkpoint("context: 20"), *resumed.history(limit=2)[1:])] \ + == ["context: 20", "context: 19"] + + +def test_a_streamed_branch_another_writer_moved_is_a_conflict_raised_not_overwritten(tmp_path): + # In this process: the second instance still stands where the branch was. + first = GitStreamBackend(tmp_path / "store.git") + second = GitStreamBackend(tmp_path / "store.git") + first.save("first", "doc.txt") + first.checkpoint("first") + second.save("second", "doc.txt") + with pytest.raises(StorageResolutionError, match="another writer"): + second.checkpoint("second lost") + # Losing the race does not lose what was staged: nothing of it reached git, so it is + # still here to be read and put somewhere else. + assert second.load_text("doc.txt") == "second" + + # From outside the stream: git refuses to move the branch, and the flush says so. + first.flush() + outside = GitBackend(tmp_path / "store.git") + outside.save("outside", "doc.txt") + outside.checkpoint("outside wins the race") + first.save("late", "doc.txt") + first.checkpoint("first is late") + with pytest.raises(StorageResolutionError, match="did not take a checkpoint"): + first.flush() + assert GitBackend(tmp_path / "store.git").load_text("doc.txt") == "outside" + + # It was said once: a branch that stays where it lost is not refused again, another + # branch of the repository goes on, and the stream ends clean. + other = GitStreamBackend(tmp_path / "store.git", "refs/heads/other") + other.save("other", "doc.txt") + other.checkpoint("another branch") + other.flush() + assert GitBackend(tmp_path / "store.git", "refs/heads/other").load_text("doc.txt") == "other" + from polystore.git_stream import GitStream + + for branch in (first, second, other): + branch._finalizer() + GitStream.reap() + + +def test_a_stream_branch_refuses_a_ref_that_holds_more_than_plain_files(tmp_path): + indexed = GitBackend(tmp_path / "store.git") + indexed.save("#!/bin/sh\n", "run.sh") + indexed._git("update-index", "--add", "--cacheinfo", + f"100755,{indexed.blob_id('run.sh')},run.sh") + indexed.checkpoint("an executable") + with pytest.raises(StorageResolutionError, match="plain files"): + GitStreamBackend(tmp_path / "store.git") + + +def test_a_file_that_reads_like_git_commands_is_only_a_file(tmp_path): + stream = GitStreamBackend(tmp_path / "store.git") + text = "$ ls logs\nget-mark :1\nprogress flushed\ncheckpoint\ndone\n" + stream.save(text, "ctx/0001-tool.txt") + made = stream.checkpoint("a transcript") + stream.flush() + assert GitBackend(tmp_path / "store.git").load_text("ctx/0001-tool.txt", ref=made.id) == text + + +def test_the_open_git_ends_with_the_last_branch_that_uses_it(tmp_path): + import gc + + from polystore.git_stream import GitStream + + def streams() -> list[GitStream]: + return [stream for (_pid, repository), stream in GitStream.open_streams.items() + if repository == (tmp_path / "store.git").resolve()] + + one = GitStreamBackend(tmp_path / "store.git") + two = GitStreamBackend(tmp_path / "store.git", "refs/heads/other") + (shared,) = streams() + one.save("kept", "doc.txt") + made = one.checkpoint("kept") + del one + gc.collect() + assert streams() == [shared] and shared.process.poll() is None + # A branch goes wherever the collector finds it, the thread opening a stream included, + # so its going takes no lock: it is noted, and the next open or flush closes the stream. + del two + with GitStream.opening: + gc.collect() + assert streams() == [shared] and shared.process.poll() is None + GitStreamBackend(tmp_path / "elsewhere.git") + # Closed, off the table, and what was never flushed by hand is on disk all the same. + assert streams() == [] and shared.process.poll() == 0 + assert GitBackend(tmp_path / "store.git").head().id == made.id + again = GitStreamBackend(tmp_path / "store.git") + assert again.head().id == made.id + + # A stream that ended says so to a branch still holding it, and a forked process is told + # to open its own. + (stream,) = streams() + stream.close() + again.save("late", "doc.txt") + with pytest.raises(StorageResolutionError, match="this stream ended"): + again.checkpoint("late") + fresh = GitStreamBackend(tmp_path / "store.git") + (stream,) = streams() + stream.key = (stream.key[0] + 1, stream.key[1]) + fresh.save("from a fork", "doc.txt") + with pytest.raises(StorageResolutionError, match="a forked process opens the branch again"): + fresh.checkpoint("from a fork")