#!/usr/bin/env python3 """Materialize verified shared packages, fetching cache misses; rebuild sources only explicitly.""" import argparse from contextlib import contextmanager import fcntl import shutil import hashlib import io import json from pathlib import Path import sqlite3 import subprocess import os import tempfile import urllib.request import zipfile import sys import csv import math from datetime import date from zones import ZoneIndex from words import terms as word_terms import unicodedata import packages HERE = Path(__file__).resolve().parent ROOT = HERE.parent.parent PINS = json.loads((HERE / "pins.json").read_text()) KINDS = ["places", "countries", "holidays", "airports", "english_words"] def verify(path, expected): actual = hashlib.sha256(path.read_bytes()).hexdigest() if actual != expected: raise ValueError(f"SHA-256 mismatch for {path.name}: expected {expected}, got {actual}") return actual def connect(dest, kind, digest): db = sqlite3.connect(dest) db.execute("PRAGMA page_size = 4096") db.executescript((ROOT / "scripts/datasets/schemas" / f"{kind}.sql").read_text()) db.execute("INSERT INTO dataset VALUES (?, ?, ?)", (kind, PINS["version"], digest)) return db def validate(db, kind, expected_rows=None): pin = PINS[kind] count = db.execute(f"SELECT count(*) FROM {kind}").fetchone()[0] expected = pin.get("row_count") if expected_rows is None else expected_rows if expected is not None and abs(count - expected) > pin.get("row_tolerance", 0): raise ValueError(f"{kind}: row count {count} outside pinned coverage {expected}") if kind == "english_words": for (term,) in db.execute("SELECT term FROM english_words"): if not (term and term == unicodedata.normalize("NFC", term.lower()) and all(c.isalpha() or c in "'-" for c in term)): raise ValueError(f"english_words: invalid row shape for {term!r}") # The production package guard checks the actual corpus, not a mock list. if expected_rows is None: for term in ["the", "roan", "calendar", "colour", "don't", "i", "monday", "will", "rose"]: if not db.execute("SELECT 1 FROM english_words WHERE term=?", [term]).fetchone(): raise ValueError(f"English corpus lost common word {term}") for term in ["aaron", "xavier", "priyanka", "aishwarya"]: if db.execute("SELECT 1 FROM english_words WHERE term=?", [term]).fetchone(): raise ValueError(f"English corpus includes non-word first name {term}") if kind == "countries": for code, name, dialling, currency, flag in db.execute("SELECT * FROM countries"): if not (len(code) == 2 and code.isascii() and code.isalpha() and code.isupper() and name.strip() and (not currency or (len(currency) == 3 and currency.isascii() and currency.isalpha() and currency.isupper())) and all(c in "0123456789,+- " for c in dialling.replace(" and ", ",")) and flag == "".join(chr(0x1F1E6 + ord(c) - ord("A")) for c in code)): raise ValueError(f"countries: invalid row shape for {code}") if kind == "holidays": for key, day, name, country, region in db.execute("SELECT * FROM holidays"): try: valid_date = date.fromisoformat(day).isoformat() == day except ValueError: valid_date = False if not (key and valid_date and name.strip() and len(country) == 2 and country.isascii() and country.isalpha() and country.isupper() and all(c.isprintable() for c in region) and region == region.strip()): raise ValueError(f"holidays: invalid row shape for {key}") coverage = db.execute("SELECT first_date,last_date FROM holiday_coverage WHERE country=? AND region=?", (country, region)).fetchone() if not coverage or not coverage[0] <= day <= coverage[1]: raise ValueError(f"holidays: row outside date coverage for {key}") if kind == "airports": for key, iata, icao, name, city, country, lat, lon, zone in db.execute("SELECT * FROM airports"): code = lambda s, size: len(s) == size and s.isascii() and s.isalpha() and s.isupper() number = key.removeprefix("ourairports:") if not (key.startswith("ourairports:") and number.isascii() and number.isdigit() and int(number) > 0 and code(iata, 3) and (not icao or code(icao, 4)) and name.strip() and code(country, 2) and math.isfinite(lat) and math.isfinite(lon) and -90 <= lat <= 90 and -180 <= lon <= 180 and zone and "/" in zone and all(c.isascii() and (c.isalnum() or c in "/_+-") for c in zone)): raise ValueError(f"airports: invalid row shape for {key}") def populate_airports(db, source, zones): with source.open(encoding="utf-8", newline="") as stream: for row in csv.DictReader(stream): if not row["iata_code"] or row["type"] == "closed": continue lat, lon = float(row["latitude_deg"]), float(row["longitude_deg"]) zone = zones.zone(lon, lat) db.execute("INSERT INTO airports VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ("ourairports:" + row["id"], row["iata_code"], row["icao_code"], row["name"], row["municipality"], row["iso_country"], lat, lon, zone)) def airports(source, dest, digest): zones = ZoneIndex(source.parent / PINS["airports"]["dependencies"][0]["filename"]) db = connect(dest, "airports", digest) populate_airports(db, source, zones) finish(db, "airports") def populate_holidays(db, provider, years): for country, regions in sorted(provider.list_supported_countries(include_aliases=False).items()): national = provider.country_holidays(country, years=years, language="en_US", expand=False) for region in [""] + sorted(regions): days = national if not region else provider.country_holidays(country, subdiv=region, years=years, language="en_US", expand=False) db.execute("INSERT INTO holiday_coverage VALUES (?, ?, ?, ?)", (country, region, f"{min(years)}-01-01", f"{max(years)}-12-31")) for day, combined in sorted(days.items()): names = combined.split("; ") national_names = national.get(day, "").split("; ") for name in names: if region and name in national_names: continue key = f"{country}:{region}:{day.isoformat()}:{hashlib.sha256(name.encode()).hexdigest()[:16]}" db.execute("INSERT INTO holidays VALUES (?, ?, ?, ?, ?)", (key, day.isoformat(), name, country, region)) def holidays(source, dest, digest): subprocess.run([sys.executable, "-I", str(HERE / "holiday_rows.py"), str(source.resolve()), str(dest.resolve()), digest], check=True) def finish(db, kind): if kind != "english_words": db.execute(f"INSERT INTO {kind}_search({kind}_search) VALUES ('rebuild')") db.execute(f"INSERT INTO {kind}_search({kind}_search) VALUES ('optimize')") db.commit() if db.execute("PRAGMA integrity_check").fetchone()[0] != "ok": raise ValueError("dataset integrity check failed") db.execute("VACUUM") db.close() def english_words(source, dest, digest): db = connect(dest, "english_words", digest) db.executemany("INSERT INTO english_words VALUES (?)", [(term,) for term in word_terms(source)]) finish(db, "english_words") def places(source, dest, digest): db = connect(dest, "places", digest) with zipfile.ZipFile(source) as archive: with archive.open("cities500.txt") as raw: for line in io.TextIOWrapper(raw, encoding="utf-8"): row = line.rstrip("\n").split("\t") if len(row) != 19: raise ValueError("unexpected GeoNames place row") if row[6] != "P": continue db.execute("INSERT INTO places VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (int(row[0]), row[1], row[2] + "," + row[3], row[8], row[10], float(row[4]), float(row[5]), int(row[14]), row[17])) finish(db, "places") def countries(source, dest, digest): db = connect(dest, "countries", digest) for line in source.read_text(encoding="utf-8").splitlines(): if not line or line.startswith("#"): continue row = line.split("\t") code = row[0] # Historic GeoNames aliases such as AN are not current ISO alpha-2 entries. if len(code) != 2 or not code.isascii() or not code.isupper() or code in PINS["countries"].get("excluded_codes", []): continue flag = "".join(chr(0x1F1E6 + ord(letter) - ord("A")) for letter in code) db.execute("INSERT INTO countries VALUES (?, ?, ?, ?, ?)", (code, row[4], row[12], row[10], flag)) finish(db, "countries") def download(url, path, expected): # Only publish completed, hash-verified downloads. with tempfile.TemporaryDirectory(dir=path.parent) as work: staged = Path(work) / "download" if url.startswith("/repos/"): # The snapshot is a Cotton release asset. The forge chooses its # configured host and credential; no private household URL or secret # belongs in the dataset pins or the build script. subprocess.run(["pnpm", "--silent", "forge", "api", "GET", url, "--output", str(staged)], cwd=ROOT, env={**os.environ, "FORGE_REPO": "decemberfm/cottondb"}, check=True) else: with urllib.request.urlopen(url, timeout=120) as response, staged.open("wb") as output: while chunk := response.read(1024 * 1024): output.write(chunk) verify(staged, expected) staged.replace(path) @contextmanager def writable_cache(cache): # The standard layout protects datasets/, including packages/. An explicit # standalone cache protects only itself, never an unrelated parent folder. folder = cache.parent if cache.name == 'packages' and cache.parent.name == 'datasets' else cache folder.parent.mkdir(parents=True, exist_ok=True) # Keep the lease outside the immutable folder. All preparations share it, # so one writer cannot restore uchg while another is downloading. with (folder.parent / ('.' + folder.name + '.prepare.lock')).open('a') as lock: fcntl.flock(lock, fcntl.LOCK_EX) folder.mkdir(parents=True, exist_ok=True) chflags = shutil.which('chflags') if chflags: subprocess.run([chflags, '-R', 'nouchg', str(folder)], check=True) try: yield finally: if chflags: subprocess.run([chflags, '-R', 'uchg', str(folder)], check=True) def prepare_cache(cache, kinds, local): with writable_cache(cache): packages.prepare(ROOT, cache, kinds, PINS, local) def main(): global PINS parser = argparse.ArgumentParser() parser.add_argument("--only", choices=KINDS) mode = parser.add_mutually_exclusive_group() mode.add_argument("--rebuild", action="store_true", help="separate source-production job; never used by a cut") mode.add_argument("--prepare-cache", action="store_true", help="fetch/import portable packages before starting a cut") mode.add_argument("--check-cache", action="store_true", help="verify shared packages and fetch misses at step 0; creates no build outputs") parser.add_argument("--verify", action="store_true", help="verify pinned package bytes (all builds verify before use)") parser.add_argument("--cache", help="shared package cache outside this worktree; defaults to COTTON_DATASET_CACHE or ~/.cache/cottondb/datasets/packages") parser.add_argument("--import-dir", type=Path, help="prepare from existing verified packages before fetching") parser.add_argument("--pins", help="pinned cut manifest file, or - for stdin") args = parser.parse_args() if args.pins: PINS = json.loads(sys.stdin.read() if args.pins == "-" else Path(args.pins).read_text()) kinds = [args.only] if args.only else KINDS # What `pnpm datasets:publish` reads; no app bundles these files. output = ROOT / ".cache/datasets/built" cache = packages.cache_root(args.cache) if cache == ROOT.resolve() or ROOT.resolve() in cache.parents: raise ValueError("The shared dataset cache must be outside the cut worktree") if args.prepare_cache: prepare_cache(cache, kinds, args.import_dir or output) return if not args.rebuild: missing = packages.preflight(cache, kinds, PINS) if missing: print(f"step 0 datasets: fetching missing packages: {', '.join(missing)}", flush=True) prepare_cache(cache, missing, args.import_dir or output) packages.preflight(cache, kinds, PINS) if args.check_cache: print(f"step 0 datasets: verified shared cache {cache}") return for kind in kinds: digest = PINS[kind]["package_sha256"] packages.publish(packages.asset_path(cache, kind, PINS[kind]), output / f"{kind}.sqlite", digest) print(f"{kind}: copied verified package {digest}") return # Explicit source production is separate from every app/cut invocation. sources = ROOT / ".cache/datasets" sources.mkdir(parents=True, exist_ok=True) output.mkdir(parents=True, exist_ok=True) for kind in kinds: pin = PINS[kind] source = sources / pin["filename"] if not source.exists(): download(pin.get("snapshot_path", pin["url"]), source, pin["sha256"]) verify(source, pin["sha256"]) for dependency in pin.get("dependencies", []): path = sources / dependency["filename"] if not path.exists(): download(dependency["url"], path, dependency["sha256"]) verify(path, dependency["sha256"]) dest = output / f"{kind}.sqlite" with tempfile.TemporaryDirectory(dir=output) as work: staged = Path(work) / dest.name globals()[kind](source, staged, pin["sha256"]) with sqlite3.connect(staged) as db: validate(db, kind) actual = hashlib.sha256(staged.read_bytes()).hexdigest() expected = pin.get("package_sha256") if expected: verify(staged, expected) elif args.verify: raise ValueError(f"{kind}: missing pinned package SHA-256") staged.chmod(0o444) staged.replace(dest) print(f"{kind}: built {actual}") if __name__ == "__main__": main()