uqa-execution 0.6.3

Volcano physical operators with row-batch pipelines
Documentation
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Bounded binary spill decoding.

use std::collections::HashSet;

use uqa_core::memory::{Produced, ProductionControl};
use uqa_core::{TemporalValue, Value};

mod value;
use uqa_sql::ast::ColumnType;

use crate::batch::{Batch, ColumnIdentity, PhysicalLayout, PhysicalRow, RowSchema};
use crate::physical::ExecResult;
use crate::spill::format::spill_error;

use super::MAX_VALUE_DEPTH;

const ROW_METADATA_LOCK_ORIGINS: u64 = 1;

#[expect(
    clippy::too_many_lines,
    reason = "binary decoding validates tags, widths, and bounds before allocation"
)]
pub(crate) fn decode_batch(record: &[u8]) -> ExecResult<Batch> {
    let mut reader = BinaryReader::new(record);
    let physical_width = reader.read_count("schema physical width", 1)?;
    let column_count = reader.read_count("schema column count", 16)?;
    let mut columns = Vec::new();
    let mut identities = Vec::new();
    let mut types = Vec::new();
    let mut slots = Vec::new();
    columns
        .try_reserve_exact(column_count)
        .map_err(|error| spill_error(format!("cannot allocate spill schema: {error}")))?;
    identities
        .try_reserve_exact(column_count)
        .map_err(|error| {
            spill_error(format!("cannot allocate spill schema identities: {error}"))
        })?;
    slots
        .try_reserve_exact(column_count)
        .map_err(|error| spill_error(format!("cannot allocate spill schema slots: {error}")))?;
    types
        .try_reserve_exact(column_count)
        .map_err(|error| spill_error(format!("cannot allocate spill schema types: {error}")))?;
    for _ in 0..column_count {
        columns.push(reader.read_string("schema column")?);
        identities.push(reader.read_identity("schema identity")?);
        slots.push(reader.read_slot("schema logical slot", physical_width)?);
        types.push(reader.read_column_type("schema column type")?);
    }
    let alias_count = reader.read_count("schema alias count", 16)?;
    let mut aliases = Vec::new();
    aliases
        .try_reserve_exact(alias_count)
        .map_err(|error| spill_error(format!("cannot allocate spill schema aliases: {error}")))?;
    for _ in 0..alias_count {
        aliases.push((
            reader.read_identity("schema alias")?,
            reader.read_slot("schema alias slot", physical_width)?,
            reader.read_column_type("schema alias type")?,
        ));
    }
    let internal_count = reader.read_count("schema internal column count", 32)?;
    let mut internal = Vec::new();
    internal
        .try_reserve_exact(internal_count)
        .map_err(|error| {
            spill_error(format!(
                "cannot allocate spill schema internal columns: {error}"
            ))
        })?;
    for _ in 0..internal_count {
        let relation = reader.read_u64("schema internal relation")?;
        let attribute = u32::try_from(reader.read_u64("schema internal attribute")?)
            .map_err(|_| spill_error("schema internal attribute exceeds u32"))?;
        internal.push((
            uqa_sql::ast::InternalColumnRef::from_raw(relation, attribute),
            reader.read_slot("schema internal slot", physical_width)?,
            reader.read_column_type("schema internal column type")?,
        ));
    }
    let score_source_count = reader.read_count("schema score source count", 24)?;
    let mut score_sources = Vec::new();
    score_sources
        .try_reserve_exact(score_source_count)
        .map_err(|error| spill_error(format!("cannot allocate spill score sources: {error}")))?;
    for _ in 0..score_source_count {
        let qualifier = match reader.read_u64("schema score source qualifier flag")? {
            0 => None,
            1 => Some(reader.read_string("schema score source qualifier")?),
            value => {
                return Err(spill_error(format!(
                    "invalid schema score source qualifier flag {value}"
                )))
            }
        };
        let relation = reader.read_u64("schema score source relation")?;
        let attribute = u32::try_from(reader.read_u64("schema score source attribute")?)
            .map_err(|_| spill_error("schema score source attribute exceeds u32"))?;
        score_sources.push((
            qualifier,
            uqa_sql::ast::InternalColumnRef::from_raw(relation, attribute),
        ));
    }
    let wildcard_hidden_count = reader.read_count("schema wildcard-hidden count", 8)?;
    let mut wildcard_hidden = HashSet::with_capacity(wildcard_hidden_count);
    for _ in 0..wildcard_hidden_count {
        let position = reader.read_count("schema wildcard-hidden position", 1)?;
        if position >= column_count {
            return Err(spill_error(format!(
                "schema wildcard-hidden position {position} is outside logical width {column_count}"
            )));
        }
        if !wildcard_hidden.insert(position) {
            return Err(spill_error(format!(
                "duplicate schema wildcard-hidden position {position}"
            )));
        }
    }
    let mut schema = RowSchema::from_physical_layout(PhysicalLayout {
        columns,
        identities,
        types,
        slots,
        physical_width,
        aliases,
        internal,
        score_sources,
        wildcard_hidden,
    })
    .map_err(|error| spill_error(format!("invalid spill schema: {error}")))?;
    let row_metadata = reader.read_u64("row metadata flags")?;
    if row_metadata
        & !(ROW_METADATA_LOCK_ORIGINS
            | u64::from(super::collations::FLAG)
            | u64::from(super::presence::FLAG))
        != 0
    {
        return Err(spill_error(format!(
            "unsupported row metadata flags {row_metadata:#x}"
        )));
    }
    let has_lock_origins = row_metadata & ROW_METADATA_LOCK_ORIGINS != 0;
    if row_metadata & u64::from(super::collations::FLAG) != 0 {
        let binding_count = column_count
            .saturating_add(alias_count)
            .saturating_add(internal_count);
        schema = super::collations::decode(&mut reader, schema, binding_count)?;
    }
    if row_metadata & u64::from(super::presence::FLAG) != 0 {
        schema = super::presence::decode(&mut reader, schema)?;
    }

    let row_count = reader.read_count("batch row count", 8)?;
    let mut rows = Vec::new();
    rows.try_reserve_exact(row_count)
        .map_err(|error| spill_error(format!("cannot allocate spill rows: {error}")))?;
    for _ in 0..row_count {
        rows.push(reader.read_row(physical_width, has_lock_origins)?);
    }
    reader.finish("spill batch")?;
    Ok(Batch::from_physical_rows(schema, rows))
}

