Skip to main content

icechunk_format/
snapshot.rs

1//! Repository state at a point in time (arrays, groups, and manifest references).
2
3use std::{borrow::Cow, collections::BTreeMap, ops::Range, sync::Arc};
4
5use bytes::Bytes;
6use chrono::{DateTime, Utc};
7use flatbuffers::{
8    FlatBufferBuilder, ForwardsUOffset, UnionWIPOffset, Vector, VerifierOptions,
9    WIPOffset,
10};
11use itertools::{Either, Itertools as _};
12use quick_cache::sync::{Cache, GuardResult};
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15
16pub use crate::NodeType;
17use crate::{
18    AttributesId, ChunkIndices, IcechunkFormatError, IcechunkFormatErrorKind,
19    IcechunkResult, ManifestId, NodeId, Path, SnapshotId,
20    flatbuffers::generated,
21    format_constants::SpecVersionBin,
22    lookup_index_by_key,
23    manifest::{Manifest, ManifestExtents, ManifestRef},
24};
25use icechunk_types::{ICResultExt as _, error::ICResultCtxExt as _};
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct DimensionShape {
29    dim_length: u64,
30    num_chunks: u32,
31}
32
33impl DimensionShape {
34    pub fn new(array_length: u64, num_chunks: u32) -> Self {
35        Self { dim_length: array_length, num_chunks }
36    }
37    pub fn array_length(&self) -> u64 {
38        self.dim_length
39    }
40    pub fn num_chunks(&self) -> u32 {
41        self.num_chunks
42    }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct ArrayShape(Vec<DimensionShape>);
47
48impl ArrayShape {
49    pub fn len(&self) -> usize {
50        self.0.len()
51    }
52    pub fn is_empty(&self) -> bool {
53        self.0.is_empty()
54    }
55
56    pub fn get(&self, ax: usize) -> Option<DimensionShape> {
57        if ax > self.len() - 1 { None } else { Some(self.0[ax].clone()) }
58    }
59
60    pub fn iter(&self) -> impl Iterator<Item = &DimensionShape> {
61        self.0.iter()
62    }
63
64    pub fn num_chunks(&self) -> impl Iterator<Item = u32> {
65        self.0.iter().map(|x| x.num_chunks())
66    }
67
68    pub fn new<I>(it: I) -> Option<Self>
69    where
70        I: IntoIterator<Item = (u64, u32)>,
71    {
72        let v = it.into_iter().map(|(al, nc)| Some(DimensionShape::new(al, nc)));
73        v.collect::<Option<Vec<_>>>().map(Self)
74    }
75
76    /// Validates the provided chunk coordinates for the array.
77    ///
78    /// This function checks if the provided chunk indices are valid for the array.
79    ///
80    /// # Arguments
81    ///
82    /// * `coord` - The chunk indices to validate.
83    ///
84    /// # Returns
85    ///
86    /// An bool indicating whether the chunk coordinates are valid.
87    ///
88    /// # Errors
89    ///
90    /// Returns false if the chunk coordinates are invalid.
91    pub fn valid_chunk_coord(&self, coord: &ChunkIndices) -> bool {
92        coord
93            .0
94            .iter()
95            .zip(self.num_chunks())
96            .all(|(index, index_permitted)| *index <= (index_permitted.max(1) - 1))
97    }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101pub enum DimensionName {
102    NotSpecified,
103    Name(String),
104}
105
106impl From<Option<&str>> for DimensionName {
107    fn from(value: Option<&str>) -> Self {
108        match value {
109            Some(s) => s.into(),
110            None => DimensionName::NotSpecified,
111        }
112    }
113}
114
115impl From<DimensionName> for Option<String> {
116    fn from(value: DimensionName) -> Option<String> {
117        match value {
118            DimensionName::NotSpecified => None,
119            DimensionName::Name(name) => Some(name),
120        }
121    }
122}
123
124impl From<&str> for DimensionName {
125    fn from(value: &str) -> Self {
126        if value.is_empty() {
127            DimensionName::NotSpecified
128        } else {
129            DimensionName::Name(value.to_string())
130        }
131    }
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135pub enum NodeData {
136    Array {
137        shape: ArrayShape,
138        dimension_names: Option<Vec<DimensionName>>,
139        manifests: Vec<ManifestRef>,
140    },
141    Group,
142}
143
144#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
145pub struct NodeSnapshot {
146    pub id: NodeId,
147    pub path: Path,
148    pub user_data: Bytes,
149    pub node_data: NodeData,
150}
151
152impl NodeSnapshot {
153    pub fn node_type(&self) -> NodeType {
154        match &self.node_data {
155            NodeData::Group => NodeType::Group,
156            NodeData::Array { .. } => NodeType::Array,
157        }
158    }
159}
160
161impl From<&generated::ObjectId8> for NodeId {
162    fn from(value: &generated::ObjectId8) -> Self {
163        NodeId::new(value.0)
164    }
165}
166
167impl From<&generated::ObjectId12> for ManifestId {
168    fn from(value: &generated::ObjectId12) -> Self {
169        ManifestId::new(value.0)
170    }
171}
172
173impl From<&generated::ObjectId12> for AttributesId {
174    fn from(value: &generated::ObjectId12) -> Self {
175        AttributesId::new(value.0)
176    }
177}
178
179impl<'a> From<generated::ManifestRef<'a>> for ManifestRef {
180    fn from(value: generated::ManifestRef<'a>) -> Self {
181        let extents = ManifestExtents::from_ranges_iter(
182            value
183                .extents()
184                .iter()
185                .map(|range| Range { start: range.from(), end: range.to() }),
186        );
187        ManifestRef { object_id: value.object_id().into(), extents }
188    }
189}
190
191impl TryFrom<&generated::DimensionShape> for DimensionShape {
192    type Error = IcechunkFormatError;
193
194    fn try_from(value: &generated::DimensionShape) -> Result<Self, Self::Error> {
195        if value.chunk_length() == 0 && value.array_length() != 0 {
196            return Err(IcechunkFormatErrorKind::InvalidArrayMetadata(format!(
197                "Array metadata has chunk_length = 0 while array_length={:?}",
198                value.array_length()
199            )))
200            .capture();
201        }
202        let num_chunks = if value.chunk_length() == 0 {
203            0
204        } else {
205            value.array_length().div_ceil(value.chunk_length()) as u32
206        };
207        Ok(DimensionShape { dim_length: value.array_length(), num_chunks })
208    }
209}
210
211impl<'a> From<&generated::DimensionShapeV2<'a>> for DimensionShape {
212    fn from(value: &generated::DimensionShapeV2<'a>) -> Self {
213        DimensionShape {
214            dim_length: value.array_length(),
215            num_chunks: value.num_chunks(),
216        }
217    }
218}
219
220impl<'a> TryFrom<generated::ArrayNodeData<'a>> for NodeData {
221    type Error = IcechunkFormatError;
222
223    fn try_from(value: generated::ArrayNodeData<'a>) -> Result<Self, Self::Error> {
224        let dimension_names = value
225            .dimension_names()
226            .map(|dn| dn.iter().map(|name| name.name().into()).collect());
227        // In our flatbuffers the V1 `shape` is required and will be an empty `[]` for V2 repos
228        // Note that `shape` is *also* `[]` for scalars in V1 repos.
229        // So we branch on `shape_v2` which is optional, and thus None, on V1 repos.
230        let shape = ArrayShape(match value.shape_v2() {
231            None => value
232                .shape()
233                .iter()
234                .map(|dim| dim.try_into())
235                .collect::<Result<Vec<_>, IcechunkFormatError>>()?,
236            Some(x) => x.iter().map(|dim| (&dim).into()).collect(),
237        });
238        let manifests = value.manifests().iter().map(|m| m.into()).collect();
239        Ok(Self::Array { shape, dimension_names, manifests })
240    }
241}
242
243impl<'a> From<generated::GroupNodeData<'a>> for NodeData {
244    fn from(_: generated::GroupNodeData<'a>) -> Self {
245        Self::Group
246    }
247}
248
249impl<'a> TryFrom<generated::NodeSnapshot<'a>> for NodeSnapshot {
250    type Error = IcechunkFormatError;
251
252    fn try_from(value: generated::NodeSnapshot<'a>) -> Result<Self, Self::Error> {
253        #[expect(clippy::expect_used, clippy::panic)]
254        let node_data: NodeData = match value.node_data_type() {
255            generated::NodeData::Array => value
256                .node_data_as_array()
257                .expect("Bug in flatbuffers library")
258                .try_into()?,
259            generated::NodeData::Group => {
260                value.node_data_as_group().expect("Bug in flatbuffers library").into()
261            }
262            x => panic!("Invalid node data type in flatbuffers file {x:?}"),
263        };
264        let res = NodeSnapshot {
265            id: value.id().into(),
266            path: Path::from_trusted(value.path()),
267            node_data,
268            user_data: Bytes::copy_from_slice(value.user_data().bytes()),
269        };
270        Ok(res)
271    }
272}
273
274impl From<&generated::ManifestFileInfo> for ManifestFileInfo {
275    fn from(value: &generated::ManifestFileInfo) -> Self {
276        Self {
277            id: value.id().into(),
278            size_bytes: value.size_bytes(),
279            num_chunk_refs: value.num_chunk_refs(),
280        }
281    }
282}
283
284impl TryFrom<&generated::ManifestFileInfoV2<'_>> for ManifestFileInfo {
285    type Error = IcechunkFormatError;
286
287    fn try_from(value: &generated::ManifestFileInfoV2<'_>) -> Result<Self, Self::Error> {
288        let id = value.id().map(|id| id.into()).ok_or_else(|| {
289            IcechunkFormatError::capture(IcechunkFormatErrorKind::InvalidFlatBuffer(
290                flatbuffers::InvalidFlatbuffer::MissingRequiredField {
291                    required: Cow::Borrowed("id"),
292                    error_trace: Default::default(),
293                },
294            ))
295        })?;
296        Ok(Self {
297            id,
298            size_bytes: value.size_bytes(),
299            num_chunk_refs: value.num_chunk_refs(),
300        })
301    }
302}
303
304pub type SnapshotProperties = BTreeMap<String, Value>;
305
306/// Insert a key-value pair into the `__icechunk` namespace object within snapshot properties.
307/// Creates the `__icechunk` object if it doesn't exist.
308pub fn inject_icechunk_metadata(
309    properties: &mut SnapshotProperties,
310    key: &str,
311    value: Value,
312) {
313    match properties.get_mut("__icechunk") {
314        Some(Value::Object(map)) => {
315            map.insert(key.to_string(), value);
316        }
317        _ => {
318            properties
319                .insert("__icechunk".to_string(), serde_json::json!({ key: value }));
320        }
321    }
322}
323
324#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Eq, Hash)]
325pub struct ManifestFileInfo {
326    pub id: ManifestId,
327    pub size_bytes: u64,
328    pub num_chunk_refs: u32,
329}
330
331impl ManifestFileInfo {
332    pub fn new(manifest: &Manifest, size_bytes: u64) -> Self {
333        Self {
334            id: manifest.id().clone(),
335            num_chunk_refs: manifest.len() as u32,
336            size_bytes,
337        }
338    }
339}
340
341// It is _extremely_ common to set/get chunks in large batches sequentially.
342// Without a cache we incur the cost of repeatedly decoding the flatbuffer.
343// This cache is very small (size 2 currently), because we could cache a large number of
344// snapshots. The size of 2 is fine for typically workloads that iterate sequentially
345// through nodes.
346// We cannot choose 1 because of a bug in the `quick_cache` dependency
347// where a size-1 cache is effectively no cache
348// https://github.com/arthurprs/quick-cache/issues/105
349const SNAPSHOT_NODE_CACHE_SIZE: usize = 2;
350
351pub struct Snapshot {
352    buffer: Vec<u8>,
353    spec_version: SpecVersionBin,
354    node_cache: Cache<Path, Arc<NodeSnapshot>>,
355}
356
357impl std::fmt::Debug for Snapshot {
358    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
359        let nodes =
360            self.iter().map(|n| n.map(|n| n.path.to_string())).collect::<Vec<_>>();
361        #[expect(deprecated)]
362        f.debug_struct("Snapshot")
363            .field("id", &self.id())
364            .field("parent_id", &self.parent_id())
365            .field("flushed_at", &self.flushed_at())
366            .field("nodes", &nodes)
367            .field(
368                "manifests",
369                &self.manifest_files().collect::<IcechunkResult<Vec<_>>>(),
370            )
371            .field("message", &self.message())
372            .field("metadata", &self.metadata())
373            .finish_non_exhaustive()
374    }
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, Hash)]
378pub struct SnapshotInfo {
379    pub id: SnapshotId,
380    pub parent_id: Option<SnapshotId>,
381    pub flushed_at: DateTime<Utc>,
382    pub message: String,
383    pub metadata: SnapshotProperties,
384}
385
386impl TryFrom<&Snapshot> for SnapshotInfo {
387    type Error = IcechunkFormatError;
388
389    fn try_from(value: &Snapshot) -> Result<Self, Self::Error> {
390        #[expect(deprecated)]
391        Ok(Self {
392            id: value.id().clone(),
393            parent_id: value.parent_id().clone(),
394            flushed_at: value.flushed_at()?,
395            message: value.message().clone(),
396            metadata: value.metadata()?.clone(),
397        })
398    }
399}
400
401impl SnapshotInfo {
402    pub fn is_initial(&self) -> bool {
403        self.id == Snapshot::INITIAL_SNAPSHOT_ID
404    }
405}
406
407impl SnapshotId {
408    pub fn is_initial(&self) -> bool {
409        *self == Snapshot::INITIAL_SNAPSHOT_ID
410    }
411}
412
413static ROOT_OPTIONS: VerifierOptions = VerifierOptions {
414    max_depth: 64,
415    max_tables: 50_000_000,
416    max_apparent_size: 1 << 31, // taken from the default
417    ignore_missing_null_terminator: true,
418};
419
420impl Snapshot {
421    pub const INITIAL_COMMIT_MESSAGE: &'static str = "Repository initialized";
422    pub const INITIAL_SNAPSHOT_ID: SnapshotId = SnapshotId::new([
423        0x0b, 0x1c, 0xc8, 0xd6, 0x78, 0x75, 0x80, 0xf0, 0xe3, 0x3a, 0x65,
424        0x34, // Decodes as 1CECHNKREP0F1RSTCMT0
425    ]);
426
427    pub fn from_buffer(
428        spec_version: SpecVersionBin,
429        buffer: Vec<u8>,
430    ) -> IcechunkResult<Snapshot> {
431        let _ = flatbuffers::root_with_opts::<generated::Snapshot<'_>>(
432            &ROOT_OPTIONS,
433            buffer.as_slice(),
434        )
435        .capture()?;
436        Ok(Snapshot {
437            buffer,
438            spec_version,
439            // this number is low because we cache a very large number of snapshot nodes.
440            node_cache: Cache::new(SNAPSHOT_NODE_CACHE_SIZE),
441        })
442    }
443
444    pub fn bytes(&self) -> &[u8] {
445        self.buffer.as_slice()
446    }
447
448    #[expect(clippy::too_many_arguments)]
449    pub fn from_iter<I>(
450        id: Option<SnapshotId>,
451        parent_id: Option<SnapshotId>,
452        spec_version: SpecVersionBin,
453        message: &str,
454        properties: Option<SnapshotProperties>,
455        mut manifest_files: Vec<ManifestFileInfo>,
456        flushed_at: Option<DateTime<Utc>>,
457        sorted_iter: I,
458    ) -> IcechunkResult<Self>
459    where
460        I: IntoIterator<Item = IcechunkResult<NodeSnapshot>>,
461    {
462        // TODO: what's a good capacity?
463        let mut builder = FlatBufferBuilder::with_capacity(4_096);
464
465        manifest_files.sort_by(|a, b| a.id.cmp(&b.id));
466        let (manifest_files_v1, manifest_files_v2) = match spec_version {
467            SpecVersionBin::V1 => {
468                let ms1 = manifest_files
469                    .iter()
470                    .map(|mfi| {
471                        let id = generated::ObjectId12::new(&mfi.id.0);
472                        generated::ManifestFileInfo::new(
473                            &id,
474                            mfi.size_bytes,
475                            mfi.num_chunk_refs,
476                        )
477                    })
478                    .collect::<Vec<_>>();
479                let ms1 = builder.create_vector(&ms1);
480                let ms2 = None;
481                (ms1, ms2)
482            }
483            SpecVersionBin::V2 => {
484                let ms2 = manifest_files
485                    .iter()
486                    .map(|mfi| {
487                        let id = generated::ObjectId12::new(&mfi.id.0);
488
489                        let args = generated::ManifestFileInfoV2Args {
490                            id: Some(&id),
491                            size_bytes: mfi.size_bytes,
492                            num_chunk_refs: mfi.num_chunk_refs,
493                            extra: None,
494                        };
495                        generated::ManifestFileInfoV2::create(&mut builder, &args)
496                    })
497                    .collect::<Vec<_>>();
498                let ms2 = builder.create_vector(&ms2);
499                let ms1 = builder.create_vector::<generated::ManifestFileInfo>(&[]);
500                (ms1, Some(ms2))
501            }
502        };
503
504        let metadata_items: Vec<_> = properties
505            .unwrap_or_default()
506            .iter()
507            .map(|(k, v)| {
508                let name = builder.create_shared_string(k.as_str());
509                let serialized = if spec_version == SpecVersionBin::V1 {
510                    rmp_serde::to_vec(v).map_err(Box::new).capture()?
511                } else {
512                    flexbuffers::to_vec(v).map_err(Box::new).capture()?
513                };
514
515                let value = builder.create_vector(serialized.as_slice());
516                Ok::<_, IcechunkFormatError>(generated::MetadataItem::create(
517                    &mut builder,
518                    &generated::MetadataItemArgs { name: Some(name), value: Some(value) },
519                ))
520            })
521            .try_collect()?;
522        let metadata_items = builder.create_vector(metadata_items.as_slice());
523
524        let message = builder.create_string(message);
525        // Icechunk 2.0 no longer uses this field
526        let parent_id = parent_id.map(|oid| generated::ObjectId12::new(&oid.0));
527        let flushed_at = flushed_at.unwrap_or_else(Utc::now).timestamp_micros() as u64;
528        let id = generated::ObjectId12::new(&id.unwrap_or_else(SnapshotId::random).0);
529
530        let nodes: Vec<_> = sorted_iter
531            .into_iter()
532            .map(|node| node.and_then(|node| mk_node(&mut builder, &node, spec_version)))
533            .try_collect()?;
534        let nodes = builder.create_vector(&nodes);
535
536        let snap = generated::Snapshot::create(
537            &mut builder,
538            &generated::SnapshotArgs {
539                id: Some(&id),
540                parent_id: parent_id.as_ref(),
541                nodes: Some(nodes),
542                flushed_at,
543                message: Some(message),
544                metadata: Some(metadata_items),
545                manifest_files: Some(manifest_files_v1),
546                manifest_files_v2,
547                ..Default::default()
548            },
549        );
550
551        builder.finish(snap, Some("Ichk"));
552        let (mut buffer, offset) = builder.collapse();
553        buffer.drain(0..offset);
554        buffer.shrink_to_fit();
555        Ok(Snapshot {
556            buffer,
557            spec_version,
558            // this number is low because we cache a very large number of snapshot nodes.
559            node_cache: Cache::new(SNAPSHOT_NODE_CACHE_SIZE),
560        })
561    }
562
563    pub fn initial(spec_version: SpecVersionBin) -> IcechunkResult<Self> {
564        let mut properties = SnapshotProperties::default();
565        inject_icechunk_metadata(&mut properties, "is_root", Value::from(true));
566        let nodes = Vec::<IcechunkResult<NodeSnapshot>>::new();
567        Self::from_iter(
568            Some(Self::INITIAL_SNAPSHOT_ID),
569            None,
570            spec_version,
571            Self::INITIAL_COMMIT_MESSAGE,
572            Some(properties),
573            Default::default(),
574            None,
575            nodes,
576        )
577    }
578
579    #[expect(unsafe_code)]
580    fn root(&self) -> generated::Snapshot<'_> {
581        // SAFETY: self.buffer was serialized by our own flatbuffers serialization code.
582        // We skip validation for performance; a corrupt buffer here indicates
583        // file corruption or a bad Icechunk implementation, not a caller error.
584        unsafe { flatbuffers::root_unchecked::<generated::Snapshot<'_>>(&self.buffer) }
585    }
586
587    pub fn id(&self) -> SnapshotId {
588        SnapshotId::new(self.root().id().0)
589    }
590
591    #[deprecated(
592        since = "2.0.0",
593        note = "New versions of icechunk don't use this field and initialize it to None"
594    )]
595    pub fn parent_id(&self) -> Option<SnapshotId> {
596        self.root().parent_id().map(|pid| SnapshotId::new(pid.0))
597    }
598
599    pub fn metadata(&self) -> IcechunkResult<SnapshotProperties> {
600        self.root()
601            .metadata()
602            .iter()
603            .map(|item| {
604                let key = item.name().to_string();
605                let value = if self.spec_version == SpecVersionBin::V1 {
606                    rmp_serde::from_slice(item.value().bytes())
607                        .map_err(Box::new)
608                        .capture()?
609                } else {
610                    flexbuffers::from_slice(item.value().bytes())
611                        .map_err(Box::new)
612                        .capture()?
613                };
614                Ok((key, value))
615            })
616            .try_collect()
617    }
618
619    pub fn flushed_at(&self) -> IcechunkResult<DateTime<Utc>> {
620        let ts = self.root().flushed_at();
621        let ts: i64 = ts
622            .try_into()
623            .map_err(|_| IcechunkFormatErrorKind::InvalidTimestamp)
624            .capture()?;
625        DateTime::from_timestamp_micros(ts)
626            .ok_or(IcechunkFormatErrorKind::InvalidTimestamp)
627            .capture()
628    }
629
630    pub fn message(&self) -> String {
631        self.root().message().to_string()
632    }
633
634    pub fn manifest_files(
635        &self,
636    ) -> impl Iterator<Item = IcechunkResult<ManifestFileInfo>> + '_ {
637        let root = self.root();
638        if let Some(mf2) = root.manifest_files_v2() {
639            Either::Left(mf2.iter().map(|mf| (&mf).try_into()))
640        } else {
641            Either::Right(root.manifest_files().iter().map(|mf| Ok(mf.into())))
642        }
643    }
644
645    /// Cretase a new `Snapshot` with all the same data as `new_child` but `self` as parent
646    #[deprecated(
647        since = "2.0.0",
648        note = "Shouldn't be necessary after 2.0, only to support Icechunk 1 repos"
649    )]
650    pub fn adopt(&self, new_child: &Snapshot) -> IcechunkResult<Self> {
651        // Rust flatbuffers implementation doesn't allow mutation of scalars, so we need to
652        // create a whole new buffer and write to it in full
653
654        Snapshot::from_iter(
655            Some(new_child.id()),
656            Some(self.id()),
657            SpecVersionBin::V1, // 2.0 doesn't use adopt
658            &new_child.message(),
659            Some(new_child.metadata()?.clone()),
660            new_child.manifest_files().try_collect()?,
661            Some(new_child.flushed_at()?),
662            new_child.iter(),
663        )
664    }
665
666    fn _get_node(&self, path: &Path) -> IcechunkResult<NodeSnapshot> {
667        let res = self
668            .root()
669            .nodes()
670            .lookup_by_key(path.to_string().as_str(), |node, path| node.path().cmp(path))
671            .ok_or_else(|| IcechunkFormatErrorKind::NodeNotFound { path: path.clone() })
672            .capture()?;
673        res.try_into()
674    }
675
676    pub fn get_node(&self, path: &Path) -> IcechunkResult<Arc<NodeSnapshot>> {
677        use GuardResult::*;
678        match self.node_cache.get_value_or_guard(path, None) {
679            Value(node) => Ok(node),
680            Timeout => Ok(Arc::new(self._get_node(path)?)),
681            Guard(guard) => {
682                let node = self._get_node(path)?;
683                let node = Arc::new(node);
684                let _ = guard.insert(Arc::clone(&node));
685                Ok(node)
686            }
687        }
688    }
689
690    pub fn get_node_index(&self, path: &Path) -> IcechunkResult<usize> {
691        let path_str = path.to_string();
692        let res =
693            lookup_index_by_key(self.root().nodes(), path_str.as_str(), |node, path| {
694                node.path().cmp(path)
695            })
696            .ok_or_else(|| IcechunkFormatErrorKind::NodeNotFound { path: path.clone() })
697            .capture()?;
698        Ok(res)
699    }
700
701    pub fn iter(&self) -> impl Iterator<Item = IcechunkResult<NodeSnapshot>> + '_ {
702        self.root().nodes().iter().map(|node| node.try_into().inject())
703    }
704
705    pub fn iter_arc(
706        self: Arc<Self>,
707        parent_group: &Path,
708    ) -> impl Iterator<Item = IcechunkResult<NodeSnapshot>> + use<> {
709        NodeIterator::new(self, parent_group)
710    }
711
712    pub fn len(&self) -> usize {
713        self.root().nodes().len()
714    }
715
716    #[must_use]
717    pub fn is_empty(&self) -> bool {
718        self.len() == 0
719    }
720
721    pub fn manifest_info(
722        &self,
723        id: &ManifestId,
724    ) -> IcechunkResult<Option<ManifestFileInfo>> {
725        let root = self.root();
726        if let Some(mf2) = root.manifest_files_v2() {
727            mf2.iter()
728                .find(|mf| mf.id().is_some_and(|mid| mid.0 == id.0))
729                .map(|mf| (&mf).try_into())
730                .transpose()
731        } else {
732            Ok(root
733                .manifest_files()
734                .iter()
735                .find(|mi| mi.id().0 == id.0)
736                .map(|man| man.into()))
737        }
738    }
739}
740
741struct NodeIterator {
742    snapshot: Arc<Snapshot>,
743    next_index: usize,
744    prefix: String,
745}
746
747impl NodeIterator {
748    fn new(snapshot: Arc<Snapshot>, parent_group: &Path) -> Self {
749        let next_index = snapshot.get_node_index(parent_group).unwrap_or_default();
750        let prefix = parent_group.to_string();
751        let prefix = if prefix == "/" { String::new() } else { prefix };
752        NodeIterator { snapshot, next_index, prefix }
753    }
754}
755
756impl Iterator for NodeIterator {
757    type Item = IcechunkResult<NodeSnapshot>;
758
759    fn next(&mut self) -> Option<Self::Item> {
760        let nodes = self.snapshot.root().nodes();
761        loop {
762            // we need to loop over all nodes starting from the index
763            // until we are sure we'll see no more children
764            if self.next_index >= nodes.len() {
765                return None;
766            }
767
768            let node: IcechunkResult<NodeSnapshot> =
769                nodes.get(self.next_index).try_into();
770
771            match node {
772                Ok(res) => {
773                    let node_path = res.path.to_string();
774                    if let Some(after_prefix) =
775                        node_path.strip_prefix(self.prefix.as_str())
776                        && (after_prefix.is_empty() || after_prefix.starts_with('/'))
777                    {
778                        self.next_index += 1;
779                        return Some(Ok(res));
780                    } else if node_path.as_str() > self.prefix.as_str()
781                        && !node_path.starts_with(self.prefix.as_str())
782                    {
783                        // We've passed all possible children of the prefix
784                        return None;
785                    } else {
786                        // Not a match but there may be matches later (foo-bar" comes before "foo/bar")
787                        self.next_index += 1;
788                    }
789                }
790                Err(err) => return Some(Err(err)),
791            }
792        }
793    }
794}
795
796fn mk_node<'bldr>(
797    builder: &mut FlatBufferBuilder<'bldr>,
798    node: &NodeSnapshot,
799    spec_version: SpecVersionBin,
800) -> IcechunkResult<WIPOffset<generated::NodeSnapshot<'bldr>>> {
801    let id = generated::ObjectId8::new(&node.id.0);
802    let path = builder.create_string(node.path.to_string().as_str());
803    let (node_data_type, node_data) =
804        mk_node_data(builder, &node.node_data, spec_version)?;
805    let user_data = Some(builder.create_vector(&node.user_data));
806    Ok(generated::NodeSnapshot::create(
807        builder,
808        &generated::NodeSnapshotArgs {
809            id: Some(&id),
810            path: Some(path),
811            node_data_type,
812            node_data,
813            user_data,
814            ..Default::default()
815        },
816    ))
817}
818
819type ShapeV1<'a> = WIPOffset<Vector<'a, generated::DimensionShape>>;
820type ShapeV2<'a> =
821    WIPOffset<Vector<'a, ForwardsUOffset<generated::DimensionShapeV2<'a>>>>;
822
823fn mk_array_shapes<'a>(
824    builder: &mut FlatBufferBuilder<'a>,
825    spec_version: SpecVersionBin,
826    shape: &ArrayShape,
827) -> (Option<ShapeV1<'a>>, Option<ShapeV2<'a>>) {
828    use SpecVersionBin::*;
829    match spec_version {
830        V1 => {
831            let shape = shape
832                .0
833                .iter()
834                .map(|ds| {
835                    let chunk_length = if ds.num_chunks == 0 {
836                        debug_assert_eq!(ds.dim_length, 0);
837                        0
838                    } else {
839                        // FIXME: this can be *very* wrong, but I'm not sure it really matters
840                        //        we still preserve num_chunks, and return the proper Zarr JSON metadata
841                        //        which is stored in NodeData::user_data which stores the zarr.json exactly
842                        //        as provided by Zarr
843                        ds.dim_length.div_ceil(ds.num_chunks as u64)
844                    };
845
846                    generated::DimensionShape::new(ds.dim_length, chunk_length)
847                })
848                .collect::<Vec<_>>();
849            (Some(builder.create_vector(shape.as_slice())), None)
850        }
851        V2 => {
852            let shape = shape
853                .0
854                .iter()
855                .map(|ds| {
856                    generated::DimensionShapeV2::create(
857                        builder,
858                        &generated::DimensionShapeV2Args {
859                            array_length: ds.dim_length,
860                            num_chunks: ds.num_chunks,
861                        },
862                    )
863                })
864                .collect::<Vec<_>>();
865            let empty_shape_for_v1_compat =
866                builder.create_vector(&[] as &[generated::DimensionShape]);
867            (
868                Some(empty_shape_for_v1_compat),
869                Some(builder.create_vector(shape.as_slice())),
870            )
871        }
872    }
873}
874
875fn mk_node_data(
876    builder: &mut FlatBufferBuilder<'_>,
877    node_data: &NodeData,
878    spec_version: SpecVersionBin,
879) -> IcechunkResult<(generated::NodeData, Option<WIPOffset<UnionWIPOffset>>)> {
880    match node_data {
881        NodeData::Array { manifests, dimension_names, shape } => {
882            let manifests = manifests
883                .iter()
884                .map(|manref| {
885                    let object_id = generated::ObjectId12::new(&manref.object_id.0);
886                    let extents = manref
887                        .extents
888                        .iter()
889                        .map(|range| {
890                            generated::ChunkIndexRange::new(range.start, range.end)
891                        })
892                        .collect::<Vec<_>>();
893                    let extents = builder.create_vector(&extents);
894                    generated::ManifestRef::create(
895                        builder,
896                        &generated::ManifestRefArgs {
897                            object_id: Some(&object_id),
898                            extents: Some(extents),
899                        },
900                    )
901                })
902                .collect::<Vec<_>>();
903            let manifests = builder.create_vector(manifests.as_slice());
904            let dimensions = dimension_names.as_ref().map(|dn| {
905                let names = dn
906                    .iter()
907                    .map(|n| match n {
908                        DimensionName::Name(s) => {
909                            let n = builder.create_shared_string(s.as_str());
910                            generated::DimensionName::create(
911                                builder,
912                                &generated::DimensionNameArgs { name: Some(n) },
913                            )
914                        }
915                        DimensionName::NotSpecified => generated::DimensionName::create(
916                            builder,
917                            &generated::DimensionNameArgs { name: None },
918                        ),
919                    })
920                    .collect::<Vec<_>>();
921                builder.create_vector(names.as_slice())
922            });
923            let (shape_v1, shape_v2) = mk_array_shapes(builder, spec_version, shape);
924            let node_data = generated::ArrayNodeData::create(
925                builder,
926                &generated::ArrayNodeDataArgs {
927                    manifests: Some(manifests),
928                    shape: shape_v1,
929                    shape_v2,
930                    dimension_names: dimensions,
931                },
932            );
933            Ok((generated::NodeData::Array, Some(node_data.as_union_value())))
934        }
935        NodeData::Group => Ok((
936            generated::NodeData::Group,
937            Some(
938                generated::GroupNodeData::create(
939                    builder,
940                    &generated::GroupNodeDataArgs {},
941                )
942                .as_union_value(),
943            ),
944        )),
945    }
946}
947
948#[cfg(test)]
949#[expect(unused_qualifications)] // proptest macros generate fully qualified paths
950mod tests {
951    use crate::{IcechunkFormatError, ObjectId};
952
953    use super::*;
954    use crate::{
955        roundtrip_serialization_tests,
956        strategies::{ShapeDim, manifest_file_info, node_snapshot, shapes_and_dims},
957    };
958    use pretty_assertions::assert_eq;
959    use proptest::prelude::*;
960    use std::iter::{self};
961
962    roundtrip_serialization_tests!(
963        serialize_and_deserialize_node_snapshot - node_snapshot,
964        serialize_and_deserialize_manifest_file_info - manifest_file_info
965    );
966
967    #[icechunk_macros::test]
968    fn test_get_node() -> Result<(), Box<dyn std::error::Error>> {
969        let shape1 = ArrayShape::new(vec![(10u64, 3), (20, 2), (30, 1)]).unwrap();
970        let dim_names1 = Some(vec!["x".into(), "y".into(), "t".into()]);
971
972        let shape2 = shape1.clone();
973        let dim_names2 = Some(vec![
974            DimensionName::NotSpecified,
975            DimensionName::NotSpecified,
976            "t".into(),
977        ]);
978
979        let shape3 = shape1.clone();
980        let dim_names3 = None;
981
982        let man_ref1 = ManifestRef {
983            object_id: ObjectId::random(),
984            extents: ManifestExtents::new(&[0, 0, 0], &[100, 100, 100]),
985        };
986        let man_ref2 = ManifestRef {
987            object_id: ObjectId::random(),
988            extents: ManifestExtents::new(&[0, 0, 0], &[100, 100, 100]),
989        };
990
991        let node_ids = iter::repeat_with(NodeId::random).take(7).collect::<Vec<_>>();
992        // nodes must be sorted by path
993        let nodes = vec![
994            NodeSnapshot {
995                path: Path::root(),
996                id: node_ids[0].clone(),
997                user_data: Bytes::new(),
998                node_data: NodeData::Group,
999            },
1000            NodeSnapshot {
1001                path: "/a".try_into().unwrap(),
1002                id: node_ids[1].clone(),
1003                user_data: Bytes::new(),
1004                node_data: NodeData::Group,
1005            },
1006            NodeSnapshot {
1007                path: "/array2".try_into().unwrap(),
1008                id: node_ids[5].clone(),
1009                user_data: Bytes::new(),
1010                node_data: NodeData::Array {
1011                    shape: shape2.clone(),
1012                    dimension_names: dim_names2.clone(),
1013                    manifests: vec![],
1014                },
1015            },
1016            NodeSnapshot {
1017                path: "/b".try_into().unwrap(),
1018                id: node_ids[2].clone(),
1019                user_data: Bytes::new(),
1020                node_data: NodeData::Group,
1021            },
1022            NodeSnapshot {
1023                path: "/b/array1".try_into().unwrap(),
1024                id: node_ids[4].clone(),
1025                user_data: Bytes::copy_from_slice(b"hello"),
1026                node_data: NodeData::Array {
1027                    shape: shape1.clone(),
1028                    dimension_names: dim_names1.clone(),
1029                    manifests: vec![man_ref1.clone(), man_ref2.clone()],
1030                },
1031            },
1032            NodeSnapshot {
1033                path: "/b/array3".try_into().unwrap(),
1034                id: node_ids[6].clone(),
1035                user_data: Bytes::new(),
1036                node_data: NodeData::Array {
1037                    shape: shape3.clone(),
1038                    dimension_names: dim_names3.clone(),
1039                    manifests: vec![],
1040                },
1041            },
1042            NodeSnapshot {
1043                path: "/b/c".try_into().unwrap(),
1044                id: node_ids[3].clone(),
1045                user_data: Bytes::copy_from_slice(b"bye"),
1046                node_data: NodeData::Group,
1047            },
1048        ];
1049        let manifests = vec![
1050            ManifestFileInfo {
1051                id: man_ref1.object_id.clone(),
1052                size_bytes: 1_000_000,
1053                num_chunk_refs: 100_000,
1054            },
1055            ManifestFileInfo {
1056                id: man_ref2.object_id.clone(),
1057                size_bytes: 1_000_000,
1058                num_chunk_refs: 100_000,
1059            },
1060        ];
1061        let st = Snapshot::from_iter(
1062            None,
1063            None,
1064            SpecVersionBin::current(),
1065            "",
1066            Default::default(),
1067            manifests,
1068            None,
1069            nodes.into_iter().map(Ok::<NodeSnapshot, IcechunkFormatError>),
1070        )
1071        .unwrap();
1072
1073        assert!(matches!(
1074            st.get_node(&"/nonexistent".try_into().unwrap()),
1075            Err(IcechunkFormatError {
1076                kind: IcechunkFormatErrorKind::NodeNotFound {
1077                    path
1078                },
1079                ..
1080            }) if path == "/nonexistent".try_into().unwrap()
1081        ));
1082
1083        let node = st.get_node(&"/b/c".try_into().unwrap()).unwrap();
1084        assert_eq!(
1085            node,
1086            Arc::new(NodeSnapshot {
1087                path: "/b/c".try_into().unwrap(),
1088                id: node_ids[3].clone(),
1089                user_data: Bytes::copy_from_slice(b"bye"),
1090                node_data: NodeData::Group,
1091            }),
1092        );
1093        let node = st.get_node(&Path::root()).unwrap();
1094        assert_eq!(
1095            node,
1096            Arc::new(NodeSnapshot {
1097                path: Path::root(),
1098                id: node_ids[0].clone(),
1099                user_data: Bytes::new(),
1100                node_data: NodeData::Group,
1101            }),
1102        );
1103        let node = st.get_node(&"/b/array1".try_into().unwrap()).unwrap();
1104        assert_eq!(
1105            node,
1106            Arc::new(NodeSnapshot {
1107                path: "/b/array1".try_into().unwrap(),
1108                id: node_ids[4].clone(),
1109                user_data: Bytes::copy_from_slice(b"hello"),
1110                node_data: NodeData::Array {
1111                    shape: shape1.clone(),
1112                    dimension_names: dim_names1.clone(),
1113                    manifests: vec![man_ref1, man_ref2]
1114                },
1115            }),
1116        );
1117        let node = st.get_node(&"/array2".try_into().unwrap()).unwrap();
1118        assert_eq!(
1119            node,
1120            Arc::new(NodeSnapshot {
1121                path: "/array2".try_into().unwrap(),
1122                id: node_ids[5].clone(),
1123                user_data: Bytes::new(),
1124                node_data: NodeData::Array {
1125                    shape: shape2.clone(),
1126                    dimension_names: dim_names2.clone(),
1127                    manifests: vec![]
1128                },
1129            }),
1130        );
1131        let node = st.get_node(&"/b/array3".try_into().unwrap()).unwrap();
1132        assert_eq!(
1133            node,
1134            Arc::new(NodeSnapshot {
1135                path: "/b/array3".try_into().unwrap(),
1136                id: node_ids[6].clone(),
1137                user_data: Bytes::new(),
1138                node_data: NodeData::Array {
1139                    shape: shape3.clone(),
1140                    dimension_names: dim_names3.clone(),
1141                    manifests: vec![]
1142                },
1143            }),
1144        );
1145        Ok(())
1146    }
1147
1148    #[icechunk_macros::test]
1149    fn test_valid_chunk_coord() {
1150        let shape1 =
1151            ArrayShape::new(vec![(10_000, 10), (10_001, 11), (9_999, 10)]).unwrap();
1152        let shape2 = ArrayShape::new(vec![(0, 1_000), (0, 1_000), (0, 1_000)]).unwrap();
1153        let coord1 = ChunkIndices(vec![9, 10, 9]);
1154        let coord2 = ChunkIndices(vec![10, 11, 10]);
1155        let coord3 = ChunkIndices(vec![0, 0, 0]);
1156
1157        assert!(shape1.valid_chunk_coord(&coord1));
1158        assert!(!shape1.valid_chunk_coord(&coord2));
1159        assert!(shape2.valid_chunk_coord(&coord3));
1160    }
1161
1162    #[icechunk_macros::test]
1163    fn test_valid_chunk_coord_zero_length_dim() {
1164        let shape = ArrayShape::new(vec![(0, 0)]).unwrap();
1165        assert!(shape.valid_chunk_coord(&ChunkIndices(vec![0])));
1166        assert!(!shape.valid_chunk_coord(&ChunkIndices(vec![1])));
1167    }
1168
1169    #[test_strategy::proptest]
1170    fn test_prop_valid_chunk_coord(
1171        #[strategy(shapes_and_dims(None, Some(1)))] shape_dim: ShapeDim,
1172        axis_offset: usize,
1173    ) {
1174        let shape = &shape_dim.shape;
1175        let ndim = shape.len();
1176        let axis = axis_offset % ndim;
1177
1178        // origin is always valid
1179        let origin = ChunkIndices(vec![0; ndim]);
1180        prop_assert!(shape.valid_chunk_coord(&origin));
1181
1182        // max valid coord is in bounds
1183        let max_valid =
1184            ChunkIndices(shape.num_chunks().map(|nc| nc.saturating_sub(1)).collect());
1185        prop_assert!(shape.valid_chunk_coord(&max_valid));
1186
1187        // bumping one axis out of bounds is rejected
1188        let mut oob = max_valid.0.clone();
1189        oob[axis] = shape.iter().nth(axis).unwrap().num_chunks().max(1);
1190        prop_assert!(!shape.valid_chunk_coord(&ChunkIndices(oob)));
1191    }
1192}