Skip to main content

xue/encode/
columns.rs

1//! A run's column store, cut from its finished map stores.
2//!
3//! `docs/zarr-profile.md`, "Column store", is normative and
4//! `xuebuild/columns.py` the reference, mirrored byte for byte. The input is
5//! the plan both writers take: which array holds which variable of which map
6//! store, its predictor and its levels. Everything else, metadata, grid, axis,
7//! codebooks, codes and tiling, is read from the stores the plan names, so
8//! nothing here knows a source or opens the registry document.
9//!
10//! A member's store is the plan's to name: a map store, or, for a surface
11//! array whose variable its bundle's series store widens, that series store,
12//! whose sixteen-bit codes the array then holds as `uint16`, so a column and
13//! a pinned point's series are one set of codes. Every other array is bytes.
14//!
15//! The unit of work is one shard of one array: a band of rows, every level
16//! over the whole axis. Its codes are held uncompressed, each map shard is
17//! read by seeking to the tiles the band overlaps, and payloads go to disk as
18//! they are compressed, so memory is one band per worker whatever the run's
19//! size. `zarr.json` is written last: until then no reader takes the directory
20//! for a store, and a failed cut removes it.
21
22use std::borrow::Cow;
23use std::collections::{BTreeMap, BTreeSet};
24use std::fs;
25use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
26use std::ops::Range;
27use std::path::{Path, PathBuf};
28
29use rayon::prelude::*;
30use serde_json::{json, Map, Value};
31
32use crate::column::{
33    is_id, ColumnGroup, COLUMN_ATTRIBUTE, COLUMN_BLOCK_CELLS, COLUMN_SHARD_ROWS, COLUMN_VERSION,
34    COORDINATES,
35};
36use crate::encode::binformat::crc32_plane;
37use crate::encode::errors::{EncodeError, Result};
38use crate::encode::pyjson::dumps_indented;
39use crate::encode::zarrstore::{
40    code_data_type, compress_chunk, compression_pool, coordinate_metadata, write_coordinates,
41    write_file, write_file_atomic,
42};
43use crate::format::{DecodeError, MAX_PLANE_LENGTH};
44use crate::zarr::{self, ArrayLayout, DataType, IndexLocation, ShardIndexEntry, DELTA_CODEC};
45
46/// The `columnsPlan` this writer reads.
47pub const PLAN_VERSION: u64 = 1;
48
49/// The inner chunks' zstd level, which the array documents declare; the grid
50/// stores' is 15. A run's whole store is cut on one machine after the run is
51/// live, and 15 costs several times the time for a few percent fewer bytes.
52const ZSTD_LEVEL: i32 = 6;
53const BLOCK: usize = COLUMN_BLOCK_CELLS as usize;
54const SHARD_ROWS: usize = COLUMN_SHARD_ROWS as usize;
55/// The index pair of a block wholly past the grid.
56const NEVER_WRITTEN: [u8; 16] = [0xff; 16];
57
58fn invalid(message: impl Into<String>) -> EncodeError {
59    EncodeError::bundle(message)
60}
61
62fn io_error(verb: &str, path: &Path, error: &std::io::Error) -> EncodeError {
63    EncodeError::conversion(format!("cannot {verb} {}: {error}", path.display()))
64}
65
66/// The element of an array's codes: `u8`, or `u16` on a surface array cut
67/// from a series store's widened variable. One cut is written over one type,
68/// so a byte array's band holds bytes, not widened codes.
69trait Code: Copy + Send + Sync {
70    /// A fill value, held to the type when the plan was resolved.
71    fn fill(value: u16) -> Self;
72    fn wrapping_sub(self, other: Self) -> Self;
73    /// One inner chunk of a member array of this type, at its full shape.
74    fn decode(layout: &ArrayLayout, payload: &[u8]) -> std::result::Result<Vec<Self>, DecodeError>;
75    /// The `bytes` codec's serialization: a byte has no order; a sixteen-bit
76    /// code is little-endian whatever the machine's.
77    fn bytes(chunk: &[Self]) -> Cow<'_, [u8]>;
78}
79
80impl Code for u8 {
81    fn fill(value: u16) -> u8 {
82        value as u8
83    }
84    fn wrapping_sub(self, other: u8) -> u8 {
85        u8::wrapping_sub(self, other)
86    }
87    fn decode(layout: &ArrayLayout, payload: &[u8]) -> std::result::Result<Vec<u8>, DecodeError> {
88        // Refuses a uint16 array.
89        zarr::decode_frame_chunk(layout, payload)
90    }
91    fn bytes(chunk: &[u8]) -> Cow<'_, [u8]> {
92        Cow::Borrowed(chunk)
93    }
94}
95
96impl Code for u16 {
97    fn fill(value: u16) -> u16 {
98        value
99    }
100    fn wrapping_sub(self, other: u16) -> u16 {
101        u16::wrapping_sub(self, other)
102    }
103    fn decode(layout: &ArrayLayout, payload: &[u8]) -> std::result::Result<Vec<u16>, DecodeError> {
104        // `decode_inner_chunk` widens a byte array, which must not pass for one
105        // of sixteen-bit codes.
106        if layout.data_type != DataType::U16 {
107            return Err(DecodeError(
108                "a uint16 column array is cut from uint16 arrays".into(),
109            ));
110        }
111        zarr::decode_inner_chunk(layout, payload)
112    }
113    fn bytes(chunk: &[u16]) -> Cow<'_, [u8]> {
114        Cow::Owned(chunk.iter().flat_map(|code| code.to_le_bytes()).collect())
115    }
116}
117
118// -- the plan ------------------------------------------------------------------
119
120struct PlanMember {
121    bundle: String,
122    variable: String,
123    /// The map store, or the series store of a widened surface member,
124    /// relative to the run directory.
125    store: String,
126}
127
128struct PlanArray {
129    id: String,
130    previous: bool,
131    levels: Option<Vec<i32>>,
132    members: Vec<PlanMember>,
133}
134
135/// An object of every `required` key and no key beyond `optional`.
136fn closed<'a>(
137    node: &'a Value,
138    required: &[&str],
139    optional: &[&str],
140    what: &str,
141) -> Result<&'a Map<String, Value>> {
142    node.as_object()
143        .filter(|object| {
144            required.iter().all(|key| object.contains_key(*key))
145                && object
146                    .keys()
147                    .all(|key| required.contains(&key.as_str()) || optional.contains(&key.as_str()))
148        })
149        .ok_or_else(|| {
150            invalid(format!(
151                "{what} must be an object of {}",
152                [required, optional].concat().join(", ")
153            ))
154        })
155}
156
157fn parse_plan(text: &str) -> Result<Vec<PlanArray>> {
158    let plan: Value = serde_json::from_str(text)
159        .map_err(|error| invalid(format!("the column plan is not JSON: {error}")))?;
160    let document = closed(&plan, &["columnsPlan", "arrays"], &[], "the column plan")?;
161    if document["columnsPlan"].as_u64() != Some(PLAN_VERSION) {
162        return Err(invalid(format!(
163            "column plan version {} is not {PLAN_VERSION}",
164            document["columnsPlan"]
165        )));
166    }
167    let entries = document["arrays"]
168        .as_array()
169        .filter(|entries| !entries.is_empty())
170        .ok_or_else(|| invalid("a column store holds at least one array"))?;
171    let mut array_ids = BTreeSet::new();
172    let mut variable_ids = BTreeSet::new();
173    let mut arrays = Vec::with_capacity(entries.len());
174    for (number, entry) in entries.iter().enumerate() {
175        let what = format!("column plan array {number}");
176        let entry = closed(entry, &["id", "predictor", "members"], &["levels"], &what)?;
177        let id = entry["id"]
178            .as_str()
179            .filter(|id| is_id(id) && !COORDINATES.contains(id))
180            .ok_or_else(|| invalid(format!("{} cannot name a column array", entry["id"])))?;
181        if !array_ids.insert(id) {
182            return Err(invalid(format!("column array {id} occurs twice")));
183        }
184        let previous = match entry["predictor"].as_str() {
185            Some("previous") => true,
186            Some("raw") => false,
187            _ => {
188                return Err(invalid(format!(
189                    "column array {id}: unknown predictor {}",
190                    entry["predictor"]
191                )))
192            }
193        };
194        let members = parse_members(&entry["members"], id, &mut variable_ids)?;
195        let levels = match entry.get("levels") {
196            Some(levels) => Some(parse_levels(levels, members.len(), id)?),
197            None if members.len() == 1 && members[0].variable == id => None,
198            None => {
199                return Err(invalid(format!(
200                    "column array {id}: a surface array has one member and is named by it"
201                )))
202            }
203        };
204        arrays.push(PlanArray {
205            id: id.to_owned(),
206            previous,
207            levels,
208            members,
209        });
210    }
211    Ok(arrays)
212}
213
214fn parse_members(node: &Value, id: &str, seen: &mut BTreeSet<String>) -> Result<Vec<PlanMember>> {
215    let entries = node
216        .as_array()
217        .filter(|entries| !entries.is_empty())
218        .ok_or_else(|| invalid(format!("column array {id} has no members")))?;
219    let mut members = Vec::with_capacity(entries.len());
220    for entry in entries {
221        let what = format!("column array {id}: a member");
222        let entry = closed(entry, &["bundle", "variable", "store"], &[], &what)?;
223        let text = |key: &str| -> Result<String> {
224            entry[key]
225                .as_str()
226                .filter(|text| !text.is_empty())
227                .map(str::to_owned)
228                .ok_or_else(|| {
229                    invalid(format!(
230                        "column array {id}: a member names its bundle, variable and store"
231                    ))
232                })
233        };
234        let member = PlanMember {
235            bundle: text("bundle")?,
236            variable: text("variable")?,
237            store: text("store")?,
238        };
239        if !seen.insert(member.variable.clone()) {
240            return Err(invalid(format!(
241                "variable {} occurs twice in one column store",
242                member.variable
243            )));
244        }
245        members.push(member);
246    }
247    Ok(members)
248}
249
250/// Strictly descending positive hPa, one per member, in the `int32` range of
251/// the `level` coordinate.
252fn parse_levels(node: &Value, count: usize, id: &str) -> Result<Vec<i32>> {
253    node.as_array()
254        .and_then(|levels| {
255            levels
256                .iter()
257                .map(|level| {
258                    level
259                        .as_u64()
260                        .and_then(|level| i32::try_from(level).ok())
261                        .filter(|&level| level > 0)
262                })
263                .collect::<Option<Vec<i32>>>()
264        })
265        .filter(|levels| levels.len() == count && levels.windows(2).all(|pair| pair[1] < pair[0]))
266        .ok_or_else(|| {
267            invalid(format!(
268                "column array {id}: levels must be strictly descending hPa, one per member"
269            ))
270        })
271}
272
273// -- what the map stores hold --------------------------------------------------
274
275/// One variable's array in a map store, or in its bundle's series store, its
276/// shard's index read and verified. A series store's array is read the same
277/// way: its tiles are its blocks, and its one time chunk the whole axis.
278struct MapArray {
279    path: PathBuf,
280    layout: ArrayLayout,
281    index: Vec<Option<ShardIndexEntry>>,
282}
283
284impl MapArray {
285    fn open(path: PathBuf, layout: ArrayLayout) -> Result<MapArray> {
286        let fail = |error: &std::io::Error| io_error("read", &path, error);
287        let mut file = fs::File::open(&path).map_err(|error| fail(&error))?;
288        let length = file.metadata().map_err(|error| fail(&error))?.len();
289        // The layout holds the index to the decoded size limit.
290        let index_length = zarr::shard_index_length(layout.chunks_per_shard as usize);
291        if length < index_length as u64 {
292            return Err(invalid(format!(
293                "{} is smaller than its index",
294                path.display()
295            )));
296        }
297        if layout.index_location == IndexLocation::End {
298            file.seek(SeekFrom::Start(length - index_length as u64))
299                .map_err(|error| fail(&error))?;
300        }
301        let mut bytes = vec![0u8; index_length];
302        file.read_exact(&mut bytes).map_err(|error| fail(&error))?;
303        let index = zarr::parse_shard_index(&bytes, layout.chunks_per_shard as usize)
304            .map_err(|error| invalid(format!("{}: {}", path.display(), error.0)))?;
305        if index.iter().flatten().any(|entry| {
306            entry
307                .offset
308                .checked_add(entry.length)
309                .is_none_or(|end| end > length)
310        }) {
311            return Err(invalid(format!(
312                "{}: an index entry exceeds the shard",
313                path.display()
314            )));
315        }
316        Ok(MapArray {
317            path,
318            layout,
319            index,
320        })
321    }
322
323    /// Every frame of a band of grid rows, read tile by tile: `place(frame,
324    /// row of the band, first column, codes)` for each run of cells. A tile
325    /// the shard never held is the array's fill value.
326    fn read_rows<T: Code>(
327        &self,
328        rows: &Range<usize>,
329        mut place: impl FnMut(usize, usize, usize, &[T]),
330    ) -> Result<()> {
331        let layout = &self.layout;
332        let fail = |error: &std::io::Error| io_error("read", &self.path, error);
333        let mut file = fs::File::open(&self.path).map_err(|error| fail(&error))?;
334        let (tile_height, tile_width) = (layout.tile_height as usize, layout.tile_width as usize);
335        let tile_cells = tile_height * tile_width;
336        let tile_rows = rows.start / tile_height..rows.end.div_ceil(tile_height);
337        let mut payload = Vec::new();
338        for time_chunk in 0..layout.time_chunks {
339            let first_frame = time_chunk as usize * layout.time_chunk as usize;
340            let frames = zarr::frames_in_time_chunk(layout, time_chunk) as usize;
341            let (_, first_entry) = zarr::shard_of(layout, time_chunk);
342            for tile_row in tile_rows.clone() {
343                let top = tile_row * tile_height;
344                let (low, high) = (rows.start.max(top), rows.end.min(top + tile_height));
345                for tile_column in 0..layout.tile_columns as usize {
346                    let entry = first_entry as usize
347                        + tile_row * layout.tile_columns as usize
348                        + tile_column;
349                    let chunk = match self.index.get(entry).copied().flatten() {
350                        None => vec![
351                            T::fill(layout.fill_value);
352                            tile_cells * layout.time_chunk as usize
353                        ],
354                        Some(span) => {
355                            // Held to the file's length when the index was read.
356                            payload.resize(span.length as usize, 0);
357                            file.seek(SeekFrom::Start(span.offset))
358                                .map_err(|error| fail(&error))?;
359                            file.read_exact(&mut payload)
360                                .map_err(|error| fail(&error))?;
361                            T::decode(layout, &payload).map_err(|error| {
362                                invalid(format!("{}: {}", self.path.display(), error.0))
363                            })?
364                        }
365                    };
366                    let left = tile_column * tile_width;
367                    let cells = tile_width.min(layout.width as usize - left);
368                    for frame in 0..frames {
369                        for row in low..high {
370                            let source = frame * tile_cells + (row - top) * tile_width;
371                            place(
372                                first_frame + frame,
373                                row - rows.start,
374                                left,
375                                &chunk[source..source + cells],
376                            );
377                        }
378                    }
379                }
380            }
381        }
382        Ok(())
383    }
384}
385
386struct Member {
387    bundle: String,
388    /// The bundle metadata's variable object, verbatim.
389    variable: Value,
390    array: MapArray,
391}
392
393/// One array of the store about to be cut.
394struct ColumnArray {
395    id: String,
396    levels: Option<Vec<i32>>,
397    /// The metadata of its first member's bundle, whose `time` is the array's.
398    metadata: Value,
399    members: Vec<Member>,
400    delta: bool,
401    fill_value: u16,
402    /// `U16` on a surface array cut from a series store's widened variable,
403    /// `U8` on every other.
404    data_type: DataType,
405    geometry: Geometry,
406}
407
408impl ColumnArray {
409    fn time(&self) -> &Value {
410        &self.metadata["time"]
411    }
412}
413
414/// A map store's group document, parsed once for all its members.
415struct Group {
416    document: Value,
417}
418
419impl Group {
420    fn read(store: &Path) -> Result<Group> {
421        let path = store.join("zarr.json");
422        let text = fs::read_to_string(&path).map_err(|error| io_error("read", &path, &error))?;
423        // Holds the document to the grid branch and to a profile that is read.
424        zarr::group_bundle_ids(&text)
425            .map_err(|error| invalid(format!("{}: {}", path.display(), error.0)))?;
426        let document = serde_json::from_str(&text)
427            .map_err(|error| invalid(format!("{}: {error}", path.display())))?;
428        Ok(Group { document })
429    }
430
431    /// One bundle's metadata block, whichever profile the store is of.
432    fn metadata(&self, bundle: &str) -> Option<&Value> {
433        let attributes = &self.document["attributes"];
434        attributes
435            .get("xue")
436            .or_else(|| attributes["xue_bundles"].get(bundle))
437            .filter(|block| block.is_object())
438    }
439
440    /// The consolidated block holds every array's document, so a cut needs no
441    /// object of the store but its group document and the shards.
442    fn array(&self, variable: &str) -> Option<&Value> {
443        self.document["consolidated_metadata"]["metadata"]
444            .get(variable)
445            .filter(|document| document.is_object())
446    }
447}
448
449/// One plan member opened: its bundle's metadata beside it.
450fn open_member(
451    run_directory: &Path,
452    plan: &PlanMember,
453    groups: &mut BTreeMap<String, Group>,
454) -> Result<(Value, Member)> {
455    let store = run_directory.join(&plan.store);
456    if !groups.contains_key(&plan.store) {
457        groups.insert(plan.store.clone(), Group::read(&store)?);
458    }
459    let group = &groups[&plan.store];
460    let metadata = group
461        .metadata(&plan.bundle)
462        .ok_or_else(|| invalid(format!("{} carries no bundle {}", plan.store, plan.bundle)))?;
463    let parsed = zarr::parse_bundle_metadata(&metadata.to_string())
464        .map_err(|error| invalid(format!("{}: {}", plan.bundle, error.0)))?;
465    let variable = metadata["variables"].as_array().and_then(|variables| {
466        variables
467            .iter()
468            .find(|variable| variable["id"] == plan.variable.as_str())
469    });
470    let (Some(variable), Some(document)) = (variable, group.array(&plan.variable)) else {
471        return Err(invalid(format!(
472            "bundle {} of {} has no array {}",
473            plan.bundle, plan.store, plan.variable
474        )));
475    };
476    let what = format!("{}/{}", plan.store, plan.variable);
477    let layout = zarr::parse_array_metadata(&document.to_string())
478        .map_err(|error| invalid(format!("{what}: {}", error.0)))?;
479    let data_type = layout.data_type.name();
480    if code_data_type(&variable["quantization"]) != data_type {
481        return Err(invalid(format!(
482            "{what}: a {data_type} array whose codebook's codes are not"
483        )));
484    }
485    if (layout.frame_count as usize, layout.height, layout.width)
486        != (
487            parsed.offsets.len(),
488            parsed.grid.height(),
489            parsed.grid.width(),
490        )
491    {
492        return Err(invalid(format!(
493            "{what}: the array's shape is not its bundle's"
494        )));
495    }
496    if layout.shard_count != 1 {
497        return Err(invalid(format!(
498            "{what}: a column store is cut from arrays of one shard"
499        )));
500    }
501    let array = MapArray::open(store.join(zarr::shard_path(&plan.variable, 0)), layout)?;
502    Ok((
503        metadata.clone(),
504        Member {
505            bundle: plan.bundle.clone(),
506            variable: variable.clone(),
507            array,
508        },
509    ))
510}
511
512/// Read the stores a plan names and settle the arrays, refusing what a column
513/// store cannot hold.
514fn resolve_plan(run_directory: &Path, plan: Vec<PlanArray>) -> Result<Vec<ColumnArray>> {
515    let mut groups = BTreeMap::new();
516    let mut arrays: Vec<ColumnArray> = Vec::with_capacity(plan.len());
517    for entry in plan {
518        let PlanArray {
519            id,
520            previous,
521            levels,
522            members: planned,
523        } = entry;
524        let mut first: Option<Value> = None;
525        let mut members: Vec<Member> = Vec::with_capacity(planned.len());
526        for member in &planned {
527            let (metadata, opened) = open_member(run_directory, member, &mut groups)?;
528            if metadata["grid"].get("projection").is_some() {
529                return Err(invalid(format!(
530                    "{}: a column store is for regular and Gaussian grids",
531                    member.bundle
532                )));
533            }
534            let reference = arrays
535                .first()
536                .map(|array| &array.metadata)
537                .or(first.as_ref())
538                .unwrap_or(&metadata);
539            if IDENTITY
540                .iter()
541                .any(|key| metadata.get(*key) != reference.get(*key))
542            {
543                return Err(invalid(format!(
544                    "{}: its metadata is of another run or profile than the store's",
545                    member.bundle
546                )));
547            }
548            if metadata["grid"] != reference["grid"] {
549                return Err(invalid(format!(
550                    "{}: its grid is not the column store's",
551                    member.bundle
552                )));
553            }
554            if first
555                .as_ref()
556                .is_some_and(|held| held["time"] != metadata["time"])
557            {
558                return Err(invalid(format!(
559                    "column array {id}: its members do not share one time axis"
560                )));
561            }
562            members.push(opened);
563            first.get_or_insert(metadata);
564        }
565        let metadata = first.ok_or_else(|| invalid(format!("column array {id} has no members")))?;
566        let mut fills = Vec::with_capacity(members.len());
567        for member in &members {
568            let data_type = member.array.layout.data_type;
569            let what = if data_type == DataType::U8 {
570                "a byte"
571            } else {
572                "a uint16 code"
573            };
574            fills.push(
575                member.variable["quantization"]["nodataCode"]
576                    .as_u64()
577                    .filter(|&code| code <= u64::from(data_type.max_code()))
578                    .ok_or_else(|| {
579                        invalid(format!(
580                            "{}: nodataCode is not {what}",
581                            member.variable["id"]
582                        ))
583                    })? as u16,
584            );
585        }
586        if fills.iter().any(|&fill| fill != fills[0]) {
587            return Err(invalid(format!(
588                "column array {id}: its members do not share one nodataCode"
589            )));
590        }
591        let data_types: BTreeSet<&str> = members
592            .iter()
593            .map(|member| member.array.layout.data_type.name())
594            .collect();
595        // A levelled array stays bytes, whatever a series store holds: its
596        // levels are drawn together from the maps' codes.
597        if levels.is_some() && data_types != BTreeSet::from(["uint8"]) {
598            return Err(invalid(format!(
599                "column array {id}: a levelled array is cut from uint8 arrays"
600            )));
601        }
602        if data_types.len() != 1 {
603            return Err(invalid(format!(
604                "column array {id}: its members are not of one data type"
605            )));
606        }
607        let layout = &members[0].array.layout;
608        let geometry = Geometry {
609            frame_count: layout.frame_count as usize,
610            levels: levels.as_ref().map(Vec::len),
611            height: layout.height as usize,
612            width: layout.width as usize,
613        };
614        geometry.check(&id)?;
615        arrays.push(ColumnArray {
616            id,
617            levels,
618            metadata,
619            // One frame has nothing to be predicted from.
620            delta: geometry.frame_count > 1 && previous,
621            fill_value: fills[0],
622            data_type: members[0].array.layout.data_type,
623            geometry,
624            members,
625        });
626    }
627    Ok(arrays)
628}
629
630/// What every member's metadata shares, in the block's order.
631const IDENTITY: [&str; 4] = ["model", "product", "runTime", "profile"];
632
633// -- geometry ------------------------------------------------------------------
634
635/// How one array is cut: an inner chunk of the whole axis and every level of
636/// one block of cells, a shard of [`SHARD_ROWS`] rows across the grid's width
637/// rounded up to whole blocks. `levels` is `None` on a surface array.
638#[derive(Debug, Clone, Copy)]
639struct Geometry {
640    frame_count: usize,
641    levels: Option<usize>,
642    height: usize,
643    width: usize,
644}
645
646impl Geometry {
647    /// What a reader refuses, refused before anything is cut.
648    fn check(&self, id: &str) -> Result<()> {
649        let within = |size: Option<usize>| size.is_some_and(|size| size as u64 <= MAX_PLANE_LENGTH);
650        if !within(self.inner_length()) {
651            return Err(invalid(format!(
652                "column array {id}: its inner chunk exceeds the decoded size limit"
653            )));
654        }
655        if !within(Some(zarr::shard_index_length(self.chunks_per_shard()))) {
656            return Err(invalid(format!(
657                "column array {id}: its shard index exceeds the decoded size limit"
658            )));
659        }
660        Ok(())
661    }
662    fn level_count(&self) -> usize {
663        self.levels.unwrap_or(1)
664    }
665    /// A shape of the array: the axis, the levels where there are any, then
666    /// the rows and columns given.
667    fn shape(&self, rows: usize, columns: usize) -> Vec<usize> {
668        [
669            Some(self.frame_count),
670            self.levels,
671            Some(rows),
672            Some(columns),
673        ]
674        .into_iter()
675        .flatten()
676        .collect()
677    }
678    fn inner_length(&self) -> Option<usize> {
679        self.frame_count
680            .checked_mul(self.level_count())?
681            .checked_mul(BLOCK * BLOCK)
682    }
683    fn block_rows(&self) -> usize {
684        SHARD_ROWS / BLOCK
685    }
686    fn block_columns(&self) -> usize {
687        self.width.div_ceil(BLOCK)
688    }
689    fn shard_width(&self) -> usize {
690        self.block_columns() * BLOCK
691    }
692    fn chunks_per_shard(&self) -> usize {
693        self.block_rows() * self.block_columns()
694    }
695    fn shard_count(&self) -> usize {
696        self.height.div_ceil(SHARD_ROWS)
697    }
698    /// The grid rows of a shard, fewer than its height on the last.
699    fn shard_rows(&self, shard: usize) -> Range<usize> {
700        shard * SHARD_ROWS..((shard + 1) * SHARD_ROWS).min(self.height)
701    }
702    fn shard_path(&self, shard: usize) -> PathBuf {
703        // The axis, every level and every column are one shard wide.
704        let mut path = PathBuf::from(if self.levels.is_some() {
705            "c/0/0"
706        } else {
707            "c/0"
708        });
709        path.push(shard.to_string());
710        path.push("0");
711        path
712    }
713}
714
715// -- shards --------------------------------------------------------------------
716
717/// A shard's codes, `[frames, levels, rows, shardWidth]`, the rows padded to
718/// whole blocks and every cell past the grid at the fill value.
719struct Band<T> {
720    geometry: Geometry,
721    rows: usize,
722    codes: Vec<T>,
723}
724
725impl<T: Code> Band<T> {
726    fn new(geometry: Geometry, rows: &Range<usize>, fill: T) -> Result<Band<T>> {
727        let padded = rows.len().next_multiple_of(BLOCK);
728        let length = geometry
729            .frame_count
730            .checked_mul(geometry.level_count())
731            .and_then(|planes| planes.checked_mul(padded))
732            .and_then(|lines| lines.checked_mul(geometry.shard_width()))
733            .ok_or_else(|| invalid("a column shard exceeds what can be addressed"))?;
734        Ok(Band {
735            geometry,
736            rows: padded,
737            codes: vec![fill; length],
738        })
739    }
740
741    fn offset(&self, frame: usize, level: usize, row: usize, column: usize) -> usize {
742        ((frame * self.geometry.level_count() + level) * self.rows + row)
743            * self.geometry.shard_width()
744            + column
745    }
746
747    /// One block as the inner chunk stores it: cut whole out of the padded
748    /// band, then the `xue.delta` encode along time when asked, modulo the
749    /// type's range (256 or 65536).
750    fn cut(&self, block_row: usize, block_column: usize, delta: bool, chunk: &mut Vec<T>) {
751        let geometry = &self.geometry;
752        chunk.clear();
753        for frame in 0..geometry.frame_count {
754            for level in 0..geometry.level_count() {
755                for line in 0..BLOCK {
756                    let start =
757                        self.offset(frame, level, block_row * BLOCK + line, block_column * BLOCK);
758                    chunk.extend_from_slice(&self.codes[start..start + BLOCK]);
759                }
760            }
761        }
762        if delta {
763            let frame_cells = geometry.level_count() * BLOCK * BLOCK;
764            for index in (frame_cells..chunk.len()).rev() {
765                chunk[index] = chunk[index].wrapping_sub(chunk[index - frame_cells]);
766            }
767        }
768    }
769}
770
771/// One shard: its length and its CRC-32.
772struct Shard {
773    length: u64,
774    crc32: String,
775}
776
777/// Cut one shard of one array into `store`. The payloads are written as they
778/// are compressed and the index, whose length is known, over the gap left for
779/// it. Block rows the grid does not reach are never written.
780fn write_shard(array: &ColumnArray, shard: usize, store: &Path) -> Result<Shard> {
781    match array.data_type {
782        DataType::U8 => write_shard_of::<u8>(array, shard, store),
783        DataType::U16 => write_shard_of::<u16>(array, shard, store),
784    }
785}
786
787fn write_shard_of<T: Code>(array: &ColumnArray, shard: usize, store: &Path) -> Result<Shard> {
788    let geometry = array.geometry;
789    let rows = geometry.shard_rows(shard);
790    let mut band = Band::new(geometry, &rows, T::fill(array.fill_value))?;
791    for (level, member) in array.members.iter().enumerate() {
792        member
793            .array
794            .read_rows::<T>(&rows, |frame, row, column, cells| {
795                let start = band.offset(frame, level, row, column);
796                band.codes[start..start + cells.len()].copy_from_slice(cells);
797            })?;
798    }
799
800    let path = store.join(&array.id).join(geometry.shard_path(shard));
801    let fail = |error: std::io::Error| io_error("write", &path, &error);
802    if let Some(parent) = path.parent() {
803        fs::create_dir_all(parent).map_err(fail)?;
804    }
805    let mut file = BufWriter::new(fs::File::create(&path).map_err(fail)?);
806    let index_length = zarr::shard_index_length(geometry.chunks_per_shard());
807    let mut index = Vec::with_capacity(index_length);
808    let mut cursor = index_length as u64;
809    file.seek(SeekFrom::Start(cursor)).map_err(fail)?;
810    let mut body = crc32fast::Hasher::new();
811    let mut chunk = Vec::new();
812    for block_row in 0..band.rows / BLOCK {
813        for block_column in 0..geometry.block_columns() {
814            band.cut(block_row, block_column, array.delta, &mut chunk);
815            let payload = compress_chunk(&T::bytes(&chunk), ZSTD_LEVEL)?;
816            index.extend_from_slice(&cursor.to_le_bytes());
817            index.extend_from_slice(&(payload.len() as u64).to_le_bytes());
818            cursor += payload.len() as u64;
819            body.update(&payload);
820            file.write_all(&payload).map_err(fail)?;
821        }
822    }
823    while index.len() < geometry.chunks_per_shard() * NEVER_WRITTEN.len() {
824        index.extend_from_slice(&NEVER_WRITTEN);
825    }
826    let checksum = zarr::crc32c(&index);
827    index.extend_from_slice(&checksum.to_le_bytes());
828    zarr::parse_shard_index(&index, geometry.chunks_per_shard())
829        .map_err(|error| invalid(format!("{}: shard index is invalid: {}", array.id, error.0)))?;
830    file.seek(SeekFrom::Start(0)).map_err(fail)?;
831    file.write_all(&index).map_err(fail)?;
832    file.flush().map_err(fail)?;
833    drop(file);
834    let on_disk = fs::metadata(&path).map_err(fail)?.len();
835    if on_disk != cursor {
836        return Err(invalid(format!(
837            "{}: shard is {on_disk} bytes, not {cursor}",
838            array.id
839        )));
840    }
841    let mut whole = crc32fast::Hasher::new();
842    whole.update(&index);
843    whole.combine(&body);
844    Ok(Shard {
845        length: cursor,
846        crc32: format!("{:08x}", whole.finalize()),
847    })
848}
849
850// -- documents -----------------------------------------------------------------
851
852/// The value under `key` where every member's variable has the same one.
853fn uniform<'a>(members: &'a [Member], key: &str) -> Option<&'a Value> {
854    let first = members.first()?.variable.get(key)?;
855    members
856        .iter()
857        .all(|member| member.variable.get(key) == Some(first))
858        .then_some(first)
859}
860
861fn array_document(array: &ColumnArray, dimensions: &[String]) -> Value {
862    let geometry = &array.geometry;
863    let mut attributes = Map::new();
864    attributes.insert(COLUMN_ATTRIBUTE.into(), json!({"array": array.id}));
865    for (name, key) in [("long_name", "label"), ("units", "unit")] {
866        if let Some(value) = uniform(&array.members, key) {
867            attributes.insert(name.into(), value.clone());
868        }
869    }
870    // CF packing, only where one spelling holds for every level.
871    if let Some(codebook) =
872        uniform(&array.members, "quantization").filter(|codebook| codebook["type"] == "linear")
873    {
874        attributes.insert("scale_factor".into(), codebook["scale"].clone());
875        attributes.insert("add_offset".into(), codebook["offset"].clone());
876    }
877    attributes.insert("_FillValue".into(), json!(array.fill_value));
878    let mut inner = Vec::new();
879    if array.delta {
880        inner.push(json!({"name": DELTA_CODEC, "configuration": {"axis": 0}}));
881    }
882    // A byte has no order, so a uint8 array keeps the bare `bytes` every
883    // store has been written with; a uint16 one spells its order out.
884    inner.push(match array.data_type {
885        DataType::U8 => json!({"name": "bytes"}),
886        DataType::U16 => json!({"name": "bytes", "configuration": {"endian": "little"}}),
887    });
888    inner.push(json!({"name": "zstd", "configuration": {"level": ZSTD_LEVEL, "checksum": true}}));
889    json!({
890        "zarr_format": 3,
891        "node_type": "array",
892        "shape": geometry.shape(geometry.height, geometry.width),
893        "data_type": array.data_type.name(),
894        "chunk_grid": {"name": "regular", "configuration": {
895            "chunk_shape": geometry.shape(SHARD_ROWS, geometry.shard_width()),
896        }},
897        "chunk_key_encoding": {"name": "default"},
898        "fill_value": array.fill_value,
899        "codecs": [{
900            "name": "sharding_indexed",
901            "configuration": {
902                "chunk_shape": geometry.shape(BLOCK, BLOCK),
903                "codecs": inner,
904                "index_codecs": [
905                    {"name": "bytes", "configuration": {"endian": "little"}},
906                    {"name": "crc32c"},
907                ],
908                "index_location": "start",
909            },
910        }],
911        "attributes": Value::Object(attributes),
912        "dimension_names": dimensions,
913    })
914}
915
916/// Each array's dimension names: `time` or `time_<array>` by its axis, then on
917/// a levelled array `level` or `level_<array>` by its levels.
918fn dimensions(arrays: &[ColumnArray]) -> Vec<Vec<String>> {
919    let store_time = arrays.first().map(ColumnArray::time);
920    let store_levels = arrays.iter().find_map(|array| array.levels.as_ref());
921    let named = |name: &str, shared: bool, id: &str| {
922        if shared {
923            name.to_owned()
924        } else {
925            format!("{name}_{id}")
926        }
927    };
928    arrays
929        .iter()
930        .map(|array| {
931            let mut names = vec![named("time", Some(array.time()) == store_time, &array.id)];
932            if array.levels.is_some() {
933                names.push(named(
934                    "level",
935                    array.levels.as_ref() == store_levels,
936                    &array.id,
937                ));
938            }
939            names.extend(["latitude".to_owned(), "longitude".to_owned()]);
940            names
941        })
942        .collect()
943}
944
945/// An array's document under its name; the bytes written.
946fn write_document(store: &Path, name: &str, document: &Value) -> Result<u64> {
947    write_file(
948        &store.join(name).join("zarr.json"),
949        dumps_indented(document).as_bytes(),
950    )
951}
952
953/// Every coordinate the arrays name, their documents in the consolidated
954/// block's order, and the bytes written.
955fn write_store_coordinates(
956    arrays: &[ColumnArray],
957    names: &[Vec<String>],
958    store: &Path,
959) -> Result<(Vec<(String, Value)>, u64)> {
960    let mut sizes: BTreeMap<String, u64> = BTreeMap::new();
961    let mut primary: Vec<(String, Value)> = Vec::new();
962    let mut level: Option<(String, Value)> = None;
963    let mut own: Vec<(String, Value)> = Vec::new();
964    for (position, (array, dimensions)) in arrays.iter().zip(names).enumerate() {
965        // The first array's axis is the store's.
966        if position == 0 || dimensions[0] != "time" {
967            // The grid store's own encoding, which takes the time and the
968            // grid's two together; the grid's are the same bytes every time.
969            let mut documents = Vec::new();
970            let coordinates = [
971                dimensions[0].clone(),
972                "latitude".to_owned(),
973                "longitude".to_owned(),
974            ];
975            let shape = (array.geometry.height, array.geometry.width);
976            sizes.extend(write_coordinates(
977                &array.metadata,
978                shape,
979                store,
980                &coordinates,
981                false,
982                &mut documents,
983            )?);
984            if position == 0 {
985                primary = documents;
986            } else {
987                own.extend(documents.into_iter().take(1));
988            }
989        }
990        let Some(levels) = &array.levels else {
991            continue;
992        };
993        let name = &dimensions[1];
994        if name == "level" && level.is_some() {
995            continue;
996        }
997        let document = coordinate_metadata(
998            levels.len(),
999            "int32",
1000            json!(0),
1001            json!({"standard_name": "air_pressure", "units": "hPa", "positive": "down"}),
1002            name,
1003        );
1004        let values: Vec<u8> = levels
1005            .iter()
1006            .flat_map(|level| level.to_le_bytes())
1007            .collect();
1008        let written = write_document(store, name, &document)?
1009            + write_file(&store.join(name).join("c").join("0"), &values)?;
1010        sizes.insert(name.clone(), written);
1011        if name == "level" {
1012            level = Some((name.clone(), document));
1013        } else {
1014            own.push((name.clone(), document));
1015        }
1016    }
1017    if let Some(level) = level {
1018        primary.insert(1, level);
1019    }
1020    primary.extend(own);
1021    Ok((primary, sizes.values().sum()))
1022}
1023
1024fn group_document(
1025    arrays: &[ColumnArray],
1026    shards: &[Vec<String>],
1027    documents: &[(String, Value)],
1028) -> Value {
1029    let first = &arrays[0];
1030    let mut block = Map::new();
1031    block.insert("version".into(), json!(COLUMN_VERSION));
1032    for key in IDENTITY {
1033        block.insert(key.into(), first.metadata[key].clone());
1034    }
1035    block.insert("time".into(), first.time().clone());
1036    block.insert("grid".into(), first.metadata["grid"].clone());
1037    let entries = arrays
1038        .iter()
1039        .zip(shards)
1040        .map(|(array, shards)| {
1041            let mut entry = Map::new();
1042            entry.insert("id".into(), json!(array.id));
1043            if array.time() != first.time() {
1044                entry.insert("time".into(), array.time().clone());
1045            }
1046            if let Some(levels) = &array.levels {
1047                entry.insert("levels".into(), json!(levels));
1048            }
1049            let members: Vec<Value> = array
1050                .members
1051                .iter()
1052                .map(|member| json!({"bundle": member.bundle, "variable": member.variable}))
1053                .collect();
1054            entry.insert("members".into(), Value::Array(members));
1055            // The group document's CRC-32 is the store's `?v=`, and the codes
1056            // are nowhere else in it.
1057            entry.insert("shards".into(), json!(shards));
1058            Value::Object(entry)
1059        })
1060        .collect();
1061    block.insert("arrays".into(), Value::Array(entries));
1062    let consolidated: Map<String, Value> = documents.iter().cloned().collect();
1063    json!({
1064        "zarr_format": 3,
1065        "node_type": "group",
1066        "attributes": {COLUMN_ATTRIBUTE: Value::Object(block)},
1067        "consolidated_metadata": {
1068            "kind": "inline",
1069            "must_understand": false,
1070            "metadata": Value::Object(consolidated),
1071        },
1072    })
1073}
1074
1075/// A group document as it is written, read back by the decoder's own reader.
1076fn checked_group(document: &Value) -> Result<String> {
1077    let text = dumps_indented(document);
1078    ColumnGroup::parse(&text)
1079        .map_err(|error| invalid(format!("column store group is invalid: {}", error.0)))?;
1080    Ok(text)
1081}
1082
1083// -- the store -----------------------------------------------------------------
1084
1085/// What one cut wrote: the manifest descriptor's three values and each
1086/// array's shard bytes.
1087#[derive(Debug, Clone)]
1088pub struct ColumnReport {
1089    pub path: PathBuf,
1090    pub byte_length: u64,
1091    pub crc32: String,
1092    pub arrays: Vec<(String, u64)>,
1093}
1094
1095impl ColumnReport {
1096    /// The report, keyed as the reference's `write_column_store`.
1097    pub fn to_value(&self) -> Value {
1098        let arrays: Map<String, Value> = self
1099            .arrays
1100            .iter()
1101            .map(|(id, length)| (id.clone(), json!(length)))
1102            .collect();
1103        json!({
1104            "path": self.path.display().to_string(),
1105            "byteLength": self.byte_length,
1106            "crc32": self.crc32,
1107            "arrays": Value::Object(arrays),
1108        })
1109    }
1110}
1111
1112/// Cut the column store a plan describes from the map stores under
1113/// `run_directory` into `output`, which must not exist, with `jobs` workers.
1114/// The bytes do not depend on `jobs`.
1115pub fn write_columns(
1116    run_directory: &Path,
1117    plan: &str,
1118    output: &Path,
1119    jobs: usize,
1120) -> Result<ColumnReport> {
1121    if output.exists() {
1122        return Err(invalid(format!("{} exists", output.display())));
1123    }
1124    let arrays = resolve_plan(run_directory, parse_plan(plan)?)?;
1125    if let Some(parent) = output.parent() {
1126        fs::create_dir_all(parent).map_err(|error| io_error("write", parent, &error))?;
1127    }
1128    fs::create_dir(output).map_err(|error| io_error("write", output, &error))?;
1129    let report = write_store(&arrays, output, jobs);
1130    if report.is_err() {
1131        let _ = fs::remove_dir_all(output);
1132    }
1133    report
1134}
1135
1136fn write_store(arrays: &[ColumnArray], output: &Path, jobs: usize) -> Result<ColumnReport> {
1137    let names = dimensions(arrays);
1138    let mut documents = Vec::with_capacity(arrays.len());
1139    let mut byte_length = 0;
1140    for (array, names) in arrays.iter().zip(&names) {
1141        let document = array_document(array, names);
1142        byte_length += write_document(output, &array.id, &document)?;
1143        documents.push((array.id.clone(), document));
1144    }
1145    let (coordinates, written) = write_store_coordinates(arrays, &names, output)?;
1146    documents.extend(coordinates);
1147    byte_length += written;
1148    // What a reader would refuse is refused here, not after a long cut: only
1149    // the shards' CRCs are still to come.
1150    let pending: Vec<Vec<String>> = arrays
1151        .iter()
1152        .map(|array| vec!["00000000".to_owned(); array.geometry.shard_count()])
1153        .collect();
1154    checked_group(&group_document(arrays, &pending, &documents))?;
1155
1156    let tasks: Vec<(usize, usize)> = arrays
1157        .iter()
1158        .enumerate()
1159        .flat_map(|(array, held)| (0..held.geometry.shard_count()).map(move |shard| (array, shard)))
1160        .collect();
1161    let written = compression_pool(jobs)?.install(|| {
1162        tasks
1163            .par_iter()
1164            // A shard is the unit: without this a worker would be handed runs of them.
1165            .with_max_len(1)
1166            .map(|&(array, shard)| write_shard(&arrays[array], shard, output))
1167            .collect::<Result<Vec<_>>>()
1168    })?;
1169    let mut shards: Vec<Vec<String>> = vec![Vec::new(); arrays.len()];
1170    let mut sizes = vec![0u64; arrays.len()];
1171    for (&(array, _), shard) in tasks.iter().zip(written) {
1172        sizes[array] += shard.length;
1173        shards[array].push(shard.crc32);
1174    }
1175    byte_length += sizes.iter().sum::<u64>();
1176
1177    let text = checked_group(&group_document(arrays, &shards, &documents))?;
1178    byte_length += write_file_atomic(&output.join("zarr.json"), text.as_bytes())?;
1179    Ok(ColumnReport {
1180        path: output.to_path_buf(),
1181        byte_length,
1182        crc32: format!("{:08x}", crc32_plane(text.as_bytes())),
1183        arrays: arrays
1184            .iter()
1185            .map(|array| array.id.clone())
1186            .zip(sizes)
1187            .collect(),
1188    })
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193    use super::*;
1194    use crate::column::{parse_column_index, ColumnReader};
1195    use crate::encode::zarrstore::{self, StoreCodes, StoreVariable};
1196    use crate::format::Predictor;
1197
1198    const HEIGHT: usize = 97;
1199    const WIDTH: usize = 10;
1200    const FRAMES: usize = 7;
1201    const NODATA: u8 = 255;
1202
1203    /// A scratch directory of the test's own, removed when it ends.
1204    struct Scratch(PathBuf);
1205
1206    impl Scratch {
1207        fn new(name: &str) -> Scratch {
1208            let root =
1209                std::env::temp_dir().join(format!("xue-columns-{name}-{}", std::process::id()));
1210            let _ = fs::remove_dir_all(&root);
1211            fs::create_dir_all(&root).expect("scratch directory");
1212            Scratch(root)
1213        }
1214    }
1215
1216    impl Drop for Scratch {
1217        fn drop(&mut self) {
1218            let _ = fs::remove_dir_all(&self.0);
1219        }
1220    }
1221
1222    fn metadata(id: &str, frames: usize, offset: f64) -> Value {
1223        json!({
1224            "schemaVersion": 3,
1225            "model": "TEST",
1226            "product": "test",
1227            "runTime": "2026-08-14T06:00:00Z",
1228            "profile": "quality",
1229            "time": {"unitSeconds": 3600, "firstFrameOffset": 0, "frameCount": frames, "frameStep": 1},
1230            "grid": {"width": WIDTH, "height": HEIGHT, "firstLongitude": 100.0, "firstLatitude": 48.0,
1231                     "longitudeStep": 0.5, "latitudeStep": -0.5, "wrapLongitude": false},
1232            "variables": [{
1233                "numericId": 1, "id": id, "label": "T", "unit": "°C",
1234                "parameter": {"discipline": 0, "parameterCategory": 0, "parameterNumber": 0,
1235                              "typeOfFirstFixedSurface": 103, "scaleFactorOfFirstFixedSurface": 0,
1236                              "scaledValueOfFirstFixedSurface": 2},
1237                "quantization": {"type": "linear", "offset": offset, "scale": 0.5,
1238                                 "minimumCode": 0, "maximumCode": 220, "nodataCode": NODATA},
1239            }],
1240        })
1241    }
1242
1243    fn code(salt: usize, frame: usize, row: usize, column: usize) -> u8 {
1244        ((salt * 31 + frame * 7 + row * 3 + column * 5) % 220) as u8
1245    }
1246
1247    /// A one-bundle map store `<id>.zarr` of `code` over its grid.
1248    fn write_map(root: &Path, metadata: &Value, salt: usize, delta: bool) {
1249        let variable = &metadata["variables"][0]["id"];
1250        let id = variable.as_str().expect("id");
1251        let count = |node: &Value| node.as_u64().expect("count") as usize;
1252        let grid = &metadata["grid"];
1253        let (height, width) = (count(&grid["height"]), count(&grid["width"]));
1254        let planes: Vec<Vec<u8>> = (0..count(&metadata["time"]["frameCount"]))
1255            .map(|frame| {
1256                (0..height * width)
1257                    .map(|cell| code(salt, frame, cell / width, cell % width))
1258                    .collect()
1259            })
1260            .collect();
1261        let codes = StoreCodes {
1262            metadata,
1263            variables: vec![StoreVariable {
1264                id: id.to_owned(),
1265                previous: true,
1266                planes: planes.iter().map(Vec::as_slice).collect(),
1267            }],
1268            // 36 rows: the first band ends inside a tile.
1269            tile: (4, 36),
1270        };
1271        let pool = compression_pool(2).expect("pool");
1272        zarrstore::write_store(&codes, &root.join(format!("{id}.zarr")), delta, None, &pool)
1273            .expect("map store");
1274    }
1275
1276    fn member(id: &str) -> Value {
1277        json!({"bundle": id, "variable": id, "store": format!("{id}.zarr")})
1278    }
1279
1280    fn surface(id: &str, predictor: &str) -> Value {
1281        json!({"id": id, "predictor": predictor, "members": [member(id)]})
1282    }
1283
1284    fn levelled(levels: &[u32], ids: &[&str]) -> Value {
1285        let members: Vec<Value> = ids.iter().copied().map(member).collect();
1286        json!({"id": "tmp", "predictor": "previous", "levels": levels, "members": members})
1287    }
1288
1289    fn plan(arrays: &[Value]) -> Value {
1290        json!({"columnsPlan": 1, "arrays": arrays})
1291    }
1292
1293    fn files(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
1294        fn walk(root: &Path, directory: &Path, held: &mut BTreeMap<PathBuf, Vec<u8>>) {
1295            for entry in fs::read_dir(directory).expect("directory") {
1296                let path = entry.expect("entry").path();
1297                if path.is_dir() {
1298                    walk(root, &path, held);
1299                } else {
1300                    let name = path.strip_prefix(root).expect("below the root").to_owned();
1301                    held.insert(name, fs::read(&path).expect("file"));
1302                }
1303            }
1304        }
1305        let mut held = BTreeMap::new();
1306        walk(root, root, &mut held);
1307        held
1308    }
1309
1310    #[test]
1311    fn a_plan_is_parsed() {
1312        let arrays = parse_plan(
1313            &plan(&[
1314                levelled(&[850, 500], &["tmp850", "tmp500"]),
1315                surface("prate", "raw"),
1316            ])
1317            .to_string(),
1318        )
1319        .expect("a valid plan");
1320        assert_eq!(arrays[0].levels.as_deref(), Some([850, 500].as_slice()));
1321        assert!(arrays[0].previous && !arrays[1].previous);
1322        assert_eq!(arrays[0].members[1].store, "tmp500.zarr");
1323        assert_eq!((arrays[1].id.as_str(), &arrays[1].levels), ("prate", &None));
1324    }
1325
1326    #[test]
1327    fn a_malformed_plan_is_refused() {
1328        let array = || levelled(&[850, 500], &["tmp850", "tmp500"]);
1329        let with = |key: &str, value: Value| {
1330            let mut array = array();
1331            array[key] = value;
1332            plan(&[array])
1333        };
1334        let mut unnamed_store = array();
1335        unnamed_store["members"][0]["store"] = json!("");
1336        let mut extra_member_key = array();
1337        extra_member_key["members"][0]["level"] = json!(850);
1338        let mut no_predictor = array();
1339        no_predictor.as_object_mut().unwrap().remove("predictor");
1340        for (what, document) in [
1341            ("no version", json!({"arrays": [array()]})),
1342            (
1343                "another version",
1344                json!({"columnsPlan": 2, "arrays": [array()]}),
1345            ),
1346            (
1347                "a fractional version",
1348                json!({"columnsPlan": 1.0, "arrays": [array()]}),
1349            ),
1350            (
1351                "a boolean version",
1352                json!({"columnsPlan": true, "arrays": [array()]}),
1353            ),
1354            (
1355                "an unknown key",
1356                json!({"columnsPlan": 1, "arrays": [array()], "block": 8}),
1357            ),
1358            ("no arrays", plan(&[])),
1359            ("an unknown array key", with("block", json!(8))),
1360            ("no predictor", plan(&[no_predictor])),
1361            ("an unknown predictor", with("predictor", json!("anchor"))),
1362            ("no members", with("members", json!([]))),
1363            ("a bad id", with("id", json!("Tmp"))),
1364            ("a coordinate's id", with("id", json!("level"))),
1365            ("a repeated array", plan(&[array(), array()])),
1366            (
1367                "a repeated variable",
1368                plan(&[array(), surface("tmp850", "raw")]),
1369            ),
1370            ("ascending levels", with("levels", json!([500, 850]))),
1371            ("repeated levels", with("levels", json!([850, 850]))),
1372            ("a level short", with("levels", json!([850]))),
1373            ("a level of zero", with("levels", json!([850, 0]))),
1374            ("a fractional level", with("levels", json!([850, 0.5]))),
1375            (
1376                "a level past the coordinate",
1377                with("levels", json!([3_000_000_000u64, 500])),
1378            ),
1379            ("null levels", with("levels", Value::Null)),
1380            ("an empty store", plan(&[unnamed_store])),
1381            ("an unknown member key", plan(&[extra_member_key])),
1382            (
1383                "a surface array under another name",
1384                plan(&[json!({
1385                    "id": "t2m", "predictor": "raw", "members": [member("tmp2m")],
1386                })]),
1387            ),
1388            (
1389                "a surface array of two",
1390                plan(&[json!({
1391                    "id": "tmp850", "predictor": "raw", "members": [member("tmp850"), member("tmp500")],
1392                })]),
1393            ),
1394        ] {
1395            assert!(
1396                parse_plan(&document.to_string()).is_err(),
1397                "{what} was accepted"
1398            );
1399        }
1400        assert!(parse_plan("{").is_err());
1401        assert!(parse_plan("[1, []]").is_err());
1402    }
1403
1404    #[test]
1405    fn a_band_pads_its_blocks_and_differences_along_time_only() {
1406        let geometry = Geometry {
1407            frame_count: 2,
1408            levels: Some(2),
1409            height: 3,
1410            width: 9,
1411        };
1412        assert_eq!(
1413            geometry.shape(SHARD_ROWS, geometry.shard_width()),
1414            [2, 2, 96, 16]
1415        );
1416        assert_eq!(geometry.shard_path(0), Path::new("c/0/0/0/0"));
1417        let mut band = Band::new(geometry, &(0..3), NODATA).expect("band");
1418        assert_eq!(band.rows, BLOCK);
1419        for frame in 0..2 {
1420            for level in 0..2 {
1421                let start = band.offset(frame, level, 2, 8);
1422                band.codes[start] = (10 * frame + level) as u8;
1423            }
1424        }
1425        let mut chunk = Vec::new();
1426        band.cut(0, 1, false, &mut chunk);
1427        assert_eq!(chunk.len(), 2 * 2 * 64);
1428        // The block's one column in the grid is its first; everything past
1429        // it and past the third row is fill.
1430        let cells: Vec<(usize, u8)> = chunk
1431            .iter()
1432            .copied()
1433            .enumerate()
1434            .filter(|&(_, code)| code != NODATA)
1435            .collect();
1436        assert_eq!(
1437            cells,
1438            [(16, 0), (64 + 16, 1), (128 + 16, 10), (192 + 16, 11)]
1439        );
1440        band.cut(0, 1, true, &mut chunk);
1441        // Each level against itself a frame earlier, padding included.
1442        assert_eq!((chunk[16], chunk[64 + 16]), (0, 1));
1443        assert_eq!((chunk[128 + 16], chunk[192 + 16]), (10, 10));
1444        assert!(chunk[..16].iter().all(|&code| code == NODATA));
1445        assert!(chunk[128..128 + 16].iter().all(|&code| code == 0));
1446    }
1447
1448    /// Every cell of every array reads back as the codes the map stores hold,
1449    /// whatever the map store's predictor, and the bytes are the same at any
1450    /// number of workers.
1451    #[test]
1452    fn a_store_holds_the_map_stores_codes() {
1453        let scratch = Scratch::new("codes");
1454        let root = scratch.0.as_path();
1455        write_map(root, &metadata("tmp850", FRAMES, -70.0), 1, true);
1456        write_map(root, &metadata("tmp500", FRAMES, -90.0), 2, false);
1457        write_map(root, &metadata("prate", FRAMES, 0.0), 3, false);
1458        write_map(root, &metadata("orog", 1, 0.0), 4, false);
1459        let document = plan(&[
1460            levelled(&[850, 500], &["tmp850", "tmp500"]),
1461            surface("prate", "raw"),
1462            surface("orog", "previous"),
1463        ])
1464        .to_string();
1465        let output = root.join("columns.zarr");
1466        let report = write_columns(root, &document, &output, 1).expect("a column store");
1467        let held = files(&output);
1468        assert_eq!(
1469            report.byte_length,
1470            held.values().map(|bytes| bytes.len() as u64).sum::<u64>()
1471        );
1472        assert_eq!(
1473            report.crc32,
1474            format!("{:08x}", crc32_plane(&held[Path::new("zarr.json")]))
1475        );
1476        let parallel = root.join("parallel.zarr");
1477        write_columns(root, &document, &parallel, 3).expect("a column store");
1478        assert!(
1479            held == files(&parallel),
1480            "the bytes depend on the number of workers"
1481        );
1482
1483        let text = String::from_utf8(held[Path::new("zarr.json")].clone()).expect("UTF-8");
1484        let group: Value = serde_json::from_str(&text).expect("JSON");
1485        let consolidated = group["consolidated_metadata"]["metadata"]
1486            .as_object()
1487            .expect("object");
1488        assert_eq!(
1489            consolidated.keys().map(String::as_str).collect::<Vec<_>>(),
1490            [
1491                "tmp",
1492                "prate",
1493                "orog",
1494                "time",
1495                "level",
1496                "latitude",
1497                "longitude",
1498                "time_orog"
1499            ]
1500        );
1501        // The two levels' codebooks differ, so the array has no CF packing.
1502        assert!(consolidated["tmp"]["attributes"]
1503            .get("scale_factor")
1504            .is_none());
1505        assert_eq!(consolidated["prate"]["attributes"]["scale_factor"], 0.5);
1506        let inner =
1507            |id: &str| consolidated[id]["codecs"][0]["configuration"]["codecs"][0]["name"].clone();
1508        // A RAW array and a one-frame array are stored without the delta.
1509        assert_eq!(
1510            [inner("tmp"), inner("prate"), inner("orog")],
1511            ["xue.delta", "bytes", "bytes"]
1512        );
1513        assert_eq!(
1514            held[Path::new("level/c/0")],
1515            [850i32.to_le_bytes(), 500i32.to_le_bytes()].concat()
1516        );
1517
1518        let mut reader = ColumnReader::new(ColumnGroup::parse(&text).expect("the group reads"));
1519        for (id, frames, salts) in [
1520            ("tmp", FRAMES, vec![1, 2]),
1521            ("prate", FRAMES, vec![3]),
1522            ("orog", 1, vec![4]),
1523        ] {
1524            let array = reader.group().array(id).expect("array").clone();
1525            assert_eq!(array.layout.shard_count, 2);
1526            let mut shards = Vec::new();
1527            for shard in 0..2 {
1528                let bytes = &held[Path::new(&array.shard_path(shard))];
1529                let index = &bytes[..array.layout.index_length()];
1530                reader.set_shard_index(id, shard, index).expect("index");
1531                let crc32 = format!("{:08x}", crc32_plane(bytes));
1532                let entries = group["attributes"]["xue_columns"]["arrays"]
1533                    .as_array()
1534                    .expect("arrays");
1535                let entry = entries
1536                    .iter()
1537                    .find(|entry| entry["id"] == id)
1538                    .expect("entry");
1539                assert_eq!(entry["shards"][shard as usize], crc32.as_str());
1540                // The second band is one row of the grid: one block row
1541                // written, eleven past the grid never.
1542                let written = parse_column_index(&array.layout, index)
1543                    .expect("index")
1544                    .iter()
1545                    .flatten()
1546                    .count();
1547                assert_eq!(written, if shard == 0 { 24 } else { 2 });
1548                shards.push(bytes);
1549            }
1550            for row in 0..HEIGHT {
1551                for column in 0..WIDTH {
1552                    let span = reader
1553                        .chunk_range(id, row as u32, column as u32)
1554                        .expect("range")
1555                        .expect("written");
1556                    let shard = shards[row / SHARD_ROWS];
1557                    let payload =
1558                        &shard[span.offset as usize..(span.offset + span.length) as usize];
1559                    let expected: Vec<u8> = (0..frames)
1560                        .flat_map(|frame| {
1561                            salts
1562                                .iter()
1563                                .map(move |&salt| code(salt, frame, row, column))
1564                        })
1565                        .collect();
1566                    let codes = reader
1567                        .column(id, row as u32, column as u32, payload)
1568                        .expect("column");
1569                    assert_eq!(codes, expected, "{id} at {row}, {column}");
1570                }
1571            }
1572        }
1573    }
1574
1575    #[test]
1576    fn a_tile_the_map_store_never_held_is_its_fill_value() {
1577        let scratch = Scratch::new("absent");
1578        let root = scratch.0.as_path();
1579        write_map(root, &metadata("tmp2m", FRAMES, 0.0), 1, false);
1580        let path = root.join("tmp2m.zarr/tmp2m/c/0/0/0");
1581        let mut shard = fs::read(&path).expect("shard");
1582        // 3 tile rows of 3 tiles, two time chunks: drop the first tile.
1583        let start = shard.len() - zarr::shard_index_length(18);
1584        shard[start..start + 16].copy_from_slice(&NEVER_WRITTEN);
1585        let end = shard.len() - 4;
1586        let checksum = zarr::crc32c(&shard[start..end]);
1587        shard[end..].copy_from_slice(&checksum.to_le_bytes());
1588        fs::write(&path, &shard).expect("shard");
1589        let text = fs::read_to_string(root.join("tmp2m.zarr/zarr.json")).expect("group");
1590        let group: Value = serde_json::from_str(&text).expect("JSON");
1591        let document = group["consolidated_metadata"]["metadata"]["tmp2m"].to_string();
1592        let layout = zarr::parse_array_metadata(&document).expect("layout");
1593        let array = MapArray::open(path, layout).expect("map array");
1594        let mut band = [0u8; FRAMES * WIDTH];
1595        array
1596            .read_rows(&(35..36), |frame, row, column, cells| {
1597                assert_eq!(row, 0);
1598                let start = frame * WIDTH + column;
1599                band[start..start + cells.len()].copy_from_slice(cells);
1600            })
1601            .expect("rows");
1602        for frame in 0..FRAMES {
1603            for column in 0..WIDTH {
1604                let expected = if frame < 6 && column < 4 {
1605                    NODATA
1606                } else {
1607                    code(1, frame, 35, column)
1608                };
1609                assert_eq!(
1610                    band[frame * WIDTH + column],
1611                    expected,
1612                    "frame {frame}, column {column}"
1613                );
1614            }
1615        }
1616    }
1617
1618    /// What a store cannot hold is refused, and leaves no directory behind.
1619    #[test]
1620    fn what_a_column_store_cannot_hold_is_refused() {
1621        let scratch = Scratch::new("refused");
1622        let root = scratch.0.as_path();
1623        let base = metadata("tmp850", FRAMES, 0.0);
1624        write_map(root, &base, 1, false);
1625        write_map(root, &metadata("tmp500", FRAMES, 0.0), 2, false);
1626        write_map(root, &metadata("tmp300", 3, 0.0), 3, false);
1627        let mut nodata = metadata("tmp250", FRAMES, 0.0);
1628        nodata["variables"][0]["quantization"]["nodataCode"] = json!(254);
1629        write_map(root, &nodata, 4, false);
1630        let mut grid = metadata("tmp200", FRAMES, 0.0);
1631        grid["grid"]["firstLongitude"] = json!(101.0);
1632        write_map(root, &grid, 5, false);
1633        // The same place in another spelling is another document.
1634        let mut spelled = metadata("tmp225", FRAMES, 0.0);
1635        spelled["grid"]["firstLongitude"] = json!(100);
1636        write_map(root, &spelled, 9, false);
1637        let mut run = metadata("tmp150", FRAMES, 0.0);
1638        run["runTime"] = json!("2026-08-14T12:00:00Z");
1639        write_map(root, &run, 6, false);
1640        let mut projected = metadata("tmp100", FRAMES, 0.0);
1641        projected["schemaVersion"] = json!(4);
1642        projected["grid"] = json!({
1643            "width": WIDTH, "height": HEIGHT, "wrapLongitude": false,
1644            "projection": {"kind": "lambert-conformal", "radius": 6371229.0, "standardParallel1": 38.5,
1645                           "standardParallel2": 38.5, "latitudeOfOrigin": 38.5, "centralMeridian": -97.5,
1646                           "x0": -1500.0, "y0": 1500.0, "dx": 3000.0, "dy": -3000.0},
1647        });
1648        write_map(root, &projected, 7, false);
1649        write_map(root, &metadata("tmp50", FRAMES, 0.0), 8, false);
1650        fs::remove_file(root.join("tmp50.zarr/tmp50/c/0/0/0")).expect("shard");
1651
1652        let output = root.join("columns.zarr");
1653        let pair = |other: &str| plan(&[levelled(&[850, 500], &["tmp850", other])]);
1654        let mut elsewhere = pair("tmp500");
1655        elsewhere["arrays"][0]["members"][1]["store"] = json!("tmp850.zarr");
1656        for (what, document) in [
1657            ("two axes in one array", pair("tmp300")),
1658            ("two nodata codes", pair("tmp250")),
1659            ("another grid", pair("tmp200")),
1660            ("a grid spelled otherwise", pair("tmp225")),
1661            ("another run", pair("tmp150")),
1662            (
1663                "another run in another array",
1664                plan(&[surface("tmp850", "raw"), surface("tmp150", "raw")]),
1665            ),
1666            ("a projected grid", plan(&[surface("tmp100", "raw")])),
1667            ("a missing shard", pair("tmp50")),
1668            ("a missing store", pair("tmp70")),
1669            ("a store without the array", elsewhere),
1670        ] {
1671            assert!(
1672                write_columns(root, &document.to_string(), &output, 2).is_err(),
1673                "{what} was accepted"
1674            );
1675            assert!(!output.exists(), "{what} left a directory behind");
1676        }
1677        // A payload that does not decode fails in the cut itself.
1678        let path = root.join("tmp500.zarr/tmp500/c/0/0/0");
1679        let mut shard = fs::read(&path).expect("shard");
1680        shard[..8].fill(0);
1681        fs::write(&path, &shard).expect("shard");
1682        assert!(write_columns(root, &pair("tmp500").to_string(), &output, 2).is_err());
1683        assert!(!output.exists(), "a failed cut left its directory");
1684
1685        let document = plan(&[surface("tmp850", "raw")]).to_string();
1686        write_columns(root, &document, &output, 1).expect("a column store");
1687        let held = files(&output);
1688        assert!(
1689            write_columns(root, &document, &output, 1).is_err(),
1690            "an existing store was written over"
1691        );
1692        assert!(held == files(&output));
1693    }
1694
1695    /// A series codebook of sixteen-bit codes, the reference's
1696    /// `SERIES_CODEBOOK_TABLE["tmp2m"]`.
1697    fn wide_codebook() -> Map<String, Value> {
1698        json!({"type": "linear", "offset": -90.0, "scale": 0.1, "minimumCode": 0,
1699               "maximumCode": 1500, "nodataCode": 65535})
1700        .as_object()
1701        .expect("object")
1702        .clone()
1703    }
1704
1705    /// Codes over the codebook that fall from its top towards its bottom on
1706    /// odd frames, so the delta wraps modulo 65536, and a nodata cell.
1707    fn wide_code(salt: usize, frame: usize, row: usize, column: usize) -> u16 {
1708        if (row, column) == (3, 4) {
1709            return 65535;
1710        }
1711        let code = ((salt * 131 + frame * 911 + row * 41 + column * 7) % 1501) as u16;
1712        if frame % 2 == 1 {
1713            1500 - code
1714        } else {
1715            code
1716        }
1717    }
1718
1719    /// A one-bundle series store `<id>.series.zarr` of `wide_code`, its one
1720    /// variable widened, cut in 8x8 blocks over the whole axis.
1721    fn write_series(root: &Path, bundle: &Value, salt: usize, previous: bool) -> Value {
1722        let id = bundle["variables"][0]["id"]
1723            .as_str()
1724            .expect("id")
1725            .to_owned();
1726        let metadata = zarrstore::series_metadata(bundle, &[(id.as_str(), wide_codebook())]);
1727        let planes: Vec<Vec<u16>> = (0..FRAMES)
1728            .map(|frame| {
1729                (0..HEIGHT * WIDTH)
1730                    .map(|cell| wide_code(salt, frame, cell / WIDTH, cell % WIDTH))
1731                    .collect()
1732            })
1733            .collect();
1734        let held = zarrstore::WidePlanes(planes.iter().map(Vec::as_slice).collect());
1735        let codes = StoreCodes {
1736            metadata: &metadata,
1737            variables: vec![StoreVariable {
1738                id: id.clone(),
1739                previous,
1740                planes: Vec::new(),
1741            }],
1742            tile: (4, 36),
1743        };
1744        let wide = [zarrstore::WideVariable {
1745            id: id.clone(),
1746            codes: &held,
1747        }];
1748        let store = root.join(format!("{id}.series.zarr"));
1749        let pool = compression_pool(2).expect("pool");
1750        zarrstore::write_store_widened(&codes, &wide, &store, previous, Some((8, 8)), &pool)
1751            .expect("series store");
1752        metadata
1753    }
1754
1755    fn series_member(id: &str) -> Value {
1756        json!({"bundle": id, "variable": id, "store": format!("{id}.series.zarr")})
1757    }
1758
1759    /// A surface array whose plan names a series store holds its sixteen-bit
1760    /// codes as `uint16`, little-endian, the member the series store's
1761    /// variable; a levelled array beside it stays bytes.
1762    #[test]
1763    fn a_surface_array_is_cut_from_a_series_stores_sixteen_bit_codes() {
1764        let scratch = Scratch::new("wide");
1765        let root = scratch.0.as_path();
1766        write_map(root, &metadata("tmp850", FRAMES, -70.0), 1, true);
1767        write_map(root, &metadata("tmp500", FRAMES, -90.0), 2, false);
1768        let tmp2m = write_series(root, &metadata("tmp2m", FRAMES, -40.0), 3, true);
1769        let prate = write_series(root, &metadata("prate", FRAMES, 0.0), 4, false);
1770        let document = plan(&[
1771            levelled(&[850, 500], &["tmp850", "tmp500"]),
1772            json!({"id": "tmp2m", "predictor": "previous", "members": [series_member("tmp2m")]}),
1773            json!({"id": "prate", "predictor": "raw", "members": [series_member("prate")]}),
1774        ])
1775        .to_string();
1776        let output = root.join("columns.zarr");
1777        write_columns(root, &document, &output, 2).expect("a column store");
1778        let held = files(&output);
1779        let parallel = root.join("parallel.zarr");
1780        write_columns(root, &document, &parallel, 1).expect("a column store");
1781        assert!(
1782            held == files(&parallel),
1783            "the bytes depend on the number of workers"
1784        );
1785
1786        let text = String::from_utf8(held[Path::new("zarr.json")].clone()).expect("UTF-8");
1787        let group: Value = serde_json::from_str(&text).expect("JSON");
1788        let consolidated = &group["consolidated_metadata"]["metadata"];
1789        let codecs = |id: &str| consolidated[id]["codecs"][0]["configuration"]["codecs"].clone();
1790        let zstd =
1791            json!({"name": "zstd", "configuration": {"level": ZSTD_LEVEL, "checksum": true}});
1792        let little = json!({"name": "bytes", "configuration": {"endian": "little"}});
1793        assert_eq!(consolidated["tmp"]["data_type"], "uint8");
1794        assert_eq!(consolidated["tmp"]["fill_value"], 255);
1795        assert_eq!(codecs("tmp")[1], json!({"name": "bytes"}));
1796        for (id, delta) in [("tmp2m", true), ("prate", false)] {
1797            let array = &consolidated[id];
1798            assert_eq!(
1799                (&array["data_type"], &array["fill_value"]),
1800                (&json!("uint16"), &json!(65535))
1801            );
1802            let mut expected = vec![little.clone(), zstd.clone()];
1803            if delta {
1804                expected.insert(
1805                    0,
1806                    json!({"name": "xue.delta", "configuration": {"axis": 0}}),
1807                );
1808            }
1809            assert_eq!(codecs(id), Value::Array(expected), "{id}");
1810            assert_eq!(array["attributes"]["_FillValue"], 65535);
1811            assert_eq!(array["attributes"]["scale_factor"], 0.1);
1812            assert_eq!(array["attributes"]["add_offset"], -90.0);
1813        }
1814        let entries = group["attributes"]["xue_columns"]["arrays"]
1815            .as_array()
1816            .expect("arrays");
1817        for (id, metadata) in [("tmp2m", &tmp2m), ("prate", &prate)] {
1818            let entry = entries
1819                .iter()
1820                .find(|entry| entry["id"] == id)
1821                .expect("entry");
1822            assert_eq!(
1823                entry["members"][0]["variable"], metadata["variables"][0],
1824                "{id}'s member"
1825            );
1826        }
1827
1828        let mut reader = ColumnReader::new(ColumnGroup::parse(&text).expect("the group reads"));
1829        for (id, salt) in [("tmp2m", 3), ("prate", 4)] {
1830            let array = reader.group().array(id).expect("array").clone();
1831            let shards: Vec<&Vec<u8>> = (0..array.layout.shard_count)
1832                .map(|shard| &held[Path::new(&array.shard_path(shard))])
1833                .collect();
1834            for (shard, bytes) in shards.iter().enumerate() {
1835                reader
1836                    .set_shard_index(id, shard as u32, &bytes[..array.layout.index_length()])
1837                    .expect("index");
1838            }
1839            for row in 0..HEIGHT {
1840                for column in 0..WIDTH {
1841                    let span = reader
1842                        .chunk_range(id, row as u32, column as u32)
1843                        .expect("range")
1844                        .expect("written");
1845                    let shard = shards[row / SHARD_ROWS];
1846                    let payload =
1847                        &shard[span.offset as usize..(span.offset + span.length) as usize];
1848                    let expected: Vec<u16> = (0..FRAMES)
1849                        .map(|frame| wide_code(salt, frame, row, column))
1850                        .collect();
1851                    let codes = reader
1852                        .column_u16(id, row as u32, column as u32, payload)
1853                        .expect("column");
1854                    assert_eq!(codes, expected, "{id} at {row}, {column}");
1855                }
1856            }
1857        }
1858    }
1859
1860    /// A levelled array of sixteen-bit codes, and an array whose codebook
1861    /// contradicts its data type, are refused and leave nothing behind.
1862    #[test]
1863    fn sixteen_bit_codes_are_a_surface_arrays_alone() {
1864        let scratch = Scratch::new("wide-refused");
1865        let root = scratch.0.as_path();
1866        write_map(root, &metadata("tmp850", FRAMES, 0.0), 1, false);
1867        write_series(root, &metadata("tmp500", FRAMES, 0.0), 2, true);
1868        write_series(root, &metadata("tmp2m", FRAMES, 0.0), 3, true);
1869        // The group's codebook says bytes, the array is uint16.
1870        let path = root.join("tmp2m.series.zarr/zarr.json");
1871        let mut group: Value =
1872            serde_json::from_slice(&fs::read(&path).expect("group")).expect("JSON");
1873        group["attributes"]["xue"]["variables"][0]["quantization"] =
1874            metadata("tmp2m", FRAMES, 0.0)["variables"][0]["quantization"].clone();
1875        fs::write(&path, dumps_indented(&group)).expect("group");
1876
1877        let output = root.join("columns.zarr");
1878        let mut levelled_wide = levelled(&[850, 500], &["tmp850", "tmp500"]);
1879        levelled_wide["members"][1] = series_member("tmp500");
1880        for (what, document) in [
1881            ("a levelled uint16 member", plan(&[levelled_wide])),
1882            (
1883                "a codebook of bytes on a uint16 array",
1884                plan(&[
1885                    json!({"id": "tmp2m", "predictor": "previous", "members": [series_member("tmp2m")]}),
1886                ]),
1887            ),
1888        ] {
1889            assert!(
1890                write_columns(root, &document.to_string(), &output, 2).is_err(),
1891                "{what} was accepted"
1892            );
1893            assert!(!output.exists(), "{what} left a directory behind");
1894        }
1895        // The same series store cut as a surface array is accepted.
1896        let document = plan(&[
1897            json!({"id": "tmp500", "predictor": "previous", "members": [series_member("tmp500")]}),
1898        ]);
1899        write_columns(root, &document.to_string(), &output, 1).expect("a column store");
1900    }
1901
1902    /// Every block of every array, decoded through the shard indices; `None`
1903    /// for one never written.
1904    fn decoded(held: &BTreeMap<PathBuf, Vec<u8>>) -> Vec<(String, Vec<Option<Vec<u8>>>)> {
1905        let text = std::str::from_utf8(&held[Path::new("zarr.json")]).expect("UTF-8");
1906        let group = ColumnGroup::parse(text).expect("the group reads");
1907        group
1908            .arrays
1909            .iter()
1910            .map(|array| {
1911                let layout = &array.layout;
1912                let predictor = if layout.delta {
1913                    Predictor::Previous
1914                } else {
1915                    Predictor::Raw
1916                };
1917                let blocks = (0..layout.shard_count)
1918                    .flat_map(|shard| {
1919                        let bytes = &held[Path::new(&array.shard_path(shard))];
1920                        let index = parse_column_index(layout, &bytes[..layout.index_length()])
1921                            .expect("index");
1922                        index.into_iter().map(move |entry| {
1923                            entry.map(|entry| {
1924                                crate::decode_chunk(
1925                                    &bytes[entry.offset as usize..][..entry.length as usize],
1926                                    layout.frame_count,
1927                                    layout.level_count * layout.block_height,
1928                                    layout.block_width,
1929                                    predictor,
1930                                )
1931                                .expect("block")
1932                            })
1933                        })
1934                    })
1935                    .collect();
1936                (array.id.clone(), blocks)
1937            })
1938            .collect()
1939    }
1940
1941    /// The group document but for the shards' CRCs, the one thing in it that
1942    /// the compressed bytes move.
1943    fn group_without_shards(held: &BTreeMap<PathBuf, Vec<u8>>) -> String {
1944        let mut group: Value = serde_json::from_slice(&held[Path::new("zarr.json")]).expect("JSON");
1945        for entry in group["attributes"]["xue_columns"]["arrays"]
1946            .as_array_mut()
1947            .expect("arrays")
1948        {
1949            entry["shards"] = Value::Null;
1950        }
1951        dumps_indented(&group)
1952    }
1953
1954    /// The committed store the reference cut: byte for byte where this libzstd
1955    /// is the one it was compressed with, and everything but the compressed
1956    /// payloads, their lengths and their CRCs where it is not.
1957    #[test]
1958    fn the_committed_store_is_reproduced() {
1959        let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/column");
1960        let read = |name: &str| fs::read_to_string(fixture.join(name)).expect("fixture");
1961        let expected: Value = serde_json::from_str(&read("expected.json")).expect("JSON");
1962        let same_zstd = expected["zstdVersion"] == crate::encode::convert::zstd_version().as_str();
1963        let reference = files(&fixture.join("columns.zarr"));
1964        let blocks = decoded(&reference);
1965        // A data array's chunks; a coordinate's are not compressed.
1966        let is_shard = |name: &Path| {
1967            blocks
1968                .iter()
1969                .any(|(id, _)| name.starts_with(Path::new(id).join("c")))
1970        };
1971        let scratch = Scratch::new("golden");
1972        for jobs in [1, 4] {
1973            let output = scratch.0.join(format!("columns.{jobs}.zarr"));
1974            write_columns(&fixture, &read("plan.json"), &output, jobs).expect("a column store");
1975            let written = files(&output);
1976            assert!(written.keys().eq(reference.keys()));
1977            for (name, bytes) in &reference {
1978                if same_zstd || !(is_shard(name) || name == Path::new("zarr.json")) {
1979                    assert!(
1980                        &written[name] == bytes,
1981                        "{} differs from the reference's",
1982                        name.display()
1983                    );
1984                }
1985            }
1986            assert_eq!(
1987                group_without_shards(&written),
1988                group_without_shards(&reference)
1989            );
1990            for ((id, written), (_, reference)) in decoded(&written).iter().zip(&blocks) {
1991                assert!(
1992                    written == reference,
1993                    "{id} holds other codes than the reference's"
1994                );
1995            }
1996        }
1997    }
1998}
1999
2000#[cfg(test)]
2001mod schema_tie_tests {
2002    //! The block this writer writes is the one
2003    //! `docs/schemas/column-group.schema.json` names.
2004    use super::IDENTITY;
2005    use crate::schematie::assert_named;
2006
2007    const SCHEMA: &str = "column-group";
2008
2009    #[test]
2010    fn the_block_written_is_the_schemas() {
2011        assert_named(
2012            SCHEMA,
2013            "/$defs/Columns",
2014            &["version", "time", "grid", "arrays"],
2015        );
2016        assert_named(SCHEMA, "/$defs/Columns", &IDENTITY);
2017        assert_named(
2018            SCHEMA,
2019            "/$defs/Array",
2020            &["id", "time", "levels", "members", "shards"],
2021        );
2022        assert_named(SCHEMA, "/$defs/Member", &["bundle", "variable"]);
2023    }
2024}