Skip to main content

vortex_scan/plan/builtins/concat/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4pub(crate) mod execute;
5
6use std::borrow::Cow;
7use std::ops::Range;
8use std::sync::Arc;
9
10use vortex_array::EmptyMetadata;
11use vortex_array::dtype::DType;
12use vortex_error::VortexResult;
13use vortex_error::vortex_bail;
14use vortex_error::vortex_ensure_eq;
15use vortex_mask::Mask;
16use vortex_session::VortexSession;
17use vortex_session::registry::CachedId;
18
19use crate::execution::operators::ConcatSource;
20use crate::execution::pipeline::Chain;
21use crate::execution::pipeline::Compiler;
22use crate::execution::pipeline::overlapping;
23use crate::plan::Eval;
24use crate::plan::EvalPlan;
25use crate::plan::LazyPlanRef;
26use crate::plan::Plan;
27use crate::plan::PlanId;
28use crate::plan::PlanParts;
29use crate::plan::PlanRef;
30use crate::plan::PlanSlots;
31use crate::plan::PlanVTable;
32use crate::plan::optimizer::PlanParentReduceRule;
33use crate::plan::selection::selected_slice;
34
35/// Concatenates its children row-wise.
36#[derive(Clone, Debug)]
37pub struct Concat;
38
39/// Row offsets of each concatenated child.
40#[derive(Clone, Debug)]
41pub struct ConcatData {
42    row_offsets: Arc<[u64]>,
43}
44
45/// A plan that concatenates its children row-wise.
46pub type ConcatPlan = Plan<Concat>;
47
48impl ConcatPlan {
49    /// Creates a concatenation from potentially unbuilt slots, one per chunk, without
50    /// validation.
51    ///
52    /// # Safety
53    ///
54    /// Every slot must be present with `dtype`; `row_offsets` must contain the cumulative row
55    /// offset of every chunk; and the sum of all chunk row counts must equal `row_count` without
56    /// overflow.
57    pub unsafe fn from_slots_unchecked(
58        dtype: DType,
59        row_count: u64,
60        row_offsets: Arc<[u64]>,
61        slots: PlanSlots,
62    ) -> Self {
63        PlanParts {
64            vtable: Concat,
65            dtype,
66            row_count,
67            slots,
68            data: ConcatData { row_offsets },
69        }
70        .into_typed()
71    }
72
73    /// Creates a concatenation over `children`.
74    ///
75    /// Every child must produce `dtype`, and the row domain is the sum of the child row counts.
76    pub fn try_new(dtype: DType, children: Vec<PlanRef>) -> VortexResult<Self> {
77        let mut row_offsets = Vec::with_capacity(children.len());
78        let mut row_count = 0u64;
79        for child in &children {
80            if child.dtype() != &dtype {
81                vortex_bail!(
82                    "Concat child dtype {} does not match {dtype}",
83                    child.dtype()
84                );
85            }
86            row_offsets.push(row_count);
87            row_count = row_count
88                .checked_add(child.row_count())
89                .ok_or_else(|| vortex_error::vortex_err!("Concat row count overflow"))?;
90        }
91        // SAFETY: Child dtypes and the checked cumulative row metadata were validated above.
92        Ok(unsafe {
93            Self::from_slots_unchecked(dtype, row_count, row_offsets.into(), children.into())
94        })
95    }
96
97    /// Returns the first row of each child within this plan's row domain.
98    pub fn row_offsets(&self) -> &[u64] {
99        &self.data().row_offsets
100    }
101
102    /// Defers independent child rewrites until a scan reaches the child. Row offsets remain
103    /// valid because each materialized result must preserve its child's row count.
104    pub(crate) fn map_chunks(
105        &self,
106        dtype: DType,
107        map: impl Fn(PlanRef) -> VortexResult<PlanRef> + Send + Sync + 'static,
108    ) -> Self {
109        let map = Arc::new(map);
110        let slots = self
111            .slots()
112            .iter()
113            .map(|slot| {
114                let chunk = slot.clone()?;
115                let map = Arc::clone(&map);
116                let dtype = dtype.clone();
117                Some(LazyPlanRef::lazy(move || {
118                    let chunk = chunk.get()?;
119                    let mapped = map(chunk.clone())?;
120                    vortex_ensure_eq!(mapped.dtype(), &dtype);
121                    vortex_ensure_eq!(mapped.row_count(), chunk.row_count());
122                    Ok(mapped)
123                }))
124            })
125            .collect();
126        PlanParts {
127            vtable: Concat,
128            dtype,
129            row_count: self.row_count(),
130            data: self.data().clone(),
131            slots,
132        }
133        .into_typed()
134    }
135}
136
137impl PlanVTable for Concat {
138    type PlanData = ConcatData;
139    type Metadata = EmptyMetadata;
140
141    fn id(&self) -> PlanId {
142        static ID: CachedId = CachedId::new("vortex.plan.concat");
143        *ID
144    }
145
146    fn metadata(_plan: &Plan<Self>) -> Option<Self::Metadata> {
147        // Row offsets are derived from the children, so nothing needs storing.
148        Some(EmptyMetadata)
149    }
150
151    fn with_slots(
152        plan: &Plan<Self>,
153        slots: &PlanSlots,
154        data: &mut Self::PlanData,
155    ) -> VortexResult<()> {
156        slots.check_len("Concat", plan.slots().len())?;
157
158        let mut row_offsets = Vec::with_capacity(slots.len());
159        let mut row_count = 0u64;
160        for index in 0..slots.len() {
161            let child = slots.required(index)?;
162            if child.dtype() != plan.dtype() {
163                vortex_bail!(
164                    "Concat child dtype {} does not match {}",
165                    child.dtype(),
166                    plan.dtype()
167                );
168            }
169            row_offsets.push(row_count);
170            row_count = row_count
171                .checked_add(child.row_count())
172                .ok_or_else(|| vortex_error::vortex_err!("Concat row count overflow"))?;
173        }
174        if row_count != plan.row_count() {
175            vortex_bail!(
176                "Concat children have {row_count} rows but the plan has {}",
177                plan.row_count()
178            );
179        }
180        data.row_offsets = row_offsets.into();
181        Ok(())
182    }
183
184    fn slot_name(_plan: &Plan<Self>, slot: usize) -> Cow<'_, str> {
185        Cow::Owned(format!("chunks[{slot}]"))
186    }
187
188    fn compile(
189        plan: &Plan<Self>,
190        rows: Range<u64>,
191        mask: &Mask,
192        compiler: &mut Compiler<'_>,
193    ) -> VortexResult<Option<Chain>> {
194        let capacity = if mask.all_true() {
195            overlapping(plan, &rows).size_hint().1.unwrap_or(0)
196        } else {
197            0
198        };
199        let mut chains = Vec::with_capacity(capacity);
200        for (index, start, local) in overlapping(plan, &rows) {
201            let Some((span, local_mask)) = selected_slice(
202                mask,
203                usize::try_from(local.start - rows.start)?
204                    ..usize::try_from(local.end - rows.start)?,
205            ) else {
206                continue;
207            };
208            let chunk = plan.slot_required(index)?;
209            if let Some(chain) = compiler.compile(
210                &chunk,
211                rows.start + span.start as u64 - start..rows.start + span.end as u64 - start,
212                &local_mask,
213            )? {
214                chains.push(chain);
215            }
216        }
217        Ok(match chains.len() {
218            0 => None,
219            // Rows inside one chunk are that chunk's rows: no concatenation is built.
220            1 => chains.pop(),
221            count => Some(compiler.join(chains, ConcatSource::new(count))),
222        })
223    }
224}
225
226/// Pushes an expression into every chunk of a [`Concat`].
227#[derive(Debug)]
228pub(crate) struct ExpressionConcatRule;
229
230impl PlanParentReduceRule<Concat> for ExpressionConcatRule {
231    type Parent = Eval;
232
233    fn reduce_parent(
234        &self,
235        child: &Plan<Concat>,
236        parent: &Plan<Eval>,
237        _child_idx: usize,
238        _session: &VortexSession,
239    ) -> VortexResult<Option<PlanRef>> {
240        let expression = parent.expression().clone();
241        Ok(Some(
242            child
243                .map_chunks(expression.dtype().clone(), move |chunk| {
244                    Ok(EvalPlan::try_new(expression.clone(), chunk)?.into_plan())
245                })
246                .into_plan(),
247        ))
248    }
249}