Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/integrity.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
99 changes: 99 additions & 0 deletions docs/engineering/BYBIT_ARCHIVE_IMPORT_RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<day>` 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=<day>/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=<day>/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-<HHMMSS>.json` and
`coverage-manifest-<HHMMSS>.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 <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=<day>/`
(two valid partitions over one day) and while an import holds the day's lock (`.import-dt=<day>.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.
101 changes: 99 additions & 2 deletions src/quant_platform/application/bybit_archive_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=<day>`` in the state ``invalid`` (its
superseded predecessors are history). A ``valid``, ``degraded``, ``closed`` or ``writing`` revision of that key, and every
partition ``dt=<day>/...`` (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,
*,
Expand All @@ -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
Expand All @@ -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")
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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=<day>``), 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."""
Expand Down Expand Up @@ -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",
]
Loading
Loading