Skip to main content

vortex_scan/execution/pipeline/
port.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Ports: queues of batches with one sink and one source, kept in an arena the scan owns so a
5//! port can outlive the pipeline or split at either end.
6//!
7//! A port has a consumer for as long as anything can be pushed into it: its source goes only
8//! once the sink has closed the port and the source has drained it, or once the port is
9//! detached from its sink's outlets, so no push ever reaches a port nobody will read.
10
11use std::collections::VecDeque;
12
13use vortex_array::ArrayRef;
14
15use crate::execution::pipeline::DEFAULT_CAPACITY;
16
17/// Identifies a port in the scan's arena.
18pub(crate) type PortId = usize;
19
20/// Identifies a pipeline in the scan's table.
21pub(crate) type PipelineId = usize;
22
23/// The source end of a port: who takes its batches.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub(crate) enum SourceEnd {
26    /// Nobody yet: a share's port waiting for the pipeline it was made for, or a port whose
27    /// source has gone.
28    Unclaimed,
29    /// The source of this pipeline, which reads the port as one of its inlets.
30    Pipeline { id: PipelineId, inlet: usize },
31    /// The scan, reading the output of the split's stage running in this slot.
32    Scan(usize),
33}
34
35/// A queue of batches with one sink and one source.
36///
37/// The first batch is inline: a segment scan commonly emits only one batch. Additional batches
38/// use a deque, whose buffer is retained when the port is reused.
39pub(crate) struct Queue {
40    front: Option<ArrayRef>,
41    batches: VecDeque<ArrayRef>,
42    /// Batches the queue may hold before its sink is blocked.
43    capacity: usize,
44    /// The sink will push nothing more.
45    closed: bool,
46    /// The sink appended data or closed this port since its last run was settled.
47    changed: bool,
48    /// The pipeline whose sink pushes into this port; none once closed.
49    pub(crate) sink: Option<PipelineId>,
50    pub(crate) source: SourceEnd,
51    /// The source will take nothing more. Set only once nothing more can be pushed, so the
52    /// slot is freed as soon as the port is also closed.
53    source_gone: bool,
54    /// The slot is free for reuse.
55    free: bool,
56}
57
58impl Queue {
59    fn new(capacity: usize, sink: Option<PipelineId>, source: SourceEnd) -> Self {
60        Self {
61            front: None,
62            batches: VecDeque::new(),
63            capacity: capacity.max(1),
64            closed: false,
65            changed: false,
66            sink,
67            source,
68            source_gone: false,
69            free: false,
70        }
71    }
72
73    pub(crate) fn has_room(&self) -> bool {
74        self.len() < self.capacity
75    }
76
77    pub(crate) fn closed(&self) -> bool {
78        self.closed
79    }
80
81    /// Whether the sink is never blocked by it.
82    #[cfg(debug_assertions)]
83    pub(crate) fn unbounded(&self) -> bool {
84        self.capacity == usize::MAX
85    }
86
87    pub(crate) fn len(&self) -> usize {
88        usize::from(self.front.is_some()) + self.batches.len()
89    }
90
91    pub(crate) fn take_changed(&mut self) -> bool {
92        std::mem::take(&mut self.changed)
93    }
94
95    pub(crate) fn pop(&mut self) -> Option<ArrayRef> {
96        std::mem::replace(&mut self.front, self.batches.pop_front())
97    }
98}
99
100/// The reading side of a port, borrowed for one call.
101pub struct Inlet<'a> {
102    queue: &'a mut Queue,
103}
104
105impl Inlet<'_> {
106    /// The oldest batch, in place, so the source can slice it down without removing it.
107    pub fn peek_mut(&mut self) -> Option<&mut ArrayRef> {
108        self.queue.front.as_mut()
109    }
110
111    /// The oldest batch, removed. Removing a batch is what frees its slot.
112    pub fn take(&mut self) -> Option<ArrayRef> {
113        self.queue.pop()
114    }
115
116    /// Whether the sink has finished. Closed and empty is the end of the inlet.
117    pub fn closed(&self) -> bool {
118        self.queue.closed
119    }
120
121    /// Whether no batch is queued.
122    pub fn is_empty(&self) -> bool {
123        self.queue.front.is_none()
124    }
125
126    /// Batches queued.
127    pub fn len(&self) -> usize {
128        self.queue.len()
129    }
130
131    /// Whether the sink can push no more until the source takes a batch. An unbounded inlet
132    /// counts as full at the default capacity, so a source waiting for it to fill still runs.
133    pub fn full(&self) -> bool {
134        self.queue.len() >= self.queue.capacity.min(DEFAULT_CAPACITY)
135    }
136
137    /// Rows queued, over every batch.
138    pub fn rows(&self) -> usize {
139        self.queue
140            .front
141            .iter()
142            .chain(self.queue.batches.iter())
143            .map(|batch| batch.len())
144            .sum()
145    }
146}
147
148/// A growable table that never moves its entries: entries live in blocks of fixed size, so
149/// adding one never copies the others, as a vector's growth does.
150pub(crate) struct Slab<T> {
151    blocks: Vec<Vec<T>>,
152    len: usize,
153}
154
155const BLOCK: usize = 64;
156
157impl<T> Default for Slab<T> {
158    fn default() -> Self {
159        Self {
160            blocks: Vec::new(),
161            len: 0,
162        }
163    }
164}
165
166impl<T> Slab<T> {
167    #[cfg(test)]
168    pub(crate) fn len(&self) -> usize {
169        self.len
170    }
171
172    /// Adds `value`, returning its index.
173    pub(crate) fn push(&mut self, value: T) -> usize {
174        if self.len.is_multiple_of(BLOCK) {
175            self.blocks.push(Vec::with_capacity(BLOCK));
176        }
177        let index = self.len;
178        self.blocks[index / BLOCK].push(value);
179        self.len += 1;
180        index
181    }
182
183    pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
184        self.blocks.iter().flatten()
185    }
186}
187
188impl<T> std::ops::Index<usize> for Slab<T> {
189    type Output = T;
190
191    fn index(&self, index: usize) -> &T {
192        &self.blocks[index / BLOCK][index % BLOCK]
193    }
194}
195
196impl<T> std::ops::IndexMut<usize> for Slab<T> {
197    fn index_mut(&mut self, index: usize) -> &mut T {
198        &mut self.blocks[index / BLOCK][index % BLOCK]
199    }
200}
201
202/// Every port of a scan. Slots are reused once a port's sink has closed it and its source has
203/// gone, so no pipeline still refers to it.
204#[derive(Default)]
205pub(crate) struct Arena {
206    queues: Slab<Queue>,
207    free: Vec<PortId>,
208}
209
210impl Arena {
211    pub(crate) fn create(
212        &mut self,
213        capacity: usize,
214        sink: Option<PipelineId>,
215        source: SourceEnd,
216    ) -> PortId {
217        match self.free.pop() {
218            Some(id) => {
219                // A freed slot keeps any overflow buffer for reuse.
220                let queue = &mut self.queues[id];
221                let capacity = capacity.max(1);
222                queue.capacity = capacity;
223                queue.closed = false;
224                queue.changed = false;
225                queue.sink = sink;
226                queue.source = source;
227                queue.source_gone = false;
228                queue.free = false;
229                id
230            }
231            None => self.queues.push(Queue::new(capacity, sink, source)),
232        }
233    }
234
235    pub(crate) fn get(&self, id: PortId) -> &Queue {
236        &self.queues[id]
237    }
238
239    pub(crate) fn get_mut(&mut self, id: PortId) -> &mut Queue {
240        &mut self.queues[id]
241    }
242
243    pub(crate) fn inlet(&mut self, id: PortId) -> Inlet<'_> {
244        Inlet {
245            queue: &mut self.queues[id],
246        }
247    }
248
249    pub(crate) fn has_room(&self, id: PortId) -> bool {
250        self.queues[id].has_room()
251    }
252
253    /// Appends a batch. Empty batches are dropped.
254    pub(crate) fn push(&mut self, id: PortId, batch: ArrayRef) {
255        let queue = &mut self.queues[id];
256        debug_assert!(
257            !queue.source_gone && !queue.closed,
258            "push into port {id} with no consumer"
259        );
260        if !batch.is_empty() {
261            if queue.front.is_none() {
262                queue.front = Some(batch);
263            } else {
264                queue.batches.push_back(batch);
265            }
266            queue.changed = true;
267        }
268    }
269
270    /// The sink will push nothing more.
271    pub(crate) fn close(&mut self, id: PortId) {
272        let queue = &mut self.queues[id];
273        queue.changed |= !queue.closed;
274        queue.closed = true;
275        queue.sink = None;
276        self.maybe_free(id);
277    }
278
279    /// The source will take nothing more: what is queued is dropped. Nothing more may be
280    /// pushed, so the sink must have closed the port or be about to, as a retiring pipeline's
281    /// inlets' sinks have.
282    pub(crate) fn drop_source(&mut self, id: PortId) {
283        let queue = &mut self.queues[id];
284        queue.source_gone = true;
285        queue.source = SourceEnd::Unclaimed;
286        queue.front = None;
287        queue.batches.clear();
288        self.maybe_free(id);
289    }
290
291    fn maybe_free(&mut self, id: PortId) {
292        let queue = &mut self.queues[id];
293        if queue.closed && queue.source_gone && !queue.free {
294            queue.free = true;
295            queue.front = None;
296            queue.batches.clear();
297            self.free.push(id);
298        }
299    }
300
301    /// Ports in use.
302    #[cfg(test)]
303    pub(crate) fn live(&self) -> usize {
304        self.queues.len() - self.free.len()
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use rstest::rstest;
311    use vortex_array::ArrayRef;
312    use vortex_array::IntoArray;
313    use vortex_buffer::buffer;
314
315    use super::Arena;
316    use super::SourceEnd;
317
318    #[rstest]
319    #[case::single(1)]
320    #[case::bounded(4)]
321    #[case::unbounded(usize::MAX)]
322    fn queued_batches_keep_order_and_reused_ports_are_empty(#[case] capacity: usize) {
323        let mut arena = Arena::default();
324        let port = arena.create(capacity, None, SourceEnd::Scan(0));
325        let arrays: Vec<_> = (0..capacity.min(4))
326            .map(|i| buffer![i as u64].into_array())
327            .collect();
328        for array in &arrays {
329            assert!(arena.has_room(port));
330            arena.push(port, array.clone());
331        }
332        assert_eq!(arena.inlet(port).len(), arrays.len());
333        assert_eq!(arena.inlet(port).rows(), arrays.len());
334        arena.close(port);
335        for expected in arrays {
336            let actual = arena.inlet(port).take().expect("queued batch");
337            assert!(ArrayRef::ptr_eq(&actual, &expected));
338        }
339        assert!(arena.inlet(port).is_empty());
340        arena.drop_source(port);
341        let reused = arena.create(1, None, SourceEnd::Scan(0));
342        assert_eq!(reused, port);
343        assert!(arena.inlet(reused).is_empty());
344        assert!(arena.has_room(reused));
345    }
346}