tauq 0.2.0

Token-efficient data notation - 49% fewer tokens than JSON (verified with tiktoken)
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
//! Column statistics for query optimization
//!
//! Statistics (min, max, null count) enable:
//! - Predicate pushdown (skip columns that can't match)
//! - Cardinality estimation (for query planning)
//! - Data profiling (understand data distribution)
//!
//! Statistics are stored in file footer for random access.

use super::varint::{decode_varint, encode_varint};
use crate::error::{InterpretError, TauqError};
use serde_json::{Value, json};

/// Statistics for a single column
#[derive(Debug, Clone)]
pub struct ColumnStats {
    /// Column identifier (field index)
    pub column_id: u32,

    /// Number of null values in this column
    pub null_count: u64,

    /// Minimum value (if orderable)
    pub min_value: Option<Value>,

    /// Maximum value (if orderable)
    pub max_value: Option<Value>,

    /// Approximate distinct value count (cardinality)
    pub cardinality: u32,

    /// Total number of rows
    pub row_count: u64,
}

impl ColumnStats {
    /// Create new column statistics
    pub fn new(column_id: u32, row_count: u64) -> Self {
        Self {
            column_id,
            null_count: 0,
            min_value: None,
            max_value: None,
            cardinality: 0,
            row_count,
        }
    }

    /// Check if value might be contained in column (based on stats)
    pub fn may_contain(&self, value: &Value) -> bool {
        match (self.min_value.as_ref(), self.max_value.as_ref()) {
            (Some(min), Some(max)) => {
                // Value is in range if: value >= min && value <= max
                !json_value_lt(value, min) && !json_value_gt(value, max)
            }
            _ => true, // Unknown range, assume it may contain
        }
    }

    /// Check if column can definitely be skipped for a range predicate
    ///
    /// Returns true if column cannot possibly contain values in [min, max]
    pub fn can_skip_range(&self, min: &Value, max: &Value) -> bool {
        match (self.min_value.as_ref(), self.max_value.as_ref()) {
            (Some(col_min), Some(col_max)) => {
                // Can skip if: col_max < min OR col_min > max
                json_value_lt(col_max, min) || json_value_gt(col_min, max)
            }
            _ => false, // Can't determine, don't skip
        }
    }

    /// Update statistics with a new value
    pub fn update(&mut self, value: Option<&Value>) {
        match value {
            Some(v) => {
                // Update min/max for orderable types
                if self.min_value.is_none() {
                    self.min_value = Some(v.clone());
                } else if let Some(min) = self.min_value.as_mut()
                    && json_value_lt(v, min)
                {
                    *min = v.clone();
                }

                if self.max_value.is_none() {
                    self.max_value = Some(v.clone());
                } else if let Some(max) = self.max_value.as_mut()
                    && json_value_gt(v, max)
                {
                    *max = v.clone();
                }

                // Update cardinality (simple approximation)
                // TODO: Use HyperLogLog for unbounded cardinality
                self.cardinality = self.cardinality.saturating_add(1);
            }
            None => {
                self.null_count += 1;
            }
        }
    }

    /// Encode statistics to bytes
    pub fn encode(&self) -> Vec<u8> {
        let mut buffer = Vec::new();

        // Column ID
        encode_varint(self.column_id as u64, &mut buffer);

        // Null count
        encode_varint(self.null_count, &mut buffer);

        // Min value
        if let Some(min) = &self.min_value {
            buffer.push(1); // Has min
            encode_json_value(min, &mut buffer);
        } else {
            buffer.push(0); // No min
        }

        // Max value
        if let Some(max) = &self.max_value {
            buffer.push(1); // Has max
            encode_json_value(max, &mut buffer);
        } else {
            buffer.push(0); // No max
        }

        // Cardinality
        encode_varint(self.cardinality as u64, &mut buffer);

        // Row count
        encode_varint(self.row_count, &mut buffer);

        buffer
    }

