Skip to main content

xue/
column.rs

1//! Reading the Zarr profile's column store.
2//!
3//! `docs/zarr-profile.md`, "Column store", is normative. A column store holds
4//! the codes of a run's published stores cut the other way: one array per
5//! quantity, `[time, level, latitude, longitude]` (a surface array has no
6//! level axis), whose inner chunk is the whole axis and every level of one
7//! small block of cells. One cell's column over the run is then one chunk per
8//! quantity. An array is `uint8`, the map stores' codes, except a surface
9//! array cut from a series store that widens its variable, which is `uint16`:
10//! [`decode_cells_u16`] reads either, [`decode_cells`] the bytes alone.
11//!
12//! Like [`crate::zarr`], this module is IO-free: it takes the group document,
13//! the shard indices and the chunks' bytes, and returns codes and values. The
14//! group's consolidated metadata holds every array document and is
15//! authoritative, so the group is the only document read. The metadata rules,
16//! the codec chain, the shard index and the chunk payload are the grid
17//! store's own; only the block, the dimensions and the cut are this branch's.
18
19use std::collections::{BTreeMap, BTreeSet};
20
21use serde_json::{json, Map, Value};
22
23use crate::format::{err, DecodeError, Predictor, MAX_PLANE_LENGTH};
24use crate::zarr::{
25    self, decode_value, parse_iso, DataType, Grid, IndexLocation, Quantization, ShardIndexEntry,
26    StoreKind, VariableMetadata, INDEX_ENTRY_BYTES,
27};
28
29/// The `xue_columns` block's version this reader implements.
30pub const COLUMN_VERSION: u64 = 1;
31/// The cells along each side of a writer's block. A reader takes the block
32/// from the array document and never assumes this one.
33pub const COLUMN_BLOCK_CELLS: u32 = 8;
34/// The rows of a writer's shard, whole blocks; a reader takes it likewise.
35pub const COLUMN_SHARD_ROWS: u32 = 96;
36/// The group attribute that carries the block, and the array attribute that
37/// names the array.
38pub(crate) const COLUMN_ATTRIBUTE: &str = "xue_columns";
39/// The grid branch's version, which goes with its block: beside this one it
40/// would leave a group that reads as two branches.
41const GRID_PROFILE_ATTRIBUTE: &str = "xue_profile";
42/// The coordinate arrays' names, which a data array must not take.
43pub(crate) const COORDINATES: [&str; 4] = ["time", "level", "latitude", "longitude"];
44/// The regular grid's numbers. A bundle's metadata reads defaults for missing
45/// ones because old metadata lacks them; nothing this old is a column store.
46const GRID_NUMBERS: [&str; 4] = [
47    "firstLongitude",
48    "firstLatitude",
49    "longitudeStep",
50    "latitudeStep",
51];
52
53// -- group ---------------------------------------------------------------------
54
55/// One level of a levelled array, or a surface array's one field: the bundle
56/// its codes come from and that bundle's variable.
57#[derive(Debug, Clone)]
58pub struct ColumnMember {
59    pub bundle: String,
60    /// The codebook is this member's own: two levels of one array may differ.
61    /// `numeric_id` is meaningless here.
62    pub variable: VariableMetadata,
63}
64
65/// One array of the store, its document held to the block.
66#[derive(Debug, Clone)]
67pub struct ColumnArray {
68    pub id: String,
69    /// Pressure levels in hPa, strictly descending, index for index with
70    /// `members`; `None` on a surface array, which has one member.
71    pub levels: Option<Vec<u32>>,
72    pub members: Vec<ColumnMember>,
73    /// The array's axis: the store's, unless it declares its own.
74    pub unit_seconds: u32,
75    pub offsets: Vec<u16>,
76    pub layout: ColumnLayout,
77}
78
79impl ColumnArray {
80    /// The object holding one shard, relative to the store. A shard spans the
81    /// whole axis, every level and every column, so only its row band counts.
82    pub fn shard_path(&self, shard: u32) -> String {
83        match self.levels {
84            Some(_) => format!("{}/c/0/0/{shard}/0", self.id),
85            None => format!("{}/c/0/{shard}/0", self.id),
86        }
87    }
88
89    /// One cell's codes ([`decode_column`] or [`decode_column_u16`], `frames ×
90    /// levels`) as physical values through each level's own codebook; `NaN`
91    /// for no value.
92    pub fn values<C: Copy + Into<u16>>(&self, codes: &[C]) -> Result<Vec<f64>, DecodeError> {
93        if codes.len() != self.layout.column_length() {
94            return Err(err("column does not fit the array's frames and levels"));
95        }
96        Ok(codes
97            .chunks_exact(self.members.len())
98            .flat_map(|frame| frame.iter().zip(&self.members))
99            .map(|(&code, member)| {
100                decode_value(&member.variable.quantization, code.into()).unwrap_or(f64::NAN)
101            })
102            .collect())
103    }
104}
105
106/// A column store's group document: the `xue_columns` block and every array
107/// document it consolidates, validated against one another.
108#[derive(Debug, Clone)]
109pub struct ColumnGroup {
110    pub version: u32,
111    pub model: String,
112    pub product: String,
113    pub run_time: String,
114    /// `run_time` in Unix seconds.
115    pub run_time_seconds: i64,
116    pub profile: String,
117    pub grid: Grid,
118    /// The store's axis, in `unit_seconds`, strictly ascending.
119    pub unit_seconds: u32,
120    pub offsets: Vec<u16>,
121    pub arrays: Vec<ColumnArray>,
122    /// The `xue_columns` block as compact JSON.
123    pub block_json: String,
124}
125
126impl ColumnGroup {
127    /// Parse a store root's `zarr.json`: a Zarr v3 group whose attributes
128    /// carry `xue_columns` and no other branch's block, at a version this
129    /// reader implements, with the consolidated document of every array the
130    /// block lists.
131    pub fn parse(text: &str) -> Result<ColumnGroup, DecodeError> {
132        let mut document: Value =
133            serde_json::from_str(text).map_err(|_| err("group metadata is not valid JSON"))?;
134        let (kind, _) = zarr::document_branch(&document)?;
135        if kind != StoreKind::Column {
136            return Err(err("group is not a column store"));
137        }
138        if document["attributes"].get(GRID_PROFILE_ATTRIBUTE).is_some() {
139            return Err(err("a column store group carries no xue_profile"));
140        }
141        let mut documents = consolidated_documents(&mut document)?;
142        let block = document["attributes"][COLUMN_ATTRIBUTE]
143            .as_object()
144            .ok_or_else(|| err("xue_columns must be an object"))?;
145        let version = block
146            .get("version")
147            .and_then(|v| v.as_u64())
148            .ok_or_else(|| err("xue_columns version missing"))?;
149        if version != COLUMN_VERSION {
150            return Err(err(format!(
151                "column store version {version} is not implemented"
152            )));
153        }
154        let model = nonempty(block, "model")?;
155        let product = nonempty(block, "product")?;
156        let profile = nonempty(block, "profile")?;
157        let run_time = nonempty(block, "runTime")?;
158        let run_time_ms = parse_iso(&run_time)
159            .ok_or_else(|| err("xue_columns runTime is not an ISO 8601 instant"))?;
160        if run_time_ms % 1000.0 != 0.0 {
161            return Err(err("xue_columns runTime must fall on a whole second"));
162        }
163        let grid = block
164            .get("grid")
165            .ok_or_else(|| err("xue_columns grid missing"))?;
166        check_grid(grid)?;
167        let time = block
168            .get("time")
169            .ok_or_else(|| err("xue_columns time missing"))?;
170
171        let entries = parse_entries(block)?;
172        let shared: Vec<&Value> = entries
173            .iter()
174            .filter(|entry| entry.time.is_none())
175            .flat_map(|entry| entry.variables.iter().copied())
176            .collect();
177        if shared.is_empty() {
178            return Err(err("xue_columns arrays must hold one on the store's axis"));
179        }
180        let axis = read_axis(grid, time, &shared)?;
181        let grid_shape = (u64::from(axis.grid.height()), u64::from(axis.grid.width()));
182        let mut shared_variables = axis.variables.into_iter();
183        let mut variable_ids = BTreeSet::new();
184        // The first levelled array's levels are the store's `level` coordinate.
185        let store_levels = entries.iter().find_map(|entry| entry.levels.clone());
186        let mut arrays = Vec::with_capacity(entries.len());
187        for entry in entries {
188            let (unit_seconds, offsets, variables) = match entry.time {
189                None => (
190                    axis.unit_seconds,
191                    axis.offsets.clone(),
192                    shared_variables
193                        .by_ref()
194                        .take(entry.variables.len())
195                        .collect::<Vec<_>>(),
196                ),
197                Some(own) => {
198                    let own = read_axis(grid, own, &entry.variables)?;
199                    if (own.unit_seconds, &own.offsets) == (axis.unit_seconds, &axis.offsets) {
200                        return Err(err(format!(
201                            "array {} repeats the store's time block",
202                            entry.id
203                        )));
204                    }
205                    (own.unit_seconds, own.offsets, own.variables)
206                }
207            };
208            for variable in &variables {
209                if !variable_ids.insert(variable.id.clone()) {
210                    return Err(err(format!("variable {} occurs twice", variable.id)));
211                }
212            }
213            let array_document = documents
214                .remove(entry.id)
215                .ok_or_else(|| err(format!("group consolidates no array {}", entry.id)))?;
216            let mut dimensions = vec![dimension("time", entry.time.is_some(), entry.id)];
217            if entry.levels.is_some() {
218                dimensions.push(dimension("level", entry.levels != store_levels, entry.id));
219            }
220            dimensions.extend(["latitude".to_owned(), "longitude".to_owned()]);
221            let layout = read_layout(
222                array_document,
223                entry.id,
224                &dimensions,
225                offsets.len() as u64,
226                entry.levels.as_ref().map(|levels| levels.len() as u64),
227                grid_shape,
228            )
229            .map_err(|error| err(format!("array {}: {}", entry.id, error.0)))?;
230            if variables
231                .iter()
232                .any(|variable| nodata_code(&variable.quantization) != f64::from(layout.fill_value))
233            {
234                return Err(err(format!(
235                    "array {}: fill_value must be every member's nodataCode",
236                    entry.id
237                )));
238            }
239            for variable in &variables {
240                check_width(&variable.quantization, layout.data_type)
241                    .map_err(|error| err(format!("array {}: {}", entry.id, error.0)))?;
242            }
243            if entry.levels.is_none() && variables[0].id != entry.id {
244                return Err(err(format!(
245                    "surface array {} must be named for its variable",
246                    entry.id
247                )));
248            }
249            arrays.push(ColumnArray {
250                id: entry.id.to_owned(),
251                levels: entry.levels,
252                members: entry
253                    .bundles
254                    .into_iter()
255                    .zip(variables)
256                    .map(|(bundle, variable)| ColumnMember {
257                        bundle: bundle.to_owned(),
258                        variable,
259                    })
260                    .collect(),
261                unit_seconds,
262                offsets,
263                layout,
264            });
265        }
266        let block_json = serde_json::to_string(block)
267            .map_err(|_| err("xue_columns block is not serializable"))?;
268        Ok(ColumnGroup {
269            version: version as u32,
270            model,
271            product,
272            run_time,
273            run_time_seconds: (run_time_ms / 1000.0) as i64,
274            profile,
275            grid: axis.grid,
276            unit_seconds: axis.unit_seconds,
277            offsets: axis.offsets,
278            arrays,
279            block_json,
280        })
281    }
282
283    pub fn array(&self, id: &str) -> Result<&ColumnArray, DecodeError> {
284        self.arrays
285            .iter()
286            .find(|array| array.id == id)
287            .ok_or_else(|| err(format!("column store holds no array {id:?}")))
288    }
289}
290
291fn nonempty(block: &Map<String, Value>, key: &str) -> Result<String, DecodeError> {
292    block
293        .get(key)
294        .and_then(|v| v.as_str())
295        .filter(|text| !text.is_empty())
296        .map(str::to_owned)
297        .ok_or_else(|| err(format!("xue_columns {key} must be a non-empty string")))
298}
299
300/// The inline consolidated array documents, taken out of the group rather than
301/// copied: they are most of it.
302fn consolidated_documents(document: &mut Value) -> Result<Map<String, Value>, DecodeError> {
303    let consolidated = document
304        .get_mut("consolidated_metadata")
305        .ok_or_else(|| err("column store group carries no consolidated metadata"))?;
306    if consolidated.get("kind").and_then(|v| v.as_str()) != Some("inline") {
307        return Err(err("consolidated metadata must be inline"));
308    }
309    match consolidated.get_mut("metadata").map(Value::take) {
310        Some(Value::Object(documents)) => Ok(documents),
311        _ => Err(err("consolidated metadata holds no documents")),
312    }
313}
314
315/// A regular or Gaussian grid with every field its schema requires. The rest
316/// of the rules are bundle metadata's, checked with the axis.
317fn check_grid(grid: &Value) -> Result<(), DecodeError> {
318    if grid.get("projection").is_some() {
319        return Err(err("a column store's grid must not be projected"));
320    }
321    if GRID_NUMBERS
322        .iter()
323        .any(|key| grid.get(key).and_then(|v| v.as_f64()).is_none())
324        || grid
325            .get("wrapLongitude")
326            .and_then(|v| v.as_bool())
327            .is_none()
328    {
329        return Err(err("xue_columns grid is incomplete"));
330    }
331    Ok(())
332}
333
334/// One entry of the block's `arrays`, its structure checked.
335struct Entry<'a> {
336    id: &'a str,
337    time: Option<&'a Value>,
338    levels: Option<Vec<u32>>,
339    bundles: Vec<&'a str>,
340    variables: Vec<&'a Value>,
341}
342
343/// `^[a-z][a-z0-9]*$`: an array id, and a bundle id.
344pub(crate) fn is_id(text: &str) -> bool {
345    text.bytes()
346        .next()
347        .is_some_and(|first| first.is_ascii_lowercase())
348        && text
349            .bytes()
350            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
351}
352
353fn parse_entries(block: &Map<String, Value>) -> Result<Vec<Entry<'_>>, DecodeError> {
354    let list = block
355        .get("arrays")
356        .and_then(|v| v.as_array())
357        .filter(|list| !list.is_empty())
358        .ok_or_else(|| err("xue_columns arrays must list at least one array"))?;
359    let mut ids = BTreeSet::new();
360    let mut entries = Vec::with_capacity(list.len());
361    for item in list {
362        let id = item
363            .get("id")
364            .and_then(|v| v.as_str())
365            .filter(|id| is_id(id) && !COORDINATES.contains(id))
366            .ok_or_else(|| err("xue_columns array id is invalid"))?;
367        if !ids.insert(id) {
368            return Err(err(format!("xue_columns array {id} occurs twice")));
369        }
370        let levels = item.get("levels").map(parse_levels).transpose()?;
371        let members = item
372            .get("members")
373            .and_then(|v| v.as_array())
374            .filter(|members| members.len() == levels.as_ref().map_or(1, Vec::len))
375            .ok_or_else(|| err(format!("array {id} must have one member per level")))?;
376        let mut bundles = Vec::with_capacity(members.len());
377        let mut variables = Vec::with_capacity(members.len());
378        for member in members {
379            bundles.push(
380                member
381                    .get("bundle")
382                    .and_then(|v| v.as_str())
383                    .filter(|bundle| is_id(bundle))
384                    .ok_or_else(|| err(format!("array {id}: a member names no bundle id")))?,
385            );
386            variables.push(
387                member
388                    .get("variable")
389                    .filter(|variable| variable.is_object())
390                    .ok_or_else(|| err(format!("array {id}: a member carries no variable")))?,
391            );
392        }
393        entries.push(Entry {
394            id,
395            time: item.get("time"),
396            levels,
397            bundles,
398            variables,
399        });
400    }
401    Ok(entries)
402}
403
404/// Positive whole hPa, strictly descending, in the `int32` range of the
405/// `level` coordinate.
406fn parse_levels(value: &Value) -> Result<Vec<u32>, DecodeError> {
407    let list = value
408        .as_array()
409        .filter(|list| !list.is_empty())
410        .ok_or_else(|| err("levels must list at least one level"))?;
411    let mut levels: Vec<u32> = Vec::with_capacity(list.len());
412    for item in list {
413        let level = item
414            .as_u64()
415            .filter(|&level| level > 0 && level <= i32::MAX as u64)
416            .ok_or_else(|| err("levels must be positive integers"))? as u32;
417        if levels.last().is_some_and(|&previous| level >= previous) {
418            return Err(err("levels must be strictly descending"));
419        }
420        levels.push(level);
421    }
422    Ok(levels)
423}
424
425struct Axis {
426    unit_seconds: u32,
427    offsets: Vec<u16>,
428    grid: Grid,
429    variables: Vec<VariableMetadata>,
430}
431
432/// The grid, a time block and the variables on it, validated as the bundle
433/// metadata they were copied from: the rules live in one place. `numericId`
434/// is local to each variable's own bundle, so they are renumbered for a
435/// document that holds variables of several, at most 255 at a time.
436fn read_axis(grid: &Value, time: &Value, variables: &[&Value]) -> Result<Axis, DecodeError> {
437    let mut read: Option<Axis> = None;
438    for group in variables.chunks(usize::from(u8::MAX)) {
439        let numbered: Vec<Value> = group
440            .iter()
441            .zip(1..=u8::MAX)
442            .map(|(&variable, number)| {
443                let mut variable = variable.clone();
444                variable["numericId"] = Value::from(number);
445                variable
446            })
447            .collect();
448        let document =
449            json!({"schemaVersion": 3, "grid": grid, "time": time, "variables": numbered});
450        let metadata = zarr::parse_bundle_metadata(&document.to_string())?;
451        match &mut read {
452            None => {
453                read = Some(Axis {
454                    unit_seconds: metadata.unit_seconds,
455                    offsets: metadata.offsets,
456                    grid: metadata.grid,
457                    variables: metadata.variables,
458                })
459            }
460            Some(axis) => axis.variables.extend(metadata.variables),
461        }
462    }
463    read.ok_or_else(|| err("xue_columns axis serves no array"))
464}
465
466fn dimension(name: &str, own: bool, array: &str) -> String {
467    if own {
468        format!("{name}_{array}")
469    } else {
470        name.to_owned()
471    }
472}
473
474fn nodata_code(quantization: &Quantization) -> f64 {
475    match *quantization {
476        Quantization::Linear { nodata_code, .. } | Quantization::Log1p { nodata_code, .. } => {
477            nodata_code
478        }
479    }
480}
481
482/// A member's codebook held to its array's `data_type`: `uint16` exactly
483/// when the no-data code does not fit a byte, which only a series store's
484/// codebook's does, and every code it names within the type. Bundle metadata
485/// admits codes up to 65535 wherever they sit, so the width is checked here.
486fn check_width(quantization: &Quantization, data_type: DataType) -> Result<(), DecodeError> {
487    let wide = nodata_code(quantization) > f64::from(u8::MAX);
488    if wide != (data_type == DataType::U16) {
489        return Err(err(format!(
490            "a {} array of a codebook whose codes are not",
491            data_type.name()
492        )));
493    }
494    let codes: &[f64] = match quantization {
495        Quantization::Linear {
496            minimum_code,
497            maximum_code,
498            nodata_code,
499            ..
500        } => &[*minimum_code, *maximum_code, *nodata_code],
501        Quantization::Log1p {
502            minimum_code,
503            maximum_code,
504            zero_code,
505            overflow_code,
506            nodata_code,
507            ..
508        } => &[
509            *minimum_code,
510            *maximum_code,
511            *zero_code,
512            *overflow_code,
513            *nodata_code,
514        ],
515    };
516    let max = f64::from(data_type.max_code());
517    if codes.iter().any(|&code| code > max) {
518        return Err(err(format!(
519            "a codebook on a {} array names a code past {max}",
520            data_type.name()
521        )));
522    }
523    Ok(())
524}
525
526// -- array ---------------------------------------------------------------------
527
528/// How an array is cut: an inner chunk of the whole axis and every level of
529/// one block of cells, a shard of whole blocks across the grid's width.
530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
531pub struct ColumnLayout {
532    pub frame_count: u32,
533    /// 1 on a surface array.
534    pub level_count: u32,
535    pub height: u32,
536    pub width: u32,
537    pub block_height: u32,
538    pub block_width: u32,
539    /// Rows per shard, whole blocks. The last shard's may run past the grid.
540    pub shard_height: u32,
541    pub shard_width: u32,
542    pub shard_count: u32,
543    /// Blocks in a shard, and pairs in its index.
544    pub chunks_per_shard: u32,
545    pub delta: bool,
546    pub index_location: IndexLocation,
547    /// `U16` on a surface array cut from a series store's widened variable.
548    pub data_type: DataType,
549    pub fill_value: u16,
550}
551
552impl ColumnLayout {
553    /// Codes of one cell's column: `frames × levels`.
554    pub fn column_length(&self) -> usize {
555        self.frame_count as usize * self.level_count as usize
556    }
557
558    /// The shard index's byte length: one pair per block plus the CRC-32C.
559    pub fn index_length(&self) -> usize {
560        zarr::shard_index_length(self.chunks_per_shard as usize)
561    }
562
563    /// The shard a cell lies in.
564    pub fn shard_of(&self, row: u32, column: u32) -> Result<u32, DecodeError> {
565        if row >= self.height || column >= self.width {
566            return Err(err("cell is outside the grid"));
567        }
568        Ok(row / self.shard_height)
569    }
570
571    /// The index position, within its shard, of the block a cell lies in.
572    pub fn position(&self, row: u32, column: u32) -> Result<usize, DecodeError> {
573        self.shard_of(row, column)?;
574        let block_row = (row % self.shard_height) / self.block_height;
575        let blocks_across = self.shard_width / self.block_width;
576        Ok(block_row as usize * blocks_across as usize + (column / self.block_width) as usize)
577    }
578
579    /// The index's span within a shard of `shard_length` bytes, `[start,
580    /// end)`.
581    pub fn shard_index_range(&self, shard_length: u64) -> Result<(u64, u64), DecodeError> {
582        let length = self.index_length() as u64;
583        if shard_length < length {
584            return Err(err("shard is shorter than its index"));
585        }
586        Ok(match self.index_location {
587            IndexLocation::Start => (0, length),
588            IndexLocation::End => (shard_length - length, shard_length),
589        })
590    }
591}
592
593/// One array's document held to the profile's codec rules and to the block.
594fn read_layout(
595    document: Value,
596    id: &str,
597    dimensions: &[String],
598    frames: u64,
599    levels: Option<u64>,
600    (height, width): (u64, u64),
601) -> Result<ColumnLayout, DecodeError> {
602    // A levelled array holds the maps' bytes; only a surface array may hold a
603    // series store's sixteen-bit codes.
604    let widths: &[DataType] = match levels {
605        Some(_) => &[DataType::U8],
606        None => &[DataType::U8, DataType::U16],
607    };
608    let array = zarr::sharded_array_of(document, dimensions.len(), widths)?;
609    let names = array
610        .value
611        .get("dimension_names")
612        .and_then(|v| v.as_array())
613        .ok_or_else(|| err("dimension_names missing"))?;
614    if !names
615        .iter()
616        .map(|name| name.as_str())
617        .eq(dimensions.iter().map(|name| Some(name.as_str())))
618    {
619        return Err(err(format!(
620            "dimension_names must be {}",
621            dimensions.join(", ")
622        )));
623    }
624    let named = array
625        .value
626        .get("attributes")
627        .and_then(|v| v.get(COLUMN_ATTRIBUTE))
628        .and_then(|v| v.get("array"))
629        .and_then(|v| v.as_str());
630    if named != Some(id) {
631        return Err(err("attributes must name the array in xue_columns"));
632    }
633    // Every shape is the axis, the levels where there are any, then cells.
634    let axes: Vec<u64> = [Some(frames), levels].into_iter().flatten().collect();
635    let cells = |shape: &[u64], what: &str| -> Result<(u64, u64), DecodeError> {
636        match shape.strip_prefix(axes.as_slice()) {
637            Some(&[rows, columns]) => Ok((rows, columns)),
638            _ => Err(err(format!(
639                "{what} must span the whole axis and every level"
640            ))),
641        }
642    };
643    if cells(&array.shape, "shape")? != (height, width) {
644        return Err(err("shape must be the store's grid"));
645    }
646    let (block_height, block_width) = cells(&array.inner_shape, "inner chunk")?;
647    let (shard_height, shard_width) = cells(&array.shard_shape, "shard")?;
648    if shard_height % block_height != 0 || shard_width % block_width != 0 {
649        return Err(err("shard must be whole blocks"));
650    }
651    if shard_width < width {
652        return Err(err("shard must cover the grid's width"));
653    }
654    let level_count = levels.unwrap_or(1);
655    block_height
656        .checked_mul(block_width)
657        .and_then(|cells| cells.checked_mul(frames))
658        .and_then(|cells| cells.checked_mul(level_count))
659        .filter(|&cells| cells <= MAX_PLANE_LENGTH)
660        .ok_or_else(|| err("inner chunk exceeds the decoded size limit"))?;
661    let chunks_per_shard = (shard_height / block_height)
662        .checked_mul(shard_width / block_width)
663        .filter(|&count| count.saturating_mul(INDEX_ENTRY_BYTES as u64) <= MAX_PLANE_LENGTH)
664        .ok_or_else(|| err("shard index exceeds the decoded size limit"))?;
665    // A block is bounded by the chunk and the blocks of a shard by its index,
666    // but their product is not: hold it to the type the layout keeps.
667    let dimension =
668        |cells: u64| u32::try_from(cells).map_err(|_| err("array exceeds the decoded size limit"));
669    Ok(ColumnLayout {
670        frame_count: dimension(frames)?,
671        level_count: dimension(level_count)?,
672        height: dimension(height)?,
673        width: dimension(width)?,
674        block_height: dimension(block_height)?,
675        block_width: dimension(block_width)?,
676        shard_height: dimension(shard_height)?,
677        shard_width: dimension(shard_width)?,
678        shard_count: dimension(height.div_ceil(shard_height))?,
679        chunks_per_shard: dimension(chunks_per_shard)?,
680        delta: array.delta,
681        index_location: array.index_location,
682        data_type: array.data_type,
683        // Held to the data type by `sharded_array_of`.
684        fill_value: array.fill_value,
685    })
686}
687
688// -- shard ---------------------------------------------------------------------
689
690/// Parse one shard's index, CRC-32C verified, no chunk lying inside an index
691/// at the shard's start. `bytes` is exactly the index.
692pub fn parse_column_index(
693    layout: &ColumnLayout,
694    bytes: &[u8],
695) -> Result<Vec<Option<ShardIndexEntry>>, DecodeError> {
696    let index = zarr::parse_shard_index(bytes, layout.chunks_per_shard as usize)?;
697    if layout.index_location == IndexLocation::Start
698        && index
699            .iter()
700            .flatten()
701            .any(|entry| entry.offset < layout.index_length() as u64)
702    {
703        return Err(err("shard index names bytes inside the index"));
704    }
705    Ok(index)
706}
707
708/// Where the block a cell lies in sits within its shard, or `None` for a
709/// block the shard never held, which reads as the fill value. `index` is that
710/// of the cell's shard ([`ColumnLayout::shard_of`]).
711pub fn chunk_range(
712    layout: &ColumnLayout,
713    index: &[Option<ShardIndexEntry>],
714    row: u32,
715    column: u32,
716) -> Result<Option<ShardIndexEntry>, DecodeError> {
717    if index.len() != layout.chunks_per_shard as usize {
718        return Err(err("shard index does not match the array's chunk grid"));
719    }
720    index
721        .get(layout.position(row, column)?)
722        .copied()
723        .ok_or_else(|| err("cell is outside the shard"))
724}
725
726/// One cell's codes, `frames × levels`, frame by frame: [`decode_cells`] of
727/// that cell alone.
728pub fn decode_column(
729    layout: &ColumnLayout,
730    row: u32,
731    column: u32,
732    payload: Option<&[u8]>,
733) -> Result<Vec<u8>, DecodeError> {
734    decode_cells(layout, &[(row, column)], payload)
735}
736
737/// [`decode_column`] of an array of either type, the codes widened: what a
738/// cell's series is read with.
739pub fn decode_column_u16(
740    layout: &ColumnLayout,
741    row: u32,
742    column: u32,
743    payload: Option<&[u8]>,
744) -> Result<Vec<u16>, DecodeError> {
745    decode_cells_u16(layout, &[(row, column)], payload)
746}
747
748/// The codes of some cells, `(row, column)`, of one block of a `uint8`
749/// array: `cells × frames × levels`, cell by cell in the order given, each
750/// frame by frame. `payload` is the block's chunk, `None` for one the shard
751/// never held. A `uint16` array is refused: its codes are
752/// [`decode_cells_u16`]'s.
753pub fn decode_cells(
754    layout: &ColumnLayout,
755    cells: &[(u32, u32)],
756    payload: Option<&[u8]>,
757) -> Result<Vec<u8>, DecodeError> {
758    if layout.data_type != DataType::U8 {
759        return Err(err("a uint16 column array is read as sixteen-bit codes"));
760    }
761    check_cells(layout, cells)?;
762    let Some(payload) = payload else {
763        // A uint8 array's fill fits a byte (`sharded_array_of`).
764        return Ok(vec![
765            layout.fill_value as u8;
766            layout.column_length() * cells.len()
767        ]);
768    };
769    let chunk = crate::decode_chunk(
770        payload,
771        layout.frame_count,
772        layout.level_count * layout.block_height,
773        layout.block_width,
774        predictor(layout),
775    )?;
776    Ok(pick_cells(layout, cells, &chunk))
777}
778
779/// [`decode_cells`] of an array of either type: a `uint8` array's codes
780/// widened, a `uint16` one's (little-endian, the delta modulo 65536) as they
781/// are.
782pub fn decode_cells_u16(
783    layout: &ColumnLayout,
784    cells: &[(u32, u32)],
785    payload: Option<&[u8]>,
786) -> Result<Vec<u16>, DecodeError> {
787    if layout.data_type == DataType::U8 {
788        return decode_cells(layout, cells, payload)
789            .map(|codes| codes.into_iter().map(u16::from).collect());
790    }
791    check_cells(layout, cells)?;
792    let Some(payload) = payload else {
793        return Ok(vec![
794            layout.fill_value;
795            layout.column_length() * cells.len()
796        ]);
797    };
798    let chunk = crate::decode_chunk_u16(
799        payload,
800        layout.frame_count,
801        layout.level_count * layout.block_height,
802        layout.block_width,
803        predictor(layout),
804    )?;
805    Ok(pick_cells(layout, cells, &chunk))
806}
807
808fn predictor(layout: &ColumnLayout) -> Predictor {
809    if layout.delta {
810        Predictor::Previous
811    } else {
812        Predictor::Raw
813    }
814}
815
816/// The cells of one read: at least one, no more than a block holds, all in
817/// one block of the grid.
818fn check_cells(layout: &ColumnLayout, cells: &[(u32, u32)]) -> Result<(), DecodeError> {
819    let &(first_row, first_column) = cells.first().ok_or_else(|| err("no cell to read"))?;
820    // The layout holds a whole block to the decoded size limit, so a read of
821    // no more cells than that needs no limit of its own.
822    if cells.len() as u64 > u64::from(layout.block_height) * u64::from(layout.block_width) {
823        return Err(err("more cells than the block holds"));
824    }
825    let block = (
826        first_row / layout.block_height,
827        first_column / layout.block_width,
828    );
829    for &(row, column) in cells {
830        layout.shard_of(row, column)?;
831        if (row / layout.block_height, column / layout.block_width) != block {
832            return Err(err("cells of one read must lie in one block"));
833        }
834    }
835    Ok(())
836}
837
838/// The cells' codes out of a decoded block. The chunk is decoded as the grid
839/// store's with the levels stacked as rows: the delta runs along time only,
840/// so a frame's stride is every level of the block. The layout holds the
841/// product to the decoded size limit.
842fn pick_cells<T: Copy>(layout: &ColumnLayout, cells: &[(u32, u32)], chunk: &[T]) -> Vec<T> {
843    let plane = layout.block_height as usize * layout.block_width as usize;
844    let mut out = Vec::with_capacity(layout.column_length() * cells.len());
845    for &(row, column) in cells {
846        let cell = (row % layout.block_height) as usize * layout.block_width as usize
847            + (column % layout.block_width) as usize;
848        out.extend(chunk.chunks_exact(plane).map(|codes| codes[cell]));
849    }
850    out
851}
852
853// -- reader --------------------------------------------------------------------
854
855/// A column store being read: the group and the shard indices handed over so
856/// far. The caller owns the requests and the chunks' bytes.
857#[derive(Debug, Clone)]
858pub struct ColumnReader {
859    group: ColumnGroup,
860    /// Verified indices by array id and shard.
861    indices: BTreeMap<(String, u32), Vec<Option<ShardIndexEntry>>>,
862}
863
864impl ColumnReader {
865    pub fn new(group: ColumnGroup) -> ColumnReader {
866        ColumnReader {
867            group,
868            indices: BTreeMap::new(),
869        }
870    }
871
872    pub fn group(&self) -> &ColumnGroup {
873        &self.group
874    }
875
876    pub fn has_shard_index(&self, id: &str, shard: u32) -> bool {
877        self.indices.contains_key(&(id.to_owned(), shard))
878    }
879
880    /// Verify one shard's index and hold it.
881    pub fn set_shard_index(
882        &mut self,
883        id: &str,
884        shard: u32,
885        bytes: &[u8],
886    ) -> Result<(), DecodeError> {
887        let layout = &self.group.array(id)?.layout;
888        if shard >= layout.shard_count {
889            return Err(err("shard is outside the array"));
890        }
891        let index = parse_column_index(layout, bytes)?;
892        self.indices.insert((id.to_owned(), shard), index);
893        Ok(())
894    }
895
896    /// [`chunk_range`] through the index held for the cell's shard; an error
897    /// until it has been handed over.
898    pub fn chunk_range(
899        &self,
900        id: &str,
901        row: u32,
902        column: u32,
903    ) -> Result<Option<ShardIndexEntry>, DecodeError> {
904        let layout = &self.group.array(id)?.layout;
905        let shard = layout.shard_of(row, column)?;
906        let index = self
907            .indices
908            .get(&(id.to_owned(), shard))
909            .ok_or_else(|| err("shard index is not resident yet"))?;
910        chunk_range(layout, index, row, column)
911    }
912
913    /// [`decode_column`], the payload held as [`ColumnReader::cells`] holds it.
914    pub fn column(
915        &self,
916        id: &str,
917        row: u32,
918        column: u32,
919        payload: &[u8],
920    ) -> Result<Vec<u8>, DecodeError> {
921        self.cells(id, &[(row, column)], payload)
922    }
923
924    /// [`decode_cells`], the payload held to what the shard's index says of
925    /// it: empty exactly for a block the shard never held, else the length
926    /// the index gives. Without that a failed or cut read would pass for
927    /// missing data.
928    pub fn cells(
929        &self,
930        id: &str,
931        cells: &[(u32, u32)],
932        payload: &[u8],
933    ) -> Result<Vec<u8>, DecodeError> {
934        let (layout, payload) = self.held_payload(id, cells, payload)?;
935        decode_cells(layout, cells, payload)
936    }
937
938    /// [`ColumnReader::column`] of an array of either type, the codes
939    /// widened ([`decode_column_u16`]).
940    pub fn column_u16(
941        &self,
942        id: &str,
943        row: u32,
944        column: u32,
945        payload: &[u8],
946    ) -> Result<Vec<u16>, DecodeError> {
947        self.cells_u16(id, &[(row, column)], payload)
948    }
949
950    /// [`ColumnReader::cells`] of an array of either type, the codes widened
951    /// ([`decode_cells_u16`]).
952    pub fn cells_u16(
953        &self,
954        id: &str,
955        cells: &[(u32, u32)],
956        payload: &[u8],
957    ) -> Result<Vec<u16>, DecodeError> {
958        let (layout, payload) = self.held_payload(id, cells, payload)?;
959        decode_cells_u16(layout, cells, payload)
960    }
961
962    /// The array's layout and the payload held to its index entry: `None`
963    /// for a block the shard never held.
964    fn held_payload<'a>(
965        &self,
966        id: &str,
967        cells: &[(u32, u32)],
968        payload: &'a [u8],
969    ) -> Result<(&ColumnLayout, Option<&'a [u8]>), DecodeError> {
970        let &(row, column) = cells.first().ok_or_else(|| err("no cell to read"))?;
971        let entry = self.chunk_range(id, row, column)?;
972        if payload.len() as u64 != entry.map_or(0, |entry| entry.length) {
973            return Err(err("chunk payload is not the length the shard index gives"));
974        }
975        Ok((&self.group.array(id)?.layout, entry.map(|_| payload)))
976    }
977}
978
979#[cfg(test)]
980mod tests {
981    use super::*;
982    use crate::zarr::crc32c;
983    use ruzstd::encoding::{compress_to_vec, CompressionLevel};
984
985    const FRAMES: usize = 3;
986    const HEIGHT: usize = 10;
987    const WIDTH: usize = 10;
988    const BLOCK: usize = 4;
989    const SHARD_HEIGHT: usize = 8;
990    const SHARD_WIDTH: usize = 12;
991    const FILL: u8 = 255;
992
993    fn variable(id: &str, level: Option<u32>, offset: f64, scale: f64) -> Value {
994        json!({
995            "numericId": 1, "id": id, "label": id, "unit": "K",
996            "quantization": {"type": "linear", "offset": offset, "scale": scale,
997                             "minimumCode": 0, "maximumCode": 254, "nodataCode": 255},
998            "parameter": {
999                "discipline": 0, "parameterCategory": 0, "parameterNumber": 0,
1000                "typeOfFirstFixedSurface": if level.is_some() { 100 } else { 101 },
1001                "scaleFactorOfFirstFixedSurface": level.map(|_| 0),
1002                "scaledValueOfFirstFixedSurface": level.map(|level| level * 100),
1003            }
1004        })
1005    }
1006
1007    fn array(
1008        id: &str,
1009        frames: usize,
1010        level: Option<(&str, usize)>,
1011        time: &str,
1012        delta: bool,
1013    ) -> Value {
1014        let over = |rows: usize, columns: usize| match level {
1015            Some((_, levels)) => json!([frames, levels, rows, columns]),
1016            None => json!([frames, rows, columns]),
1017        };
1018        let mut dimensions = vec![time];
1019        dimensions.extend(level.map(|(name, _)| name));
1020        dimensions.extend(["latitude", "longitude"]);
1021        let mut codecs = vec![
1022            json!({"name": "bytes"}),
1023            json!({"name": "zstd", "configuration": {"level": 6, "checksum": true}}),
1024        ];
1025        if delta {
1026            codecs.insert(
1027                0,
1028                json!({"name": "xue.delta", "configuration": {"axis": 0}}),
1029            );
1030        }
1031        json!({
1032            "zarr_format": 3, "node_type": "array", "data_type": "uint8",
1033            "shape": over(HEIGHT, WIDTH),
1034            "chunk_grid": {"name": "regular",
1035                           "configuration": {"chunk_shape": over(SHARD_HEIGHT, SHARD_WIDTH)}},
1036            "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}},
1037            "fill_value": FILL,
1038            "codecs": [{"name": "sharding_indexed", "configuration": {
1039                "chunk_shape": over(BLOCK, BLOCK), "codecs": codecs,
1040                "index_codecs": [{"name": "bytes", "configuration": {"endian": "little"}},
1041                                 {"name": "crc32c"}],
1042                "index_location": "start"}}],
1043            "attributes": {"_FillValue": FILL, "xue_columns": {"array": id}},
1044            "dimension_names": dimensions,
1045        })
1046    }
1047
1048    /// Two levelled arrays on different levels, `tmp` with a codebook per
1049    /// level and `rh` RAW, and a one-frame surface array.
1050    fn group_document(edit: impl FnOnce(&mut Value)) -> String {
1051        let mut document = json!({
1052            "zarr_format": 3, "node_type": "group",
1053            "attributes": {"xue_columns": {
1054                "version": 1, "model": "GFS", "product": "pgrb2.0p25",
1055                "runTime": "2026-11-24T00:00:00Z", "profile": "balanced",
1056                "time": {"unitSeconds": 3600, "firstFrameOffset": 0, "frameCount": FRAMES,
1057                         "frameOffsets": [0, 1, 3]},
1058                "grid": {"width": WIDTH, "height": HEIGHT, "firstLongitude": 0.0,
1059                         "firstLatitude": 10.0, "longitudeStep": 0.25, "latitudeStep": -0.25,
1060                         "wrapLongitude": false},
1061                "arrays": [
1062                    {"id": "tmp", "levels": [1000, 850], "members": [
1063                        {"bundle": "tmp1000", "variable": variable("tmp1000", Some(1000), -50.0, 0.5)},
1064                        {"bundle": "tmp850", "variable": variable("tmp850", Some(850), -80.0, 1.0)}]},
1065                    {"id": "rh", "levels": [1000], "members": [
1066                        {"bundle": "rh1000", "variable": variable("rh1000", Some(1000), 0.0, 1.0)}]},
1067                    {"id": "orog",
1068                     "time": {"unitSeconds": 3600, "firstFrameOffset": 0, "frameCount": 1, "frameStep": 1},
1069                     "members": [{"bundle": "orog", "variable": variable("orog", None, -500.0, 30.0)}]}
1070                ]
1071            }},
1072            "consolidated_metadata": {"kind": "inline", "must_understand": false, "metadata": {
1073                "tmp": array("tmp", FRAMES, Some(("level", 2)), "time", true),
1074                "rh": array("rh", FRAMES, Some(("level_rh", 1)), "time", false),
1075                "orog": array("orog", 1, None, "time_orog", false),
1076            }}
1077        });
1078        edit(&mut document);
1079        document.to_string()
1080    }
1081
1082    fn code(frame: usize, level: usize, row: usize, column: usize) -> u8 {
1083        if row == 5 && column == 6 {
1084            return FILL;
1085        }
1086        ((frame * 91 + level * 37 + row * 13 + column * 5) % 255) as u8
1087    }
1088
1089    /// One shard of `layout` under [`code`], its blocks in row-major order
1090    /// after the index, `skip` the index position left out.
1091    fn shard(layout: &ColumnLayout, shard: usize, skip: Option<usize>) -> Vec<u8> {
1092        let (frames, levels) = (layout.frame_count as usize, layout.level_count as usize);
1093        let mut index = Vec::new();
1094        let mut data = Vec::new();
1095        for position in 0..layout.chunks_per_shard as usize {
1096            let across = SHARD_WIDTH / BLOCK;
1097            let row = shard * SHARD_HEIGHT + position / across * BLOCK;
1098            let column = position % across * BLOCK;
1099            if row >= HEIGHT || column >= WIDTH || skip == Some(position) {
1100                index.extend_from_slice(&[0xff; 16]);
1101                continue;
1102            }
1103            let mut chunk = Vec::new();
1104            for frame in 0..frames {
1105                for level in 0..levels {
1106                    for cell in 0..BLOCK * BLOCK {
1107                        let (r, c) = (row + cell / BLOCK, column + cell % BLOCK);
1108                        chunk.push(if r < HEIGHT && c < WIDTH {
1109                            code(frame, level, r, c)
1110                        } else {
1111                            FILL
1112                        });
1113                    }
1114                }
1115            }
1116            if layout.delta {
1117                let stride = levels * BLOCK * BLOCK;
1118                for at in (stride..chunk.len()).rev() {
1119                    chunk[at] = chunk[at].wrapping_sub(chunk[at - stride]);
1120                }
1121            }
1122            let payload = compress_to_vec(chunk.as_slice(), CompressionLevel::Fastest);
1123            index.extend_from_slice(&((layout.index_length() + data.len()) as u64).to_le_bytes());
1124            index.extend_from_slice(&(payload.len() as u64).to_le_bytes());
1125            data.extend_from_slice(&payload);
1126        }
1127        let checksum = crc32c(&index);
1128        index.extend_from_slice(&checksum.to_le_bytes());
1129        [index, data].concat()
1130    }
1131
1132    fn payload(shard: &[u8], entry: Option<ShardIndexEntry>) -> &[u8] {
1133        entry.map_or(&[], |entry| {
1134            &shard[entry.offset as usize..][..entry.length as usize]
1135        })
1136    }
1137
1138    #[test]
1139    fn reads_the_block_and_every_layout() {
1140        let text = group_document(|_| {});
1141        assert_eq!(zarr::store_kind(&text).unwrap(), StoreKind::Column);
1142        let group = ColumnGroup::parse(&text).unwrap();
1143        assert_eq!(group.model, "GFS");
1144        assert_eq!(group.profile, "balanced");
1145        assert_eq!(group.run_time_seconds, 1_795_478_400);
1146        assert_eq!(group.offsets, [0, 1, 3]);
1147        let ids: Vec<&str> = group.arrays.iter().map(|array| array.id.as_str()).collect();
1148        assert_eq!(ids, ["tmp", "rh", "orog"]);
1149
1150        let tmp = group.array("tmp").unwrap();
1151        assert_eq!(tmp.levels.as_deref(), Some(&[1000, 850][..]));
1152        assert_eq!(tmp.members[1].bundle, "tmp850");
1153        assert_eq!(tmp.members[1].variable.id, "tmp850");
1154        assert!(tmp.layout.delta);
1155        assert_eq!(tmp.layout.shard_count, 2);
1156        assert_eq!(tmp.layout.chunks_per_shard, 6);
1157        assert_eq!(tmp.layout.index_length(), 100);
1158        assert_eq!(tmp.layout.shard_index_range(500).unwrap(), (0, 100));
1159        assert!(tmp.layout.shard_index_range(99).is_err());
1160        assert_eq!(tmp.shard_path(1), "tmp/c/0/0/1/0");
1161        assert_eq!(tmp.layout.shard_of(7, 9).unwrap(), 0);
1162        assert_eq!(tmp.layout.shard_of(8, 0).unwrap(), 1);
1163        assert_eq!(tmp.layout.position(8, 0).unwrap(), 0);
1164        assert_eq!(tmp.layout.position(7, 9).unwrap(), 5);
1165        assert!(tmp.layout.shard_of(10, 0).is_err());
1166        assert!(tmp.layout.position(0, 10).is_err());
1167
1168        assert!(!group.array("rh").unwrap().layout.delta);
1169        let orog = group.array("orog").unwrap();
1170        assert_eq!(orog.offsets, [0]);
1171        assert_eq!(orog.layout.level_count, 1);
1172        assert_eq!(orog.shard_path(1), "orog/c/0/1/0");
1173        assert!(group.array("time").is_err());
1174
1175        let block: Value = serde_json::from_str(&group.block_json).unwrap();
1176        let whole: Value = serde_json::from_str(&text).unwrap();
1177        assert_eq!(block, whole["attributes"]["xue_columns"]);
1178    }
1179
1180    #[test]
1181    fn a_column_is_one_chunk() {
1182        for (id, skip) in [("tmp", None), ("rh", Some(1)), ("orog", None)] {
1183            let group = ColumnGroup::parse(&group_document(|_| {})).unwrap();
1184            let layout = group.array(id).unwrap().layout;
1185            let shards = [shard(&layout, 0, skip), shard(&layout, 1, None)];
1186            let mut reader = ColumnReader::new(group);
1187            assert!(reader.chunk_range(id, 0, 0).is_err(), "no index yet");
1188            for (number, bytes) in shards.iter().enumerate() {
1189                let index = &bytes[..layout.index_length()];
1190                reader.set_shard_index(id, number as u32, index).unwrap();
1191                assert!(reader.has_shard_index(id, number as u32));
1192            }
1193            assert!(!reader.has_shard_index(id, 2));
1194            for row in 0..HEIGHT {
1195                for column in 0..WIDTH {
1196                    let (r, c) = (row as u32, column as u32);
1197                    let entry = reader.chunk_range(id, r, c).unwrap();
1198                    let written = skip.is_none() || row >= 4 || !(4..8).contains(&column);
1199                    assert_eq!(entry.is_some(), written, "{id} {row} {column}");
1200                    let bytes = payload(&shards[row / SHARD_HEIGHT], entry);
1201                    let codes = reader.column(id, r, c, bytes).unwrap();
1202                    let want: Vec<u8> = (0..layout.frame_count as usize)
1203                        .flat_map(|frame| {
1204                            (0..layout.level_count as usize).map(move |level| (frame, level))
1205                        })
1206                        .map(|(frame, level)| {
1207                            if written {
1208                                code(frame, level, row, column)
1209                            } else {
1210                                FILL
1211                            }
1212                        })
1213                        .collect();
1214                    assert_eq!(codes, want, "{id} {row} {column}");
1215                }
1216            }
1217        }
1218    }
1219
1220    #[test]
1221    fn the_cells_of_a_block_are_one_chunk() {
1222        for (id, skip) in [("tmp", None), ("rh", Some(1)), ("orog", None)] {
1223            let group = ColumnGroup::parse(&group_document(|_| {})).unwrap();
1224            let layout = group.array(id).unwrap().layout;
1225            let shards = [shard(&layout, 0, skip), shard(&layout, 1, None)];
1226            let mut reader = ColumnReader::new(group);
1227            for (number, bytes) in shards.iter().enumerate() {
1228                let index = &bytes[..layout.index_length()];
1229                reader.set_shard_index(id, number as u32, index).unwrap();
1230            }
1231            // Out of order, with a repeat; in a block the shard may lack, and
1232            // in one the grid's edge cuts.
1233            for cells in [
1234                vec![(3, 1), (0, 0), (2, 3), (3, 1)],
1235                vec![(1, 7), (0, 4)],
1236                vec![(9, 9), (8, 8)],
1237            ] {
1238                let (row, column) = cells[0];
1239                let entry = reader.chunk_range(id, row, column).unwrap();
1240                let bytes = payload(&shards[row as usize / SHARD_HEIGHT], entry);
1241                let want: Vec<u8> = cells
1242                    .iter()
1243                    .flat_map(|&(row, column)| reader.column(id, row, column, bytes).unwrap())
1244                    .collect();
1245                assert_eq!(want.len(), cells.len() * layout.column_length());
1246                assert_eq!(reader.cells(id, &cells, bytes).unwrap(), want, "{id}");
1247            }
1248        }
1249    }
1250
1251    #[test]
1252    fn cells_are_held_to_one_block_and_one_payload() {
1253        let group = ColumnGroup::parse(&group_document(|_| {})).unwrap();
1254        let layout = group.array("tmp").unwrap().layout;
1255        let bytes = shard(&layout, 0, Some(1));
1256        let mut reader = ColumnReader::new(group);
1257        assert!(reader.cells("tmp", &[(0, 0)], &[]).is_err(), "no index yet");
1258        reader
1259            .set_shard_index("tmp", 0, &bytes[..layout.index_length()])
1260            .unwrap();
1261        let chunk = payload(&bytes, reader.chunk_range("tmp", 0, 0).unwrap());
1262        assert!(reader.cells("tmp", &[(0, 0), (3, 3)], chunk).is_ok());
1263        assert!(reader.cells("tmp", &[], chunk).is_err(), "no cell");
1264        for other in [(4, 0), (0, 4), (4, 4)] {
1265            assert!(reader.cells("tmp", &[(0, 0), other], chunk).is_err());
1266        }
1267        for outside in [(10, 0), (0, 10)] {
1268            assert!(reader.cells("tmp", &[(0, 0), outside], chunk).is_err());
1269        }
1270        assert!(reader.cells("tmp", &[(0, 0), (3, 3)], &[]).is_err());
1271        assert!(reader.cells("tmp", &[(0, 0)], &chunk[1..]).is_err());
1272        // A block never written is the fill, cell by cell, and takes no bytes.
1273        assert!(reader.cells("tmp", &[(0, 4), (1, 5)], chunk).is_err());
1274        assert_eq!(
1275            reader.cells("tmp", &[(0, 4), (1, 5)], &[]).unwrap(),
1276            [FILL; 12]
1277        );
1278        // One block that is fill does not excuse another's cell.
1279        assert!(decode_cells(&layout, &[(0, 4), (0, 0)], None).is_err());
1280        assert!(decode_cells(&layout, &[], None).is_err());
1281        // No more cells than the block has, whatever they are.
1282        let many = vec![(0, 0); BLOCK * BLOCK];
1283        assert!(reader.cells("tmp", &many, chunk).is_ok());
1284        let more = vec![(0, 0); BLOCK * BLOCK + 1];
1285        let refused = reader.cells("tmp", &more, chunk).unwrap_err();
1286        assert!(refused
1287            .to_string()
1288            .contains("more cells than the block holds"));
1289    }
1290
1291    const WIDE_FILL: u16 = 65_535;
1292
1293    /// [`group_document`] with a fourth array, `tmp2m`, a surface array of a
1294    /// series store's sixteen-bit codes under its series codebook.
1295    fn wide_document(edit: impl FnOnce(&mut Value)) -> String {
1296        let text = group_document(|d| {
1297            let mut variable = variable("tmp2m", None, -90.0, 0.1);
1298            variable["quantization"]["maximumCode"] = json!(1500);
1299            variable["quantization"]["nodataCode"] = json!(WIDE_FILL);
1300            d["attributes"]["xue_columns"]["arrays"]
1301                .as_array_mut()
1302                .unwrap()
1303                .push(
1304                    json!({"id": "tmp2m", "members": [{"bundle": "tmp2m", "variable": variable}]}),
1305                );
1306            let mut document = array("tmp2m", FRAMES, None, "time", true);
1307            document["data_type"] = json!("uint16");
1308            document["fill_value"] = json!(WIDE_FILL);
1309            document["attributes"]["_FillValue"] = json!(WIDE_FILL);
1310            document["codecs"][0]["configuration"]["codecs"][1] =
1311                json!({"name": "bytes", "configuration": {"endian": "little"}});
1312            d["consolidated_metadata"]["metadata"]["tmp2m"] = document;
1313            edit(d);
1314        });
1315        text
1316    }
1317
1318    /// Past a byte, and falling as often as rising along the axis, so the
1319    /// delta wraps modulo 65536.
1320    fn wide_code(frame: usize, row: usize, column: usize) -> u16 {
1321        if row == 5 && column == 6 {
1322            return WIDE_FILL;
1323        }
1324        (1500 - (frame * 611 + row * 37 + column * 11) % 1200) as u16
1325    }
1326
1327    /// [`shard`] of the sixteen-bit array under [`wide_code`]: little-endian
1328    /// codes, the delta modulo 65536.
1329    fn wide_shard(layout: &ColumnLayout, shard: usize) -> Vec<u8> {
1330        let mut index = Vec::new();
1331        let mut data = Vec::new();
1332        let across = SHARD_WIDTH / BLOCK;
1333        for position in 0..layout.chunks_per_shard as usize {
1334            let row = shard * SHARD_HEIGHT + position / across * BLOCK;
1335            let column = position % across * BLOCK;
1336            if row >= HEIGHT || column >= WIDTH {
1337                index.extend_from_slice(&[0xff; 16]);
1338                continue;
1339            }
1340            let mut chunk: Vec<u16> = Vec::new();
1341            for frame in 0..layout.frame_count as usize {
1342                for cell in 0..BLOCK * BLOCK {
1343                    let (r, c) = (row + cell / BLOCK, column + cell % BLOCK);
1344                    chunk.push(if r < HEIGHT && c < WIDTH {
1345                        wide_code(frame, r, c)
1346                    } else {
1347                        WIDE_FILL
1348                    });
1349                }
1350            }
1351            let stride = BLOCK * BLOCK;
1352            for at in (stride..chunk.len()).rev() {
1353                chunk[at] = chunk[at].wrapping_sub(chunk[at - stride]);
1354            }
1355            let bytes: Vec<u8> = chunk.iter().flat_map(|code| code.to_le_bytes()).collect();
1356            let payload = compress_to_vec(bytes.as_slice(), CompressionLevel::Fastest);
1357            index.extend_from_slice(&((layout.index_length() + data.len()) as u64).to_le_bytes());
1358            index.extend_from_slice(&(payload.len() as u64).to_le_bytes());
1359            data.extend_from_slice(&payload);
1360        }
1361        let checksum = crc32c(&index);
1362        index.extend_from_slice(&checksum.to_le_bytes());
1363        [index, data].concat()
1364    }
1365
1366    #[test]
1367    fn a_surface_array_of_sixteen_bit_codes() {
1368        let group = ColumnGroup::parse(&wide_document(|_| {})).unwrap();
1369        let wide = group.array("tmp2m").unwrap();
1370        let layout = wide.layout;
1371        assert_eq!(
1372            (layout.data_type, layout.fill_value),
1373            (DataType::U16, WIDE_FILL)
1374        );
1375        assert!(layout.delta);
1376        assert_eq!(group.array("tmp").unwrap().layout.data_type, DataType::U8);
1377        let shards = [wide_shard(&layout, 0), wide_shard(&layout, 1)];
1378        let mut reader = ColumnReader::new(group.clone());
1379        for (number, bytes) in shards.iter().enumerate() {
1380            reader
1381                .set_shard_index("tmp2m", number as u32, &bytes[..layout.index_length()])
1382                .unwrap();
1383        }
1384        for row in 0..HEIGHT {
1385            for column in 0..WIDTH {
1386                let (r, c) = (row as u32, column as u32);
1387                let entry = reader.chunk_range("tmp2m", r, c).unwrap();
1388                let bytes = payload(&shards[row / SHARD_HEIGHT], entry);
1389                let want: Vec<u16> = (0..FRAMES)
1390                    .map(|frame| wide_code(frame, row, column))
1391                    .collect();
1392                assert_eq!(
1393                    reader.column_u16("tmp2m", r, c, bytes).unwrap(),
1394                    want,
1395                    "{row} {column}"
1396                );
1397                assert!(
1398                    reader.column("tmp2m", r, c, bytes).is_err(),
1399                    "a byte read of sixteen-bit codes"
1400                );
1401            }
1402        }
1403        let cells = [(1, 1), (0, 0), (3, 2), (1, 1)];
1404        let bytes = payload(&shards[0], reader.chunk_range("tmp2m", 0, 0).unwrap());
1405        let want: Vec<u16> = cells
1406            .iter()
1407            .flat_map(|&(row, column)| {
1408                (0..FRAMES).map(move |frame| wide_code(frame, row as usize, column as usize))
1409            })
1410            .collect();
1411        assert_eq!(reader.cells_u16("tmp2m", &cells, bytes).unwrap(), want);
1412        assert!(reader.cells("tmp2m", &cells, bytes).is_err());
1413        assert_eq!(
1414            decode_cells_u16(&layout, &[(0, 4), (1, 5)], None).unwrap(),
1415            [WIDE_FILL; 6]
1416        );
1417        // The member's codebook dequantizes the codes.
1418        let values = wide.values(&[0u16, 1500, WIDE_FILL]).unwrap();
1419        assert_eq!(values[0], -90.0);
1420        assert!((values[1] - 60.0).abs() < 1e-9);
1421        assert!(values[2].is_nan());
1422    }
1423
1424    #[test]
1425    fn a_byte_array_reads_widened_too() {
1426        let group = ColumnGroup::parse(&wide_document(|_| {})).unwrap();
1427        let layout = group.array("tmp").unwrap().layout;
1428        let bytes = shard(&layout, 0, None);
1429        let mut reader = ColumnReader::new(group);
1430        reader
1431            .set_shard_index("tmp", 0, &bytes[..layout.index_length()])
1432            .unwrap();
1433        for (row, column) in [(0, 0), (5, 6), (7, 9)] {
1434            let chunk = payload(&bytes, reader.chunk_range("tmp", row, column).unwrap());
1435            let narrow = reader.column("tmp", row, column, chunk).unwrap();
1436            let wide = reader.column_u16("tmp", row, column, chunk).unwrap();
1437            assert_eq!(
1438                wide,
1439                narrow
1440                    .iter()
1441                    .map(|&code| u16::from(code))
1442                    .collect::<Vec<u16>>()
1443            );
1444        }
1445        assert_eq!(
1446            decode_cells_u16(&layout, &[(0, 4)], None).unwrap(),
1447            [u16::from(FILL); 6]
1448        );
1449    }
1450
1451    #[test]
1452    fn rejects_malformed_sixteen_bit_arrays() {
1453        fn wide(d: &mut Value) -> &mut Value {
1454            &mut d["consolidated_metadata"]["metadata"]["tmp2m"]
1455        }
1456        fn bytes_codec(d: &mut Value) -> &mut Value {
1457            &mut wide(d)["codecs"][0]["configuration"]["codecs"][1]
1458        }
1459        fn codebook(d: &mut Value, array: usize) -> &mut Value {
1460            &mut d["attributes"]["xue_columns"]["arrays"][array]["members"][0]["variable"]
1461                ["quantization"]
1462        }
1463        let edits: Vec<fn(&mut Value)> = vec![
1464            |d| bytes_codec(d)["configuration"]["endian"] = json!("big"),
1465            |d| {
1466                bytes_codec(d)
1467                    .as_object_mut()
1468                    .unwrap()
1469                    .remove("configuration");
1470            },
1471            |d| wide(d)["fill_value"] = json!(255),
1472            |d| wide(d)["fill_value"] = json!(70_000),
1473            |d| wide(d)["data_type"] = json!("uint8"),
1474            |d| wide(d)["data_type"] = json!("uint32"),
1475            // A byte codebook in a sixteen-bit array.
1476            |d| {
1477                codebook(d, 3)["nodataCode"] = json!(255);
1478                codebook(d, 3)["maximumCode"] = json!(254);
1479                wide(d)["fill_value"] = json!(255);
1480            },
1481            |d| codebook(d, 3)["maximumCode"] = json!(70_000),
1482            // A code past a byte in a byte array.
1483            |d| codebook(d, 2)["maximumCode"] = json!(300),
1484            // A levelled array holds bytes only.
1485            |d| {
1486                let tmp = &mut d["consolidated_metadata"]["metadata"]["tmp"];
1487                tmp["data_type"] = json!("uint16");
1488                tmp["codecs"][0]["configuration"]["codecs"][1] =
1489                    json!({"name": "bytes", "configuration": {"endian": "little"}});
1490            },
1491        ];
1492        assert!(ColumnGroup::parse(&wide_document(|_| {})).is_ok());
1493        for (position, edit) in edits.into_iter().enumerate() {
1494            assert!(
1495                ColumnGroup::parse(&wide_document(edit)).is_err(),
1496                "edit {position} was accepted"
1497            );
1498        }
1499    }
1500
1501    #[test]
1502    fn each_level_reads_through_its_own_codebook() {
1503        let group = ColumnGroup::parse(&group_document(|_| {})).unwrap();
1504        let tmp = group.array("tmp").unwrap();
1505        let values = tmp.values(&[100u8, 100, 0, 254, 255, 1]).unwrap();
1506        assert_eq!(&values[..4], [0.0, 20.0, -50.0, 174.0]);
1507        assert!(values[4].is_nan());
1508        assert_eq!(values[5], -79.0);
1509        assert!(tmp.values(&[0u8; 5]).is_err());
1510    }
1511
1512    #[test]
1513    fn a_payload_is_held_to_the_index() {
1514        let group = ColumnGroup::parse(&group_document(|_| {})).unwrap();
1515        let layout = group.array("tmp").unwrap().layout;
1516        let bytes = shard(&layout, 0, Some(1));
1517        let index = bytes[..layout.index_length()].to_vec();
1518        let mut reader = ColumnReader::new(group);
1519        assert!(reader.column("tmp", 0, 0, &[]).is_err(), "no index yet");
1520
1521        assert!(reader.set_shard_index("tmp", 2, &index).is_err());
1522        assert!(reader.set_shard_index("hgt", 0, &index).is_err());
1523        assert!(reader.set_shard_index("tmp", 0, &index[1..]).is_err());
1524        let mut flipped = index.clone();
1525        flipped[3] ^= 1;
1526        assert!(reader.set_shard_index("tmp", 0, &flipped).is_err());
1527        // A pair whose chunk starts inside the index, its checksum right.
1528        let mut inside = index.clone();
1529        inside[..8].copy_from_slice(&99u64.to_le_bytes());
1530        let end = inside.len() - 4;
1531        let checksum = crc32c(&inside[..end]);
1532        inside[end..].copy_from_slice(&checksum.to_le_bytes());
1533        assert!(reader.set_shard_index("tmp", 0, &inside).is_err());
1534        assert!(!reader.has_shard_index("tmp", 0));
1535        reader.set_shard_index("tmp", 0, &index).unwrap();
1536
1537        let chunk = payload(&bytes, reader.chunk_range("tmp", 0, 0).unwrap()).to_vec();
1538        assert!(reader.column("tmp", 0, 0, &chunk).is_ok());
1539        assert!(
1540            reader.column("tmp", 0, 0, &[]).is_err(),
1541            "a written chunk is not empty"
1542        );
1543        assert!(reader.column("tmp", 0, 0, &chunk[1..]).is_err());
1544        let mut damaged = chunk.clone();
1545        *damaged.last_mut().unwrap() ^= 1;
1546        assert!(reader.column("tmp", 0, 0, &damaged).is_err());
1547        assert!(
1548            reader.column("tmp", 0, 4, &chunk).is_err(),
1549            "a hole has no payload"
1550        );
1551        assert_eq!(reader.column("tmp", 0, 4, &[]).unwrap(), [FILL; 6]);
1552        assert!(reader.column("tmp", 10, 0, &[]).is_err());
1553        assert!(reader.column("tmp", 0, 10, &[]).is_err());
1554        // A whole frame of the wrong shape.
1555        let short = compress_to_vec(&[0u8; 95][..], CompressionLevel::Fastest);
1556        assert!(decode_column(&layout, 0, 0, Some(&short)).is_err());
1557    }
1558
1559    #[test]
1560    fn an_index_at_the_end_reads_too() {
1561        let group = ColumnGroup::parse(&group_document(|d| {
1562            d["consolidated_metadata"]["metadata"]["tmp"]["codecs"][0]["configuration"]
1563                ["index_location"] = json!("end");
1564        }))
1565        .unwrap();
1566        let layout = group.array("tmp").unwrap().layout;
1567        assert_eq!(layout.index_location, IndexLocation::End);
1568        assert_eq!(layout.shard_index_range(500).unwrap(), (400, 500));
1569        let mut index = Vec::new();
1570        for position in 0..6u64 {
1571            index.extend_from_slice(&(position * 7).to_le_bytes());
1572            index.extend_from_slice(&7u64.to_le_bytes());
1573        }
1574        let checksum = crc32c(&index);
1575        index.extend_from_slice(&checksum.to_le_bytes());
1576        let mut reader = ColumnReader::new(group);
1577        reader.set_shard_index("tmp", 0, &index).unwrap();
1578        let entry = reader.chunk_range("tmp", 0, 9).unwrap().unwrap();
1579        assert_eq!((entry.offset, entry.length), (14, 7));
1580    }
1581
1582    #[test]
1583    fn more_variables_than_a_bundle_numbers_still_read() {
1584        let levels: Vec<u32> = (1..=300).rev().collect();
1585        let text = group_document(|d| {
1586            let members: Vec<Value> = levels
1587                .iter()
1588                .map(|&level| {
1589                    let id = format!("tmp{level}");
1590                    json!({"bundle": id, "variable": variable(&id, Some(level), 0.0, 1.0)})
1591                })
1592                .collect();
1593            let block = &mut d["attributes"]["xue_columns"]["arrays"][0];
1594            block["levels"] = json!(levels);
1595            block["members"] = json!(members);
1596            d["consolidated_metadata"]["metadata"]["tmp"] =
1597                array("tmp", FRAMES, Some(("level", 300)), "time", true);
1598        });
1599        let group = ColumnGroup::parse(&text).unwrap();
1600        assert_eq!(group.arrays[0].members[299].variable.id, "tmp1");
1601        assert_eq!(group.arrays[1].members[0].variable.id, "rh1000");
1602    }
1603
1604    #[test]
1605    fn tells_the_branches_apart() {
1606        for other in ["xue", "xue_bundles", "xue_polar", "xue_network"] {
1607            let both = group_document(|d| d["attributes"][other] = json!({"version": 1}));
1608            assert!(zarr::store_kind(&both).is_err(), "{other}");
1609            assert!(ColumnGroup::parse(&both).is_err(), "{other}");
1610            let alone = group_document(|d| d["attributes"] = json!({other: {"version": 1}}));
1611            assert!(ColumnGroup::parse(&alone).is_err(), "{other}");
1612        }
1613        for profile in [1, 2] {
1614            let both = group_document(|d| d["attributes"]["xue_profile"] = json!(profile));
1615            assert!(ColumnGroup::parse(&both).is_err(), "xue_profile {profile}");
1616        }
1617        // The level is the writer's: a reader follows the chain whatever it is.
1618        for level in [1, 15] {
1619            let text = group_document(|d| {
1620                let tmp = &mut d["consolidated_metadata"]["metadata"]["tmp"];
1621                tmp["codecs"][0]["configuration"]["codecs"][2]["configuration"]["level"] =
1622                    json!(level);
1623            });
1624            assert!(ColumnGroup::parse(&text).is_ok(), "level {level}");
1625        }
1626        let text = group_document(|_| {});
1627        assert!(zarr::parse_group_metadata(&text).is_err());
1628        assert!(zarr::parse_group_metadata_for(&text, "tmp1000").is_err());
1629        assert!(crate::network::parse_network_group(&text).is_err());
1630    }
1631
1632    #[test]
1633    fn rejects_malformed_blocks() {
1634        fn block(d: &mut Value) -> &mut Value {
1635            &mut d["attributes"]["xue_columns"]
1636        }
1637        fn remove(value: &mut Value, key: &str) {
1638            value.as_object_mut().unwrap().remove(key);
1639        }
1640        let edits: Vec<fn(&mut Value)> = vec![
1641            |d| block(d)["version"] = json!(2),
1642            |d| remove(block(d), "version"),
1643            |d| d["attributes"]["xue_columns"] = json!([]),
1644            |d| block(d)["model"] = json!(""),
1645            |d| remove(block(d), "product"),
1646            |d| remove(block(d), "profile"),
1647            |d| block(d)["runTime"] = json!("yesterday"),
1648            |d| block(d)["runTime"] = json!("2026-11-24T00:00:00.5Z"),
1649            |d| remove(block(d), "time"),
1650            |d| block(d)["time"]["frameOffsets"] = json!([0, 1, 2]),
1651            |d| block(d)["time"]["frameCount"] = json!(0),
1652            |d| block(d)["time"]["hours"] = json!([0]),
1653            |d| remove(block(d), "grid"),
1654            |d| remove(&mut block(d)["grid"], "longitudeStep"),
1655            |d| remove(&mut block(d)["grid"], "wrapLongitude"),
1656            |d| block(d)["grid"]["width"] = json!(1u64 << 40),
1657            |d| block(d)["grid"]["width"] = json!(11),
1658            |d| block(d)["grid"]["projection"] = json!({"kind": "lambertConformal"}),
1659            |d| block(d)["grid"]["gaussian"] = json!({"n": 2, "firstRow": 0, "rowStride": 1}),
1660            |d| block(d)["arrays"] = json!([]),
1661            |d| block(d)["arrays"][0]["id"] = json!("Tmp"),
1662            |d| block(d)["arrays"][0]["id"] = json!("level"),
1663            |d| block(d)["arrays"][0]["id"] = json!("tmp_2"),
1664            |d| block(d)["arrays"][0]["id"] = json!("hgt"),
1665            |d| block(d)["arrays"][1]["id"] = json!("tmp"),
1666            |d| block(d)["arrays"][0]["levels"] = json!([850, 1000]),
1667            |d| block(d)["arrays"][0]["levels"] = json!([1000, 1000]),
1668            |d| block(d)["arrays"][0]["levels"] = json!([1000, 0]),
1669            |d| block(d)["arrays"][0]["levels"] = json!([1000.5, 850]),
1670            |d| block(d)["arrays"][0]["levels"] = json!([1u64 << 32, 850]),
1671            |d| block(d)["arrays"][0]["levels"] = json!([]),
1672            |d| block(d)["arrays"][0]["levels"] = json!([1000]),
1673            |d| block(d)["arrays"][0]["levels"] = json!(null),
1674            |d| remove(&mut block(d)["arrays"][0], "levels"),
1675            |d| block(d)["arrays"][2]["members"] = json!([]),
1676            |d| block(d)["arrays"][0]["members"][0]["bundle"] = json!(""),
1677            |d| block(d)["arrays"][0]["members"][0]["bundle"] = json!("Tmp1000"),
1678            |d| block(d)["arrays"][0]["members"][0]["bundle"] = json!("1000tmp"),
1679            |d| block(d)["arrays"][0]["members"][0]["bundle"] = json!("tmp/1000"),
1680            |d| block(d)["arrays"][0]["members"][0]["bundle"] = json!(1000),
1681            |d| remove(&mut block(d)["arrays"][0]["members"][0], "variable"),
1682            |d| block(d)["arrays"][0]["members"][0]["variable"] = json!(1),
1683            |d| {
1684                remove(
1685                    &mut block(d)["arrays"][0]["members"][0]["variable"],
1686                    "parameter",
1687                )
1688            },
1689            |d| {
1690                remove(
1691                    &mut block(d)["arrays"][0]["members"][0]["variable"],
1692                    "quantization",
1693                )
1694            },
1695            |d| block(d)["arrays"][0]["members"][1]["variable"]["id"] = json!("tmp1000"),
1696            |d| block(d)["arrays"][1]["members"][0]["variable"]["id"] = json!("tmp1000"),
1697            // One member's codebook reserves another code than the array's fill.
1698            |d| {
1699                block(d)["arrays"][0]["members"][1]["variable"]["quantization"]["nodataCode"] =
1700                    json!(254)
1701            },
1702            |d| block(d)["arrays"][2]["members"][0]["variable"]["id"] = json!("orography"),
1703            // Its own axis, but the store's.
1704            |d| {
1705                block(d)["arrays"][1]["time"] = block(d)["time"].clone();
1706                d["consolidated_metadata"]["metadata"]["rh"]["dimension_names"][0] =
1707                    json!("time_rh");
1708            },
1709            |d| remove(d, "consolidated_metadata"),
1710            |d| d["consolidated_metadata"]["kind"] = json!("other"),
1711            |d| d["consolidated_metadata"]["metadata"] = json!([]),
1712            |d| remove(&mut d["consolidated_metadata"]["metadata"], "rh"),
1713            |d| d["node_type"] = json!("array"),
1714        ];
1715        for (position, edit) in edits.into_iter().enumerate() {
1716            assert!(
1717                ColumnGroup::parse(&group_document(edit)).is_err(),
1718                "edit {position} was accepted"
1719            );
1720        }
1721        assert!(ColumnGroup::parse("{").is_err());
1722        // Nothing left on the store's axis.
1723        let own = group_document(|d| {
1724            let arrays = block(d)["arrays"].as_array_mut().unwrap();
1725            arrays.drain(..2);
1726        });
1727        assert!(ColumnGroup::parse(&own).is_err());
1728    }
1729
1730    #[test]
1731    fn rejects_malformed_arrays() {
1732        fn shard_shape(a: &mut Value) -> &mut Value {
1733            &mut a["chunk_grid"]["configuration"]["chunk_shape"]
1734        }
1735        fn sharding(a: &mut Value) -> &mut Value {
1736            &mut a["codecs"][0]["configuration"]
1737        }
1738        let edits: Vec<fn(&mut Value)> = vec![
1739            |a| a["node_type"] = json!("group"),
1740            |a| a["data_type"] = json!("int16"),
1741            |a| a["shape"] = json!([3, 2, 10]),
1742            |a| a["shape"] = json!([4, 2, 10, 10]),
1743            |a| a["shape"] = json!([3, 1, 10, 10]),
1744            |a| a["shape"] = json!([3, 2, 10, 9]),
1745            |a| a["dimension_names"] = json!(["time", "level", "longitude", "latitude"]),
1746            |a| a["dimension_names"] = json!(["time", "level_tmp", "latitude", "longitude"]),
1747            |a| a["dimension_names"] = json!(["time", "level", "latitude"]),
1748            |a| a["dimension_names"] = json!(null),
1749            |a| a["attributes"] = json!({}),
1750            |a| a["attributes"]["xue_columns"]["array"] = json!("rh"),
1751            |a| a["fill_value"] = json!(0),
1752            |a| a["chunk_key_encoding"]["name"] = json!("v2"),
1753            |a| *shard_shape(a) = json!([6, 2, 8, 12]),
1754            |a| *shard_shape(a) = json!([3, 4, 8, 12]),
1755            |a| *shard_shape(a) = json!([3, 2, 9, 12]),
1756            |a| *shard_shape(a) = json!([3, 2, 8, 10]),
1757            |a| *shard_shape(a) = json!([3, 2, 8, 8]),
1758            |a| *shard_shape(a) = json!([3, 2, 1u64 << 60, 1u64 << 60]),
1759            |a| *shard_shape(a) = json!([3, 2, 4u64 << 32, 12]),
1760            |a| sharding(a)["chunk_shape"] = json!([1, 2, 4, 4]),
1761            |a| sharding(a)["chunk_shape"] = json!([3, 1, 4, 4]),
1762            |a| sharding(a)["chunk_shape"] = json!([3, 2, 0, 4]),
1763            |a| {
1764                sharding(a)["chunk_shape"] = json!([3, 2, 1u64 << 24, 12]);
1765                *shard_shape(a) = json!([3, 2, 1u64 << 24, 12]);
1766            },
1767            |a| {
1768                sharding(a)["chunk_shape"] = json!([3, 2, 1u64 << 62, 1u64 << 62]);
1769                *shard_shape(a) = json!([3, 2, 1u64 << 62, 1u64 << 62]);
1770            },
1771            |a| sharding(a)["index_location"] = json!("middle"),
1772            |a| sharding(a)["index_codecs"] = json!([{"name": "bytes"}]),
1773            |a| sharding(a)["codecs"][0]["configuration"]["axis"] = json!(1),
1774            |a| sharding(a)["codecs"] = json!([{"name": "bytes"}, {"name": "gzip"}]),
1775            |a| a["codecs"] = json!([{"name": "bytes"}, {"name": "zstd"}]),
1776        ];
1777        for (position, edit) in edits.into_iter().enumerate() {
1778            let text = group_document(|d| edit(&mut d["consolidated_metadata"]["metadata"]["tmp"]));
1779            assert!(
1780                ColumnGroup::parse(&text).is_err(),
1781                "edit {position} was accepted"
1782            );
1783        }
1784        // A level list of its own is named for its array, and so is an axis.
1785        for (id, at, name) in [("rh", 1, "level"), ("orog", 0, "time")] {
1786            let text = group_document(|d| {
1787                d["consolidated_metadata"]["metadata"][id]["dimension_names"][at] = json!(name);
1788            });
1789            assert!(ColumnGroup::parse(&text).is_err(), "{id}");
1790        }
1791        // A block larger than the grid, and a shard wider than it, are legal.
1792        let wide = group_document(|d| {
1793            let tmp = &mut d["consolidated_metadata"]["metadata"]["tmp"];
1794            *shard_shape(tmp) = json!([3, 2, 16, 32]);
1795            sharding(tmp)["chunk_shape"] = json!([3, 2, 16, 16]);
1796        });
1797        let layout = ColumnGroup::parse(&wide).unwrap().arrays[0].layout;
1798        assert_eq!((layout.shard_count, layout.chunks_per_shard), (1, 2));
1799    }
1800}
1801
1802#[cfg(test)]
1803mod schema_tie_tests {
1804    //! The group and array fields this reader reads are the ones
1805    //! `docs/schemas/` names. The array's shape, codecs and fill value are
1806    //! `crate::zarr`'s to read, and tied there.
1807    use super::{COLUMN_ATTRIBUTE, GRID_NUMBERS, GRID_PROFILE_ATTRIBUTE};
1808    use crate::schematie::{assert_named, schema};
1809
1810    #[test]
1811    fn the_column_block_read_is_the_schemas() {
1812        assert_named("column-group", "", &["consolidated_metadata"]);
1813        assert_named(
1814            "store-group",
1815            "/$defs/ConsolidatedMetadata",
1816            &["kind", "metadata"],
1817        );
1818        assert_named(
1819            "column-group",
1820            "/properties/attributes",
1821            &[COLUMN_ATTRIBUTE, GRID_PROFILE_ATTRIBUTE],
1822        );
1823        assert_named(
1824            "column-group",
1825            "/$defs/Columns",
1826            &[
1827                "version", "model", "product", "runTime", "profile", "time", "grid", "arrays",
1828            ],
1829        );
1830        assert_named(
1831            "column-group",
1832            "/$defs/Array",
1833            &["id", "time", "levels", "members"],
1834        );
1835        assert_named("column-group", "/$defs/Member", &["bundle", "variable"]);
1836        assert_named("bundle-metadata", "/$defs/Grid", &GRID_NUMBERS);
1837        assert_named(
1838            "bundle-metadata",
1839            "/$defs/Grid",
1840            &["projection", "wrapLongitude"],
1841        );
1842        assert_named(
1843            "bundle-metadata",
1844            "/$defs/Variable",
1845            &["numericId", "id", "quantization"],
1846        );
1847        assert_named("store-array", "", &["dimension_names", "attributes"]);
1848        assert_named("store-array", "/$defs/Attributes", &[COLUMN_ATTRIBUTE]);
1849        assert_named("store-array", "/$defs/ColumnArrayBlock", &["array"]);
1850    }
1851
1852    /// The fields the block must carry are the ones the reader refuses a
1853    /// block without.
1854    #[test]
1855    fn the_version_and_the_required_fields_agree() {
1856        let schema = schema("column-group");
1857        let columns = &schema["$defs"]["Columns"];
1858        assert_eq!(
1859            columns["properties"]["version"]["const"],
1860            super::COLUMN_VERSION
1861        );
1862        for field in [
1863            "version", "model", "product", "runTime", "profile", "time", "grid", "arrays",
1864        ] {
1865            let required = columns["required"].as_array().unwrap();
1866            assert!(required.iter().any(|name| name == field), "{field}");
1867        }
1868    }
1869}