Skip to content

sequence-validation - #97

Merged
marcinvalas merged 52 commits into
masterfrom
sequence-validation
Nov 20, 2026
Merged

marcinvalas merged 52 commits into
masterfrom
sequence-validation

Conversation

@marcinvalas

@marcinvalas marcinvalas commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Adds sequence validation to the live receive path shared by stream() and streamNormalized(). Exchange adapters provide sequence information; the shared checker rejects gaps before output, reports SequenceGapError and uses existing connection recovery. Validation defaults to true; validateSequence: false disables continuity checks.

Consolidates existing continuous checks from mappers/feeds and adds missing extractors using recorder protocol rules as the reference. Snapshot acquisition, subscriptions and historical mapping stay outside the sequence-only scope unless an integration explicitly requires a local adaptation.

Release notes

Suggested version: minor (new option, new default behavior, no API break).

  • Behavior change: stream() and streamNormalized() now validate exchange sequence numbers by default. On a gap the connection reconnects, the error goes to onError as SequenceGapError, and normalized books restart from a fresh snapshot. Pass validateSequence: false to keep the previous behavior.
  • New validateSequence option on stream() and streamNormalized().
  • createRealTimeFeed and the real-time feed base classes keep onError as the 4th argument; validateSequence is added after it.

Exchange integrations

All 42 integrations have recorded acceptance, with coverage limitations noted below. Checked means required acceptance is complete within the stated coverage, not just that code exists.

  • binance-futures
  • binance-delivery
  • binance
  • binance-us
  • aster
  • aster-futures
  • bitget
  • bitget-futures
  • bitvavo
  • bullish — dated-future live gap coverage unavailable on quiet markets.
  • bybit
  • bybit-spot
  • bybit-options
  • bybit-spread — sparse live fault-injection coverage.
  • coinbase
  • coinbase-derivatives — historical blocks only.
  • cryptofacilities — inverse perpetuals covered historically.
  • delta
  • delta-india — historical coverage starts October 29.
  • gate-io
  • gate-io-futures — OBU history starts October 21.
  • gemini — historical checks prove native continuity, not snapshot completeness.
  • hitbtc — recorder's separate timestamp-lag guard is not migrated.
  • huobi-dm
  • huobi-dm-swap
  • huobi-dm-linear-swap
  • kucoin — Accepted; present on the PR branch.
  • kucoin-futures — Accepted; snapshot-startup limitation below; present on the PR branch.
  • lighter — Perpetual/spot acceptance recorded; present on the PR branch.
  • lighter-rh — Perpetual and USDG spot books accepted; historical coverage limits below; present on the PR branch.
  • mexc — Spot sequence validation accepted; present on the PR branch.
  • mexc-futures — Acceptance recorded in the plan; present on the PR branch.
  • whitebit — Sequence migration accepted locally; recorded dates November 6–10, no first-of-month coverage yet.
  • okex — Public books accepted; authenticated TBT channels excluded, matching recorder.
  • okex-futures — Public books accepted; authenticated TBT channels excluded, matching recorder.
  • okex-swap — Public books accepted; authenticated TBT channels excluded, matching recorder.
  • okex-options — Public books accepted; authenticated TBT channels excluded, matching recorder.
  • poloniex — book_lv2 accepted; recorded checks use BCH instead of quiet SUI.
  • woo-x
  • deribit — Startup/continuity rules accepted; public .100ms live and recorded .raw verified.
  • huobi — Fresh sequence-only acceptance recorded November 12; snapshot-startup/alignment findings remain open.
  • backpack — Post-release migration accepted; present on the PR branch. Recorded coverage is limited to release-day slices; authenticated public historical replay remains unverified.

