geolith-dataset-builder 0.4.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! `geolith dataset stage`: an engine build → the upload-ready tree of object
//! keys.
//!
//! Ported from the former `scripts/datasets/stage.ts`. Writes
//! `$DATA_ROOT/datasets/stage/<build-id>/` holding the public set only, the
//! keys the bucket receives under the key prefix (`storage.prefix`): the build's
//! files plus `numbers.parquet`, the boundary files of the release, the
//! pointer `current.json`, and the local-only `stage.json` (never uploaded).
//! The tree is written as `.<build-id>.partial/` and renamed once
//! `stage.json` is written, so a complete stage is a `<build-id>/` dir.

use std::fs;
use std::path::{Path, PathBuf};

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, Result,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::areas::run as run_areas;
use crate::cli::{AreasArgs, StageArgs};
use crate::downloads::{check_parquet, write_numbers_parquet};
use crate::layout::{
    Settings, boundaries_dir, boundaries_prefix, build_prefix, current_key, files_under,
    is_build_id, is_public, layout_key_refusal, read_json, settings, sha256_hex, utc_now,
};

/// The engine's `manifest.json`.
#[derive(Debug, Deserialize)]
struct EngineManifest {
    /// Build id, also the name of the engine dir.
    build_id: String,
    /// Attribution carried into the pointer.
    attribution: String,
    /// The shipped files, relative to the engine dir.
    files: Vec<EngineFile>,
}

/// One file of the engine manifest.
#[derive(Debug, Deserialize)]
struct EngineFile {
    /// Path relative to the engine dir.
    path: String,
}

/// The engine's `index.json`, as the pointer reads it.
#[derive(Debug, Deserialize)]
struct EngineIndex {
    /// First day of the period.
    period_start: String,
    /// Last day of the period.
    period_end: String,
    /// `final` or `prelim`.
    status: String,
    /// Date after which the page is stale.
    stale_after: String,
    /// Acknowledgement of the area codes.
    #[serde(default)]
    codes_attribution: Option<String>,
    /// The comparison of the build.
    #[serde(default)]
    comparison: Option<EngineComparison>,
}

/// The comparison of a build.
#[derive(Debug, Deserialize)]
struct EngineComparison {
    /// Sensor the values come from.
    #[serde(default)]
    sensor: Option<String>,
}

/// The pointer `current.json` of a build, in the script's field order.
#[derive(Debug, Serialize)]
struct PointerFile<'a> {
    dataset: &'a str,
    country: String,
    build_id: &'a str,
    prefix: String,
    period_start: String,
    period_end: String,
    status: String,
    stale_after: String,
    boundaries: String,
    boundary_release: String,
    boundary_tiles_revision: u8,
    attribution: String,
    boundaries_attribution: String,
    codes_attribution: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sensor: Option<String>,
    written_at: String,
}

/// `stage.json`, local only and never uploaded.
#[derive(Debug, Serialize)]
struct StageJson {
    build_id: String,
    files: Vec<StageEntry>,
    staged_at: String,
}

/// One file of `stage.json`.
#[derive(Debug, Serialize)]
struct StageEntry {
    key: String,
    bytes: u64,
    sha256: String,
}

/// The exact text of the pointer `current.json` of build `build_id`: pretty
/// JSON in the script's field order, one trailing newline. `stage` writes
/// these bytes; a reader library can build the same file for its tests.
///
/// `index` is the build's `index.json`; the pointer takes its period,
/// status, stale date, codes attribution and sensor. `attribution` is the
/// build attribution of the engine manifest, `boundaries_attribution` the
/// one of the boundaries, `written_at` the `YYYY-MM-DDTHH:MM:SSZ` instant.
///
/// # Errors
///
/// Fails when `index` lacks `period_start`, `period_end`, `status` or
/// `stale_after`, or the pointer cannot be serialized.
pub fn pointer_json(
    s: &Settings,
    build_id: &str,
    index: &Value,
    attribution: &str,
    boundaries_attribution: &str,
    written_at: &str,
) -> Result<String> {
    let index: EngineIndex = serde_json::from_value(index.clone())
        .json_of("index.json lacks the fields of a pointer")?;
    let pointer = PointerFile {
        dataset: &s.dataset,
        country: s.cc.to_uppercase(),
        build_id,
        prefix: build_prefix(s, build_id),
        period_start: index.period_start,
        period_end: index.period_end,
        status: index.status,
        stale_after: index.stale_after,
        boundaries: boundaries_prefix(s),
        boundary_release: s.boundary_release.clone(),
        boundary_tiles_revision: s.boundary_tiles_revision,
        attribution: attribution.to_owned(),
        boundaries_attribution: boundaries_attribution.to_owned(),
        codes_attribution: index.codes_attribution,
        sensor: index.comparison.and_then(|comparison| comparison.sensor),
        written_at: written_at.to_owned(),
    };
    let mut text = serde_json::to_string_pretty(&pointer).json_of("serializing the pointer")?;
    text.push('\n');
    Ok(text)
}

