mirror of
https://github.com/elder-plinius/OBLITERATUS.git
synced 2026-12-05 10:34:23 +01:00
fix(persistence): never roll back or delete published no-replace outputs; keep default checkpoint semantics
Codex review r3 for #621: once the opt-in no-replace checkpoint commit has published, it is never rolled back (a later sync failure is reported and the complete checkpoint left in place), and discovery never moves or deletes a published file (a later failure names what was published); only private temp files are removed. The staging path is never cleaned after a no-replace publish. The default replace_existing=True path keeps main's semantics unchanged (its rollback race is tracked in #645).
This commit is contained in:
5 files changed
+217
-142
No files matched your search
+7
-3
@@ -61,9 +61,13 @@ confidence-interval, and canonical substring-protocol behavior.
|
||||
(`renameat2(RENAME_NOREPLACE)` on Linux), so even an empty directory created
|
||||
by a non-cooperating process is never replaced; platforms without such a
|
||||
rename fail closed. Discovery output publishing no longer falls back to
|
||||
writing files in place when hard links are unsupported, and its rollback
|
||||
removes only files that are still the ones it published. Checkpoint rollback
|
||||
likewise leaves a destination that another process replaced after promotion.
|
||||
writing files in place when hard links are unsupported, and it never moves
|
||||
or deletes a file once published: if a later file conflicts or fails, the
|
||||
published files stay and the error names them as a possibly incomplete set.
|
||||
A `vocab-surgery apply` checkpoint is never rolled back once promoted; a later
|
||||
parent-directory sync failure is reported and the complete checkpoint stays
|
||||
in place. The default `atomic_checkpoint_directory` behavior used by other
|
||||
callers is unchanged.
|
||||
- `vocab-surgery apply` and `discover` no longer overwrite an output that a
|
||||
concurrent run created after the initial existence check (#602). The checkpoint
|
||||
destination is rechecked under the commit lock, and discovery files are
|
||||
|
||||
@@ -99,20 +99,23 @@ If the tokenizer does not expose its vocabulary, the report records
|
||||
`vocabulary_sha256: null` with a `vocabulary_sha256_unavailable_reason`, and the
|
||||
config carries no pin.
|
||||
|
||||
Discovery refuses to overwrite `--output` or `--config-output`. Both files are
|
||||
published atomically and only if neither path exists at the end of the run, so
|
||||
a concurrent run writing the same paths cannot be silently overwritten; the
|
||||
later run fails with `FileExistsError`. Each file appears complete or not at
|
||||
all: it is hard-linked into place, or, where the filesystem cannot hard-link,
|
||||
moved with an atomic rename that refuses an existing path. If neither is
|
||||
available the command fails rather than writing the file in place. When a
|
||||
later file conflicts, earlier files are removed only if they are still the
|
||||
ones this run published. The config is linked first and the
|
||||
report last, so the report never exists without its config. This is safe
|
||||
against errors but not against a crash: if the process is killed between the
|
||||
two links, the config can remain without the report, together with hidden
|
||||
`.<name>.<uuid>.tmp` files beside the outputs. Delete them before rerunning,
|
||||
because the rerun refuses an existing `--config-output`.
|
||||
Discovery refuses to overwrite `--output` or `--config-output`. Each file is
|
||||
published only if its path does not exist, so a concurrent run writing the
|
||||
same paths cannot be silently overwritten; the later run fails with
|
||||
`FileExistsError`. Each file appears complete or not at all: it is hard-linked
|
||||
into place, or, where the filesystem cannot hard-link, moved with an atomic
|
||||
rename that refuses an existing path. If neither is available the command fails
|
||||
rather than writing the file in place.
|
||||
|
||||
The config is published first and the report last, so the report never exists
|
||||
without its config. A published file is never moved or deleted afterwards,
|
||||
because there is no race-free way to prove it was not replaced by another
|
||||
process. If the report then conflicts or fails to publish, the config stays in
|
||||
place and the error names it and says the pair may be incomplete; only private
|
||||
temporary files are removed. A crash between the two links leaves the same
|
||||
state, plus hidden `.<name>.<uuid>.tmp` files beside the outputs. Review or
|
||||
delete the leftover config before rerunning, because the rerun refuses an
|
||||
existing `--config-output`.
|
||||
|
||||
If an edited model routes around the first token set, run discovery on the new
|
||||
residual responses and extend the reviewed config rather than replacing it:
|
||||
@@ -197,8 +200,9 @@ creates the same `--output-dir` first, even as an empty directory, this run
|
||||
fails with `FileExistsError` and leaves it intact. On a platform or filesystem
|
||||
without such a rename the command fails instead of risking a replacement;
|
||||
choose an output location on a local filesystem that supports atomic
|
||||
no-replace rename. If the commit fails after promotion, rollback leaves the
|
||||
destination alone when another process has already replaced it.
|
||||
no-replace rename. Once the checkpoint is promoted it is complete and is never
|
||||
rolled back: if syncing the parent directory then fails, the command reports
|
||||
that the rename may not survive a crash and leaves the checkpoint in place.
|
||||
Before publishing the standalone Hugging Face checkpoint, the CLI reloads its
|
||||
staged tokenizer locally and compares the default template digest with the one
|
||||
observed at load time. A mismatch aborts the export. The receipt records both
|
||||
|
||||
@@ -371,46 +371,14 @@ def _checkpoint_lock(destination: Path) -> Iterator[None]:
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def _path_identity(path: Path) -> tuple[int, int] | None:
|
||||
"""Return ``(st_dev, st_ino)`` of ``path`` without following symlinks."""
|
||||
try:
|
||||
status = os.lstat(path)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
return status.st_dev, status.st_ino
|
||||
|
||||
|
||||
def _rollback_checkpoint_commit(
|
||||
destination: Path,
|
||||
staging: Path,
|
||||
backup: Path | None,
|
||||
*,
|
||||
had_destination: bool,
|
||||
promoted_identity: tuple[int, int] | None = None,
|
||||
) -> None:
|
||||
"""Restore the pre-commit state after a failed or cancelled commit.
|
||||
|
||||
``promoted_identity`` is the staging directory's ``(st_dev, st_ino)``. When
|
||||
given, a destination with another identity belongs to a writer that
|
||||
bypassed the commit lock and is never moved, replaced or deleted.
|
||||
"""
|
||||
if (
|
||||
promoted_identity is not None
|
||||
and _path_exists(destination)
|
||||
and _path_identity(destination) != promoted_identity
|
||||
and not _path_exists(staging)
|
||||
):
|
||||
logger.warning(
|
||||
"Leaving checkpoint destination %s in place during rollback: "
|
||||
"another writer replaced it",
|
||||
destination,
|
||||
)
|
||||
if backup is not None and _path_exists(backup):
|
||||
raise RuntimeError(
|
||||
f"Checkpoint destination {destination} was replaced by another writer; "
|
||||
f"recover the previous checkpoint from {backup}",
|
||||
)
|
||||
return
|
||||
"""Restore the pre-commit state after a failed or cancelled commit."""
|
||||
if backup is not None and _path_exists(backup):
|
||||
if _path_exists(destination):
|
||||
if _path_exists(staging):
|
||||
@@ -450,18 +418,23 @@ def atomic_checkpoint_directory(
|
||||
|
||||
An existing checkpoint is moved to a uniquely named backup immediately
|
||||
before promotion. Concurrent commits to the same destination are serialized.
|
||||
With ``replace_existing=False`` the destination is checked under the commit
|
||||
lock instead, and the staging directory is promoted with an atomic rename
|
||||
that refuses an existing destination, so the commit fails with
|
||||
``FileExistsError`` if any path occupies it, even an empty directory created
|
||||
by a writer that bypasses the lock. Where no such rename exists the commit
|
||||
fails with ``NoReplaceRenameUnsupported`` instead of risking a replacement.
|
||||
Validation and durable file flushes happen before the commit lock is taken.
|
||||
If commit or parent-directory sync fails, the previous destination is
|
||||
restored. Cancellation and other ``BaseException`` failures follow the same
|
||||
rollback path as ordinary exceptions. Strict backup cleanup failures after
|
||||
promotion are uncertain: backup removal may already be partial, so neither
|
||||
the promoted destination nor the surviving backup is used for rollback.
|
||||
|
||||
``replace_existing=False`` opts into no-clobber publishing. The destination
|
||||
is checked under the commit lock, and the staging directory is promoted with
|
||||
an atomic rename that refuses any existing path, even an empty directory
|
||||
created by a writer that bypasses the lock; a conflict raises
|
||||
``FileExistsError``. Where no such rename exists the commit fails with
|
||||
``NoReplaceRenameUnsupported`` instead of risking a replacement. Once that
|
||||
promotion succeeds the checkpoint is complete and is never rolled back or
|
||||
removed: a later parent-directory sync failure raises ``RuntimeError``
|
||||
saying the rename may not be durable, and the staging pathname, which
|
||||
another process may have reused, is not cleaned up.
|
||||
"""
|
||||
destination = Path(destination)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -472,6 +445,7 @@ def atomic_checkpoint_directory(
|
||||
),
|
||||
)
|
||||
backup: Path | None = None
|
||||
published_no_replace = False
|
||||
try:
|
||||
yield staging
|
||||
if validate is not None:
|
||||
@@ -483,7 +457,6 @@ def atomic_checkpoint_directory(
|
||||
raise FileExistsError(
|
||||
f"Checkpoint destination already exists: {destination}",
|
||||
)
|
||||
promoted_identity = _path_identity(staging)
|
||||
try:
|
||||
if had_destination:
|
||||
backup = destination.with_name(
|
||||
@@ -500,15 +473,21 @@ def atomic_checkpoint_directory(
|
||||
raise FileExistsError(
|
||||
f"Checkpoint destination already exists: {destination}",
|
||||
) from error
|
||||
published_no_replace = True
|
||||
_sync_directory(destination.parent)
|
||||
except BaseException:
|
||||
except BaseException as commit_error:
|
||||
if published_no_replace:
|
||||
raise RuntimeError(
|
||||
f"Checkpoint was published to {destination}, but syncing "
|
||||
f"{destination.parent} failed, so the rename may not survive a crash. "
|
||||
"The complete checkpoint was left in place and nothing was rolled back.",
|
||||
) from commit_error
|
||||
try:
|
||||
_rollback_checkpoint_commit(
|
||||
destination,
|
||||
staging,
|
||||
backup,
|
||||
had_destination=had_destination,
|
||||
promoted_identity=promoted_identity,
|
||||
)
|
||||
except BaseException as restore_error:
|
||||
recovery_path = backup if backup is not None else staging
|
||||
@@ -534,7 +513,8 @@ def atomic_checkpoint_directory(
|
||||
cleanup_error,
|
||||
)
|
||||
except BaseException:
|
||||
_cleanup_failed_staging(staging)
|
||||
if not published_no_replace:
|
||||
_cleanup_failed_staging(staging)
|
||||
raise
|
||||
|
||||
|
||||
@@ -555,21 +535,6 @@ def _publish_file_no_replace(temporary: Path, destination: Path) -> None:
|
||||
) from rename_error
|
||||
|
||||
|
||||
def _unlink_if_identical(path: Path, identity: tuple[int, int]) -> None:
|
||||
"""Remove ``path`` only if it is still the file this process published."""
|
||||
try:
|
||||
current = os.lstat(path)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
if (current.st_dev, current.st_ino) != identity:
|
||||
logger.warning("Leaving %s in place: another writer replaced it", path)
|
||||
return
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError as cleanup_error:
|
||||
logger.warning("Could not remove partially published %s: %s", path, cleanup_error)
|
||||
|
||||
|
||||
def write_new_text_files(files: Mapping[Path, str], *, encoding: str = "utf-8") -> None:
|
||||
"""Publish complete new text files without replacing any existing path.
|
||||
|
||||
@@ -580,17 +545,16 @@ def write_new_text_files(files: Mapping[Path, str], *, encoding: str = "utf-8")
|
||||
``NoReplaceRenameUnsupported`` rather than writing the destination in place.
|
||||
Every published file therefore appears complete or not at all.
|
||||
|
||||
If any destination already exists, files this call published are removed
|
||||
and ``FileExistsError`` names the conflicting path. Rollback removes a path
|
||||
only while it is still the file this call published (same device and
|
||||
inode), so a file another writer put there meanwhile is left alone.
|
||||
|
||||
Publication is exception-safe, not crash-safe: if the process dies between
|
||||
links, earlier files stay published and hidden ``.<name>.<uuid>.tmp`` files
|
||||
can remain beside them.
|
||||
Files are published in mapping order, and a published file is never moved
|
||||
or deleted again: ownership of a path cannot be proven without a race, so
|
||||
nothing that might belong to another writer is touched. If a later file
|
||||
conflicts (``FileExistsError``) or publishing fails, the files already
|
||||
published stay in place and the error names them, because the set may be
|
||||
incomplete. Only private temporary files are removed. Publication is not
|
||||
crash-safe either: a crash can leave published files without the rest and
|
||||
hidden ``.<name>.<uuid>.tmp`` files beside them.
|
||||
"""
|
||||
temporaries: dict[Path, Path] = {}
|
||||
identities: dict[Path, tuple[int, int]] = {}
|
||||
published: list[Path] = []
|
||||
try:
|
||||
for destination, text in files.items():
|
||||
@@ -603,19 +567,30 @@ def write_new_text_files(files: Mapping[Path, str], *, encoding: str = "utf-8")
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
written = os.fstat(stream.fileno())
|
||||
identities[destination] = (written.st_dev, written.st_ino)
|
||||
for destination, temporary in temporaries.items():
|
||||
try:
|
||||
_publish_file_no_replace(temporary, destination)
|
||||
except FileExistsError as error:
|
||||
raise FileExistsError(f"Output already exists: {destination}") from error
|
||||
raise FileExistsError(
|
||||
f"Output already exists: {destination}" + _published_note(published),
|
||||
) from error
|
||||
published.append(destination)
|
||||
_sync_directory(destination.parent)
|
||||
except BaseException:
|
||||
for destination in reversed(published):
|
||||
_unlink_if_identical(destination, identities[destination])
|
||||
except BaseException as error:
|
||||
if published and not isinstance(error, FileExistsError):
|
||||
note = _published_note(published).lstrip("; ")
|
||||
logger.error("Publishing stopped: %s", note)
|
||||
error.add_note(note)
|
||||
raise
|
||||
finally:
|
||||
for temporary in temporaries.values():
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _published_note(published: list[Path]) -> str:
|
||||
if not published:
|
||||
return ""
|
||||
names = ", ".join(str(path) for path in published)
|
||||
return (
|
||||
f"; already published and left in place (the set may be incomplete): {names}"
|
||||
)
|
||||
@@ -16,7 +16,11 @@ import obliteratus.persistence_contracts as persistence
|
||||
|
||||
|
||||
def emulated_rename_no_replace(source, destination):
|
||||
"""Deterministic stand-in for the atomic no-replace rename on hosts without it."""
|
||||
"""Deterministic stand-in for the atomic no-replace rename on hosts without it.
|
||||
|
||||
The existence check and rename are two steps, so this is not atomic. That is
|
||||
fine for these tests, which drive every interleaving deterministically.
|
||||
"""
|
||||
import errno
|
||||
|
||||
if os.path.lexists(destination):
|
||||
@@ -891,19 +895,21 @@ def test_atomic_checkpoint_default_still_replaces_existing_destination(tmp_path)
|
||||
|
||||
|
||||
def test_exclusive_text_files_publish_complete_files_or_nothing(tmp_path):
|
||||
first = tmp_path / "out" / "report.json"
|
||||
second = tmp_path / "out" / "config.json"
|
||||
second.parent.mkdir()
|
||||
second.write_text("competitor\n", encoding="utf-8")
|
||||
first = tmp_path / "out" / "config.json"
|
||||
second = tmp_path / "out" / "report.json"
|
||||
first.parent.mkdir()
|
||||
first.write_text("competitor\n", encoding="utf-8")
|
||||
|
||||
with pytest.raises(FileExistsError, match="already exists"):
|
||||
persistence.write_new_text_files({first: "report\n", second: "config\n"})
|
||||
# The first file conflicts, so nothing is published.
|
||||
with pytest.raises(FileExistsError) as raised:
|
||||
persistence.write_new_text_files({first: "config\n", second: "report\n"})
|
||||
|
||||
assert not first.exists()
|
||||
assert second.read_text(encoding="utf-8") == "competitor\n"
|
||||
assert sorted(path.name for path in second.parent.iterdir()) == ["config.json"]
|
||||
assert str(raised.value) == f"Output already exists: {first}"
|
||||
assert not second.exists()
|
||||
assert first.read_text(encoding="utf-8") == "competitor\n"
|
||||
assert sorted(path.name for path in first.parent.iterdir()) == ["config.json"]
|
||||
|
||||
second.unlink()
|
||||
first.unlink()
|
||||
persistence.write_new_text_files({first: "report\n", second: "config\n"})
|
||||
assert first.read_text(encoding="utf-8") == "report\n"
|
||||
assert second.read_text(encoding="utf-8") == "config\n"
|
||||
@@ -955,7 +961,50 @@ def test_atomic_checkpoint_without_replacement_fails_closed_without_no_replace_r
|
||||
assert sorted(path.name for path in tmp_path.iterdir()) == [".checkpoint.lock"]
|
||||
|
||||
|
||||
def test_exclusive_text_files_rollback_leaves_a_replaced_path_alone(tmp_path, monkeypatch):
|
||||
def test_exclusive_text_files_never_remove_a_published_file(tmp_path):
|
||||
first = tmp_path / "config.json"
|
||||
second = tmp_path / "report.json"
|
||||
second.write_text("competitor report\n", encoding="utf-8")
|
||||
|
||||
with pytest.raises(FileExistsError) as raised:
|
||||
persistence.write_new_text_files({first: "config\n", second: "report\n"})
|
||||
|
||||
# Ownership of a published path cannot be proven without a race, so the
|
||||
# published file stays and the error says the set may be incomplete.
|
||||
assert str(raised.value) == (
|
||||
f"Output already exists: {second}; already published and left in place "
|
||||
f"(the set may be incomplete): {first}"
|
||||
)
|
||||
assert first.read_text(encoding="utf-8") == "config\n"
|
||||
assert second.read_text(encoding="utf-8") == "competitor report\n"
|
||||
assert sorted(path.name for path in tmp_path.iterdir()) == ["config.json", "report.json"]
|
||||
|
||||
|
||||
def test_exclusive_text_files_report_published_files_when_a_later_step_fails(
|
||||
tmp_path, monkeypatch,
|
||||
):
|
||||
first = tmp_path / "config.json"
|
||||
second = tmp_path / "report.json"
|
||||
real_publish = persistence._publish_file_no_replace
|
||||
|
||||
def fail_on_the_second(temporary, destination):
|
||||
if destination == second:
|
||||
raise OSError("injected publish failure")
|
||||
return real_publish(temporary, destination)
|
||||
|
||||
monkeypatch.setattr(persistence, "_publish_file_no_replace", fail_on_the_second)
|
||||
with pytest.raises(OSError, match="injected publish failure") as raised:
|
||||
persistence.write_new_text_files({first: "config\n", second: "report\n"})
|
||||
|
||||
assert raised.value.__notes__ == [
|
||||
f"already published and left in place (the set may be incomplete): {first}",
|
||||
]
|
||||
assert first.read_text(encoding="utf-8") == "config\n"
|
||||
# Only the never-published private temporary file was removed.
|
||||
assert sorted(path.name for path in tmp_path.iterdir()) == ["config.json"]
|
||||
|
||||
|
||||
def test_exclusive_text_files_leave_a_replaced_published_path_alone(tmp_path, monkeypatch):
|
||||
first = tmp_path / "config.json"
|
||||
second = tmp_path / "report.json"
|
||||
second.write_text("competitor report\n", encoding="utf-8")
|
||||
@@ -1047,45 +1096,82 @@ def test_no_replace_rename_refuses_existing_files_and_directories(tmp_path):
|
||||
assert fresh.exists() and not source.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("replace_existing", [False, True])
|
||||
def test_atomic_checkpoint_rollback_leaves_a_destination_another_writer_replaced(
|
||||
tmp_path, monkeypatch, portable_no_replace_rename, replace_existing,
|
||||
):
|
||||
destination = tmp_path / "checkpoint"
|
||||
if replace_existing:
|
||||
destination.mkdir()
|
||||
(destination / "model.bin").write_bytes(b"previous")
|
||||
moved_ours = tmp_path / "moved-ours"
|
||||
def _published_checkpoint_sync_failure(destination, after_promotion):
|
||||
"""Fail the parent sync that follows promotion, after running ``after_promotion``."""
|
||||
real_sync = persistence._sync_directory
|
||||
injected = []
|
||||
state = {"failed": False}
|
||||
|
||||
def replace_then_fail_parent_sync(path):
|
||||
promoted = (destination / "model.bin").is_file() and (
|
||||
(destination / "model.bin").read_bytes() == b"ours"
|
||||
)
|
||||
if path == destination.parent and promoted and not injected:
|
||||
# A writer that bypasses the lock swaps in its own checkpoint just
|
||||
# before this commit's parent-directory sync fails.
|
||||
os.rename(destination, moved_ours)
|
||||
destination.mkdir()
|
||||
(destination / "winner.txt").write_text("other writer", encoding="utf-8")
|
||||
injected.append(path)
|
||||
def sync(path):
|
||||
model = destination / "model.bin"
|
||||
promoted = model.is_file() and model.read_bytes() == b"ours"
|
||||
if path == destination.parent and promoted and not state["failed"]:
|
||||
state["failed"] = True
|
||||
after_promotion()
|
||||
raise OSError("injected parent directory sync failure")
|
||||
real_sync(path)
|
||||
|
||||
monkeypatch.setattr(persistence, "_sync_directory", replace_then_fail_parent_sync)
|
||||
with pytest.raises((OSError, RuntimeError)):
|
||||
with persistence.atomic_checkpoint_directory(
|
||||
destination, replace_existing=replace_existing,
|
||||
) as staging:
|
||||
return sync, state
|
||||
|
||||
|
||||
def _another_writer_swaps(destination, moved_ours):
|
||||
os.rename(destination, moved_ours)
|
||||
destination.mkdir()
|
||||
(destination / "winner.txt").write_text("other writer", encoding="utf-8")
|
||||
|
||||
|
||||
def test_published_no_replace_checkpoint_is_never_rolled_back(
|
||||
tmp_path, monkeypatch, portable_no_replace_rename,
|
||||
):
|
||||
destination = tmp_path / "checkpoint"
|
||||
moved_ours = tmp_path / "moved-ours"
|
||||
sync, state = _published_checkpoint_sync_failure(
|
||||
destination, lambda: _another_writer_swaps(destination, moved_ours),
|
||||
)
|
||||
monkeypatch.setattr(persistence, "_sync_directory", sync)
|
||||
with pytest.raises(RuntimeError) as raised:
|
||||
with persistence.atomic_checkpoint_directory(destination, replace_existing=False) as staging:
|
||||
(staging / "model.bin").write_bytes(b"ours")
|
||||
|
||||
assert injected
|
||||
assert state["failed"]
|
||||
assert str(raised.value) == (
|
||||
f"Checkpoint was published to {destination}, but syncing {tmp_path} failed, so the "
|
||||
"rename may not survive a crash. The complete checkpoint was left in place and "
|
||||
"nothing was rolled back."
|
||||
)
|
||||
assert str(raised.value.__cause__) == "injected parent directory sync failure"
|
||||
assert sorted(path.name for path in destination.iterdir()) == ["winner.txt"]
|
||||
assert (destination / "winner.txt").read_text(encoding="utf-8") == "other writer"
|
||||
if replace_existing:
|
||||
backups = list(tmp_path.glob(".checkpoint.backup-*"))
|
||||
assert len(backups) == 1 and (backups[0] / "model.bin").read_bytes() == b"previous"
|
||||
assert (moved_ours / "model.bin").read_bytes() == b"ours"
|
||||
|
||||
|
||||
def test_published_no_replace_checkpoint_never_cleans_a_recreated_staging_path(
|
||||
tmp_path, monkeypatch, portable_no_replace_rename,
|
||||
):
|
||||
# The default replace path keeps its upstream rollback, which reuses the
|
||||
# staging pathname; that pre-existing race is tracked separately.
|
||||
destination = tmp_path / "checkpoint"
|
||||
recreated = []
|
||||
|
||||
def another_writer_recreates_the_staging_path():
|
||||
staging = recreated_paths[0]
|
||||
staging.mkdir()
|
||||
(staging / "theirs.txt").write_text("other writer", encoding="utf-8")
|
||||
recreated.append(staging)
|
||||
|
||||
recreated_paths = []
|
||||
sync, state = _published_checkpoint_sync_failure(
|
||||
destination, another_writer_recreates_the_staging_path,
|
||||
)
|
||||
monkeypatch.setattr(persistence, "_sync_directory", sync)
|
||||
with pytest.raises(RuntimeError, match="nothing was rolled back"):
|
||||
with persistence.atomic_checkpoint_directory(
|
||||
destination, replace_existing=False,
|
||||
) as staging:
|
||||
recreated_paths.append(staging)
|
||||
(staging / "model.bin").write_bytes(b"ours")
|
||||
|
||||
assert state["failed"] and recreated
|
||||
assert (recreated[0] / "theirs.txt").read_text(encoding="utf-8") == "other writer"
|
||||
assert (destination / "model.bin").read_bytes() == b"ours"
|
||||
|
||||
|
||||
def test_no_replace_rename_maps_directory_conflicts_to_file_exists():
|
||||
|
||||
@@ -694,15 +694,21 @@ def test_discover_cli_never_clobbers_an_output_created_by_a_concurrent_run(
|
||||
tokenizer=TinyTokenizer(), model_name="tiny", cleanup=concurrent_run_finishes_first,
|
||||
)
|
||||
monkeypatch.setattr(vocab_surgery_cli, "_load", lambda _args: handle)
|
||||
with pytest.raises(FileExistsError, match="already exists"):
|
||||
with pytest.raises(FileExistsError, match="already exists") as raised:
|
||||
vocab_surgery_cli._discover(args, Mock())
|
||||
assert competitor.read_text(encoding="utf-8") == "competitor\n"
|
||||
# Nothing from the losing run survives: no partial pair and no temporaries.
|
||||
other = args.config_output if collide == "output" else args.output
|
||||
assert not other.exists()
|
||||
assert sorted(path.name for path in tmp_path.iterdir()) == sorted(
|
||||
["target.jsonl", "control.jsonl", competitor.name],
|
||||
)
|
||||
survivors = ["target.jsonl", "control.jsonl", competitor.name]
|
||||
if collide == "output":
|
||||
# The config was published first. A published file is never removed,
|
||||
# so it stays and the error names it as a possibly incomplete set.
|
||||
assert str(args.config_output) in str(raised.value)
|
||||
assert "may be incomplete" in str(raised.value)
|
||||
assert json.loads(args.config_output.read_text(encoding="utf-8"))["operations"]
|
||||
survivors.append(args.config_output.name)
|
||||
else:
|
||||
assert not args.output.exists()
|
||||
# No temporaries survive.
|
||||
assert sorted(path.name for path in tmp_path.iterdir()) == sorted(survivors)
|
||||
|
||||
|
||||
def test_apply_cli_never_clobbers_a_checkpoint_created_by_a_concurrent_run(tmp_path, monkeypatch):
|
||||
|
||||
Reference in new issue
Block a user