fix: keep the offline database build offline

preserve_large_file_entries mixed the keep-or-drop rule with a download,
a write into bios/ and a SystemExit. The rule is now surviving_entries,
the restore a separate step that receives offline, and read_database
raises DatabaseUnreadable that the build turns into exit 1. generate_db
gains --offline, which pipeline --offline passes to step 1.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 16:43:57 +01:00
1 parent 8ec1c3aa2f
commit a30984912c
8 files changed
+208 -147

No files matched your search

+39 -30
View File
@@ -4,64 +4,73 @@ from __future__ import annotations
import json
import os
from pathlib import Path
def load_gitignored_large_files() -> set[str]:
"""The bios/ paths .gitignore registers as release assets."""
class DatabaseUnreadable(Exception):
"""The previous database exists and is not JSON: its release-asset entries cannot be kept."""
def load_gitignored_large_files(gitignore: str | Path) -> set[str]:
"""The bios/ paths a .gitignore registers as release assets."""
from model.largefiles import load_registered_paths
return set(load_registered_paths(".gitignore"))
return set(load_registered_paths(gitignore))
def preserve_large_file_entries(files: dict, db_path: str) -> int:
"""Keep the entries of release assets the checkout does not hold.
Files kept out of git live as assets of the large-files release, and
.gitignore registers their paths. An entry survives a scan that missed
its file only under that registered path: a bare name is shared by
other files (pak0.pk3, history.db), and a path rewritten into the
download cache is no longer one .gitignore knows, so the manifest
would send the installer to the repository for it. A fetched asset is
written back to its registered path.
"""
from model.largefiles import fetch_large_file, restore_verified
registered = load_gitignored_large_files()
if not registered:
return 0
def read_database(db_path: str) -> dict | None:
"""The previous database, None when there is none."""
try:
with open(db_path) as f:
existing_db = json.load(f)
return json.load(f)
except FileNotFoundError:
return 0
return None
except json.JSONDecodeError as e:
# An unreadable database is not an absent one: rewriting it from a
# checkout without the release assets would drop every entry they
# hold, and the manifests regenerated from it would omit them.
raise SystemExit(
raise DatabaseUnreadable(
f"{db_path} is not valid JSON ({e}). Restore it from git "
"or regenerate it on a checkout holding the release assets before "
"scanning again"
) from e
def surviving_entries(existing_db: dict, files: dict, registered: set[str]) -> dict:
"""The entries of the previous database a scan that missed their file keeps.
Files kept out of git live as assets of the large-files release, and
.gitignore registers their paths. An entry survives only under that
registered path: a bare name is shared by other files (pak0.pk3,
history.db), and a path rewritten into the download cache is no longer
one .gitignore knows, so the manifest would send the installer to the
repository for it.
"""
# A path the scan just claimed holds known bytes. An older entry naming
# the same path describes a revision that is no longer there, and keeping
# it would publish a hash that contradicts the file it points at.
scanned_paths = {entry.get("path", "") for entry in files.values()}
return {
sha1: entry
for sha1, entry in existing_db.get("files", {}).items()
if sha1 not in files
and entry.get("path", "") in registered
and entry.get("path", "") not in scanned_paths
}
count = 0
for sha1, entry in existing_db.get("files", {}).items():
def restore_release_assets(entries: dict, registered: set[str], *, offline: bool) -> None:
"""Write each kept entry's asset back to its registered path, fetched only when online."""
from model.largefiles import fetch_large_file, restore_verified
for sha1, entry in entries.items():
path = entry.get("path", "")
if sha1 in files or path not in registered or path in scanned_paths:
continue
cached = fetch_large_file(
path,
expected_sha1=entry.get("sha1", ""),
expected_md5=entry.get("md5", ""),
offline=offline,
registered=registered,
)
if cached and not os.path.exists(path):
restore_verified(cached, path, sha1)
files[sha1] = entry
count += 1
return count
+31 -3
View File
@@ -11,14 +11,38 @@ from collection.declared import declarations
from collection.hashcache import CACHE_FILE, load_cache, save_cache
from collection.indexes import database_indexes
from collection.record import database_record, record_retired, write_database
from collection.releaseassets import preserve_large_file_entries
from collection.releaseassets import (
DatabaseUnreadable,
load_gitignored_large_files,
read_database,
restore_release_assets,
surviving_entries,
)
from collection.scan import scan_bios_dir
from model import retired
from model.dumpcatalog import annotate_provenance, load_provenance_snapshots
# Database entries name paths relative to the working directory, and so does
# the registry of release assets beside them.
GITIGNORE = Path(".gitignore")
def preserve_release_assets(files: dict, db_path: str, *, offline: bool) -> int:
"""Keep the entries of release assets the scan missed, their files restored, and count them."""
registered = load_gitignored_large_files(GITIGNORE)
if not registered:
return 0
existing_db = read_database(db_path)
if existing_db is None:
return 0
kept = surviving_entries(existing_db, files, registered)
restore_release_assets(kept, registered, offline=offline)
files.update(kept)
return len(kept)
def generate(args: argparse.Namespace) -> int:
"""Scan bios/ and write the database, 1 when a declared source cannot be read."""
"""Scan bios/ and write the database, 1 when a declared source or the old database cannot be read."""
bios_dir = Path(args.bios_dir)
# A forced run rehashes every file but keeps the previous digests to
@@ -32,7 +56,11 @@ def generate(args: argparse.Namespace) -> int:
print("Warning: No BIOS files found", file=sys.stderr)
# Preserve entries for large files stored as release assets (.gitignore)
preserved = preserve_large_file_entries(files, args.output)
try:
preserved = preserve_release_assets(files, args.output, offline=args.offline)
except DatabaseUnreadable as exc:
print(exc, file=sys.stderr)
return 1
if preserved:
print(f" Preserved {preserved} large file entries from existing database")
+5
View File
@@ -40,6 +40,11 @@ def main() -> int:
default=DEFAULT_PROVENANCE_DIR,
help="Directory with dump-catalog snapshots",
)
parser.add_argument(
"--offline",
action="store_true",
help="Restore release assets from the local cache only, never download",
)
args = parser.parse_args()
require_directory(args.bios_dir)
with repository_output_lock(args.output):
+15 -14
View File
@@ -12,7 +12,7 @@ from orchestrate.labels import STEP_LABELS, skip_notice
from orchestrate.results import SKIPPED
def database_steps(results: dict) -> bool:
def database_steps(args: argparse.Namespace, results: dict) -> bool:
"""Steps 0 to 1c: schemas, database, dump catalogs, romset recipes."""
all_ok = True
# Step 0: the schema check PR validation runs. Without it a profile with
@@ -35,19 +35,20 @@ def database_steps(results: dict) -> bool:
results["validate_schemas"] = ok
all_ok = all_ok and ok
# Step 1: Generate database
ok, _ = runner.run(
[
sys.executable,
"scripts/generate_db.py",
"--force",
"--bios-dir",
"bios",
"--output",
"database.json",
],
STEP_LABELS["generate_db"],
)
# Step 1: Generate database. Offline, a release asset missing from
# .cache/large/ is not downloaded to restore it.
db_cmd = [
sys.executable,
"scripts/generate_db.py",
"--force",
"--bios-dir",
"bios",
"--output",
"database.json",
]
if args.offline:
db_cmd.append("--offline")
ok, _ = runner.run(db_cmd, STEP_LABELS["generate_db"])
results["generate_db"] = ok
if not ok:
print("\nDatabase generation failed, aborting.")
+1 -1
View File
@@ -147,7 +147,7 @@ def main() -> None:
total_start = time.monotonic()
results = StepResults(total_start)
all_ok = database_steps(results)
all_ok = database_steps(args, results)
all_ok = refresh_steps(args, results) and all_ok
all_ok = truth_steps(args, results) and all_ok
ok, verify_output, destinations_file = verify_steps(args, results, held)