uqa-execution 0.5.3

Volcano physical operators with row-batch pipelines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Spillable ordered aggregate-value buffering.

use super::ordering::{
    compare_sort_keys, compare_sort_keys_with_catalog, minimum_by, sort_records,
};
use uqa_sql::expr::enums::{EnumComparisonState, EnumLabelCatalog};

use super::{
    BufRead, BufReader, BufWriter, File, Ordering, SQLError, Seek, SeekFrom, Value, Write,
    AGGREGATE_MERGE_FAN_IN,
};

#[derive(Clone, serde::Deserialize, serde::Serialize)]
pub struct AggregateValueRecord {
    pub(super) value: Value,
    pub(super) sort_keys: Vec<super::ordering::AggregateSortKey>,
    pub(super) sequence: u64,
}

pub struct JsonSpillRun {
    pub(super) file: uqa_storage::temporary_file::TemporaryFile,
    pub(super) max_record_bytes: usize,
}

pub fn write_json_spill_record(
    writer: &mut impl Write,
    value: &impl serde::Serialize,
    description: &str,
) -> Result<usize, SQLError> {
    let payload = serde_json::to_vec(value).map_err(|error| {
        SQLError::Internal(format!("failed to serialize {description}: {error}"))
    })?;
    let record_bytes = payload
        .len()
        .checked_add(1)
        .ok_or_else(|| SQLError::Internal(format!("{description} size overflow")))?;
    writer
        .write_all(&payload)
        .map_err(|error| SQLError::Internal(format!("failed to write {description}: {error}")))?;
    writer
        .write_all(b"\n")
        .map_err(|error| SQLError::Internal(format!("failed to write {description}: {error}")))?;
    Ok(record_bytes)
}

pub fn read_bounded_json_spill_record<R: BufRead>(
    reader: &mut R,
    max_record_bytes: usize,
    description: &str,
) -> Result<Option<Vec<u8>>, SQLError> {
    let mut record = Vec::new();
    loop {
        let (chunk_len, terminated) = {
            let available = reader.fill_buf().map_err(|error| {
                SQLError::Internal(format!("failed to read {description}: {error}"))
            })?;
            if available.is_empty() {
                if record.is_empty() {
                    return Ok(None);
                }
                return Err(SQLError::Internal(format!(
                    "truncated {description}: missing record delimiter"
                )));
            }
            match available.iter().position(|byte| *byte == b'\n') {
                Some(index) => (index + 1, true),
                None => (available.len(), false),
            }
        };
        let next_len = record
            .len()
            .checked_add(chunk_len)
            .ok_or_else(|| SQLError::Internal(format!("{description} length overflow")))?;
        if next_len > max_record_bytes {
            return Err(SQLError::Internal(format!(
                "{description} exceeds recorded maximum of {max_record_bytes} bytes"
            )));
        }
        record.try_reserve(chunk_len).map_err(|error| {
            SQLError::Internal(format!(
                "unable to allocate {chunk_len} more bytes for {description}: {error}"
            ))
        })?;
        let available = reader.fill_buf().map_err(|error| {
            SQLError::Internal(format!("failed to read {description}: {error}"))
        })?;
        record.extend_from_slice(&available[..chunk_len]);
        reader.consume(chunk_len);
        if terminated {
            let delimiter = record.pop();
            debug_assert_eq!(delimiter, Some(b'\n'));
            return Ok(Some(record));
        }
    }
}

pub struct AggregateValueBuffer {
    pub(super) rows: Vec<AggregateValueRecord>,
    pub(super) runs: Vec<JsonSpillRun>,
    pub(super) next_sequence: u64,
    pub(super) budget_bytes: usize,
    pub(super) memory_bytes: usize,
    pub(super) comparison_states: Option<std::sync::Arc<[EnumComparisonState]>>,
}

impl Default for AggregateValueBuffer {
    fn default() -> Self {
        Self::new(64 * 1024 * 1024)
    }
}

impl AggregateValueBuffer {
    pub(super) fn new(budget_bytes: usize) -> Self {
        Self {
            rows: Vec::new(),
            runs: Vec::new(),
            next_sequence: 0,
            budget_bytes: budget_bytes.max(1),
            memory_bytes: 0,
            comparison_states: None,
        }
    }

