"""Synthetic source guards for the shipping dataset builder.""" import hashlib import importlib.util import json from pathlib import Path import sqlite3 import tempfile import unittest import zipfile import csv from unittest.mock import Mock, patch import sys from datetime import date spec = importlib.util.spec_from_file_location("build", Path(__file__).with_name("build.py")) build = importlib.util.module_from_spec(spec) spec.loader.exec_module(build) class DatasetGuards(unittest.TestCase): def test_warm_shared_cache_builds_two_clean_checkouts_with_no_host_or_source(self): # RULE: A warm cut consumes SHA-verified packages without the host or source snapshots, so existing cache bytes remain sufficient for a build. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() portable = b"synthetic packaged bytes" digest = hashlib.sha256(portable).hexdigest() pins = {"package_root": "/repos/o/r/releases/1/assets", "holidays": {"package_sha256": digest}} cache = root / "shared" asset = cache / digest / "holidays.sqlite" asset.parent.mkdir(parents=True) asset.write_bytes(portable) for name in ("cut-a", "cut-b"): checkout = root / name with patch.object(build, "ROOT", checkout), patch.object(build, "PINS", pins), \ patch.object(build, "download", side_effect=AssertionError("no host")), \ patch.object(build, "holidays", side_effect=AssertionError("no source job")), \ patch.object(sys, "argv", ["build.py", "--only", "holidays", "--verify", "--cache", str(cache)]): build.main() self.assertEqual((checkout / ".cache/datasets/built/holidays.sqlite").read_bytes(), portable) def test_missing_package_is_fetched_before_build_continues(self): # RULE: A missing shared package is fetched and SHA-verified at step 0, because disposable cache loss must not stop a cut. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() cache = root / "shared" portable = b"synthetic package" digest = hashlib.sha256(portable).hexdigest() pins = {"package_root": "/synthetic", **{kind: {"package_sha256": digest} for kind in ("places", "holidays")}} asset = cache / digest / "places.sqlite" asset.parent.mkdir(parents=True) asset.write_bytes(portable) def fetch(repo, url, destination, expected): self.assertEqual(url, '/synthetic/holidays.sqlite') self.assertEqual(expected, digest) destination.write_bytes(portable) try: with patch.object(build, "ROOT", root / "cut"), patch.object(build, "PINS", pins), \ patch.object(build, "KINDS", ["places", "holidays"]), \ patch.object(build.packages, "acquire", side_effect=fetch) as acquire, \ patch.object(sys, "argv", ["build.py", "--cache", str(cache)]): build.main() acquire.assert_called_once() self.assertEqual((root / 'cut/.cache/datasets/built/holidays.sqlite').read_bytes(), portable) finally: self.unlock(cache) def test_corrupt_package_refuses_before_fetch_or_build(self): # RULE: Existing bytes that disagree with their pinned SHA refuse before any fetch or output, so repairing a cache miss cannot hide corruption. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() cache = root / 'shared' digest = hashlib.sha256(b'good').hexdigest() pins = {kind: {'package_sha256': digest} for kind in ('places', 'holidays')} asset = cache / digest / 'holidays.sqlite' asset.parent.mkdir(parents=True) asset.write_bytes(b'bad') with patch.object(build, 'ROOT', root / 'cut'), patch.object(build, 'PINS', pins), \ patch.object(build, 'KINDS', ['places', 'holidays']), \ patch.object(build.packages, 'acquire', side_effect=AssertionError('no fetch')), \ patch.object(sys, 'argv', ['build.py', '--cache', str(cache)]): with self.assertRaisesRegex(ValueError, 'step 0.*holidays.sqlite.*' + digest): build.main() self.assertFalse((root / 'cut/apps').exists()) @staticmethod def unlock(folder): import shutil, subprocess if shutil.which('chflags') and folder.exists(): subprocess.run(['chflags', '-R', 'nouchg', str(folder)], check=True) def test_prepare_cache_relocks_after_success_and_failure(self): # RULE: Preparation clears and restores immutability even on failure, so a fetch can write without leaving the shared cache open to sweepers. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() cache = root / 'datasets/packages' for failed in (False, True): with self.subTest(failed=failed), patch.object(build, 'ROOT', root / 'cut'), \ patch.object(build.packages, 'prepare', side_effect=RuntimeError('synthetic fetch failure') if failed else None), \ patch('shutil.which', return_value='/synthetic/chflags'), \ patch.object(build.subprocess, 'run') as flag, \ patch.object(sys, 'argv', ['build.py', '--prepare-cache', '--cache', str(cache)]): if failed: with self.assertRaisesRegex(RuntimeError, 'synthetic fetch failure'): build.main() else: build.main() self.assertEqual([call.args[0] for call in flag.call_args_list], [ ['/synthetic/chflags', '-R', 'nouchg', str(cache.parent)], ['/synthetic/chflags', '-R', 'uchg', str(cache.parent)]]) @unittest.skipUnless(__import__('shutil').which('chflags'), 'filesystem immutable flags require chflags') def test_prepare_cache_real_immutable_round_trip(self): # RULE: On filesystems with chflags, --prepare-cache can update a protected dataset folder and restores its immutable bit afterward. import stat, subprocess with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() cache = root / 'datasets/packages' cache.mkdir(parents=True) subprocess.run(['chflags', '-R', 'uchg', str(cache.parent)], check=True) def prepare(*args): self.assertFalse(cache.parent.stat().st_flags & stat.UF_IMMUTABLE) (cache / 'synthetic').write_bytes(b'verified bytes') try: with patch.object(build, 'ROOT', root / 'cut'), \ patch.object(build.packages, 'prepare', side_effect=prepare), \ patch.object(sys, 'argv', ['build.py', '--prepare-cache', '--cache', str(cache)]): build.main() self.assertTrue(cache.parent.stat().st_flags & stat.UF_IMMUTABLE) self.assertTrue((cache / 'synthetic').stat().st_flags & stat.UF_IMMUTABLE) finally: self.unlock(cache.parent) def test_airport_shape_and_timezone_polygon_holes(self): # RULE: Every current IATA airport gets a zone from pinned boundary geometry; holes and closed airports cannot silently invent a zone or a live airport. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() polygons = root / "zones.zip" geometry = {"features": [{"properties": {"tzid": "Asia/Kolkata"}, "geometry": {"type": "Polygon", "coordinates": [[[70,10],[90,10],[90,30],[70,30],[70,10]], [[80,20],[81,20],[81,21],[80,21],[80,20]]]}}]} with zipfile.ZipFile(polygons, "w") as archive: archive.writestr("combined-with-oceans.json", json.dumps(geometry)) index = build.ZoneIndex(polygons) self.assertEqual(index.zone(78.48, 17.38), "Asia/Kolkata") with self.assertRaisesRegex(ValueError, "No timezone"): index.zone(80.5, 20.5) source = root / "airports.csv" source.write_text("id,ident,type,name,latitude_deg,longitude_deg,iso_country,municipality,icao_code,iata_code\n1,VOHS,large_airport,Hyderabad,17.38,78.48,IN,Hyderabad,VOHS,HYD\n2,OLD,closed,Old Airport,17,78,IN,Hyderabad,,OLD\n") db = build.connect(root / "airports.sqlite", "airports", "synthetic") build.populate_airports(db, source, index) build.validate(db, "airports", expected_rows=1) self.assertEqual(db.execute("select timezone from airports where id='ourairports:1'").fetchone()[0], "Asia/Kolkata") db.execute("update airports set iata='hyD'") with self.assertRaisesRegex(ValueError, "shape"): build.validate(db, "airports", expected_rows=1) def test_holidays_keep_regional_exceptions_without_duplicate_national_days(self): # RULE: A regional calendar adds only its exceptions to national holidays, and exposes its pinned date coverage instead of guessing outside it. with tempfile.TemporaryDirectory() as tmp: dest = Path(tmp) / "holidays.sqlite" db = build.connect(dest, "holidays", "synthetic") provider = Mock() provider.list_supported_countries.return_value = {"US": ["CA"]} national = {date(2026, 7, 4): "Independence Day"} provider.country_holidays.side_effect = [national, {**national, date(2026, 3, 31): "Cesar Chavez Day"}] build.populate_holidays(db, provider, [2026]) build.validate(db, "holidays", expected_rows=2) self.assertEqual(db.execute("select region from holidays where date='2026-07-04'").fetchall(), [("",)]) self.assertEqual(db.execute("select first_date,last_date from holiday_coverage where region='CA'").fetchone(), ("2026-01-01", "2026-12-31")) db.execute("update holidays set date='2026-02-30'") with self.assertRaisesRegex(ValueError, "shape"): build.validate(db, "holidays", expected_rows=2) def test_countries_shape_and_pinned_coverage(self): # RULE: Country packages preserve the pinned source's coverage and code alphabets; missing territory facts are never invented. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() source = root / "countries.txt" source.write_text("IN\tIND\t356\tIN\tIndia\tDelhi\t1\t1\tAS\t.in\tINR\tRupee\t91\nAN\tANT\t530\tNT\tNetherlands Antilles\t\t1\t1\tNA\t.an\tANG\tGuilder\t599\n") dest = root / "countries.sqlite" build.countries(source, dest, "synthetic") with sqlite3.connect(dest) as db: build.validate(db, "countries", expected_rows=1) self.assertEqual(db.execute("select id from countries_search where countries_search match 'ind*'").fetchone()[0], "IN") db.execute("update countries set currency='inr'") with self.assertRaisesRegex(ValueError, "shape"): build.validate(db, "countries", expected_rows=1) self.assertEqual(build.PINS["countries"]["row_count"], 250) def test_source_hash_mismatch_refuses_before_packaging(self): # RULE: A changed upstream dump never silently changes a build's world facts; pin every source by SHA-256. with tempfile.TemporaryDirectory() as tmp: source = Path(tmp) / "source" source.write_bytes(b"changed") with self.assertRaisesRegex(ValueError, "SHA-256"): build.verify(source, "0" * 64) def test_download_publishes_only_the_verified_complete_file(self): # RULE: An interrupted or changed source never becomes the build cache's pinned input. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() source = root / "source" source.write_bytes(b"synthetic public facts") destination = root / "cached" with self.assertRaises(ValueError): build.download(source.as_uri(), destination, "0" * 64) self.assertFalse(destination.exists()) digest = hashlib.sha256(source.read_bytes()).hexdigest() build.download(source.as_uri(), destination, digest) self.assertEqual(destination.read_bytes(), source.read_bytes()) def test_package_carries_source_identity_and_searches_alternate_names(self): # RULE: The package's index is built from the pinned source, including alternate names, before it ships. with tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() source = root / "cities.zip" with zipfile.ZipFile(source, "w") as archive: archive.writestr("cities500.txt", "1269843\tHyderabad\tHyderabad\tBhagyanagar,హైదరాబాద్\t17.38\t78.48\tP\tPPLA\tIN\t\t40\t\t\t\t6809970\t\t0\tAsia/Kolkata\t2026-10-14\n") dest = root / "places.sqlite" digest = hashlib.sha256(source.read_bytes()).hexdigest() build.places(source, dest, digest) db = sqlite3.connect(dest) self.assertEqual(db.execute("select source_sha256 from dataset").fetchone()[0], digest) self.assertEqual(db.execute("select rowid from places_search where places_search match 'bhag*'").fetchone()[0], 1269843) self.assertEqual(db.execute("pragma integrity_check").fetchone()[0], "ok") if __name__ == "__main__": unittest.main()