diff --git a/.github/workflows/integrity.yml b/.github/workflows/integrity.yml index 47042dc..e6c7fe2 100644 --- a/.github/workflows/integrity.yml +++ b/.github/workflows/integrity.yml @@ -417,6 +417,44 @@ jobs: DATA_GATEWAY_TEST_DSN: postgresql://postgres:ci-postgres-password@127.0.0.1:5432/market_catalog_quality_reassessment run: python tests/integration_quality_reassessment_postgres.py + legacy-day-rebuild-postgres: + name: Disposable PostgreSQL 17 legacy day rebuild test + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: ci-postgres-password + POSTGRES_DB: market_catalog_legacy_day_rebuild + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d market_catalog_legacy_day_rebuild" + --health-interval 5s + --health-timeout 5s + --health-retries 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install legacy day rebuild test dependencies + run: python -m pip install --disable-pip-version-check -r tests/requirements.txt + - name: Initialize catalog schema + env: + POSTGRES_USER: postgres + POSTGRES_DB: market_catalog_legacy_day_rebuild + PGPASSWORD: ci-postgres-password + PGHOST: 127.0.0.1 + PGPORT: '5432' + run: | + docker run --rm --network host -v "$GITHUB_WORKSPACE:/workspace:ro" -e POSTGRES_USER -e POSTGRES_DB -e PGPASSWORD -e PGHOST -e PGPORT postgres:17 psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -f /workspace/db/init/001_catalog.sql + - name: Run legacy day rebuild PostgreSQL integration + env: + DATA_GATEWAY_TEST_DSN: postgresql://postgres:ci-postgres-password@127.0.0.1:5432/market_catalog_legacy_day_rebuild + run: python tests/integration_bybit_legacy_day_rebuild_postgres.py + adversarial-refusal-postgres: name: Disposable PostgreSQL 17 adversarial publication refusal test runs-on: ubuntu-latest diff --git a/docs/engineering/BYBIT_ARCHIVE_IMPORT_RUNBOOK.md b/docs/engineering/BYBIT_ARCHIVE_IMPORT_RUNBOOK.md index 02d3299..779ffdb 100644 --- a/docs/engineering/BYBIT_ARCHIVE_IMPORT_RUNBOOK.md +++ b/docs/engineering/BYBIT_ARCHIVE_IMPORT_RUNBOOK.md @@ -72,3 +72,102 @@ python tools/check_trades_catalog.py When the instrument shows the expected `valid` partitions, deleting `/srv/marketdata/replaced-ETHUSDT` is the maintainer's decision and step. + +## 6. Rebuild damaged legacy live days (DG-R, ADR-0074 Amendment 2) + +Operator-run, one explicitly named set of days at a time, from a plan that was reviewed. The days come from you, never from the tool: +the 31 candidate dates of the amendment are an inventory, not a plan. Start with `2026-10-20`; further days only from a new plan. + +**What it does, per day, in this order:** (1) *retire* the damaged live revision of `dt=` with a superseding quality +reassessment (`fail`, reason `legacy_publication_incomplete_day`, naming the archive file), which the existing lifecycle maps to +`invalid`: nothing is deleted, its bytes, manifests, reports and admissions stay, and every read policy excludes it; (2) *import* the +whole archive day as revision 1 of `dt=/seg=000000.000` through the ordinary S13/S14 path; (3) *verify* it against the archive +file field by field and by a strict `DataGateway` read (count, order, duplicates). The rebuilt rows carry the archive's null +`receive_ts` and `sequence`: the provider `sequence` of the rows the damaged revision served is lost in the served data (declared and +accepted; the old bytes are kept). + +**Between the retire and the import the day is served by nothing** (a strict read refuses, `allow-partial` reports the gap). There is +no atomic switch by design. The tool does one day at a time and holds no lock between days or while it reads and verifies. + +### 6.1 Before you start + +- The days are closed in UTC: the end of the day is at least 24 hours before the execution. +- The archive file of each day **and of every neighbouring day whose trades the damaged revision holds** (a day can hold rows of the + day before or after it) is in one directory, fetched with `tools/fetch_bybit_trade_archive.py` (section 1). +- The live-ingest checkpoint path of the instrument, so the tool can refuse a day the checkpoint is bound to. +- The producing commit: the checkout is clean and its `HEAD` is what you want written in the manifests (or pass `--code-ref`). +- `CATALOG_DSN` (or the variable named by `--dsn-env`) holds the PostgreSQL DSN; it is never passed on the command line. + +### 6.2 Plan (read-only) + +```bash +python tools/rebuild_bybit_legacy_days.py --storage-root-id hot plan --days 2026-10-20 \ + --archive-dir /srv/marketdata/staging/BTCUSDT --checkpoint-path /srv/marketdata/canonical/_k10_checkpoints/live-ingest-server-v1.json \ + --out plan-2026-10-20.json +``` + +It prints the **digest** and the action per day (`retire+import`, `import`, `verify` or `refused` with the reasons) and writes the plan +file, which it never overwrites. Read the plan file before you go on: for each day the incumbent revision (partition UUID, key, +revision, state, hashes, coverage), the archive file (URL, SHA-256, size, observation time, rows), the key to create, and the +conservation summary (how many records the damaged revision holds and the days they belong to). + +A day is **refused**, and nothing is changed for it, when: it is not closed in UTC; it has a live slice (`dt=/seg=...`), a +checkpoint bound to one of its partitions or an open gap record that names it; its live revision is not `valid` (or `invalid` +retired by this operation for the same archive file); the incumbent's Parquet or durable manifests are missing, do not load, or are not +the ones the catalog and its quality reports certified (the manifests are looked for beside the Parquet and, for a day published by the +live publisher before the slices, in the root of the dataset as `partition-manifest-.json` and +`coverage-manifest-.json`, the time without the date: a root file that a later day overwrote in the same second is not this +revision's and the day is refused); the archive file is missing or fails the strict parsing; or **conservation +fails**: every record of the damaged revision, by `(exchange_ts, trade_id)`, must exist in the archive file of its own UTC day with +the same venue, instrument, exchange time (millisecond), side, price and size. The records that belong to **another** day must stay +served: a `valid` partition of that day must hold those very records (a later, partial batch of the day that does not is not enough), +or that day must be in the same plan and not refused, so that it is rebuilt from its own archive file; a day of the plan that is refused +contributes nothing, and what depended on it is refused in turn. The hash of every archive file read for this is in the plan. A trade id that the damaged revision holds twice with different content refuses the day too. Any +difference refuses the day; there is no partial acceptance. + +### 6.3 Execute + +```bash +python tools/rebuild_bybit_legacy_days.py --storage-root-id hot execute --plan plan-2026-10-20.json --digest \ + --archive-dir /srv/marketdata/staging/BTCUSDT --checkpoint-path /srv/marketdata/canonical/_k10_checkpoints/live-ingest-server-v1.json +``` + +The tool recomputes the plan from the catalog, the files and the clock and refuses (`STALE`, nothing done) if the digest differs: a +changed incumbent, archive file or catalog, or a day that closed in between. It never acquires another target and never widens the +set of days. It stops at the first day that fails; the later days are not attempted. The import and the verification are bound to the +archive file the plan approved: they check its SHA-256 on the bytes they parse, so a file replaced after the plan is refused (`SOURCE`) +and a file replaced after the import fails the verification, whatever is in the directory then. If a run stops after a day that depended +on a later day of the plan, the later day is retired or untouched: run `verify`, then plan again or `restore` as below. + +**Crashes and retries.** After a crash between the retire and the import the day is retired and not imported: run the same command +again and it imports. After a crash between the import and the verification, run it again: it finds the valid key it would create and +verifies. A crash while the import was writing files leaves them unpublished; the rerun is refused `TARGET` or `CATALOG` until you +decide what to do with them (nothing is deleted by the tool). + +### 6.4 Verify, and the way back + +```bash +python tools/rebuild_bybit_legacy_days.py --storage-root-id hot verify --days 2026-10-20 --archive-dir /srv/marketdata/staging/BTCUSDT +``` + +Read-only and repeatable; pass `--plan plan-2026-10-20.json` to check each day against the archive file the plan approved (the report +always names the SHA-256 of the file it compared). It passes only if the imported Parquet is identical to the archive file and a strict gateway read returns +exactly the archive's records, in `(exchange_ts, trade_id)` order, once each. A strict read can also be refused when a neighbouring +legacy day's coverage crosses midnight and overlaps the rebuilt day: that neighbour is retired and rebuilt by its own plan. + +**Restore** is explicit, never automatic, and only for a day that was retired and **not** rebuilt (the import failed and you prefer +the damaged day to no day): + +```bash +python tools/rebuild_bybit_legacy_days.py --storage-root-id hot restore --day 2026-10-20 +``` + +It adds a superseding `pass` that returns the revision to `valid`; it is refused while the day has any partition under `dt=/` +(two valid partitions over one day) and while an import holds the day's lock (`.import-dt=.lock`, the one the import takes from its +check to its publication; it never waits, so run it again when the import is over). The ordinary importer still refuses an occupied day, a retired one included: the rebuild is a +separate operation and never a `--force`. + +### 6.5 What this does not do + +It does not run itself, choose days, delete or clean retired or superseded revisions (the retention decision is the maintainer's), touch +live slices, checkpoints, gap evidence or healthy days, repair live gaps, or run on the server for you. diff --git a/src/quant_platform/application/bybit_archive_import.py b/src/quant_platform/application/bybit_archive_import.py index 4826e8c..79704f4 100644 --- a/src/quant_platform/application/bybit_archive_import.py +++ b/src/quant_platform/application/bybit_archive_import.py @@ -129,6 +129,85 @@ def import_bybit_archive_day( ) +REBUILD_SEGMENT = "seg=000000.000" +REBUILD_COVERAGE_TAG_SUFFIX = "-rebuild" + + +def rebuild_partition_key(day: str) -> str: + """The fixed key a rebuilt day is imported under: the two-level grammar of ADR-0075 for a window that starts at the day's start.""" + + return f"dt={day}/{REBUILD_SEGMENT}" + + +def import_bybit_archive_day_after_retirement( + connection: Any, + *, + instrument: str, + day: str, + archive_path: str | Path, + storage_root_id: str, + code_ref: str, + expected_source_sha256: str, +) -> ArchiveImportReport: + """The rebuild variant of the import (ADR-0074 Amendment 2, A2.2): the day's legacy revision, once ``invalid``, does not occupy it. + + The ordinary :func:`import_bybit_archive_day` refuses any day that has a partition, in any state, and keeps doing so. This + variant lets through one thing only: the live revision of the **exact** key ``dt=`` in the state ``invalid`` (its + superseded predecessors are history). A ``valid``, ``degraded``, ``closed`` or ``writing`` revision of that key, and every + partition ``dt=/...`` (including the key it would create), still refuses. The key it creates is fixed + (:func:`rebuild_partition_key`); it is not a ``--force`` and takes no key argument. The bytes it parses and materializes must + hash to ``expected_source_sha256`` (the file the plan approved): another file is refused as ``SOURCE`` before anything is written.""" + + try: + identity = bybit_archive_dataset_identity(instrument) + bybit_archive_file_name(instrument, day) # validates the day + start = datetime.combine(date.fromisoformat(day), datetime.min.time(), tzinfo=timezone.utc) + except Exception as exc: + raise ArchiveImportRefused("REQUEST", str(exc)) from exc + if not isinstance(code_ref, str) or not code_ref.strip(): + raise ArchiveImportRefused("REQUEST", "code_ref must name the producing code") + abs_path = _storage_root_path(connection, storage_root_id) + _refuse_unless_retired(connection, identity, day, instrument) + dataset_root = Path(abs_path).joinpath( + identity.layer, identity.dataset_kind, identity.venue, identity.instrument, identity.record_schema_id + ) + try: + dataset_root.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise ArchiveImportRefused("TARGET", f"cannot create the dataset root: {exc}") from exc + # the lock is the day's, the same file the ordinary import takes: the two exclude each other (its name is derived from the day, + # not from the two-level key, which would name a directory that does not exist) + with _day_lock(dataset_root / f".import-dt={day}.lock"): + _refuse_unless_retired(connection, identity, day, instrument) + return _import_locked( + connection, identity=identity, instrument=instrument, day=day, start=start, partition_key=rebuild_partition_key(day), + archive_path=archive_path, storage_root_id=storage_root_id, code_ref=code_ref, dataset_root=dataset_root, + coverage_tag_suffix=REBUILD_COVERAGE_TAG_SUFFIX, expected_source_sha256=expected_source_sha256, + ) + + +def _refuse_unless_retired(connection: Any, identity: Any, day: str, instrument: str) -> None: + legacy_key = f"dt={day}" + with connection.cursor() as cursor: + cursor.execute( + "SELECT p.partition_key, p.state FROM catalog.partitions p JOIN catalog.datasets d ON d.dataset_id = p.dataset_id " + "WHERE d.layer = %s AND d.kind = %s AND d.venue = %s AND d.instrument = %s AND d.schema_id = %s " + "AND d.feature_set_def_id IS NULL AND (p.partition_key = %s OR p.partition_key LIKE %s)", + (identity.layer, identity.dataset_kind, identity.venue, identity.instrument, identity.record_schema_id, + legacy_key, f"{legacy_key}/%"), + ) + rows = cursor.fetchall() + connection.rollback() + foreign = [key for key, _state in rows if key != legacy_key] + if foreign: + raise ArchiveImportRefused("CATALOG", f"{instrument} {day} has partitions under {legacy_key}/ ({', '.join(sorted(foreign))}); " + "the rebuild creates its key only on a day that has none") + live = [state for _key, state in rows if state != "superseded"] + if live != ["invalid"]: + raise ArchiveImportRefused( + "CATALOG", f"{instrument} {legacy_key} must have exactly one live revision and it must be invalid (retired); found {live}") + + def _import_locked( connection: Any, *, @@ -141,6 +220,8 @@ def _import_locked( storage_root_id: str, code_ref: str, dataset_root: Path, + coverage_tag_suffix: str = "", + expected_source_sha256: str | None = None, ) -> ArchiveImportReport: rel_path = f"{partition_key}/part-001.parquet" artifact_path = dataset_root / rel_path @@ -155,6 +236,10 @@ def _import_locked( records_day = read_bybit_archive_day(archive_path, instrument=instrument, day=day) except Exception as exc: raise ArchiveImportRefused("SOURCE", str(exc)) from exc + if expected_source_sha256 is not None and records_day.evidence.file_sha256 != expected_source_sha256: + raise ArchiveImportRefused( + "SOURCE", f"the archive file is not the approved one: it hashes to {records_day.evidence.file_sha256}, " + f"the plan approved {expected_source_sha256}") interval_start = start.strftime("%Y-%m-%dT%H:%M:%SZ") interval_end = (start + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%SZ") @@ -169,7 +254,7 @@ def _import_locked( partition_key=partition_key, revision=1, rel_path=rel_path, created_at=now, closed_at=now, producer=ARCHIVE_IMPORT_PRODUCER, code_ref=code_ref, ) - tag = f"bybit-archive-{instrument.lower()}-{day}" + tag = f"bybit-archive-{instrument.lower()}-{day}{coverage_tag_suffix}" coverage = build_bybit_trade_v1_source_extract_coverage( dataset_identity=identity, coverage_id=f"{tag}-v1", intent_start=interval_start, intent_end=interval_end, assertion_id=f"{tag}-complete-v1", assertion_start=interval_start, assertion_end=interval_end, @@ -234,7 +319,8 @@ def compare_archive_day_with_parquet( the old file must not carry them either). A row of the old file without a ``trade_id`` cannot be matched and is a difference. """ - archive = read_bybit_archive_day(archive_path, instrument=instrument, day=day).records + archive_day = read_bybit_archive_day(archive_path, instrument=instrument, day=day) + archive = archive_day.records existing: dict[str, Any] = {} parquet_rows = 0 null_trade_ids = 0 @@ -267,6 +353,7 @@ def compare_archive_day_with_parquet( return { "instrument": instrument, "day": day, + "archive_sha256": archive_day.evidence.file_sha256, "archive_rows": len(archive), "parquet_rows": parquet_rows, "parquet_null_trade_ids": null_trade_ids, @@ -304,6 +391,12 @@ def _acquire_lock(path: Path) -> None: handle.write(f"pid={os.getpid()} host={socket.gethostname()} at={_utc_text(datetime.now(timezone.utc))}") +def day_lock(dataset_root: Path, day: str): + """The lock of one legacy day (``dt=``), the one the ordinary import and the rebuild import take; it never waits.""" + + return _day_lock(dataset_root / f".import-dt={day}.lock") + + @contextmanager def _day_lock(path: Path) -> Iterator[None]: """Exclusive lock on one day: a held or left-over lock refuses the import.""" @@ -421,5 +514,9 @@ def _utc_text(moment: datetime) -> str: "bybit_archive_file_name", "bybit_archive_url", "compare_archive_day_with_parquet", + "day_lock", + "REBUILD_SEGMENT", "import_bybit_archive_day", + "import_bybit_archive_day_after_retirement", + "rebuild_partition_key", ] diff --git a/src/quant_platform/application/bybit_legacy_day_rebuild.py b/src/quant_platform/application/bybit_legacy_day_rebuild.py new file mode 100644 index 0000000..838a2e9 --- /dev/null +++ b/src/quant_platform/application/bybit_legacy_day_rebuild.py @@ -0,0 +1,754 @@ +"""R02 (DG-R): the operator-run rebuild of explicitly selected, closed legacy live days (ADR-0074 Amendment 2, A2.2 and A2.4 to A2.5). + +A legacy live day (``dt=``, many superseded revisions, one ``valid`` revision that holds only the day's last batch) is rebuilt +from the Bybit public archive, one day at a time, in this order: **retire** the damaged live revision with the ``R01`` reassessment +(``valid -> invalid``, nothing deleted), **import** the whole archive day as revision 1 of ``dt=/seg=000000.000`` through the +ordinary S13/S14 path, **verify** it field by field against the archive and by a strict ``DataGateway`` read. + +* ``plan_rebuild`` is read-only. It records, per day, the incumbent live revision, the archive file, the producing commit, the key to + create and the result of every refusal below; its digest is what the executor must present. ``execute_rebuild`` recomputes the plan + from the current catalog, files and clock: a changed incumbent, source, catalog or a day that closed in between makes the plan stale + and nothing is done. The executor never acquires another target and never widens the set of days. +* A day is refused, and nothing is changed for it, if it is not closed in UTC (its end is less than 24 hours before execution); it has + a live slice, a checkpoint binding to one of its partitions or an open gap record that names it; its live revision is not ``valid`` + (or ``invalid`` retired by this operation for the same archive); conservation fails; or the archive fails the strict parsing. + **Conservation:** every record of the incumbent, by ``(exchange_ts, trade_id)``, exists in the archive file of its own UTC day with + the same venue, instrument, exchange time (millisecond), side, price and size, and that day is readable afterwards (rebuilt in the + same plan or already valid); any difference refuses the day, there is no partial acceptance. +* One day at a time; no lock is held across days or while the archive is read or verified. A crash between the retire and the import is + recovered by running again (the retired day is imported); a crash between the import and the verification, by running again (the + valid key is found and verified). The restore (a superseding ``pass``) is :func:`restore_retired_day`, never automatic. + +The rows rebuilt carry the archive's null ``receive_ts`` and ``sequence``; the provider ``sequence`` of the rows the incumbent served +is lost in the served data (declared and accepted in A2.4; the old bytes are kept). Nothing is deleted and no retention is touched. +""" + +from __future__ import annotations + +from contextlib import ExitStack +from datetime import date, datetime, timedelta, timezone +from decimal import Decimal +import hashlib +from pathlib import Path +from typing import Any, Iterable, Mapping, Sequence + +from quant_platform.access.catalog import Catalog +from quant_platform.access.gateway import DataGateway +from quant_platform.access.models import DataRequest, LifecyclePolicy +from quant_platform.application.bybit_archive_import import ( + ArchiveImportRefused, + compare_archive_day_with_parquet, + day_lock, + import_bybit_archive_day_after_retirement, + rebuild_partition_key, +) +from quant_platform.application.live_gap_orchestration import load_open_long_gap_records +from quant_platform.canonical import canonical_bytes +from quant_platform.data import Instant +from quant_platform.data.parquet import scan_trade_v1_all +from quant_platform.data.quality_reassessment import ( + REASON_LEGACY_INCOMPLETE_DAY, + LifecycleInputs, + ReassessmentResult, + load_lifecycle_inputs, + reassess_live_partition, +) +from quant_platform.operations.checkpoint import CheckpointStore +from quant_platform.source_adapters.bybit import BYBIT_ORDERING_PROVIDER, BYBIT_TRADE_V1_ORDERING_POLICY +from quant_platform.source_adapters.bybit_archive import ( + bybit_archive_dataset_identity, + bybit_archive_file_name, + bybit_archive_url, + read_bybit_archive_day, +) + +INSTRUMENT = "BTCUSDT" # the damage is the legacy BTCUSDT live path's; the amendment names no other instrument +PLAN_SCHEMA = "bybit-legacy-day-rebuild-plan-v1" +MAX_DAYS_PER_PLAN = 31 +_DAY_NS = 86_400 * 10**9 +_MS_NS = 10**6 +_EXAMPLES = 5 + + +class RebuildRefused(RuntimeError): + """The plan, the execution or the restore is refused; ``phase`` names the step. Nothing was changed by the refused step.""" + + def __init__(self, phase: str, message: str): + self.phase = phase + super().__init__(f"{phase}: {message}") + + +# ------------------------------------------------------------------------------------------------------------ catalog views + + +def _identity(): + return bybit_archive_dataset_identity(INSTRUMENT) + + +def _storage_root(connection: Any, storage_root_id: str) -> Path: + with connection.cursor() as cursor: + cursor.execute("SELECT abs_path FROM catalog.storage_roots WHERE storage_root_id = %s", (storage_root_id,)) + row = cursor.fetchone() + connection.rollback() + if row is None: + raise RebuildRefused("REQUEST", f"storage root {storage_root_id!r} is not registered") + return Path(str(row[0])) + + +def _dataset_root(abs_path: Path) -> Path: + identity = _identity() + return abs_path.joinpath(identity.layer, identity.dataset_kind, identity.venue, identity.instrument, identity.record_schema_id) + + +def _day_partitions(connection: Any, day: str) -> list[dict[str, Any]]: + """Every partition of the dataset whose key is ``dt=`` or under it, superseded ones included, by key and revision.""" + + identity = _identity() + with connection.cursor() as cursor: + cursor.execute( + "SELECT p.partition_id::text, p.partition_key, p.revision, p.state, p.rel_path, p.ts_start, p.ts_end, p.row_count, " + "p.content_sha256, p.manifest_sha256 FROM catalog.partitions p JOIN catalog.datasets d ON d.dataset_id = p.dataset_id " + "WHERE d.layer = %s AND d.kind = %s AND d.venue = %s AND d.instrument = %s AND d.schema_id = %s " + "AND d.feature_set_def_id IS NULL AND (p.partition_key = %s OR p.partition_key LIKE %s) " + "ORDER BY p.partition_key, p.revision", + (identity.layer, identity.dataset_kind, identity.venue, identity.instrument, identity.record_schema_id, + f"dt={day}", f"dt={day}/%"), + ) + rows = cursor.fetchall() + connection.rollback() + return [ + {"partition_id": str(r[0]), "key": r[1], "revision": int(r[2]), "state": r[3], "rel_path": r[4], + "ts_start": Instant.parse(r[5]).isoformat(), "ts_end": Instant.parse(r[6]).isoformat(), "row_count": int(r[7]), + "content_sha256": str(r[8]).strip(), "manifest_sha256": str(r[9]).strip()} + for r in rows + ] + + +def _live_rows(rows: Sequence[Mapping[str, Any]], key: str) -> list[Mapping[str, Any]]: + return [r for r in rows if r["key"] == key and r["state"] != "superseded"] + + +def _held_by_valid(connection: Any, dataset_root: Path, owner: str, trade_ids: Iterable[str]) -> bool: + """Every trade id is in a ``valid`` partition of the day ``owner`` (its legacy key, a rebuilt key or a slice): it is served there. + + A ``valid`` partition of the day is not enough: a later, partial batch of the day does not hold what an earlier one did.""" + + wanted = set(trade_ids) + for row in _day_partitions(connection, owner): + if not wanted: + break + path = dataset_root / row["rel_path"] + if row["state"] != "valid" or not path.is_file(): + continue + for batch in scan_trade_v1_all(path, batch_size=65_536): + wanted.difference_update(record.trade_id for record in batch) + if not wanted: + break + return not wanted + + +def _assessment_scopes(connection: Any, partition_id: str) -> list[tuple[str, str]]: + with connection.cursor() as cursor: + cursor.execute( + "SELECT DISTINCT check_suite, metrics->>'certification_profile' FROM catalog.quality_reports WHERE partition_id = %s", + (partition_id,), + ) + rows = cursor.fetchall() + connection.rollback() + return sorted((str(a), str(b)) for a, b in rows) + + +def _retired_for(connection: Any, partition_id: str, archive_sha256: str) -> bool: + """The partition carries a ``fail`` of this operation (the legacy reason) measured against this very archive file.""" + + with connection.cursor() as cursor: + cursor.execute("SELECT violations FROM catalog.quality_reports WHERE partition_id = %s AND status = 'fail'", (partition_id,)) + rows = cursor.fetchall() + connection.rollback() + for (violations,) in rows: + for item in violations or (): + if (isinstance(item, Mapping) and item.get("message") == REASON_LEGACY_INCOMPLETE_DAY + and isinstance(item.get("archive"), Mapping) and item["archive"].get("sha256") == archive_sha256): + return True + return False + + +def _manifest_files(dataset_root: Path, rel_path: str, manifest_sha256: str | None = None) -> tuple[Path, Path]: + """The partition and coverage manifests that belong to an artifact ``/part-.parquet`` (``001`` is unsuffixed). + + Two layouts exist. The importer and the live slices write them beside the artifact; the live publisher before the slices (#510) + wrote ``partition-manifest-.json`` and ``coverage-manifest-.json`` in the root of the dataset, the time without + the date. The pair beside the artifact is looked at first; with the catalog's manifest hash, the first location whose partition + manifest has that hash wins, so a root file that a later day overwrote (the same second) is never taken for this revision's.""" + + artifact = dataset_root / rel_path + stem = artifact.stem # part- + suffix = stem.split("-", 1)[1] if "-" in stem else "001" + if suffix == "001": + return artifact.parent / "partition-manifest.json", artifact.parent / "coverage-manifest.json" + names = (f"partition-manifest-{suffix}.json", f"coverage-manifest-{suffix}.json") + candidates = [(artifact.parent / names[0], artifact.parent / names[1])] + if artifact.parent != dataset_root: + candidates.append((dataset_root / names[0], dataset_root / names[1])) + if manifest_sha256 is not None: + for partition_manifest, coverage_manifest in candidates: + if partition_manifest.is_file() and _sha256_file(partition_manifest) == manifest_sha256: + return partition_manifest, coverage_manifest + for partition_manifest, coverage_manifest in candidates: + if partition_manifest.is_file(): + return partition_manifest, coverage_manifest + return candidates[0] + + +# ------------------------------------------------------------------------------------------------------------ the checks + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def _differences(archive: Any, live: Any) -> tuple[list[str], bool]: + """``(value differences, text-only difference)`` of one trade between the archive and the incumbent.""" + + differences = [name for name in ("venue", "instrument", "aggressor_side") if getattr(archive, name) != getattr(live, name)] + if archive.exchange_ts.epoch_ns != live.exchange_ts.epoch_ns // _MS_NS * _MS_NS: + differences.append("exchange_ts_ms") + text_only = False + for name in ("price", "size"): + if getattr(archive, name) != getattr(live, name): + if Decimal(getattr(archive, name)) != Decimal(getattr(live, name)): + differences.append(f"{name}_value") + else: + text_only = True + return differences, text_only + + +def _row(record: Any) -> tuple[Any, ...]: + return (record.venue, record.instrument, record.aggressor_side, record.price, record.size, record.exchange_ts.epoch_ns) + + +def _conservation(incumbent_file: Path, day: str, archive_dir: Path) -> tuple[list[str], dict[str, Any], dict[str, set[str]]]: + """Refusals, a summary and the trade ids that belong to other days. + + Every record of the incumbent must be in the archive file of its own UTC day, equal in the common fields. Whether the records of + another day stay served once the incumbent is retired is not decided here: the plan sees all its days (:func:`_resolve_dependencies`). + The summary carries the hash of each archive file read, so that the digest binds the neighbours' files too.""" + + refusals: list[str] = [] + incumbent: dict[str, Any] = {} + duplicated = 0 + for batch in scan_trade_v1_all(incumbent_file, batch_size=65_536): + for record in batch: + if record.trade_id is None: + refusals.append("a record of the incumbent has no trade_id and cannot be compared with the archive") + return refusals, {}, {} + first = incumbent.setdefault(record.trade_id, record) + if first is not record: + duplicated += 1 + if _row(first) != _row(record): + refusals.append(f"the incumbent holds trade_id {record.trade_id!r} twice with different content") + return refusals, {}, {} + by_day: dict[str, list[Any]] = {} + for record in incumbent.values(): + by_day.setdefault(Instant(record.exchange_ts.epoch_ns // _DAY_NS * _DAY_NS).isoformat()[:10], []).append(record) + summary: dict[str, Any] = {"rows": len(incumbent), "duplicate_trade_ids": duplicated, "days": {}, "text_only_differences": 0, "archives": {}} + outside: dict[str, set[str]] = {} + for owner in sorted(by_day): + records = by_day[owner] + summary["days"][owner] = len(records) + archive_path = archive_dir / bybit_archive_file_name(INSTRUMENT, owner) + if not archive_path.is_file(): + refusals.append(f"{len(records)} records of the incumbent belong to {owner}, whose archive file {archive_path.name} is missing") + continue + try: + parsed = read_bybit_archive_day(archive_path, instrument=INSTRUMENT, day=owner) + except Exception as exc: # noqa: BLE001 - a malformed neighbour file refuses the day, never crashes the plan + refusals.append(f"the archive file of {owner} fails the strict parsing: {exc}") + continue + summary["archives"][owner] = parsed.evidence.file_sha256 + wanted = {r.trade_id for r in records} + found = {r.trade_id: r for r in parsed.records if r.trade_id in wanted} + del parsed + absent = sorted(wanted - set(found)) + if absent: + refusals.append(f"{len(absent)} records of the incumbent are not in the archive file of {owner} (e.g. {absent[:_EXAMPLES]})") + differing = [] + for record in records: + if record.trade_id in found: + names, text_only = _differences(found[record.trade_id], record) + summary["text_only_differences"] += int(text_only) + if names: + differing.append((record.trade_id, names)) + if differing: + refusals.append(f"{len(differing)} records of the incumbent differ from the archive of {owner} (e.g. {differing[:_EXAMPLES]})") + if owner != day: + outside[owner] = wanted + return refusals, summary, outside + + +def _day_text(day: str) -> tuple[int, int]: + start = datetime.combine(date.fromisoformat(day), datetime.min.time(), tzinfo=timezone.utc) + start_ns = int(start.timestamp()) * 10**9 + return start_ns, start_ns + _DAY_NS + + +def _utc_text(moment: datetime) -> str: + return moment.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") + + +# ------------------------------------------------------------------------------------------------------------ the plan + + +def _validated_days(days: Sequence[str]) -> list[str]: + if not days: + raise RebuildRefused("REQUEST", "at least one day must be named: the rebuild never chooses its own days") + if len(days) > MAX_DAYS_PER_PLAN: + raise RebuildRefused("REQUEST", f"a plan names at most {MAX_DAYS_PER_PLAN} days") + if len(set(days)) != len(days) or list(days) != sorted(days): + raise RebuildRefused("REQUEST", "the days must be unique and in ascending order") + for day in days: + try: + bybit_archive_file_name(INSTRUMENT, day) + except Exception as exc: + raise RebuildRefused("REQUEST", f"{day!r}: {exc}") from exc + return list(days) + + +_INCUMBENT_IDENTITY = ( + "partition_id", "key", "revision", "rel_path", "ts_start", "ts_end", "row_count", "content_sha256", "manifest_sha256", + "check_suite", "certification_profile", "partition_manifest_file", "coverage_manifest_file", "coverage_manifest_sha256", + "coverage_ids", "assertion_ids", +) + + +def _digest(plan: Mapping[str, Any]) -> str: + """The digest binds what the operation is about (the incumbent's identity, the archive, the checks, the commit), not how far it has + got: the state of the incumbent and the action are progress, so a plan stays current after a retire that was not followed by the + import (the crash of A2.5) and is stale as soon as anything the operation depends on changes. + + ``outside_held`` (whether a valid partition of another day holds the incumbent's records of that day) is progress too: it turns + true when the plan itself rebuilds that day. It is left out; what it means for the plan is in the refusals, which are bound and + are decided for every day on each planning, a retry after a crash included (:func:`_resolve_dependencies`), so a change from + outside (a held record no longer held, a day of the plan no longer rebuildable) still changes the digest.""" + + days = [] + for entry in plan["days"]: + incumbent = entry.get("incumbent") + conservation = entry.get("conservation") + days.append({ + "day": entry["day"], "key_to_create": entry["key_to_create"], "archive": entry.get("archive"), + "conservation": None if conservation is None else {k: v for k, v in conservation.items() if k != "outside_held"}, + "refusals": entry.get("refusals"), + "incumbent": None if incumbent is None else {k: incumbent.get(k) for k in _INCUMBENT_IDENTITY}, + }) + body = {key: plan[key] for key in ("schema", "instrument", "storage_root_id", "code_ref")} + body["days"] = days + return hashlib.sha256(canonical_bytes(body, profile="sorted-compact-ascii-v1", allow_nan=False)).hexdigest() + + +def plan_rebuild( + connection: Any, + *, + days: Sequence[str], + archive_dir: str | Path, + storage_root_id: str, + checkpoint_path: str | Path, + code_ref: str, + now: datetime | None = None, +) -> dict[str, Any]: + """The read-only plan for the named days, with its digest. Writes nothing and holds no lock.""" + + days = _validated_days(days) + if not isinstance(code_ref, str) or not code_ref.strip(): + raise RebuildRefused("REQUEST", "the plan names the producing commit (code_ref)") + now = now or datetime.now(timezone.utc) + archive_dir = Path(archive_dir) + abs_path = _storage_root(connection, storage_root_id) + checkpoint = CheckpointStore(Path(checkpoint_path)).load() if Path(checkpoint_path).exists() else None + gaps = load_open_long_gap_records(storage_root=abs_path, instrument=INSTRUMENT) + entries = [ + _plan_day(connection, day, archive_dir, abs_path, checkpoint, gaps, now) for day in days + ] + _resolve_dependencies(entries) + plan: dict[str, Any] = { + "schema": PLAN_SCHEMA, + "instrument": INSTRUMENT, + "storage_root_id": storage_root_id, + "code_ref": code_ref.strip(), + "days": entries, + } + plan["digest"] = _digest(plan) + return plan + + +def _plan_day( + connection: Any, day: str, archive_dir: Path, abs_path: Path, checkpoint: Any, gaps: Any, now: datetime, +) -> dict[str, Any]: + refusals: list[str] = [] + start_ns, end_ns = _day_text(day) + key = rebuild_partition_key(day) + legacy_key = f"dt={day}" + entry: dict[str, Any] = {"day": day, "key_to_create": key, "incumbent": None, "archive": None, "conservation": None, "action": "refused"} + + if end_ns > int((now - timedelta(hours=24)).timestamp()) * 10**9: + refusals.append("the day is not closed in UTC: its end is less than 24 hours before the execution") + + rows = _day_partitions(connection, day) + slices = sorted({r["key"] for r in rows if r["key"] != legacy_key and r["key"] != key}) + if slices: + refusals.append(f"the day has live slices: {', '.join(slices)}") + created = _live_rows(rows, key) + if checkpoint is not None and (checkpoint.partition_key == legacy_key or str(checkpoint.partition_key).startswith(f"{legacy_key}/")): + refusals.append(f"the live checkpoint is bound to {checkpoint.partition_key} of this day") + if gaps.unparseable_manifest_paths: + refusals.append("a long-gap manifest cannot be read, so no open gap can be excluded") + for record in gaps.records: + gap_start = Instant.parse(record.interval.coverage_start).epoch_ns + gap_end = Instant.parse(record.interval.coverage_end).epoch_ns + if gap_start < end_ns and start_ns < gap_end: + refusals.append(f"an open gap record ({record.coverage_id}) names this day") + + # the archive file of the day: strict parsing, identity, hash + archive_path = archive_dir / bybit_archive_file_name(INSTRUMENT, day) + archive: dict[str, Any] | None = None + if not archive_path.is_file(): + refusals.append(f"the archive file {archive_path.name} is not in the archive directory") + else: + try: + parsed = read_bybit_archive_day(archive_path, instrument=INSTRUMENT, day=day) + evidence = parsed.evidence + archive = { + "file_name": evidence.file_name, "url": bybit_archive_url(INSTRUMENT, day), "sha256": evidence.file_sha256, + "size_bytes": evidence.file_size_bytes, "rows": evidence.row_count, + "observed_at": _utc_text(datetime.fromtimestamp(archive_path.stat().st_mtime, timezone.utc)), + } + del parsed + except Exception as exc: # noqa: BLE001 - the strict parsing refusing the file refuses the day + refusals.append(f"the archive file fails the strict parsing: {exc}") + entry["archive"] = archive + + # the incumbent live revision of the legacy key + live = _live_rows(rows, legacy_key) + incumbent: dict[str, Any] | None = None + if len(live) != 1: + refusals.append(f"{legacy_key} must have exactly one live revision; it has {len(live)}") + else: + incumbent = dict(live[0]) + if incumbent["state"] not in ("valid", "invalid"): + refusals.append(f"the live revision of {legacy_key} is {incumbent['state']}, not valid") + elif incumbent["state"] == "invalid" and (archive is None or not _retired_for(connection, incumbent["partition_id"], archive["sha256"])): + refusals.append(f"the live revision of {legacy_key} is invalid but was not retired by this operation for this archive file") + scopes = _assessment_scopes(connection, incumbent["partition_id"]) + if len(scopes) != 1: + refusals.append(f"the incumbent's assessments name {len(scopes)} suite/profile pairs; exactly one is required") + else: + incumbent["check_suite"], incumbent["certification_profile"] = scopes[0] + refusals += _incumbent_evidence(connection, abs_path, incumbent) + incumbent_file = _dataset_root(abs_path) / incumbent["rel_path"] + if incumbent_file.is_file() and _sha256_file(incumbent_file) == incumbent["content_sha256"]: + found, summary, outside = _conservation(incumbent_file, day, archive_dir) + refusals += found + if summary: + summary["outside_held"] = { + owner: _held_by_valid(connection, _dataset_root(abs_path), owner, ids) for owner, ids in sorted(outside.items()) + } + entry["conservation"] = summary + entry["incumbent"] = incumbent + if created: + if len(created) != 1 or created[0]["state"] != "valid": + refusals.append(f"the key to create, {key}, exists in the state {[r['state'] for r in created]}") + elif incumbent is not None and incumbent["state"] == "valid": + refusals.append(f"{key} is valid while {legacy_key} is valid too: two valid partitions cover the day") + entry["created"] = {"partition_id": created[0]["partition_id"], "state": created[0]["state"]} if created else None + entry["refusals"] = refusals + if not refusals: + if created: + entry["action"] = "verify" + elif incumbent is not None and incumbent["state"] == "invalid": + entry["action"] = "import" + else: + entry["action"] = "retire+import" + return entry + + +def _resolve_dependencies(entries: list[dict[str, Any]]) -> None: + """Refuse a day whose incumbent holds records of another day that would stop being served. + + The records of another day stay served if a ``valid`` partition of that day holds them (``outside_held``, decided against the + catalog) or if that day is in this plan and is not refused, so it ends rebuilt from its own archive file. A day of the plan that + is refused contributes nothing, and what depended on it is refused in turn, until nothing changes. Every day that is not refused + is judged, a retirement to come and a day already retired or rebuilt (a retry after a crash) alike: the progress of the days of + the plan is allowed (the other day, rebuilt by this plan, serves the records), the loss of an external dependency (the other day, + not in the plan, retired by something else) is a refusal, so the retry is refused before any further change.""" + + by_day = {entry["day"]: entry for entry in entries} + changed = True + while changed: + changed = False + for entry in entries: + if entry["action"] == "refused" or not entry["conservation"]: + continue + for owner, held in sorted(entry["conservation"].get("outside_held", {}).items()): + other = by_day.get(owner) + if held or (other is not None and other["action"] != "refused"): + continue + count = entry["conservation"]["days"].get(owner, 0) + where = "that day is refused in this plan" if other is not None else "that day is not in this plan" + entry["refusals"].append( + f"{count} records of the incumbent belong to {owner}, no valid partition of {owner} holds them and {where}: " + "they would stop being served") + entry["action"] = "refused" + changed = True + break + + +def _certified_coverage(connection: Any, partition_id: str) -> list[tuple[tuple[str, ...], tuple[str, ...]]]: + """The coverage manifest hashes and ids the incumbent's quality reports certified (the distinct pairs; one is expected).""" + + with connection.cursor() as cursor: + cursor.execute( + "SELECT DISTINCT metrics->'coverage_manifest_sha256', metrics->'coverage_manifest_ids' FROM catalog.quality_reports " + "WHERE partition_id = %s AND metrics ? 'coverage_manifest_sha256'", + (partition_id,), + ) + rows = cursor.fetchall() + connection.rollback() + return sorted((tuple(map(str, hashes or ())), tuple(map(str, ids or ()))) for hashes, ids in rows) + + +def _incumbent_evidence(connection: Any, abs_path: Path, incumbent: dict[str, Any]) -> list[str]: + """The incumbent's file and durable manifests exist, load, are the ones the catalog holds and the coverage the reports certified.""" + + problems: list[str] = [] + dataset_root = _dataset_root(abs_path) + artifact = dataset_root / incumbent["rel_path"] + if not artifact.is_file(): + problems.append(f"the incumbent's Parquet {incumbent['rel_path']} is not on disk") + elif _sha256_file(artifact) != incumbent["content_sha256"]: + problems.append("the incumbent's Parquet does not hash to the catalog's content hash") + partition_manifest, coverage_manifest = _manifest_files(dataset_root, incumbent["rel_path"], incumbent["manifest_sha256"]) + for label, path in (("partition", partition_manifest), ("coverage", coverage_manifest), ("dataset", dataset_root / "dataset-manifest.json")): + if not path.is_file(): + problems.append(f"the incumbent's {label} manifest {path.name} is not on disk") + if partition_manifest.is_file(): + if _sha256_file(partition_manifest) != incumbent["manifest_sha256"]: + problems.append("the incumbent's partition manifest does not hash to the catalog's manifest hash") + incumbent["partition_manifest_file"] = str(partition_manifest.relative_to(dataset_root)).replace("\\", "/") + if coverage_manifest.is_file(): + incumbent["coverage_manifest_file"] = str(coverage_manifest.relative_to(dataset_root)).replace("\\", "/") + incumbent["coverage_manifest_sha256"] = _sha256_file(coverage_manifest) + if not problems: + certified = _certified_coverage(connection, incumbent["partition_id"]) + if len(certified) != 1: + problems.append(f"the incumbent's quality reports certify {len(certified)} coverage manifest sets; exactly one is required") + else: + try: + loaded = load_lifecycle_inputs( + dataset_root / "dataset-manifest.json", partition_manifest, [coverage_manifest], + ) + except Exception as exc: # noqa: BLE001 - a manifest that does not load refuses the day in the plan, not in the retire + problems.append(f"the incumbent's durable manifests do not load: {exc}") + else: + hashes, ids = certified[0] + if loaded.coverage_sha256 != hashes or tuple(loaded.coverage_ids) != ids: + problems.append("the incumbent's coverage manifest is not the one its quality reports certified") + incumbent["coverage_ids"] = list(loaded.coverage_ids) + incumbent["assertion_ids"] = list(loaded.assertion_ids) + return problems + + +# ------------------------------------------------------------------------------------------------------------ execution + + +def execute_rebuild( + connection: Any, + *, + plan: Mapping[str, Any], + digest: str, + archive_dir: str | Path, + checkpoint_path: str | Path, + now: datetime | None = None, +) -> dict[str, Any]: + """Execute a reviewed plan, one day at a time; refuses a plan that is not the one presented or no longer current.""" + + if plan.get("schema") != PLAN_SCHEMA: + raise RebuildRefused("PLAN", "not a legacy-day rebuild plan") + if _digest(plan) != plan.get("digest") or plan.get("digest") != digest: + raise RebuildRefused("PLAN", "the plan does not match the digest presented") + current = plan_rebuild( + connection, days=[entry["day"] for entry in plan["days"]], archive_dir=archive_dir, + storage_root_id=plan["storage_root_id"], checkpoint_path=checkpoint_path, code_ref=plan["code_ref"], now=now, + ) + if current["digest"] != digest: + raise RebuildRefused("STALE", "the incumbent, the archive, the catalog or the clock changed since the plan; plan again") + results: list[dict[str, Any]] = [] + for entry in current["days"]: # the live state of the same targets: a day already retired or rebuilt resumes where it stopped + result = _execute_day(connection, entry, current, Path(archive_dir)) + results.append(result) + if result["outcome"] not in ("rebuilt", "verified", "refused"): + break # a failure stops the run: the operator decides, the executor does not go on to the next day + return {"plan_digest": digest, "days": results} + + +def _execute_day(connection: Any, entry: Mapping[str, Any], plan: Mapping[str, Any], archive_dir: Path) -> dict[str, Any]: + day = entry["day"] + result: dict[str, Any] = {"day": day, "key": entry["key_to_create"], "action": entry["action"]} + if entry["action"] == "refused": + return {**result, "outcome": "refused", "refusals": list(entry["refusals"])} + archive_path = archive_dir / entry["archive"]["file_name"] + steps: list[str] = [] + if entry["action"] == "retire+import": + try: + retired = _retire(connection, entry, plan) + except Exception as exc: # noqa: BLE001 - reported with its phase; nothing else is attempted for this day + return {**result, "outcome": "retire_failed", "detail": f"{type(exc).__name__}: {exc}", "steps": steps} + steps.append("retired" if retired.inserted else "already retired") + if entry["action"] in ("retire+import", "import"): + try: + report = import_bybit_archive_day_after_retirement( + connection, instrument=INSTRUMENT, day=day, archive_path=archive_path, storage_root_id=plan["storage_root_id"], + code_ref=plan["code_ref"], expected_source_sha256=entry["archive"]["sha256"], + ) + except ArchiveImportRefused as exc: + return {**result, "outcome": "import_refused", "phase": exc.phase, "detail": str(exc), "steps": steps} + steps.append(f"imported {report.row_count} rows as {report.state}") + if report.state != "valid": + return {**result, "outcome": "import_not_valid", "detail": report.state, "steps": steps} + verified = verify_rebuilt_day( + connection, day=day, archive_dir=archive_dir, storage_root_id=plan["storage_root_id"], + expected_archive_sha256=entry["archive"]["sha256"], + ) + steps.append("verified" if verified["passed"] else "verification failed") + outcome = ("verified" if entry["action"] == "verify" else "rebuilt") if verified["passed"] else "verify_failed" + return {**result, "outcome": outcome, "steps": steps, "verification": verified} + + +def _incumbent_inputs(abs_path: Path, incumbent: Mapping[str, Any]) -> LifecycleInputs: + dataset_root = _dataset_root(abs_path) + return load_lifecycle_inputs( + dataset_root / "dataset-manifest.json", dataset_root / incumbent["partition_manifest_file"], + [dataset_root / incumbent["coverage_manifest_file"]], + ) + + +def _retire(connection: Any, entry: Mapping[str, Any], plan: Mapping[str, Any]) -> ReassessmentResult: + incumbent = entry["incumbent"] + abs_path = _storage_root(connection, plan["storage_root_id"]) + return reassess_live_partition( + connection, inputs=_incumbent_inputs(abs_path, incumbent), + coverage_start=Instant.parse(incumbent["ts_start"]), coverage_end=Instant.parse(incumbent["ts_end"]), + storage_root_id=plan["storage_root_id"], expected_profile=incumbent["certification_profile"], + expected_check_suite=incumbent["check_suite"], status="fail", code_ref=plan["code_ref"], + archive_identity={**{k: entry["archive"][k] for k in ("url", "sha256", "size_bytes", "rows", "file_name")}, + "plan_digest": plan["digest"]}, + ) + + +# ------------------------------------------------------------------------------------------------------------ verify, restore + + +def verify_rebuilt_day( + connection: Any, *, day: str, archive_dir: str | Path, storage_root_id: str, expected_archive_sha256: str | None = None, +) -> dict[str, Any]: + """Read-only. The imported records equal the archive field by field, and a strict gateway read returns them exactly. + + The report names the hash of the archive file it compared. With ``expected_archive_sha256`` (the plan's) another file is a + finding: the verification does not accept whatever file is in the directory now.""" + + archive_path = Path(archive_dir) / bybit_archive_file_name(INSTRUMENT, day) + key = rebuild_partition_key(day) + report: dict[str, Any] = {"day": day, "key": key, "passed": False, "problems": []} + created = [r for r in _day_partitions(connection, day) if r["key"] == key and r["state"] != "superseded"] + if len(created) != 1 or created[0]["state"] != "valid": + report["problems"].append(f"{key} has no single valid revision ({[r['state'] for r in created]})") + return report + parquet = _dataset_root(_storage_root(connection, storage_root_id)) / created[0]["rel_path"] + compared = compare_archive_day_with_parquet(archive_path, parquet, instrument=INSTRUMENT, day=day) + report["archive_sha256"] = compared["archive_sha256"] + if expected_archive_sha256 is not None and compared["archive_sha256"] != expected_archive_sha256: + report["problems"].append( + f"the archive file now in the directory hashes to {compared['archive_sha256']}, not to the approved {expected_archive_sha256}") + report["comparison"] = {k: compared[k] for k in ("archive_rows", "parquet_rows", "only_in_archive", "only_in_parquet", + "field_differences", "same_trades", "identical")} + if not compared["identical"]: + report["problems"].append("the imported Parquet is not identical to the archive file, field by field") + start_ns, end_ns = _day_text(day) + request = DataRequest( + _identity(), Instant(start_ns), Instant(end_ns), schema_requirement="trade-v1", lifecycle_policy=LifecyclePolicy.VALID_ONLY, + coverage_policy="strict", ordering_policy=BYBIT_TRADE_V1_ORDERING_POLICY, + ) + try: + records = DataGateway(Catalog(connection=connection), ordering_providers=(BYBIT_ORDERING_PROVIDER,)).read(request).records + except Exception as exc: # noqa: BLE001 - a refused strict read (a gap, an overlap with a neighbour) is a finding + report["problems"].append(f"the strict read of the day was refused: {type(exc).__name__}: {exc}") + connection.rollback() + return report + connection.rollback() + ids = [r.trade_id for r in records] + keys = [(r.exchange_ts.epoch_ns, r.trade_id) for r in records] + report["read"] = {"records": len(records), "unique_trade_ids": len(set(ids)), "in_order": keys == sorted(keys)} + if len(records) != compared["archive_rows"]: + report["problems"].append(f"the strict read returned {len(records)} records, the archive has {compared['archive_rows']}") + if len(set(ids)) != len(ids): + report["problems"].append("the strict read returned a trade more than once") + if keys != sorted(keys): + report["problems"].append("the strict read is not in (exchange_ts, trade_id) order") + report["passed"] = not report["problems"] + return report + + +def restore_retired_day(connection: Any, *, day: str, storage_root_id: str, code_ref: str) -> ReassessmentResult: + """The documented way back: a superseding ``pass`` returns the retired legacy revision to ``valid``. Never automatic. + + Refused while the day has any partition under ``dt=/``: restoring would put two valid partitions over one day. It takes the + day's lock, the one the rebuild import holds from its check to its publication, and decides under it: a restore cannot slip in + between the import's check and its publication, and an import after a restore finds a valid day and refuses.""" + + dataset_root = _dataset_root(_storage_root(connection, storage_root_id)) + with ExitStack() as stack: + try: + stack.enter_context(day_lock(dataset_root, day)) + except ArchiveImportRefused as exc: + raise RebuildRefused("RESTORE", f"the day is locked by an import ({exc}); nothing was changed") from exc + return _restore_locked(connection, day=day, storage_root_id=storage_root_id, code_ref=code_ref) + + +def _restore_locked(connection: Any, *, day: str, storage_root_id: str, code_ref: str) -> ReassessmentResult: + rows = _day_partitions(connection, day) + under = [r["key"] for r in rows if r["key"] != f"dt={day}"] + if under: + raise RebuildRefused("RESTORE", f"{day} has partitions under dt={day}/ ({', '.join(sorted(set(under)))}); restoring would overlap them") + live = _live_rows(rows, f"dt={day}") + if len(live) != 1 or live[0]["state"] != "invalid": + raise RebuildRefused("RESTORE", f"dt={day} must have exactly one live revision and it must be invalid") + incumbent = dict(live[0]) + scopes = _assessment_scopes(connection, incumbent["partition_id"]) + if len(scopes) != 1: + raise RebuildRefused("RESTORE", "the incumbent's assessments name more than one suite/profile pair") + incumbent["check_suite"], incumbent["certification_profile"] = scopes[0] + abs_path = _storage_root(connection, storage_root_id) + problems = _incumbent_evidence(connection, abs_path, incumbent) + if problems: + raise RebuildRefused("RESTORE", "; ".join(problems)) + return reassess_live_partition( + connection, inputs=_incumbent_inputs(abs_path, incumbent), + coverage_start=Instant.parse(incumbent["ts_start"]), coverage_end=Instant.parse(incumbent["ts_end"]), + storage_root_id=storage_root_id, expected_profile=incumbent["certification_profile"], + expected_check_suite=incumbent["check_suite"], status="pass", code_ref=code_ref, + ) + + +__all__ = [ + "INSTRUMENT", + "MAX_DAYS_PER_PLAN", + "PLAN_SCHEMA", + "RebuildRefused", + "execute_rebuild", + "plan_rebuild", + "restore_retired_day", + "verify_rebuilt_day", +] diff --git a/tests/integration_bybit_legacy_day_rebuild_postgres.py b/tests/integration_bybit_legacy_day_rebuild_postgres.py new file mode 100644 index 0000000..0bef275 --- /dev/null +++ b/tests/integration_bybit_legacy_day_rebuild_postgres.py @@ -0,0 +1,787 @@ +#!/usr/bin/env python3 +"""Real PostgreSQL proof of the legacy-day rebuild (DG-R R02, ADR-0074 Amendment 2). + +Legacy-shaped days are made with the ordinary importer: a day published from a *partial* archive file is one ``valid`` revision of +``dt=`` that holds only part of the day (the shape of the damaged live days). The rebuild plans, retires (``R01``), imports the +whole archive day as revision 1 of ``dt=/seg=000000.000`` through the ordinary S13/S14 path and verifies it. Every refusal leaves +the catalog, the files and the live checkpoint byte-identical; a crash between the steps is recovered by running the same plan again. +Requires ``DATA_GATEWAY_TEST_DSN`` and a POSIX storage root. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import gzip +import hashlib +import json +import os +from pathlib import Path +import sys +import tempfile +from types import SimpleNamespace +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +import psycopg # noqa: E402 +import quant_platform.application.bybit_legacy_day_rebuild as rebuild # noqa: E402 +from quant_platform.access.catalog import Catalog # noqa: E402 +from quant_platform.access.gateway import DataGateway # noqa: E402 +from quant_platform.access.models import DataRequest, LifecyclePolicy # noqa: E402 +from quant_platform.application import bybit_archive_import as importer # noqa: E402 +from quant_platform.application.bybit_archive_import import ( # noqa: E402 + ArchiveImportRefused, + import_bybit_archive_day, + import_bybit_archive_day_after_retirement, +) +from quant_platform.application.bybit_legacy_day_rebuild import ( # noqa: E402 + RebuildRefused, + execute_rebuild, + plan_rebuild, + restore_retired_day, + verify_rebuilt_day, +) +from quant_platform.data import Instant # noqa: E402 +from quant_platform.data.models import NoCoverage # noqa: E402 +from quant_platform.data.parquet import scan_trade_v1_all # noqa: E402 +from quant_platform.operations.checkpoint import CheckpointStore, LiveCheckpointV1, advance_checkpoint # noqa: E402 +from quant_platform.source_adapters.bybit import BYBIT_ORDERING_PROVIDER, BYBIT_TRADE_V1_ORDERING_POLICY # noqa: E402 +from quant_platform.source_adapters.bybit_archive import bybit_archive_dataset_identity, read_bybit_archive_day # noqa: E402 +from quant_platform.source_adapters.bybit_live import bybit_live_dataset_identity # noqa: E402 + +HEADER = "timestamp,symbol,side,size,price,tickDirection,trdMatchID,grossValue,homeNotional,foreignNotional" +STORAGE_ROOT_ID = "rebuild-hot" +INSTRUMENT = "BTCUSDT" +PILOT = "2026-10-20" +CODE_REF = "r02-commit" + + +def day_ms(day: str) -> int: + return int(datetime.fromisoformat(day).replace(tzinfo=timezone.utc).timestamp()) * 1000 + + +def world(day: str, count: int = 400) -> list[tuple[int, str, str, str, str]]: + """The whole day: ``(ms, trade_id, side, price, size)``; some trades share a millisecond (ties are ordered by trade id).""" + + rows = [] + for i in range(count): + ms = day_ms(day) + 1000 + i * 200_000 + if i % 7 == 3 and rows: + ms = rows[-1][0] # a tie: the same millisecond as the previous trade (ordered by trade id) + rows.append((ms, f"{day}-{i:06d}", "Buy" if i % 2 == 0 else "Sell", f"{60000 + (i % 500) / 10:.1f}", f"{(i % 9 + 1) / 100:.2f}")) + return rows + + +def write_archive(directory: Path, day: str, rows, name: str | None = None) -> Path: + path = directory / (name or f"{INSTRUMENT}{day}.csv.gz") + lines = [HEADER] + [f"{ms // 1000}.{ms % 1000:03d},{INSTRUMENT},{side},{size},{price},PlusTick,{trade_id},1,{size},1" + for ms, trade_id, side, price, size in rows] + path.write_bytes(gzip.compress(("\n".join(lines) + "\n").encode("utf-8"))) + return path + + +def sha(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def sql(connection, query, params=()): + with connection.cursor() as cursor: + cursor.execute(query, params) + rows = cursor.fetchall() if cursor.description else None + connection.commit() + return rows + + +def snapshot(connection, storage: Path, checkpoint: Path) -> tuple: + """Everything a refused operation must leave alone: the catalog rows and reports, every file, the checkpoint.""" + + rows = sql(connection, "SELECT p.partition_key, p.revision, p.state, p.content_sha256, p.manifest_sha256 FROM catalog.partitions p " + "JOIN catalog.datasets d ON d.dataset_id = p.dataset_id WHERE d.instrument = %s ORDER BY 1, 2", (INSTRUMENT,)) + reports = sql(connection, "SELECT p.partition_key, r.status, r.code_ref FROM catalog.quality_reports r JOIN catalog.partitions p " + "ON p.partition_id = r.partition_id ORDER BY 1, 2, 3") + files = sorted((str(p.relative_to(storage)), hashlib.sha256(p.read_bytes()).hexdigest()) for p in storage.rglob("*") if p.is_file()) + return rows, reports, files, checkpoint.read_bytes() if checkpoint.exists() else None + + +def states(connection) -> dict[str, list[str]]: + result: dict[str, list[str]] = {} + for key, state in sql(connection, "SELECT p.partition_key, p.state FROM catalog.partitions p JOIN catalog.datasets d ON d.dataset_id = " + "p.dataset_id WHERE d.instrument = %s ORDER BY p.partition_key, p.revision", (INSTRUMENT,)): + result.setdefault(key, []).append(state) + return result + + +def gateway_ids(connection, day: str, coverage: str = "strict") -> list[str] | None: + start = day_ms(day) * 1_000_000 + request = DataRequest(bybit_archive_dataset_identity(INSTRUMENT), Instant(start), Instant(start + 86_400 * 10**9), + schema_requirement="trade-v1", lifecycle_policy=LifecyclePolicy.VALID_ONLY, coverage_policy=coverage, + ordering_policy=BYBIT_TRADE_V1_ORDERING_POLICY) + try: + return [r.trade_id for r in DataGateway(Catalog(connection=connection), ordering_providers=(BYBIT_ORDERING_PROVIDER,)).read(request).records] + except NoCoverage: + connection.rollback() + return None + + +def main() -> int: + dsn = os.environ.get("DATA_GATEWAY_TEST_DSN") + if not dsn: + print("POSTGRESQL LEGACY DAY REBUILD GATE NOT EXECUTED LOCALLY") + return 0 + with tempfile.TemporaryDirectory() as holder: + base = Path(holder) + storage, staging, archives = base / "storage", base / "staging", base / "archives" + for directory in (storage, staging, archives): + directory.mkdir() + checkpoint = storage / "_k10_checkpoints" / "live-ingest-server-v1.json" + checkpoint.parent.mkdir() + days = ["2026-10-08", "2026-10-09", "2026-10-18", "2026-10-19", PILOT, "2026-10-21"] + full = {day: world(day) for day in days} + with psycopg.connect(dsn) as connection: + sql(connection, "INSERT INTO catalog.schema_registry (schema_id,name,version,json_sha256,body) VALUES ('trade-v1','trade',1,%s,%s::jsonb) ON CONFLICT DO NOTHING", ("0" * 64, "{}")) + sql(connection, "INSERT INTO catalog.storage_roots (storage_root_id,abs_path,tier) VALUES (%s,%s,'hot')", (STORAGE_ROOT_ID, str(storage))) + dataset_root = storage / "canonical" / "trades" / "bybit" / INSTRUMENT / "trade-v1" + for day in days: + write_archive(archives, day, full[day]) + + def legacy(day: str, subset=None) -> None: + """A damaged legacy day: one valid ``dt=`` revision that holds only part of the day.""" + rows = subset if subset is not None else full[day][::7] + path = write_archive(staging, day, rows) + report = import_bybit_archive_day(connection, instrument=INSTRUMENT, day=day, archive_path=path, + storage_root_id=STORAGE_ROOT_ID, code_ref="legacy-commit") + assert report.state == "valid", report + path.unlink() + + for day in days[:5]: + legacy(day) + # the live checkpoint: bound to a partition of a day that is not rebuilt here + CheckpointStore(checkpoint).save(advance_checkpoint(None, LiveCheckpointV1( + dataset_identity=bybit_live_dataset_identity(INSTRUMENT), source_semantics_id="bybit-public-trades-websocket-v1", + last_canonical_exchange_ts=Instant(1000), last_canonical_trade_id="anchor", last_observed_sequence=None, + catalog_dataset_id="dataset", partition_key="dt=2026-10-22/seg=000000.000", revision=1, + partition_manifest_sha256="a" * 64, coverage_segment_id="coverage-1", generation=1, created_at=Instant(0)))) + + def make_plan(selected, **kwargs): + return plan_rebuild(connection, days=selected, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID, + checkpoint_path=checkpoint, code_ref=CODE_REF, **kwargs) + + def run(plan, **kwargs): + return execute_rebuild(connection, plan=plan, digest=plan["digest"], archive_dir=archives, checkpoint_path=checkpoint, **kwargs) + + def refused_plan(selected, reason, **kwargs): + plan = make_plan(selected, **kwargs) + entry = plan["days"][0] + assert entry["action"] == "refused" and any(reason in item for item in entry["refusals"]), (reason, entry["refusals"]) + before = snapshot(connection, storage, checkpoint) + result = run(plan, **kwargs) + assert result["days"][0]["outcome"] == "refused", result + assert snapshot(connection, storage, checkpoint) == before, f"a refused day ({reason}) must change nothing" + return plan + + # 1. the plan is read-only, bound by a digest, and says what it will do + before = snapshot(connection, storage, checkpoint) + plan = make_plan([PILOT]) + assert snapshot(connection, storage, checkpoint) == before, "planning must write nothing" + entry = plan["days"][0] + assert entry["action"] == "retire+import" and not entry["refusals"], entry + assert entry["key_to_create"] == f"dt={PILOT}/seg=000000.000" and entry["incumbent"]["state"] == "valid" + assert entry["archive"]["rows"] == len(full[PILOT]) and entry["conservation"]["rows"] == len(full[PILOT][::7]) + assert plan == make_plan([PILOT]) and plan["digest"] == make_plan([PILOT])["digest"] + incumbent_id = entry["incumbent"]["partition_id"] + old_file = dataset_root / entry["incumbent"]["rel_path"] + old_bytes = old_file.read_bytes() + other_days_before = {key: v for key, v in states(connection).items() if key != f"dt={PILOT}"} + frozen_files = {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in frozen_files_paths(dataset_root, PILOT)} + + # 2. refusals: a presented digest that is not the plan's, and a plan that is no longer current + for wrong in ("0" * 64, plan["digest"][:-1] + ("0" if plan["digest"][-1] != "0" else "1")): + try: + execute_rebuild(connection, plan=plan, digest=wrong, archive_dir=archives, checkpoint_path=checkpoint) + except RebuildRefused as exc: + assert exc.phase == "PLAN", exc + else: + raise AssertionError("a wrong digest must be refused") + tampered = {**plan, "code_ref": "someone-else"} + try: + execute_rebuild(connection, plan=tampered, digest=plan["digest"], archive_dir=archives, checkpoint_path=checkpoint) + except RebuildRefused as exc: + assert exc.phase == "PLAN" + else: + raise AssertionError("an edited plan must be refused") + assert snapshot(connection, storage, checkpoint) == before + + # 3. the other refusals, each on its own and each leaving everything as it was + refused_plan([PILOT], "not closed", now=datetime.fromisoformat(PILOT).replace(tzinfo=timezone.utc) + timedelta(hours=30)) + sql(connection, "UPDATE catalog.partitions SET state='closed' WHERE partition_id=%s", (incumbent_id,)) + plan_closed = make_plan([PILOT]) + assert plan_closed["days"][0]["action"] == "refused" and any("not valid" in r for r in plan_closed["days"][0]["refusals"]) + sql(connection, "UPDATE catalog.partitions SET state='valid' WHERE partition_id=%s", (incumbent_id,)) + # a live slice of the day + sql(connection, "INSERT INTO catalog.partitions (dataset_id, partition_key, revision, storage_root_id, rel_path, ts_start, ts_end, " + "row_count, byte_size, content_sha256, state, manifest_sha256, created_at, closed_at, producer, code_ref) " + "SELECT dataset_id, %s, 1, storage_root_id, replace(rel_path, %s, %s), ts_start, ts_start, 0, byte_size, " + "content_sha256, 'valid', manifest_sha256, created_at, closed_at, producer, code_ref FROM catalog.partitions " + "WHERE partition_id=%s", (f"dt={PILOT}/seg=120000.000", f"dt={PILOT}/", f"dt={PILOT}/seg=120000.000/", incumbent_id)) + refused_plan([PILOT], "live slices") + try: + import_bybit_archive_day_after_retirement(connection, instrument=INSTRUMENT, day=PILOT, archive_path=archives / f"{INSTRUMENT}{PILOT}.csv.gz", + storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF, expected_source_sha256=sha(archives / f"{INSTRUMENT}{PILOT}.csv.gz")) + except ArchiveImportRefused as exc: + assert exc.phase == "CATALOG" + else: + raise AssertionError("the variant must refuse a day with a live slice") + sql(connection, "DELETE FROM catalog.partitions WHERE partition_key=%s", (f"dt={PILOT}/seg=120000.000",)) + assert states(connection)[f"dt={PILOT}"] == ["valid"] + + # a checkpoint bound to a partition of the day + saved = checkpoint.read_bytes() + checkpoint.unlink() + CheckpointStore(checkpoint).save(advance_checkpoint(None, LiveCheckpointV1( + dataset_identity=bybit_live_dataset_identity(INSTRUMENT), source_semantics_id="bybit-public-trades-websocket-v1", + last_canonical_exchange_ts=Instant(2000), last_canonical_trade_id="anchor2", last_observed_sequence=None, + catalog_dataset_id="dataset", partition_key=f"dt={PILOT}/seg=000100.000", revision=1, + partition_manifest_sha256="b" * 64, coverage_segment_id="coverage-1", generation=1, created_at=Instant(0)))) + refused_plan([PILOT], "checkpoint") + checkpoint.write_bytes(saved) + + # an open gap record that names the day + from quant_platform.application.live_gap_orchestration import LongGapInterval, TradeKeyBoundary, record_explicit_long_gap + + gap_at = Instant((day_ms(PILOT) + 3_600_000) * 1_000_000) + record_explicit_long_gap( + storage_root=storage, producer="gap-probe", code_ref="gap", detected_at=Instant(gap_at.epoch_ns + 5 * 10**9), + interval=LongGapInterval(start_key=TradeKeyBoundary(venue="bybit", instrument=INSTRUMENT, exchange_ts=gap_at, trade_id="x"), + detected_at=Instant(gap_at.epoch_ns + 5 * 10**9), reason="probe", recent_window_records=None, + buffered_ws_records=None), instrument=INSTRUMENT) + refused_plan([PILOT], "open gap record") + for gap_file in dataset_root.glob("coverage-manifest-long-gap-*.json"): + gap_file.unlink() + + # the archive file: missing, malformed, a row of the incumbent that is not in it, a differing common field + real_archive = archives / f"{INSTRUMENT}{PILOT}.csv.gz" + kept = real_archive.read_bytes() + real_archive.unlink() + refused_plan([PILOT], "is not in the archive directory") + real_archive.write_bytes(gzip.compress(b"not,a,valid,archive\n")) + refused_plan([PILOT], "strict parsing") + write_archive(archives, PILOT, [row for row in full[PILOT] if row not in full[PILOT][::7][3:4]]) + refused_plan([PILOT], "are not in the archive file") + changed = [(ms, i, s, "99999.9" if n == 14 else p, z) for n, (ms, i, s, p, z) in enumerate(full[PILOT])] + write_archive(archives, PILOT, changed) + refused_plan([PILOT], "differ from the archive") + real_archive.write_bytes(kept) + + # 4. a plan is stale when the source changed after it was made + stale = make_plan([PILOT]) + shifted = real_archive.stat().st_mtime + 3600 + os.utime(real_archive, (shifted, shifted)) + before = snapshot(connection, storage, checkpoint) + try: + run(stale) + except RebuildRefused as exc: + assert exc.phase == "STALE", exc + else: + raise AssertionError("a plan whose source changed must be stale") + assert snapshot(connection, storage, checkpoint) == before + os.utime(real_archive, (shifted - 3600, shifted - 3600)) + + # 5. the rebuild of the pilot day, in order, with the crash windows + plan = make_plan([PILOT]) + assert plan["days"][0]["action"] == "retire+import", plan["days"][0]["refusals"] + with mock.patch.object(rebuild, "import_bybit_archive_day_after_retirement", side_effect=RuntimeError("crash after retire")): + try: + run(plan) + except RuntimeError: + pass + else: + raise AssertionError("the crash was not raised") + assert states(connection)[f"dt={PILOT}"] == ["invalid"] and f"dt={PILOT}/seg=000000.000" not in states(connection) + assert gateway_ids(connection, PILOT) is None, "between the retire and the import the day is uncovered (a strict read refuses)" + retired_plan = make_plan([PILOT]) + assert retired_plan["digest"] == plan["digest"], "the retire is progress, not a change of the plan" + assert retired_plan["days"][0]["action"] == "import" + with mock.patch.object(rebuild, "verify_rebuilt_day", side_effect=RuntimeError("crash after import")): + try: + run(plan) # the same plan, run again: the retired day is imported, then the crash + except RuntimeError: + pass + else: + raise AssertionError("the second crash was not raised") + assert states(connection)[f"dt={PILOT}/seg=000000.000"] == ["valid"] and states(connection)[f"dt={PILOT}"] == ["invalid"] + assert make_plan([PILOT])["days"][0]["action"] == "verify" and make_plan([PILOT])["digest"] == plan["digest"] + result = run(plan) # the same plan again: the valid key is found and verified + (day_result,) = result["days"] + assert day_result["outcome"] == "verified" and day_result["verification"]["passed"], day_result + + # 6. the pilot day reads strictly as exactly the archive, in order, without duplicates, equal field by field + archive_records = read_bybit_archive_day(archives / f"{INSTRUMENT}{PILOT}.csv.gz", instrument=INSTRUMENT, day=PILOT).records + ids = gateway_ids(connection, PILOT) + assert ids == [r.trade_id for r in archive_records] and len(ids) == len(set(ids)) == len(full[PILOT]), "the pilot day" + new_file = dataset_root / f"dt={PILOT}" / "seg=000000.000" / "part-001.parquet" + rebuilt = [r for batch in scan_trade_v1_all(new_file, batch_size=1000) for r in batch] + assert len(rebuilt) == len(archive_records) + for got, want in zip(rebuilt, archive_records): + assert (got.venue, got.instrument, got.exchange_ts, got.aggressor_side, got.price, got.size, got.trade_id) == \ + (want.venue, want.instrument, want.exchange_ts, want.aggressor_side, want.price, want.size, want.trade_id) + assert got.receive_ts is None and got.sequence is None, "the rebuilt rows carry the archive's null receive_ts and sequence" + assert verify_rebuilt_day(connection, day=PILOT, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID)["passed"] + # nothing else moved: the retired incumbent is intact, the other days and the checkpoint are byte-identical + assert old_file.read_bytes() == old_bytes + assert {key: v for key, v in states(connection).items() if not key.startswith(f"dt={PILOT}")} == other_days_before + assert {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in frozen_files_paths(dataset_root, PILOT)} == frozen_files + assert checkpoint.read_bytes() == saved + for day in ("2026-10-18", "2026-10-19"): + assert gateway_ids(connection, day) is not None and len(gateway_ids(connection, day)) == len(full[day][::7]) + + # 7. the ordinary importer still refuses the occupied day, a retired one included, and the variant refuses what is not retired + try: + import_bybit_archive_day(connection, instrument=INSTRUMENT, day=PILOT, archive_path=archives / f"{INSTRUMENT}{PILOT}.csv.gz", + storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF) + except ArchiveImportRefused as exc: + assert exc.phase == "CATALOG" + else: + raise AssertionError("the ordinary importer must refuse an occupied day") + for day in ("2026-10-18",): # valid legacy day: the variant refuses + try: + import_bybit_archive_day_after_retirement(connection, instrument=INSTRUMENT, day=day, archive_path=archives / f"{INSTRUMENT}{day}.csv.gz", + storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF, expected_source_sha256=sha(archives / f"{INSTRUMENT}{day}.csv.gz")) + except ArchiveImportRefused as exc: + assert exc.phase == "CATALOG" + else: + raise AssertionError("the variant must refuse a day whose legacy revision is valid") + try: # and a rebuilt day, again + import_bybit_archive_day_after_retirement(connection, instrument=INSTRUMENT, day=PILOT, archive_path=archives / f"{INSTRUMENT}{PILOT}.csv.gz", + storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF, expected_source_sha256=sha(archives / f"{INSTRUMENT}{PILOT}.csv.gz")) + except ArchiveImportRefused as exc: + assert exc.phase == "CATALOG" + else: + raise AssertionError("the variant must refuse a day that is already rebuilt") + + # 8. restore: refused over a rebuilt day; for a day retired and not rebuilt, a superseding pass returns it to valid + try: + restore_retired_day(connection, day=PILOT, storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF) + except RebuildRefused as exc: + assert exc.phase == "RESTORE" + else: + raise AssertionError("restoring over a rebuilt day must be refused") + plan_18 = make_plan(["2026-10-18"]) + with mock.patch.object(rebuild, "import_bybit_archive_day_after_retirement", side_effect=ArchiveImportRefused("S13", "probe")): + result = run(plan_18) + assert result["days"][0]["outcome"] == "import_refused" and states(connection)["dt=2026-10-18"] == ["invalid"] + restored = restore_retired_day(connection, day="2026-10-18", storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF) + assert restored.lifecycle.resulting_state == "valid" and states(connection)["dt=2026-10-18"] == ["valid"] + assert len(gateway_ids(connection, "2026-10-18")) == len(full["2026-10-18"][::7]) + retry = run(make_plan(["2026-10-18"])) # and the day can still be rebuilt afterwards + assert retry["days"][0]["outcome"] == "rebuilt", retry + assert gateway_ids(connection, "2026-10-18") == [r[1] for r in full["2026-10-18"]] + # 9. conservation across days: the incumbent holds records of a neighbouring day (the 529 rows of the evidence) + from quant_platform.data.models import TradeRecord + from quant_platform.source_adapters.bybit import materialize_bybit_trade_v1 + + def crafted(name: str, rows_of: list) -> Path: + path = base / name + records = sorted((TradeRecord("bybit", INSTRUMENT, Instant(ms * 1_000_000), price, size, side.lower(), None, tid, None) + for ms, tid, side, price, size in rows_of), key=lambda r: (r.exchange_ts.epoch_ns, r.trade_id)) + materialize_bybit_trade_v1(path, tuple(records), dataset_identity=bybit_archive_dataset_identity(INSTRUMENT)) + return path + + far = "2026-10-30" + write_archive(archives, far, world(far)) + mixed = full[PILOT][::7][:3] + full["2026-10-19"][:2] + refusals, summary, outside = rebuild._conservation(crafted("mixed.parquet", mixed), PILOT, archives) + assert refusals == [] and summary["days"] == {PILOT: 3, "2026-10-19": 2}, (refusals, summary) + assert outside == {"2026-10-19": {r[1] for r in full["2026-10-19"][:2]}}, outside + assert summary["archives"] == {d: sha(archives / f"{INSTRUMENT}{d}.csv.gz") for d in (PILOT, "2026-10-19")}, summary + + # whether those records stay served is the plan's question: a valid partition of their day must hold them (a valid partition + # of the day is not enough: the later, partial batch of a day does not hold what the batch before it did) + def held(owner, ids): + return rebuild._held_by_valid(connection, dataset_root, owner, ids) + + assert held("2026-10-19", {r[1] for r in full["2026-10-19"][::7]}) + assert not held("2026-10-19", {full["2026-10-19"][1][1]}), "a trade the partial revision does not hold" + assert not held("2026-10-19", {full["2026-10-19"][0][1], full["2026-10-19"][1][1]}), "one held, one not" + assert not held(far, {world(far)[0][1]}), "a day without any partition" + refusals, _, outside = rebuild._conservation(crafted("far.parquet", full[PILOT][:2] + world(far)[:1]), PILOT, archives) + assert refusals == [] and set(outside) == {far}, (refusals, outside) + (archives / f"{INSTRUMENT}{far}.csv.gz").rename(archives / "gone") + refusals, _, _ = rebuild._conservation(crafted("far.parquet", full[PILOT][:2] + world(far)[:1]), PILOT, archives) + assert len(refusals) == 1 and "is missing" in refusals[0], refusals + (archives / "gone").rename(archives / f"{INSTRUMENT}{far}.csv.gz") + bad = world(far)[:1] + bad = [(bad[0][0], bad[0][1], bad[0][2], "1.0", bad[0][4])] + refusals, _, _ = rebuild._conservation(crafted("bad.parquet", full[PILOT][:2] + bad), PILOT, archives) + assert len(refusals) == 1 and "differ from the archive" in refusals[0], refusals + nameless = crafted("ok.parquet", full[PILOT][:2]) + assert rebuild._conservation(nameless, PILOT, archives)[0] == [] + # 10. a neighbouring day whose legacy coverage crossed midnight: until its own retirement it overlaps the rebuilt day, which + # the gateway refuses to read strictly; after its own rebuild both days read correctly + neighbour = "2026-10-21" + crossing_path = write_archive(staging, neighbour, full[neighbour][::7]) + crossing_start = datetime.fromisoformat(neighbour).replace(tzinfo=timezone.utc) - timedelta(minutes=1) + dataset_identity = bybit_archive_dataset_identity(INSTRUMENT) + importer._import_locked( + connection, identity=dataset_identity, instrument=INSTRUMENT, day=neighbour, start=crossing_start, + partition_key=f"dt={neighbour}", archive_path=crossing_path, storage_root_id=STORAGE_ROOT_ID, code_ref="legacy-commit", + dataset_root=dataset_root) + crossing_path.unlink() + assert states(connection)[f"dt={neighbour}"] == ["valid"] + verdict = verify_rebuilt_day(connection, day=PILOT, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID) + assert not verdict["passed"] and any("strict read" in problem for problem in verdict["problems"]), verdict + result = run(make_plan([neighbour])) + assert result["days"][0]["outcome"] == "rebuilt", result + for day in (PILOT, neighbour): + assert gateway_ids(connection, day) == [r[1] for r in full[day]], day + # a gap on another day does not refuse this one; an invalid revision this operation did not retire is refused; the + # incumbent's durable manifest must be on disk + other_gap = Instant((day_ms("2026-10-19") + 3_600_000) * 1_000_000) + record_explicit_long_gap( + storage_root=storage, producer="gap-probe", code_ref="gap", detected_at=Instant(other_gap.epoch_ns + 5 * 10**9), + interval=LongGapInterval(start_key=TradeKeyBoundary(venue="bybit", instrument=INSTRUMENT, exchange_ts=other_gap, trade_id="y"), + detected_at=Instant(other_gap.epoch_ns + 5 * 10**9), reason="probe", recent_window_records=None, + buffered_ws_records=None), instrument=INSTRUMENT) + assert make_plan([PILOT])["days"][0]["refusals"] == [], "a gap on another day must not refuse this day" + refused_plan(["2026-10-19"], "open gap record") + for gap_file in dataset_root.glob("coverage-manifest-long-gap-*.json"): + gap_file.unlink() + sql(connection, "UPDATE catalog.partitions SET state='invalid' WHERE partition_key='dt=2026-10-19'") + refused_plan(["2026-10-19"], "was not retired by this operation") + sql(connection, "UPDATE catalog.partitions SET state='valid' WHERE partition_key='dt=2026-10-19'") + manifest = dataset_root / "dt=2026-10-19" / "partition-manifest.json" + manifest.rename(manifest.with_name("moved.json")) + refused_plan(["2026-10-19"], "partition manifest") + manifest.with_name("moved.json").rename(manifest) + assert make_plan(["2026-10-19"])["days"][0]["action"] == "retire+import" + # the coverage manifest is checked by the plan, not first by the retire: unreadable, or not the one the reports certified + coverage_file = dataset_root / "dt=2026-10-19" / "coverage-manifest.json" + coverage_raw = coverage_file.read_bytes() + coverage_file.write_bytes(coverage_raw + b"\n") + refused_plan(["2026-10-19"], "not the one its quality reports certified") + coverage_file.write_bytes(b"{not json") + refused_plan(["2026-10-19"], "do not load") + coverage_file.write_bytes(coverage_raw) + # two reports that certify different coverage sets: the plan cannot tell which one is the incumbent's + sql(connection, "INSERT INTO catalog.quality_reports (partition_id, check_suite, status, metrics) SELECT q.partition_id, q.check_suite, 'pass', " + "jsonb_build_object('certification_profile', q.metrics->>'certification_profile', " + "'coverage_manifest_sha256', jsonb_build_array(repeat('0', 64)), 'coverage_manifest_ids', jsonb_build_array('other')) " + "FROM catalog.quality_reports q JOIN catalog.partitions p ON p.partition_id = q.partition_id " + "WHERE p.partition_key='dt=2026-10-19' LIMIT 1") + try: + refused_plan(["2026-10-19"], "certify 2 coverage manifest sets") + finally: + sql(connection, "DELETE FROM catalog.quality_reports WHERE metrics->'coverage_manifest_ids' = '[\"other\"]'::jsonb") + incumbent_19 = make_plan(["2026-10-19"])["days"][0]["incumbent"] + assert incumbent_19["coverage_ids"] == ["bybit-archive-btcusdt-2026-10-19-v1"] and incumbent_19["assertion_ids"], incumbent_19 + + # the verification checks the gateway's answer for count, order and duplicates, not only the Parquet + class Shuffled: + def __init__(self, records): + self.records = records + + def read(self, request): + return SimpleNamespace(records=self.records(request)) + + def verify_with(transform): + real = DataGateway(Catalog(connection=connection), ordering_providers=(BYBIT_ORDERING_PROVIDER,)) + with mock.patch.object(rebuild, "DataGateway", lambda *a, **k: Shuffled(lambda request: transform(list(real.read(request).records)))): + return verify_rebuilt_day(connection, day=PILOT, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID) + + assert verify_with(lambda records: records)["passed"] + for transform, message in ((lambda r: r[:-1], "returned"), (lambda r: r + r[:1], "more than once"), + (lambda r: list(reversed(r)), "order"), (lambda r: r[1:] + r[:1], "order")): + verdict = verify_with(transform) + assert not verdict["passed"] and any(message in problem for problem in verdict["problems"]), (message, verdict) + + # more refusals on a day that is still legacy: a key to create that exists, a gap manifest that cannot be read, the variant's own + # guard, the verification's own check of the Parquet, and a restore of a day that was never retired + (legacy_id,) = sql(connection, "SELECT partition_id::text FROM catalog.partitions WHERE partition_key='dt=2026-10-19'")[0] + copy_row = ("INSERT INTO catalog.partitions (dataset_id, partition_key, revision, storage_root_id, rel_path, ts_start, ts_end, " + "row_count, byte_size, content_sha256, state, manifest_sha256, created_at, closed_at, producer, code_ref) " + "SELECT dataset_id, %s, 1, storage_root_id, replace(rel_path, %s, %s), ts_start, ts_end, row_count, byte_size, " + "content_sha256, %s, manifest_sha256, created_at, closed_at, producer, code_ref FROM catalog.partitions " + "WHERE partition_id=%s") + new_key = "dt=2026-10-19/seg=000000.000" + for forced, reason in (("closed", "exists in the state"), ("valid", "two valid partitions")): + sql(connection, copy_row, (new_key, "dt=2026-10-19/", f"{new_key}/", forced, legacy_id)) + try: + refused_plan(["2026-10-19"], reason) + finally: + sql(connection, "DELETE FROM catalog.partitions WHERE partition_key=%s", (new_key,)) + sql(connection, "UPDATE catalog.partitions SET state='invalid' WHERE partition_id=%s", (legacy_id,)) + sql(connection, copy_row, ("dt=2026-10-19/seg=120000.000", "dt=2026-10-19/", "dt=2026-10-19/seg=120000.000/", "valid", legacy_id)) + try: + import_bybit_archive_day_after_retirement(connection, instrument=INSTRUMENT, day="2026-10-19", + archive_path=archives / f"{INSTRUMENT}2026-10-19.csv.gz", + storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF, expected_source_sha256=sha(archives / f"{INSTRUMENT}2026-10-19.csv.gz")) + except ArchiveImportRefused as exc: + assert exc.phase == "CATALOG" and "seg=120000.000" in str(exc), exc + else: + raise AssertionError("the variant must refuse a retired day that has another partition under it") + finally: + sql(connection, "DELETE FROM catalog.partitions WHERE partition_key='dt=2026-10-19/seg=120000.000'") + sql(connection, "UPDATE catalog.partitions SET state='valid' WHERE partition_id=%s", (legacy_id,)) + try: + restore_retired_day(connection, day="2026-10-19", storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF) + except RebuildRefused as exc: + assert exc.phase == "RESTORE" and "must be invalid" in str(exc), exc + else: + raise AssertionError("a valid day was never retired: there is nothing to restore") + bad_gap = dataset_root / "coverage-manifest-long-gap-unreadable.json" + bad_gap.write_text(json.dumps({"coverage_id": "long-gap-unreadable", "assertions": [{ + "assertion_id": "a", "status": "known_gap", "start": "2026-10-19T00:00:00Z", "end": "2026-10-19T00:00:01Z", + "evidence": [{"kind": "transport_interruption", "detail": "not json"}]}]}), encoding="utf-8") + try: + refused_plan(["2026-10-19"], "cannot be read") + finally: + bad_gap.unlink() + real = rebuild.compare_archive_day_with_parquet + + def not_identical(*args, **kwargs): + return {**real(*args, **kwargs), "identical": False} + + with mock.patch.object(rebuild, "compare_archive_day_with_parquet", not_identical): + verdict = verify_rebuilt_day(connection, day=PILOT, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID) + assert not verdict["passed"] and any("not identical" in problem for problem in verdict["problems"]), verdict + coverage_ids = {} + for key_dir, label in ((f"dt={PILOT}/seg=000000.000", "rebuilt"), ("dt=2026-10-19", "legacy")): + coverage_ids[label] = json.loads((dataset_root / key_dir / "coverage-manifest.json").read_text(encoding="utf-8"))["coverage_id"] + assert coverage_ids == {"rebuilt": f"bybit-archive-btcusdt-{PILOT}-rebuild-v1", "legacy": "bybit-archive-btcusdt-2026-10-19-v1"}, coverage_ids + + # 11. the executor does one day at a time and stops at the first that fails: the next day is not attempted + # a day published by the live publisher before the slices: ``part-`` and its manifests in the dataset root + old_dir = dataset_root / "dt=2026-10-08" + (old_dir / "part-001.parquet").rename(old_dir / "part-235942.parquet") + (old_dir / "partition-manifest.json").rename(dataset_root / "partition-manifest-235942.json") + (old_dir / "coverage-manifest.json").rename(dataset_root / "coverage-manifest-235942.json") + sql(connection, "UPDATE catalog.partitions SET rel_path=%s WHERE partition_key='dt=2026-10-08'", ("dt=2026-10-08/part-235942.parquet",)) + two = make_plan(["2026-10-08", "2026-10-09"]) + assert two["days"][0]["incumbent"]["partition_manifest_file"] == "partition-manifest-235942.json", two["days"][0]["incumbent"] + assert two["days"][0]["incumbent"]["coverage_manifest_file"] == "coverage-manifest-235942.json" + assert two["days"][0]["action"] == "retire+import" and not two["days"][0]["refusals"], two["days"][0] + # the manifest inside still names part-001, so the layout is only good for the plan: put the day back before the retire + (old_dir / "part-235942.parquet").rename(old_dir / "part-001.parquet") + (dataset_root / "partition-manifest-235942.json").rename(old_dir / "partition-manifest.json") + (dataset_root / "coverage-manifest-235942.json").rename(old_dir / "coverage-manifest.json") + sql(connection, "UPDATE catalog.partitions SET rel_path=%s WHERE partition_key='dt=2026-10-08'", ("dt=2026-10-08/part-001.parquet",)) + two = make_plan(["2026-10-08", "2026-10-09"]) + assert [d["action"] for d in two["days"]] == ["retire+import", "retire+import"], [d["refusals"] for d in two["days"]] + with mock.patch.object(rebuild, "import_bybit_archive_day_after_retirement", side_effect=ArchiveImportRefused("S13", "probe")): + stopped = run(two) + assert [d["outcome"] for d in stopped["days"]] == ["import_refused"], stopped + assert states(connection)["dt=2026-10-09"] == ["valid"], "the second day must not have been touched" + assert states(connection)["dt=2026-10-08"] == ["invalid"] + done = run(make_plan(["2026-10-08", "2026-10-09"])) # and a new run, with the first day retired, completes both + assert [d["outcome"] for d in done["days"]] == ["rebuilt", "rebuilt"], done + + # 12. the records of a neighbouring day must stay served (the review of #531, P1). Two incumbents hold two trades of the next + # day, the shape of the live batch across midnight; the next day's own legacy revision is a later, partial batch + dataset_identity_12 = bybit_archive_dataset_identity(INSTRUMENT) + + def crossing_legacy(day: str, owner: str, rows) -> None: + path = write_archive(staging, owner, rows) + start_of = datetime.fromisoformat(day).replace(tzinfo=timezone.utc) + timedelta(hours=23, minutes=59) + importer._import_locked(connection, identity=dataset_identity_12, instrument=INSTRUMENT, day=owner, start=start_of, + partition_key=f"dt={day}", archive_path=path, storage_root_id=STORAGE_ROOT_ID, + code_ref="legacy-commit", dataset_root=dataset_root) + path.unlink() + + bare, owner_lacking, positive, owner_holding = "2026-10-14", "2026-10-15", "2026-10-16", "2026-10-17" + for day in (bare, owner_lacking, positive, owner_holding): + full[day] = world(day) + write_archive(archives, day, full[day]) + crossing_legacy(bare, owner_lacking, full[owner_lacking][:2]) + legacy(owner_lacking, subset=[full[owner_lacking][5]]) # its valid revision does not hold the two trades + crossing_legacy(positive, owner_holding, full[owner_holding][:2]) + legacy(owner_holding, subset=full[owner_holding][:2] + [full[owner_holding][5]]) # this one does + lost = {full[owner_lacking][0][1], full[owner_lacking][1][1]} + assert not rebuild._held_by_valid(connection, dataset_root, owner_lacking, lost) + refused_plan([bare], "stop being served") + sql(connection, "UPDATE catalog.partitions SET state='closed' WHERE partition_key=%s", (f"dt={owner_lacking}",)) + assert not rebuild._held_by_valid(connection, dataset_root, owner_lacking, {full[owner_lacking][5][1]}), "a closed partition serves nothing" + both = make_plan([bare, owner_lacking]) # the day that would hold them is in the plan but is refused: it contributes nothing + assert [d["action"] for d in both["days"]] == ["refused", "refused"], [d["refusals"] for d in both["days"]] + assert any("refused in this plan" in r for r in both["days"][0]["refusals"]), both["days"][0]["refusals"] + sql(connection, "UPDATE catalog.partitions SET state='valid' WHERE partition_key=%s", (f"dt={owner_lacking}",)) + ok = make_plan([bare, owner_lacking]) # the day is rebuilt by the same plan: it serves them from its own archive file + assert [d["action"] for d in ok["days"]] == ["retire+import", "retire+import"], [d["refusals"] for d in ok["days"]] + result = run(ok) + assert [d["outcome"] for d in result["days"]] == ["rebuilt", "rebuilt"], result + assert lost <= set(gateway_ids(connection, owner_lacking)) and gateway_ids(connection, bare) == [r[1] for r in full[bare]] + held_plan = make_plan([positive]) # a valid partition of the other day holds both: nothing is lost + assert held_plan["days"][0]["action"] == "retire+import", held_plan["days"][0]["refusals"] + assert held_plan["days"][0]["conservation"]["outside_held"] == {owner_holding: True} + kept = {full[owner_holding][0][1], full[owner_holding][1][1]} + sql(connection, "UPDATE catalog.partitions SET state='closed' WHERE partition_key=%s", (f"dt={owner_holding}",)) + changed_plan = make_plan([positive]) # a change from outside is still a change of the plan + assert changed_plan["days"][0]["action"] == "refused" and changed_plan["digest"] != held_plan["digest"] + sql(connection, "UPDATE catalog.partitions SET state='valid' WHERE partition_key=%s", (f"dt={owner_holding}",)) + assert make_plan([positive])["digest"] == held_plan["digest"] + result = run(held_plan) + assert result["days"][0]["outcome"] == "rebuilt", result + assert kept <= set(gateway_ids(connection, owner_holding)) + + # 12b. a plan of two linked days recovers with the same plan after a crash before the verification of the second (A2.5): the + # rebuild itself turns "the next day holds the records" from false to true, which is progress, not a change of the plan + first_day, second_day = "2026-10-06", "2026-10-07" + for day in (first_day, second_day): + full[day] = world(day) + write_archive(archives, day, full[day]) + crossing_legacy(first_day, second_day, full[second_day][:2]) + legacy(second_day, subset=[full[second_day][5]]) + linked = make_plan([first_day, second_day]) + assert [d["action"] for d in linked["days"]] == ["retire+import", "retire+import"], [d["refusals"] for d in linked["days"]] + assert linked["days"][0]["conservation"]["outside_held"] == {second_day: False} + real_verify = rebuild.verify_rebuilt_day + + def crash_on_second(connection_, *, day, **kwargs): + if day == second_day: + raise RuntimeError("crash before the verification of the second day") + return real_verify(connection_, day=day, **kwargs) + + with mock.patch.object(rebuild, "verify_rebuilt_day", crash_on_second): + try: + run(linked) + except RuntimeError: + pass + else: + raise AssertionError("the crash was not raised") + assert states(connection)[f"dt={second_day}/seg=000000.000"] == ["valid"] and states(connection)[f"dt={second_day}"] == ["invalid"] + after_crash = make_plan([first_day, second_day]) + assert [d["action"] for d in after_crash["days"]] == ["verify", "verify"] + assert after_crash["days"][0]["conservation"]["outside_held"] == {second_day: True} # the progress the plan expected + assert after_crash["digest"] == linked["digest"], "the progress of the plan must not change its digest" + result = run(linked) # the same plan, the same digest + assert [d["outcome"] for d in result["days"]] == ["verified", "verified"], result + assert gateway_ids(connection, first_day) == [r[1] for r in full[first_day]] + assert gateway_ids(connection, second_day) == [r[1] for r in full[second_day]] + + # 12c. an external dependency lost between the retire and the retry: the other day, not in the plan, is retired by something + # else after the first day was retired and before it was imported. The old digest does not authorize the retry + ext_a, ext_b = "2026-10-04", "2026-10-05" + for day in (ext_a, ext_b): + full[day] = world(day) + write_archive(archives, day, full[day]) + crossing_legacy(ext_a, ext_b, full[ext_b][:2]) + legacy(ext_b, subset=full[ext_b][:2] + [full[ext_b][5]]) # B holds the two trades, so A alone is planned + external = make_plan([ext_a]) + assert external["days"][0]["action"] == "retire+import" and external["days"][0]["conservation"]["outside_held"] == {ext_b: True} + with mock.patch.object(rebuild, "import_bybit_archive_day_after_retirement", side_effect=RuntimeError("crash after the retire")): + try: + run(external) + except RuntimeError: + pass + else: + raise AssertionError("the crash was not raised") + assert states(connection)[f"dt={ext_a}"] == ["invalid"] and f"dt={ext_a}/seg=000000.000" not in states(connection) + assert make_plan([ext_a])["digest"] == external["digest"] and make_plan([ext_a])["days"][0]["action"] == "import" + sql(connection, "UPDATE catalog.partitions SET state='invalid' WHERE partition_key=%s", (f"dt={ext_b}",)) # B retired by another operation + lost_plan = make_plan([ext_a]) + assert lost_plan["days"][0]["action"] == "refused" and lost_plan["digest"] != external["digest"], lost_plan["days"][0] + before_stale = snapshot(connection, storage, checkpoint) + try: + run(external) + except RebuildRefused as exc: + assert exc.phase == "STALE", exc + else: + raise AssertionError("the plan approved with B holding the records must not complete once B is retired") + assert snapshot(connection, storage, checkpoint) == before_stale, "the refused retry must change nothing" + sql(connection, "UPDATE catalog.partitions SET state='valid' WHERE partition_key=%s", (f"dt={ext_b}",)) + assert make_plan([ext_a])["digest"] == external["digest"] + result = run(external) # B holds the records again: the same plan completes + assert result["days"][0]["outcome"] == "rebuilt", result + + # 13. restore and import share the day's guard (P1): a restore cannot slip in between the import's check and its publication + retired_day = "2026-10-12" + full[retired_day] = world(retired_day) + write_archive(archives, retired_day, full[retired_day]) + legacy(retired_day) + with mock.patch.object(rebuild, "import_bybit_archive_day_after_retirement", side_effect=ArchiveImportRefused("S13", "probe")): + assert run(make_plan([retired_day]))["days"][0]["outcome"] == "import_refused" + assert states(connection)[f"dt={retired_day}"] == ["invalid"] + with importer.day_lock(dataset_root, retired_day): + try: + restore_retired_day(connection, day=retired_day, storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF) + except RebuildRefused as exc: + assert exc.phase == "RESTORE" and "locked by an import" in str(exc), exc + else: + raise AssertionError("a restore must be refused while the import holds the day") + assert states(connection)[f"dt={retired_day}"] == ["invalid"] + real_locked, attempts = importer._import_locked, [] + + def interleaved(*args, **kwargs): # the restore arrives after the import's checks and before its publication + try: + restore_retired_day(connection, day=retired_day, storage_root_id=STORAGE_ROOT_ID, code_ref=CODE_REF) + except RebuildRefused as exc: + attempts.append(str(exc)) + return real_locked(*args, **kwargs) + + with mock.patch.object(importer, "_import_locked", interleaved): + result = run(make_plan([retired_day])) + assert result["days"][0]["outcome"] == "rebuilt", result + assert len(attempts) == 1 and "locked by an import" in attempts[0], attempts + assert states(connection)[f"dt={retired_day}"] == ["invalid"] + assert states(connection)[f"dt={retired_day}/seg=000000.000"] == ["valid"] + assert gateway_ids(connection, retired_day) == [r[1] for r in full[retired_day]] # one valid partition, a strict read works + + # 14. the imported bytes are the approved ones (P1): a file replaced after the plan is refused, and so is a verification of + # another file + swapped_day = "2026-10-11" + full[swapped_day] = world(swapped_day) + archive_file = write_archive(archives, swapped_day, full[swapped_day]) + approved = archive_file.read_bytes() + approved_sha = hashlib.sha256(approved).hexdigest() + legacy(swapped_day) + swap_plan = make_plan([swapped_day]) + real_import = rebuild.import_bybit_archive_day_after_retirement + + def replace_archive(): + write_archive(archives, swapped_day, [(ms, i.replace(swapped_day, "replaced"), s, p, z) for ms, i, s, p, z in full[swapped_day]]) + + def swapped(*args, **kwargs): + replace_archive() + return real_import(*args, **kwargs) + + with mock.patch.object(rebuild, "import_bybit_archive_day_after_retirement", swapped): + result = run(swap_plan) + outcome = result["days"][0] + assert outcome["outcome"] == "import_refused" and outcome["phase"] == "SOURCE" and "not the approved one" in outcome["detail"], outcome + assert states(connection)[f"dt={swapped_day}"] == ["invalid"] and f"dt={swapped_day}/seg=000000.000" not in states(connection) + archive_file.write_bytes(approved) + result = run(make_plan([swapped_day])) # the retired day resumes with the approved file + assert result["days"][0]["outcome"] == "rebuilt" and result["days"][0]["verification"]["archive_sha256"] == approved_sha + replace_archive() + verdict = verify_rebuilt_day(connection, day=swapped_day, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID, + expected_archive_sha256=approved_sha) + assert not verdict["passed"] and any("not to the approved" in problem for problem in verdict["problems"]), verdict + archive_file.write_bytes(approved) + assert verify_rebuilt_day(connection, day=swapped_day, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID, + expected_archive_sha256=approved_sha)["passed"] + # and a file replaced between the import and the executor's own verification is a failed verification, not a pass + late_day = "2026-10-10" + full[late_day] = world(late_day) + late_file = write_archive(archives, late_day, full[late_day]) + late_bytes = late_file.read_bytes() + legacy(late_day) + + def late_swap(*args, **kwargs): + report = real_import(*args, **kwargs) + write_archive(archives, late_day, [(ms, i.replace(late_day, "replaced"), s, p, z) for ms, i, s, p, z in full[late_day]]) + return report + + with mock.patch.object(rebuild, "import_bybit_archive_day_after_retirement", late_swap): + result = run(make_plan([late_day])) + outcome = result["days"][0] + assert outcome["outcome"] == "verify_failed" and any("not to the approved" in x for x in outcome["verification"]["problems"]), outcome + late_file.write_bytes(late_bytes) + assert verify_rebuilt_day(connection, day=late_day, archive_dir=archives, storage_root_id=STORAGE_ROOT_ID)["passed"] + print("POSTGRESQL LEGACY DAY REBUILD GATE PASSED") + return 0 + + +def frozen_files_paths(dataset_root: Path, pilot: str): + return [p for p in dataset_root.rglob("*") if p.is_file() and f"dt={pilot}" not in p.parts[-3:] and not p.name.startswith(".")] + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_bybit_legacy_day_rebuild_v1.py b/tests/test_bybit_legacy_day_rebuild_v1.py new file mode 100644 index 0000000..329b309 --- /dev/null +++ b/tests/test_bybit_legacy_day_rebuild_v1.py @@ -0,0 +1,268 @@ +"""DG-R R02: the pure rules of the legacy-day rebuild (the catalog behaviour is the PostgreSQL gate).""" + +from __future__ import annotations + +from copy import deepcopy +import io +from contextlib import redirect_stderr +import os +from pathlib import Path +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +sys.path.insert(0, str(ROOT / "tools")) + +from quant_platform.application import bybit_legacy_day_rebuild as rebuild # noqa: E402 +from quant_platform.application.bybit_archive_import import rebuild_partition_key # noqa: E402 +from quant_platform.data import Instant # noqa: E402 + + +def record(price="100.1", size="0.5", side="buy", ts_ns=1_700_000_000_123_000_000, venue="bybit", instrument="BTCUSDT"): + return SimpleNamespace(price=price, size=size, aggressor_side=side, exchange_ts=Instant(ts_ns), venue=venue, instrument=instrument) + + +INCUMBENT = { + "partition_id": "p", "key": "dt=2026-10-20", "revision": 7, "state": "valid", "rel_path": "dt=2026-10-20/part-007.parquet", + "ts_start": "2026-10-20T00:00:00Z", "ts_end": "2026-10-21T00:00:00Z", "row_count": 10, "content_sha256": "a" * 64, + "manifest_sha256": "b" * 64, "check_suite": "suite", "certification_profile": "profile", + "partition_manifest_file": "dt=2026-10-20/partition-manifest-007.json", "coverage_manifest_file": "dt=2026-10-20/coverage-manifest-007.json", + "coverage_manifest_sha256": "c" * 64, +} +ENTRY = { + "day": "2026-10-20", "key_to_create": "dt=2026-10-20/seg=000000.000", "action": "retire+import", "refusals": [], "incumbent": INCUMBENT, + "archive": {"file_name": "BTCUSDT2026-10-20.csv.gz", "sha256": "d" * 64, "rows": 3, "size_bytes": 9, "url": "u", "observed_at": "t"}, + "conservation": {"rows": 10, "days": {"2026-10-20": 10}, "duplicate_trade_ids": 0, "text_only_differences": 0}, +} +PLAN = {"schema": rebuild.PLAN_SCHEMA, "instrument": "BTCUSDT", "storage_root_id": "hot", "code_ref": "commit", "days": [ENTRY]} + + +class RequestTests(unittest.TestCase): + def test_the_days_are_named_never_chosen_and_bounded(self) -> None: + self.assertEqual(["2026-10-19", "2026-10-20"], rebuild._validated_days(["2026-10-19", "2026-10-20"])) + for bad in ([], ["2026-10-20", "2026-10-19"], ["2026-10-20", "2026-10-20"], ["2026-13-01"], ["20261020"], [""]): + with self.assertRaises(rebuild.RebuildRefused): + rebuild._validated_days(bad) + days = [f"2026-09-{day:02d}" for day in range(1, 31)] + ["2026-10-01", "2026-10-02"] + with self.assertRaises(rebuild.RebuildRefused): + rebuild._validated_days(days) + self.assertEqual(31, rebuild.MAX_DAYS_PER_PLAN) + + def test_only_btcusdt_and_the_fixed_key(self) -> None: + self.assertEqual("BTCUSDT", rebuild.INSTRUMENT) + self.assertEqual("dt=2026-10-20/seg=000000.000", rebuild_partition_key("2026-10-20")) + + +class ManifestNamingTests(unittest.TestCase): + def test_a_revision_names_its_manifests_by_the_suffix_of_its_artifact(self) -> None: + root = Path("/data") + self.assertEqual((root / "dt=d/partition-manifest.json", root / "dt=d/coverage-manifest.json"), + rebuild._manifest_files(root, "dt=d/part-001.parquet")) + self.assertEqual((root / "dt=d/partition-manifest-412.json", root / "dt=d/coverage-manifest-412.json"), + rebuild._manifest_files(root, "dt=d/part-412.parquet")) + + +class LegacyManifestLocationTests(unittest.TestCase): + """The live publisher before the slices (#510) wrote its manifests in the dataset root, ``HHMMSS`` without the date.""" + + def test_the_manifests_beside_the_artifact_or_in_the_dataset_root_by_the_catalog_hash(self) -> None: + import hashlib + + with tempfile.TemporaryDirectory() as holder: + root = Path(holder) + (root / "dt=d").mkdir() + rel = "dt=d/part-235942.parquet" + mine = b'{"day": "d"}' + digest = hashlib.sha256(mine).hexdigest() + # nothing on disk: the first location is named, so that the refusal can say what is missing + self.assertEqual((root / "dt=d/partition-manifest-235942.json", root / "dt=d/coverage-manifest-235942.json"), + rebuild._manifest_files(root, rel, digest)) + # the legacy layout: only the dataset root holds them + (root / "partition-manifest-235942.json").write_bytes(mine) + self.assertEqual((root / "partition-manifest-235942.json", root / "coverage-manifest-235942.json"), + rebuild._manifest_files(root, rel, digest)) + # a file of the same second of another day overwrote the root one: it is still the only one found, and the caller + # (the evidence check) refuses it because it does not hash to the catalog's + (root / "partition-manifest-235942.json").write_bytes(b'{"day": "other"}') + found = rebuild._manifest_files(root, rel, digest)[0] + self.assertEqual(root / "partition-manifest-235942.json", found) + self.assertNotEqual(digest, hashlib.sha256(found.read_bytes()).hexdigest()) + # both locations hold one: the one with the catalog's hash wins, whichever it is + (root / "dt=d/partition-manifest-235942.json").write_bytes(mine) + self.assertEqual(root / "dt=d/partition-manifest-235942.json", rebuild._manifest_files(root, rel, digest)[0]) + (root / "dt=d/partition-manifest-235942.json").write_bytes(b'{"day": "x"}') + (root / "partition-manifest-235942.json").write_bytes(mine) + self.assertEqual(root / "partition-manifest-235942.json", rebuild._manifest_files(root, rel, digest)[0]) + + +class DuplicateTradeIdTests(unittest.TestCase): + def conservation(self, *records): + with mock.patch.object(rebuild, "scan_trade_v1_all", lambda *a, **k: iter([list(records)])): + return rebuild._conservation(Path("incumbent.parquet"), "2026-10-20", Path(".")) + + def with_id(self, trade_id, **kwargs): + item = record(**kwargs) + item.trade_id = trade_id + return item + + def test_a_trade_id_twice_with_different_content_refuses_the_day(self) -> None: + refusals, summary, outside = self.conservation(self.with_id("t1", price="100.1"), self.with_id("t1", price="100.2")) + self.assertEqual(({}, {}), (summary, outside)) + self.assertEqual(1, len(refusals)) + self.assertIn("twice with different content", refusals[0]) + + def test_a_trade_id_twice_with_the_same_content_is_counted_not_hidden(self) -> None: + refusals, summary, _outside = self.conservation(self.with_id("t1"), self.with_id("t1")) + # the archive file of the day is absent in this directory, so the day still refuses; the duplicate is counted + self.assertEqual(1, summary["duplicate_trade_ids"]) + self.assertEqual(1, summary["rows"]) + self.assertFalse(any("twice" in item for item in refusals)) + + +def dependent(day, depends, action="retire+import"): + """A plan entry whose incumbent holds records of other days; ``depends`` maps each such day to whether a valid partition holds them.""" + + return {"day": day, "action": action, "refusals": [], "conservation": {"days": {d: 2 for d in depends}, "outside_held": dict(depends)}} + + +class DependencyTests(unittest.TestCase): + """The records of another day must stay served: held by a valid partition there, or that day rebuilt by this very plan.""" + + def resolve(self, *entries): + entries = list(entries) + rebuild._resolve_dependencies(entries) + return {e["day"]: e["action"] for e in entries} + + def test_records_held_by_a_valid_partition_of_their_day_stay_served(self) -> None: + self.assertEqual({"a": "retire+import"}, self.resolve(dependent("a", {"b": True}))) + + def test_records_held_nowhere_refuse_the_day_before_the_retire(self) -> None: + entry = dependent("a", {"b": False}) + self.assertEqual({"a": "refused"}, self.resolve(entry)) + self.assertIn("they would stop being served", entry["refusals"][0]) + self.assertIn("not in this plan", entry["refusals"][0]) + + def test_a_day_of_the_plan_serves_them_only_if_it_is_not_refused(self) -> None: + self.assertEqual({"a": "retire+import", "b": "retire+import"}, self.resolve(dependent("a", {"b": False}), dependent("b", {}))) + refused = dependent("b", {}, action="refused") + entry = dependent("a", {"b": False}) + self.assertEqual({"a": "refused", "b": "refused"}, self.resolve(entry, refused)) + self.assertIn("refused in this plan", entry["refusals"][0]) + # a refused day changes nothing, so what its valid partition holds is still served + self.assertEqual({"a": "retire+import", "b": "refused"}, self.resolve(dependent("a", {"b": True}), dependent("b", {}, action="refused"))) + + def test_a_refusal_propagates_along_the_chain(self) -> None: + a, b = dependent("a", {"b": False}), dependent("b", {"c": False}) + self.assertEqual({"a": "refused", "b": "refused"}, self.resolve(a, b)) + + def test_a_retry_after_a_crash_is_judged_again(self) -> None: + # the incumbent is retired already (a retry): the loss of an external dependency is a refusal, before any further change + for action in ("import", "verify"): + entry = dependent("a", {"b": False}, action=action) + self.assertEqual({"a": "refused"}, self.resolve(entry), action) + self.assertIn("they would stop being served", entry["refusals"][0]) + # the progress of the days of the plan is allowed: the other day is rebuilt (or being rebuilt) by this plan + self.assertEqual({"a": "verify", "b": "import"}, self.resolve(dependent("a", {"b": True}, action="verify"), dependent("b", {}, action="import"))) + self.assertEqual({"a": "import", "b": "verify"}, self.resolve(dependent("a", {"b": False}, action="import"), dependent("b", {}, action="verify"))) + + +class DifferenceTests(unittest.TestCase): + def test_a_value_difference_is_a_difference_and_a_trailing_zero_is_not(self) -> None: + self.assertEqual(([], False), rebuild._differences(record(), record())) + self.assertEqual(([], True), rebuild._differences(record(price="100.10"), record(price="100.1"))) + self.assertEqual(([], True), rebuild._differences(record(size="0.50"), record(size="0.5"))) + for kwargs, name in (({"price": "100.2"}, "price_value"), ({"size": "0.6"}, "size_value"), ({"side": "sell"}, "aggressor_side"), + ({"venue": "x"}, "venue"), ({"instrument": "ETHUSDT"}, "instrument")): + self.assertEqual(([name], False), rebuild._differences(record(), record(**kwargs)), name) + + def test_the_exchange_time_is_compared_at_the_millisecond_of_the_archive(self) -> None: + archive = record(ts_ns=1_700_000_000_123_000_000) + self.assertEqual(([], False), rebuild._differences(archive, record(ts_ns=1_700_000_000_123_456_789))) # the live row is truncated + self.assertEqual((["exchange_ts_ms"], False), rebuild._differences(archive, record(ts_ns=1_700_000_000_124_000_000))) + + +class DigestTests(unittest.TestCase): + def digest(self, plan) -> str: + return rebuild._digest(plan) + + def test_the_digest_binds_what_the_operation_depends_on(self) -> None: + base = self.digest(PLAN) + changes = { + "code_ref": lambda p: p.update(code_ref="other"), + "storage_root": lambda p: p.update(storage_root_id="cold"), + "archive hash": lambda p: p["days"][0]["archive"].update(sha256="e" * 64), + "archive observed": lambda p: p["days"][0]["archive"].update(observed_at="later"), + "incumbent hash": lambda p: p["days"][0]["incumbent"].update(content_sha256="f" * 64), + "incumbent partition": lambda p: p["days"][0]["incumbent"].update(partition_id="q"), + "incumbent revision": lambda p: p["days"][0]["incumbent"].update(revision=8), + "incumbent coverage": lambda p: p["days"][0]["incumbent"].update(coverage_manifest_sha256="0" * 64), + "incumbent coverage ids": lambda p: p["days"][0]["incumbent"].update(coverage_ids=["c1"]), + "incumbent assertion ids": lambda p: p["days"][0]["incumbent"].update(assertion_ids=["a1"]), + "conservation": lambda p: p["days"][0]["conservation"].update(rows=11), + "neighbour archive": lambda p: p["days"][0]["conservation"].update(archives={"2026-10-19": "e" * 64}), + "refusals": lambda p: p["days"][0].update(refusals=["not closed"]), + "key": lambda p: p["days"][0].update(key_to_create="dt=2026-10-20/seg=000001.000"), + "days": lambda p: p["days"].append(deepcopy(p["days"][0]) | {"day": "2026-10-21"}), + } + for name, change in changes.items(): + changed = deepcopy(PLAN) + change(changed) + self.assertNotEqual(base, self.digest(changed), name) + + def test_progress_is_not_part_of_the_digest(self) -> None: + base = self.digest(PLAN) + for change in (lambda p: p["days"][0]["conservation"].update(outside_held={"2026-10-19": True}), + lambda p: p["days"][0].update(action="import"), lambda p: p["days"][0]["incumbent"].update(state="invalid"), + lambda p: p["days"][0].update(created={"partition_id": "n", "state": "valid"}, action="verify"), + lambda p: p.update(digest="anything")): + moved = deepcopy(PLAN) + change(moved) + self.assertEqual(base, self.digest(moved)) + + +class CommandLineTests(unittest.TestCase): + def run_cli(self, argv, environment=None): + import rebuild_bybit_legacy_days as tool + + with mock.patch.dict(os.environ, environment or {}, clear=False), redirect_stderr(io.StringIO()) as error: + with self.assertRaises(SystemExit) as raised: + tool.main(argv) + return raised.exception.code, error.getvalue() + + def test_a_missing_dsn_variable_and_an_existing_plan_file_are_usage_errors(self) -> None: + plan_args = ["plan", "--days", "2026-10-20", "--archive-dir", ".", "--checkpoint-path", "c.json", "--code-ref", "x"] + os.environ.pop("REBUILD_TEST_DSN", None) + code, message = self.run_cli(["--dsn-env", "REBUILD_TEST_DSN", *plan_args, "--out", "plan.json"]) + self.assertEqual(2, code) + self.assertIn("REBUILD_TEST_DSN", message) + with tempfile.TemporaryDirectory() as holder: + existing = Path(holder) / "plan.json" + existing.write_text("{}") + code, message = self.run_cli(["--dsn-env", "REBUILD_TEST_DSN", *plan_args, "--out", str(existing)], {"REBUILD_TEST_DSN": "dbname=x"}) + self.assertEqual(2, code) + self.assertIn("never overwritten", message) + + def test_the_dsn_is_never_taken_from_the_command_line(self) -> None: + code, message = self.run_cli(["--dsn-env", "dbname=x password=y", "verify", "--days", "2026-10-20", "--archive-dir", "."]) + self.assertEqual(2, code) + self.assertIn("not a connection string", message) + + +class RunbookTests(unittest.TestCase): + def test_the_runbook_documents_the_four_commands_the_refusals_and_the_way_back(self) -> None: + text = (ROOT / "docs" / "engineering" / "BYBIT_ARCHIVE_IMPORT_RUNBOOK.md").read_text(encoding="utf-8") + section = " ".join(text.split("## 6. Rebuild damaged legacy live days", 1)[1].split()) + for needed in ("tools/rebuild_bybit_legacy_days.py", " plan ", " execute ", " verify ", " restore ", "--digest", "STALE", + "dt=/seg=000000.000", "legacy_publication_incomplete_day", "not closed in UTC", "conservation", + "no partial acceptance", "never a `--force`", "does not run itself, choose days, delete", "Start with `2026-10-20`", + "stops at the first day that fails"): + self.assertIn(needed, section, needed) + self.assertTrue((ROOT / "tools" / "rebuild_bybit_legacy_days.py").is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_canonical_v1.py b/tests/test_canonical_v1.py index bccea42..2cf785d 100644 --- a/tests/test_canonical_v1.py +++ b/tests/test_canonical_v1.py @@ -130,6 +130,11 @@ def test_each_migrated_site_preserves_its_argument_profile_and_nan_policy(self): "ordinal": 1, "scope": "partition_identity_text", "argument_ast": ast.dump(ast.parse("identity.stable_dict()", mode="eval").body, include_attributes=False), "parameters": {"profile": "sorted-compact-ascii-v1", "allow_nan": False}, + }, { + "path": "src/quant_platform/application/bybit_legacy_day_rebuild.py", + "ordinal": 1, "scope": "_digest", + "argument_ast": ast.dump(ast.parse("body", mode="eval").body, include_attributes=False), + "parameters": {"profile": "sorted-compact-ascii-v1", "allow_nan": False}, }, { "path": "src/quant_platform/representation/bar_flow.py", "ordinal": 1, "scope": "BarFlowDefinitionV1.canonical_utf8_serialization", @@ -140,7 +145,8 @@ def test_each_migrated_site_preserves_its_argument_profile_and_nan_policy(self): "ordinal": 2, "scope": "HistoricalBarFlowResult.result_identity", "argument_ast": ast.dump(ast.parse("payload", mode="eval").body, include_attributes=False), "parameters": {"profile": "sorted-compact-ascii-v1", "allow_nan": False}, - }] # #338: existing J12 canonical identities, unchanged byte profile; #339: the J13 wire message; #391: the natural partition identity text. + }] # #338: existing J12 canonical identities, unchanged byte profile; #339: the J13 wire message; #391: the natural partition identity text; + # #520 / R02: the digest of a legacy-day rebuild plan. # #461 / ADR-0073: additive bar-flow definition and result domains; # all historical sites and the pre-migration fixture remain unchanged. # #342: the feature-provider identity (ADR-0069 s7, the ADR-0068 diff --git a/tests/test_package_boundaries_v1.py b/tests/test_package_boundaries_v1.py index 69b3fcb..1574fb0 100644 --- a/tests/test_package_boundaries_v1.py +++ b/tests/test_package_boundaries_v1.py @@ -113,6 +113,7 @@ "quant_platform.application.admitted_input_definitions": "application", "quant_platform.application.instrument_catalog_check": "application", "quant_platform.application.bybit_archive_import": "application", + "quant_platform.application.bybit_legacy_day_rebuild": "application", "quant_platform.application.deck_result_bundle": "application", "quant_platform.application.admitted_input_transport": "application", "quant_platform.application.feature_provider_identity": "application", diff --git a/tools/rebuild_bybit_legacy_days.py b/tools/rebuild_bybit_legacy_days.py new file mode 100644 index 0000000..ddfb95e --- /dev/null +++ b/tools/rebuild_bybit_legacy_days.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Rebuild explicitly selected, closed legacy BTCUSDT live days from the Bybit public archive (DG-R R02, ADR-0074 Amendment 2). + +Operator-run, one command per step, nothing automatic: + +* ``plan`` read-only: writes a plan file (and prints its digest) for the named days. Refuses to overwrite a file. +* ``execute`` runs a reviewed plan, one day at a time: retire the damaged live revision, import the whole archive day as revision 1 of + ``dt=/seg=000000.000``, verify. It must be given the digest of the plan and recomputes the plan first: a plan that is not + current is refused and nothing is done. +* ``verify`` read-only: compares a rebuilt day with the archive file and with a strict DataGateway read. +* ``restore`` the documented way back for a retired day that was not rebuilt: a superseding pass returns it to valid. + +The connection string is read from an environment variable (``--dsn-env``, default ``CATALOG_DSN``), never from the command line. +``--code-ref`` defaults to the commit of this checkout and is refused when the tree has uncommitted changes. Exit status 0 when every +day asked for is done (or verified), 1 when a day is refused or fails, 2 on a usage error. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) + +from quant_platform.application.bybit_legacy_day_rebuild import ( # noqa: E402 + RebuildRefused, + execute_rebuild, + plan_rebuild, + restore_retired_day, + verify_rebuilt_day, +) + + +def _clean_head() -> str | None: + try: + status = subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, check=True, capture_output=True, text=True) + head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, check=True, capture_output=True, text=True) + except (OSError, subprocess.CalledProcessError): + return None + return None if status.stdout.strip() else head.stdout.strip() + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--storage-root-id", default="hot") + parser.add_argument("--dsn-env", default="CATALOG_DSN", help="environment variable that holds the PostgreSQL DSN") + sub = parser.add_subparsers(dest="command", required=True) + plan = sub.add_parser("plan", help="read-only plan for the named days") + plan.add_argument("--days", required=True, help="comma-separated UTC days, ascending, e.g. 2026-10-20") + plan.add_argument("--archive-dir", required=True, type=Path, help="directory with BTCUSDT.csv.gz (the days and their neighbours)") + plan.add_argument("--checkpoint-path", required=True, type=Path, help="the live-ingest checkpoint file") + plan.add_argument("--out", required=True, type=Path, help="plan file to write (never overwritten)") + plan.add_argument("--code-ref", help="producing commit; default: the clean HEAD of this checkout") + execute = sub.add_parser("execute", help="run a reviewed plan") + execute.add_argument("--plan", required=True, type=Path) + execute.add_argument("--digest", required=True, help="the digest of the plan, as printed by `plan`") + execute.add_argument("--archive-dir", required=True, type=Path) + execute.add_argument("--checkpoint-path", required=True, type=Path) + verify = sub.add_parser("verify", help="read-only verification of rebuilt days") + verify.add_argument("--days", required=True) + verify.add_argument("--archive-dir", required=True, type=Path) + verify.add_argument("--plan", type=Path, help="the executed plan: a day is verified against the archive file the plan approved") + restore = sub.add_parser("restore", help="return a retired, not rebuilt day to valid") + restore.add_argument("--day", required=True) + restore.add_argument("--code-ref", help="producing commit; default: the clean HEAD of this checkout") + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = _parser() + arguments = parser.parse_args(argv) + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", arguments.dsn_env): + parser.error("--dsn-env names an environment variable, not a connection string") + dsn = os.environ.get(arguments.dsn_env) + if not dsn: + parser.error(f"the environment variable {arguments.dsn_env} is not set") + needs_commit = arguments.command in ("plan", "restore") + code_ref = getattr(arguments, "code_ref", None) or (_clean_head() if needs_commit else None) + if needs_commit and not code_ref: + parser.error("the checkout has uncommitted changes (or no git); commit them or pass --code-ref") + if arguments.command == "plan" and arguments.out.exists(): + parser.error(f"{arguments.out} exists; a plan file is never overwritten") + import psycopg + + with psycopg.connect(dsn) as connection: + try: + if arguments.command == "plan": + plan = plan_rebuild( + connection, days=[d.strip() for d in arguments.days.split(",") if d.strip()], archive_dir=arguments.archive_dir, + storage_root_id=arguments.storage_root_id, checkpoint_path=arguments.checkpoint_path, code_ref=code_ref, + ) + arguments.out.write_text(json.dumps(plan, sort_keys=True, indent=2) + "\n", encoding="utf-8") + refused = [d["day"] for d in plan["days"] if d["action"] == "refused"] + print(json.dumps({"digest": plan["digest"], "plan_file": str(arguments.out), + "days": {d["day"]: d["action"] for d in plan["days"]}, + "refusals": {d["day"]: d["refusals"] for d in plan["days"] if d["refusals"]}}, sort_keys=True)) + return 1 if refused else 0 + if arguments.command == "execute": + plan = json.loads(arguments.plan.read_text(encoding="utf-8")) + result = execute_rebuild(connection, plan=plan, digest=arguments.digest, archive_dir=arguments.archive_dir, + checkpoint_path=arguments.checkpoint_path) + print(json.dumps(result, sort_keys=True)) + return 0 if all(d["outcome"] in ("rebuilt", "verified") for d in result["days"]) else 1 + if arguments.command == "verify": + approved = {} + if arguments.plan is not None: + approved = {e["day"]: e["archive"]["sha256"] for e in json.loads(arguments.plan.read_text(encoding="utf-8"))["days"] + if e.get("archive")} + reports = [verify_rebuilt_day(connection, day=d.strip(), archive_dir=arguments.archive_dir, + storage_root_id=arguments.storage_root_id, expected_archive_sha256=approved.get(d.strip())) + for d in arguments.days.split(",") if d.strip()] + print(json.dumps(reports, sort_keys=True)) + return 0 if all(r["passed"] for r in reports) else 1 + restored = restore_retired_day(connection, day=arguments.day, storage_root_id=arguments.storage_root_id, code_ref=code_ref) + print(json.dumps({"day": arguments.day, "restored": restored.lifecycle.resulting_state, "inserted": restored.inserted})) + return 0 if restored.lifecycle.resulting_state == "valid" else 1 + except RebuildRefused as exc: + print(json.dumps({"refused": exc.phase, "detail": str(exc)}, sort_keys=True)) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main())