Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_backup_schedule.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_backup_schedule.py · 19.1 KB · 422 lines
1"""Scheduled backups to a destination off the box, and the restore test.
2
3The claims these tests hold the module to, because each is a way a backup
4can look fine and not be:
5
6- a snapshot taken while writers are writing is still consistent: every
7 collection's table agrees with its change log, and the restore test
8 passes;
9- a snapshot whose bytes rotted at the destination FAILS its restore test,
10 and names the file;
11- retention deletes only its own old snapshots, never anything else that
12 lives at the destination, and never the newest one that passed a test;
13- a destination inside the data directory, missing (an unmounted disk) or
14 unwritable is refused before anything is written;
15- unchanged files are hard links to the previous snapshot, not copies;
16- secrets stay out, exactly as object_backup keeps them out.
17"""
18from __future__ import annotations
19
20import json
21import os
22import threading
23from datetime import datetime, timedelta, timezone
24from pathlib import Path
25
26import pytest
27
28import object_backup_schedule as sched
29import object_records
30
31
32def _write(path: Path, content: str | bytes) -> Path:
33 path.parent.mkdir(parents=True, exist_ok=True)
34 if isinstance(content, bytes):
35 path.write_bytes(content)
36 else:
37 path.write_text(content)
38 return path
39
40
41@pytest.fixture
42def box(tmp_path, monkeypatch):
43 """A small live box (objects, records, schemas, files, users, secrets)
44 and an empty destination on its own directory."""
45 objects_dir = tmp_path / "live" / "objects"
46 data_dir = tmp_path / "live" / "data"
47 dest = tmp_path / "offsite"
48 dest.mkdir()
49 _write(objects_dir / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
50 _write(data_dir / "schemas" / "notes.json", json.dumps({
51 "name": "notes", "fields": [{"name": "id", "type": "string"},
52 {"name": "title", "type": "string"}]}))
53 for index in range(5):
54 object_records.create_collection_record(
55 "notes", {"id": f"n{index}", "title": f"note {index}"}, base_dir=data_dir)
56 _write(data_dir / "collections" / "files" / "records.tsv",
57 "id\tname\towner_id\nf1\tphoto.png\tada\n")
58 _write(data_dir / "user_files" / "ada" / "f1", b"\x89PNG bytes" * 100)
59 _write(data_dir / "permissions" / "policy.json", json.dumps({"rules": []}))
60 _write(data_dir / "identity" / "users.tsv",
61 "user_id\taccount_id\temail\tdisplay_name\tstatus\troles\tsubscriptions\t"
62 "created_at\tupdated_at\nada\tacct1\tada@example.com\tAda\tactive\tadmin\t\t\t\n")
63 _write(data_dir / "identity" / "credentials.tsv", "id\tsecret\nx\tHUNTER2\n")
64 _write(data_dir / "identity" / "service_keys.tsv", "id\tsecret\nx\tHUNTER2\n")
65 _write(data_dir / "exchange" / "private" / "k.key", "HUNTER2")
66 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_dir))
67 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
68 env = {sched.DESTINATION_ENV: str(dest), sched.KEEP_ENV: "3"}
69 return {"objects": objects_dir, "data": data_dir, "dest": dest, "env": env,
70 "tmp": tmp_path}
71
72
73def _backup(box, **kwargs):
74 return sched.run_backup(box["data"], env=box["env"], objects_dir=box["objects"], **kwargs)
75
76
77def test_a_backup_restores_and_passes_its_restore_test(box):
78 result = _backup(box)
79 assert result["ok"], result
80 assert result["restore_test"]["ok"], result
81 snapshot = box["dest"] / result["name"]
82 manifest = json.loads((snapshot / "manifest.json").read_text())
83 assert manifest["fingerprint"]["collections"]["notes"]["count"] == 5
84 assert (snapshot / "data" / "user_files" / "ada" / "f1").is_file()
85 assert (snapshot / "objects" / "site" / "home.py").is_file()
86 test = json.loads((snapshot / "restore-test.json").read_text())
87 assert test["ok"] and test["checked"]["records"] >= 6
88
89
90def test_secrets_stay_on_the_box(box):
91 result = _backup(box)
92 snapshot = box["dest"] / result["name"]
93 names = {path.relative_to(snapshot).as_posix() for path in snapshot.rglob("*")}
94 assert "data/identity/users.tsv" in names
95 assert "data/identity/credentials.tsv" not in names
96 assert "data/identity/service_keys.tsv" not in names
97 assert not any(name.startswith("data/exchange") for name in names)
98 for path in snapshot.rglob("*"):
99 if path.is_file():
100 assert b"HUNTER2" not in path.read_bytes(), path
101 manifest = json.loads((snapshot / "manifest.json").read_text())
102 assert "identity/credentials.tsv" in manifest["excluded"]
103 assert "exchange" in manifest["excluded"]
104
105
106def test_a_corrupted_backup_fails_the_restore_test_and_names_the_file(box):
107 result = _backup(box)
108 snapshot = box["dest"] / result["name"]
109 target = snapshot / "data" / "collections" / "notes" / "records.tsv"
110 data = bytearray(target.read_bytes())
111 data[-3] = ord("X") if data[-3] != ord("X") else ord("Y") # same size, different bytes
112 os.chmod(target, 0o600)
113 target.write_bytes(bytes(data))
114 test = sched.run_restore_test(box["data"], env=box["env"], objects_dir=box["objects"])
115 assert test["ok"] is False
116 assert any("data/collections/notes/records.tsv" in error for error in test["errors"])
117 payload = sched.status(box["data"], env=box["env"], objects_dir=box["objects"])
118 assert payload["healthy"] is False
119 assert "restore_test_failed" in {problem["id"] for problem in payload["problems"]}
120
121
122def test_a_missing_file_and_a_stowaway_both_fail_the_restore_test(box):
123 result = _backup(box)
124 snapshot = box["dest"] / result["name"]
125 (snapshot / "data" / "user_files" / "ada" / "f1").unlink()
126 _write(snapshot / "data" / "collections" / "notes" / "extra.tsv", "id\nzz\n")
127 test = sched.restore_test(snapshot)
128 assert not test["ok"]
129 joined = " ".join(test["errors"])
130 assert "missing from snapshot: data/user_files/ada/f1" in joined
131 assert "not in the manifest: data/collections/notes/extra.tsv" in joined
132
133
134def test_a_manifest_that_disagrees_with_the_loaders_fails(box):
135 """The record-level check is independent of the byte-level one: a
136 manifest whose recorded count is wrong fails even with every byte intact."""
137 result = _backup(box)
138 snapshot = box["dest"] / result["name"]
139 manifest = json.loads((snapshot / "manifest.json").read_text())
140 manifest["fingerprint"]["collections"]["notes"]["count"] = 4
141 (snapshot / "manifest.json").write_text(json.dumps(manifest))
142 test = sched.restore_test(snapshot)
143 assert not test["ok"]
144 assert any(error.startswith("collection notes:") for error in test["errors"])
145
146
147def test_the_restore_test_never_touches_live_data(box):
148 before = {path: path.read_bytes() for path in box["data"].rglob("*") if path.is_file()
149 and not path.name.startswith(".")}
150 result = _backup(box)
151 assert result["restore_test"]["ok"]
152 after = {path: path.read_bytes() for path in box["data"].rglob("*") if path.is_file()
153 and not path.name.startswith(".")}
154 assert before == after
155 with pytest.raises(sched.BackupScheduleError, match="overlaps live data"):
156 sched.restore_test(box["dest"] / result["name"], work_dir=box["data"] / "tmp",
157 live_dirs=(box["data"],))
158
159
160def test_a_backup_taken_while_writes_happen_is_consistent(box):
161 """Writers keep creating notes for the whole backup. Every snapshot's
162 notes table must agree with its change log row for row (they are
163 captured together under the collection's lock), and the restore test
164 must pass."""
165 stop = threading.Event()
166 written = []
167
168 errors = []
169
170 def writer(prefix):
171 index = 0
172 try:
173 while not stop.is_set():
174 object_records.create_collection_record(
175 "notes", {"id": f"{prefix}{index}", "title": "x" * 200},
176 base_dir=box["data"])
177 written.append(index)
178 index += 1
179 except Exception as exc: # noqa: BLE001 -- surfaced by the assert below
180 errors.append(exc)
181
182 threads = [threading.Thread(target=writer, args=(prefix,)) for prefix in ("wa", "wb")]
183 for thread in threads:
184 thread.start()
185 try:
186 while len(written) < 20 and not errors:
187 pass
188 before = len(written)
189 result = _backup(box)
190 during = len(written) - before
191 finally:
192 stop.set()
193 for thread in threads:
194 thread.join()
195 assert not errors
196 assert during > 0, "the writers must have been writing during the backup"
197 assert result["ok"] and result["restore_test"]["ok"], result
198 snapshot = box["dest"] / result["name"]
199 rows = object_records.read_collection_records("notes", base_dir=snapshot / "data")
200 changes = (snapshot / "data" / "record_changes" / "notes" / "changes.jsonl").read_text()
201 created = {json.loads(line)["record_id"] for line in changes.splitlines() if line}
202 assert {row["id"] for row in rows} == created
203 assert len(rows) > 5
204
205
206def test_unchanged_files_are_hard_links_to_the_previous_snapshot(box):
207 first = _backup(box)
208 object_records.create_collection_record("notes", {"id": "n9", "title": "new"},
209 base_dir=box["data"])
210 second = _backup(box, now=datetime.now(timezone.utc) + timedelta(seconds=1))
211 assert second["ok"] and second["restore_test"]["ok"], second
212 assert second["linked"] >= 3 and second["copied"] >= 1
213 a = box["dest"] / first["name"] / "data" / "user_files" / "ada" / "f1"
214 b = box["dest"] / second["name"] / "data" / "user_files" / "ada" / "f1"
215 assert os.stat(a).st_ino == os.stat(b).st_ino
216 old = box["dest"] / first["name"] / "data" / "collections" / "notes" / "records.tsv"
217 new = box["dest"] / second["name"] / "data" / "collections" / "notes" / "records.tsv"
218 assert os.stat(old).st_ino != os.stat(new).st_ino
219 assert b"n9" in new.read_bytes() and b"n9" not in old.read_bytes()
220
221
222def test_a_failed_restore_test_makes_the_next_backup_a_full_copy(box):
223 """A rotted file must not be linked forward forever."""
224 first = _backup(box)
225 (box["dest"] / first["name"] / "restore-test.json").write_text('{"ok": false}')
226 second = _backup(box, now=datetime.now(timezone.utc) + timedelta(seconds=1))
227 assert second["linked"] == 0 and second["linked_from"] is None
228
229
230def test_retention_deletes_only_its_own_old_snapshots(box):
231 other = _write(box["dest"] / "family-photos" / "a.jpg", b"jpg")
232 lookalike = box["dest"] / "dbbasic-snapshot-20200101T000000000000Z"
233 _write(lookalike / "notes.txt", "a hand-made copy with no manifest of ours")
234 start = datetime.now(timezone.utc)
235 names = []
236 for offset in range(5):
237 result = _backup(box, now=start + timedelta(seconds=offset))
238 assert result["ok"]
239 names.append(result["name"])
240 kept = [snap.name for snap in sched.list_snapshots(box["dest"])]
241 assert kept == sorted(names, reverse=True)[:3]
242 assert other.read_bytes() == b"jpg"
243 assert (lookalike / "notes.txt").is_file()
244
245
246def test_retention_keeps_the_newest_snapshot_that_passed_its_test(box):
247 start = datetime.now(timezone.utc)
248 names = [sched.create_snapshot(box["dest"], data_dir=box["data"], objects_dir=box["objects"],
249 now=start + timedelta(seconds=offset))["name"]
250 for offset in range(6)]
251 for name in names:
252 (box["dest"] / name / "restore-test.json").write_text('{"ok": false}')
253 (box["dest"] / names[0] / "restore-test.json").write_text('{"ok": true}')
254 removed = sched.prune_snapshots(box["dest"], 3)
255 assert (box["dest"] / names[0]).is_dir()
256 assert sorted(removed) == names[1:3]
257
258
259def test_partial_snapshots_left_by_a_crash_are_swept(box):
260 partial = box["dest"] / ".partial-dbbasic-snapshot-20200101T000000000000Z"
261 _write(partial / "data" / "x", "half")
262 assert _backup(box)["ok"]
263 assert not partial.exists()
264
265
266def test_a_destination_inside_the_data_directory_is_refused(box):
267 inside = box["data"] / "backups-here"
268 inside.mkdir()
269 env = {sched.DESTINATION_ENV: str(inside)}
270 result = sched.run_backup(box["data"], env=env, objects_dir=box["objects"])
271 assert result["ok"] is False
272 assert "overlaps the data directory" in result["error"]
273 assert list(inside.iterdir()) == []
274 payload = sched.status(box["data"], env=env, objects_dir=box["objects"])
275 assert "destination_refused" in {problem["id"] for problem in payload["problems"]}
276
277
278def test_a_missing_destination_is_refused_and_never_created(box):
279 """An unmounted disk's mount point may be missing or empty; writing a
280 "backup" onto the root disk would never leave the box."""
281 missing = box["tmp"] / "not-mounted"
282 result = sched.run_backup(box["data"], env={sched.DESTINATION_ENV: str(missing)},
283 objects_dir=box["objects"])
284 assert result["ok"] is False and "does not exist" in result["error"]
285 assert not missing.exists()
286
287
288@pytest.mark.skipif(hasattr(os, "geteuid") and os.geteuid() == 0, reason="root can write anywhere")
289def test_an_unwritable_destination_is_refused(box):
290 os.chmod(box["dest"], 0o500)
291 try:
292 result = _backup(box)
293 finally:
294 os.chmod(box["dest"], 0o700)
295 assert result["ok"] is False and "not writable" in result["error"]
296
297
298def test_a_relative_destination_is_refused(box):
299 problems = sched.destination_problems("relative/path", data_dir=box["data"])
300 assert any("absolute" in problem for problem in problems)
301
302
303def test_off_by_default_and_quiet(box):
304 payload = sched.status(box["data"], env={})
305 assert payload["enabled"] is False and payload["problems"] == []
306 assert payload["healthy"] is False and "off" in payload["note"]
307 assert sched.due(box["data"], env={}) is False
308 with pytest.raises(sched.BackupScheduleError):
309 sched.run_backup(box["data"], env={})
310
311
312def test_status_is_healthy_only_after_a_backup_and_a_passing_test(box):
313 payload = sched.status(box["data"], env=box["env"], objects_dir=box["objects"])
314 assert payload["healthy"] is False
315 assert {"backup_missing", "restore_test_missing"} <= {p["id"] for p in payload["problems"]}
316 _backup(box)
317 payload = sched.status(box["data"], env=box["env"], objects_dir=box["objects"])
318 assert payload["healthy"] is True, payload["problems"]
319 assert payload["last_good_backup"]["files"] >= 5
320
321
322def test_a_stale_backup_is_a_problem(box):
323 _backup(box)
324 later = datetime.now(timezone.utc) + timedelta(days=3)
325 payload = sched.status(box["data"], env=box["env"], objects_dir=box["objects"], now=later)
326 ids = {problem["id"] for problem in payload["problems"]}
327 assert {"backup_stale", "restore_test_stale"} <= ids
328 assert payload["healthy"] is False
329
330
331def test_due_follows_the_interval_and_retries_a_failure_sooner(box):
332 env = dict(box["env"], **{sched.INTERVAL_ENV: "86400"})
333 assert sched.due(box["data"], env=env)
334 sched.run_backup(box["data"], env=env, objects_dir=box["objects"])
335 now = datetime.now(timezone.utc)
336 assert not sched.due(box["data"], env=env, now=now + timedelta(hours=2))
337 assert sched.due(box["data"], env=env, now=now + timedelta(days=1, minutes=1))
338 bad = dict(env, **{sched.DESTINATION_ENV: str(box["tmp"] / "gone")})
339 sched.run_backup(box["data"], env=bad, objects_dir=box["objects"])
340 assert sched.due(box["data"], env=bad, now=datetime.now(timezone.utc) + timedelta(hours=2))
341
342
343def test_a_failed_backup_never_looks_healthy_even_after_an_older_good_one(box):
344 _backup(box)
345 bad = dict(box["env"], **{sched.DESTINATION_ENV: str(box["tmp"] / "gone")})
346 sched.run_backup(box["data"], env=bad, objects_dir=box["objects"])
347 payload = sched.status(box["data"], env=box["env"], objects_dir=box["objects"])
348 assert "backup_failed" in {problem["id"] for problem in payload["problems"]}
349 assert payload["healthy"] is False
350
351
352def test_restore_copies_a_snapshot_back_and_refuses_to_clobber(box):
353 result = _backup(box)
354 snapshot = box["dest"] / result["name"]
355 target = box["tmp"] / "restored"
356 summary = sched.restore_snapshot(snapshot, objects_dir=target / "objects",
357 data_dir=target / "data")
358 assert summary["files"] >= 5
359 rows = object_records.read_collection_records("notes", base_dir=target / "data")
360 assert sorted(row["id"] for row in rows) == [f"n{i}" for i in range(5)]
361 with pytest.raises(sched.BackupScheduleError, match="already exists"):
362 sched.restore_snapshot(snapshot, objects_dir=target / "objects", data_dir=target / "data")
363
364
365def test_the_after_command_hook_runs_with_the_snapshot_path(box, tmp_path):
366 marker = tmp_path / "hook-ran.txt"
367 script = _write(tmp_path / "hook.py",
368 "import sys, pathlib\n"
369 f"pathlib.Path({str(marker)!r}).write_text(sys.argv[1])\n")
370 import sys
371 env = dict(box["env"], **{sched.AFTER_COMMAND_ENV: f"{sys.executable} {script}"})
372 result = sched.run_backup(box["data"], env=env, objects_dir=box["objects"])
373 assert result["after_command"]["ok"], result["after_command"]
374 assert marker.read_text().endswith(result["name"])
375
376
377def test_a_failing_after_command_is_a_problem(box):
378 env = dict(box["env"], **{sched.AFTER_COMMAND_ENV: "/nonexistent/encrypt-and-ship"})
379 result = sched.run_backup(box["data"], env=env, objects_dir=box["objects"])
380 assert result["after_command"]["ok"] is False
381 payload = sched.status(box["data"], env=env, objects_dir=box["objects"])
382 assert "after_command_failed" in {problem["id"] for problem in payload["problems"]}
383
384
385def test_a_second_run_against_the_same_destination_is_refused_while_one_runs(box):
386 with sched._destination_lock(box["dest"]):
387 with pytest.raises(sched.BackupScheduleError, match="already running"):
388 _backup(box)
389
390
391def test_the_cli_runs_tests_and_reports(box, monkeypatch, capsys):
392 monkeypatch.setenv(sched.DESTINATION_ENV, str(box["dest"]))
393 assert sched.main(["run", "--data-dir", str(box["data"]),
394 "--objects-dir", str(box["objects"])]) == 0
395 capsys.readouterr()
396 assert sched.main(["test", "--data-dir", str(box["data"]),
397 "--objects-dir", str(box["objects"])]) == 0
398 assert json.loads(capsys.readouterr().out)["ok"] is True
399 assert sched.main(["status", "--data-dir", str(box["data"]),
400 "--objects-dir", str(box["objects"])]) == 0
401 assert json.loads(capsys.readouterr().out)["healthy"] is True
402
403
404def test_a_run_whose_process_died_does_not_show_as_running(box):
405 import subprocess
406 import sys
407
408 child = subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"],
409 capture_output=True, text=True, check=True)
410 dead_pid = int(child.stdout)
411 sched._record(box["data"], running={"kind": "backup", "started_at": "2026-01-01T00:00:00Z",
412 "pid": dead_pid})
413 assert sched.status(box["data"], env=box["env"])["running"] is None
414 sched._record(box["data"], running={"kind": "backup", "started_at": "2026-01-01T00:00:00Z",
415 "pid": os.getpid()})
416 assert sched.status(box["data"], env=box["env"])["running"]["kind"] == "backup"
417
418
419def test_status_history_is_bounded(box):
420 for _ in range(sched.HISTORY_LIMIT + 5):
421 sched._record(box["data"], event={"kind": "backup", "ok": True})
422 assert len(sched.read_status(box["data"])["history"]) == sched.HISTORY_LIMIT