From 575f7f7d1a208b7a6568b3407f724c8fd30a1e0b Mon Sep 17 00:00:00 2001 From: TalesOfThales <101120927+userFRM@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:02:43 +0100 Subject: [PATCH 1/7] perf(shard): split a one-day bar chain into call and put requests A bounded-interval pull declines the time axis because interval bars accumulate from the request's window start, so a band seam changes bar values. That decline also dropped the right split for chain cross-products, which has no seam: each contract's bars come from its own request over the full window. A one-day chain at 1s or 1m therefore went out as one request, while the same chain over several days split by date. Split a both-rights chain at a bounded interval into one call band and one put band over the whole window. Keep both rights together when the query asks for the out_of_the_money implied-volatility method, which the server refuses on a single right because each strike's volatility comes from the other side; the planner now reads that field from the binomial Greeks queries. --- CHANGELOG.md | 2 + thetadatadx-rs/src/mdds/macros.rs | 3 + thetadatadx-rs/src/mdds/shard.rs | 91 ++++++++++++++++++++++--------- 3 files changed, 71 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6c29854f..fcf0c92ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **A one-day option chain at a bar interval is fetched as two concurrent requests, one for calls and one for puts.** A history pull over every strike and both rights at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. Splitting by right leaves every contract's bars whole, so the SDK now sends the calls and the puts as separate requests over the full window, and a buffered pull merges them into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. Set `bulk_fetch="off"` to send one request in the server's own order. + - **TypeScript streaming callbacks keep up with a higher message rate.** The native side hands events to the Node main thread in arrays instead of waking it once per event, and the package still calls your `startStreaming` callback once per event, in order. On the offline callback benchmark (`thetadatadx-ts/benches/streaming_throughput.mjs`) a no-op callback goes from about 300k to about 460k events a second, and live on the dev replay server the Node main thread is about a fifth less busy at the same message rate. A callback that throws still ends the process at that event unless an `uncaughtException` handler is installed; with one, the handler gets the error and the rest of the events are still delivered. - **The five Greeks tick structs carry `implied_vol_source`, which breaks Rust code that builds or exhaustively destructures them and C or C++ code built against the previous header.** `GreeksAllTick`, `GreeksEodTick`, `GreeksFirstOrderTick`, `GreeksSecondOrderTick` and `GreeksThirdOrderTick` gain `implied_vol_source` and its presence flag `has_implied_vol_source`. In Rust a struct literal or a pattern that names every field has to add both, or `..`. Python and TypeScript only gain a field, `None` or `undefined` where the route does not send it. In C and C++ the new members move the contract identity members that follow them and change the size of the five structs, and `ThetaDataDxEndpointRequestOptions` gains the two new parameters as `const char*` members at its end, so a program built against the previous header would read the wrong bytes; rebuild against the new header. diff --git a/thetadatadx-rs/src/mdds/macros.rs b/thetadatadx-rs/src/mdds/macros.rs index 0743d461b..32dd03c31 100644 --- a/thetadatadx-rs/src/mdds/macros.rs +++ b/thetadatadx-rs/src/mdds/macros.rs @@ -814,6 +814,9 @@ macro_rules! shard_read_field { ($sq:ident, $params:ident, interval) => { $sq.interval = $crate::mdds::shard::opt_wire_str(&$params.interval); }; + ($sq:ident, $params:ident, implied_vol_method) => { + $sq.implied_vol_method = $crate::mdds::shard::opt_wire_str(&$params.implied_vol_method); + }; // NOTE: no `expiration` arm — the top-level `expiration` field on the // option protos is the always-empty legacy slot; the live value rides // in `contract_spec` and is read there. diff --git a/thetadatadx-rs/src/mdds/shard.rs b/thetadatadx-rs/src/mdds/shard.rs index e011d5f30..be3fb1de6 100644 --- a/thetadatadx-rs/src/mdds/shard.rs +++ b/thetadatadx-rs/src/mdds/shard.rs @@ -306,6 +306,8 @@ pub(crate) struct ShardQuery { pub end_time: Option, /// Bar / snapshot interval as issued (`tick`, `1s`, `1m`, ...). pub interval: Option, + /// Implied-volatility method of a binomial Greeks query, when present. + pub implied_vol_method: Option, } // ─── Wire-field projection helpers (used by the endpoint macros) ───────── @@ -432,7 +434,8 @@ pub(crate) enum ShardDecline { /// bar VALUES even when the row count matches; a time-banded pull /// cannot reproduce the single stream. Tick pulls carry no bars and /// time-shard freely; date bands are unaffected (bars re-anchor at - /// each day's own window start either way). + /// each day's own window start either way), and a both-rights chain + /// still splits by right over the whole window. IntervalBars, /// Pull issued from inside this client's own streaming delivery /// handler: the outer pull holds the request pool until the handler @@ -466,7 +469,8 @@ impl ShardDecline { /// fan-out, so sharding cannot win. Chain cross-products and /// tick-interval pulls have no such ceiling and band the range on the /// window alone. (The time axis never gets this far with a bounded -/// interval — [`ShardDecline::IntervalBars`] declines it outright.) +/// interval: it splits a both-rights chain by right over the whole +/// window and declines everything else as [`ShardDecline::IntervalBars`].) const SHARD_MIN_GRID_ROWS: u64 = 10_000_000; /// Minimum wall-clock span of one time band (five minutes). The server @@ -592,9 +596,13 @@ fn chain_cross_product(q: &ShardQuery) -> bool { /// `call` band and a `put` band actually halves the contract set. A chain /// already pinned to one right (`right = "call"` / `"put"` with a strike /// wildcard, or a multi-expiration single-right pull) has nothing to split -/// on this axis and takes the time split instead. +/// on this axis and takes the time split instead. The `out_of_the_money` +/// implied-volatility method reads each strike's volatility from the other +/// side, so the server refuses it on anything but `right = both`. fn splittable_by_right(q: &ShardQuery) -> bool { - chain_cross_product(q) && matches!(q.right.as_deref(), None | Some("both")) + chain_cross_product(q) + && matches!(q.right.as_deref(), None | Some("both")) + && q.implied_vol_method.as_deref() != Some("out_of_the_money") } /// Whether the query is a tick pull (no bar interval). The server accepts a @@ -646,10 +654,10 @@ fn select_axis(q: &ShardQuery) -> Option { /// starts at the query's own `start_time` and the last ends at its /// `end_time`; band durations differ by at most 1 ms. /// -/// Only tick pulls reach this cut: `plan_query` declines the time axis -/// for bounded-interval queries outright, because interval bars -/// accumulate from the request's window start and any mid-window seam -/// would change bar values (see [`ShardDecline::IntervalBars`]). +/// Only tick pulls cut the window into more than one band: interval +/// bars accumulate from the request's window start and any mid-window +/// seam would change bar values (see [`ShardDecline::IntervalBars`]), +/// so a bounded-interval chain takes one whole-window band per right. fn time_bands(start_ms: i64, end_ms: i64, n: i64, right: Option<&str>) -> Vec { let window = end_ms - start_ms + 1; (0..n) @@ -807,8 +815,8 @@ pub(crate) fn auto_plan( /// `auto_plan`): /// an endpoint outside the shardable set, a shape with no cut axis, /// `width < 2`, a window too narrow for two bands of -/// [`MIN_SHARD_BAND_MS`], a bounded-interval pull on the time axis -/// (bar values anchor to the window start — +/// [`MIN_SHARD_BAND_MS`], a bounded-interval pull on the time axis that +/// is not a both-rights chain (bar values anchor to the window start — /// [`ShardDecline::IntervalBars`]), or a bounded-interval /// single-contract date-axis pull whose bar grid provably stays under /// [`SHARD_MIN_GRID_ROWS`]. @@ -851,8 +859,16 @@ fn plan_query(endpoint: &str, q: &ShardQuery, width: usize) -> Result = /// state. Draining is deliberate — cancelling siblings would truncate /// them at arbitrary chunk boundaries, leaving ragged half-delivered /// windows no caller could reason about, while draining leaves exactly -/// the failed bands' windows as the known gaps. The wall-clock cost of -/// draining is bounded by the call's deadline -/// (`run_with_optional_deadline` wraps the whole fan-out), and dropping +/// the failed bands' windows as the known gaps. A sibling drains only +/// while its server keeps sending (the silence limit), a call deadline +/// bounds the whole fan-out (`run_with_optional_deadline`), and dropping /// the join future — the deadline path — still cancels every band at /// once. /// @@ -1950,8 +1966,8 @@ mod tests { // Interval bars accumulate from the request's window start // (cumulative vwap, last-tick carry), so a mid-window band seam // changes bar VALUES even when the row count matches. No - // bounded-interval single-day pull may time-shard — concrete or - // chain alike. + // bounded-interval single-day pull may cut its window — concrete + // or chain alike. let mut concrete = chain_day_query(); concrete.expiration = Some("20260710".into()); concrete.strike = Some("6000".into()); @@ -1964,21 +1980,33 @@ mod tests { // The same contract at tick interval carries no bars and shards. concrete.interval = Some("tick".into()); assert!(plan_query("option_history_quote", &concrete, 8).is_ok()); - // A chain cross-product at a bounded interval is anchored the - // same way: its right-split time bands would re-anchor every - // bar, so it declines too. + // A both-rights chain at a bounded interval splits by right + // only: one band per right over the whole window, so no bar + // loses its anchor. let mut chain = chain_day_query(); chain.interval = Some("1s".into()); + let whole_window = |right: &str| ShardBand::Time { + start_time: "09:30:00.000".into(), + end_time: "16:00:00.000".into(), + right: Some(right.into()), + }; + assert_eq!( + plan_query("option_history_quote", &chain, 8).map(|p| p.bands), + Ok(vec![whole_window("call"), whole_window("put")]) + ); + // The `out_of_the_money` volatility method reads the other side, + // so that chain stays whole. + chain.implied_vol_method = Some("out_of_the_money".into()); assert_eq!( - plan_query("option_history_quote", &chain, 8), + plan_query("option_history_binomial_greeks_first_order", &chain, 8), Err(ShardDecline::IntervalBars) ); - // An unrecognized interval spelling errs toward the single - // stream — it may well be a bar interval to the server, and a - // fan-out is only ever a performance transform. - chain.interval = Some("weird".into()); + chain.implied_vol_method = None; + // An unrecognized interval spelling errs toward bars: it may well + // be a bar interval to the server, so the window stays whole. + concrete.interval = Some("weird".into()); assert_eq!( - plan_query("option_history_quote", &chain, 8), + plan_query("option_history_quote", &concrete, 8), Err(ShardDecline::IntervalBars) ); // The tick chain keeps the headline call/put fan-out. @@ -2373,6 +2401,19 @@ mod tests { }, ] ); + // The server refuses `out_of_the_money` on one right, so that + // chain keeps both rights in every band. + let q = ShardQuery { + implied_vol_method: Some("out_of_the_money".into()), + ..q + }; + let plan = plan_query("option_history_binomial_greeks_first_order", &q, 8) + .expect("chain should still date-shard"); + assert!( + plan.bands + .iter() + .all(|b| matches!(b, ShardBand::Date { right: None, .. })) + ); } #[test] From f5551e045c267084b8015fb989e6ee922a9bc723 Mon Sep 17 00:00:00 2001 From: TalesOfThales <101120927+userFRM@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:02:43 +0100 Subject: [PATCH 2/7] fix(mdds): bound a request without a deadline by server silence request_timeout_secs wrapped the whole request in one timeout, the wait for a request permit included. The server prepares a large response before its first byte and then streams it for as long as the rows take, so a healthy pull that was still streaming failed at five minutes, and a request queued behind a full pool spent its time waiting. A request that sets no deadline now has no total limit. The configured seconds bound how long the server may stay silent: the open, and then each next message, through the same stall guard flat-file downloads use. A stall fails as a DeadlineExceeded status, which the retry policy treats as transient. An explicit per-call deadline still bounds the whole call, and zero still lifts every limit. --- CHANGELOG.md | 2 + .../include/config_accessors.h.inc | 6 +- .../include/config_accessors.hpp.inc | 6 +- thetadatadx-py/examples/chain_quote_bench.py | 4 - .../python/thetadatadx/__init__.pyi | 4 +- thetadatadx-rs/config.default.toml | 8 +- thetadatadx-rs/examples/chain_quote_bench.rs | 4 - thetadatadx-rs/src/config/mdds.rs | 50 ++-- thetadatadx-rs/src/config/mod.rs | 2 +- thetadatadx-rs/src/grpc/channel.rs | 11 +- thetadatadx-rs/src/grpc/mod.rs | 8 +- thetadatadx-rs/src/mdds/endpoint_args.rs | 64 +++--- thetadatadx-rs/src/mdds/macros.rs | 215 ++++++------------ thetadatadx-rs/src/mdds/stream.rs | 87 ++++--- thetadatadx-rs/src/surface/config.rs | 6 +- thetadatadx-rs/tests/common/grpc_mock.rs | 13 +- thetadatadx-rs/tests/test_endpoint_routing.rs | 126 ++++++---- thetadatadx-ts/examples/chain_quote_bench.ts | 5 +- thetadatadx-ts/index.d.ts | 6 +- 19 files changed, 304 insertions(+), 323 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fcf0c92ea..edad1e373 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **A market-data request without its own deadline is no longer cut off after five minutes.** `request_timeout_secs` (default 300) bounded the whole request, so a large pull that was still streaming, such as a day of one-second quotes across an option chain, failed part way with a deadline error, and a request waiting for a free slot in the request pool spent its time there. It now bounds only how long the server may stay silent: for the response to start, and then between two messages. A pull that keeps streaming runs to completion, through the local server and the MCP server too, while a stalled one still fails, now as a `DeadlineExceeded` status that the retry policy treats as transient, as a flat-file download already did. A per-call deadline (`with_deadline` in Rust, `timeout_ms` elsewhere) still bounds the whole call, and 0 still lifts every limit. Migration: Rust code that matched `Error::Timeout` for the configured limit should match `Error::Grpc { kind: GrpcStatusKind::DeadlineExceeded, .. }`. Python, TypeScript, C and C++ report a stall as the same `DeadlineExceededError` (`THETADATADX_ERR_DEADLINE_EXCEEDED`) as before. + - **A subscribe larger than the command queue no longer fails part way.** One `subscribe_many` (`subscribeMany` in TypeScript) over a whole option chain, such as SPXW quotes and trades within 10% of spot (19,228 streams), could fail with "command queue full" and leave the session subscribed to only part of the list. Subscribe and unsubscribe now wait while the queue to the streaming connection is full, so a call of any size goes through, in every language. The error is returned only if the connection takes no commands for longer than its read timeout. - **A large subscribe no longer spends seconds on bookkeeping.** Each subscribe searched every subscription already made and swept every unanswered one, so one `subscribe_many` over a whole option chain took time that grew with the square of its size, seconds of CPU on the calling thread for the 19,228-stream SPXW chain. Both lookups are now constant time, and the same subscribe takes milliseconds. In Rust, `SubscriptionKind` now implements `Hash`. diff --git a/thetadatadx-cpp/include/config_accessors.h.inc b/thetadatadx-cpp/include/config_accessors.h.inc index 85cde260b..b348762ab 100644 --- a/thetadatadx-cpp/include/config_accessors.h.inc +++ b/thetadatadx-cpp/include/config_accessors.h.inc @@ -272,14 +272,14 @@ void thetadatadx_config_set_warn_on_buffered_threshold_bytes(ThetaDataDxConfig* */ int32_t thetadatadx_config_get_warn_on_buffered_threshold_bytes(const ThetaDataDxConfig* config, size_t* out_n); -/** Set the default per-request deadline (seconds) for market-data queries. +/** Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. * - * It bounds every request that did not set its own deadline, so a live-but-silent stream resolves to a timeout instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the deadline: it is floored to the 300-second default at request time, so the deadline always applies. + * A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. * Default `300` (5 minutes). */ void thetadatadx_config_set_request_timeout_secs(ThetaDataDxConfig* config, uint64_t secs); -/** Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the deadline. +/** Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit. * Default `300` (5 minutes). * * Writes the value into `*out`. Returns `0` on success, `-1` if either pointer is null. diff --git a/thetadatadx-cpp/include/config_accessors.hpp.inc b/thetadatadx-cpp/include/config_accessors.hpp.inc index e7907eba2..52f3e5a3f 100644 --- a/thetadatadx-cpp/include/config_accessors.hpp.inc +++ b/thetadatadx-cpp/include/config_accessors.hpp.inc @@ -349,15 +349,15 @@ return out; } - /// Set the default per-request deadline (seconds) for market-data queries. + /// Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. /// - /// It bounds every request that did not set its own deadline, so a live-but-silent stream resolves to a timeout instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the deadline: it is floored to the 300-second default at request time, so the deadline always applies. + /// A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. /// Default `300` (5 minutes). void set_request_timeout_secs(std::uint64_t secs) { thetadatadx_config_set_request_timeout_secs(handle_.get(), secs); } - /// Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the deadline. + /// Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit. /// Default `300` (5 minutes). /// /// Returns `0` on a null handle. diff --git a/thetadatadx-py/examples/chain_quote_bench.py b/thetadatadx-py/examples/chain_quote_bench.py index 3f876b080..082211b73 100644 --- a/thetadatadx-py/examples/chain_quote_bench.py +++ b/thetadatadx-py/examples/chain_quote_bench.py @@ -154,9 +154,6 @@ def on_chunk(chunk: QuoteTickList) -> None: file=sys.stderr, ) - # A full-day 0DTE pull can run 6-15 minutes; the config default - # request_timeout_secs (300 s) would kill it, so opt out of any deadline - # with timeout_ms=0 (normalized to "no deadline" by effective_deadline). try: ( client.option_history_quote_builder(symbol, expiration) @@ -164,7 +161,6 @@ def on_chunk(chunk: QuoteTickList) -> None: .right("both") .date(date) .interval(interval) - .timeout_ms(0) .stream(on_chunk) ) except Exception as e: # noqa: BLE001 diff --git a/thetadatadx-py/python/thetadatadx/__init__.pyi b/thetadatadx-py/python/thetadatadx/__init__.pyi index 115758ec9..0c2250cf0 100644 --- a/thetadatadx-py/python/thetadatadx/__init__.pyi +++ b/thetadatadx-py/python/thetadatadx/__init__.pyi @@ -301,9 +301,9 @@ class Config: Default ``104_857_600`` (100 MiB). """ request_timeout_secs: int - """Set the default per-request deadline (seconds) for market-data queries. + """Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. - It bounds every request that did not set its own deadline, so a live-but-silent stream resolves to a timeout instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the deadline: it is floored to the 300-second default at request time, so the deadline always applies. + A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. Default ``300`` (5 minutes). """ market_data_stream_window_size_kb: int diff --git a/thetadatadx-rs/config.default.toml b/thetadatadx-rs/config.default.toml index a3017619d..bd7a73181 100644 --- a/thetadatadx-rs/config.default.toml +++ b/thetadatadx-rs/config.default.toml @@ -40,9 +40,11 @@ max_message_size = 4194304 # gRPC connect timeout (seconds). Default 10. Validated to [1, 300]. # connect_timeout_secs = 10 -# Per-request market-data deadline (seconds). Default 300. A 0 is floored to -# 300 at request time, so a silent server cannot hang a request; opt a single -# request out with with_deadline(0) instead. Not range-limited. +# How long a market-data request may wait on a silent server (seconds), for +# the response to start and then for each next message; a request that keeps +# streaming has no total limit. Default 300. A 0 is floored to 300 at request +# time, so a silent server cannot hang a request; opt a single request out +# with with_deadline(0) instead. Not range-limited. # request_timeout_secs = 300 # Buffered-response size (bytes) above which a warning is logged. Default diff --git a/thetadatadx-rs/examples/chain_quote_bench.rs b/thetadatadx-rs/examples/chain_quote_bench.rs index b7b404732..a65f8e7b3 100644 --- a/thetadatadx-rs/examples/chain_quote_bench.rs +++ b/thetadatadx-rs/examples/chain_quote_bench.rs @@ -151,16 +151,12 @@ async fn main() -> ExitCode { // excludes connect/auth and measures backend-to-first-chunk latency. let dispatch = Instant::now(); let handler_progress = progress.clone(); - // A full-day 0DTE pull can run 6-15 minutes; the config default - // `request_timeout_secs` (300 s) would kill it, so opt out of any deadline - // with `Duration::ZERO` (normalized to "no deadline" by `effective_deadline`). let stream_result = client .option_history_quote_stream(&symbol, &expiration) .date(&date) .strike("*") .right("both") .interval(&interval) - .with_deadline(Duration::ZERO) .stream(move |ticks| { let mut p = handler_progress.lock().expect("progress mutex poisoned"); if p.ttfb.is_none() { diff --git a/thetadatadx-rs/src/config/mdds.rs b/thetadatadx-rs/src/config/mdds.rs index d954dce12..66dc72746 100644 --- a/thetadatadx-rs/src/config/mdds.rs +++ b/thetadatadx-rs/src/config/mdds.rs @@ -11,13 +11,12 @@ //! See `docs-site/docs/configuration.md` for the per-binding setter //! samples. -/// Default per-request market-data deadline in seconds (5 min). +/// Default market-data silence limit in seconds (5 min). /// -/// The floor the effective-deadline resolver applies when a caller leaves the -/// per-request deadline unset AND the configured `request_timeout_secs` is `0`: -/// a `0` there would disable the gRPC hang guard for every deadline-less -/// request, so a live-but-silent server could hang the client forever. Sits -/// above the slowest realistic bulk pull. The per-call +/// The floor the request-limit resolver applies when the configured +/// `request_timeout_secs` is `0`: a `0` there would disable the gRPC hang +/// guard for every request without its own deadline, so a live-but-silent +/// server could hang the client forever. The per-call /// `with_deadline(Duration::ZERO)` opt-out is a separate, explicit path and is /// unaffected by this floor. pub(crate) const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 300; @@ -152,28 +151,31 @@ pub struct MarketDataConfig { /// cadence. pub connect_timeout_secs: u64, - /// Default per-request deadline for market-data (gRPC) queries, in - /// seconds. + /// How long a market-data (gRPC) request may wait on a silent server, + /// in seconds: for the response to start, and then for each next + /// message. /// - /// A server that holds the HTTP/2 stream open while sending no - /// chunks would otherwise hang `collect_stream` / `stream(...)` - /// indefinitely: the gRPC keepalive PING only detects a fully dead - /// peer, not a live-but-silent one. This default bounds every - /// request that did not call `with_deadline(...)`, so a stalled - /// stream resolves to `Error::Timeout` instead of blocking forever. + /// A request without its own deadline has no limit on its total + /// length, since the server prepares a large response before its + /// first byte and then streams it for as long as it takes. A server + /// that holds the HTTP/2 stream open while sending nothing would + /// otherwise hang the request indefinitely: the gRPC keepalive PING + /// only detects a fully dead peer, not a live-but-silent one. Past + /// this limit the attempt fails as a `DeadlineExceeded` stall, which + /// the retry policy treats as transient. /// - /// Configuring `0` here does **not** disable the guard: the effective- - /// deadline resolver every market-data request routes through floors a `0` - /// to the production default (`300s`) so a deadline-less request can never - /// hang the client forever, regardless of whether the config was validated. - /// Opt a single request out with the per-call escape hatch instead. + /// Configuring `0` here does **not** disable the guard: the request- + /// limit resolver every market-data request routes through floors a `0` + /// to the production default (`300s`), regardless of whether the config + /// was validated. Opt a single request out with the per-call escape + /// hatch instead. /// - /// Per-call control overrides this: `with_deadline(Duration)` sets a - /// shorter or longer bound, and `with_deadline(Duration::ZERO)` - /// opts a single request out of any deadline. + /// Per-call control overrides this: `with_deadline(Duration)` bounds + /// the whole request instead, and `with_deadline(Duration::ZERO)` + /// lifts every limit for that request. /// - /// Default `300s` (5 min) — comfortably above the slowest realistic - /// multi-million-row bulk pull while still bounding a wedged stream. + /// Default `300s` (5 min): a server that is preparing a response + /// answers well inside it, and a wedged stream still fails. pub request_timeout_secs: u64, /// Estimated-bytes threshold above which the buffered `.await` diff --git a/thetadatadx-rs/src/config/mod.rs b/thetadatadx-rs/src/config/mod.rs index 8beacf9e6..2f2a2d844 100644 --- a/thetadatadx-rs/src/config/mod.rs +++ b/thetadatadx-rs/src/config/mod.rs @@ -1028,7 +1028,7 @@ impl DirectConfig { } // NOTE: a `0` market-data `request_timeout_secs` is NOT floored here. // The floor lives at the single consumption point - // ([`crate::mdds::macros::effective_deadline`]) so the gRPC hang guard + // ([`crate::mdds::macros::request_limits`]) so the gRPC hang guard // holds even for callers who never run `validate` — the connect paths // and the SDK bindings pass unvalidated config snapshots. Flooring only // here would leave those paths exposed. diff --git a/thetadatadx-rs/src/grpc/channel.rs b/thetadatadx-rs/src/grpc/channel.rs index f1bde6899..69443da57 100644 --- a/thetadatadx-rs/src/grpc/channel.rs +++ b/thetadatadx-rs/src/grpc/channel.rs @@ -521,12 +521,13 @@ impl Channel { /// Returns a [`ChannelError`] when the request cannot be built or /// the RPC fails to open. /// - /// A request carries no deadline of its own. The caller's deadline is - /// applied a layer up, where `crate::mdds::macros` wraps the whole + /// A request carries no deadline of its own. The caller's limits are + /// applied a layer up, in `crate::mdds`: a deadline wraps the whole /// dispatch (this open phase, the response stream and any retry) in - /// one `tokio::time::timeout` and surfaces `Error::Timeout`. Dropping - /// the returned stream on expiry sends RST_STREAM, so the server - /// releases its side either way. + /// one `tokio::time::timeout` and surfaces `Error::Timeout`, and the + /// silence limit bounds this open and each next message. Dropping the + /// returned stream on expiry sends RST_STREAM, so the server releases + /// its side either way. pub async fn server_streaming( &self, method: &'static str, diff --git a/thetadatadx-rs/src/grpc/mod.rs b/thetadatadx-rs/src/grpc/mod.rs index 3830073a7..121912df0 100644 --- a/thetadatadx-rs/src/grpc/mod.rs +++ b/thetadatadx-rs/src/grpc/mod.rs @@ -51,10 +51,10 @@ //! [`ChannelError::H2Stream`]; the connection itself is healthy and //! the next RPC on the same channel can succeed. //! -//! A per-call deadline is not this module's business: `crate::mdds` -//! wraps a whole dispatch in one timeout and reports `Error::Timeout`, -//! and dropping the stream sends RST_STREAM so the server releases its -//! side. +//! Time limits are not this module's business: `crate::mdds` wraps a +//! whole dispatch in the caller's deadline and reports `Error::Timeout`, +//! or bounds each wait on a silent server, and dropping the stream sends +//! RST_STREAM so the server releases its side. // Sub-modules carry transport infrastructure consumed only by the // crate itself and by `__test-helpers`-gated integration tests. diff --git a/thetadatadx-rs/src/mdds/endpoint_args.rs b/thetadatadx-rs/src/mdds/endpoint_args.rs index b7e5c3a2d..1aecec45d 100644 --- a/thetadatadx-rs/src/mdds/endpoint_args.rs +++ b/thetadatadx-rs/src/mdds/endpoint_args.rs @@ -57,21 +57,21 @@ pub enum EndpointArgValue { /// deadline" from "the caller explicitly disabled the deadline" — both /// collapse to `None`. That ambiguity makes `with_timeout_ms(0)` silently /// fall back to the configured -/// [`crate::config::MarketDataConfig::request_timeout_secs`] default instead -/// of opting the call out of any deadline. This tri-state keeps the two -/// intents distinct so the generated dispatch can honour each: +/// [`crate::config::MarketDataConfig::request_timeout_secs`] silence limit +/// instead of opting the call out of every limit. This tri-state keeps the +/// two intents distinct so the generated dispatch can honour each: /// -/// | Variant | Source | Effect on the dispatched call | -/// |--------------|-------------------------|----------------------------------------------------------------| -/// | `Unset` | no `with_timeout_ms` | fall back to the configured `request_timeout_secs` default | -/// | `Disabled` | `with_timeout_ms(0)` | no deadline — the call runs unbounded (the documented opt-out) | -/// | `Millis(n)` | `with_timeout_ms(n>0)` | a per-call deadline of `n` milliseconds | +/// | Variant | Source | Effect on the dispatched call | +/// |--------------|-------------------------|-----------------------------------------------------------------------| +/// | `Unset` | no `with_timeout_ms` | no deadline; fails only after `request_timeout_secs` of silence | +/// | `Disabled` | `with_timeout_ms(0)` | no limit at all: the call runs unbounded (the documented opt-out) | +/// | `Millis(n)` | `with_timeout_ms(n>0)` | a per-call deadline of `n` milliseconds on the whole call | /// /// Only present when the `__internal` feature is enabled. #[cfg(feature = "__internal")] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum DeadlineSetting { - /// No per-call deadline was set; fall back to the configured default. + /// No per-call deadline was set; the configured silence limit applies. #[default] Unset, /// The deadline was explicitly disabled (`with_timeout_ms(0)`); the @@ -87,12 +87,12 @@ impl DeadlineSetting { /// dispatch applies to an endpoint builder via `with_deadline`. /// /// - [`Self::Unset`] → `None`: the dispatch must NOT call `with_deadline`, - /// so the builder falls back to the configured `request_timeout_secs` - /// default. + /// so the builder keeps the configured `request_timeout_secs` silence + /// limit. /// - [`Self::Disabled`] → `Some(Duration::ZERO)`: an explicit zero, which /// `with_deadline` carries through to - /// [`crate::mdds::macros::effective_deadline`] where it disables the - /// deadline entirely (the call runs unbounded). + /// [`crate::mdds::macros::request_limits`] where it lifts every limit + /// (the call runs unbounded). /// - [`Self::Millis`] → `Some(Duration::from_millis(n))`: the explicit /// per-call bound. #[must_use] @@ -140,9 +140,9 @@ impl EndpointArgs { /// `ms == 0` is the deadline opt-out: it records /// [`DeadlineSetting::Disabled`] so the dispatched call runs unbounded. /// This is distinct from never calling `with_timeout_ms` at all - /// ([`DeadlineSetting::Unset`]), which falls back to the configured - /// [`crate::config::MarketDataConfig::request_timeout_secs`] default. A - /// positive `ms` records [`DeadlineSetting::Millis`]. + /// ([`DeadlineSetting::Unset`]), which keeps the configured + /// [`crate::config::MarketDataConfig::request_timeout_secs`] silence + /// limit. A positive `ms` records [`DeadlineSetting::Millis`]. #[must_use] pub fn with_timeout_ms(mut self, ms: u64) -> Self { self.set_timeout_ms(ms); @@ -535,8 +535,8 @@ pub enum EndpointOutput { /// threads [`EndpointArgs::deadline_setting`] onto the endpoint builder via /// `with_deadline`. The builder is the single deadline authority, so the /// three deadline intents are honoured exactly: [`DeadlineSetting::Unset`] -/// falls back to the configured -/// [`crate::config::MarketDataConfig::request_timeout_secs`] default, +/// keeps the configured +/// [`crate::config::MarketDataConfig::request_timeout_secs`] silence limit, /// [`DeadlineSetting::Disabled`] (`with_timeout_ms(0)`) runs unbounded, and /// [`DeadlineSetting::Millis`] applies the explicit per-call bound. On expiry /// the in-flight future is dropped — its locals (`_permit`, @@ -886,8 +886,8 @@ mod tests { /// `timeout_ms == 0` is the deadline opt-out: it records `Disabled`, a /// state distinct from `Unset`. The generated dispatch reads /// `deadline_setting()` to tell them apart — `Disabled` runs the call - /// unbounded while `Unset` falls back to the configured - /// `request_timeout_secs` default. + /// unbounded while `Unset` keeps the configured `request_timeout_secs` + /// silence limit. #[test] fn with_timeout_ms_zero_records_disabled() { let args = EndpointArgs::new().with_timeout_ms(0); @@ -911,9 +911,9 @@ mod tests { /// The tri-state maps to the builder deadline the generated dispatch /// applies. This is the crux of the registry/FFI opt-out fix: `Unset` - /// must NOT apply a deadline (the builder keeps the configured default), + /// must NOT apply a deadline (the builder keeps the configured limit), /// `Disabled` must apply an explicit `Duration::ZERO` (which - /// `with_deadline` / `effective_deadline` resolve to "no deadline"), and + /// `with_deadline` / `request_limits` resolve to no limit at all), and /// `Millis(n)` must apply that exact bound. #[test] fn deadline_setting_maps_to_builder_deadline() { @@ -927,21 +927,21 @@ mod tests { DeadlineSetting::Millis(250).builder_deadline(), Some(Duration::from_millis(250)) ); - // The disabled builder deadline must route through effective_deadline - // to "no deadline" even against a positive configured default, so the - // opt-out actually holds end-to-end. + // The disabled builder deadline must route through request_limits + // to no limit at all even against a positive configured limit, so + // the opt-out actually holds end-to-end. let disabled = DeadlineSetting::Disabled.builder_deadline(); assert_eq!( - crate::mdds::macros::effective_deadline(disabled, 300), - None, - "with_timeout_ms(0) must disable the deadline, not fall back to the default" + crate::mdds::macros::request_limits(disabled, 300), + (None, None), + "with_timeout_ms(0) must lift every limit, not fall back to the configured one" ); - // Unset routes to the configured default. + // Unset routes to the configured silence limit. let unset = DeadlineSetting::Unset.builder_deadline(); assert_eq!( - crate::mdds::macros::effective_deadline(unset, 300), - Some(Duration::from_secs(300)), - "an unset deadline must fall back to the configured default" + crate::mdds::macros::request_limits(unset, 300), + (None, Some(Duration::from_secs(300))), + "an unset deadline must keep the configured silence limit" ); } diff --git a/thetadatadx-rs/src/mdds/macros.rs b/thetadatadx-rs/src/mdds/macros.rs index 32dd03c31..39955d2dd 100644 --- a/thetadatadx-rs/src/mdds/macros.rs +++ b/thetadatadx-rs/src/mdds/macros.rs @@ -14,48 +14,44 @@ //! `_permit` releases the request-semaphore slot, the tonic `Streaming` is //! dropped (RST_STREAM on the underlying H2 stream), and the call returns //! `Err(Error::Timeout { duration_ms })`. The `MarketDataClient` is unaffected; -//! a subsequent call on the same handle succeeds. +//! a subsequent call on the same handle succeeds. A call that sets no +//! deadline has none; it fails only when the server falls silent (see +//! [`request_limits`]). -/// Resolve the effective per-request deadline. +/// Resolve one market-data call's time limits, as `(deadline, idle)`. /// -/// An explicit `with_deadline(...)` always wins, including -/// `with_deadline(Duration::ZERO)` which means "disable the deadline" and -/// opts the request out of any deadline. A zero `explicit` duration is -/// normalized to `None` here so the opt-out holds on every endpoint — -/// letting a zero `Duration` reach [`tokio::time::timeout`] would fire on -/// the first poll and time the call out instantly, the opposite of the -/// documented contract. When the caller set nothing (`explicit == None`), -/// fall back to the configured -/// [`crate::config::MarketDataConfig::request_timeout_secs`] default so a -/// server holding the stream open without sending chunks cannot hang the -/// request indefinitely. +/// An explicit `with_deadline(d)` bounds the whole call, and +/// `with_deadline(Duration::ZERO)` lifts every limit: a zero `explicit` is +/// normalized to `(None, None)` here so the opt-out holds on every +/// endpoint, since a zero `Duration` reaching [`tokio::time::timeout`] +/// would fire on the first poll. A call that sets nothing has no +/// deadline: the server prepares a large response before its first byte +/// and then streams it for as long as it takes, so a wall-clock bound +/// would cut off healthy pulls. It fails instead when the server sends +/// nothing for the configured +/// [`crate::config::MarketDataConfig::request_timeout_secs`], before the +/// response or between two messages, which a live but silent server +/// cannot otherwise be told from a slow one. /// -/// A configured default of `0` does NOT disable the fallback: it is floored to -/// the production default here — the single -/// point every market-data request routes through — so the gRPC hang guard -/// holds regardless of whether [`crate::config::DirectConfig::validate`] ran -/// on the config (the connect paths and the SDK bindings pass unvalidated -/// snapshots). The only way to run a request with no deadline is the explicit -/// per-call `with_deadline(Duration::ZERO)` opt-out above. -pub(crate) fn effective_deadline( +/// A configured `0` is floored to the production default here, the single +/// point every market-data request routes through, so the guard holds +/// whether or not [`crate::config::DirectConfig::validate`] ran on the +/// config (the connect paths and the SDK bindings pass unvalidated +/// snapshots). +pub(crate) fn request_limits( explicit: Option, - default_secs: u64, -) -> Option { + idle_secs: u64, +) -> (Option, Option) { match explicit { - // An explicit zero is the deadline opt-out: normalize to "no - // deadline" rather than a zero-length timeout that fires at once. - Some(d) if d.is_zero() => None, - Some(d) => Some(d), - // Unset: fall back to the configured default, flooring a `0` (which - // would otherwise disable the guard) to the terminal-safe default so a - // silent-but-live server cannot hang a deadline-less request forever. + Some(d) if d.is_zero() => (None, None), + Some(d) => (Some(d), None), None => { - let secs = if default_secs == 0 { + let secs = if idle_secs == 0 { crate::config::DEFAULT_REQUEST_TIMEOUT_SECS } else { - default_secs + idle_secs }; - Some(std::time::Duration::from_secs(secs)) + (None, Some(std::time::Duration::from_secs(secs))) } } } @@ -620,7 +616,7 @@ fn classify_error(err: &crate::error::Error) -> StatusClass { /// (through `IntoFuture`) runs [`MarketDataClient::fetch_list`], which drops /// the in-flight gRPC call on expiry and returns `Err(Error::Timeout)`. A /// caller who sets nothing sends the SSOT defaults under the configured -/// [`crate::config::MarketDataConfig::request_timeout_secs`] deadline. +/// [`crate::config::MarketDataConfig::request_timeout_secs`] silence limit. macro_rules! list_endpoint { ( $(#[$meta:meta])* @@ -646,9 +642,9 @@ macro_rules! list_endpoint { /// Apply a per-call deadline. /// - /// `Duration::ZERO` disables the deadline, including the - /// configured `request_timeout_secs` default. Same contract as - /// the parsed builders. + /// `Duration::ZERO` lifts every limit, including the + /// configured `request_timeout_secs` silence limit. Same + /// contract as the parsed builders. #[must_use] pub fn with_deadline(mut self, duration: std::time::Duration) -> Self { self.deadline = Some(duration); @@ -934,20 +930,21 @@ macro_rules! parsed_endpoint { /// underlying `MarketDataClient` is unaffected; subsequent calls /// on the same handle succeed. /// - /// `Duration::ZERO` means "disable the deadline": it opts the - /// call out of any bound, including the configured - /// `request_timeout_secs` default. The explicit zero is carried - /// through to [`effective_deadline`], which normalizes it to "no - /// deadline" — leaving it to fall back to the configured default - /// (the behaviour of an unset deadline) would make the opt-out - /// silently impose a bound. Pass a positive `Duration` (e.g. + /// Without one the call has no deadline and fails only when + /// the server sends nothing for the configured + /// `request_timeout_secs`. `Duration::ZERO` lifts that limit + /// too. The explicit zero is carried through to + /// [`request_limits`], which resolves it to no limit at all; + /// leaving it to fall back to the configured limit (the + /// behaviour of an unset deadline) would make the opt-out + /// silently impose one. Pass a positive `Duration` (e.g. /// `Duration::from_millis(1)`) for a near-instant expiration. #[must_use] pub fn with_deadline(mut self, duration: std::time::Duration) -> Self { // Carry the value through verbatim — including `ZERO`. A // bare `None` here means "caller set nothing" and routes to - // the configured default; an explicit `ZERO` must instead - // disable the deadline, which `effective_deadline` resolves. + // the configured limit; an explicit `ZERO` must instead + // lift every limit, which `request_limits` resolves. self.deadline = Some(duration); self } @@ -1018,9 +1015,8 @@ macro_rules! parsed_endpoint { /// at all, in which case the underlying error surfaces /// unchanged like a single-stream failure. Dropping the /// future (the deadline path) still cancels every band; - /// on a very large pull, size `with_deadline` (or the - /// configured `request_timeout_secs`) to the whole pull, - /// since it also bounds the sibling drain after a band + /// on a very large pull, size `with_deadline` to the whole + /// pull, since it also bounds the sibling drain after a band /// failure. For the single stream's exact chunk order, use /// the buffered `.await` (which merges) or set /// [`bulk_fetch = Off`](crate::config::BulkFetchPolicy::Off). @@ -1217,16 +1213,16 @@ macro_rules! stream_endpoint { /// On expiry the in-flight gRPC stream is cancelled and the /// `stream(...)` call resolves to `Err(Error::Timeout)`. The /// underlying `MarketDataClient` is unaffected; subsequent calls on - /// the same handle succeed. `Duration::ZERO` opts the call out of any - /// bound, including the configured `request_timeout_secs` default; the - /// explicit zero is carried through verbatim and resolved by - /// `effective_deadline`. + /// the same handle succeed. Without one the call fails only when the + /// server sends nothing for the configured `request_timeout_secs`. + /// `Duration::ZERO` lifts that limit too; the explicit zero is carried + /// through verbatim and resolved by `request_limits`. #[must_use] pub fn with_deadline(mut self, duration: std::time::Duration) -> Self { // Carry the value through verbatim, including `ZERO`. A bare // `None` means "caller set nothing" and routes to the configured - // default; an explicit `ZERO` must instead disable the deadline, - // which `effective_deadline` resolves. + // limit; an explicit `ZERO` must instead lift every limit, + // which `request_limits` resolves. self.deadline = Some(duration); self } @@ -1286,9 +1282,8 @@ macro_rules! stream_endpoint { /// which case the underlying error surfaces unchanged like a /// single-stream failure. Dropping the future (the deadline path) /// still cancels every band; on a very large pull, size - /// `with_deadline` (or the configured `request_timeout_secs`) to - /// the whole pull, since it also bounds the sibling drain after a - /// band failure. For the single stream's exact chunk order, use the + /// `with_deadline` to the whole pull, since it also bounds the + /// sibling drain after a band failure. For the single stream's exact chunk order, use the /// buffered sibling builder (which merges) or set /// [`bulk_fetch = Off`](crate::config::BulkFetchPolicy::Off). /// Small pulls never shard. @@ -1553,91 +1548,31 @@ mod classify_error_tests { } #[cfg(test)] -mod effective_deadline_tests { - use super::{effective_deadline, run_with_optional_deadline}; +mod request_limits_tests { + use super::request_limits; use std::time::Duration; - /// With no explicit `with_deadline(...)`, the configured default is - /// applied. This is the load-bearing assertion that a request which - /// set no deadline still gets one, so a server holding the stream - /// open without sending chunks cannot hang the call forever. - #[test] - fn applies_configured_default_when_caller_set_none() { - assert_eq!( - effective_deadline(None, 300), - Some(Duration::from_secs(300)) - ); - } - - /// An explicit deadline always wins over the configured default. - #[test] - fn explicit_deadline_overrides_default() { - assert_eq!( - effective_deadline(Some(Duration::from_secs(5)), 300), - Some(Duration::from_secs(5)) - ); - } - - /// A configured default of `0` is FLOORED to the production default - /// rather than disabling the guard: a deadline-less request must never be - /// left unbounded just because the config carried a `0` (validated or - /// not). This is the single consumption-point floor — the only way to run - /// a request with no deadline is the explicit `with_deadline(Duration::ZERO)` - /// opt-out (covered separately), NOT a `0` in the config. - #[test] - fn zero_default_is_floored_to_the_production_default() { - assert_eq!( - effective_deadline(None, 0), - Some(Duration::from_secs( - crate::config::DEFAULT_REQUEST_TIMEOUT_SECS - )), - ); - } - - /// The production default seeds a positive per-request deadline, so - /// the market-data request path is bounded out of the box. #[test] - fn production_default_is_positive() { - let cfg = crate::config::MarketDataConfig::production_defaults(); - assert!(cfg.request_timeout_secs > 0); - assert_eq!( - effective_deadline(None, cfg.request_timeout_secs), - Some(Duration::from_secs(cfg.request_timeout_secs)) - ); - } - - /// An explicit `Duration::ZERO` is the deadline opt-out and must - /// normalize to `None` even when a positive configured default is in - /// force — the explicit zero wins over the fallback. Letting the zero - /// flow through would wrap the call in `timeout(ZERO, ..)` and fire on - /// the first poll, breaking the advertised opt-out on every list - /// endpoint. - #[test] - fn explicit_zero_disables_deadline_over_configured_default() { - assert_eq!(effective_deadline(Some(Duration::ZERO), 300), None); - } - - /// End-to-end guard for the list-endpoint deadline contract: the - /// builder's `with_deadline` resolves its deadline via `effective_deadline`, - /// so an explicit `Duration::ZERO` must yield `None` and the wrapped - /// future must run to completion rather than timing out on the first - /// poll. Drive a future that only resolves after a real `await` point - /// to prove the opt-out actually disables the timeout. - #[tokio::test] - async fn explicit_zero_deadline_runs_to_completion() { - let deadline = effective_deadline(Some(Duration::ZERO), 300); - assert_eq!(deadline, None, "explicit zero must disable the deadline"); - let out: Result = run_with_optional_deadline(deadline, async { - // Yield once so a zero-length timeout would have a poll to - // fire on before this resolves. - tokio::task::yield_now().await; - Ok(7) - }) - .await; - assert!( - matches!(out, Ok(7)), - "an explicit-zero deadline must let the call complete, got {out:?}" - ); + fn request_limits_resolve_every_deadline_setting() { + let secs = Duration::from_secs; + let floor = secs(crate::config::DEFAULT_REQUEST_TIMEOUT_SECS); + for (explicit, configured, want) in [ + // Unset: no deadline, only the configured silence limit, a `0` + // floored so the hang guard holds on an unvalidated config. + (None, 300, (None, Some(secs(300)))), + (None, 0, (None, Some(floor))), + // An explicit deadline bounds the whole call instead. + (Some(secs(5)), 300, (Some(secs(5)), None)), + // An explicit zero lifts every limit; a zero-length timeout + // would fire on the first poll. + (Some(Duration::ZERO), 300, (None, None)), + ] { + assert_eq!( + request_limits(explicit, configured), + want, + "explicit {explicit:?}, configured {configured}" + ); + } } } diff --git a/thetadatadx-rs/src/mdds/stream.rs b/thetadatadx-rs/src/mdds/stream.rs index 9b4c370f6..5b54695e1 100644 --- a/thetadatadx-rs/src/mdds/stream.rs +++ b/thetadatadx-rs/src/mdds/stream.rs @@ -29,7 +29,7 @@ use crate::proto; use super::client::MarketDataClient; use super::macros::{ - effective_deadline, run_streaming_retry_loop, run_unary_retry_loop, run_with_optional_deadline, + request_limits, run_streaming_retry_loop, run_unary_retry_loop, run_with_optional_deadline, warn_buffered_response_size, }; use super::shard::{ChainSortKey, ShardBand, ShardPlan, ShardStreamFuture}; @@ -69,9 +69,11 @@ pub(crate) type TickParser = fn(&proto::DataTable) -> Result, decode:: /// the connection's keepalive never notices. const FLAT_FILE_IDLE: Duration = Duration::from_secs(60); -/// Await `next`, failing once `idle` passes without it. The failure is a -/// `DeadlineExceeded` status, as a gRPC client reports its own deadline, so -/// the retry loop treats the stall as transient and reconnects. +/// Await `next`, failing once `idle` passes without it: the stall guard of +/// every flat-file download and of every market-data request without its own +/// deadline. The failure is a `DeadlineExceeded` status, as a gRPC client +/// reports its own deadline, so the retry loop treats the stall as transient +/// and reconnects. async fn within_idle(idle: Option, next: impl Future) -> Result { let Some(idle) = idle else { return Ok(next.await); @@ -131,8 +133,9 @@ impl MarketDataClient { pub(crate) async fn collect_stream( &self, stream: ServerStreaming, + idle: Option, ) -> Result { - collect_stream_table(stream).await + collect_stream_table(stream, idle).await } /// Process streamed responses chunk-by-chunk without materializing all rows. @@ -419,7 +422,8 @@ impl MarketDataClient { query: &dyn EndpointQuery, column: &str, ) -> Result, Error> { - let deadline = effective_deadline(deadline, self.config().market_data.request_timeout_secs); + let (deadline, idle) = + request_limits(deadline, self.config().market_data.request_timeout_secs); run_with_optional_deadline(deadline, async move { tracing::debug!(endpoint, "gRPC request"); metrics::counter!("thetadatadx.grpc.requests", "endpoint" => endpoint).increment(1); @@ -433,11 +437,11 @@ impl MarketDataClient { // The lease lives across the open, so the pool's picker // counts the pending open on its channel. let lease = self.channel(); - let stream = query - .open(&lease, self.build_query_info(snap.uuid)) - .await - .map_err(Error::from)?; - self.collect_stream(stream).await + let stream = + within_idle(idle, query.open(&lease, self.build_query_info(snap.uuid))) + .await? + .map_err(Error::from)?; + self.collect_stream(stream, idle).await }, ) .await?; @@ -475,7 +479,8 @@ impl MarketDataClient { where T: WireColumns + ChainSortKey + Clone + Send + 'static, { - let deadline = effective_deadline(deadline, self.config().market_data.request_timeout_secs); + let (deadline, idle) = + request_limits(deadline, self.config().market_data.request_timeout_secs); run_with_optional_deadline(deadline, async move { tracing::debug!(endpoint, "gRPC request"); metrics::counter!("thetadatadx.grpc.requests", "endpoint" => endpoint).increment(1); @@ -520,16 +525,19 @@ impl MarketDataClient { endpoint, |snap| async move { let lease = dispatch.channel(); - let stream = query - .open(&lease, dispatch.query_info(snap.uuid)) - .await - .map_err(Error::from)?; + let stream = within_idle( + idle, + query.open(&lease, dispatch.query_info(snap.uuid)), + ) + .await? + .map_err(Error::from)?; // The rows accumulate inside the // attempt, so a band re-fetched after // a mid-collect transient starts // empty and the replay cannot // duplicate rows. - collect_stream_typed(stream, parse, band_produced).await + collect_stream_typed(stream, parse, band_produced, idle) + .await }, ) .await @@ -570,11 +578,13 @@ impl MarketDataClient { endpoint, |snap| async move { let lease = self.channel(); - let stream = query - .open(&lease, self.build_query_info(snap.uuid)) - .await - .map_err(Error::from)?; - self.collect_stream(stream).await + let stream = within_idle( + idle, + query.open(&lease, self.build_query_info(snap.uuid)), + ) + .await? + .map_err(Error::from)?; + self.collect_stream(stream, idle).await }, ) .await? @@ -629,7 +639,8 @@ impl MarketDataClient { where T: WireColumns + Send, { - let deadline = effective_deadline(deadline, self.config().market_data.request_timeout_secs); + let (deadline, idle) = + request_limits(deadline, self.config().market_data.request_timeout_secs); run_with_optional_deadline(deadline, async move { tracing::debug!(endpoint, "gRPC streaming request"); metrics::counter!("thetadatadx.grpc.requests", "endpoint" => endpoint).increment(1); @@ -667,8 +678,8 @@ impl MarketDataClient { &delivered, |snap| { self.deliver_ticks( - &*query, snap.uuid, parse, callback, &delivered, - stopped, + &*query, snap.uuid, idle, parse, callback, + &delivered, stopped, ) }, ) @@ -699,7 +710,7 @@ impl MarketDataClient { &delivered, |snap| { self.deliver_ticks( - &*query, snap.uuid, parse, callback, &delivered, stopped, + &*query, snap.uuid, idle, parse, callback, &delivered, stopped, ) }, ) @@ -735,6 +746,7 @@ impl MarketDataClient { &self, query: &dyn EndpointQuery, uuid: String, + idle: Option, parse: TickParser, callback: &tokio::sync::Mutex<&mut ChunkCallback<'_, T>>, delivered: &AtomicBool, @@ -749,9 +761,8 @@ impl MarketDataClient { return Ok(()); } let lease = self.channel(); - let stream = query - .open(&lease, self.build_query_info(uuid)) - .await + let stream = within_idle(idle, query.open(&lease, self.build_query_info(uuid))) + .await? .map_err(Error::from)?; let mut decode_error: Option = None; // Marks the callback's await as this client's delivery scope, so a @@ -760,7 +771,7 @@ impl MarketDataClient { // `acquire_request_permit`). let sem_addr = std::sync::Arc::as_ptr(&self.request_semaphore) as usize; let drain_result = self - .for_each_chunk_async_control(stream, None, |headers, rows| { + .for_each_chunk_async_control(stream, idle, |headers, rows| { let mut stop_stream = decode_error.is_some(); let ticks = if stop_stream { None @@ -837,7 +848,8 @@ impl MarketDataClient { F: FnMut(Vec, Vec) -> Fut, Fut: Future>, { - let deadline = effective_deadline(deadline, self.config().market_data.request_timeout_secs); + let (deadline, idle) = + request_limits(deadline, self.config().market_data.request_timeout_secs); run_with_optional_deadline(deadline, async { tracing::debug!(endpoint, "gRPC streaming request"); metrics::counter!("thetadatadx.grpc.requests", "endpoint" => endpoint).increment(1); @@ -854,12 +866,11 @@ impl MarketDataClient { |snap| async move { let stream = { let lease = self.channel(); - query - .open(&lease, self.build_query_info(snap.uuid)) - .await + within_idle(idle, query.open(&lease, self.build_query_info(snap.uuid))) + .await? .map_err(Error::from)? }; - self.for_each_chunk_async_control(stream, None, |headers, rows| async move { + self.for_each_chunk_async_control(stream, idle, |headers, rows| async move { if !rows.is_empty() { delivered.store(true, Ordering::Release); } @@ -893,6 +904,7 @@ impl MarketDataClient { /// Same conditions as [`MarketDataClient::collect_stream`]. pub(crate) async fn collect_stream_table( mut stream: ServerStreaming, + idle: Option, ) -> Result { let mut all_rows = Vec::new(); let mut headers: Vec = Vec::new(); @@ -900,7 +912,7 @@ pub(crate) async fn collect_stream_table( let max_message_size = stream.max_message_size(); - while let Some(response) = stream.next().await { + while let Some(response) = within_idle(idle, stream.next()).await? { let response = response?; // Use original_size as a rough pre-allocation hint on the first chunk. @@ -977,6 +989,7 @@ pub(crate) async fn collect_stream_typed( mut stream: ServerStreaming, parser: P, produced: &std::sync::atomic::AtomicBool, + idle: Option, ) -> Result, Error> where P: Fn(&proto::DataTable) -> Result, E>, @@ -984,7 +997,7 @@ where { let mut collect = TypedCollect::default(); let max_message_size = stream.max_message_size(); - while let Some(response) = stream.next().await { + while let Some(response) = within_idle(idle, stream.next()).await? { let response = response?; // Same first-chunk row-count hint as `collect_stream_table` // (~64 B per wire row), capped at the channel ceiling; the typed diff --git a/thetadatadx-rs/src/surface/config.rs b/thetadatadx-rs/src/surface/config.rs index 594098323..1e85174af 100644 --- a/thetadatadx-rs/src/surface/config.rs +++ b/thetadatadx-rs/src/surface/config.rs @@ -338,14 +338,14 @@ macro_rules! __config { param: secs, default: 300 "5 minutes", doc: [ - "Set the default per-request deadline (seconds) for market-data queries.", + "Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message.", "", - "It bounds every request that did not set its own deadline, so a live-but-silent stream resolves to a timeout instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the deadline: it is floored to the 300-second default at request time, so the deadline always applies.", + "A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time.", ], } get thetadatadx_config_get_request_timeout_secs(out: u64) [market_data.request_timeout_secs] { default: 300 "5 minutes", - doc: ["Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the deadline."], + doc: ["Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit."], } set thetadatadx_config_set_market_data_stream_window_size_kb(kb: usize) [market_data.stream_window_size_kb] { param: kb, diff --git a/thetadatadx-rs/tests/common/grpc_mock.rs b/thetadatadx-rs/tests/common/grpc_mock.rs index 5f5121b58..cfa47149b 100644 --- a/thetadatadx-rs/tests/common/grpc_mock.rs +++ b/thetadatadx-rs/tests/common/grpc_mock.rs @@ -185,6 +185,9 @@ pub struct MockBehaviour { /// holding the stream open: a live server that has stopped sending, /// which the connection's keepalive cannot tell from a slow one. pub stall_after_head: bool, + /// When `Some`, the mock waits this long before each DATA frame: a + /// server that keeps streaming, slowly. + pub chunk_interval: Option, } impl MockServer { @@ -527,7 +530,9 @@ async fn handle_request( &status_message, poison_status_details, behaviour.http_status_code, - )?; + behaviour.chunk_interval, + ) + .await?; Ok(()) } @@ -616,13 +621,14 @@ async fn respond_partial_then_drop( Ok(()) } -fn respond_chunks( +async fn respond_chunks( mut respond: SendResponse, chunks: &[ResponseData], status_code: u32, status_message: &str, poison_status_details: bool, http_status_code: Option, + chunk_interval: Option, ) -> Result<(), Box> { let mut response = Response::new(()); *response.status_mut() = StatusCode::OK; @@ -636,6 +642,9 @@ fn respond_chunks( let mut send_stream = respond.send_response(response, false)?; for chunk in chunks { + if let Some(d) = chunk_interval { + tokio::time::sleep(d).await; + } let framed = frame(chunk); send_stream.send_data(framed, false)?; } diff --git a/thetadatadx-rs/tests/test_endpoint_routing.rs b/thetadatadx-rs/tests/test_endpoint_routing.rs index ce40e7fd2..75847d887 100644 --- a/thetadatadx-rs/tests/test_endpoint_routing.rs +++ b/thetadatadx-rs/tests/test_endpoint_routing.rs @@ -463,54 +463,75 @@ async fn by_name_stream_ends_at_a_break() { assert_eq!(chunks, 1, "the handler was called again after it broke"); } -// List endpoints honor the per-request deadline +// List endpoints honor the per-request limits // -// List RPCs (`*_list_*`) must apply the same deadline contract as the -// tick endpoints: the configured `request_timeout_secs` bounds a call that -// sets none, and `with_deadline` sets an explicit per-call deadline. -// Without it a live-but-silent stream hangs the request forever (the gRPC -// keepalive PING only detects a fully dead peer, not a stalled one). +// List RPCs (`*_list_*`) must apply the same contract as the tick +// endpoints: a call that sets no deadline fails once the server is silent +// for the configured `request_timeout_secs`, and `with_deadline` sets an +// explicit per-call deadline. Without the silence limit a live-but-silent +// stream hangs the request forever (the gRPC keepalive PING only detects a +// fully dead peer, not a stalled one). // ──────────────────────────────────────────────────────────────────── use std::time::Duration; use thetadatadx::Error; -/// Build a `MarketDataClient` wired to a mock that delays its response by -/// `pre_response_delay`, with `request_timeout_secs` set on the config so -/// the default-deadline path can be exercised deterministically. -async fn client_for_delayed_mock( - response: proto::ResponseData, - pre_response_delay: Duration, +/// Build a `MarketDataClient` wired to a mock that serves `chunks` after +/// `behaviour`'s delays, with `request_timeout_secs` set on the config so +/// the silence limit can be exercised deterministically. Retries are off, +/// so a stall surfaces on its first attempt. +async fn client_for_paced_mock( + chunks: Vec, + behaviour: mock::MockBehaviour, request_timeout_secs: u64, ) -> (mock::MockServer, MarketDataClient) { - let server = mock::MockServer::spawn_with_behaviour( - vec![response], - 0, - String::new(), - mock::MockBehaviour { - pre_response_delay: Some(pre_response_delay), - ..mock::MockBehaviour::default() - }, - ) - .await; + let server = mock::MockServer::spawn_with_behaviour(chunks, 0, String::new(), behaviour).await; let channel = Channel::connect_h2c("127.0.0.1", server.addr.port()) .await .expect("h2c connect to mock"); let pool = ChannelPool::from_channels(vec![channel]); let mut cfg = DirectConfig::production(); cfg.market_data.request_timeout_secs = request_timeout_secs; + cfg.retry = thetadatadx::RetryPolicy::disabled(); let sem = Arc::new(Semaphore::new(4)); let client = MarketDataClient::for_endpoint_routing_test(cfg, pool, sem); (server, client) } +/// The mock withholds its one chunk `pre_response_delay`, then serves it. +async fn client_for_delayed_mock( + response: proto::ResponseData, + pre_response_delay: Duration, + request_timeout_secs: u64, +) -> (mock::MockServer, MarketDataClient) { + let behaviour = mock::MockBehaviour { + pre_response_delay: Some(pre_response_delay), + ..mock::MockBehaviour::default() + }; + client_for_paced_mock(vec![response], behaviour, request_timeout_secs).await +} + +/// A call that set no deadline fails once the server is silent for the +/// configured limit, as a `DeadlineExceeded` stall. +fn assert_silence_limit_stall(result: Result) { + assert!( + matches!( + result, + Err(Error::Grpc { + kind: thetadatadx::GrpcStatusKind::DeadlineExceeded, + .. + }) + ), + "expected a DeadlineExceeded stall from the configured limit, got {result:?}" + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn list_endpoint_plain_call_is_bounded_by_configured_default() { - // The mock holds the response 5s; the configured default deadline is - // 1s. The plain `stock_list_symbols()` (no explicit deadline) must - // surface `Error::Timeout` from the configured default rather than - // hang on the silent stream. + // The mock holds the response 5s; the configured silence limit is 1s. + // The plain `stock_list_symbols()` (no explicit deadline) must fail as + // a stall rather than hang on the silent stream. let (_mock, client) = client_for_delayed_mock( mock::make_response_data(&["AAPL"]), Duration::from_secs(5), @@ -518,16 +539,31 @@ async fn list_endpoint_plain_call_is_bounded_by_configured_default() { ) .await; + assert_silence_limit_stall(client.stock_list_symbols().await); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plain_call_that_keeps_streaming_outlives_the_configured_limit() { + // Four chunks 400ms apart take 1.6s, past the 1s limit, but the server + // is never silent for 1s: a call that set no deadline must complete. + let behaviour = mock::MockBehaviour { + chunk_interval: Some(Duration::from_millis(400)), + ..mock::MockBehaviour::default() + }; + let chunks = vec![mock::make_response_data(&["AAPL"]); 4]; + let (_mock, client) = client_for_paced_mock(chunks, behaviour, 1).await; + + let started = std::time::Instant::now(); let result = client.stock_list_symbols().await; - match result { - Err(Error::Timeout { duration_ms }) => { - assert!( - duration_ms <= 1_000, - "default deadline carried the wrong bound; got {duration_ms}ms" - ); - } - other => panic!("expected Error::Timeout from the configured default, got {other:?}"), - } + assert!( + result.is_ok(), + "a pull that keeps streaming must not time out, got {result:?}" + ); + assert!( + started.elapsed() >= Duration::from_secs(1), + "the pull ended inside the limit, so it proves nothing: {:?}", + started.elapsed() + ); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -560,11 +596,11 @@ async fn list_endpoint_with_deadline_bounds_the_call() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn stream_endpoint_unset_deadline_applies_configured_default() { // The four generated `*_stream` builders must route an unset deadline - // through `effective_deadline`, exactly like the parsed builders: with - // no explicit `with_deadline`, the configured `request_timeout_secs` - // (1s here) must bound the call so a live-but-silent server cannot hang - // it forever and starve the request-semaphore. The mock holds the - // response 5s. + // through `request_limits`, exactly like the parsed builders: with no + // explicit `with_deadline`, the configured `request_timeout_secs` (1s + // here) must bound the server's silence so a live-but-silent server + // cannot hang the call forever and starve the request-semaphore. The + // mock holds the response 5s. let (_mock, client) = client_for_delayed_mock( mock::make_response_data(&["AAPL"]), Duration::from_secs(5), @@ -577,15 +613,7 @@ async fn stream_endpoint_unset_deadline_applies_configured_default() { .date("20240102") .stream(|_ticks| {}) .await; - match result { - Err(Error::Timeout { duration_ms }) => { - assert!( - duration_ms <= 1_000, - "unset-deadline stream applied the wrong default bound; got {duration_ms}ms" - ); - } - other => panic!("expected Error::Timeout from the configured default, got {other:?}"), - } + assert_silence_limit_stall(result); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/thetadatadx-ts/examples/chain_quote_bench.ts b/thetadatadx-ts/examples/chain_quote_bench.ts index c02a2fa56..541e739d0 100644 --- a/thetadatadx-ts/examples/chain_quote_bench.ts +++ b/thetadatadx-ts/examples/chain_quote_bench.ts @@ -138,14 +138,11 @@ async function main(): Promise { // so TTFB excludes connect/auth and measures backend-to-first-chunk latency. const dispatch = nowSecs(); - // A full-day 0DTE pull can run 6-15 minutes; the config default - // requestTimeoutSecs (300 s) would kill it, so opt out of any deadline - // with timeoutMs: 0 (documented as "no deadline"). try { await client.optionHistoryQuoteStream( symbol, expiration, - { strike: "*", right: "both", date, interval, timeoutMs: 0 }, + { strike: "*", right: "both", date, interval }, (chunk) => { const now = nowSecs(); if (ttfbSecs === null) { diff --git a/thetadatadx-ts/index.d.ts b/thetadatadx-ts/index.d.ts index 1b4a6d9a5..9185db817 100644 --- a/thetadatadx-ts/index.d.ts +++ b/thetadatadx-ts/index.d.ts @@ -472,14 +472,14 @@ export declare class Config { */ get warnOnBufferedThresholdBytes(): bigint /** - * Set the default per-request deadline (seconds) for market-data queries. + * Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. * - * It bounds every request that did not set its own deadline, so a live-but-silent stream resolves to a timeout instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the deadline: it is floored to the 300-second default at request time, so the deadline always applies. + * A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. * Default `300n` (5 minutes). */ setRequestTimeoutSecs(secs: bigint): void /** - * Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the deadline. + * Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit. * Default `300n` (5 minutes). */ get requestTimeoutSecs(): bigint From 26f35af5188ede65cee655cf0d25e3c7529c7943 Mon Sep 17 00:00:00 2001 From: TalesOfThales <101120927+userFRM@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:49:45 +0100 Subject: [PATCH 3/7] perf(shard): split a one-day bar chain over every expiration by expiration A one-day option chain at a bar interval cannot be cut in time, because each bar accumulates from the window start, so it went out as at most two requests, one per right. On a full chain each of those carries hundreds of millions of rows on one server stream, which delivers a few tens of thousands of rows a second. A chain over every expiration now lists the day's contracts first and sends one request per expiration, calls and puts separately, each over the whole window, so every contract's bars are unchanged. The list asks for quoted contracts, which covers every contract with a bar, and forwards the query's max_dte so it names the same expirations as the chain. A chain with one expiration, a chain under a million bars, or a failed list keeps the call/put pair; a single-right chain, or an out_of_the_money Greeks chain that needs both rights, takes one band per expiration and otherwise stays one request. --- CHANGELOG.md | 2 +- docs-site/docs/articles/bulk-downloads.md | 2 + thetadatadx-rs/src/error.rs | 17 +- thetadatadx-rs/src/mdds/macros.rs | 18 +- thetadatadx-rs/src/mdds/shard.rs | 359 +++++++++++++++++++--- thetadatadx-rs/src/mdds/stream.rs | 4 +- 6 files changed, 349 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edad1e373..e5c5c5745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- **A one-day option chain at a bar interval is fetched as two concurrent requests, one for calls and one for puts.** A history pull over every strike and both rights at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. Splitting by right leaves every contract's bars whole, so the SDK now sends the calls and the puts as separate requests over the full window, and a buffered pull merges them into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. Set `bulk_fetch="off"` to send one request in the server's own order. +- **A one-day option chain at a bar interval is split across concurrent requests by expiration.** A history pull over every strike at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. The SDK now splits such a chain by contract instead, so every contract's bars still cover the whole window. A chain over every expiration first lists the day's contracts in one request, then fetches each expiration on its own, calls and puts separately. A chain with one expiration, or one whose contract list fails, is fetched as one request for calls and one for puts, and a small chain keeps that pair, since dozens of requests would cost it more than they save. A buffered pull merges the pieces into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. Set `bulk_fetch="off"` to send one request in the server's own order. - **TypeScript streaming callbacks keep up with a higher message rate.** The native side hands events to the Node main thread in arrays instead of waking it once per event, and the package still calls your `startStreaming` callback once per event, in order. On the offline callback benchmark (`thetadatadx-ts/benches/streaming_throughput.mjs`) a no-op callback goes from about 300k to about 460k events a second, and live on the dev replay server the Node main thread is about a fifth less busy at the same message rate. A callback that throws still ends the process at that event unless an `uncaughtException` handler is installed; with one, the handler gets the error and the rest of the events are still delivered. diff --git a/docs-site/docs/articles/bulk-downloads.md b/docs-site/docs/articles/bulk-downloads.md index 4a843f2c7..d5769c9fe 100644 --- a/docs-site/docs/articles/bulk-downloads.md +++ b/docs-site/docs/articles/bulk-downloads.md @@ -29,6 +29,8 @@ Raise them for even fatter streams if you have memory to spare, or lower them wh A single large request does not have to be one stream. The SDK splits the requested time (or date) range into equal concurrent pieces. The split comes straight from the shape of the request, with no sizing round-trip. It then runs them in parallel across your concurrent-request pool and reassembles them into exactly the rows one request would have returned. +A one-day option chain at a bar interval, such as `1s` or `1m`, is split by contract instead of by time: each bar builds up from the start of the requested window, so a piece starting mid-day would return different bars. A chain over every expiration first lists the day's contracts in one small request, then fetches each expiration as its own request, calls and puts separately. A chain with a single expiration splits into calls and puts. Either way, every contract's bars cover the whole window, exactly as one request returns them. + The number of pieces is the request-pool size, which defaults to your account's allowance: the SDK sizes the pool to your subscription tier at connect time (Free 1 / Value 2 / Standard 4 / Pro 8), and setting `max_concurrent_requests` overrides that with no client-side cap, because the server enforces the real allowance. See [Concurrent Requests](/articles/concurrent-requests). On Pro, one big query becomes eight pieces fetching at once; a boosted account with `max_concurrent_requests = 32` fans out 32 ways. How much that shortens the wall clock depends on how much of the fan-out the server actually runs in parallel under current conditions; the table below shows one measured day. It scales down cleanly too: four pieces on Standard, two on Value, one on Free. diff --git a/thetadatadx-rs/src/error.rs b/thetadatadx-rs/src/error.rs index db0a465bd..aea52bc4a 100644 --- a/thetadatadx-rs/src/error.rs +++ b/thetadatadx-rs/src/error.rs @@ -566,16 +566,14 @@ fn format_shard_windows(bands: &[crate::ShardBand]) -> String { if index > 0 { out.push_str(", "); } - match band { + let right = match band { crate::ShardBand::Date { start_date, end_date, right, } => { let _ = write!(out, "{start_date}..{end_date}"); - if let Some(right) = right { - let _ = write!(out, " ({right})"); - } + right } crate::ShardBand::Time { start_time, @@ -583,10 +581,15 @@ fn format_shard_windows(bands: &[crate::ShardBand]) -> String { right, } => { let _ = write!(out, "{start_time}..{end_time}"); - if let Some(right) = right { - let _ = write!(out, " ({right})"); - } + right } + crate::ShardBand::Expiration { expiration, right } => { + let _ = write!(out, "expiration {expiration}"); + right + } + }; + if let Some(right) = right { + let _ = write!(out, " ({right})"); } } if bands.len() > MAX_LISTED_WINDOWS { diff --git a/thetadatadx-rs/src/mdds/macros.rs b/thetadatadx-rs/src/mdds/macros.rs index 39955d2dd..7b02a64fb 100644 --- a/thetadatadx-rs/src/mdds/macros.rs +++ b/thetadatadx-rs/src/mdds/macros.rs @@ -813,6 +813,9 @@ macro_rules! shard_read_field { ($sq:ident, $params:ident, implied_vol_method) => { $sq.implied_vol_method = $crate::mdds::shard::opt_wire_str(&$params.implied_vol_method); }; + ($sq:ident, $params:ident, max_dte) => { + $sq.max_dte = $params.max_dte; + }; // NOTE: no `expiration` arm — the top-level `expiration` field on the // option protos is the always-empty legacy slot; the live value rides // in `contract_spec` and is read there. @@ -852,11 +855,16 @@ macro_rules! shard_apply_field { // without a `contract_spec` never emit this arm; a band carrying no // `right` leaves it as issued. ($params:ident, $band:ident, contract_spec) => { - if let Some(right) = (match $band { - $crate::mdds::shard::ShardBand::Time { right, .. } - | $crate::mdds::shard::ShardBand::Date { right, .. } => right.as_deref(), - }) { - if let Some(cs) = $params.contract_spec.as_mut() { + if let Some(cs) = $params.contract_spec.as_mut() { + let right = match $band { + $crate::mdds::shard::ShardBand::Time { right, .. } + | $crate::mdds::shard::ShardBand::Date { right, .. } => right, + $crate::mdds::shard::ShardBand::Expiration { expiration, right } => { + $crate::mdds::shard::set_wire_str(&mut cs.expiration, expiration); + right + } + }; + if let Some(right) = right { $crate::mdds::shard::set_wire_str(&mut cs.right, right); } } diff --git a/thetadatadx-rs/src/mdds/shard.rs b/thetadatadx-rs/src/mdds/shard.rs index be3fb1de6..45d230b2a 100644 --- a/thetadatadx-rs/src/mdds/shard.rs +++ b/thetadatadx-rs/src/mdds/shard.rs @@ -1,13 +1,16 @@ //! Automatic sharding of large history pulls. //! //! One logical query becomes N disjoint sub-requests along a filter -//! axis (date band, time band), dispatched concurrently across the -//! channel pool. Bands are cut from the request shape alone — -//! equal wall-clock duration on the time axis, equal day count on the -//! date axis — never from a sizing query. Balance is equal span, not -//! equal rows: a deliberate trade that costs zero extra round-trips and -//! zero per-endpoint tuning, and the concurrency win dominates the -//! residual row imbalance between bands. The buffered `.await` path merges the shard +//! axis (date band, time band, expiration), dispatched concurrently +//! across the channel pool. Date and time bands are cut from the request +//! shape alone — equal wall-clock duration on the time axis, equal day +//! count on the date axis — never from a sizing query. Balance is equal +//! span, not equal rows: a deliberate trade that costs zero extra +//! round-trips and zero per-endpoint tuning, and the concurrency win +//! dominates the residual row imbalance between bands. The one exception +//! is a one-day bar chain over every expiration, which no time band can +//! cut: it lists the day's contracts first (one request) and fans out one +//! request per expiration (see `resolve_plan`). The buffered `.await` path merges the shard //! responses back into exactly the rows the single-stream response would //! have carried — in the exact server order for single-contract / stock / //! index pulls, in a deterministic canonical contract order for chains @@ -27,7 +30,8 @@ //! gate, axis selection, and the equal-span band cut — pure //! computation, no request issued. Anything that does not clearly //! benefit resolves to `None` and runs on today's single stream, -//! byte-identical. +//! byte-identical. `resolve_plan` then runs the contract list of an +//! expiration split, the only plan that needs one. //! 3. Each [`ShardBand`] is applied onto a clone of the original wire //! parameters — every shard is a normal terminal-parity query differing //! only in its band fields. @@ -63,13 +67,13 @@ //! # Semaphore safety //! //! The joining driver never holds a request permit: each shard acquires -//! its own permit inside its spawned task. Since the semaphore is sized -//! to the channel pool and a plan never exceeds the pool -//! size, N shards make progress even at `pool_size == 1` (they simply -//! serialize). +//! its own permit inside its spawned task, so a plan of any size makes +//! progress even at `pool_size == 1`: bands beyond the pool simply +//! queue for a permit. use std::sync::Arc; +use crate::OptionContract; use crate::auth::SessionToken; use crate::columns::{Ticks, WireColumns}; use crate::config::{BulkFetchPolicy, RetryPolicy}; @@ -259,6 +263,16 @@ pub enum ShardBand { /// query's own `right` untouched. right: Option, }, + /// One expiration of an option chain over the query's whole window. + /// A one-day chain at a bar interval splits this way: each bar + /// accumulates from the window start, so a time band would change it. + Expiration { + /// The band's expiration (`YYYYMMDD`). + expiration: String, + /// `Some("call")` / `Some("put")` restricts the band to one side of + /// that expiration; `None` leaves the query's own `right` untouched. + right: Option, + }, } /// An equal-span fan-out plan for one logical history query: the @@ -276,6 +290,29 @@ pub enum ShardBand { pub(crate) struct ShardPlan { /// Disjoint, exhaustive band overrides in output order. pub bands: Vec, + /// Set when the chain splits by expiration. The bands then come from + /// the day's contract list ([`resolve_plan`]), and `bands` is what runs + /// when the list fails or the chain is too small for the split to pay, + /// an empty `bands` meaning the single stream. + pub listing: Option, +} + +/// The contract list an expiration split reads before it fans out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ChainListing { + /// The chain's root. + pub symbol: String, + /// The query's day (`YYYYMMDD`). + pub date: String, + /// The query's `max_dte`, forwarded so the list names exactly the + /// expirations the chain returns. + pub max_dte: Option, + /// The query's single right, `'C'` or `'P'`, when it names one. + pub right: Option, + /// Whether each expiration splits again into a call and a put band. + pub split_rights: bool, + /// Bars one contract returns over the query's window. + pub bars_per_contract: u64, } /// Wire-level view of a history query, as consumed by the shard planner. @@ -308,6 +345,8 @@ pub(crate) struct ShardQuery { pub interval: Option, /// Implied-volatility method of a binomial Greeks query, when present. pub implied_vol_method: Option, + /// Days-to-expiration cap of a chain query, when present. + pub max_dte: Option, } // ─── Wire-field projection helpers (used by the endpoint macros) ───────── @@ -434,8 +473,8 @@ pub(crate) enum ShardDecline { /// bar VALUES even when the row count matches; a time-banded pull /// cannot reproduce the single stream. Tick pulls carry no bars and /// time-shard freely; date bands are unaffected (bars re-anchor at - /// each day's own window start either way), and a both-rights chain - /// still splits by right over the whole window. + /// each day's own window start either way), and a chain still splits + /// by expiration or right over the whole window. IntervalBars, /// Pull issued from inside this client's own streaming delivery /// handler: the outer pull holds the request pool until the handler @@ -469,10 +508,16 @@ impl ShardDecline { /// fan-out, so sharding cannot win. Chain cross-products and /// tick-interval pulls have no such ceiling and band the range on the /// window alone. (The time axis never gets this far with a bounded -/// interval: it splits a both-rights chain by right over the whole +/// interval: it splits a chain by expiration or right over the whole /// window and declines everything else as [`ShardDecline::IntervalBars`].) const SHARD_MIN_GRID_ROWS: u64 = 10_000_000; +/// Bar ceiling below which a listed one-day chain keeps the call/put pair +/// rather than one request per expiration. A chain this small finishes in +/// seconds on two streams, and the extra round trips of dozens of small +/// requests would add back what the wider fan-out saves. +const EXPIRATION_SPLIT_MIN_ROWS: u64 = 1_000_000; + /// Minimum wall-clock span of one time band (five minutes). The server /// spends a roughly fixed prepare interval per request before the first /// byte, so a band much narrower than this pays fan-out overhead without @@ -605,6 +650,65 @@ fn splittable_by_right(q: &ShardQuery) -> bool { && q.implied_vol_method.as_deref() != Some("out_of_the_money") } +/// The listing step of a one-day bar chain over every expiration and +/// strike, `None` for any other shape. `window_ms` is the query's window. +fn chain_listing(q: &ShardQuery, window_ms: i64) -> Option { + if q.expiration.as_deref() != Some("*") || q.strike.as_deref().is_some_and(|s| s != "*") { + return None; + } + let ivl = q.interval.as_deref().and_then(interval_ms)?; + let right = match q.right.as_deref() { + None | Some("both") => None, + Some("call") => Some('C'), + Some("put") => Some('P'), + Some(_) => return None, + }; + Some(ChainListing { + symbol: q.symbol.clone()?, + date: q.date.clone().or_else(|| q.start_date.clone())?, + max_dte: q.max_dte, + right, + split_rights: splittable_by_right(q), + bars_per_contract: u64::try_from(window_ms / ivl + 1).ok()?, + }) +} + +/// The expiration bands for `listing` over the day's `contracts`, in +/// ascending expiration order, calls before puts. `None` keeps the plan's +/// fallback: a chain under two expirations has nothing to split, and one +/// under [`EXPIRATION_SPLIT_MIN_ROWS`] does not pay for the requests. +fn expiration_bands( + listing: &ChainListing, + contracts: &[OptionContract], +) -> Option> { + let in_chain = contracts + .iter() + .filter(|c| listing.right.is_none_or(|r| c.right == r)); + let rows = u64::try_from(in_chain.clone().count()) + .unwrap_or(u64::MAX) + .saturating_mul(listing.bars_per_contract); + let expirations: std::collections::BTreeSet = in_chain.map(|c| c.expiration).collect(); + if expirations.len() < 2 || rows < EXPIRATION_SPLIT_MIN_ROWS { + return None; + } + let rights: &[Option<&str>] = if listing.split_rights { + &[Some("call"), Some("put")] + } else { + &[None] + }; + Some( + expirations + .iter() + .flat_map(|e| { + rights.iter().map(move |r| ShardBand::Expiration { + expiration: e.to_string(), + right: r.map(str::to_owned), + }) + }) + .collect(), + ) +} + /// Whether the query is a tick pull (no bar interval). The server accepts a /// tick *chain* only one day at a time, so a tick pull's bands must never span /// more than one day (Auto assembles a multi-day tick chain from single-day @@ -657,7 +761,8 @@ fn select_axis(q: &ShardQuery) -> Option { /// Only tick pulls cut the window into more than one band: interval /// bars accumulate from the request's window start and any mid-window /// seam would change bar values (see [`ShardDecline::IntervalBars`]), -/// so a bounded-interval chain takes one whole-window band per right. +/// so a bounded-interval chain takes whole-window bands, one per right or +/// per expiration. fn time_bands(start_ms: i64, end_ms: i64, n: i64, right: Option<&str>) -> Vec { let window = end_ms - start_ms + 1; (0..n) @@ -779,6 +884,8 @@ pub(crate) fn auto_plan( let axis = match p.bands.first() { Some(ShardBand::Time { .. }) => "time", Some(ShardBand::Date { .. }) => "date", + Some(ShardBand::Expiration { .. }) => "expiration", + None if p.listing.is_some() => "expiration", None => "none", }; tracing::debug!( @@ -800,6 +907,45 @@ pub(crate) fn auto_plan( } } +/// Finish an `auto_plan` result: a plan that carries a listing step lists the +/// day's contracts (one request) and splits the chain into one band per +/// expiration. A list that fails, or a chain too small for the split, keeps +/// the plan's own bands. `None` runs the single stream. +pub(crate) async fn resolve_plan( + client: &MarketDataClient, + plan: Option, +) -> Option { + let mut plan = plan?; + if let Some(listing) = plan.listing.take() { + // Quotes rather than trades: every contract with a bar that day was + // quoted, so the quote list never misses an expiration the chain + // returns. + let mut list = client + .option_list_contracts("quote", &listing.date) + .symbol(&listing.symbol); + if let Some(max_dte) = listing.max_dte { + list = list.max_dte(max_dte); + } + match list.await { + Ok(contracts) => { + if let Some(bands) = expiration_bands(&listing, &contracts) { + tracing::debug!( + contracts = contracts.len(), + shards = bands.len(), + "chain split by expiration" + ); + plan.bands = bands; + } + } + Err(error) => tracing::debug!( + %error, + "contract list failed; the chain is not split by expiration" + ), + } + } + (!plan.bands.is_empty()).then_some(plan) +} + /// Build the shard plan for `endpoint` and `q` at fan-out width `width`, /// from the request shape alone — pure computation, no request issued. /// @@ -808,7 +954,9 @@ pub(crate) fn auto_plan( /// axis — run concurrently; it never issues a sizing query. Balance is /// equal span, not equal rows: a deliberate trade that costs zero extra /// round-trips and zero per-endpoint tuning, and the concurrency win -/// dominates the residual row imbalance between bands. +/// dominates the residual row imbalance between bands. A one-day bar +/// chain over every expiration returns a listing step with its fallback +/// bands, which [`resolve_plan`] completes. /// /// Used by [`auto_plan`]. Declines — the query should stay on a single /// stream — carry the gate that fired ([`ShardDecline`], logged by @@ -816,10 +964,10 @@ pub(crate) fn auto_plan( /// an endpoint outside the shardable set, a shape with no cut axis, /// `width < 2`, a window too narrow for two bands of /// [`MIN_SHARD_BAND_MS`], a bounded-interval pull on the time axis that -/// is not a both-rights chain (bar values anchor to the window start — -/// [`ShardDecline::IntervalBars`]), or a bounded-interval -/// single-contract date-axis pull whose bar grid provably stays under -/// [`SHARD_MIN_GRID_ROWS`]. +/// is neither a both-rights nor an every-expiration chain (bar values +/// anchor to the window start — [`ShardDecline::IntervalBars`]), or a +/// bounded-interval single-contract date-axis pull whose bar grid +/// provably stays under [`SHARD_MIN_GRID_ROWS`]. fn plan_query(endpoint: &str, q: &ShardQuery, width: usize) -> Result { if !is_shardable_history_endpoint(endpoint) { return Err(ShardDecline::UnlistedEndpoint); @@ -863,13 +1011,22 @@ fn plan_query(endpoint: &str, q: &ShardQuery, width: usize) -> Result Result Result { @@ -947,7 +1108,10 @@ fn plan_query(endpoint: &str, q: &ShardQuery, width: usize) -> Result Result tracing::Span { band_end = %end_time, band_right = ?right, ), + ShardBand::Expiration { expiration, right } => tracing::debug_span!( + "shard_band", + band_expiration = %expiration, + band_right = ?right, + ), } } @@ -1749,7 +1919,7 @@ mod tests { /// The `right` override a band carries (`None` for a plain time band). fn band_right(b: &ShardBand) -> Option<&str> { match b { - ShardBand::Time { right, .. } => right.as_deref(), + ShardBand::Time { right, .. } | ShardBand::Expiration { right, .. } => right.as_deref(), ShardBand::Date { .. } => None, } } @@ -1915,6 +2085,23 @@ mod tests { Some("put"), "a right-carrying date band must rewrite contract_spec.right on the wire" ); + + // An expiration band rewrites the expiration and right, and leaves + // the window as issued. + let expiration_band = ShardBand::Expiration { + expiration: "20260724".into(), + right: Some("call".into()), + }; + let mut q5 = query(); + let band = &expiration_band; + shard_apply_field!(q5, band, contract_spec); + shard_apply_field!(q5, band, start_time); + shard_apply_field!(q5, band, end_time); + let spec = q5.contract_spec.as_ref().unwrap(); + assert_eq!(spec.expiration, "20260724"); + assert_eq!(spec.right.as_deref(), Some("call")); + assert_eq!(q5.start_time.as_deref(), Some("09:30:00.000")); + assert_eq!(q5.end_time.as_deref(), Some("16:00:00.000")); } #[test] @@ -1961,6 +2148,69 @@ mod tests { ); } + #[test] + fn expiration_bands_cover_every_listed_expiration_once() { + let contract = |expiration, right| OptionContract { + symbol: "SPXW".into(), + expiration, + strike: 6000.0, + right, + }; + // Unsorted, with repeats across strikes and rights. + let day = [ + contract(20260717, 'P'), + contract(20260710, 'C'), + contract(20260717, 'C'), + contract(20260710, 'P'), + contract(20260724, 'P'), + ]; + let band = |expiration: &str, right: Option<&str>| ShardBand::Expiration { + expiration: expiration.into(), + right: right.map(str::to_owned), + }; + let listing = |right, split_rights, bars_per_contract| ChainListing { + symbol: "SPXW".into(), + date: "20260710".into(), + max_dte: None, + right, + split_rights, + bars_per_contract, + }; + let big = EXPIRATION_SPLIT_MIN_ROWS; + assert_eq!( + expiration_bands(&listing(None, true, big), &day), + Some(vec![ + band("20260710", Some("call")), + band("20260710", Some("put")), + band("20260717", Some("call")), + band("20260717", Some("put")), + band("20260724", Some("call")), + band("20260724", Some("put")), + ]) + ); + // Both rights kept whole per expiration. + assert_eq!( + expiration_bands(&listing(None, false, big), &day), + Some(vec![ + band("20260710", None), + band("20260717", None), + band("20260724", None), + ]) + ); + // A call chain lists only the expirations with calls, and keeps its + // own right. + assert_eq!( + expiration_bands(&listing(Some('C'), false, big), &day), + Some(vec![band("20260710", None), band("20260717", None)]) + ); + // Under two expirations, or under the row floor (five contracts + // just below it), the plan keeps its fallback. + assert_eq!(expiration_bands(&listing(None, true, big), &day[..1]), None); + let under = (EXPIRATION_SPLIT_MIN_ROWS - 1) / 5; + assert_eq!(expiration_bands(&listing(None, true, under), &day), None); + assert!(expiration_bands(&listing(None, true, under + 1), &day).is_some()); + } + #[test] fn bounded_interval_declines_the_time_axis_for_every_shape() { // Interval bars accumulate from the request's window start @@ -1980,9 +2230,9 @@ mod tests { // The same contract at tick interval carries no bars and shards. concrete.interval = Some("tick".into()); assert!(plan_query("option_history_quote", &concrete, 8).is_ok()); - // A both-rights chain at a bounded interval splits by right - // only: one band per right over the whole window, so no bar - // loses its anchor. + // A both-rights chain at a bounded interval never cuts its window: + // every expiration lists first and splits per expiration and right, + // with one band per right over the whole window as the fallback. let mut chain = chain_day_query(); chain.interval = Some("1s".into()); let whole_window = |right: &str| ShardBand::Time { @@ -1990,15 +2240,48 @@ mod tests { end_time: "16:00:00.000".into(), right: Some(right.into()), }; + let listing = |split_rights| ChainListing { + symbol: "SPXW".into(), + date: "20260710".into(), + max_dte: None, + right: None, + split_rights, + bars_per_contract: 23_401, + }; + assert_eq!( + plan_query("option_history_quote", &chain, 8), + Ok(ShardPlan { + bands: vec![whole_window("call"), whole_window("put")], + listing: Some(listing(true)), + }) + ); + // One expiration has nothing to list. + let mut one_expiration = chain.clone(); + one_expiration.expiration = Some("20260710".into()); assert_eq!( - plan_query("option_history_quote", &chain, 8).map(|p| p.bands), - Ok(vec![whole_window("call"), whole_window("put")]) + plan_query("option_history_quote", &one_expiration, 8), + Ok(ShardPlan { + bands: vec![whole_window("call"), whole_window("put")], + listing: None, + }) ); - // The `out_of_the_money` volatility method reads the other side, - // so that chain stays whole. + // The `out_of_the_money` volatility method reads the other side, so + // each expiration keeps both rights and the fallback is one stream. chain.implied_vol_method = Some("out_of_the_money".into()); assert_eq!( plan_query("option_history_binomial_greeks_first_order", &chain, 8), + Ok(ShardPlan { + bands: Vec::new(), + listing: Some(listing(false)), + }) + ); + one_expiration.implied_vol_method = Some("out_of_the_money".into()); + assert_eq!( + plan_query( + "option_history_binomial_greeks_first_order", + &one_expiration, + 8 + ), Err(ShardDecline::IntervalBars) ); chain.implied_vol_method = None; @@ -2174,7 +2457,7 @@ mod tests { Ymd::from_yyyymmdd(start_date).unwrap().to_ord(), Ymd::from_yyyymmdd(end_date).unwrap().to_ord(), ), - ShardBand::Time { .. } => panic!("expected date bands"), + other => panic!("expected date bands, got {other:?}"), }) .collect(); assert_eq!(ords[0].0, Ymd::from_yyyymmdd("20240101").unwrap().to_ord()); @@ -2280,7 +2563,7 @@ mod tests { parse_ms_of_day(start_time).unwrap(), parse_ms_of_day(end_time).unwrap(), ), - ShardBand::Date { .. } => panic!("expected time bands"), + other => panic!("expected time bands, got {other:?}"), } } @@ -2450,7 +2733,7 @@ mod tests { "no right split for a multi-day tick chain" ); } - ShardBand::Time { .. } => panic!("expected date bands"), + other => panic!("expected date bands, got {other:?}"), } } } @@ -2484,7 +2767,7 @@ mod tests { end_date, .. } => assert_eq!(start_date, end_date, "each tick band must be a single day"), - ShardBand::Time { .. } => panic!("expected date bands"), + other => panic!("expected date bands, got {other:?}"), } } } diff --git a/thetadatadx-rs/src/mdds/stream.rs b/thetadatadx-rs/src/mdds/stream.rs index 5b54695e1..3b2a9dde3 100644 --- a/thetadatadx-rs/src/mdds/stream.rs +++ b/thetadatadx-rs/src/mdds/stream.rs @@ -486,7 +486,7 @@ impl MarketDataClient { metrics::counter!("thetadatadx.grpc.requests", "endpoint" => endpoint).increment(1); let started = std::time::Instant::now(); let query = query?; - let ticks = match query.plan(self) { + let ticks = match super::shard::resolve_plan(self, query.plan(self)).await { Some(plan) => { // One independent top-level request per band. Each // spawned task acquires its OWN request permit; this @@ -652,7 +652,7 @@ impl MarketDataClient { let callback = tokio::sync::Mutex::new(callback); let stopped = AtomicBool::new(false); let (callback, stopped) = (&callback, &stopped); - match query.plan(self) { + match super::shard::resolve_plan(self, query.plan(self)).await { Some(plan) => { let policy = &self.config().retry; let mut bands: Vec> = From bca5996f03446cfc3411d613f0942023c14d2828 Mon Sep 17 00:00:00 2001 From: TalesOfThales <101120927+userFRM@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:53:12 +0100 Subject: [PATCH 4/7] fix(shard): keep an OHLC chain over every expiration on one request The server refuses an OHLC chain whose expiration is `*` as a single request, but it serves each expiration on its own, so the expiration split turned a refused pull into a successful one. Bulk fetch must only change how a pull is fetched, never whether the server answers it. The split now applies only to the endpoints whose server serves an every-expiration chain on one request: quotes and the Black-Scholes and binomial Greeks. An OHLC chain keeps the call and put pair, whose requests the server refuses exactly as it refuses the single stream. --- thetadatadx-rs/src/mdds/shard.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/thetadatadx-rs/src/mdds/shard.rs b/thetadatadx-rs/src/mdds/shard.rs index 45d230b2a..b51ac710c 100644 --- a/thetadatadx-rs/src/mdds/shard.rs +++ b/thetadatadx-rs/src/mdds/shard.rs @@ -652,8 +652,18 @@ fn splittable_by_right(q: &ShardQuery) -> bool { /// The listing step of a one-day bar chain over every expiration and /// strike, `None` for any other shape. `window_ms` is the query's window. -fn chain_listing(q: &ShardQuery, window_ms: i64) -> Option { - if q.expiration.as_deref() != Some("*") || q.strike.as_deref().is_some_and(|s| s != "*") { +/// +/// Only endpoints whose server serves an every-expiration chain on one +/// request take it. OHLC refuses that chain, and one request per +/// expiration would answer a pull the single stream cannot. +fn chain_listing(endpoint: &str, q: &ShardQuery, window_ms: i64) -> Option { + let serves_every_expiration = endpoint == "option_history_quote" + || endpoint.starts_with("option_history_greeks_") + || endpoint.starts_with("option_history_binomial_greeks_"); + if !serves_every_expiration + || q.expiration.as_deref() != Some("*") + || q.strike.as_deref().is_some_and(|s| s != "*") + { return None; } let ivl = q.interval.as_deref().and_then(interval_ms)?; @@ -1017,7 +1027,7 @@ fn plan_query(endpoint: &str, q: &ShardQuery, width: usize) -> Result Date: Mon, 9 Nov 2026 15:53:12 +0100 Subject: [PATCH 5/7] feat(config)!: make bulk fetch opt-in Which ways a large pull can be split depends on what the server accepts: the date and time bands rely on its inclusive window semantics, and the expiration split on it serving each expiration of a chain on its own. A change on the server side can break a split before the SDK follows it, so bulk fetch is too dependent on the server to be on by default. `bulk_fetch` now defaults to `"off"`, and every query runs as one request in the server's own order unless the caller sets `bulk_fetch = "auto"`. The README lists bulk fetch among the features with that caveat, and the bulk downloads article shows how to turn it on in each language and states that an OHLC chain over every expiration is refused rather than split. --- CHANGELOG.md | 4 ++- README.md | 1 + docs-site/docs/articles/bulk-downloads.md | 30 ++++++++++++++++--- .../docs/articles/concurrent-requests.md | 4 +-- .../include/config_accessors.h.inc | 6 ++-- .../include/config_accessors.hpp.inc | 6 ++-- .../python/thetadatadx/__init__.pyi | 4 +-- thetadatadx-rs/config.default.toml | 11 +++---- thetadatadx-rs/src/config/mdds.rs | 28 +++++++++-------- thetadatadx-rs/src/config/mod.rs | 10 +++---- thetadatadx-rs/src/surface/config.rs | 6 ++-- thetadatadx-rs/tests/sharded_fanout.rs | 3 +- thetadatadx-ts/index.d.ts | 6 ++-- 13 files changed, 75 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5c5c5745..fd0fb56dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- **A one-day option chain at a bar interval is split across concurrent requests by expiration.** A history pull over every strike at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. The SDK now splits such a chain by contract instead, so every contract's bars still cover the whole window. A chain over every expiration first lists the day's contracts in one request, then fetches each expiration on its own, calls and puts separately. A chain with one expiration, or one whose contract list fails, is fetched as one request for calls and one for puts, and a small chain keeps that pair, since dozens of requests would cost it more than they save. A buffered pull merges the pieces into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. Set `bulk_fetch="off"` to send one request in the server's own order. +- **Bulk fetch is opt-in: `bulk_fetch` now defaults to `"off"`.** How a large pull can be split depends on what the server accepts, and a change on the server side can break a split before the SDK follows it, so every query now runs as one request, in the server's own order, unless you turn the split on. Migration: set `bulk_fetch = "auto"` to keep splitting large history pulls: `config.bulk_fetch = "auto"` in Python, `config.market_data.bulk_fetch = BulkFetchPolicy::Auto` in Rust, `config.setBulkFetch("auto")` in TypeScript, `config.set_bulk_fetch(0)` in C++, or `bulk_fetch = "auto"` under `[market_data]` in a TOML config file. + +- **A one-day option chain at a bar interval is split across concurrent requests by expiration.** A history pull over every strike at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. With `bulk_fetch = "auto"`, the SDK now splits such a chain by contract instead, so every contract's bars still cover the whole window. A chain over every expiration first lists the day's contracts in one request, then fetches each expiration on its own, calls and puts separately. A chain with one expiration, or one whose contract list fails, is fetched as one request for calls and one for puts, and a small chain keeps that pair, since dozens of requests would cost it more than they save. A buffered pull merges the pieces into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. An OHLC chain over every expiration is refused by the server as one request, so it is not split either. - **TypeScript streaming callbacks keep up with a higher message rate.** The native side hands events to the Node main thread in arrays instead of waking it once per event, and the package still calls your `startStreaming` callback once per event, in order. On the offline callback benchmark (`thetadatadx-ts/benches/streaming_throughput.mjs`) a no-op callback goes from about 300k to about 460k events a second, and live on the dev replay server the Node main thread is about a fifth less busy at the same message rate. A callback that throws still ends the process at that event unless an `uncaughtException` handler is installed; with one, the handler gets the error and the rest of the events are still delivered. diff --git a/README.md b/README.md index 08da80516..90a341ea9 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ High-performance market-data SDKs for [ThetaData](https://thetadata.us), in **Py - **Complete coverage**: stocks, options, indices, and rates across 81 typed endpoints. - **Three access modes, one client**: point-in-time history, real-time streaming, and bulk flat-file downloads. +- **Optional bulk fetch**: with `bulk_fetch = "auto"`, a large history pull runs as several concurrent requests within your account's concurrent-request allowance and is merged back into the rows one request returns. It is off by default, because which splits work depends on what the server accepts. See [Bulk Downloads](https://userfrm.github.io/ThetaDataDx/articles/bulk-downloads). - **DataFrames built in**: every result chains straight to Polars, pandas, or Arrow over a zero-copy boundary. - **Greeks on demand**: first- through third-order Greeks and implied volatility, served straight from the option endpoints. - **The same surface in every language**: identical methods and identical typed errors, Python through Rust. diff --git a/docs-site/docs/articles/bulk-downloads.md b/docs-site/docs/articles/bulk-downloads.md index d5769c9fe..8ad7d5bb0 100644 --- a/docs-site/docs/articles/bulk-downloads.md +++ b/docs-site/docs/articles/bulk-downloads.md @@ -29,15 +29,37 @@ Raise them for even fatter streams if you have memory to spare, or lower them wh A single large request does not have to be one stream. The SDK splits the requested time (or date) range into equal concurrent pieces. The split comes straight from the shape of the request, with no sizing round-trip. It then runs them in parallel across your concurrent-request pool and reassembles them into exactly the rows one request would have returned. -A one-day option chain at a bar interval, such as `1s` or `1m`, is split by contract instead of by time: each bar builds up from the start of the requested window, so a piece starting mid-day would return different bars. A chain over every expiration first lists the day's contracts in one small request, then fetches each expiration as its own request, calls and puts separately. A chain with a single expiration splits into calls and puts. Either way, every contract's bars cover the whole window, exactly as one request returns them. +A one-day option chain at a bar interval, such as `1s` or `1m`, is split by contract instead of by time: each bar builds up from the start of the requested window, so a piece starting mid-day would return different bars. A chain over every expiration first lists the day's contracts in one small request, then fetches each expiration as its own request, calls and puts separately. A chain with a single expiration splits into calls and puts. Either way, every contract's bars cover the whole window, exactly as one request returns them. An OHLC chain over every expiration is one the server refuses as a single request, and the SDK returns that same error rather than working around it. The number of pieces is the request-pool size, which defaults to your account's allowance: the SDK sizes the pool to your subscription tier at connect time (Free 1 / Value 2 / Standard 4 / Pro 8), and setting `max_concurrent_requests` overrides that with no client-side cap, because the server enforces the real allowance. See [Concurrent Requests](/articles/concurrent-requests). On Pro, one big query becomes eight pieces fetching at once; a boosted account with `max_concurrent_requests = 32` fans out 32 ways. How much that shortens the wall clock depends on how much of the fan-out the server actually runs in parallel under current conditions; the table below shows one measured day. It scales down cleanly too: four pieces on Standard, two on Value, one on Free. -Sharding is on by default. Small pulls stay a single request, so there is nothing to tune for them. If you want control: +Sharding is opt-in. Which ways a request can be split depends on what the server accepts, and a change on the server side could break a split before the SDK catches up, so every query is one request until you turn it on: -- `bulk_fetch = "off"` runs every query as one request, in the server's own order. +```python +from thetadatadx import Client, Config, Credentials + +cfg = Config.production() +cfg.bulk_fetch = "auto" +client = Client(Credentials.from_file("creds.txt"), cfg) +``` + +```rust +use thetadatadx::config::{BulkFetchPolicy, DirectConfig}; + +let mut cfg = DirectConfig::production(); +cfg.market_data.bulk_fetch = BulkFetchPolicy::Auto; +``` + +```typescript +const cfg = Config.production(); +cfg.setBulkFetch("auto"); +``` + +In a TOML config file, set `bulk_fetch = "auto"` under `[market_data]`. Small pulls stay a single request even then, so there is nothing to tune for them. If you want control: + +- `bulk_fetch = "off"` (the default) runs every query as one request, in the server's own order. - `shard_concurrency` caps how many pieces run at once (default: the full pool). Lower it to leave concurrency free for other requests running at the same time. Sharding only fills the pool you configured. It never exceeds it. @@ -121,7 +143,7 @@ Every setup returns the same rows. A concrete single contract comes back byte-fo | Field | Default | What it does | |---|---|---| -| `bulk_fetch` | `"auto"` | `"auto"` splits large pulls across the request pool; `"off"` runs one request in server order. | +| `bulk_fetch` | `"off"` | `"auto"` splits large pulls across the request pool; `"off"` runs one request in server order. | | `max_concurrent_requests` | your tier | Concurrent-request pool size. Defaults to your subscription tier's allowance; set it to a boosted allowance to go wider (the server enforces the real limit). | | `shard_concurrency` | full pool | Caps pieces per pull. Lower to share concurrency with other requests. | | `stream_window_size_kb` | `8192` | Per-stream HTTP/2 flow-control window, in KB. | diff --git a/docs-site/docs/articles/concurrent-requests.md b/docs-site/docs/articles/concurrent-requests.md index effbed57f..d7834f1de 100644 --- a/docs-site/docs/articles/concurrent-requests.md +++ b/docs-site/docs/articles/concurrent-requests.md @@ -66,12 +66,12 @@ Pick the client by what else you need (streaming, sync calls, a smaller surface) ## One giant request, split for you -The pattern above parallelizes work you have already split into many requests. The SDK also does the reverse for you: a **single** large history request has its time or date range split into equal pieces, run in parallel across the request pool, and reassembled into exactly the rows one request would have returned. You write one ordinary query and it runs at your configured concurrency. This is on by default. +The pattern above parallelizes work you have already split into many requests. The SDK also does the reverse for you: a **single** large history request has its time or date range split into equal pieces, run in parallel across the request pool, and reassembled into exactly the rows one request would have returned. You write one ordinary query and it runs at your configured concurrency. Turn it on with `bulk_fetch = "auto"`. See [Bulk Downloads](/articles/bulk-downloads) for the full picture: how the split works, buffered versus streaming delivery, the `bulk_fetch` and `shard_concurrency` knobs, API examples, and measured performance. ## When parallelism pays -Concurrency multiplies throughput on multi-request workloads: per-day backfills, per-contract chain pulls, anything you can split with `split_date_range`. For a single large request you no longer have to split it yourself, since `bulk_fetch` does it automatically ([above](#one-giant-request-split-for-you)); splitting manually still works when you want direct control over the pieces. +Concurrency multiplies throughput on multi-request workloads: per-day backfills, per-contract chain pulls, anything you can split with `split_date_range`. For a single large request you no longer have to split it yourself, since `bulk_fetch = "auto"` does it for you ([above](#one-giant-request-split-for-you)); splitting manually still works when you want direct control over the pieces. If the service reports exhaustion (because a burst exceeded your account's allowance, or during peak hours), the SDK retries with backoff before surfacing an error. Long-running bulk jobs should expect occasional retries at peak; see [Data Issues?](/articles/data-issues) if a job stalls beyond that. diff --git a/thetadatadx-cpp/include/config_accessors.h.inc b/thetadatadx-cpp/include/config_accessors.h.inc index b348762ab..39edcfde7 100644 --- a/thetadatadx-cpp/include/config_accessors.h.inc +++ b/thetadatadx-cpp/include/config_accessors.h.inc @@ -311,9 +311,9 @@ void thetadatadx_config_set_market_data_connection_window_size_kb(ThetaDataDxCon int32_t thetadatadx_config_get_market_data_connection_window_size_kb(const ThetaDataDxConfig* config, size_t* out_kb); /** Set the automatic bulk-fetch sharding policy for history pulls, covering both the buffered and the chunk-streaming call paths. - * Default `Auto`. + * Default `Off`. * - * - `policy = 0` (`Auto`): a large history pull's requested time or date range is split into equal concurrent bands across the account's concurrent-request budget, decided from the request shape alone (no sizing request is issued). Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + * - `policy = 0` (`Auto`): a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. * - `policy = 1` (`Off`): every query runs as a single stream, in the server's own row and chunk order. * * Returns `0` on success, or `-1` with `thetadatadx_last_error()` set when `config` is null or `policy` is not one of these codes; an unknown code carries `THETADATADX_ERR_INVALID_PARAMETER`. @@ -321,7 +321,7 @@ int32_t thetadatadx_config_get_market_data_connection_window_size_kb(const Theta int32_t thetadatadx_config_set_bulk_fetch(ThetaDataDxConfig* config, int32_t policy); /** Current bulk-fetch sharding policy. - * Default `Auto`. + * Default `Off`. * * Writes the code into `*out_policy`: * diff --git a/thetadatadx-cpp/include/config_accessors.hpp.inc b/thetadatadx-cpp/include/config_accessors.hpp.inc index 52f3e5a3f..192dcb451 100644 --- a/thetadatadx-cpp/include/config_accessors.hpp.inc +++ b/thetadatadx-cpp/include/config_accessors.hpp.inc @@ -400,9 +400,9 @@ } /// Set the automatic bulk-fetch sharding policy for history pulls, covering both the buffered and the chunk-streaming call paths. - /// Default `Auto`. + /// Default `Off`. /// - /// - `0` (`Auto`): a large history pull's requested time or date range is split into equal concurrent bands across the account's concurrent-request budget, decided from the request shape alone (no sizing request is issued). Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + /// - `0` (`Auto`): a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. /// - `1` (`Off`): every query runs as a single stream, in the server's own row and chunk order. /// /// Throws `thetadatadx::InvalidParameterError` on any other code and `thetadatadx::ConfigError` on a null handle. @@ -413,7 +413,7 @@ } /// Current bulk-fetch sharding policy. - /// Default `Auto`. + /// Default `Off`. /// /// Returns the code the setter takes, or `0` on a null handle. int get_bulk_fetch() const { diff --git a/thetadatadx-py/python/thetadatadx/__init__.pyi b/thetadatadx-py/python/thetadatadx/__init__.pyi index 0c2250cf0..f95ddb312 100644 --- a/thetadatadx-py/python/thetadatadx/__init__.pyi +++ b/thetadatadx-py/python/thetadatadx/__init__.pyi @@ -316,11 +316,11 @@ class Config: """ bulk_fetch: Literal["auto", "off"] """Set the automatic bulk-fetch sharding policy for history pulls, covering both the buffered and the chunk-streaming call paths. - Default ``"auto"``. + Default ``"off"``. Accepts, case-insensitively: - - ``"auto"``: a large history pull's requested time or date range is split into equal concurrent bands across the account's concurrent-request budget, decided from the request shape alone (no sizing request is issued). Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + - ``"auto"``: a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. - ``"off"``: every query runs as a single stream, in the server's own row and chunk order. """ shard_concurrency: Optional[int] diff --git a/thetadatadx-rs/config.default.toml b/thetadatadx-rs/config.default.toml index bd7a73181..619178e46 100644 --- a/thetadatadx-rs/config.default.toml +++ b/thetadatadx-rs/config.default.toml @@ -18,11 +18,12 @@ keepalive_timeout_secs = 10 # Max inbound gRPC message size (bytes). Default 4MB. max_message_size = 4194304 -# Bulk-fetch sharding policy for large history pulls. "auto" (default) splits -# a big pull's time or date range into equal concurrent bands across the -# concurrent-request pool; "off" runs every query as a single stream in the -# server's own row and chunk order. Case-insensitive. -# bulk_fetch = "auto" +# Bulk-fetch sharding policy for large history pulls. "off" (default) runs +# every query as a single stream in the server's own row and chunk order; +# "auto" splits a big pull into concurrent requests across the +# concurrent-request pool: equal time or date bands, or one request per +# expiration for a one-day bar chain. Case-insensitive. +# bulk_fetch = "off" # Fan-out cap for bulk_fetch = "auto". Absent (default) uses the full # max_concurrent_requests budget; set a smaller number to reserve capacity. diff --git a/thetadatadx-rs/src/config/mdds.rs b/thetadatadx-rs/src/config/mdds.rs index 66dc72746..6cb2442c2 100644 --- a/thetadatadx-rs/src/config/mdds.rs +++ b/thetadatadx-rs/src/config/mdds.rs @@ -25,10 +25,15 @@ pub(crate) const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 300; /// `.await` on a history builder and the chunk-streaming `.stream*` /// calls alike. /// -/// Under `Auto` (the default) the SDK splits a large history pull into -/// equal disjoint sub-requests along a filter axis (a date band or a -/// time band) — cut from the request's own shape, with no sizing query -/// — and runs them across the channel pool. +/// The fan-out is opt-in: `Off` is the default, and `Auto` turns it on. +/// How a pull can be split depends on what the server accepts, so a +/// server change can break a split before this SDK can follow it. +/// +/// Under `Auto` the SDK splits a large history pull into disjoint +/// sub-requests and runs them across the channel pool: equal date or +/// time bands cut from the request's own shape, or, for a one-day bar +/// chain over every expiration, one request per expiration after a list +/// of the day's contracts. /// /// The buffered path merges the results into exactly the rows the /// single stream would have returned. Row order: single-contract, @@ -55,11 +60,10 @@ pub(crate) const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 300; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[non_exhaustive] pub enum BulkFetchPolicy { - /// Shard large history pulls across the concurrent-request budget - /// (default). - #[default] + /// Shard large history pulls across the concurrent-request budget. Auto, - /// Always issue a single stream per query. + /// Always issue a single stream per query (default). + #[default] Off, } @@ -205,9 +209,9 @@ pub struct MarketDataConfig { /// Automatic bulk-fetch sharding policy for history pulls — buffered /// `.await` and chunk-streaming `.stream*` alike. /// - /// See [`BulkFetchPolicy`]. Default [`BulkFetchPolicy::Auto`]: large - /// history pulls are split into equal concurrent sub-requests across - /// the channel pool. Buffered + /// See [`BulkFetchPolicy`]. Default [`BulkFetchPolicy::Off`]. + /// [`BulkFetchPolicy::Auto`] splits large history pulls into + /// concurrent sub-requests across the channel pool. Buffered /// pulls merge the shards back into exactly the rows of the /// single-stream response — single-contract, stock, and index pulls /// in the exact single-stream order, option-chain pulls in a @@ -302,7 +306,7 @@ impl MarketDataConfig { // operator-visible "you are on the wrong API for this // workload" signal at this boundary. warn_on_buffered_threshold_bytes: 100 * 1024 * 1024, - bulk_fetch: BulkFetchPolicy::Auto, + bulk_fetch: BulkFetchPolicy::Off, // None = the full `max_concurrent_requests` budget. shard_concurrency: None, // None = size the pool to the account's subscription tier at diff --git a/thetadatadx-rs/src/config/mod.rs b/thetadatadx-rs/src/config/mod.rs index 2f2a2d844..6904e2a71 100644 --- a/thetadatadx-rs/src/config/mod.rs +++ b/thetadatadx-rs/src/config/mod.rs @@ -1110,7 +1110,7 @@ mod config_file { keepalive_time_secs: u64, keepalive_timeout_secs: u64, max_message_size: usize, - /// Bulk-fetch sharding policy: `"auto"` (default) or `"off"` + /// Bulk-fetch sharding policy: `"off"` (default) or `"auto"` /// (case-insensitive). An unrecognised value is a load error. bulk_fetch: String, /// Fan-out cap for `bulk_fetch = "auto"`. `None` (key absent) uses @@ -1756,18 +1756,18 @@ mod tests { fn market_data_section_sets_bulk_fetch_and_shard_concurrency() { let toml = r#" [market_data] - bulk_fetch = "off" + bulk_fetch = "auto" shard_concurrency = 4 "#; let config = DirectConfig::from_toml_str(toml).unwrap(); - assert_eq!(config.market_data.bulk_fetch, BulkFetchPolicy::Off); + assert_eq!(config.market_data.bulk_fetch, BulkFetchPolicy::Auto); assert_eq!(config.market_data.shard_concurrency, Some(4)); } #[test] - fn market_data_bulk_fetch_defaults_to_auto_and_shard_none_when_absent() { + fn market_data_bulk_fetch_defaults_to_off_and_shard_none_when_absent() { let config = DirectConfig::from_toml_str("").unwrap(); - assert_eq!(config.market_data.bulk_fetch, BulkFetchPolicy::Auto); + assert_eq!(config.market_data.bulk_fetch, BulkFetchPolicy::Off); assert_eq!(config.market_data.shard_concurrency, None); } diff --git a/thetadatadx-rs/src/surface/config.rs b/thetadatadx-rs/src/surface/config.rs index 1e85174af..16c1473fb 100644 --- a/thetadatadx-rs/src/surface/config.rs +++ b/thetadatadx-rs/src/surface/config.rs @@ -367,9 +367,9 @@ macro_rules! __config { } set thetadatadx_config_set_bulk_fetch(policy: i32) [market_data.bulk_fetch] { param: policy, - default: Auto, + default: Off, values: BulkFetchPolicy { - 0 Auto "a large history pull's requested time or date range is split into equal concurrent bands across the account's concurrent-request budget, decided from the request shape alone (no sizing request is issued). Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded.", + 0 Auto "a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded.", 1 Off "every query runs as a single stream, in the server's own row and chunk order.", }, errors: { @@ -381,7 +381,7 @@ macro_rules! __config { doc: ["Set the automatic bulk-fetch sharding policy for history pulls, covering both the buffered and the chunk-streaming call paths."], } get thetadatadx_config_get_bulk_fetch(out_policy: i32) [market_data.bulk_fetch] { - default: Auto, + default: Off, values: BulkFetchPolicy { 0 Auto, 1 Off }, doc: ["Current bulk-fetch sharding policy."], } diff --git a/thetadatadx-rs/tests/sharded_fanout.rs b/thetadatadx-rs/tests/sharded_fanout.rs index c3d8caa55..b6848bcd7 100644 --- a/thetadatadx-rs/tests/sharded_fanout.rs +++ b/thetadatadx-rs/tests/sharded_fanout.rs @@ -35,7 +35,7 @@ use thetadatadx::wire::{ CompressionAlgo, CompressionDescription, DataTable, DataValue, DataValueList, ResponseData, data_value, }; -use thetadatadx::{DirectConfig, Error, RetryPolicy, ShardBand}; +use thetadatadx::{BulkFetchPolicy, DirectConfig, Error, RetryPolicy, ShardBand}; /// Tag-compatible mirror of the `StockHistoryTradeRequest` / /// `StockHistoryTradeRequestQuery` wire pair, trimmed to the band @@ -352,6 +352,7 @@ async fn client_for_mock_with( retry.max_attempts = 3; retry.jitter = false; cfg.retry = retry; + cfg.market_data.bulk_fetch = BulkFetchPolicy::Auto; cfg.market_data.shard_concurrency = shard_concurrency; let sem = Arc::new(Semaphore::new(width)); MarketDataClient::for_endpoint_routing_test(cfg, pool, sem) diff --git a/thetadatadx-ts/index.d.ts b/thetadatadx-ts/index.d.ts index 9185db817..15d1a4111 100644 --- a/thetadatadx-ts/index.d.ts +++ b/thetadatadx-ts/index.d.ts @@ -505,17 +505,17 @@ export declare class Config { get marketDataConnectionWindowSizeKb(): bigint /** * Set the automatic bulk-fetch sharding policy for history pulls, covering both the buffered and the chunk-streaming call paths. - * Default `"auto"`. + * Default `"off"`. * * Accepts, case-insensitively: * - * - `"auto"`: a large history pull's requested time or date range is split into equal concurrent bands across the account's concurrent-request budget, decided from the request shape alone (no sizing request is issued). Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + * - `"auto"`: a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. * - `"off"`: every query runs as a single stream, in the server's own row and chunk order. */ setBulkFetch(policy: string): void /** * Current bulk-fetch sharding policy. - * Default `"auto"`. + * Default `"off"`. * * Reads as the lowercase name the setter takes. */ From 751195d69368ccd563712918913def95c20c86ea Mon Sep 17 00:00:00 2001 From: TalesOfThales <101120927+userFRM@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:18:41 +0100 Subject: [PATCH 6/7] fix(mdds): wait up to 45 minutes for a silent server by default The server prepares a large response before it sends its first row, and for a one-day chain of one-second bars that preparation can take longer than five minutes. With `request_timeout_secs` at 300, such a pull failed as a stall before any data arrived, although the server would have answered: one request for the SPY chain at one-second bars over ten minutes took 23 minutes in one run and stalled out in the other. The default is now 2700 seconds. The limit still applies only to silence, so a wedged stream still fails, and a caller who wants to give up sooner sets `request_timeout_secs` lower. The flat-file article no longer tells callers to lift the limit for a large download. A download that keeps streaming has no time limit, and lifting the limit would let a stalled download wait forever. --- CHANGELOG.md | 2 +- docs-site/docs/articles/flat-files.md | 11 +++-------- thetadatadx-cpp/include/config_accessors.h.inc | 8 ++++---- .../include/config_accessors.hpp.inc | 8 ++++---- thetadatadx-cpp/tests/config_pool_sizing.cpp | 4 ++-- thetadatadx-ffi/src/auth.rs | 4 ++-- thetadatadx-py/python/thetadatadx/__init__.pyi | 4 ++-- .../tests/test_config_pool_sizing.py | 6 +++--- thetadatadx-rs/config.default.toml | 10 ++++++---- thetadatadx-rs/src/config/mdds.rs | 18 ++++++++++-------- thetadatadx-rs/src/config/mod.rs | 12 ++++++------ thetadatadx-rs/src/surface/config.rs | 8 ++++---- .../__tests__/config_pool_sizing.test.mjs | 4 ++-- thetadatadx-ts/index.d.ts | 8 ++++---- 14 files changed, 53 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd0fb56dc..ae4ac0c29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,7 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **A market-data request without its own deadline is no longer cut off after five minutes.** `request_timeout_secs` (default 300) bounded the whole request, so a large pull that was still streaming, such as a day of one-second quotes across an option chain, failed part way with a deadline error, and a request waiting for a free slot in the request pool spent its time there. It now bounds only how long the server may stay silent: for the response to start, and then between two messages. A pull that keeps streaming runs to completion, through the local server and the MCP server too, while a stalled one still fails, now as a `DeadlineExceeded` status that the retry policy treats as transient, as a flat-file download already did. A per-call deadline (`with_deadline` in Rust, `timeout_ms` elsewhere) still bounds the whole call, and 0 still lifts every limit. Migration: Rust code that matched `Error::Timeout` for the configured limit should match `Error::Grpc { kind: GrpcStatusKind::DeadlineExceeded, .. }`. Python, TypeScript, C and C++ report a stall as the same `DeadlineExceededError` (`THETADATADX_ERR_DEADLINE_EXCEEDED`) as before. +- **A market-data request without its own deadline is no longer cut off after five minutes.** `request_timeout_secs` (default 300) bounded the whole request, so a large pull that was still streaming, such as a day of one-second quotes across an option chain, failed part way with a deadline error, and a request waiting for a free slot in the request pool spent its time there. It now bounds only how long the server may stay silent: for the response to start, and then between two messages. Its default is now 2700 seconds (45 minutes), because the server prepares a large response before sending its first row, and on a one-day chain of one-second bars that can take longer than five minutes. A pull that keeps streaming runs to completion, through the local server and the MCP server too, while a stalled one still fails, now as a `DeadlineExceeded` status that the retry policy treats as transient, as a flat-file download already did. A per-call deadline (`with_deadline` in Rust, `timeout_ms` elsewhere) still bounds the whole call, and 0 still lifts every limit. Migration: Rust code that matched `Error::Timeout` for the configured limit should match `Error::Grpc { kind: GrpcStatusKind::DeadlineExceeded, .. }`. Python, TypeScript, C and C++ report a stall as the same `DeadlineExceededError` (`THETADATADX_ERR_DEADLINE_EXCEEDED`) as before. Set `request_timeout_secs` lower to give up on a silent server sooner. - **A subscribe larger than the command queue no longer fails part way.** One `subscribe_many` (`subscribeMany` in TypeScript) over a whole option chain, such as SPXW quotes and trades within 10% of spot (19,228 streams), could fail with "command queue full" and leave the session subscribed to only part of the list. Subscribe and unsubscribe now wait while the queue to the streaming connection is full, so a call of any size goes through, in every language. The error is returned only if the connection takes no commands for longer than its read timeout. - **A large subscribe no longer spends seconds on bookkeeping.** Each subscribe searched every subscription already made and swept every unanswered one, so one `subscribe_many` over a whole option chain took time that grew with the square of its size, seconds of CPU on the calling thread for the 19,228-stream SPXW chain. Both lookups are now constant time, and the same subscribe takes milliseconds. In Rust, `SubscriptionKind` now implements `Hash`. diff --git a/docs-site/docs/articles/flat-files.md b/docs-site/docs/articles/flat-files.md index 011d4f1d7..fe4a97f8a 100644 --- a/docs-site/docs/articles/flat-files.md +++ b/docs-site/docs/articles/flat-files.md @@ -32,15 +32,13 @@ The most recent **7 calendar days** are available; the prior day is generally re ## Pull a file -A small file (stock or index EOD) comes back whole like any other endpoint. The trade-quote, quote and option files are far larger: stream them chunk by chunk, and lift the per-request deadline, which defaults to 300 seconds and would end a long download early. +A small file (stock or index EOD) comes back whole like any other endpoint. The trade-quote, quote and option files are far larger: stream them chunk by chunk. A download that keeps streaming has no time limit; the SDK gives up only when the server sends nothing for `request_timeout_secs` (default 2700 seconds). diff --git a/thetadatadx-cpp/include/config_accessors.h.inc b/thetadatadx-cpp/include/config_accessors.h.inc index 39edcfde7..f8147c911 100644 --- a/thetadatadx-cpp/include/config_accessors.h.inc +++ b/thetadatadx-cpp/include/config_accessors.h.inc @@ -274,13 +274,13 @@ int32_t thetadatadx_config_get_warn_on_buffered_threshold_bytes(const ThetaDataD /** Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. * - * A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. - * Default `300` (5 minutes). + * A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). The default leaves room for the server to prepare a large response, such as a one-day chain of one-second bars, before its first row. Zero does not disable the limit: it is floored to the 2700-second default at request time. + * Default `2700` (45 minutes). */ void thetadatadx_config_set_request_timeout_secs(ThetaDataDxConfig* config, uint64_t secs); -/** Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit. - * Default `300` (5 minutes). +/** Current `market_data.request_timeout_secs` value. A stored zero is floored to the 2700-second default at request time rather than disabling the limit. + * Default `2700` (45 minutes). * * Writes the value into `*out`. Returns `0` on success, `-1` if either pointer is null. */ diff --git a/thetadatadx-cpp/include/config_accessors.hpp.inc b/thetadatadx-cpp/include/config_accessors.hpp.inc index 192dcb451..2cef44bf0 100644 --- a/thetadatadx-cpp/include/config_accessors.hpp.inc +++ b/thetadatadx-cpp/include/config_accessors.hpp.inc @@ -351,14 +351,14 @@ /// Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. /// - /// A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. - /// Default `300` (5 minutes). + /// A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). The default leaves room for the server to prepare a large response, such as a one-day chain of one-second bars, before its first row. Zero does not disable the limit: it is floored to the 2700-second default at request time. + /// Default `2700` (45 minutes). void set_request_timeout_secs(std::uint64_t secs) { thetadatadx_config_set_request_timeout_secs(handle_.get(), secs); } - /// Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit. - /// Default `300` (5 minutes). + /// Current `market_data.request_timeout_secs` value. A stored zero is floored to the 2700-second default at request time rather than disabling the limit. + /// Default `2700` (45 minutes). /// /// Returns `0` on a null handle. std::uint64_t get_request_timeout_secs() const { diff --git a/thetadatadx-cpp/tests/config_pool_sizing.cpp b/thetadatadx-cpp/tests/config_pool_sizing.cpp index 740a3f259..44d70d697 100644 --- a/thetadatadx-cpp/tests/config_pool_sizing.cpp +++ b/thetadatadx-cpp/tests/config_pool_sizing.cpp @@ -17,8 +17,8 @@ TEST_CASE("Config market-data request_timeout_secs setter + getter round-trip", // The readback getter mirrors the Python `Config.request_timeout_secs` // and TypeScript `requestTimeoutSecs` surfaces, so a value set // through the C++ wrapper reads back through the same wrapper. - // Production seeds the 300s default per-request deadline. - REQUIRE(cfg.get_request_timeout_secs() == 300u); + // Production seeds the 45-minute default silence limit. + REQUIRE(cfg.get_request_timeout_secs() == 2700u); cfg.set_request_timeout_secs(45); REQUIRE(cfg.get_request_timeout_secs() == 45u); cfg.set_request_timeout_secs(600); diff --git a/thetadatadx-ffi/src/auth.rs b/thetadatadx-ffi/src/auth.rs index 4b9e823bd..0b605829f 100644 --- a/thetadatadx-ffi/src/auth.rs +++ b/thetadatadx-ffi/src/auth.rs @@ -903,13 +903,13 @@ mod pool_sizing_tests { assert!(!cfg.is_null()); // SAFETY: handle just returned by thetadatadx_config_production. unsafe { - // Default seeded at 300s by `MarketDataConfig::default()`. + // Default seeded at 2700s by `MarketDataConfig::default()`. let mut current: u64 = 0; assert_eq!( super::thetadatadx_config_get_request_timeout_secs(cfg, &mut current), 0 ); - assert_eq!(current, 300); + assert_eq!(current, 2700); // Override. super::thetadatadx_config_set_request_timeout_secs(cfg, 45); assert_eq!((*cfg).inner.market_data.request_timeout_secs, 45); diff --git a/thetadatadx-py/python/thetadatadx/__init__.pyi b/thetadatadx-py/python/thetadatadx/__init__.pyi index f95ddb312..4d79a484a 100644 --- a/thetadatadx-py/python/thetadatadx/__init__.pyi +++ b/thetadatadx-py/python/thetadatadx/__init__.pyi @@ -303,8 +303,8 @@ class Config: request_timeout_secs: int """Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. - A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. - Default ``300`` (5 minutes). + A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). The default leaves room for the server to prepare a large response, such as a one-day chain of one-second bars, before its first row. Zero does not disable the limit: it is floored to the 2700-second default at request time. + Default ``2700`` (45 minutes). """ market_data_stream_window_size_kb: int """Set the initial per-stream HTTP/2 flow-control window, in KB, for the market-data gRPC channel. A larger window raises the throughput ceiling on bulk streaming pulls before HTTP/2 backpressure kicks in. The value is clamped into ``[64, 2_097_151]`` KB at validate/connect time. diff --git a/thetadatadx-py/tests/test_config_pool_sizing.py b/thetadatadx-py/tests/test_config_pool_sizing.py index 52c75da14..61e688471 100644 --- a/thetadatadx-py/tests/test_config_pool_sizing.py +++ b/thetadatadx-py/tests/test_config_pool_sizing.py @@ -23,11 +23,11 @@ def _import_module(): # ─── request_timeout_secs ─────────────────────────────────────────── -def test_request_timeout_secs_defaults_to_300(): - """`request_timeout_secs` defaults to the 300s per-request deadline.""" +def test_request_timeout_secs_defaults_to_2700(): + """`request_timeout_secs` defaults to the 45-minute silence limit.""" mod = _import_module() cfg = mod.Config.production() - assert cfg.request_timeout_secs == 300 + assert cfg.request_timeout_secs == 2700 def test_request_timeout_secs_round_trips(): diff --git a/thetadatadx-rs/config.default.toml b/thetadatadx-rs/config.default.toml index 619178e46..9abc6e143 100644 --- a/thetadatadx-rs/config.default.toml +++ b/thetadatadx-rs/config.default.toml @@ -43,10 +43,12 @@ max_message_size = 4194304 # How long a market-data request may wait on a silent server (seconds), for # the response to start and then for each next message; a request that keeps -# streaming has no total limit. Default 300. A 0 is floored to 300 at request -# time, so a silent server cannot hang a request; opt a single request out -# with with_deadline(0) instead. Not range-limited. -# request_timeout_secs = 300 +# streaming has no total limit. Default 2700 (45 minutes), room for the server +# to prepare a large response such as a one-day chain of one-second bars. A 0 +# is floored to 2700 at request time, so a silent server cannot hang a +# request; opt a single request out with with_deadline(0) instead. Not +# range-limited. +# request_timeout_secs = 2700 # Buffered-response size (bytes) above which a warning is logged. Default # 104857600 (100 MiB). diff --git a/thetadatadx-rs/src/config/mdds.rs b/thetadatadx-rs/src/config/mdds.rs index 6cb2442c2..851683920 100644 --- a/thetadatadx-rs/src/config/mdds.rs +++ b/thetadatadx-rs/src/config/mdds.rs @@ -11,7 +11,7 @@ //! See `docs-site/docs/configuration.md` for the per-binding setter //! samples. -/// Default market-data silence limit in seconds (5 min). +/// Default market-data silence limit in seconds (45 min). /// /// The floor the request-limit resolver applies when the configured /// `request_timeout_secs` is `0`: a `0` there would disable the gRPC hang @@ -19,7 +19,7 @@ /// server could hang the client forever. The per-call /// `with_deadline(Duration::ZERO)` opt-out is a separate, explicit path and is /// unaffected by this floor. -pub(crate) const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 300; +pub(crate) const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 2700; /// Policy for automatic sharding of large history pulls — the buffered /// `.await` on a history builder and the chunk-streaming `.stream*` @@ -170,7 +170,7 @@ pub struct MarketDataConfig { /// /// Configuring `0` here does **not** disable the guard: the request- /// limit resolver every market-data request routes through floors a `0` - /// to the production default (`300s`), regardless of whether the config + /// to the production default (`2700s`), regardless of whether the config /// was validated. Opt a single request out with the per-call escape /// hatch instead. /// @@ -178,8 +178,9 @@ pub struct MarketDataConfig { /// the whole request instead, and `with_deadline(Duration::ZERO)` /// lifts every limit for that request. /// - /// Default `300s` (5 min): a server that is preparing a response - /// answers well inside it, and a wedged stream still fails. + /// Default `2700s` (45 min): the server prepares a large response + /// before its first row, which on a one-day chain of one-second bars + /// can take longer than five minutes, and a wedged stream still fails. pub request_timeout_secs: u64, /// Estimated-bytes threshold above which the buffered `.await` @@ -294,10 +295,11 @@ impl MarketDataConfig { stream_window_size_kb: 8_192, connection_window_size_kb: 16_384, connect_timeout_secs: 10, - // 5 min — bounds a server that holds the stream open while + // 45 min — bounds a server that holds the stream open while // sending no chunks (h2 keepalive only catches a fully dead - // peer). Sits above the slowest realistic bulk pull; - // `with_deadline(Duration::ZERO)` opts a single request out. + // peer), with room for the long prepare of a one-second bar + // chain; `with_deadline(Duration::ZERO)` opts a single + // request out. request_timeout_secs: DEFAULT_REQUEST_TIMEOUT_SECS, // 100 MiB — empirically catches bulk pulls (multi-million // row option-chain or multi-day backfill responses) while diff --git a/thetadatadx-rs/src/config/mod.rs b/thetadatadx-rs/src/config/mod.rs index 6904e2a71..0ff5a2413 100644 --- a/thetadatadx-rs/src/config/mod.rs +++ b/thetadatadx-rs/src/config/mod.rs @@ -1127,9 +1127,9 @@ mod config_file { /// gRPC connect timeout (seconds). `validate` enforces the same /// range as the programmatic path. connect_timeout_secs: u64, - /// Per-request market-data deadline (seconds). Default `300`; not - /// range-limited. A `0` is stored verbatim and floored to `300` at - /// request time, so it does not disable the deadline. + /// Market-data silence limit (seconds). Default `2700`; not + /// range-limited. A `0` is stored verbatim and floored to `2700` at + /// request time, so it does not disable the limit. request_timeout_secs: u64, /// Buffered-response size (bytes) above which a warning is logged. /// Default `104_857_600` (100 MiB). @@ -1830,7 +1830,7 @@ mod tests { fn market_data_timeouts_default_when_absent() { let config = DirectConfig::from_toml_str("").unwrap(); assert_eq!(config.market_data.connect_timeout_secs, 10); - assert_eq!(config.market_data.request_timeout_secs, 300); + assert_eq!(config.market_data.request_timeout_secs, 2700); assert_eq!( config.market_data.warn_on_buffered_threshold_bytes, 100 * 1024 * 1024 @@ -2399,11 +2399,11 @@ mod tests { fn market_data_defaults_match_production_baseline() { let mdds = crate::config::MarketDataConfig::production_defaults(); // The buffered-response warn fires at 100 MiB by default, and - // the per-request deadline is the 300s ceiling. Channel-pool + // the silence limit is 45 minutes. Channel-pool // concurrency carries no default here — it is resolved from // the subscription tier at connect time. assert_eq!(mdds.warn_on_buffered_threshold_bytes, 100 * 1024 * 1024); - assert_eq!(mdds.request_timeout_secs, 300); + assert_eq!(mdds.request_timeout_secs, 2700); } // ── RetryPolicy / env var tests ────────────────────────────────── diff --git a/thetadatadx-rs/src/surface/config.rs b/thetadatadx-rs/src/surface/config.rs index 16c1473fb..c9219324e 100644 --- a/thetadatadx-rs/src/surface/config.rs +++ b/thetadatadx-rs/src/surface/config.rs @@ -336,16 +336,16 @@ macro_rules! __config { } set thetadatadx_config_set_request_timeout_secs(secs: u64) [market_data.request_timeout_secs] { param: secs, - default: 300 "5 minutes", + default: 2700 "45 minutes", doc: [ "Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message.", "", - "A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time.", + "A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). The default leaves room for the server to prepare a large response, such as a one-day chain of one-second bars, before its first row. Zero does not disable the limit: it is floored to the 2700-second default at request time.", ], } get thetadatadx_config_get_request_timeout_secs(out: u64) [market_data.request_timeout_secs] { - default: 300 "5 minutes", - doc: ["Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit."], + default: 2700 "45 minutes", + doc: ["Current `market_data.request_timeout_secs` value. A stored zero is floored to the 2700-second default at request time rather than disabling the limit."], } set thetadatadx_config_set_market_data_stream_window_size_kb(kb: usize) [market_data.stream_window_size_kb] { param: kb, diff --git a/thetadatadx-ts/__tests__/config_pool_sizing.test.mjs b/thetadatadx-ts/__tests__/config_pool_sizing.test.mjs index 287a85678..614d90062 100644 --- a/thetadatadx-ts/__tests__/config_pool_sizing.test.mjs +++ b/thetadatadx-ts/__tests__/config_pool_sizing.test.mjs @@ -22,9 +22,9 @@ try { const { Config } = mod; describe('Config.requestTimeoutSecs', () => { - it('defaults to 300n (5-minute per-request deadline)', () => { + it('defaults to 2700n (45-minute silence limit)', () => { const cfg = Config.production(); - assert.equal(cfg.requestTimeoutSecs, 300n); + assert.equal(cfg.requestTimeoutSecs, 2700n); }); it('round-trips through the setter; 0n disables the default', () => { diff --git a/thetadatadx-ts/index.d.ts b/thetadatadx-ts/index.d.ts index 15d1a4111..64803a4c7 100644 --- a/thetadatadx-ts/index.d.ts +++ b/thetadatadx-ts/index.d.ts @@ -474,13 +474,13 @@ export declare class Config { /** * Set how long (seconds) a market-data request may wait on a silent server: for the response to start, and then for each next message. * - * A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). Zero does not disable the limit: it is floored to the 300-second default at request time. - * Default `300n` (5 minutes). + * A request that did not set its own deadline has no limit on its total length, so a large pull that keeps streaming runs to completion, while a live-but-silent stream fails as a stall instead of blocking forever (the gRPC keepalive PING only detects a fully dead peer). The default leaves room for the server to prepare a large response, such as a one-day chain of one-second bars, before its first row. Zero does not disable the limit: it is floored to the 2700-second default at request time. + * Default `2700n` (45 minutes). */ setRequestTimeoutSecs(secs: bigint): void /** - * Current `market_data.request_timeout_secs` value. A stored zero is floored to the 300-second default at request time rather than disabling the limit. - * Default `300n` (5 minutes). + * Current `market_data.request_timeout_secs` value. A stored zero is floored to the 2700-second default at request time rather than disabling the limit. + * Default `2700n` (45 minutes). */ get requestTimeoutSecs(): bigint /** From 92ff3daf1c2341607d4409928c2569a128b5087c Mon Sep 17 00:00:00 2001 From: TalesOfThales <101120927+userFRM@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:40:26 +0100 Subject: [PATCH 7/7] perf(shard): split a one-day quote-tick chain over every expiration by expiration A time split of a quote-tick chain does not divide the server's work: every time band still carries the whole chain, and the server prepares all of it before it sends a band's first row. On SPXW quote ticks from 09:30 to 09:45, the single request and the time split each sent nothing for five minutes, while one request per expiration and right returned 108,872,335 rows in 247 seconds. DIA over the same window took 75 seconds on the time split and 17 on the expiration split, with the same rows. A quote-tick chain over every expiration now takes the listing step a bar chain takes, sized at one quote a second per contract, and keeps its time bands as the fallback when the list fails or the chain is too small. Trades are not split this way: a trade chain is sparse enough that one request per expiration made SPXW trades about twice as slow as the time split. --- CHANGELOG.md | 2 +- docs-site/docs/articles/bulk-downloads.md | 2 +- .../include/config_accessors.h.inc | 2 +- .../include/config_accessors.hpp.inc | 2 +- .../python/thetadatadx/__init__.pyi | 2 +- thetadatadx-rs/src/config/mdds.rs | 6 +- thetadatadx-rs/src/mdds/shard.rs | 77 ++++++++++++------- thetadatadx-rs/src/surface/config.rs | 2 +- thetadatadx-ts/index.d.ts | 2 +- 9 files changed, 61 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae4ac0c29..9c3ff7bd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Bulk fetch is opt-in: `bulk_fetch` now defaults to `"off"`.** How a large pull can be split depends on what the server accepts, and a change on the server side can break a split before the SDK follows it, so every query now runs as one request, in the server's own order, unless you turn the split on. Migration: set `bulk_fetch = "auto"` to keep splitting large history pulls: `config.bulk_fetch = "auto"` in Python, `config.market_data.bulk_fetch = BulkFetchPolicy::Auto` in Rust, `config.setBulkFetch("auto")` in TypeScript, `config.set_bulk_fetch(0)` in C++, or `bulk_fetch = "auto"` under `[market_data]` in a TOML config file. -- **A one-day option chain at a bar interval is split across concurrent requests by expiration.** A history pull over every strike at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. With `bulk_fetch = "auto"`, the SDK now splits such a chain by contract instead, so every contract's bars still cover the whole window. A chain over every expiration first lists the day's contracts in one request, then fetches each expiration on its own, calls and puts separately. A chain with one expiration, or one whose contract list fails, is fetched as one request for calls and one for puts, and a small chain keeps that pair, since dozens of requests would cost it more than they save. A buffered pull merges the pieces into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. An OHLC chain over every expiration is refused by the server as one request, so it is not split either. +- **A one-day option chain at a bar interval is split across concurrent requests by expiration.** A history pull over every strike at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. With `bulk_fetch = "auto"`, the SDK now splits such a chain by contract instead, so every contract's bars still cover the whole window. A chain over every expiration first lists the day's contracts in one request, then fetches each expiration on its own, calls and puts separately. A chain with one expiration, or one whose contract list fails, is fetched as one request for calls and one for puts, and a small chain keeps that pair, since dozens of requests would cost it more than they save. A buffered pull merges the pieces into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. Quote ticks over every expiration split the same way: the server prepares the whole chain for every piece of a time split, so on SPXW those pieces sent nothing for minutes, while one request per expiration started at once. A trade chain keeps the time split, because its trades are too few for one request per expiration to pay. An OHLC chain over every expiration is refused by the server as one request, so it is not split either. - **TypeScript streaming callbacks keep up with a higher message rate.** The native side hands events to the Node main thread in arrays instead of waking it once per event, and the package still calls your `startStreaming` callback once per event, in order. On the offline callback benchmark (`thetadatadx-ts/benches/streaming_throughput.mjs`) a no-op callback goes from about 300k to about 460k events a second, and live on the dev replay server the Node main thread is about a fifth less busy at the same message rate. A callback that throws still ends the process at that event unless an `uncaughtException` handler is installed; with one, the handler gets the error and the rest of the events are still delivered. diff --git a/docs-site/docs/articles/bulk-downloads.md b/docs-site/docs/articles/bulk-downloads.md index 8ad7d5bb0..5cf0380fd 100644 --- a/docs-site/docs/articles/bulk-downloads.md +++ b/docs-site/docs/articles/bulk-downloads.md @@ -29,7 +29,7 @@ Raise them for even fatter streams if you have memory to spare, or lower them wh A single large request does not have to be one stream. The SDK splits the requested time (or date) range into equal concurrent pieces. The split comes straight from the shape of the request, with no sizing round-trip. It then runs them in parallel across your concurrent-request pool and reassembles them into exactly the rows one request would have returned. -A one-day option chain at a bar interval, such as `1s` or `1m`, is split by contract instead of by time: each bar builds up from the start of the requested window, so a piece starting mid-day would return different bars. A chain over every expiration first lists the day's contracts in one small request, then fetches each expiration as its own request, calls and puts separately. A chain with a single expiration splits into calls and puts. Either way, every contract's bars cover the whole window, exactly as one request returns them. An OHLC chain over every expiration is one the server refuses as a single request, and the SDK returns that same error rather than working around it. +A one-day option chain at a bar interval, such as `1s` or `1m`, is split by contract instead of by time: each bar builds up from the start of the requested window, so a piece starting mid-day would return different bars. A chain over every expiration first lists the day's contracts in one small request, then fetches each expiration as its own request, calls and puts separately. A chain with a single expiration splits into calls and puts. Either way, every contract's bars cover the whole window, exactly as one request returns them. Quote ticks over every expiration split the same way, because the server prepares the whole chain for every piece of a time split; a trade chain keeps the time split, since it is too sparse for one request per expiration to pay. An OHLC chain over every expiration is one the server refuses as a single request, and the SDK returns that same error rather than working around it. The number of pieces is the request-pool size, which defaults to your account's allowance: the SDK sizes the pool to your subscription tier at connect time (Free 1 / Value 2 / Standard 4 / Pro 8), and setting `max_concurrent_requests` overrides that with no client-side cap, because the server enforces the real allowance. See [Concurrent Requests](/articles/concurrent-requests). diff --git a/thetadatadx-cpp/include/config_accessors.h.inc b/thetadatadx-cpp/include/config_accessors.h.inc index f8147c911..ceb45e354 100644 --- a/thetadatadx-cpp/include/config_accessors.h.inc +++ b/thetadatadx-cpp/include/config_accessors.h.inc @@ -313,7 +313,7 @@ int32_t thetadatadx_config_get_market_data_connection_window_size_kb(const Theta /** Set the automatic bulk-fetch sharding policy for history pulls, covering both the buffered and the chunk-streaming call paths. * Default `Off`. * - * - `policy = 0` (`Auto`): a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + * - `policy = 0` (`Auto`): a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar or quote-tick chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. * - `policy = 1` (`Off`): every query runs as a single stream, in the server's own row and chunk order. * * Returns `0` on success, or `-1` with `thetadatadx_last_error()` set when `config` is null or `policy` is not one of these codes; an unknown code carries `THETADATADX_ERR_INVALID_PARAMETER`. diff --git a/thetadatadx-cpp/include/config_accessors.hpp.inc b/thetadatadx-cpp/include/config_accessors.hpp.inc index 2cef44bf0..97cb03eaa 100644 --- a/thetadatadx-cpp/include/config_accessors.hpp.inc +++ b/thetadatadx-cpp/include/config_accessors.hpp.inc @@ -402,7 +402,7 @@ /// Set the automatic bulk-fetch sharding policy for history pulls, covering both the buffered and the chunk-streaming call paths. /// Default `Off`. /// - /// - `0` (`Auto`): a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + /// - `0` (`Auto`): a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar or quote-tick chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. /// - `1` (`Off`): every query runs as a single stream, in the server's own row and chunk order. /// /// Throws `thetadatadx::InvalidParameterError` on any other code and `thetadatadx::ConfigError` on a null handle. diff --git a/thetadatadx-py/python/thetadatadx/__init__.pyi b/thetadatadx-py/python/thetadatadx/__init__.pyi index 4d79a484a..8d8e31382 100644 --- a/thetadatadx-py/python/thetadatadx/__init__.pyi +++ b/thetadatadx-py/python/thetadatadx/__init__.pyi @@ -320,7 +320,7 @@ class Config: Accepts, case-insensitively: - - ``"auto"``: a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + - ``"auto"``: a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar or quote-tick chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. - ``"off"``: every query runs as a single stream, in the server's own row and chunk order. """ shard_concurrency: Optional[int] diff --git a/thetadatadx-rs/src/config/mdds.rs b/thetadatadx-rs/src/config/mdds.rs index 851683920..6ba630c6b 100644 --- a/thetadatadx-rs/src/config/mdds.rs +++ b/thetadatadx-rs/src/config/mdds.rs @@ -31,9 +31,9 @@ pub(crate) const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 2700; /// /// Under `Auto` the SDK splits a large history pull into disjoint /// sub-requests and runs them across the channel pool: equal date or -/// time bands cut from the request's own shape, or, for a one-day bar -/// chain over every expiration, one request per expiration after a list -/// of the day's contracts. +/// time bands cut from the request's own shape, or, for a one-day bar or +/// quote-tick chain over every expiration, one request per expiration +/// after a list of the day's contracts. /// /// The buffered path merges the results into exactly the rows the /// single stream would have returned. Row order: single-contract, diff --git a/thetadatadx-rs/src/mdds/shard.rs b/thetadatadx-rs/src/mdds/shard.rs index b51ac710c..7e2721655 100644 --- a/thetadatadx-rs/src/mdds/shard.rs +++ b/thetadatadx-rs/src/mdds/shard.rs @@ -8,9 +8,10 @@ //! span, not equal rows: a deliberate trade that costs zero extra //! round-trips and zero per-endpoint tuning, and the concurrency win //! dominates the residual row imbalance between bands. The one exception -//! is a one-day bar chain over every expiration, which no time band can -//! cut: it lists the day's contracts first (one request) and fans out one -//! request per expiration (see `resolve_plan`). The buffered `.await` path merges the shard +//! is a one-day quoted chain over every expiration: a time band cannot cut +//! its bars, and every time band of its quote ticks still carries the +//! whole chain. It lists the day's contracts first (one request) and fans +//! out one request per expiration (see `resolve_plan`). The buffered `.await` path merges the shard //! responses back into exactly the rows the single-stream response would //! have carried — in the exact server order for single-contract / stock / //! index pulls, in a deterministic canonical contract order for chains @@ -264,8 +265,9 @@ pub enum ShardBand { right: Option, }, /// One expiration of an option chain over the query's whole window. - /// A one-day chain at a bar interval splits this way: each bar - /// accumulates from the window start, so a time band would change it. + /// A one-day quoted chain splits this way: each bar accumulates from + /// the window start, so a time band would change it, and every time + /// band of its quote ticks still carries the whole chain. Expiration { /// The band's expiration (`YYYYMMDD`). expiration: String, @@ -311,8 +313,9 @@ pub(crate) struct ChainListing { pub right: Option, /// Whether each expiration splits again into a call and a put band. pub split_rights: bool, - /// Bars one contract returns over the query's window. - pub bars_per_contract: u64, + /// Rows one contract returns over the query's window: its bars at a + /// bar interval, or one quote a second as the estimate for ticks. + pub rows_per_contract: u64, } /// Wire-level view of a history query, as consumed by the shard planner. @@ -512,9 +515,9 @@ impl ShardDecline { /// window and declines everything else as [`ShardDecline::IntervalBars`].) const SHARD_MIN_GRID_ROWS: u64 = 10_000_000; -/// Bar ceiling below which a listed one-day chain keeps the call/put pair +/// Row estimate below which a listed one-day chain keeps its fallback bands /// rather than one request per expiration. A chain this small finishes in -/// seconds on two streams, and the extra round trips of dozens of small +/// seconds on a few streams, and the extra round trips of dozens of small /// requests would add back what the wider fan-out saves. const EXPIRATION_SPLIT_MIN_ROWS: u64 = 1_000_000; @@ -650,12 +653,14 @@ fn splittable_by_right(q: &ShardQuery) -> bool { && q.implied_vol_method.as_deref() != Some("out_of_the_money") } -/// The listing step of a one-day bar chain over every expiration and -/// strike, `None` for any other shape. `window_ms` is the query's window. +/// The listing step of a one-day chain over every expiration and strike, +/// `None` for any other shape. `window_ms` is the query's window. /// /// Only endpoints whose server serves an every-expiration chain on one /// request take it. OHLC refuses that chain, and one request per -/// expiration would answer a pull the single stream cannot. +/// expiration would answer a pull the single stream cannot. Trades are +/// not among them: a trade chain is sparse enough that one request per +/// expiration costs more round trips than the time bands it replaces. fn chain_listing(endpoint: &str, q: &ShardQuery, window_ms: i64) -> Option { let serves_every_expiration = endpoint == "option_history_quote" || endpoint.starts_with("option_history_greeks_") @@ -666,7 +671,11 @@ fn chain_listing(endpoint: &str, q: &ShardQuery, window_ms: i64) -> Option None, Some("call") => Some('C'), @@ -679,7 +688,7 @@ fn chain_listing(endpoint: &str, q: &ShardQuery, window_ms: i64) -> Option = in_chain.map(|c| c.expiration).collect(); if expirations.len() < 2 || rows < EXPIRATION_SPLIT_MIN_ROWS { return None; @@ -1025,9 +1034,11 @@ fn plan_query(endpoint: &str, q: &ShardQuery, width: usize) -> Result Result Ok(ShardPlan { + bands: Vec::new(), + listing, + }), + None => Err(ShardDecline::NarrowWindow), + }; } Ok(ShardPlan { bands: time_bands(start_ms, end_ms, n, None), - listing: None, + listing, }) } ShardAxis::Date => { @@ -1967,6 +1981,17 @@ mod tests { assert_eq!(pair[1].0, pair[0].1 + 1, "bands abut within a right"); } } + // Those bands are the fallback: the quote chain lists its contracts + // and splits by expiration, at one quote a second per contract. + // A trade chain is too sparse for that and keeps the time bands. + let listing = plan + .listing + .expect("a quote-tick chain lists its contracts"); + assert!(listing.split_rights); + assert_eq!(listing.rows_per_contract, 23_401); + let trades = plan_query("option_history_trade", &chain_day_query(), 8) + .expect("a trade chain shards on time"); + assert_eq!((trades.bands.len(), trades.listing), (8, None)); } #[test] @@ -2178,13 +2203,13 @@ mod tests { expiration: expiration.into(), right: right.map(str::to_owned), }; - let listing = |right, split_rights, bars_per_contract| ChainListing { + let listing = |right, split_rights, rows_per_contract| ChainListing { symbol: "SPXW".into(), date: "20260710".into(), max_dte: None, right, split_rights, - bars_per_contract, + rows_per_contract, }; let big = EXPIRATION_SPLIT_MIN_ROWS; assert_eq!( @@ -2256,7 +2281,7 @@ mod tests { max_dte: None, right: None, split_rights, - bars_per_contract: 23_401, + rows_per_contract: 23_401, }; assert_eq!( plan_query("option_history_quote", &chain, 8), diff --git a/thetadatadx-rs/src/surface/config.rs b/thetadatadx-rs/src/surface/config.rs index c9219324e..369805bd2 100644 --- a/thetadatadx-rs/src/surface/config.rs +++ b/thetadatadx-rs/src/surface/config.rs @@ -369,7 +369,7 @@ macro_rules! __config { param: policy, default: Off, values: BulkFetchPolicy { - 0 Auto "a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded.", + 0 Auto "a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar or quote-tick chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded.", 1 Off "every query runs as a single stream, in the server's own row and chunk order.", }, errors: { diff --git a/thetadatadx-ts/index.d.ts b/thetadatadx-ts/index.d.ts index 64803a4c7..b591ec4f3 100644 --- a/thetadatadx-ts/index.d.ts +++ b/thetadatadx-ts/index.d.ts @@ -509,7 +509,7 @@ export declare class Config { * * Accepts, case-insensitively: * - * - `"auto"`: a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. + * - `"auto"`: a large history pull is split into concurrent requests across the account's concurrent-request budget: its requested time or date range into equal bands, decided from the request shape alone, or, for a one-day bar or quote-tick chain over every expiration, one request per expiration after one request that lists the day's contracts. Buffered pulls merge the shards back into exactly the rows of the single-stream response: single-contract, stock, and index pulls keep the exact single-stream row order, while option-chain pulls come back in a deterministic canonical order (expiration, strike, right ascending; calls before puts; time-ascending within each contract). Streaming pulls forward each band's chunks to the handler as they arrive: every chunk exactly once, but chunks from different bands interleave in arrival order rather than the single stream's order. Small pulls and non-history endpoints are never sharded. * - `"off"`: every query runs as a single stream, in the server's own row and chunk order. */ setBulkFetch(policy: string): void