Skip to main content

query/
dummy_catalog.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
15//! Dummy catalog for region server.
16
17use std::any::Any;
18use std::collections::HashMap;
19use std::fmt;
20use std::sync::{Arc, Mutex};
21
22use api::v1::SemanticType;
23use async_trait::async_trait;
24use catalog::error::Result as CatalogResult;
25use catalog::{CatalogManager, CatalogManagerRef};
26use common_catalog::consts::FILE_ENGINE;
27use common_recordbatch::OrderOption;
28use common_recordbatch::filter::SimpleFilterEvaluator;
29use datafusion::catalog::{CatalogProvider, CatalogProviderList, SchemaProvider, Session};
30use datafusion::datasource::TableProvider;
31use datafusion::physical_plan::ExecutionPlan;
32use datafusion_common::DataFusionError;
33use datafusion_expr::{Expr, TableProviderFilterPushDown, TableType};
34use datatypes::arrow::datatypes::SchemaRef;
35use datatypes::data_type::DataType;
36use datatypes::types::json_type::JsonNativeType;
37use futures::stream::BoxStream;
38use session::context::{QueryContext, QueryContextRef};
39use snafu::ResultExt;
40use store_api::metadata::RegionMetadataRef;
41use store_api::region_engine::RegionEngineRef;
42use store_api::storage::{RegionId, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector};
43use table::TableRef;
44use table::metadata::{TableId, TableInfoRef};
45use table::table::adapter::{dictionary_encode_string_columns, supports_pk_dictionary_encoding};
46use table::table::scan::RegionScanExec;
47
48use crate::error::{GetRegionMetadataSnafu, Result};
49use crate::options::{FlowIncrementalMode, FlowQueryExtensions};
50
51/// Resolve to the given region (specified by [RegionId]) unconditionally.
52#[derive(Clone, Debug)]
53pub struct DummyCatalogList {
54    catalog: DummyCatalogProvider,
55}
56
57impl DummyCatalogList {
58    /// Creates a new catalog list with the given table provider.
59    pub fn with_table_provider(table_provider: Arc<dyn TableProvider>) -> Self {
60        let schema_provider = DummySchemaProvider {
61            table: table_provider,
62        };
63        let catalog_provider = DummyCatalogProvider {
64            schema: schema_provider,
65        };
66        Self {
67            catalog: catalog_provider,
68        }
69    }
70}
71
72impl CatalogProviderList for DummyCatalogList {
73    fn register_catalog(
74        &self,
75        _name: String,
76        _catalog: Arc<dyn CatalogProvider>,
77    ) -> Option<Arc<dyn CatalogProvider>> {
78        None
79    }
80
81    fn catalog_names(&self) -> Vec<String> {
82        vec![]
83    }
84
85    fn catalog(&self, _name: &str) -> Option<Arc<dyn CatalogProvider>> {
86        Some(Arc::new(self.catalog.clone()))
87    }
88}
89
90/// A dummy catalog provider for [DummyCatalogList].
91#[derive(Clone, Debug)]
92struct DummyCatalogProvider {
93    schema: DummySchemaProvider,
94}
95
96impl CatalogProvider for DummyCatalogProvider {
97    fn schema_names(&self) -> Vec<String> {
98        vec![]
99    }
100
101    fn schema(&self, _name: &str) -> Option<Arc<dyn SchemaProvider>> {
102        Some(Arc::new(self.schema.clone()))
103    }
104}
105
106/// A dummy schema provider for [DummyCatalogList].
107#[derive(Clone, Debug)]
108struct DummySchemaProvider {
109    table: Arc<dyn TableProvider>,
110}
111
112#[async_trait]
113impl SchemaProvider for DummySchemaProvider {
114    fn table_names(&self) -> Vec<String> {
115        vec![]
116    }
117
118    async fn table(
119        &self,
120        _name: &str,
121    ) -> datafusion::error::Result<Option<Arc<dyn TableProvider>>> {
122        Ok(Some(self.table.clone()))
123    }
124
125    fn table_exist(&self, _name: &str) -> bool {
126        true
127    }
128}
129
130/// For [TableProvider] and [DummyCatalogList]
131#[derive(Clone)]
132pub struct DummyTableProvider {
133    region_id: RegionId,
134    engine: RegionEngineRef,
135    metadata: RegionMetadataRef,
136    /// Keeping a mutable request makes it possible to change in the optimize phase.
137    scan_request: Arc<Mutex<ScanRequest>>,
138    query_ctx: Option<QueryContextRef>,
139}
140
141impl fmt::Debug for DummyTableProvider {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.debug_struct("DummyTableProvider")
144            .field("region_id", &self.region_id)
145            .field("metadata", &self.metadata)
146            .field("scan_request", &self.scan_request)
147            .finish()
148    }
149}
150
151#[async_trait]
152impl TableProvider for DummyTableProvider {
153    fn schema(&self) -> SchemaRef {
154        let schema = self.metadata.schema.arrow_schema();
155        if !supports_pk_dictionary_encoding(self.engine.name()) {
156            return schema.clone();
157        }
158        dictionary_encode_string_columns(schema, |index| {
159            self.metadata.column_metadatas[index].semantic_type == SemanticType::Tag
160        })
161    }
162
163    fn table_type(&self) -> TableType {
164        TableType::Base
165    }
166
167    async fn scan(
168        &self,
169        _state: &dyn Session,
170        projection: Option<&Vec<usize>>,
171        filters: &[Expr],
172        limit: Option<usize>,
173    ) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
174        let mut request = self.scan_request.lock().unwrap().clone();
175        request.projection = projection.cloned();
176        request.filters = filters.to_vec();
177        request.limit = limit;
178        if let Some(query_ctx) = &self.query_ctx {
179            let is_sink_scan = is_sink_scan(query_ctx, self.region_id)
180                .map_err(|e| DataFusionError::External(Box::new(e)))?;
181            apply_cached_snapshot_to_request(query_ctx, self.region_id, is_sink_scan, &mut request);
182        }
183
184        let scanner = self
185            .engine
186            .handle_query(self.region_id, request.clone())
187            .await
188            .map_err(|e| DataFusionError::External(Box::new(e)))?;
189
190        if request.snapshot_on_scan
191            && let Some(query_ctx) = &self.query_ctx
192            && let Some(snapshot_sequence) = scanner.snapshot_sequence()
193        {
194            bind_snapshot_bound_region_seq(query_ctx, self.region_id, snapshot_sequence)
195                .map_err(|e| DataFusionError::External(Box::new(e)))?;
196        }
197
198        let query_memory_tracker = self.engine.query_memory_tracker();
199        let mut scan_exec = RegionScanExec::new(scanner, request, query_memory_tracker)?;
200        if let Some(query_ctx) = &self.query_ctx {
201            scan_exec.set_explain_verbose(query_ctx.explain_verbose());
202        }
203        Ok(Arc::new(scan_exec))
204    }
205
206    fn supports_filters_pushdown(
207        &self,
208        filters: &[&Expr],
209    ) -> datafusion::error::Result<Vec<TableProviderFilterPushDown>> {
210        // File readers may use predicates for pruning without filtering individual rows.
211        if self.is_file_engine() {
212            return Ok(vec![TableProviderFilterPushDown::Inexact; filters.len()]);
213        }
214
215        let supported = filters
216            .iter()
217            .map(|e| {
218                // Simple filter on primary key columns are precisely evaluated.
219                if let Some(simple_filter) =
220                    SimpleFilterEvaluator::try_new_with_column_type(e, &|name| {
221                        self.metadata
222                            .column_by_name(name)
223                            .map(|column| column.column_schema.data_type.as_arrow_type())
224                    })
225                {
226                    if self
227                        .metadata
228                        .column_by_name(simple_filter.column_name())
229                        .and_then(|c| {
230                            (c.semantic_type == SemanticType::Tag
231                                || c.semantic_type == SemanticType::Timestamp)
232                                .then_some(())
233                        })
234                        .is_some()
235                    {
236                        TableProviderFilterPushDown::Exact
237                    } else {
238                        TableProviderFilterPushDown::Inexact
239                    }
240                } else {
241                    TableProviderFilterPushDown::Inexact
242                }
243            })
244            .collect();
245        Ok(supported)
246    }
247}
248
249impl DummyTableProvider {
250    /// Creates a new provider.
251    pub fn new(region_id: RegionId, engine: RegionEngineRef, metadata: RegionMetadataRef) -> Self {
252        let preserve_pk_dictionary_encoding = supports_pk_dictionary_encoding(engine.name());
253        Self {
254            region_id,
255            engine,
256            metadata,
257            scan_request: Arc::new(Mutex::new(ScanRequest {
258                preserve_pk_dictionary_encoding,
259                ..Default::default()
260            })),
261            query_ctx: None,
262        }
263    }
264
265    pub fn region_metadata(&self) -> RegionMetadataRef {
266        self.metadata.clone()
267    }
268
269    /// Returns whether this provider scans File Engine regions.
270    pub(crate) fn is_file_engine(&self) -> bool {
271        self.engine.name() == FILE_ENGINE
272    }
273
274    /// Sets the ordering hint of the query to the provider.
275    pub fn with_ordering_hint(&self, order_opts: &[OrderOption]) {
276        self.scan_request.lock().unwrap().output_ordering = Some(order_opts.to_vec());
277    }
278
279    /// Sets the distribution hint of the query to the provider.
280    pub fn with_distribution(&self, distribution: TimeSeriesDistribution) {
281        self.scan_request.lock().unwrap().distribution = Some(distribution);
282    }
283
284    /// Sets the time series selector hint of the query to the provider.
285    pub fn with_time_series_selector_hint(&self, selector: TimeSeriesRowSelector) {
286        self.scan_request.lock().unwrap().series_row_selector = Some(selector);
287    }
288
289    /// Clones this provider for one logical table-scan use-site.
290    ///
291    /// The optimizer may attach different hints to scans that share the same
292    /// catalog provider, so the per-scan request must not share its mutex.
293    pub fn clone_for_scan(&self) -> Self {
294        Self {
295            scan_request: Arc::new(Mutex::new(self.scan_request.lock().unwrap().clone())),
296            ..self.clone()
297        }
298    }
299
300    pub fn with_sequence(&self, sequence: u64) {
301        self.scan_request.lock().unwrap().memtable_max_sequence = Some(sequence);
302    }
303
304    pub(crate) fn with_json_type_hint(&self, hint: HashMap<String, JsonNativeType>) {
305        self.scan_request.lock().unwrap().json_type_hint = hint;
306    }
307
308    /// Whether this Mito scan still needs a count hint. Optimizer passes may
309    /// revisit the same aggregate; an already hinted provider is left alone.
310    pub(crate) fn needs_metadata_aggr_hint(&self) -> bool {
311        self.engine.name() == "mito" && !self.scan_request.lock().unwrap().metadata_aggr_hint
312    }
313
314    /// Requests exact-count preparation from Mito.
315    pub(crate) fn with_metadata_aggr_hint(&self) {
316        if self.engine.name() == "mito" {
317            self.scan_request.lock().unwrap().metadata_aggr_hint = true;
318        }
319    }
320
321    /// Gets the scan request of the provider.
322    #[cfg(test)]
323    pub fn scan_request(&self) -> ScanRequest {
324        self.scan_request.lock().unwrap().clone()
325    }
326}
327
328pub struct DummyTableProviderFactory;
329
330impl DummyTableProviderFactory {
331    pub async fn create_table_provider(
332        &self,
333        region_id: RegionId,
334        engine: RegionEngineRef,
335        query_ctx: Option<QueryContextRef>,
336    ) -> Result<DummyTableProvider> {
337        let metadata =
338            engine
339                .get_metadata(region_id)
340                .await
341                .with_context(|_| GetRegionMetadataSnafu {
342                    engine: engine.name(),
343                    region_id,
344                })?;
345
346        let mut scan_request = if let Some(ctx) = query_ctx.as_ref() {
347            scan_request_from_query_context(region_id, ctx)?
348        } else {
349            ScanRequest::default()
350        };
351        scan_request.preserve_pk_dictionary_encoding =
352            supports_pk_dictionary_encoding(engine.name());
353
354        Ok(DummyTableProvider {
355            region_id,
356            engine,
357            metadata,
358            scan_request: Arc::new(Mutex::new(scan_request)),
359            query_ctx,
360        })
361    }
362}
363
364fn scan_request_from_query_context(
365    region_id: RegionId,
366    query_ctx: &QueryContext,
367) -> Result<ScanRequest> {
368    let decision = decide_flow_scan(query_ctx, region_id)?;
369    Ok(build_scan_request(query_ctx, region_id, &decision))
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
373struct FlowScanDecision {
374    /// Whether this region is the flow sink-table scan.
375    /// Sink scans intentionally bypass incremental and snapshot-binding semantics.
376    is_sink_scan: bool,
377    /// Whether this scan should bind a memtable upper bound when opening the scan.
378    /// This is only the initial intent; if a cached bound already exists in `query_ctx`,
379    /// we reuse that cached bound instead and clear this flag.
380    snapshot_on_scan: bool,
381    /// Optional lower exclusive memtable sequence bound for incremental reads.
382    /// When set, only rows with sequence strictly greater than this bound are read from memtables.
383    memtable_min_sequence: Option<u64>,
384    /// Optional cached per-region snapshot already bound in `query_ctx`.
385    /// When present, this becomes the effective memtable upper bound and suppresses
386    /// binding a new snapshot on scan open.
387    memtable_max_sequence: Option<u64>,
388    /// Whether to skip SST files for memtable-only incremental source scans.
389    skip_sst_files: bool,
390    /// Whether this source scan must enforce the exact sequence range.
391    exact_sequence_range: bool,
392}
393
394impl FlowScanDecision {
395    fn plain_scan() -> Self {
396        Self {
397            is_sink_scan: true,
398            snapshot_on_scan: false,
399            memtable_min_sequence: None,
400            memtable_max_sequence: None,
401            skip_sst_files: false,
402            exact_sequence_range: false,
403        }
404    }
405}
406
407fn decide_flow_scan(query_ctx: &QueryContext, region_id: RegionId) -> Result<FlowScanDecision> {
408    let Some(flow_extensions) =
409        FlowQueryExtensions::parse_flow_extensions(&query_ctx.extensions())?
410    else {
411        return Ok(FlowScanDecision {
412            is_sink_scan: false,
413            snapshot_on_scan: false,
414            memtable_min_sequence: None,
415            memtable_max_sequence: query_ctx.get_snapshot(region_id.as_u64()),
416            skip_sst_files: false,
417            exact_sequence_range: false,
418        });
419    };
420
421    // Sink-table scans intentionally bypass all flow scan semantics. They should
422    // behave like plain reads and must not participate in incremental lower bounds
423    // or per-region snapshot binding/reuse.
424    if flow_extensions.sink_table_id == Some(region_id.table_id()) {
425        return Ok(FlowScanDecision::plain_scan());
426    }
427
428    let apply_incremental = flow_extensions.validate_for_scan(region_id)?;
429
430    let memtable_min_sequence = if apply_incremental {
431        flow_extensions
432            .incremental_after_seqs
433            .as_ref()
434            .and_then(|seqs| seqs.get(&region_id.as_u64()))
435            .copied()
436    } else {
437        None
438    };
439
440    let memtable_max_sequence = query_ctx.get_snapshot(region_id.as_u64());
441
442    // `skip_sst_files` is only valid for memtable-only incremental deltas,
443    // identified by a lower checkpoint bound. A snapshot upper bound without an
444    // incremental lower bound is a fenced full-snapshot read and must keep SSTs
445    // in the scan so mito can reject stale upper bounds after H has been flushed
446    // into SSTs, instead of silently bypassing the stale-fence check. If a future
447    // incremental delta also carries an upper bound, the lower-bound stale check
448    // still proves whether memtable-only is safe.
449    let skip_sst_files = apply_incremental
450        && memtable_min_sequence.is_some()
451        && flow_extensions.incremental_mode == Some(FlowIncrementalMode::MemtableOnly);
452
453    Ok(FlowScanDecision {
454        is_sink_scan: false,
455        snapshot_on_scan: memtable_max_sequence.is_none()
456            && flow_extensions.should_collect_region_watermark(),
457        memtable_min_sequence,
458        memtable_max_sequence,
459        skip_sst_files,
460        exact_sequence_range: apply_incremental
461            && flow_extensions.incremental_mode == Some(FlowIncrementalMode::SequenceRange),
462    })
463}
464
465fn build_scan_request(
466    query_ctx: &QueryContext,
467    region_id: RegionId,
468    decision: &FlowScanDecision,
469) -> ScanRequest {
470    // Build the initial scan request from the final decision known at provider creation
471    // time. A later scan may still refresh `memtable_max_sequence` if another source scan
472    // has bound a snapshot into `query_ctx` after this provider was created.
473    ScanRequest {
474        sst_min_sequence: (!decision.is_sink_scan && !decision.exact_sequence_range)
475            .then(|| query_ctx.sst_min_sequence(region_id.as_u64()))
476            .flatten(),
477        skip_sst_files: decision.skip_sst_files,
478        snapshot_on_scan: decision.snapshot_on_scan,
479        exact_sequence_range: decision.exact_sequence_range,
480        memtable_min_sequence: decision.memtable_min_sequence,
481        memtable_max_sequence: decision.memtable_max_sequence,
482        ..Default::default()
483    }
484}
485
486fn is_sink_scan(query_ctx: &QueryContext, region_id: RegionId) -> Result<bool> {
487    Ok(
488        FlowQueryExtensions::parse_flow_extensions(&query_ctx.extensions())?
489            .is_some_and(|exts| exts.sink_table_id == Some(region_id.table_id())),
490    )
491}
492
493fn apply_cached_snapshot_to_request(
494    query_ctx: &QueryContext,
495    region_id: RegionId,
496    is_sink_scan: bool,
497    scan_request: &mut ScanRequest,
498) {
499    if is_sink_scan {
500        return;
501    }
502
503    if let Some(snapshot_sequence) = query_ctx.get_snapshot(region_id.as_u64()) {
504        // Reuse the previously bound per-region snapshot instead of rebinding a new
505        // upper bound on scan open. This refresh is still needed at scan time because
506        // the provider's cached request may have been built before another source scan
507        // bound the shared query-level snapshot into `query_ctx`.
508        scan_request.memtable_max_sequence = Some(snapshot_sequence);
509        scan_request.snapshot_on_scan = false;
510    }
511}
512
513fn bind_snapshot_bound_region_seq(
514    query_ctx: &QueryContext,
515    region_id: RegionId,
516    snapshot_sequence: u64,
517) -> Result<u64> {
518    if let Some(existing) = query_ctx.get_snapshot(region_id.as_u64()) {
519        if existing != snapshot_sequence {
520            return crate::error::ConflictingSnapshotSequenceSnafu {
521                region_id,
522                existing,
523                new: snapshot_sequence,
524            }
525            .fail();
526        }
527        Ok(existing)
528    } else {
529        query_ctx.set_snapshot(region_id.as_u64(), snapshot_sequence);
530        Ok(snapshot_sequence)
531    }
532}
533
534#[async_trait]
535impl TableProviderFactory for DummyTableProviderFactory {
536    async fn create(
537        &self,
538        region_id: RegionId,
539        engine: RegionEngineRef,
540        ctx: Option<QueryContextRef>,
541    ) -> Result<Arc<dyn TableProvider>> {
542        let provider = self.create_table_provider(region_id, engine, ctx).await?;
543        Ok(Arc::new(provider))
544    }
545}
546
547#[async_trait]
548pub trait TableProviderFactory: Send + Sync {
549    async fn create(
550        &self,
551        region_id: RegionId,
552        engine: RegionEngineRef,
553        ctx: Option<QueryContextRef>,
554    ) -> Result<Arc<dyn TableProvider>>;
555}
556
557pub type TableProviderFactoryRef = Arc<dyn TableProviderFactory>;
558
559/// A dummy catalog manager that always returns empty results.
560///
561/// Used to fill the arg of `QueryEngineFactory::new_with_plugins` in datanode.
562pub struct DummyCatalogManager;
563
564impl DummyCatalogManager {
565    /// Returns a new `CatalogManagerRef` instance.
566    pub fn arc() -> CatalogManagerRef {
567        Arc::new(Self)
568    }
569}
570
571#[async_trait::async_trait]
572impl CatalogManager for DummyCatalogManager {
573    fn as_any(&self) -> &dyn Any {
574        self
575    }
576
577    async fn catalog_names(&self) -> CatalogResult<Vec<String>> {
578        Ok(vec![])
579    }
580
581    async fn schema_names(
582        &self,
583        _catalog: &str,
584        _query_ctx: Option<&QueryContext>,
585    ) -> CatalogResult<Vec<String>> {
586        Ok(vec![])
587    }
588
589    async fn table_names(
590        &self,
591        _catalog: &str,
592        _schema: &str,
593        _query_ctx: Option<&QueryContext>,
594    ) -> CatalogResult<Vec<String>> {
595        Ok(vec![])
596    }
597
598    async fn catalog_exists(&self, _catalog: &str) -> CatalogResult<bool> {
599        Ok(false)
600    }
601
602    async fn schema_exists(
603        &self,
604        _catalog: &str,
605        _schema: &str,
606        _query_ctx: Option<&QueryContext>,
607    ) -> CatalogResult<bool> {
608        Ok(false)
609    }
610
611    async fn table_exists(
612        &self,
613        _catalog: &str,
614        _schema: &str,
615        _table: &str,
616        _query_ctx: Option<&QueryContext>,
617    ) -> CatalogResult<bool> {
618        Ok(false)
619    }
620
621    async fn table(
622        &self,
623        _catalog: &str,
624        _schema: &str,
625        _table_name: &str,
626        _query_ctx: Option<&QueryContext>,
627    ) -> CatalogResult<Option<TableRef>> {
628        Ok(None)
629    }
630
631    async fn table_id(
632        &self,
633        _catalog: &str,
634        _schema: &str,
635        _table_name: &str,
636        _query_ctx: Option<&QueryContext>,
637    ) -> CatalogResult<Option<TableId>> {
638        Ok(None)
639    }
640
641    async fn table_info_by_id(&self, _table_id: TableId) -> CatalogResult<Option<TableInfoRef>> {
642        Ok(None)
643    }
644
645    async fn tables_by_ids(
646        &self,
647        _catalog: &str,
648        _schema: &str,
649        _table_ids: &[TableId],
650    ) -> CatalogResult<Vec<TableRef>> {
651        Ok(vec![])
652    }
653
654    fn tables<'a>(
655        &'a self,
656        _catalog: &'a str,
657        _schema: &'a str,
658        _query_ctx: Option<&'a QueryContext>,
659    ) -> BoxStream<'a, CatalogResult<TableRef>> {
660        Box::pin(futures::stream::empty())
661    }
662}
663
664#[cfg(test)]
665mod tests {
666    use std::collections::HashMap;
667    use std::sync::{Arc, RwLock};
668
669    use common_error::ext::ErrorExt;
670    use common_error::status_code::StatusCode;
671    use session::context::QueryContextBuilder;
672
673    use super::*;
674    use crate::error::Error;
675    use crate::options::{
676        FLOW_INCREMENTAL_AFTER_SEQS, FLOW_INCREMENTAL_MODE, FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE,
677        FLOW_RETURN_REGION_SEQ, FLOW_SINK_TABLE_ID,
678    };
679
680    #[test]
681    fn test_nullable_label_filter_pushdown() {
682        use datafusion_expr::{Cast, col, lit};
683        use datatypes::arrow::datatypes::DataType as ArrowDataType;
684
685        let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1));
686        let cast_label = Expr::Cast(Cast::new(Box::new(col("k0")), ArrowDataType::Utf8));
687        let cast_field = Expr::Cast(Cast::new(Box::new(col("v0")), ArrowDataType::Utf8));
688        let filters = [
689            col("k0").is_null().or(col("k0").not_eq(lit("lo"))),
690            col("k0").is_null().or(cast_label.not_eq(lit("lo"))),
691            col("k0").is_null().or(col("v0").not_eq(lit(1.0))),
692            cast_field.eq(lit("1")),
693            col("k0").in_list(vec![lit(""), lit("lo")], false),
694            col("k0").in_list(vec![lit(""), lit("lo")], true),
695        ];
696        assert_eq!(
697            provider
698                .supports_filters_pushdown(&filters.iter().collect::<Vec<_>>())
699                .unwrap(),
700            vec![
701                TableProviderFilterPushDown::Exact,
702                TableProviderFilterPushDown::Exact,
703                TableProviderFilterPushDown::Inexact,
704                TableProviderFilterPushDown::Inexact,
705                TableProviderFilterPushDown::Inexact,
706                TableProviderFilterPushDown::Inexact,
707            ]
708        );
709    }
710
711    fn test_region_id() -> RegionId {
712        RegionId::new(1024, 1)
713    }
714
715    #[test]
716    fn test_scan_request_from_query_context_uses_snapshot_bound_intent() {
717        let region_id = test_region_id();
718        let query_ctx = QueryContextBuilder::default()
719            .extensions(HashMap::from([(
720                "flow.return_region_seq".to_string(),
721                "true".to_string(),
722            )]))
723            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
724                region_id.as_u64(),
725                42_u64,
726            )]))))
727            .sst_min_sequences(Arc::new(RwLock::new(HashMap::from([(
728                region_id.as_u64(),
729                7_u64,
730            )]))))
731            .build();
732
733        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
734
735        assert!(!request.snapshot_on_scan);
736        assert_eq!(request.memtable_max_sequence, Some(42));
737        assert_eq!(request.sst_min_sequence, Some(7));
738    }
739
740    #[test]
741    fn test_terminal_watermark_context_source_and_sink_scan_semantics() {
742        let region_id = test_region_id();
743        let query_ctx = QueryContextBuilder::default()
744            .extensions(HashMap::from([(
745                FLOW_RETURN_REGION_SEQ.to_string(),
746                "true".to_string(),
747            )]))
748            .build();
749
750        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
751
752        assert!(request.snapshot_on_scan);
753        assert_eq!(request.memtable_min_sequence, None);
754        assert_eq!(request.memtable_max_sequence, None);
755        assert_eq!(request.sst_min_sequence, None);
756
757        let query_ctx = QueryContextBuilder::default()
758            .extensions(HashMap::from([
759                (FLOW_RETURN_REGION_SEQ.to_string(), "true".to_string()),
760                (
761                    FLOW_SINK_TABLE_ID.to_string(),
762                    region_id.table_id().to_string(),
763                ),
764            ]))
765            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
766                region_id.as_u64(),
767                88_u64,
768            )]))))
769            .sst_min_sequences(Arc::new(RwLock::new(HashMap::from([(
770                region_id.as_u64(),
771                77_u64,
772            )]))))
773            .build();
774
775        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
776
777        assert!(!request.snapshot_on_scan);
778        assert_eq!(request.memtable_min_sequence, None);
779        assert_eq!(request.memtable_max_sequence, None);
780        assert_eq!(request.sst_min_sequence, None);
781    }
782
783    #[test]
784    fn test_scan_request_from_incremental_context_uses_snapshot_bound_intent() {
785        let region_id = test_region_id();
786        let query_ctx = QueryContextBuilder::default()
787            .extensions(HashMap::from([(
788                "flow.incremental_after_seqs".to_string(),
789                format!(r#"{{"{}":10}}"#, region_id.as_u64()),
790            )]))
791            .build();
792
793        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
794
795        assert!(request.snapshot_on_scan);
796        assert_eq!(request.memtable_min_sequence, Some(10));
797        assert_eq!(request.memtable_max_sequence, None);
798    }
799
800    #[test]
801    fn test_scan_request_from_sequence_range_context_uses_exact_source_scan() {
802        let region_id = test_region_id();
803        let query_ctx = QueryContextBuilder::default()
804            .extensions(HashMap::from([
805                (
806                    FLOW_INCREMENTAL_MODE.to_string(),
807                    FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(),
808                ),
809                (
810                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
811                    format!(r#"{{"{}":10}}"#, region_id.as_u64()),
812                ),
813            ]))
814            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
815                region_id.as_u64(),
816                42_u64,
817            )]))))
818            .sst_min_sequences(Arc::new(RwLock::new(HashMap::from([(
819                region_id.as_u64(),
820                7_u64,
821            )]))))
822            .build();
823
824        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
825
826        assert!(request.exact_sequence_range);
827        assert!(!request.skip_sst_files);
828        assert_eq!(request.memtable_min_sequence, Some(10));
829        assert_eq!(request.memtable_max_sequence, Some(42));
830        assert_eq!(request.sst_min_sequence, None);
831    }
832
833    #[test]
834    fn test_scan_request_from_sequence_range_context_binds_snapshot_on_scan() {
835        let region_id = test_region_id();
836        let query_ctx = QueryContextBuilder::default()
837            .extensions(HashMap::from([
838                (
839                    FLOW_INCREMENTAL_MODE.to_string(),
840                    FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(),
841                ),
842                (
843                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
844                    format!(r#"{{"{}":10}}"#, region_id.as_u64()),
845                ),
846            ]))
847            .build();
848
849        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
850
851        assert!(request.exact_sequence_range);
852        assert!(request.snapshot_on_scan);
853        assert_eq!(request.memtable_min_sequence, Some(10));
854        assert_eq!(request.memtable_max_sequence, None);
855        assert!(!request.skip_sst_files);
856    }
857
858    #[test]
859    fn test_scan_request_from_query_context_keeps_snapshot_fields() {
860        let region_id = test_region_id();
861        let query_ctx = QueryContextBuilder::default()
862            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
863                region_id.as_u64(),
864                100,
865            )]))))
866            .sst_min_sequences(Arc::new(RwLock::new(HashMap::from([(
867                region_id.as_u64(),
868                90,
869            )]))))
870            .build();
871
872        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
873        assert_eq!(request.memtable_max_sequence, Some(100));
874        assert_eq!(request.sst_min_sequence, Some(90));
875        assert_eq!(request.memtable_min_sequence, None);
876        assert!(!request.snapshot_on_scan);
877        assert!(!request.skip_sst_files);
878    }
879
880    #[test]
881    fn test_scan_request_from_query_context_reuses_existing_snapshot_for_incremental_scan() {
882        let region_id = test_region_id();
883        let query_ctx = QueryContextBuilder::default()
884            .extensions(HashMap::from([
885                (
886                    FLOW_INCREMENTAL_MODE.to_string(),
887                    "memtable_only".to_string(),
888                ),
889                (
890                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
891                    format!(r#"{{"{}":10}}"#, region_id.as_u64()),
892                ),
893            ]))
894            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
895                region_id.as_u64(),
896                42_u64,
897            )]))))
898            .build();
899
900        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
901
902        assert_eq!(request.memtable_min_sequence, Some(10));
903        assert_eq!(request.memtable_max_sequence, Some(42));
904        assert!(!request.snapshot_on_scan);
905        assert!(request.skip_sst_files);
906    }
907
908    #[test]
909    fn test_apply_cached_snapshot_to_request_updates_cached_scan_request() {
910        let region_id = test_region_id();
911        let query_ctx = QueryContextBuilder::default()
912            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
913                region_id.as_u64(),
914                88_u64,
915            )]))))
916            .build();
917        let mut request = ScanRequest {
918            snapshot_on_scan: true,
919            ..Default::default()
920        };
921
922        apply_cached_snapshot_to_request(&query_ctx, region_id, false, &mut request);
923
924        assert_eq!(request.memtable_max_sequence, Some(88));
925        assert!(!request.snapshot_on_scan);
926    }
927
928    #[test]
929    fn test_apply_cached_snapshot_to_request_preserves_exact_sequence_range() {
930        let region_id = test_region_id();
931        let query_ctx = QueryContextBuilder::default()
932            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
933                region_id.as_u64(),
934                10_u64,
935            )]))))
936            .build();
937        let mut request = ScanRequest {
938            memtable_min_sequence: Some(10),
939            snapshot_on_scan: true,
940            exact_sequence_range: true,
941            ..Default::default()
942        };
943
944        apply_cached_snapshot_to_request(&query_ctx, region_id, false, &mut request);
945
946        assert_eq!(request.memtable_min_sequence, Some(10));
947        assert_eq!(request.memtable_max_sequence, Some(10));
948        assert!(request.exact_sequence_range);
949        assert!(!request.skip_sst_files);
950        assert_eq!(request.sst_min_sequence, None);
951        assert!(!request.snapshot_on_scan);
952    }
953
954    #[test]
955    fn test_apply_cached_snapshot_to_request_skips_sink_scan() {
956        let region_id = test_region_id();
957        let query_ctx = QueryContextBuilder::default()
958            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
959                region_id.as_u64(),
960                88_u64,
961            )]))))
962            .build();
963        let mut request = ScanRequest {
964            snapshot_on_scan: true,
965            ..Default::default()
966        };
967
968        apply_cached_snapshot_to_request(&query_ctx, region_id, true, &mut request);
969
970        assert_eq!(request.memtable_max_sequence, None);
971        assert!(request.snapshot_on_scan);
972    }
973
974    #[test]
975    fn test_bind_snapshot_bound_region_seq_reuses_existing_snapshot() {
976        let region_id = test_region_id();
977        let query_ctx = QueryContextBuilder::default()
978            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
979                region_id.as_u64(),
980                42_u64,
981            )]))))
982            .build();
983
984        let err = bind_snapshot_bound_region_seq(&query_ctx, region_id, 99).unwrap_err();
985
986        assert!(matches!(err, Error::ConflictingSnapshotSequence { .. }));
987        assert_eq!(query_ctx.get_snapshot(region_id.as_u64()), Some(42));
988    }
989
990    #[test]
991    fn test_bind_snapshot_bound_region_seq_sets_snapshot_once() {
992        let region_id = test_region_id();
993        let query_ctx = QueryContextBuilder::default().build();
994
995        let seq = bind_snapshot_bound_region_seq(&query_ctx, region_id, 99).unwrap();
996
997        assert_eq!(seq, 99);
998        assert_eq!(query_ctx.get_snapshot(region_id.as_u64()), Some(99));
999    }
1000
1001    #[test]
1002    fn test_scan_request_from_query_context_applies_incremental_after_seq_for_source_scan() {
1003        let region_id = test_region_id();
1004        let query_ctx = QueryContextBuilder::default()
1005            .extensions(HashMap::from([
1006                (
1007                    FLOW_INCREMENTAL_MODE.to_string(),
1008                    "memtable_only".to_string(),
1009                ),
1010                (
1011                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
1012                    format!(r#"{{"{}":55}}"#, region_id.as_u64()),
1013                ),
1014            ]))
1015            .build();
1016
1017        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
1018        assert_eq!(request.memtable_min_sequence, Some(55));
1019        assert_eq!(request.sst_min_sequence, None);
1020        assert!(request.skip_sst_files);
1021        assert!(!request.exact_sequence_range);
1022    }
1023
1024    #[test]
1025    fn test_scan_request_from_sequence_range_context_excludes_sink_scan() {
1026        let region_id = test_region_id();
1027        let query_ctx = QueryContextBuilder::default()
1028            .extensions(HashMap::from([
1029                (
1030                    FLOW_INCREMENTAL_MODE.to_string(),
1031                    FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(),
1032                ),
1033                (
1034                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
1035                    format!(r#"{{"{}":55}}"#, region_id.as_u64()),
1036                ),
1037                (
1038                    FLOW_SINK_TABLE_ID.to_string(),
1039                    region_id.table_id().to_string(),
1040                ),
1041            ]))
1042            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
1043                region_id.as_u64(),
1044                88_u64,
1045            )]))))
1046            .sst_min_sequences(Arc::new(RwLock::new(HashMap::from([(
1047                region_id.as_u64(),
1048                77_u64,
1049            )]))))
1050            .build();
1051
1052        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
1053
1054        assert!(!request.exact_sequence_range);
1055        assert!(!request.skip_sst_files);
1056        assert_eq!(request.memtable_min_sequence, None);
1057        assert_eq!(request.memtable_max_sequence, None);
1058        assert_eq!(request.sst_min_sequence, None);
1059    }
1060
1061    #[test]
1062    fn test_scan_request_from_query_context_does_not_apply_incremental_for_sink_table() {
1063        let region_id = test_region_id();
1064        let query_ctx = QueryContextBuilder::default()
1065            .extensions(HashMap::from([
1066                (
1067                    FLOW_INCREMENTAL_MODE.to_string(),
1068                    "memtable_only".to_string(),
1069                ),
1070                (
1071                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
1072                    format!(r#"{{"{}":55}}"#, region_id.as_u64()),
1073                ),
1074                (
1075                    FLOW_SINK_TABLE_ID.to_string(),
1076                    region_id.table_id().to_string(),
1077                ),
1078            ]))
1079            .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(
1080                region_id.as_u64(),
1081                88_u64,
1082            )]))))
1083            .sst_min_sequences(Arc::new(RwLock::new(HashMap::from([(
1084                region_id.as_u64(),
1085                77_u64,
1086            )]))))
1087            .build();
1088
1089        let request = scan_request_from_query_context(region_id, &query_ctx).unwrap();
1090        assert_eq!(request.memtable_min_sequence, None);
1091        assert_eq!(request.memtable_max_sequence, None);
1092        assert_eq!(request.sst_min_sequence, None);
1093        assert!(!request.skip_sst_files);
1094        assert!(!request.snapshot_on_scan);
1095    }
1096
1097    #[test]
1098    fn test_scan_request_from_query_context_rejects_missing_memtable_only_region() {
1099        let region_id = test_region_id();
1100        let query_ctx = QueryContextBuilder::default()
1101            .extensions(HashMap::from([
1102                (
1103                    FLOW_INCREMENTAL_MODE.to_string(),
1104                    "memtable_only".to_string(),
1105                ),
1106                (
1107                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
1108                    r#"{"9":55}"#.to_string(),
1109                ),
1110            ]))
1111            .build();
1112
1113        let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err();
1114        assert!(matches!(err, Error::InvalidQueryContextExtension { .. }));
1115    }
1116
1117    #[test]
1118    fn test_scan_request_from_sequence_range_rejects_missing_source_bound() {
1119        let region_id = test_region_id();
1120        let query_ctx = QueryContextBuilder::default()
1121            .extensions(HashMap::from([
1122                (
1123                    FLOW_INCREMENTAL_MODE.to_string(),
1124                    FLOW_INCREMENTAL_MODE_SEQUENCE_RANGE.to_string(),
1125                ),
1126                (
1127                    FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
1128                    r#"{"9":55}"#.to_string(),
1129                ),
1130            ]))
1131            .build();
1132
1133        let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err();
1134        assert!(matches!(err, Error::InvalidQueryContextExtension { .. }));
1135        assert_eq!(err.status_code(), StatusCode::InvalidArguments);
1136    }
1137
1138    #[test]
1139    fn test_scan_request_from_query_context_rejects_invalid_incremental_json() {
1140        let region_id = test_region_id();
1141        let query_ctx = QueryContextBuilder::default()
1142            .extensions(HashMap::from([(
1143                FLOW_INCREMENTAL_AFTER_SEQS.to_string(),
1144                "not-json".to_string(),
1145            )]))
1146            .build();
1147
1148        let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err();
1149        assert!(matches!(err, Error::InvalidQueryContextExtension { .. }));
1150        assert_eq!(err.status_code(), StatusCode::InvalidArguments);
1151    }
1152
1153    #[test]
1154    fn test_scan_request_from_query_context_rejects_invalid_sink_table_id() {
1155        let region_id = test_region_id();
1156        let query_ctx = QueryContextBuilder::default()
1157            .extensions(HashMap::from([(
1158                FLOW_SINK_TABLE_ID.to_string(),
1159                "abc".to_string(),
1160            )]))
1161            .build();
1162
1163        let err = scan_request_from_query_context(region_id, &query_ctx).unwrap_err();
1164        assert!(matches!(err, Error::InvalidQueryContextExtension { .. }));
1165        assert_eq!(err.status_code(), StatusCode::InvalidArguments);
1166    }
1167}