Findings and outstanding work

  • Deribit: ports recorder's startup rule (ignore pre-snapshot changes, first change may span the anchor, then exact prev_change_id links or duplicates); gaps reconnect the whole connection instead of resubscribing one book. Live .100ms, recorded .raw, omission/opt-out and book reconstruction checks passed.
  • Poloniex: validates book_lv2 lastId → id per data[0].symbol, and snapshots reset the chain, matching recorder. Live, recorded, omission/opt-out and reconstruction checks passed.
  • OKX family: one extractor for public books links prevSeqId → seqId per instId, including inside batches, matching recorder. Authenticated TBT channels are excluded, as in recorder.
  • WhiteBIT: the shared checker replaces the feed's own check (past_update_id → update_id per market, snapshots reset). Recorded coverage starts November 6, so there is no first-of-month sample.
  • MEXC spot / Futures: spot validates fromVersion - 1 → toVersion; Futures validates begin - 1 → end with version fallback, both per symbol, matching recorder. Live, recorded and omission/opt-out checks passed.
  • Lighter / Lighter RH: a shared extractor validates begin_nonce → nonce per channel, and snapshots reset, matching recorder. RH recordings start September 23, so only two first-of-month dates exist.
  • KuCoin Futures: validates level2 data.sequence / sequence - 1 per symbol, matching recorder; live, recorded and omission/opt-out checks passed. Outstanding: stale REST snapshots cause full reconnects (12 in 90 s on 10 contracts); a recorder-style per-symbol retry removed them but is left for a separate PR, decision pending.
  • KuCoin spot: validates trade.l2update sequenceEnd / sequenceStart - 1 per symbol, matching recorder. Live, recorded and omission/opt-out checks passed with no errors or disconnects.
  • Huobi spot: validates MBP prevSeqNum against the previous seqNum per symbol, matching recorder; snapshots do not reset the chain. Live, recorded and omission/opt-out checks passed.
  • Huobi snapshot work (separate PRs): quiet-market initialization, null-snapshot retry, snapshot/update alignment, the 20-update buffer limit, timer cancellation, and snapshot requests above 50 symbols remain open (recorder caps a connection at 50 because of 429s; Node has no cap and was checked with 10). None of them concern sequence validation.
  • WOO X: validates orderbookupdate prevTs → ts per data.s, matching recorder; REST snapshots do not reset the chain. Outstanding (separate PR): the REST snapshot can be older than the first applied update (2 of 9 books live), and neither Node nor recorder checks this alignment.
  • Backpack: depth continuity now uses the shared feed checker (U - 1 → u per symbol), matching recorder. The mapper retains buffering, stale-update suppression and the first live update’s snapshot overlap check, including with validateSequence: false. Native and normalized live checks passed across six spot/perpetual markets. Three release-day slices covered 138,578 depth/snapshot messages; 71,758 normalized messages exactly matched the released mapper, and 36 omission/opt-out controls passed. Public historical API attempts returned HTTP 401 without an API key; recorded slices were replayed through a local HTTP fixture. Multi-date/first-of-month coverage is not yet available.
  • Legacy Huobi options stay outside this migration.

Validation and tracking

Validation (November 17): local Node 26.12.1 npm test passed all 512 tests, including build and test type checks; npm run check-format passed. Backpack live, recorded-data, reconnect, opt-out and receive-path throughput checks passed. Node 24 and the broader RUN_LIVE_TESTS=1 suite were not rerun for this migration. The earlier November 16 GitHub CI passed on Node 24.22.1 and 26.12.1 (492 tests); those results predate the Backpack migration. Each integration has live and recorded-data checks, with the limits noted above.

The workspace plan, plans/tardis-node-realtime-sequence-validation.md, owns detailed per-integration evidence and outstanding work. Keep this description's 42-entry checklist, pending reasons, findings and summary counts synchronized with that plan whenever migration status changes.

- Updated multiple real-time feed classes to include a `validateSequence` parameter in the `_getRealTimeFeeds` method.
- Enhanced the `RealTimeFeedBase` class to handle sequence validation, throwing a `SequenceGapError` when sequence discrepancies are detected.
- Introduced tests for sequence validation, including scenarios for handling gaps, duplicates, and independent keys.
- Adjusted stream functions to support the new `validateSequence` option, ensuring backward compatibility.
@marcinvalas
marcinvalas marked this pull request as draft November 4, 2026 14:24
…mplement sequence handling in real-time feed with corresponding tests
…d enhance sequence handling with corresponding tests
… message types and sequence validation logic
… with sequence handling and add corresponding tests
…lement sequence handling with corresponding tests
…ence handling in real-time feeds with corresponding tests
… with sequence handling and corresponding tests
…sequence handling in MexcFuturesRealTimeFeed
…disconnect handling

- Removed normalization and disconnect handling from KuCoin, MEXC, OKEx, Poloniex, WhiteBIT, and WOO X tests.
- Simplified test cases by eliminating unnecessary complexity while maintaining core functionality.
- Updated assertions to reflect changes in message structure and error handling.
…licit parameters for timeout, error handling, and sequence validation
…licit parameters for timeout, error handling, and sequence validation
…nstead of null across multiple real-time feed classes
@marcinvalas
marcinvalas marked this pull request as ready for review November 17, 2026 12:17
@thaaddeus

Copy link
Copy Markdown
Member