/// A staged build, read back from its `stage.json`.
#[derive(Debug, Clone)]
pub struct Stage {
    /// The stage dir.
    pub dir: PathBuf,
    /// Every staged object except the pointer, sorted by key.
    pub objects: Vec<crate::layout::StageFile>,
    /// The `stage.json` entry of the pointer, when listed.
    pub pointer: Option<crate::layout::StageFile>,
}

/// The pointer of a stage, as it names the build and its period.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Pointer {
    /// Build id the pointer names.
    #[serde(default)]
    pub build_id: String,
    /// Last day of the period.
    #[serde(default)]
    pub period_end: String,
}

/// Write the JSON at `path` through `<name>.partial` and a rename.
///
/// # Errors
///
/// Fails when the value cannot be serialized or the file written.
fn write_json<T: Serialize + ?Sized>(path: &Path, value: &T) -> Result<()> {
    let mut text =
        serde_json::to_string_pretty(value).json_of(format!("serializing {}", path.display()))?;
    text.push('\n');
    let partial = path.with_extension("partial");
    fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
    fs::rename(&partial, path).io_at(IoOp::RenameTo, path)
}

/// Copy `from` to `to` through `<name>.partial` and a rename.
///
/// # Errors
///
/// Fails when `from` is missing or either write fails.
fn copy_file(from: &Path, to: &Path) -> Result<()> {
    if !from.is_file() {
        return Err(DatasetError::stage(format!("missing {}", from.display())));
    }
    if let Some(parent) = to.parent() {
        fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
    }
    let partial = to.with_extension("partial");
    fs::copy(from, &partial).io_step(format!(
        "copying {} to {}",
        from.display(),
        partial.display()
    ))?;
    fs::rename(&partial, to).io_at(IoOp::RenameTo, to)
}

/// The data source the area files of `manifest` name as `source`.
///
/// # Errors
///
/// Fails when there is no area file, one has no source, or two differ.
fn source_of(engine_dir: &Path, manifest: &EngineManifest) -> Result<String> {
    let mut areas: Vec<&str> = manifest
        .files
        .iter()
        .map(|file| file.path.as_str())
        .filter(|path| path.starts_with("areas/"))
        .collect();
    areas.sort_unstable();
    let mut source: Option<String> = None;
    let mut first = "";
    for path in areas {
        let value = read_json(&engine_dir.join(path))?;
        let name = value
            .get("source")
            .and_then(Value::as_str)
            .filter(|text| !text.trim().is_empty())
            .ok_or_else(|| {
                DatasetError::stage(format!("{} has no source", engine_dir.join(path).display()))
            })?;
        match &source {
            None => {
                source = Some(name.to_owned());
                first = path;
            }
            Some(known) if known != name => {
                return Err(DatasetError::stage(format!(
                    "{} names source {name}, not {known} ({first})",
                    engine_dir.join(path).display()
                )));
            }
            Some(_) => {}
        }
    }
    source.ok_or_else(|| DatasetError::stage(format!("{} has no area file", engine_dir.display())))
}

/// Why the boundary downloads in `areas_dir` no longer match its
/// `areas.geojson`, or `None` when they match.
fn stale_download(areas_dir: &Path) -> Result<Option<String>> {
    let geojson = areas_dir.join("areas.geojson");
    let parquet = areas_dir.join("areas.parquet");
    let geojson_time = crate::layout::modified_millis(&geojson)?;
    let parquet_time = crate::layout::modified_millis(&parquet)?;
    if geojson_time > parquet_time {
        return Ok(Some(format!(
            "{} is newer than {}",
            geojson.display(),
            parquet.display()
        )));
    }
    let features = read_json(&geojson)?
        .get("features")
        .and_then(Value::as_array)
        .map_or(0, Vec::len);
    let report = check_parquet(&parquet)?;
    if report.rows == i64::try_from(features).unwrap_or(i64::MAX) {
        Ok(None)
    } else {
        Ok(Some(format!(
            "{} has {} rows, {} has {features}",
            parquet.display(),
            report.rows,
            geojson.display()
        )))
    }
}

/// Stage `engine_dir`; returns the stage dir.
///
/// # Errors
///
/// Fails on an unreadable engine build, a file outside the public set, a
/// stale boundary download, or a write that fails.
pub fn stage(s: &Settings, engine_dir: &Path) -> Result<PathBuf> {
    let manifest: EngineManifest =
        serde_json::from_value(read_json(&engine_dir.join("manifest.json"))?)
            .io_at(IoOp::Read, engine_dir.join("manifest.json"))?;
    let id = manifest.build_id.clone();
    let name = engine_dir
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    if name != id {
        return Err(DatasetError::stage(format!(
            "{} holds build {id}, not {name}",
            engine_dir.display()
        )));
    }
    let done = s.stage_root.join(&id);
    if done.join("stage.json").is_file() {
        return Ok(done);
    }
    if done.exists() {
        return Err(DatasetError::stage(format!(
            "{} exists without stage.json",
            done.display()
        )));
    }

    let partial = s.stage_root.join(format!(".{id}.partial"));
    if partial.exists() {
        fs::remove_dir_all(&partial).io_at(IoOp::Remove, &partial)?;
    }
    let prefix = build_prefix(s, &id);
    for file in &manifest.files {
        if !is_public(s, &id, &format!("{prefix}{}", file.path)) {
            return Err(DatasetError::stage(format!(
                "{} of the engine manifest is not a public file",
                file.path
            )));
        }
        copy_file(
            &engine_dir.join(&file.path),
            &partial.join(&prefix).join(&file.path),
        )?;
    }
    let source = source_of(engine_dir, &manifest)?;
    write_numbers_parquet(
        &engine_dir.join("numbers.csv"),
        &engine_dir.join("index.json"),
        &source,
        &partial.join(&prefix).join("numbers.parquet"),
    )?;

    let areas_dir = s
        .data_root
        .join("datasets/boundaries")
        .join(&s.cc)
        .join(boundaries_dir(s));
    // The boundary downloads are made once per release, beside areas.pmtiles.
    if !areas_dir.join("areas.parquet").is_file() || !areas_dir.join("LICENSE.txt").is_file() {
        run_areas(&AreasArgs {
            overture: None,
            country_config: s
                .country_config_path
                .is_file()
                .then(|| s.country_config_path.clone()),
            boundaries_dir: None,
            countries: None,
            subtype: "county".to_owned(),
            india_outline: None,
            release: Some(s.boundary_release.clone()),
            max_zoom: 8,
            allow_districtless: None,
            out: areas_dir.clone(),
        })?;
    }
    if let Some(problem) = stale_download(&areas_dir)? {
        return Err(DatasetError::stage(format!(
            "{problem}: move {} and {} away and rerun (stage never rewrites them)",
            areas_dir.join("areas.parquet").display(),
            areas_dir.join("LICENSE.txt").display()
        )));
    }
    for name in ["areas.pmtiles", "areas.parquet", "LICENSE.txt"] {
        copy_file(
            &areas_dir.join(name),
            &partial.join(boundaries_prefix(s)).join(name),
        )?;
    }

    let index = read_json(&engine_dir.join("index.json"))?;
    let boundaries_attribution = read_json(&areas_dir.join("areas.geojson"))?
        .get("attribution")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned();
    let pointer = pointer_json(
        s,
        &id,
        &index,
        &manifest.attribution,
        &boundaries_attribution,
        &utc_now(),
    )?;
    let pointer_path = partial.join(current_key(s));
    let pointer_partial = pointer_path.with_extension("partial");
    if let Some(parent) = pointer_path.parent() {
        fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
    }
    fs::write(&pointer_partial, pointer).io_at(IoOp::Write, &pointer_partial)?;
    fs::rename(&pointer_partial, &pointer_path).io_at(IoOp::RenameTo, &pointer_path)?;

    let mut files = Vec::new();
    let top = s.key_top();
    for key in files_under(&partial.join(top))?
        .into_iter()
        .map(|relative| format!("{top}/{relative}"))
    {
        let path = partial.join(&key);
        let bytes = fs::metadata(&path).io_at(IoOp::Read, &path)?.len();
        files.push(StageEntry {
            key,
            bytes,
            sha256: sha256_hex(&path)?,
        });
    }
    write_json(
        &partial.join("stage.json"),
        &StageJson {
            build_id: id.clone(),
            files,
            staged_at: utc_now(),
        },
    )?;
    fs::rename(&partial, &done).io_step(format!(
        "renaming {} to {}",
        partial.display(),
        done.display()
    ))?;
    Ok(done)
}

/// Run `geolith dataset stage`.
///
/// # Errors
///
/// Propagates [`stage`]'s errors and the settings' errors.
pub fn run(args: &StageArgs) -> Result<PathBuf> {
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    stage(&s, &args.engine_build_dir)
}

/// The stage of build `id`, read back from its `stage.json`.
///
/// # Errors
///
/// Fails when the id is not a build id or the stage is not complete.
pub fn read_stage(s: &Settings, id: &str) -> Result<Stage> {
    if !is_build_id(id) {
        return Err(DatasetError::stage(format!(
            "build id {id} is not <YYYY-MM-DD>.<YYYYMMDDTHHMMZ>"
        )));
    }
    let dir = s.stage_root.join(id);
    let path = dir.join("stage.json");
    if !path.is_file() {
        return Err(DatasetError::stage(format!(
            "no complete stage {id} in {}",
            s.stage_root.display()
        )));
    }
    let value = read_json(&path)?;
    let files: Vec<crate::layout::StageFile> = value
        .get("files")
        .and_then(Value::as_array)
        .map(|files| {
            files
                .iter()
                .filter_map(|file| {
                    Some(crate::layout::StageFile {
                        key: file.get("key")?.as_str()?.to_owned(),
                        bytes: file.get("bytes")?.as_u64()?,
                        sha256: file
                            .get("sha256")
                            .and_then(Value::as_str)
                            .unwrap_or_default()
                            .to_owned(),
                    })
                })
                .collect()
        })
        .unwrap_or_default();
    let current = current_key(s);
    let mut objects: Vec<_> = files
        .iter()
        .filter(|file| file.key != current)
        .cloned()
        .collect();
    objects.sort_by(|a, b| a.key.cmp(&b.key));
    let pointer = files.iter().find(|file| file.key == current).cloned();
    Ok(Stage {
        dir,
        objects,
        pointer,
    })
}

/// The staged objects, each checked to be public and in the dated layout.
///
/// # Errors
///
/// Fails naming the first key that is not.
pub fn public_objects<'a>(
    s: &Settings,
    stage: &'a Stage,
    id: &str,
) -> Result<&'a [crate::layout::StageFile]> {
    for file in &stage.objects {
        if !is_public(s, id, &file.key) {
            return Err(DatasetError::stage(format!(
                "{} refused: not a public file of {id}",
                file.key
            )));
        }
        if let Some(refusal) = layout_key_refusal(&s.key_root, &file.key, false) {
            return Err(DatasetError::stage(refusal.to_string()));
        }
    }
    Ok(&stage.objects)
}

/// The staged pointer of `id`, checked against `stage.json` and the id.
///
/// # Errors
///
/// Fails when the pointer is missing, differs from `stage.json`, or names
/// another build.
pub fn staged_pointer(s: &Settings, stage: &Stage, id: &str) -> Result<Pointer> {
    let key = current_key(s);
    let local = stage.dir.join(&key);
    let entry = stage
        .pointer
        .as_ref()
        .ok_or_else(|| DatasetError::stage(format!("stage.json of {id} does not list {key}")))?;
    if !local.is_file() {
        return Err(DatasetError::stage(format!(
            "{key} is missing from the stage of {id}"
        )));
    }
    let bytes = fs::metadata(&local).io_at(IoOp::Read, &local)?.len();
    if bytes != entry.bytes {
        return Err(DatasetError::stage(format!(
            "{key} has {bytes} bytes, stage.json lists {}: not published",
            entry.bytes
        )));
    }
    if sha256_hex(&local)? != entry.sha256 {
        return Err(DatasetError::stage(format!(
            "sha256 of {key} differs from stage.json: not published"
        )));
    }
    let pointer: Pointer = serde_json::from_value(read_json(&local)?)
        .json_of(format!("cannot read {key}: not a pointer"))?;
    if pointer.build_id != id {
        return Err(DatasetError::stage(format!(
            "{key} names build {}, not {id}: not published",
            pointer.build_id
        )));
    }
    Ok(pointer)
}

