Skip to content

Commit ffaa26d

Browse files
committed
fixup! feat(backup): a live SQLite store is staged as one consistent copy (#731, slice 3)
fix(backup): kill the 26 surviving mutants of the unit check's mutation gate Pipeline run 42801544562, job unit: the diff mutation gate kept 26 survivors in sqlite_snapshot.py, backup_stage.py and backup_snapshot.py. The messages, the read-only URI, the staging refusals and created_at are now pinned by tests; pages=-1 (Python's default) and the default of consumed_ok are gone, so no mutant can alter them. Local mutmut 3.8.1: 0 survivors in all three files. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018kyZYsLE4ZAVorxvEdFaQv
1 parent be865d5 commit ffaa26d

5 files changed

Lines changed: 109 additions & 9 deletions

File tree

‎mcp_server/handlers/backup_snapshot.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ def _stage_files(root: Path, staging: Path, spec: ResourceSpec) -> None:
6565
if spec.kind == "dir": # an empty directory is still present
6666
private_dirs(staging, spec.path)
6767
consumed_ok = spec.name == _CAPTURE_SPOOL # see the module docstring
68-
copy_files(root, staging, [record[0] for record in records], consumed_ok)
68+
copy_files(
69+
root, staging, [record[0] for record in records], consumed_ok=consumed_ok
70+
)
6971

7072

