Skip to main content

common_query/
request.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
15mod base64_serde;
16mod initial_remote_dyn_filter_reg;
17#[cfg(any(test, feature = "testing"))]
18pub mod remote_membership_test_support;
19
20use std::cell::Cell;
21use std::sync::Arc;
22
23use api::v1::region::RegionRequestHeader;
24use datafusion::arrow::array::{Array, ArrayRef, StringArray};
25use datafusion::execution::TaskContext;
26use datafusion::physical_expr::expressions::{Column, InListExpr, Literal};
27use datafusion::physical_expr::{conjunction, split_conjunction};
28use datafusion::physical_plan::joins::HashTableLookupExpr;
29use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr};
30use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
31use datafusion_common::{DataFusionError, Result as DataFusionResult, ScalarValue};
32use datafusion_expr::LogicalPlan;
33use datafusion_proto::physical_plan::from_proto::parse_physical_expr;
34use datafusion_proto::physical_plan::to_proto::{
35    serialize_physical_expr, serialize_physical_expr_with_converter,
36};
37use datafusion_proto::physical_plan::{
38    DefaultPhysicalExtensionCodec, DefaultPhysicalProtoConverter, PhysicalExtensionCodec,
39    PhysicalPlanDecodeContext, PhysicalProtoConverterExtension,
40};
41use datafusion_proto::protobuf::physical_expr_node::ExprType as PhysicalExprNodeType;
42use datafusion_proto::protobuf::{PhysicalExprNode, PhysicalInListNode, PhysicalPlanNode};
43use prost::Message;
44use serde::{Deserialize, Serialize};
45use snafu::ensure;
46use store_api::storage::RegionId;
47
48/// Current wire-format version for remote dynamic filter payload updates.
49pub use self::initial_remote_dyn_filter_reg::{
50    INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, InitialDynFilterReg,
51    InitialDynFilterRegs, InitialDynFilterSnapshot,
52};
53use crate::error::{
54    DynFilterPayloadTooLargeSnafu, DynFilterUnsupportedSnafu, Error as CommonQueryError,
55};
56
57pub const DYN_FILTER_PROTOCOL_VERSION: u32 = 1;
58/// Shared raw protobuf byte budget for remote dynamic filter payloads.
59pub const REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES: usize = 512 * 1024;
60
61/// Smallest number of encoded bytes a single `IN` list literal can take.
62///
63/// Every list entry is a `PhysicalExprNode` whose `literal` arm holds the
64/// [`ScalarValue`] message itself, so the oneof field tag plus its length prefix are
65/// already 2 bytes even for an empty `Utf8` value (whose `ScalarValue` body may encode to
66/// nothing at all). Protobuf sizes add up across nesting, so a payload of `B` bytes can
67/// never hold more than `B / 2` literals. This is the floor the value bound is derived
68/// from; it is not an encoder policy constant.
69const MIN_ENCODED_LITERAL_BYTES: usize = 2;
70
71/// Upper bound on how many `IN` list literals `max_payload_bytes` can hold.
72///
73/// The count bound is derived from the transport budget with
74/// [`MIN_ENCODED_LITERAL_BYTES`] rather than being an arbitrary cap: a larger budget
75/// admits proportionally more build keys, and a small budget refuses the membership
76/// before a single literal is built.
77fn max_membership_values(max_payload_bytes: usize) -> usize {
78    max_payload_bytes / MIN_ENCODED_LITERAL_BYTES
79}
80
81/// Frame size reported for a payload refused because it does not fit the budget.
82///
83/// A refused payload is never materialized, so there is no measured frame length. The
84/// error reports the largest lower bound that is known instead: the price of the literals
85/// the refused membership would have written (`lower_bound`), or - when nothing about the
86/// shape is known - one byte over the budget. Either way the number is genuinely above
87/// `max_payload_bytes`; it is a bound, never a measurement, and it is only used for
88/// diagnostics.
89fn refused_payload_size(lower_bound: usize, max_payload_bytes: usize) -> usize {
90    lower_bound.max(max_payload_bytes.saturating_add(1))
91}
92
93/// Serialized predicate payload for remote dynamic filter updates.
94///
95/// The payload is tagged in JSON so receivers can reject unsupported encodings
96/// before decoding engine-specific bytes. For DataFusion expressions the
97/// `payload` bytes are serialized by `serde_json` as a base64 string, for example:
98///
99/// ```json
100/// { "kind": "datafusion", "payload": "CQgH" }
101/// ```
102#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
103#[non_exhaustive]
104#[serde(tag = "kind", content = "payload", rename_all = "snake_case")]
105pub enum DynFilterPayload {
106    /// A serialized DataFusion [`PhysicalExpr`] encoded as a protobuf
107    /// [`PhysicalExprNode`].
108    Datafusion(#[serde(with = "base64_serde::bytes")] Vec<u8>),
109}
110
111impl DynFilterPayload {
112    /// Encodes a DataFusion physical expression into a bounded dynamic filter payload.
113    ///
114    /// # Narrow contract: a key list used as a positive pruning hint
115    ///
116    /// A runtime [`HashTableLookupExpr`] is written as the existing
117    /// `PhysicalInListNode` — `key IN (build key, ...)` — built from the lookup's
118    /// published build-key list, so no new wire variant is needed. The expression tree
119    /// around it is preserved node for node: `IS NULL`, `NOT`, `CASE`, `AND`, `OR` and
120    /// every other parent are serialized as-is, and a `NOT` over a lookup therefore
121    /// becomes `NOT IN`.
122    ///
123    /// The membership is a **hint for pruning only**, not a re-statement of the join
124    /// semantics. For supported positive pruning, the list preserves actual build-key
125    /// matches; it is not universal Boolean equivalence. `IN`/`NOT IN` propagate
126    /// `NULL` while a hash lookup can be definite on a `NULL` probe key, and hash
127    /// presence can admit collisions, so a predicate that inspects the *negation* of a
128    /// lookup is not universally equivalent.
129    ///
130    /// The conversion is decided by the lookup alone (single-column `Utf8`, non-empty,
131    /// `NULL`-free build keys — see [`HashTableLookupExpr::build_key_membership`]).
132    /// Exactly one node changes: every [`HashTableLookupExpr`] is written as its key
133    /// list, wherever it sits in the tree (`NOT lookup` included, which is why it
134    /// becomes `NOT IN`). No node is ever replaced by a *weaker stand-in* — in
135    /// particular never by `true` — and no membership is dropped from inside a
136    /// predicate: when a lookup cannot be written at all, the whole top-level `AND`
137    /// conjunct that holds it is dropped (see below) or the payload is rejected.
138    ///
139    /// # Top-level conjunctive retention
140    ///
141    /// If a lookup has no such key list (accessor limitation) or the serialized predicate
142    /// does not fit `max_payload_bytes`, [`split_conjunction`] splits the original
143    /// expression and the whole conjuncts that cannot be shipped are dropped. Dropping an
144    /// `AND` term can only widen a predicate, so the result never drops a row the producer
145    /// would keep. Which conjuncts go depends on why the payload was refused:
146    ///
147    /// - a lookup has no wire form: only conjuncts holding a [`HashTableLookupExpr`] are
148    ///   dropped. A static [`InListExpr`] is representable, so `lookup AND id IN (...)`
149    ///   keeps the list and stays `id IN (...)`;
150    /// - the payload is over budget: conjuncts holding a [`HashTableLookupExpr`] *or* an
151    ///   [`InListExpr`] are dropped, because a static `IN` list is the node that usually
152    ///   blows the budget. `bounds AND oversized IN (...)` becomes `bounds`.
153    ///
154    /// Either way a conjunct is kept or dropped as a whole: a membership nested inside
155    /// `NOT`, `CASE` or `OR` drops that entire conjunct instead of being rewritten.
156    /// Retained conjuncts are encoded again under the same budget, and when the first two
157    /// rules still leave an over-budget payload the second one is applied as well, so a
158    /// static `IN` list that is too large for the budget is dropped last.
159    ///
160    /// # Encoder-level no-substitution rule
161    ///
162    /// This encoder never replaces a node in the producer expression with `true`: it
163    /// serializes the expression, retries after dropping whole top-level conjuncts under
164    /// the retention rules above, or returns an error. A caller decides what a refused
165    /// generation means for its receiver. Initial capture keeps the parent filter local;
166    /// the long-lived query fanout path
167    /// (`remote_dyn_filter_registry::fanout_snapshot_for_query`) publishes an explicit
168    /// `true` reset to invalidate a stale region-side predicate. That reset is not a
169    /// representation of the refused producer expression.
170    ///
171    /// The two refusals stay distinct so callers can tell a shape problem from a size
172    /// problem:
173    ///
174    /// - [`CommonQueryError::DynFilterUnsupported`]: no conjunct can be retained because
175    ///   every one of them holds a lookup with no UTF-8 key list (`NOT lookup`, `CASE` /
176    ///   `OR` over such a membership). The wire has no form for the predicate.
177    /// - [`CommonQueryError::DynFilterPayloadTooLarge`]: the predicate is representable but
178    ///   does not fit `max_payload_bytes` - either a key list itself exceeds the budget, or
179    ///   the retained conjuncts still do not fit. An over-budget key list is never reported
180    ///   as unsupported; it is a size refusal and uses
181    ///   [`ConjunctRetention::OverBudget`].
182    ///
183    /// These refusals do not fail the query in either caller: initial capture leaves the
184    /// parent filter local, while fanout sends an explicit `true` reset instead of leaving
185    /// a stale narrower predicate installed.
186    pub fn from_datafusion_expr(
187        expr: &Arc<dyn PhysicalExpr>,
188        max_payload_bytes: usize,
189    ) -> DataFusionResult<Self> {
190        match encode_bounded_physical_expr_to_bytes(expr, max_payload_bytes) {
191            Ok(bytes) => Ok(Self::Datafusion(bytes)),
192            // The predicate cannot be shipped as it stands: either a lookup has no key
193            // list, or the frame does not fit the budget. Keep the widest *safe* part of
194            // the predicate instead of publishing an always-true filter.
195            Err(CommonQueryError::DynFilterUnsupported { .. }) => retain_membership_free_conjuncts(
196                expr,
197                max_payload_bytes,
198                ConjunctRetention::UnrepresentableLookup,
199            ),
200            Err(CommonQueryError::DynFilterPayloadTooLarge { .. }) => {
201                retain_membership_free_conjuncts(
202                    expr,
203                    max_payload_bytes,
204                    ConjunctRetention::OverBudget,
205                )
206            }
207            Err(error) => Err(DataFusionError::from(error)),
208        }
209    }
210
211    /// Decodes a DataFusion dynamic filter payload against the provided input schema.
212    ///
213    /// The decoded expression is validated to ensure column indexes stay within the receiver-side
214    /// schema, column names are consistent (defensive check), and the payload stays within
215    /// `max_payload_bytes`.
216    ///
217    /// # Precondition: pruning only, never row filtering
218    ///
219    /// The decoded predicate is only a **pruning hint**. The sole production consumer —
220    /// `Predicate::dyn_filters` (in the `table` crate) and its pruning path, reached by
221    /// mito2's row-group pruner — uses it to skip containers whose statistics prove that
222    /// no row can match, so a predicate that is merely *wider* than the producer's costs
223    /// nothing but a wasted scan.
224    ///
225    /// The payload is not a re-statement of the producer predicate: the membership is the
226    /// join's build-key list, so `IN`/`NOT IN` `NULL` propagation and hash collisions can
227    /// make it disagree with a runtime lookup, and the encoder drops whole top-level
228    /// conjuncts it cannot ship (see [`DynFilterPayload::from_datafusion_expr`]). A
229    /// consumer that *filters rows* would turn every such widening into lost data, so row
230    /// filtering must not consume this payload unconditionally: it would need to prove the
231    /// predicate is equivalent for the rows it drops, which this format does not carry.
232    pub fn decode_datafusion_expr(
233        &self,
234        task_ctx: &TaskContext,
235        input_schema: &datafusion::arrow::datatypes::Schema,
236        max_payload_bytes: usize,
237    ) -> DataFusionResult<Arc<dyn PhysicalExpr>> {
238        let Self::Datafusion(bytes) = self;
239        validate_payload_size(bytes.len(), max_payload_bytes).map_err(DataFusionError::from)?;
240        let codec = DefaultPhysicalExtensionCodec {};
241        let proto = PhysicalExprNode::decode(bytes.as_slice()).map_err(|e| {
242            DataFusionError::Internal(format!("Failed to decode PhysicalExprNode: {e}"))
243        })?;
244
245        let expr = parse_physical_expr(&proto, task_ctx, input_schema, &codec)?;
246        validate_supported_payload_expr(&expr)?;
247        validate_decoded_payload_expr(&expr, input_schema)?;
248        Ok(expr)
249    }
250}
251
252fn encode_physical_expr_to_bytes(expr: &Arc<dyn PhysicalExpr>) -> DataFusionResult<Vec<u8>> {
253    let codec = DefaultPhysicalExtensionCodec {};
254    let proto = serialize_physical_expr(expr, &codec)?;
255    let mut bytes = Vec::new();
256    proto.encode(&mut bytes).map_err(|e| {
257        DataFusionError::Internal(format!("Failed to encode PhysicalExprNode: {e}"))
258    })?;
259    Ok(bytes)
260}
261
262struct BoundedPhysicalExprEncoder {
263    max_payload_bytes: usize,
264    encoded_bytes: Cell<usize>,
265    /// Set when the encoding aborted on a runtime lookup that has no serializable key
266    /// list.
267    ///
268    /// The abort travels out as an ordinary [`DataFusionError`], which would lose the
269    /// typed dynamic filter error on the way, so the flag is what lets
270    /// `encode_bounded_physical_expr_to_bytes` rebuild
271    /// [`CommonQueryError::DynFilterUnsupported`]. No placeholder is ever encoded in its
272    /// place.
273    unsupported: Cell<bool>,
274    /// Set to the reported frame size when the encoding aborted because a build-key
275    /// membership does not fit `max_payload_bytes`.
276    ///
277    /// This is a size refusal, not a shape one, so
278    /// `encode_bounded_physical_expr_to_bytes` rebuilds
279    /// [`CommonQueryError::DynFilterPayloadTooLarge`] from it instead of reporting the
280    /// predicate as having no wire form.
281    over_budget: Cell<Option<usize>>,
282}
283
284impl BoundedPhysicalExprEncoder {
285    fn new(max_payload_bytes: usize) -> Self {
286        Self {
287            max_payload_bytes,
288            encoded_bytes: Cell::new(0),
289            unsupported: Cell::new(false),
290            over_budget: Cell::new(None),
291        }
292    }
293
294    /// Charges `proto` (including its encoded children) against the payload budget.
295    ///
296    /// The accounting is additive over siblings and exact for the top-level node, so
297    /// no branch can push the payload over budget unnoticed.
298    fn finish(
299        &self,
300        before_children: usize,
301        proto: PhysicalExprNode,
302    ) -> DataFusionResult<PhysicalExprNode> {
303        let encoded_bytes = before_children.saturating_add(proto.encoded_len());
304        self.encoded_bytes.set(encoded_bytes);
305        validate_payload_size(encoded_bytes, self.max_payload_bytes)
306            .map_err(DataFusionError::from)?;
307        Ok(proto)
308    }
309
310    /// Encodes a lookup as its build-key membership, charging every list literal and
311    /// node against the payload budget.
312    ///
313    /// The decision only looks at the lookup itself: if DataFusion can hand out the
314    /// single-column `Utf8` build-key list it is written as `key IN (...)`; otherwise the
315    /// whole payload aborts. A lookup is a real predicate that DataFusion only degrades to
316    /// `true` in its own proto encoder, so this transport must not write any substitute for
317    /// it, and the abort keeps the two reasons apart: no key list at all (unsupported) is
318    /// not the same thing as a key list that exceeds the budget (too large).
319    fn membership_to_proto(
320        &self,
321        lookup: &HashTableLookupExpr,
322        codec: &dyn PhysicalExtensionCodec,
323    ) -> DataFusionResult<PhysicalExprNode> {
324        let membership = match RemoteMembership::from_lookup(lookup, self.max_payload_bytes) {
325            Ok(membership) => membership,
326            // A lookup without a key list has no wire form at all: that is a shape
327            // refusal, not a size one.
328            Err(MembershipRefusal::NoKeyList) => return Err(self.abort_unsupported_lookup()),
329            // The key list exists but does not fit the budget: report it as a size
330            // refusal so it is not counted as "no wire form".
331            Err(MembershipRefusal::OverBudget { build_keys }) => {
332                return Err(self.abort_over_budget_membership(build_keys));
333            }
334        };
335        // The count bound is enforced once more before any literal exists, so a build side
336        // larger than the budget can hold is never materialized. This cannot fail for any
337        // other reason here: the accessor already guaranteed a non-empty, `NULL`-free
338        // `Utf8` list, so a refusal is again a size refusal.
339        let Some(literals) = utf8_list_literals(
340            &membership.values,
341            max_membership_values(self.max_payload_bytes),
342        ) else {
343            return Err(self.abort_over_budget_membership(membership.values.len()));
344        };
345
346        let before_children = self.encoded_bytes.get();
347        let mut list = Vec::with_capacity(literals.len());
348        for literal in literals {
349            list.push(self.physical_expr_to_proto(&literal, codec)?);
350        }
351
352        // The `InList` proto is built by hand instead of going through the generic
353        // serializer: that path needs an `InListExpr`, whose only constructors
354        // (`InListExpr::try_new` / `try_new_from_array`) require an input `Schema` to
355        // resolve the key expression's data type, and this encoder converts a bare
356        // expression without one. The key is known to be `Utf8` (see
357        // `HashTableLookupExpr::build_key_membership`), which is exactly what the list
358        // below writes, so no type check is lost.
359        let proto = PhysicalExprNode {
360            expr_id: None,
361            expr_type: Some(PhysicalExprNodeType::InList(Box::new(PhysicalInListNode {
362                expr: Some(Box::new(
363                    self.physical_expr_to_proto(&membership.key, codec)?,
364                )),
365                list,
366                negated: false,
367            }))),
368        };
369
370        self.finish(before_children, proto)
371    }
372
373    /// Aborts the payload because the wire has no form for `lookup`.
374    ///
375    /// The returned error only carries the abort; [`Self::unsupported`] is what the caller
376    /// reads to rebuild the typed dynamic filter error.
377    fn abort_unsupported_lookup(&self) -> DataFusionError {
378        self.unsupported.set(true);
379        DataFusionError::NotImplemented(
380            "hash table lookup has no UTF-8 build-key membership to encode".to_string(),
381        )
382    }
383
384    /// Aborts the payload because a build-key membership does not fit `max_payload_bytes`.
385    ///
386    /// This is a *size* refusal, never a "no wire form" one, so the caller rebuilds
387    /// [`CommonQueryError::DynFilterPayloadTooLarge`] from [`Self::over_budget`] instead of
388    /// [`CommonQueryError::DynFilterUnsupported`]. `build_keys` is the number of build keys
389    /// the refused list would have written; every one of them costs at least
390    /// [`MIN_ENCODED_LITERAL_BYTES`], so that product is a real lower bound of the frame.
391    fn abort_over_budget_membership(&self, build_keys: usize) -> DataFusionError {
392        self.over_budget.set(Some(refused_payload_size(
393            build_keys.saturating_mul(MIN_ENCODED_LITERAL_BYTES),
394            self.max_payload_bytes,
395        )));
396        DataFusionError::NotImplemented(
397            "hash table lookup build-key membership exceeds the payload budget".to_string(),
398        )
399    }
400}
401
402impl PhysicalProtoConverterExtension for BoundedPhysicalExprEncoder {
403    fn proto_to_execution_plan(
404        &self,
405        proto: &PhysicalPlanNode,
406        ctx: &PhysicalPlanDecodeContext<'_>,
407    ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
408        DefaultPhysicalProtoConverter {}.proto_to_execution_plan(proto, ctx)
409    }
410
411    fn execution_plan_to_proto(
412        &self,
413        plan: &Arc<dyn ExecutionPlan>,
414        codec: &dyn PhysicalExtensionCodec,
415    ) -> DataFusionResult<PhysicalPlanNode> {
416        DefaultPhysicalProtoConverter {}.execution_plan_to_proto(plan, codec)
417    }
418
419    fn proto_to_physical_expr(
420        &self,
421        proto: &PhysicalExprNode,
422        input_schema: &datafusion::arrow::datatypes::Schema,
423        ctx: &PhysicalPlanDecodeContext<'_>,
424    ) -> DataFusionResult<Arc<dyn PhysicalExpr>> {
425        DefaultPhysicalProtoConverter {}.proto_to_physical_expr(proto, input_schema, ctx)
426    }
427
428    fn physical_expr_to_proto(
429        &self,
430        expr: &Arc<dyn PhysicalExpr>,
431        codec: &dyn PhysicalExtensionCodec,
432    ) -> DataFusionResult<PhysicalExprNode> {
433        // A real `HashTableLookupExpr` has no wire form: DataFusion's own
434        // `try_to_proto` degrades it to `true`. Intercept it so the build-key list can
435        // be written with the existing `InList` node instead. The decision is made by
436        // the lookup alone; every other node, including `IS NULL`, `NOT`, `CASE`,
437        // `AND` and `OR`, is serialized exactly as it is.
438        if let Some(lookup) = expr.downcast_ref::<HashTableLookupExpr>() {
439            return self.membership_to_proto(lookup, codec);
440        }
441
442        let before_children = self.encoded_bytes.get();
443        let proto = serialize_physical_expr_with_converter(expr, codec, self)?;
444        // Replace the children's contribution with the whole subtree, including protobuf framing.
445        // Checking each child stops large IN lists before materializing all their Arrow IPC literals.
446        self.finish(before_children, proto)
447    }
448}
449
450/// Encodes `expr` for the remote wire under `max_payload_bytes`.
451///
452/// Returns the typed [`CommonQueryError::DynFilterUnsupported`] when the predicate holds a
453/// lookup whose key list cannot be serialized, and
454/// [`CommonQueryError::DynFilterPayloadTooLarge`] when the frame (or a build-key
455/// membership) does not fit the budget. The two refusals stay distinct: an over-budget
456/// membership is a size refusal and is never reported as a predicate without a wire form.
457/// The caller answers both with [`retain_membership_free_conjuncts`]; neither is ever
458/// replaced with `true`.
459fn encode_bounded_physical_expr_to_bytes(
460    expr: &Arc<dyn PhysicalExpr>,
461    max_payload_bytes: usize,
462) -> Result<Vec<u8>, CommonQueryError> {
463    let codec = DefaultPhysicalExtensionCodec {};
464    let encoder = BoundedPhysicalExprEncoder::new(max_payload_bytes);
465    let proto = encoder.physical_expr_to_proto(expr, &codec);
466    // A build-key membership that exceeds the budget is a size refusal even though the
467    // frame that would have held it is never materialized.
468    if let Some(payload_size_bytes) = encoder.over_budget.get() {
469        return Err(DynFilterPayloadTooLargeSnafu {
470            payload_size_bytes,
471            max_payload_bytes,
472        }
473        .build());
474    }
475    let unsupported = encoder.unsupported.get();
476    // The encoder stops at the node that went over budget, so this reports the size
477    // error unwrapped instead of the wrapped DataFusion error.
478    validate_payload_size(encoder.encoded_bytes.get(), max_payload_bytes)?;
479    if unsupported {
480        return Err(DynFilterUnsupportedSnafu {
481            reason: "the predicate holds a hash table lookup without a UTF-8 build-key \
482                     membership",
483        }
484        .build());
485    }
486    Ok(proto.map_err(CommonQueryError::from)?.encode_to_vec())
487}
488
489/// Which top-level conjuncts [`retain_membership_free_conjuncts`] has to drop.
490#[derive(Clone, Copy, Debug)]
491enum ConjunctRetention {
492    /// The payload holds a [`HashTableLookupExpr`] without a wire form, so such a lookup
493    /// is the only unshippable node: a static [`InListExpr`] is representable and stays.
494    UnrepresentableLookup,
495    /// The payload exceeds its budget. A static [`InListExpr`] is the node most likely to
496    /// be the oversized one, so it is dropped with the lookups.
497    OverBudget,
498}
499
500/// Keeps the top-level conjuncts of a predicate that cannot be shipped as it stands.
501///
502/// Dropping an `AND` term can only widen a predicate, so the retained payload still never
503/// drops a row the producer would keep. `retention` decides which conjuncts have to go. It
504/// only widens as far as it has to: when the narrow retention leaves conjuncts that still do
505/// not fit `max_payload_bytes`, the [`InListExpr`]-bearing ones are dropped as well, because
506/// a static `IN` list is the node most likely to be the oversized one.
507///
508/// The refusal keeps the two reasons apart instead of folding them into "no wire form":
509/// nothing retained under [`ConjunctRetention::UnrepresentableLookup`] means the wire
510/// really has no form for the predicate
511/// ([`CommonQueryError::DynFilterUnsupported`]), while nothing retained under
512/// [`ConjunctRetention::OverBudget`] (or a retained payload that still does not fit) is a
513/// size refusal ([`CommonQueryError::DynFilterPayloadTooLarge`]). Transport never
514/// substitutes `true` for either.
515fn retain_membership_free_conjuncts(
516    expr: &Arc<dyn PhysicalExpr>,
517    max_payload_bytes: usize,
518    retention: ConjunctRetention,
519) -> DataFusionResult<DynFilterPayload> {
520    match encode_retained_conjuncts_to_bytes(expr, max_payload_bytes, retention) {
521        Ok(Some(bytes)) => Ok(DynFilterPayload::Datafusion(bytes)),
522        // Nothing could be retained. Which refusal that is depends on *why* the conjuncts
523        // had to go, and the two must not be mixed up: an over-budget predicate is
524        // representable, it only does not fit.
525        Ok(None) => Err(match retention {
526            ConjunctRetention::UnrepresentableLookup => DynFilterUnsupportedSnafu {
527                reason: "every top-level conjunct of the predicate holds a hash table \
528                         lookup without a UTF-8 build-key membership, so the wire has no \
529                         form for it",
530            }
531            .build()
532            .into(),
533            ConjunctRetention::OverBudget => DynFilterPayloadTooLargeSnafu {
534                payload_size_bytes: refused_payload_size(0, max_payload_bytes),
535                max_payload_bytes,
536            }
537            .build()
538            .into(),
539        }),
540        Err(CommonQueryError::DynFilterPayloadTooLarge { .. })
541            if matches!(retention, ConjunctRetention::UnrepresentableLookup) =>
542        {
543            retain_membership_free_conjuncts(expr, max_payload_bytes, ConjunctRetention::OverBudget)
544        }
545        Err(error) => Err(error.into()),
546    }
547}
548
549/// Encodes the top-level conjuncts of `expr` that `retention` allows to keep.
550///
551/// [`split_conjunction`] hands out the top-level `AND` terms of the original
552/// expression; a term is dropped as a whole when its subtree holds a node the retention
553/// cannot ship (see [`ConjunctRetention`]). Membership nested inside `NOT`, `CASE` or `OR`
554/// therefore drops that whole conjunct instead of being rewritten in place, so the payload
555/// only ever loses top-level `AND` terms, which can only widen a predicate.
556///
557/// The retained terms are encoded again under the same `max_payload_bytes`, so a caller
558/// supplied budget still bounds the frame. Returns `Ok(None)` when no conjunct can be
559/// retained; the caller decides which typed refusal that is from `retention`, because an
560/// empty retention caused by an unrepresentable lookup is not the same thing as an empty
561/// retention caused by the budget.
562fn encode_retained_conjuncts_to_bytes(
563    expr: &Arc<dyn PhysicalExpr>,
564    max_payload_bytes: usize,
565    retention: ConjunctRetention,
566) -> Result<Option<Vec<u8>>, CommonQueryError> {
567    let mut retained = Vec::new();
568    for conjunct in split_conjunction(expr) {
569        if !retention.drops_conjunct(conjunct)? {
570            retained.push(Arc::clone(conjunct));
571        }
572    }
573    if retained.is_empty() {
574        return Ok(None);
575    }
576    encode_bounded_physical_expr_to_bytes(&conjunction(retained), max_payload_bytes).map(Some)
577}
578
579impl ConjunctRetention {
580    /// Whether the whole subtree of `expr` holds a node this retention cannot ship.
581    ///
582    /// This is a "whole conjunct" test on purpose: a conjunct that reaches such a node
583    /// anywhere is dropped by the retention instead of being rewritten around it.
584    fn drops_conjunct(self, expr: &Arc<dyn PhysicalExpr>) -> DataFusionResult<bool> {
585        let mut found = false;
586        expr.apply(|node| {
587            let unshippable = match self {
588                Self::UnrepresentableLookup => node.is::<HashTableLookupExpr>(),
589                Self::OverBudget => node.is::<HashTableLookupExpr>() || node.is::<InListExpr>(),
590            };
591            if unshippable {
592                found = true;
593                Ok(TreeNodeRecursion::Stop)
594            } else {
595                Ok(TreeNodeRecursion::Continue)
596            }
597        })?;
598        Ok(found)
599    }
600}
601
602/// Build-key list of one hash lookup, written as `probe_key IN (value, ...)`.
603///
604/// The membership reuses the existing `PhysicalInListNode`, so no new wire variant
605/// and no in-payload version tag are needed, and it is charged against the normal
606/// payload budget. Only the build-key list itself is consulted here; the wire form
607/// never depends on where the lookup sits in the predicate tree.
608struct RemoteMembership {
609    /// Probe-side key expression, reused as the `InList` operand.
610    key: Arc<dyn PhysicalExpr>,
611    /// Published build key values, tied to the lookup's build lease.
612    values: ArrayRef,
613}
614
615impl RemoteMembership {
616    /// Key-list membership of `lookup`, or the reason it cannot be written.
617    ///
618    /// The count bound handed to DataFusion is derived from the byte budget (see
619    /// [`max_membership_values`]) instead of being a policy constant, and the byte bound
620    /// is the raw payload budget itself, which every build-key buffer has to fit before it
621    /// can be written as literals. Both are conservative early guards, not the exact
622    /// serialized frame length: the encoder still charges every literal against the budget
623    /// node by node.
624    ///
625    /// The accessor keeps the value-level limitations — it returns `None` for lookups
626    /// without a build lease (e.g. a test-only lookup), composite keys, non-`Utf8` keys
627    /// (integer/float/decimal/dictionary/unknown), and `NULL`-containing or empty build
628    /// keys — and [`utf8_list_literals`] re-checks everything it materializes. Those are
629    /// accessor and materialization limitations, not encoder policy.
630    ///
631    /// The accessor folds its shape and size checks into one `None`, so a key list that
632    /// exists but exceeds the bounds is told apart by asking again with the bounds lifted:
633    /// only a list that exists at all can be refused for its size, and a size refusal must
634    /// not be reported as a predicate without a wire form (it is
635    /// [`CommonQueryError::DynFilterPayloadTooLarge`], not
636    /// [`CommonQueryError::DynFilterUnsupported`]).
637    fn from_lookup(
638        lookup: &HashTableLookupExpr,
639        max_payload_bytes: usize,
640    ) -> Result<Self, MembershipRefusal> {
641        match lookup
642            .build_key_membership(max_membership_values(max_payload_bytes), max_payload_bytes)
643        {
644            Some(membership) => Ok(Self {
645                key: Arc::clone(membership.key()),
646                values: Arc::clone(membership.values()),
647            }),
648            None => Err(match lookup.build_key_membership(usize::MAX, usize::MAX) {
649                Some(unbounded) => MembershipRefusal::OverBudget {
650                    build_keys: unbounded.values().len(),
651                },
652                None => MembershipRefusal::NoKeyList,
653            }),
654        }
655    }
656}
657
658/// Why a lookup's build-key membership cannot be written as `probe_key IN (...)`.
659///
660/// The two reasons are answered differently: [`Self::NoKeyList`] means the wire has no
661/// form for the node, while [`Self::OverBudget`] means the membership is real but too
662/// large for the payload budget, which the encoder reports as a size refusal.
663#[derive(Clone, Copy, Debug, PartialEq, Eq)]
664enum MembershipRefusal {
665    /// The lookup has no single-column `Utf8` build-key list at all: no build lease,
666    /// composite key, unsupported key type, or an empty / `NULL`-containing build side.
667    NoKeyList,
668    /// The build-key list exists but exceeds the caller's bounds. `build_keys` is how many
669    /// literals it would have written, measured from the unbounded accessor.
670    OverBudget { build_keys: usize },
671}
672
673/// Materializes the `IN` list literals for a build-key membership.
674///
675/// This is the authoritative value check: the list is only built for a non-empty,
676/// `NULL`-free, non-dictionary `Utf8` array of at most `max_values` entries. `max_values`
677/// is checked *before* a [`Literal`] is created for every build key, so an over-large
678/// build side is refused instead of being materialized and then measured. The caller has
679/// already been through [`RemoteMembership::from_lookup`], so a refusal here can only be
680/// the count bound and is reported as a size refusal, not as a missing wire form.
681fn utf8_list_literals(values: &ArrayRef, max_values: usize) -> Option<Vec<Arc<dyn PhysicalExpr>>> {
682    let values = values.as_any().downcast_ref::<StringArray>()?;
683    if values.is_empty() || values.null_count() != 0 || values.len() > max_values {
684        return None;
685    }
686    values
687        .iter()
688        .map(|value| {
689            value.map(|value| {
690                Arc::new(Literal::new(ScalarValue::Utf8(Some(value.to_owned()))))
691                    as Arc<dyn PhysicalExpr>
692            })
693        })
694        .collect()
695}
696
697pub(crate) fn decode_physical_expr_from_bytes(
698    bytes: &[u8],
699    task_ctx: &TaskContext,
700    input_schema: &datafusion::arrow::datatypes::Schema,
701    max_payload_bytes: usize,
702) -> DataFusionResult<Arc<dyn PhysicalExpr>> {
703    validate_payload_size(bytes.len(), max_payload_bytes).map_err(DataFusionError::from)?;
704    let codec = DefaultPhysicalExtensionCodec {};
705    let proto = PhysicalExprNode::decode(bytes).map_err(|e| {
706        DataFusionError::Internal(format!("Failed to decode PhysicalExprNode: {e}"))
707    })?;
708
709    let expr = parse_physical_expr(&proto, task_ctx, input_schema, &codec)?;
710    validate_supported_payload_expr(&expr)?;
711    validate_decoded_payload_expr(&expr, input_schema)?;
712    Ok(expr)
713}
714
715fn validate_payload_size(
716    payload_size_bytes: usize,
717    max_payload_bytes: usize,
718) -> Result<(), CommonQueryError> {
719    ensure!(
720        payload_size_bytes <= max_payload_bytes,
721        DynFilterPayloadTooLargeSnafu {
722            payload_size_bytes,
723            max_payload_bytes,
724        }
725    );
726
727    Ok(())
728}
729
730/// Asserts the predicate is reported as having no wire form instead of becoming `true`.
731#[cfg(test)]
732fn assert_unsupported(error: DataFusionError) {
733    assert_typed_dyn_filter_error(error, "DynFilterUnsupported", |error| {
734        matches!(error, CommonQueryError::DynFilterUnsupported { .. })
735    });
736}
737
738/// Asserts the retained payload still exceeds the caller-supplied budget.
739#[cfg(test)]
740fn assert_too_large(error: DataFusionError) {
741    assert_typed_dyn_filter_error(error, "DynFilterPayloadTooLarge", |error| {
742        matches!(error, CommonQueryError::DynFilterPayloadTooLarge { .. })
743    });
744}
745
746#[cfg(test)]
747fn assert_typed_dyn_filter_error(
748    error: DataFusionError,
749    expected: &str,
750    matches_error: impl Fn(&CommonQueryError) -> bool,
751) {
752    let DataFusionError::External(error) = error else {
753        panic!("expected external common query error, got: {error:?}");
754    };
755    let typed = error
756        .downcast_ref::<CommonQueryError>()
757        .unwrap_or_else(|| panic!("expected external {expected}, got: {error:?}"));
758    assert!(matches_error(typed), "expected {expected}, got: {error:?}");
759}
760
761/// Whether `error` reports a dynamic filter predicate the wire cannot represent.
762///
763/// Transport never rewrites a producer predicate to `true`, so a producer answers this
764/// error by not shipping the producer predicate and keeping the query running. Callers
765/// that keep a long-lived region-side predicate treat it as an invalidation trigger: the
766/// stale predicate is replaced by an explicit `true` reset (see
767/// `remote_dyn_filter_registry`), so a producer that later widens its filter cannot be
768/// pruned away by it.
769pub fn is_dyn_filter_unsupported(error: &DataFusionError) -> bool {
770    matches!(
771        error,
772        DataFusionError::External(source)
773            if source
774                .downcast_ref::<CommonQueryError>()
775                .is_some_and(CommonQueryError::is_dyn_filter_unsupported)
776    )
777}
778
779/// Whether `error` reports a dynamic filter payload that exceeded `max_payload_bytes`.
780///
781/// This is the other refusal [`DynFilterPayload::from_datafusion_expr`] reports, next to
782/// [`is_dyn_filter_unsupported`]: the predicate exists and is representable, but even the
783/// retained top-level conjuncts do not fit the budget. It is *not* a "no wire form" case
784/// and must not be reported as one. Like the unsupported case it is answered by not
785/// shipping the producer predicate (the query keeps running) and never by narrowing or
786/// rewriting it; a caller that keeps a long-lived region predicate publishes the explicit
787/// `true` reset instead, so a stale, narrower predicate cannot prune rows the producer
788/// still keeps.
789pub fn is_dyn_filter_payload_too_large(error: &DataFusionError) -> bool {
790    matches!(
791        error,
792        DataFusionError::External(source)
793            if source
794                .downcast_ref::<CommonQueryError>()
795                .is_some_and(|error| matches!(
796                    error,
797                    CommonQueryError::DynFilterPayloadTooLarge { .. }
798                ))
799    )
800}
801
802fn validate_supported_payload_expr(expr: &Arc<dyn PhysicalExpr>) -> DataFusionResult<()> {
803    expr.apply(|node| {
804        if node.is::<HashTableLookupExpr>() {
805            return Err(DataFusionError::Plan(
806                "HashTableLookupExpr cannot be encoded into DynFilterPayload::Datafusion"
807                    .to_string(),
808            ));
809        }
810
811        Ok(TreeNodeRecursion::Continue)
812    })?;
813
814    Ok(())
815}
816
817/// Validates decoded dynamic filter physical expressions against the receiver-side schema.
818///
819/// Rejects out-of-bounds column indexes and, as a defensive check, rejects columns whose
820/// name disagrees with the corresponding schema field. DataFusion physical `Column` is
821/// index-authoritative, so a name mismatch usually indicates a coordinator/receiver
822/// schema inconsistency that should be surfaced loudly.
823fn validate_decoded_payload_expr(
824    expr: &Arc<dyn PhysicalExpr>,
825    input_schema: &datafusion::arrow::datatypes::Schema,
826) -> DataFusionResult<()> {
827    expr.apply(|node| {
828        if let Some(column) = node.downcast_ref::<Column>() {
829            let Some(field) = input_schema.fields().get(column.index()) else {
830                return Err(DataFusionError::Plan(format!(
831                    "Decoded Column '{}' references out-of-bounds index {} for input schema of size {}",
832                    column.name(),
833                    column.index(),
834                    input_schema.fields().len()
835                )));
836            };
837
838            if field.name() != column.name() {
839                return Err(DataFusionError::Plan(format!(
840                    "Decoded Column name/index mismatch: payload has '{}' at index {}, but schema field is '{}'",
841                    column.name(),
842                    column.index(),
843                    field.name()
844                )));
845            }
846        }
847
848        Ok(TreeNodeRecursion::Continue)
849    })?;
850
851    Ok(())
852}
853
854/// A remote dynamic filter update sent from a query coordinator to region servers.
855///
856/// `generation` is monotonic within a `query_id`/`filter_id` pair and matches the
857/// gRPC field name used by `RemoteDynFilterUpdate`. Receivers use it to ignore
858/// stale updates while `is_complete` marks the final payload for the filter.
859#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
860pub struct DynFilterUpdate {
861    /// Protocol version used by this update payload.
862    pub protocol_version: u32,
863    /// Internal query identifier that owns this dynamic filter lifecycle.
864    pub query_id: String,
865    /// Identifier of the dynamic filter within the query.
866    pub filter_id: String,
867    /// Monotonic update generation for this filter.
868    pub generation: u64,
869    /// Whether this update completes the dynamic filter stream.
870    pub is_complete: bool,
871    /// Serialized predicate payload carried by this update.
872    pub payload: DynFilterPayload,
873}
874
875impl DynFilterUpdate {
876    /// Creates a dynamic filter update with the current protocol version.
877    pub fn new(
878        query_id: String,
879        filter_id: String,
880        generation: u64,
881        is_complete: bool,
882        payload: DynFilterPayload,
883    ) -> Self {
884        Self {
885            protocol_version: DYN_FILTER_PROTOCOL_VERSION,
886            query_id,
887            filter_id,
888            generation,
889            is_complete,
890            payload,
891        }
892    }
893}
894
895/// The query request to be handled by the RegionServer (Datanode).
896#[derive(Clone, Debug)]
897pub struct QueryRequest {
898    /// The header of this request. Often to store some context of the query. None means all to defaults.
899    pub header: Option<RegionRequestHeader>,
900
901    /// The id of the region to be queried.
902    pub region_id: RegionId,
903
904    /// The form of the query: a logical plan.
905    pub plan: LogicalPlan,
906}
907
908/// First node of type `T` anywhere in `expr`.
909#[cfg(test)]
910fn find_expr<T: PhysicalExpr>(expr: &Arc<dyn PhysicalExpr>) -> Option<Arc<dyn PhysicalExpr>> {
911    let mut found = None;
912    expr.apply(|node| {
913        if node.is::<T>() {
914            found = Some(Arc::clone(node));
915            Ok(TreeNodeRecursion::Stop)
916        } else {
917            Ok(TreeNodeRecursion::Continue)
918        }
919    })
920    .unwrap();
921    found
922}
923
924/// Whether `expr` holds a node of type `T` anywhere.
925#[cfg(test)]
926fn has_expr<T: PhysicalExpr>(expr: &Arc<dyn PhysicalExpr>) -> bool {
927    find_expr::<T>(expr).is_some()
928}
929
930/// Encodes `expr` at `max_payload_bytes` and decodes it against `schema`. This is the
931/// round trip a receiver performs, so the tests never assert on the encoder alone.
932#[cfg(test)]
933fn decode(
934    expr: &Arc<dyn PhysicalExpr>,
935    schema: &Arc<datafusion::arrow::datatypes::Schema>,
936    max_payload_bytes: usize,
937) -> Arc<dyn PhysicalExpr> {
938    DynFilterPayload::from_datafusion_expr(expr, max_payload_bytes)
939        .unwrap()
940        .decode_datafusion_expr(&TaskContext::default(), schema, max_payload_bytes)
941        .unwrap()
942}
943
944#[cfg(test)]
945mod tests {
946    use std::sync::Arc;
947
948    use base64::Engine;
949    use base64::prelude::BASE64_STANDARD;
950    use datafusion::arrow::array::{ArrayRef, Int32Array, StringArray};
951    use datafusion::arrow::datatypes::{DataType, Field, Schema};
952    use datafusion::physical_expr::expressions::{BinaryExpr, Column, InListExpr, NotExpr, lit};
953    use datafusion::physical_plan::expressions::col;
954    use datafusion::physical_plan::joins::join_hash_map::JoinHashMapU32;
955    use datafusion::physical_plan::joins::{HashTableLookupExpr, Map, SeededRandomState};
956    use datafusion_expr::Operator;
957
958    use super::*;
959
960    #[test]
961    fn dyn_filter_update_sets_protocol_version() {
962        let update = DynFilterUpdate::new(
963            "query-1".to_string(),
964            "filter-1".to_string(),
965            3,
966            false,
967            DynFilterPayload::Datafusion(vec![1, 2, 3]),
968        );
969
970        assert_eq!(update.protocol_version, DYN_FILTER_PROTOCOL_VERSION);
971        assert!(!update.is_complete);
972        assert!(
973            matches!(update.payload, DynFilterPayload::Datafusion(ref bytes) if bytes == &vec![1, 2, 3])
974        );
975    }
976
977    #[test]
978    fn dyn_filter_update_json_round_trip_preserves_payload_shape() {
979        let update = DynFilterUpdate::new(
980            "query-2".to_string(),
981            "filter-9".to_string(),
982            9,
983            true,
984            DynFilterPayload::Datafusion(vec![9, 8, 7]),
985        );
986
987        let json = serde_json::to_string(&update).unwrap();
988        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
989        let decoded: DynFilterUpdate = serde_json::from_str(&json).unwrap();
990
991        assert_eq!(value["generation"], serde_json::json!(9));
992        assert!(value.get("epoch").is_none());
993        assert_eq!(
994            value["payload"],
995            serde_json::json!({ "kind": "datafusion", "payload": BASE64_STANDARD.encode([9, 8, 7]) })
996        );
997        assert_eq!(decoded, update);
998        assert!(decoded.is_complete);
999        assert!(
1000            matches!(decoded.payload, DynFilterPayload::Datafusion(ref bytes) if bytes == &vec![9, 8, 7])
1001        );
1002    }
1003
1004    #[test]
1005    fn dyn_filter_payload_json_uses_base64_for_empty_and_padded_payloads() {
1006        let empty = serde_json::to_value(DynFilterPayload::Datafusion(vec![])).unwrap();
1007        let one = serde_json::to_value(DynFilterPayload::Datafusion(vec![1])).unwrap();
1008        let two = serde_json::to_value(DynFilterPayload::Datafusion(vec![1, 2])).unwrap();
1009
1010        assert_eq!(
1011            empty,
1012            serde_json::json!({"kind": "datafusion", "payload": ""})
1013        );
1014        assert_eq!(
1015            one,
1016            serde_json::json!({"kind": "datafusion", "payload": BASE64_STANDARD.encode([1])})
1017        );
1018        assert_eq!(
1019            two,
1020            serde_json::json!({"kind": "datafusion", "payload": BASE64_STANDARD.encode([1, 2])})
1021        );
1022    }
1023
1024    #[test]
1025    fn dyn_filter_payload_json_rejects_invalid_base64() {
1026        let err = serde_json::from_value::<DynFilterPayload>(serde_json::json!({
1027            "kind": "datafusion",
1028            "payload": "not base64!",
1029        }))
1030        .unwrap_err();
1031
1032        assert!(
1033            err.to_string()
1034                .contains("invalid base64 dynamic filter payload")
1035        );
1036    }
1037
1038    #[test]
1039    fn dyn_filter_payload_round_trips_physical_column_expr() {
1040        let schema = Schema::new(vec![Field::new("host", DataType::Utf8, false)]);
1041        let expr: Arc<dyn PhysicalExpr> =
1042            Arc::new(Column::new_with_schema("host", &schema).unwrap());
1043
1044        let payload = DynFilterPayload::from_datafusion_expr(&expr, 1024).unwrap();
1045        let decoded = payload
1046            .decode_datafusion_expr(&TaskContext::default(), &schema, 1024)
1047            .unwrap();
1048
1049        let original = expr.downcast_ref::<Column>().unwrap();
1050        let decoded = decoded.downcast_ref::<Column>().unwrap();
1051
1052        assert_eq!(decoded.name(), original.name());
1053        assert_eq!(decoded.index(), original.index());
1054    }
1055
1056    #[test]
1057    fn dyn_filter_payload_decode_rejects_invalid_bytes() {
1058        let schema = Schema::new(vec![Field::new("host", DataType::Utf8, false)]);
1059        let payload = DynFilterPayload::Datafusion(vec![1, 2, 3]);
1060
1061        let err = payload
1062            .decode_datafusion_expr(&TaskContext::default(), &schema, 1024)
1063            .unwrap_err();
1064
1065        assert!(matches!(err, DataFusionError::Internal(_)));
1066    }
1067
1068    #[test]
1069    fn dyn_filter_payload_decode_rejects_column_name_index_mismatch() {
1070        let schema = Schema::new(vec![Field::new("host", DataType::Utf8, false)]);
1071        let expr: Arc<dyn PhysicalExpr> = Arc::new(Column::new("service", 0));
1072
1073        let payload = DynFilterPayload::from_datafusion_expr(&expr, 1024).unwrap();
1074        let err = payload
1075            .decode_datafusion_expr(&TaskContext::default(), &schema, 1024)
1076            .unwrap_err();
1077
1078        let msg = err.to_string();
1079        assert!(
1080            msg.contains("name/index mismatch"),
1081            "expected name/index mismatch error, got: {msg}"
1082        );
1083        assert!(msg.contains("service"));
1084        assert!(msg.contains("host"));
1085    }
1086
1087    #[test]
1088    fn dyn_filter_payload_decode_rejects_out_of_bounds_column_index() {
1089        let schema = Schema::new(vec![Field::new("host", DataType::Utf8, false)]);
1090        let expr: Arc<dyn PhysicalExpr> = Arc::new(Column::new("host", 1));
1091
1092        let payload = DynFilterPayload::from_datafusion_expr(&expr, 1024).unwrap();
1093        let err = payload
1094            .decode_datafusion_expr(&TaskContext::default(), &schema, 1024)
1095            .unwrap_err();
1096
1097        assert!(matches!(err, DataFusionError::Plan(_)));
1098    }
1099
1100    /// A hand-built lookup has no build lease, hence no key list: the wire cannot
1101    /// represent it, so the encoder aborts unless a membership-free conjunct can be kept.
1102    fn unrepresentable_lookup(key: &Arc<dyn PhysicalExpr>) -> Arc<dyn PhysicalExpr> {
1103        Arc::new(HashTableLookupExpr::new(
1104            vec![Arc::clone(key)],
1105            SeededRandomState::with_seed(0),
1106            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(0)))),
1107            "hash_lookup".to_string(),
1108            None,
1109        )) as Arc<dyn PhysicalExpr>
1110    }
1111
1112    #[test]
1113    fn dyn_filter_payload_unconvertible_lookup_keeps_integer_bounds() {
1114        // `bounds AND lookup` where the lookup has no key list: only the
1115        // membership-bearing conjunct is dropped, so the integer bounds still travel as a
1116        // regular payload instead of an always-true filter or an error.
1117        let schema = Arc::new(Schema::new(vec![Field::new(
1118            "device_id",
1119            DataType::Int32,
1120            false,
1121        )]));
1122        let device_id = col("device_id", &schema).unwrap();
1123        let lower_bound = Arc::new(BinaryExpr::new(
1124            Arc::clone(&device_id),
1125            Operator::GtEq,
1126            lit(10i32),
1127        )) as Arc<dyn PhysicalExpr>;
1128        let upper_bound = Arc::new(BinaryExpr::new(
1129            Arc::clone(&device_id),
1130            Operator::LtEq,
1131            lit(20i32),
1132        )) as Arc<dyn PhysicalExpr>;
1133        let bounds = Arc::new(BinaryExpr::new(lower_bound, Operator::And, upper_bound))
1134            as Arc<dyn PhysicalExpr>;
1135        let expr = Arc::new(BinaryExpr::new(
1136            Arc::clone(&bounds),
1137            Operator::And,
1138            unrepresentable_lookup(&device_id),
1139        )) as Arc<dyn PhysicalExpr>;
1140
1141        // The predicate itself has no wire form: the lookup has no key list.
1142        assert!(matches!(
1143            encode_bounded_physical_expr_to_bytes(&expr, 1024),
1144            Err(CommonQueryError::DynFilterUnsupported { .. })
1145        ));
1146
1147        // Keeping the membership-free top-level conjuncts turns it into a normal payload.
1148        let decoded = decode(&expr, &schema, 1024);
1149        let display = decoded.to_string();
1150        assert!(
1151            display.contains(">= 10"),
1152            "lower bound must survive: {display}"
1153        );
1154        assert!(
1155            display.contains("<= 20"),
1156            "upper bound must survive: {display}"
1157        );
1158        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{display}");
1159        assert!(!has_expr::<InListExpr>(&decoded), "{display}");
1160        // Both bounds are copied verbatim: no `AND` term was rewritten in place.
1161        assert_eq!(
1162            encode_physical_expr_to_bytes(&decoded).unwrap(),
1163            encode_physical_expr_to_bytes(&bounds).unwrap()
1164        );
1165    }
1166
1167    #[test]
1168    fn unrepresentable_lookup_drops_only_the_lookup_conjunct() {
1169        // One unsupported lookup (no key list) between the bounds and a static `IN` list
1170        // that is itself perfectly representable: only the lookup-bearing conjunct is
1171        // dropped, so the list survives as a whole and the payload stays as narrow as the
1172        // wire allows.
1173        let schema = Arc::new(Schema::new(vec![Field::new(
1174            "device_id",
1175            DataType::Int32,
1176            false,
1177        )]));
1178        let device_id = col("device_id", &schema).unwrap();
1179        let lower_bound = Arc::new(BinaryExpr::new(
1180            Arc::clone(&device_id),
1181            Operator::GtEq,
1182            lit(10i32),
1183        )) as Arc<dyn PhysicalExpr>;
1184        let upper_bound = Arc::new(BinaryExpr::new(
1185            Arc::clone(&device_id),
1186            Operator::LtEq,
1187            lit(20i32),
1188        )) as Arc<dyn PhysicalExpr>;
1189        let bounds = Arc::new(BinaryExpr::new(
1190            Arc::clone(&lower_bound),
1191            Operator::And,
1192            Arc::clone(&upper_bound),
1193        )) as Arc<dyn PhysicalExpr>;
1194        let in_list = Arc::new(
1195            InListExpr::try_new(
1196                Arc::clone(&device_id),
1197                (10..20).map(lit).collect(),
1198                false,
1199                &schema,
1200            )
1201            .unwrap(),
1202        ) as Arc<dyn PhysicalExpr>;
1203        let expr = Arc::new(BinaryExpr::new(
1204            Arc::new(BinaryExpr::new(
1205                Arc::clone(&bounds),
1206                Operator::And,
1207                unrepresentable_lookup(&device_id),
1208            )) as Arc<dyn PhysicalExpr>,
1209            Operator::And,
1210            Arc::clone(&in_list),
1211        )) as Arc<dyn PhysicalExpr>;
1212
1213        let decoded = decode(&expr, &schema, REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES);
1214        let display = decoded.to_string();
1215        assert!(display.contains(">= 10"), "{display}");
1216        assert!(display.contains("<= 20"), "{display}");
1217        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{display}");
1218        // The static `IN` list is representable, so it is kept verbatim.
1219        assert!(has_expr::<InListExpr>(&decoded), "{display}");
1220        assert_eq!(
1221            split_conjunction(&decoded).len(),
1222            3,
1223            "the two bounds and the static `IN` list survive: {display}"
1224        );
1225        // The retained conjuncts are the original terms verbatim: the list was not
1226        // rewritten, truncated or moved.
1227        let retained_in_list = find_expr::<InListExpr>(&decoded).expect("static IN survives");
1228        let retained_in_list = retained_in_list.downcast_ref::<InListExpr>().unwrap();
1229        assert!(!retained_in_list.negated());
1230        assert_eq!(retained_in_list.list().len(), 10);
1231        let retained = conjunction(vec![
1232            Arc::clone(&lower_bound),
1233            Arc::clone(&upper_bound),
1234            in_list,
1235        ]);
1236        assert_eq!(
1237            encode_physical_expr_to_bytes(&decoded).unwrap(),
1238            encode_physical_expr_to_bytes(&retained).unwrap()
1239        );
1240    }
1241
1242    #[test]
1243    fn over_budget_membership_drops_the_oversized_in_list_too() {
1244        // The same shape under a budget that only fits the bounds: keeping the
1245        // representative-but-large `IN` list is not enough, so the retention widens once
1246        // more and drops the `InListExpr`-bearing conjuncts as well.
1247        let schema = Arc::new(Schema::new(vec![Field::new(
1248            "device_id",
1249            DataType::Int32,
1250            false,
1251        )]));
1252        let device_id = col("device_id", &schema).unwrap();
1253        let lower_bound = Arc::new(BinaryExpr::new(
1254            Arc::clone(&device_id),
1255            Operator::GtEq,
1256            lit(10i32),
1257        )) as Arc<dyn PhysicalExpr>;
1258        let upper_bound = Arc::new(BinaryExpr::new(
1259            Arc::clone(&device_id),
1260            Operator::LtEq,
1261            lit(20i32),
1262        )) as Arc<dyn PhysicalExpr>;
1263        let bounds = Arc::new(BinaryExpr::new(
1264            Arc::clone(&lower_bound),
1265            Operator::And,
1266            Arc::clone(&upper_bound),
1267        )) as Arc<dyn PhysicalExpr>;
1268        let in_list = Arc::new(
1269            InListExpr::try_new(
1270                Arc::clone(&device_id),
1271                (10..20).map(lit).collect(),
1272                false,
1273                &schema,
1274            )
1275            .unwrap(),
1276        ) as Arc<dyn PhysicalExpr>;
1277        let expr = Arc::new(BinaryExpr::new(
1278            Arc::new(BinaryExpr::new(
1279                Arc::clone(&bounds),
1280                Operator::And,
1281                unrepresentable_lookup(&device_id),
1282            )) as Arc<dyn PhysicalExpr>,
1283            Operator::And,
1284            in_list,
1285        )) as Arc<dyn PhysicalExpr>;
1286
1287        let budget = encode_physical_expr_to_bytes(&bounds).unwrap().len();
1288        assert!(encode_bounded_physical_expr_to_bytes(&expr, budget).is_err());
1289
1290        let decoded = decode(&expr, &schema, budget);
1291        let display = decoded.to_string();
1292        assert!(display.contains(">= 10"), "{display}");
1293        assert!(display.contains("<= 20"), "{display}");
1294        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{display}");
1295        assert!(!has_expr::<InListExpr>(&decoded), "{display}");
1296        assert_eq!(
1297            encode_physical_expr_to_bytes(&decoded).unwrap(),
1298            encode_physical_expr_to_bytes(&bounds).unwrap()
1299        );
1300    }
1301
1302    #[test]
1303    fn dyn_filter_payload_negated_unconvertible_lookup_is_unsupported() {
1304        // `NOT lookup` is a single top-level conjunct that carries the membership, so
1305        // there is nothing safe to keep. Transport must not encode `NOT true` (or `true`)
1306        // in its place: the predicate is reported as unsupported.
1307        let schema = Arc::new(Schema::new(vec![Field::new(
1308            "device_id",
1309            DataType::Int32,
1310            false,
1311        )]));
1312        let device_id = col("device_id", &schema).unwrap();
1313        let not_lookup =
1314            Arc::new(NotExpr::new(unrepresentable_lookup(&device_id))) as Arc<dyn PhysicalExpr>;
1315
1316        assert_unsupported(DynFilterPayload::from_datafusion_expr(&not_lookup, 1024).unwrap_err());
1317    }
1318
1319    #[test]
1320    fn dyn_filter_payload_membership_under_or_is_unsupported() {
1321        // `bound OR lookup` is a single top-level conjunct that carries the membership:
1322        // rewriting it to `bound OR true` would be nothing but `true`, and keeping only
1323        // the bound would *narrow* the predicate, so it is reported as unsupported.
1324        let schema = Arc::new(Schema::new(vec![Field::new(
1325            "device_id",
1326            DataType::Int32,
1327            false,
1328        )]));
1329        let device_id = col("device_id", &schema).unwrap();
1330        let lower_bound = Arc::new(BinaryExpr::new(
1331            Arc::clone(&device_id),
1332            Operator::GtEq,
1333            lit(10i32),
1334        )) as Arc<dyn PhysicalExpr>;
1335        let expr = Arc::new(BinaryExpr::new(
1336            lower_bound,
1337            Operator::Or,
1338            unrepresentable_lookup(&device_id),
1339        )) as Arc<dyn PhysicalExpr>;
1340
1341        assert_unsupported(DynFilterPayload::from_datafusion_expr(&expr, 1024).unwrap_err());
1342    }
1343
1344    #[test]
1345    fn dyn_filter_payload_over_budget_keeps_bounds() {
1346        let schema = Arc::new(Schema::new(vec![Field::new(
1347            "device_id",
1348            DataType::Int32,
1349            false,
1350        )]));
1351        let device_id = col("device_id", &schema).unwrap();
1352        let lower_bound = Arc::new(BinaryExpr::new(
1353            Arc::clone(&device_id),
1354            Operator::GtEq,
1355            lit(8192i32),
1356        )) as Arc<dyn PhysicalExpr>;
1357        let upper_bound = Arc::new(BinaryExpr::new(
1358            Arc::clone(&device_id),
1359            Operator::LtEq,
1360            lit(8255i32),
1361        )) as Arc<dyn PhysicalExpr>;
1362        let bounds = Arc::new(BinaryExpr::new(
1363            Arc::clone(&lower_bound),
1364            Operator::And,
1365            Arc::clone(&upper_bound),
1366        )) as Arc<dyn PhysicalExpr>;
1367        let oversized_in = Arc::new(
1368            InListExpr::try_new(
1369                Arc::clone(&device_id),
1370                (8192..8256).map(lit).collect(),
1371                false,
1372                &schema,
1373            )
1374            .unwrap(),
1375        ) as Arc<dyn PhysicalExpr>;
1376        let expr = Arc::new(BinaryExpr::new(
1377            Arc::clone(&bounds),
1378            Operator::And,
1379            oversized_in,
1380        )) as Arc<dyn PhysicalExpr>;
1381
1382        // A caller-supplied limit that fits the bounds but not the oversized `IN` list:
1383        // the membership conjunct is dropped and the bounds are encoded under the same
1384        // budget.
1385        let bounds_size = encode_physical_expr_to_bytes(&bounds).unwrap().len();
1386        assert!(encode_bounded_physical_expr_to_bytes(&expr, bounds_size).is_err());
1387
1388        let decoded = decode(&expr, &schema, bounds_size);
1389        let display = decoded.to_string();
1390        assert!(display.contains(">= 8192"), "{display}");
1391        assert!(display.contains("<= 8255"), "{display}");
1392        assert!(!has_expr::<InListExpr>(&decoded), "{display}");
1393        assert_eq!(
1394            encode_physical_expr_to_bytes(&decoded).unwrap(),
1395            encode_physical_expr_to_bytes(&bounds).unwrap()
1396        );
1397
1398        // A budget that does not even fit the retained bounds is reported as too large:
1399        // nothing that cannot be shipped may be replaced with `true`.
1400        let true_size = encode_physical_expr_to_bytes(&lit(true)).unwrap().len();
1401        assert!(true_size < bounds_size);
1402        assert_too_large(DynFilterPayload::from_datafusion_expr(&expr, true_size).unwrap_err());
1403    }
1404
1405    #[test]
1406    fn bounded_encoding_preserves_bytes_and_exact_limit() {
1407        let schema = Schema::new(vec![Field::new("device_id", DataType::Int32, false)]);
1408        let device_id = Arc::new(Column::new("device_id", 0)) as Arc<dyn PhysicalExpr>;
1409        let in_list = Arc::new(
1410            InListExpr::try_new(
1411                Arc::clone(&device_id),
1412                (0..64).map(lit).collect(),
1413                false,
1414                &schema,
1415            )
1416            .unwrap(),
1417        ) as Arc<dyn PhysicalExpr>;
1418        let lower_bound = Arc::new(BinaryExpr::new(device_id, Operator::GtEq, lit(10i32)))
1419            as Arc<dyn PhysicalExpr>;
1420        let expr =
1421            Arc::new(BinaryExpr::new(lower_bound, Operator::And, in_list)) as Arc<dyn PhysicalExpr>;
1422        let expected = serialize_physical_expr(&expr, &DefaultPhysicalExtensionCodec {})
1423            .unwrap()
1424            .encode_to_vec();
1425
1426        assert_eq!(
1427            encode_bounded_physical_expr_to_bytes(&expr, expected.len()).unwrap(),
1428            expected
1429        );
1430        assert!(matches!(
1431            encode_bounded_physical_expr_to_bytes(&expr, expected.len() - 1),
1432            Err(CommonQueryError::DynFilterPayloadTooLarge { .. })
1433        ));
1434    }
1435
1436    #[test]
1437    fn bounded_encoding_stops_before_later_children() {
1438        let schema = Schema::new(vec![Field::new("host", DataType::Utf8, false)]);
1439        let expr = Arc::new(
1440            InListExpr::try_new(
1441                Arc::new(Column::new("host", 0)),
1442                (0..8).map(|i| lit(i.to_string().repeat(1024))).collect(),
1443                false,
1444                &schema,
1445            )
1446            .unwrap(),
1447        ) as Arc<dyn PhysicalExpr>;
1448        let full_size = encode_physical_expr_to_bytes(&expr).unwrap().len();
1449        assert!(full_size > 8192);
1450
1451        let error = encode_bounded_physical_expr_to_bytes(&expr, 2048).unwrap_err();
1452        let CommonQueryError::DynFilterPayloadTooLarge {
1453            payload_size_bytes, ..
1454        } = error
1455        else {
1456            panic!("expected payload size error, got {error:?}");
1457        };
1458        assert!((2048..4096).contains(&payload_size_bytes));
1459    }
1460
1461    #[test]
1462    fn dyn_filter_payload_rejects_oversized_payload() {
1463        let expr: Arc<dyn PhysicalExpr> = Arc::new(Column::new("host", 0));
1464
1465        let err = DynFilterPayload::from_datafusion_expr(&expr, 1).unwrap_err();
1466
1467        let DataFusionError::External(error) = err else {
1468            panic!("expected external common query error, got: {err:?}");
1469        };
1470        assert!(matches!(
1471            error.downcast_ref::<CommonQueryError>(),
1472            Some(CommonQueryError::DynFilterPayloadTooLarge { .. })
1473        ));
1474    }
1475
1476    #[test]
1477    fn membership_value_bound_really_bounds_what_the_byte_budget_holds() {
1478        // The count bound has to be *real*, not a restatement of its own formula: a
1479        // payload of `B` bytes can never hold more than `B / MIN_ENCODED_LITERAL_BYTES`
1480        // list literals. Prove it by encoding one literal more than the bound and checking
1481        // that the resulting frame really exceeds `B`.
1482        let budget = 512;
1483        let bound = max_membership_values(budget);
1484        assert!(bound > 1, "the bound must leave room for a real list");
1485        let schema = Schema::new(vec![Field::new("host", DataType::Utf8, true)]);
1486        let minimal_in_list = |values: usize| {
1487            Arc::new(
1488                InListExpr::try_new(
1489                    Arc::new(Column::new("host", 0)),
1490                    (0..values).map(|_| lit("")).collect(),
1491                    false,
1492                    &schema,
1493                )
1494                .unwrap(),
1495            ) as Arc<dyn PhysicalExpr>
1496        };
1497
1498        let over_bound = encode_physical_expr_to_bytes(&minimal_in_list(bound + 1)).unwrap();
1499        assert!(
1500            over_bound.len() > budget,
1501            "{} literals must not fit a {budget}-byte budget, but the frame is {} bytes",
1502            bound + 1,
1503            over_bound.len()
1504        );
1505        // The same payload is refused by the bounded encoder, so the derived bound and the
1506        // encoder agree on where the budget ends.
1507        assert!(matches!(
1508            encode_bounded_physical_expr_to_bytes(&minimal_in_list(bound + 1), budget),
1509            Err(CommonQueryError::DynFilterPayloadTooLarge { .. })
1510        ));
1511        // The floor the bound is derived from must hold for the cheapest literal there is.
1512        let cheapest = encode_physical_expr_to_bytes(&lit("")).unwrap().len();
1513        assert!(
1514            cheapest >= MIN_ENCODED_LITERAL_BYTES,
1515            "floor must hold for the cheapest literal, got {cheapest} bytes"
1516        );
1517    }
1518
1519    #[test]
1520    fn utf8_list_literals_is_the_authoritative_value_check() {
1521        let values: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c"]));
1522        assert!(utf8_list_literals(&values, 3).is_some());
1523        // The count is bounded before a single `Literal` is built.
1524        assert!(utf8_list_literals(&values, 2).is_none());
1525        assert!(utf8_list_literals(&values, 0).is_none());
1526        // NULL-containing, empty and non-`Utf8` arrays are refused here, not only by the
1527        // `HashTableLookupExpr` accessor.
1528        let with_null: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), None]));
1529        assert!(utf8_list_literals(&with_null, 8).is_none());
1530        let empty: ArrayRef = Arc::new(StringArray::from(Vec::<&str>::new()));
1531        assert!(utf8_list_literals(&empty, 8).is_none());
1532        let not_utf8: ArrayRef = Arc::new(Int32Array::from(vec![1, 2]));
1533        assert!(utf8_list_literals(&not_utf8, 8).is_none());
1534    }
1535}
1536
1537/// Remote dynamic filter membership recovered from *real* DataFusion build leases.
1538///
1539/// The tests above build `HashTableLookupExpr` by hand, which always has
1540/// `build_lease = None`. These tests run an actual `HashJoinExec` so DataFusion
1541/// publishes lookups backed by a real build lease, which is the only way to prove that
1542/// the key list (and the membership-free conjunct retention) actually works.
1543///
1544/// Most remote predicates are checked twice: structurally (what the payload contains)
1545/// and by **evaluating** the producer predicate and the decoded predicate on the same
1546/// `NULL`-free rows. Evaluation pins the contract that applies here: the converted
1547/// membership is the build key list, so on `NULL`-free keys only, the decoded predicate
1548/// keeps exactly the rows the producer kept. It is a pruning hint, not a universal
1549/// equivalence — see `not_lookup_becomes_not_in` for the `NULL` caveat.
1550#[cfg(test)]
1551mod remote_membership_tests {
1552    use std::collections::BTreeMap;
1553
1554    use datafusion::arrow::array::{
1555        ArrayRef, BooleanArray, Float64Array, Int32Array, StringArray, StringDictionaryBuilder,
1556    };
1557    use datafusion::arrow::datatypes::{DataType, Field, Int32Type, Schema};
1558    use datafusion::arrow::record_batch::RecordBatch;
1559    use datafusion::physical_expr::expressions::{
1560        BinaryExpr, CaseExpr, Column, InListExpr, IsNullExpr, Literal, NotExpr, lit,
1561    };
1562    use datafusion::physical_plan::PhysicalExpr;
1563    use datafusion::physical_plan::joins::{HashExpr, HashTableLookupExpr};
1564    use datafusion_expr::Operator;
1565
1566    use super::remote_membership_test_support::{
1567        RealDynFilter, key, one_column_schema, partitions, run_real_hash_join, utf8, utf8_join,
1568    };
1569    use super::*;
1570
1571    fn in_lists(expr: &Arc<dyn PhysicalExpr>) -> Vec<Arc<dyn PhysicalExpr>> {
1572        let mut found = Vec::new();
1573        expr.apply(|node| {
1574            if node.is::<InListExpr>() {
1575                found.push(Arc::clone(node));
1576            }
1577            Ok(TreeNodeRecursion::Continue)
1578        })
1579        .unwrap();
1580        found
1581    }
1582
1583    fn in_list_values(expr: &Arc<dyn PhysicalExpr>) -> Vec<String> {
1584        let in_list = expr.downcast_ref::<InListExpr>().unwrap();
1585        assert!(!in_list.negated());
1586        in_list
1587            .list()
1588            .iter()
1589            .map(|literal| {
1590                literal
1591                    .downcast_ref::<Literal>()
1592                    .unwrap()
1593                    .value()
1594                    .to_string()
1595                    .trim_matches('\'')
1596                    .to_string()
1597            })
1598            .collect()
1599    }
1600
1601    fn assert_has_bounds(expr: &Arc<dyn PhysicalExpr>) {
1602        let display = expr.to_string();
1603        assert!(display.contains(">="), "missing lower bound: {display}");
1604        assert!(display.contains("<="), "missing upper bound: {display}");
1605    }
1606
1607    fn utf8_batch(schema: &Arc<Schema>, values: &[&str]) -> RecordBatch {
1608        RecordBatch::try_new(Arc::clone(schema), vec![utf8(values)]).unwrap()
1609    }
1610
1611    fn selected(expr: &Arc<dyn PhysicalExpr>, batch: &RecordBatch) -> Vec<bool> {
1612        let array = expr
1613            .evaluate(batch)
1614            .unwrap()
1615            .into_array(batch.num_rows())
1616            .unwrap();
1617        let booleans = array.as_any().downcast_ref::<BooleanArray>().unwrap();
1618        (0..batch.num_rows())
1619            .map(|index| booleans.value(index))
1620            .collect()
1621    }
1622
1623    /// Widening check: the decoded predicate keeps every row the producer kept.
1624    ///
1625    /// Only used on `NULL`-free rows, where the build-key membership is exact for the
1626    /// converted node.
1627    fn assert_fail_open(
1628        original: &Arc<dyn PhysicalExpr>,
1629        decoded: &Arc<dyn PhysicalExpr>,
1630        batch: &RecordBatch,
1631    ) -> (Vec<bool>, Vec<bool>) {
1632        let original_selected = selected(original, batch);
1633        let decoded_selected = selected(decoded, batch);
1634        for (row, (kept, kept_after)) in original_selected
1635            .iter()
1636            .zip(decoded_selected.iter())
1637            .enumerate()
1638        {
1639            assert!(
1640                kept_after >= kept,
1641                "decoded predicate dropped row {row}: producer={kept} decoded={kept_after} \
1642                 (decoded predicate: {decoded})"
1643            );
1644        }
1645        (original_selected, decoded_selected)
1646    }
1647
1648    /// Branch chosen by the CASE routing expression for every row.
1649    fn routed_branch(case: &CaseExpr, batch: &RecordBatch) -> Vec<u64> {
1650        let routing = case.expr().expect("hash routing operand");
1651        let array = routing
1652            .evaluate(batch)
1653            .unwrap()
1654            .into_array(batch.num_rows())
1655            .unwrap();
1656        let branches = array
1657            .as_any()
1658            .downcast_ref::<datafusion::arrow::array::UInt64Array>()
1659            .unwrap();
1660        (0..batch.num_rows())
1661            .map(|index| branches.value(index))
1662            .collect()
1663    }
1664
1665    fn hash_seed(expr: &Arc<dyn PhysicalExpr>) -> u64 {
1666        let mut seed = None;
1667        expr.apply(|node| {
1668            if let Some(hash) = node.downcast_ref::<HashExpr>() {
1669                seed = Some(hash.seed());
1670                Ok(TreeNodeRecursion::Stop)
1671            } else {
1672                Ok(TreeNodeRecursion::Continue)
1673            }
1674        })
1675        .unwrap();
1676        seed.expect("hash routing expression")
1677    }
1678
1679    /// `trace_id` values used to evaluate recovered filters.
1680    fn evaluation_batch(schema: &Arc<Schema>, values: &[String]) -> RecordBatch {
1681        let borrowed = values.iter().map(String::as_str).collect::<Vec<_>>();
1682        utf8_batch(schema, &borrowed)
1683    }
1684
1685    /// UTF-8 batch that can contain SQL NULLs, for wrapper semantics.
1686    fn nullable_evaluation_batch(schema: &Arc<Schema>, values: &[Option<String>]) -> RecordBatch {
1687        let array = StringArray::from(values.to_vec());
1688        RecordBatch::try_new(Arc::clone(schema), vec![Arc::new(array) as ArrayRef]).unwrap()
1689    }
1690
1691    #[tokio::test]
1692    async fn membership_round_trips_real_utf8_build_lease() {
1693        let schema = one_column_schema("trace_id", DataType::Utf8);
1694        let (build, probe, values) = utf8_join(1);
1695        let trace_id = key("trace_id", 0);
1696        let filter = run_real_hash_join(
1697            1,
1698            Arc::clone(&schema),
1699            Arc::clone(&schema),
1700            build,
1701            probe,
1702            vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))],
1703        )
1704        .await;
1705
1706        // The producer predicate really holds a runtime-only lookup...
1707        assert!(has_expr::<HashTableLookupExpr>(&filter.expr));
1708
1709        // ...and it is serialized as exact build membership, not as `true`.
1710        let decoded = decode(
1711            &filter.expr,
1712            &filter.probe_schema,
1713            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
1714        );
1715        assert!(!has_expr::<HashTableLookupExpr>(&decoded));
1716        let lists = in_lists(&decoded);
1717        assert_eq!(lists.len(), 1, "expected one recovered InList: {decoded}");
1718        assert_eq!(in_list_values(&lists[0]), values);
1719        assert_has_bounds(&decoded);
1720
1721        // Members are selected, non-members are not, nothing else changes.
1722        let mut rows = values.clone();
1723        rows.push("miss-not-a-member".to_string());
1724        let batch = evaluation_batch(&schema, &rows);
1725        let (original_selected, decoded_selected) =
1726            assert_fail_open(&filter.expr, &decoded, &batch);
1727        for row in 0..values.len() {
1728            assert!(original_selected[row], "member row {row} must be selected");
1729            assert!(decoded_selected[row], "member row {row} must stay selected");
1730        }
1731        assert!(
1732            !decoded_selected[values.len()],
1733            "non-member must not be selected"
1734        );
1735    }
1736
1737    #[tokio::test]
1738    async fn membership_preserves_three_branch_case_structure() {
1739        let schema = one_column_schema("trace_id", DataType::Utf8);
1740        let (build, probe, values) = utf8_join(3);
1741        let trace_id = key("trace_id", 0);
1742        let filter = run_real_hash_join(
1743            3,
1744            Arc::clone(&schema),
1745            Arc::clone(&schema),
1746            build,
1747            probe,
1748            vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))],
1749        )
1750        .await;
1751
1752        // Three hash-routed partitions produce a three-branch CASE.
1753        let original_case = filter
1754            .expr
1755            .downcast_ref::<CaseExpr>()
1756            .expect("real three-branch CASE");
1757        assert_eq!(original_case.when_then_expr().len(), 3);
1758
1759        let decoded = decode(
1760            &filter.expr,
1761            &filter.probe_schema,
1762            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
1763        );
1764        let case = decoded.downcast_ref::<CaseExpr>().expect("CASE preserved");
1765        assert_eq!(case.when_then_expr().len(), 3);
1766        assert!(case.else_expr().is_some());
1767
1768        // Routing is untouched: same operand expression and same `HashExpr` seed, so
1769        // the receiver selects the same branch for every row.
1770        assert_eq!(
1771            original_case.expr().unwrap().to_string(),
1772            case.expr().unwrap().to_string()
1773        );
1774        assert_eq!(
1775            hash_seed(original_case.expr().unwrap()),
1776            hash_seed(case.expr().unwrap())
1777        );
1778
1779        // Branch-specific membership: the WHEN literal names the branch, so the values
1780        // recovered for each branch can be checked individually.
1781        let mut branch_values: BTreeMap<u64, Vec<String>> = BTreeMap::new();
1782        for (when, then) in case.when_then_expr() {
1783            let branch = match when.downcast_ref::<Literal>().unwrap().value() {
1784                ScalarValue::UInt64(Some(branch)) => *branch,
1785                other => panic!("unexpected CASE routing literal: {other:?}"),
1786            };
1787            let lists = in_lists(then);
1788            assert_eq!(lists.len(), 1, "each branch keeps its membership: {then}");
1789            let mut branch_list = in_list_values(&lists[0]);
1790            branch_list.sort();
1791            assert!(
1792                branch_values.insert(branch, branch_list).is_none(),
1793                "branch {branch} appears twice"
1794            );
1795            assert_has_bounds(then);
1796        }
1797        assert_eq!(branch_values.len(), 3, "three distinct branches");
1798
1799        // Every build key is recovered exactly once, in its own branch.
1800        let mut recovered = branch_values
1801            .values()
1802            .flatten()
1803            .cloned()
1804            .collect::<Vec<_>>();
1805        recovered.sort();
1806        assert_eq!(recovered, values);
1807
1808        // Evaluation proves branch-specific routing: a row is selected iff its key is in
1809        // the membership of the branch the routing sends it to.
1810        let mut rows = values.clone();
1811        rows.extend((0..4).map(|i| format!("miss-{i:02}")));
1812        let batch = evaluation_batch(&schema, &rows);
1813        let (original_selected, decoded_selected) =
1814            assert_fail_open(&filter.expr, &decoded, &batch);
1815        let branches = routed_branch(case, &batch);
1816        for (row, value) in rows.iter().enumerate() {
1817            let branch = branches[row];
1818            let expected = branch_values
1819                .get(&branch)
1820                .is_some_and(|members| members.binary_search(value).is_ok());
1821            assert_eq!(
1822                decoded_selected[row], expected,
1823                "row {value} routed to branch {branch} must be selected iff it is a \
1824                 member of that branch's list"
1825            );
1826            // Build members must keep their decision; misses only ever widen.
1827            if expected {
1828                assert!(
1829                    original_selected[row],
1830                    "producer must select its own build member {value}"
1831                );
1832                assert!(decoded_selected[row]);
1833            }
1834        }
1835        assert!(
1836            decoded_selected
1837                .iter()
1838                .filter(|selected| **selected)
1839                .count()
1840                >= values.len(),
1841            "every build member must still be selected"
1842        );
1843    }
1844
1845    /// Runs a real one-partition `Utf8` hash join over `key_count` distinct keys.
1846    async fn real_join_with_keys(key_count: usize) -> (Arc<Schema>, RealDynFilter, Vec<String>) {
1847        let schema = one_column_schema("trace_id", DataType::Utf8);
1848        let trace_id = key("trace_id", 0);
1849        let values = (0..key_count)
1850            .map(|i| format!("trace-{i:04}"))
1851            .collect::<Vec<_>>();
1852        let borrowed = values.iter().map(String::as_str).collect::<Vec<_>>();
1853        let build = partitions(&schema, vec![vec![utf8(&borrowed)]]);
1854        let probe = partitions(&schema, vec![vec![utf8(&borrowed)]]);
1855        let filter = run_real_hash_join(
1856            1,
1857            Arc::clone(&schema),
1858            Arc::clone(&schema),
1859            build,
1860            probe,
1861            vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))],
1862        )
1863        .await;
1864        (schema, filter, values)
1865    }
1866
1867    #[tokio::test]
1868    async fn bounds_survive_unrepresentable_integer_lookup() {
1869        // Integer keys are not a single-column `Utf8` membership, so this real lookup has
1870        // no wire form. Retention keeps the top-level bounds and drops the lookup
1871        // conjunct, so the decoded predicate only ever gets wider.
1872        let schema = one_column_schema("k", DataType::Int32);
1873        let k = key("k", 0);
1874        let filter = run_real_hash_join(
1875            1,
1876            Arc::clone(&schema),
1877            Arc::clone(&schema),
1878            partitions(
1879                &schema,
1880                vec![vec![Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef]],
1881            ),
1882            partitions(
1883                &schema,
1884                vec![vec![
1885                    Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 10])) as ArrayRef
1886                ]],
1887            ),
1888            vec![(Arc::clone(&k), Arc::clone(&k))],
1889        )
1890        .await;
1891        let lookup = find_expr::<HashTableLookupExpr>(&filter.expr).expect("real lookup");
1892
1893        let lower_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::GtEq, lit(2i32)))
1894            as Arc<dyn PhysicalExpr>;
1895        let upper_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::LtEq, lit(4i32)))
1896            as Arc<dyn PhysicalExpr>;
1897        let bounds = Arc::new(BinaryExpr::new(lower_bound, Operator::And, upper_bound))
1898            as Arc<dyn PhysicalExpr>;
1899        let expr = Arc::new(BinaryExpr::new(Arc::clone(&bounds), Operator::And, lookup))
1900            as Arc<dyn PhysicalExpr>;
1901
1902        let decoded = decode(
1903            &expr,
1904            &filter.probe_schema,
1905            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
1906        );
1907        let display = decoded.to_string();
1908        assert!(
1909            display.contains(">= 2"),
1910            "lower bound must survive: {display}"
1911        );
1912        assert!(
1913            display.contains("<= 4"),
1914            "upper bound must survive: {display}"
1915        );
1916        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{display}");
1917        assert!(!has_expr::<InListExpr>(&decoded), "{display}");
1918
1919        // The producer and the decoded predicate agree on every row the producer kept and
1920        // only diverge on the non-member `4`, where the retained payload widens.
1921        let batch = RecordBatch::try_new(
1922            Arc::clone(&schema),
1923            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 10])) as ArrayRef],
1924        )
1925        .unwrap();
1926        let (original_selected, decoded_selected) = assert_fail_open(&expr, &decoded, &batch);
1927        assert_eq!(
1928            original_selected,
1929            vec![false, true, true, false, false, false]
1930        );
1931        assert_eq!(
1932            decoded_selected,
1933            vec![false, true, true, true, false, false]
1934        );
1935    }
1936
1937    #[tokio::test]
1938    async fn small_budget_keeps_bounds_and_drops_real_membership() {
1939        // A real `Utf8` lookup next to integer bounds, shipped under a caller-supplied
1940        // limit that fits only the bounds: retention drops the membership conjunct and
1941        // still sends the bounds, which can only widen the producer predicate.
1942        let probe_schema = Arc::new(Schema::new(vec![
1943            Field::new("trace_id", DataType::Utf8, true),
1944            Field::new("k", DataType::Int32, true),
1945        ]));
1946        let build_schema = one_column_schema("trace_id", DataType::Utf8);
1947        let long = "t".repeat(256);
1948        let values = (0..24)
1949            .map(|i| format!("{long}-{i:02}"))
1950            .collect::<Vec<_>>();
1951        let borrowed = values.iter().map(String::as_str).collect::<Vec<_>>();
1952        let build_key = key("trace_id", 0);
1953        let probe_key = key("trace_id", 0);
1954        let filter = run_real_hash_join(
1955            1,
1956            Arc::clone(&build_schema),
1957            Arc::clone(&probe_schema),
1958            partitions(&build_schema, vec![vec![utf8(&borrowed)]]),
1959            partitions(
1960                &probe_schema,
1961                vec![vec![
1962                    utf8(&borrowed),
1963                    Arc::new(Int32Array::from(vec![0i32; values.len()])) as ArrayRef,
1964                ]],
1965            ),
1966            vec![(Arc::clone(&build_key), Arc::clone(&probe_key))],
1967        )
1968        .await;
1969        let lookup = find_expr::<HashTableLookupExpr>(&filter.expr).expect("real lookup");
1970
1971        let k = key("k", 1);
1972        let lower_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::GtEq, lit(2i32)))
1973            as Arc<dyn PhysicalExpr>;
1974        let upper_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::LtEq, lit(5i32)))
1975            as Arc<dyn PhysicalExpr>;
1976        let bounds = Arc::new(BinaryExpr::new(lower_bound, Operator::And, upper_bound))
1977            as Arc<dyn PhysicalExpr>;
1978        let expr = Arc::new(BinaryExpr::new(Arc::clone(&bounds), Operator::And, lookup))
1979            as Arc<dyn PhysicalExpr>;
1980
1981        // Only the bounds fit: the membership of 24 long keys is far beyond this budget.
1982        let bounds_size = encode_physical_expr_to_bytes(&bounds).unwrap().len();
1983        let decoded = decode(&expr, &filter.probe_schema, bounds_size);
1984        let display = decoded.to_string();
1985        assert!(
1986            display.contains(">= 2"),
1987            "lower bound must survive: {display}"
1988        );
1989        assert!(
1990            display.contains("<= 5"),
1991            "upper bound must survive: {display}"
1992        );
1993        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{display}");
1994        assert!(!has_expr::<InListExpr>(&decoded), "{display}");
1995
1996        // Evaluation: a member inside the bounds is kept by both, a member outside the
1997        // bounds is dropped by both, and only the non-member is widened.
1998        let trace_ids = vec![
1999            values[0].as_str(),
2000            values[1].as_str(),
2001            "miss-not-a-member",
2002            values[2].as_str(),
2003        ];
2004        let batch = RecordBatch::try_new(
2005            Arc::clone(&probe_schema),
2006            vec![
2007                utf8(&trace_ids),
2008                Arc::new(Int32Array::from(vec![2i32, 6, 3, 5])) as ArrayRef,
2009            ],
2010        )
2011        .unwrap();
2012        let (original_selected, decoded_selected) = assert_fail_open(&expr, &decoded, &batch);
2013        assert_eq!(original_selected, vec![true, false, false, true]);
2014        assert_eq!(decoded_selected, vec![true, false, true, true]);
2015    }
2016
2017    #[tokio::test]
2018    async fn real_642_key_hash_join_becomes_exact_642_literal_in() {
2019        let (schema, filter, values) = real_join_with_keys(642).await;
2020        assert_eq!(values.len(), 642);
2021        // The producer predicate really holds a runtime-only lookup...
2022        assert!(has_expr::<HashTableLookupExpr>(&filter.expr));
2023
2024        // ...and it is written as one literal per build key within the payload budget.
2025        let decoded = decode(
2026            &filter.expr,
2027            &filter.probe_schema,
2028            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2029        );
2030        assert!(!has_expr::<HashTableLookupExpr>(&decoded));
2031        let lists = in_lists(&decoded);
2032        assert_eq!(lists.len(), 1, "expected one converted InList: {decoded}");
2033        let mut recovered = in_list_values(&lists[0]);
2034        assert_eq!(recovered.len(), 642, "one literal per build key");
2035        recovered.sort();
2036        assert_eq!(recovered, values);
2037
2038        // The membership selects exactly the build keys.
2039        let mut rows = values.clone();
2040        rows.push("miss-not-a-member".to_string());
2041        let batch = evaluation_batch(&schema, &rows);
2042        let (original_selected, decoded_selected) =
2043            assert_fail_open(&filter.expr, &decoded, &batch);
2044        for row in 0..values.len() {
2045            assert!(
2046                original_selected[row],
2047                "build key row {row} must be selected"
2048            );
2049            assert!(
2050                decoded_selected[row],
2051                "build key row {row} must stay selected"
2052            );
2053        }
2054        assert!(
2055            !decoded_selected[values.len()],
2056            "non-member must not be selected"
2057        );
2058    }
2059
2060    #[tokio::test]
2061    async fn large_build_side_is_refused_before_materializing_literals() {
2062        // A build side far larger than a small budget can hold must be refused by the
2063        // derived count bound *before* the encoder creates one `Literal` per build key.
2064        let (_, filter, values) = real_join_with_keys(1024).await;
2065        let lookup = find_expr::<HashTableLookupExpr>(&filter.expr).expect("real lookup");
2066        let lookup = lookup.downcast_ref::<HashTableLookupExpr>().unwrap();
2067
2068        // DataFusion itself would hand out every build key ...
2069        let unbounded = lookup
2070            .build_key_membership(usize::MAX, usize::MAX)
2071            .expect("the build lease holds the keys");
2072        assert_eq!(unbounded.values().len(), values.len());
2073
2074        // ... but a budget that only fits the producer's own bounds leaves room for a few
2075        // literals, so the count bound derived from it refuses the list outright.
2076        let bounds = conjunction(
2077            split_conjunction(&filter.expr)
2078                .into_iter()
2079                .filter(|conjunct| !has_expr::<HashTableLookupExpr>(conjunct))
2080                .cloned()
2081                .collect::<Vec<_>>(),
2082        );
2083        let budget = encode_physical_expr_to_bytes(&bounds).unwrap().len();
2084        assert!(
2085            max_membership_values(budget) < values.len(),
2086            "the derived count bound must stay below the build side size"
2087        );
2088        // The refusal is reported as a *size* refusal, not as a predicate without a wire
2089        // form: the key list exists, it just does not fit this budget.
2090        assert!(
2091            matches!(
2092                RemoteMembership::from_lookup(lookup, budget),
2093                Err(MembershipRefusal::OverBudget { build_keys }) if build_keys == values.len()
2094            ),
2095            "an over-large build key list must be refused as over budget"
2096        );
2097
2098        // Nothing of the 1024-key membership reaches the payload.
2099        let decoded = decode(&filter.expr, &filter.probe_schema, budget);
2100        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{decoded}");
2101        assert!(!has_expr::<InListExpr>(&decoded), "{decoded}");
2102        assert_has_bounds(&decoded);
2103    }
2104
2105    #[tokio::test]
2106    async fn lookup_or_key_is_null_preserves_wrapper_and_becomes_in_list() {
2107        // The `key IS NULL OR <filter>` wrapper of a null-aware join is an ordinary
2108        // node: it stays in the payload and only the lookup inside it is converted.
2109        let (schema, filter, values) = real_join_with_keys(8).await;
2110        let lookup = find_expr::<HashTableLookupExpr>(&filter.expr).expect("real lookup");
2111        let trace_id = key("trace_id", 0);
2112        let wrapped = Arc::new(BinaryExpr::new(
2113            Arc::clone(&lookup),
2114            Operator::Or,
2115            Arc::new(IsNullExpr::new(Arc::clone(&trace_id))),
2116        )) as Arc<dyn PhysicalExpr>;
2117
2118        let decoded = decode(
2119            &wrapped,
2120            &filter.probe_schema,
2121            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2122        );
2123        let display = decoded.to_string();
2124        assert!(
2125            display.contains("IS NULL"),
2126            "IS NULL wrapper must survive: {display}"
2127        );
2128        assert!(!display.contains("hash_lookup"), "{display}");
2129        let lists = in_lists(&decoded);
2130        assert_eq!(lists.len(), 1, "expected one converted InList: {display}");
2131        assert_eq!(in_list_values(&lists[0]), values);
2132
2133        let mut rows = values
2134            .iter()
2135            .map(|value| Some(value.clone()))
2136            .collect::<Vec<_>>();
2137        rows.push(Some("miss-not-a-member".to_string()));
2138        rows.push(None);
2139        let batch = nullable_evaluation_batch(&schema, &rows);
2140        let (original_selected, decoded_selected) = assert_fail_open(&wrapped, &decoded, &batch);
2141        for row in 0..values.len() {
2142            assert!(original_selected[row]);
2143            assert!(decoded_selected[row]);
2144        }
2145        assert!(
2146            original_selected[rows.len() - 1],
2147            "producer `lookup OR key IS NULL` keeps a NULL probe"
2148        );
2149        assert!(
2150            decoded_selected[rows.len() - 1],
2151            "decoded `IN ... OR key IS NULL` must also keep a NULL probe"
2152        );
2153    }
2154
2155    #[tokio::test]
2156    async fn null_build_keys_keep_only_the_safe_bounds() {
2157        // The key-list accessor requires `NULL`-free build keys, so a build side with a
2158        // `NULL` key has no membership. This producer shape is `bounds AND lookup`: the
2159        // bounds DataFusion derived from the non-`NULL` keys are retained, and the lookup
2160        // is dropped instead of the predicate being replaced with `true`.
2161        let schema = one_column_schema("trace_id", DataType::Utf8);
2162        let trace_id = key("trace_id", 0);
2163        let build_values: ArrayRef = Arc::new(StringArray::from(vec![
2164            Some("trace-a"),
2165            None,
2166            Some("trace-b"),
2167        ]));
2168        let filter = run_real_hash_join(
2169            1,
2170            Arc::clone(&schema),
2171            Arc::clone(&schema),
2172            partitions(&schema, vec![vec![build_values]]),
2173            partitions(&schema, vec![vec![utf8(&["trace-a", "trace-b", "miss"])]]),
2174            vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))],
2175        )
2176        .await;
2177        assert!(has_expr::<HashTableLookupExpr>(&filter.expr));
2178        let producer = filter.expr.to_string();
2179        assert!(producer.contains(">= trace-a"), "{producer}");
2180        assert!(producer.contains("<= trace-b"), "{producer}");
2181
2182        let decoded = decode(
2183            &filter.expr,
2184            &filter.probe_schema,
2185            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2186        );
2187        let display = decoded.to_string();
2188        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{display}");
2189        assert!(!has_expr::<InListExpr>(&decoded), "{display}");
2190        assert!(display.contains(">= trace-a"), "{display}");
2191        assert!(display.contains("<= trace-b"), "{display}");
2192        assert_ne!(display, "true", "transport must not widen to `true`");
2193
2194        // The retained conjuncts are the producer bounds verbatim.
2195        let bounds = split_conjunction(&filter.expr)
2196            .into_iter()
2197            .filter(|conjunct| !has_expr::<HashTableLookupExpr>(conjunct))
2198            .cloned()
2199            .collect::<Vec<_>>();
2200        assert_eq!(
2201            encode_physical_expr_to_bytes(&decoded).unwrap(),
2202            encode_physical_expr_to_bytes(&conjunction(bounds)).unwrap()
2203        );
2204
2205        // Widening only: every build key row the producer kept is still kept.
2206        let rows = ["trace-a", "trace-b", "miss"]
2207            .map(ToString::to_string)
2208            .to_vec();
2209        let batch = evaluation_batch(&schema, &rows);
2210        let (original_selected, decoded_selected) =
2211            assert_fail_open(&filter.expr, &decoded, &batch);
2212        assert_eq!(original_selected, vec![true, true, false]);
2213        assert!(decoded_selected[0], "build key row must stay selected");
2214        assert!(decoded_selected[1], "build key row must stay selected");
2215    }
2216
2217    /// `NOT lookup` becomes `NOT (key IN (...))`.
2218    ///
2219    /// This narrow contract is about **positive pruning**: the membership is the build
2220    /// key list of the join, so converting the node in place structurally preserves the
2221    /// negation instead of substituting `true` into it. It is *not* a claim of
2222    /// universal equivalence with the join: `IN`/`NOT IN` are `NULL`-propagating while
2223    /// a hash lookup can be definite on a `NULL` probe key, so a `NULL` key that the
2224    /// lookup keeps can still be dropped by `NOT IN`. The rows below are non-`NULL`,
2225    /// which is the shape the hint is meant for.
2226    #[tokio::test]
2227    async fn not_lookup_becomes_not_in() {
2228        let (schema, filter, values) = real_join_with_keys(8).await;
2229        let lookup = find_expr::<HashTableLookupExpr>(&filter.expr).expect("real lookup");
2230        let not_lookup = Arc::new(NotExpr::new(Arc::clone(&lookup))) as Arc<dyn PhysicalExpr>;
2231
2232        let decoded = decode(
2233            &not_lookup,
2234            &filter.probe_schema,
2235            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2236        );
2237        let display = decoded.to_string();
2238        assert!(
2239            display.starts_with("NOT "),
2240            "NOT must survive the wire: {display}"
2241        );
2242        let lists = in_lists(&decoded);
2243        assert_eq!(lists.len(), 1, "expected one converted InList: {display}");
2244        assert_eq!(in_list_values(&lists[0]), values);
2245
2246        let mut rows = values.clone();
2247        rows.push("miss-not-a-member".to_string());
2248        let batch = evaluation_batch(&schema, &rows);
2249        let (original_selected, decoded_selected) = assert_fail_open(&not_lookup, &decoded, &batch);
2250        assert!(original_selected[..values.len()].iter().all(|kept| !*kept));
2251        assert!(
2252            original_selected[values.len()],
2253            "producer `NOT lookup` keeps the non-member"
2254        );
2255        assert!(decoded_selected[..values.len()].iter().all(|kept| !*kept));
2256        assert!(
2257            decoded_selected[values.len()],
2258            "decoded `NOT IN` keeps the non-member"
2259        );
2260    }
2261
2262    #[tokio::test]
2263    async fn unsupported_float_composite_and_dictionary_keys_keep_only_safe_conjuncts() {
2264        // Float64 keys: the key-list accessor only exposes a single `Utf8` column.
2265        let float_schema = one_column_schema("k", DataType::Float64);
2266        let float_on = key("k", 0);
2267        let float_filter = run_real_hash_join(
2268            2,
2269            Arc::clone(&float_schema),
2270            Arc::clone(&float_schema),
2271            partitions(
2272                &float_schema,
2273                vec![
2274                    vec![Arc::new(Float64Array::from(vec![0.0, -0.0])) as ArrayRef],
2275                    vec![Arc::new(Float64Array::from(vec![1.5])) as ArrayRef],
2276                ],
2277            ),
2278            partitions(
2279                &float_schema,
2280                vec![
2281                    vec![Arc::new(Float64Array::from(vec![0.0, 2.5])) as ArrayRef],
2282                    vec![Arc::new(Float64Array::from(vec![1.5])) as ArrayRef],
2283                ],
2284            ),
2285            vec![(Arc::clone(&float_on), Arc::clone(&float_on))],
2286        )
2287        .await;
2288        assert!(has_expr::<HashTableLookupExpr>(&float_filter.expr));
2289        // The partitioned producer publishes a per-partition `CASE`, so the only
2290        // top-level conjunct carries the membership and there is nothing safe to keep:
2291        // the predicate is reported as unsupported instead of becoming `true`.
2292        assert_unsupported(
2293            DynFilterPayload::from_datafusion_expr(
2294                &float_filter.expr,
2295                REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2296            )
2297            .unwrap_err(),
2298        );
2299
2300        // Composite (two-column) keys: not a single-column membership. Both columns
2301        // take part in the hash partitioning, exactly like a real two-key join.
2302        let composite_schema = Arc::new(Schema::new(vec![
2303            Field::new("trace_id", DataType::Utf8, true),
2304            Field::new("host", DataType::Utf8, true),
2305        ]));
2306        let composite_on = vec![
2307            (key("trace_id", 0), key("trace_id", 0)),
2308            (key("host", 1), key("host", 1)),
2309        ];
2310        let composite_filter = run_real_hash_join(
2311            2,
2312            Arc::clone(&composite_schema),
2313            Arc::clone(&composite_schema),
2314            partitions(
2315                &composite_schema,
2316                vec![
2317                    vec![utf8(&["trace-0", "trace-1"]), utf8(&["host-a", "host-a"])],
2318                    vec![utf8(&["trace-2"]), utf8(&["host-b"])],
2319                ],
2320            ),
2321            partitions(
2322                &composite_schema,
2323                vec![
2324                    vec![utf8(&["trace-0", "trace-9"]), utf8(&["host-a", "host-z"])],
2325                    vec![utf8(&["trace-2"]), utf8(&["host-b"])],
2326                ],
2327            ),
2328            composite_on,
2329        )
2330        .await;
2331        assert!(has_expr::<HashTableLookupExpr>(&composite_filter.expr));
2332        // Same per-partition `CASE` shape as the float case: unsupported, not `true`.
2333        assert_unsupported(
2334            DynFilterPayload::from_datafusion_expr(
2335                &composite_filter.expr,
2336                REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2337            )
2338            .unwrap_err(),
2339        );
2340
2341        // Dictionary keys: not a plain `Utf8` key column.
2342        let dict_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
2343        let dict_schema = one_column_schema("trace_id", dict_type);
2344        let dict_on = key("trace_id", 0);
2345        let mut dict_builder = StringDictionaryBuilder::<Int32Type>::new();
2346        dict_builder.append_value("trace-0");
2347        dict_builder.append_value("trace-1");
2348        let dict_values: ArrayRef = Arc::new(dict_builder.finish());
2349        let dict_filter = run_real_hash_join(
2350            2,
2351            Arc::clone(&dict_schema),
2352            Arc::clone(&dict_schema),
2353            partitions(&dict_schema, vec![vec![Arc::clone(&dict_values)]]),
2354            partitions(&dict_schema, vec![vec![dict_values]]),
2355            vec![(Arc::clone(&dict_on), Arc::clone(&dict_on))],
2356        )
2357        .await;
2358        assert!(has_expr::<HashTableLookupExpr>(&dict_filter.expr));
2359        let decoded = decode(
2360            &dict_filter.expr,
2361            &dict_filter.probe_schema,
2362            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2363        );
2364        // Dictionary keys are not a plain `Utf8` key column either. This producer shape
2365        // is a flat `bounds AND lookup`, so retention keeps the bounds conjunct that
2366        // DataFusion itself published and drops only the membership.
2367        let display = decoded.to_string();
2368        assert!(!has_expr::<HashTableLookupExpr>(&decoded), "{display}");
2369        assert!(!has_expr::<InListExpr>(&decoded), "{display}");
2370        assert!(
2371            display.contains(">="),
2372            "lower bound must survive: {display}"
2373        );
2374        assert!(
2375            display.contains("<="),
2376            "upper bound must survive: {display}"
2377        );
2378    }
2379
2380    #[tokio::test]
2381    async fn producer_paths_encode_150_and_1024_keys() {
2382        // The two producer shapes that can carry a build key list: the static `IN` list
2383        // pushdown (150 and 1024 are the pushdown limits of the runtime experiment) and
2384        // the hash lookup. Neither is capped by an encoder-side value/byte policy: the
2385        // only bound is the payload budget itself.
2386        for key_count in [150, 1024] {
2387            let (schema, filter, values) = real_join_with_keys(key_count).await;
2388            assert!(has_expr::<HashTableLookupExpr>(&filter.expr));
2389            let decoded = decode(
2390                &filter.expr,
2391                &filter.probe_schema,
2392                REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2393            );
2394            let lists = in_lists(&decoded);
2395            assert_eq!(lists.len(), 1, "{key_count} keys: {decoded}");
2396            assert_eq!(in_list_values(&lists[0]), values);
2397
2398            // The static `IN` list pushdown of the same size encodes as well.
2399            let in_list = Arc::new(
2400                InListExpr::try_new(
2401                    key("trace_id", 0),
2402                    values.iter().map(|value| lit(value.clone())).collect(),
2403                    false,
2404                    &schema,
2405                )
2406                .unwrap(),
2407            ) as Arc<dyn PhysicalExpr>;
2408            let decoded = decode(
2409                &in_list,
2410                &filter.probe_schema,
2411                REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2412            );
2413            let lists = in_lists(&decoded);
2414            assert_eq!(lists.len(), 1, "{key_count} static keys: {decoded}");
2415            assert_eq!(in_list_values(&lists[0]), values);
2416        }
2417    }
2418
2419    #[tokio::test]
2420    async fn over_budget_membership_case_is_a_size_refusal() {
2421        let schema = one_column_schema("trace_id", DataType::Utf8);
2422        // Long values so the membership lists dominate the payload.
2423        let long = "t".repeat(256);
2424        let values = (0..24)
2425            .map(|i| format!("{long}-{i:02}"))
2426            .collect::<Vec<_>>();
2427        let borrowed = values.iter().map(String::as_str).collect::<Vec<_>>();
2428        let build = partitions(&schema, vec![vec![utf8(&borrowed)]]);
2429        let probe = partitions(&schema, vec![vec![utf8(&borrowed)]]);
2430        let trace_id = key("trace_id", 0);
2431        let filter = run_real_hash_join(
2432            3,
2433            Arc::clone(&schema),
2434            Arc::clone(&schema),
2435            build,
2436            probe,
2437            vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))],
2438        )
2439        .await;
2440        assert!(has_expr::<HashTableLookupExpr>(&filter.expr));
2441
2442        // The real payload budget carries all three branch memberships exactly.
2443        let decoded = decode(
2444            &filter.expr,
2445            &filter.probe_schema,
2446            REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES,
2447        );
2448        assert_eq!(in_lists(&decoded).len(), 3);
2449        let case = decoded.downcast_ref::<CaseExpr>().expect("CASE preserved");
2450        assert_eq!(case.when_then_expr().len(), 3);
2451
2452        // The whole predicate is one top-level `CASE` conjunct that carries the
2453        // membership, so a budget that only fits `true` has nothing safe to keep:
2454        // membership is never rewritten inside `CASE` and the payload is an explicit
2455        // error instead of an always-true filter. The predicates *are* representable, they
2456        // only do not fit, so the refusal is a size one and not "no wire form".
2457        let true_size = encode_physical_expr_to_bytes(&lit(true)).unwrap().len();
2458        assert!(true_size < REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES);
2459        assert_too_large(
2460            DynFilterPayload::from_datafusion_expr(&filter.expr, true_size).unwrap_err(),
2461        );
2462    }
2463
2464    #[test]
2465    fn over_budget_negation_is_a_size_refusal() {
2466        let schema = Arc::new(Schema::new(vec![Field::new("host", DataType::Utf8, false)]));
2467        let host = Arc::new(Column::new("host", 0)) as Arc<dyn PhysicalExpr>;
2468        let long = "h".repeat(256);
2469        let in_list = Arc::new(
2470            InListExpr::try_new(
2471                Arc::clone(&host),
2472                (0..16).map(|i| lit(format!("{long}-{i:02}"))).collect(),
2473                false,
2474                &schema,
2475            )
2476            .unwrap(),
2477        ) as Arc<dyn PhysicalExpr>;
2478        // `NOT (host IN (...))`: dropping the list in place would evaluate `NOT true`
2479        // = false and drop every row, so the whole conjunct is dropped. Nothing is left
2480        // to ship and the predicate itself is representable, so the refusal is a size one.
2481        let not_in = Arc::new(NotExpr::new(Arc::clone(&in_list))) as Arc<dyn PhysicalExpr>;
2482        let true_size = encode_physical_expr_to_bytes(&lit(true)).unwrap().len();
2483
2484        assert_too_large(DynFilterPayload::from_datafusion_expr(&not_in, true_size).unwrap_err());
2485    }
2486
2487    #[tokio::test]
2488    async fn recovered_payload_uses_only_existing_wire_variants() {
2489        let schema = one_column_schema("trace_id", DataType::Utf8);
2490        let (build, probe, values) = utf8_join(3);
2491        let trace_id = key("trace_id", 0);
2492        let filter = run_real_hash_join(
2493            3,
2494            Arc::clone(&schema),
2495            Arc::clone(&schema),
2496            build,
2497            probe,
2498            vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))],
2499        )
2500        .await;
2501        let max = REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES;
2502
2503        // The recovered payload decodes with the default extension codec, which rejects
2504        // every expression variant it does not know: a new wire variant would fail here.
2505        let payload = DynFilterPayload::from_datafusion_expr(&filter.expr, max).unwrap();
2506        let bytes = match &payload {
2507            DynFilterPayload::Datafusion(bytes) => bytes.clone(),
2508        };
2509        let decoded = payload
2510            .decode_datafusion_expr(&TaskContext::default(), &filter.probe_schema, max)
2511            .unwrap();
2512        assert_eq!(in_lists(&decoded).len(), 3);
2513        assert_eq!(
2514            hash_seed(
2515                filter
2516                    .expr
2517                    .downcast_ref::<CaseExpr>()
2518                    .unwrap()
2519                    .expr()
2520                    .unwrap()
2521            ),
2522            hash_seed(decoded.downcast_ref::<CaseExpr>().unwrap().expr().unwrap()),
2523            "HashExpr routing seed must survive the wire"
2524        );
2525
2526        // Receivers still accept a plain `true` payload: an older sender could publish one,
2527        // and a producer may legitimately publish `true` itself. This transport no longer
2528        // synthesizes `true` as an encoding fallback, so the decode-side compatibility stays
2529        // while the encode-side fallback is gone.
2530        let legacy_bytes = encode_physical_expr_to_bytes(&lit(true)).unwrap();
2531        assert!(legacy_bytes.len() < bytes.len());
2532        let legacy_decoded = DynFilterPayload::Datafusion(legacy_bytes)
2533            .decode_datafusion_expr(&TaskContext::default(), &filter.probe_schema, max)
2534            .unwrap();
2535        assert_eq!(legacy_decoded.to_string(), "true");
2536        let mut rows = values.clone();
2537        rows.push("miss-not-a-member".to_string());
2538        let batch = evaluation_batch(&schema, &rows);
2539        assert_fail_open(&filter.expr, &legacy_decoded, &batch);
2540    }
2541}