Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
feat(registry): add optional idempotent registration (#1964)
Abdulwaarith Zakariyya5866dd764477
diff --git a/changelog.d/0.76.0/1964.added.md b/changelog.d/0.76.0/1964.added.mdnew file mode 100644index 00000000..1567a3d0--- /dev/null+++ b/changelog.d/0.76.0/1964.added.md@@ -0,0 +1,6 @@+- **`soup registry push --idempotency-key` and `RegistryStore.push(idempotency_key=...)` make a registration safe to retry (#1763 by @abdulwaarith0 in #1964).**+ A repeated push with the same key returns the existing entry instead of creating a twin, as+ long as it repeats the entry's name, tag, base model, task, run, config and data hash; anything+ else under that key is refused with an error naming the entry. Two writers pushing the same key+ at once end up with one entry. Existing registry databases gain the nullable column in place.+ Pushes without a key are unchanged.diff --git a/docs/adapters-and-governance.md b/docs/adapters-and-governance.mdindex 9a760217..e9f4d933 100644--- a/docs/adapters-and-governance.md+++ b/docs/adapters-and-governance.md@@ -283,6 +283,9 @@ soup registry push --run-id run_202611_abc123 --name llama31-chat --tag v1# Also record the training data file's SHA-256 as data_hashsoup registry push --run-id run_202611_abc123 --name llama31-chat --tag v1 --data data/train.jsonl+# Safe to retry: the same key and the same registration return the existing entry+soup registry push --run-id run_202611_abc123 --name llama31-chat --tag v1 --idempotency-key job-42+# List entries (filter by name, tag, base model, task)soup registry listsoup registry list --name llama31-chat --tag prod@@ -305,6 +308,8 @@ soup registry delete llama31-chat-v1 --yes**Training data:** `push --data <file>` stores the file's SHA-256 as the entry's `data_hash`, shown by `soup registry show`. It records the file registered as the training input, not proof of what the run trained on. The file must be under the current directory; without `--data` the entry has no `data_hash`.+**Retries:** `push --idempotency-key <key>` (or `RegistryStore.push(idempotency_key=...)`) makes a registration safe to repeat after a crash or a timeout. A later push with the same key writes nothing and returns the existing entry, provided it repeats that entry's name, base model, task, run, config and data hash and its tag is one of the entry's tags; anything else under the same key is refused with an error naming the entry. Notes are not compared. Two writers pushing the same key at once end up with one entry. A key is 1 to 128 characters from letters, digits, `.`, `_`, `:` and `-`; pushes without one behave as before. `RegistryStore.get_by_idempotency_key(key)` finds the entry. Deleting the entry frees its key.+**Lineage DAG** — every entry can point to a parent (its ancestor run). Walk the DAG for any name with:```bashdiff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 0b03fd2c..ca224454 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -3230,6 +3230,7 @@ Usage: `soup registry push [OPTIONS]`| `--tag`, `-t` | text | `v1` | | Tag (e.g. v1, prod-2024) || `--notes` | text | `""` | | Free-form notes || `--data` | text | | | Training data file to record: its SHA-256 is stored as data_hash. This is the file registered as the training input, not proof of what the run trained on. Must be a file under the current directory. |+| `--idempotency-key` | text | | | Make a retry safe: a later push with the same key and the same run, name, tag and data returns the existing entry instead of a new one; anything different is refused. 1-128 characters from letters, digits, '.', '\_', ':', '-'. |### `soup registry search`diff --git a/docs/commands.md b/docs/commands.mdindex eab9a4fd..d0525d5e 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -195,6 +195,7 @@ soup recipes verify --no-templates Recipes only; skip src/soup_cli/tesoup recipes verify --json One JSON row per config on stdout; advisories go to stderrsoup registry push --run-id <id> --name n --tag v1 Register runsoup registry push ... --data train.jsonl Also record that file's SHA-256 as data_hash+soup registry push ... --idempotency-key k Retry-safe: same key + same registration -> existing entrysoup registry list [--name n] [--tag v1] List registry entriessoup registry show <ref> Entry details + artifacts + ancestorssoup registry diff <a> <b> Side-by-side config + eval deltadiff --git a/src/soup_cli/commands/registry.py b/src/soup_cli/commands/registry.pyindex 08ef00c9..8f224449 100644--- a/src/soup_cli/commands/registry.py+++ b/src/soup_cli/commands/registry.py@@ -15,6 +15,7 @@ from soup_cli.registry.diff import config_diff, eval_deltafrom soup_cli.registry.store import (AmbiguousRefError,RegistryStore,+ validate_idempotency_key,validate_name,validate_tag,)@@ -72,11 +73,21 @@ def push_cmd("what the run trained on. Must be a file under the current directory."),),+ idempotency_key: Optional[str] = typer.Option(+ None, "--idempotency-key",+ help=(+ "Make a retry safe: a later push with the same key and the same run, name, "+ "tag and data returns the existing entry instead of a new one; anything "+ "different is refused. 1-128 characters from letters, digits, '.', '_', ':', '-'."+ ),+ ),) -> None:"""Register a completed training run as a registry entry."""try:validate_name(name)validate_tag(tag)+ if idempotency_key is not None:+ validate_idempotency_key(idempotency_key)except ValueError as exc:_fail(f"Invalid input: {exc}")data_path = _data_file(data) if data is not None else None@@ -88,15 +99,21 @@ def push_cmd(if tracker.get_run(run_id) is None:_fail(f"Run not found: {run_id}")with RegistryStore() as store:+ earlier = (+ store.get_by_idempotency_key(idempotency_key)+ if idempotency_key is not None else None+ )try:entry_id = store.register_from_run(tracker, run_id, name=name, tag=tag,notes=notes or None, data_path=data_path,+ idempotency_key=idempotency_key,)except ValueError as exc:_fail(str(exc))+ verb = "Already registered" if earlier and earlier["id"] == entry_id else "Registered"console.print(Panel(- f"Registered [cyan]{escape(name)}[/]:[magenta]{escape(tag)}[/]\n"+ f"{verb} [cyan]{escape(name)}[/]:[magenta]{escape(tag)}[/]\n"f"Entry ID: [bold]{escape(entry_id)}[/]",title="Registry", border_style="green",))diff --git a/src/soup_cli/registry/store.py b/src/soup_cli/registry/store.pyindex 664f9e76..c2003bbe 100644--- a/src/soup_cli/registry/store.py+++ b/src/soup_cli/registry/store.py@@ -3,7 +3,8 @@Schema (see Part A of v0.26.0 plan):registry_entries(id, name, tag, base_model, task, run_id, config_json,- config_hash, data_hash, entry_hash, created_at, notes)+ config_hash, data_hash, entry_hash, created_at, notes,+ idempotency_key)registry_artifacts(id, entry_id, kind, path, sha256, size_bytes,created_at)registry_lineage(id, child_id, parent_id, relation, created_at)@@ -35,6 +36,10 @@ class AmbiguousRefError(ValueError):"""Raised when a reference matches more than one registry entry."""+class IdempotencyConflictError(ValueError):+ """Raised when an idempotency key is reused for a different registration."""++# How many candidate ids an ambiguous ``name:tag`` error lists before "and N more"._AMBIGUOUS_IDS_SHOWN = 5@@ -68,6 +73,11 @@ _VALID_RELATIONS = frozenset(_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_\-.]{0,127}$")_TAG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_\-.]{0,63}$")+_IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")++# What a retry under the same idempotency key has to repeat. ``notes`` is free-form and+# not compared; the tag only has to be one of the entry's tags.+_IDEMPOTENT_FIELDS = ("name", "base_model", "task", "run_id", "config_hash", "data_hash")_SCHEMA_SQL = """CREATE TABLE IF NOT EXISTS registry_entries (@@ -81,7 +91,8 @@ CREATE TABLE IF NOT EXISTS registry_entries (data_hash TEXT,entry_hash TEXT NOT NULL,created_at TEXT NOT NULL,- notes TEXT+ notes TEXT,+ idempotency_key TEXT);CREATE TABLE IF NOT EXISTS registry_artifacts (@@ -153,6 +164,15 @@ def validate_tag(tag: str) -> None:)+def validate_idempotency_key(key: str) -> None:+ """Raise ValueError unless ``key`` is 1-128 characters from ``[A-Za-z0-9._:-]``."""+ if not isinstance(key, str) or not _IDEMPOTENCY_KEY_RE.fullmatch(key):+ raise ValueError(+ "idempotency key must be 1 to 128 characters from letters, digits, "+ "'.', '_', ':' and '-'"+ )++def _is_under(path: Path, base: Path) -> bool:"""Whether ``path`` is inside ``base`` using realpath + commonpath.@@ -230,8 +250,28 @@ class RegistryStore:return self._conndef _ensure_schema(self) -> None:+ """Create the tables, and add ``idempotency_key`` to a database made before it.++ Gated on ``PRAGMA table_info`` so a second open is a no-op, and tolerant of a+ sibling process adding the column between that check and the ALTER, as in+ :meth:`ExperimentTracker._ensure_schema`. The unique index is created after the+ column exists; every older row is NULL, so it cannot fail on existing entries.+ """conn = self._get_conn()conn.executescript(_SCHEMA_SQL)+ columns = {+ row[1] for row in conn.execute("PRAGMA table_info(registry_entries)").fetchall()+ }+ if "idempotency_key" not in columns:+ try:+ conn.execute("ALTER TABLE registry_entries ADD COLUMN idempotency_key TEXT")+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ conn.execute(+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_reg_entries_idempotency_key "+ "ON registry_entries(idempotency_key) WHERE idempotency_key IS NOT NULL"+ )conn.commit()def _tighten_perms(self) -> None:@@ -268,14 +308,23 @@ class RegistryStore:config: dict[str, Any],data_path: Optional[str] = None,notes: Optional[str] = None,+ idempotency_key: Optional[str] = None,) -> str:- """Create a new registry entry. Returns the new entry's id."""+ """Create a new registry entry. Returns the new entry's id.++ With ``idempotency_key``, a push whose key is already taken writes nothing and+ returns that entry's id, provided it repeats the entry's name, base model, task,+ ``run_id``, config hash and data hash, and the tag is one of the entry's tags.+ Otherwise it raises :class:`IdempotencyConflictError` naming the entry.+ """validate_name(name)validate_tag(tag)if not base_model:raise ValueError("base_model is required")if not task:raise ValueError("task is required")+ if idempotency_key is not None:+ validate_idempotency_key(idempotency_key)entry_id = _generate_entry_id()now = datetime.now().isoformat()@@ -285,26 +334,71 @@ class RegistryStore:entry_hash = hash_entry(config=config, data_path=data_path, base_model=base_model,)+ request = {+ "name": name, "base_model": base_model, "task": task, "run_id": run_id,+ "config_hash": config_hash, "data_hash": data_hash,+ }++ if idempotency_key is not None:+ existing = self._find_by_key(idempotency_key)+ if existing is not None:+ return self._replay(existing, request, tag, idempotency_key)conn = self._get_conn()- conn.execute(- """INSERT INTO registry_entries- (id, name, base_model, task, run_id, config_json,- config_hash, data_hash, entry_hash, created_at, notes)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",- (- entry_id, name, base_model, task, run_id,- json.dumps(config, default=str, sort_keys=True),- config_hash, data_hash, entry_hash, now, notes,- ),- )- conn.execute(- "INSERT INTO registry_tags (entry_id, tag) VALUES (?, ?)",- (entry_id, tag),- )- conn.commit()+ try:+ conn.execute(+ """INSERT INTO registry_entries+ (id, name, base_model, task, run_id, config_json,+ config_hash, data_hash, entry_hash, created_at, notes,+ idempotency_key)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ (+ entry_id, name, base_model, task, run_id,+ json.dumps(config, default=str, sort_keys=True),+ config_hash, data_hash, entry_hash, now, notes,+ idempotency_key,+ ),+ )+ conn.execute(+ "INSERT INTO registry_tags (entry_id, tag) VALUES (?, ?)",+ (entry_id, tag),+ )+ conn.commit()+ except sqlite3.IntegrityError:+ conn.rollback()+ # Another writer took the key after the lookup above: answer from its entry.+ existing = (+ self._find_by_key(idempotency_key) if idempotency_key is not None else None+ )+ if existing is None:+ raise+ return self._replay(existing, request, tag, idempotency_key)return entry_id+ def get_by_idempotency_key(self, key: str) -> Optional[dict]:+ """The entry pushed with idempotency key ``key``, or ``None``."""+ validate_idempotency_key(key)+ return self._find_by_key(key)++ def _find_by_key(self, key: str) -> Optional[dict]:+ row = self._get_conn().execute(+ "SELECT * FROM registry_entries WHERE idempotency_key = ?", (key,),+ ).fetchone()+ return self._hydrate(dict(row)) if row is not None else None++ @staticmethod+ def _replay(entry: dict, request: dict, tag: str, key: str) -> str:+ """``entry``'s id if ``request`` repeats it, else IdempotencyConflictError."""+ differing = [field for field in _IDEMPOTENT_FIELDS if entry.get(field) != request[field]]+ if tag not in entry["tags"]:+ differing.insert(1, "tag")+ if differing:+ raise IdempotencyConflictError(+ f"idempotency key '{key}' is already used by entry {entry['id']}, "+ f"which has a different {', '.join(differing)}"+ )+ return entry["id"]+def add_tag(self, entry_id: str, tag: str) -> None:validate_tag(tag)if self.get(entry_id) is None:@@ -686,12 +780,14 @@ class RegistryStore:tag: str,notes: Optional[str] = None,data_path: Optional[str] = None,+ idempotency_key: Optional[str] = None,) -> str:"""Create a registry entry from an existing training run.``data_path`` names the file to record as the run's training input; itsSHA-256 becomes ``data_hash``. It is what the caller says was trained on,not proof of it. Without it, ``data_hash`` stays ``None``.+ ``idempotency_key`` is passed to :meth:`push`."""run = tracker.get_run(run_id)if run is None:@@ -716,6 +812,7 @@ class RegistryStore:config=config,data_path=data_path,notes=notes,+ idempotency_key=idempotency_key,)def get_eval_results(self, entry_id: str) -> list[dict]:diff --git a/tests/test_registry_idempotency.py b/tests/test_registry_idempotency.pynew file mode 100644index 00000000..4f832ee3--- /dev/null+++ b/tests/test_registry_idempotency.py@@ -0,0 +1,528 @@+"""``RegistryStore.push(idempotency_key=...)``: a retried registration finds its entry (#1763)."""++from __future__ import annotations++import sqlite3+import threading+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.registry.store import (+ IdempotencyConflictError,+ RegistryStore,+ validate_idempotency_key,+)+from tests.conftest import strip_ansi++runner = CliRunner()++CONFIG = {"base": "llama", "task": "sft", "lr": 2e-4}++# registry_entries and registry_tags as every soup-cli before #1763 created them.+_LEGACY_SCHEMA = """+CREATE TABLE registry_entries (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ base_model TEXT NOT NULL,+ task TEXT NOT NULL,+ run_id TEXT,+ config_json TEXT NOT NULL,+ config_hash TEXT NOT NULL,+ data_hash TEXT,+ entry_hash TEXT NOT NULL,+ created_at TEXT NOT NULL,+ notes TEXT+);+CREATE TABLE registry_tags (+ entry_id TEXT NOT NULL REFERENCES registry_entries(id) ON DELETE CASCADE,+ tag TEXT NOT NULL,+ PRIMARY KEY (entry_id, tag)+);+"""+++def store(tmp_path):+ with RegistryStore(db_path=tmp_path / "reg.db") as s:+ yield s+++def _push(store: RegistryStore, key=None, **overrides) -> str:+ request = {+ "name": "chat", "tag": "v1", "base_model": "llama", "task": "sft",+ "run_id": "run_1", "config": CONFIG,+ }+ request.update(overrides)+ return store.push(idempotency_key=key, **request)+++def _counts(db: Path) -> tuple[int, int]:+ conn = sqlite3.connect(str(db))+ try:+ entries = conn.execute("SELECT COUNT(*) FROM registry_entries").fetchone()[0]+ tags = conn.execute("SELECT COUNT(*) FROM registry_tags").fetchone()[0]+ finally:+ conn.close()+ return entries, tags+++def _columns(db: Path) -> list[str]:+ conn = sqlite3.connect(str(db))+ try:+ return [row[1] for row in conn.execute("PRAGMA table_info(registry_entries)")]+ finally:+ conn.close()+++def _legacy_db(db: Path) -> None:+ """A database written by today's soup-cli: two twin entries and one tag each."""+ conn = sqlite3.connect(str(db))+ try:+ conn.executescript(_LEGACY_SCHEMA)+ for entry_id in ("reg_old_1", "reg_old_2"):+ conn.execute(+ "INSERT INTO registry_entries (id, name, base_model, task, run_id, config_json,"+ " config_hash, data_hash, entry_hash, created_at, notes)"+ " VALUES (?, 'chat', 'llama', 'sft', 'run_old', '{}', 'c', NULL, 'e',"+ " '2026-01-01T00:00:00', NULL)",+ (entry_id,),+ )+ conn.execute("INSERT INTO registry_tags VALUES (?, 'v1')", (entry_id,))+ conn.commit()+ finally:+ conn.close()+++# -- repeat and conflict ------------------------------------------------------+++def test_a_repeated_push_returns_the_same_entry_and_writes_nothing(store):+ first = _push(store, key="job-42")++ second = _push(store, key="job-42")++ assert second == first+ assert _counts(store.db_path) == (1, 1)+ assert store.get(first)["idempotency_key"] == "job-42"+++def test_the_entry_is_found_by_its_key(store):+ entry_id = _push(store, key="job-42")++ found = store.get_by_idempotency_key("job-42")++ assert found["id"] == entry_id+ assert found["tags"] == ["v1"]+ assert store.get_by_idempotency_key("job-43") is None+++ ("field", "override"),+ [+ ("name", {"name": "other"}),+ ("tag", {"tag": "v2"}),+ ("base_model", {"base_model": "qwen"}),+ ("task", {"task": "dpo"}),+ ("run_id", {"run_id": "run_2"}),+ ("config_hash", {"config": {**CONFIG, "lr": 1e-4}}),+ ],+)+def test_the_same_key_for_a_different_request_is_refused(store, field, override):+ first = _push(store, key="job-42")++ with pytest.raises(IdempotencyConflictError) as excinfo:+ _push(store, key="job-42", **override)++ message = str(excinfo.value)+ assert first in message+ assert field in message+ assert _counts(store.db_path) == (1, 1)+++def test_a_different_data_file_under_the_same_key_is_refused(store, tmp_path):+ data = tmp_path / "train.jsonl"+ data.write_text('{"text": "a"}\n', encoding="utf-8")+ first = _push(store, key="job-42", data_path=str(data))+ assert _push(store, key="job-42", data_path=str(data)) == first++ data.write_text('{"text": "b"}\n', encoding="utf-8")+ with pytest.raises(IdempotencyConflictError, match="data_hash"):+ _push(store, key="job-42", data_path=str(data))+ with pytest.raises(IdempotencyConflictError, match="data_hash"):+ _push(store, key="job-42")+ assert _counts(store.db_path) == (1, 1)+++def test_the_conflict_is_a_value_error(store):+ _push(store, key="job-42")++ with pytest.raises(ValueError):+ _push(store, key="job-42", run_id="run_2")+++def test_notes_are_not_part_of_the_request(store):+ first = _push(store, key="job-42", notes="first try")++ assert _push(store, key="job-42", notes="retry") == first+ assert store.get(first)["notes"] == "first try"+++def test_a_tag_added_later_does_not_break_the_retry(store):+ first = _push(store, key="job-42")+ store.add_tag(first, "prod")++ assert _push(store, key="job-42") == first+ assert store.get(first)["tags"] == ["prod", "v1"]+++def test_pushes_without_a_key_never_collide(store):+ first = _push(store)+ second = _push(store)++ assert first != second+ assert _counts(store.db_path) == (2, 2)+ assert store.get(first)["idempotency_key"] is None+++def test_different_keys_make_different_entries(store):+ assert _push(store, key="job-42") != _push(store, key="job-43")+ assert _counts(store.db_path) == (2, 2)+++def test_a_deleted_entry_frees_its_key(store):+ first = _push(store, key="job-42")+ store.delete(first)++ second = _push(store, key="job-42")++ assert second != first+ assert _counts(store.db_path) == (1, 1)+++# -- key format -----------------------------------------------------------------++[email protected]("key", ["a", "x" * 128, "run:20261015.a_b-c", "0"])+def test_valid_keys(key):+ validate_idempotency_key(key)+++ "key",+ ["", "x" * 129, "a b", "a/b", "a\\b", "a\n", "\na", "a\x00", "ключ", "a;b", "a%b", 42],+)+def test_invalid_keys_are_refused_before_anything_is_written(store, key):+ with pytest.raises(ValueError, match="idempotency key"):+ validate_idempotency_key(key)+ with pytest.raises(ValueError, match="idempotency key"):+ _push(store, key=key)+ with pytest.raises(ValueError, match="idempotency key"):+ store.get_by_idempotency_key(key)+ assert _counts(store.db_path) == (0, 0)+++# -- schema upgrade ---------------------------------------------------------------+++def test_a_new_database_has_the_column_and_the_unique_index(tmp_path):+ db = tmp_path / "reg.db"+ RegistryStore(db_path=db).close()++ assert "idempotency_key" in _columns(db)+ conn = sqlite3.connect(str(db))+ try:+ sql = conn.execute(+ "SELECT sql FROM sqlite_master WHERE name = 'idx_reg_entries_idempotency_key'"+ ).fetchone()[0]+ finally:+ conn.close()+ assert "UNIQUE" in sql.upper()+ assert "WHERE idempotency_key IS NOT NULL" in sql+++def test_control_a_legacy_database_has_no_column(tmp_path):+ """If this failed, the upgrade tests below would not be testing an upgrade."""+ db = tmp_path / "legacy.db"+ _legacy_db(db)++ assert "idempotency_key" not in _columns(db)+++def test_a_legacy_database_is_upgraded_in_place(tmp_path):+ db = tmp_path / "legacy.db"+ _legacy_db(db)+ conn = sqlite3.connect(str(db))+ before = conn.execute("SELECT * FROM registry_entries ORDER BY id").fetchall()+ conn.close()++ with RegistryStore(db_path=db) as store:+ assert "idempotency_key" in _columns(db)+ old = store.get("reg_old_1")+ assert old["idempotency_key"] is None+ assert old["tags"] == ["v1"]+ first = _push(store, key="job-42")+ assert _push(store, key="job-42") == first++ conn = sqlite3.connect(str(db))+ after = conn.execute(+ "SELECT * FROM registry_entries WHERE id LIKE 'reg_old_%' ORDER BY id"+ ).fetchall()+ conn.close()+ assert [row[:-1] for row in after] == before # old rows only gain a NULL key+ assert [row[-1] for row in after] == [None, None]+ assert _counts(db) == (3, 3)+++class _RecordingConn:+ """Records every statement passed to ``execute``, including ones that then fail.++ sqlite3's trace callback misses a statement refused while it is prepared, such as an+ ALTER that adds a column the table already has, so it can't tell a guarded upgrade+ from one that relies on the duplicate-column handler.+ """++ def __init__(self, conn: sqlite3.Connection, statements: list[str]):+ self._conn = conn+ self._statements = statements++ def execute(self, sql, *args):+ self._statements.append(sql)+ return self._conn.execute(sql, *args)++ def __getattr__(self, name):+ return getattr(self._conn, name)+++def test_opening_an_upgraded_database_again_issues_no_alter(tmp_path, monkeypatch):+ db = tmp_path / "legacy.db"+ _legacy_db(db)+ real_get_conn = RegistryStore._get_conn+ statements: list[str] = []+ monkeypatch.setattr(+ RegistryStore, "_get_conn", lambda self: _RecordingConn(real_get_conn(self), statements),+ )++ RegistryStore(db_path=db).close() # first open: must ALTER+ assert any("ALTER TABLE" in q.upper() for q in statements)+ statements.clear()+ RegistryStore(db_path=db).close() # second: must not++ assert [q for q in statements if "ALTER TABLE" in q.upper()] == []+ assert any("PRAGMA table_info(registry_entries)" in q for q in statements)+++class _Rows(list):+ def fetchall(self):+ return list(self)+++class _StaleColumnsConn:+ """A connection whose column check misses a column another process just added."""++ def __init__(self, conn: sqlite3.Connection, db: Path):+ self._conn = conn+ self._db = db++ def execute(self, sql, *args):+ if sql.startswith("PRAGMA table_info(registry_entries)"):+ stale = self._conn.execute(sql, *args).fetchall()+ other = sqlite3.connect(str(self._db))+ other.execute("ALTER TABLE registry_entries ADD COLUMN idempotency_key TEXT")+ other.commit()+ other.close()+ return _Rows(stale)+ return self._conn.execute(sql, *args)++ def __getattr__(self, name):+ return getattr(self._conn, name)+++def test_a_column_added_by_another_process_mid_upgrade_is_tolerated(tmp_path, monkeypatch):+ db = tmp_path / "legacy.db"+ _legacy_db(db)+ real_get_conn = RegistryStore._get_conn++ def racing_get_conn(self):+ conn = real_get_conn(self)+ return _StaleColumnsConn(conn, self.db_path)++ monkeypatch.setattr(RegistryStore, "_get_conn", racing_get_conn)+ store = RegistryStore(db_path=db)+ monkeypatch.setattr(RegistryStore, "_get_conn", real_get_conn)+ try:+ assert _columns(db).count("idempotency_key") == 1+ first = _push(store, key="job-42")+ assert _push(store, key="job-42") == first+ finally:+ store.close()+++# -- two writers ------------------------------------------------------------------+++def test_a_key_taken_between_the_lookup_and_the_insert_returns_that_entry(tmp_path, monkeypatch):+ """The insert loses to a writer that committed after this push looked the key up."""+ db = tmp_path / "reg.db"+ with RegistryStore(db_path=db) as winner, RegistryStore(db_path=db) as loser:+ lookups: list[str] = []+ real_find = RegistryStore._find_by_key++ def find_misses_first(key):+ lookups.append(key)+ return None if len(lookups) == 1 else real_find(loser, key)++ monkeypatch.setattr(loser, "_find_by_key", find_misses_first)+ first = _push(winner, key="job-42")++ assert _push(loser, key="job-42") == first+ assert lookups == ["job-42", "job-42"]++ lookups.clear()+ with pytest.raises(IdempotencyConflictError):+ _push(loser, key="job-42", run_id="run_2")+ assert lookups == ["job-42", "job-42"]+ assert _counts(db) == (1, 1)+++def test_two_stores_pushing_the_same_key_at_once_leave_one_entry(tmp_path):+ db = tmp_path / "reg.db"+ RegistryStore(db_path=db).close()+ writers = 4+ barrier = threading.Barrier(writers)+ results: list[str] = []+ errors: list[BaseException] = []++ def push_once():+ try:+ with RegistryStore(db_path=db) as store:+ barrier.wait()+ results.append(_push(store, key="job-42"))+ except BaseException as exc: # noqa: BLE001 - surfaced by the assertion below+ errors.append(exc)++ threads = [threading.Thread(target=push_once) for _ in range(writers)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ assert errors == []+ assert len(results) == writers+ assert len(set(results)) == 1+ assert _counts(db) == (1, 1)+++# -- run registration and the CLI ---------------------------------------------------+++def _finished_run() -> str:+ from soup_cli.experiment.tracker import ExperimentTracker++ tracker = ExperimentTracker()+ try:+ run_id = tracker.start_run(+ config_dict=CONFIG, device="cpu", device_name="cpu", gpu_info={},+ )+ tracker.finish_run(run_id, 2.0, 0.5, 100, 60.0, "out")+ finally:+ tracker.close()+ return run_id+++def work(tmp_path, monkeypatch):+ """A working directory with isolated experiment and registry databases."""+ cwd = tmp_path / "work"+ cwd.mkdir()+ monkeypatch.setenv("SOUP_DB_PATH", str(tmp_path / "exp.db"))+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(tmp_path / "reg.db"))+ monkeypatch.chdir(cwd)+ return tmp_path+++def test_register_from_run_passes_the_key_through(work):+ from soup_cli.experiment.tracker import ExperimentTracker++ run_id = _finished_run()+ tracker = ExperimentTracker()+ try:+ with RegistryStore() as store:+ first = store.register_from_run(+ tracker, run_id, name="chat", tag="v1", idempotency_key="job-42",+ )+ again = store.register_from_run(+ tracker, run_id, name="chat", tag="v1", idempotency_key="job-42",+ )+ assert again == first+ assert store.get(first)["idempotency_key"] == "job-42"+ with pytest.raises(IdempotencyConflictError):+ store.register_from_run(+ tracker, run_id, name="chat", tag="v2", idempotency_key="job-42",+ )+ finally:+ tracker.close()+ assert _counts(work / "reg.db") == (1, 1)+++def _cli_push(run_id: str, *extra: str):+ return runner.invoke(+ app, ["registry", "push", "--run-id", run_id, "--name", "chat", "--tag", "v1", *extra],+ )+++def test_cli_retry_with_the_same_key_reports_the_existing_entry(work):+ run_id = _finished_run()++ first = _cli_push(run_id, "--idempotency-key", "job-42")+ second = _cli_push(run_id, "--idempotency-key", "job-42")++ assert first.exit_code == 0, (first.output, repr(first.exception))+ assert second.exit_code == 0, (second.output, repr(second.exception))+ assert "Registered" in strip_ansi(first.output)+ with RegistryStore() as store:+ entry = store.get_by_idempotency_key("job-42")+ out = strip_ansi(second.output)+ assert "Already registered" in out+ assert entry["id"] in out+ assert _counts(work / "reg.db") == (1, 1)+++def test_cli_same_key_for_a_different_tag_fails_naming_the_entry(work):+ run_id = _finished_run()+ assert _cli_push(run_id, "--idempotency-key", "job-42").exit_code == 0++ result = runner.invoke(+ app,+ ["registry", "push", "--run-id", run_id, "--name", "chat", "--tag", "v2",+ "--idempotency-key", "job-42"],+ )++ assert result.exit_code == 1+ out = strip_ansi(result.output)+ assert "job-42" in out and "tag" in out+ assert "Traceback" not in out+ assert _counts(work / "reg.db") == (1, 1)+++def test_cli_invalid_key_is_refused_before_any_database_is_opened(work):+ result = _cli_push("run_x", "--idempotency-key", "bad key")++ assert result.exit_code == 1+ assert "idempotency key" in strip_ansi(result.output)+ assert not (work / "reg.db").exists()+ assert not (work / "exp.db").exists()+++def test_cli_without_a_key_is_unchanged(work):+ run_id = _finished_run()++ assert _cli_push(run_id).exit_code == 0+ assert _cli_push(run_id).exit_code == 0++ with RegistryStore() as store:+ entries = store.list(run_id=run_id)+ assert len(entries) == 2+ assert {e["idempotency_key"] for e in entries} == {None}