    pub(super) fn push(
        &mut self,
        value: Value,
        sort_keys: Vec<super::ordering::AggregateSortKey>,
        enums: Option<&dyn EnumLabelCatalog>,
    ) -> Result<(), SQLError> {
        if !sort_keys.is_empty()
            && self.comparison_states.is_none()
            && enums.is_some_and(EnumLabelCatalog::has_enum_types)
        {
            self.comparison_states = Some(
                (0..sort_keys.len())
                    .map(|_| EnumComparisonState::default())
                    .collect(),
            );
        }
        let next_sequence = self
            .next_sequence
            .checked_add(1)
            .ok_or_else(|| SQLError::Internal("aggregate value sequence overflow".into()))?;
        let record = AggregateValueRecord {
            value,
            sort_keys,
            sequence: self.next_sequence,
        };
        let bytes = serde_json::to_vec(&record)
            .map_err(|error| {
                SQLError::Internal(format!("failed to size aggregate value: {error}"))
            })?
            .len()
            .checked_add(1)
            .ok_or_else(|| SQLError::Internal("aggregate value size overflow".into()))?;
        if !self.rows.is_empty()
            && self
                .memory_bytes
                .checked_add(bytes)
                .is_none_or(|total| total > self.budget_bytes)
        {
            self.flush_run(enums)?;
        }
        let next_memory_bytes = self
            .memory_bytes
            .checked_add(bytes)
            .ok_or_else(|| SQLError::Internal("aggregate value size overflow".into()))?;
        self.rows.push(record);
        self.memory_bytes = next_memory_bytes;
        self.next_sequence = next_sequence;
        // One value is indivisible. It passes through memory once and is
        // immediately written when its encoding alone exceeds the budget.
        if self.memory_bytes > self.budget_bytes {
            self.flush_run(enums)?;
        }
        Ok(())
    }

    pub(super) fn ordered_values(
        &self,
        enums: Option<&dyn EnumLabelCatalog>,
    ) -> Result<Vec<Value>, SQLError> {
        let capacity = usize::try_from(self.next_sequence).map_err(|_| {
            SQLError::Internal("aggregate value count exceeds address space".into())
        })?;
        let mut values = Vec::new();
        values.try_reserve_exact(capacity).map_err(|error| {
            SQLError::Internal(format!(
                "unable to allocate aggregate result for {capacity} values: {error}"
            ))
        })?;
        self.for_each_ordered(enums, |record| {
            values.push(record.value);
            Ok(())
        })?;
        Ok(values)
    }

    pub(super) fn for_each_ordered(
        &self,
        enums: Option<&dyn EnumLabelCatalog>,
        mut visit: impl FnMut(AggregateValueRecord) -> Result<(), SQLError>,
    ) -> Result<(), SQLError> {
        let mut memory = self.rows.clone();
        sort_records(&mut memory, |left, right| {
            compare_aggregate_value_records_with_catalog(
                left,
                right,
                enums,
                self.comparison_states.as_deref().unwrap_or_default(),
            )
        })?;
        let mut readers = Vec::with_capacity(self.runs.len() + usize::from(!memory.is_empty()));
        if !memory.is_empty() {
            readers.push(AggregateValueRunReader::memory(memory));
        }
        for run in &self.runs {
            readers.push(AggregateValueRunReader::file(run)?);
        }
        while let Some((index, _)) = minimum_by(
            readers
                .iter()
                .enumerate()
                .filter_map(|(index, reader)| reader.current().map(|record| (index, record))),
            |(_, left), (_, right)| {
                compare_aggregate_value_records_with_catalog(
                    left,
                    right,
                    enums,
                    self.comparison_states.as_deref().unwrap_or_default(),
                )
            },
        )? {
            visit(readers[index].take_current()?)?;
        }
        Ok(())
    }

    pub(super) fn flush_run(
        &mut self,
        enums: Option<&dyn EnumLabelCatalog>,
    ) -> Result<(), SQLError> {
        if self.rows.is_empty() {
            return Ok(());
        }
        sort_records(&mut self.rows, |left, right| {
            compare_aggregate_value_records_with_catalog(
                left,
                right,
                enums,
                self.comparison_states.as_deref().unwrap_or_default(),
            )
        })?;
        let mut run = uqa_storage::temporary_file::TemporaryFile::new().map_err(|err| {
            SQLError::Internal(format!("failed to create aggregate spill file: {err}"))
        })?;
        let mut max_record_bytes = 0;
        {
            let mut writer = BufWriter::new(run.as_file_mut());
            for row in self.rows.drain(..) {
                let record_bytes =
                    write_json_spill_record(&mut writer, &row, "aggregate spill row")?;
                max_record_bytes = max_record_bytes.max(record_bytes);
            }
            writer.flush().map_err(|err| {
                SQLError::Internal(format!("failed to flush aggregate spill file: {err}"))
            })?;
        }
        run.as_file_mut().seek(SeekFrom::Start(0)).map_err(|err| {
            SQLError::Internal(format!("failed to rewind aggregate spill file: {err}"))
        })?;
        self.runs.push(JsonSpillRun {
            file: run,
            max_record_bytes,
        });
        self.memory_bytes = 0;
        if self.runs.len() >= AGGREGATE_MERGE_FAN_IN {
            let inputs = self
                .runs
                .drain(..AGGREGATE_MERGE_FAN_IN)
                .collect::<Vec<_>>();
            self.runs.push(merge_aggregate_value_runs_with_catalog(
                inputs,
                enums,
                self.comparison_states.as_deref().unwrap_or_default(),
            )?);
        }
        Ok(())
    }
}

