From a8db7eec72bd358a664a8b4dff7e618b90917f84 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 06:13:32 +0000 Subject: [PATCH 1/5] feat(db): named database upgrades with a lock, a run log and lens migrations Data upgrades were tracked by a position counter, ran in every starting process at once, and left no record. Steps now have names (adopting the two the counter tracked), one process runs them under a lease lock while the others wait, each run or failure is kept in migration:, and lens migrations lists them without running anything. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01CMvFKqsrnJrxxvME87LRk7 --- CHANGELOG.md | 4 + CONTRIBUTING.md | 2 + docs/database.md | 30 +++- docs/get-started.md | 1 + fastapi_backend/app/cli.py | 18 +- fastapi_backend/app/domain/migrations.py | 169 ++++++++++++++++++ fastapi_backend/app/domain/store.py | 29 ++- .../tests/api/test_access_settings.py | 2 +- fastapi_backend/tests/api/test_setup.py | 4 +- .../tests/domain/test_migrations.py | 143 +++++++++++++++ 10 files changed, 379 insertions(+), 23 deletions(-) create mode 100644 fastapi_backend/app/domain/migrations.py create mode 100644 fastapi_backend/tests/domain/test_migrations.py diff --git a/CHANGELOG.md b/CHANGELOG.md index fc1854751..32b3627be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Safer upgrades of existing installs.** Data upgrades are now named steps that run once per database, under a lock + so only one process runs them while the others wait, with a record of when each ran and why one failed. + `lens migrations` lists them. See docs/database.md, Upgrades. + - **Query the graph in Cypher, and walk it.** The archive is now a property graph of namespaces, collections, recordings, speakers and entities. `POST /api/v1/graph/query` runs read-only Cypher (the language of Neo4j and ISO GQL) over the namespaces you can read; `/graph/related` gives a node's parents, children, ancestors, descendants or diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0639abe6b..25df671cd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,6 +16,8 @@ Thanks for helping. The full guide, with the backend and frontend conventions, i - Backend: `make test-backend` and `make lint-backend` (ruff, mypy). Frontend: `make test-frontend` and `make lint-frontend`. - Add tests with the change, and update `docs/` when behaviour or configuration changes. +- Changing the shape of stored data? Existing installs have real data: add an upgrade step + (docs/database.md, Upgrades) rather than expecting a fresh database. - One concern per pull request. Keep generated files (`openapi.json`, the frontend client) in the same PR as the API change that produced them. diff --git a/docs/database.md b/docs/database.md index 79daa8342..385cb1798 100644 --- a/docs/database.md +++ b/docs/database.md @@ -33,7 +33,8 @@ engine and with SurrealDB 2.3 and 3.2 servers. ## Schema The schema is defined idempotently in `app/domain/store.py` (`SCHEMA`) and applied on every start -(`DEFINE ... IF NOT EXISTS`), so there are no migration files. Tables are `SCHEMALESS` with indexes on the fields +(`DEFINE ... IF NOT EXISTS`), so new tables, fields and indexes need no migration (see [Upgrades](#upgrades) for the +rest). Tables are `SCHEMALESS` with indexes on the fields that are queried. Graph edges are real relations: `mentions` (segment → entity) and `same_as` (speaker → speaker). ```sql @@ -48,8 +49,31 @@ cosine; servers only) defined when the first vector is stored, since its `DIMENS which model and dimension that is. A server searches it with `embedding <|k,ef|> $vec AND …filters`, which 3.2.4 applies inside the index scan (a filtered search still returns k rows). -When a change needs data rewritten (not just a new index), add an idempotent step to `store.connect()` guarded by a -version stored in the `seq` table, so it runs once per database. +## Upgrades + +Installs keep their data across updates (running `install.sh` again, a new image, `git pull`). New tables, fields and +indexes arrive through `SCHEMA` on the next start. Anything else, such as rewriting stored values, moving data between +tables, or changing or removing an index that already exists, is a named step in `app/domain/migrations.py`: + +* Every process that opens the database (the API, workers, `lens watch`, `lens` commands) runs the steps the database + hasn't had yet when it starts, in order. One process takes a lock (`migration_lock:run`) and runs them; the others + wait, so no code reads data in a shape it doesn't expect. A holder that dies loses the lock after five minutes. +* Each step run is recorded in `migration:⟨name⟩` with when and how long it took. A step that fails records its error + and stops the start; once the cause is fixed, the next start runs it again. +* `lens migrations` lists every step (done, pending, failed, or unknown when a newer Lens ran it) without running + anything, so it works while an upgrade is failing; `lens migrations --run` runs the pending ones. + +To add a step: + +1. Write a function `fn(db)` next to the code it serves. It must be safe to run twice, since a start that stops half + way runs it again; prefer `UPDATE ... WHERE ` over rewriting every row. +2. Append `("short-name", module.fn)` to `steps()` in `migrations.py`, and the name to `SHIPPED` in + `tests/domain/test_migrations.py`. Never rename, reorder or remove a shipped step: databases remember steps by + name, so a renamed one runs again and a removed one never runs. +3. Keep reads tolerant of the old shape until the step has run (it runs before requests are served, but a worker on + another machine may still be on the old version). +4. Test it on data in the old shape, against a SurrealDB server too (`LENS_TEST_SURREAL_URL`); + `test_every_step_is_safe_to_repeat` checks that a second run changes nothing. ## Concurrency diff --git a/docs/get-started.md b/docs/get-started.md index bf943de79..ea5b3f8f1 100644 --- a/docs/get-started.md +++ b/docs/get-started.md @@ -105,6 +105,7 @@ lens search "capsid" --ns podcasts lens search "money worries" --mode semantic # by meaning (with an embedding model; see configuration.md) lens embed # index what isn't yet searchable by meaning lens reindex # after changing search.stemming +lens migrations # database upgrades: run, pending or failed ``` Docker on macOS can't use the Apple GPU. Keep the database and API in Docker and run a native worker against the same diff --git a/fastapi_backend/app/cli.py b/fastapi_backend/app/cli.py index 49d9ce3ab..cfbcd1c92 100644 --- a/fastapi_backend/app/cli.py +++ b/fastapi_backend/app/cli.py @@ -96,6 +96,8 @@ def _main_base(argv=None): p.add_argument("--host") p.add_argument("--port", type=int) sub.add_parser("status") + p = sub.add_parser("migrations", help="list the database upgrades: run, pending or failed (docs/database.md)") + p.add_argument("--run", action="store_true", help="run the pending ones now (Lens also runs them when it starts)") sub.add_parser("reindex", help="rebuild the search index (after changing search.tokenizer)") p = sub.add_parser("encrypt", help="encrypt the files Lens keeps, and keep encrypting new ones (docs/encryption.md)") p.add_argument("--off", action="store_true", help="decrypt them again and stop encrypting new ones") @@ -122,7 +124,7 @@ def _main_base(argv=None): os.environ["ARCHIVE_CONFIG"] = a.config uvicorn.run("app.main:app", host=a.host or cfg["server"]["host"], port=a.port or cfg["server"]["port"], proxy_headers=True) return - conn = store.connect(cfg) + conn = store.connect(cfg, upgrade=a.cmd != "migrations") # so a failed upgrade can still be looked at try: if a.cmd in ("scan", "transcribe", "diarize", "analyze", "embed", "summarize", "run", "report"): which = ["scan", "transcribe", "diarize", "analyze", "embed", "summarize", "report"] if a.cmd == "run" else [a.cmd] @@ -184,6 +186,20 @@ def _main_base(argv=None): print(f" {n:<16} {st:<12} {c:>5} {ms / 3.6e6:6.1f} h") for r in conn.rows("SELECT title, error FROM recording WHERE error != NONE LIMIT 10"): print(f" error: {r['title']}: {r['error']}") + elif a.cmd == "migrations": + from .domain import migrations + + if a.run: + ran = migrations.run(conn) + print(f"ran {len(ran)} upgrade(s): {', '.join(ran)}" if ran else "nothing to run") + for m in migrations.status(conn): + when = {"done": m["done_at"], "failed": m["failed_at"]}.get(m["state"]) or "" + took = f" ({m['took_ms']} ms)" if m["state"] == "done" and m.get("took_ms") else "" + print(f" {m['state']:<8} {m['name']:<28} {when}{took}") + if m["state"] == "failed": + print(f" {m['error']}") + elif m["state"] == "unknown": + print(" run by a newer Lens than this one") elif a.cmd == "reindex": store.reindex(conn, cfg) print("search index rebuilt") diff --git a/fastapi_backend/app/domain/migrations.py b/fastapi_backend/app/domain/migrations.py new file mode 100644 index 000000000..4f805410b --- /dev/null +++ b/fastapi_backend/app/domain/migrations.py @@ -0,0 +1,169 @@ +"""Upgrading the data of an existing install: named steps that run once per database, in order (docs/database.md). + +The schema itself (tables, fields, indexes) is applied on every start from store.SCHEMA. A step here is for what that +can't do: rewriting stored data, or changing or removing an index that already exists. Each step: + +- has a name that never changes, and goes at the end of STEPS (never reorder, rename or remove one: a database + remembers steps by name, so a renamed step runs again and a removed one is simply never run); +- is safe to run twice, because a start that stops half way runs it again; +- lives with the code it serves, so STEPS only names it. + +Every process that opens the database (the API, workers, `lens watch`, `lens` commands) checks for pending steps when it +starts. One of them takes the lock and runs them; the others wait until it is done, so nothing reads data in a shape +its code doesn't expect. A dead holder's lock lapses after LEASE seconds. What ran, when, how long it took and why a +step failed are kept in `migration:⟨name⟩`; `lens migrations` lists them. +""" + +from __future__ import annotations + +import logging +import os +import socket +import threading +import time +import uuid + +from .store import R, now + +log = logging.getLogger("lens") + +LEASE = 300 # seconds a lock holder may go quiet before another process takes over +WAIT_LOG = 30 # how often a waiting process says what it is waiting for + +# The steps that came before named steps, tracked then by a counter (seq:migrations = how many had run): a database +# whose counter reached n has done the first n of these, under these names. +LEGACY = ("access-levels", "collection-homes") + + +def steps(): + """[(name, fn(db))] in the order they run. Append only.""" + from . import access, hierarchy + + return [ + # IIIF-only access levels (public, transcript, signed-in, private) become the access setting + ("access-levels", access.migrate_legacy), + # every namespace gets its default collection and every recording a home + ("collection-homes", hierarchy.migrate_homes), + ] + + +class Failed(RuntimeError): + def __init__(self, name, err): + super().__init__( + f"upgrading the database stopped at step {name!r}: {err}. Fix the cause and start Lens again; the step runs " + "again from the start and is safe to repeat (`lens migrations` lists what has run)." + ) + self.step = name + + +def _done(db): + return {r["name"] for r in db.rows("SELECT name FROM migration WHERE done_at != NONE")} + + +def _adopt_legacy(db): + """Record the steps an older Lens ran under its counter, so they aren't run again.""" + n = int((db.one("SELECT n FROM $r", r=R("seq", "migrations")) or {}).get("n") or 0) + if not n: + return + have = _done(db) + for name in LEGACY[:n]: + if name not in have: + db.q("UPSERT $r CONTENT $d", r=R("migration", name), d={"name": name, "done_at": now(), "took_ms": 0, "legacy": True}) + + +def pending(db, registered=None): + """Names of the steps this database has still to run, in order.""" + _adopt_legacy(db) + done = _done(db) + return [name for name, _ in (registered if registered is not None else steps()) if name not in done] + + +def status(db, registered=None): + """Every step this code knows and any the database ran that it doesn't (from a newer Lens), in order: + [{name, state: done|pending|failed|unknown, done_at, took_ms, failed_at, error}].""" + _adopt_legacy(db) + rows = {r["name"]: r for r in db.rows("SELECT * OMIT id FROM migration")} + out = [] + for name, _ in registered if registered is not None else steps(): + r = rows.pop(name, {}) + state = "done" if r.get("done_at") else "failed" if r.get("error") else "pending" + out.append({"name": name, "state": state, **{k: r.get(k) for k in ("done_at", "took_ms", "failed_at", "error")}}) + for name, r in sorted(rows.items(), key=lambda kv: str(kv[1].get("done_at"))): + out.append({"name": name, "state": "unknown", **{k: r.get(k) for k in ("done_at", "took_ms", "failed_at", "error")}}) + return out + + +# ---------- the lock ---------- +def _take(db, holder): + db.q("DELETE $r WHERE until < $t", r=R("migration_lock", "run"), t=time.time()) + try: + db.q("CREATE $r CONTENT $d", r=R("migration_lock", "run"), d={"holder": holder, "until": time.time() + LEASE, "since": now()}) + return True + except Exception as e: # noqa: BLE001 + if "already exists" in str(e): + return False + raise + + +def _renew(db, holder): + db.q("UPDATE $r SET until = $u WHERE holder = $h", r=R("migration_lock", "run"), u=time.time() + LEASE, h=holder) + + +def _release(db, holder): + db.q("DELETE $r WHERE holder = $h", r=R("migration_lock", "run"), h=holder) + + +def _holder(db): + return (db.one("SELECT holder FROM $r", r=R("migration_lock", "run")) or {}).get("holder") + + +def run(db, registered=None, poll=1.0): + """Run the pending steps, or wait while another process runs them. Returns the names this process ran.""" + registered = registered if registered is not None else steps() + if not pending(db, registered): + return [] + holder = f"{socket.gethostname()}:{os.getpid()}:{uuid.uuid4().hex[:8]}" + said = 0.0 + while not _take(db, holder): + if not pending(db, registered): + return [] # the process that held the lock finished them + if time.time() - said > WAIT_LOG: + log.info("waiting for %s to finish upgrading the database", _holder(db) or "another process") + said = time.time() + time.sleep(poll) + stop = threading.Event() + + def beat(): + while not stop.wait(LEASE / 5): + try: + _renew(db, holder) + except Exception: # noqa: BLE001 + log.exception("could not renew the database upgrade lock") + + beater = threading.Thread(target=beat, name="migration-lease", daemon=True) + beater.start() + ran = [] + try: + fns = dict(registered) + for name in pending(db, registered): # again: another process may have run some before this one got the lock + log.info("upgrading the database: %s", name) + t = time.time() + try: + fns[name](db) + except Exception as e: + db.q("UPSERT $r MERGE $d", r=R("migration", name), d={"name": name, "failed_at": now(), "error": str(e)[:2000]}) + log.exception("upgrading the database stopped at %s", name) + raise Failed(name, e) from e + took = int((time.time() - t) * 1000) + db.q( + "UPSERT $r CONTENT $d", + r=R("migration", name), + d={"name": name, "done_at": now(), "took_ms": took, "by": holder}, + ) + log.info("upgraded the database: %s (%d ms)", name, took) + ran.append(name) + finally: + stop.set() + beater.join(timeout=5) + _release(db, holder) + return ran diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index 2916aa33e..05f24691d 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -616,10 +616,13 @@ def close(self): SCHEMA = [ - # counters (next_id), the migration marker and the settings version. Defined up front: SurrealDB 3 refuses to + # counters (next_id), the old migration counter and the settings version. Defined up front: SurrealDB 3 refuses to # SELECT from a table nobody has written to yet ("table 'seq' does not exist"), which a fresh database with no # namespaces in archive.yaml would otherwise hit in migrate() before anything had created it. "DEFINE TABLE IF NOT EXISTS seq SCHEMALESS", + # data upgrades (domain/migrations.py): migration:⟨name⟩ for each step run or failed, and the lock while one runs + "DEFINE TABLE IF NOT EXISTS migration SCHEMALESS", + "DEFINE TABLE IF NOT EXISTS migration_lock SCHEMALESS", # first-run setup (domain/setup.py): setup:wizard while the web wizard is still to be finished "DEFINE TABLE IF NOT EXISTS setup SCHEMALESS", # No composite indexes: on SurrealDB 2.x a (space, x) index makes "space = $s" lookups return nothing, so @@ -952,7 +955,9 @@ def _text_index(db): return found -def connect(cfg): +def connect(cfg, upgrade=True): + """Open the database, apply the schema and, unless upgrade=False (for `lens migrations`), bring its data up to + date (domain/migrations.py).""" db = DB(cfg) db.q(_analyzer(cfg)) for s in SCHEMA: @@ -961,24 +966,16 @@ def connect(cfg): for name, spec in cfg["namespaces"].items(): sid = ns_id(db, name) db.q("UPDATE $r SET graph = $g", r=R("space", sid), g=spec["graph"]) - migrate(db) + if upgrade: + migrate(db) return db -def _migrations(): - from . import access, hierarchy # each step lives with the code it serves - - return [access.migrate_legacy, hierarchy.migrate_homes] - - def migrate(db): - """Data rewrites that run once per database, in order. The last one done is kept in seq:migrations; each step is - safe to repeat, so two processes starting together, or a start that stops half way, do no harm.""" - done = int((db.one("SELECT n FROM $r", r=R("seq", "migrations")) or {}).get("n") or 0) - for n, step in enumerate(_migrations(), 1): - if n > done: - step(db) - db.q("UPSERT $r SET n = $n", r=R("seq", "migrations"), n=n) + """Run the data upgrades this database hasn't had yet (domain/migrations.py).""" + from . import migrations + + return migrations.run(db) def reindex(db, cfg): diff --git a/fastapi_backend/tests/api/test_access_settings.py b/fastapi_backend/tests/api/test_access_settings.py index 53f7ae5f2..727f972aa 100644 --- a/fastapi_backend/tests/api/test_access_settings.py +++ b/fastapi_backend/tests/api/test_access_settings.py @@ -121,7 +121,7 @@ def test_convert_the_iiif_levels(db, cfg, folder): # before the conversion, reads already understand the old levels assert metadata.stored(db, x[1])["access"] == "public" and metadata.stored(db, x[1])["open"] == ["transcript", "index"] assert access.of(db, inheriting)["access"] == "restricted" - db.q("DELETE $r", r=R("seq", "migrations")) + db.q("DELETE $r", r=R("migration", "access-levels")) store.migrate(db) got = {rid: access.of(db, rid) for rid in x} assert [(got[r]["access"], got[r]["open"], got[r]["inherited"]) for r in x[:3]] == [ diff --git a/fastapi_backend/tests/api/test_setup.py b/fastapi_backend/tests/api/test_setup.py index d4cdfb1d5..73e323abf 100644 --- a/fastapi_backend/tests/api/test_setup.py +++ b/fastapi_backend/tests/api/test_setup.py @@ -8,7 +8,7 @@ import pytest from fastapi.testclient import TestClient -from app.domain import auth, store +from app.domain import auth, migrations, store from app.domain import settings as app_settings from tests.conftest import TEST_URL from tests.helpers import login, make_user @@ -61,7 +61,7 @@ def make(): def test_fresh_database_without_namespaces_starts(folder): db = store.connect(bare_cfg(folder)) try: - assert db.values("SELECT VALUE n FROM $r", r=store.R("seq", "migrations")) == [2] + assert migrations.pending(db) == [] and [m["state"] for m in migrations.status(db)] == ["done", "done"] assert store.space_names(db) == {} finally: db.close() diff --git a/fastapi_backend/tests/domain/test_migrations.py b/fastapi_backend/tests/domain/test_migrations.py new file mode 100644 index 000000000..54390df15 --- /dev/null +++ b/fastapi_backend/tests/domain/test_migrations.py @@ -0,0 +1,143 @@ +"""Database upgrades (app/domain/migrations.py): named steps that run once per database, under a lock, with a record.""" + +from __future__ import annotations + +import json +import threading +import time + +import pytest + +from app import cli +from app.domain import migrations, store +from app.domain.store import R + +# Every step that has shipped, in order. A database remembers steps by name, so these may never be renamed, reordered +# or removed: add new steps to the end of migrations.steps() and here. +SHIPPED = ["access-levels", "collection-homes"] + + +def test_steps_are_append_only(): + names = [n for n, _ in migrations.steps()] + assert names[: len(SHIPPED)] == SHIPPED, "a shipped step was renamed, reordered or removed" + assert names == SHIPPED, "add the new step's name to SHIPPED too" + assert len(set(names)) == len(names) + assert list(migrations.LEGACY) == SHIPPED[: len(migrations.LEGACY)] + + +def test_a_fresh_database_has_run_every_step(db): + assert migrations.pending(db) == [] + assert [(m["name"], m["state"]) for m in migrations.status(db)] == [(n, "done") for n in SHIPPED] + assert store.migrate(db) == [] # nothing left + assert db.rows("SELECT * FROM migration_lock") == [] + + +def _old_shape(db): + """Data as an older Lens left it: an IIIF-only access level and a recording without a collection.""" + sid = store.ns_id(db, "pods") + rid = db.next_id("recording") + db.q("CREATE $r CONTENT $d", r=R("recording", rid), d={"space": sid, "title": "old", "meta_json": json.dumps({"access": "signed-in"})}) + return rid + + +def _everything(db): + """Every table's rows, minus the upgrade bookkeeping.""" + tables = [s.split()[5] for s in store.SCHEMA if s.startswith("DEFINE TABLE")] + skip = {"migration", "migration_lock", "seq"} + return {t: sorted(map(repr, db.rows(f"SELECT * FROM {t}"))) for t in tables if t not in skip} + + +@pytest.mark.parametrize("name", SHIPPED) +def test_every_step_is_safe_to_repeat(db, name): + _old_shape(db) + step = dict(migrations.steps())[name] + step(db) + once = _everything(db) + step(db) + assert _everything(db) == once + + +def test_steps_an_older_lens_counted_are_not_run_again(db): + """Before named steps, a counter (seq:migrations) said how many had run.""" + db.q("DELETE migration") + db.q("UPSERT $r SET n = 1", r=R("seq", "migrations")) + rid = _old_shape(db) + assert migrations.pending(db) == ["collection-homes"] + assert store.migrate(db) == ["collection-homes"] + row = db.one("SELECT meta_json, collection FROM $r", r=R("recording", rid)) + assert json.loads(row["meta_json"]) == {"access": "signed-in"} # access-levels was counted as done, so not rerun + assert row["collection"] == store.default_collection(db, store.ns_id(db, "pods")) + assert db.one("SELECT legacy FROM $r", r=R("migration", "access-levels"))["legacy"] is True + + +def test_a_failed_step_is_recorded_and_runs_again_next_start(db): + calls = [] + + def broken(_db): + calls.append("broken") + raise ValueError("disk full") + + registered = [("one", lambda _db: calls.append("one")), ("two", broken), ("three", lambda _db: calls.append("three"))] + with pytest.raises(migrations.Failed, match="'two': disk full"): + migrations.run(db, registered) + assert calls == ["one", "broken"] + got = {m["name"]: m for m in migrations.status(db, registered)} + assert (got["one"]["state"], got["two"]["state"], got["three"]["state"]) == ("done", "failed", "pending") + assert got["two"]["error"] == "disk full" + assert db.rows("SELECT * FROM migration_lock") == [] # released, so the next start isn't kept waiting + + registered[1] = ("two", lambda _db: calls.append("two")) # the cause fixed + assert migrations.run(db, registered) == ["two", "three"] + assert calls == ["one", "broken", "two", "three"] + assert [m["state"] for m in migrations.status(db, registered)][:3] == ["done", "done", "done"] + + +def test_one_process_runs_the_steps_while_the_others_wait(db): + calls = [] + + def slow(_db): + calls.append(1) + time.sleep(0.3) + + registered = [("slow", slow)] + results = [] + threads = [threading.Thread(target=lambda: results.append(migrations.run(db, registered, poll=0.02))) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join(10) + assert calls == [1] + assert sorted(results) == [[], [], [], ["slow"]] + + +def test_waits_for_a_live_holder_and_takes_over_from_a_dead_one(db, monkeypatch): + calls = [] + registered = [("x", lambda _db: calls.append(1))] + db.q("CREATE $r CONTENT $d", r=R("migration_lock", "run"), d={"holder": "elsewhere", "until": time.time() + 60}) + t = threading.Thread(target=lambda: migrations.run(db, registered, poll=0.02)) + t.start() + time.sleep(0.2) + assert calls == [] and t.is_alive() # waiting: nothing reads data in a shape its code doesn't expect + db.q("UPDATE $r SET until = $u", r=R("migration_lock", "run"), u=time.time() - 1) # the holder died + t.join(5) + assert calls == [1] + assert db.rows("SELECT * FROM migration_lock") == [] + + +def test_steps_from_a_newer_lens_are_listed(db): + db.q("UPSERT $r CONTENT $d", r=R("migration", "from-the-future"), d={"name": "from-the-future", "done_at": store.now()}) + assert migrations.status(db)[-1]["name"] == "from-the-future" and migrations.status(db)[-1]["state"] == "unknown" + assert migrations.pending(db) == [] + + +def test_lens_migrations_lists_and_runs(tmp_path, monkeypatch, capsys): + monkeypatch.delenv("SURREAL_URL", raising=False) + cfg_path = tmp_path / "archive.yaml" + cfg_path.write_text("data_dir: ./data\nnamespaces:\n pods:\n paths: []\n") + cli.main(["--config", str(cfg_path), "migrations"]) # opens without upgrading: a fresh database, all pending + out = capsys.readouterr().out + assert "pending access-levels" in out and "pending collection-homes" in out + cli.main(["--config", str(cfg_path), "migrations", "--run"]) + out = capsys.readouterr().out + assert "ran 2 upgrade(s): access-levels, collection-homes" in out + assert "done access-levels" in out From 41c682a8d1d03e181e5982eb73a08b699ee8b755 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 06:22:52 +0000 Subject: [PATCH 2/5] feat(db): back the database up before upgrading it, and lens backup A database with data is exported (server) or copied with it closed (embedded) into /backups before pending upgrade steps run; the newest three are kept. A failed backup stops the upgrade unless LENS_UPGRADE_BACKUP=off. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01CMvFKqsrnJrxxvME87LRk7 --- CHANGELOG.md | 3 +- docs/database.md | 18 +++- docs/get-started.md | 1 + fastapi_backend/app/cli.py | 6 ++ fastapi_backend/app/domain/migrations.py | 91 ++++++++++++++++++- fastapi_backend/app/domain/store.py | 18 ++++ .../tests/domain/test_migrations.py | 89 ++++++++++++++++++ 7 files changed, 220 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32b3627be..389f9d59b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,8 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version - **Safer upgrades of existing installs.** Data upgrades are now named steps that run once per database, under a lock so only one process runs them while the others wait, with a record of when each ran and why one failed. - `lens migrations` lists them. See docs/database.md, Upgrades. + `lens migrations` lists them. A database with data is backed up into `/backups` before it is upgraded + (the newest three are kept), and `lens backup` takes one on demand. See docs/database.md, Upgrades. - **Query the graph in Cypher, and walk it.** The archive is now a property graph of namespaces, collections, recordings, speakers and entities. `POST /api/v1/graph/query` runs read-only Cypher (the language of Neo4j and ISO diff --git a/docs/database.md b/docs/database.md index 385cb1798..69a1df76f 100644 --- a/docs/database.md +++ b/docs/database.md @@ -58,6 +58,10 @@ tables, or changing or removing an index that already exists, is a named step in * Every process that opens the database (the API, workers, `lens watch`, `lens` commands) runs the steps the database hasn't had yet when it starts, in order. One process takes a lock (`migration_lock:run`) and runs them; the others wait, so no code reads data in a shape it doesn't expect. A holder that dies loses the lock after five minutes. +* Before a database that holds data (any recording or account) runs pending steps, the process holding the lock backs + it up into `/backups/before-upgrade-