    /// Decode statistics from bytes
    pub fn decode(bytes: &[u8]) -> Result<(Self, usize), TauqError> {
        let mut offset = 0;

        // Column ID
        let (column_id, size) = decode_varint(&bytes[offset..])?;
        offset += size;

        // Null count
        let (null_count, size) = decode_varint(&bytes[offset..])?;
        offset += size;

        // Min value
        let min_value = if bytes[offset] == 1 {
            offset += 1;
            let (val, size) = decode_json_value(&bytes[offset..])?;
            offset += size;
            Some(val)
        } else {
            offset += 1;
            None
        };

        // Max value
        let max_value = if bytes[offset] == 1 {
            offset += 1;
            let (val, size) = decode_json_value(&bytes[offset..])?;
            offset += size;
            Some(val)
        } else {
            offset += 1;
            None
        };

        // Cardinality
        let (cardinality, size) = decode_varint(&bytes[offset..])?;
        offset += size;

        // Row count
        let (row_count, size) = decode_varint(&bytes[offset..])?;
        offset += size;

        Ok((
            ColumnStats {
                column_id: column_id as u32,
                null_count,
                min_value,
                max_value,
                cardinality: cardinality as u32,
                row_count,
            },
            offset,
        ))
    }
}

/// Encode JSON value as compact bytes
fn encode_json_value(value: &Value, buf: &mut Vec<u8>) {
    // Type tag (0=null, 1=bool, 2=number, 3=string)
    match value {
        Value::Null => {
            buf.push(0);
        }
        Value::Bool(b) => {
            buf.push(1);
            buf.push(if *b { 1 } else { 0 });
        }
        Value::Number(n) => {
            buf.push(2);
            // Encode number as f64 bits
            if let Some(f) = n.as_f64() {
                buf.extend_from_slice(&f.to_le_bytes());
            } else {
                // Fallback to i64
                let i = n.as_i64().unwrap_or(0);
                buf.extend_from_slice(&i.to_le_bytes());
            }
        }
        Value::String(s) => {
            buf.push(3);
            encode_varint(s.len() as u64, buf);
            buf.extend_from_slice(s.as_bytes());
        }
        _ => {
            // For complex types, use null
            buf.push(0);
        }
    }
}

/// Decode JSON value from bytes
fn decode_json_value(bytes: &[u8]) -> Result<(Value, usize), TauqError> {
    if bytes.is_empty() {
        return Err(TauqError::Interpret(InterpretError::new(
            "Cannot decode JSON value: empty buffer",
        )));
    }

    let tag = bytes[0];
    let mut offset = 1;

    match tag {
        0 => Ok((Value::Null, 1)),
        1 => {
            if bytes.len() < 2 {
                return Err(TauqError::Interpret(InterpretError::new(
                    "Invalid bool value",
                )));
            }
            let b = bytes[1] != 0;
            Ok((Value::Bool(b), 2))
        }
        2 => {
            // Try f64 first (8 bytes)
            if bytes.len() >= offset + 8 {
                let bytes_arr: [u8; 8] = [
                    bytes[offset],
                    bytes[offset + 1],
                    bytes[offset + 2],
                    bytes[offset + 3],
                    bytes[offset + 4],
                    bytes[offset + 5],
                    bytes[offset + 6],
                    bytes[offset + 7],
                ];
                let f = f64::from_le_bytes(bytes_arr);
                Ok((json!(f), offset + 8))
            } else {
                Err(TauqError::Interpret(InterpretError::new(
                    "Invalid number value",
                )))
            }
        }
        3 => {
            // String
            let (len, size) = decode_varint(&bytes[offset..])?;
            offset += size;
            let len = len as usize;
            if bytes.len() < offset + len {
                return Err(TauqError::Interpret(InterpretError::new(
                    "Invalid string value",
                )));
            }
            let s = String::from_utf8(bytes[offset..offset + len].to_vec())
                .map_err(|_| TauqError::Interpret(InterpretError::new("Invalid UTF-8 string")))?;
            Ok((Value::String(s), offset + len))
        }
        _ => Err(TauqError::Interpret(InterpretError::new(format!(
            "Unknown JSON value type tag: {}",
            tag
        )))),
    }
}