A few add special cases the docs don't have (but our recorder has). I'd remove those so this stays the simple, docs-based check it is meant to be:

  1. Deribit: drop allowOverlap, the pre-snapshot skip and the missing-prev_change_id throw (src/realtimefeeds/deribit.ts:58-83). The docs say the first notification is a snapshot, and every later change must have prev_change_id equal to the previous change_id; on a mismatch, re-subscribe. Over a full day for 8 instruments (6.5M messages), all 57 first changes after a snapshot linked exactly, and no change arrived before a snapshot. The plain rule (previousSequence: type === 'snapshot' ? undefined : prev_change_id) gives the same result. Both rules break only at the 08:00 UTC expiry, where Deribit re-links option books to an older prev_change_id. Reconnecting there is what the docs ask for, so I'd keep it.

  2. Bitvavo: leave getBook out of the chain and drop receivedBookUpdates / resolveSnapshotSequenceId (src/realtimefeeds/bitvavo.ts:16-58). The docs' continuity rule is about book events: each startMdSeqNo follows the previous endMdSeqNo. Over 30 minutes of every market (5.4M events), checking only book events gives 0 breaks, the same as the current code. Resetting the chain on getBook without the extra overlap logic would give 5. Snapshot alignment already lives in the mapper (validateSnapshotOverlap).

  3. Binance delivery: drop the pu === -1 special case (src/realtimefeeds/binance.ts:388 and the throw in onMessage at :400-403). The COIN-M docs only say pu must equal the previous u. With the plain rule, pu: -1 doesn't match, so the connection reconnects as it does now. The one case it misses is pu: -1 as the very first update for a symbol on a connection, and there the book mapper already aligns the first update with the snapshot. The difference is that validateSequence: false would then really turn it off, as the README says.

  4. Bullish: drop getSequence (src/realtimefeeds/bullish.ts:95-103). The docs give no continuity rule for V1TALevel2, and all 427,431 recorded L2 messages on 2026-11-01 are type: "snapshot", each a complete book of up to 200 levels per side. A skipped range loses nothing there, so a reconnect would only cost data.

The rest follow the docs: Binance spot/futures, Aster, Bitget, Bybit, Gemini, Coinbase, Kraken Futures, Delta, Gate.io, HTX, KuCoin, Lighter, MEXC, Poloniex, WhiteBIT and WOO X. None produced a false gap on recorded or live data.

On code style, I'd bring the new getSequence code closer to how feeds are written on master:

  1. Keep message: any with optional chaining. Master feeds read messages as any (message.data?.e === 'depthUpdate'). Here most feeds switch to typed unions with 'x' in message narrowing, which is why 26 message types are now exported from the mapper files, while Binance, Aster and Bitget still use any. One style is enough. With any, the mapper type exports can go and most mappers stay untouched.

  2. Drop the new throws for missing or non-integer fields in Bitvavo (realtimefeeds/bitvavo.ts:18, :50, and mappers/bitvavo.ts:55, :102), WhiteBIT (whitebit.ts:119), Deribit (deribit.ts:70) and KuCoin Futures (kucoinfutures.ts:120). The docs define these fields. If an exchange ever drops one, a throw turns every message into an error and a reconnect. Without the throw, a missing field only skips the check for that message. The MEXC spot guards (mexc.ts:74-80) don't throw, but five conditions for two fields can be one Number(...) conversion each.

  3. Gate.io futures: decide what stays of the old onMessage check (gateiofutures.ts:164-178). The gap rule moved to getSequence, but the rest of the master check (Number.isSafeInteger, u < U, update before snapshot) still throws even with validateSequence: false. Either put it under the flag or keep only the snapshot requirement.

  4. Use the channel or symbol string as the key without parsing it. Huobi (message.ch.split('.')[1]) and Gate.io (message.result.s.split('.')[1]) split a string on every message. On recorded data, with only the key changed to message.ch or message.result.s, the check goes from about 250 ns to 70 ns per message for Huobi, and from about 260–380 ns to about 100 ns for Gate.io. Parsing a message takes about 1 µs and normalizing it about 1.5 µs, so this is not urgent, but the simpler key also reads better.

…g across various mappers and real-time feeds

- Updated DeltaIndia, Deribit, GateIO, GateIOFutures, Gemini, HitBTC, Huobi, Kucoin, KucoinFutures, Lighter, Mexc, MexcFutures, Okex, Poloniex, WhiteBit, and Woox mappers to streamline message type definitions.
- Removed redundant export statements for message types that were not utilized.
- Simplified sequence extraction logic in real-time feeds by using `any` type for message parameters, enhancing flexibility in handling incoming messages.
- Ensured consistent handling of message properties across different exchanges, improving maintainability and readability of the codebase.
…s in Bitvavo, Kucoin, Mexc, and WhiteBit real-time feeds
…Huobi real-time feeds and adjust related tests
@thaaddeus

Copy link
Copy Markdown
Member

Looks good to me, ready merge and release (minor bump).

@thaaddeus

Copy link
Copy Markdown
Member

Just one small thing in ADD_NEW_EXCHANGE.md - let's not mention recorder there.

@marcinvalas
marcinvalas merged commit 2cbb678 into master Nov 20, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants