1use crate::storage::unified::{
38 read_column_block, write_column_block, ColumnBlockError, ColumnInput, ColumnSemantics,
39};
40use reddb_types::types::{DataType, Value};
41
42const GRANULE_SIZE: u32 = 128;
46
47pub type Row = Vec<Value>;
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct ProjectionColumn {
55 pub column_id: u32,
57 pub data_type: DataType,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct ProjectionSchema {
64 pub columns: Vec<ProjectionColumn>,
65}
66
67impl ProjectionSchema {
68 pub fn new(columns: Vec<ProjectionColumn>) -> Self {
69 Self { columns }
70 }
71
72 fn width(&self) -> usize {
73 self.columns.len()
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum ProjectionError {
81 TypeMismatch {
83 column: usize,
84 expected: DataType,
85 found: &'static str,
86 },
87 RowWidth { expected: usize, found: usize },
89 NonMonotonicLsn { last: u64, next: u64 },
91 Block(ColumnBlockError),
93 Envelope(String),
95 CorruptSegment(&'static str),
98}
99
100impl std::fmt::Display for ProjectionError {
101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 match self {
103 Self::TypeMismatch {
104 column,
105 expected,
106 found,
107 } => write!(
108 f,
109 "projection column {column}: expected {expected}, found {found}"
110 ),
111 Self::RowWidth { expected, found } => {
112 write!(
113 f,
114 "projection row width mismatch: expected {expected}, got {found}"
115 )
116 }
117 Self::NonMonotonicLsn { last, next } => {
118 write!(f, "projection: non-monotonic lsn {next} after {last}")
119 }
120 Self::Block(e) => write!(f, "projection segment decode failed: {e}"),
121 Self::Envelope(detail) => write!(f, "projection segment envelope failed: {detail}"),
122 Self::CorruptSegment(detail) => write!(f, "projection segment corrupt: {detail}"),
123 }
124 }
125}
126
127impl std::error::Error for ProjectionError {}
128
129impl ProjectionError {
130 fn is_projection_artifact_failure(&self) -> bool {
131 matches!(
132 self,
133 Self::Block(_) | Self::Envelope(_) | Self::CorruptSegment(_)
134 )
135 }
136}
137
138impl From<ColumnBlockError> for ProjectionError {
139 fn from(e: ColumnBlockError) -> Self {
140 Self::Block(e)
141 }
142}
143
144#[derive(Debug, Clone, PartialEq)]
146struct LsnRow {
147 lsn: u64,
148 row: Row,
149}
150
151#[derive(Debug, Clone)]
155pub struct AppendOnlyCollection {
156 schema: ProjectionSchema,
157 rows: Vec<LsnRow>,
158 last_lsn: u64,
159}
160
161impl AppendOnlyCollection {
162 pub fn new(schema: ProjectionSchema) -> Self {
163 Self {
164 schema,
165 rows: Vec::new(),
166 last_lsn: 0,
167 }
168 }
169
170 pub fn schema(&self) -> &ProjectionSchema {
171 &self.schema
172 }
173
174 pub fn latest_lsn(&self) -> u64 {
177 self.last_lsn
178 }
179
180 pub fn append(&mut self, lsn: u64, row: Row) -> Result<(), ProjectionError> {
183 if row.len() != self.schema.width() {
184 return Err(ProjectionError::RowWidth {
185 expected: self.schema.width(),
186 found: row.len(),
187 });
188 }
189 if lsn <= self.last_lsn {
190 return Err(ProjectionError::NonMonotonicLsn {
191 last: self.last_lsn,
192 next: lsn,
193 });
194 }
195 for (idx, value) in row.iter().enumerate() {
196 check_value_type(idx, &self.schema.columns[idx].data_type, value)?;
197 }
198 self.last_lsn = lsn;
199 self.rows.push(LsnRow { lsn, row });
200 Ok(())
201 }
202
203 pub fn row_scan(&self, pinned_lsn: u64) -> Vec<Row> {
207 self.rows
208 .iter()
209 .filter(|r| r.lsn <= pinned_lsn)
210 .map(|r| r.row.clone())
211 .collect()
212 }
213
214 fn rows_between(&self, after: u64, up_to: u64) -> impl Iterator<Item = &LsnRow> {
216 self.rows
217 .iter()
218 .filter(move |r| r.lsn > after && r.lsn <= up_to)
219 }
220
221 fn next_visible_lsn_after(&self, after: u64, up_to: u64) -> Option<u64> {
222 self.rows_between(after, up_to).next().map(|r| r.lsn)
223 }
224}
225
226#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct ProjectionSegmentEntry {
231 pub segment_id: u64,
232 pub first_lsn: u64,
234 pub last_lsn: u64,
235 pub row_count: u64,
236 pub sealed_crc32: u32,
239 pub derived: bool,
241}
242
243#[derive(Debug, Clone, Default, PartialEq, Eq)]
246pub struct ProjectionManifest {
247 segments: Vec<ProjectionSegmentEntry>,
248 last_materialized_lsn: u64,
249}
250
251impl ProjectionManifest {
252 pub fn last_materialized_lsn(&self) -> u64 {
256 self.last_materialized_lsn
257 }
258
259 pub fn segments(&self) -> &[ProjectionSegmentEntry] {
260 &self.segments
261 }
262
263 pub fn all_derived(&self) -> bool {
266 self.segments.iter().all(|s| s.derived)
267 }
268
269 pub fn durable_entries(&self) -> impl Iterator<Item = &ProjectionSegmentEntry> {
272 self.segments.iter().filter(|s| !s.derived)
273 }
274}
275
276#[derive(Debug, Clone, Copy)]
278pub struct TranscodeBudget {
279 pub max_rows: u64,
282 pub segment_rows: u64,
284 pub size_floor_rows: u64,
289}
290
291impl Default for TranscodeBudget {
292 fn default() -> Self {
293 Self {
294 max_rows: u64::MAX,
295 segment_rows: 1024,
296 size_floor_rows: 1,
297 }
298 }
299}
300
301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub struct EmitOutcome {
304 pub segments_emitted: usize,
305 pub rows_materialized: u64,
306 pub rows_deferred: u64,
309 pub budget_exhausted: bool,
311 pub floor_skipped: bool,
313}
314
315#[derive(Debug, Clone)]
318struct StoredSegment {
319 entry: ProjectionSegmentEntry,
320 sealed: Vec<u8>,
321}
322
323#[derive(Debug, Clone)]
325pub struct ColumnarProjection {
326 schema: ProjectionSchema,
327 key: [u8; 32],
328 segments: Vec<StoredSegment>,
329 manifest: ProjectionManifest,
330 next_segment_id: u64,
331}
332
333impl ColumnarProjection {
334 pub fn new(schema: ProjectionSchema, key: [u8; 32]) -> Self {
336 Self {
337 schema,
338 key,
339 segments: Vec::new(),
340 manifest: ProjectionManifest::default(),
341 next_segment_id: 1,
342 }
343 }
344
345 pub fn manifest(&self) -> &ProjectionManifest {
346 &self.manifest
347 }
348
349 pub fn drop_projection(&mut self) {
353 self.segments.clear();
354 self.manifest = ProjectionManifest::default();
355 }
356
357 pub fn rebuild_from_truth(
361 &mut self,
362 collection: &AppendOnlyCollection,
363 checkpoint_lsn: u64,
364 budget: TranscodeBudget,
365 ) -> Result<EmitOutcome, ProjectionError> {
366 self.drop_projection();
367 self.emit_at_checkpoint(collection, checkpoint_lsn, budget)
368 }
369
370 pub fn emit_at_checkpoint(
375 &mut self,
376 collection: &AppendOnlyCollection,
377 checkpoint_lsn: u64,
378 budget: TranscodeBudget,
379 ) -> Result<EmitOutcome, ProjectionError> {
380 let watermark = self.manifest.last_materialized_lsn;
381 let pending: Vec<&LsnRow> = collection.rows_between(watermark, checkpoint_lsn).collect();
382 let available = pending.len() as u64;
383
384 if available < budget.size_floor_rows.max(1) {
385 return Ok(EmitOutcome {
386 segments_emitted: 0,
387 rows_materialized: 0,
388 rows_deferred: available,
389 budget_exhausted: false,
390 floor_skipped: available > 0,
391 });
392 }
393
394 let to_materialize = available.min(budget.max_rows) as usize;
395 let segment_rows = budget.segment_rows.max(1) as usize;
396 let mut segments_emitted = 0usize;
397
398 for chunk in pending[..to_materialize].chunks(segment_rows) {
399 let entry = self.seal_segment(chunk)?;
400 self.manifest.last_materialized_lsn = entry.last_lsn;
401 self.manifest.segments.push(entry);
402 segments_emitted += 1;
403 }
404
405 let rows_deferred = available - to_materialize as u64;
406 Ok(EmitOutcome {
407 segments_emitted,
408 rows_materialized: to_materialize as u64,
409 rows_deferred,
410 budget_exhausted: rows_deferred > 0,
411 floor_skipped: false,
412 })
413 }
414
415 fn seal_segment(
418 &mut self,
419 rows: &[&LsnRow],
420 ) -> Result<ProjectionSegmentEntry, ProjectionError> {
421 let segment_id = self.next_segment_id;
422 self.next_segment_id += 1;
423 let first_lsn = rows.first().map(|r| r.lsn).unwrap_or(0);
424 let last_lsn = rows.last().map(|r| r.lsn).unwrap_or(0);
425
426 let mut column_bytes: Vec<Vec<u8>> = vec![Vec::new(); self.schema.columns.len()];
428 for lsn_row in rows {
429 for (idx, value) in lsn_row.row.iter().enumerate() {
430 let dt = self.schema.columns[idx].data_type;
431 check_value_type(idx, &dt, value)?;
432 encode_cell(dt, value, &mut column_bytes[idx])?;
433 }
434 }
435
436 let inputs: Vec<ColumnInput<'_>> = self
437 .schema
438 .columns
439 .iter()
440 .zip(column_bytes.iter())
441 .map(|(col, data)| ColumnInput {
442 column_id: col.column_id,
443 logical_type: col.data_type.to_byte(),
444 semantics: ColumnSemantics::Generic,
445 data,
446 })
447 .collect();
448
449 let frame = write_column_block(
451 segment_id,
452 self.schema.columns.len() as u64,
453 rows.len() as u64,
454 first_lsn,
455 last_lsn,
456 GRANULE_SIZE,
457 &inputs,
458 )?;
459
460 let sealed = reddb_crypto::encrypt_page(&self.key, segment_id as u32, &frame)
463 .map_err(|e| ProjectionError::Envelope(e.to_string()))?;
464 let sealed_crc32 = crc32fast::hash(&sealed);
465
466 let entry = ProjectionSegmentEntry {
467 segment_id,
468 first_lsn,
469 last_lsn,
470 row_count: rows.len() as u64,
471 sealed_crc32,
472 derived: true,
473 };
474 self.segments.push(StoredSegment {
475 entry: entry.clone(),
476 sealed,
477 });
478 Ok(entry)
479 }
480
481 pub fn analytical_scan(
488 &self,
489 collection: &AppendOnlyCollection,
490 pinned_lsn: u64,
491 ) -> Result<Vec<Row>, ProjectionError> {
492 let columnar_ceiling = self.manifest.last_materialized_lsn.min(pinned_lsn);
493
494 let mut out = Vec::new();
495 let mut tail_start = 0u64;
496 for stored in &self.segments {
497 if stored.entry.last_lsn > columnar_ceiling {
498 continue;
499 }
500 match collection.next_visible_lsn_after(tail_start, pinned_lsn) {
501 Some(next_lsn) if next_lsn == stored.entry.first_lsn => {}
502 Some(_) | None => return Ok(collection.row_scan(pinned_lsn)),
503 }
504 self.verify_and_decode_segment(stored, &mut out)?;
505 tail_start = tail_start.max(stored.entry.last_lsn);
506 }
507
508 for lsn_row in collection.rows_between(tail_start, pinned_lsn) {
511 out.push(lsn_row.row.clone());
512 }
513 Ok(out)
514 }
515
516 pub fn repairing_analytical_scan(
521 &mut self,
522 collection: &AppendOnlyCollection,
523 pinned_lsn: u64,
524 budget: TranscodeBudget,
525 ) -> Result<Vec<Row>, ProjectionError> {
526 if self.projection_artifacts_missing() {
527 self.rebuild_from_truth(collection, pinned_lsn, budget)?;
528 return self.analytical_scan(collection, pinned_lsn);
529 }
530
531 match self.analytical_scan(collection, pinned_lsn) {
532 Ok(rows) => Ok(rows),
533 Err(err) if err.is_projection_artifact_failure() => {
534 self.rebuild_from_truth(collection, pinned_lsn, budget)?;
535 self.analytical_scan(collection, pinned_lsn)
536 }
537 Err(err) => Err(err),
538 }
539 }
540
541 fn projection_artifacts_missing(&self) -> bool {
542 if self.manifest.segments.is_empty() {
543 return false;
544 }
545 if self.manifest.segments.len() != self.segments.len() {
546 return true;
547 }
548 self.manifest
549 .segments
550 .iter()
551 .zip(self.segments.iter())
552 .any(|(manifest, stored)| manifest != &stored.entry)
553 }
554
555 fn verify_and_decode_segment(
558 &self,
559 stored: &StoredSegment,
560 out: &mut Vec<Row>,
561 ) -> Result<(), ProjectionError> {
562 if crc32fast::hash(&stored.sealed) != stored.entry.sealed_crc32 {
563 return Err(ProjectionError::CorruptSegment("sealed checksum mismatch"));
564 }
565 let frame =
566 reddb_crypto::decrypt_page(&self.key, stored.entry.segment_id as u32, &stored.sealed)
567 .map_err(|e| ProjectionError::Envelope(e.to_string()))?;
568 let block = read_column_block(&frame)?;
570 let row_count = block.row_count as usize;
571
572 let mut decoded_columns: Vec<Vec<Value>> = Vec::with_capacity(self.schema.columns.len());
574 for col in &self.schema.columns {
575 let decoded = block
576 .columns
577 .iter()
578 .find(|c| c.column_id == col.column_id)
579 .ok_or(ProjectionError::CorruptSegment("missing column"))?;
580 decoded_columns.push(decode_column(col.data_type, &decoded.data, row_count)?);
581 }
582
583 let base = out.len();
588 for _ in 0..row_count {
589 out.push(Vec::with_capacity(self.schema.columns.len()));
590 }
591 for column in decoded_columns {
592 debug_assert_eq!(
596 column.len(),
597 row_count,
598 "decoded column is not row_count long"
599 );
600 for (r, value) in column.into_iter().take(row_count).enumerate() {
601 out[base + r].push(value);
602 }
603 }
604 Ok(())
605 }
606}
607
608fn check_value_type(column: usize, dt: &DataType, value: &Value) -> Result<(), ProjectionError> {
611 if value_matches_declared_type(dt, value) {
612 return Ok(());
613 }
614 Err(ProjectionError::TypeMismatch {
615 column,
616 expected: *dt,
617 found: value_kind(value),
618 })
619}
620
621fn value_matches_declared_type(dt: &DataType, value: &Value) -> bool {
622 match (dt, value) {
623 (DataType::Nullable, Value::Null) => true,
624 (DataType::TextZstd, Value::Text(_)) => true,
625 (DataType::BlobZstd, Value::Blob(_)) => true,
626 _ => value.data_type() == *dt,
627 }
628}
629
630fn value_kind(value: &Value) -> &'static str {
631 match value {
632 Value::Null => "Null",
633 Value::Integer(_) => "Integer",
634 Value::UnsignedInteger(_) => "UnsignedInteger",
635 Value::Timestamp(_) => "Timestamp",
636 Value::Float(_) => "Float",
637 Value::Boolean(_) => "Boolean",
638 Value::Text(_) => "Text",
639 Value::Blob(_) => "Blob",
640 Value::Duration(_) => "Duration",
641 Value::IpAddr(_) => "IpAddr",
642 Value::MacAddr(_) => "MacAddr",
643 Value::Vector(_) => "Vector",
644 Value::Json(_) => "Json",
645 Value::Uuid(_) => "Uuid",
646 Value::NodeRef(_) => "NodeRef",
647 Value::EdgeRef(_) => "EdgeRef",
648 Value::VectorRef(_, _) => "VectorRef",
649 Value::RowRef(_, _) => "RowRef",
650 Value::Color(_) => "Color",
651 Value::Email(_) => "Email",
652 Value::Url(_) => "Url",
653 Value::Phone(_) => "Phone",
654 Value::Semver(_) => "Semver",
655 Value::Cidr(_, _) => "Cidr",
656 Value::Date(_) => "Date",
657 Value::Time(_) => "Time",
658 Value::Decimal(_) => "Decimal",
659 Value::DecimalText(_) => "DecimalText",
660 Value::EnumValue(_) => "Enum",
661 Value::Array(_) => "Array",
662 Value::TimestampMs(_) => "TimestampMs",
663 Value::Ipv4(_) => "Ipv4",
664 Value::Ipv6(_) => "Ipv6",
665 Value::Subnet(_, _) => "Subnet",
666 Value::Port(_) => "Port",
667 Value::Latitude(_) => "Latitude",
668 Value::Longitude(_) => "Longitude",
669 Value::GeoPoint(_, _) => "GeoPoint",
670 Value::Country2(_) => "Country2",
671 Value::Country3(_) => "Country3",
672 Value::Lang2(_) => "Lang2",
673 Value::Lang5(_) => "Lang5",
674 Value::Currency(_) => "Currency",
675 Value::AssetCode(_) => "AssetCode",
676 Value::Money { .. } => "Money",
677 Value::Temperature(_) => "Temperature",
678 Value::Cron(_) => "Cron",
679 Value::ColorAlpha(_) => "ColorAlpha",
680 Value::BigInt(_) => "BigInt",
681 Value::KeyRef(_, _) => "KeyRef",
682 Value::DocRef(_, _) => "DocRef",
683 Value::TableRef(_) => "TableRef",
684 Value::PageRef(_) => "PageRef",
685 Value::Secret(_) => "Secret",
686 Value::Password(_) => "Password",
687 }
688}
689
690fn encode_cell(dt: DataType, value: &Value, out: &mut Vec<u8>) -> Result<(), ProjectionError> {
692 check_value_type(0, &dt, value)?;
693 let encoded = value.to_bytes();
694 out.extend_from_slice(&(encoded.len() as u32).to_le_bytes());
695 out.extend_from_slice(&encoded);
696 Ok(())
697}
698
699fn decode_column(
702 dt: DataType,
703 data: &[u8],
704 row_count: usize,
705) -> Result<Vec<Value>, ProjectionError> {
706 let mut out = Vec::with_capacity(row_count);
707 let mut cur = 0usize;
708 for _ in 0..row_count {
709 if cur + 4 > data.len() {
710 return Err(ProjectionError::CorruptSegment("truncated value length"));
711 }
712 let len = u32::from_le_bytes(to_4(&data[cur..cur + 4])) as usize;
713 cur += 4;
714 let end = cur
715 .checked_add(len)
716 .filter(|e| *e <= data.len())
717 .ok_or(ProjectionError::CorruptSegment("truncated value body"))?;
718 let (value, consumed) = Value::from_bytes(&data[cur..end])
719 .map_err(|_| ProjectionError::CorruptSegment("invalid value bytes"))?;
720 if consumed != len {
721 return Err(ProjectionError::CorruptSegment("trailing value bytes"));
722 }
723 if !value_matches_declared_type(&dt, &value) {
724 return Err(ProjectionError::CorruptSegment(
725 "decoded value type mismatch",
726 ));
727 }
728 out.push(value);
729 cur = end;
730 }
731 if cur != data.len() {
732 return Err(ProjectionError::CorruptSegment("trailing column bytes"));
733 }
734 Ok(out)
735}
736
737fn to_4(b: &[u8]) -> [u8; 4] {
738 let mut a = [0u8; 4];
739 a.copy_from_slice(b);
740 a
741}
742
743#[cfg(test)]
744mod tests {
745 use super::*;
746 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
747
748 const KEY: [u8; 32] = [7u8; 32];
749
750 fn schema() -> ProjectionSchema {
751 ProjectionSchema::new(vec![
752 ProjectionColumn {
753 column_id: 0,
754 data_type: DataType::Timestamp,
755 },
756 ProjectionColumn {
757 column_id: 1,
758 data_type: DataType::Integer,
759 },
760 ProjectionColumn {
761 column_id: 2,
762 data_type: DataType::Float,
763 },
764 ProjectionColumn {
765 column_id: 3,
766 data_type: DataType::Boolean,
767 },
768 ProjectionColumn {
769 column_id: 4,
770 data_type: DataType::Text,
771 },
772 ])
773 }
774
775 fn row(i: i64) -> Row {
776 vec![
777 Value::Timestamp(1_700_000_000 + i),
778 Value::Integer(i * 3),
779 Value::Float(i as f64 * 0.5),
780 Value::Boolean(i % 2 == 0),
781 Value::Text(format!("event-{i}").into()),
782 ]
783 }
784
785 fn full_type_schema_and_row(seed: u8) -> (ProjectionSchema, Row) {
786 let types_and_values = vec![
787 (DataType::Nullable, Value::Null),
788 (DataType::Integer, Value::Integer(i64::MIN + seed as i64)),
789 (
790 DataType::UnsignedInteger,
791 Value::UnsignedInteger(u64::MAX - seed as u64),
792 ),
793 (
794 DataType::Float,
795 Value::Float(f64::from_bits(0x4009_21fb_5444_2d18)),
796 ),
797 (DataType::Text, Value::Text(format!("text-{seed}").into())),
798 (DataType::Blob, Value::Blob(vec![0, seed, 255])),
799 (DataType::Boolean, Value::Boolean(seed % 2 == 0)),
800 (
801 DataType::Timestamp,
802 Value::Timestamp(-1_700_000_000 + seed as i64),
803 ),
804 (DataType::Duration, Value::Duration(-42 + seed as i64)),
805 (
806 DataType::IpAddr,
807 Value::IpAddr(IpAddr::V6(Ipv6Addr::new(
808 0x2606,
809 0x4700,
810 0,
811 0,
812 0,
813 0,
814 0,
815 seed as u16,
816 ))),
817 ),
818 (DataType::MacAddr, Value::MacAddr([0, 1, 2, 3, 4, seed])),
819 (
820 DataType::Vector,
821 Value::Vector(vec![1.25, -2.5, seed as f32]),
822 ),
823 (
824 DataType::Json,
825 Value::Json(format!(r#"{{"seed":{seed}}}"#).into_bytes()),
826 ),
827 (DataType::Uuid, Value::Uuid([seed; 16])),
828 (DataType::NodeRef, Value::NodeRef(format!("node-{seed}"))),
829 (DataType::EdgeRef, Value::EdgeRef(format!("edge-{seed}"))),
830 (
831 DataType::VectorRef,
832 Value::VectorRef(format!("vectors-{seed}"), 99),
833 ),
834 (
835 DataType::RowRef,
836 Value::RowRef(format!("table-{seed}"), 100),
837 ),
838 (DataType::Color, Value::Color([seed, 2, 3])),
839 (
840 DataType::Email,
841 Value::Email(format!("u{seed}@example.com")),
842 ),
843 (
844 DataType::Url,
845 Value::Url(format!("https://example.com/{seed}")),
846 ),
847 (DataType::Phone, Value::Phone(55_119_000_0000 + seed as u64)),
848 (DataType::Semver, Value::Semver(1_002_003 + seed as u32)),
849 (DataType::Cidr, Value::Cidr(0x0a00_0000 + seed as u32, 24)),
850 (DataType::Date, Value::Date(-20_000 + seed as i32)),
851 (DataType::Time, Value::Time(86_399_000 - seed as u32)),
852 (DataType::Decimal, Value::Decimal(-123_456 + seed as i64)),
853 (DataType::Enum, Value::EnumValue(seed)),
854 (
855 DataType::Array,
856 Value::Array(vec![
857 Value::Integer(seed as i64),
858 Value::Text("nested".into()),
859 ]),
860 ),
861 (
862 DataType::TimestampMs,
863 Value::TimestampMs(1_700_000_000_000 + seed as i64),
864 ),
865 (
866 DataType::Ipv4,
867 Value::Ipv4(u32::from(Ipv4Addr::new(192, 0, 2, seed))),
868 ),
869 (DataType::Ipv6, Value::Ipv6(Ipv6Addr::LOCALHOST.octets())),
870 (
871 DataType::Subnet,
872 Value::Subnet(0xc000_0200 + seed as u32, 0xffff_ff00),
873 ),
874 (DataType::Port, Value::Port(8000 + seed as u16)),
875 (
876 DataType::Latitude,
877 Value::Latitude(-23_550_000 + seed as i32),
878 ),
879 (
880 DataType::Longitude,
881 Value::Longitude(-46_633_000 + seed as i32),
882 ),
883 (
884 DataType::GeoPoint,
885 Value::GeoPoint(-23_550_000, -46_633_000 + seed as i32),
886 ),
887 (DataType::Country2, Value::Country2(*b"BR")),
888 (DataType::Country3, Value::Country3(*b"BRA")),
889 (DataType::Lang2, Value::Lang2(*b"pt")),
890 (DataType::Lang5, Value::Lang5(*b"pt-BR")),
891 (DataType::Currency, Value::Currency(*b"BRL")),
892 (
893 DataType::AssetCode,
894 Value::AssetCode(format!("ASSET{seed}")),
895 ),
896 (
897 DataType::Money,
898 Value::Money {
899 asset_code: "BRL".to_string(),
900 minor_units: -1_234_567 + seed as i64,
901 scale: 2,
902 },
903 ),
904 (DataType::ColorAlpha, Value::ColorAlpha([seed, 2, 3, 4])),
905 (DataType::BigInt, Value::BigInt(i64::MAX - seed as i64)),
906 (
907 DataType::KeyRef,
908 Value::KeyRef(format!("kv-{seed}"), format!("key-{seed}")),
909 ),
910 (DataType::DocRef, Value::DocRef(format!("docs-{seed}"), 321)),
911 (DataType::TableRef, Value::TableRef(format!("table-{seed}"))),
912 (DataType::PageRef, Value::PageRef(42 + seed as u32)),
913 (DataType::Secret, Value::Secret(vec![seed, 7, 8, 9])),
914 (
915 DataType::Password,
916 Value::Password(format!("argon2id-hash-{seed}")),
917 ),
918 (
919 DataType::TextZstd,
920 Value::Text(format!("toast-text-{seed}").into()),
921 ),
922 (DataType::BlobZstd, Value::Blob(vec![9, 8, 7, seed])),
923 ];
924
925 let columns = types_and_values
926 .iter()
927 .enumerate()
928 .map(|(idx, (data_type, _))| ProjectionColumn {
929 column_id: idx as u32,
930 data_type: *data_type,
931 })
932 .collect();
933 let row = types_and_values
934 .into_iter()
935 .map(|(_, value)| value)
936 .collect();
937 (ProjectionSchema::new(columns), row)
938 }
939
940 fn filled(n: i64) -> AppendOnlyCollection {
942 let mut c = AppendOnlyCollection::new(schema());
943 for i in 1..=n {
944 c.append(i as u64, row(i)).expect("append");
945 }
946 c
947 }
948
949 #[test]
950 fn write_path_never_dual_writes_columnar() {
951 let collection = filled(10);
954 let projection = ColumnarProjection::new(schema(), KEY);
955 assert_eq!(projection.manifest().segments().len(), 0);
956 assert_eq!(projection.manifest().last_materialized_lsn(), 0);
957 assert_eq!(collection.row_scan(collection.latest_lsn()).len(), 10);
959 }
960
961 #[test]
962 fn equivalence_oracle_scan_matches_row_scan() {
963 let collection = filled(500);
965 let mut projection = ColumnarProjection::new(schema(), KEY);
966 projection
967 .emit_at_checkpoint(&collection, 300, TranscodeBudget::default())
968 .expect("emit");
969
970 let pinned = collection.latest_lsn();
971 let via_projection = projection
972 .analytical_scan(&collection, pinned)
973 .expect("scan");
974 let via_row = collection.row_scan(pinned);
975
976 assert_eq!(via_projection.len(), 500);
977 assert_eq!(
978 via_projection, via_row,
979 "projection scan must equal row scan"
980 );
981 }
982
983 #[test]
984 fn columnar_segments_are_actually_exercised() {
985 let collection = filled(300);
988 let mut projection = ColumnarProjection::new(schema(), KEY);
989 let outcome = projection
990 .emit_at_checkpoint(&collection, 300, TranscodeBudget::default())
991 .expect("emit");
992 assert!(outcome.segments_emitted >= 1);
993 assert_eq!(projection.manifest().last_materialized_lsn(), 300);
994 let scan = projection.analytical_scan(&collection, 300).expect("scan");
996 assert_eq!(scan, collection.row_scan(300));
997 }
998
999 #[test]
1000 fn full_value_type_set_round_trips_through_columnar_projection() {
1001 let (schema, first) = full_type_schema_and_row(1);
1002 let (_, second) = full_type_schema_and_row(2);
1003 let mut collection = AppendOnlyCollection::new(schema.clone());
1004 collection.append(1, first).expect("append first");
1005 collection.append(2, second).expect("append second");
1006
1007 let mut projection = ColumnarProjection::new(schema, KEY);
1008 let outcome = projection
1009 .emit_at_checkpoint(&collection, 2, TranscodeBudget::default())
1010 .expect("emit");
1011 assert_eq!(outcome.rows_materialized, 2);
1012 assert_eq!(outcome.rows_deferred, 0);
1013
1014 let via_projection = projection.analytical_scan(&collection, 2).expect("scan");
1015 let via_row = collection.row_scan(2);
1016 assert_eq!(
1017 via_projection, via_row,
1018 "every storable value type must round-trip without coercion or loss"
1019 );
1020 }
1021
1022 #[test]
1023 fn freshness_row_after_checkpoint_is_immediately_visible() {
1024 let mut collection = filled(100);
1027 let mut projection = ColumnarProjection::new(schema(), KEY);
1028 projection
1029 .emit_at_checkpoint(&collection, 100, TranscodeBudget::default())
1030 .expect("emit");
1031 assert_eq!(projection.manifest().last_materialized_lsn(), 100);
1032
1033 collection.append(101, row(101)).expect("append fresh");
1035
1036 let scan = projection.analytical_scan(&collection, 101).expect("scan");
1037 assert_eq!(scan.len(), 101, "fresh row must be visible immediately");
1038 assert_eq!(scan.last().cloned().unwrap(), row(101));
1039 assert_eq!(projection.manifest().last_materialized_lsn(), 100);
1041 }
1042
1043 #[test]
1044 fn as_of_composes_by_pinning_a_historical_lsn() {
1045 let collection = filled(200);
1047 let mut projection = ColumnarProjection::new(schema(), KEY);
1048 projection
1049 .emit_at_checkpoint(&collection, 200, TranscodeBudget::default())
1050 .expect("emit");
1051
1052 for pin in [1u64, 57, 150, 200] {
1053 let via_projection = projection.analytical_scan(&collection, pin).expect("scan");
1054 assert_eq!(
1055 via_projection,
1056 collection.row_scan(pin),
1057 "AS OF {pin} must match row scan"
1058 );
1059 assert_eq!(via_projection.len(), pin as usize);
1060 }
1061 }
1062
1063 #[test]
1064 fn historical_pin_before_projection_coverage_falls_back_to_row_path() {
1065 let collection = filled(300);
1070 let mut projection = ColumnarProjection::new(schema(), KEY);
1071 projection
1072 .emit_at_checkpoint(
1073 &collection,
1074 300,
1075 TranscodeBudget {
1076 max_rows: u64::MAX,
1077 segment_rows: 100,
1078 size_floor_rows: 1,
1079 },
1080 )
1081 .expect("emit segmented projection");
1082
1083 projection.segments.remove(0);
1084 projection.manifest.segments.remove(0);
1085
1086 let pinned = 250;
1087 let via_projection = projection
1088 .analytical_scan(&collection, pinned)
1089 .expect("historical scan");
1090 let via_row = collection.row_scan(pinned);
1091
1092 assert_eq!(
1093 via_projection, via_row,
1094 "historical AS OF must not drop rows older than projection coverage"
1095 );
1096 }
1097
1098 #[test]
1099 fn manifest_entries_are_derived_and_checksummed_and_enveloped() {
1100 let collection = filled(50);
1102 let mut projection = ColumnarProjection::new(schema(), KEY);
1103 projection
1104 .emit_at_checkpoint(&collection, 50, TranscodeBudget::default())
1105 .expect("emit");
1106
1107 let manifest = projection.manifest();
1108 assert!(manifest.all_derived());
1109 assert_eq!(
1110 manifest.durable_entries().count(),
1111 0,
1112 "derived → backup skips"
1113 );
1114 for entry in manifest.segments() {
1115 assert!(entry.derived);
1116 assert_ne!(entry.sealed_crc32, 0);
1117 }
1118
1119 let seg = &projection.segments[0];
1122 let wrong = ColumnarProjection::new(schema(), [9u8; 32]);
1123 let err = wrong
1124 .verify_and_decode_segment(seg, &mut Vec::new())
1125 .expect_err("wrong key must fail");
1126 assert!(matches!(err, ProjectionError::Envelope(_)));
1127 }
1128
1129 #[test]
1130 fn sealed_segment_tamper_is_rejected_by_checksum() {
1131 let collection = filled(20);
1132 let mut projection = ColumnarProjection::new(schema(), KEY);
1133 projection
1134 .emit_at_checkpoint(&collection, 20, TranscodeBudget::default())
1135 .expect("emit");
1136 let mut tampered = projection.segments[0].clone();
1138 tampered.sealed[0] ^= 0xFF;
1139 let err = projection
1140 .verify_and_decode_segment(&tampered, &mut Vec::new())
1141 .expect_err("tamper must be rejected");
1142 assert_eq!(
1143 err,
1144 ProjectionError::CorruptSegment("sealed checksum mismatch")
1145 );
1146 }
1147
1148 #[test]
1149 fn transcoding_budget_completes_and_defers() {
1150 let collection = filled(1000);
1153 let mut projection = ColumnarProjection::new(schema(), KEY);
1154
1155 let budget = TranscodeBudget {
1156 max_rows: 400,
1157 segment_rows: 128,
1158 size_floor_rows: 1,
1159 };
1160 let first = projection
1161 .emit_at_checkpoint(&collection, 1000, budget)
1162 .expect("first checkpoint");
1163 assert!(first.budget_exhausted);
1164 assert_eq!(first.rows_materialized, 400);
1165 assert_eq!(first.rows_deferred, 600);
1166 assert_eq!(projection.manifest().last_materialized_lsn(), 400);
1167
1168 let mid = projection.analytical_scan(&collection, 1000).expect("scan");
1171 assert_eq!(mid, collection.row_scan(1000));
1172 assert_eq!(mid.len(), 1000);
1173
1174 let mut rounds = 1;
1178 loop {
1179 let out = projection
1180 .emit_at_checkpoint(&collection, 1000, budget)
1181 .expect("checkpoint");
1182 rounds += 1;
1183 assert_eq!(
1184 projection.analytical_scan(&collection, 1000).expect("scan"),
1185 collection.row_scan(1000)
1186 );
1187 if !out.budget_exhausted {
1188 assert_eq!(out.rows_deferred, 0);
1189 break;
1190 }
1191 }
1192 assert_eq!(rounds, 3);
1194 assert_eq!(projection.manifest().last_materialized_lsn(), 1000);
1195
1196 let full = projection.analytical_scan(&collection, 1000).expect("scan");
1197 assert_eq!(full, collection.row_scan(1000));
1198 }
1199
1200 #[test]
1201 fn size_floor_skips_tiny_materialization() {
1202 let collection = filled(3);
1204 let mut projection = ColumnarProjection::new(schema(), KEY);
1205 let budget = TranscodeBudget {
1206 max_rows: u64::MAX,
1207 segment_rows: 128,
1208 size_floor_rows: 10,
1209 };
1210 let outcome = projection
1211 .emit_at_checkpoint(&collection, 3, budget)
1212 .expect("emit");
1213 assert!(outcome.floor_skipped);
1214 assert_eq!(outcome.segments_emitted, 0);
1215 assert_eq!(projection.manifest().last_materialized_lsn(), 0);
1216 assert_eq!(
1218 projection.analytical_scan(&collection, 3).expect("scan"),
1219 collection.row_scan(3)
1220 );
1221 }
1222
1223 #[test]
1224 fn drop_and_rebuild_is_repair() {
1225 let collection = filled(300);
1227 let mut projection = ColumnarProjection::new(schema(), KEY);
1228 projection
1229 .emit_at_checkpoint(&collection, 300, TranscodeBudget::default())
1230 .expect("emit");
1231 let before = projection.analytical_scan(&collection, 300).expect("scan");
1232
1233 projection.drop_projection();
1234 assert_eq!(projection.manifest().segments().len(), 0);
1235 assert_eq!(
1237 projection.analytical_scan(&collection, 300).expect("scan"),
1238 collection.row_scan(300)
1239 );
1240
1241 projection
1243 .emit_at_checkpoint(&collection, 300, TranscodeBudget::default())
1244 .expect("rebuild");
1245 let after = projection.analytical_scan(&collection, 300).expect("scan");
1246 assert_eq!(before, after);
1247 }
1248
1249 #[test]
1250 fn repairing_scan_rebuilds_after_projection_artifacts_are_deleted() {
1251 let collection = filled(300);
1252 let mut projection = ColumnarProjection::new(schema(), KEY);
1253 projection
1254 .emit_at_checkpoint(&collection, 300, TranscodeBudget::default())
1255 .expect("emit");
1256 assert!(!projection.segments.is_empty());
1257
1258 projection.segments.clear();
1261
1262 let scan = projection
1263 .repairing_analytical_scan(&collection, 300, TranscodeBudget::default())
1264 .expect("repairing scan");
1265
1266 assert_eq!(scan, collection.row_scan(300));
1267 assert!(!projection.manifest().segments().is_empty());
1268 assert!(!projection.segments.is_empty());
1269 }
1270
1271 #[test]
1272 fn repairing_scan_rebuilds_after_projection_checksum_mismatch() {
1273 let collection = filled(20);
1274 let mut projection = ColumnarProjection::new(schema(), KEY);
1275 projection
1276 .emit_at_checkpoint(&collection, 20, TranscodeBudget::default())
1277 .expect("emit");
1278 let original_segment_id = projection.manifest().segments()[0].segment_id;
1279
1280 projection.segments[0].sealed[0] ^= 0xFF;
1281
1282 let scan = projection
1283 .repairing_analytical_scan(&collection, 20, TranscodeBudget::default())
1284 .expect("repairing scan");
1285
1286 assert_eq!(scan, collection.row_scan(20));
1287 assert_ne!(
1288 projection.manifest().segments()[0].segment_id,
1289 original_segment_id,
1290 "corrupt projection bytes must be replaced by a rebuilt segment"
1291 );
1292 }
1293
1294 #[test]
1295 fn append_rejects_non_monotonic_lsn_and_bad_arity() {
1296 let mut c = AppendOnlyCollection::new(schema());
1297 c.append(5, row(1)).expect("first");
1298 assert!(matches!(
1299 c.append(5, row(2)),
1300 Err(ProjectionError::NonMonotonicLsn { .. })
1301 ));
1302 assert!(matches!(
1303 c.append(6, vec![Value::Integer(1)]),
1304 Err(ProjectionError::RowWidth { .. })
1305 ));
1306 }
1307
1308 #[test]
1309 fn mismatched_types_are_rejected() {
1310 let s = ProjectionSchema::new(vec![ProjectionColumn {
1311 column_id: 0,
1312 data_type: DataType::Integer,
1313 }]);
1314 let mut c = AppendOnlyCollection::new(s);
1315 assert!(matches!(
1316 c.append(1, vec![Value::Text("x".into())]),
1317 Err(ProjectionError::TypeMismatch { .. })
1318 ));
1319 }
1320}