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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion opstore/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ under the same PREPARED/COMMITTED discipline; recovery completes or conflicts.

### blobs.py
- `put(bytes) -> "sha256:..."` (dedup, fsync, `<root>/blobs/sha256/<2>/<hex>`),
`open_stream/get`, `has`, `size`. Blobs deleted **only** by gc.py.
`open_stream/get`, `has`, `size`. The exclusive temp is unique per writer
(pid + random token) so two in-process puts of the same hash do not collide.
Blobs deleted **only** by gc.py.
- Named pointers table with `cas_swap(name, expected_hash|None, new_hash)`.

### leases.py
Expand Down
26 changes: 19 additions & 7 deletions opstore/src/opstore/blobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
- ``put(data) -> "sha256:<hex>"`` dedups by content hash and stores at
``<root>/blobs/sha256/<first2>/<hex>``. Writes go to a same-directory temp
file which is fsynced, atomically renamed into place, and followed by a
parent-directory fsync before the accounting row is committed. Blob files are
deleted only by gc.py.
parent-directory fsync before the accounting row is committed. The temp name
is unique per writer (pid + random token), not pid alone: two in-process
puts of the same hash — two concurrent builds of the same part — must not
collide on ``O_CREAT|O_EXCL``. Blob files are deleted only by gc.py.
- Crash points (``CrashHook``): ``blobs.put.after_file_fsync``,
``blobs.put.after_rename``, ``blobs.put.after_dir_fsync``,
``blobs.put.after_db_insert``. Recovery is re-``put``: a durable file without
Expand Down Expand Up @@ -69,18 +71,28 @@ def put(self, data: bytes, retention_class: str = "default") -> str:
final = self.path_for(blob_hash)
if not final.exists():
final.parent.mkdir(parents=True, exist_ok=True)
tmp = final.parent / f".{final.name}.{os.getpid()}.tmp"
# Pid alone is unique across processes, not across threads in this
# process. Concurrent ``put`` of the same hash (two sessions
# building the same part) used to share ``.{digest}.{pid}.tmp`` and
# the second ``O_CREAT|O_EXCL`` raised FileExistsError(17).
tmp = final.parent / f".{final.name}.{os.getpid()}.{os.urandom(8).hex()}.tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
try:
os.write(fd, data)
os.fsync(fd)
finally:
os.close(fd)
self._crash.maybe_crash(CRASH_AFTER_FILE_FSYNC)
os.rename(tmp, final)
self._crash.maybe_crash(CRASH_AFTER_RENAME)
_fsync_dir(final.parent)
self._crash.maybe_crash(CRASH_AFTER_DIR_FSYNC)
# Another writer may have installed the same content while we
# fsynced. Drop our temp rather than racing the exclusive create
# a second time; the file on disk is the same bytes.
if final.exists():
os.unlink(tmp)
else:
os.rename(tmp, final)
self._crash.maybe_crash(CRASH_AFTER_RENAME)
_fsync_dir(final.parent)
self._crash.maybe_crash(CRASH_AFTER_DIR_FSYNC)
with self._db.transaction() as conn:
conn.execute(
"INSERT INTO blobs(hash, size, created_at, retention_class) "
Expand Down
60 changes: 60 additions & 0 deletions opstore/tests/test_blobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import threading
from pathlib import Path

import pytest
Expand Down Expand Up @@ -48,6 +49,65 @@ def test_blob_path_layout_and_no_temp_leftovers(blobs: BlobStore, store_root: Pa
assert leftovers == []


def _concurrent_put(blobs: BlobStore, payload: bytes) -> tuple[list[str], list[BaseException]]:
"""Two threads, one payload, started together."""
failures: list[BaseException] = []
hashes: list[str] = []
lock = threading.Lock()
both_in = threading.Barrier(2, timeout=10)

def turn() -> None:
both_in.wait()
try:
blob_hash = blobs.put(payload)
except BaseException as exc: # pragma: no cover - the regression itself
with lock:
failures.append(exc)
return
with lock:
hashes.append(blob_hash)

threads = [threading.Thread(target=turn) for _ in range(2)]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout=30)
return hashes, failures


def test_concurrent_puts_of_the_same_bytes_do_not_raise(
blobs: BlobStore, store_root: Path, db: Database
) -> None:
"""Two threads putting the same hash must both return, not FileExistsError.

``Publisher.freeze_inputs`` releases the part lock before geometry runs, so
two sessions may build the same part at once and both ``put`` the same
artifact bytes. The temp file used to be ``.{digest}.{pid}.tmp`` — unique
across processes, not across threads — and the second ``O_CREAT|O_EXCL``
crashed ``test_two_concurrent_runs_each_read_their_own_request``.
"""
last_hash = ""
for index in range(40):
# Fresh bytes each pair so both threads still race on a missing file.
# Repeating one payload would make iteration 2+ a no-op exists() check.
payload = f"identical concurrent artifact {index}".encode()
hashes, failures = _concurrent_put(blobs, payload)
assert failures == [], repr(failures[0])
assert len(hashes) == 2
assert hashes[0] == hashes[1] == sha256_bytes(payload)
last_hash = hashes[0]

digest = hex_of(last_hash)
final = store_root / "blobs" / "sha256" / digest[:2] / digest
assert final.is_file()
leftovers = [
p for p in (store_root / "blobs").rglob("*") if p.is_file() and p.name.startswith(".")
]
assert leftovers == []
rows = db.conn.execute("SELECT hash FROM blobs WHERE hash = ?", (last_hash,)).fetchall()
assert len(rows) == 1


def test_dedup_single_file_single_row(
blobs: BlobStore, fake_clock: FakeClock, db: Database
) -> None:
Expand Down
5 changes: 4 additions & 1 deletion server/tests/test_request_binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import sys
import threading
import traceback
from collections.abc import Iterator
from pathlib import Path
from typing import Any, cast
Expand Down Expand Up @@ -108,7 +109,9 @@ def turn(key: str, principal: Principal, run_id: str) -> None:
t.start()
for t in threads:
t.join(timeout=180)
assert errors == [], f"a concurrent turn crashed: {errors[0]!r}"
assert errors == [], f"a concurrent turn crashed: {errors[0]!r}\n" + "".join(
traceback.format_exception(errors[0])
)

assert seen["a"] == [40.0], "session A's critique read session B's request"
assert seen["b"] == [77.0], "session B's critique read session A's request"
Expand Down
Loading