From 1ba1c92fbc4148a2d6de038472973cc34ed5868c Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:27:27 +0200 Subject: [PATCH 01/13] docs(adr): propose bounded legacy live-day reconstruction (#515) --- ...multi-instrument-bybit-linear-trades-v1.md | 223 ++++++++++++++++++ 1 file changed, 223 insertions(+) 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..61bcbea 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 @@ -263,3 +263,226 @@ 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:** PROPOSED (design gate [#515](https://github.com/NeoNix-Lab/quant-platform/issues/515)) +**Date:** 2026-10-24 + +The accepted ADR and Amendment 1 above remain operative. This proposal is not an +implementation, a governance reconciliation, an acceptance record or authority to +change production data. The maintainer requested a reviewable reconstruction +proposal after the operator evidence below. Acceptance and the bounded +implementation authorization are separate steps. + +### 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 replace every date in it. +The 2026-10-23 sample contains both legacy revisions and new live slices; it is +excluded from the first replacement 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 Proposed decision and authority boundary + +Authorize an operator-requested reconstruction of explicitly selected, closed +UTC days of legacy `canonical/trades/bybit/BTCUSDT/trade-v1` from the whole-day +archive of Amendment 1. This is replacement of damaged historical publication, +not restoration of the original live session's continuity or sequence evidence. + +The ordinary archive importer keeps its existing refusal for an occupied day. +Reconstruction is a separate application operation composed over the existing +data-plane repair owner, never a `--force` bypass in the ordinary importer. +Healthy historical/SQLite days, new live slice keys, other datasets and the +active ingest checkpoint are not replacement targets. + +ADOPT the immutable candidate staging, evidence bindings, lock order, +compare-and-cutover, quality/eligibility owners and durable convergence principles +of [ADR-0033](ADR-0033-backfill-repair-v1.md). ADAPT their application composition +for this bounded defect. Do not introduce a parallel repair engine. + +Current `CoverageGapTrigger` cannot replace an occupied natural key, and +`InvalidRevisionTrigger` requires an authoritative failed assessment and an +`invalid` predecessor. A legacy final batch can legitimately be `valid` over its +small interval; calling it invalid merely because it is not a whole day would +falsify its existing assessment. Neither v1 trigger authorizes this operation. + +The proposed additive repair semantics are explicitly named +`quant-platform/a10-legacy-day-rebuild-v1`, distinct from +`quant-platform/a10-repair-v1`. Their predecessor-bound trigger records the +confirmed legacy publication defect, requested whole-day support, archive +identity and exact incumbent evidence. Existing v1 trigger eligibility, intent +IDs and outcomes keep their meaning. Implementation must specify and test the +new intent/plan serialization and dispatch; it must not reinterpret old intents. + +### A2.3 Inspectable plan and temporal closure + +Before materialization, a read-only plan captures: + +- the authorized dataset, explicit UTC days and reason for reconstruction; +- each incumbent partition UUID, key, revision, lifecycle state, physical and + manifest hashes, coverage documents/hashes, declared intervals and paths; +- the source URL, file SHA-256, byte size, source-observation time, expected + count, mapping/profile, producing code commit and planned candidate revision; +- coverage, observed-record and adjacent-day effects; active checkpoint + bindings; overlapping slice or healthy-history identities; +- immutable candidate locations, resource bounds, a canonical plan digest and + per-partition repair obligations bound to that exact plan. + +Re-read and compare this evidence under the repair owner's locks before any +visibility change. A changed predecessor, new overlap, changed source or changed +checkpoint relationship makes the plan stale; it cannot silently acquire a +different target or authorize another date. + +Every incumbent effect must be contained in the explicitly authorized union of +closed days, using both declared coverage and actual record bounds. A legacy +batch spanning midnight can couple adjacent days. The plan reports that closure +and refuses execution if it reaches an unapproved date, healthy historical day, +live slice, checkpoint-bound partition or active/current UTC day. An adjacent day +can enter only through a newly approved plan; no automatic date-range expansion, +clipping of old manifests, or loss of the 529 out-of-day rows is authorized. + +A connected component of approved adjacent legacy days is one atomic visibility +unit, while each candidate remains its own UTC-day partition with its own source +and certification. Independent components can execute separately and report +separate outcomes. This is explicit caller orchestration, not native aggregate +range completeness or a scheduler (ADR-0054). + +The first 2026-10-20 pilot validates preparation and refusal/cutover semantics in +disposable PostgreSQL, including neighboring production-shaped intervals. It is +not permission to replace that day in production while its boundary closure is +unresolved. A plan whose closure cannot meet these restrictions remains blocked. + +### A2.4 Candidate evidence and immutable storage + +ADOPT Amendment 1's source profile, strict archive parsing, millisecond mapping, +unique non-empty trade IDs, canonical ordering and half-open UTC-day coverage. +Complete means the day as the archived source publishes it, not measured provider +infallibility or certified continuity of the old WebSocket session. + +Materialize each candidate in a collision-safe immutable location distinct from +every incumbent artifact and manifest. Its final partition revision is the +contiguous successor captured by the plan, not revision 1 by convenience; its +files and coverage documents bind that revision. Dataset identity and existing +dataset-manifest bytes remain unchanged. Use paths representable by the existing +manifest schemas, with no overwrite or directory move of incumbent data. + +Preparation validates file and canonical-content hashes, full source-to-candidate +canonical-record equality, ordering, uniqueness, identity and day ownership. It +produces authentic source-specific certification evidence for the candidate's +final identity using S13's verification semantics without calling its ordinary +predecessor-superseding seal. Fabricated quality reports or copied predecessor +reports cannot authorize replacement. Failed attempts retain their own evidence +for inspection but never alter predecessor visibility. + +Archive reconstruction preserves the archive's null `receive_ts` and `sequence`; +it does not fabricate live-only fields. Live-to-archive comparison distinguishes +those expected provenance differences from changes in venue, instrument, +exchange time, side, price or size. ID membership alone is not a full-field gate. +Source observation, preparation and cutover times are recorded honestly; neither +availability nor the producing commit is backdated to the trade date. + +### A2.5 Cutover, readers and restart + +The repair owner provides a transaction-scoped composition for the new semantics: +all relevant dataset/lineage locks in the existing order, then affected partition +topologies in deterministic order, then under-lock reauthorization of the whole +plan. No component commits between its daily candidates. + +Within that transaction, admit the final candidate revisions, apply the existing +A16 and S14 transaction-scoped decisions, supersede the exact approved incumbent +revisions, and persist predecessor/candidate/plan convergence provenance. Refusal +of any candidate rolls back the whole component, leaving all predecessors as +they were. Commit only when every candidate is eligible and the component's +coverage/identity/row-equality gates pass. Retain authentic failed-attempt evidence +outside the rolled-back visibility transaction. + +This extends A10 composition only for the new version. It does not weaken S13's +ordinary durable phase boundaries or globally suppress its commits. A10's +existing cutover already reuses A16/S14 rather than calling ordinary S13 admission; +the bounded extension must retain that ownership and evidence discipline. + +Readers resolving an affected component must use a coherent catalog generation +for partition selection and coverage evidence, or receive a typed retry/refusal. +One read may see all of the old component or all of the new component, never a +mixture. Immutable retained predecessor files let an already-resolved read finish +after cutover. Application composition owns DataGateway read-back; the data repair +package must not import Access to perform it (ADR-0019 and ADR-0033). + +Persist a versioned plan/attempt/convergence record bound to the exact evidence; +do not overload existing v1 provenance rows or infer completion from matching +content hashes. A crash before commit leaves old visibility intact; prepared +immutable files remain unpublished evidence. After commit, an exact replay +returns durable convergence, not a second successor revision. A changed plan or +candidate is a distinct attempt and must be reauthorized. A lost response after +commit is resolved from provenance before any retry mutates data. + +Existing gap evidence and live checkpoint bytes remain untouched. Reconstruction +does not mark historical live gaps repaired, rewind a checkpoint, claim missing +sequence continuity, or enable the archive as an automatic live repair source. +Already sealed admissions and in-flight deliveries retain their referenced bytes +and source identities; new admissions resolve the new eligible revision. No +retention or physical/catalog deletion is part of this operation (ADR-0049). + +### A2.6 Exact effect if accepted + +| Authority | Bounded amendment | +| --- | --- | +| This ADR A1.6 item 3 and occupied-day refusal | Remain the default for ordinary import; the separately authorized legacy-day reconstruction above is the explicit exception. | +| ADR-0075 section 7, delegation item 3 and acceptance item 3 | Lift the pause only for the explicitly approved historical legacy-day reconstruction; current slices, consolidation and live interruption evidence remain unchanged. | +| ADR-0033 decision and partition-bounded cutover | Add the distinctly versioned legacy-defect trigger and atomic composition of approved adjacent daily obligations; existing v1 triggers and cutover remain unchanged. | +| ADR-0044 | No amendment: no automatic live-gap repair or new proof of live continuity. | +| ADR-0018, frozen records/manifests, identity and ordering | No in-place changes. New repair control/provenance semantics need an explicit versioned contract and migration in their own authorized implementation slice. | +| S13, A16 and S14 ordinary publication | Existing phase boundaries and eligibility/quality authority remain; reconstruction composes the repair-owned transaction-scoped seams. | + +This proposal does not accept ADR-0075 Amendment 1 (#512 / PR #513), change its +numbering, resolve #511, complete O02/O03 or grant new capability credit. It does +not change SCOPE, Roadmap, Capability Map/DAG or Open Decisions. Acceptance must be +recorded explicitly and followed by a separately authorized implementation issue +and governance reconciliation where the active scope requires one. Production +execution follows a reviewed, pinned implementation and a reviewed date plan. + +### A2.7 Required implementation and operational proof + +1. **Plan/refusal slice.** Versioned defect, plan and provenance contracts; read-only + inventory and boundary closure. Tests reject healthy historical/SQLite days, + slices, open UTC days, checkpoint targets, unapproved neighbors and stale plans. +2. **Candidate slice.** Immutable archive mapping/materialization and genuine + final-identity certification evidence; prove full-field equality, malformed + source refusal, hash/coverage binding and concurrent-attempt isolation. The + 2026-10-20 pilot must contain exactly 1,568,861 archive records, all in-day. +3. **Cutover slice.** Disposable PostgreSQL probes for S13-equivalent verification, + A16/S14 refusal, failure after first candidate admission, process/connection + loss before and after commit, stale predecessor evidence and exact retry. + Every failed component leaves predecessor rows, bytes and readability intact. + Real concurrent reader/writer interleavings prove coherent reads, loser + non-mutation and lock ordering against ordinary S13/S14/A16. A two-day + midnight-crossing fixture proves no adjacent-day record or coverage loss. +4. **Read-back/operator slice.** Strict DataGateway reads compare the full archive + records, count, ordering and duplicate keys over each replaced day; verify + unchanged non-target coverage, old admission bytes and live checkpoint. Repeat + recovery from a lost successful response. Provide resource/time bounds and an + inspect/prepare/execute/resume runbook. No automatic rollback or deletion. + +The runtime proof is required after implementation; this design-only proposal +does not claim any of those probes passed. Only after the isolated pilot and +boundary-safe production plan succeed can the operator reconstruct further +explicitly approved closed days. The 31-date inventory is not that execution plan. From d6c45b4ad7ca7ce9432ad81706cc86bff9b984db Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:49:53 +0200 Subject: [PATCH 02/13] docs(adr): reduce ADR-0074 Amendment 2 to retire-then-import (#515) Retire the damaged legacy day with an ADR-0030 reassessment (fail -> invalid), then import the archive day under dt=/seg=000000.000 through the ordinary S13/S14 path. The atomic A10 replacement of the first draft is recorded as considered and not adopted. Refs #515 Co-Authored-By: Claude Sonnet 5.5 --- ...multi-instrument-bybit-linear-trades-v1.md | 357 +++++++++--------- 1 file changed, 175 insertions(+), 182 deletions(-) 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 61bcbea..af7c1e1 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 @@ -274,7 +274,10 @@ resolved as proposed: The accepted ADR and Amendment 1 above remain operative. This proposal is not an implementation, a governance reconciliation, an acceptance record or authority to change production data. The maintainer requested a reviewable reconstruction -proposal after the operator evidence below. Acceptance and the bounded +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). Acceptance and the bounded implementation authorization are separate steps. ### A2.1 Problem and evidence @@ -296,193 +299,183 @@ These are supplied operational evidence, not a new independent server audit. | 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 replace every date in it. +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 replacement 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 Proposed decision and authority boundary - -Authorize an operator-requested reconstruction of explicitly selected, closed -UTC days of legacy `canonical/trades/bybit/BTCUSDT/trade-v1` from the whole-day -archive of Amendment 1. This is replacement of damaged historical publication, -not restoration of the original live session's continuity or sequence evidence. - -The ordinary archive importer keeps its existing refusal for an occupied day. -Reconstruction is a separate application operation composed over the existing -data-plane repair owner, never a `--force` bypass in the ordinary importer. -Healthy historical/SQLite days, new live slice keys, other datasets and the -active ingest checkpoint are not replacement targets. - -ADOPT the immutable candidate staging, evidence bindings, lock order, -compare-and-cutover, quality/eligibility owners and durable convergence principles -of [ADR-0033](ADR-0033-backfill-repair-v1.md). ADAPT their application composition -for this bounded defect. Do not introduce a parallel repair engine. - -Current `CoverageGapTrigger` cannot replace an occupied natural key, and -`InvalidRevisionTrigger` requires an authoritative failed assessment and an -`invalid` predecessor. A legacy final batch can legitimately be `valid` over its -small interval; calling it invalid merely because it is not a whole day would -falsify its existing assessment. Neither v1 trigger authorizes this operation. - -The proposed additive repair semantics are explicitly named -`quant-platform/a10-legacy-day-rebuild-v1`, distinct from -`quant-platform/a10-repair-v1`. Their predecessor-bound trigger records the -confirmed legacy publication defect, requested whole-day support, archive -identity and exact incumbent evidence. Existing v1 trigger eligibility, intent -IDs and outcomes keep their meaning. Implementation must specify and test the -new intent/plan serialization and dispatch; it must not reinterpret old intents. - -### A2.3 Inspectable plan and temporal closure - -Before materialization, a read-only plan captures: - -- the authorized dataset, explicit UTC days and reason for reconstruction; -- each incumbent partition UUID, key, revision, lifecycle state, physical and - manifest hashes, coverage documents/hashes, declared intervals and paths; -- the source URL, file SHA-256, byte size, source-observation time, expected - count, mapping/profile, producing code commit and planned candidate revision; -- coverage, observed-record and adjacent-day effects; active checkpoint - bindings; overlapping slice or healthy-history identities; -- immutable candidate locations, resource bounds, a canonical plan digest and - per-partition repair obligations bound to that exact plan. - -Re-read and compare this evidence under the repair owner's locks before any -visibility change. A changed predecessor, new overlap, changed source or changed -checkpoint relationship makes the plan stale; it cannot silently acquire a -different target or authorize another date. - -Every incumbent effect must be contained in the explicitly authorized union of -closed days, using both declared coverage and actual record bounds. A legacy -batch spanning midnight can couple adjacent days. The plan reports that closure -and refuses execution if it reaches an unapproved date, healthy historical day, -live slice, checkpoint-bound partition or active/current UTC day. An adjacent day -can enter only through a newly approved plan; no automatic date-range expansion, -clipping of old manifests, or loss of the 529 out-of-day rows is authorized. - -A connected component of approved adjacent legacy days is one atomic visibility -unit, while each candidate remains its own UTC-day partition with its own source -and certification. Independent components can execute separately and report -separate outcomes. This is explicit caller orchestration, not native aggregate -range completeness or a scheduler (ADR-0054). - -The first 2026-10-20 pilot validates preparation and refusal/cutover semantics in -disposable PostgreSQL, including neighboring production-shaped intervals. It is -not permission to replace that day in production while its boundary closure is -unresolved. A plan whose closure cannot meet these restrictions remains blocked. - -### A2.4 Candidate evidence and immutable storage - -ADOPT Amendment 1's source profile, strict archive parsing, millisecond mapping, -unique non-empty trade IDs, canonical ordering and half-open UTC-day coverage. -Complete means the day as the archived source publishes it, not measured provider -infallibility or certified continuity of the old WebSocket session. - -Materialize each candidate in a collision-safe immutable location distinct from -every incumbent artifact and manifest. Its final partition revision is the -contiguous successor captured by the plan, not revision 1 by convenience; its -files and coverage documents bind that revision. Dataset identity and existing -dataset-manifest bytes remain unchanged. Use paths representable by the existing -manifest schemas, with no overwrite or directory move of incumbent data. - -Preparation validates file and canonical-content hashes, full source-to-candidate -canonical-record equality, ordering, uniqueness, identity and day ownership. It -produces authentic source-specific certification evidence for the candidate's -final identity using S13's verification semantics without calling its ordinary -predecessor-superseding seal. Fabricated quality reports or copied predecessor -reports cannot authorize replacement. Failed attempts retain their own evidence -for inspection but never alter predecessor visibility. - -Archive reconstruction preserves the archive's null `receive_ts` and `sequence`; -it does not fabricate live-only fields. Live-to-archive comparison distinguishes -those expected provenance differences from changes in venue, instrument, -exchange time, side, price or size. ID membership alone is not a full-field gate. -Source observation, preparation and cutover times are recorded honestly; neither -availability nor the producing commit is backdated to the trade date. - -### A2.5 Cutover, readers and restart - -The repair owner provides a transaction-scoped composition for the new semantics: -all relevant dataset/lineage locks in the existing order, then affected partition -topologies in deterministic order, then under-lock reauthorization of the whole -plan. No component commits between its daily candidates. - -Within that transaction, admit the final candidate revisions, apply the existing -A16 and S14 transaction-scoped decisions, supersede the exact approved incumbent -revisions, and persist predecessor/candidate/plan convergence provenance. Refusal -of any candidate rolls back the whole component, leaving all predecessors as -they were. Commit only when every candidate is eligible and the component's -coverage/identity/row-equality gates pass. Retain authentic failed-attempt evidence -outside the rolled-back visibility transaction. - -This extends A10 composition only for the new version. It does not weaken S13's -ordinary durable phase boundaries or globally suppress its commits. A10's -existing cutover already reuses A16/S14 rather than calling ordinary S13 admission; -the bounded extension must retain that ownership and evidence discipline. - -Readers resolving an affected component must use a coherent catalog generation -for partition selection and coverage evidence, or receive a typed retry/refusal. -One read may see all of the old component or all of the new component, never a -mixture. Immutable retained predecessor files let an already-resolved read finish -after cutover. Application composition owns DataGateway read-back; the data repair -package must not import Access to perform it (ADR-0019 and ADR-0033). - -Persist a versioned plan/attempt/convergence record bound to the exact evidence; -do not overload existing v1 provenance rows or infer completion from matching -content hashes. A crash before commit leaves old visibility intact; prepared -immutable files remain unpublished evidence. After commit, an exact replay -returns durable convergence, not a second successor revision. A changed plan or -candidate is a distinct attempt and must be reauthorized. A lost response after -commit is resolved from provenance before any retry mutates data. - -Existing gap evidence and live checkpoint bytes remain untouched. Reconstruction -does not mark historical live gaps repaired, rewind a checkpoint, claim missing -sequence continuity, or enable the archive as an automatic live repair source. -Already sealed admissions and in-flight deliveries retain their referenced bytes -and source identities; new admissions resolve the new eligible revision. No -retention or physical/catalog deletion is part of this operation (ADR-0049). +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 | Remain the default for ordinary import; the separately authorized legacy-day reconstruction above is the explicit exception. | -| ADR-0075 section 7, delegation item 3 and acceptance item 3 | Lift the pause only for the explicitly approved historical legacy-day reconstruction; current slices, consolidation and live interruption evidence remain unchanged. | -| ADR-0033 decision and partition-bounded cutover | Add the distinctly versioned legacy-defect trigger and atomic composition of approved adjacent daily obligations; existing v1 triggers and cutover remain unchanged. | -| ADR-0044 | No amendment: no automatic live-gap repair or new proof of live continuity. | -| ADR-0018, frozen records/manifests, identity and ordering | No in-place changes. New repair control/provenance semantics need an explicit versioned contract and migration in their own authorized implementation slice. | -| S13, A16 and S14 ordinary publication | Existing phase boundaries and eligibility/quality authority remain; reconstruction composes the repair-owned transaction-scoped seams. | - -This proposal does not accept ADR-0075 Amendment 1 (#512 / PR #513), change its -numbering, resolve #511, complete O02/O03 or grant new capability credit. It does -not change SCOPE, Roadmap, Capability Map/DAG or Open Decisions. Acceptance must be -recorded explicitly and followed by a separately authorized implementation issue -and governance reconciliation where the active scope requires one. Production -execution follows a reviewed, pinned implementation and a reviewed date plan. +| 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. **Plan/refusal slice.** Versioned defect, plan and provenance contracts; read-only - inventory and boundary closure. Tests reject healthy historical/SQLite days, - slices, open UTC days, checkpoint targets, unapproved neighbors and stale plans. -2. **Candidate slice.** Immutable archive mapping/materialization and genuine - final-identity certification evidence; prove full-field equality, malformed - source refusal, hash/coverage binding and concurrent-attempt isolation. The - 2026-10-20 pilot must contain exactly 1,568,861 archive records, all in-day. -3. **Cutover slice.** Disposable PostgreSQL probes for S13-equivalent verification, - A16/S14 refusal, failure after first candidate admission, process/connection - loss before and after commit, stale predecessor evidence and exact retry. - Every failed component leaves predecessor rows, bytes and readability intact. - Real concurrent reader/writer interleavings prove coherent reads, loser - non-mutation and lock ordering against ordinary S13/S14/A16. A two-day - midnight-crossing fixture proves no adjacent-day record or coverage loss. -4. **Read-back/operator slice.** Strict DataGateway reads compare the full archive - records, count, ordering and duplicate keys over each replaced day; verify - unchanged non-target coverage, old admission bytes and live checkpoint. Repeat - recovery from a lost successful response. Provide resource/time bounds and an - inspect/prepare/execute/resume runbook. No automatic rollback or deletion. - -The runtime proof is required after implementation; this design-only proposal -does not claim any of those probes passed. Only after the isolated pilot and -boundary-safe production plan succeed can the operator reconstruct further -explicitly approved closed days. The 31-date inventory is not that execution plan. +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. From d927fd818573b5a611fdda7693dbbf2b09308c67 Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:08:20 +0200 Subject: [PATCH 03/13] docs(adr): record the acceptance of ADR-0074 Amendment 2 (#515) Refs #515 Co-Authored-By: Claude Sonnet 5.5 --- ...multi-instrument-bybit-linear-trades-v1.md | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) 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 af7c1e1..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 @@ -268,17 +269,16 @@ resolved as proposed: ## Amendment 2 - Rebuild damaged legacy BTCUSDT live days from the archive -**Status:** PROPOSED (design gate [#515](https://github.com/NeoNix-Lab/quant-platform/issues/515)) +**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 proposal is not an -implementation, a governance reconciliation, an acceptance record or authority to -change production data. The maintainer requested a reviewable reconstruction +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). Acceptance and the bounded -implementation authorization are separate steps. +not replace a partition atomically (see A2.8). The bounded implementation is +authorized separately (governance issue #518). ### A2.1 Problem and evidence @@ -479,3 +479,13 @@ slices and a lock on the dataset row that the live publication needs, for a bene (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. From 5144adc2125a28c24e0923f74b6480c694a5bb2a Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:19:24 +0200 Subject: [PATCH 04/13] docs(governance): DG-R - register R01 and R02, reconcile O01 with ADR-0075 Amendment 1 (#518) Co-Authored-By: Claude Sonnet 5.5 --- SCOPE.md | 59 +++++++++++++++++++++-------- docs/architecture/OPEN_DECISIONS.md | 30 ++++++++++----- docs/product/CAPABILITY_DAG.md | 45 ++++++++++++++++------ docs/product/CAPABILITY_MAP.md | 5 ++- docs/product/ROADMAP.md | 22 +++++++---- 5 files changed, 116 insertions(+), 45 deletions(-) diff --git a/SCOPE.md b/SCOPE.md index 1f4dc3a..b2c2c2e 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: **OPEN — three gates. 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` merged (PR #510, credited at the closeout), `O02` and `O03` AUTHORIZED (governance issue #507), not started. 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 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). The operator promoted it to `main` once already (PR #514, 2026-10-24: DG-M, DG-N and `O01`, before `O02`, `O03` and the closeout); the rest of the wave follows, and the first version of the product is declared concluded by the maintainer after the 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 its live days are not fully readable or complete (DG-O); 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. @@ -71,7 +72,7 @@ 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 | +| `O01` | Append-only live slices | `A11`, `K10`, `T01` | **merged** (#509 / PR #510); credited at the closeout | | `O02` | Continuous live session | `O01` | after `O01` is merged | | `O03` | Configuration, runbook and real-provider proof | `O02`, `T03`, `T04` | after `O02` is merged | @@ -83,19 +84,42 @@ Order: strictly `O01`, `O02`, `O03`, one bounded mutation slice at a time; `T02` ### 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; design-gate issues #377, #487, #504, #512, #515; evidence issue #378; implementation issues #485, #487, #491, #493, #495, #497, #499, #501, #509, #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 +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) + 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) +DG-O: O01 merged (credited at the closeout), O02, O03 FROZEN / MISSING (authorized by #507) +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. @@ -121,7 +146,8 @@ Credit, do not reimplement or re-prove absent invalidating evidence: every atom - `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. - 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: only `O01` is merged (PR #510, not credited here). The live path no longer supersedes each cycle, but it still closes its WebSocket between cycles (`O02`) and the server is not redeployed with `O01`. The existing live partitions and their superseded revisions are left as they are by DG-O. Slices are not consolidated into a day partition. The provider's `exchange_ts` ordering is an assumption until `O03` measures 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. @@ -137,9 +163,9 @@ 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. +- `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. `R01` and `R02` (Part D) are post-version: they are not a condition of the declaration below. - 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 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 later promotion 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 and the deployment are recorded separately; they are not claimed by this scope. --- @@ -150,7 +176,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..10e02c3 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-R registration (#518) 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 = 105 / 132 = 79.5% ``` ## Resolved foundation — reference only @@ -958,16 +958,28 @@ 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`. 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). +## 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/product/CAPABILITY_DAG.md b/docs/product/CAPABILITY_DAG.md index af47006..360500a 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 `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` (`O01` is merged, PR #510, and credited at the closeout), and `T02` additionally requires `O03`. 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-R registration (#518), 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 = 105 / 132 = 79.5% ``` Reconciliation #444 preserves all accepted DG-K/DG-K2 credits from main and @@ -43,7 +43,11 @@ 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-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 +175,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. @@ -397,10 +402,19 @@ Registered and authorized by governance issue #507 after the design gate #504 pr | 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). | +| 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 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). Merged (PR #510); credited at the closeout. | | 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`. | +### 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 | +|---|---|---|---|---|---|---|---| +| 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 The `Requires` relation is a DAG. In particular, operational capability and implementation sequencing are not conflated: @@ -594,12 +608,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` is authorized by #507 and not started. 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 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. ```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 | @@ -744,6 +766,7 @@ DG-C/L2 L2 historical v1 (#442) COMPLETE on implement/l2 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-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..6858c60 100644 --- a/docs/product/CAPABILITY_MAP.md +++ b/docs/product/CAPABILITY_MAP.md @@ -135,9 +135,11 @@ Implementation-state vocabulary is exactly `COMPLETE | PARTIAL | MISSING`. | 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 | 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 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). Merged (PR #510); credited at the closeout. | | 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`. | +| 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) @@ -201,6 +203,7 @@ IMPLEMENTATION_COMPLETE = 99 / 119 = 83.2% | `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-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..3190b31 100644 --- a/docs/product/ROADMAP.md +++ b/docs/product/ROADMAP.md @@ -84,6 +84,7 @@ DG-M Canonical feature identity (implement/fid) COMPLETE within recorded bounds 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-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,21 @@ 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 = 105 / 132 = 79.5% ``` -DG-O registration (#507): ADR-0075 accepted; `O01`-`O03` added as `FROZEN`/`MISSING` (127 -> 130 atoms; semantic 90.6% -> 90.8%; +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%); @@ -200,6 +204,7 @@ DG-K2 Server/deck deployment composition RESOLVED / IMPLEMENTED within r 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-R Rebuild of damaged legacy live days v1 AUTHORIZED (ADR-0074 Amendment 2 ACCEPTED #515; reconciliation #518); implementation not started ``` Important current boundaries: @@ -220,7 +225,8 @@ Explicit deferables — second-provider resolution, exact L3/MBO semantics, Data - 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-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 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 From e0a04b85874bfa348c6eca7759b315bfca7756a7 Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:58:36 +0200 Subject: [PATCH 05/13] live: one continuous WebSocket session, bounded buffer, explicit interruptions (O02, ADR-0075) Reader thread + bounded buffer, slice assembler, interruption handling with subscribe-first reconciliation, signals, continuous entry of the server (default off), PostgreSQL proof. Refs #523 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/integrity.yml | 38 ++ .../LIVE_INGEST_SERVER_DEPLOYMENT.md | 16 + src/quant_platform/application/bybit_live.py | 86 ++- .../application/live_ingest_server.py | 153 +++++ .../application/live_session.py | 450 ++++++++++++++ .../source_adapters/bybit_live_assembler.py | 168 +++++ tests/integration_live_session_postgres.py | 347 +++++++++++ tests/test_live_assembler_v1.py | 207 +++++++ tests/test_live_session_v1.py | 580 ++++++++++++++++++ tests/test_package_boundaries_v1.py | 2 + 10 files changed, 2044 insertions(+), 3 deletions(-) create mode 100644 src/quant_platform/application/live_session.py create mode 100644 src/quant_platform/source_adapters/bybit_live_assembler.py create mode 100644 tests/integration_live_session_postgres.py create mode 100644 tests/test_live_assembler_v1.py create mode 100644 tests/test_live_session_v1.py 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/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md index 57311d7..b5a089b 100644 --- a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md +++ b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md @@ -147,6 +147,22 @@ dt=/seg=/part-001.p `SLICE_ORDERING_VIOLATION`, publishes nothing, and the next start reconciles from the checkpoint. - Partitions published before ADR-0075 (`dt=`, many superseded revisions) are left as they are; there is no repair. +### Continuous session (ADR-0075 slice 9.2, `O02`): in the code, not enabled + +`LiveIngestServerConfigV1.continuous_session` (a `LiveSessionConfig`) makes the server run ONE WebSocket session instead of the bounded +cycles: the connection is not closed between publications, a bounded buffer (default 20 000 messages) decouples the reader from +the publisher, and slices close after `slice_seconds` (300) or `slice_max_trades` (50 000). The default is `None`: the cycle loop above +is unchanged, and the unit templates, the CLI flags, this runbook's operating steps and the one-hour real-provider run belong to `O03`. +What an operator will see when it is enabled: + +- A disconnect, a missing pong, a full buffer or a trade below the open window **ends the session**; what was received is published, + the interruption is signalled (`HEALTH_SNAPSHOT`, `DEGRADED`, `phase=interruption`, with the reason and the counters), the session + reconnects with a bounded backoff, subscribes first, fetches the recent trades and reconciles from the last durable key. +- Continuity proven: the reconciled trades are published as slices and the chain stays exact. Anchor outside the recent window: an + explicit gap (ADR-0044), recorded, `DEGRADED`; a new window starts at the first trade after it and nothing is claimed across the gap. +- Every published slice signals the buffer high-water mark and capacity, the slice lag in milliseconds, the number of reconnects and + of ordering violations. A publication, catalog or checkpoint failure stops the loop (`FAILURE`), as in the cycle loop. + ## Rollback This runbook does not automate rollback. If the service fails: 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..4764fd5 --- /dev/null +++ b/src/quant_platform/application/live_session.py @@ -0,0 +1,450 @@ +"""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 + + 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"}: + with self._lock: + self._tracker.heartbeat(conn_id=document.get("conn_id")) + 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 + + # ------------------------------------------------------------------------------------------------ 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 + 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) + 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 _reconcile(self, reader: _Reader, buffer: "queue.Queue[LiveTradeBatch]", assembler: SliceAssembler) -> list[LiveTradeBatch]: + """Subscribed first, then the recent trades (ADR-0042 section 5): the overlap of the two is the continuity proof.""" + + ports = self._ports + staged = self._drain_available(buffer) + if not ports.checkpoint_exists(): + assembler.start_window(None) + self._chain_end = None + return staged + 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) + 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=bybit_trade_v1_ordering_key(accepted[-1])) + 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() + assembler.start_window(floor, skip_through=ports.last_durable_key()) + 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) + 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/source_adapters/bybit_live_assembler.py b/src/quant_platform/source_adapters/bybit_live_assembler.py new file mode 100644 index 0000000..7a70198 --- /dev/null +++ b/src/quant_platform/source_adapters/bybit_live_assembler.py @@ -0,0 +1,168 @@ +"""Bybit live slice assembler v1 (ADR-0075 sections 2 and 5): the open window of a continuous session. + +The reader of a session hands the trades of each message to :meth:`SliceAssembler.add`; the publisher asks :meth:`take_due` which slices +are ready and :meth:`flush` for the rest when the session ends. A slice closes after ``slice_seconds`` of wall clock or +``slice_max_trades`` trades, at a message boundary; the boundary is the greatest ``exchange_ts`` received and the trades equal to it stay +for the next slice; a window never crosses a UTC midnight; a trade below the open window's start is an ordering violation (counted, never +accepted). No clock, network or catalog is read except the injected clock. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +import time + +from ..data.models import Instant, TradeRecord +from .bybit import bybit_trade_v1_ordering_key +from .bybit_live import deduplicate_live_records +from .bybit_live_slices import ( + SLICE_MAX_TRADES_DEFAULT, + SLICE_SECONDS_DEFAULT, + LiveSlice, + LiveSliceError, + utc_day_start_ns, +) + +_NS_PER_MS = 1_000_000 +_NS_PER_DAY = 86_400 * 1_000_000_000 + +Key = tuple[Instant, str] + + +class SliceAssembler: + """The records received since the last boundary, and the rules that cut them into slices.""" + + def __init__( + self, + *, + max_trades: int = SLICE_MAX_TRADES_DEFAULT, + slice_seconds: int = SLICE_SECONDS_DEFAULT, + window_start: Instant | None = None, + skip_through: Key | None = None, + clock: Callable[[], float] = time.monotonic, + ) -> None: + if not isinstance(max_trades, int) or isinstance(max_trades, bool) or max_trades < 1: + raise LiveSliceError("max_trades must be a positive integer") + if not isinstance(slice_seconds, int) or isinstance(slice_seconds, bool) or slice_seconds < 1: + raise LiveSliceError("slice_seconds must be a positive integer") + self._max_trades = max_trades + self._slice_seconds = slice_seconds + self._clock = clock + self._window_start_ns: int | None = None if window_start is None else window_start.epoch_ns + self._skip_through = skip_through + self._pending: dict[Key, TradeRecord] = {} + self._opened_at: float | None = None + self.ordering_violations = 0 + self.duplicates_skipped = 0 + + @property + def window_start(self) -> Instant | None: + return None if self._window_start_ns is None else Instant(self._window_start_ns) + + @property + def pending_count(self) -> int: + return len(self._pending) + + def start_window(self, start: Instant | None, *, skip_through: Key | None = None) -> None: + """A new chain after a reconciliation (``start`` = what it published up to) or after an explicit gap (``None``).""" + + if self._pending: + raise LiveSliceError("a window cannot be restarted while records are pending") + self._window_start_ns = None if start is None else start.epoch_ns + self._skip_through = skip_through + self._opened_at = None + + def add(self, records: Iterable[TradeRecord]) -> int: + """Take the trades of one message; returns how many were ordering violations (not accepted).""" + + accepted: list[tuple[Key, TradeRecord]] = [] + violations = 0 + for record in records: + if record.exchange_ts.epoch_ns % _NS_PER_MS: + raise LiveSliceError(f"record exchange_ts must be a whole millisecond: {record.exchange_ts.isoformat()}") + key = bybit_trade_v1_ordering_key(record) + if self._skip_through is not None and key <= self._skip_through: + self.duplicates_skipped += 1 + continue + if self._window_start_ns is not None and record.exchange_ts.epoch_ns < self._window_start_ns: + violations += 1 + continue + accepted.append((key, record)) + if self._window_start_ns is None and accepted: + self._window_start_ns = min(record.exchange_ts.epoch_ns for _key, record in accepted) + for key, record in accepted: + previous = self._pending.get(key) + # an equivalent duplicate is idempotent; a conflicting payload for one key fails closed (ADR-0040 section 4) + self._pending[key] = record if previous is None else deduplicate_live_records((previous, record))[0] + if accepted and self._opened_at is None: + self._opened_at = self._clock() + self.ordering_violations += violations + return violations + + def due(self) -> bool: + if not self._pending or self._window_start_ns is None: + return False + if self._pending_max_ns() >= utc_day_start_ns(self._window_start_ns) + _NS_PER_DAY: + return True + if len(self._pending) >= self._max_trades: + return True + return self._opened_at is not None and self._clock() - self._opened_at >= self._slice_seconds + + def take_due(self) -> list[LiveSlice]: + """The slices ready now: a UTC midnight is cut at once, the size and wall-clock bounds cut at the greatest ``exchange_ts``.""" + + slices = self._cut_midnights() + if self._pending and (len(self._pending) >= self._max_trades or self._time_is_up()): + boundary = self._pending_max_ns() + before = [key for key in self._pending if key[0].epoch_ns < boundary] + if before: + slices.append(self._take(before, boundary)) + self._opened_at = self._clock() # the carried trades open the next window + # nothing before the boundary: the whole window is one millisecond, which cannot be cut; it waits + return slices + + def flush(self) -> list[LiveSlice]: + """Everything received, when the session ends: the last window closes one millisecond after its greatest ``exchange_ts``.""" + + slices = self._cut_midnights() + if self._pending: + end = self._pending_max_ns() + _NS_PER_MS + slices.append(self._take(list(self._pending), end)) + self._window_start_ns = None + self._opened_at = None + return slices + + # ------------------------------------------------------------------------------------------------------------ + + def _pending_max_ns(self) -> int: + return max(key[0].epoch_ns for key in self._pending) + + def _time_is_up(self) -> bool: + return self._opened_at is not None and self._clock() - self._opened_at >= self._slice_seconds + + def _cut_midnights(self) -> list[LiveSlice]: + slices: list[LiveSlice] = [] + while self._pending and self._window_start_ns is not None: + midnight = utc_day_start_ns(self._window_start_ns) + _NS_PER_DAY + if self._pending_max_ns() < midnight: + break + before = [key for key in self._pending if key[0].epoch_ns < midnight] + if before: + slices.append(self._take(before, midnight)) + if self._pending: + self._opened_at = self._clock() # the trades after the midnight open the next window + else: + self._window_start_ns = midnight # a window that holds no trade is not published + return slices + + def _take(self, keys: list[Key], end_ns: int) -> LiveSlice: + assert self._window_start_ns is not None + records = tuple(self._pending.pop(key) for key in sorted(keys)) + slice_ = LiveSlice(Instant(self._window_start_ns), Instant(end_ns), records) + self._window_start_ns = end_ns + if not self._pending: + self._opened_at = None + return slice_ + + +__all__ = ["SliceAssembler"] diff --git a/tests/integration_live_session_postgres.py b/tests/integration_live_session_postgres.py new file mode 100644 index 0000000..a29e1ab --- /dev/null +++ b/tests/integration_live_session_postgres.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Real PostgreSQL proof of the continuous live session (DG-O O02, ADR-0075 slice 9.2). + +The real ``run_live_ingest_server`` runs ONE session for ``ETHUSDT`` over a real storage root and catalog, through the real +publication path (assembler, S13, S14, DataGateway read-back), the real reconciliation and real checkpoint files. Only the provider is +scripted: a WebSocket with the ``websockets.connect`` shape and a recent-trades window drawn from one list of "true" trades, so what +the session misses during an outage is exactly what the reconciliation can (or cannot) recover. Requires ``DATA_GATEWAY_TEST_DSN``. + +Proves: several slices over ONE connection whose windows chain exactly (a strict read over all of them returns every delivered trade); +a disconnect followed by a reconciliation that restores continuity (the trades the session missed are recovered, none twice, and a +strict read across the interruption succeeds); an anchor outside the recent window is an explicit gap (recorded, never a ``complete`` +claim: a strict read across it refuses, ``allow-partial`` returns everything, the checkpoint does not move across it); a crash between +a publication and the checkpoint advance is replayed without a duplicate; a trade below the open window is counted and ends the +session. +""" + +from __future__ import annotations + +from datetime import timedelta +import os +from pathlib import Path +import sys +import tempfile +import threading +import time +import types +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +sys.path.insert(0, str(ROOT / "tests")) +import psycopg # noqa: E402 +import quant_platform.application.bybit_live as app # noqa: E402 +from integration_live_slices_postgres import gateway_read, key_of, partitions, rows # noqa: E402 +from quant_platform.application.live_gap_orchestration import load_open_long_gap_records # noqa: E402 +from quant_platform.application.live_ingest_server import ( # noqa: E402 + SERVER_FAILED, + SERVER_STOPPED, + LiveIngestServerConfigV1, + run_live_ingest_server, +) +from quant_platform.application.live_session import LiveSessionConfig # noqa: E402 +from quant_platform.data import Instant # noqa: E402 +from quant_platform.data.models import NoCoverage # noqa: E402 +from quant_platform.operations.checkpoint import CheckpointStore # noqa: E402 +from quant_platform.operations.observability import SignalKind # noqa: E402 +from quant_platform.operations.pressure import PressurePolicyDefinition # noqa: E402 +from quant_platform.source_adapters.bybit_live import canonicalize_bybit_live_message # noqa: E402 +from test_live_session_v1 import Closed, FakeProvider # noqa: E402 + +STORAGE_ROOT_ID = "live-hot" +INSTRUMENT = "ETHUSDT" +MS = 1_000_000 +BASE_MS = int(Instant.parse("2026-10-21T10:00:00Z").epoch_ns // MS) +POLICY = PressurePolicyDefinition( + max_capacity_observation_age=timedelta(seconds=300), pressure_available_bytes=1, critical_available_bytes=1, + exhausted_available_bytes=0, +) +SESSION = LiveSessionConfig( + slice_seconds=3600, slice_max_trades=7, buffer_messages=500, ping_interval=30.0, pong_timeout=5.0, connect_timeout=5.0, + reconnect_delay=0.05, reconnect_delay_max=0.1, tick=0.01, +) + + +class World: + """The true trades of the instrument. The session sees the ones the provider delivers; the REST window sees the tail of all.""" + + def __init__(self) -> None: + self.trades: list = [] + self.next_ms = BASE_MS + self.index = 0 + + def make(self, count: int, step: int = 3) -> list: + made = [] + for _ in range(count): + row = {"i": f"t-{self.index}", "s": INSTRUMENT, "T": self.next_ms, "S": "Buy" if self.index % 2 == 0 else "Sell", + "p": f"100.{self.index % 90 + 10}", "v": "0.5", "seq": self.index + 1} + made.append(row) + self.index += 1 + self.next_ms += step + records = canonicalize_bybit_live_message( + {"topic": f"publicTrade.{INSTRUMENT}", "type": "snapshot", "ts": self.next_ms, "data": made}, instrument=INSTRUMENT).records + self.trades.extend(records) + return made + + @staticmethod + def message(rows_: list) -> dict: + return {"topic": f"publicTrade.{INSTRUMENT}", "type": "snapshot", "ts": rows_[-1]["T"], "data": rows_} + + +class Run: + """One run of the real server in a worker thread.""" + + def __init__(self, dsn, storage, checkpoint, provider: FakeProvider) -> None: + self.provider = provider + self.signals: list = [] + self.stop = threading.Event() + self.report = None + self.error = None + self.config = LiveIngestServerConfigV1( + storage_root=storage, storage_root_id=STORAGE_ROOT_ID, checkpoint_path=checkpoint, pressure_policy=POLICY, dsn=dsn, + producer="live-session-proof", code_ref="integration", recent_limit=1000, instrument=INSTRUMENT, + continuous_session=SESSION, + ) + self.thread = threading.Thread(target=self._run, daemon=True) + + def _run(self) -> None: + try: + self.report = run_live_ingest_server(self.config, stop_requested=self.stop.is_set, on_signal=self.signals.append) + except BaseException as exc: # noqa: BLE001 + self.error = exc + + def start(self) -> "Run": + self.thread.start() + return self + + def finish(self) -> None: + self.stop.set() + self.thread.join(30) + assert not self.thread.is_alive(), "the server did not stop" + assert self.error is None, repr(self.error) + + def until(self, condition, what: str, timeout: float = 20.0) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if self.error is not None or self.report is not None: + raise AssertionError(f"the server ended while waiting for {what}: {self.error!r} {self.report}") + if condition(): + return + time.sleep(0.01) + raise AssertionError(f"timed out waiting for {what}; signals={[dict(s.payload).get('phase') for s in self.signals][-8:]}") + + def health(self, phase: str) -> list[dict]: + return [dict(s.payload) for s in self.signals if s.kind is SignalKind.HEALTH_SNAPSHOT and dict(s.payload).get("phase") == phase] + + +def websockets_stub(provider: FakeProvider): + module = types.ModuleType("websockets") + module.connect = provider.connect + module.ConnectionClosed = Closed + return mock.patch.dict(sys.modules, {"websockets": module}) + + +def slices(connection): + return partitions(connection, INSTRUMENT) + + +def check_catalog(connection, expected_trades: set[str]) -> list: + """Nothing superseded, nothing but valid revision 1; every trade the session published readable exactly once, in order.""" + + found = slices(connection) + assert found and {r[1] for r in found} == {1} and {r[2] for r in found} == {"valid"}, [(r[0], r[1], r[2]) for r in found] + everything = gateway_read(connection, Instant.parse(found[0][3]), Instant.parse(found[-1][4]), "allow-partial", INSTRUMENT) + ids = [r.trade_id for r in everything] + assert len(ids) == len(set(ids)), "a trade is published twice" + assert set(ids) == expected_trades, (sorted(expected_trades - set(ids)), sorted(set(ids) - expected_trades)) + assert [key_of(r) for r in everything] == sorted(key_of(r) for r in everything) + return found + + +def chain_is_exact(found: list) -> bool: + return all(Instant.parse(a[4]) == Instant.parse(b[3]) for a, b in zip(found, found[1:])) + + +def main() -> int: + dsn = os.environ.get("DATA_GATEWAY_TEST_DSN") + if not dsn: + print("POSTGRESQL LIVE SESSION GATE NOT EXECUTED LOCALLY") + return 0 + with tempfile.TemporaryDirectory() as holder, psycopg.connect(dsn) as connection: + storage = Path(holder) / "storage" + checkpoint = storage / "_k10_checkpoints" / f"live-ingest-server-v1-{INSTRUMENT}.json" + checkpoint.parent.mkdir(parents=True) + with connection.cursor() as cursor: + cursor.execute("INSERT INTO catalog.schema_registry (schema_id,name,version,json_sha256,body) VALUES ('trade-v1','trade',1,%s,%s::jsonb) ON CONFLICT DO NOTHING", ("0" * 64, "{}")) + cursor.execute("INSERT INTO catalog.storage_roots (storage_root_id,abs_path,tier) VALUES (%s,%s,'hot')", (STORAGE_ROOT_ID, str(storage))) + connection.commit() + + world = World() + provider = FakeProvider() + delivered: set[str] = set() # the trades the platform has published or must publish (the session saw them or the REST proved them) + + arrival_while_reconciling = {"armed": False} + + def recent(*, limit, instrument="BTCUSDT"): + if arrival_while_reconciling["armed"]: + # trades that arrive while the session reconciles: in the REST window AND over the new socket (the overlap proof) + arrival_while_reconciling["armed"] = False + rows_ = world.make(4) + provider.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + return tuple(world.trades[-limit:]) + + with mock.patch.object(app, "fetch_recent_public_trades", recent), websockets_stub(provider): + # 1. One session, many slices: the connection is opened once, never closed between publications, the windows chain + # exactly, and a STRICT read over all of them returns every delivered trade. + run = Run(dsn, storage, checkpoint, provider).start() + run.until(lambda: provider.sockets, "the connection") + for k in range(8): + rows_ = world.make(5) + provider.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + time.sleep(0.12) + run.until(lambda: len(slices(connection)) >= 4, "four slices") + time.sleep(0.5) + assert provider.connects == 1 and provider.closed_sockets == 0, (provider.connects, provider.closed_sockets) + published = slices(connection) + assert chain_is_exact(published), "the windows of one session must chain exactly" + strict = gateway_read(connection, Instant.parse(published[0][3]), Instant.parse(published[-1][4]), "strict", INSTRUMENT) + assert strict and {r.trade_id for r in strict} <= delivered + saved = CheckpointStore(checkpoint).load() + assert saved.partition_key == published[-1][0] and saved.generation == len(published), saved + assert all(0 <= dict(s.payload)["buffer_high_water"] <= 500 for s in run.signals + if s.kind is SignalKind.HEALTH_SNAPSHOT and dict(s.payload).get("phase") == "slice") + + # 2. A disconnect: what was listened to is published, the session reconnects, the recent trades prove continuity from + # the last durable key, the trades the session MISSED are recovered, none twice, and a strict read across the + # interruption succeeds. + before = len(slices(connection)) + missed = world.make(6) # delivered nowhere over the WebSocket: the provider closes the connection first + delivered.update(r["i"] for r in missed) + arrival_while_reconciling["armed"] = True + provider.close() + run.until(lambda: provider.connects == 2, "the reconnect") + run.until(lambda: run.health("reconcile"), "the reconciliation") + more = world.make(5) + provider.push(world.message(more)) + delivered.update(r["i"] for r in more) + time.sleep(0.3) + run.until(lambda: len(slices(connection)) > before + 1, "the slices after the reconnect") + interruptions = run.health("interruption") + assert [h["interruption"] for h in interruptions] == ["disconnect"], interruptions + assert provider.connects == 2 + published = slices(connection) + assert chain_is_exact(published), "the interruption was proven continuous: the chain must stay exact" + gateway_read(connection, Instant.parse(published[0][3]), Instant.parse(published[-1][4]), "strict", INSTRUMENT) + run.finish() + assert run.report.status == SERVER_STOPPED and not [s for s in run.signals if s.kind is SignalKind.FAILURE] + assert run.health("slice")[-1]["reconnects"] == 1 # the slice published at the stop is the second session's + found = check_catalog(connection, delivered) + assert chain_is_exact(found) + assert CheckpointStore(checkpoint).load().partition_key == found[-1][0] + + # 3. An anchor outside the recent window is an explicit gap: recorded, never a complete claim, the checkpoint does not + # move across it, and a strict read across it refuses. + provider2 = FakeProvider() + run = Run(dsn, storage, checkpoint, provider2) + world.make(60) # a long outage: the REST window below holds only the last few + tail = world.trades[-3:] + generation = CheckpointStore(checkpoint).load().generation + + def recent_after_outage(*, limit, instrument="BTCUSDT"): + return tuple(tail) + + with mock.patch.object(app, "fetch_recent_public_trades", recent_after_outage), websockets_stub(provider2): + run.start() + run.until(lambda: provider2.sockets, "the connection after the outage") + run.until(lambda: run.health("reconcile") and any("anchor" in str(h.get("reason", "")) or "last durable" in str(h.get("reason", "")) for h in run.health("reconcile")), "the gap") + assert CheckpointStore(checkpoint).load().generation == generation, "the checkpoint moved across a gap" + assert load_open_long_gap_records(storage_root=storage, instrument=INSTRUMENT).records, "the gap was not recorded" + after = world.make(8) + provider2.push(world.message(after)) + delivered.update(r["i"] for r in after) + time.sleep(0.3) + run.finish() + found = check_catalog(connection, delivered) + assert not chain_is_exact(found), "a gap must not be chained over" + try: + gateway_read(connection, Instant.parse(found[0][3]), Instant.parse(found[-1][4]), "strict", INSTRUMENT) + except NoCoverage: + pass + else: + raise AssertionError("a strict read across an explicit gap must refuse") + assert CheckpointStore(checkpoint).load().generation > generation # the next publication advanced it, after the gap + + # 4. A crash between a publication and the checkpoint advance: the checkpoint is behind a durable slice; the restart + # replays it and publishes no second trade. + provider3 = FakeProvider() + crash = Run(dsn, storage, checkpoint, provider3) + real_persist = app.persist_publication_checkpoint + calls = {"n": 0} + + def failing_persist(**kwargs): + calls["n"] += 1 + if calls["n"] == 2: + raise RuntimeError("crash after the publication, before the checkpoint advance") + return real_persist(**kwargs) + + def recent_all(*, limit, instrument="BTCUSDT"): + return tuple(world.trades[-limit:]) + + with mock.patch.object(app, "fetch_recent_public_trades", recent_all), \ + mock.patch.object(app, "persist_publication_checkpoint", failing_persist), websockets_stub(provider3): + crash.start() + crash.until(lambda: provider3.sockets and crash.health("reconcile"), "the reconciliation") + for _ in range(4): + rows_ = world.make(5) + provider3.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + time.sleep(0.15) + crash.thread.join(15) + assert crash.report is not None and crash.report.status == SERVER_FAILED, ( + crash.report, calls, [(s.kind.name, dict(s.payload).get("phase"), dict(s.payload).get("reason")) for s in crash.signals][-8:]) + behind = CheckpointStore(checkpoint).load() + durable = slices(connection) + assert Instant.parse(durable[-1][4]) > behind.last_canonical_exchange_ts, "the slice was not durable ahead of the checkpoint" + provider4 = FakeProvider() + restart = Run(dsn, storage, checkpoint, provider4) + with mock.patch.object(app, "fetch_recent_public_trades", recent_all), websockets_stub(provider4): + restart.start() + restart.until(lambda: provider4.sockets and (restart.health("reconcile") or restart.health("slice")), "the replay") + more = world.make(4) + provider4.push(world.message(more)) + delivered.update(r["i"] for r in more) + time.sleep(0.3) + restart.finish() + found = check_catalog(connection, delivered) # no trade twice, none lost + + # 5. A trade below the open window is counted, never accepted, and ends the session. + provider5 = FakeProvider() + late = Run(dsn, storage, checkpoint, provider5) + with mock.patch.object(app, "fetch_recent_public_trades", recent_all), websockets_stub(provider5): + late.start() + late.until(lambda: provider5.sockets and late.health("reconcile"), "the reconciliation") + rows_ = world.make(5) + provider5.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + rows_ = world.make(5) + provider5.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + late.until(lambda: len(slices(connection)) > len(found), "a slice") + window_start = Instant.parse(slices(connection)[-1][4]) + straggler = {"i": "t-late", "s": INSTRUMENT, "T": window_start.epoch_ns // MS - 4, "S": "Buy", "p": "100.1", "v": "0.5", "seq": 99999} + provider5.push(world.message([straggler])) + late.until(lambda: late.health("interruption"), "the interruption") + late.finish() + assert late.health("interruption")[0]["interruption"] == "ordering_violation" + assert late.health("interruption")[0]["ordering_violations"] == 1 + check_catalog(connection, delivered) # "t-late" was never published + + assert [r[0] for r in rows(connection, "SELECT instrument FROM catalog.datasets ORDER BY 1")] == [INSTRUMENT] + print("POSTGRESQL LIVE SESSION GATE PASSED") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_live_assembler_v1.py b/tests/test_live_assembler_v1.py new file mode 100644 index 0000000..ac43d81 --- /dev/null +++ b/tests/test_live_assembler_v1.py @@ -0,0 +1,207 @@ +"""DG-O O02 (ADR-0075 sections 2 and 5): the slice assembler of a continuous session. Pure: an injected clock, no network, no catalog.""" + +from __future__ import annotations + +from pathlib import Path +import random +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) + +from quant_platform.data.models import Instant, TradeRecord # noqa: E402 +from quant_platform.source_adapters.bybit_live import BybitLiveIntegrityError # noqa: E402 +from quant_platform.source_adapters.bybit_live_assembler import SliceAssembler # noqa: E402 +from quant_platform.source_adapters.bybit_live_slices import LiveSliceError # noqa: E402 + +MS = 1_000_000 +DAY_MS = 86_400_000 +D0 = int(Instant.parse("2026-10-21T14:30:15Z").epoch_ns // MS) +MIDNIGHT = int(Instant.parse("2026-10-22T00:00:00Z").epoch_ns // MS) + + +def trade(ms: int, trade_id: str, price: str = "100.10", sequence: str = "1") -> TradeRecord: + return TradeRecord("bybit", "ETHUSDT", Instant(ms * MS), price, "0.5", "buy", None, trade_id, sequence) + + +class Clock: + def __init__(self) -> None: + self.now = 1000.0 + + def __call__(self) -> float: + return self.now + + +def ids(slice_) -> list[str]: + return [r.trade_id for r in slice_.records] + + +class AssemblerTests(unittest.TestCase): + def setUp(self) -> None: + self.clock = Clock() + + def assembler(self, **kwargs) -> SliceAssembler: + return SliceAssembler(clock=self.clock, **kwargs) + + def test_the_first_window_starts_at_the_earliest_trade_of_the_first_message(self) -> None: + a = self.assembler() + self.assertIsNone(a.window_start) + self.assertEqual(0, a.add([trade(D0 + 5, "b"), trade(D0 + 2, "a")])) + self.assertEqual(Instant((D0 + 2) * MS), a.window_start) + self.assertFalse(a.due()) + self.assertEqual([], a.take_due()) + + def test_the_wall_clock_bound_closes_at_the_greatest_exchange_ts_and_ties_stay(self) -> None: + a = self.assembler(slice_seconds=300) + a.add([trade(D0, "a"), trade(D0 + 10, "b")]) + a.add([trade(D0 + 20, "c"), trade(D0 + 20, "d")]) + self.clock.now += 299.9 + self.assertFalse(a.due()) + self.clock.now += 0.2 + self.assertTrue(a.due()) + slices = a.take_due() + self.assertEqual(1, len(slices)) + self.assertEqual((Instant(D0 * MS), Instant((D0 + 20) * MS)), (slices[0].window_start, slices[0].window_end)) + self.assertEqual(["a", "b"], ids(slices[0])) + self.assertEqual(2, a.pending_count) # the two trades of the boundary millisecond stay + self.assertEqual(Instant((D0 + 20) * MS), a.window_start) + self.assertFalse(a.due()) # the carried trades opened a new window: its clock restarted + + def test_the_wall_clock_bound_is_inclusive(self) -> None: + a = self.assembler(slice_seconds=300) + a.add([trade(D0, "a"), trade(D0 + 10, "b")]) + self.clock.now += 300.0 + self.assertTrue(a.due()) + (only,) = a.take_due() + self.assertEqual(["a"], ids(only)) + + def test_a_trade_exactly_at_midnight_is_cut_at_once(self) -> None: + a = self.assembler() + a.add([trade(MIDNIGHT - 1, "a"), trade(MIDNIGHT, "b")]) + self.assertTrue(a.due()) + (before,) = a.take_due() + self.assertEqual((["a"], Instant(MIDNIGHT * MS)), (ids(before), before.window_end)) + self.assertEqual(Instant(MIDNIGHT * MS), a.window_start) + self.assertEqual(1, a.pending_count) + + def test_the_size_bound_closes_a_slice(self) -> None: + a = self.assembler(max_trades=3) + a.add([trade(D0, "a"), trade(D0 + 1, "b")]) + self.assertFalse(a.due()) + a.add([trade(D0 + 2, "c")]) + self.assertTrue(a.due()) + (only,) = a.take_due() + self.assertEqual(["a", "b"], ids(only)) + self.assertEqual(1, a.pending_count) + + def test_a_window_of_one_millisecond_cannot_be_cut_and_waits(self) -> None: + a = self.assembler(max_trades=2) + a.add([trade(D0, "a"), trade(D0, "b")]) + self.assertTrue(a.due()) + self.assertEqual([], a.take_due()) + self.assertEqual(2, a.pending_count) + a.add([trade(D0 + 1, "c")]) + (only,) = a.take_due() + self.assertEqual(["a", "b"], ids(only)) + + def test_a_utc_midnight_is_cut_at_once_and_the_later_trades_open_the_next_window(self) -> None: + a = self.assembler() + a.add([trade(MIDNIGHT - 5, "a"), trade(MIDNIGHT - 1, "b")]) + self.assertEqual([], a.take_due()) + a.add([trade(MIDNIGHT, "c"), trade(MIDNIGHT + 3, "d")]) + self.assertTrue(a.due()) + (before,) = a.take_due() + self.assertEqual(["a", "b"], ids(before)) + self.assertEqual(Instant(MIDNIGHT * MS), before.window_end) + self.assertEqual(Instant(MIDNIGHT * MS), a.window_start) + self.assertEqual(2, a.pending_count) + (after,) = a.flush() + self.assertEqual((Instant(MIDNIGHT * MS), Instant((MIDNIGHT + 4) * MS)), (after.window_start, after.window_end)) + self.assertEqual(["c", "d"], ids(after)) + + def test_a_trade_below_the_open_windows_start_is_an_ordering_violation(self) -> None: + a = self.assembler() + a.add([trade(D0, "a"), trade(D0 + 10, "b")]) + self.clock.now += 301 + a.take_due() # the window now starts at D0 + 10 + self.assertEqual(1, a.add([trade(D0 + 9, "late"), trade(D0 + 11, "c")])) + self.assertEqual(1, a.ordering_violations) + self.assertEqual(0, a.add([trade(D0 + 10, "tie")])) # a trade at the boundary is the next window's own + self.assertEqual(["b", "tie", "c"], [k[1] for k in sorted(a._pending)]) + + def test_an_equivalent_duplicate_is_idempotent_and_a_conflicting_one_fails_closed(self) -> None: + a = self.assembler() + a.add([trade(D0, "a")]) + a.add([trade(D0, "a")]) + self.assertEqual(1, a.pending_count) + with self.assertRaises(BybitLiveIntegrityError): + a.add([trade(D0, "a", price="999.9")]) + + def test_trades_at_or_before_the_skip_key_are_duplicates_of_what_is_already_published(self) -> None: + skip = (Instant((D0 + 5) * MS), "m") + a = self.assembler(window_start=Instant((D0 + 6) * MS), skip_through=skip) + a.add([trade(D0 + 5, "m"), trade(D0 + 4, "z"), trade(D0 + 6, "n")]) + self.assertEqual((2, 0, 1), (a.duplicates_skipped, a.ordering_violations, a.pending_count)) + + def test_flush_closes_one_millisecond_after_the_greatest_trade_and_ends_the_chain(self) -> None: + a = self.assembler() + a.add([trade(D0, "a"), trade(D0 + 7, "b"), trade(D0 + 7, "c")]) + (only,) = a.flush() + self.assertEqual((Instant(D0 * MS), Instant((D0 + 8) * MS)), (only.window_start, only.window_end)) + self.assertEqual(["a", "b", "c"], ids(only)) + self.assertEqual((0, None), (a.pending_count, a.window_start)) + self.assertEqual([], a.flush()) + + def test_a_window_cannot_be_restarted_while_records_are_pending(self) -> None: + a = self.assembler() + a.add([trade(D0, "a")]) + with self.assertRaises(LiveSliceError): + a.start_window(None) + a.flush() + a.start_window(Instant((D0 + 100) * MS), skip_through=(Instant((D0 + 99) * MS), "z")) + self.assertEqual(Instant((D0 + 100) * MS), a.window_start) + + def test_a_sub_millisecond_trade_and_bad_bounds_are_refused(self) -> None: + with self.assertRaises(LiveSliceError): + self.assembler().add([TradeRecord("bybit", "ETHUSDT", Instant(D0 * MS + 1), "1", "1", "buy", None, "a", "1")]) + for bad in (0, -1, True, 1.5): + with self.assertRaises(LiveSliceError): + self.assembler(max_trades=bad) + with self.assertRaises(LiveSliceError): + self.assembler(slice_seconds=bad) + + def test_random_streams_lose_nothing_and_chain_exactly(self) -> None: + for seed in range(40): + rng = random.Random(seed) + a = self.assembler(max_trades=rng.choice((2, 5, 50)), slice_seconds=rng.choice((1, 10, 300))) + published: list = [] + sent: list[TradeRecord] = [] + ts = MIDNIGHT - rng.randrange(0, 2000) + for index in range(rng.randrange(1, 120)): + ts += rng.choice((0, 0, 1, 3, 40, 900)) + batch = [trade(ts, f"s{seed}-{index}-{k}") for k in range(rng.randrange(1, 4))] + sent.extend(batch) + self.assertEqual(0, a.add(batch)) + self.clock.now += rng.choice((0.0, 0.5, 4.0, 12.0)) + published.extend(a.take_due()) + published.extend(a.flush()) + with self.subTest(seed=seed): + got = [r.trade_id for s in published for r in s.records] + self.assertEqual(sorted(r.trade_id for r in sent), sorted(got)) + self.assertEqual(len(got), len(set(got))) + for left, right in zip(published, published[1:]): + self.assertTrue( + left.window_end == right.window_start or left.window_end.epoch_ns % (DAY_MS * MS) == 0, + (left.window_end, right.window_start), + ) + self.assertLess(left.records[-1].exchange_ts.epoch_ns, right.records[0].exchange_ts.epoch_ns) + for s in published: + self.assertTrue(s.records) + self.assertLessEqual(s.window_start.epoch_ns, s.records[0].exchange_ts.epoch_ns) + self.assertLess(s.records[-1].exchange_ts.epoch_ns, s.window_end.epoch_ns) + self.assertLessEqual(s.window_end.epoch_ns, (s.window_start.epoch_ns // (DAY_MS * MS) + 1) * DAY_MS * MS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_live_session_v1.py b/tests/test_live_session_v1.py new file mode 100644 index 0000000..2450be4 --- /dev/null +++ b/tests/test_live_session_v1.py @@ -0,0 +1,580 @@ +"""DG-O O02 (ADR-0075 sections 1 and 5): the continuous session -- one connection, a bounded buffer, explicit interruptions. + +A scripted provider (an object with the ``websockets.connect`` shape) and scripted ports: no network, no catalog. The engine runs in a +worker thread (as in the server) while the test thread drives the provider and waits for conditions. The PostgreSQL proof through the +real publication path is ``tests/integration_live_session_postgres.py``. +""" + +from __future__ import annotations + +import json +from pathlib import Path +import queue +import sys +import threading +import time +from types import SimpleNamespace +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) + +from quant_platform.application.live_session import ( # noqa: E402 + Interruption, + LiveSessionConfig, + LiveSessionEngine, + LiveSessionFailure, + LiveSessionPorts, +) +from quant_platform.data.models import Instant, TradeRecord # noqa: E402 +from quant_platform.source_adapters.bybit_live import SessionState # noqa: E402 + +MS = 1_000_000 +INSTRUMENT = "ETHUSDT" +T0 = int(Instant.parse("2026-10-21T10:00:00Z").epoch_ns // MS) + + +class Closed(Exception): + """The scripted provider's way to close the connection.""" + + +def trade_message(first_ms: int, *ids: str, step: int = 1, instrument: str = INSTRUMENT) -> dict: + rows = [ + {"i": trade_id, "s": instrument, "T": first_ms + k * step, "S": "Buy", "p": "100.10", "v": "0.5", "seq": 7} + for k, trade_id in enumerate(ids) + ] + return {"topic": f"publicTrade.{instrument}", "type": "snapshot", "ts": first_ms + len(ids), "data": rows} + + +def record(ms: int, trade_id: str) -> TradeRecord: + return TradeRecord("bybit", INSTRUMENT, Instant(ms * MS), "100.10", "0.5", "buy", None, trade_id, "7") + + +class FakeSocket: + def __init__(self, provider: "FakeProvider") -> None: + self.provider = provider + self.inbox: "queue.Queue" = queue.Queue() + + async def send(self, payload: str) -> None: + import asyncio + + document = json.loads(payload) + self.provider.sent.append(document) + self.provider.log.append(document["op"]) + if document["op"] == "subscribe" and self.provider.acknowledge: + self.inbox.put(json.dumps({"op": "subscribe", "success": True, "conn_id": "c"})) + if document["op"] == "ping" and self.provider.pong: + self.inbox.put(json.dumps({"op": "ping", "ret_msg": "pong", "success": True, "conn_id": "c"})) + await asyncio.sleep(0) + + async def recv(self) -> str: + import asyncio + + while True: + try: + item = self.inbox.get_nowait() + except queue.Empty: + await asyncio.sleep(0.002) + continue + if isinstance(item, BaseException): + raise item + return item + + async def __aenter__(self) -> "FakeSocket": + return self + + async def __aexit__(self, *exc_info: object) -> bool: + self.provider.closed_sockets += 1 + return False + + +class FakeProvider: + def __init__(self) -> None: + self.sockets: list[FakeSocket] = [] + self.sent: list[dict] = [] + self.log: list[str] = [] + self.connects = 0 + self.closed_sockets = 0 + self.acknowledge = True + self.pong = True + self.fail_connects = 0 + + def connect(self, url, **kwargs): + self.connects += 1 + self.log.append("connect") + if self.fail_connects: + self.fail_connects -= 1 + raise OSError("connection refused") + socket = FakeSocket(self) + self.sockets.append(socket) + return socket + + @property + def socket(self) -> FakeSocket: + return self.sockets[-1] + + def push(self, message: dict) -> None: + self.socket.inbox.put(json.dumps(message)) + + def close(self) -> None: + self.socket.inbox.put(Closed("the provider closed the connection")) + + +class Harness: + """The engine with scripted ports, in a worker thread.""" + + def __init__(self, provider: FakeProvider, *, config: LiveSessionConfig | None = None, checkpoint: bool = False, + reconcile=None, recent=(), floor=None, last_key=None, publish_status="PASS", gate: threading.Event | None = None) -> None: + self.provider = provider + self.slices: list = [] + self.chain_starts: list = [] + self.evidences: list = [] + self.persisted: list = [] + self.events: list[tuple[str, dict]] = [] + self.reconciled: list = [] + self.gaps: list = [] + self.checkpoint = checkpoint + self.publish_status = publish_status + self.gate = gate + self.stop = threading.Event() + self.error: BaseException | None = None + self.summary = None + self.sleeps: list[float] = [] + self._reconcile = reconcile + self._recent = recent + self._floor = floor + self._last_key = last_key + self.config = config or LiveSessionConfig( + slice_seconds=3600, slice_max_trades=3, buffer_messages=50, ping_interval=30.0, pong_timeout=5.0, + connect_timeout=2.0, reconnect_delay=0.01, reconnect_delay_max=0.02, tick=0.01) + ports = LiveSessionPorts( + connect=provider.connect, fetch_recent=self._fetch, publish_slice=self._publish, persist_checkpoint=self.persisted.append, + reconcile=self._reconcile_call, checkpoint_exists=lambda: self.checkpoint, published_floor=lambda: self._floor, + last_durable_key=lambda: self._last_key, record_gap=self._gap, connection_errors=(OSError, Closed), + sleep=lambda s: self.sleeps.append(s) or time.sleep(0.001), + ) + self.engine = LiveSessionEngine( + instrument=INSTRUMENT, config=self.config, ports=ports, on_event=lambda name, **f: self.events.append((name, f))) + self.thread = threading.Thread(target=self._run, daemon=True) + + def _fetch(self, limit): + self.provider.log.append("fetch_recent") + return self._recent + + def _publish(self, sliced, chain_start, evidence): + if self.gate is not None: + self.gate.wait(10) + self.provider.log.append("publish") + self.slices.append(sliced) + self.chain_starts.append(chain_start) + self.evidences.append(evidence) + return SimpleNamespace(status=self.publish_status) + + def _reconcile_call(self, recent, buffered): + self.provider.log.append("reconcile") + self.reconciled.append((recent, buffered)) + return self._reconcile(recent, buffered) + + def _gap(self, report): + self.gaps.append(report) + return "gap-record" + + def _run(self) -> None: + try: + self.summary = self.engine.run(self.stop.is_set) + except BaseException as exc: # noqa: BLE001 + self.error = exc + + def __enter__(self) -> "Harness": + self.thread.start() + return self + + def __exit__(self, *exc_info: object) -> None: + self.stop.set() + if self.gate is not None: + self.gate.set() + self.thread.join(15) + + def until(self, condition, what: str, timeout: float = 5.0) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if self.error is not None: + raise AssertionError(f"the engine failed: {self.error!r}") + if condition(): + return + time.sleep(0.005) + raise AssertionError(f"timed out waiting for {what}; log={self.provider.log[-12:]} error={self.error!r}") + + def events_named(self, name: str) -> list[dict]: + return [fields for event, fields in self.events if event == name] + + +def pass_restart(window_end_ms: int, accepted: list[TradeRecord], slices: int = 1): + return SimpleNamespace( + status="PASS", publication=SimpleNamespace(window_end=Instant(window_end_ms * MS).isoformat(), slices=slices), + restart_outcome=SimpleNamespace(accepted_records=tuple(accepted))) + + +class ContinuousSessionTests(unittest.TestCase): + def test_many_slices_are_published_over_one_connection_and_chain_exactly(self) -> None: + provider = FakeProvider() + with Harness(provider) as h: + h.until(lambda: provider.connects == 1 and len(provider.sockets) == 1, "the connection") + for k in range(8): + provider.push(trade_message(T0 + k * 10, f"a{k}", f"b{k}")) + time.sleep(0.03) # a message at a time: each turn of the publisher closes what is due + h.until(lambda: len(h.slices) >= 3, "three slices") + first_socket = provider.socket + self.assertIsNone(h.error) + self.assertEqual(1, provider.connects) # the session was never closed between publications + self.assertEqual(1, provider.closed_sockets) # and was closed once, by the stop + self.assertEqual( + [("subscribe", [f"publicTrade.{INSTRUMENT}"])], + [(d["op"], d["args"]) for d in provider.sent if d["op"] == "subscribe"]) + for left, right in zip(h.slices, h.slices[1:]): + self.assertEqual(left.window_end, right.window_start) # exact chain + # every trade the provider delivered is in exactly one slice + got = [r.trade_id for s in h.slices for r in s.records] + self.assertEqual(sorted(f"{p}{k}" for k in range(8) for p in "ab"), sorted(got)) + self.assertEqual([None] + [s.window_end for s in h.slices[:-1]], h.chain_starts) + self.assertEqual(h.chain_starts[1:], [s.window_start for s in h.slices[1:]]) + self.assertIs(first_socket, provider.sockets[0]) + + def test_the_checkpoint_advances_only_after_each_slice_is_published(self) -> None: + provider = FakeProvider() + with Harness(provider) as h: + h.until(lambda: provider.sockets, "the connection") + for k in range(4): + provider.push(trade_message(T0 + k * 10, f"a{k}", f"b{k}")) + time.sleep(0.05) # one message at a time: each turn of the publisher closes what is due + h.until(lambda: len(h.persisted) >= 2, "two checkpoint advances") + log = provider.log + publishes = [i for i, name in enumerate(log) if name == "publish"] + self.assertGreaterEqual(len(publishes), 2) + self.assertEqual(len(h.slices), len(h.persisted)) + + def test_the_evidence_of_a_slice_is_an_alive_session_and_claims_completeness(self) -> None: + provider = FakeProvider() + with Harness(provider) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b")) + provider.push(trade_message(T0 + 10, "c", "d")) + h.until(lambda: h.slices, "a slice") + evidence = h.evidences[0] + self.assertTrue(evidence.can_assert_complete_interval) + self.assertEqual(SessionState.ACQUIRING, evidence.final_state) + self.assertEqual((), evidence.interruptions) + + def test_a_clean_stop_publishes_what_is_pending_and_closes_the_session(self) -> None: + provider = FakeProvider() + config = LiveSessionConfig(slice_seconds=3600, slice_max_trades=1000, buffer_messages=50, tick=0.01, ping_interval=30) + with Harness(provider, config=config) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b", "c")) + time.sleep(0.15) + self.assertEqual([], h.slices) # nothing is due yet + self.assertIsNone(h.error) + (only,) = h.slices + self.assertEqual(["a", "b", "c"], [r.trade_id for r in only.records]) + self.assertEqual(Instant((T0 + 3) * MS), only.window_end) # one millisecond after its greatest trade + self.assertEqual(1, len(h.persisted)) + self.assertEqual(1, provider.closed_sockets) + + +class WallClockTests(unittest.TestCase): + def test_slice_seconds_of_wall_clock_close_a_slice_even_when_no_message_arrives(self) -> None: + provider = FakeProvider() + clock = {"now": 5000.0} + config = LiveSessionConfig( + slice_seconds=300, slice_max_trades=1000, buffer_messages=50, tick=0.01, ping_interval=10_000, pong_timeout=5000.0, + connect_timeout=5000.0) + h = Harness(provider, config=config) + h.engine._ports.clock = lambda: clock["now"] + with h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b")) + provider.push(trade_message(T0 + 5, "c")) + time.sleep(0.15) + self.assertEqual([], h.slices) # 3 trades, far from any bound + clock["now"] += 299.0 + time.sleep(0.1) + self.assertEqual([], h.slices) + clock["now"] += 2.0 # 301 s of wall clock since the window opened + h.until(lambda: h.slices, "the slice closed by the wall clock") + (only, *_) = h.slices + self.assertEqual(["a", "b"], [r.trade_id for r in only.records]) # "c" is the boundary millisecond: it stays + self.assertEqual(Instant((T0 + 5) * MS), only.window_end) + + +class InterruptionTests(unittest.TestCase): + def test_a_disconnect_publishes_what_was_listened_to_then_reconnects_and_reconciles(self) -> None: + provider = FakeProvider() + anchor = record(T0 + 2, "c") + + def reconcile(recent, buffered): + return pass_restart(T0 + 40, [record(T0 + 20, "x"), record(T0 + 30, "y")]) + + with Harness(provider, checkpoint=True, reconcile=reconcile, recent=(anchor,)) as h: + h.until(lambda: provider.sockets and "reconcile" in provider.log, "the first reconciliation") + provider.push(trade_message(T0 + 100, "a", "b", "c")) + provider.push(trade_message(T0 + 110, "d")) + h.until(lambda: len(h.slices) >= 1, "a slice") + provider.close() + h.until(lambda: provider.connects == 2 and len(h.events_named("interruption")) == 1, "the reconnect") + h.until(lambda: h.provider.log.count("reconcile") == 2, "the second reconciliation") + (event,) = h.events_named("interruption") + self.assertEqual(Interruption.DISCONNECT.value, event["reason"]) + self.assertEqual(1, h.summary.reconnects) + # the trades received before the disconnect are all published (the last window closes 1 ms after its greatest trade) + published = sorted(r.trade_id for s in h.slices for r in s.records) + self.assertEqual(["a", "b", "c", "d"], published) + self.assertTrue(all(e.can_assert_complete_interval for e in h.evidences)) # taken before the interruption was recorded + + def test_the_session_subscribes_before_it_fetches_the_recent_trades(self) -> None: + provider = FakeProvider() + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0, [record(T0, "x")])) as h: + h.until(lambda: "reconcile" in provider.log, "the reconciliation") + log = provider.log + self.assertLess(log.index("subscribe"), log.index("fetch_recent")) + self.assertLess(log.index("fetch_recent"), log.index("reconcile")) + + def test_the_buffered_trades_reach_the_reconciliation_and_their_duplicates_are_dropped_afterwards(self) -> None: + provider = FakeProvider() + seen = {} + + def reconcile(recent, buffered): + seen["buffered"] = [r.trade_id for r in buffered] + return pass_restart(T0 + 6, [record(T0 + 1, "p"), record(T0 + 5, "q")]) + + gate = threading.Event() + original = provider.connect + + def connect(url, **kwargs): + socket = original(url, **kwargs) + socket.inbox.put(json.dumps(trade_message(T0 + 5, "q"))) # already delivered before the subscription ack is read + return socket + + provider.connect = connect + config = LiveSessionConfig(slice_seconds=3600, slice_max_trades=1000, buffer_messages=50, tick=0.01, ping_interval=30) + with Harness(provider, config=config, checkpoint=True, reconcile=reconcile) as h: + h.until(lambda: "reconcile" in provider.log, "the reconciliation") + provider.push(trade_message(T0 + 5, "q")) # a duplicate of a reconciled trade + provider.push(trade_message(T0 + 8, "r")) + time.sleep(0.2) + gate.set() + self.assertIn("q", seen["buffered"]) + flushed = [r.trade_id for s in h.slices for r in s.records] + self.assertEqual(["r"], flushed) # "q" was published by the reconciliation, not twice + self.assertEqual(0, h.engine.summary.ordering_violations) + + def test_a_full_buffer_ends_the_session_as_an_interruption_and_publishes_what_was_buffered(self) -> None: + provider = FakeProvider() + gate = threading.Event() + config = LiveSessionConfig( + slice_seconds=3600, slice_max_trades=2, buffer_messages=2, tick=0.01, ping_interval=30, reconnect_delay=0.01, + reconnect_delay_max=0.02) + with Harness(provider, config=config, gate=gate) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b")) # a slice is due, and publishing blocks on the gate + h.until(lambda: "publish" not in provider.log and h.engine.summary.slices_published == 0 and + provider.socket.inbox.empty(), "the publisher to take the first message") + time.sleep(0.05) + for k in range(6): # the publisher is busy: the reader fills the buffer of 2 and must stop + provider.push(trade_message(T0 + 10 + k, f"m{k}")) + h.until(lambda: provider.closed_sockets >= 1, "the reader to end the session") + gate.set() + h.until(lambda: h.events_named("interruption"), "the interruption") + (event, *_) = h.events_named("interruption") + self.assertEqual(Interruption.BUFFER_OVERFLOW.value, event["reason"]) + self.assertEqual(2, event["buffer_high_water"]) + self.assertEqual(2, event["buffer_capacity"]) + self.assertGreaterEqual(h.summary.interruptions.get("buffer_overflow", 0), 1) + buffered = {r.trade_id for s in h.slices for r in s.records} + self.assertTrue({"a", "b", "m0", "m1"} <= buffered) # what had been buffered is published, none of it silently dropped + + def test_a_missing_pong_is_a_heartbeat_timeout_and_an_idle_instrument_with_pongs_is_not(self) -> None: + config = LiveSessionConfig( + slice_seconds=3600, slice_max_trades=10, buffer_messages=50, tick=0.01, ping_interval=0.05, pong_timeout=0.1, + reconnect_delay=0.01, reconnect_delay_max=0.02) + quiet = FakeProvider() # answers every ping, sends no trade: an idle instrument + with Harness(quiet, config=config) as h: + h.until(lambda: quiet.log.count("ping") >= 3, "three pings") + self.assertEqual([], h.events_named("interruption")) + self.assertEqual(1, quiet.connects) + dead = FakeProvider() + dead.pong = False + with Harness(dead, config=config) as h: + h.until(lambda: h.events_named("interruption"), "the heartbeat timeout") + self.assertEqual(Interruption.HEARTBEAT_TIMEOUT.value, h.events_named("interruption")[0]["reason"]) + + def test_a_trade_below_the_open_window_is_an_ordering_violation_counted_and_never_accepted(self) -> None: + provider = FakeProvider() + with Harness(provider) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b")) + provider.push(trade_message(T0 + 10, "c", "d")) # 4 trades: a slice closes, the window now starts at T0 + 10 + h.until(lambda: h.slices, "a slice") + provider.push(trade_message(T0 + 3, "late")) + h.until(lambda: h.events_named("interruption"), "the interruption") + self.assertEqual(Interruption.ORDERING_VIOLATION.value, h.events_named("interruption")[0]["reason"]) + self.assertEqual(1, h.summary.ordering_violations) + self.assertNotIn("late", [r.trade_id for s in h.slices for r in s.records]) + + def test_a_refused_connection_is_retried_with_a_bounded_backoff(self) -> None: + provider = FakeProvider() + provider.fail_connects = 3 + with Harness(provider) as h: + h.until(lambda: provider.sockets, "the connection after the refusals") + self.assertEqual(4, provider.connects) + reasons = [e["reason"] for e in h.events_named("interruption")] + self.assertEqual([Interruption.DISCONNECT.value] * 3, reasons[:3]) + self.assertTrue(all(delay <= h.config.reconnect_delay_max for delay in h.sleeps)) + self.assertGreater(max(h.sleeps), h.config.reconnect_delay) # it grows after a refusal, up to the bound + self.assertEqual(1, len(provider.sockets)) + + def test_a_message_that_cannot_be_canonicalized_stops_the_loop_after_publishing_what_was_valid(self) -> None: + provider = FakeProvider() + with Harness(provider) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b")) + provider.push(trade_message(T0 + 5, "x", instrument="BTCUSDT") | {"topic": f"publicTrade.{INSTRUMENT}"}) + h.thread.join(5) + self.assertIsInstance(h.error, LiveSessionFailure) + self.assertEqual(["a", "b"], [r.trade_id for s in h.slices for r in s.records]) + + +class ReconciliationTests(unittest.TestCase): + def test_a_resumed_reconciliation_chains_the_next_slice_to_what_it_published(self) -> None: + provider = FakeProvider() + end = T0 + 51 + accepted = [record(T0 + 50, "last")] + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(end, accepted)) as h: + h.until(lambda: "reconcile" in provider.log, "the reconciliation") + provider.push(trade_message(end, "n1", "n2", "n3")) + h.until(lambda: h.slices, "a slice") + self.assertEqual(Instant(end * MS), h.slices[0].window_start) + self.assertEqual(Instant(end * MS), h.chain_starts[0]) + self.assertEqual(1, h.summary.reconciliations) + + def test_a_reconciliation_with_nothing_new_continues_from_the_floor(self) -> None: + provider = FakeProvider() + floor = Instant((T0 + 9) * MS) + pending = SimpleNamespace(status="REAL_RESTART_PROOF_PENDING") + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pending, floor=floor, + last_key=(Instant((T0 + 8) * MS), "k")) as h: + h.until(lambda: "reconcile" in provider.log, "the reconciliation") + provider.push(trade_message(T0 + 8, "dup")) # at or before the last durable key: a duplicate + provider.push(trade_message(T0 + 9, "n1", "n2", "n3")) + h.until(lambda: h.slices, "a slice") + self.assertEqual(floor, h.slices[0].window_start) + self.assertNotIn("dup", [r.trade_id for r in h.slices[0].records]) + self.assertEqual((0, []), (h.summary.ordering_violations, h.events_named("interruption"))) # a duplicate is not a violation + + def test_an_unresolved_gap_is_recorded_and_a_new_chain_starts_without_claiming_the_gap(self) -> None: + provider = FakeProvider() + gap = SimpleNamespace( + status="GAP_DETECTED", restart_outcome=SimpleNamespace(reconcile_result=SimpleNamespace(evidence={"reason": "anchor absent"}))) + with Harness(provider, checkpoint=True, reconcile=lambda r, b: gap) as h: + h.until(lambda: "reconcile" in provider.log, "the reconciliation") + provider.push(trade_message(T0 + 500, "n1", "n2", "n3")) + h.until(lambda: h.slices, "a slice") + self.assertEqual(1, len(h.gaps)) + self.assertEqual(Instant((T0 + 500) * MS), h.slices[0].window_start) # a new chain at its first trade + self.assertIsNone(h.chain_starts[0]) # nothing is chained across the gap + self.assertEqual(1, h.summary.gaps) + self.assertEqual("anchor absent", h.events_named("gap")[0]["reason"]) + + def test_the_chain_of_an_earlier_session_is_not_carried_over_a_gap(self) -> None: + provider = FakeProvider() + gap = SimpleNamespace( + status="GAP_DETECTED", restart_outcome=SimpleNamespace(reconcile_result=SimpleNamespace(evidence={"reason": "anchor absent"}))) + with Harness(provider, reconcile=lambda r, b: gap) as h: + h.until(lambda: provider.sockets, "the first connection") + provider.push(trade_message(T0, "a", "b", "c")) + h.until(lambda: h.slices, "a slice of the first session") + h.checkpoint = True # a checkpoint exists from now on: the next session reconciles + provider.close() + h.until(lambda: provider.connects == 2 and "reconcile" in provider.log, "the reconciliation of the second session") + provider.push(trade_message(T0 + 5000, "n1", "n2", "n3")) + h.until(lambda: any(sl.window_start == Instant((T0 + 5000) * MS) for sl in h.slices), "a slice after the gap") + after = [i for i, sl in enumerate(h.slices) if sl.window_start == Instant((T0 + 5000) * MS)][0] + self.assertGreater(after, 0) # the first session published before the gap + self.assertIsNone(h.chain_starts[after]) # nothing is chained across the gap + self.assertEqual([], h.events_named("unclaimed_span")) # the gap is the explanation, not an idle midnight + + def test_a_reconciliation_that_fails_stops_the_loop(self) -> None: + provider = FakeProvider() + with Harness(provider, checkpoint=True, reconcile=lambda r, b: SimpleNamespace(status="CERTIFICATION_FAILED")) as h: + h.thread.join(5) + self.assertIsInstance(h.error, LiveSessionFailure) + self.assertEqual([], h.slices) + + def test_with_no_checkpoint_there_is_nothing_to_reconcile(self) -> None: + provider = FakeProvider() + with Harness(provider, checkpoint=False) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b", "c")) + h.until(lambda: h.slices, "a slice") + self.assertNotIn("reconcile", provider.log) + self.assertNotIn("fetch_recent", provider.log) + + +class PublicationTests(unittest.TestCase): + def test_a_failed_publication_stops_the_loop_and_the_checkpoint_never_advances(self) -> None: + provider = FakeProvider() + with Harness(provider, publish_status="CERTIFICATION_FAILED") as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b", "c")) + h.thread.join(5) + self.assertIsInstance(h.error, LiveSessionFailure) + self.assertEqual([], h.persisted) + + def test_a_window_that_moved_past_an_idle_midnight_is_reported_not_chained(self) -> None: + provider = FakeProvider() + midnight = int(Instant.parse("2026-10-22T00:00:00Z").epoch_ns // MS) + floor = Instant((midnight - 5000) * MS) + pending = SimpleNamespace(status="REAL_RESTART_PROOF_PENDING") + config = LiveSessionConfig(slice_seconds=3600, slice_max_trades=3, buffer_messages=50, tick=0.01, ping_interval=30) + with Harness(provider, config=config, checkpoint=True, reconcile=lambda r, b: pending, floor=floor) as h: + h.until(lambda: "reconcile" in provider.log, "the reconciliation") + provider.push(trade_message(midnight + 1000, "n1", "n2", "n3")) + h.until(lambda: h.slices, "a slice") + self.assertEqual(Instant(midnight * MS), h.slices[0].window_start) + self.assertIsNone(h.chain_starts[0]) + self.assertEqual(1, len(h.events_named("unclaimed_span"))) + + def test_the_signal_fields_of_a_published_slice(self) -> None: + provider = FakeProvider() + with Harness(provider) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b", "c")) + h.until(lambda: h.events_named("slice_published"), "a slice") + (event, *_) = h.events_named("slice_published") + self.assertEqual(2, event["trades"]) # the third trade is the boundary millisecond: it stays for the next slice + self.assertEqual(50, event["buffer_capacity"]) + self.assertGreaterEqual(event["slice_lag_ms"], 0) + self.assertIsInstance(event["slice_lag_ms"], int) + for name in ("reconnects", "ordering_violations", "buffer_high_water", "partition_key", "window_end"): + self.assertIn(name, event) + + +class ConfigTests(unittest.TestCase): + def test_bad_configuration_is_refused(self) -> None: + for kwargs in ( + {"slice_seconds": 0}, {"slice_max_trades": -1}, {"buffer_messages": True}, {"recent_limit": 1001}, + {"ping_interval": 0}, {"tick": -1.0}, {"reconnect_delay": 5.0, "reconnect_delay_max": 1.0}, + ): + with self.subTest(kwargs=kwargs), self.assertRaises(ValueError): + LiveSessionConfig(**kwargs) + + def test_the_accepted_defaults(self) -> None: + config = LiveSessionConfig() + self.assertEqual((300, 50_000, 20_000, 1000), (config.slice_seconds, config.slice_max_trades, config.buffer_messages, config.recent_limit)) + + def test_an_instrument_outside_the_allow_list_is_refused(self) -> None: + with self.assertRaises(Exception): + LiveSessionEngine(instrument="ADAUSDT", config=LiveSessionConfig(), ports=SimpleNamespace()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_package_boundaries_v1.py b/tests/test_package_boundaries_v1.py index 1ba789c..150bb5b 100644 --- a/tests/test_package_boundaries_v1.py +++ b/tests/test_package_boundaries_v1.py @@ -92,6 +92,7 @@ "quant_platform.source_adapters.bybit_archive": "source", "quant_platform.source_adapters.bybit_live": "source", "quant_platform.source_adapters.bybit_live_slices": "source", + "quant_platform.source_adapters.bybit_live_assembler": "source", "quant_platform.source_adapters.bybit_l2": "source", "quant_platform.source_adapters.bybit_l2_archive": "source", "quant_platform.source_adapters.l2": "source", @@ -126,6 +127,7 @@ "quant_platform.application.live_candle_stream": "application", "quant_platform.application.live_gap_orchestration": "application", "quant_platform.application.live_ingest_server": "application", + "quant_platform.application.live_session": "application", "quant_platform.application.market_data": "application", "quant_platform.application.bybit_l2_day_evidence": "application", "quant_platform.application.bybit_l2_day_ingest": "application", From 1cda445b8befd262aa1e4dbf15515d68f8e8a753 Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:07:47 +0200 Subject: [PATCH 06/13] fix(data): O02 continuity needs an overlap, bounded heartbeat history, live buffer high-water (#523) Review of #524: - P1: the session no longer reconciles on an empty buffer. It waits for the first trade of the subscription, takes the recent-trades snapshot after it and hands it to the reconciliation, so the existing seam requires a key in both; otherwise the interval is an explicit gap. Only the anchor and the keys the reconciliation accepted are duplicates afterwards (skip_keys). - P2: pongs are counted, not appended to the tracker, so the history is the session states only. - P2: the buffer high-water is refreshed from the live reader at every publication. Tests: continuity proof, bounded history, high-water, never-acknowledged subscription, stale REST window (integration phase 6); mutation round 0 survivors. Co-Authored-By: Claude Sonnet 5.5 --- .../application/live_session.py | 46 ++++++-- .../source_adapters/bybit_live_assembler.py | 15 ++- tests/integration_live_session_postgres.py | 70 ++++++++--- tests/test_live_assembler_v1.py | 9 ++ tests/test_live_session_v1.py | 110 ++++++++++++++++-- 5 files changed, 218 insertions(+), 32 deletions(-) diff --git a/src/quant_platform/application/live_session.py b/src/quant_platform/application/live_session.py index 4764fd5..d13ab4b 100644 --- a/src/quant_platform/application/live_session.py +++ b/src/quant_platform/application/live_session.py @@ -140,6 +140,7 @@ def __init__( self.detail = "" self.error: BaseException | None = None self.high_water = 0 + self.pongs = 0 def run(self) -> None: try: @@ -180,8 +181,9 @@ async def _read(self) -> None: self.subscribed.set() continue if op in {"ping", "pong"}: - with self._lock: - self._tracker.heartbeat(conn_id=document.get("conn_id")) + # 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: @@ -221,6 +223,8 @@ def __init__( 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 @@ -264,6 +268,7 @@ def _session(self, stop_requested: Callable[[], bool]) -> Interruption | 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) @@ -272,7 +277,12 @@ def _session(self, stop_requested: Callable[[], bool]) -> Interruption | None: reason = reader.interruption or Interruption.DISCONNECT failure = reader.error else: - staged = self._reconcile(reader, buffer, assembler) + 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: @@ -356,8 +366,17 @@ def _drain_available(self, buffer: "queue.Queue[LiveTradeBatch]") -> list[LiveTr except queue.Empty: return drained - def _reconcile(self, reader: _Reader, buffer: "queue.Queue[LiveTradeBatch]", assembler: SliceAssembler) -> list[LiveTradeBatch]: - """Subscribed first, then the recent trades (ADR-0042 section 5): the overlap of the two is the continuity proof.""" + 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) @@ -365,23 +384,34 @@ def _reconcile(self, reader: _Reader, buffer: "queue.Queue[LiveTradeBatch]", ass assembler.start_window(None) self._chain_end = None return staged + while not staged: + if stop_requested() or reader.finished.is_set(): + return None + try: + staged.append(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=bybit_trade_v1_ordering_key(accepted[-1])) + 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() - assembler.start_window(floor, skip_through=ports.last_durable_key()) + 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()) @@ -417,6 +447,8 @@ def _evidence(self, tracker: LiveSessionTracker) -> BybitLiveSessionEvidence: 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 diff --git a/src/quant_platform/source_adapters/bybit_live_assembler.py b/src/quant_platform/source_adapters/bybit_live_assembler.py index 7a70198..b474fb2 100644 --- a/src/quant_platform/source_adapters/bybit_live_assembler.py +++ b/src/quant_platform/source_adapters/bybit_live_assembler.py @@ -39,6 +39,7 @@ def __init__( slice_seconds: int = SLICE_SECONDS_DEFAULT, window_start: Instant | None = None, skip_through: Key | None = None, + skip_keys: Iterable[Key] = (), clock: Callable[[], float] = time.monotonic, ) -> None: if not isinstance(max_trades, int) or isinstance(max_trades, bool) or max_trades < 1: @@ -50,6 +51,7 @@ def __init__( self._clock = clock self._window_start_ns: int | None = None if window_start is None else window_start.epoch_ns self._skip_through = skip_through + self._skip_keys = frozenset(skip_keys) self._pending: dict[Key, TradeRecord] = {} self._opened_at: float | None = None self.ordering_violations = 0 @@ -63,13 +65,20 @@ def window_start(self) -> Instant | None: def pending_count(self) -> int: return len(self._pending) - def start_window(self, start: Instant | None, *, skip_through: Key | None = None) -> None: - """A new chain after a reconciliation (``start`` = what it published up to) or after an explicit gap (``None``).""" + def start_window( + self, start: Instant | None, *, skip_through: Key | None = None, skip_keys: Iterable[Key] = (), + ) -> None: + """A new chain after a reconciliation (``start`` = what it published up to) or after an explicit gap (``None``). + + The duplicates of what is already published are the keys at or before ``skip_through`` (the last durable key before the + reconciliation) and the keys the reconciliation itself accepted (``skip_keys``): a trade the reconciliation never saw is not + a duplicate of anything, however low its key, and is judged like any other.""" if self._pending: raise LiveSliceError("a window cannot be restarted while records are pending") self._window_start_ns = None if start is None else start.epoch_ns self._skip_through = skip_through + self._skip_keys = frozenset(skip_keys) self._opened_at = None def add(self, records: Iterable[TradeRecord]) -> int: @@ -81,7 +90,7 @@ def add(self, records: Iterable[TradeRecord]) -> int: if record.exchange_ts.epoch_ns % _NS_PER_MS: raise LiveSliceError(f"record exchange_ts must be a whole millisecond: {record.exchange_ts.isoformat()}") key = bybit_trade_v1_ordering_key(record) - if self._skip_through is not None and key <= self._skip_through: + if (self._skip_through is not None and key <= self._skip_through) or key in self._skip_keys: self.duplicates_skipped += 1 continue if self._window_start_ns is not None and record.exchange_ts.epoch_ns < self._window_start_ns: diff --git a/tests/integration_live_session_postgres.py b/tests/integration_live_session_postgres.py index a29e1ab..449e697 100644 --- a/tests/integration_live_session_postgres.py +++ b/tests/integration_live_session_postgres.py @@ -180,15 +180,7 @@ def main() -> int: provider = FakeProvider() delivered: set[str] = set() # the trades the platform has published or must publish (the session saw them or the REST proved them) - arrival_while_reconciling = {"armed": False} - def recent(*, limit, instrument="BTCUSDT"): - if arrival_while_reconciling["armed"]: - # trades that arrive while the session reconciles: in the REST window AND over the new socket (the overlap proof) - arrival_while_reconciling["armed"] = False - rows_ = world.make(4) - provider.push(world.message(rows_)) - delivered.update(r["i"] for r in rows_) return tuple(world.trades[-limit:]) with mock.patch.object(app, "fetch_recent_public_trades", recent), websockets_stub(provider): @@ -219,9 +211,13 @@ def recent(*, limit, instrument="BTCUSDT"): before = len(slices(connection)) missed = world.make(6) # delivered nowhere over the WebSocket: the provider closes the connection first delivered.update(r["i"] for r in missed) - arrival_while_reconciling["armed"] = True provider.close() - run.until(lambda: provider.connects == 2, "the reconnect") + run.until(lambda: provider.connects == 2 and len(provider.sockets) == 2, "the reconnect") + # the first trades of the new subscription: they are in the REST window too (taken after them), the overlap that proves + # continuity; until a trade arrives the session waits and reconciles nothing + arrival = world.make(4) + provider.push(world.message(arrival)) + delivered.update(r["i"] for r in arrival) run.until(lambda: run.health("reconcile"), "the reconciliation") more = world.make(5) provider.push(world.message(more)) @@ -255,6 +251,9 @@ def recent_after_outage(*, limit, instrument="BTCUSDT"): with mock.patch.object(app, "fetch_recent_public_trades", recent_after_outage), websockets_stub(provider2): run.start() run.until(lambda: provider2.sockets, "the connection after the outage") + first_after = world.make(2) # the first trades of the subscription: below every bound, nothing is published yet + provider2.push(world.message(first_after)) + delivered.update(r["i"] for r in first_after) run.until(lambda: run.health("reconcile") and any("anchor" in str(h.get("reason", "")) or "last durable" in str(h.get("reason", "")) for h in run.health("reconcile")), "the gap") assert CheckpointStore(checkpoint).load().generation == generation, "the checkpoint moved across a gap" assert load_open_long_gap_records(storage_root=storage, instrument=INSTRUMENT).records, "the gap was not recorded" @@ -292,8 +291,12 @@ def recent_all(*, limit, instrument="BTCUSDT"): with mock.patch.object(app, "fetch_recent_public_trades", recent_all), \ mock.patch.object(app, "persist_publication_checkpoint", failing_persist), websockets_stub(provider3): crash.start() - crash.until(lambda: provider3.sockets and crash.health("reconcile"), "the reconciliation") - for _ in range(4): + crash.until(lambda: provider3.sockets, "the connection") + rows_ = world.make(3) + provider3.push(world.message(rows_)) # the first trade of the subscription: the reconciliation follows it + delivered.update(r["i"] for r in rows_) + crash.until(lambda: crash.health("reconcile"), "the reconciliation") + for _ in range(5): rows_ = world.make(5) provider3.push(world.message(rows_)) delivered.update(r["i"] for r in rows_) @@ -308,7 +311,11 @@ def recent_all(*, limit, instrument="BTCUSDT"): restart = Run(dsn, storage, checkpoint, provider4) with mock.patch.object(app, "fetch_recent_public_trades", recent_all), websockets_stub(provider4): restart.start() - restart.until(lambda: provider4.sockets and (restart.health("reconcile") or restart.health("slice")), "the replay") + restart.until(lambda: provider4.sockets, "the connection") + rows_ = world.make(2) + provider4.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + restart.until(lambda: restart.health("reconcile") or restart.health("slice"), "the replay") more = world.make(4) provider4.push(world.message(more)) delivered.update(r["i"] for r in more) @@ -321,7 +328,11 @@ def recent_all(*, limit, instrument="BTCUSDT"): late = Run(dsn, storage, checkpoint, provider5) with mock.patch.object(app, "fetch_recent_public_trades", recent_all), websockets_stub(provider5): late.start() - late.until(lambda: provider5.sockets and late.health("reconcile"), "the reconciliation") + late.until(lambda: provider5.sockets, "the connection") + rows_ = world.make(2) + provider5.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + late.until(lambda: late.health("reconcile"), "the reconciliation") rows_ = world.make(5) provider5.push(world.message(rows_)) delivered.update(r["i"] for r in rows_) @@ -338,6 +349,37 @@ def recent_all(*, limit, instrument="BTCUSDT"): assert late.health("interruption")[0]["ordering_violations"] == 1 check_catalog(connection, delivered) # "t-late" was never published + # 6. A recent-trades window that still holds the anchor but is behind the subscription proves nothing: the trades of the + # interval nobody listened to are missing from both. The first trades of the subscription do not meet the window, so + # the interval is an explicit gap, never "continuity restored"; the trades in between are not claimed. + stale = tuple(world.trades) # holds the anchor (the last trade ever published), nothing newer + world.make(3) # delivered nowhere: the unlistened interval + provider6 = FakeProvider() + behind = Run(dsn, storage, checkpoint, provider6) + before_gaps = len(load_open_long_gap_records(storage_root=storage, instrument=INSTRUMENT).records) + generation = CheckpointStore(checkpoint).load().generation + + def recent_stale(*, limit, instrument="BTCUSDT"): + return stale + + with mock.patch.object(app, "fetch_recent_public_trades", recent_stale), websockets_stub(provider6): + behind.start() + behind.until(lambda: provider6.sockets, "the connection") + rows_ = world.make(2) + provider6.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + behind.until(lambda: behind.health("reconcile"), "the gap") + assert any("last durable" in str(h.get("reason", "")) or "overlap" in str(h.get("reason", "")) + for h in behind.health("reconcile")), behind.health("reconcile") + assert CheckpointStore(checkpoint).load().generation == generation, "the checkpoint moved across an unproven interval" + assert len(load_open_long_gap_records(storage_root=storage, instrument=INSTRUMENT).records) == before_gaps + 1 + rows_ = world.make(8) + provider6.push(world.message(rows_)) + delivered.update(r["i"] for r in rows_) + time.sleep(0.4) + behind.finish() + found = check_catalog(connection, delivered) # the three unlistened trades are not in it: nothing was claimed for them + assert [r[0] for r in rows(connection, "SELECT instrument FROM catalog.datasets ORDER BY 1")] == [INSTRUMENT] print("POSTGRESQL LIVE SESSION GATE PASSED") return 0 diff --git a/tests/test_live_assembler_v1.py b/tests/test_live_assembler_v1.py index ac43d81..4770e5d 100644 --- a/tests/test_live_assembler_v1.py +++ b/tests/test_live_assembler_v1.py @@ -144,6 +144,15 @@ def test_trades_at_or_before_the_skip_key_are_duplicates_of_what_is_already_publ a.add([trade(D0 + 5, "m"), trade(D0 + 4, "z"), trade(D0 + 6, "n")]) self.assertEqual((2, 0, 1), (a.duplicates_skipped, a.ordering_violations, a.pending_count)) + def test_only_the_keys_a_reconciliation_accepted_are_duplicates_not_every_key_below_the_last_of_them(self) -> None: + a = self.assembler() + a.start_window(Instant((D0 + 6) * MS), skip_through=(Instant((D0 + 2) * MS), "a"), skip_keys=[(Instant((D0 + 5) * MS), "m")]) + # "m" was accepted by the reconciliation; "k" (below its last key, never seen) is a trade like any other: it is late + violations = a.add([trade(D0 + 5, "m"), trade(D0 + 4, "k"), trade(D0 + 2, "a"), trade(D0 + 7, "n")]) + self.assertEqual(2, a.duplicates_skipped) # "m" by key, "a" by the anchor + self.assertEqual(1, violations) # "k" + self.assertEqual(1, a.pending_count) # "n" + def test_flush_closes_one_millisecond_after_the_greatest_trade_and_ends_the_chain(self) -> None: a = self.assembler() a.add([trade(D0, "a"), trade(D0 + 7, "b"), trade(D0 + 7, "c")]) diff --git a/tests/test_live_session_v1.py b/tests/test_live_session_v1.py index 2450be4..38be46b 100644 --- a/tests/test_live_session_v1.py +++ b/tests/test_live_session_v1.py @@ -315,24 +315,29 @@ def reconcile(recent, buffered): return pass_restart(T0 + 40, [record(T0 + 20, "x"), record(T0 + 30, "y")]) with Harness(provider, checkpoint=True, reconcile=reconcile, recent=(anchor,)) as h: - h.until(lambda: provider.sockets and "reconcile" in provider.log, "the first reconciliation") - provider.push(trade_message(T0 + 100, "a", "b", "c")) + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0 + 100, "a", "b", "c")) # the first trade of the subscription: the reconciliation follows it + h.until(lambda: "reconcile" in provider.log, "the first reconciliation") provider.push(trade_message(T0 + 110, "d")) h.until(lambda: len(h.slices) >= 1, "a slice") provider.close() h.until(lambda: provider.connects == 2 and len(h.events_named("interruption")) == 1, "the reconnect") + provider.push(trade_message(T0 + 200, "e")) # the second subscription's first trade h.until(lambda: h.provider.log.count("reconcile") == 2, "the second reconciliation") (event,) = h.events_named("interruption") self.assertEqual(Interruption.DISCONNECT.value, event["reason"]) self.assertEqual(1, h.summary.reconnects) # the trades received before the disconnect are all published (the last window closes 1 ms after its greatest trade) published = sorted(r.trade_id for s in h.slices for r in s.records) - self.assertEqual(["a", "b", "c", "d"], published) + self.assertEqual(["a", "b", "c", "d", "e"], published) self.assertTrue(all(e.can_assert_complete_interval for e in h.evidences)) # taken before the interruption was recorded def test_the_session_subscribes_before_it_fetches_the_recent_trades(self) -> None: provider = FakeProvider() with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0, [record(T0, "x")])) as h: + h.until(lambda: provider.sockets, "the connection") + self.assertNotIn("fetch_recent", provider.log) # nothing is fetched before a trade of this subscription arrives + provider.push(trade_message(T0 + 3, "a")) h.until(lambda: "reconcile" in provider.log, "the reconciliation") log = provider.log self.assertLess(log.index("subscribe"), log.index("fetch_recent")) @@ -449,21 +454,34 @@ def test_a_resumed_reconciliation_chains_the_next_slice_to_what_it_published(sel end = T0 + 51 accepted = [record(T0 + 50, "last")] with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(end, accepted)) as h: - h.until(lambda: "reconcile" in provider.log, "the reconciliation") + h.until(lambda: provider.sockets, "the connection") provider.push(trade_message(end, "n1", "n2", "n3")) + h.until(lambda: "reconcile" in provider.log, "the reconciliation") h.until(lambda: h.slices, "a slice") self.assertEqual(Instant(end * MS), h.slices[0].window_start) self.assertEqual(Instant(end * MS), h.chain_starts[0]) self.assertEqual(1, h.summary.reconciliations) + def test_a_buffered_trade_at_or_before_the_last_durable_key_is_a_duplicate_not_a_violation(self) -> None: + provider = FakeProvider() + end = T0 + 51 + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(end, [record(T0 + 60, "new")]), + last_key=(Instant((T0 + 50) * MS), "anchor")) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0 + 48, "old1", "old2")) # T0 + 48 and T0 + 49: already durable, the anchor is T0 + 50 + h.until(lambda: "reconcile" in provider.log, "the reconciliation") + time.sleep(0.2) + self.assertEqual((0, []), (h.summary.ordering_violations, h.events_named("interruption"))) + def test_a_reconciliation_with_nothing_new_continues_from_the_floor(self) -> None: provider = FakeProvider() floor = Instant((T0 + 9) * MS) pending = SimpleNamespace(status="REAL_RESTART_PROOF_PENDING") with Harness(provider, checkpoint=True, reconcile=lambda r, b: pending, floor=floor, last_key=(Instant((T0 + 8) * MS), "k")) as h: - h.until(lambda: "reconcile" in provider.log, "the reconciliation") + h.until(lambda: provider.sockets, "the connection") provider.push(trade_message(T0 + 8, "dup")) # at or before the last durable key: a duplicate + h.until(lambda: "reconcile" in provider.log, "the reconciliation") provider.push(trade_message(T0 + 9, "n1", "n2", "n3")) h.until(lambda: h.slices, "a slice") self.assertEqual(floor, h.slices[0].window_start) @@ -475,8 +493,9 @@ def test_an_unresolved_gap_is_recorded_and_a_new_chain_starts_without_claiming_t gap = SimpleNamespace( status="GAP_DETECTED", restart_outcome=SimpleNamespace(reconcile_result=SimpleNamespace(evidence={"reason": "anchor absent"}))) with Harness(provider, checkpoint=True, reconcile=lambda r, b: gap) as h: - h.until(lambda: "reconcile" in provider.log, "the reconciliation") + h.until(lambda: provider.sockets, "the connection") provider.push(trade_message(T0 + 500, "n1", "n2", "n3")) + h.until(lambda: "reconcile" in provider.log, "the reconciliation") h.until(lambda: h.slices, "a slice") self.assertEqual(1, len(h.gaps)) self.assertEqual(Instant((T0 + 500) * MS), h.slices[0].window_start) # a new chain at its first trade @@ -494,8 +513,9 @@ def test_the_chain_of_an_earlier_session_is_not_carried_over_a_gap(self) -> None h.until(lambda: h.slices, "a slice of the first session") h.checkpoint = True # a checkpoint exists from now on: the next session reconciles provider.close() - h.until(lambda: provider.connects == 2 and "reconcile" in provider.log, "the reconciliation of the second session") + h.until(lambda: provider.connects == 2 and len(provider.sockets) == 2, "the second connection") provider.push(trade_message(T0 + 5000, "n1", "n2", "n3")) + h.until(lambda: "reconcile" in provider.log, "the reconciliation of the second session") h.until(lambda: any(sl.window_start == Instant((T0 + 5000) * MS) for sl in h.slices), "a slice after the gap") after = [i for i, sl in enumerate(h.slices) if sl.window_start == Instant((T0 + 5000) * MS)][0] self.assertGreater(after, 0) # the first session published before the gap @@ -505,6 +525,8 @@ def test_the_chain_of_an_earlier_session_is_not_carried_over_a_gap(self) -> None def test_a_reconciliation_that_fails_stops_the_loop(self) -> None: provider = FakeProvider() with Harness(provider, checkpoint=True, reconcile=lambda r, b: SimpleNamespace(status="CERTIFICATION_FAILED")) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a")) h.thread.join(5) self.assertIsInstance(h.error, LiveSessionFailure) self.assertEqual([], h.slices) @@ -536,8 +558,9 @@ def test_a_window_that_moved_past_an_idle_midnight_is_reported_not_chained(self) pending = SimpleNamespace(status="REAL_RESTART_PROOF_PENDING") config = LiveSessionConfig(slice_seconds=3600, slice_max_trades=3, buffer_messages=50, tick=0.01, ping_interval=30) with Harness(provider, config=config, checkpoint=True, reconcile=lambda r, b: pending, floor=floor) as h: - h.until(lambda: "reconcile" in provider.log, "the reconciliation") + h.until(lambda: provider.sockets, "the connection") provider.push(trade_message(midnight + 1000, "n1", "n2", "n3")) + h.until(lambda: "reconcile" in provider.log, "the reconciliation") h.until(lambda: h.slices, "a slice") self.assertEqual(Instant(midnight * MS), h.slices[0].window_start) self.assertIsNone(h.chain_starts[0]) @@ -558,6 +581,77 @@ def test_the_signal_fields_of_a_published_slice(self) -> None: self.assertIn(name, event) +class ContinuityProofTests(unittest.TestCase): + """ADR-0042 section 5: the recent trades prove continuity only when they meet the trades of the subscription.""" + + def test_an_idle_subscription_neither_fetches_nor_reconciles_until_a_trade_arrives(self) -> None: + provider = FakeProvider() + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0, [record(T0, "x")])) as h: + h.until(lambda: provider.sockets, "the connection") + time.sleep(0.3) + self.assertNotIn("fetch_recent", provider.log) + self.assertNotIn("reconcile", provider.log) + self.assertEqual([], h.events_named("reconciled")) # an empty buffer is never read as continuity restored + self.assertIsNone(h.error) + + def test_the_snapshot_is_taken_after_the_first_trade_and_the_reconciliation_receives_it(self) -> None: + provider = FakeProvider() + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0 + 2, [record(T0 + 1, "x")])) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0 + 5, "w1", "w2")) + h.until(lambda: h.reconciled, "the reconciliation") + recent, buffered = h.reconciled[0] + self.assertEqual(["w1", "w2"], [r.trade_id for r in buffered]) # never an empty buffer + log = provider.log + self.assertLess(log.index("subscribe"), log.index("fetch_recent")) + + def test_a_session_that_ends_before_any_trade_reconciles_nothing_and_is_an_interruption(self) -> None: + provider = FakeProvider() + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0, [record(T0, "x")])) as h: + h.until(lambda: provider.sockets, "the connection") + provider.close() + h.until(lambda: h.events_named("interruption"), "the interruption") + self.assertEqual("disconnect", h.events_named("interruption")[0]["reason"]) + self.assertNotIn("reconcile", provider.log) + self.assertNotIn("fetch_recent", provider.log) + + + def test_a_subscription_that_is_never_acknowledged_ends_the_session_instead_of_waiting_for_a_trade(self) -> None: + provider = FakeProvider() + provider.acknowledge = False + config = LiveSessionConfig( + slice_seconds=3600, slice_max_trades=3, buffer_messages=50, ping_interval=30.0, pong_timeout=5.0, + connect_timeout=0.2, reconnect_delay=5.0, reconnect_delay_max=5.0, tick=0.01) + with Harness(provider, config=config, checkpoint=True, + reconcile=lambda r, b: pass_restart(T0, [record(T0, "x")])) as h: + h.until(lambda: h.events_named("interruption"), "the interruption after the connect timeout") + self.assertNotIn("reconcile", provider.log) + + +class BoundedMemoryAndPressureTests(unittest.TestCase): + def test_a_long_session_does_not_accumulate_heartbeat_history(self) -> None: + provider = FakeProvider() + config = LiveSessionConfig( + slice_seconds=3600, slice_max_trades=3, buffer_messages=50, tick=0.005, ping_interval=0.005, pong_timeout=5.0, + connect_timeout=5.0) + with Harness(provider, config=config) as h: + h.until(lambda: provider.sockets, "the connection") + h.until(lambda: provider.log.count("ping") >= 120, "a hundred and twenty pings and their pongs") + self.assertLessEqual(len(h.engine.tracker._events), 6) # the states of the session, not one event per pong + self.assertEqual(1, provider.connects) + + def test_the_high_water_mark_is_reported_while_the_first_session_is_still_open(self) -> None: + provider = FakeProvider() + with Harness(provider) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push(trade_message(T0, "a", "b")) + provider.push(trade_message(T0 + 10, "c", "d")) + h.until(lambda: h.events_named("slice_published"), "a slice") + (event, *_) = h.events_named("slice_published") + self.assertGreater(event["buffer_high_water"], 0) # the session has not ended + self.assertEqual(0, provider.closed_sockets) + + class ConfigTests(unittest.TestCase): def test_bad_configuration_is_refused(self) -> None: for kwargs in ( From 3666dd4cbf5e160d02042bab2fdbf4d39c70cded Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:28:20 +0100 Subject: [PATCH 07/13] fix(data): O02 reconciliation waits for a trade, not for a frame (#523) Second review of #524: an empty topic snapshot (data=[]) is admitted by the canonical entry and returned a batch with no records, which unlocked the wait with an empty buffered set, so the reconciliation again required no WS/REST overlap. The wait now requires at least one record of the subscription; a frame with no trade is ignored until one arrives. Tests: unit (empty snapshot, then the first real trade; fails on the previous wait) and PostgreSQL phase 6 (an empty frame before the trades unlocks nothing; the stale-REST gap is still recorded). Co-Authored-By: Claude Sonnet 5.5 --- src/quant_platform/application/live_session.py | 2 +- tests/integration_live_session_postgres.py | 5 +++++ tests/test_live_session_v1.py | 12 ++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/quant_platform/application/live_session.py b/src/quant_platform/application/live_session.py index d13ab4b..ff2be1e 100644 --- a/src/quant_platform/application/live_session.py +++ b/src/quant_platform/application/live_session.py @@ -384,7 +384,7 @@ def _reconcile( assembler.start_window(None) self._chain_end = None return staged - while not staged: + while not any(batch.records for batch in staged): # a frame with no trade is not a trade (an empty snapshot is admitted) if stop_requested() or reader.finished.is_set(): return None try: diff --git a/tests/integration_live_session_postgres.py b/tests/integration_live_session_postgres.py index 449e697..623f4fe 100644 --- a/tests/integration_live_session_postgres.py +++ b/tests/integration_live_session_postgres.py @@ -365,6 +365,11 @@ def recent_stale(*, limit, instrument="BTCUSDT"): with mock.patch.object(app, "fetch_recent_public_trades", recent_stale), websockets_stub(provider6): behind.start() behind.until(lambda: provider6.sockets, "the connection") + # a frame with no trade (an empty snapshot is admitted by the canonical entry) is not the overlap candidate: + # nothing is fetched or reconciled until a trade of the subscription arrives + provider6.push({"topic": f"publicTrade.{INSTRUMENT}", "type": "snapshot", "ts": 1, "data": []}) + time.sleep(0.4) + assert not behind.health("reconcile"), "an empty snapshot unlocked the reconciliation" rows_ = world.make(2) provider6.push(world.message(rows_)) delivered.update(r["i"] for r in rows_) diff --git a/tests/test_live_session_v1.py b/tests/test_live_session_v1.py index 38be46b..1550556 100644 --- a/tests/test_live_session_v1.py +++ b/tests/test_live_session_v1.py @@ -605,6 +605,18 @@ def test_the_snapshot_is_taken_after_the_first_trade_and_the_reconciliation_rece log = provider.log self.assertLess(log.index("subscribe"), log.index("fetch_recent")) + def test_an_empty_snapshot_is_not_a_trade_the_session_keeps_waiting_for_one(self) -> None: + provider = FakeProvider() + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0 + 2, [record(T0 + 1, "x")])) as h: + h.until(lambda: provider.sockets, "the connection") + provider.push({"topic": f"publicTrade.{INSTRUMENT}", "type": "snapshot", "ts": T0, "data": []}) + time.sleep(0.3) + self.assertNotIn("fetch_recent", provider.log) # a frame with no trade proves no overlap + self.assertNotIn("reconcile", provider.log) + provider.push(trade_message(T0 + 5, "w1", "w2")) + h.until(lambda: h.reconciled, "the reconciliation after the first real trade") + self.assertEqual(["w1", "w2"], [r.trade_id for r in h.reconciled[0][1]]) + def test_a_session_that_ends_before_any_trade_reconciles_nothing_and_is_an_interruption(self) -> None: provider = FakeProvider() with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0, [record(T0, "x")])) as h: From cace9022933a825617646153beabf63499916335 Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:01:50 +0100 Subject: [PATCH 08/13] fix(data): O02 drops empty frames while waiting for the first trade (#523) Third review of #524: the wait for the first trade held every empty frame in a local list outside the bounded buffer (400 retained with a buffer of 4). Frames with no trade are now counted as messages and dropped, never held. Test: 300 empty frames leave no held batches and unlock nothing; fails when the frames are kept. Co-Authored-By: Claude Sonnet 5.5 --- .../application/live_session.py | 12 ++++++++++-- tests/test_live_session_v1.py | 19 ++++++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/quant_platform/application/live_session.py b/src/quant_platform/application/live_session.py index ff2be1e..d6712c6 100644 --- a/src/quant_platform/application/live_session.py +++ b/src/quant_platform/application/live_session.py @@ -366,6 +366,11 @@ def _drain_available(self, buffer: "queue.Queue[LiveTradeBatch]") -> list[LiveTr 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], @@ -384,11 +389,14 @@ def _reconcile( assembler.start_window(None) self._chain_end = None return staged - while not any(batch.records for batch in staged): # a frame with no trade is not a trade (an empty snapshot is admitted) + # 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.append(buffer.get(timeout=self._config.tick)) + staged += self._keep_trades([buffer.get(timeout=self._config.tick)]) except queue.Empty: continue recent = tuple(ports.fetch_recent(self._config.recent_limit)) diff --git a/tests/test_live_session_v1.py b/tests/test_live_session_v1.py index 1550556..9a81c68 100644 --- a/tests/test_live_session_v1.py +++ b/tests/test_live_session_v1.py @@ -7,6 +7,7 @@ from __future__ import annotations +import gc import json from pathlib import Path import queue @@ -27,7 +28,7 @@ LiveSessionPorts, ) from quant_platform.data.models import Instant, TradeRecord # noqa: E402 -from quant_platform.source_adapters.bybit_live import SessionState # noqa: E402 +from quant_platform.source_adapters.bybit_live import LiveTradeBatch, SessionState # noqa: E402 MS = 1_000_000 INSTRUMENT = "ETHUSDT" @@ -617,6 +618,22 @@ def test_an_empty_snapshot_is_not_a_trade_the_session_keeps_waiting_for_one(self h.until(lambda: h.reconciled, "the reconciliation after the first real trade") self.assertEqual(["w1", "w2"], [r.trade_id for r in h.reconciled[0][1]]) + def test_frames_with_no_trade_are_not_held_while_the_session_waits_for_the_first_trade(self) -> None: + provider = FakeProvider() + empty = {"topic": f"publicTrade.{INSTRUMENT}", "type": "snapshot", "ts": T0, "data": []} + with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0 + 2, [record(T0 + 1, "x")])) as h: + h.until(lambda: provider.sockets, "the connection") + for _ in range(300): + provider.push(empty) + time.sleep(0.001) + h.until(lambda: h.engine._messages >= 300, "the empty frames to be taken") + gc.collect() + held = sum(1 for o in gc.get_objects() if isinstance(o, LiveTradeBatch) and not o.records) + self.assertLess(held, 20) # not one per frame: the wait must not grow past the bounded buffer + self.assertNotIn("reconcile", provider.log) + provider.push(trade_message(T0 + 5, "w1")) + h.until(lambda: h.reconciled, "the reconciliation after the first real trade") + def test_a_session_that_ends_before_any_trade_reconciles_nothing_and_is_an_interruption(self) -> None: provider = FakeProvider() with Harness(provider, checkpoint=True, reconcile=lambda r, b: pass_restart(T0, [record(T0, "x")])) as h: From 30491fe04840d26d696b8248c9951f2c0648bdd9 Mon Sep 17 00:00:00 2001 From: NeoNix <112125692+NeoNix-Lab@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:45:47 +0100 Subject: [PATCH 09/13] live: continuous-session configuration, runbook and window evidence tool (O03, ADR-0075 slice 9.3) (#525) - CLI: --mode {cycles,continuous} (default cycles, unchanged) and --slice-seconds, --slice-max-trades, --buffer-messages, valid only with continuous; empty value = default so a unit whose env file predates the options still starts; invalid values refused before any connection. - Units and env examples (BTCUSDT unit and @ template): mode and the three bounds rendered into ExecStart; defaults cycles with empty bounds. - Runbook: operating the continuous session, rollback to cycles, the one-hour real-provider proof procedure and its stop conditions. - Evidence tool (read-only): archive vs strict DataGateway read over the claimed windows, holes, ordering violations and health counters from the captured signals; stop conditions on an undeclared loss, a refused strict read, a double or out-of-order read, a payload that differs. - Tests: CLI, artifacts, runbook, evidence (unit, mutation-checked) and PostgreSQL phase 7. Co-Authored-By: Claude Sonnet 5.5 --- .../LIVE_INGEST_SERVER_DEPLOYMENT.md | 83 +++- .../quant-platform-live-ingest.env.example | 9 + .../quant-platform-live-ingest.service | 2 +- .../quant-platform-live-ingest@.env.example | 9 + .../quant-platform-live-ingest@.service | 2 +- .../application/live_window_evidence.py | 377 ++++++++++++++++++ tests/integration_live_session_postgres.py | 49 ++- tests/test_live_ingest_server_cli_v1.py | 79 ++++ .../test_live_ingest_template_artifacts_v1.py | 156 +++++++- tests/test_live_window_evidence_v1.py | 280 +++++++++++++ tests/test_package_boundaries_v1.py | 1 + tools/live_ingest_server.py | 58 ++- tools/live_window_evidence.py | 79 ++++ 13 files changed, 1163 insertions(+), 21 deletions(-) create mode 100644 src/quant_platform/application/live_window_evidence.py create mode 100644 tests/test_live_window_evidence_v1.py create mode 100644 tools/live_window_evidence.py diff --git a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md index b5a089b..61b51d3 100644 --- a/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md +++ b/docs/engineering/LIVE_INGEST_SERVER_DEPLOYMENT.md @@ -147,21 +147,82 @@ dt=/seg=/part-001.p `SLICE_ORDERING_VIOLATION`, publishes nothing, and the next start reconciles from the checkpoint. - Partitions published before ADR-0075 (`dt=`, many superseded revisions) are left as they are; there is no repair. -### Continuous session (ADR-0075 slice 9.2, `O02`): in the code, not enabled +### Continuous session (ADR-0075 slices 9.2 and 9.3, `O02` and `O03`): opt-in per unit -`LiveIngestServerConfigV1.continuous_session` (a `LiveSessionConfig`) makes the server run ONE WebSocket session instead of the bounded -cycles: the connection is not closed between publications, a bounded buffer (default 20 000 messages) decouples the reader from -the publisher, and slices close after `slice_seconds` (300) or `slice_max_trades` (50 000). The default is `None`: the cycle loop above -is unchanged, and the unit templates, the CLI flags, this runbook's operating steps and the one-hour real-provider run belong to `O03`. -What an operator will see when it is enabled: +`--mode continuous` (environment variable `QP_LIVE_INGEST_MODE`) makes the server run ONE WebSocket session instead of the bounded +cycles: the connection is not closed between publications, a bounded buffer decouples the reader from the publisher, and slices +close after `slice_seconds` of wall clock or `slice_max_trades` trades. The default is `cycles`, the loop described above, and +nothing changes for a unit whose environment file does not set the mode (an empty or unset value is `cycles`, and an environment +file that predates these variables still starts the unit). Enabling it is an operator step: edit the environment file of the +instance and restart the unit; the repository enables nothing, and deployment of a changed server stays manual. +| Variable | Flag | Default | Meaning | +|---|---|---|---| +| `QP_LIVE_INGEST_MODE` | `--mode` | `cycles` | `cycles` or `continuous` | +| `QP_LIVE_INGEST_SLICE_SECONDS` | `--slice-seconds` | 300 | continuous only: wall-clock seconds after which an open slice closes | +| `QP_LIVE_INGEST_SLICE_MAX_TRADES` | `--slice-max-trades` | 50000 | continuous only: trades after which an open slice closes | +| `QP_LIVE_INGEST_BUFFER_MESSAGES` | `--buffer-messages` | 20000 | continuous only: bound of the reader's buffer; a full buffer ends the session | + +The three bounds are valid only with `continuous`: with `cycles` the server refuses to start (exit status 2) rather than ignore +them, so leave them empty (an empty value is the default). A non-positive or non-integer value is refused before any connection. +`--recent-limit` also applies to the reconciliation after an interruption. The ping interval, pong timeout and reconnect backoff are +not configuration. `--max-cycles`, when used for a bounded proof, counts health snapshots: one per published slice in this mode. + +Example, an instance switched to the continuous session with the defaults (`/etc/quant-platform/live-ingest-server-ETHUSDT.env`): + +```text +QP_LIVE_INGEST_MODE=continuous +QP_LIVE_INGEST_SLICE_SECONDS= +QP_LIVE_INGEST_SLICE_MAX_TRADES= +QP_LIVE_INGEST_BUFFER_MESSAGES= +``` + +What an operator sees: + +- Startup prints `mode=continuous` and the three bounds in force. - A disconnect, a missing pong, a full buffer or a trade below the open window **ends the session**; what was received is published, the interruption is signalled (`HEALTH_SNAPSHOT`, `DEGRADED`, `phase=interruption`, with the reason and the counters), the session - reconnects with a bounded backoff, subscribes first, fetches the recent trades and reconciles from the last durable key. -- Continuity proven: the reconciled trades are published as slices and the chain stays exact. Anchor outside the recent window: an - explicit gap (ADR-0044), recorded, `DEGRADED`; a new window starts at the first trade after it and nothing is claimed across the gap. -- Every published slice signals the buffer high-water mark and capacity, the slice lag in milliseconds, the number of reconnects and - of ordering violations. A publication, catalog or checkpoint failure stops the loop (`FAILURE`), as in the cycle loop. + reconnects with a bounded backoff, subscribes first and waits for the first trade of the new subscription. It then fetches the + recent trades and reconciles from the last durable key; a subscription with no trade yet reconciles nothing and claims nothing. +- Continuity proven (a trade of the subscription is in the recent-trades window): the reconciled trades are published as slices and + the chain stays exact. Anchor outside the window, or a window that does not meet the subscription: an explicit gap (ADR-0044), + recorded, `DEGRADED`; a new window starts at the first trade after it and nothing is claimed across the gap. +- Every published slice signals `phase=slice` with `buffer_high_water` and `buffer_capacity`, `slice_lag_ms`, `reconnects` and + `ordering_violations`. A UTC midnight with no trade is reported as an unclaimed span. A publication, catalog or checkpoint failure + stops the loop (`FAILURE`), as in the cycle loop. +- A `DataGateway` read under `strict` coverage across an interruption's gap is refused; under `allow-partial` it returns everything + published. + +**Rollback to the cycles:** set `QP_LIVE_INGEST_MODE=cycles` (and the bounds empty), restart the unit. The checkpoint and the +published partitions are the same in both modes: the first cycle reconciles from the durable checkpoint. + +### One-hour real-provider proof (`O03`; the `T02` proof for `ETHUSDT`) + +Operator-executed; the repository starts nothing. It measures what ADR-0075 leaves as an assumption: the captured share against +the provider's archive, the ordering of the provider's `exchange_ts`, the slice sizes and the health signals. Use a **disposable +catalog and storage root** (or an `ETHUSDT`-only root the maintainer chooses): the proof never touches the `BTCUSDT` dataset or its +unit, and it enables nothing in production (the ADR-0074 section 6 capacity gate stands). + +```bash +# 1. Run the continuous session for at least one hour, with the signals captured. Stop it cleanly with SIGTERM/SIGINT. +python tools/live_ingest_server.py --instrument ETHUSDT --mode continuous \ + --storage-root --storage-root-id --checkpoint-path /canonical/_k10_checkpoints/live-ingest-server-v1-ETHUSDT.json \ + --code-ref "$(git rev-parse HEAD)" 2>&1 | tee live-ethusdt-run.log + +# 2. After the UTC day (or days) of the run has ended, fetch the archive of each day it touched (tools/fetch_bybit_trade_archive.py). +# 3. Produce the evidence (read-only; exit 0 = no stop condition, 1 = a stop condition, 2 = usage): +python tools/live_window_evidence.py --instrument ETHUSDT --archive ETHUSDT.csv.gz [more days] \ + --signals-log live-ethusdt-run.log --code-ref --mode continuous > ethusdt-evidence.json +``` + +The report states, for the window the run claimed (the valid live slices): the archive trades in it, the trades a `strict` gateway +read returns (chunks of at most twelve slices, ending on slice boundaries), the captured ratio, the holes between exact chains (each +an interval the run declared unclaimed, with the archive trades it contains), the slices (count, rows and seconds: minimum, median, +maximum) and the counters of the session. **Stop conditions** (exit 1; do not read the proof as passed and report): an archive trade +inside a claimed window that is not read back (an undeclared loss); a strict read of a claimed window refused; a trade read twice or +out of order; a trade whose payload differs from the archive. A shortfall against the archive that falls inside an unclaimed span is +reported, not hidden, and is not a stop condition; an ordering violation is a measurement (it is an interruption by design), to be +explained in the evidence. Record the report, the log and the commit in the pull request of `O03`. ## Rollback diff --git a/infra/systemd/quant-platform-live-ingest.env.example b/infra/systemd/quant-platform-live-ingest.env.example index f0cab0c..81cf33a 100644 --- a/infra/systemd/quant-platform-live-ingest.env.example +++ b/infra/systemd/quant-platform-live-ingest.env.example @@ -24,6 +24,15 @@ QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE=1000 QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE=20 QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS=5 +# Session mode (ADR-0075, DG-O). cycles (the default; empty means cycles) is the bounded cycle loop; continuous keeps ONE WebSocket +# session open between publications. The three bounds apply to continuous only and an empty value is the default (300 s, 50000 +# trades, 20000 messages): leave them empty with cycles, the server refuses a bound together with cycles. Changing the mode is a +# restart of the unit, an operator step; the checkpoint and the published partitions are the same in both modes. +QP_LIVE_INGEST_MODE=cycles +QP_LIVE_INGEST_SLICE_SECONDS= +QP_LIVE_INGEST_SLICE_MAX_TRADES= +QP_LIVE_INGEST_BUFFER_MESSAGES= + QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES=53687091200 QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES=21474836480 QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES=5368709120 diff --git a/infra/systemd/quant-platform-live-ingest.service b/infra/systemd/quant-platform-live-ingest.service index b348280..ba47de0 100644 --- a/infra/systemd/quant-platform-live-ingest.service +++ b/infra/systemd/quant-platform-live-ingest.service @@ -11,7 +11,7 @@ Group=marketdata WorkingDirectory=/opt/market-platform EnvironmentFile=/etc/quant-platform/live-ingest-server.env UMask=0027 -ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_PATH} --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} +ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_PATH} --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} --mode=${QP_LIVE_INGEST_MODE} --slice-seconds=${QP_LIVE_INGEST_SLICE_SECONDS} --slice-max-trades=${QP_LIVE_INGEST_SLICE_MAX_TRADES} --buffer-messages=${QP_LIVE_INGEST_BUFFER_MESSAGES} Restart=on-failure RestartSec=10s KillSignal=SIGTERM diff --git a/infra/systemd/quant-platform-live-ingest@.env.example b/infra/systemd/quant-platform-live-ingest@.env.example index ec42661..d3183b5 100644 --- a/infra/systemd/quant-platform-live-ingest@.env.example +++ b/infra/systemd/quant-platform-live-ingest@.env.example @@ -29,6 +29,15 @@ QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE=1000 QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE=20 QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS=5 +# Session mode (ADR-0075, DG-O). cycles (the default; empty means cycles) is the bounded cycle loop; continuous keeps ONE WebSocket +# session open between publications. The three bounds apply to continuous only and an empty value is the default (300 s, 50000 +# trades, 20000 messages): leave them empty with cycles, the server refuses a bound together with cycles. Changing the mode is a +# restart of the unit, an operator step; the checkpoint and the published partitions are the same in both modes. +QP_LIVE_INGEST_MODE=cycles +QP_LIVE_INGEST_SLICE_SECONDS= +QP_LIVE_INGEST_SLICE_MAX_TRADES= +QP_LIVE_INGEST_BUFFER_MESSAGES= + QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES=53687091200 QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES=21474836480 QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES=5368709120 diff --git a/infra/systemd/quant-platform-live-ingest@.service b/infra/systemd/quant-platform-live-ingest@.service index 06de9d8..416c17a 100644 --- a/infra/systemd/quant-platform-live-ingest@.service +++ b/infra/systemd/quant-platform-live-ingest@.service @@ -13,7 +13,7 @@ EnvironmentFile=/etc/quant-platform/live-ingest-server-%i.env UMask=0027 # BTCUSDT stays on quant-platform-live-ingest.service: two writers on one dataset must not be startable (ADR-0074 section 3). ExecStartPre=/usr/bin/test "%i" != "BTCUSDT" -ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --instrument %i --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_DIR}/live-ingest-server-v1-%i.json --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} +ExecStart=/opt/market-platform/.venv/bin/python /opt/market-platform/tools/live_ingest_server.py --instrument %i --storage-root ${QP_LIVE_INGEST_STORAGE_ROOT} --storage-root-id ${QP_LIVE_INGEST_STORAGE_ROOT_ID} --checkpoint-path ${QP_LIVE_INGEST_CHECKPOINT_DIR}/live-ingest-server-v1-%i.json --recent-limit ${QP_LIVE_INGEST_RECENT_LIMIT} --code-ref ${QP_LIVE_INGEST_CODE_REF} --producer ${QP_LIVE_INGEST_PRODUCER} --max-messages-per-cycle ${QP_LIVE_INGEST_MAX_MESSAGES_PER_CYCLE} --max-seconds-per-cycle ${QP_LIVE_INGEST_MAX_SECONDS_PER_CYCLE} --cycle-interval-seconds ${QP_LIVE_INGEST_CYCLE_INTERVAL_SECONDS} --pressure-available-bytes ${QP_LIVE_INGEST_PRESSURE_AVAILABLE_BYTES} --pressure-critical-available-bytes ${QP_LIVE_INGEST_PRESSURE_CRITICAL_AVAILABLE_BYTES} --pressure-exhausted-available-bytes ${QP_LIVE_INGEST_PRESSURE_EXHAUSTED_AVAILABLE_BYTES} --pressure-max-capacity-age-seconds ${QP_LIVE_INGEST_PRESSURE_MAX_CAPACITY_AGE_SECONDS} --mode=${QP_LIVE_INGEST_MODE} --slice-seconds=${QP_LIVE_INGEST_SLICE_SECONDS} --slice-max-trades=${QP_LIVE_INGEST_SLICE_MAX_TRADES} --buffer-messages=${QP_LIVE_INGEST_BUFFER_MESSAGES} Restart=on-failure RestartSec=10s KillSignal=SIGTERM diff --git a/src/quant_platform/application/live_window_evidence.py b/src/quant_platform/application/live_window_evidence.py new file mode 100644 index 0000000..1ce614a --- /dev/null +++ b/src/quant_platform/application/live_window_evidence.py @@ -0,0 +1,377 @@ +"""Evidence of a continuous live run against the Bybit archive (ADR-0075 slice 9.3, DG-O ``O03``). + +Read-only: it reads the catalog and the files through the ``DataGateway``, the archive files and a captured server log, and writes +nothing. The question it answers is the one ADR-0075 asks of the real-provider run: of the trades the provider's archive holds for +the window the run claimed, how many does a ``strict`` gateway read return, and is every one that does not explained by an +interval the run itself declared unclaimed? + +* The **windows the run claimed** are the valid live slices of the instrument inside the requested window (a slice is a half-open + window, ``complete`` over exactly that window). Consecutive slices that chain exactly form a **segment**; a hole between two + segments is an interval nobody claimed (an interruption with an explicit gap, a midnight with no trade). +* An archive trade **inside a claimed window** that is not read back is a loss the run did not declare: a stop condition. One inside + a hole is the declared cost of that interruption: reported with the hole, not a failure. A trade read back that the archive does + not hold is reported (the archive is the provider's later view); one the archive holds with a different payload, or read twice, + is a stop condition. +* The signals are taken from the captured stdout of ``tools/live_ingest_server.py`` (``signal kind=... k=v,k=v`` lines): the + counters the session reports (ordering violations, reconnects, buffer high-water mark, slice lag) and the interruptions. + +The result states what was measured; it never turns a shortfall into a pass, and it makes no claim about the provider beyond the run. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass +from decimal import Decimal +from pathlib import Path +import re +from statistics import median +from typing import Any + +from quant_platform.data import Instant +from quant_platform.data.models import TradeRecord + +_NS_PER_DAY = 86_400_000_000_000 +_NS_PER_MS = 1_000_000 +_EXAMPLES = 5 +_READ_CHUNK = 12 # slices per strict read (a K12 window carries at most 16 members) + + +@dataclass(frozen=True, slots=True) +class SliceWindow: + """One published live partition: its key, revision, lifecycle state, half-open window and row count.""" + + key: str + revision: int + state: str + start: Instant + end: Instant + rows: int + + +def _ms(instant: Instant) -> int: + return instant.epoch_ns // _NS_PER_MS * _NS_PER_MS + + +def chain_segments(slices: Sequence[SliceWindow]) -> list[tuple[Instant, Instant, list[SliceWindow]]]: + """The maximal runs of slices that chain exactly (each starts where the previous ended), by start.""" + + segments: list[tuple[Instant, Instant, list[SliceWindow]]] = [] + for item in sorted(slices, key=lambda s: (s.start.epoch_ns, s.end.epoch_ns)): + if segments and segments[-1][1].epoch_ns == item.start.epoch_ns: + start, _end, members = segments[-1] + segments[-1] = (start, item.end, [*members, item]) + else: + segments.append((item.start, item.end, [item])) + return segments + + +def _holes(segments: Sequence[tuple[Instant, Instant, list[SliceWindow]]]) -> list[tuple[Instant, Instant]]: + return [(a[1], b[0]) for a, b in zip(segments, segments[1:])] + + +def _field_differences(archive: TradeRecord, read: TradeRecord) -> list[str]: + """What differs between the archive's and the gateway's view of one trade (the fields the archive carries).""" + + differences = [] + for name in ("venue", "instrument", "aggressor_side"): + if getattr(archive, name) != getattr(read, name): + differences.append(name) + if _ms(archive.exchange_ts) != _ms(read.exchange_ts): + differences.append("exchange_ts_ms") + for name in ("price", "size"): + if Decimal(getattr(archive, name)) != Decimal(getattr(read, name)): + differences.append(f"{name}_value") + return differences + + +_SIGNAL_LINE = re.compile(r"^signal kind=(?P\S+) capability=\S+ signal_id=\S+(?: (?P.*))?$") + + +def _field(payload: str, name: str) -> str | None: + match = re.search(rf"(?:^|[ ,]){re.escape(name)}=([^,\s]*)", payload) + return None if match is None else match.group(1) + + +def summarize_signals(text: str) -> dict[str, Any]: + """The counters and interruptions of a captured ``tools/live_ingest_server.py`` stdout. + + The session's counters are cumulative, so the largest value seen is the final one; the lag is reported as a maximum.""" + + kinds: Counter[str] = Counter() + phases: Counter[str] = Counter() + health: Counter[str] = Counter() + interruptions: Counter[str] = Counter() + maxima = {"ordering_violations": 0, "reconnects": 0, "buffer_high_water": 0, "buffer_capacity": 0, "slice_lag_ms": 0} + lags: list[int] = [] + failures: list[str] = [] + final_state: str | None = None + for line in text.splitlines(): + match = _SIGNAL_LINE.match(line.strip()) + if match is None: + continue + kind, payload = match.group("kind"), match.group("payload") or "" + kinds[kind] += 1 + phase = _field(payload, "phase") + if phase: + phases[phase] += 1 + if kind == "HEALTH_SNAPSHOT": + state = _field(payload, "health") + if state: + health[state] += 1 + interruption = _field(payload, "interruption") + if interruption: + interruptions[interruption] += 1 + for name in maxima: + value = _field(payload, name) + if value is not None and value.lstrip("-").isdigit(): + maxima[name] = max(maxima[name], int(value)) + if name == "slice_lag_ms": + lags.append(int(value)) + if kind == "FAILURE": + failures.append(_field(payload, "failure_code") or "unknown") + resulting = _field(payload, "resulting_state") + if resulting: + final_state = resulting + return { + "signals": dict(sorted(kinds.items())), + "health_snapshots": dict(sorted(health.items())), + "phases": dict(sorted(phases.items())), + "interruptions": dict(sorted(interruptions.items())), + "ordering_violations": maxima["ordering_violations"], + "reconnects": maxima["reconnects"], + "buffer_high_water": maxima["buffer_high_water"], + "buffer_capacity": maxima["buffer_capacity"], + "slice_lag_ms_max": maxima["slice_lag_ms"], + "slice_lag_ms_median": int(median(lags)) if lags else 0, + "failures": failures, + "final_lifecycle_state": final_state, + } + + +def build_window_evidence( + *, + instrument: str, + archive: Iterable[TradeRecord], + slices: Sequence[SliceWindow], + read_segment: Callable[[Instant, Instant], Sequence[TradeRecord]], + window: tuple[Instant, Instant] | None = None, + signals_text: str | None = None, + configuration: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Compare the claimed windows of a run with the archive; ``read_segment(start, end)`` is the ``strict`` gateway read.""" + + valid = _claimed(slices, window) + stops: list[str] = [] + if not valid: + return {"instrument": instrument, "passed": False, "stop_conditions": ["no valid live slice in the window"], + "window": None} + ordered_slices = sorted(valid, key=lambda s: (s.start.epoch_ns, s.end.epoch_ns)) + overlapping = sum(1 for a, b in zip(ordered_slices, ordered_slices[1:]) if b.start.epoch_ns < a.end.epoch_ns) + if overlapping: # the catalog admits no two valid partitions of one dataset over the same time (partitions_one_live) + stops.append(f"{overlapping} valid slices overlap the one before them") + segments = chain_segments(valid) + holes = _holes(segments) + start, end = segments[0][0], segments[-1][1] + + # what the gateway returns for the claimed windows, one strict read per exact chain + read: list[TradeRecord] = [] + refused: list[str] = [] + for _seg_start, _seg_end, members in segments: + for first in range(0, len(members), _READ_CHUNK): # a read is bounded in members (K12): chunks end on slice boundaries + chunk = members[first:first + _READ_CHUNK] + a, b = chunk[0].start, chunk[-1].end + try: + read.extend(read_segment(a, b)) + except Exception as exc: # noqa: BLE001 - a refused strict read is a finding of the evidence, never a crash + refused.append(f"{a.isoformat()}..{b.isoformat()}: {type(exc).__name__}: {exc}") + if refused: + stops.append(f"a strict read of a claimed window was refused ({len(refused)})") + read_ids = Counter(record.trade_id for record in read) + duplicated = sorted(trade_id for trade_id, count in read_ids.items() if count > 1) + if duplicated: + stops.append(f"{len(duplicated)} trades are read more than once") + read_by_id = {record.trade_id: record for record in read} + ordered = [(r.exchange_ts.epoch_ns, r.trade_id) for r in read] + out_of_order = sum(1 for a, b in zip(ordered, ordered[1:]) if b[0] < a[0]) + if out_of_order: + stops.append(f"the gateway returned {out_of_order} trades out of exchange_ts order") + + low, high = start.epoch_ns, end.epoch_ns + in_window = {r.trade_id: r for r in archive if low <= r.exchange_ts.epoch_ns < high} + inside_claimed: list[str] = [] + inside_hole: dict[int, list[str]] = {i: [] for i in range(len(holes))} + for trade_id, record in in_window.items(): + if trade_id in read_by_id: + continue + ts = record.exchange_ts.epoch_ns + for index, (hole_start, hole_end) in enumerate(holes): + if hole_start.epoch_ns <= ts < hole_end.epoch_ns: + inside_hole[index].append(trade_id) + break + else: + inside_claimed.append(trade_id) + if inside_claimed: + stops.append(f"{len(inside_claimed)} archive trades inside a claimed window are not read back (an undeclared loss)") + extra = sorted(trade_id for trade_id in read_by_id if trade_id not in in_window) + conflicts: dict[str, list[str]] = {} + for trade_id, record in read_by_id.items(): + if trade_id in in_window: + differences = _field_differences(in_window[trade_id], record) + if differences: + conflicts[trade_id] = differences + if conflicts: + stops.append(f"{len(conflicts)} trades differ from the archive") + captured = len(set(read_by_id) & set(in_window)) + + window_ns = high - low + listened_ns = sum(b - a for a, b in ((s[0].epoch_ns, s[1].epoch_ns) for s in segments)) + row_counts = [s.rows for s in valid] + lengths = [(s.end.epoch_ns - s.start.epoch_ns) / 1e9 for s in valid] + report: dict[str, Any] = { + "instrument": instrument, + "window": {"start": start.isoformat(), "end": end.isoformat(), "seconds": window_ns / 1e9}, + "configuration": dict(configuration or {}), + "slices": { + "valid": len(valid), + "not_valid_in_catalog": len([s for s in slices if s.state != "valid"]), + "revisions_above_one": len([s for s in valid if s.revision != 1]), + "rows_total": sum(row_counts), + "rows_min": min(row_counts), "rows_median": int(median(row_counts)), "rows_max": max(row_counts), + "seconds_min": min(lengths), "seconds_median": median(lengths), "seconds_max": max(lengths), + "chain_segments": len(segments), + }, + "holes": [ + {"start": a.isoformat(), "end": b.isoformat(), "seconds": (b.epoch_ns - a.epoch_ns) / 1e9, + "archive_trades_inside": len(inside_hole[i]), "examples": sorted(inside_hole[i])[:_EXAMPLES]} + for i, (a, b) in enumerate(holes) + ], + "claimed_share": listened_ns / window_ns if window_ns else 1.0, + "archive_trades_in_window": len(in_window), + "read_through_gateway": len(read), + "captured_of_archive": captured, + "captured_ratio": captured / len(in_window) if in_window else 1.0, + "missing_inside_claimed_windows": len(inside_claimed), + "missing_inside_unclaimed_spans": sum(len(v) for v in inside_hole.values()), + "read_not_in_archive": len(extra), + "examples_missing_inside_claimed_windows": sorted(inside_claimed)[:_EXAMPLES], + "examples_read_not_in_archive": extra[:_EXAMPLES], + "conflicts": {k: conflicts[k] for k in sorted(conflicts)[:_EXAMPLES]}, + "strict_reads_refused": refused, + "duplicated_reads": duplicated[:_EXAMPLES], + "stop_conditions": stops, + "passed": not stops, + } + if signals_text is not None: + report["signals"] = summarize_signals(signals_text) + return report + + +_ARCHIVE_NAME = re.compile(r"^(?P[A-Z0-9]+)(?P\d{4}-\d{2}-\d{2})\.csv\.gz$") + + +def archive_days_needed(window_start: Instant, window_end: Instant) -> list[str]: + """The UTC days (``YYYY-MM-DD``) a half-open window touches; each needs its archive file.""" + + first = window_start.epoch_ns // _NS_PER_DAY + last = (window_end.epoch_ns - 1) // _NS_PER_DAY + return [Instant(day * _NS_PER_DAY).isoformat()[:10] for day in range(first, last + 1)] + + +def parse_window(start: str | None, end: str | None) -> tuple[Instant, Instant] | None: + """The requested window from two ISO instants, or ``None`` when neither is given.""" + + if start is None and end is None: + return None + if start is None or end is None: + raise ValueError("a window needs both a start and an end") + low, high = Instant.parse(start), Instant.parse(end) + if not low.epoch_ns < high.epoch_ns: + raise ValueError("the window start must be before its end") + return low, high + + +def archive_days_missing( + slices: Sequence[SliceWindow], window: tuple[Instant, Instant] | None, available: Iterable[str], +) -> tuple[list[str], list[str]]: + """``(days the claimed windows touch, those without an archive file)``; both empty when no valid slice is in the window.""" + + valid = _claimed(slices, window) + if not valid: + return [], [] + needed = archive_days_needed(min(s.start for s in valid), max(s.end for s in valid)) + have = set(available) + return needed, [day for day in needed if day not in have] + + +def _claimed(slices: Sequence[SliceWindow], window: tuple[Instant, Instant] | None) -> list[SliceWindow]: + valid = [s for s in slices if s.state == "valid"] + if window is not None: + valid = [s for s in valid if s.start.epoch_ns >= window[0].epoch_ns and s.end.epoch_ns <= window[1].epoch_ns] + return valid + + +def load_archive_days(paths: Iterable[str | Path], *, instrument: str) -> dict[str, list[TradeRecord]]: + """``day -> records`` of local ``.csv.gz`` files (the day is read from the file name).""" + + from quant_platform.source_adapters.bybit_archive import read_bybit_archive_day + + days: dict[str, list[TradeRecord]] = {} + for path in paths: + match = _ARCHIVE_NAME.match(Path(path).name) + if match is None or match.group("instrument") != instrument: + raise ValueError(f"{Path(path).name!r} is not a {instrument}.csv.gz archive file") + days[match.group("day")] = list(read_bybit_archive_day(path, instrument=instrument, day=match.group("day")).records) + return days + + +# ---------------------------------------------------------------------------------------------------- the real catalog + + +def read_live_slices(dsn: str | None, instrument: str) -> list[SliceWindow]: + """Every live-slice partition (``dt=/seg=