Skip to main content

query/
options.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::path::PathBuf;
17
18use chrono::{DateTime, Utc};
19use common_base::memory_limit::MemoryLimit;
20use common_base::readable_size::ReadableSize;
21use datafusion::config::{ConfigEntry, ConfigExtension, ExtensionOptions};
22use serde::{Deserialize, Serialize};
23use session::context::QueryContextRef;
24use store_api::storage::RegionId;
25use table::metadata::TableId;
26
27use crate::error::{Error, InvalidQueryContextExtensionSnafu, Result};
28
29pub const FLOW_INCREMENTAL_AFTER_SEQS: &str = "flow.incremental_after_seqs";
30pub const FLOW_INCREMENTAL_MODE: &str = "flow.incremental_mode";
31pub const FLOW_RETURN_REGION_SEQ: &str = "flow.return_region_seq";
32pub const FLOW_SINK_TABLE_ID: &str = "flow.sink_table_id";
33/// Flow scheduler binding for the logical time of one scheduled attempt.
34/// Query planning, SQL/TQL parsing, range-select rewrite and DataFusion
35/// execution read this extension so `now()` is stable for the whole attempt.
36pub const FLOW_SCHEDULED_TIME_MILLIS: &str = "flow.scheduled_time_millis";
37/// Enable by default, set to false to explicitly disable.
38pub const QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN: &str =
39    "query.enable_remote_dynamic_filter_pushdown";
40
41pub const FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY: &str = "memtable_only";
42pub const FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE: &str = "sequence_range";
43
44/// Query spill mode controlling disk manager behavior.
45#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
46#[serde(rename_all = "snake_case")]
47pub enum QuerySpillMode {
48    /// Preserve DataFusion default disk manager behavior (OS temp directory).
49    Default,
50    /// Explicitly configure spill path, quota, and compression.
51    Custom,
52    /// Explicitly disable disk spilling; temporary file creation will error.
53    Disabled,
54}
55
56/// Compression for spilled data files.
57#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
58#[serde(rename_all = "snake_case")]
59pub enum QuerySpillCompression {
60    /// No compression (default, matches DataFusion default).
61    Uncompressed,
62    /// LZ4 frame compression.
63    Lz4Frame,
64    /// Zstandard compression.
65    Zstd,
66}
67
68/// Memory pool allocation policy.
69#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
70#[serde(rename_all = "snake_case")]
71pub enum QueryMemoryPoolPolicy {
72    /// Greedy first-come-first-served (default).
73    Greedy,
74    /// Fair divides memory available after unspillable reservations evenly among
75    /// spillable reservations and may trigger earlier spills.
76    Fair,
77}
78
79#[derive(Debug, Clone, Default)]
80pub struct FactorizedJoinAggOptions {
81    pub enabled: bool,
82}
83
84impl ConfigExtension for FactorizedJoinAggOptions {
85    const PREFIX: &'static str = "factorized_join_agg";
86}
87
88impl ExtensionOptions for FactorizedJoinAggOptions {
89    fn as_any(&self) -> &dyn std::any::Any {
90        self
91    }
92    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
93        self
94    }
95    fn cloned(&self) -> Box<dyn ExtensionOptions> {
96        Box::new(self.clone())
97    }
98    fn set(&mut self, key: &str, value: &str) -> datafusion::error::Result<()> {
99        Err(datafusion::common::DataFusionError::NotImplemented(
100            format!("FactorizedJoinAggOptions does not support set key: {key} with value: {value}"),
101        ))
102    }
103    fn entries(&self) -> Vec<ConfigEntry> {
104        vec![ConfigEntry {
105            key: "enabled".to_string(),
106            value: Some(self.enabled.to_string()),
107            description: "Enable experimental factorized join aggregation",
108        }]
109    }
110}
111
112/// Query engine configuration options.
113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
114#[serde(default)]
115pub struct QueryOptions {
116    /// Parallelism of query engine. Default to 0, which implies the number of logical CPUs.
117    pub parallelism: usize,
118    /// Whether to allow query fallback when push down fails.
119    pub allow_query_fallback: bool,
120    /// Experimental: enable shape-based factorized AVG/SUM join aggregation. Default false.
121    pub experimental_enable_factorized_join_agg: bool,
122    /// Memory pool size for query execution. Setting it to 0 disables the limit (unbounded).
123    /// Supports absolute size (e.g., "2GB") or percentage (e.g., "50%").
124    /// When this limit is reached, queries will fail with ResourceExhausted error.
125    pub memory_pool_size: MemoryLimit,
126    /// Whether to expose per-region query load metrics.
127    #[serde(skip)]
128    pub enable_per_region_metrics: bool,
129    /// Experimental: spill-to-disk mode.
130    /// - `default`: preserve DataFusion built-in OS temp directory behavior.
131    /// - `custom`: explicitly configure spill path, max directory size, and compression.
132    /// - `disabled`: explicitly disable disk spilling.
133    pub experimental_spill_mode: QuerySpillMode,
134    /// Experimental: spill directory path. Ignored unless `experimental_spill_mode` is
135    /// `"custom"`. When set, spill files are written into this directory.
136    pub experimental_spill_path: Option<PathBuf>,
137    /// Experimental: maximum total size of the spill directory (data written to spill files).
138    /// Ignored unless `experimental_spill_mode` is `"custom"`. Default: `1GiB`.
139    pub experimental_spill_max_temp_directory_size: ReadableSize,
140    /// Experimental: compression algorithm applied to spilled data.
141    /// Ignored unless `experimental_spill_mode` is `"custom"`. Default: `uncompressed`.
142    pub experimental_spill_compression: QuerySpillCompression,
143    /// Experimental: memory pool allocation policy.
144    /// - `greedy`: Greedy first-come-first-served (default).
145    /// - `fair`: Fair divides memory available after unspillable reservations
146    ///   evenly among spillable reservations and may trigger earlier spills.
147    pub experimental_memory_pool_policy: QueryMemoryPoolPolicy,
148    /// Enables the experimental native PromQL execution path for compatible queries. This
149    /// path currently applies only to standalone queries using in-process region transport.
150    ///
151    /// This is the engine-wide default. A session `SET query.experimental_native_promql = true`
152    /// or a per-request `query.experimental_native_promql` option overrides it, in that order, so
153    /// a `true` default routes every query natively and a `false` one still lets one query or one
154    /// session ask for it. Default: `false`.
155    pub experimental_native_promql: bool,
156    /// Hosts that object stores built from SQL statements (`COPY`, `COPY DATABASE`,
157    /// `EXPORT/IMPORT DATABASE` and external tables) may connect to. Empty means no restriction.
158    pub remote_allowed_hosts: Vec<String>,
159    /// Whether such an object store without credentials in its connection options may use the
160    /// server's own credentials.
161    pub allow_server_credentials: bool,
162}
163
164#[allow(clippy::derivable_impls)]
165impl Default for QueryOptions {
166    fn default() -> Self {
167        Self {
168            parallelism: 0,
169            allow_query_fallback: false,
170            experimental_enable_factorized_join_agg: false,
171            memory_pool_size: MemoryLimit::default(),
172            enable_per_region_metrics: false,
173            experimental_spill_mode: QuerySpillMode::Default,
174            experimental_spill_path: None,
175            experimental_spill_max_temp_directory_size: ReadableSize::gb(1),
176            experimental_spill_compression: QuerySpillCompression::Uncompressed,
177            experimental_memory_pool_policy: QueryMemoryPoolPolicy::Greedy,
178            experimental_native_promql: false,
179            remote_allowed_hosts: Vec::new(),
180            allow_server_credentials: true,
181        }
182    }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum FlowIncrementalMode {
187    MemtableOnly,
188    SequenceRange,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Default)]
192pub struct FlowQueryExtensions {
193    /// Maps region id -> lower exclusive sequence bound for incremental reads.
194    pub incremental_after_seqs: Option<HashMap<u64, u64>>,
195    /// Incremental read mode requested by the caller.
196    pub incremental_mode: Option<FlowIncrementalMode>,
197    /// Whether the caller expects per-region watermark metadata in terminal metrics.
198    pub return_region_seq: bool,
199    /// Optional sink table id used to distinguish source scans from sink reads.
200    pub sink_table_id: Option<TableId>,
201}
202
203impl FlowQueryExtensions {
204    /// Parses flow-specific query extensions when any flow key is present.
205    ///
206    /// Returns `Ok(None)` for ordinary queries with no flow-related extensions,
207    /// `Ok(Some(_))` when flow context is present and valid, and `Err(_)` when a
208    /// flow-related extension is present but malformed or incomplete.
209    pub fn parse_flow_extensions(extensions: &HashMap<String, String>) -> Result<Option<Self>> {
210        let has_flow_context = extensions.contains_key(FLOW_INCREMENTAL_AFTER_SEQS)
211            || extensions.contains_key(FLOW_INCREMENTAL_MODE)
212            || extensions.contains_key(FLOW_RETURN_REGION_SEQ)
213            || extensions.contains_key(FLOW_SINK_TABLE_ID);
214
215        if !has_flow_context {
216            return Ok(None);
217        }
218
219        let incremental_mode = extensions
220            .get(FLOW_INCREMENTAL_MODE)
221            .map(|value| match value.as_str() {
222                v if v.eq_ignore_ascii_case(FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY) => {
223                    Ok(FlowIncrementalMode::MemtableOnly)
224                }
225                v if v.eq_ignore_ascii_case(FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE) => {
226                    Ok(FlowIncrementalMode::SequenceRange)
227                }
228                _ => Err(invalid_query_context_extension(format!(
229                    "Invalid value for {}: {}",
230                    FLOW_INCREMENTAL_MODE, value
231                ))),
232            })
233            .transpose()?;
234
235        let incremental_after_seqs = extensions
236            .get(FLOW_INCREMENTAL_AFTER_SEQS)
237            .map(|value| parse_incremental_after_seqs(value.as_str()))
238            .transpose()?;
239
240        let return_region_seq = extensions
241            .get(FLOW_RETURN_REGION_SEQ)
242            .map(|value| parse_bool(FLOW_RETURN_REGION_SEQ, value.as_str()))
243            .transpose()?
244            .unwrap_or(false);
245
246        let sink_table_id = extensions
247            .get(FLOW_SINK_TABLE_ID)
248            .map(|value| {
249                value.parse::<TableId>().map_err(|_| {
250                    invalid_query_context_extension(format!(
251                        "Invalid value for {}: {}",
252                        FLOW_SINK_TABLE_ID, value
253                    ))
254                })
255            })
256            .transpose()?;
257
258        if matches!(
259            incremental_mode,
260            Some(FlowIncrementalMode::MemtableOnly | FlowIncrementalMode::SequenceRange)
261        ) {
262            let mode = if incremental_mode == Some(FlowIncrementalMode::MemtableOnly) {
263                FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY
264            } else {
265                FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE
266            };
267            let after_seqs = incremental_after_seqs.as_ref().ok_or_else(|| {
268                invalid_query_context_extension(format!(
269                    "{} is required when {}={}.",
270                    FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode
271                ))
272            })?;
273            if after_seqs.is_empty() {
274                return Err(invalid_query_context_extension(format!(
275                    "{} must not be empty when {}={}.",
276                    FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode
277                )));
278            }
279        }
280
281        Ok(Some(Self {
282            incremental_after_seqs,
283            incremental_mode,
284            return_region_seq,
285            sink_table_id,
286        }))
287    }
288
289    pub fn validate_for_scan(&self, source_region_id: RegionId) -> Result<bool> {
290        if self.sink_table_id.is_some() && self.sink_table_id == Some(source_region_id.table_id()) {
291            return Ok(false);
292        }
293
294        if matches!(
295            self.incremental_mode,
296            Some(FlowIncrementalMode::MemtableOnly | FlowIncrementalMode::SequenceRange)
297        ) {
298            let mode = if self.incremental_mode == Some(FlowIncrementalMode::MemtableOnly) {
299                FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY
300            } else {
301                FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE
302            };
303            let after_seqs = self.incremental_after_seqs.as_ref().ok_or_else(|| {
304                invalid_query_context_extension(format!(
305                    "{} is required when {}={}.",
306                    FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode
307                ))
308            })?;
309
310            if !after_seqs.contains_key(&source_region_id.as_u64()) {
311                return Err(invalid_query_context_extension(format!(
312                    "Missing region {} in {} when {}={}.",
313                    source_region_id, FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, mode
314                )));
315            }
316        }
317
318        Ok(self.incremental_after_seqs.is_some())
319    }
320
321    pub fn should_collect_region_watermark(&self) -> bool {
322        should_collect_region_watermark(
323            self.return_region_seq,
324            self.incremental_after_seqs.is_some(),
325        )
326    }
327}
328
329/// Returns whether query-level remote dynamic filter propagation is enabled.
330///
331/// The option defaults to enabled to preserve existing behavior. Callers may set
332/// `query.enable_remote_dynamic_filter_pushdown=false` in query context
333/// extensions to disable FE->DN remote dynamic filter propagation for a single
334/// query.
335pub fn remote_dyn_filter_pushdown_enabled_from_extensions(
336    extensions: &HashMap<String, String>,
337) -> Result<bool> {
338    extensions
339        .get(QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN)
340        .map(|value| parse_bool(QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN, value.as_str()))
341        .transpose()
342        .map(|value| value.unwrap_or(true))
343}
344
345/// Returns whether raw Flow query extensions request terminal region watermark collection.
346///
347/// This is only an intent/presence check for transport/scan plumbing; callers that need
348/// validated Flow options must still use [`FlowQueryExtensions::parse_flow_extensions`].
349pub fn should_collect_region_watermark_from_extensions(
350    extensions: &HashMap<String, String>,
351) -> bool {
352    let return_region_seq = extensions
353        .get(FLOW_RETURN_REGION_SEQ)
354        .is_some_and(|value| value.eq_ignore_ascii_case("true"));
355    let has_incremental_after_seqs = extensions.contains_key(FLOW_INCREMENTAL_AFTER_SEQS);
356
357    should_collect_region_watermark(return_region_seq, has_incremental_after_seqs)
358}
359
360fn should_collect_region_watermark(
361    return_region_seq: bool,
362    has_incremental_after_seqs: bool,
363) -> bool {
364    return_region_seq || has_incremental_after_seqs
365}
366
367fn parse_incremental_after_seqs(value: &str) -> Result<HashMap<u64, u64>> {
368    let raw = serde_json::from_str::<HashMap<String, serde_json::Value>>(value).map_err(|e| {
369        invalid_query_context_extension(format!(
370            "Invalid JSON for {}: {} ({})",
371            FLOW_INCREMENTAL_AFTER_SEQS, value, e
372        ))
373    })?;
374
375    raw.into_iter()
376        .map(|(region_id, raw_seq)| {
377            let region_id = region_id.parse::<u64>().map_err(|_| {
378                invalid_query_context_extension(format!(
379                    "Invalid region id in {}: {}",
380                    FLOW_INCREMENTAL_AFTER_SEQS, region_id
381                ))
382            })?;
383
384            let seq = match raw_seq {
385                serde_json::Value::Number(num) => num.as_u64().ok_or_else(|| {
386                    invalid_query_context_extension(format!(
387                        "Invalid sequence value in {} for region {}: {}",
388                        FLOW_INCREMENTAL_AFTER_SEQS, region_id, num
389                    ))
390                })?,
391                serde_json::Value::String(s) => s.parse::<u64>().map_err(|_| {
392                    invalid_query_context_extension(format!(
393                        "Invalid sequence string in {} for region {}: {}",
394                        FLOW_INCREMENTAL_AFTER_SEQS, region_id, s
395                    ))
396                })?,
397                _ => {
398                    return Err(invalid_query_context_extension(format!(
399                        "Invalid sequence value type in {} for region {}",
400                        FLOW_INCREMENTAL_AFTER_SEQS, region_id
401                    )));
402                }
403            };
404
405            Ok((region_id, seq))
406        })
407        .collect()
408}
409
410fn parse_bool(option_name: &str, value: &str) -> Result<bool> {
411    match value {
412        v if v.eq_ignore_ascii_case("true") => Ok(true),
413        v if v.eq_ignore_ascii_case("false") => Ok(false),
414        _ => Err(invalid_query_context_extension(format!(
415            "Invalid value for {}: {}",
416            option_name, value
417        ))),
418    }
419}
420
421/// Parse the scheduled time (in milliseconds since Unix epoch) from extensions.
422///
423/// Returns `Ok(None)` if the extension key is absent, `Ok(Some(millis))` on success,
424/// or `Err` if the value is malformed.
425pub fn parse_scheduled_time_millis(extensions: &HashMap<String, String>) -> Result<Option<i64>> {
426    match extensions.get(FLOW_SCHEDULED_TIME_MILLIS) {
427        Some(val) => val.parse::<i64>().map(Some).map_err(|_| {
428            invalid_query_context_extension(format!(
429                "Invalid value for {}: {}",
430                FLOW_SCHEDULED_TIME_MILLIS, val
431            ))
432        }),
433        None => Ok(None),
434    }
435}
436
437/// Parse the scheduled time from extensions into a [`DateTime<Utc>`].
438///
439/// Returns `Ok(None)` if the extension key is absent, `Ok(Some(datetime))` on success,
440/// or `Err` if the value is malformed.  Millis that produce an out-of-range timestamp are
441/// also rejected.
442pub fn parse_scheduled_time_datetime(
443    extensions: &HashMap<String, String>,
444) -> Result<Option<DateTime<Utc>>> {
445    match parse_scheduled_time_millis(extensions)? {
446        Some(millis) => DateTime::from_timestamp_millis(millis)
447            .map(Some)
448            .ok_or_else(|| {
449                invalid_query_context_extension(format!(
450                    "Out-of-range timestamp for {}: {} ms",
451                    FLOW_SCHEDULED_TIME_MILLIS, millis
452                ))
453            }),
454        None => Ok(None),
455    }
456}
457
458/// Best-effort helper: extract scheduled time from a [`QueryContextRef`] as a [`DateTime<Utc>`].
459///
460/// Errors are silently swallowed, returning `None`; use [`parse_scheduled_time_datetime`]
461/// at call sites that need to reject malformed scheduled time.
462pub fn scheduled_time_from_ctx(query_ctx: &QueryContextRef) -> Option<DateTime<Utc>> {
463    let extensions = query_ctx.extensions();
464    parse_scheduled_time_datetime(&extensions).ok().flatten()
465}
466
467/// Carries the scheduled logical "now" through [`ConfigOptions::extensions`] so
468/// that the distributed plan analyzer can apply it during expression
469/// simplification (preventing wall-clock constant-folding of `now()`).
470#[derive(Debug, Clone)]
471pub(crate) struct ScheduledTimeExtension {
472    pub(crate) scheduled_time: Option<DateTime<Utc>>,
473}
474
475impl ConfigExtension for ScheduledTimeExtension {
476    const PREFIX: &'static str = "flow_scheduled_time";
477}
478
479impl ExtensionOptions for ScheduledTimeExtension {
480    fn as_any(&self) -> &dyn std::any::Any {
481        self
482    }
483
484    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
485        self
486    }
487
488    fn cloned(&self) -> Box<dyn ExtensionOptions> {
489        Box::new(self.clone())
490    }
491
492    fn set(&mut self, key: &str, value: &str) -> datafusion::error::Result<()> {
493        Err(datafusion_common::DataFusionError::NotImplemented(format!(
494            "ScheduledTimeExtension does not support set key: {key} with value: {value}"
495        )))
496    }
497
498    fn entries(&self) -> Vec<ConfigEntry> {
499        vec![]
500    }
501}
502
503/// Carries the native PromQL route switch a query asked for through
504/// [`ConfigOptions::extensions`].
505///
506/// The value is resolved once per query, where the query options snapshot is applied to the
507/// planning state: the request extension
508/// [`NATIVE_PROMQL_EXTENSION_KEY`](crate::promql::planner::NATIVE_PROMQL_EXTENSION_KEY) over a
509/// session `SET` of the same option over the engine-wide
510/// [`QueryOptions::experimental_native_promql`] default. Planning and `SHOW` both read it back from
511/// there, so a query that states nothing routes as the engine default says.
512///
513/// What it records is the *request*, not the plan the query got: planning still applies the
514/// conditions that decide whether the route can be taken at all (a statement that allows query
515/// fallback or one planned inside a CTE keeps the existing plan whatever this says), so `SHOW
516/// query.experimental_native_promql` answers what the query asked for.
517#[derive(Debug, Clone, Copy)]
518pub(crate) struct NativePromqlExtension {
519    pub(crate) requested: bool,
520}
521
522impl ConfigExtension for NativePromqlExtension {
523    const PREFIX: &'static str = "native_promql";
524}
525
526impl ExtensionOptions for NativePromqlExtension {
527    fn as_any(&self) -> &dyn std::any::Any {
528        self
529    }
530
531    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
532        self
533    }
534
535    fn cloned(&self) -> Box<dyn ExtensionOptions> {
536        Box::new(*self)
537    }
538
539    fn set(&mut self, key: &str, value: &str) -> datafusion::error::Result<()> {
540        Err(datafusion_common::DataFusionError::NotImplemented(format!(
541            "NativePromqlExtension does not support set key: {key} with value: {value}"
542        )))
543    }
544
545    fn entries(&self) -> Vec<ConfigEntry> {
546        vec![ConfigEntry {
547            key: "requested".to_string(),
548            value: Some(self.requested.to_string()),
549            description: "Whether the query requests the native fused-series PromQL route",
550        }]
551    }
552}
553
554fn invalid_query_context_extension(reason: String) -> Error {
555    InvalidQueryContextExtensionSnafu { reason }.build()
556}
557
558#[cfg(test)]
559mod flow_extension_tests {
560    use super::*;
561
562    #[test]
563    fn test_parse_flow_extensions_returns_none_for_non_flow_query() {
564        let exts = HashMap::new();
565        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap();
566
567        assert_eq!(parsed, None);
568    }
569
570    #[test]
571    fn test_remote_dyn_filter_pushdown_enabled_from_extensions_defaults_true() {
572        assert!(remote_dyn_filter_pushdown_enabled_from_extensions(&HashMap::new()).unwrap());
573    }
574
575    #[test]
576    fn test_remote_dyn_filter_pushdown_enabled_from_extensions_parses_bool() {
577        let exts = HashMap::from([(
578            QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN.to_string(),
579            "false".to_string(),
580        )]);
581        assert!(!remote_dyn_filter_pushdown_enabled_from_extensions(&exts).unwrap());
582
583        let exts = HashMap::from([(
584            QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN.to_string(),
585            "true".to_string(),
586        )]);
587        assert!(remote_dyn_filter_pushdown_enabled_from_extensions(&exts).unwrap());
588    }
589
590    #[test]
591    fn test_remote_dyn_filter_pushdown_enabled_from_extensions_rejects_invalid_bool() {
592        let exts = HashMap::from([(
593            QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN.to_string(),
594            "invalid".to_string(),
595        )]);
596
597        let err = remote_dyn_filter_pushdown_enabled_from_extensions(&exts).unwrap_err();
598        assert!(format!("{err}").contains(QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN));
599    }
600
601    #[test]
602    fn test_parse_flow_extensions_memtable_only_success() {
603        let exts = HashMap::from([
604            (
605                FLOW_INCREMENTAL_MODE.to_string(),
606                FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY.to_string(),
607            ),
608            (
609                FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
610                r#"{"1":10,"2":20}"#.to_string(),
611            ),
612            (FLOW_RETURN_REGION_SEQ.to_string(), "true".to_string()),
613            (FLOW_SINK_TABLE_ID.to_string(), "1024".to_string()),
614        ]);
615
616        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
617            .unwrap()
618            .unwrap();
619        assert_eq!(
620            parsed.incremental_mode,
621            Some(FlowIncrementalMode::MemtableOnly)
622        );
623        assert_eq!(
624            parsed.incremental_after_seqs.unwrap(),
625            HashMap::from([(1, 10), (2, 20)])
626        );
627        assert!(parsed.return_region_seq);
628        assert_eq!(parsed.sink_table_id, Some(1024));
629    }
630
631    #[test]
632    fn test_parse_flow_extensions_sequence_range_success() {
633        let exts = HashMap::from([
634            (
635                FLOW_INCREMENTAL_MODE.to_string(),
636                FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(),
637            ),
638            (
639                FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
640                r#"{"1":10}"#.to_string(),
641            ),
642        ]);
643
644        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
645            .unwrap()
646            .unwrap();
647        assert_eq!(
648            parsed.incremental_mode,
649            Some(FlowIncrementalMode::SequenceRange)
650        );
651        assert_eq!(
652            parsed.incremental_after_seqs,
653            Some(HashMap::from([(1, 10)]))
654        );
655    }
656
657    #[test]
658    fn test_parse_flow_extensions_sequence_range_rejects_empty_after_seqs() {
659        let exts = HashMap::from([
660            (
661                FLOW_INCREMENTAL_MODE.to_string(),
662                FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(),
663            ),
664            (FLOW_INCREMENTAL_AFTER_SEQS.to_string(), "{}".to_string()),
665        ]);
666
667        let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err();
668        assert!(format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS));
669    }
670
671    #[test]
672    fn test_parse_flow_extensions_sequence_range_requires_after_seqs() {
673        let exts = HashMap::from([(
674            FLOW_INCREMENTAL_MODE.to_string(),
675            FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(),
676        )]);
677
678        let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err();
679        assert!(format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS));
680    }
681
682    #[test]
683    fn test_parse_flow_extensions_mode_requires_after_seqs() {
684        let exts = HashMap::from([(
685            FLOW_INCREMENTAL_MODE.to_string(),
686            FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY.to_string(),
687        )]);
688
689        let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err();
690        assert!(format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS));
691    }
692
693    #[test]
694    fn test_parse_flow_extensions_invalid_mode() {
695        let exts = HashMap::from([(FLOW_INCREMENTAL_MODE.to_string(), "foo".to_string())]);
696
697        let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err();
698        assert!(format!("{err}").contains(FLOW_INCREMENTAL_MODE));
699    }
700
701    #[test]
702    fn test_parse_flow_extensions_invalid_after_seqs_json() {
703        let exts = HashMap::from([
704            (
705                FLOW_INCREMENTAL_MODE.to_string(),
706                FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY.to_string(),
707            ),
708            (
709                FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
710                "not-json".to_string(),
711            ),
712        ]);
713
714        let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err();
715        assert!(format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS));
716    }
717
718    #[test]
719    fn test_parse_flow_extensions_after_seqs_string_values() {
720        let exts = HashMap::from([(
721            FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
722            r#"{"1":"10","2":"20"}"#.to_string(),
723        )]);
724
725        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
726            .unwrap()
727            .unwrap();
728        assert_eq!(
729            parsed.incremental_after_seqs.unwrap(),
730            HashMap::from([(1, 10), (2, 20)])
731        );
732    }
733
734    #[test]
735    fn test_parse_flow_extensions_after_seqs_invalid_value_type() {
736        let exts = HashMap::from([(
737            FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
738            r#"{"1":true}"#.to_string(),
739        )]);
740
741        let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err();
742        assert!(format!("{err}").contains(FLOW_INCREMENTAL_AFTER_SEQS));
743    }
744
745    #[test]
746    fn test_parse_flow_extensions_invalid_sink_table_id() {
747        let exts = HashMap::from([(FLOW_SINK_TABLE_ID.to_string(), "x".to_string())]);
748
749        let err = FlowQueryExtensions::parse_flow_extensions(&exts).unwrap_err();
750        assert!(format!("{err}").contains(FLOW_SINK_TABLE_ID));
751    }
752
753    #[test]
754    fn test_validate_for_scan_missing_source_region() {
755        let source_region_id = RegionId::new(100, 2);
756        let existing_region_id = RegionId::new(100, 1);
757        let exts = HashMap::from([
758            (
759                FLOW_INCREMENTAL_MODE.to_string(),
760                FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY.to_string(),
761            ),
762            (
763                FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
764                format!(r#"{{"{}":10}}"#, existing_region_id.as_u64()),
765            ),
766        ]);
767
768        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
769            .unwrap()
770            .unwrap();
771        let err = parsed.validate_for_scan(source_region_id).unwrap_err();
772        assert!(format!("{err}").contains("Missing region"));
773    }
774
775    #[test]
776    fn test_validate_for_scan_sink_table_excluded() {
777        let source_region_id = RegionId::new(1024, 1);
778        let exts = HashMap::from([
779            (
780                FLOW_INCREMENTAL_MODE.to_string(),
781                FLOW_INCREMENTAL_MODE_MEMTABLE_ONLY.to_string(),
782            ),
783            (
784                FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
785                format!(r#"{{"{}":10}}"#, source_region_id.as_u64()),
786            ),
787            (FLOW_SINK_TABLE_ID.to_string(), "1024".to_string()),
788        ]);
789
790        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
791            .unwrap()
792            .unwrap();
793        let apply_incremental = parsed.validate_for_scan(source_region_id).unwrap();
794        assert!(!apply_incremental);
795    }
796
797    #[test]
798    fn test_should_collect_region_watermark_defaults_false() {
799        let parsed = FlowQueryExtensions::default();
800        assert!(!parsed.should_collect_region_watermark());
801    }
802
803    #[test]
804    fn test_should_collect_region_watermark_true_for_return_region_seq() {
805        let parsed = FlowQueryExtensions {
806            return_region_seq: true,
807            ..Default::default()
808        };
809        assert!(parsed.should_collect_region_watermark());
810    }
811
812    #[test]
813    fn test_should_collect_region_watermark_true_for_incremental_query() {
814        let parsed = FlowQueryExtensions {
815            incremental_after_seqs: Some(HashMap::from([(1, 10)])),
816            ..Default::default()
817        };
818        assert!(parsed.should_collect_region_watermark());
819    }
820
821    #[test]
822    fn test_should_collect_region_watermark_from_extensions() {
823        let exts = HashMap::from([(FLOW_RETURN_REGION_SEQ.to_string(), "true".to_string())]);
824        assert!(should_collect_region_watermark_from_extensions(&exts));
825
826        let exts = HashMap::from([(
827            FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
828            r#"{"1":10}"#.to_string(),
829        )]);
830        assert!(should_collect_region_watermark_from_extensions(&exts));
831
832        let exts = HashMap::from([(FLOW_RETURN_REGION_SEQ.to_string(), "false".to_string())]);
833        assert!(!should_collect_region_watermark_from_extensions(&exts));
834        assert!(!should_collect_region_watermark_from_extensions(
835            &HashMap::new()
836        ));
837    }
838
839    #[test]
840    fn test_parse_flow_extensions_return_region_seq_only_returns_some() {
841        let exts = HashMap::from([(FLOW_RETURN_REGION_SEQ.to_string(), "true".to_string())]);
842
843        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
844            .unwrap()
845            .unwrap();
846
847        assert!(parsed.return_region_seq);
848    }
849
850    #[test]
851    fn test_parse_flow_extensions_sink_table_only_returns_some() {
852        let exts = HashMap::from([(FLOW_SINK_TABLE_ID.to_string(), "1024".to_string())]);
853
854        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
855            .unwrap()
856            .unwrap();
857
858        assert_eq!(parsed.sink_table_id, Some(1024));
859    }
860
861    #[test]
862    fn test_parse_flow_extensions_incremental_after_seqs_only_returns_some() {
863        let exts = HashMap::from([(
864            FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
865            r#"{"1":10}"#.to_string(),
866        )]);
867
868        let parsed = FlowQueryExtensions::parse_flow_extensions(&exts)
869            .unwrap()
870            .unwrap();
871
872        assert_eq!(
873            parsed.incremental_after_seqs,
874            Some(HashMap::from([(1, 10)]))
875        );
876    }
877
878    // --- scheduled time helper tests ---
879
880    #[test]
881    fn test_parse_scheduled_time_millis_absent() {
882        let exts = HashMap::new();
883        assert_eq!(parse_scheduled_time_millis(&exts).unwrap(), None);
884    }
885
886    #[test]
887    fn test_parse_scheduled_time_millis_valid() {
888        let exts = HashMap::from([(
889            FLOW_SCHEDULED_TIME_MILLIS.to_string(),
890            "1700000000000".to_string(),
891        )]);
892        assert_eq!(
893            parse_scheduled_time_millis(&exts).unwrap(),
894            Some(1700000000000)
895        );
896    }
897
898    #[test]
899    fn test_parse_scheduled_time_millis_malformed() {
900        let exts = HashMap::from([(
901            FLOW_SCHEDULED_TIME_MILLIS.to_string(),
902            "not-a-number".to_string(),
903        )]);
904        let err = parse_scheduled_time_millis(&exts).unwrap_err();
905        assert!(format!("{err}").contains(FLOW_SCHEDULED_TIME_MILLIS));
906    }
907
908    #[test]
909    fn test_parse_scheduled_time_datetime_valid() {
910        let exts = HashMap::from([(
911            FLOW_SCHEDULED_TIME_MILLIS.to_string(),
912            "1700000000000".to_string(),
913        )]);
914        let dt = parse_scheduled_time_datetime(&exts).unwrap().unwrap();
915        assert_eq!(dt.timestamp_millis(), 1700000000000);
916    }
917
918    #[test]
919    fn test_parse_scheduled_time_datetime_negative_millis() {
920        let exts = HashMap::from([(FLOW_SCHEDULED_TIME_MILLIS.to_string(), "-1".to_string())]);
921        let dt = parse_scheduled_time_datetime(&exts).unwrap().unwrap();
922        assert_eq!(dt.timestamp_millis(), -1);
923    }
924
925    #[test]
926    fn test_parse_scheduled_time_datetime_out_of_range() {
927        // i64::MAX millis is well beyond representable chrono::DateTime range
928        let exts = HashMap::from([(FLOW_SCHEDULED_TIME_MILLIS.to_string(), i64::MAX.to_string())]);
929        let err = parse_scheduled_time_datetime(&exts).unwrap_err();
930        assert!(format!("{err}").contains("Out-of-range"));
931    }
932}
933
934#[cfg(test)]
935mod query_options_tests {
936    use super::*;
937
938    #[test]
939    fn test_parse_spill_options_from_toml() {
940        let toml_str = r#"
941experimental_spill_mode = "custom"
942experimental_spill_path = "/tmp/spill"
943experimental_spill_max_temp_directory_size = "50GiB"
944experimental_spill_compression = "zstd"
945experimental_memory_pool_policy = "fair"
946"#;
947        let opts: QueryOptions = toml::from_str(toml_str).unwrap();
948        assert_eq!(opts.experimental_spill_mode, QuerySpillMode::Custom);
949        assert_eq!(
950            opts.experimental_spill_path,
951            Some(PathBuf::from("/tmp/spill"))
952        );
953        assert_eq!(
954            opts.experimental_spill_max_temp_directory_size,
955            ReadableSize::gb(50)
956        );
957        assert_eq!(
958            opts.experimental_spill_compression,
959            QuerySpillCompression::Zstd
960        );
961        assert_eq!(
962            opts.experimental_memory_pool_policy,
963            QueryMemoryPoolPolicy::Fair
964        );
965    }
966
967    /// The native PromQL route is opt-in: a query that states nothing keeps the plan the
968    /// existing planner builds.
969    ///
970    /// The per-request `query.experimental_native_promql` extension is read by
971    /// `query::promql::planner::native::native_promql_requested`; this default is the other
972    /// half of that gate today, and it becomes the only gate for a query that states nothing
973    /// once #10262 lands. Flipping it would expose the native route to every query that sets
974    /// the extension.
975    #[test]
976    fn test_native_promql_is_off_by_default() {
977        assert!(!QueryOptions::default().experimental_native_promql);
978    }
979
980    #[test]
981    fn test_parse_invalid_spill_option_values() {
982        for toml_str in [
983            r#"experimental_spill_mode = "invalid""#,
984            r#"experimental_spill_compression = "gzip""#,
985            r#"experimental_memory_pool_policy = "none""#,
986        ] {
987            assert!(
988                toml::from_str::<QueryOptions>(toml_str).is_err(),
989                "{toml_str}"
990            );
991        }
992    }
993}