From 30491fe04840d26d696b8248c9951f2c0648bdd9 Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:45:47 +0100 Subject: [PATCH 1/4] live: continuous-session configuration, runbook and window evidence tool (O03, ADR-0075 slice 9.3) (#525) - CLI: --mode {cycles,continuous} (default cycles, unchanged) and --slice-seconds, --slice-max-trades, --buffer-messages, valid only with continuous; empty value = default so a unit whose env file predates the options still starts; invalid values refused before any connection. - Units and env examples (BTCUSDT unit and @ template): mode and the three bounds rendered into ExecStart; defaults cycles with empty bounds. - Runbook: operating the continuous session, rollback to cycles, the one-hour real-provider proof procedure and its stop conditions. - Evidence tool (read-only): archive vs strict DataGateway read over the claimed windows, holes, ordering violations and health counters from the captured signals; stop conditions on an undeclared loss, a refused strict read, a double or out-of-order read, a payload that differs. - Tests: CLI, artifacts, runbook, evidence (unit, mutation-checked) and PostgreSQL phase 7. Co-Authored-By: Claude Sonnet 5.5 --- .../LIVE_INGEST_SERVER_DEPLOYMENT.md | 83 +++- .../quant-platform-live-ingest.env.example | 9 + .../quant-platform-live-ingest.service | 2 +- .../quant-platform-live-ingest@.env.example | 9 + .../quant-platform-live-ingest@.service | 2 +- .../application/live_window_evidence.py | 377 ++++++++++++++++++ tests/integration_live_session_postgres.py | 49 ++- tests/test_live_ingest_server_cli_v1.py | 79 ++++ .../test_live_ingest_template_artifacts_v1.py | 156 +++++++- tests/test_live_window_evidence_v1.py | 280 +++++++++++++ tests/test_package_boundaries_v1.py | 1 + tools/live_ingest_server.py | 58 ++- tools/live_window_evidence.py | 79 ++++ 13 files changed, 1163 insertions(+), 21 deletions(-) create mode 100644 src/quant_platform/application/live_window_evidence.py create mode 100644 tests/test_live_window_evidence_v1.py create mode 100644 tools/live_window_evidence.py diff --git a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md index b5a089bb..61b51d3c 100644 --- a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md +++ b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md @@ -147,21 +147,82 @@ dt=/seg=/part-001.p `SLICE_ORDERING_VIOLATION`, publishes nothing, and the next start reconciles from the checkpoint. - Partitions published before ADR-0075 (`dt=`, many superseded revisions) are left as they are; there is no repair. -### Continuous session (ADR-0075 slice 9.2, `O02`): in the code, not enabled +### Continuous session (ADR-0075 slices 9.2 and 9.3, `O02` and `O03`): opt-in per unit -`LiveIngestServerConfigV1.continuous_session` (a `LiveSessionConfig`) makes the server run ONE WebSocket session instead of the bounded -cycles: the connection is not closed between publications, a bounded buffer (default 20 000 messages) decouples the reader from -the publisher, and slices close after `slice_seconds` (300) or `slice_max_trades` (50 000). The default is `None`: the cycle loop above -is unchanged, and the unit templates, the CLI flags, this runbook's operating steps and the one-hour real-provider run belong to `O03`. -What an operator will see when it is enabled: +`--mode continuous` (environment variable `QP_LIVE_INGEST_MODE`) makes the server run ONE WebSocket session instead of the bounded +cycles: the connection is not closed between publications, a bounded buffer decouples the reader from the publisher, and slices +close after `slice_seconds` of wall clock or `slice_max_trades` trades. The default is `cycles`, the loop described above, and +nothing changes for a unit whose environment file does not set the mode (an empty or unset value is `cycles`, and an environment +file that predates these variables still starts the unit). Enabling it is an operator step: edit the environment file of the +instance and restart the unit; the repository enables nothing, and deployment of a changed server stays manual. +| Variable | Flag | Default | Meaning | +|---|---|---|---| +| `QP_LIVE_INGEST_MODE` | `--mode` | `cycles` | `cycles` or `continuous` | +| `QP_LIVE_INGEST_SLICE_SECONDS` | `--slice-seconds` | 300 | continuous only: wall-clock seconds after which an open slice closes | +| `QP_LIVE_INGEST_SLICE_MAX_TRADES` | `--slice-max-trades` | 50000 | continuous only: trades after which an open slice closes | +| `QP_LIVE_INGEST_BUFFER_MESSAGES` | `--buffer-messages` | 20000 | continuous only: bound of the reader's buffer; a full buffer ends the session | + +The three bounds are valid only with `continuous`: with `cycles` the server refuses to start (exit status 2) rather than ignore +them, so leave them empty (an empty value is the default). A non-positive or non-integer value is refused before any connection. +`--recent-limit` also applies to the reconciliation after an interruption. The ping interval, pong timeout and reconnect backoff are +not configuration. `--max-cycles`, when used for a bounded proof, counts health snapshots: one per published slice in this mode. + +Example, an instance switched to the continuous session with the defaults (`/etc/quant-platform/live-ingest-server-ETHUSDT.env`): + +```text +QP_LIVE_INGEST_MODE=continuous +QP_LIVE_INGEST_SLICE_SECONDS= +QP_LIVE_INGEST_SLICE_MAX_TRADES= +QP_LIVE_INGEST_BUFFER_MESSAGES= +``` + +What an operator sees: + +- Startup prints `mode=continuous` and the three bounds in force. - A disconnect, a missing pong, a full buffer or a trade below the open window **ends the session**; what was received is published, the interruption is signalled (`HEALTH_SNAPSHOT`, `DEGRADED`, `phase=interruption`, with the reason and the counters), the session - reconnects with a bounded backoff, subscribes first, fetches the recent trades and reconciles from the last durable key. -- Continuity proven: the reconciled trades are published as slices and the chain stays exact. Anchor outside the recent window: an - explicit gap (ADR-0044), recorded, `DEGRADED`; a new window starts at the first trade after it and nothing is claimed across the gap. -- Every published slice signals the buffer high-water mark and capacity, the slice lag in milliseconds, the number of reconnects and - of ordering violations. A publication, catalog or checkpoint failure stops the loop (`FAILURE`), as in the cycle loop. + reconnects with a bounded backoff, subscribes first and waits for the first trade of the new subscription. It then fetches the + recent trades and reconciles from the last durable key; a subscription with no trade yet reconciles nothing and claims nothing. +- Continuity proven (a trade of the subscription is in the recent-trades window): the reconciled trades are published as slices and + the chain stays exact. Anchor outside the window, or a window that does not meet the subscription: an explicit gap (ADR-0044), + recorded, `DEGRADED`; a new window starts at the first trade after it and nothing is claimed across the gap. +- Every published slice signals `phase=slice` with `buffer_high_water` and `buffer_capacity`, `slice_lag_ms`, `reconnects` and + `ordering_violations`. A UTC midnight with no trade is reported as an unclaimed span. A publication, catalog or checkpoint failure + stops the loop (`FAILURE`), as in the cycle loop. +- A `DataGateway` read under `strict` coverage across an interruption's gap is refused; under `allow-partial` it returns everything + published. + +**Rollback to the cycles:** set `QP_LIVE_INGEST_MODE=cycles` (and the bounds empty), restart the unit. The checkpoint and the +published partitions are the same in both modes: the first cycle reconciles from the durable checkpoint. + +### One-hour real-provider proof (`O03`; the `T02` proof for `ETHUSDT`) + +Operator-executed; the repository starts nothing. It measures what ADR-0075 leaves as an assumption: the captured share against +the provider's archive, the ordering of the provider's `exchange_ts`, the slice sizes and the health signals. Use a **disposable +catalog and storage root** (or an `ETHUSDT`-only root the maintainer chooses): the proof never touches the `BTCUSDT` dataset or its +unit, and it enables nothing in production (the ADR-0074 section 6 capacity gate stands). + +```bash +# 1. Run the continuous session for at least one hour, with the signals captured. Stop it cleanly with SIGTERM/SIGINT. +python tools/live_ingest_server.py --instrument ETHUSDT --mode continuous \ + --storage-root --storage-root-id --checkpoint-path /canonical/_k10_checkpoints/live-ingest-server-v1-ETHUSDT.json \ + --code-ref "$(git rev-parse HEAD)" 2>&1 | tee live-ethusdt-run.log + +# 2. After the UTC day (or days) of the run has ended, fetch the archive of each day it touched (tools/fetch_bybit_trade_archive.py). +# 3. Produce the evidence (read-only; exit 0 = no stop condition, 1 = a stop condition, 2 = usage): +python tools/live_window_evidence.py --instrument ETHUSDT --archive ETHUSDT.csv.gz [more days] \ + --signals-log live-ethusdt-run.log --code-ref --mode continuous > ethusdt-evidence.json +``` + +The report states, for the window the run claimed (the valid live slices): the archive trades in it, the trades a `strict` gateway +read returns (chunks of at most twelve slices, ending on slice boundaries), the captured ratio, the holes between exact chains (each +an interval the run declared unclaimed, with the archive trades it contains), the slices (count, rows and seconds: minimum, median, +maximum) and the counters of the session. **Stop conditions** (exit 1; do not read the proof as passed and report): an archive trade +inside a claimed window that is not read back (an undeclared loss); a strict read of a claimed window refused; a trade read twice or +out of order; a trade whose payload differs from the archive. A shortfall against the archive that falls inside an unclaimed span is +reported, not hidden, and is not a stop condition; an ordering violation is a measurement (it is an interruption by design), to be +explained in the evidence. Record the report, the log and the commit in the pull request of `O03`. ## Rollback diff --git a/infra/systemd/quant-platform-live-ingest.env.example b/infra/systemd/quant-platform-live-ingest.env.example index f0cab0c0..81cf33a8 100644 --- a/infra/systemd/quant-platform-live-ingest.env.example +++ b/infra/systemd/quant-platform-live-ingest.env.example @@ -24,6 +24,15 @@ QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE=1000 QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE=20 QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS=5 +# Session mode (ADR-0075, DG-O). cycles (the default; empty means cycles) is the bounded cycle loop; continuous keeps ONE WebSocket +# session open between publications. The three bounds apply to continuous only and an empty value is the default (300 s, 50000 +# trades, 20000 messages): leave them empty with cycles, the server refuses a bound together with cycles. Changing the mode is a +# restart of the unit, an operator step; the checkpoint and the published partitions are the same in both modes. +QP_LIVE_INGEST_MODE=cycles +QP_LIVE_INGEST_SLICE_SECONDS= +QP_LIVE_INGEST_SLICE_MAX_TRADES= +QP_LIVE_INGEST_BUFFER_MESSAGES= + QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES=53687091200 QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES=21474836480 QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES=5368709120 diff --git a/infra/systemd/quant-platform-live-ingest.service b/infra/systemd/quant-platform-live-ingest.service index b3482800..ba47de05 100644 --- a/infra/systemd/quant-platform-live-ingest.service +++ b/infra/systemd/quant-platform-live-ingest.service @@ -11,7 +11,7 @@ Group=marketdata WorkingDirectory=/opt/market-platform EnvironmentFile=/etc/quant-platform/live-ingest-server.env UMask=0027 -ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_PATH} --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} +ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_PATH} --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} --mode=${QP_LIVE_INGEST_MODE} --slice-seconds=${QP_LIVE_INGEST_SLICE_SECONDS} --slice-max-trades=${QP_LIVE_INGEST_SLICE_MAX_TRADES} --buffer-messages=${QP_LIVE_INGEST_BUFFER_MESSAGES} Restart=on-failure RestartSec=10s KillSignal=SIGTERM diff --git a/infra/systemd/quant-platform-live-ingest@.env.example b/infra/systemd/quant-platform-live-ingest@.env.example index ec426613..d3183b53 100644 --- a/infra/systemd/quant-platform-live-ingest@.env.example +++ b/infra/systemd/quant-platform-live-ingest@.env.example @@ -29,6 +29,15 @@ QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE=1000 QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE=20 QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS=5 +# Session mode (ADR-0075, DG-O). cycles (the default; empty means cycles) is the bounded cycle loop; continuous keeps ONE WebSocket +# session open between publications. The three bounds apply to continuous only and an empty value is the default (300 s, 50000 +# trades, 20000 messages): leave them empty with cycles, the server refuses a bound together with cycles. Changing the mode is a +# restart of the unit, an operator step; the checkpoint and the published partitions are the same in both modes. +QP_LIVE_INGEST_MODE=cycles +QP_LIVE_INGEST_SLICE_SECONDS= +QP_LIVE_INGEST_SLICE_MAX_TRADES= +QP_LIVE_INGEST_BUFFER_MESSAGES= + QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES=53687091200 QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES=21474836480 QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES=5368709120 diff --git a/infra/systemd/quant-platform-live-ingest@.service b/infra/systemd/quant-platform-live-ingest@.service index 06de9d84..416c17ab 100644 --- a/infra/systemd/quant-platform-live-ingest@.service +++ b/infra/systemd/quant-platform-live-ingest@.service @@ -13,7 +13,7 @@ EnvironmentFile=/etc/quant-platform/live-ingest-server-%i.env UMask=0027 # BTCUSDT stays on quant-platform-live-ingest.service: two writers on one dataset must not be startable (ADR-0074 section 3). ExecStartPre=/usr/bin/test "%i" != "BTCUSDT" -ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --instrument %i --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_DIR}/live-ingest-server-v1-%i.json --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} +ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --instrument %i --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_DIR}/live-ingest-server-v1-%i.json --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} --mode=${QP_LIVE_INGEST_MODE} --slice-seconds=${QP_LIVE_INGEST_SLICE_SECONDS} --slice-max-trades=${QP_LIVE_INGEST_SLICE_MAX_TRADES} --buffer-messages=${QP_LIVE_INGEST_BUFFER_MESSAGES} Restart=on-failure RestartSec=10s KillSignal=SIGTERM diff --git a/src/quant_platform/application/live_window_evidence.py b/src/quant_platform/application/live_window_evidence.py new file mode 100644 index 00000000..1ce614aa --- /dev/null +++ b/src/quant_platform/application/live_window_evidence.py @@ -0,0 +1,377 @@ +"""Evidence of a continuous live run against the Bybit archive (ADR-0075 slice 9.3, DG-O ``O03``). + +Read-only: it reads the catalog and the files through the ``DataGateway``, the archive files and a captured server log, and writes +nothing. The question it answers is the one ADR-0075 asks of the real-provider run: of the trades the provider's archive holds for +the window the run claimed, how many does a ``strict`` gateway read return, and is every one that does not explained by an +interval the run itself declared unclaimed? + +* The **windows the run claimed** are the valid live slices of the instrument inside the requested window (a slice is a half-open + window, ``complete`` over exactly that window). Consecutive slices that chain exactly form a **segment**; a hole between two + segments is an interval nobody claimed (an interruption with an explicit gap, a midnight with no trade). +* An archive trade **inside a claimed window** that is not read back is a loss the run did not declare: a stop condition. One inside + a hole is the declared cost of that interruption: reported with the hole, not a failure. A trade read back that the archive does + not hold is reported (the archive is the provider's later view); one the archive holds with a different payload, or read twice, + is a stop condition. +* The signals are taken from the captured stdout of ``tools/live_ingest_server.py`` (``signal kind=... k=v,k=v`` lines): the + counters the session reports (ordering violations, reconnects, buffer high-water mark, slice lag) and the interruptions. + +The result states what was measured; it never turns a shortfall into a pass, and it makes no claim about the provider beyond the run. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass +from decimal import Decimal +from pathlib import Path +import re +from statistics import median +from typing import Any + +from quant_platform.data import Instant +from quant_platform.data.models import TradeRecord + +_NS_PER_DAY = 86_400_000_000_000 +_NS_PER_MS = 1_000_000 +_EXAMPLES = 5 +_READ_CHUNK = 12 # slices per strict read (a K12 window carries at most 16 members) + + +@dataclass(frozen=True, slots=True) +class SliceWindow: + """One published live partition: its key, revision, lifecycle state, half-open window and row count.""" + + key: str + revision: int + state: str + start: Instant + end: Instant + rows: int + + +def _ms(instant: Instant) -> int: + return instant.epoch_ns // _NS_PER_MS * _NS_PER_MS + + +def chain_segments(slices: Sequence[SliceWindow]) -> list[tuple[Instant, Instant, list[SliceWindow]]]: + """The maximal runs of slices that chain exactly (each starts where the previous ended), by start.""" + + segments: list[tuple[Instant, Instant, list[SliceWindow]]] = [] + for item in sorted(slices, key=lambda s: (s.start.epoch_ns, s.end.epoch_ns)): + if segments and segments[-1][1].epoch_ns == item.start.epoch_ns: + start, _end, members = segments[-1] + segments[-1] = (start, item.end, [*members, item]) + else: + segments.append((item.start, item.end, [item])) + return segments + + +def _holes(segments: Sequence[tuple[Instant, Instant, list[SliceWindow]]]) -> list[tuple[Instant, Instant]]: + return [(a[1], b[0]) for a, b in zip(segments, segments[1:])] + + +def _field_differences(archive: TradeRecord, read: TradeRecord) -> list[str]: + """What differs between the archive's and the gateway's view of one trade (the fields the archive carries).""" + + differences = [] + for name in ("venue", "instrument", "aggressor_side"): + if getattr(archive, name) != getattr(read, name): + differences.append(name) + if _ms(archive.exchange_ts) != _ms(read.exchange_ts): + differences.append("exchange_ts_ms") + for name in ("price", "size"): + if Decimal(getattr(archive, name)) != Decimal(getattr(read, name)): + differences.append(f"{name}_value") + return differences + + +_SIGNAL_LINE = re.compile(r"^signal kind=(?P\S+) capability=\S+ signal_id=\S+(?: (?P.*))?$") + + +def _field(payload: str, name: str) -> str | None: + match = re.search(rf"(?:^|[ ,]){re.escape(name)}=([^,\s]*)", payload) + return None if match is None else match.group(1) + + +def summarize_signals(text: str) -> dict[str, Any]: + """The counters and interruptions of a captured ``tools/live_ingest_server.py`` stdout. + + The session's counters are cumulative, so the largest value seen is the final one; the lag is reported as a maximum.""" + + kinds: Counter[str] = Counter() + phases: Counter[str] = Counter() + health: Counter[str] = Counter() + interruptions: Counter[str] = Counter() + maxima = {"ordering_violations": 0, "reconnects": 0, "buffer_high_water": 0, "buffer_capacity": 0, "slice_lag_ms": 0} + lags: list[int] = [] + failures: list[str] = [] + final_state: str | None = None + for line in text.splitlines(): + match = _SIGNAL_LINE.match(line.strip()) + if match is None: + continue + kind, payload = match.group("kind"), match.group("payload") or "" + kinds[kind] += 1 + phase = _field(payload, "phase") + if phase: + phases[phase] += 1 + if kind == "HEALTH_SNAPSHOT": + state = _field(payload, "health") + if state: + health[state] += 1 + interruption = _field(payload, "interruption") + if interruption: + interruptions[interruption] += 1 + for name in maxima: + value = _field(payload, name) + if value is not None and value.lstrip("-").isdigit(): + maxima[name] = max(maxima[name], int(value)) + if name == "slice_lag_ms": + lags.append(int(value)) + if kind == "FAILURE": + failures.append(_field(payload, "failure_code") or "unknown") + resulting = _field(payload, "resulting_state") + if resulting: + final_state = resulting + return { + "signals": dict(sorted(kinds.items())), + "health_snapshots": dict(sorted(health.items())), + "phases": dict(sorted(phases.items())), + "interruptions": dict(sorted(interruptions.items())), + "ordering_violations": maxima["ordering_violations"], + "reconnects": maxima["reconnects"], + "buffer_high_water": maxima["buffer_high_water"], + "buffer_capacity": maxima["buffer_capacity"], + "slice_lag_ms_max": maxima["slice_lag_ms"], + "slice_lag_ms_median": int(median(lags)) if lags else 0, + "failures": failures, + "final_lifecycle_state": final_state, + } + + +def build_window_evidence( + *, + instrument: str, + archive: Iterable[TradeRecord], + slices: Sequence[SliceWindow], + read_segment: Callable[[Instant, Instant], Sequence[TradeRecord]], + window: tuple[Instant, Instant] | None = None, + signals_text: str | None = None, + configuration: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Compare the claimed windows of a run with the archive; ``read_segment(start, end)`` is the ``strict`` gateway read.""" + + valid = _claimed(slices, window) + stops: list[str] = [] + if not valid: + return {"instrument": instrument, "passed": False, "stop_conditions": ["no valid live slice in the window"], + "window": None} + ordered_slices = sorted(valid, key=lambda s: (s.start.epoch_ns, s.end.epoch_ns)) + overlapping = sum(1 for a, b in zip(ordered_slices, ordered_slices[1:]) if b.start.epoch_ns < a.end.epoch_ns) + if overlapping: # the catalog admits no two valid partitions of one dataset over the same time (partitions_one_live) + stops.append(f"{overlapping} valid slices overlap the one before them") + segments = chain_segments(valid) + holes = _holes(segments) + start, end = segments[0][0], segments[-1][1] + + # what the gateway returns for the claimed windows, one strict read per exact chain + read: list[TradeRecord] = [] + refused: list[str] = [] + for _seg_start, _seg_end, members in segments: + for first in range(0, len(members), _READ_CHUNK): # a read is bounded in members (K12): chunks end on slice boundaries + chunk = members[first:first + _READ_CHUNK] + a, b = chunk[0].start, chunk[-1].end + try: + read.extend(read_segment(a, b)) + except Exception as exc: # noqa: BLE001 - a refused strict read is a finding of the evidence, never a crash + refused.append(f"{a.isoformat()}..{b.isoformat()}: {type(exc).__name__}: {exc}") + if refused: + stops.append(f"a strict read of a claimed window was refused ({len(refused)})") + read_ids = Counter(record.trade_id for record in read) + duplicated = sorted(trade_id for trade_id, count in read_ids.items() if count > 1) + if duplicated: + stops.append(f"{len(duplicated)} trades are read more than once") + read_by_id = {record.trade_id: record for record in read} + ordered = [(r.exchange_ts.epoch_ns, r.trade_id) for r in read] + out_of_order = sum(1 for a, b in zip(ordered, ordered[1:]) if b[0] < a[0]) + if out_of_order: + stops.append(f"the gateway returned {out_of_order} trades out of exchange_ts order") + + low, high = start.epoch_ns, end.epoch_ns + in_window = {r.trade_id: r for r in archive if low <= r.exchange_ts.epoch_ns < high} + inside_claimed: list[str] = [] + inside_hole: dict[int, list[str]] = {i: [] for i in range(len(holes))} + for trade_id, record in in_window.items(): + if trade_id in read_by_id: + continue + ts = record.exchange_ts.epoch_ns + for index, (hole_start, hole_end) in enumerate(holes): + if hole_start.epoch_ns <= ts < hole_end.epoch_ns: + inside_hole[index].append(trade_id) + break + else: + inside_claimed.append(trade_id) + if inside_claimed: + stops.append(f"{len(inside_claimed)} archive trades inside a claimed window are not read back (an undeclared loss)") + extra = sorted(trade_id for trade_id in read_by_id if trade_id not in in_window) + conflicts: dict[str, list[str]] = {} + for trade_id, record in read_by_id.items(): + if trade_id in in_window: + differences = _field_differences(in_window[trade_id], record) + if differences: + conflicts[trade_id] = differences + if conflicts: + stops.append(f"{len(conflicts)} trades differ from the archive") + captured = len(set(read_by_id) & set(in_window)) + + window_ns = high - low + listened_ns = sum(b - a for a, b in ((s[0].epoch_ns, s[1].epoch_ns) for s in segments)) + row_counts = [s.rows for s in valid] + lengths = [(s.end.epoch_ns - s.start.epoch_ns) / 1e9 for s in valid] + report: dict[str, Any] = { + "instrument": instrument, + "window": {"start": start.isoformat(), "end": end.isoformat(), "seconds": window_ns / 1e9}, + "configuration": dict(configuration or {}), + "slices": { + "valid": len(valid), + "not_valid_in_catalog": len([s for s in slices if s.state != "valid"]), + "revisions_above_one": len([s for s in valid if s.revision != 1]), + "rows_total": sum(row_counts), + "rows_min": min(row_counts), "rows_median": int(median(row_counts)), "rows_max": max(row_counts), + "seconds_min": min(lengths), "seconds_median": median(lengths), "seconds_max": max(lengths), + "chain_segments": len(segments), + }, + "holes": [ + {"start": a.isoformat(), "end": b.isoformat(), "seconds": (b.epoch_ns - a.epoch_ns) / 1e9, + "archive_trades_inside": len(inside_hole[i]), "examples": sorted(inside_hole[i])[:_EXAMPLES]} + for i, (a, b) in enumerate(holes) + ], + "claimed_share": listened_ns / window_ns if window_ns else 1.0, + "archive_trades_in_window": len(in_window), + "read_through_gateway": len(read), + "captured_of_archive": captured, + "captured_ratio": captured / len(in_window) if in_window else 1.0, + "missing_inside_claimed_windows": len(inside_claimed), + "missing_inside_unclaimed_spans": sum(len(v) for v in inside_hole.values()), + "read_not_in_archive": len(extra), + "examples_missing_inside_claimed_windows": sorted(inside_claimed)[:_EXAMPLES], + "examples_read_not_in_archive": extra[:_EXAMPLES], + "conflicts": {k: conflicts[k] for k in sorted(conflicts)[:_EXAMPLES]}, + "strict_reads_refused": refused, + "duplicated_reads": duplicated[:_EXAMPLES], + "stop_conditions": stops, + "passed": not stops, + } + if signals_text is not None: + report["signals"] = summarize_signals(signals_text) + return report + + +_ARCHIVE_NAME = re.compile(r"^(?P[A-Z0-9]+)(?P\d{4}-\d{2}-\d{2})\.csv\.gz$") + + +def archive_days_needed(window_start: Instant, window_end: Instant) -> list[str]: + """The UTC days (``YYYY-MM-DD``) a half-open window touches; each needs its archive file.""" + + first = window_start.epoch_ns // _NS_PER_DAY + last = (window_end.epoch_ns - 1) // _NS_PER_DAY + return [Instant(day * _NS_PER_DAY).isoformat()[:10] for day in range(first, last + 1)] + + +def parse_window(start: str | None, end: str | None) -> tuple[Instant, Instant] | None: + """The requested window from two ISO instants, or ``None`` when neither is given.""" + + if start is None and end is None: + return None + if start is None or end is None: + raise ValueError("a window needs both a start and an end") + low, high = Instant.parse(start), Instant.parse(end) + if not low.epoch_ns < high.epoch_ns: + raise ValueError("the window start must be before its end") + return low, high + + +def archive_days_missing( + slices: Sequence[SliceWindow], window: tuple[Instant, Instant] | None, available: Iterable[str], +) -> tuple[list[str], list[str]]: + """``(days the claimed windows touch, those without an archive file)``; both empty when no valid slice is in the window.""" + + valid = _claimed(slices, window) + if not valid: + return [], [] + needed = archive_days_needed(min(s.start for s in valid), max(s.end for s in valid)) + have = set(available) + return needed, [day for day in needed if day not in have] + + +def _claimed(slices: Sequence[SliceWindow], window: tuple[Instant, Instant] | None) -> list[SliceWindow]: + valid = [s for s in slices if s.state == "valid"] + if window is not None: + valid = [s for s in valid if s.start.epoch_ns >= window[0].epoch_ns and s.end.epoch_ns <= window[1].epoch_ns] + return valid + + +def load_archive_days(paths: Iterable[str | Path], *, instrument: str) -> dict[str, list[TradeRecord]]: + """``day -> records`` of local ``.csv.gz`` files (the day is read from the file name).""" + + from quant_platform.source_adapters.bybit_archive import read_bybit_archive_day + + days: dict[str, list[TradeRecord]] = {} + for path in paths: + match = _ARCHIVE_NAME.match(Path(path).name) + if match is None or match.group("instrument") != instrument: + raise ValueError(f"{Path(path).name!r} is not a {instrument}.csv.gz archive file") + days[match.group("day")] = list(read_bybit_archive_day(path, instrument=instrument, day=match.group("day")).records) + return days + + +# ---------------------------------------------------------------------------------------------------- the real catalog + + +def read_live_slices(dsn: str | None, instrument: str) -> list[SliceWindow]: + """Every live-slice partition (``dt=/seg=