pub(crate) fn decode_physical_row_record(
    record: &[u8],
    physical_width: usize,
) -> ExecResult<PhysicalRow> {
    let mut reader = BinaryReader::new(record);
    let mut row = reader.read_row(physical_width, false)?;
    if reader.remaining() != 0 {
        row = row.with_lock_origins(reader.read_lock_origins()?);
    }
    reader.finish("indexed spill row")?;
    Ok(row)
}

/// Read the sole value of a frozen constant record, admitting its decoded payload before allocation.
pub(crate) fn decode_constant_record(
    record: &[u8],
    control: &ProductionControl<'_>,
) -> ExecResult<Produced<Value>> {
    control.check()?;
    let mut reader = BinaryReader::new(record);
    if reader.read_count("row value count", 1)? != 1 {
        return Err(spill_error(
            "retained constant storage has invalid row width",
        ));
    }
    let value = reader.read_value_with_control(0, control)?;
    if reader.remaining() != 0 && reader.read_count("lock origin count", 32)? != 0 {
        return Err(spill_error(
            "retained constant storage has unexpected row origins",
        ));
    }
    reader.finish("indexed spill row")?;
    control.check()?;
    Ok(value)
}

/// The document `encode_document` wrote at the start of `bytes`, and the bytes after it.
pub(crate) fn decode_document(
    bytes: &[u8],
) -> ExecResult<(uqa_storage::document_store::Document, &[u8])> {
    let mut reader = BinaryReader::new(bytes);
    let Value::Map(fields) = reader.read_value(0)? else {
        return Err(spill_error("spilled document is not a map"));
    };
    Ok((fields, &bytes[reader.position..]))
}

pub(super) struct BinaryReader<'a> {
    bytes: &'a [u8],
    position: usize,
}

