From d042155403ff7e48e5e61703e6c644a8422f2b5b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:35:50 +0000 Subject: [PATCH 1/7] git: a batch is stored by two git processes whatever its size save_batch looped over save, and save started git twice per file, so a caller that records n files to add one paid 2n process starts each time. Every blob now goes through one hash-object and every path through one update-index; saving one file is the batch of one. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- src/polystore/git.py | 34 ++++++++++++++++++++++++---------- tests/test_git_backend.py | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/src/polystore/git.py b/src/polystore/git.py index 3b30b4f..a19e2ed 100644 --- a/src/polystore/git.py +++ b/src/polystore/git.py @@ -134,20 +134,34 @@ 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._run( + "update-index", "--add", "-z", "--index-info", + input="".join(f"{_FILE_MODE} {blob}\t{path}\0" + for blob, path in zip(blobs, paths, strict=True)).encode(), + ) # -- DataSource --------------------------------------------------------- diff --git a/tests/test_git_backend.py b/tests/test_git_backend.py index 5bc467e..46a57ea 100644 --- a/tests/test_git_backend.py +++ b/tests/test_git_backend.py @@ -188,3 +188,27 @@ 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" From cbd8e66f0784ffe655b96e659c4563d9b3f41b2a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:59:00 +0000 Subject: [PATCH 2/7] A git branch written through one long-lived git GitStreamBackend keeps its staged tree in memory, names blobs and trees itself, and writes each checkpoint down one git fast-import that stays open for the repository. A checkpoint starts no process: 0.8 ms against 36 ms for a context of 60 turns. It is on disk, where another process reads it, at flush; reading anything not staged here flushes first. The index member's staging steps are named methods the stream member overrides, and both pass the same branch tests. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- src/polystore/__init__.py | 1 + src/polystore/constants.py | 1 + src/polystore/git.py | 57 ++++++--- src/polystore/git_stream.py | 238 ++++++++++++++++++++++++++++++++++++ tests/test_git_backend.py | 46 ++++++- 5 files changed, 321 insertions(+), 22 deletions(-) create mode 100644 src/polystore/git_stream.py 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 a19e2ed..cd04de4 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( @@ -157,11 +181,7 @@ def save_batch(self, data_list: list[Any], identifiers: list[str | Path], **kwar "hash-object", "-w", "--stdin-paths", input="".join(f"{file}\n" for file in files).encode(), ).split() - self._run( - "update-index", "--add", "-z", "--index-info", - input="".join(f"{_FILE_MODE} {blob}\t{path}\0" - for blob, path in zip(blobs, paths, strict=True)).encode(), - ) + self._stage_blobs(dict(zip(paths, blobs, strict=True))) # -- DataSource --------------------------------------------------------- @@ -270,8 +290,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) @@ -330,7 +349,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..7b2cb21 --- /dev/null +++ b/src/polystore/git_stream.py @@ -0,0 +1,238 @@ +"""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 for the repository. A checkpoint costs no process. + +What that changes for a caller: a checkpoint is in git's hands when ``checkpoint`` returns and +on disk, where another process reads it, at ``flush``. Reading anything this instance has not +staged flushes first. The branch has this one writer: another writer's checkpoint in between +is not detected here. +""" + +from __future__ import annotations + +import atexit +import hashlib +import subprocess +import threading +import time +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 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 in this + process and open until the process ends.""" + + open_streams: ClassVar[dict[Path, GitStream]] = {} + opening: ClassVar[threading.Lock] = threading.Lock() + + def __init__(self, backend: GitStreamBackend) -> None: + self.turn = threading.RLock() + self.unflushed = 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]] = {} + 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=subprocess.PIPE, + env=backend._environment(bound=True), + ) + atexit.register(self.close) + + @classmethod + def of(cls, backend: GitStreamBackend) -> GitStream: + repository = backend.repository.resolve() + with cls.opening: + if repository not in cls.open_streams: + cls.open_streams[repository] = cls(backend) + return cls.open_streams[repository] + + @classmethod + def settle(cls, repository: Path) -> None: + """Put on disk whatever this process has streamed to ``repository``.""" + stream = cls.open_streams.get(repository.resolve()) + if stream is not None: + stream.flush() + + def told(self, text: bytes, answered: bool = False) -> str: + """Write ``text`` to git and, for a command git answers, read its one line.""" + try: + self.process.stdin.write(text) + if not answered: + return "" + self.process.stdin.flush() + answer = self.process.stdout.readline() + except BrokenPipeError: + answer = b"" + if answered and not answer: + raise StorageResolutionError( + "git fast-import stopped: " + + self.process.stderr.read().decode(errors="replace").strip()) + return answer.decode().strip() + + def commit(self, ref: str, parent: str | None, 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.""" + with self.turn: + self.marks += 1 + lines = [b"".join((b"blob\ndata %d\n" % len(data), data, b"\n")) for data in fresh.values()] + said = message.encode() + lines.append( + f"commit {ref}\nmark :{self.marks}\n" + f"committer polystore {timestamp} +0000\n".encode() + + b"data %d\n" % len(said) + said + b"\n") + tip, mark = self.tips.get(ref, (None, 0)) + lines.append(b"" if parent is None + else f"from {f':{mark}' if parent == tip 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 = self.told(b"".join(lines) + f"\nget-mark :{self.marks}\n".encode(), answered=True) + 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.""" + with self.turn: + if self.unflushed: + self.told(b"checkpoint\nprogress flushed\n", answered=True) + self.unflushed = False + + def close(self) -> None: + with self.turn: + if self.process.poll() is None: + self.process.communicate(b"done\n") + + +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.of(self) + + 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: + self._tree = super()._entries(ref) if ref else {} + 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. On disk at ``flush``.""" + tree = tree_id(self._tree) + parent = self._base + if parent is not None and parent.tree == tree: + return parent + staged = {path: blob for path, blob in self._tree.items() if self._recorded.get(path) != blob} + timestamp = int(time.time()) + commit = self._stream.commit( + self.ref, parent.id if parent else None, message, + {blob: self._fresh[blob] for blob in set(staged.values()) if blob in self._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.""" + GitStream.settle(self.repository) + + 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()}) diff --git a/tests/test_git_backend.py b/tests/test_git_backend.py index 46a57ea..350bb48 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): @@ -212,3 +214,41 @@ def counted(command, *arguments, **keywords): 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"] From 206e1423fc742f838b70906f4a9fddcf02d051c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:24:30 +0000 Subject: [PATCH 3/7] A stream branch keeps the base's promises, at flush Review (pm-trainer): a lost race was silent, the computed tree id was never checked while running, and the open git never closed. - A branch this stream has moved past the instance's head is a conflict raised at checkpoint. A branch another process moved is refused by git at flush; what git says goes to a file read at every flush, and the flush raises it. - Every checkpoint asks git for the root tree it made, in the same write, and raises if it differs from the one computed. A ref holding anything but plain files is refused when opened. - The open git closes when its last branch goes, leaves the table when it closes or dies, and is kept per process. Committer identity comes from the environment's one declaration; an unchanged checkpoint drops the blobs staged for it; answers are counted, not searched for in file content. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- src/polystore/git.py | 17 ++-- src/polystore/git_stream.py | 181 +++++++++++++++++++++++++----------- tests/test_git_backend.py | 66 +++++++++++++ 3 files changed, 203 insertions(+), 61 deletions(-) diff --git a/src/polystore/git.py b/src/polystore/git.py index cd04de4..810601a 100644 --- a/src/polystore/git.py +++ b/src/polystore/git.py @@ -134,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]: diff --git a/src/polystore/git_stream.py b/src/polystore/git_stream.py index 7b2cb21..7c92e72 100644 --- a/src/polystore/git_stream.py +++ b/src/polystore/git_stream.py @@ -3,21 +3,25 @@ ``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 for the repository. A checkpoint costs no process. - -What that changes for a caller: a checkpoint is in git's hands when ``checkpoint`` returns and -on disk, where another process reads it, at ``flush``. Reading anything this instance has not -staged flushes first. The branch has this one writer: another writer's checkpoint in between -is not detected here. +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 pathlib import Path from typing import Any, ClassVar @@ -34,8 +38,8 @@ def blob_id(data: bytes) -> str: def tree_id(entries: dict[str, str]) -> str: - """The id git gives the tree of ``entries``: each path, relative to the tree, and its - blob id.""" + """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(): @@ -62,91 +66,152 @@ def _quoted(path: str) -> str: class GitStream: - """One ``git fast-import`` on a repository, shared by every stream branch of it in this - process and open until the process ends.""" + """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.""" - open_streams: ClassVar[dict[Path, GitStream]] = {} + #: 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() - def __init__(self, backend: GitStreamBackend) -> None: + def __init__(self, backend: GitStreamBackend, key: tuple[int, Path]) -> None: + self.key = key self.turn = threading.RLock() + self.branches = 0 self.unflushed = 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. + said = backend.repository / "polystore-stream" + said.mkdir(exist_ok=True) + handle, self.said = tempfile.mkstemp(dir=said, suffix=".err") + 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=subprocess.PIPE, - env=backend._environment(bound=True), + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=handle, env=environment, ) - atexit.register(self.close) + os.close(handle) @classmethod - def of(cls, backend: GitStreamBackend) -> GitStream: - repository = backend.repository.resolve() + def joined(cls, backend: GitStreamBackend) -> GitStream: + """The repository's open stream, with one more branch on it.""" + key = (os.getpid(), backend.repository.resolve()) with cls.opening: - if repository not in cls.open_streams: - cls.open_streams[repository] = cls(backend) - return cls.open_streams[repository] + 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(repository.resolve()) + stream = cls.open_streams.get((os.getpid(), repository.resolve())) if stream is not None: stream.flush() - def told(self, text: bytes, answered: bool = False) -> str: - """Write ``text`` to git and, for a command git answers, read its one line.""" + def left(self) -> None: + """One branch fewer; the last one closes the stream.""" + with self.opening: + self.branches -= 1 + if self.branches: + return + self.close() + + def refused(self) -> str: + """What git has said since it was last asked: it is quiet unless something is wrong.""" + with open(self.said, "rb") as said: + said.seek(self.heard) + text = said.read() + 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) - if not answered: - return "" self.process.stdin.flush() - answer = self.process.stdout.readline() + lines = [self.process.stdout.readline().decode().rstrip("\n") for _ in range(answers)] except BrokenPipeError: - answer = b"" - if answered and not answer: - raise StorageResolutionError( - "git fast-import stopped: " - + self.process.stderr.read().decode(errors="replace").strip()) - return answer.decode().strip() - - def commit(self, ref: str, parent: str | None, message: str, fresh: dict[str, bytes], - removed: list[str], staged: dict[str, str], timestamp: int) -> str: + 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.""" + 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: + 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 - lines = [b"".join((b"blob\ndata %d\n" % len(data), data, b"\n")) for data in fresh.values()] 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 polystore {timestamp} +0000\n".encode() + f"committer {self.committer} {timestamp} +0000\n".encode() + b"data %d\n" % len(said) + said + b"\n") - tip, mark = self.tips.get(ref, (None, 0)) lines.append(b"" if parent is None - else f"from {f':{mark}' if parent == tip else parent}\n".encode()) + 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 = self.told(b"".join(lines) + f"\nget-mark :{self.marks}\n".encode(), answered=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.""" + """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.""" with self.turn: if self.unflushed: - self.told(b"checkpoint\nprogress flushed\n", answered=True) self.unflushed = False + self.told(b"checkpoint\nprogress flushed\n", 1) + refused = self.refused() + if refused: + 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() + os.unlink(self.said) + 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.process.poll() is None: - self.process.communicate(b"done\n") + if self.process.poll() is not None: + return + self.process.communicate(b"done\n") + refused = self.ended() + if self.process.returncode or refused: + raise StorageResolutionError( + f"git fast-import ended with {self.process.returncode}: {refused}") class GitStreamBackend(GitBackend): @@ -160,7 +225,8 @@ def _open_staging(self) -> None: self._tree: dict[str, str] = {} self._recorded: dict[str, str] = {} self._fresh: dict[str, bytes] = {} - self._stream = GitStream.of(self) + self._stream = GitStream.joined(self) + self._finalizer = weakref.finalize(self, self._stream.left) def _staging_environment(self) -> dict[str, str]: return {} @@ -172,7 +238,13 @@ def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) return super()._run(*arguments, input=input, bound=bound) def _stage_tree_at(self, ref: str | None) -> None: - self._tree = super()._entries(ref) if ref else {} + 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) @@ -211,25 +283,26 @@ def load(self, file_path: str | Path, **kwargs) -> bytes: 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. On disk at ``flush``.""" + 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} + self._fresh.clear() if parent is not None and parent.tree == tree: return parent - staged = {path: blob for path, blob in self._tree.items() if self._recorded.get(path) != blob} timestamp = int(time.time()) commit = self._stream.commit( - self.ref, parent.id if parent else None, message, - {blob: self._fresh[blob] for blob in set(staged.values()) if blob in self._fresh}, + 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.""" - GitStream.settle(self.repository) + self._stream.flush() def tree_id(self, directory: str | Path = "") -> str: base = self._path(directory, directory=True) diff --git a/tests/test_git_backend.py b/tests/test_git_backend.py index 350bb48..186a40e 100644 --- a/tests/test_git_backend.py +++ b/tests/test_git_backend.py @@ -252,3 +252,69 @@ def git(*arguments: str) -> str: 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") + + # 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" + + +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 + del two + gc.collect() + # 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 + assert GitStreamBackend(tmp_path / "store.git").head().id == made.id From a23207eae949e6d167327db1240fec7059d0be19 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:28:13 +0000 Subject: [PATCH 4/7] A stream's refusal is said once, and its record outlives the repository What git says goes to a nameless file, so a repository deleted under an open stream no longer fails the stream's close while looking for it. After a flush raises a refused branch, git is told to forget where the stream had its branches: the refusal is not repeated at close, and other branches go on. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- src/polystore/git_stream.py | 27 ++++++++++++++++----------- tests/test_git_backend.py | 10 ++++++++++ 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/polystore/git_stream.py b/src/polystore/git_stream.py index 7c92e72..4d95638 100644 --- a/src/polystore/git_stream.py +++ b/src/polystore/git_stream.py @@ -78,6 +78,7 @@ def __init__(self, backend: GitStreamBackend, key: tuple[int, Path]) -> None: 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. @@ -86,16 +87,14 @@ def __init__(self, backend: GitStreamBackend, key: tuple[int, Path]) -> None: 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. - said = backend.repository / "polystore-stream" - said.mkdir(exist_ok=True) - handle, self.said = tempfile.mkstemp(dir=said, suffix=".err") + # 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=handle, env=environment, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.said, env=environment, ) - os.close(handle) @classmethod def joined(cls, backend: GitStreamBackend) -> GitStream: @@ -125,9 +124,9 @@ def left(self) -> None: def refused(self) -> str: """What git has said since it was last asked: it is quiet unless something is wrong.""" - with open(self.said, "rb") as said: - said.seek(self.heard) - text = said.read() + # Git writes through the same open file, so its place in it is git's, not ours. + self.said.seek(self.heard) + text = self.said.read() self.heard += len(text) return text.decode(errors="replace").strip() @@ -189,6 +188,11 @@ def flush(self) -> None: 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: @@ -198,7 +202,7 @@ def ended(self) -> str: if self.open_streams.get(self.key) is self: del self.open_streams[self.key] refused = self.refused() - os.unlink(self.said) + self.said.close() return refused def close(self) -> None: @@ -209,7 +213,8 @@ def close(self) -> None: return self.process.communicate(b"done\n") refused = self.ended() - if self.process.returncode or refused: + # 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}") diff --git a/tests/test_git_backend.py b/tests/test_git_backend.py index 186a40e..a0ceaa9 100644 --- a/tests/test_git_backend.py +++ b/tests/test_git_backend.py @@ -275,6 +275,16 @@ def test_a_streamed_branch_another_writer_moved_is_a_conflict_raised_not_overwri 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" + for branch in (first, second, other): + branch._finalizer() + def test_a_stream_branch_refuses_a_ref_that_holds_more_than_plain_files(tmp_path): indexed = GitBackend(tmp_path / "store.git") From a284d010fdcf2c7a9cdd087567f1a99d90d63891 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:43:47 +0000 Subject: [PATCH 5/7] A branch's going takes no lock, and a lost race keeps what it staged Review (pm-trainer): the finalizer took the lock an opening stream holds, so a collection inside an open waited on itself for ever; and a checkpoint dropped its staged bytes before it knew the commit had happened. - A branch's finalizer only notes that it has gone. The next open or flush closes the streams left without branches; one exit hook closes the rest. - The bytes are let go after the commit returns, or when the tree is unchanged. - A stream that ended, or one inherited through a fork, says so when used. - Git's words are read beside its place in the file, not by moving it. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- src/polystore/git_stream.py | 70 ++++++++++++++++++++++++++++++------- tests/test_git_backend.py | 30 ++++++++++++++-- 2 files changed, 85 insertions(+), 15 deletions(-) diff --git a/src/polystore/git_stream.py b/src/polystore/git_stream.py index 4d95638..e550495 100644 --- a/src/polystore/git_stream.py +++ b/src/polystore/git_stream.py @@ -15,6 +15,7 @@ from __future__ import annotations +import atexit import hashlib import os import subprocess @@ -22,6 +23,7 @@ import threading import time import weakref +from collections import deque from pathlib import Path from typing import Any, ClassVar @@ -72,6 +74,9 @@ class GitStream: #: 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 @@ -96,9 +101,39 @@ def __init__(self, backend: GitStreamBackend, key: tuple[int, Path]) -> None: 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 + if not stream.branches 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: + 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: @@ -114,19 +149,19 @@ def settle(cls, repository: Path) -> None: if stream is not None: stream.flush() - def left(self) -> None: - """One branch fewer; the last one closes the stream.""" - with self.opening: - self.branches -= 1 - if self.branches: - return - self.close() + 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.""" - # Git writes through the same open file, so its place in it is git's, not ours. - self.said.seek(self.heard) - text = self.said.read() + # 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() @@ -151,6 +186,7 @@ def commit(self, ref: str, parent: str | None, tree: str, message: str, 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( @@ -182,7 +218,9 @@ def commit(self, ref: str, parent: str | None, tree: str, message: str, 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) @@ -209,7 +247,7 @@ 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.process.poll() is not None: + if self.said.closed: return self.process.communicate(b"done\n") refused = self.ended() @@ -231,7 +269,7 @@ def _open_staging(self) -> None: self._recorded: dict[str, str] = {} self._fresh: dict[str, bytes] = {} self._stream = GitStream.joined(self) - self._finalizer = weakref.finalize(self, self._stream.left) + self._finalizer = weakref.finalize(self, GitStream.departures.append, self._stream) def _staging_environment(self) -> dict[str, str]: return {} @@ -294,13 +332,16 @@ def checkpoint(self, message: str) -> GitCommit: 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} - self._fresh.clear() + # 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 @@ -314,3 +355,6 @@ def tree_id(self, directory: str | Path = "") -> str: 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 a0ceaa9..f4162cb 100644 --- a/tests/test_git_backend.py +++ b/tests/test_git_backend.py @@ -263,6 +263,9 @@ def test_a_streamed_branch_another_writer_moved_is_a_conflict_raised_not_overwri 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() @@ -282,8 +285,11 @@ def test_a_streamed_branch_another_writer_moved_is_a_conflict_raised_not_overwri 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): @@ -322,9 +328,29 @@ def streams() -> list[GitStream]: 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 - gc.collect() + 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 - assert GitStreamBackend(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") From d8a9250c76e9bc994982dd1b744d050c968d90af Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:44:15 +0000 Subject: [PATCH 6/7] A forked process does not close its parent's streams Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- src/polystore/git_stream.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/polystore/git_stream.py b/src/polystore/git_stream.py index e550495..1dd1391 100644 --- a/src/polystore/git_stream.py +++ b/src/polystore/git_stream.py @@ -111,7 +111,10 @@ def reap(cls) -> None: while cls.departures: stream = cls.departures.popleft() stream.branches -= 1 - if not stream.branches and cls.open_streams.get(stream.key) is stream: + # 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 = [] From 1eaea92a7131e591e9365614827e63c539432a4c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:47:25 +0000 Subject: [PATCH 7/7] Every stream that failed to close is named, not only the first Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdxTa9e8d6J4PvBWMM9 --- src/polystore/git_stream.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/polystore/git_stream.py b/src/polystore/git_stream.py index 1dd1391..32753c0 100644 --- a/src/polystore/git_stream.py +++ b/src/polystore/git_stream.py @@ -124,6 +124,8 @@ def reap(cls) -> None: except StorageResolutionError as failure: failures.append(failure) if failures: + for other in failures[1:]: + failures[0].add_note(str(other)) raise failures[0] @classmethod