Skip to main content

query/dist_plan/
dyn_filter_bridge.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::any::Any;
16use std::sync::Arc;
17
18use common_query::request::{
19    DynFilterPayload, INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, InitialDynFilterReg,
20    InitialDynFilterRegs, InitialDynFilterSnapshot, REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
21    is_dyn_filter_payload_too_large, is_dyn_filter_unsupported,
22};
23use datafusion::physical_plan::filter_pushdown::PushedDown;
24use datafusion_common::Result;
25use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
26use datafusion_expr::ColumnarValue;
27use datafusion_physical_expr::PhysicalExpr;
28use datafusion_physical_expr::expressions::{Column, DynamicFilterPhysicalExpr, Literal, lit};
29use datafusion_physical_expr::scalar_subquery::ScalarSubqueryExpr;
30use datafusion_physical_expr::utils::collect_columns;
31use session::context::{QueryContext, QueryContextRef};
32use store_api::storage::RegionId;
33
34use crate::dist_plan::filter_id::build_remote_dyn_filter_id;
35use crate::dist_plan::{
36    FilterId, QueryDynFilterRegistry, RemoteDynFilterProducerId, Subscriber, SubscriberRegistration,
37};
38use crate::metrics::REMOTE_DYN_FILTER_ENCODE_TOTAL;
39use crate::region_query::RegionQueryTarget;
40
41#[derive(Debug, Clone)]
42pub(crate) struct CapturedDynFilter {
43    filter_id: FilterId,
44    initial_registration: InitialDynFilterReg,
45    pub(crate) alive_dyn_filter: Arc<DynamicFilterPhysicalExpr>,
46    /// A parent filter that references uncorrelated scalar subqueries. Its value is only
47    /// known once `ScalarSubqueryExec` has run the subqueries, so `alive_dyn_filter`
48    /// starts as `true` and is replaced by the resolved filter before regions are queried.
49    // TODO(discord9): temporary bridge. DataFusion fills the scalar subquery results in
50    // `ScalarSubqueryExec` but does not expose predicates using them as
51    // `DynamicFilterPhysicalExpr`, so we keep the predicate and bind it ourselves. Once
52    // upstream does and the pinned DataFusion includes it, remove this field and the
53    // scalar subquery capture/resolve path in favor of the regular dyn filter capture.
54    // Keep the per-phase bookkeeping in `MergeScanExec`.
55    scalar_subquery_filter: Option<Arc<dyn PhysicalExpr>>,
56}
57
58#[derive(Debug, Clone)]
59pub(crate) struct RemoteDynFilterPushdown {
60    pub(crate) captured_dyn_filters: Vec<CapturedDynFilter>,
61    /// Preflight result per parent filter.
62    pub(crate) pushed_down: Vec<PushedDown>,
63}
64
65/// Captures `parent_filters` as remote dyn filters. `accepted` holds filters captured by
66/// another pushdown phase; they are sent in the same request, so the initial registration
67/// budget is checked against both and they are kept if the new filters do not fit.
68pub(crate) fn capture_remote_dyn_filters_for_pushdown(
69    remote_dyn_filter_producer_id: RemoteDynFilterProducerId,
70    first_producer_local_ordinal: usize,
71    accepted: &[CapturedDynFilter],
72    parent_filters: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
73) -> RemoteDynFilterPushdown {
74    let mut pushed_down = Vec::with_capacity(parent_filters.len());
75    let mut captured_dyn_filters = Vec::new();
76
77    for (index, filter) in parent_filters.into_iter().enumerate() {
78        let producer_local_ordinal = first_producer_local_ordinal + index;
79        let captured = if let Some(alive_dyn_filter) = downcast_dynamic_filter(filter.clone()) {
80            build_captured_dyn_filter(
81                remote_dyn_filter_producer_id,
82                producer_local_ordinal,
83                alive_dyn_filter,
84            )
85            .map(pushdown_for_captured_filter)
86        } else if is_scalar_subquery_filter(&filter) {
87            // The filter is only forwarded to regions for pruning; the parent keeps
88            // evaluating it, so report it as not pushed down.
89            build_scalar_subquery_dyn_filter(
90                remote_dyn_filter_producer_id,
91                producer_local_ordinal,
92                filter,
93            )
94            .map(|captured| (captured, PushedDown::No))
95        } else {
96            pushed_down.push(PushedDown::No);
97            continue;
98        };
99
100        match captured {
101            Ok((captured_dyn_filter, pushdown)) => {
102                pushed_down.push(pushdown);
103                captured_dyn_filters.push(captured_dyn_filter);
104            }
105            Err(error) => {
106                common_telemetry::warn!(error; "Remote dyn filter is not pushed down because initial registration cannot be built");
107                pushed_down.push(PushedDown::No);
108            }
109        }
110    }
111
112    let combined = accepted
113        .iter()
114        .chain(&captured_dyn_filters)
115        .cloned()
116        .collect::<Vec<_>>();
117    if let Err(error) = validate_initial_registrations_for_pushdown(&combined) {
118        common_telemetry::warn!(error; "Remote dyn filters are not pushed down because initial registrations are invalid");
119        return RemoteDynFilterPushdown {
120            captured_dyn_filters: Vec::new(),
121            pushed_down: vec![PushedDown::No; pushed_down.len()],
122        };
123    }
124
125    RemoteDynFilterPushdown {
126        captured_dyn_filters,
127        pushed_down,
128    }
129}
130
131/// A captured filter is only reported as pushed down when its initial snapshot could be
132/// shipped.
133///
134/// An unsupported (or oversized) snapshot is never rewritten to `true`, so a region
135/// receives **no initial predicate** from the initial registration. The registration
136/// itself is still sent - filter id plus children - and the receiver installs a `true`
137/// placeholder for it, which is why the region is not filtered yet but the later updates
138/// already have somewhere to land. The parent must therefore keep evaluating the filter
139/// itself, which is what [`PushedDown::No`] tells DataFusion.
140fn pushdown_for_captured_filter(captured: CapturedDynFilter) -> (CapturedDynFilter, PushedDown) {
141    let pushed_down = if captured.initial_registration.initial_snapshot.is_some() {
142        PushedDown::Yes
143    } else {
144        PushedDown::No
145    };
146
147    (captured, pushed_down)
148}
149
150/// Returns true if `filter` references at least one scalar subquery and is otherwise
151/// built only from columns and literals, so it becomes a plain predicate once the
152/// subqueries are resolved.
153///
154/// `IN` lists are accepted: the retention contract in
155/// [`DynFilterPayload::from_datafusion_expr`] only ever drops whole top-level `AND`
156/// conjuncts and never substitutes `true` for a node, so an `IN` list inside an arbitrary
157/// predicate such as `(host IN (...)) = false` cannot be narrowed by transport. A payload
158/// that cannot be shipped as it stands is an explicit error, which the capture answers by
159/// only attaching no initial predicate (the region keeps its `true` placeholder) while the
160/// parent keeps evaluating the filter.
161fn is_scalar_subquery_filter(filter: &Arc<dyn PhysicalExpr>) -> bool {
162    let mut has_scalar_subquery = false;
163    let mut supported = true;
164    let _ = filter.apply(|expr| {
165        if expr.is::<ScalarSubqueryExpr>() {
166            has_scalar_subquery = true;
167        } else if expr.children().is_empty() && !expr.is::<Column>() && !expr.is::<Literal>() {
168            supported = false;
169            return Ok(TreeNodeRecursion::Stop);
170        }
171        Ok(TreeNodeRecursion::Continue)
172    });
173    has_scalar_subquery && supported
174}
175
176fn build_scalar_subquery_dyn_filter(
177    remote_dyn_filter_producer_id: RemoteDynFilterProducerId,
178    producer_local_ordinal: usize,
179    filter: Arc<dyn PhysicalExpr>,
180) -> Result<CapturedDynFilter> {
181    let mut columns = collect_columns(&filter).into_iter().collect::<Vec<_>>();
182    columns.sort_by_key(|column| column.index());
183    let children = columns
184        .into_iter()
185        .map(|column| Arc::new(column) as Arc<dyn PhysicalExpr>)
186        .collect();
187    let alive_dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(children, lit(true)));
188    let mut captured = build_captured_dyn_filter(
189        remote_dyn_filter_producer_id,
190        producer_local_ordinal,
191        alive_dyn_filter,
192    )?;
193    captured.scalar_subquery_filter = Some(filter);
194    Ok(captured)
195}
196
197/// Replaces the scalar subqueries in captured filters with their results.
198///
199/// `ScalarSubqueryExec` runs its subqueries before executing its input, so the results
200/// are available when `MergeScanExec` is executed. This runs on every execution because
201/// `ScalarSubqueryExec::reset_state` clears the results for re-execution. A filter whose
202/// subqueries are unresolved falls back to `true`, which only disables pruning.
203pub(crate) fn resolve_scalar_subquery_dyn_filters(captured_dyn_filters: &[CapturedDynFilter]) {
204    for captured in captured_dyn_filters {
205        let Some(filter) = &captured.scalar_subquery_filter else {
206            continue;
207        };
208        let resolved = replace_scalar_subqueries(filter).unwrap_or_else(|error| {
209            common_telemetry::debug!(
210                "Scalar subquery filter {} is not forwarded to regions: {}",
211                filter,
212                error
213            );
214            lit(true)
215        });
216        if captured
217            .alive_dyn_filter
218            .current()
219            .is_ok_and(|current| current.as_ref() == resolved.as_ref())
220        {
221            continue;
222        }
223        if let Err(error) = captured.alive_dyn_filter.update(resolved) {
224            common_telemetry::warn!(error; "Failed to update scalar subquery remote dyn filter");
225        }
226    }
227}
228
229fn replace_scalar_subqueries(filter: &Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
230    let empty_batch =
231        arrow::record_batch::RecordBatch::new_empty(Arc::new(arrow_schema::Schema::empty()));
232    filter
233        .clone()
234        .transform_up(|expr| {
235            if !expr.is::<ScalarSubqueryExpr>() {
236                return Ok(Transformed::no(expr));
237            }
238            // Fails if the subquery has not been executed yet.
239            match expr.evaluate(&empty_batch)? {
240                ColumnarValue::Scalar(value) => Ok(Transformed::yes(lit(value))),
241                ColumnarValue::Array(_) => Err(datafusion_common::DataFusionError::Internal(
242                    "scalar subquery evaluated to an array".to_string(),
243                )),
244            }
245        })
246        .map(|transformed| transformed.data)
247}
248
249fn downcast_dynamic_filter(
250    expr: Arc<dyn datafusion::physical_plan::PhysicalExpr>,
251) -> Option<Arc<DynamicFilterPhysicalExpr>> {
252    (expr as Arc<dyn Any + Send + Sync + 'static>)
253        .downcast::<DynamicFilterPhysicalExpr>()
254        .ok()
255}
256
257pub(crate) fn register_remote_dyn_filters(
258    registry: &QueryDynFilterRegistry,
259    captured_dyn_filters: &[CapturedDynFilter],
260) {
261    for captured_dyn_filter in captured_dyn_filters {
262        let _ = registry.register_remote_dyn_filter(
263            captured_dyn_filter.filter_id.clone(),
264            captured_dyn_filter.alive_dyn_filter.clone(),
265        );
266    }
267}
268
269pub(crate) fn register_dyn_filter_subscribers_for_region(
270    registry: &QueryDynFilterRegistry,
271    region_id: RegionId,
272    target: RegionQueryTarget,
273    captured_dyn_filters: &[CapturedDynFilter],
274) -> Vec<(FilterId, Subscriber)> {
275    let mut added = Vec::new();
276    for captured_dyn_filter in captured_dyn_filters {
277        let subscriber = Subscriber::new(region_id, target.clone());
278        let registration =
279            registry.register_subscriber(&captured_dyn_filter.filter_id, subscriber.clone());
280        match registration {
281            SubscriberRegistration::Added => {
282                added.push((captured_dyn_filter.filter_id.clone(), subscriber))
283            }
284            SubscriberRegistration::Duplicate => {}
285            SubscriberRegistration::MissingFilter => {
286                common_telemetry::warn!(
287                    "Remote dynamic filter {} missing when registering subscriber for region {} at target {:?}",
288                    captured_dyn_filter.filter_id,
289                    region_id,
290                    target
291                );
292            }
293        }
294    }
295    added
296}
297
298fn build_captured_dyn_filter(
299    remote_dyn_filter_producer_id: RemoteDynFilterProducerId,
300    producer_local_ordinal: usize,
301    alive_dyn_filter: Arc<DynamicFilterPhysicalExpr>,
302) -> Result<CapturedDynFilter> {
303    let children = alive_dyn_filter
304        .children()
305        .into_iter()
306        .cloned()
307        .collect::<Vec<_>>();
308    let filter_id = build_remote_dyn_filter_id(
309        remote_dyn_filter_producer_id,
310        producer_local_ordinal,
311        &children,
312    )?;
313    let initial_registration =
314        InitialDynFilterReg::from_filter_id_and_children(filter_id.to_string(), &children)?;
315
316    Ok(CapturedDynFilter {
317        filter_id,
318        initial_registration: attach_initial_snapshot(initial_registration, &alive_dyn_filter),
319        alive_dyn_filter,
320        scalar_subquery_filter: None,
321    })
322}
323
324fn validate_initial_registrations_for_pushdown(
325    captured_dyn_filters: &[CapturedDynFilter],
326) -> std::result::Result<(), String> {
327    let regs = build_initial_dyn_filter_regs_for_region(captured_dyn_filters);
328    regs.validate_default_bounds()?;
329    regs.to_extension_value()
330        .map_err(|error| error.to_string())?;
331    Ok(())
332}
333
334fn attach_initial_snapshot(
335    initial_registration: InitialDynFilterReg,
336    alive_dyn_filter: &DynamicFilterPhysicalExpr,
337) -> InitialDynFilterReg {
338    let Some(initial_snapshot) = initial_snapshot(alive_dyn_filter) else {
339        return initial_registration;
340    };
341
342    initial_registration.with_initial_snapshot(initial_snapshot)
343}
344
345/// Initial snapshot of a captured filter, or `None` when regions must not be filtered yet.
346///
347/// A predicate transport cannot represent (or that does not fit the payload budget) is
348/// *not* replaced with `true`: only the initial snapshot is dropped (warn + metric), so the
349/// region starts with no initial predicate but still receives the registration itself
350/// (filter id plus children) and installs its `true` placeholder. Later updates land in
351/// that placeholder - a representable payload, or the explicit `true` reset the registry
352/// publishes when a generation has no wire form. The capture reports `PushedDown::No` so
353/// the parent keeps evaluating the filter itself.
354fn initial_snapshot(
355    alive_dyn_filter: &DynamicFilterPhysicalExpr,
356) -> Option<InitialDynFilterSnapshot> {
357    let generation = alive_dyn_filter.snapshot_generation();
358    let current = match alive_dyn_filter.current() {
359        Ok(current) => current,
360        Err(error) => {
361            common_telemetry::warn!(error; "Failed to read remote dyn filter initial snapshot");
362            return None;
363        }
364    };
365
366    let payload = match DynFilterPayload::from_datafusion_expr(
367        &current,
368        REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
369    ) {
370        Ok(payload) => payload,
371        Err(error) if is_dyn_filter_unsupported(&error) => {
372            REMOTE_DYN_FILTER_ENCODE_TOTAL
373                .with_label_values(&["unsupported"])
374                .inc();
375            common_telemetry::warn!(
376                error; "Remote dyn filter initial snapshot is dropped because the predicate has no wire form"
377            );
378            return None;
379        }
380        Err(error) if is_dyn_filter_payload_too_large(&error) => {
381            REMOTE_DYN_FILTER_ENCODE_TOTAL
382                .with_label_values(&["too_large"])
383                .inc();
384            common_telemetry::warn!(
385                error; "Remote dyn filter initial snapshot is dropped because the predicate does not fit the payload budget"
386            );
387            return None;
388        }
389        Err(error) => {
390            common_telemetry::warn!(error; "Failed to encode remote dyn filter initial snapshot");
391            return None;
392        }
393    };
394
395    // Current DataFusion exposes `wait_complete()`, but no non-blocking completion getter.
396    let is_complete = false;
397    Some(InitialDynFilterSnapshot::new(
398        payload,
399        generation,
400        is_complete,
401    ))
402}
403
404fn build_initial_dyn_filter_regs_for_region(
405    captured_dyn_filters: &[CapturedDynFilter],
406) -> InitialDynFilterRegs {
407    InitialDynFilterRegs::new(
408        captured_dyn_filters
409            .iter()
410            .map(|captured| captured.initial_registration.clone())
411            .collect(),
412    )
413}
414
415pub(crate) fn query_context_with_initial_dyn_filter_regs(
416    query_ctx: &QueryContextRef,
417    region_id: RegionId,
418    captured_dyn_filters: &[CapturedDynFilter],
419) -> QueryContext {
420    let regs = build_initial_dyn_filter_regs_for_region(captured_dyn_filters);
421    query_context_with_initial_dyn_filter_regs_value(query_ctx, region_id, &regs)
422}
423
424pub(crate) fn query_context_with_refreshed_initial_dyn_filter_regs(
425    query_ctx: &QueryContextRef,
426    _region_id: RegionId,
427    captured_dyn_filters: &[CapturedDynFilter],
428) -> QueryContext {
429    let refreshed = InitialDynFilterRegs::new(
430        captured_dyn_filters
431            .iter()
432            .map(|captured| {
433                attach_initial_snapshot(
434                    captured.initial_registration.clone(),
435                    &captured.alive_dyn_filter,
436                )
437            })
438            .collect(),
439    );
440    let serialized = match serialize_initial_dyn_filter_regs(&refreshed) {
441        Ok(serialized) => serialized,
442        Err(error) => {
443            common_telemetry::warn!(error; "Failed to refresh remote dynamic filter initial registrations; using optimization-time snapshots");
444            return query_context_with_initial_dyn_filter_regs(
445                query_ctx,
446                _region_id,
447                captured_dyn_filters,
448            );
449        }
450    };
451    query_context_with_serialized_initial_dyn_filter_regs(query_ctx, serialized)
452}
453
454fn query_context_with_initial_dyn_filter_regs_value(
455    query_ctx: &QueryContextRef,
456    region_id: RegionId,
457    regs: &InitialDynFilterRegs,
458) -> QueryContext {
459    let region_query_ctx = query_ctx.as_ref().clone();
460    if regs.is_empty() {
461        return region_query_ctx;
462    }
463
464    match serialize_initial_dyn_filter_regs(regs) {
465        Ok(serialized) => {
466            return query_context_with_serialized_initial_dyn_filter_regs(query_ctx, serialized);
467        }
468        Err(error) => {
469            common_telemetry::warn!(error; "Failed to serialize initial remote dyn filter registrations for region {}", region_id)
470        }
471    }
472
473    region_query_ctx
474}
475
476fn query_context_with_serialized_initial_dyn_filter_regs(
477    query_ctx: &QueryContextRef,
478    serialized: String,
479) -> QueryContext {
480    let mut region_query_ctx = query_ctx.as_ref().clone();
481    region_query_ctx.set_extension(
482        INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY,
483        serialized,
484    );
485    region_query_ctx
486}
487
488fn serialize_initial_dyn_filter_regs(
489    regs: &InitialDynFilterRegs,
490) -> std::result::Result<String, String> {
491    regs.validate_default_bounds()?;
492    regs.to_extension_value().map_err(|error| error.to_string())
493}
494
495#[cfg(test)]
496mod tests {
497    use std::fmt;
498    use std::hash::{Hash, Hasher};
499
500    use common_meta::peer::Peer;
501    use datafusion::execution::TaskContext;
502    use datafusion::physical_plan::joins::join_hash_map::JoinHashMapU32;
503    use datafusion::physical_plan::joins::{HashTableLookupExpr, Map, SeededRandomState};
504    use datafusion_common::ScalarValue;
505    use datafusion_expr::ColumnarValue;
506    use datafusion_expr::Operator;
507    use datafusion_expr::physical_planning_context::{ScalarSubqueryResults, SubqueryIndex};
508    use datafusion_physical_expr::expressions::{BinaryExpr, NotExpr};
509    use session::query_id::QueryId;
510    use uuid::Uuid;
511
512    use super::*;
513    use crate::region_query::RegionQueryTarget;
514
515    #[derive(Debug)]
516    struct UnserializableExpr;
517
518    impl fmt::Display for UnserializableExpr {
519        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520            write!(f, "unserializable_expr")
521        }
522    }
523
524    impl Hash for UnserializableExpr {
525        fn hash<H: Hasher>(&self, state: &mut H) {
526            "unserializable_expr".hash(state);
527        }
528    }
529
530    impl PartialEq for UnserializableExpr {
531        fn eq(&self, _other: &Self) -> bool {
532            true
533        }
534    }
535
536    impl Eq for UnserializableExpr {}
537
538    impl datafusion_physical_expr::PhysicalExpr for UnserializableExpr {
539        fn data_type(
540            &self,
541            _input_schema: &arrow_schema::Schema,
542        ) -> datafusion_common::Result<arrow_schema::DataType> {
543            Ok(arrow_schema::DataType::Boolean)
544        }
545
546        fn nullable(
547            &self,
548            _input_schema: &arrow_schema::Schema,
549        ) -> datafusion_common::Result<bool> {
550            Ok(false)
551        }
552
553        fn evaluate(
554            &self,
555            _batch: &common_recordbatch::DfRecordBatch,
556        ) -> datafusion_common::Result<ColumnarValue> {
557            Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))))
558        }
559
560        fn children(&self) -> Vec<&Arc<dyn datafusion_physical_expr::PhysicalExpr>> {
561            Vec::new()
562        }
563
564        fn with_new_children(
565            self: Arc<Self>,
566            _children: Vec<Arc<dyn datafusion_physical_expr::PhysicalExpr>>,
567        ) -> datafusion_common::Result<Arc<dyn datafusion_physical_expr::PhysicalExpr>> {
568            Ok(self)
569        }
570
571        fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
572            write!(f, "{self}")
573        }
574    }
575
576    fn test_query_id(value: u128) -> QueryId {
577        QueryId::from(Uuid::from_u128(value))
578    }
579
580    fn test_remote_dyn_filter_producer_id(value: u64) -> RemoteDynFilterProducerId {
581        RemoteDynFilterProducerId::new(value)
582    }
583
584    fn test_target(id: u64) -> RegionQueryTarget {
585        RegionQueryTarget::new(Peer {
586            id,
587            addr: format!("127.0.0.1:{id}"),
588        })
589    }
590
591    fn test_captured_dyn_filter(
592        remote_dyn_filter_producer_id: RemoteDynFilterProducerId,
593        producer_local_ordinal: usize,
594        column_name: &str,
595        column_index: usize,
596    ) -> CapturedDynFilter {
597        build_captured_dyn_filter(
598            remote_dyn_filter_producer_id,
599            producer_local_ordinal,
600            Arc::new(DynamicFilterPhysicalExpr::new(
601                vec![Arc::new(Column::new(column_name, column_index)) as Arc<_>],
602                lit(true) as _,
603            )),
604        )
605        .unwrap()
606    }
607
608    /// A probe filter whose current predicate has no wire form.
609    ///
610    /// A hand-built lookup has no build lease, hence no key list, and `NOT lookup` is a
611    /// single top-level conjunct that carries the membership: neither a key list nor a
612    /// membership-free conjunct exists.
613    fn test_unsupported_snapshot_filter(
614        column_name: &str,
615        column_index: usize,
616    ) -> Arc<DynamicFilterPhysicalExpr> {
617        let column = Arc::new(Column::new(column_name, column_index)) as Arc<dyn PhysicalExpr>;
618        let lookup = Arc::new(HashTableLookupExpr::new(
619            vec![Arc::clone(&column)],
620            SeededRandomState::with_seed(0),
621            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(0)))),
622            "hash_lookup".to_string(),
623            None,
624        )) as Arc<dyn PhysicalExpr>;
625        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(
626            vec![Arc::clone(&column) as _],
627            lit(true) as _,
628        ));
629        dyn_filter
630            .update(Arc::new(NotExpr::new(lookup)) as _)
631            .unwrap();
632        dyn_filter
633    }
634
635    fn test_dyn_filter_with_snapshot_payload(
636        column_name: &str,
637        column_index: usize,
638        payload_bytes: usize,
639    ) -> Arc<DynamicFilterPhysicalExpr> {
640        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(
641            vec![Arc::new(Column::new(column_name, column_index)) as Arc<_>],
642            lit(true) as _,
643        ));
644        dyn_filter
645            .update(lit(ScalarValue::Utf8(Some("x".repeat(payload_bytes)))) as _)
646            .unwrap();
647        dyn_filter
648    }
649
650    fn refreshed_regs(captured: &[CapturedDynFilter]) -> InitialDynFilterRegs {
651        let query_ctx = QueryContext::arc();
652        let region_query_ctx = query_context_with_refreshed_initial_dyn_filter_regs(
653            &query_ctx,
654            RegionId::new(1024, 7),
655            captured,
656        );
657        InitialDynFilterRegs::from_extension_value(
658            region_query_ctx
659                .extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY)
660                .unwrap(),
661        )
662        .unwrap()
663    }
664
665    fn decode_snapshot(snapshot: &InitialDynFilterSnapshot, column_name: &str) -> String {
666        snapshot
667            .payload
668            .decode_datafusion_expr(
669                &TaskContext::default(),
670                &arrow_schema::Schema::new(vec![arrow_schema::Field::new(
671                    column_name,
672                    arrow_schema::DataType::Utf8,
673                    false,
674                )]),
675                REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
676            )
677            .unwrap()
678            .to_string()
679    }
680
681    fn pushed_down(pushdown: &RemoteDynFilterPushdown) -> Vec<bool> {
682        pushdown
683            .pushed_down
684            .iter()
685            .map(|pushed_down| matches!(pushed_down, PushedDown::Yes))
686            .collect()
687    }
688
689    fn host_eq_scalar_subquery(results: &ScalarSubqueryResults) -> Arc<dyn PhysicalExpr> {
690        Arc::new(BinaryExpr::new(
691            Arc::new(Column::new("host", 0)),
692            Operator::Eq,
693            Arc::new(ScalarSubqueryExpr::new(
694                arrow_schema::DataType::Utf8,
695                true,
696                SubqueryIndex::new(0),
697                results.clone(),
698            )),
699        ))
700    }
701
702    #[test]
703    fn scalar_subquery_filter_is_captured_but_left_to_parent() {
704        let results = ScalarSubqueryResults::new(1);
705        let parent_filters = vec![
706            host_eq_scalar_subquery(&results),
707            Arc::new(BinaryExpr::new(
708                Arc::new(Column::new("host", 0)),
709                Operator::Eq,
710                lit("a"),
711            )) as Arc<dyn PhysicalExpr>,
712        ];
713
714        let pushdown = capture_remote_dyn_filters_for_pushdown(
715            test_remote_dyn_filter_producer_id(42),
716            0,
717            &[],
718            parent_filters,
719        );
720
721        assert_eq!(pushed_down(&pushdown), vec![false, false]);
722        assert_eq!(pushdown.captured_dyn_filters.len(), 1);
723        assert_eq!(
724            pushdown.captured_dyn_filters[0]
725                .filter_id
726                .producer_ordinal(),
727            0
728        );
729    }
730
731    #[test]
732    fn scalar_subquery_filter_with_in_list_is_captured_and_never_narrowed() {
733        // Transport never substitutes `true` for a node and only drops whole top-level
734        // conjuncts, so the `IN` list inside `(host IN ('a', 'b')) = (SELECT flag ...)` is
735        // kept or refused as a whole, never narrowed.
736        let results = ScalarSubqueryResults::new(1);
737        let schema = arrow_schema::Schema::new(vec![arrow_schema::Field::new(
738            "host",
739            arrow_schema::DataType::Utf8,
740            true,
741        )]);
742        let host_in_list = datafusion_physical_expr::expressions::in_list(
743            Arc::new(Column::new("host", 0)),
744            vec![lit("a"), lit("b")],
745            &false,
746            &schema,
747        )
748        .unwrap();
749        let filter = Arc::new(BinaryExpr::new(
750            host_in_list,
751            Operator::Eq,
752            Arc::new(ScalarSubqueryExpr::new(
753                arrow_schema::DataType::Boolean,
754                true,
755                SubqueryIndex::new(0),
756                results.clone(),
757            )),
758        )) as Arc<dyn PhysicalExpr>;
759
760        let pushdown = capture_remote_dyn_filters_for_pushdown(
761            test_remote_dyn_filter_producer_id(42),
762            0,
763            &[],
764            vec![filter],
765        );
766
767        // Captured like any other scalar subquery filter, and still left to the parent.
768        assert_eq!(pushed_down(&pushdown), vec![false]);
769        assert_eq!(pushdown.captured_dyn_filters.len(), 1);
770        let captured = &pushdown.captured_dyn_filters[0];
771
772        // Once resolved, the published predicate keeps the `IN` list structurally instead
773        // of widening it to `true`: `(host IN (...)) = true`.
774        results
775            .set(SubqueryIndex::new(0), ScalarValue::Boolean(Some(true)))
776            .unwrap();
777        resolve_scalar_subquery_dyn_filters(std::slice::from_ref(captured));
778        let snapshot = refreshed_regs(std::slice::from_ref(captured)).regs[0]
779            .initial_snapshot
780            .clone()
781            .expect("the resolved predicate is representable");
782        let display = decode_snapshot(&snapshot, "host");
783        assert!(
784            display.contains("IN"),
785            "the IN list must survive the wire: {display}"
786        );
787        assert_ne!(display, "true", "transport must not widen to `true`");
788        assert!(
789            display.ends_with("= true"),
790            "the equality over the IN list must survive: {display}"
791        );
792
793        // A payload that does not fit is refused outright rather than narrowed: the whole
794        // conjunct is dropped and nothing is left to ship.
795        let current = captured.alive_dyn_filter.current().unwrap();
796        let refused = DynFilterPayload::from_datafusion_expr(&current, 8).unwrap_err();
797        assert!(
798            is_dyn_filter_payload_too_large(&refused),
799            "an oversized payload must be refused as too large, got: {refused:?}"
800        );
801    }
802
803    #[test]
804    fn scalar_subquery_dyn_filter_follows_subquery_results() {
805        let results = ScalarSubqueryResults::new(1);
806        let captured = capture_remote_dyn_filters_for_pushdown(
807            test_remote_dyn_filter_producer_id(42),
808            0,
809            &[],
810            vec![host_eq_scalar_subquery(&results)],
811        )
812        .captured_dyn_filters;
813        let snapshot = |captured: &[CapturedDynFilter]| {
814            decode_snapshot(
815                refreshed_regs(captured).regs[0]
816                    .initial_snapshot
817                    .as_ref()
818                    .unwrap(),
819                "host",
820            )
821        };
822
823        // Not executed yet: regions must not be filtered.
824        resolve_scalar_subquery_dyn_filters(&captured);
825        assert_eq!(snapshot(&captured), "true");
826
827        results
828            .set(
829                SubqueryIndex::new(0),
830                ScalarValue::Utf8(Some("a".to_string())),
831            )
832            .unwrap();
833        resolve_scalar_subquery_dyn_filters(&captured);
834        assert_eq!(snapshot(&captured), "host@0 = a");
835
836        // `ScalarSubqueryExec::reset_state` clears the results before re-execution.
837        results.clear();
838        resolve_scalar_subquery_dyn_filters(&captured);
839        assert_eq!(snapshot(&captured), "true");
840    }
841
842    #[test]
843    fn capture_remote_dyn_filters_for_pushdown_preserves_parent_filter_ordinals() {
844        let parent_filters = vec![
845            Arc::new(Column::new("service", 0)) as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
846            Arc::new(DynamicFilterPhysicalExpr::new(
847                vec![Arc::new(Column::new("host", 1)) as Arc<_>],
848                lit(true) as _,
849            )) as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
850            Arc::new(Column::new("zone", 2)) as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
851            Arc::new(DynamicFilterPhysicalExpr::new(
852                vec![Arc::new(Column::new("pod", 3)) as Arc<_>],
853                lit(true) as _,
854            )) as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
855        ];
856
857        let remote_dyn_filter_producer_id = test_remote_dyn_filter_producer_id(42);
858        let captured = capture_remote_dyn_filters_for_pushdown(
859            remote_dyn_filter_producer_id,
860            0,
861            &[],
862            parent_filters,
863        )
864        .captured_dyn_filters;
865
866        assert_eq!(captured.len(), 2);
867        assert_eq!(
868            captured[0].filter_id.remote_dyn_filter_producer_id(),
869            remote_dyn_filter_producer_id
870        );
871        assert_eq!(
872            captured[1].filter_id.remote_dyn_filter_producer_id(),
873            remote_dyn_filter_producer_id
874        );
875        assert_eq!(captured[0].filter_id.producer_ordinal(), 1);
876        assert_eq!(captured[1].filter_id.producer_ordinal(), 3);
877    }
878
879    #[test]
880    fn capture_remote_dyn_filters_for_pushdown_marks_only_valid_initial_regs() {
881        let parent_filters = vec![
882            Arc::new(Column::new("service", 0)) as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
883            Arc::new(DynamicFilterPhysicalExpr::new(
884                vec![Arc::new(Column::new("host", 1)) as Arc<_>],
885                lit(true) as _,
886            )) as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
887            Arc::new(Column::new("zone", 2)) as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
888        ];
889
890        let remote_dyn_filter_producer_id = test_remote_dyn_filter_producer_id(42);
891        let pushdown = capture_remote_dyn_filters_for_pushdown(
892            remote_dyn_filter_producer_id,
893            0,
894            &[],
895            parent_filters,
896        );
897
898        assert_eq!(pushed_down(&pushdown), vec![false, true, false]);
899        assert_eq!(pushdown.captured_dyn_filters.len(), 1);
900        assert_eq!(
901            pushdown.captured_dyn_filters[0]
902                .filter_id
903                .remote_dyn_filter_producer_id(),
904            remote_dyn_filter_producer_id
905        );
906        assert_eq!(
907            pushdown.captured_dyn_filters[0]
908                .filter_id
909                .producer_ordinal(),
910            1
911        );
912        assert!(
913            pushdown.captured_dyn_filters[0]
914                .initial_registration
915                .initial_snapshot
916                .is_some()
917        );
918    }
919
920    #[test]
921    fn capture_remote_dyn_filters_for_pushdown_rejects_unencodable_registration() {
922        let parent_filters = vec![Arc::new(DynamicFilterPhysicalExpr::new(
923            vec![Arc::new(UnserializableExpr) as Arc<_>],
924            lit(true) as _,
925        ))
926            as Arc<dyn datafusion::physical_plan::PhysicalExpr>];
927
928        let pushdown = capture_remote_dyn_filters_for_pushdown(
929            test_remote_dyn_filter_producer_id(42),
930            0,
931            &[],
932            parent_filters,
933        );
934
935        assert_eq!(pushed_down(&pushdown), vec![false]);
936        assert!(pushdown.captured_dyn_filters.is_empty());
937    }
938
939    #[test]
940    fn capture_remote_dyn_filters_for_pushdown_skips_unsupported_initial_snapshot() {
941        // The parent retention and the registration are checked end to end: the capture
942        // still sends its registration (filter id plus children) but no initial predicate,
943        // the region installs its `true` placeholder, and a later representable generation
944        // still reaches it.
945        let dyn_filter = test_unsupported_snapshot_filter("host", 0);
946        let parent_filters =
947            vec![Arc::clone(&dyn_filter) as Arc<dyn datafusion::physical_plan::PhysicalExpr>];
948
949        let pushdown = capture_remote_dyn_filters_for_pushdown(
950            test_remote_dyn_filter_producer_id(42),
951            0,
952            &[],
953            parent_filters,
954        );
955
956        // No snapshot is published (and it is never replaced with `true`), so the parent
957        // must keep evaluating the filter itself.
958        assert_eq!(pushed_down(&pushdown), vec![false]);
959        assert_eq!(pushdown.captured_dyn_filters.len(), 1);
960        let captured = &pushdown.captured_dyn_filters[0];
961        assert!(captured.initial_registration.initial_snapshot.is_none());
962        assert!(
963            !captured
964                .initial_registration
965                .child_exprs_datafusion_proto
966                .is_empty(),
967            "the registration must still describe the filter children"
968        );
969
970        // The registration survives the wire: filter id and children are intact, and the
971        // region installs the filter with a `true` placeholder and no initial predicate.
972        let regs = build_initial_dyn_filter_regs_for_region(&pushdown.captured_dyn_filters);
973        let serialized = regs.to_extension_value().unwrap();
974        let received = InitialDynFilterRegs::from_extension_value(&serialized).unwrap();
975        assert_eq!(received.regs.len(), 1);
976        assert_eq!(
977            received.regs[0].filter_id,
978            captured.filter_id.to_string(),
979            "the filter id must survive serialization"
980        );
981        assert!(received.regs[0].initial_snapshot.is_none());
982        let schema = Arc::new(arrow_schema::Schema::new(vec![arrow_schema::Field::new(
983            "host",
984            arrow_schema::DataType::Utf8,
985            true,
986        )]));
987        let children = received.regs[0]
988            .decode_children(
989                &TaskContext::default(),
990                &schema,
991                REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
992            )
993            .unwrap();
994        assert_eq!(children.len(), 1);
995        assert!(children[0].is::<Column>());
996
997        // A later generation transport can represent is delivered to the installed filter.
998        dyn_filter.update(lit(false) as _).unwrap();
999        let current = captured.alive_dyn_filter.current().unwrap();
1000        let payload =
1001            DynFilterPayload::from_datafusion_expr(&current, REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES)
1002                .unwrap();
1003        let decoded = payload
1004            .decode_datafusion_expr(
1005                &TaskContext::default(),
1006                &schema,
1007                REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
1008            )
1009            .unwrap();
1010        assert_eq!(decoded.to_string(), "false");
1011        let installed = Arc::new(DynamicFilterPhysicalExpr::new(children, lit(true) as _));
1012        let generation = installed.snapshot_generation();
1013        installed.update(decoded).unwrap();
1014        assert!(
1015            installed.snapshot_generation() > generation,
1016            "the receiver generation must advance"
1017        );
1018        assert_eq!(installed.current().unwrap().to_string(), "false");
1019    }
1020
1021    #[test]
1022    fn capture_remote_dyn_filters_for_pushdown_attaches_initial_snapshot_after_update() {
1023        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(
1024            vec![Arc::new(Column::new("host", 1)) as Arc<_>],
1025            lit(true) as _,
1026        ));
1027        dyn_filter.update(lit(false) as _).unwrap();
1028        let parent_filters = vec![dyn_filter as Arc<dyn datafusion::physical_plan::PhysicalExpr>];
1029
1030        let pushdown = capture_remote_dyn_filters_for_pushdown(
1031            test_remote_dyn_filter_producer_id(42),
1032            0,
1033            &[],
1034            parent_filters,
1035        );
1036
1037        assert_eq!(pushed_down(&pushdown), vec![true]);
1038        let snapshot = pushdown.captured_dyn_filters[0]
1039            .initial_registration
1040            .initial_snapshot
1041            .as_ref()
1042            .unwrap();
1043        assert_eq!(snapshot.generation, 2);
1044        assert!(!snapshot.is_complete);
1045        assert!(matches!(
1046            snapshot.payload,
1047            DynFilterPayload::Datafusion(ref bytes) if !bytes.is_empty()
1048        ));
1049    }
1050
1051    #[test]
1052    fn capture_remote_dyn_filters_for_pushdown_rejects_oversized_snapshots() {
1053        let oversized_total_snapshot_bytes = REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES * 3 / 5;
1054        let parent_filters = vec![
1055            test_dyn_filter_with_snapshot_payload("host", 0, oversized_total_snapshot_bytes)
1056                as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
1057            test_dyn_filter_with_snapshot_payload("pod", 1, oversized_total_snapshot_bytes)
1058                as Arc<dyn datafusion::physical_plan::PhysicalExpr>,
1059        ];
1060
1061        let pushdown = capture_remote_dyn_filters_for_pushdown(
1062            test_remote_dyn_filter_producer_id(42),
1063            0,
1064            &[],
1065            parent_filters,
1066        );
1067
1068        assert_eq!(pushed_down(&pushdown), vec![false, false]);
1069        assert!(pushdown.captured_dyn_filters.is_empty());
1070    }
1071
1072    #[test]
1073    fn capture_remote_dyn_filters_for_pushdown_keeps_accepted_filters_within_budget() {
1074        const MAX_INITIAL_REGS: usize = 64;
1075
1076        let accepted = capture_remote_dyn_filters_for_pushdown(
1077            test_remote_dyn_filter_producer_id(42),
1078            0,
1079            &[],
1080            (0..MAX_INITIAL_REGS)
1081                .map(|ordinal| {
1082                    test_dyn_filter_with_snapshot_payload(&format!("host_{ordinal}"), ordinal, 1)
1083                        as Arc<dyn PhysicalExpr>
1084                })
1085                .collect(),
1086        )
1087        .captured_dyn_filters;
1088        assert_eq!(accepted.len(), MAX_INITIAL_REGS);
1089
1090        let results = ScalarSubqueryResults::new(1);
1091        let pushdown = capture_remote_dyn_filters_for_pushdown(
1092            test_remote_dyn_filter_producer_id(42),
1093            1 << 31,
1094            &accepted,
1095            vec![host_eq_scalar_subquery(&results)],
1096        );
1097
1098        assert_eq!(pushed_down(&pushdown), vec![false]);
1099        assert!(pushdown.captured_dyn_filters.is_empty());
1100    }
1101
1102    #[test]
1103    fn capture_remote_dyn_filters_for_pushdown_rejects_too_many_regs_with_snapshots() {
1104        const TOO_MANY_INITIAL_REGS: usize = 65;
1105
1106        let parent_filters = (0..TOO_MANY_INITIAL_REGS)
1107            .map(|ordinal| {
1108                test_dyn_filter_with_snapshot_payload(&format!("host_{ordinal}"), ordinal, 1)
1109                    as Arc<dyn datafusion::physical_plan::PhysicalExpr>
1110            })
1111            .collect::<Vec<_>>();
1112
1113        let pushdown = capture_remote_dyn_filters_for_pushdown(
1114            test_remote_dyn_filter_producer_id(42),
1115            0,
1116            &[],
1117            parent_filters,
1118        );
1119
1120        assert!(pushdown.captured_dyn_filters.is_empty());
1121        assert_eq!(pushed_down(&pushdown), vec![false; TOO_MANY_INITIAL_REGS]);
1122    }
1123
1124    #[test]
1125    fn register_dyn_filter_subscribers_for_region_reuses_existing_entry() {
1126        let registry = QueryDynFilterRegistry::new(test_query_id(1));
1127        let captured_dyn_filters = vec![test_captured_dyn_filter(
1128            test_remote_dyn_filter_producer_id(42),
1129            2,
1130            "host",
1131            0,
1132        )];
1133        let first_region_id = RegionId::new(1024, 7);
1134        let second_region_id = RegionId::new(1024, 8);
1135
1136        register_remote_dyn_filters(&registry, &captured_dyn_filters);
1137        register_dyn_filter_subscribers_for_region(
1138            &registry,
1139            first_region_id,
1140            test_target(1),
1141            &captured_dyn_filters,
1142        );
1143        register_dyn_filter_subscribers_for_region(
1144            &registry,
1145            second_region_id,
1146            test_target(2),
1147            &captured_dyn_filters,
1148        );
1149
1150        assert_eq!(registry.entry_count(), 1);
1151        let entry = registry.entries().pop().unwrap();
1152        assert_eq!(
1153            entry.filter_id().remote_dyn_filter_producer_id(),
1154            test_remote_dyn_filter_producer_id(42)
1155        );
1156        assert_eq!(entry.filter_id().producer_ordinal(), 2);
1157        let subscribers = entry.subscribers();
1158        assert_eq!(subscribers.len(), 2);
1159        assert!(
1160            subscribers
1161                .iter()
1162                .any(|subscriber| subscriber.region_id() == first_region_id)
1163        );
1164        assert!(
1165            subscribers
1166                .iter()
1167                .any(|subscriber| subscriber.region_id() == second_region_id)
1168        );
1169    }
1170
1171    #[test]
1172    fn register_remote_dyn_filters_keeps_independent_producer_ids_distinct() {
1173        let registry = QueryDynFilterRegistry::new(test_query_id(1));
1174        let make_filter = |remote_dyn_filter_producer_id| {
1175            test_captured_dyn_filter(remote_dyn_filter_producer_id, 2, "host", 0)
1176        };
1177
1178        register_remote_dyn_filters(
1179            &registry,
1180            &[make_filter(test_remote_dyn_filter_producer_id(42))],
1181        );
1182        register_remote_dyn_filters(
1183            &registry,
1184            &[make_filter(test_remote_dyn_filter_producer_id(43))],
1185        );
1186
1187        assert_eq!(registry.entry_count(), 2);
1188    }
1189
1190    #[test]
1191    fn query_context_includes_region_initial_dyn_filter_regs() {
1192        let captured_dyn_filters = vec![test_captured_dyn_filter(
1193            test_remote_dyn_filter_producer_id(42),
1194            2,
1195            "host",
1196            0,
1197        )];
1198        let region_id = RegionId::new(1024, 7);
1199        let query_ctx = QueryContext::arc();
1200
1201        let region_query_ctx = query_context_with_initial_dyn_filter_regs(
1202            &query_ctx,
1203            region_id,
1204            &captured_dyn_filters,
1205        );
1206        let extension = region_query_ctx
1207            .extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY)
1208            .unwrap();
1209        let regs = InitialDynFilterRegs::from_extension_value(extension).unwrap();
1210        let decoded_children = regs.regs[0]
1211            .decode_children(
1212                &TaskContext::default(),
1213                &arrow_schema::Schema::new(vec![arrow_schema::Field::new(
1214                    "host",
1215                    arrow_schema::DataType::Utf8,
1216                    false,
1217                )]),
1218                1024,
1219            )
1220            .unwrap();
1221        assert_eq!(regs.regs.len(), 1);
1222        assert_eq!(
1223            regs.regs[0].filter_id,
1224            captured_dyn_filters[0].filter_id.to_string()
1225        );
1226        assert_eq!(decoded_children.len(), 1);
1227        assert!(decoded_children[0].is::<Column>());
1228    }
1229
1230    #[test]
1231    fn refreshed_initial_regs_use_live_filter_snapshot_without_mutating_capture() {
1232        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(
1233            vec![Arc::new(Column::new("host", 0)) as Arc<_>],
1234            lit(true) as _,
1235        ));
1236        let captured = vec![
1237            build_captured_dyn_filter(
1238                test_remote_dyn_filter_producer_id(42),
1239                0,
1240                dyn_filter.clone(),
1241            )
1242            .unwrap(),
1243        ];
1244        let original_generation = captured[0]
1245            .initial_registration
1246            .initial_snapshot
1247            .as_ref()
1248            .unwrap()
1249            .generation;
1250        dyn_filter.update(lit(false) as _).unwrap();
1251        dyn_filter.mark_complete();
1252
1253        let regs = refreshed_regs(&captured);
1254
1255        let snapshot = regs.regs[0].initial_snapshot.as_ref().unwrap();
1256        assert_eq!(snapshot.generation, 2);
1257        assert!(!snapshot.is_complete);
1258        assert_ne!(decode_snapshot(snapshot, "host"), "true");
1259        assert_eq!(
1260            captured[0]
1261                .initial_registration
1262                .initial_snapshot
1263                .as_ref()
1264                .unwrap()
1265                .generation,
1266            original_generation
1267        );
1268    }
1269
1270    #[test]
1271    fn refresh_keeps_old_snapshot_when_one_live_filter_cannot_encode() {
1272        let good = Arc::new(DynamicFilterPhysicalExpr::new(
1273            vec![Arc::new(Column::new("good", 0)) as Arc<_>],
1274            lit(true) as _,
1275        ));
1276        let bad = Arc::new(DynamicFilterPhysicalExpr::new(
1277            vec![Arc::new(Column::new("bad", 0)) as Arc<_>],
1278            lit(true) as _,
1279        ));
1280        let captured = vec![
1281            build_captured_dyn_filter(test_remote_dyn_filter_producer_id(42), 0, good.clone())
1282                .unwrap(),
1283            build_captured_dyn_filter(test_remote_dyn_filter_producer_id(42), 1, bad.clone())
1284                .unwrap(),
1285        ];
1286        let old_bad_generation = captured[1]
1287            .initial_registration
1288            .initial_snapshot
1289            .as_ref()
1290            .unwrap()
1291            .generation;
1292        good.update(lit(false) as _).unwrap();
1293        bad.update(Arc::new(UnserializableExpr) as _).unwrap();
1294
1295        let regs = refreshed_regs(&captured);
1296        assert_eq!(
1297            regs.regs[0].initial_snapshot.as_ref().unwrap().generation,
1298            2
1299        );
1300        assert_eq!(
1301            regs.regs[1].initial_snapshot.as_ref().unwrap().generation,
1302            old_bad_generation
1303        );
1304    }
1305
1306    #[test]
1307    fn refresh_aggregate_overflow_falls_back_to_original_snapshots() {
1308        let payload_bytes = REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES * 3 / 5;
1309        let first = test_dyn_filter_with_snapshot_payload("first", 0, 1);
1310        let second = test_dyn_filter_with_snapshot_payload("second", 0, 1);
1311        let captured = vec![
1312            build_captured_dyn_filter(test_remote_dyn_filter_producer_id(42), 0, first.clone())
1313                .unwrap(),
1314            build_captured_dyn_filter(test_remote_dyn_filter_producer_id(42), 1, second.clone())
1315                .unwrap(),
1316        ];
1317        let original = captured
1318            .iter()
1319            .map(|captured| {
1320                captured
1321                    .initial_registration
1322                    .initial_snapshot
1323                    .clone()
1324                    .unwrap()
1325            })
1326            .collect::<Vec<_>>();
1327        first
1328            .update(lit(ScalarValue::Utf8(Some("x".repeat(payload_bytes)))) as _)
1329            .unwrap();
1330        second
1331            .update(lit(ScalarValue::Utf8(Some("y".repeat(payload_bytes)))) as _)
1332            .unwrap();
1333
1334        let regs = refreshed_regs(&captured);
1335        for (refreshed, original) in regs.regs.iter().zip(original) {
1336            let refreshed = refreshed.initial_snapshot.as_ref().unwrap();
1337            assert_eq!(refreshed.generation, original.generation);
1338            assert_eq!(refreshed.payload, original.payload);
1339        }
1340    }
1341
1342    #[test]
1343    fn query_context_drops_initial_regs_when_duplicate_filter_ids_exceed_bounds() {
1344        let captured_dyn_filters = vec![
1345            test_captured_dyn_filter(test_remote_dyn_filter_producer_id(42), 2, "host", 0),
1346            test_captured_dyn_filter(test_remote_dyn_filter_producer_id(42), 2, "host", 0),
1347        ];
1348        let region_id = RegionId::new(1024, 7);
1349        let query_ctx = QueryContext::arc();
1350
1351        let region_query_ctx = query_context_with_initial_dyn_filter_regs(
1352            &query_ctx,
1353            region_id,
1354            &captured_dyn_filters,
1355        );
1356
1357        assert!(
1358            region_query_ctx
1359                .extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY)
1360                .is_none()
1361        );
1362    }
1363}