scirs2-io 0.4.2

Input/Output utilities module for SciRS2 (scirs2-io)
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! Apache Iceberg table format support (simplified pure-Rust implementation).
//!
//! Provides an in-memory Apache Iceberg table abstraction with:
//! - Schema definition (fields, types, nullability)
//! - Snapshot-based versioning for time travel
//! - JSON serialization of table metadata
//! - Append-only writes with commit semantics

use std::collections::HashMap;
use std::path::Path;

use serde_json::{json, Value};
use uuid::Uuid;

// ──────────────────────────────────────────────────────────────────────────────
// Error type
// ──────────────────────────────────────────────────────────────────────────────

/// Errors that can arise when working with Iceberg tables.
#[derive(Debug, thiserror::Error)]
pub enum IcebergError {
    /// An underlying I/O error.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    /// Table metadata is malformed or missing required fields.
    #[error("Invalid metadata: {0}")]
    InvalidMetadata(String),
    /// The requested snapshot does not exist in the table history.
    #[error("Snapshot not found: {0}")]
    SnapshotNotFound(i64),
    /// The supplied data does not match the declared schema.
    #[error("Schema mismatch: {0}")]
    SchemaMismatch(String),
    /// JSON serialization / deserialization error.
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
}

// ──────────────────────────────────────────────────────────────────────────────
// Type system
// ──────────────────────────────────────────────────────────────────────────────

/// Iceberg column type.
#[derive(Debug, Clone, PartialEq)]
pub enum IcebergType {
    /// Boolean value.
    Boolean,
    /// 32-bit signed integer.
    Integer,
    /// 64-bit signed integer.
    Long,
    /// 32-bit IEEE 754 floating-point number.
    Float,
    /// 64-bit IEEE 754 floating-point number.
    Double,
    /// UTF-8 string.
    String,
    /// Opaque byte array.
    Bytes,
    /// Calendar date (days since epoch).
    Date,
    /// Microsecond-precision timestamp.
    Timestamp,
    /// Variable-length list whose element type is `Box<IcebergType>`.
    List(Box<IcebergType>),
    /// Nested struct of named fields.
    Struct(Vec<IcebergField>),
}

impl IcebergType {
    /// Return a JSON-compatible type string for metadata serialization.
    fn type_string(&self) -> Value {
        match self {
            IcebergType::Boolean => json!("boolean"),
            IcebergType::Integer => json!("int"),
            IcebergType::Long => json!("long"),
            IcebergType::Float => json!("float"),
            IcebergType::Double => json!("double"),
            IcebergType::String => json!("string"),
            IcebergType::Bytes => json!("binary"),
            IcebergType::Date => json!("date"),
            IcebergType::Timestamp => json!("timestamp"),
            IcebergType::List(elem) => json!({
                "type": "list",
                "element-type": elem.type_string(),
            }),
            IcebergType::Struct(fields) => {
                let serialized: Vec<Value> = fields.iter().map(|f| f.to_json()).collect();
                json!({ "type": "struct", "fields": serialized })
            }
        }
    }