pub enum AggregateValueRunReader {
    Memory {
        rows: std::vec::IntoIter<AggregateValueRecord>,
        current: Option<AggregateValueRecord>,
    },
    File {
        reader: BufReader<File>,
        current: Option<AggregateValueRecord>,
        max_record_bytes: usize,
    },
}

impl AggregateValueRunReader {
    pub(super) fn memory(rows: Vec<AggregateValueRecord>) -> Self {
        let mut rows = rows.into_iter();
        let current = rows.next();
        Self::Memory { rows, current }
    }

    pub(super) fn file(run: &JsonSpillRun) -> Result<Self, SQLError> {
        let file = run.file.reopen().map_err(|error| {
            SQLError::Internal(format!("failed to reopen aggregate spill file: {error}"))
        })?;
        let mut reader = BufReader::new(file);
        let current = read_aggregate_value_record(&mut reader, run.max_record_bytes)?;
        Ok(Self::File {
            reader,
            current,
            max_record_bytes: run.max_record_bytes,
        })
    }

    pub(super) fn current(&self) -> Option<&AggregateValueRecord> {
        match self {
            Self::Memory { current, .. } | Self::File { current, .. } => current.as_ref(),
        }
    }

    pub(super) fn take_current(&mut self) -> Result<AggregateValueRecord, SQLError> {
        match self {
            Self::Memory { rows, current } => {
                let record = current
                    .take()
                    .ok_or_else(|| SQLError::Internal("aggregate memory run exhausted".into()))?;
                *current = rows.next();
                Ok(record)
            }
            Self::File {
                reader,
                current,
                max_record_bytes,
            } => {
                let record = current
                    .take()
                    .ok_or_else(|| SQLError::Internal("aggregate spill run exhausted".into()))?;
                *current = read_aggregate_value_record(reader, *max_record_bytes)?;
                Ok(record)
            }
        }
    }
}

pub fn read_aggregate_value_record(
    reader: &mut impl std::io::BufRead,
    max_record_bytes: usize,
) -> Result<Option<AggregateValueRecord>, SQLError> {
    let Some(record) =
        read_bounded_json_spill_record(reader, max_record_bytes, "aggregate spill row")?
    else {
        return Ok(None);
    };
    serde_json::from_slice(&record).map(Some).map_err(|error| {
        SQLError::Internal(format!(
            "failed to deserialize aggregate spill row: {error}"
        ))
    })
}

pub fn merge_aggregate_value_runs(runs: Vec<JsonSpillRun>) -> Result<JsonSpillRun, SQLError> {
    merge_aggregate_value_runs_with_catalog(runs, None, &[])
}

fn merge_aggregate_value_runs_with_catalog(
    runs: Vec<JsonSpillRun>,
    enums: Option<&dyn EnumLabelCatalog>,
    states: &[EnumComparisonState],
) -> Result<JsonSpillRun, SQLError> {
    let mut readers = runs
        .iter()
        .map(AggregateValueRunReader::file)
        .collect::<Result<Vec<_>, _>>()?;
    let mut output = uqa_storage::temporary_file::TemporaryFile::new().map_err(|error| {
        SQLError::Internal(format!("failed to create aggregate merge run: {error}"))
    })?;
    let mut max_record_bytes = 0;
    {
        let mut writer = BufWriter::new(output.as_file_mut());
        while let Some((index, _)) = minimum_by(
            readers
                .iter()
                .enumerate()
                .filter_map(|(index, reader)| reader.current().map(|record| (index, record))),
            |(_, left), (_, right)| {
                compare_aggregate_value_records_with_catalog(left, right, enums, states)
            },
        )? {
            let record = readers[index].take_current()?;
            let record_bytes =
                write_json_spill_record(&mut writer, &record, "aggregate merge row")?;
            max_record_bytes = max_record_bytes.max(record_bytes);
        }
        writer.flush().map_err(|error| {
            SQLError::Internal(format!("failed to flush aggregate merge run: {error}"))
        })?;
    }
    output
        .as_file_mut()
        .seek(SeekFrom::Start(0))
        .map_err(|error| {
            SQLError::Internal(format!("failed to rewind aggregate merge run: {error}"))
        })?;
    Ok(JsonSpillRun {
        file: output,
        max_record_bytes,
    })
}

pub fn compare_aggregate_value_records(
    a: &AggregateValueRecord,
    b: &AggregateValueRecord,
) -> Result<Ordering, SQLError> {
    let ordering = compare_sort_keys(&a.sort_keys, &b.sort_keys)?;
    Ok(ordering.then_with(|| a.sequence.cmp(&b.sequence)))
}

fn compare_aggregate_value_records_with_catalog(
    a: &AggregateValueRecord,
    b: &AggregateValueRecord,
    enums: Option<&dyn EnumLabelCatalog>,
    states: &[EnumComparisonState],
) -> Result<Ordering, SQLError> {
    let ordering = compare_sort_keys_with_catalog(&a.sort_keys, &b.sort_keys, enums, states)?;
    Ok(ordering.then_with(|| a.sequence.cmp(&b.sequence)))
}