* refactor(database): stage restores before publishing restore_from_file is now stage_restore + publish_staged (database/ restore_stage.py). The stage lives in a .pm-restore-* folder in the library's own folder, is migrated, has damaged workflow documents repaired from an inline copy or cleared, is verified with every document read and is bound by its SHA-256. Publishing keeps a unique, standalone, 0600 safety backup (microsecond names), copies the pages through the backup API as before and then truncates the WAL, which stayed database-sized after a restore. The safety backup writer moves to database/safety_backup.py so the database layer and maintenance share it. * fix(database): read the verify streams one row at a time The provenance and review-evidence checks iterated their cursors; on a managed connection iteration prefetches 128 rows, so up to 128 large values were held at once while the docstrings promised one. Both now use fetchone. * feat(backup): review a restore, run it as an Activity job, verify backups - POST /restore/preview stages an upload in the library's folder and answers what it holds beside the live library, writing nothing live; DELETE discards it; at most two stages are held (429 too-large). - POST /restore/apply rechecks the live fingerprint (409 plan-changed) and starts "Database restore": exclusive, not cancellable, indeterminate. It waits for request leases, publishes the exact staged bytes, swaps the database, prunes safety backups and logs counts, repairs and the backup. - The legacy /restore runs the same stage and publish as an exclusive hold with its old response, so a restore and the health check, Move library and every other job refuse each other. - JobRegistry.lease: Needs review decisions and maintenance and restore previews are refused while an exclusive job runs, and a restore waits for them before it switches the file. - GET /backup holds a guarded slot, verifies a standalone snapshot before streaming it and removes the closed temp file; GET /backup/status lists the safety backups on disk and this session's verified download. * docs(testing): backup and restore contract * test(system): a restore refuses a running health check The health route test relied on a legacy restore interleaving with a running check; the restore is now exclusive and refuses it, naming the check. The diagnostics backup tests follow the backup handler into py/api/backup_restore.py. * fix(backup): drop stale restore previews off the event loop A restore drops the previews reviewed against the old library; their stage files are now removed in the executor, with the old database's connections. * test(backup): wait for the backup hold to end before reading its state CI (py3.11/3.12 on Linux, every macOS) read the registry right after the client had the last byte, before the handler left its hold and removed its temp file: the job was still running. The tests now wait on that state. * test(images): the scan dialog's Back up now leaves a finished backup hold A backup download now holds a guarded registry slot while it streams (#249 S8), so the jobs list holds that finished hold after the dialog's Back up now; the spec still proves Cancel starts no scan. * fix(backup): final review round for the restore and backup routes - I1: once the stage's copy replaced the library the restore succeeded: pruning, reopening self.db, dropping old previews and closing the old object only log, so the job finishes and the legacy /restore answers 200 instead of "the library was not changed". The generation is always bumped. - M1: a backup download holds its guarded slot only while the snapshot is written; the stream runs outside it, so a stalled download blocks nothing. - M2: a restore preview leases only its read of the live library, not the upload or the staging; a restore whose drain still times out keeps the reviewed stage under its token. - M3: the reviewed-preview store changes only on the event loop; stage folders are removed in the executor. - M4: a document whose body inflates completely while only its recorded hash or only its length disagrees is re-keyed (or merged into the document holding that text) instead of dropped. - M5: a backup download is refused only when the snapshot is not SQLite or fails integrity_check; a semantic check failure still downloads, logged, sent as X-PromptManager-Verify and recorded as not verified. - M6: a refused, failed or cancelled preview removes its stage, also when the cancel lands while a worker still stages; a timer removes expired stages without another request. - M7, N1: repair reads rows one at a time and counts distinct images. - N3: the live fingerprint never commits a transaction it did not open. * test(backup): close the old library the close-failure test leaves open CI (py3.12 Linux and the coverage gate) found the old object's executor-thread connections still open at teardown: the test patches its close_all to fail, and once the object is collected close_all_instances no longer reaches it. The test now closes it itself. * fix(backup): re-review round for restore repair, apply and backup cleanup - R1: when re-keying merges an intact body into a holder whose own body was damaged, the rewritten holder leaves the damaged list, so the clear pass no longer deletes it and unlinks the images just moved to it. - R2: a losing duplicate apply removes a stage only when the store still held it, never one another apply's job has taken. - R3: a restore that times out waiting for requests keeps its review only while it is unexpired and its slot is free; otherwise the stage goes and the job says to try again. - R4: a backup download cancelled while its snapshot is written removes the snapshot once the worker finishes.
186 lines
6.2 KiB
Python
186 lines
6.2 KiB
Python
"""Safety backups beside the live database: one writer for every caller.
|
|
|
|
A safety backup is ``<db>.<label>_<YYYYmmdd_HHMMSS_ffffff>[_n]`` in the
|
|
library's own folder. It is written by SQLite's backup API into a temp file
|
|
beside the database (``SAFETY_TEMP_PREFIX``, swept at startup after a crash),
|
|
made one self-contained file (rollback journal), optionally verified, fsynced,
|
|
made private (``0o600`` on POSIX) and only then given its unique name, so a
|
|
backup name never carries a half-written file. The names are unique within
|
|
one second (microseconds, then a counter): on Windows two backups in the same
|
|
second must not overwrite each other.
|
|
|
|
Maintenance applies take a verified backup (``py/api/maintenance.py``); a
|
|
restore takes an unverified one, because the database it replaces may be the
|
|
damaged one the user is recovering from (``database/restore_stage.py``).
|
|
"""
|
|
|
|
import datetime
|
|
import os
|
|
import sqlite3
|
|
import tempfile
|
|
from contextlib import closing
|
|
|
|
SAFETY_TEMP_PREFIX = ".pm-safety-"
|
|
_NAME_ATTEMPTS = 1000
|
|
|
|
|
|
class SafetyBackupFailed(Exception):
|
|
"""The safety backup could not be written, verified or put in place.
|
|
|
|
``reason`` is the verify reason when the copy did not verify.
|
|
"""
|
|
|
|
def __init__(self, message, reason=None):
|
|
super().__init__(message)
|
|
self.reason = reason
|
|
|
|
|
|
def _now():
|
|
return datetime.datetime.now()
|
|
|
|
|
|
def remove_quietly(*paths):
|
|
"""Remove each existing path, ignoring errors (cleanup after a failure)."""
|
|
for path in paths:
|
|
try:
|
|
if path and os.path.exists(path):
|
|
os.remove(path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def backup_names(db_path, label="backup"):
|
|
"""Candidate names, unique within one second (microseconds, then ``_n``)."""
|
|
base = f"{db_path}.{label}_{_now().strftime('%Y%m%d_%H%M%S_%f')}"
|
|
for attempt in range(_NAME_ATTEMPTS):
|
|
yield base if attempt == 0 else f"{base}_{attempt}"
|
|
|
|
|
|
def reserve_backup_name(db_path, label="backup"):
|
|
"""Create and return an unused ``<db>.<label>_<stamp>[_n]`` (O_EXCL)."""
|
|
for candidate in backup_names(db_path, label):
|
|
try:
|
|
fd = os.open(candidate, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
except FileExistsError:
|
|
continue
|
|
os.close(fd)
|
|
return candidate
|
|
raise SafetyBackupFailed("No free backup name")
|
|
|
|
|
|
def place_backup(temp, db_path, label="backup"):
|
|
"""Give the finished ``temp`` its unique backup name; return that path.
|
|
|
|
``os.link`` is atomic and refuses an existing name, so no empty or half
|
|
file ever carries a backup name, even across a crash. A filesystem
|
|
without hard links falls back to reserving the name (``O_EXCL``) and
|
|
``os.replace``. The temp file is removed by the caller.
|
|
"""
|
|
for candidate in backup_names(db_path, label):
|
|
try:
|
|
os.link(temp, candidate)
|
|
except FileExistsError:
|
|
continue
|
|
except (OSError, NotImplementedError):
|
|
break # no hard links here
|
|
else:
|
|
return candidate
|
|
else:
|
|
raise SafetyBackupFailed("No free backup name")
|
|
final = reserve_backup_name(db_path, label)
|
|
try:
|
|
os.replace(temp, final)
|
|
except OSError:
|
|
remove_quietly(final)
|
|
raise
|
|
return final
|
|
|
|
|
|
def sweep_safety_temps(db_path):
|
|
"""Remove the temp copies an interrupted safety backup left (blocking).
|
|
|
|
Called once at startup, before any job can take a backup. Returns the
|
|
names removed.
|
|
"""
|
|
folder = os.path.dirname(os.path.abspath(db_path))
|
|
removed = []
|
|
try:
|
|
names = os.listdir(folder)
|
|
except OSError:
|
|
return removed
|
|
for name in names:
|
|
if not (name.startswith(SAFETY_TEMP_PREFIX) and ".tmp" in name):
|
|
continue
|
|
try:
|
|
os.remove(os.path.join(folder, name))
|
|
removed.append(name)
|
|
except OSError:
|
|
continue
|
|
return removed
|
|
|
|
|
|
def make_standalone(path):
|
|
"""Make the copy one self-contained file (rollback journal, not WAL).
|
|
|
|
The backup API copies the live database's WAL flag; a WAL file opened
|
|
read-only later (a verify, a restore preview) would leave ``-wal`` and
|
|
``-shm`` sidecars beside it.
|
|
"""
|
|
try:
|
|
with closing(sqlite3.connect(path)) as conn:
|
|
conn.execute("PRAGMA journal_mode=DELETE").fetchone()
|
|
except sqlite3.Error as exc:
|
|
raise SafetyBackupFailed("The backup could not be finished") from exc
|
|
|
|
|
|
def fsync_file(path):
|
|
with open(path, "rb+") as handle:
|
|
os.fsync(handle.fileno())
|
|
|
|
|
|
def safety_temp(db_path):
|
|
"""A new, closed temp file beside the database (``SAFETY_TEMP_PREFIX``)."""
|
|
fd, temp = tempfile.mkstemp(
|
|
dir=os.path.dirname(os.path.abspath(db_path)),
|
|
prefix=SAFETY_TEMP_PREFIX,
|
|
suffix=".tmp",
|
|
)
|
|
os.close(fd)
|
|
return temp
|
|
|
|
|
|
def take_safety_backup(model, label="backup", *, verify=True):
|
|
"""Write (and by default verify) a safety backup; return its path (blocking).
|
|
|
|
The copy is made in a temp file beside the database and only renamed
|
|
onto its final, unique name ``<db>.<label>_<stamp>`` once it is complete
|
|
(and verified), so a backup file on disk is always a whole one. ``label``
|
|
"backup" joins the pruned pool; another label (the workflow storage
|
|
migration's ``pre-workflow-storage``) is kept until the user removes it.
|
|
Raises SafetyBackupFailed, leaving no file.
|
|
"""
|
|
db_path = os.path.abspath(model.db_path)
|
|
temp = safety_temp(db_path)
|
|
final = None
|
|
try:
|
|
if not model.backup_database(temp):
|
|
raise SafetyBackupFailed("The backup could not be written")
|
|
make_standalone(temp)
|
|
if verify:
|
|
ok, reason = model.verify_database_file(temp)
|
|
if not ok:
|
|
raise SafetyBackupFailed("The backup did not verify", reason)
|
|
fsync_file(temp)
|
|
if os.name != "nt":
|
|
os.chmod(temp, 0o600)
|
|
final = place_backup(temp, db_path, label)
|
|
return final
|
|
except OSError as exc:
|
|
remove_quietly(final)
|
|
raise SafetyBackupFailed("The backup could not be put in place") from exc
|
|
except SafetyBackupFailed:
|
|
remove_quietly(final)
|
|
raise
|
|
finally:
|
|
remove_quietly(temp, temp + "-journal", temp + "-wal", temp + "-shm")
|