impl<'a> BinaryReader<'a> {
    pub(super) fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, position: 0 }
    }

    fn remaining(&self) -> usize {
        self.bytes.len().saturating_sub(self.position)
    }

    fn read_exact<const N: usize>(&mut self, description: &str) -> ExecResult<[u8; N]> {
        let end = self
            .position
            .checked_add(N)
            .ok_or_else(|| spill_error(format!("{description} offset overflow")))?;
        let slice = self
            .bytes
            .get(self.position..end)
            .ok_or_else(|| spill_error(format!("truncated {description}")))?;
        self.position = end;
        slice
            .try_into()
            .map_err(|_| spill_error(format!("invalid {description} width")))
    }

    fn read_u8(&mut self, description: &str) -> ExecResult<u8> {
        Ok(self.read_exact::<1>(description)?[0])
    }

    pub(super) fn read_u64(&mut self, description: &str) -> ExecResult<u64> {
        self.read_exact::<8>(description).map(u64::from_le_bytes)
    }

    fn read_i64(&mut self, description: &str) -> ExecResult<i64> {
        self.read_exact::<8>(description).map(i64::from_le_bytes)
    }

    fn read_i32(&mut self, description: &str) -> ExecResult<i32> {
        self.read_exact::<4>(description).map(i32::from_le_bytes)
    }

    pub(super) fn read_count(
        &mut self,
        description: &str,
        minimum_item_bytes: usize,
    ) -> ExecResult<usize> {
        let count = usize::try_from(self.read_u64(description)?)
            .map_err(|_| spill_error(format!("{description} exceeds address space")))?;
        if count > self.remaining().saturating_div(minimum_item_bytes.max(1)) {
            return Err(spill_error(format!("invalid {description} {count}")));
        }
        Ok(count)
    }

    fn read_bytes(&mut self, description: &str) -> ExecResult<&'a [u8]> {
        let length = usize::try_from(self.read_u64(description)?)
            .map_err(|_| spill_error(format!("{description} length exceeds address space")))?;
        let end = self
            .position
            .checked_add(length)
            .ok_or_else(|| spill_error(format!("{description} offset overflow")))?;
        let value = self
            .bytes
            .get(self.position..end)
            .ok_or_else(|| spill_error(format!("truncated {description}")))?;
        self.position = end;
        Ok(value)
    }

    pub(super) fn read_string(&mut self, description: &str) -> ExecResult<String> {
        let bytes = self.read_bytes(description)?;
        String::from_utf8(bytes.to_vec())
            .map_err(|error| spill_error(format!("invalid UTF-8 in {description}: {error}")))
    }

    pub(super) fn read_identity(&mut self, description: &str) -> ExecResult<ColumnIdentity> {
        let qualifier = self.read_string(description)?;
        let column = self.read_string(description)?;
        if column.is_empty() {
            return Err(spill_error(format!(
                "{description} has an empty column name"
            )));
        }
        Ok(if qualifier.is_empty() {
            ColumnIdentity::unqualified(column)
        } else {
            ColumnIdentity::qualified(qualifier, column)
        })
    }

    fn read_column_type(&mut self, description: &str) -> ExecResult<Option<ColumnType>> {
        let encoded = self.read_string(description)?;
        if encoded.is_empty() {
            return Ok(None);
        }
        serde_json::from_str(&encoded)
            .map(Some)
            .map_err(|error| spill_error(format!("invalid {description}: {error}")))
    }

    fn read_slot(&mut self, description: &str, physical_width: usize) -> ExecResult<Option<usize>> {
        let encoded = self.read_u64(description)?;
        if encoded == u64::MAX {
            return Ok(None);
        }
        let slot = usize::try_from(encoded)
            .map_err(|_| spill_error(format!("{description} exceeds address space")))?;
        if slot >= physical_width {
            return Err(spill_error(format!(
                "{description} {slot} is outside physical width {physical_width}"
            )));
        }
        Ok(Some(slot))
    }

    fn read_row(
        &mut self,
        expected_values: usize,
        has_lock_origins: bool,
    ) -> ExecResult<PhysicalRow> {
        let value_count = self.read_count("row value count", 1)?;
        if value_count != expected_values {
            return Err(spill_error(format!(
                "spill row has {value_count} values for {expected_values} columns"
            )));
        }
        let mut values = Vec::new();
        values
            .try_reserve_exact(value_count)
            .map_err(|error| spill_error(format!("cannot allocate spill row: {error}")))?;
        for _ in 0..value_count {
            values.push(self.read_value(0)?);
        }
        let row = PhysicalRow::from_values(values);
        if !has_lock_origins {
            return Ok(row);
        }
        Ok(row.with_lock_origins(self.read_lock_origins()?))
    }

    fn read_lock_origins(&mut self) -> ExecResult<Vec<crate::RowLockOrigin>> {
        let origin_count = self.read_count("lock origin count", 32)?;
        let mut origins = Vec::new();
        origins
            .try_reserve_exact(origin_count)
            .map_err(|error| spill_error(format!("cannot allocate lock origins: {error}")))?;
        for _ in 0..origin_count {
            let qualifier = self.read_string("lock origin qualifier")?;
            let scan_qualifier = self.read_string("lock origin scan qualifier")?;
            let storage_name = self.read_string("lock origin storage")?;
            let doc_id = self.read_u64("lock origin doc id")?;
            origins.push(crate::RowLockOrigin {
                qualifier: qualifier.into(),
                scan_qualifier: scan_qualifier.into(),
                storage_name: storage_name.into(),
                doc_id,
            });
        }
        Ok(origins)
    }

    fn read_value(&mut self, depth: usize) -> ExecResult<Value> {
        Ok(self
            .read_value_with_control(depth, &ProductionControl::uncontrolled())?
            .into_uncontrolled()
            .expect("ordinary spill value"))
    }

    fn read_temporal(&mut self) -> ExecResult<TemporalValue> {
        match self.read_u8("temporal tag")? {
            0 => Ok(TemporalValue::Date {
                days: self.read_i32("date")?,
            }),
            1 => Ok(TemporalValue::Time {
                micros: self.read_i64("time")?,
            }),
            2 => Ok(TemporalValue::TimeTz {
                micros: self.read_i64("time with time zone")?,
                offset_seconds: self.read_i32("time zone offset")?,
            }),
            3 => Ok(TemporalValue::Timestamp {
                postgres_micros: self.read_i64("timestamp")?,
            }),
            4 => Ok(TemporalValue::TimestampTz {
                postgres_micros: self.read_i64("timestamp with time zone")?,
            }),
            5 => Ok(TemporalValue::Interval {
                months: self.read_i32("interval months")?,
                days: self.read_i32("interval days")?,
                micros: self.read_i64("interval micros")?,
            }),
            tag => Err(spill_error(format!("invalid temporal tag {tag}"))),
        }
    }

    fn finish(self, description: &str) -> ExecResult<()> {
        if self.position == self.bytes.len() {
            Ok(())
        } else {
            Err(spill_error(format!(
                "{description} has {} trailing bytes",
                self.bytes.len() - self.position
            )))
        }
    }
}