/// Compare two JSON values for less-than (for statistics)
fn json_value_lt(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Number(an), Value::Number(bn)) => {
            if let (Some(af), Some(bf)) = (an.as_f64(), bn.as_f64()) {
                af < bf
            } else {
                false
            }
        }
        (Value::String(as_), Value::String(bs)) => as_ < bs,
        _ => false,
    }
}

/// Compare two JSON values for greater-than (for statistics)
fn json_value_gt(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Number(an), Value::Number(bn)) => {
            if let (Some(af), Some(bf)) = (an.as_f64(), bn.as_f64()) {
                af > bf
            } else {
                false
            }
        }
        (Value::String(as_), Value::String(bs)) => as_ > bs,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_stats_may_contain() {
        let mut stats = ColumnStats::new(0, 100);
        stats.min_value = Some(json!(10));
        stats.max_value = Some(json!(50));

        assert!(stats.may_contain(&json!(25)));
        assert!(stats.may_contain(&json!(10)));
        assert!(stats.may_contain(&json!(50)));
        assert!(!stats.may_contain(&json!(5)));
        assert!(!stats.may_contain(&json!(100)));
    }

    #[test]
    fn test_stats_can_skip_range() {
        let mut stats = ColumnStats::new(0, 100);
        stats.min_value = Some(json!(10));
        stats.max_value = Some(json!(50));

        // Query: [60, 80] - outside range
        assert!(stats.can_skip_range(&json!(60), &json!(80)));

        // Query: [0, 5] - outside range
        assert!(stats.can_skip_range(&json!(0), &json!(5)));

        // Query: [25, 75] - overlaps
        assert!(!stats.can_skip_range(&json!(25), &json!(75)));

        // Query: [10, 50] - exact match
        assert!(!stats.can_skip_range(&json!(10), &json!(50)));
    }

    #[test]
    fn test_stats_encode_decode() {
        let mut stats = ColumnStats::new(42, 1000);
        stats.null_count = 5;
        stats.min_value = Some(json!(10));
        stats.max_value = Some(json!(100));
        stats.cardinality = 95;

        let encoded = stats.encode();
        let (decoded, _) = ColumnStats::decode(&encoded).unwrap();

        assert_eq!(decoded.column_id, 42);
        assert_eq!(decoded.null_count, 5);

        // Compare numeric values (encoding converts to f64, so compare semantically)
        if let (Some(Value::Number(min)), Some(Value::Number(orig_min))) =
            (decoded.min_value.as_ref(), stats.min_value.as_ref())
        {
            assert_eq!(min.as_f64(), orig_min.as_f64());
        } else {
            panic!("min_value mismatch");
        }

        if let (Some(Value::Number(max)), Some(Value::Number(orig_max))) =
            (decoded.max_value.as_ref(), stats.max_value.as_ref())
        {
            assert_eq!(max.as_f64(), orig_max.as_f64());
        } else {
            panic!("max_value mismatch");
        }

        assert_eq!(decoded.cardinality, 95);
        assert_eq!(decoded.row_count, 1000);
    }

    #[test]
    fn test_stats_update() {
        let mut stats = ColumnStats::new(0, 0);

        stats.update(Some(&json!(5)));
        assert_eq!(stats.min_value, Some(json!(5)));
        assert_eq!(stats.max_value, Some(json!(5)));

        stats.update(Some(&json!(10)));
        assert_eq!(stats.min_value, Some(json!(5)));
        assert_eq!(stats.max_value, Some(json!(10)));

        stats.update(Some(&json!(1)));
        assert_eq!(stats.min_value, Some(json!(1)));
        assert_eq!(stats.max_value, Some(json!(10)));

        stats.update(None);
        assert_eq!(stats.null_count, 1);
    }
}