diff --git a/.github/workflows/integrity.yml b/.github/workflows/integrity.yml index efb5b1e..0a2ef51 100644 --- a/.github/workflows/integrity.yml +++ b/.github/workflows/integrity.yml @@ -341,6 +341,44 @@ jobs: DATA_GATEWAY_TEST_DSN: postgresql://postgres:ci-postgres-password@127.0.0.1:5432/market_catalog_live_slices run: python tests/integration_live_slices_postgres.py + live-session-postgres: + name: Disposable PostgreSQL 17 live ingest continuous session test + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: ci-postgres-password + POSTGRES_DB: market_catalog_live_session + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d market_catalog_live_session" + --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 live session 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_live_session + 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 live ingest continuous session PostgreSQL integration + env: + DATA_GATEWAY_TEST_DSN: postgresql://postgres:ci-postgres-password@127.0.0.1:5432/market_catalog_live_session + run: python tests/integration_live_session_postgres.py + adversarial-refusal-postgres: name: Disposable PostgreSQL 17 adversarial publication refusal test runs-on: ubuntu-latest diff --git a/SCOPE.md b/SCOPE.md index 1f4dc3a..ba77572 100644 --- a/SCOPE.md +++ b/SCOPE.md @@ -1,8 +1,8 @@ -# Scope: DG-N — Multi-instrument Bybit linear trades v1, and DG-O — Live publication v1 +# Scope: DG-N — Multi-instrument Bybit linear trades v1, DG-O — Live publication v1, and DG-R — Rebuild of damaged legacy live days v1 -Status: **OPEN — two gates of one wave. DG-N: design gate CLOSED; `T01` and `T04` COMPLETE (reconciliation #489); `T03` merged (PR #492) and `T02` parts 1 to 5 merged (PR #494, #496, #498, #500, #502), both credited at the closeout, `T02` closing with `O03`. DG-O: design gate CLOSED (ADR-0075 `ACCEPTED` 2026-10-21, #504); `O01`, `O02` and `O03` AUTHORIZED (governance issue #507), not started.** Measured on the maintainer's server on 2026-10-21: the live publication supersedes each cycle with the next (a day reads as under 0.4% of its published trades) and about 27% of a day's trades are never acquired; DG-O fixes both, before the rest of the wave. The integration branch is `implement/fid`, the current wave (the maintainer's choice, 2026-10-19): when the atoms are merged and reconciled, the whole wave (DG-M, DG-N and DG-O) is promoted to `main` by the operator and the first version of the product is declared concluded. **Today `BTCUSDT` is the only instrument ingested live and registered on the server, and its live days are not fully readable or complete (DG-O); the other four instruments are readable once their partitions are `valid`.** +Status: **DG-N and DG-O CLOSED within recorded bounds (closeout #527); DG-R OPEN, post-version.** DG-N: design gate CLOSED; `T01`, `T04`, `T03` and `T02` COMPLETE (reconciliations #489, #527; PR #486, #488, #492, #494, #496, #498, #500, #502, #526). DG-O: design gate CLOSED (ADR-0075 `ACCEPTED` 2026-10-21, #504); `O01`, `O02` and `O03` COMPLETE (PR #510, #524, #526; governance #507, #527). **The one-hour `ETHUSDT` real-provider run of `O03` (the `T02` proof) was not performed and is not claimed** (the maintainer's decision, 2026-10-25): the atoms are credited within the bound of their code, configuration, runbook, evidence tool and tests. DG-R: design gate CLOSED (ADR-0074 Amendment 2 `ACCEPTED` 2026-10-24, #515); `R01` and `R02` AUTHORIZED (governance issue #518), post-version, not started. Measured on the maintainer's server on 2026-10-21: the live publication superseded each cycle with the next (a day read as under 0.4% of its published trades) and about 27% of a day's trades were never acquired; DG-O fixes both in the code, which is **not deployed** and was never run against the real provider. The integration branch is `implement/fid`, the current wave (the maintainer's choice, 2026-10-19). The operator promoted it to `main` once already (PR #514, 2026-10-24: DG-M, DG-N and `O01`); a later promotion carries the rest. The first version of the product is declared concluded by the maintainer, after this closeout. DG-R is post-version work and does not block that declaration. **Today `BTCUSDT` is the only instrument ingested live and registered on the server, and the server runs the code deployed before DG-O: its live days remain not fully readable or complete until the operator deploys and (for the old days) DG-R rebuilds them; the other four instruments are readable once their partitions are `valid`.** -Scope kind: a sequencing scope for two gates of one wave: DG-N (design gate closed; Part B authorized inventory) and DG-O (design gate closed; Part C authorized inventory). +Scope kind: a sequencing scope for three gates: DG-N (design gate closed; Part B authorized inventory), DG-O (design gate closed; Part C authorized inventory) and DG-R (design gate closed; Part D authorized inventory, post-version). --- @@ -23,6 +23,7 @@ The platform ingests, publishes, serves and delivers Bybit linear trades for one 1. **ADR-0040, ADR-0041, ADR-0042, ADR-0043, ADR-0044:** the live trades acquisition, the checkpoint identity (it carries its `dataset_identity`), the single-process loop and the explicit-gap policy with no authoritative repair source. ADR-0074 amends only what its section 8 lists. 2. **ADR-0057, ADR-0064, ADR-0069, ADR-0072:** the server is the sole authority for canonical data; the deck receives verified bytes and has no storage mount; the wire and the K12/K13 contracts do not change. 3. **ADR-0075** (accepted 2026-10-21; DG-O, Part C): one continuous session and append-only slices, ADR-0044 unchanged. + **Amendment 1** (accepted 2026-10-23, PR #513): a bridge slice with no trade for a reconciliation across a UTC midnight, the next revision only over an attempt that never became valid, the floor as the end of the latest valid partition. 4. **ADR-0074** (accepted) and its **Amendment 1** (accepted 2026-10-20: the Bybit public trade archive is the historical source of every instrument): the decisions in the Part B acceptance below. 5. Every `BTCUSDT` identity, the ordering key `(exchange_ts, trade_id)` and `TradeKeyV1` are unchanged byte for byte (pinned by `tests/test_multi_instrument_trades_contract_v1.py`). 6. **Out of this scope:** a second venue (`A12`), spot and inverse markets, L2 for other instruments (its ordering policy is keyed by `(venue, instrument)`), a generic provider resolver, capacity measurements (#378), deployment to the server. @@ -47,8 +48,8 @@ Each atom is its own implementation issue (`[implementation]` template), opened |---|---|---|---| | `T01` | Read and delivery for the allow-list | `A06`, `A08`, `A09`, `K12` | **COMPLETE** (#485, PR #486) | | `T04` | Historical import `--instrument` from the Bybit public archive | `A07`, `T01` | **COMPLETE** (#487, PR #488) | -| `T03` | Explicit per-instrument fees | `H02`, `T01` | **merged** (#491, PR #492); credited at the closeout | -| `T02` | Live ingest per instrument | `A11`, `K10`, `T01`, `T03`, `T04`, `O03` | parts 1 to 5 merged (#493 / PR #494, #495 / PR #496, #497 / PR #498, #499 / PR #500, #501 / PR #502); closes with `O03` (its one-hour proof); credited at the closeout | +| `T03` | Explicit per-instrument fees | `H02`, `T01` | **COMPLETE** (#491, PR #492; closeout #527) | +| `T02` | Live ingest per instrument | `A11`, `K10`, `T01`, `T03`, `T04`, `O03` | **COMPLETE** (#493 / PR #494, #495 / PR #496, #497 / PR #498, #499 / PR #500, #501 / PR #502; closed by `O03`, PR #526; closeout #527) -- the one-hour real-provider run is not claimed | ```text T01 ──> T04 ──> T03 ──> T02 @@ -71,31 +72,54 @@ Problem, measured on 2026-10-21 (ADR-0075 F1, F2): every cycle is a new revision | Atom | Result | Requires (besides ADR-0075) | Start gate | |---|---|---|---| -| `O01` | Append-only live slices | `A11`, `K10`, `T01` | startable | -| `O02` | Continuous live session | `O01` | after `O01` is merged | -| `O03` | Configuration, runbook and real-provider proof | `O02`, `T03`, `T04` | after `O02` is merged | +| `O01` | Append-only live slices | `A11`, `K10`, `T01` | **COMPLETE** (#509 / PR #510; closeout #527) | +| `O02` | Continuous live session | `O01` | **COMPLETE** (#523 / PR #524; closeout #527) | +| `O03` | Configuration, runbook and real-provider proof | `O02`, `T03`, `T04` | **COMPLETE within its bound** (#525 / PR #526; closeout #527) -- the real-provider run is not claimed | ```text O01 ──> O02 ──> O03 ──> T02 ``` -Order: strictly `O01`, `O02`, `O03`, one bounded mutation slice at a time; `T02` is credited when `O03` is merged. +Order: strictly `O01`, `O02`, `O03`, one bounded mutation slice at a time; `T02` was credited when `O03` merged (closeout #527). ### Acceptance per atom (from ADR-0075; an implementation issue adds no semantic decision) -- **`O01`** (§2 to §4, slice 9.1). A slice is the trades of one instrument whose `exchange_ts` lies in a half-open window; it closes after `slice_seconds` (300) or `slice_max_trades` (50 000), at a message boundary, with the boundary the greatest `exchange_ts` received and trades equal to it kept for the next slice; a window never crosses a UTC midnight and an empty window is not published. Each slice is **revision 1 of its own partition** `dt=/seg=` with `part-001.parquet` and manifests named by the window, and is never superseded; the windows of one session chain exactly and the coverage of a slice is `complete` over its window. The checkpoint invariants of ADR-0042 are unchanged; the checkpoint binds a slice partition and the window end comes from the catalog. The live certification profile accepts the key grammar and checks the chain. Over the existing bounded acquisition. Tests that fail on today's behaviour: a multi-cycle run leaves every trade readable through the `DataGateway` with no `superseded` partition (against a real PostgreSQL); two publications in one second do not collide; the `BTCUSDT` identities, the ordering key and `TradeKeyV1` are unchanged; mutation checks. +- **`O01`** (§2 to §4, slice 9.1). A slice is the trades of one instrument whose `exchange_ts` lies in a half-open window; it closes after `slice_seconds` (300) or `slice_max_trades` (50 000), at a message boundary, with the boundary the greatest `exchange_ts` received and trades equal to it kept for the next slice; a window never crosses a UTC midnight and an empty window is not published (except the bridge slice of a reconciliation, Amendment 1 below). Each slice is **revision 1 of its own partition** `dt=/seg=` with `part-001.parquet` and manifests named by the window, and a valid slice is never superseded; the windows of one session chain exactly and the coverage of a slice is `complete` over its window. The checkpoint invariants of ADR-0042 are unchanged; the checkpoint binds a slice partition and the window end comes from the catalog. The live certification profile accepts the key grammar and checks the chain. Over the existing bounded acquisition. Tests that fail on today's behaviour: a multi-cycle run leaves every trade readable through the `DataGateway` with no `superseded` partition (against a real PostgreSQL); two publications in one second do not collide; the `BTCUSDT` identities, the ordering key and `TradeKeyV1` are unchanged; mutation checks. ADR-0075 Amendment 1 (accepted 2026-10-23, PR #513): a reconciliation whose proven span reaches a UTC midnight before its first new trade publishes a slice with no trade up to the midnight, and a slice is a revision later than 1 only over an attempt that never became valid (a valid slice is never superseded); the floor is the end of the latest valid partition. Merged (PR #510). - **`O02`** (§1, §5, slice 9.2). One WebSocket session per instance, not closed between publications; a reader feeds a bounded buffer (20 000 messages) that the publisher drains; a buffer overflow, a real disconnect and a received trade whose `exchange_ts` is below the last boundary each end the session as an interruption, handled as ADR-0040 §7 and ADR-0042 §5 decide (bounded reconciliation from the last durable key, else an explicit gap; ADR-0044 unchanged) and counted; signals for the buffer high-water mark, the slice lag, the reconnects and the ordering violations. Tests with a scripted provider: no interval of the session is unlistened; an interruption is never a `complete` claim; the checkpoint never advances across one; mutation checks. - **`O03`** (§9.3, slice 9.3). `slice_seconds`, `slice_max_trades` and the buffer bound in `LiveIngestServerConfigV1`, the CLI, the unit templates and the runbook; a real-provider run of **at least one hour** for `ETHUSDT` (the `T02` proof) that reports the trades captured against the Bybit archive of the same day, the trades readable through the `DataGateway`, the number of `exchange_ts` ordering violations and the health signals, recorded as evidence. Deployment of a changed server to the host stays a manual operator step. +## Part D — DG-R: rebuild of damaged legacy live days (authorized implementation inventory, post-version) + +Registered by governance issue #518 after ADR-0074 Amendment 2 (`ACCEPTED` 2026-10-24, design gate #515, PR #516 and #521). Each atom is its own implementation issue (`[implementation]` template): `R01` is #519 and `R02` is #520, citing their rows here. Every one targets `implement/fid`, never `main`. These atoms are **post-version**: they do not block `O02`, `O03`, the closeout or the declaration that the first version is concluded. + +Problem (operator-reported evidence, 2026-10-23/24, not an audit): the legacy live path published each cycle as a new revision of `dt=` and superseded the previous one, so a closed day reads as its last batch; 31 candidate days, 2026-09-23 to 2026-10-23; for 2026-10-20 the archive has 1,568,861 trades, the local in-day unique IDs are 1,141,530 (all in the archive; 427,331 absent) and 529 local rows fall outside the day. The ID comparison does not establish equality of every field. + +| Atom | Result | Requires (besides ADR-0074 Amendment 2) | Start gate | +|---|---|---|---| +| `R01` | Superseding reassessment writer | `A16`, `A08`, `A09` | startable after this reconciliation merges (and the acceptance record, PR #521) | +| `R02` | Legacy-day rebuild: plan, retire, import, verify | `R01`, `T04` | after `R01` is merged | + +```text +R01 ──> R02 +``` + +Order: strictly `R01`, `R02`, one bounded mutation slice at a time. + +### Acceptance per atom (from ADR-0074 Amendment 2; an implementation issue adds no semantic decision) + +- **`R01`** (A2.3, issue #519). A writer, in the data plane next to `quality_lifecycle.py`, of a superseding reassessment report for the current live revision of one natural partition that is not `closed`: it copies the bound evidence of the assessment it supersedes unchanged, sets the status and a violation `legacy_publication_incomplete_day`, carries `metrics.supersedes_assessment_signature` and the producing commit; the lifecycle application then maps `fail` to `invalid` through the existing seam, and a superseding `pass` restores `valid`. Refuses a superseded, foreign or `writing` revision; idempotent; same lock order as the lifecycle application; ordinary `record_quality_report` is unchanged. Tests against a real PostgreSQL (state change both ways, supersession link, evidence copy, idempotence, refusals, a `VALID_ONLY` read excludes the retired revision, a concurrent S13 publication waits and proceeds, old bytes and reports unchanged); mutation checks. First check: who reacts to the state `invalid` (retention, eligibility, admitted inputs). +- **`R02`** (A2.2, A2.4 to A2.7, issue #520). An importer variant for which the `invalid` revision of the exact key `dt=` does not occupy the day (everything else still refuses), the fixed key `dt=/seg=000000.000`; a read-only plan with a digest (incumbent revision and hashes, archive file identity, producing commit, key to create, the result of the refusals); refusals with nothing changed: day not closed in UTC (less than 24 hours), live slices, checkpoint binding or open gap record naming the day, live revision not `valid`, failed **conservation** (every record of the incumbent live revision found, field for field, in the archive file of its own day, which must be readable afterwards), a differing common field, an archive that fails strict parsing or differs from the planned hash, a stale plan; one day at a time, no lock held across days; retire, import, verify (full-field comparison and a strict `DataGateway` read: count, order, duplicates); recovery of a crash between retire and import and between import and verify; restore by a superseding `pass`. Tests against a real PostgreSQL, including the pilot shape of 2026-10-20 (a strict read returns exactly 1,568,861 archive records, in order, without duplicates, equal field by field) and byte-identical non-target days and live checkpoint; mutation checks; CLI and runbook. + --- ## Authority - `AGENTS.md` -- governance issues #381, #409, #453, #458, #475, #479, #483, #489, #507; design-gate issues #377, #487, #504; evidence issue #378; implementation issues #485, #487, #491, #493, #495, #497, #499, #501 -- `docs/decisions/ADR-0074-multi-instrument-bybit-linear-trades-v1.md` (`ACCEPTED`, with Amendment 1 `ACCEPTED`) -- `docs/decisions/ADR-0075-live-trades-continuous-session-and-append-only-slices-v1.md` (`ACCEPTED`) -- `docs/product/ROADMAP.md`, `docs/product/CAPABILITY_DAG.md` (`T` atoms), `docs/architecture/OPEN_DECISIONS.md` (DG-N) +- governance issues #381, #409, #453, #458, #475, #479, #483, #489, #507, #518, #527; design-gate issues #377, #487, #504, #512, #515; evidence issue #378; implementation issues #485, #487, #491, #493, #495, #497, #499, #501, #509, #523, #525, #519, #520 +- `docs/decisions/ADR-0074-multi-instrument-bybit-linear-trades-v1.md` (`ACCEPTED`, with Amendment 1 and Amendment 2 `ACCEPTED`) +- `docs/decisions/ADR-0075-live-trades-continuous-session-and-append-only-slices-v1.md` (`ACCEPTED`, with Amendment 1 `ACCEPTED`) +- `docs/decisions/ADR-0030-general-quality-lifecycle-v1.md` and `docs/decisions/ADR-0033-backfill-repair-v1.md` (unchanged; ADR-0030 is used by Part D) +- `docs/product/ROADMAP.md`, `docs/product/CAPABILITY_DAG.md` (`T` atoms), `docs/architecture/OPEN_DECISIONS.md` (DG-N, DG-O, DG-R) - ADR-0040, ADR-0041, ADR-0042, ADR-0043, ADR-0044, ADR-0054, ADR-0057, ADR-0064, ADR-0069, ADR-0072 - `tests/test_package_boundaries_v1.py`, `tests/test_multi_instrument_trades_contract_v1.py` @@ -106,10 +130,11 @@ Accepted ADRs and frozen contracts remain normative. This reconciliation weakens ## Baseline and Credited State ```text -main @ ef14279 (DG-K P01-P06, DG-K2 S01-S07 and DG-C/A14 v1 COMPLETE within recorded bounds) -implement/fid: main + DG-M (M01, M02, M04, M05 COMPLETE, closeout #475, follow-on #477) + ADR-0074 (#481, #482) + T01 (#486) + T04 and Amendment 1 (#488) + T03 (#492) + T02 parts 1 to 5 (#494, #496, #498, #500, #502) + ADR-0075 (#505, #506) + this reconciliation -DG-N: T01, T04 COMPLETE (reconciliation #489); T03, T02 FROZEN / MISSING (authorized by #483; merged, credited at the closeout) -DG-O: O01, O02, O03 FROZEN / MISSING (authorized by #507) +main @ 9cf0b5e (DG-K P01-P06, DG-K2 S01-S07 and DG-C/A14 v1 COMPLETE within recorded bounds; promotion PR #514 brought implement/fid @ fc69cc1 -- DG-M, DG-N, O01 -- into main on 2026-10-24, then ADR-0075 Amendment 1, PR #513) +implement/fid: main + DG-M (M01, M02, M04, M05 COMPLETE, closeout #475, follow-on #477) + ADR-0074 (#481, #482) + T01 (#486) + T04 and Amendment 1 (#488) + T03 (#492) + T02 parts 1 to 5 (#494, #496, #498, #500, #502) + ADR-0075 (#505, #506) + O01 (#510) + ADR-0075 Amendment 1 (#512 / PR #513, via main) + ADR-0074 Amendment 2 (#515 / PR #516, #521) + DG-R registration (#518 / PR #522) + O02 (#524) + O03 (#526) + this closeout (#527) +DG-N: T01, T04 COMPLETE (reconciliation #489); T03, T02 COMPLETE within bounds (closeout #527; the one-hour real-provider run is not claimed) +DG-O: O01, O02, O03 COMPLETE within bounds (closeout #527; PR #510, #524, #526) +DG-R: R01, R02 FROZEN / MISSING (authorized by #518; post-version) ``` Credit, do not reimplement or re-prove absent invalidating evidence: every atom `COMPLETE` in `CAPABILITY_DAG.md`, within the bound its row records. @@ -118,15 +143,27 @@ Credit, do not reimplement or re-prove absent invalidating evidence: every atom ## Explicit non-claims -- `T03` and `T02` parts 1 to 5 are merged but **not credited** here: `T02` closes with `O03`, and nothing is deployed, so no non-BTC instrument is ingested live on the server. +- **The one-hour `ETHUSDT` real-provider run of `O03` (the `T02` proof) was not performed.** `T02` and `O03` are credited within the bound of their code, configuration, runbook, evidence tool and tests (the maintainer's decision, 2026-10-25). What a real hour would report is not claimed: the captured share against the Bybit archive, the slice sizes, the health signals and the number of `exchange_ts` ordering violations. The ordering of the provider's `exchange_ts` stays an **assumption**; the 300 s / 50 000 trades / 20 000 messages bounds are accepted, not measured. +- **Nothing is deployed.** The server runs the code deployed before DG-O: it still supersedes each cycle and closes its WebSocket between cycles until the operator promotes and restarts it. The default of the CLI, the environment examples and the units is `cycles`; enabling the continuous mode is an operator step, and making it the default is the maintainer's decision after a real run. - No non-BTC dataset is registered in the server catalog, so none is readable there yet: the maintainer's existing ETH/SOL/XRP/DOGE Parquet are not registered (they cannot be certified, Amendment 1) and are to be replaced by the archive import, an operator step not yet done. The server-side record-by-record proof of BTCUSDT 2024-01-15 and any real-host run are operator evidence and are not claimed. - No capacity is measured (#378): the daily volume, memory and disk figures offered for other instruments are not used, and nothing beyond the bounded `ETHUSDT` proof is enabled before the measurement and the 365-day rule. -- DG-O: nothing is implemented. The live path still supersedes each cycle with the next and still closes its WebSocket between cycles. The existing live partitions and their superseded revisions are left as they are and are not repaired (recovery is paused: if a gap makes the data unusable, the history is re-ingested from scratch). Slices are not consolidated into a day partition. The provider's `exchange_ts` ordering is an assumption until `O03` measures it. +- DG-O: the existing live partitions and their superseded revisions are left as they are. Slices are not consolidated into a day partition. After a reconnect the session waits for the first trade of the new subscription before reconciling (a quiet interval delays it; a REST window that does not meet the subscription is an explicit gap): how often that happens is unmeasured. The `known_gap` span ends at the local detection instant; the evidence tool classifies missing trades against it. +- DG-R: nothing is implemented and no legacy day has been rebuilt or retired. The 2026-10-20 evidence is operator-reported; the ID comparison does not establish field equality (the proof is `R02`'s). The 31 candidate dates are not an execution plan: the days come only from a reviewed plan. The atomic replacement is considered and not adopted (ADR-0074 A2.8). Nothing is deleted; retention of retired or superseded revisions is the maintainer's. Running the rebuild on the server is an operator step. - No deployment, no L2 for other instruments, no second venue, no spot or inverse market, no repair or backfill of live gaps. - The generic provider `E07`, the FEI line and Omega are untouched. --- +## Closeout result (#527) + +`T03`, `T02` (parts 1 to 5 and the closing `O03`), `O01`, `O02` and `O03` are merged into `implement/fid` and credited `COMPLETE` within the bounds their rows in `CAPABILITY_DAG.md` record, each with mutation-checked tests, real-PostgreSQL integration where it publishes, and independent review findings fixed. The inventory is 110 of 132 (83.3%), recomputed from the DAG rows by script and equal across the four governance files; no decision-state change. DG-R (`R01`, `R02`) is untouched. + +## Reopening triggers (none authorized) + +Recorded in full in `docs/architecture/OPEN_DECISIONS.md` ("Closeout of DG-N and DG-O"): (1) the real-provider run and its report; (2) the provider's `exchange_ts` ordering; (3) the bounds; (4) the default mode and the deployment; (5) thin instruments and gaps after a reconnect; (6) the clock of the recorded gap span; (7) capacity (#378) and further instruments; (8) the damaged legacy days (DG-R); (9) consolidation of slices. + +--- + ## Mutation policy - Only `governance/` or `admin/` branches may change `SCOPE.md`, `ROADMAP.md`, `CAPABILITY_MAP.md`, `CAPABILITY_DAG.md` or `OPEN_DECISIONS.md`. Implementation issues leave them untouched and report stale governance in the PR. @@ -137,10 +174,10 @@ Credit, do not reimplement or re-prove absent invalidating evidence: every atom ## Exit criteria for this scope -- `T01`, `T04`, `T03`, `T02` and `O01`, `O02`, `O03` implemented and merged into `implement/fid` within the acceptance above (`T02` closes with `O03`), each with its mutation-checked tests. -- A governance closeout issue credits each atom with its PR and bound and records what is not claimed. -- The operator's promotion PR of `implement/fid` (DG-M, DG-N and DG-O) into `main`, and the declaration that the first version of the product is concluded. -- The Phase A measurements (#378), the production enabling of further live instruments and the deployment are recorded separately; they are not claimed by this scope. +- **Met:** `T01`, `T04`, `T03`, `T02` and `O01`, `O02`, `O03` implemented and merged into `implement/fid` within the acceptance above (`T02` closed with `O03`), each with its mutation-checked tests -- **except** the real-provider run of at least one hour of `O03`, which was not performed and is not claimed (the maintainer's decision, 2026-10-25). `R01` and `R02` (Part D) are post-version: they are not a condition of the declaration below. +- **Met:** a governance closeout issue (#527) credits each atom with its PR and bound and records what is not claimed. +- The promotion of `implement/fid` (DG-M, DG-N and DG-O) into `main`: PR #514 promoted DG-M, DG-N and `O01` on 2026-10-24, before `O02`, `O03` and the closeout; a promotion PR opened after #527 merges carries the rest. The declaration that the first version of the product is concluded is the maintainer's, after the closeout. +- The Phase A measurements (#378), the production enabling of further live instruments, the deployment and the real-provider run are recorded separately; they are not claimed by this scope. --- @@ -150,7 +187,8 @@ Credit, do not reimplement or re-prove absent invalidating evidence: every atom - measured capacity (#378) and enabling live ingest beyond `BTCUSDT` in production; - deployment to the server and any change to the deployment units on the host; - repair or backfill of live gaps (ADR-0044); -- consolidation of slices into a day partition, and the repair or re-publication of the already damaged live days (ADR-0075 item 7); +- consolidation of slices into a day partition (ADR-0075 item 7); the rebuild of the already damaged live days is Part D; +- the atomic replacement of a live revision, automatic repair of live gaps (ADR-0044), and retention or deletion of retired or superseded revisions (ADR-0074 Amendment 2); - the generic provider extension `E07`, the FEI line, Omega, `J11`. --- diff --git a/docs/architecture/OPEN_DECISIONS.md b/docs/architecture/OPEN_DECISIONS.md index f640899..03e318e 100644 --- a/docs/architecture/OPEN_DECISIONS.md +++ b/docs/architecture/OPEN_DECISIONS.md @@ -2,7 +2,7 @@ This document records only decisions that are still live or intentionally deferred. Accepted ADRs/contracts remain semantic authority; [`../product/CAPABILITY_DAG.md`](../product/CAPABILITY_DAG.md) records which atoms each decision blocks and when a branch of a gate family is activated. -## Inventory checkpoint — DG-O registration (#507) +## Inventory checkpoint — DG-N/DG-O closeout (#527) Recomputed from the union of the actual DAG rows and checked against expanded Capability Map rows, preserving both parents' accepted credits. No new atom, @@ -11,15 +11,15 @@ capability or follow-on authorization is created. DG-K/DG-K2 are already on main The [scope verifier](../../SCOPE.md#executable-governance-verification) captures both OIDs. ```text -TOTAL_ATOMS = 130 -CLASSIFIED_ATOMS = 130 +TOTAL_ATOMS = 132 +CLASSIFIED_ATOMS = 132 UNCLASSIFIED_GAPS = 0 -SEMANTIC_FROZEN_OR_RESOLVED = 118 / 130 = 90.8% +SEMANTIC_FROZEN_OR_RESOLVED = 120 / 132 = 90.9% OPEN_BLOCKING = 3 OPEN_DEFERABLE = 9 -ROADMAP_DEFINED = 118 + 3 + 9 = 130 -ROADMAP_PLANNING_COMPLETENESS = 130 / 130 = 100% -IMPLEMENTATION_COMPLETE = 105 / 130 = 80.8% +ROADMAP_DEFINED = 120 + 3 + 9 = 132 +ROADMAP_PLANNING_COMPLETENESS = 132 / 132 = 100% +IMPLEMENTATION_COMPLETE = 110 / 132 = 83.3% ``` ## Resolved foundation — reference only @@ -944,7 +944,7 @@ linear USDT instruments (BTCUSDT, ETHUSDT, SOLUSDT, XRPUSDT, DOGEUSDT) in one co identity with every BTCUSDT identity unchanged; one live process per instrument; ADR-0044 unchanged (explicit gaps, no repair source); existing Parquet enters only through the producer path; a capacity rule (at least 365 days to the critical-pressure threshold) that gates production enabling and waits for the #378 measurements; explicit fees per instrument. Implementation of `T01`, `T04`, `T03`, `T02` is -authorized (`SCOPE.md` Part B): `T01` and `T04` are `COMPLETE` (#489; PR #486, #488), `T03` and `T02` are not started. Amendment 1 +authorized (`SCOPE.md` Part B): `T01` and `T04` are `COMPLETE` (#489; PR #486, #488), `T03` and `T02` are `COMPLETE` within their bounds (closeout #527; PR #492, #494 to #502, #526). Amendment 1 (#487, accepted 2026-10-20) decided the historical source: the Bybit public trade archive for every instrument, BTCUSDT included, with versioned source profiles, certification accepting the SQLite and the archive profile, and the existing Parquet replaced through the archive import instead of registered (their declared CSV source profile was never produced by any commit and S13 refuses it). @@ -958,16 +958,49 @@ BTCUSDT 2024-01-15 (operator steps, with `tools/compare_archive_day.py`); L2 for Designed by #504 (ADR-0075, PR #505), accepted on 2026-10-21 (PR #506) and registered by #507. Decided: one continuous WebSocket session per instance decoupled from publication by a bounded buffer; slices with chained exchange-time windows (300 s or 50 000 trades, never across a UTC -midnight); each slice is revision 1 of its own partition `dt=/seg=` and is never superseded; checkpoint invariants unchanged +midnight); each slice is revision 1 of its own partition `dt=/seg=` and a valid slice is never superseded (Amendment 1, accepted 2026-10-23: a bridge slice with no trade across a +UTC midnight in a reconciliation, and the next revision only over an attempt that never became valid); checkpoint invariants unchanged (it binds a slice partition); interruptions as ADR-0040 section 7 and ADR-0042 section 5 already decide, ADR-0044 unchanged. Implementation of -`O01`, `O02`, `O03` is authorized (`SCOPE.md` Part C) and not started; `T02` closes with `O03`. +`O01`, `O02`, `O03` was authorized (`SCOPE.md` Part C) and is `COMPLETE` within the bounds of the closeout #527 (PR #510, #524, #526); `T02` closed with `O03`. Live follow-ups, none authorized: consolidation of a closed day's slices into one partition (a read optimization, opened only on a measured read or admission cost); the already damaged live days (the superseded revisions and the trades never acquired before the fix), left as they -are with recovery paused, re-ingested from scratch if a gap makes the data unusable; the assumption that the provider's `exchange_ts` is +are by DG-O and rebuilt, day by day, by DG-R once it is implemented; the assumption that the provider's `exchange_ts` is non-decreasing along the stream, measured by `O03`; the retention policy's classification of `superseded` partitions as candidates by age (the cleanup code is the maintainer's and is untouched). +### Closeout of DG-N and DG-O (#527): reopening triggers (none authorized) + +`T03`, `T02`, `O01`, `O02` and `O03` are credited within their bounds. **The one-hour `ETHUSDT` real-provider run of `O03` (the `T02` proof) was not performed; the maintainer +credited the atoms without it (2026-10-25).** Each limit has a named way to reopen: + +1. **Real-provider run.** No continuous session has run against the real Bybit provider for an hour and no report of `tools/live_window_evidence.py` exists. Trigger: the operator + performs the run (procedure in `docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md`) on a host, catalog and root of their choice and records the report. +2. **`exchange_ts` ordering.** That the provider's stream is non-decreasing in `exchange_ts` stays an assumption (ADR-0075 "Not claimed"); a violation is an interruption by design. + Trigger: the report of trigger 1 counts the violations. +3. **The bounds.** 300 s, 50 000 trades and 20 000 messages are accepted, not measured. Trigger: evidence from trigger 1. +4. **Default mode and deployment.** The default of the CLI, the environment examples and the units is `cycles`; the server is not redeployed with `O01` to `O03`; enabling the + continuous mode on a unit is an operator step. Flipping the default is the maintainer's decision after the numbers of trigger 1. +5. **Thin instruments and gaps.** After a reconnect the session waits for the first trade of the new subscription before reconciling; on a quiet interval this delays the + reconciliation, and a REST window that does not meet the subscription is an explicit gap. How often this happens on `ETHUSDT` is unmeasured. Trigger: evidence from trigger 1. +6. **Clock of the recorded gap span.** The `known_gap` span ends at the detection instant of the local clock; the evidence tool classifies missing trades against that span, so a + local clock far behind the exchange could report a trade near the end of a hole as undeclared. Trigger: a false stop observed in a real report. +7. **Capacity and further instruments.** #378 is not measured; nothing beyond the bounded `ETHUSDT` proof is enabled before the measurement and the 365-day rule (ADR-0074 section 6). + No non-BTC dataset is registered in the server catalog; replacing the maintainer's Parquet by the archive import is an operator step. +8. **Damaged legacy days.** Left as they are by DG-O; their rebuild is DG-R (`R01`, `R02`, authorized, post-version) and the run on the server is the operator's. +9. **Consolidation of slices.** Outside the first version; opened only on a measured read or admission cost (ADR-0075). + +## DG-R — Rebuild of damaged legacy live days v1 — RESOLVED (ADR-0074 Amendment 2 `ACCEPTED`, #515) + +Designed by #515 (ADR-0074 Amendment 2, PR #516), accepted on 2026-10-24 (PR #521) and registered by #518. Decided: for explicitly selected, closed UTC days of the +legacy `dt=` publication, retire the damaged live revision with an ordinary ADR-0030 reassessment (`fail` -> `invalid`, nothing deleted), import the whole-day +archive file as revision 1 of `dt=/seg=000000.000` through the ordinary S13/S14 path, verify in full. The ordinary importer keeps refusing an occupied day. +Implementation of `R01` and `R02` is authorized (`SCOPE.md` Part D) and not started; they are post-version. + +Live follow-ups, none authorized: the atomic replacement of a live revision (ADR-0033 cutover extended to a component of adjacent days), opened only if a consumer of +those days appears (A2.8); retention or deletion of retired and superseded legacy revisions (the cleanup code is the maintainer's); the days to rebuild, which come only +from a reviewed plan; who reacts to the state `invalid` (retention, eligibility, admitted inputs), to be checked first by `R01`. + ## Explicitly deferable decisions The following are classified and therefore not roadmap unknowns: diff --git a/docs/decisions/ADR-0074-multi-instrument-bybit-linear-trades-v1.md b/docs/decisions/ADR-0074-multi-instrument-bybit-linear-trades-v1.md index 5c9da65..678d9fe 100644 --- a/docs/decisions/ADR-0074-multi-instrument-bybit-linear-trades-v1.md +++ b/docs/decisions/ADR-0074-multi-instrument-bybit-linear-trades-v1.md @@ -1,7 +1,8 @@ # ADR-0074 - Multi-instrument Bybit linear trades: read, delivery and live ingest v1 **Status:** ACCEPTED (design gate #377, PR #481; accepted by the maintainer 2026-10-19, recorded in issue #377). Amendment 1 -(historical source, design gate #487): ACCEPTED 2026-10-20. +(historical source, design gate #487): ACCEPTED 2026-10-20. Amendment 2 (rebuild of damaged legacy live days, design gate #515): +ACCEPTED 2026-10-24. **Date:** 2026-10-19 Design gate #377; evidence issue #378. Amends ADR-0040, ADR-0043 and the applicability of the Bybit `trade-v1` ordering and @@ -263,3 +264,228 @@ resolved as proposed: 1. **Precision.** Milliseconds, truncated (A1.2 item 4). 2. **Download.** `tools/fetch_bybit_trade_archive.py` fetches days into a staging directory; the import reads the local file. 3. **Re-import of the 2 118 `BTCUSDT` days.** No; an archive import of a day that already has a catalog partition is refused. + +--- + +## Amendment 2 - Rebuild damaged legacy BTCUSDT live days from the archive + +**Status:** ACCEPTED (design gate [#515](https://github.com/NeoNix-Lab/quant-platform/issues/515), PR #516; accepted by the maintainer 2026-10-24, see A2.9) +**Date:** 2026-10-24 + +The accepted ADR and Amendment 1 above remain operative. This amendment is not an +implementation, a governance reconciliation or authority to change production data. The maintainer requested a reviewable reconstruction +proposal after the operator evidence below, and chose the reduced form of it +(2026-10-24): **retire** the damaged legacy day from reads with an ordinary +quality reassessment, then **import** the archive day under a free key. It does +not replace a partition atomically (see A2.8). The bounded implementation is +authorized separately (governance issue #518). + +### A2.1 Problem and evidence + +On `homelab`, the legacy live publisher wrote a new revision of `dt=` for +each batch, superseding the preceding batch rather than accumulating the day. +The archive can supply trades never acquired between cycles; re-enabling the +superseded batches alone cannot restore them. + +Operator-reported checks in the deployment conversation, on producing commit +`fc69cc17e8f8aeee1326d1b26287b8db1e61b73d`, establish the following bounded facts. +These are supplied operational evidence, not a new independent server audit. + +| Check | Result | +| --- | --- | +| Catalog inventory | 31 candidate dates, 2026-09-23 through 2026-10-23; 85,056 superseded legacy revisions, 24,160,325 declared rows; 9,908 declared rows in valid legacy revisions. Totals are not unique-trade counts. | +| 2026-10-20 local files | 3,326 distinct readable Parquet footers; all row counts match the catalog; 1,142,059 rows; 41,257,944 bytes. No full physical-hash check was performed by this inventory. | +| Archive | `BTCUSDT2026-10-20.csv.gz`, 57,387,589 bytes, SHA-256 `d45890283c23973ee061364ff2faf5835dee6dc9c1fee1cbd648375377c4447d`; 1,568,861 rows and unique trade IDs. | +| In-day ID comparison | 1,141,530 local unique IDs, all in the archive; no in-day duplicate or null IDs; 427,331 archive IDs absent locally. Equality of other canonical fields was not tested. | +| Day ownership | 529 local rows fall outside 2026-10-20. Legacy catalog coverage intervals also cross UTC midnight. A partition-key date alone does not delimit the replacement's effects. | + +The inventory is a candidate list, not permission to rebuild every date in it. +The 2026-10-23 sample contains both legacy revisions and new live slices; it is +excluded from the first scope. Whether a day is closed is evaluated in UTC at +execution, not from a local calendar date or this document's date. + +### A2.2 Decision + +Authorize an operator-requested rebuild of explicitly selected, closed UTC days of +`canonical/trades/bybit/BTCUSDT/trade-v1` whose publication is a legacy +`dt=` family (many superseded revisions and one live revision that holds only +the day's last batch). Per selected day, in this order: + +1. **Retire.** Record a superseding quality reassessment of the day's current live + revision, `fail` on completeness, and apply [ADR-0030](ADR-0030-general-quality-lifecycle-v1.md)'s + existing mapping `fail -> invalid`. Nothing is deleted or rewritten: the + revision stays the live (non-superseded) row of its key, now `invalid`, with its + bytes, manifests, quality reports and admissions intact. Every read policy + excludes `invalid`, so the day is no longer served from the damaged batch. +2. **Import.** Import the whole-day archive file of Amendment 1 (same download + identity, strict parsing, millisecond mapping, unique non-empty trade IDs, + half-open UTC-day coverage) through the ordinary S13/S14 path as **revision 1 of + the key `dt=/seg=000000.000`**, `part-001.parquet`: the key grammar of + ADR-0075 section 3 for a window that starts at the day's first instant. The legacy + key stays as it is; the new key is free, so no revision is raised and no + predecessor is superseded. +3. **Verify.** Compare the imported records with the archive file in full + (`tools/compare_archive_day.py`), then read the day through the `DataGateway` + strictly and check count, order and duplicates. + +The ordinary importer keeps its refusal of an occupied day (A1.6 item 3). The +rebuild is a separate operation that treats the retired (`invalid`) legacy revision +of that exact day as not occupying it, and nothing else: a `valid` or `closed` +partition of the day, or any `dt=/seg=...` partition other than the one it +creates, still refuses. It is never a `--force` of the ordinary importer. + +### A2.3 The reassessment writer + +ADR-0030 already defines reassessment: a new, target-bound, immutable quality +report that carries `metrics.supersedes_assessment_signature` of the assessment it +supersedes, and an application step that maps its status to a state. The state +transition exists (`valid` is an allowed source state for `fail`). What does not +exist is a writer of such a report for a revision that is not `closed`: +`record_quality_report` refuses any other state, and the repair path writes reports +only for candidates inside its own cutover. + +The slice adds that writer, in the data plane next to the lifecycle seam, with these +properties: + +- it targets the current live revision of one natural partition, locked in the same + order as the lifecycle application, and refuses a superseded, foreign or + `writing` revision; +- it copies the bound evidence of the assessment it supersedes unchanged (profile, + natural identity, dataset, partition and content hashes, coverage manifest and + assertion identities) and sets the status, the coverage category and a + violation that names the reason (`legacy_publication_incomplete_day`) and the + archive identity that shows it; it carries the producing commit; +- the reassessment is honest: the partition is not corrupt, it is incomplete for + its day, and the report says so; it is idempotent (the same semantic signature + adds no second leaf); +- the lifecycle application then runs through the existing seam, in its own short + transaction (a few milliseconds of the dataset row lock, per partition). + +**Restore.** A later reassessment `pass` that supersedes the `fail` returns the +revision to `valid` by the same seam. It is the documented way back if the import +or its verification fails and the operator prefers the damaged day to no day. + +### A2.4 Plan, preconditions and refusals + +A read-only plan precedes any change and is bound by a digest the executing command +must present. For each selected day it records: the incumbent revision (partition +UUID, key, revision, state, physical and manifest hashes, coverage identities), the +archive file (URL, SHA-256, size, source-observation time, row count), the producing +commit, the key to create and the result of the checks below. A changed incumbent, +source or catalog makes the plan stale; the executor never acquires another target +and never widens the date set. + +A day is refused, and nothing is changed for it, if any of the following holds: + +- the day is not closed in UTC: its end is less than 24 hours before execution; +- the day has a live slice (`dt=/seg=...` other than the one to create), a + checkpoint binding to any of its partitions, or an open gap record that names it; +- its current live revision is not `valid`; +- **conservation fails.** Every record of the incumbent live revision, by + `(exchange_ts, trade_id)`, must be found with equal venue, instrument, exchange + time, side, price and size in the archive file of its own UTC day, and that day + must be readable after the operation (rebuilt in the same plan, or already valid + in the catalog). A record outside the day (the 529 rows of the evidence) is + checked against its own day, not dropped. Any difference in a common field refuses + the day; there is no partial acceptance; +- the archive file fails Amendment 1's strict parsing or its hash differs from the + plan. + +The incumbent live revision of a legacy day holds only the day's last batch; the +superseded revisions are not read today and are not part of the conservation +check. The rebuilt day carries the archive's null `receive_ts` and `sequence`. The +rows that the incumbent revision serves lose the provider `sequence` they have now +(ADR-0040 keeps it as live evidence): this is an accepted, declared loss of +provenance on those rows, recoverable from the retained bytes, and not a claim of the +original session's continuity. + +### A2.5 Readers, concurrency and failure + +- **No atomic switch, by design.** Between *Retire* and *Import* the day is served + by nothing: a strict read refuses with `NoCoverage`; `allow-partial` reports the + gap. The order is chosen so that this is an honest absence and never a state in + which two valid partitions cover the same day (the gateway refuses that overlap). + The days are closed and have no consumer yet (usage tests start after the first + version); the plan states the window per day and the executor does one day at a time. +- **Coherent reads.** `Catalog.select_partitions` selects partitions in one SQL + statement filtered by lifecycle state, so each lifecycle commit is seen whole or + not at all by a reader; the proofs below use that mechanism. +- **Crash and retry.** After a crash between *Retire* and *Import* the day is + retired and unimported; rerunning the plan imports it. After a crash between the + import and the verification the executor finds the valid key it would create + and goes to the verification, which is read-only and repeatable. The attempt is + identified by the plan digest. +- **Concurrency.** The lifecycle application and the import take the same dataset + row lock as the live publication, each for a short transaction. The executor does + not hold a lock across days, the files' reading or the verification. +- **Untouched.** Live checkpoint files, gap evidence, healthy historical days, live + slices, other datasets and all old bytes. No deletion, catalog reset or retention + is part of the operation ([ADR-0049](ADR-0049-retention-deletion-authority-v1.md)). Cleaning + retired or superseded legacy revisions is the maintainer's retention decision. + +### A2.6 Exact effect if accepted + +| Authority | Bounded amendment | +| --- | --- | +| This ADR A1.6 item 3 and occupied-day refusal | Remains the default for ordinary import. The rebuild treats the retired legacy revision of the selected day as not occupying it and imports under `dt=/seg=000000.000`; nothing else is let through. | +| ADR-0075 section 7, delegation item 3 and acceptance item 3 | Lift the pause only for the explicitly selected, closed legacy days; current slices, consolidation and live interruption evidence remain unchanged. | +| ADR-0030 (A16) | No change of meaning. Adds the writer of a reassessment report for a revision that is not `closed` (A2.3). | +| ADR-0033 (A10) | Not used. The first scope does not need an atomic replacement (A2.8); A10 and its triggers are unchanged. | +| ADR-0044 | No amendment: no automatic live-gap repair, no new proof of live continuity. | +| ADR-0018, frozen records and manifests, identity, ordering | Unchanged. The new key uses the accepted two-level grammar; no schema, migration or new control table. | +| S13, S14 | Unchanged; the import uses them as they are. | + +This proposal does not accept ADR-0075 Amendment 1 (#512 / PR #513), resolve #511, +complete O02/O03 or grant capability credit. It changes no governance file. +Acceptance must be recorded explicitly and followed by a separately authorized +implementation issue and, where the active scope requires it, a governance +reconciliation. Production execution follows a reviewed, pinned implementation and a +reviewed date plan. The 31-date inventory is not that plan. + +### A2.7 Required implementation and operational proof + +1. **Writer slice.** The reassessment writer (A2.3) over a disposable PostgreSQL: + `valid -> invalid` and back by a superseding `pass`; the supersession link; the + bound evidence copied unchanged; idempotence; refusal of a superseded, foreign or + stale target; a concurrent publication on the same dataset waits and then + proceeds; a `VALID_ONLY` read excludes the retired revision; the old bytes, + manifests and reports unchanged. +2. **Rebuild slice.** The importer variant, the plan and its digest, the + conservation check, the runbook. Disposable PostgreSQL probes: a retired day is + imported under the new key; a `valid` or `closed` incumbent, a live slice, a + checkpoint binding, an open day, a stale plan and a differing common field each + refuse without changing anything; a crash between *Retire* and *Import* and + another between *Import* and the verification are recovered by rerunning; the + restore path; a neighbouring day with its own retired revision whose legacy + coverage crossed midnight reads correctly. Strict `DataGateway` read of the pilot + day returns exactly 1,568,861 archive records, in order, without duplicates, + with full-field equality to the archive (null `receive_ts` and `sequence` + expected); non-target days and the live checkpoint are byte-identical. +3. **Operation.** Dry-run, execute and verify on `2026-10-20` first; further days + only from a new reviewed plan. Nothing in the production run is claimed by this + proposal. + +The runtime proof is required after implementation; this design-only proposal does +not claim any of those probes passed. + +### A2.8 Considered and not adopted + +An atomic replacement of the live revision (retire and admit the successor in one +transaction, with the predecessor readable until the switch), built on ADR-0033's +cutover and extended to a component of adjacent days with new versioned repair +triggers, provenance and migration, a prospective certification seam in S13, and a +bounded lock hold against the live service. Its cost is several implementation +slices and a lock on the dataset row that the live publication needs, for a benefit +(no read gap) that closed days without consumers do not require. It stays available +as a later amendment if a consumer of these days appears; this proposal does not +close that door. + +### A2.9 Acceptance record + +Accepted by the maintainer on 2026-10-24 ("accetto la #516"), after the maintainer chose the reduced form (retire, then import) +over the atomic replacement of the first draft on 2026-10-24. The text of A2.1 to A2.8 stands as written; the +operator-reported evidence of A2.1 is accepted as evidence, not as an audit. + +Not done by this acceptance: the implementation (`R01`, issue #519; `R02`, issue #520); the governance registration of those +atoms (issue #518); any change of production data; the choice of the days to rebuild, which comes only from a reviewed plan +(A2.4). Cleaning retired or superseded legacy revisions remains the maintainer's retention decision. diff --git a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md index 57311d7..c9409b3 100644 --- a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md +++ b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md @@ -147,6 +147,96 @@ 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 slices 9.2 and 9.3, `O02` and `O03`): opt-in per unit + +`--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 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 This runbook does not automate rollback. If the service fails: diff --git a/docs/product/CAPABILITY_DAG.md b/docs/product/CAPABILITY_DAG.md index af47006..6ff3d4e 100644 --- a/docs/product/CAPABILITY_DAG.md +++ b/docs/product/CAPABILITY_DAG.md @@ -9,7 +9,7 @@ supervised happy-path proof on the smallest real partition; deployability carrie ADR-0072 Amendment 1 bounds and the recorded proof findings. S08 is not authorized, J11 remains deferred, and no Wave 8 or DG-K/DG-K2 Golden proof is claimed. L2 promotion to main is a separate final wave PR; no deployment is performed here. DG-M — Canonical feature identity for deck -results v1 is CLOSED on `implement/fid` (#475). DG-N — Multi-instrument Bybit linear trades v1 is registered and authorized (#483, ADR-0074 `ACCEPTED`): `T01` and `T04` are `COMPLETE` within their row bounds (PR #486, #488; ADR-0074 Amendment 1, #489), `T03` and `T02` are `FROZEN`/`MISSING`. DG-O — Live publication: continuous session and append-only slices v1 is registered and authorized (#507, ADR-0075 `ACCEPTED`): `O01`-`O03` are `FROZEN`/`MISSING`, nothing is implemented, and `T02` additionally requires `O03`. DG-M detail: `M01`, `M02`, `M04` and `M05` are COMPLETE within their row bounds (PR #466, #468, +results v1 is CLOSED on `implement/fid` (#475). DG-N — Multi-instrument Bybit linear trades v1 is registered and authorized (#483, ADR-0074 `ACCEPTED`): `T01` and `T04` are `COMPLETE` within their row bounds (PR #486, #488; ADR-0074 Amendment 1, #489), `T03` and `T02` are `COMPLETE` within their row bounds at the DG-N/DG-O closeout (#527). DG-O — Live publication: continuous session and append-only slices v1 is registered and authorized (#507, ADR-0075 `ACCEPTED`): `O01`-`O03` are `COMPLETE` within their row bounds at the closeout (#527; PR #510, #524, #526), and `T02` additionally required `O03`. The one-hour `ETHUSDT` real-provider run is not claimed. DG-R — Rebuild of damaged legacy live days v1 is registered and authorized (#518, ADR-0074 Amendment 2 `ACCEPTED`): `R01` and `R02` are `FROZEN`/`MISSING`, nothing is implemented. DG-M detail: `M01`, `M02`, `M04` and `M05` are COMPLETE within their row bounds (PR #466, #468, #473, #474) under ADR-0073 and its Amendment 1, `M03` is superseded; the server now seals the identities of the definitions a deck names and the deck builder must declare them. No real-host run is claimed, and promotion into `main` is the operator's separate PR.** @@ -21,19 +21,19 @@ Roadmap readiness is not the same thing as freezing every future semantic choice An atom is roadmap-defined when its observable outcome, owner, dependencies, unlocks, acceptance proposition and decision state are classified, and any unresolved decision is either assigned to an atom-specific blocking gate or has an explicit deferable evidence trigger. -Current audited inventory after the DG-O registration (#507), +Current audited inventory after the DG-N/DG-O closeout (#527), recomputed mechanically from the atom tables, not by hand: ```text -TOTAL_ATOMS = 130 -CLASSIFIED_ATOMS = 130 +TOTAL_ATOMS = 132 +CLASSIFIED_ATOMS = 132 UNCLASSIFIED_GAPS = 0 -SEMANTIC_FROZEN_OR_RESOLVED = 118 / 130 = 90.8% +SEMANTIC_FROZEN_OR_RESOLVED = 120 / 132 = 90.9% OPEN_BLOCKING = 3 OPEN_DEFERABLE = 9 -ROADMAP_DEFINED = 118 + 3 + 9 = 130 -ROADMAP_PLANNING_COMPLETENESS = 130 / 130 = 100% -IMPLEMENTATION_COMPLETE = 105 / 130 = 80.8% +ROADMAP_DEFINED = 120 + 3 + 9 = 132 +ROADMAP_PLANNING_COMPLETENESS = 132 / 132 = 100% +IMPLEMENTATION_COMPLETE = 110 / 132 = 83.3% ``` Reconciliation #444 preserves all accepted DG-K/DG-K2 credits from main and @@ -43,7 +43,16 @@ invented by this merge; the seven L2 subatoms and eight S atoms were already registered on their respective lines. [SCOPE.md](../../SCOPE.md#executable-governance-verification) contains the executable two-parent verification. -DG-O registration and authorization (issue #507): ADR-0075 is `ACCEPTED` (#504, 2026-10-21). Three atoms `O01`-`O03` are added directly as +DG-N/DG-O closeout (issue #527): `T03`, `T02`, `O01`, `O02` and `O03` move from `MISSING` to `COMPLETE` on `implement/fid` within the bounds their rows record (105 -> 110 of 132; +implementation 79.5% -> 83.3%); no new atom and no decision-state change (120 decided, 3 `OPEN_BLOCKING`, 9 `OPEN_DEFERABLE`). `R01` and `R02` stay `FROZEN`/`MISSING`. The +one-hour `ETHUSDT` real-provider run of `O03` / `T02` is **not** performed and not claimed (the maintainer's decision, 2026-10-25). The counts are recomputed from these tables by script. +Promotion into `main` is the operator's separate PR. + +Earlier, DG-R registration and authorization (issue #518): ADR-0074 Amendment 2 is `ACCEPTED` (#515, 2026-10-24). Two atoms `R01` and `R02` are added directly as +`FROZEN`/`MISSING` (130 -> 132 atoms; 118 -> 120 decided); no existing atom changes state. `O01` is merged (PR #510) and is credited by the DG-O closeout, not here; +its row text is reconciled with ADR-0075 Amendment 1. The counts above are recomputed from these tables by script. + +Earlier, DG-O registration and authorization (issue #507): ADR-0075 is `ACCEPTED` (#504, 2026-10-21). Three atoms `O01`-`O03` are added directly as `FROZEN`/`MISSING` (127 -> 130 atoms; 115 -> 118 decided); no existing atom changes state, and `T02` gains the requirement `O03` (its one-hour `ETHUSDT` proof is the one of `O03`). `T03` and `T02` parts 1 to 5 are merged and are credited by the DG-N closeout, not here. The counts above are recomputed from these tables by script. @@ -171,6 +180,7 @@ S Server/deck composition (DG-K2) M Feature identity (DG-M) T Multi-instrument trades (DG-N) O Live publication (DG-O) +R Rebuild of damaged legacy live days (DG-R) ``` The implemented ownership direction remains governed by ADR-0024 and architecture tests. `application` composes existing capabilities and owns no quantitative meaning. @@ -382,24 +392,33 @@ Registered by governance issue #453 after the DG-K2 closeout (#409); the design ### T — Multi-instrument Bybit linear trades (DG-N) -Registered and authorized by governance issue #483 after the design gate #377 produced ADR-0074, `ACCEPTED` on 2026-10-19 (PR #482). The maintainer wants to read, deliver and ingest live the Bybit linear USDT instruments BTCUSDT, ETHUSDT, SOLUSDT, XRPUSDT and DOGEUSDT, and to run this work in the current wave (`implement/fid`). `SCOPE.md` Part B records the start gate and the acceptance of each atom; the order is `T01`, `T04`, `T03`, `T02`. `T01` and `T04` are `COMPLETE` on `implement/fid` (reconciliation #489); `T03` and `T02` are not implemented. +Registered and authorized by governance issue #483 after the design gate #377 produced ADR-0074, `ACCEPTED` on 2026-10-19 (PR #482). The maintainer wants to read, deliver and ingest live the Bybit linear USDT instruments BTCUSDT, ETHUSDT, SOLUSDT, XRPUSDT and DOGEUSDT, and to run this work in the current wave (`implement/fid`). `SCOPE.md` Part B records the start gate and the acceptance of each atom; the order is `T01`, `T04`, `T03`, `T02`. `T01` and `T04` are `COMPLETE` on `implement/fid` (reconciliation #489); `T03` and `T02` are `COMPLETE` within their bounds at the closeout (#527). | ID | Capability | Owner | Requires | Unlocks | Decision | Impl | Acceptance / authority | |---|---|---|---|---|---|---|---| | T01 | Multi-instrument read and delivery v1 | Data Access/Application | A06, A08, A09, K12 | T04, T03, T02 | FROZEN | COMPLETE | ADR-0074 §1, §2, §5 (accepted; authorized by #483). The closed constant `BYBIT_LINEAR_TRADE_INSTRUMENTS_V1` (BTCUSDT, ETHUSDT, SOLUSDT, XRPUSDT, DOGEUSDT) drives the ordering and eligibility applicability; a non-BTC dataset is read, admitted and delivered end to end (`DataGateway`, K12 `admit`/`deliver`); a read-only check of the catalog for the allow-list; what is missing enters the catalog only through the producer path (for the existing Parquet, by the archive import of ADR-0074 Amendment 1, not by registration); BTC identities and ordering key unchanged. Credited `COMPLETE` at the DG-N reconciliation (#489): #485 / PR #486 on `implement/fid`; the allow-list constant drives the ordering and eligibility applicability for all five instruments, each read through the `DataGateway` and admitted and delivered through K12 end to end on real Parquet and the J14 transfers, plus a read-only catalog check; mutation-checked; BTC identities and ordering key unchanged. The registration of the existing Parquet was superseded by ADR-0074 Amendment 1 (they are replaced through the archive import). Not claimed: that any non-BTC dataset is registered in the server catalog, a real-host run. | | T04 | Historical import per instrument v1 | Source/Producer | A07, T01 | T02 | FROZEN | COMPLETE | ADR-0074 §4 and Amendment 1 (accepted; authorized by #483, re-scoped by #487). `--instrument` over the allow-list for the one-UTC-day historical import from the Bybit public trade archive (a local file, no network call in the producer path); history enters only through the producer path; no repair of live gaps (ADR-0044 stands). Credited `COMPLETE` at the DG-N reconciliation (#489): #487 / PR #488 on `implement/fid`; ADR-0074 Amendment 1 (accepted 2026-10-20) names the Bybit public trade archive as the historical source of every instrument; the archive adapter, the SQLite and archive certification profiles (no mixtures), the one-UTC-day import with `--instrument` through the producer path (S13, S14) under a per-day lock, the fetch, import and compare tools, the runbook and a PostgreSQL integration test in CI; BTCUSDT 2024-01-15 from the archive equals the SQLite golden on aggregates. Not claimed: the server-side record-by-record proof, a real-host run, any download or replacement of the existing files. | -| T03 | Explicit per-instrument fees v1 | Execution | H02, T01 | T02 | FROZEN | MISSING | ADR-0074 §7 (accepted; authorized by #483). Fee parameters are explicit per instrument; an execution or replay over a dataset whose instrument is not BTCUSDT and that names no fee schedule is refused (fail-closed); BTCUSDT behaviour unchanged. | -| T02 | Live trades ingest per instrument v1 | Data Plane/Operations | A11, K10, T01, T03, T04, O03 | multi-asset live research | FROZEN | MISSING | ADR-0074 §3, §6 (accepted; authorized by #483). Adapter and server parameterized by instrument; one process per instrument with its own checkpoint and subject (`quant-platform-live-ingest@.service`, runbook); two instances proved not to collide on checkpoints, partitions or catalog rows; one hour of real provider traffic for ETHUSDT (delivered by `O03`); deployment is a manual operator step and the capacity rule gates enabling beyond BTCUSDT. | +| T03 | Explicit per-instrument fees v1 | Execution | H02, T01 | T02 | FROZEN | COMPLETE | ADR-0074 §7 (accepted; authorized by #483). Fee parameters are explicit per instrument; an execution or replay over a dataset whose instrument is not BTCUSDT and that names no fee schedule is refused (fail-closed); BTCUSDT behaviour unchanged. Credited `COMPLETE` at the DG-N/DG-O closeout (#527): #491 / PR #492 on `implement/fid`; the explicit fee schedule per instrument, the refusal (fail-closed, stable reason) of an execution or replay over a non-BTCUSDT dataset that names no schedule, mutation-checked; BTCUSDT behaviour unchanged. Not claimed: any fee value for another instrument. | +| T02 | Live trades ingest per instrument v1 | Data Plane/Operations | A11, K10, T01, T03, T04, O03 | multi-asset live research | FROZEN | COMPLETE | ADR-0074 §3, §6 (accepted; authorized by #483). Adapter and server parameterized by instrument; one process per instrument with its own checkpoint and subject (`quant-platform-live-ingest@.service`, runbook); two instances proved not to collide on checkpoints, partitions or catalog rows; one hour of real provider traffic for ETHUSDT (delivered by `O03`); deployment is a manual operator step and the capacity rule gates enabling beyond BTCUSDT. Credited `COMPLETE` at the DG-N/DG-O closeout (#527), within the bound of its code, configuration, runbook and tests: parts 1 to 5 #493 / PR #494, #495 / PR #496, #497 / PR #498, #499 / PR #500, #501 / PR #502 (adapter, acquisition, publication, checkpoint, restart, server, CLI, template unit, per-instance environment, runbook, and the proof that two instances on one catalog do not collide on checkpoints, partitions or catalog rows), closed by `O03` (#525 / PR #526: the continuous-session configuration, the runbook and the evidence tool that produces the one-hour report). **Not claimed: the one-hour `ETHUSDT` real-provider run itself** (operator evidence, trigger in `OPEN_DECISIONS.md`), a deployment, a non-BTC dataset registered on the server, the capacity (#378). | ### O — Live publication: continuous session and append-only slices (DG-O) -Registered and authorized by governance issue #507 after the design gate #504 produced ADR-0075, `ACCEPTED` on 2026-10-21 (PR #505, #506). Measured on the maintainer's server on 2026-10-21: the live publication supersedes every cycle with the next (a day reads as under 0.4% of its published trades) and the loop closes its WebSocket between cycles (about 27% of a day's trades are never acquired). `SCOPE.md` Part C records the start gate and the acceptance of each atom; the order is `O01`, `O02`, `O03`. No atom here is implemented. `T02` requires `O03`: its one-hour `ETHUSDT` proof is the one of `O03`. +Registered and authorized by governance issue #507 after the design gate #504 produced ADR-0075, `ACCEPTED` on 2026-10-21 (PR #505, #506). Measured on the maintainer's server on 2026-10-21: the live publication supersedes every cycle with the next (a day reads as under 0.4% of its published trades) and the loop closes its WebSocket between cycles (about 27% of a day's trades are never acquired). `SCOPE.md` Part C records the start gate and the acceptance of each atom; the order is `O01`, `O02`, `O03`. `O01`-`O03` are `COMPLETE` within their bounds at the closeout (#527). `T02` required `O03`: its one-hour `ETHUSDT` proof is the one of `O03`. + +| ID | Capability | Owner | Requires | Unlocks | Decision | Impl | Acceptance / authority | +|---|---|---|---|---|---|---|---| +| O01 | Append-only live slices v1 | Data Plane/Application | A11, K10, T01 | O02 | FROZEN | COMPLETE | ADR-0075 §2 to §4 (accepted; authorized by #507). A slice is the trades of one instrument in a half-open exchange-time window, closed after `slice_seconds` (300) or `slice_max_trades` (50 000) at a message boundary and never crossing a UTC midnight; each slice is revision 1 of its own partition `dt=/seg=` and a valid slice is never superseded (Amendment 1: only an attempt that never became valid is replaced by the next revision, and a reconciliation across a UTC midnight publishes a slice with no trade); windows of one session chain exactly; the checkpoint binds a slice partition; the live certification profile accepts the key grammar and checks the chain. Ends F1 (a day reads as its last cycle). Credited `COMPLETE` at the DG-N/DG-O closeout (#527): #509 / PR #510 (+ #511 audit findings, ADR-0075 Amendment 1 #512 / PR #513); append-only slices, chained windows, the checkpoint bound to a slice, a valid slice never superseded, mutation-checked, real-PostgreSQL integration. Not claimed: that the existing damaged days are repaired (DG-R), consolidation, a deployment. | +| O02 | Continuous live session v1 | Data Plane/Operations | O01 | O03 | FROZEN | COMPLETE | ADR-0075 §1, §5 (accepted; authorized by #507). One WebSocket session per instance, decoupled from publication by a bounded buffer (20 000 messages); a buffer overflow, a disconnect or an ordering violation is an interruption handled by ADR-0040 §7 and ADR-0042 §5 (reconcile from the last durable key or record an explicit gap; ADR-0044 unchanged); signals for the buffer and the interruptions. Ends F2 (about 27% of a day's trades never acquired). Credited `COMPLETE` at the DG-N/DG-O closeout (#527): #523 / PR #524; one session per instance, bounded buffer, the four interruptions, subscribe first and wait for the first trade of the subscription before reconciling with an overlap proof (else an explicit gap), signals; scripted-provider proof and a PostgreSQL integration, mutation-checked; independent review findings (continuity without overlap, empty frames, heartbeat history, high-water) fixed. Not claimed: behaviour against the real provider (ordering of `exchange_ts`, ping policy, thin instruments), a deployment. | +| O03 | Live slice configuration, runbook and real-provider proof v1 | Data Plane/Operations | O02, T03, T04 | T02 | FROZEN | COMPLETE | ADR-0075 §9.3 (accepted; authorized by #507). `slice_seconds`, `slice_max_trades` and the buffer bound in the unit templates and the runbook; a real-provider run of at least one hour for ETHUSDT that reports the trades captured against the Bybit archive of the same day, the trades readable through the DataGateway and the number of `exchange_ts` ordering violations. This is the one-hour proof of `T02`. Credited `COMPLETE` at the DG-N/DG-O closeout (#527), within the bound of its code, configuration, runbook and evidence tool: #525 / PR #526; `--mode {cycles,continuous}` (default `cycles`) and the three bounds in the CLI, both unit templates and both environment examples (an environment file that predates them still starts the unit), the runbook, and `tools/live_window_evidence.py` (read-only: the archive against a strict `DataGateway` read of the claimed windows, each missing trade classified against the recorded gap spans or signalled spans, stop conditions), PostgreSQL integration, mutation-checked; independent review findings fixed. **Not claimed: the real-provider run of at least one hour and its report** (the maintainer's decision of 2026-10-25: credited without it; operator evidence), the measurement of the provider's `exchange_ts` ordering, of the captured share and of the bounds, a deployment. | + +### R — Rebuild of damaged legacy live days (DG-R) + +Registered and authorized by governance issue #518 after the design gate #515 produced ADR-0074 Amendment 2, `ACCEPTED` on 2026-10-24 (PR #516 and #521). Operator-reported evidence (2026-10-23/24, not an audit): 31 candidate legacy days, 2026-09-23 to 2026-10-23; for 2026-10-20 the archive has 1,568,861 trades and the local in-day unique IDs are 1,141,530 (427,331 absent; 529 rows outside the day). `SCOPE.md` Part D records the start gate and the acceptance of each atom; the order is `R01`, `R02`. No atom here is implemented, and no legacy day has been rebuilt. They are post-version work: they do not block `O02` or `O03`. | ID | Capability | Owner | Requires | Unlocks | Decision | Impl | Acceptance / authority | |---|---|---|---|---|---|---|---| -| O01 | Append-only live slices v1 | Data Plane/Application | A11, K10, T01 | O02 | FROZEN | MISSING | ADR-0075 §2 to §4 (accepted; authorized by #507). A slice is the trades of one instrument in a half-open exchange-time window, closed after `slice_seconds` (300) or `slice_max_trades` (50 000) at a message boundary and never crossing a UTC midnight; each slice is revision 1 of its own partition `dt=/seg=` and is never superseded; windows of one session chain exactly; the checkpoint binds a slice partition; the live certification profile accepts the key grammar and checks the chain. Ends F1 (a day reads as its last cycle). | -| O02 | Continuous live session v1 | Data Plane/Operations | O01 | O03 | FROZEN | MISSING | ADR-0075 §1, §5 (accepted; authorized by #507). One WebSocket session per instance, decoupled from publication by a bounded buffer (20 000 messages); a buffer overflow, a disconnect or an ordering violation is an interruption handled by ADR-0040 §7 and ADR-0042 §5 (reconcile from the last durable key or record an explicit gap; ADR-0044 unchanged); signals for the buffer and the interruptions. Ends F2 (about 27% of a day's trades never acquired). | -| O03 | Live slice configuration, runbook and real-provider proof v1 | Data Plane/Operations | O02, T03, T04 | T02 | FROZEN | MISSING | ADR-0075 §9.3 (accepted; authorized by #507). `slice_seconds`, `slice_max_trades` and the buffer bound in the unit templates and the runbook; a real-provider run of at least one hour for ETHUSDT that reports the trades captured against the Bybit archive of the same day, the trades readable through the DataGateway and the number of `exchange_ts` ordering violations. This is the one-hour proof of `T02`. | +| R01 | Superseding reassessment writer v1 | Data Plane | A16, A08, A09 | R02 | FROZEN | MISSING | ADR-0074 Amendment 2 A2.3 (accepted; authorized by #518). A writer of a target-bound reassessment report for the current live revision of a natural partition that is not `closed` (today `record_quality_report` refuses it): it copies the bound evidence of the superseded assessment, carries `metrics.supersedes_assessment_signature`, and is applied through the existing ADR-0030 seam (`fail` -> `invalid`; a superseding `pass` restores `valid`); nothing is deleted or rewritten; idempotent; locks in the lifecycle order. | +| R02 | Legacy-day rebuild: plan, retire, import, verify v1 | Source/Application | R01, T04 | BTCUSDT live-era history readable | FROZEN | MISSING | ADR-0074 Amendment 2 A2.2, A2.4 to A2.7 (accepted; authorized by #518). For explicitly selected, closed UTC days of the damaged legacy `dt=` publication: a read-only plan with a digest, retire the live revision (`R01`), import the archive day as revision 1 of `dt=/seg=000000.000` through the ordinary S13/S14 path, verify in full and through the DataGateway; refusals (open day, slices, checkpoint binding, conservation, differing field, stale plan); the ordinary importer still refuses an occupied day. | ## Dependency integrity @@ -586,7 +605,7 @@ M01 ──> M02 ──> M04 ──> M05 (M03 superseded) ### DG-N — Multi-instrument Bybit linear trades v1 — CLOSED (design gate; ADR-0074 `ACCEPTED`, #377) -Closed by ADR-0074: a closed allow-list of five Bybit linear USDT instruments, per-instrument dataset, subject and checkpoint identity, one live process per instrument, ADR-0044 unchanged for gaps, a capacity rule that gates production enabling on the #378 measurements, explicit fees per instrument. Implementation of `T01`-`T04` was authorized by #483; `T01` and `T04` are `COMPLETE` (#489) and `T03` and `T02` are not started. ADR-0074 Amendment 1 (accepted 2026-10-20, #487) chose the Bybit public trade archive as the historical source. Fixed inputs (not reopened): ADR-0040, ADR-0042, ADR-0043, ADR-0044, no change of any BTCUSDT identity byte. Out of scope: a second venue (`A12`), spot and inverse, L2 for other instruments, a generic provider resolver, measured capacity. +Closed by ADR-0074: a closed allow-list of five Bybit linear USDT instruments, per-instrument dataset, subject and checkpoint identity, one live process per instrument, ADR-0044 unchanged for gaps, a capacity rule that gates production enabling on the #378 measurements, explicit fees per instrument. Implementation of `T01`-`T04` was authorized by #483; `T01` and `T04` are `COMPLETE` (#489) and `T03` and `T02` are `COMPLETE` within their bounds (#527). ADR-0074 Amendment 1 (accepted 2026-10-20, #487) chose the Bybit public trade archive as the historical source. Fixed inputs (not reopened): ADR-0040, ADR-0042, ADR-0043, ADR-0044, no change of any BTCUSDT identity byte. Out of scope: a second venue (`A12`), spot and inverse, L2 for other instruments, a generic provider resolver, measured capacity. ```text T01 ──> T04 ──> T03 ──> T02 @@ -594,12 +613,20 @@ T01 ──> T04 ──> T03 ──> T02 ### DG-O — Live publication: continuous session and append-only slices v1 — CLOSED (design gate; ADR-0075 `ACCEPTED`, #504) -Closed by ADR-0075: one continuous WebSocket session per instance decoupled from publication by a bounded buffer; slices with chained exchange-time windows (300 s or 50 000 trades); each slice is revision 1 of its own partition `dt=/seg=`, never superseded; interruptions follow ADR-0040 §7 and ADR-0042 §5, ADR-0044 unchanged. Implementation of `O01`-`O03` is authorized by #507 and not started. Not decided (deferred, with a measured trigger): consolidation of a closed day's slices into one partition. Not repaired (paused by the maintainer): the already damaged live days, which stay as they are; if a gap makes the data unusable the history is re-ingested from scratch. Assumption to be measured by `O03`: the provider's `exchange_ts` is non-decreasing along the stream. Out of scope: a second venue (`A12`), L2, any change to `trade-v1`, the ordering key, `TradeKeyV1` or the J02 wire. +Closed by ADR-0075: one continuous WebSocket session per instance decoupled from publication by a bounded buffer; slices with chained exchange-time windows (300 s or 50 000 trades); each slice is revision 1 of its own partition `dt=/seg=`, never superseded; interruptions follow ADR-0040 §7 and ADR-0042 §5, ADR-0044 unchanged. Implementation of `O01`-`O03` was authorized by #507; all three are `COMPLETE` within their bounds (#527), without the real-provider run. Not decided (deferred, with a measured trigger): consolidation of a closed day's slices into one partition. The already damaged live days are not repaired by DG-O; DG-R (ADR-0074 Amendment 2) rebuilds explicitly selected closed days from the Bybit archive. Assumption, still not measured (the `O03` run is not performed): the provider's `exchange_ts` is non-decreasing along the stream. Out of scope: a second venue (`A12`), L2, any change to `trade-v1`, the ordering key, `TradeKeyV1` or the J02 wire. ```text O01 ──> O02 ──> O03 ──> T02 ``` +### DG-R — Rebuild of damaged legacy live days v1 — CLOSED (design gate; ADR-0074 Amendment 2 `ACCEPTED`, #515) + +Closed by ADR-0074 Amendment 2: for explicitly selected, closed UTC days, retire the damaged live revision with an ordinary ADR-0030 reassessment (`fail` -> `invalid`; nothing deleted), import the whole-day archive file as revision 1 of `dt=/seg=000000.000` through the ordinary S13/S14 path, verify in full. The first draft's atomic replacement (ADR-0033 cutover extended to a component of adjacent days) is considered and not adopted (A2.8). Implementation of `R01` and `R02` is authorized by #518 and not started. Not decided: the atomic replacement, until a consumer of those days appears. Out of scope: consolidation of slices, automatic repair of live gaps (ADR-0044), retention or deletion of retired or superseded revisions, any change to `trade-v1`, the ordering key, `TradeKeyV1` or the J02 wire. + +```text +R01 ──> R02 +``` + ## Vertical milestones | ID | Path | Proposition | State | @@ -742,8 +769,9 @@ DG-K2 Server/deck deployment composition COMPLETE within recorded DG-C/L2 L2 historical v1 (#442) COMPLETE on implement/l2: A14,A14a-A14e; golden #413/#430 11/11; A14f/A14g held MISSING; separate L2 promotion to main DG-M Canonical feature identity for deck results v1 COMPLETE within recorded bounds on implement/fid (closeout #475); M01,M02,M04,M05; M03 superseded; no real-host run claimed -DG-N Multi-instrument Bybit linear trades v1 IN PROGRESS on implement/fid (#483, #489; ADR-0074 ACCEPTED #377 and Amendment 1); T01,T04 COMPLETE; T03,T02 FROZEN/MISSING -DG-O Live publication: continuous session and append-only slices v1 AUTHORIZED (#507; ADR-0075 ACCEPTED #504); O01,O02,O03 FROZEN/MISSING; nothing implemented +DG-N Multi-instrument Bybit linear trades v1 CLOSED within bounds on implement/fid (#483, #489, #527; ADR-0074 ACCEPTED #377 and Amendment 1); T01,T04,T03,T02 COMPLETE (the one-hour ETHUSDT run is not claimed) +DG-O Live publication: continuous session and append-only slices v1 CLOSED within bounds on implement/fid (#507, #527; ADR-0075 ACCEPTED #504); O01,O02,O03 COMPLETE (no real-provider run) +DG-R Rebuild of damaged legacy live days v1 AUTHORIZED (#518; ADR-0074 Amendment 2 ACCEPTED #515); R01,R02 FROZEN/MISSING; post-version; nothing implemented Wave 9 Reinforcement Learning I06 strategic RL, I07 execution RL Wave 10 Paper / Live product J07 then J08 after required data/execution/ops gates ``` diff --git a/docs/product/CAPABILITY_MAP.md b/docs/product/CAPABILITY_MAP.md index 7beb939..99d96a9 100644 --- a/docs/product/CAPABILITY_MAP.md +++ b/docs/product/CAPABILITY_MAP.md @@ -133,11 +133,13 @@ Implementation-state vocabulary is exactly `COMPLETE | PARTIAL | MISSING`. | Feature identity | Deck feature-identity declaration and proof v1 | FROZEN | COMPLETE | Client/Operations | M05 | DG-M (#453, design gate #454, ADR-0073 accepted #457, authorized by #458). The deck builder no longer adds definition references itself and refuses `definition_not_declared`; K13 `_validate_run_compatibility` unchanged and now non-vacuous; the four facts of §8 proved on `PostgresSplitTopology`, with the omission case refused and zero writes asserted. Amendment 2 of ADR-0072 §5 is appended by this atom. The server attests the admitted name, not the deck's computation. Credited `COMPLETE` at the DG-M closeout (#475): #464 / PR #474 on `implement/fid`; ADR-0072 Amendment 2 (§5 item 2); the four facts of ADR-0073 §8 proved on `PostgresSplitTopology` (CI; also 18 of 18 run in WSL on PostgreSQL 16). The real-host run is operator evidence and is not claimed. | | Instruments | Multi-instrument read and delivery v1 | FROZEN | COMPLETE | Data Access/Application | T01 | DG-N (#377, ADR-0074 accepted #482, authorized by #483). The closed constant `BYBIT_LINEAR_TRADE_INSTRUMENTS_V1` (BTCUSDT, ETHUSDT, SOLUSDT, XRPUSDT, DOGEUSDT) drives the ordering and eligibility applicability; a non-BTC dataset is read, admitted and delivered end to end (`DataGateway`, K12 `admit`/`deliver`); a read-only check of the catalog for the allow-list; what is missing enters the catalog only through the producer path (for the existing Parquet, by the archive import of ADR-0074 Amendment 1, not by registration); BTC identities and ordering key unchanged. Credited `COMPLETE` at the DG-N reconciliation (#489): #485 / PR #486 on `implement/fid`; the allow-list constant drives the ordering and eligibility applicability for all five instruments, each read through the `DataGateway` and admitted and delivered through K12 end to end on real Parquet and the J14 transfers, plus a read-only catalog check; mutation-checked; BTC identities and ordering key unchanged. The registration of the existing Parquet was superseded by ADR-0074 Amendment 1 (they are replaced through the archive import). Not claimed: that any non-BTC dataset is registered in the server catalog, a real-host run. | | Instruments | Historical import per instrument v1 | FROZEN | COMPLETE | Source/Producer | T04 | DG-N (#377, ADR-0074 accepted #482, authorized by #483). `--instrument` over the allow-list for the one-UTC-day historical import from the Bybit public trade archive (ADR-0074 Amendment 1; a local file, no network call in the producer path); history enters only through the producer path; no repair of live gaps (ADR-0044 stands). Credited `COMPLETE` at the DG-N reconciliation (#489): #487 / PR #488 on `implement/fid`; ADR-0074 Amendment 1 (accepted 2026-10-20) names the Bybit public trade archive as the historical source of every instrument; the archive adapter, the SQLite and archive certification profiles (no mixtures), the one-UTC-day import with `--instrument` through the producer path (S13, S14) under a per-day lock, the fetch, import and compare tools, the runbook and a PostgreSQL integration test in CI; BTCUSDT 2024-01-15 from the archive equals the SQLite golden on aggregates. Not claimed: the server-side record-by-record proof, a real-host run, any download or replacement of the existing files. | -| Instruments | Explicit per-instrument fees v1 | FROZEN | MISSING | Execution | T03 | DG-N (#377, ADR-0074 accepted #482, authorized by #483). Fee parameters are explicit per instrument; an execution or replay over a dataset whose instrument is not BTCUSDT and that names no fee schedule is refused (fail-closed); BTCUSDT behaviour unchanged. | -| Instruments | Live trades ingest per instrument v1 | FROZEN | MISSING | Data Plane/Operations | T02 | DG-N (#377, ADR-0074 accepted #482, authorized by #483). Adapter and server parameterized by instrument; one process per instrument with its own checkpoint and subject (`quant-platform-live-ingest@.service`, runbook); two instances proved not to collide on checkpoints, partitions or catalog rows; one hour of real provider traffic for ETHUSDT (delivered by `O03`); deployment is a manual operator step and the capacity rule gates enabling beyond BTCUSDT. | -| Live publication | Append-only live slices v1 | FROZEN | MISSING | Data Plane/Application | O01 | DG-O (#504, ADR-0075 accepted, authorized by #507). A slice is the trades of one instrument in a half-open exchange-time window, closed after `slice_seconds` (300) or `slice_max_trades` (50 000) at a message boundary and never crossing a UTC midnight; each slice is revision 1 of its own partition `dt=/seg=` and is never superseded; windows of one session chain exactly; the checkpoint binds a slice partition; the live certification profile accepts the key grammar and checks the chain. Ends F1 (a day reads as its last cycle). | -| Live publication | Continuous live session v1 | FROZEN | MISSING | Data Plane/Operations | O02 | DG-O (#504, ADR-0075 accepted, authorized by #507). One WebSocket session per instance, decoupled from publication by a bounded buffer (20 000 messages); a buffer overflow, a disconnect or an ordering violation is an interruption handled by ADR-0040 §7 and ADR-0042 §5 (reconcile from the last durable key or record an explicit gap; ADR-0044 unchanged); signals for the buffer and the interruptions. Ends F2 (about 27% of a day's trades never acquired). | -| Live publication | Live slice configuration, runbook and real-provider proof v1 | FROZEN | MISSING | Data Plane/Operations | O03 | DG-O (#504, ADR-0075 accepted, authorized by #507). `slice_seconds`, `slice_max_trades` and the buffer bound in the unit templates and the runbook; a real-provider run of at least one hour for ETHUSDT that reports the trades captured against the Bybit archive of the same day, the trades readable through the DataGateway and the number of `exchange_ts` ordering violations. This is the one-hour proof of `T02`. | +| Instruments | Explicit per-instrument fees v1 | FROZEN | COMPLETE | Execution | T03 | DG-N (#377, ADR-0074 accepted #482, authorized by #483). Fee parameters are explicit per instrument; an execution or replay over a dataset whose instrument is not BTCUSDT and that names no fee schedule is refused (fail-closed); BTCUSDT behaviour unchanged. Credited `COMPLETE` at the DG-N/DG-O closeout (#527): #491 / PR #492 on `implement/fid`; the explicit fee schedule per instrument, the refusal (fail-closed, stable reason) of an execution or replay over a non-BTCUSDT dataset that names no schedule, mutation-checked; BTCUSDT behaviour unchanged. Not claimed: any fee value for another instrument. | +| Instruments | Live trades ingest per instrument v1 | FROZEN | COMPLETE | Data Plane/Operations | T02 | DG-N (#377, ADR-0074 accepted #482, authorized by #483). Adapter and server parameterized by instrument; one process per instrument with its own checkpoint and subject (`quant-platform-live-ingest@.service`, runbook); two instances proved not to collide on checkpoints, partitions or catalog rows; one hour of real provider traffic for ETHUSDT (delivered by `O03`); deployment is a manual operator step and the capacity rule gates enabling beyond BTCUSDT. Credited `COMPLETE` at the DG-N/DG-O closeout (#527), within the bound of its code, configuration, runbook and tests: parts 1 to 5 #493 / PR #494, #495 / PR #496, #497 / PR #498, #499 / PR #500, #501 / PR #502 (adapter, acquisition, publication, checkpoint, restart, server, CLI, template unit, per-instance environment, runbook, and the proof that two instances on one catalog do not collide on checkpoints, partitions or catalog rows), closed by `O03` (#525 / PR #526: the continuous-session configuration, the runbook and the evidence tool that produces the one-hour report). **Not claimed: the one-hour `ETHUSDT` real-provider run itself** (operator evidence, trigger in `OPEN_DECISIONS.md`), a deployment, a non-BTC dataset registered on the server, the capacity (#378). | +| Live publication | Append-only live slices v1 | FROZEN | COMPLETE | Data Plane/Application | O01 | DG-O (#504, ADR-0075 accepted, authorized by #507). A slice is the trades of one instrument in a half-open exchange-time window, closed after `slice_seconds` (300) or `slice_max_trades` (50 000) at a message boundary and never crossing a UTC midnight; each slice is revision 1 of its own partition `dt=/seg=` and a valid slice is never superseded (Amendment 1: only an attempt that never became valid is replaced by the next revision, and a reconciliation across a UTC midnight publishes a slice with no trade); windows of one session chain exactly; the checkpoint binds a slice partition; the live certification profile accepts the key grammar and checks the chain. Ends F1 (a day reads as its last cycle). Credited `COMPLETE` at the DG-N/DG-O closeout (#527): #509 / PR #510 (+ #511 audit findings, ADR-0075 Amendment 1 #512 / PR #513); append-only slices, chained windows, the checkpoint bound to a slice, a valid slice never superseded, mutation-checked, real-PostgreSQL integration. Not claimed: that the existing damaged days are repaired (DG-R), consolidation, a deployment. | +| Live publication | Continuous live session v1 | FROZEN | COMPLETE | Data Plane/Operations | O02 | DG-O (#504, ADR-0075 accepted, authorized by #507). One WebSocket session per instance, decoupled from publication by a bounded buffer (20 000 messages); a buffer overflow, a disconnect or an ordering violation is an interruption handled by ADR-0040 §7 and ADR-0042 §5 (reconcile from the last durable key or record an explicit gap; ADR-0044 unchanged); signals for the buffer and the interruptions. Ends F2 (about 27% of a day's trades never acquired). Credited `COMPLETE` at the DG-N/DG-O closeout (#527): #523 / PR #524; one session per instance, bounded buffer, the four interruptions, subscribe first and wait for the first trade of the subscription before reconciling with an overlap proof (else an explicit gap), signals; scripted-provider proof and a PostgreSQL integration, mutation-checked; independent review findings (continuity without overlap, empty frames, heartbeat history, high-water) fixed. Not claimed: behaviour against the real provider (ordering of `exchange_ts`, ping policy, thin instruments), a deployment. | +| Live publication | Live slice configuration, runbook and real-provider proof v1 | FROZEN | COMPLETE | Data Plane/Operations | O03 | DG-O (#504, ADR-0075 accepted, authorized by #507). `slice_seconds`, `slice_max_trades` and the buffer bound in the unit templates and the runbook; a real-provider run of at least one hour for ETHUSDT that reports the trades captured against the Bybit archive of the same day, the trades readable through the DataGateway and the number of `exchange_ts` ordering violations. This is the one-hour proof of `T02`. Credited `COMPLETE` at the DG-N/DG-O closeout (#527), within the bound of its code, configuration, runbook and evidence tool: #525 / PR #526; `--mode {cycles,continuous}` (default `cycles`) and the three bounds in the CLI, both unit templates and both environment examples (an environment file that predates them still starts the unit), the runbook, and `tools/live_window_evidence.py` (read-only: the archive against a strict `DataGateway` read of the claimed windows, each missing trade classified against the recorded gap spans or signalled spans, stop conditions), PostgreSQL integration, mutation-checked; independent review findings fixed. **Not claimed: the real-provider run of at least one hour and its report** (the maintainer's decision of 2026-10-25: credited without it; operator evidence), the measurement of the provider's `exchange_ts` ordering, of the captured share and of the bounds, a deployment. | +| Live publication | Superseding reassessment writer v1 | FROZEN | MISSING | Data Plane | R01 | DG-R (#515, ADR-0074 Amendment 2 accepted, authorized by #518). A writer of a target-bound reassessment report for the current live revision of a natural partition that is not `closed` (today `record_quality_report` refuses it): it copies the bound evidence of the superseded assessment, carries `metrics.supersedes_assessment_signature`, and is applied through the existing ADR-0030 seam (`fail` -> `invalid`; a superseding `pass` restores `valid`); nothing is deleted or rewritten; idempotent; locks in the lifecycle order. | +| Live publication | Legacy-day rebuild: plan, retire, import, verify v1 | FROZEN | MISSING | Source/Application | R02 | DG-R (#515, ADR-0074 Amendment 2 accepted, authorized by #518). For explicitly selected, closed UTC days of the damaged legacy `dt=` publication: a read-only plan with a digest, retire the live revision (`R01`), import the archive day as revision 1 of `dt=/seg=000000.000` through the ordinary S13/S14 path, verify in full and through the DataGateway; refusals (open day, slices, checkpoint binding, conservation, differing field, stale plan); the ordinary importer still refuses an occupied day. | ## Inventory checkpoint — L2/main reconciliation (#444) @@ -199,8 +201,9 @@ IMPLEMENTATION_COMPLETE = 99 / 119 = 83.2% | Wave 8 Full Platform API & Remote Service Topology | COMPLETE (operator closeout #327) | J03/J09/J10/J12/J13/J14/J15/K12/K13 implemented by PR #307-#312, #315, #320, #321 and promoted by PR #322; owner-accepted extras #313/#314 by PR #323/#324 via `implement/wave-8.1` and PR #326. J10/J12/J13 are in-process seams only; no Wave 8 Golden proof artifact is claimed. PR #317 (A14 L2 groundwork) does not complete A14. | | `DG-K2` Server/deck deployment composition (governance #382, #389, #409; design gate #383, #387; Amendment 1 #431) | COMPLETE within recorded bounds (operator closeout #409) | ADR-0072 `ACCEPTED`, Amendment 1 raises the delivery bounds to 512 MiB per file and 1 GiB per admission. `S01`-`S07` (K12 authority, K13 composition, API host composition, credential and trust operations, deck workload module, deployment units, two-part topology proof) are implemented and merged into `implement/dgk2`; the supervised proof is one happy path on the real server. Deployable only within the bounds; promotion into `main` is the operator's separate PR. `S08` (first data-local handlers) is not authorized. Omega adoption out of scope. | | `DG-M` Canonical feature identity for deck results (governance #453, #458, #475; design gate #454, #457) | COMPLETE within recorded bounds (closeout #475) | ADR-0073 `ACCEPTED` with Amendment 1 (one bar duration per admission). `M01` (bar-flow representation, PR #466), `M02` (failed-aggression feature, PR #468), `M04` (server registry and `definitions` carriage, PR #473) and `M05` (deck declaration rule and proof, PR #474) are implemented and merged into `implement/fid`; `M03` is superseded. The server seals the identities of the definitions a deck names and the deck builder must declare them; K13 is unchanged. The deck protocol client carries `definitions` (follow-on #477 / PR #478, not an atom). Not claimed: a real-host run, correctness on real data, duration in the observation identity. Promotion into `main` is the operator's separate PR. [Eight triggers, trigger 3 closed by #477, none authorized](../architecture/OPEN_DECISIONS.md#dg-m-v1-reopening-triggers-475). | -| `DG-N` Multi-instrument Bybit linear trades (governance #483, #489; design gates #377, #487) | IN PROGRESS (`T01`, `T04` COMPLETE; `T03`, `T02` not started) | ADR-0074 `ACCEPTED` with Amendment 1 (the Bybit public trade archive is the historical source). `T01` (read and delivery for the allow-list, PR #486) and `T04` (historical import per instrument from the archive, PR #488) are implemented and merged into `implement/fid`; `T03` (explicit fees) and `T02` (live ingest per instrument) are `FROZEN`/`MISSING`, in that order. The allow-list is BTCUSDT, ETHUSDT, SOLUSDT, XRPUSDT, DOGEUSDT. Not claimed: that any non-BTC dataset is registered in the server catalog (the existing Parquet are replaced by the archive import, an operator step not yet done), the server-side record-by-record proof, a measured capacity, a deployment, L2 or a second venue. | -| `DG-O` Live publication: continuous session and append-only slices (governance #507; design gate #504) | AUTHORIZED (not started) | ADR-0075 `ACCEPTED`. `O01` (append-only slices), `O02` (continuous session) and `O03` (configuration, runbook and a real-provider proof) are `FROZEN`/`MISSING` on `implement/fid`, in that order; `T02` closes with `O03`. Measured on 2026-10-21: the live path supersedes each cycle with the next (a day reads as under 0.4% of its published trades) and about 27% of a day's trades are never acquired. Not claimed: anything implemented; consolidation of slices (deferred to a measured trigger); repair of the already damaged days (paused, left as they are); the provider's `exchange_ts` ordering (an assumption `O03` measures); a deployment. | +| `DG-N` Multi-instrument Bybit linear trades (governance #483, #489; design gates #377, #487) | CLOSED within bounds (`T01`, `T04`, `T03`, `T02` COMPLETE; the one-hour `ETHUSDT` real-provider run is not claimed) | ADR-0074 `ACCEPTED` with Amendment 1 (the Bybit public trade archive is the historical source). `T01` (read and delivery for the allow-list, PR #486) and `T04` (historical import per instrument from the archive, PR #488) are implemented and merged into `implement/fid`; `T03` (explicit fees, PR #492) and `T02` (live ingest per instrument, PR #494 to #502, closed by `O03`, PR #526) are `COMPLETE` within their bounds at the closeout (#527). The allow-list is BTCUSDT, ETHUSDT, SOLUSDT, XRPUSDT, DOGEUSDT. Not claimed: that any non-BTC dataset is registered in the server catalog (the existing Parquet are replaced by the archive import, an operator step not yet done), the server-side record-by-record proof, a measured capacity, a deployment, L2 or a second venue. | +| `DG-O` Live publication: continuous session and append-only slices (governance #507; design gate #504) | CLOSED within bounds (`O01`, `O02`, `O03` COMPLETE; no real-provider run) | ADR-0075 `ACCEPTED`. `O01` (append-only slices), `O02` (continuous session) and `O03` (configuration, runbook and a real-provider proof) are `COMPLETE` within their bounds on `implement/fid` (PR #510, #524, #526; closeout #527); `T02` closed with `O03`. Measured on 2026-10-21: the live path supersedes each cycle with the next (a day reads as under 0.4% of its published trades) and about 27% of a day's trades are never acquired. Not claimed: the real-provider run of at least one hour and its report; consolidation of slices (deferred to a measured trigger); repair of the already damaged days (paused, left as they are); the provider's `exchange_ts` ordering (still an assumption: the `O03` run is not performed); a deployment. | +| `DG-R` Rebuild of damaged legacy live days (governance #518; design gate #515) | AUTHORIZED (not started; post-version) | ADR-0074 Amendment 2 `ACCEPTED`. `R01` (superseding reassessment writer) and `R02` (plan, retire, import, verify selected closed legacy days) are `FROZEN`/`MISSING` on `implement/fid`, in that order; they do not block `O02` or `O03`. Operator-reported evidence: for 2026-10-20 the archive has 1,568,861 trades, the local in-day unique IDs are 1,141,530. Not claimed: anything implemented; any legacy day rebuilt; field-by-field equality with the archive (the proof is `R02`'s); the atomic replacement (considered, not adopted); retention or deletion of retired revisions; a production run. | | `DG-K` Process Topology v1 (governance #318, design gate #319, closeout #381) | COMPLETE within recorded bounds (operator closeout #381) | ADR-0068 and ADR-0069 accepted (#319); P01-P06 implemented and merged into `implement/dgk` (PR #344-#353, #355, #356, #359, #361, #366, #373, #380; amendments ADR-0064 Am.1, ADR-0066 Am.1, ADR-0068 Am.1, ADR-0069 Am.1 and Am.2). Not claimed: any executable that composes the families (`tools/api_server.py` serves J02 v1 only, without TLS/mTLS options), production K12 authority seams, K13 composition in a host, a deck-side bundle producer, credential issuance and deployment runbook, a data-local J03 handler (the registry ships empty), and an end-to-end proof on the real topology. Promotion into `main` is the operator's separate PR; no Golden proof claimed. | | `DG-C` L2 historical v1 closeout (#442, `implement/l2`) | COMPLETE within v1 bounds | `A14`, `A14a`-`A14e` COMPLETE (PR #375/#379/#401/#411/#417/#408); golden #413/#430 accepted, 11/11 at `1cdd78f`. ADR-0070 Amendments 1-2; ADR-0049 Amendment 1 (#424): one redundant copy only, never the last. #425/#426 credited as operational tool, no A14 atom or new K09 credit. `A14f`/`A14g` held; separate promotion to `main` after DG-K. [Limits and eight triggers, none authorized](../architecture/OPEN_DECISIONS.md#l2-v1-reopening-triggers-442). | | Wave 1 (`implement/wave-1`, issues #51-#77) | CONCLUDED | 2026-09-19; issue #73's Human Golden E2E closeout (1440-candle 1m D03, official `GOLDEN E2E: PASS`) is closed and credited. | diff --git a/docs/product/ROADMAP.md b/docs/product/ROADMAP.md index baea1b0..b259fe3 100644 --- a/docs/product/ROADMAP.md +++ b/docs/product/ROADMAP.md @@ -82,8 +82,9 @@ DG-K2 Server/deck deployment composition COMPLETE within recorded bounds S01-S07 on implement/dgk2; supervised proof: one happy path; S08 not authorized) DG-M Canonical feature identity (implement/fid) COMPLETE within recorded bounds (closeout #475; ADR-0073 and Amendment 1; PR #466/#468/#473/#474); M03 superseded; no real-host run claimed; promotion to main is separate -DG-N Multi-instrument Bybit linear trades (implement/fid) IN PROGRESS (#483, #489; ADR-0074 ACCEPTED #377, Amendment 1); T01,T04 COMPLETE (PR #486, #488); T03,T02 not started -DG-O Live publication (implement/fid) AUTHORIZED (#507; ADR-0075 ACCEPTED #504); O01,O02,O03 not started; T02 closes with O03 +DG-N Multi-instrument Bybit linear trades (implement/fid) CLOSED within bounds (#483, #489, #527; ADR-0074 ACCEPTED #377, Amendment 1); T01,T04,T03,T02 COMPLETE (PR #486, #488, #492, #494-#502, #526); no real-provider run +DG-O Live publication (implement/fid) CLOSED within bounds (#507, #527; ADR-0075 ACCEPTED #504); O01,O02,O03 COMPLETE (PR #510, #524, #526); T02 closed with O03; no real-provider run +DG-R Rebuild of damaged legacy live days (implement/fid) AUTHORIZED (#518; ADR-0074 Amendment 2 ACCEPTED #515); R01,R02 not started; post-version DG-C L2 historical v1 (implement/l2, #442) COMPLETE (A14,A14a-A14e; PR #375/#379/#401/#411/#417/#408; golden #413/#430, 11/11 at 1cdd78f; explicit gaps); A14f/A14g held MISSING; promotion to main is separate @@ -109,18 +110,24 @@ Completed checkpoints are credited and must not be re-proved absent a concrete i ## Roadmap vNext planning state ```text -TOTAL_ATOMS = 130 -CLASSIFIED_ATOMS = 130 +TOTAL_ATOMS = 132 +CLASSIFIED_ATOMS = 132 UNCLASSIFIED_GAPS = 0 -SEMANTIC_FROZEN_OR_RESOLVED = 118 / 130 = 90.8% +SEMANTIC_FROZEN_OR_RESOLVED = 120 / 132 = 90.9% OPEN_BLOCKING = 3 OPEN_DEFERABLE = 9 -ROADMAP_DEFINED = 118 + 3 + 9 = 130 -ROADMAP_PLANNING_COMPLETENESS = 130 / 130 = 100% -IMPLEMENTATION_COMPLETE = 105 / 130 = 80.8% +ROADMAP_DEFINED = 120 + 3 + 9 = 132 +ROADMAP_PLANNING_COMPLETENESS = 132 / 132 = 100% +IMPLEMENTATION_COMPLETE = 110 / 132 = 83.3% ``` -DG-O registration (#507): ADR-0075 accepted; `O01`-`O03` added as `FROZEN`/`MISSING` (127 -> 130 atoms; semantic 90.6% -> 90.8%; +DG-N/DG-O closeout (#527): `T03`, `T02`, `O01`, `O02` and `O03` are credited `COMPLETE` on `implement/fid` within their bounds (PR #492, #494 to #502, #510, #524, #526; +105 -> 110 of 132; implementation 79.5% -> 83.3%); no new atom and no decision-state change. The one-hour `ETHUSDT` real-provider run is not performed and not claimed. + +Earlier, DG-R registration (#518): ADR-0074 Amendment 2 accepted; `R01` and `R02` added as `FROZEN`/`MISSING` (130 -> 132 atoms; semantic 90.8% -> 90.9%; +implementation 80.8% -> 79.5%); nothing is implemented. + +Earlier, DG-O registration (#507): ADR-0075 accepted; `O01`-`O03` added as `FROZEN`/`MISSING` (127 -> 130 atoms; semantic 90.6% -> 90.8%; implementation 82.7% -> 80.8%); nothing is implemented. Earlier, DG-N reconciliation (#489): `T01` and `T04` are credited `COMPLETE` on `implement/fid` (103 -> 105 of 127; implementation 81.1% -> 82.7%); @@ -198,8 +205,9 @@ DG-J Remote Service Topology (Wave 8) RESOLVED / IMPLEMENTED DG-K Process Topology v1 RESOLVED / IMPLEMENTED within recorded bounds (ADR-0068, ADR-0069; closeout #381) DG-K2 Server/deck deployment composition RESOLVED / IMPLEMENTED within recorded bounds (ADR-0072, Amendment 1; closeout #409) DG-M Canonical feature identity for deck results RESOLVED / IMPLEMENTED within recorded bounds (ADR-0073, Amendment 1; closeout #475) -DG-N Multi-instrument Bybit linear trades v1 IN PROGRESS (ADR-0074 ACCEPTED #377 and Amendment 1; reconciliations #483, #489); T01,T04 implemented, T03,T02 not started -DG-O Live publication: continuous session and append-only slices v1 AUTHORIZED (ADR-0075 ACCEPTED #504; reconciliation #507); implementation not started +DG-N Multi-instrument Bybit linear trades v1 CLOSED within bounds (ADR-0074 ACCEPTED #377 and Amendment 1; reconciliations #483, #489, #527); T01,T04,T03,T02 COMPLETE +DG-O Live publication: continuous session and append-only slices v1 CLOSED within bounds (ADR-0075 ACCEPTED #504; reconciliations #507, #527); O01,O02,O03 COMPLETE; the one-hour real-provider run is not claimed +DG-R Rebuild of damaged legacy live days v1 AUTHORIZED (ADR-0074 Amendment 2 ACCEPTED #515; reconciliation #518); implementation not started ``` Important current boundaries: @@ -219,8 +227,9 @@ Explicit deferables — second-provider resolution, exact L3/MBO semantics, Data - DG-K: Process Topology v1 is resolved (#318 registration, #319 design gate: ADR-0068 process topology v1, ADR-0069 J02 carriage of consumer seams and deck handoff v1). `P01`-`P06` are `FROZEN`/`COMPLETE` within recorded bounds (operator closeout #381), merged into `implement/dgk`, not composed in any executable and without a Golden proof; owner inputs fix identity-preserving canonical profiles, hosts in `tools/`, one J03 worker, a free server with data-local J03 handlers only, heavy compute on the deck on its own initiative, and `J11` not planned. See `OPEN_DECISIONS.md` (DG-K). - DG-K2: registered by #382 after the DG-K closeout; its design gate #383 produced ADR-0072, accepted on 2026-10-16, and #389 authorizes `S01`-`S07` (K12 authority, K13 composition, API host with TLS/mTLS, credential and trust operations, deck workload module, deployment units, two-part topology proof) on the integration branch `implement/dgk2` (name proposed, to be confirmed by the maintainer). Closed by operator closeout #409: all seven are implemented on `implement/dgk2` within the bounds recorded in `CAPABILITY_DAG.md`; the split is deployable only within the bounds of ADR-0072 Amendment 1; Omega adoption is out of scope. Default proposed placement: before Wave 9, because the split is the precondition for any remote consumer; the order remains the maintainer's. - DG-M: registered by #453 after the DG-K2 closeout; the maintainer named feature traceability as a requirement on 2026-10-18. Its design gate #454 produced ADR-0073, accepted on 2026-10-18 (#457), #458 authorized `M01` (bar-flow representation), `M02` (failed-aggression feature), `M04` (server registry and `definitions` carriage) and `M05` (deck declaration rule and proof) on the integration branch `implement/fid`; `M03` is superseded. Closed by operator closeout #475: all four are implemented and merged (PR #466, #468, #473, #474) within the bounds recorded in `CAPABILITY_DAG.md`; no real-host run is claimed, and promotion into `main` is the operator's separate PR. Follow-on #477 / PR #478: the deck protocol client carries `definitions` (not an atom). Independent of the FEI line. Default proposed placement: after DG-K2 and before Wave 9; the order remains the maintainer's. -- DG-N: the maintainer holds Parquet trades for other Bybit linear USDT instruments and wants them read, delivered and ingested live (2026-10-19). The design gate #377 produced ADR-0074 (accepted, #482) and #483 authorized `T01` (read and delivery), `T04` (historical import), `T03` (explicit fees) and `T02` (live ingest per instrument) on `implement/fid`, in the current wave; the wave is promoted to `main` at its end. Amendment 1 (#487, accepted 2026-10-20) chose the Bybit public trade archive as the only historical source, because the existing files declare a source profile no commit produced and S13 refuses; `T01` and `T04` are `COMPLETE` (#489). A second venue, spot, inverse and L2 for other instruments are out of scope. -- DG-O: measured on the maintainer's server on 2026-10-21 (a read-only catalog query and the Bybit public archive): the live publication supersedes each cycle with the next, so a day reads as under 0.4% of its published trades, and the loop closes its WebSocket between cycles, so about 27% of a day's trades are never acquired. The design gate #504 produced ADR-0075 (accepted) and #507 authorizes `O01` (append-only slices), `O02` (continuous session) and `O03` (configuration, runbook, real-provider proof) on `implement/fid`, before the rest of the wave; `T02` closes with `O03`. Consolidation of slices is outside the first version; the already damaged live days are not repaired (recovery paused; re-ingest from scratch if a gap makes the data unusable). +- DG-N: the maintainer holds Parquet trades for other Bybit linear USDT instruments and wants them read, delivered and ingested live (2026-10-19). The design gate #377 produced ADR-0074 (accepted, #482) and #483 authorized `T01` (read and delivery), `T04` (historical import), `T03` (explicit fees) and `T02` (live ingest per instrument) on `implement/fid`, in the current wave; the wave is promoted to `main` at its end. Amendment 1 (#487, accepted 2026-10-20) chose the Bybit public trade archive as the only historical source, because the existing files declare a source profile no commit produced and S13 refuses; `T01` and `T04` are `COMPLETE` (#489); `T03` and `T02` are `COMPLETE` within their bounds (closeout #527). A second venue, spot, inverse and L2 for other instruments are out of scope. +- DG-O: measured on the maintainer's server on 2026-10-21 (a read-only catalog query and the Bybit public archive): the live publication supersedes each cycle with the next, so a day reads as under 0.4% of its published trades, and the loop closes its WebSocket between cycles, so about 27% of a day's trades are never acquired. The design gate #504 produced ADR-0075 (accepted) and #507 authorizes `O01` (append-only slices), `O02` (continuous session) and `O03` (configuration, runbook, real-provider proof) on `implement/fid`, before the rest of the wave; `T02` closed with `O03`; all three are `COMPLETE` within their bounds (closeout #527) and the one-hour real-provider run is not performed. Consolidation of slices is outside the first version; the already damaged live days are not repaired by DG-O (see DG-R). +- DG-R: the days published by the legacy live path (31 candidate days, 2026-09-23 to 2026-10-23) read as their last batch and miss trades never acquired. ADR-0074 Amendment 2 (accepted 2026-10-24) rebuilds explicitly selected, closed days: retire the damaged revision with an ordinary reassessment, import the archive day under a free key, verify. #518 authorizes `R01` (reassessment writer) and `R02` (plan, retire, import, verify) on `implement/fid`; they are post-version and do not block `O02` or `O03`. The atomic replacement of the first draft is not adopted; the run on the server is the operator's, from a reviewed plan. ## Operational dependency direction 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/bybit_live.py b/src/quant_platform/application/bybit_live.py index 8fba895..2ad0cbd 100644 --- a/src/quant_platform/application/bybit_live.py +++ b/src/quant_platform/application/bybit_live.py @@ -333,6 +333,8 @@ class RealServerPublishProofReport: slice_keys: tuple[str, ...] = () ordering_violations: int = 0 replayed_records: int = 0 + # the end (exclusive) of the last window published, ISO text: where the next window of a continuous session starts + window_end: str | None = None def _connect_catalog(dsn: str | None): @@ -481,6 +483,12 @@ class _PublishedSlice: eligibility_published: bool +def published_floor(dsn: str | None, instrument: str = SUPPORTED_SYMBOL) -> Instant | None: + """The end of the latest valid partition of the instrument's dataset (see :func:`_published_floor`).""" + + return _published_floor(dsn, bybit_live_dataset_identity(instrument)) + + def _read_back_slice(connection: Any, identity: Any, window: LiveSlice) -> list[Any]: """Read one slice's window through the DataGateway (valid partitions only, strict coverage).""" @@ -569,6 +577,18 @@ def _publish_slices( published.append(outcome) previous_end = planned.window_end + return _pass_report(acquisition, dataset_root, published, dataset_manifest_fields, len(plan.below_floor)) + + +def _pass_report( + acquisition: LiveProviderProofReport, + dataset_root: Path, + published: list[_PublishedSlice], + dataset_manifest_fields: dict[str, Any], + replayed_records: int, +) -> RealServerPublishProofReport: + """The report of a publication that passed: ``durable_publication`` is the LAST slice's, the one a checkpoint binds.""" + last = published[-1] total_read = sum(item.read_count for item in published) return RealServerPublishProofReport( @@ -591,11 +611,53 @@ def _publish_slices( coverage_assertion_id=last.coverage_assertion_id, slices=len(published), slice_keys=tuple(item.planned.partition_key for item in published), - replayed_records=len(plan.below_floor), + replayed_records=replayed_records, + window_end=last.planned.window_end.isoformat(), **dataset_manifest_fields, ) +def publish_live_slice( + *, + planned: LiveSlice, + chain_start: Instant | None, + live_session_evidence: BybitLiveSessionEvidence, + storage_root: str | Path, + storage_root_id: str, + dsn: str | None, + producer: str, + code_ref: str, + instrument: str = SUPPORTED_SYMBOL, +) -> RealServerPublishProofReport: + """Publish ONE slice that a continuous session assembled (ADR-0075 section 2): the floor, the revision, S13, S14 and the + DataGateway read-back of ``O01``, with the session evidence of that window. A window that starts before what a reader can + already see is refused (``SLICE_ORDERING_VIOLATION``), nothing published.""" + + identity = bybit_live_dataset_identity(instrument) + acquisition = LiveProviderProofReport( + status="PASS", topic=bybit_live_topic(instrument), messages=live_session_evidence.validated_messages, + records=len(planned.records), duplicates_removed=0, final_state=live_session_evidence.final_state.value, + errors=(), accepted_records=planned.records, session_evidence=live_session_evidence, + ) + floor = _published_floor(dsn, identity) + if floor is not None and planned.window_start < floor: + return RealServerPublishProofReport(status="SLICE_ORDERING_VIOLATION", acquisition=acquisition, ordering_violations=1) + dataset_root = Path(storage_root).joinpath( + identity.layer, identity.dataset_kind, identity.venue, identity.instrument, identity.record_schema_id, + ) + dataset_manifest_fields: dict[str, Any] = {} + outcome = _publish_one_slice( + planned=planned, revision=_next_slice_revision(dsn, identity, planned.partition_key), + identity=identity, dataset_root=dataset_root, dataset_manifest_path=dataset_root / "dataset-manifest.json", + dataset_manifest_fields=dataset_manifest_fields, floor=floor, chain_start=chain_start, reconciling=False, + live_session_evidence=live_session_evidence, reconcile_result=None, storage_root_id=storage_root_id, dsn=dsn, + producer=producer, code_ref=code_ref, acquisition=acquisition, replayed_records=0, + ) + if isinstance(outcome, RealServerPublishProofReport): + return outcome + return _pass_report(acquisition, dataset_root, [outcome], dataset_manifest_fields, 0) + + def _publish_one_slice( *, planned: LiveSlice, @@ -1107,6 +1169,14 @@ def _persist_checkpoint_from_publication( return store, checkpoint +def persist_publication_checkpoint( + *, publication: RealServerPublishProofReport, checkpoint_path: str | Path, instrument: str = SUPPORTED_SYMBOL, +) -> tuple[CheckpointStore, LiveCheckpointV1] | None: + """Advance the checkpoint after a durable publication (ADR-0042 section 2); ``None`` when the publication carries no progress.""" + + return _persist_checkpoint_from_publication(publication=publication, checkpoint_path=checkpoint_path, instrument=instrument) + + def run_real_server_restart_publish_phase( *, max_messages: int, @@ -1172,9 +1242,15 @@ def run_real_server_restart_phase( recent_limit: int = 1000, durable_publication: DurablePublicationState | None = None, instrument: str = SUPPORTED_SYMBOL, + recent_records: tuple[TradeRecord, ...] | None = None, + buffered_ws_records: tuple[TradeRecord, ...] = (), ) -> RealServerRestartProofReport: """Load an existing checkpoint, reconcile, publish, then advance it. + ``recent_records`` and ``buffered_ws_records`` are for a continuous session (ADR-0075 section 5): it subscribed first, holds the + trades received since, and fetched the recent trades itself, so the overlap between the two is the continuity proof. Without + them the recent trades are fetched here and no WebSocket records are held, as for a restart. + Standalone restart reads the current durable catalog binding for the checkpoint's partition family before fetching the provider's recent-trade window, so stale or superseded checkpoints fail closed before recovery @@ -1204,11 +1280,12 @@ def run_real_server_restart_phase( partition_manifest_sha256=current_publication.partition_manifest_sha256, ) - recent_records = fetch_recent_public_trades(limit=recent_limit, instrument=instrument) + if recent_records is None: + recent_records = fetch_recent_public_trades(limit=recent_limit, instrument=instrument) outcome = resume_live_ingest( checkpoint_store=store, recent_rest_records=recent_records, - buffered_ws_records=(), + buffered_ws_records=buffered_ws_records, durable_publication=current_publication, ) status = "PASS" if outcome.status == "RESUMED" else outcome.status @@ -1351,6 +1428,9 @@ def run_real_server_restart_proof( "fetch_recent_public_trades", "load_current_durable_publication_state", "next_checkpoint", + "persist_publication_checkpoint", + "publish_live_slice", + "published_floor", "resume_live_ingest", "run_bounded_live_provider_proof", "run_bounded_live_provider_proof_sync", diff --git a/src/quant_platform/application/live_ingest_server.py b/src/quant_platform/application/live_ingest_server.py index 423f0a2..ff06d47 100644 --- a/src/quant_platform/application/live_ingest_server.py +++ b/src/quant_platform/application/live_ingest_server.py @@ -34,6 +34,12 @@ from typing import Any from quant_platform.application import bybit_live +from quant_platform.application.live_session import ( + LiveSessionConfig, + LiveSessionEngine, + LiveSessionFailure, + LiveSessionPorts, +) from quant_platform.application.live_gap_orchestration import ( LongGapRecord, SESSION_CONTINUOUS, @@ -87,6 +93,9 @@ class LiveIngestServerConfigV1: cycle_interval_seconds: float = 5.0 # ADR-0074: one process, one instrument of the allow-list. The default keeps the existing BTCUSDT unit unchanged. instrument: str = SUPPORTED_SYMBOL + # ADR-0075 slice 9.2: when given, the server runs ONE continuous session (live_session) instead of the bounded cycles. The + # default (None) is the cycle loop, unchanged; the CLI, the unit templates and the default are O03. + continuous_session: LiveSessionConfig | None = None def __post_init__(self) -> None: bybit_live_dataset_identity(self.instrument) # refuses anything outside BYBIT_LINEAR_TRADE_INSTRUMENTS_V1 @@ -267,6 +276,8 @@ def emit(signal: OperationalSignalV1) -> None: on_signal(signal) emit(_lifecycle_signal(subject, previous_state="STARTING", resulting_state="RUNNING")) + if config.continuous_session is not None: + return _run_continuous(config, subject, signals, emit, stop_requested, sleep) store = CheckpointStore(config.checkpoint_path) cycles = 0 @@ -452,6 +463,147 @@ def emit(signal: OperationalSignalV1) -> None: return LiveIngestServerReport(status=status, cycles=cycles, signals=tuple(signals)) +def _production_ports(config: LiveIngestServerConfigV1, sleep: Callable[[float], None]) -> LiveSessionPorts: + """The real seams of one instance: the provider, the recent trades, the publication path and the checkpoint.""" + + try: + import websockets # type: ignore[import-not-found] + except ImportError as exc: + raise bybit_live.LiveProviderProofPending("LIVE_PROVIDER_PROOF_PENDING: optional dependency 'websockets' is not installed") from exc + store = CheckpointStore(config.checkpoint_path) + instrument = config.instrument + + def last_durable_key(): + checkpoint = store.load() + return None if checkpoint is None else (checkpoint.last_canonical_exchange_ts, checkpoint.last_canonical_trade_id) + + def publish(sliced, chain_start, evidence): + return bybit_live.publish_live_slice( + planned=sliced, chain_start=chain_start, live_session_evidence=evidence, storage_root=config.storage_root, + storage_root_id=config.storage_root_id, dsn=config.dsn, producer=config.producer, code_ref=config.code_ref, + instrument=instrument, + ) + + def persist(report): + return bybit_live.persist_publication_checkpoint( + publication=report, checkpoint_path=config.checkpoint_path, instrument=instrument) + + def reconcile(recent, buffered): + return bybit_live.run_real_server_restart_phase( + checkpoint_path=config.checkpoint_path, dsn=config.dsn, storage_root=config.storage_root, + storage_root_id=config.storage_root_id, producer=config.producer, code_ref=config.code_ref, + recent_limit=config.recent_limit, instrument=instrument, recent_records=tuple(recent), + buffered_ws_records=tuple(buffered), + ) + + def record_gap(report): + detected_at = _now() + return record_explicit_long_gap( + storage_root=config.storage_root, interval=long_gap_interval_from_restart_report(report, detected_at=detected_at), + producer=config.producer, code_ref=config.code_ref, detected_at=detected_at, instrument=instrument, + ) + + return LiveSessionPorts( + connect=websockets.connect, + fetch_recent=lambda limit: bybit_live.fetch_recent_public_trades(limit=limit, instrument=instrument), + publish_slice=publish, persist_checkpoint=persist, reconcile=reconcile, + checkpoint_exists=lambda: store.load() is not None, + published_floor=lambda: bybit_live.published_floor(config.dsn, instrument), + last_durable_key=last_durable_key, record_gap=record_gap, + connection_errors=(OSError, websockets.ConnectionClosed), sleep=sleep, + ) + + +def _run_continuous( + config: LiveIngestServerConfigV1, + subject: SubjectReference, + signals: list[OperationalSignalV1], + emit: Callable[[OperationalSignalV1], None], + stop_requested: Callable[[], bool], + sleep: Callable[[float], None], +) -> LiveIngestServerReport: + """ADR-0075 slice 9.2 under the signals of ADR-0043 section 4: one session, slices, explicit interruptions.""" + + store = CheckpointStore(config.checkpoint_path) + gap_load = load_open_long_gap_records(storage_root=config.storage_root, instrument=config.instrument) + open_gaps: list[LongGapRecord] = list(gap_load.records) + if gap_load.unparseable_manifest_paths: + emit(_observation_unavailable_signal( + subject, + reason=( + f"{len(gap_load.unparseable_manifest_paths)} durable long-gap coverage " + "manifest(s) could not be reconstructed at startup" + ), + unparseable_manifest_paths=list(gap_load.unparseable_manifest_paths), + )) + status = SERVER_STOPPED + summary = None + + def checkpoint_evidence() -> tuple[EvidenceReference, ...]: + checkpoint = store.load() + return _checkpoint_evidence(None if checkpoint is None else checkpoint.checkpoint_identity) + + def on_event(name: str, **fields: Any) -> None: + records = tuple(open_gaps) + pressure_payload, pressure_evidence = _pressure_evidence(config) + common = {**_open_gap_signal_payload(records), **pressure_payload} + evidence = checkpoint_evidence() + pressure_evidence + _open_gap_evidence(records) + counters = { + key: fields[key] for key in ("reconnects", "ordering_violations", "buffer_high_water", "buffer_capacity") if key in fields + } + if name == "slice_published": + emit(_health_signal( + subject, health=HealthState.HEALTHY, session_state=_session_state(records), phase="slice", + partition_key=fields["partition_key"], trades=fields["trades"], window_end=fields["window_end"], + slice_lag_ms=fields["slice_lag_ms"], evidence=evidence, **counters, **common, + )) + elif name == "reconciled": + emit(_health_signal( + subject, health=HealthState.HEALTHY, session_state=_session_state(records), phase="reconcile", + records=fields["records"], slices=fields["slices"], evidence=evidence, **common, + )) + elif name == "interruption": + emit(_health_signal( + subject, health=HealthState.DEGRADED, session_state=_session_state(records), phase="interruption", + reason=f"{fields['reason']}: {fields['detail']}".rstrip(": "), interruption=fields["reason"], + evidence=evidence, **counters, **common, + )) + elif name == "gap": + record = fields["record"] + _merge_open_gap_record(open_gaps, record) + records = tuple(open_gaps) + emit(_health_signal( + subject, health=HealthState.DEGRADED, session_state=SESSION_RESUMED_WITH_EXPLICIT_GAP, phase="reconcile", + reason=str(fields.get("reason") or "last durable key absent from the bounded recent-trades window"), + gap_coverage_id=record.coverage_id, gap_assertion_id=record.assertion_id, + gap_manifest_path=record.coverage_manifest_path, gap_state=record.interval_state, + evidence=evidence + _open_gap_evidence((record,)), **{**_open_gap_signal_payload(records), **pressure_payload}, + )) + elif name == "unclaimed_span": + emit(_health_signal( + subject, health=HealthState.DEGRADED, session_state=_session_state(records), phase="slice", + reason="a UTC midnight with no trade left a span without a slice; it is not claimed", + unclaimed_start=fields["start"], unclaimed_end=fields["end"], evidence=evidence, **common, + )) + + try: + engine = LiveSessionEngine( + instrument=config.instrument, config=config.continuous_session, + ports=_production_ports(config, sleep), on_event=on_event, + ) + summary = engine.run(stop_requested) + except Exception as exc: # noqa: BLE001 - any failure must surface as a FAILURE signal, never a silent exit + code = "SLICE_PUBLICATION_FAILED" if isinstance(exc, LiveSessionFailure) else type(exc).__name__ + emit(_failure_signal(subject, failure_code=code, message=str(exc))) + status = SERVER_FAILED + emit(_lifecycle_signal( + subject, previous_state="RUNNING", resulting_state=status, + cycles=0 if summary is None else summary.slices_published, + )) + return LiveIngestServerReport( + status=status, cycles=0 if summary is None else summary.slices_published, signals=tuple(signals)) + + __all__ = [ "BYBIT_LINEAR_TRADE_INSTRUMENTS_V1", "CAPABILITY_ID", @@ -462,6 +614,7 @@ def emit(signal: OperationalSignalV1) -> None: "SERVER_GAP_DETECTED_AWAITING_REMEDIATION", "LiveIngestServerConfigV1", "LiveIngestServerReport", + "LiveSessionConfig", # Re-exported so the executable boundary (tools/live_ingest_server.py) # can build a policy value without importing quant_platform.operations # directly -- executable tooling talks to the application seam only. diff --git a/src/quant_platform/application/live_session.py b/src/quant_platform/application/live_session.py new file mode 100644 index 0000000..d6712c6 --- /dev/null +++ b/src/quant_platform/application/live_session.py @@ -0,0 +1,490 @@ +"""ADR-0075 slice 9.2: one continuous Bybit WebSocket session per instance, a bounded buffer and explicit interruptions. + +The reader (a thread with its own asyncio loop) stays connected: it subscribes, pings, canonicalizes every message and puts it in a +BOUNDED buffer. The publisher (the caller's thread) drains the buffer into slices (``SliceAssembler``) and publishes them while the +reader keeps listening; a slice is published, and only then the checkpoint advances. The session ends only by an *interruption* -- +a disconnect, a missing pong, a full buffer, an ordering violation -- or by the caller's stop; an interruption is counted, signalled +and followed by the bounded reconciliation of ADR-0040 section 7 and ADR-0042 section 5 (continuity proven from the last durable key, +else an explicit gap, ADR-0044 unchanged). It is never turned into a ``complete`` claim over the unlistened span. + +This module owns the loop and holds no catalog, storage or provider code: everything that touches them is a *port* the caller gives +(``LiveSessionPorts``), so the same engine runs against a scripted provider in the tests and against the real publication path in the +server (``live_ingest_server``). +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +from enum import Enum +import json +import queue +import threading +import time +from typing import Any + +from quant_platform.data.models import Instant, TradeRecord +from quant_platform.source_adapters.bybit import bybit_trade_v1_ordering_key +from quant_platform.source_adapters.bybit_live import ( + BYBIT_LIVE_MAPPING_V1, + BYBIT_LIVE_SOURCE_SEMANTICS_V1, + BybitLiveSessionEvidence, + LiveSessionTracker, + LiveTradeBatch, + SessionEvent, + SessionState, + bybit_live_topic, + canonicalize_bybit_live_message, +) +from quant_platform.source_adapters.bybit_live_assembler import SliceAssembler +from quant_platform.source_adapters.bybit_live_slices import SLICE_MAX_TRADES_DEFAULT, SLICE_SECONDS_DEFAULT, LiveSlice + +BYBIT_PUBLIC_LINEAR_WS_URL = "wss://stream.bybit.com/v5/public/linear" +BUFFER_MESSAGES_DEFAULT = 20_000 + + +class Interruption(str, Enum): + """Why a session ended (ADR-0075 section 5). Each one is counted, signalled and reconciled.""" + + DISCONNECT = "disconnect" + HEARTBEAT_TIMEOUT = "heartbeat_timeout" + BUFFER_OVERFLOW = "buffer_overflow" + ORDERING_VIOLATION = "ordering_violation" + + +class LiveSessionFailure(RuntimeError): + """Not an interruption: a publication, reconciliation or source failure that stops the loop (fail closed).""" + + +@dataclass(frozen=True, slots=True, kw_only=True) +class LiveSessionConfig: + slice_seconds: int = SLICE_SECONDS_DEFAULT + slice_max_trades: int = SLICE_MAX_TRADES_DEFAULT + buffer_messages: int = BUFFER_MESSAGES_DEFAULT + ping_interval: float = 20.0 + pong_timeout: float = 10.0 + connect_timeout: float = 30.0 + recent_limit: int = 1000 + reconnect_delay: float = 1.0 + reconnect_delay_max: float = 30.0 + tick: float = 0.2 + + def __post_init__(self) -> None: + for name in ("slice_seconds", "slice_max_trades", "buffer_messages", "recent_limit"): + value = getattr(self, name) + if not isinstance(value, int) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if not 1 <= self.recent_limit <= 1000: + raise ValueError("recent_limit must be in [1, 1000]") + for name in ("ping_interval", "pong_timeout", "connect_timeout", "reconnect_delay", "reconnect_delay_max", "tick"): + if not getattr(self, name) > 0: + raise ValueError(f"{name} must be positive") + if self.reconnect_delay_max < self.reconnect_delay: + raise ValueError("reconnect_delay_max must not be below reconnect_delay") + + +@dataclass(slots=True) +class LiveSessionPorts: + """Everything the engine needs from the outside world. The server builds the real ones; the tests script them.""" + + connect: Callable[..., Any] # websockets.connect-like: connect(url, ping_interval=None, close_timeout=5) -> async context manager + fetch_recent: Callable[[int], Sequence[TradeRecord]] + publish_slice: Callable[[LiveSlice, Instant | None, BybitLiveSessionEvidence], Any] # -> report with .status + persist_checkpoint: Callable[[Any], Any] # the publication report -> advances the checkpoint + reconcile: Callable[[Sequence[TradeRecord], Sequence[TradeRecord]], Any] # (recent, buffered) -> restart report + checkpoint_exists: Callable[[], bool] + published_floor: Callable[[], Instant | None] + last_durable_key: Callable[[], tuple[Instant, str] | None] + record_gap: Callable[[Any], Any] + connection_errors: tuple[type[BaseException], ...] = (OSError,) + clock: Callable[[], float] = time.monotonic + wall_ns: Callable[[], int] = time.time_ns + sleep: Callable[[float], None] = time.sleep + + +@dataclass(slots=True) +class LiveSessionSummary: + slices_published: int = 0 + sessions: int = 0 + reconnects: int = 0 + reconciliations: int = 0 + gaps: int = 0 + ordering_violations: int = 0 + buffer_high_water: int = 0 + interruptions: dict[str, int] = field(default_factory=dict) + + +class _Reader(threading.Thread): + """The connected session: one connection, kept open until the session ends.""" + + def __init__( + self, *, connect: Callable[..., Any], instrument: str, tracker: LiveSessionTracker, lock: threading.Lock, + out: "queue.Queue[LiveTradeBatch]", config: LiveSessionConfig, stop: threading.Event, + connection_errors: tuple[type[BaseException], ...], clock: Callable[[], float], + ) -> None: + super().__init__(name=f"live-session-reader-{instrument}", daemon=True) + self._connect = connect + self._instrument = instrument + self._topic = bybit_live_topic(instrument) + self._tracker = tracker + self._lock = lock + self._out = out + self._config = config + self._stop_event = stop + self._connection_errors = connection_errors + self._clock = clock + self.subscribed = threading.Event() + self.finished = threading.Event() + self.interruption: Interruption | None = None + self.detail = "" + self.error: BaseException | None = None + self.high_water = 0 + self.pongs = 0 + + def run(self) -> None: + try: + asyncio.run(self._read()) + except BaseException as exc: # noqa: BLE001 - surfaced to the publisher, which fails closed + self.error = exc + finally: + self.finished.set() + + async def _read(self) -> None: + config = self._config + try: + async with self._connect(BYBIT_PUBLIC_LINEAR_WS_URL, ping_interval=None, close_timeout=5) as socket: + with self._lock: + self._tracker.connected() + await socket.send('{"op": "subscribe", "args": ["%s"]}' % self._topic) # the topic is an allow-listed symbol: no escaping needed + next_ping = self._clock() + config.ping_interval + ping_sent_at: float | None = None + while not self._stop_event.is_set(): + now = self._clock() + if ping_sent_at is not None and now - ping_sent_at > config.pong_timeout: + self.interruption, self.detail = Interruption.HEARTBEAT_TIMEOUT, "no pong within the timeout" + return + if ping_sent_at is None and now >= next_ping: + await socket.send('{"op": "ping"}') + ping_sent_at = now + try: + raw = await asyncio.wait_for(socket.recv(), timeout=config.tick) + except asyncio.TimeoutError: + continue + document = json.loads(raw) + op = document.get("op") + if op == "subscribe": + if document.get("success") is not True: + raise LiveSessionFailure(f"subscription refused: {document!r}") + with self._lock: + self._tracker.subscribed(topic=self._topic, conn_id=document.get("conn_id")) + self.subscribed.set() + continue + if op in {"ping", "pong"}: + # counted, not appended to the tracker: its event list lives as long as the connection and would grow + # with every pong; the liveness evidence is the deadline above + self.pongs += 1 + ping_sent_at, next_ping = None, self._clock() + config.ping_interval + continue + if document.get("topic") != self._topic: + continue + batch = canonicalize_bybit_live_message(document, instrument=self._instrument) + with self._lock: + self._tracker.observed_message(batch) + self.subscribed.set() # a topic message is itself the acknowledgement (ADR-0040 section 6) + try: + self._out.put_nowait(batch) + except queue.Full: + # never a silent drop: the session ends here, the buffered messages are published, the rest is reconciled + self.interruption, self.detail = Interruption.BUFFER_OVERFLOW, "the buffer is full" + return + self.high_water = max(self.high_water, self._out.qsize()) + except self._connection_errors as exc: + self.interruption, self.detail = Interruption.DISCONNECT, f"{type(exc).__name__}: {exc}" + + +class LiveSessionEngine: + """The loop of one instance: sessions, slices, interruptions, reconciliation (ADR-0075 sections 1, 2 and 5).""" + + def __init__( + self, + *, + instrument: str, + config: LiveSessionConfig, + ports: LiveSessionPorts, + on_event: Callable[..., None] = lambda name, **fields: None, + ) -> None: + bybit_live_topic(instrument) # validates the instrument against the allow-list + self._instrument = instrument + self._config = config + self._ports = ports + self._on_event = on_event + self.summary = LiveSessionSummary() + self._chain_end: Instant | None = None + self._messages = 0 + self._records = 0 + self._reader: _Reader | None = None + self.tracker: LiveSessionTracker | None = None # the current session's, for diagnostics + + # ------------------------------------------------------------------------------------------------ loop + + def run(self, stop_requested: Callable[[], bool] = lambda: False) -> LiveSessionSummary: + delay = self._config.reconnect_delay + while not stop_requested(): + published_before = self.summary.slices_published + interruption = self._session(stop_requested) + if interruption is None: # the caller's stop + break + self.summary.interruptions[interruption.value] = self.summary.interruptions.get(interruption.value, 0) + 1 + delay = self._config.reconnect_delay if self.summary.slices_published > published_before else min( + self._config.reconnect_delay_max, delay * 2) + self._wait(delay, stop_requested) + return self.summary + + def _wait(self, seconds: float, stop_requested: Callable[[], bool]) -> None: + remaining = seconds + while remaining > 0 and not stop_requested(): + step = min(remaining, 1.0) + self._ports.sleep(step) + remaining -= step + + # ------------------------------------------------------------------------------------------------ one session + + def _session(self, stop_requested: Callable[[], bool]) -> Interruption | None: + ports, config = self._ports, self._config + self.summary.sessions += 1 + if self.summary.sessions > 1: + self.summary.reconnects += 1 + tracker = LiveSessionTracker(self._instrument) + lock = threading.Lock() + buffer: "queue.Queue[LiveTradeBatch]" = queue.Queue(maxsize=config.buffer_messages) + stop_reader = threading.Event() + reader = _Reader( + connect=ports.connect, instrument=self._instrument, tracker=tracker, lock=lock, out=buffer, config=config, + stop=stop_reader, connection_errors=ports.connection_errors, clock=ports.clock, + ) + assembler = SliceAssembler(max_trades=config.slice_max_trades, slice_seconds=config.slice_seconds, clock=ports.clock) + reason: Interruption | None = None + failure: BaseException | None = None + stopped = False + self._messages = self._records = 0 + self._reader, self.tracker = reader, tracker + reader.start() + try: + established = self._await_subscription(reader, stop_requested) + if not established: + stopped = stop_requested() + reason = reader.interruption or Interruption.DISCONNECT + failure = reader.error + else: + staged = self._reconcile(reader, buffer, assembler, stop_requested) + if staged is None: # the session ended, or a stop came, before it received a single trade + stopped = stop_requested() + reason = reader.interruption or (None if stopped else Interruption.DISCONNECT) + failure = reader.error + staged = [] + for batch in staged: # message by message, as in the steady state: a burst is cut at the bounds too + self._take(assembler, batch) + if assembler.ordering_violations: + reason = Interruption.ORDERING_VIOLATION + break + for sliced in assembler.take_due(): + self._publish(sliced, tracker) + while reason is None and not stopped and failure is None: + reason, stopped, failure = self._step(reader, buffer, assembler, tracker, stop_requested) + finally: + stop_reader.set() + reader.join(timeout=10.0) + # what was listened to is published BEFORE the interruption is recorded: the evidence of those windows is the session's + # alive state, and a disconnect that comes after them must not turn their claim into a gap + try: + while True: + try: + self._take(assembler, buffer.get_nowait()) + except queue.Empty: + break + for sliced in assembler.flush(): + self._publish(sliced, tracker) + finally: + self.summary.buffer_high_water = max(self.summary.buffer_high_water, reader.high_water) + if assembler.ordering_violations and reason is None: + reason = Interruption.ORDERING_VIOLATION + self.summary.ordering_violations += assembler.ordering_violations + failure = failure or reader.error + if failure is not None: + raise (failure if isinstance(failure, LiveSessionFailure) else LiveSessionFailure( + f"source failure: {type(failure).__name__}: {failure}")) + if stopped and reason is None: + return None + reason = reason or reader.interruption or Interruption.DISCONNECT + self._on_event( + "interruption", reason=reason.value, detail=reader.detail, reconnects=self.summary.reconnects, + ordering_violations=self.summary.ordering_violations, buffer_high_water=self.summary.buffer_high_water, + buffer_capacity=config.buffer_messages, + ) + return reason + + def _await_subscription(self, reader: _Reader, stop_requested: Callable[[], bool]) -> bool: + deadline = self._ports.clock() + self._config.connect_timeout + while not reader.subscribed.is_set(): + if reader.finished.is_set() or stop_requested() or self._ports.clock() > deadline: + return False + reader.finished.wait(self._config.tick) + return True + + def _step(self, reader, buffer, assembler, tracker, stop_requested): + """One turn of the publisher: a message, the slices that are due. Returns ``(reason, stopped, failure)``.""" + + if stop_requested(): + return None, True, None + try: + batch = buffer.get(timeout=self._config.tick) + except queue.Empty: + batch = None + if batch is not None: + self._take(assembler, batch) + if assembler.ordering_violations: + return Interruption.ORDERING_VIOLATION, False, None + elif reader.finished.is_set(): + return reader.interruption or Interruption.DISCONNECT, False, reader.error + for sliced in assembler.take_due(): + self._publish(sliced, tracker) + return None, False, None + + def _take(self, assembler: SliceAssembler, batch: LiveTradeBatch) -> None: + self._messages += 1 + self._records += len(batch.records) + assembler.add(batch.records) + + # ------------------------------------------------------------------------------------------------ reconciliation + + def _drain_available(self, buffer: "queue.Queue[LiveTradeBatch]") -> list[LiveTradeBatch]: + drained: list[LiveTradeBatch] = [] + while True: + try: + drained.append(buffer.get_nowait()) + except queue.Empty: + return drained + + def _keep_trades(self, batches: list[LiveTradeBatch]) -> list[LiveTradeBatch]: + kept = [batch for batch in batches if batch.records] + self._messages += len(batches) - len(kept) + return kept + + def _reconcile( + self, reader: _Reader, buffer: "queue.Queue[LiveTradeBatch]", assembler: SliceAssembler, + stop_requested: Callable[[], bool], + ) -> list[LiveTradeBatch] | None: + """Subscribed first, then the recent trades (ADR-0042 section 5): the overlap of the two is the continuity proof. + + The recent trades are a snapshot of unknown freshness: their anchor says the last durable key is in the window, not that the + window reaches this subscription. So the snapshot is taken AFTER the first trade of the subscription has arrived, and that + trade is handed to the reconciliation with it: the existing seam then requires a key present in both, else the interval is an + explicit gap. A session that has received no trade yet has nothing to lose and waits (heartbeat and stop stay live); + it is never read as continuity restored. ``None`` if the session ended or a stop came first.""" + + ports = self._ports + staged = self._drain_available(buffer) + if not ports.checkpoint_exists(): + assembler.start_window(None) + self._chain_end = None + return staged + # a frame with no trade is not a trade (an empty snapshot is admitted): it is counted and dropped, never held, so the + # wait for the first trade cannot grow past the bounded buffer + staged = self._keep_trades(staged) + while not staged: + if stop_requested() or reader.finished.is_set(): + return None + try: + staged += self._keep_trades([buffer.get(timeout=self._config.tick)]) + except queue.Empty: + continue + recent = tuple(ports.fetch_recent(self._config.recent_limit)) + staged += self._drain_available(buffer) + buffered = tuple(record for batch in staged for record in batch.records) + anchor = ports.last_durable_key() # before the reconciliation advances it + report = ports.reconcile(recent, buffered) + status = getattr(report, "status", None) + if status == "PASS": + publication = report.publication + accepted = report.restart_outcome.accepted_records + end = Instant.parse(publication.window_end) + assembler.start_window( + end, skip_through=anchor, skip_keys=(bybit_trade_v1_ordering_key(record) for record in accepted)) + self._chain_end = end + self.summary.reconciliations += 1 + self.summary.slices_published += publication.slices + self._on_event("reconciled", records=len(accepted), slices=publication.slices, window_end=publication.window_end) + elif status == "REAL_RESTART_PROOF_PENDING": + floor = ports.published_floor() + replayed = getattr(getattr(report, "restart_outcome", None), "accepted_records", ()) or () + assembler.start_window( + floor, skip_through=anchor, skip_keys=(bybit_trade_v1_ordering_key(record) for record in replayed)) + self._chain_end = floor + self.summary.reconciliations += 1 + self._on_event("reconciled", records=0, slices=0, window_end=None if floor is None else floor.isoformat()) + elif status == "GAP_DETECTED": + record = ports.record_gap(report) + assembler.start_window(None) + self._chain_end = None + self.summary.gaps += 1 + self._on_event("gap", record=record, reason=getattr(report.restart_outcome.reconcile_result, "evidence", {}).get("reason")) + else: + raise LiveSessionFailure(f"reconciliation failed: {status}") + return staged + + # ------------------------------------------------------------------------------------------------ publication + + def _evidence(self, tracker: LiveSessionTracker) -> BybitLiveSessionEvidence: + """The evidence of the window being published: the session was subscribed and acquiring through it, nothing else is claimed. + + Built from the segment since the last slice, not from the tracker's whole history (which grows with every heartbeat).""" + + if tracker.state is not SessionState.ACQUIRING: + raise LiveSessionFailure(f"a slice cannot be published from a session in state {tracker.state.value}") + events = tuple( + SessionEvent(state, "session_continuing", {"messages_in_window": self._messages}) + for state in (SessionState.CONNECTED, SessionState.SUBSCRIBED, SessionState.ACQUIRING) + ) + return BybitLiveSessionEvidence( + source_semantics_id=BYBIT_LIVE_SOURCE_SEMANTICS_V1, mapping_id=BYBIT_LIVE_MAPPING_V1, + final_state=SessionState.ACQUIRING, events=events, interruptions=(), integrity_conflicts=(), + validated_messages=self._messages, accepted_records=self._records, + ) + + def _publish(self, sliced: LiveSlice, tracker: LiveSessionTracker) -> None: + ports = self._ports + evidence = self._evidence(tracker) + if self._reader is not None: # the pressure of the session that is still open, not only of the ones that ended + self.summary.buffer_high_water = max(self.summary.buffer_high_water, self._reader.high_water) + chain_start = self._chain_end + if chain_start is not None and chain_start != sliced.window_start: + # the window moved past a UTC midnight that held no trade: that span has no slice and is not claimed + self._on_event("unclaimed_span", start=chain_start.isoformat(), end=sliced.window_start.isoformat()) + chain_start = None + report = ports.publish_slice(sliced, chain_start, evidence) + if getattr(report, "status", None) != "PASS": + raise LiveSessionFailure(f"slice publication failed: {getattr(report, 'status', None)}") + ports.persist_checkpoint(report) # only after the slice is durable (ADR-0042 section 2) + self._chain_end = sliced.window_end + self._messages = self._records = 0 + self.summary.slices_published += 1 + lag_ms = max(0, (ports.wall_ns() - sliced.window_end.epoch_ns) // 1_000_000) # signals carry integers, not floats + self._on_event( + "slice_published", partition_key=sliced.partition_key, trades=len(sliced.records), + window_end=sliced.window_end.isoformat(), slice_lag_ms=lag_ms, reconnects=self.summary.reconnects, + ordering_violations=self.summary.ordering_violations, buffer_high_water=self.summary.buffer_high_water, + buffer_capacity=self._config.buffer_messages, report=report, + ) + + +__all__ = [ + "BUFFER_MESSAGES_DEFAULT", + "BYBIT_PUBLIC_LINEAR_WS_URL", + "Interruption", + "LiveSessionConfig", + "LiveSessionEngine", + "LiveSessionFailure", + "LiveSessionPorts", + "LiveSessionSummary", +] 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=