    /// Parse an `IcebergType` from a JSON value produced by `type_string`.
    fn from_json(v: &Value) -> Result<Self, IcebergError> {
        match v {
            Value::String(s) => match s.as_str() {
                "boolean" => Ok(IcebergType::Boolean),
                "int" => Ok(IcebergType::Integer),
                "long" => Ok(IcebergType::Long),
                "float" => Ok(IcebergType::Float),
                "double" => Ok(IcebergType::Double),
                "string" => Ok(IcebergType::String),
                "binary" => Ok(IcebergType::Bytes),
                "date" => Ok(IcebergType::Date),
                "timestamp" => Ok(IcebergType::Timestamp),
                other => Err(IcebergError::InvalidMetadata(format!(
                    "Unknown scalar type: {other}"
                ))),
            },
            Value::Object(map) => {
                let type_tag = map
                    .get("type")
                    .and_then(|t| t.as_str())
                    .ok_or_else(|| IcebergError::InvalidMetadata("Missing 'type' key".into()))?;
                match type_tag {
                    "list" => {
                        let elem_json = map.get("element-type").ok_or_else(|| {
                            IcebergError::InvalidMetadata("List missing element-type".into())
                        })?;
                        Ok(IcebergType::List(Box::new(IcebergType::from_json(
                            elem_json,
                        )?)))
                    }
                    "struct" => {
                        let fields_json =
                            map.get("fields")
                                .and_then(|f| f.as_array())
                                .ok_or_else(|| {
                                    IcebergError::InvalidMetadata(
                                        "Struct missing fields array".into(),
                                    )
                                })?;
                        let fields = fields_json
                            .iter()
                            .map(IcebergField::from_json)
                            .collect::<Result<Vec<_>, _>>()?;
                        Ok(IcebergType::Struct(fields))
                    }
                    other => Err(IcebergError::InvalidMetadata(format!(
                        "Unknown complex type: {other}"
                    ))),
                }
            }
            _ => Err(IcebergError::InvalidMetadata(format!(
                "Unexpected JSON for type: {v}"
            ))),
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Schema
// ──────────────────────────────────────────────────────────────────────────────

/// A single named field in an Iceberg schema or nested struct.
#[derive(Debug, Clone, PartialEq)]
pub struct IcebergField {
    /// Stable, monotonically increasing column identifier.
    pub id: i32,
    /// Column name (case-sensitive).
    pub name: std::string::String,
    /// Declared column type.
    pub field_type: IcebergType,
    /// When `true` the column must not contain null values.
    pub required: bool,
    /// Optional human-readable description.
    pub doc: Option<std::string::String>,
}

impl IcebergField {
    fn to_json(&self) -> Value {
        let mut map = serde_json::Map::new();
        map.insert("id".into(), json!(self.id));
        map.insert("name".into(), json!(self.name));
        map.insert("type".into(), self.field_type.type_string());
        map.insert("required".into(), json!(self.required));
        if let Some(doc) = &self.doc {
            map.insert("doc".into(), json!(doc));
        }
        Value::Object(map)
    }

    fn from_json(v: &Value) -> Result<Self, IcebergError> {
        let id = v["id"]
            .as_i64()
            .ok_or_else(|| IcebergError::InvalidMetadata("Field missing 'id'".into()))?
            as i32;
        let name = v["name"]
            .as_str()
            .ok_or_else(|| IcebergError::InvalidMetadata("Field missing 'name'".into()))?
            .to_string();
        let field_type = IcebergType::from_json(&v["type"])?;
        let required = v["required"].as_bool().unwrap_or(false);
        let doc = v["doc"].as_str().map(|s| s.to_string());
        Ok(IcebergField {
            id,
            name,
            field_type,
            required,
            doc,
        })
    }
}

/// Iceberg table schema, comprising an ordered list of typed fields.
#[derive(Debug, Clone)]
pub struct IcebergSchema {
    /// Monotonically increasing schema identifier.
    pub schema_id: i32,
    /// Ordered list of column descriptors.
    pub fields: Vec<IcebergField>,
}

impl IcebergSchema {
    fn to_json(&self) -> Value {
        json!({
            "schema-id": self.schema_id,
            "type": "struct",
            "fields": self.fields.iter().map(|f| f.to_json()).collect::<Vec<_>>(),
        })
    }

    fn from_json(v: &Value) -> Result<Self, IcebergError> {
        let schema_id = v["schema-id"].as_i64().unwrap_or(0) as i32;
        let fields = v["fields"]
            .as_array()
            .ok_or_else(|| IcebergError::InvalidMetadata("Schema missing 'fields'".into()))?
            .iter()
            .map(IcebergField::from_json)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(IcebergSchema { schema_id, fields })
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Snapshots
// ──────────────────────────────────────────────────────────────────────────────

/// An Iceberg snapshot captures the table state at a specific point in time.
///
/// In the full Iceberg spec a snapshot references a manifest list file which
/// in turn references manifest files describing individual data files. This
/// implementation keeps the row data in-memory instead, but preserves all
/// metadata fields for compatibility with the JSON format.
#[derive(Debug, Clone)]
pub struct IcebergSnapshot {
    /// Globally unique 64-bit snapshot identifier.
    pub snapshot_id: i64,
    /// Snapshot ID of the immediate predecessor, if any.
    pub parent_snapshot_id: Option<i64>,
    /// Monotonically increasing sequence number for ordering.
    pub sequence_number: i64,
    /// Unix time in milliseconds when this snapshot was committed.
    pub timestamp_ms: i64,
    /// Path to the manifest list file (in-memory: descriptive placeholder).
    pub manifest_list: std::string::String,
    /// Arbitrary key-value pairs summarising the commit (e.g. added-files count).
    pub summary: HashMap<std::string::String, std::string::String>,
}

impl IcebergSnapshot {
    fn to_json(&self) -> Value {
        let mut summary_map = serde_json::Map::new();
        for (k, v) in &self.summary {
            summary_map.insert(k.clone(), json!(v));
        }
        let mut obj = serde_json::Map::new();
        obj.insert("snapshot-id".into(), json!(self.snapshot_id));
        if let Some(parent) = self.parent_snapshot_id {
            obj.insert("parent-snapshot-id".into(), json!(parent));
        }
        obj.insert("sequence-number".into(), json!(self.sequence_number));
        obj.insert("timestamp-ms".into(), json!(self.timestamp_ms));
        obj.insert("manifest-list".into(), json!(self.manifest_list));
        obj.insert("summary".into(), Value::Object(summary_map));
        Value::Object(obj)
    }

    fn from_json(v: &Value) -> Result<Self, IcebergError> {
        let snapshot_id = v["snapshot-id"].as_i64().ok_or_else(|| {
            IcebergError::InvalidMetadata("Snapshot missing 'snapshot-id'".into())
        })?;
        let parent_snapshot_id = v["parent-snapshot-id"].as_i64();
        let sequence_number = v["sequence-number"].as_i64().unwrap_or(0);
        let timestamp_ms = v["timestamp-ms"].as_i64().unwrap_or(0);
        let manifest_list = v["manifest-list"].as_str().unwrap_or("").to_string();
        let mut summary = HashMap::new();
        if let Some(s) = v["summary"].as_object() {
            for (k, val) in s {
                if let Some(vs) = val.as_str() {
                    summary.insert(k.clone(), vs.to_string());
                }
            }
        }
        Ok(IcebergSnapshot {
            snapshot_id,
            parent_snapshot_id,
            sequence_number,
            timestamp_ms,
            manifest_list,
            summary,
        })
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Table metadata
// ──────────────────────────────────────────────────────────────────────────────

/// Iceberg table metadata, analogous to the `metadata.json` file on disk.
#[derive(Debug, Clone)]
pub struct IcebergTableMetadata {
    /// Iceberg format version (1 or 2).
    pub format_version: u32,
    /// Globally unique table identifier (UUID v4).
    pub table_uuid: std::string::String,
    /// Canonical location of the table data (e.g. `s3://bucket/prefix/`).
    pub location: std::string::String,
    /// Highest sequence number used so far.
    pub last_sequence_number: i64,
    /// Unix time in milliseconds of the last metadata update.
    pub last_updated_ms: i64,
    /// Highest column ID assigned so far.
    pub last_column_id: i32,
    /// Current table schema.
    pub schema: IcebergSchema,
    /// Ordered list of all snapshots.
    pub snapshots: Vec<IcebergSnapshot>,
    /// ID of the snapshot currently considered "current", if any.
    pub current_snapshot_id: Option<i64>,
}

impl IcebergTableMetadata {
    fn to_json(&self) -> Value {
        let snapshots: Vec<Value> = self.snapshots.iter().map(|s| s.to_json()).collect();
        let mut obj = serde_json::Map::new();
        obj.insert("format-version".into(), json!(self.format_version));
        obj.insert("table-uuid".into(), json!(self.table_uuid));
        obj.insert("location".into(), json!(self.location));
        obj.insert(
            "last-sequence-number".into(),
            json!(self.last_sequence_number),
        );
        obj.insert("last-updated-ms".into(), json!(self.last_updated_ms));
        obj.insert("last-column-id".into(), json!(self.last_column_id));
        obj.insert("schema".into(), self.schema.to_json());
        obj.insert("snapshots".into(), json!(snapshots));
        if let Some(id) = self.current_snapshot_id {
            obj.insert("current-snapshot-id".into(), json!(id));
        }
        Value::Object(obj)
    }

    fn from_json(v: &Value) -> Result<Self, IcebergError> {
        let format_version = v["format-version"].as_u64().unwrap_or(2) as u32;
        let table_uuid = v["table-uuid"].as_str().unwrap_or("").to_string();
        let location = v["location"].as_str().unwrap_or("").to_string();
        let last_sequence_number = v["last-sequence-number"].as_i64().unwrap_or(0);
        let last_updated_ms = v["last-updated-ms"].as_i64().unwrap_or(0);
        let last_column_id = v["last-column-id"].as_i64().unwrap_or(0) as i32;
        let schema = IcebergSchema::from_json(&v["schema"])?;
        let snapshots = v["snapshots"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .map(IcebergSnapshot::from_json)
                    .collect::<Result<Vec<_>, _>>()
            })
            .unwrap_or(Ok(Vec::new()))?;
        let current_snapshot_id = v["current-snapshot-id"].as_i64();
        Ok(IcebergTableMetadata {
            format_version,
            table_uuid,
            location,
            last_sequence_number,
            last_updated_ms,
            last_column_id,
            schema,
            snapshots,
            current_snapshot_id,
        })
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Value type
// ──────────────────────────────────────────────────────────────────────────────

/// A single typed Iceberg cell value.
#[derive(Debug, Clone, PartialEq)]
pub enum IcebergValue {
    /// SQL NULL.
    Null,
    /// Boolean.
    Boolean(bool),
    /// 32-bit signed integer.
    Integer(i32),
    /// 64-bit signed integer.
    Long(i64),
    /// 32-bit floating-point number.
    Float(f32),
    /// 64-bit floating-point number.
    Double(f64),
    /// UTF-8 string.
    String(std::string::String),
    /// Opaque byte array.
    Bytes(Vec<u8>),
}

// ──────────────────────────────────────────────────────────────────────────────
// In-memory Iceberg table
// ──────────────────────────────────────────────────────────────────────────────

/// In-memory Apache Iceberg table for testing and small datasets.
///
/// Stores all column data in `HashMap<column_name, Vec<IcebergValue>>` and
/// maintains a snapshot history for time-travel queries.
pub struct IcebergTable {
    metadata: IcebergTableMetadata,
    /// Current column data, keyed by column name.
    data: HashMap<std::string::String, Vec<IcebergValue>>,
    /// Snapshot row-count history: `snapshot_id -> row_count`.
    snapshot_row_counts: HashMap<i64, usize>,
}

impl IcebergTable {
    // ── Construction ─────────────────────────────────────────────────────────

    /// Create a new empty table at `location` with the given `schema`.
    pub fn new(location: impl Into<std::string::String>, schema: IcebergSchema) -> Self {
        let location = location.into();
        let last_column_id = schema.fields.iter().map(|f| f.id).max().unwrap_or(0);
        let metadata = IcebergTableMetadata {
            format_version: 2,
            table_uuid: Uuid::new_v4().to_string(),
            location: location.clone(),
            last_sequence_number: 0,
            last_updated_ms: current_timestamp_ms(),
            last_column_id,
            schema: schema.clone(),
            snapshots: Vec::new(),
            current_snapshot_id: None,
        };
        let data = schema
            .fields
            .iter()
            .map(|f| (f.name.clone(), Vec::new()))
            .collect();
        IcebergTable {
            metadata,
            data,
            snapshot_row_counts: HashMap::new(),
        }
    }

    // ── Write operations ──────────────────────────────────────────────────────

    /// Append `rows` to the table.
    ///
    /// `rows` is a map from column name to a `Vec` of values. All column
    /// vectors must have the same length; columns not present in `rows` will
    /// have `IcebergValue::Null` appended for each new row.
    pub fn append(
        &mut self,
        rows: HashMap<std::string::String, Vec<IcebergValue>>,
    ) -> Result<(), IcebergError> {
        // Determine row count from the first column supplied.
        let row_count = rows.values().next().map(|v| v.len()).unwrap_or(0);

        // Validate all supplied columns have the same length.
        for (col_name, col_data) in &rows {
            if col_data.len() != row_count {
                return Err(IcebergError::SchemaMismatch(format!(
                    "Column '{col_name}' has {} values but expected {row_count}",
                    col_data.len()
                )));
            }
        }

        // Validate all supplied column names are in the schema.
        for col_name in rows.keys() {
            if !self.data.contains_key(col_name.as_str()) {
                return Err(IcebergError::SchemaMismatch(format!(
                    "Column '{col_name}' not found in schema"
                )));
            }
        }

        // Append data, filling missing columns with Null.
        for field in &self.metadata.schema.fields.clone() {
            let column = self.data.entry(field.name.clone()).or_default();
            if let Some(new_values) = rows.get(&field.name) {
                column.extend(new_values.iter().cloned());
            } else {
                column.extend(std::iter::repeat(IcebergValue::Null).take(row_count));
            }
        }

        self.metadata.last_updated_ms = current_timestamp_ms();
        Ok(())
    }

    // ── Read operations ───────────────────────────────────────────────────────

    /// Return the number of rows currently in the table.
    pub fn num_rows(&self) -> usize {
        self.data.values().next().map(|v| v.len()).unwrap_or(0)
    }

    /// Return the column names in schema order.
    pub fn column_names(&self) -> Vec<&str> {
        self.metadata
            .schema
            .fields
            .iter()
            .map(|f| f.name.as_str())
            .collect()
    }

    /// Read a column as a slice of values. Returns `None` if the column does not exist.
    pub fn read_column(&self, name: &str) -> Option<&[IcebergValue]> {
        self.data.get(name).map(|v| v.as_slice())
    }

    // ── Snapshot management ───────────────────────────────────────────────────

    /// Commit the current state as a new snapshot and return the new snapshot ID.
    pub fn commit_snapshot(&mut self) -> i64 {
        let snapshot_id = generate_snapshot_id();
        let sequence_number = self.metadata.last_sequence_number + 1;
        let row_count = self.num_rows();

        let parent_id = self.metadata.current_snapshot_id;
        let mut summary = HashMap::new();
        summary.insert("operation".to_string(), "append".to_string());
        summary.insert("added-records".to_string(), row_count.to_string());

        let snapshot = IcebergSnapshot {
            snapshot_id,
            parent_snapshot_id: parent_id,
            sequence_number,
            timestamp_ms: current_timestamp_ms(),
            manifest_list: format!(
                "{}/metadata/snap-{}-1-manifest-list.avro",
                self.metadata.location, snapshot_id
            ),
            summary,
        };

        self.snapshot_row_counts.insert(snapshot_id, row_count);
        self.metadata.snapshots.push(snapshot);
        self.metadata.current_snapshot_id = Some(snapshot_id);
        self.metadata.last_sequence_number = sequence_number;
        self.metadata.last_updated_ms = current_timestamp_ms();

        snapshot_id
    }

    /// Look up metadata for a specific snapshot by ID.
    ///
    /// Returns `None` if no snapshot with `snapshot_id` exists.
    pub fn as_of_snapshot(&self, snapshot_id: i64) -> Option<IcebergSnapshot> {
        self.metadata
            .snapshots
            .iter()
            .find(|s| s.snapshot_id == snapshot_id)
            .cloned()
    }

    // ── Metadata I/O ─────────────────────────────────────────────────────────

    /// Write the table metadata as a JSON file to `path`.
    pub fn write_metadata_json(&self, path: &Path) -> Result<(), IcebergError> {
        let json_value = self.metadata.to_json();
        let json_bytes = serde_json::to_vec_pretty(&json_value).map_err(IcebergError::Json)?;
        std::fs::write(path, json_bytes).map_err(IcebergError::Io)
    }

    /// Read table metadata from a JSON file at `path`.
    pub fn read_metadata_json(path: &Path) -> Result<IcebergTableMetadata, IcebergError> {
        let bytes = std::fs::read(path).map_err(IcebergError::Io)?;
        let json_value: Value = serde_json::from_slice(&bytes).map_err(IcebergError::Json)?;
        IcebergTableMetadata::from_json(&json_value)
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────────────────────────────────────

fn current_timestamp_ms() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

fn generate_snapshot_id() -> i64 {
    // Use a combination of timestamp and a small random-ish component derived
    // from the UUID to produce a stable but unique i64 snapshot ID.
    let ts = current_timestamp_ms();
    let uuid_hi = Uuid::new_v4().as_u64_pair().0 as i64;
    ts ^ (uuid_hi & 0x0000_FFFF_FFFF_FFFF)
}

// ──────────────────────────────────────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────────────────────────────────────

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

    fn make_schema() -> IcebergSchema {
        IcebergSchema {
            schema_id: 1,
            fields: vec![
                IcebergField {
                    id: 1,
                    name: "id".to_string(),
                    field_type: IcebergType::Long,
                    required: true,
                    doc: None,
                },
                IcebergField {
                    id: 2,
                    name: "value".to_string(),
                    field_type: IcebergType::Double,
                    required: false,
                    doc: Some("sensor reading".to_string()),
                },
                IcebergField {
                    id: 3,
                    name: "label".to_string(),
                    field_type: IcebergType::String,
                    required: false,
                    doc: None,
                },
            ],
        }
    }

    #[test]
    fn test_iceberg_create_append() {
        let mut table = IcebergTable::new("s3://bucket/test-table", make_schema());
        assert_eq!(table.num_rows(), 0);

        let mut rows = HashMap::new();
        rows.insert(
            "id".to_string(),
            vec![IcebergValue::Long(1), IcebergValue::Long(2)],
        );
        rows.insert(
            "value".to_string(),
            vec![
                IcebergValue::Double(std::f64::consts::PI),
                IcebergValue::Double(std::f64::consts::E),
            ],
        );
        rows.insert(
            "label".to_string(),
            vec![
                IcebergValue::String("a".to_string()),
                IcebergValue::String("b".to_string()),
            ],
        );
        table.append(rows).expect("append failed");
        assert_eq!(table.num_rows(), 2);
    }

    #[test]
    fn test_iceberg_schema() {
        let table = IcebergTable::new("file:///tmp/test", make_schema());
        let names = table.column_names();
        assert_eq!(names, vec!["id", "value", "label"]);
    }

    #[test]
    fn test_iceberg_snapshot() {
        let mut table = IcebergTable::new("file:///tmp/test", make_schema());

        let mut rows = HashMap::new();
        rows.insert("id".to_string(), vec![IcebergValue::Long(42)]);
        rows.insert("value".to_string(), vec![IcebergValue::Double(1.0)]);
        rows.insert(
            "label".to_string(),
            vec![IcebergValue::String("x".to_string())],
        );
        table.append(rows).expect("append failed");

        let snap_id = table.commit_snapshot();
        assert!(snap_id != 0);

        let snap = table.as_of_snapshot(snap_id).expect("snapshot not found");
        assert_eq!(snap.snapshot_id, snap_id);
        assert_eq!(table.metadata.current_snapshot_id, Some(snap_id));
    }

    #[test]
    fn test_iceberg_metadata_json() {
        let mut table = IcebergTable::new("file:///tmp/meta-test", make_schema());

        let mut rows = HashMap::new();
        rows.insert(
            "id".to_string(),
            vec![IcebergValue::Long(1), IcebergValue::Long(2)],
        );
        rows.insert(
            "value".to_string(),
            vec![IcebergValue::Double(0.5), IcebergValue::Double(1.5)],
        );
        rows.insert(
            "label".to_string(),
            vec![
                IcebergValue::String("p".to_string()),
                IcebergValue::String("q".to_string()),
            ],
        );
        table.append(rows).expect("append failed");
        table.commit_snapshot();

        let tmp_dir = std::env::temp_dir();
        let path = tmp_dir.join("iceberg_test_metadata.json");

        table
            .write_metadata_json(&path)
            .expect("write_metadata_json failed");

        let loaded = IcebergTable::read_metadata_json(&path).expect("read_metadata_json failed");

        assert_eq!(loaded.format_version, 2);
        assert_eq!(loaded.schema.fields.len(), 3);
        assert_eq!(loaded.schema.fields[0].name, "id");
        assert_eq!(loaded.schema.fields[1].name, "value");
        assert!(loaded.current_snapshot_id.is_some());
        assert_eq!(
            loaded.current_snapshot_id,
            table.metadata.current_snapshot_id
        );
    }
}