7173
def snapshot_backup(

‎mcp_server/infrastructure/backup_stage.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def private_dirs(staging: Path, relative: str) -> Path:
6868

6969

7070
def copy_files(
71-
root: Path, staging: Path, paths: Iterable[str], consumed_ok: bool = False
71+
root: Path, staging: Path, paths: Iterable[str], *, consumed_ok: bool
7272
) -> None:
7373
"""Copy each ``root/path`` to a new ``0o600`` file ``staging/path``.
7474

‎mcp_server/infrastructure/sqlite_snapshot.py‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
before SQLite opens it (ADR-1112), as the store is.
1616
1717
source: issue #731; docs/audits/owned-resources-backup-2026-11-05.md §3, §5;
18-
SQLite online backup API, https://www.sqlite.org/backup.html: a single
18+
SQLite online backup API, https://www.sqlite.org/backup.html (Python's
19+
``Connection.backup`` defaults to ``pages=-1``): a single
1920
``sqlite3_backup_step()`` call with a negative page count "copies the entire
2021
source database in one call", holding one read lock on the source throughout.
2122
"""
@@ -40,14 +41,14 @@ def _open_source(source: Path) -> sqlite3.Connection:
4041
return sqlite_connect(f"{source.resolve().as_uri()}?mode=ro", uri=True)
4142

4243

43-
def _seal(target: sqlite3.Connection, path: Path) -> None:
44+
def _seal(target: sqlite3.Connection) -> None:
4445
"""Make the copy one file and refuse it if SQLite does not call it intact."""
4546
mode = target.execute("PRAGMA journal_mode=DELETE").fetchone()[0]
4647
if mode != "delete":
47-
raise SnapshotError(f"{path} kept journal_mode={mode}")
48+
raise SnapshotError(f"the copy kept journal_mode={mode}")
4849
verdict = [row[0] for row in target.execute("PRAGMA integrity_check")]
4950
if verdict != ["ok"]:
50-
raise SnapshotError(f"{path} failed integrity_check: {verdict[:3]}")
51+
raise SnapshotError(f"the copy failed integrity_check: {'; '.join(verdict)}")
5152

5253

5354
def snapshot_sqlite(source: Path, target: Path) -> None:
@@ -62,5 +63,5 @@ def snapshot_sqlite(source: Path, target: Path) -> None:
6263
with closing(_open_source(source)) as src:
6364
create_private_file(target)
6465
with closing(sqlite_connect(str(target))) as dst:
65-
src.backup(dst, pages=-1)
66-
_seal(dst, target)
66+
src.backup(dst) # pages=-1 by default: one step
67+
_seal(dst)

‎tests_py/handlers/test_backup_snapshot.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
from __future__ import annotations
44

55
import hashlib
6+
from datetime import datetime, timezone
67
import os
8+
import re
79
import sqlite3
810
import stat
911
import sys
@@ -80,7 +82,11 @@ def test_a_postgresql_root_stages_its_files_only(tmp_path):
8082

8183

8284
def test_a_managed_root_is_refused_until_its_cluster_can_be_copied(tmp_path):
83-
with pytest.raises(ManifestError, match="managed PostgreSQL"):
85+
expected = (
86+
"a managed PostgreSQL backup needs a stopped copy or a logical dump, "
87+
"not implemented yet (issue #731)"
88+
)
89+
with pytest.raises(ManifestError, match=f"^{re.escape(expected)}$"):
8490
snapshot_backup(tmp_path / "root", tmp_path / "staging", "managed")
8591
assert not (tmp_path / "staging").exists()
8692

@@ -196,3 +202,33 @@ def scan_then_delete(base, relative, kind):
196202
monkeypatch.setattr(backup_snapshot_module, "scan_resource", scan_then_delete)
197203
with pytest.raises(FileNotFoundError):
198204
snapshot_backup(root, staging, "sqlite")
205+
206+
207+
def test_the_manifest_carries_the_given_instant(tmp_path):
208+
root, staging = tmp_path / "root", tmp_path / "staging"
209+
_live_store(root).close()
210+
now = datetime(2026, 11, 10, 11, 0, 0, tzinfo=timezone.utc)
211+
manifest = snapshot_backup(root, staging, "sqlite", now=now)
212+
assert manifest["created_at"] == "2026-11-10T11:00:00+00:00"
213+
214+
215+
def test_a_store_path_that_is_a_directory_is_refused(tmp_path):
216+
root = tmp_path / "root"
217+
(root / "methodology" / "memory.db").mkdir(parents=True)
218+
with pytest.raises(BackupScanError, match="expected to be a file"):
219+
snapshot_backup(root, tmp_path / "staging", "sqlite")
220+
221+
222+
def test_a_staging_path_that_is_a_file_is_refused(tmp_path):
223+
root, staging = tmp_path / "root", tmp_path / "staging"
224+
_live_store(root).close()
225+
staging.write_bytes(b"x")
226+
with pytest.raises(StagingError, match=r"staging is not a directory$"):
227+
snapshot_backup(root, staging, "sqlite")
228+
229+
230+
def test_a_staging_root_with_missing_parents_is_created(tmp_path):
231+
root, staging = tmp_path / "root", tmp_path / "a" / "b" / "staging"
232+
_live_store(root).close()
233+
snapshot_backup(root, staging, "sqlite")
234+
assert (staging / "methodology" / "memory.db").is_file()

‎tests_py/infrastructure/test_sqlite_snapshot.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import pytest
1313

14+
from mcp_server.infrastructure import sqlite_snapshot
1415
from mcp_server.infrastructure.sqlite_snapshot import SnapshotError, snapshot_sqlite
1516

1617

@@ -118,3 +119,63 @@ def test_the_copy_is_owner_only_whatever_the_umask(tmp_path):
118119
finally:
119120
os.umask(previous)
120121
assert stat.S_IMODE(target.stat().st_mode) == 0o600
122+
123+
124+
def test_a_target_whose_directory_is_missing_is_refused(tmp_path):
125+
source, target = tmp_path / "memory.db", tmp_path / "absent" / "copy.db"
126+
_wal_store(source).close()
127+
with pytest.raises(SnapshotError, match=r"absent is not a directory$"):
128+
snapshot_sqlite(source, target)
129+
130+
131+
class _Rows:
132+
def __init__(self, rows):
133+
self._rows = rows
134+
135+
def fetchone(self):
136+
return self._rows[0]
137+
138+
def __iter__(self):
139+
return iter(self._rows)
140+
141+
142+
class _Copy:
143+
"""A connection whose PRAGMA answers are given: what a damaged copy reports."""
144+
145+
def __init__(self, journal, integrity):
146+
self.answers = {
147+
"PRAGMA journal_mode=DELETE": journal,
148+
"PRAGMA integrity_check": integrity,
149+
}
150+
151+
def execute(self, sql):
152+
return _Rows(self.answers[sql])
153+
154+
155+
def test_a_copy_that_keeps_its_wal_is_refused():
156+
with pytest.raises(SnapshotError, match=r"^the copy kept journal_mode=wal$"):
157+
sqlite_snapshot._seal(_Copy([("wal",)], [("ok",)]))
158+
159+
160+
def test_a_copy_that_fails_integrity_check_is_refused_with_every_finding():
161+
findings = [(f"row {n} missing from index",) for n in range(5)]
162+
message = "; ".join(f[0] for f in findings)
163+
with pytest.raises(SnapshotError) as refused:
164+
sqlite_snapshot._seal(_Copy([("delete",)], findings))
165+
assert str(refused.value) == f"the copy failed integrity_check: {message}"
166+
167+
168+
def test_the_source_is_opened_read_only_by_an_explicit_uri(tmp_path, monkeypatch):
169+
"""``mode=ro`` is a URI parameter: without ``uri=True`` a Python whose SQLite
170+
is built without SQLITE_USE_URI would open (or create) a file of that name."""
171+
source = tmp_path / "memory.db"
172+
_wal_store(source).close()
173+
opened = []
174+
175+
def spy(target, **kwargs):
176+
opened.append((target, kwargs))
177+
return sqlite3.connect(":memory:")
178+
179+
monkeypatch.setattr(sqlite_snapshot, "sqlite_connect", spy)
180+
sqlite_snapshot._open_source(source).close()
181+
assert opened == [(f"{source.resolve().as_uri()}?mode=ro", {"uri": True})]

0 commit comments

Comments
 (0)