diff --git a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md index b5a089b..c9409b3 100644 --- a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md +++ b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md @@ -147,21 +147,95 @@ 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 --storage-root \ + --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 compared: 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 with the archive trades each +contains and **what declares it**, the slices (count, rows and seconds: minimum, median, maximum) and the counters of the session. +Without `--start`/`--end` the window is the extent of the valid live slices; with them it is exactly the window asked for (a slice +that crosses a bound is refused, not clipped, and the archive of every day the whole window touches is required), so the archive +trades before the first slice and after the last count against the proof. + +A missing trade in a hole is excused only by a **span the run recorded** that contains it: the `known_gap` assertion of an explicit +gap record under `--storage-root` (ADR-0044; its last durable key must lie in the segment before the hole) or an `unclaimed_span` +signal in the captured log. Each missing trade is classified against those spans, not against the hole around it: a gap that ends +before a later loss does not excuse that loss, and the end of a span is exclusive. The absence of a partition is not a declaration +of its cause. + +**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); an archive trade in a hole outside every recorded gap span and signalled span (an undeclared loss); an archive +trade of the requested window before the first or after the last claimed window; a strict read of a claimed window refused; a trade +read twice or out of the canonical `(exchange_ts, trade_id)` order; a trade whose payload differs from the archive; valid slices that +overlap; a gap manifest that cannot be read. A shortfall against the archive inside a **recorded 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 f0cab0c..81cf33a 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 b348280..ba47de0 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 ec42661..d3183b5 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 06de9d8..416c17a 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 0000000..a6d59a2 --- /dev/null +++ b/src/quant_platform/application/live_window_evidence.py @@ -0,0 +1,495 @@ +"""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. The requested window is kept as asked: with ``--start/--end`` the archive trades of the + head (before the first slice) and of the tail (after the last) are counted and classified like any other; a slice that crosses a + bound is refused, not clipped. +* 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 excuses a missing trade only when that trade lies **inside a span the run recorded**: the ``known_gap`` assertion of an + explicit gap record (ADR-0044, a durable manifest whose last durable key lies in the segment before the hole) or an + ``unclaimed_span`` signal of the captured log. Each missing trade is classified against those spans, not against the whole hole: + a gap that ends before a later loss does not excuse it. A missing catalog partition is not a declaration of its cause: a trade in + a hole outside every recorded span, and one in a head or a tail, is a stop condition. A trade read back that the archive does not hold is reported; one the archive holds with a + different payload, read twice or out of the canonical ``(exchange_ts, trade_id)`` order, 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 +from quant_platform.source_adapters.bybit import bybit_trade_v1_ordering_key + +_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 + + +@dataclass(frozen=True, slots=True) +class DeclaredGap: + """An explicit gap the run recorded (ADR-0044): the span ``[start, end)`` of its ``known_gap`` assertion and the coverage id. + + ``start`` is the exchange time of its last durable key and ``end`` the instant it was detected; the manifest declares that + span and no more.""" + + start: Instant + end: Instant + coverage_id: str + + +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 unclaimed_spans(text: str) -> list[tuple[Instant, Instant]]: + """The ``unclaimed_span`` signals of a captured log: the spans a UTC midnight with no trade left without a slice.""" + + spans = [] + for line in text.splitlines(): + match = _SIGNAL_LINE.match(line.strip()) + if match is None: + continue + payload = match.group("payload") or "" + start, end = _field(payload, "unclaimed_start"), _field(payload, "unclaimed_end") + if start and end: + spans.append((Instant.parse(start), Instant.parse(end))) + return spans + + +def _declarations( + hole: tuple[Instant, Instant], previous_start: Instant, gaps: Sequence[DeclaredGap], + spans: Sequence[tuple[Instant, Instant]], +) -> list[tuple[str, int, int]]: + """``(label, start_ns, end_ns)`` of what the run recorded about one hole. + + A gap belongs to the hole when its last durable key lies in the segment before it; a signalled span, when it overlaps it. Only + the recorded span declares: a trade is excused by the span that contains it, never by the hole that surrounds it.""" + + found = [(f"gap_record:{gap.coverage_id}:{gap.start.isoformat()}..{gap.end.isoformat()}", gap.start.epoch_ns, gap.end.epoch_ns) + for gap in gaps if previous_start.epoch_ns <= gap.start.epoch_ns < hole[1].epoch_ns] + found += [(f"unclaimed_span_signal:{a.isoformat()}..{b.isoformat()}", a.epoch_ns, b.epoch_ns) + for a, b in spans if a.epoch_ns < hole[1].epoch_ns and hole[0].epoch_ns < b.epoch_ns] + return found + + +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, + declared_gaps: Sequence[DeclaredGap] = (), + unparseable_gap_manifests: int = 0, + 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. + + ``window`` is the requested window and is kept as given; without one it is the extent of the valid slices.""" + + valid = _claimed(slices, window) + stops: list[str] = [] + archive_records = list(archive) + if not valid: + low, high = (None, None) if window is None else (window[0].epoch_ns, window[1].epoch_ns) + counted = 0 if low is None else sum(1 for r in archive_records if low <= r.exchange_ts.epoch_ns < high) + return {"instrument": instrument, "passed": False, "stop_conditions": ["no valid live slice in the window"], + "window": None if window is None else {"start": window[0].isoformat(), "end": window[1].isoformat()}, + "archive_trades_in_window": counted} + 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") + if unparseable_gap_manifests: + stops.append(f"{unparseable_gap_manifests} gap manifests of the run could not be read (the holes cannot be attributed)") + segments = chain_segments(valid) + holes = _holes(segments) + start, end = (segments[0][0], segments[-1][1]) if window is None else window + spans = unclaimed_spans(signals_text) if signals_text is not None else [] + + # 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} + keys = [bybit_trade_v1_ordering_key(r) for r in read] # the canonical total order, ties by trade_id included + out_of_order = sum(1 for a, b in zip(keys, keys[1:]) if (b[0].epoch_ns, b[1]) < (a[0].epoch_ns, a[1])) + if out_of_order: + stops.append(f"the gateway returned {out_of_order} trades out of (exchange_ts, trade_id) order") + + low, high = start.epoch_ns, end.epoch_ns + in_window = {r.trade_id: r for r in archive_records if low <= r.exchange_ts.epoch_ns < high} + first_claimed, last_claimed = segments[0][0].epoch_ns, segments[-1][1].epoch_ns + inside_claimed: list[str] = [] + outside_edges: list[str] = [] # the head and the tail of the requested window: nothing was claimed there + hole_trades: 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 + if ts < first_claimed or ts >= last_claimed: + outside_edges.append(trade_id) + continue + for index, (hole_start, hole_end) in enumerate(holes): + if hole_start.epoch_ns <= ts < hole_end.epoch_ns: + hole_trades[index].append(trade_id) + break + else: + inside_claimed.append(trade_id) + declarations = [_declarations(hole, segments[i][0], declared_gaps, spans) for i, hole in enumerate(holes)] + declared_trades: dict[int, list[str]] = {} + undeclared_trades: dict[int, list[str]] = {} + for index, trade_ids in hole_trades.items(): + spans_of_hole = declarations[index] + declared_trades[index], undeclared_trades[index] = [], [] + for trade_id in trade_ids: # one pass: each trade is tested against the few recorded spans of its hole + ts = in_window[trade_id].exchange_ts.epoch_ns + inside = any(a <= ts < b for _label, a, b in spans_of_hole) + (declared_trades if inside else undeclared_trades)[index].append(trade_id) + declared_missing = sum(len(v) for v in declared_trades.values()) + undeclared_missing = sum(len(v) for v in undeclared_trades.values()) + if inside_claimed: + stops.append(f"{len(inside_claimed)} archive trades inside a claimed window are not read back (an undeclared loss)") + if undeclared_missing: + stops.append(f"{undeclared_missing} archive trades lie in a hole between slices outside every recorded gap span and " + "signalled span (an undeclared loss)") + if outside_edges: + stops.append(f"{len(outside_edges)} archive trades of the requested window lie before the first or after the last claimed window") + 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, + "requested": window is not None}, + "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, + "declared_by": [label for label, _a, _b in declarations[i]], + "archive_trades_inside": len(hole_trades[i]), "declared_trades": len(declared_trades[i]), + "undeclared_trades": len(undeclared_trades[i]), "examples": sorted(hole_trades[i])[:_EXAMPLES], + "undeclared_examples": sorted(undeclared_trades[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_declared_gaps": declared_missing, + "missing_inside_undeclared_holes": undeclared_missing, + "missing_outside_claimed_edges": len(outside_edges), + "read_not_in_archive": len(extra), + "examples_missing_inside_claimed_windows": sorted(inside_claimed)[:_EXAMPLES], + "examples_missing_outside_claimed_edges": sorted(outside_edges)[:_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 compared window touches, those without an archive file)``. + + The compared window is the requested one, whole, whatever slices exist in it; without one it is the extent of the valid slices + (both empty when there are none).""" + + valid = _claimed(slices, window) + if window is not None: + needed = archive_days_needed(window[0], window[1]) + elif valid: + needed = archive_days_needed(min(s.start for s in valid), max(s.end for s in valid)) + else: + return [], [] + 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]: + """The valid slices inside the window; a valid slice that crosses a bound makes the window unsupported (ValueError).""" + + valid = [s for s in slices if s.state == "valid"] + if window is None: + return valid + low, high = window[0].epoch_ns, window[1].epoch_ns + for item in valid: + for bound in (low, high): + if item.start.epoch_ns < bound < item.end.epoch_ns: + raise ValueError( + f"the slice {item.key} ({item.start.isoformat()}..{item.end.isoformat()}) crosses the window bound " + f"{Instant(bound).isoformat()}: choose bounds on slice boundaries or omit --start/--end") + return [s for s in valid if s.start.epoch_ns >= low and s.end.epoch_ns <= high] + + +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_declared_gaps(storage_root: str | Path, instrument: str) -> tuple[list[DeclaredGap], int]: + """The explicit gaps recorded under the storage root (ADR-0044 manifests), and how many manifests could not be read.""" + + from quant_platform.application.live_gap_orchestration import load_open_long_gap_records + + loaded = load_open_long_gap_records(storage_root=storage_root, instrument=instrument) + gaps = [DeclaredGap(Instant.parse(record.interval.coverage_start), Instant.parse(record.interval.coverage_end), record.coverage_id) + for record in loaded.records] + return gaps, len(loaded.unparseable_manifest_paths) + + +def read_live_slices(dsn: str | None, instrument: str) -> list[SliceWindow]: + """Every live-slice partition (``dt=/seg=