/// A `current.json` pointer parsed from a JSON value.
///
/// # Errors
///
/// Fails when the value is not an object with a `YYYY-MM-DD` `period_end` and
/// a build-id `build_id`.
pub fn parse_pointer(value: &Value) -> Result<Pointer> {
    let period_end = value
        .get("period_end")
        .and_then(Value::as_str)
        .filter(|date| {
            let bytes = date.as_bytes();
            bytes.len() == 10
                && bytes[4] == b'-'
                && bytes[7] == b'-'
                && [0, 1, 2, 3, 5, 6, 8, 9]
                    .iter()
                    .all(|i| bytes[*i].is_ascii_digit())
        });
    let build_id = value
        .get("build_id")
        .and_then(Value::as_str)
        .filter(|id| is_build_id(id));
    match (period_end, build_id) {
        (Some(period_end), Some(build_id)) => Ok(Pointer {
            build_id: build_id.to_owned(),
            period_end: period_end.to_owned(),
        }),
        _ => Err(DatasetError::stage(
            "lacks a YYYY-MM-DD period_end or a build-id build_id",
        )),
    }
}

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

    #[test]
    fn a_pointer_names_the_build_and_its_period() {
        let value = serde_json::json!({
            "build_id": "2026-11-20.20261121T2329Z",
            "period_end": "2026-11-18",
            "dataset": "ndvi"
        });
        let pointer = parse_pointer(&value).expect("pointer");
        assert_eq!(pointer.build_id, "2026-11-20.20261121T2329Z");
        assert_eq!(pointer.period_end, "2026-11-18");
    }

    #[test]
    fn the_pointer_text_is_pretty_json_in_the_script_field_order() {
        let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
        s.boundary_tiles_revision = 2;
        let index = serde_json::json!({
            "period_start": "2026-11-06",
            "period_end": "2026-11-10",
            "status": "prelim",
            "stale_after": "2026-11-28",
            "codes_attribution": "Codes",
            "comparison": { "sensor": "OLCI" }
        });
        let text = pointer_json(
            &s,
            "2026-11-10.20251117T0900Z",
            &index,
            "Attribution",
            "Boundaries",
            "2026-11-27T00:00:00Z",
        )
        .expect("pointer");
        let expected = concat!(
            "{\n",
            "  \"dataset\": \"rainfall\",\n",
            "  \"country\": \"IN\",\n",
            "  \"build_id\": \"2026-11-10.20251117T0900Z\",\n",
            "  \"prefix\": \"datasets/rainfall/in/2026-11-10.20251117T0900Z/\",\n",
            "  \"period_start\": \"2026-11-06\",\n",
            "  \"period_end\": \"2026-11-10\",\n",
            "  \"status\": \"prelim\",\n",
            "  \"stale_after\": \"2026-11-28\",\n",
            "  \"boundaries\": \"datasets/boundaries/in/2026-10-21.0-r2/\",\n",
            "  \"boundary_release\": \"2026-10-21.0\",\n",
            "  \"boundary_tiles_revision\": 2,\n",
            "  \"attribution\": \"Attribution\",\n",
            "  \"boundaries_attribution\": \"Boundaries\",\n",
            "  \"codes_attribution\": \"Codes\",\n",
            "  \"sensor\": \"OLCI\",\n",
            "  \"written_at\": \"2026-11-27T00:00:00Z\"\n",
            "}\n"
        );
        assert_eq!(text, expected);
        assert!(pointer_json(&s, "x", &serde_json::json!({}), "a", "b", "c").is_err());
    }

    #[test]
    fn a_pointer_without_a_dated_period_end_is_refused() {
        let value = serde_json::json!({ "build_id": "2026-11-20.20261121T2329Z" });
        assert!(parse_pointer(&value).is_err());
    }

    #[test]
    fn a_stage_reads_back_without_its_pointer_among_the_objects() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let stage_root = dir.path().join("datasets/stage");
        let id = "2026-11-20.20261120T0000Z";
        let stage_dir = stage_root.join(id);
        std::fs::create_dir_all(&stage_dir).expect("mkdir");
        std::fs::write(
            stage_dir.join("stage.json"),
            r#"{"build_id":"2026-11-20.20261120T0000Z","files":[
                {"key":"datasets/rainfall/in/2026-11-20.20261120T0000Z/tiles.pmtiles","bytes":3,"sha256":"aa"},
                {"key":"datasets/rainfall/in/current.json","bytes":2,"sha256":"bb"},
                {"key":"datasets/rainfall/in/2026-11-20.20261120T0000Z/index.json","bytes":1,"sha256":"cc"}]}"#,
        )
        .expect("write");
        let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
        s.stage_root = stage_root;
        let stage = read_stage(&s, id).expect("stage");
        assert_eq!(stage.objects.len(), 2);
        assert_eq!(
            stage.objects[0].key,
            "datasets/rainfall/in/2026-11-20.20261120T0000Z/index.json"
        );
        assert_eq!(
            stage.objects[1].key,
            "datasets/rainfall/in/2026-11-20.20261120T0000Z/tiles.pmtiles"
        );
        assert_eq!(
            stage.pointer.expect("pointer entry").key,
            "datasets/rainfall/in/current.json"
        );
    }
}