use std::fs;
use anyhow::{Context, Result, bail};
use serde_json::Value;
use crate::cli::BoundsArgs;
use crate::layout::{build_prefix, current_key, read_json, settings};
use crate::remote::connect;
use crate::slots::{SlotTable, slot_key, slot_table_path};
use crate::stage::{Pointer, parse_pointer};
pub const RAINFALL_MAX_MM: f64 = 3000.0;
pub const NDVI_MIN: f64 = -0.08;
pub const NDVI_MAX: f64 = 0.92;
pub const RAINFALL_MEAN_FACTOR: f64 = 3.0;
pub const RAINFALL_MEAN_FLOOR_MM: f64 = 2.0;
pub const NDVI_MEAN_MARGIN: f64 = 0.15;
pub const DRY_SLOT_SHARE: f64 = 0.8;
pub const MIN_AREAS_WITH_VALUE_RAINFALL: f64 = 0.95;
pub const MIN_AREAS_WITH_VALUE_NDVI: f64 = 0.9;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct BoundsInput<'a> {
pub dataset: &'a str,
pub build_id: &'a str,
pub areas: usize,
pub series: &'a Value,
pub index: &'a Value,
pub values: &'a [f64],
pub slots: Option<&'a SlotTable>,
pub pointer: Option<&'a Pointer>,
pub boundaries: (&'a str, u8),
pub current: &'a Value,
}
#[must_use]
pub fn min_areas_with_value(dataset: &str) -> f64 {
if dataset == "rainfall" {
MIN_AREAS_WITH_VALUE_RAINFALL
} else if dataset == "ndvi" {
MIN_AREAS_WITH_VALUE_NDVI
} else {
0.9
}
}
fn text(value: &Value, key: &str) -> String {
value
.get(key)
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned()
}
pub fn bounds_failures(input: &BoundsInput<'_>) -> Result<Vec<String>> {
let mut failures: Vec<String> = Vec::new();
let periods = input
.series
.get("periods")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or_default();
let Some(latest) = periods.last() else {
return Ok(vec!["the staged series.json lists no period".to_owned()]);
};
let named = text(input.index, "build_id");
if named != input.build_id {
failures.push(format!(
"index.json names build {}, not {}",
if named.is_empty() { "none" } else { &named },
input.build_id
));
}
let latest_end = text(latest, "period_end");
let index_end = text(input.index, "period_end");
let end = if index_end.is_empty() {
latest_end.clone()
} else {
index_end
};
if latest_end != end {
failures.push(format!(
"the latest series period ends {latest_end}, index.json {end}"
));
}
if let Some(pointer) = input.pointer
&& end < pointer.period_end
{
failures.push(format!(
"the new period {end} is before the published {}",
pointer.period_end
));
}
let share = min_areas_with_value(input.dataset);
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let floor = (input.areas as f64 * share).floor() as usize;
if input.values.len() < floor {
failures.push(format!(
"only {} of {} areas carry a value of the new period (floor {floor})",
input.values.len(),
input.areas
));
}
if input.values.is_empty() {
return Ok(failures);
}
let min = input.values.iter().copied().fold(f64::INFINITY, f64::min);
let max = input
.values
.iter()
.copied()
.fold(f64::NEG_INFINITY, f64::max);
let mean = input.values.iter().sum::<f64>() / input.values.len() as f64;
let first = input.values[0];
let all_same = input.values.iter().all(|value| *value == first);
let slot = slot_key(&end, input.dataset)?;
let history = input.slots.and_then(|table| table.slots.get(&slot));
if history.is_none() {
failures.push(format!(
"no historical slot {slot} in {}-slots.json (the gate cannot judge the period)",
input.dataset
));
}
if input.dataset == "rainfall" {
if min < 0.0 {
failures.push(format!("rainfall min {min} is below 0"));
}
if max > RAINFALL_MAX_MM {
failures.push(format!(
"rainfall max {max} is above {RAINFALL_MAX_MM} mm in a pentad"
));
}
if all_same && first != 0.0 {
failures.push(format!("every area has the same rainfall ({first} mm)"));
}
if all_same && first == 0.0 {
let wettest = history
.and_then(|history| history.min_share_under_1mm)
.unwrap_or(0.0);
if wettest < DRY_SLOT_SHARE {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let percent = (wettest * 100.0).round() as i64;
failures.push(format!(
"all {} areas are 0 mm in slot {slot}, whose wettest 1991-2020 year still \
had only {percent}% of areas under 1 mm",
input.values.len()
));
}
}
if let Some(history) = history {
let ceiling = RAINFALL_MEAN_FLOOR_MM.max(RAINFALL_MEAN_FACTOR * history.mean_max);
if mean > ceiling {
failures.push(format!(
"the national mean {mean:.2} mm is above {ceiling:.2} mm ({} x the slot's \
1991-2020 maximum {:.2} mm)",
RAINFALL_MEAN_FACTOR, history.mean_max
));
}
}
} else if input.dataset == "ndvi" {
if min < NDVI_MIN {
failures.push(format!("ndvi min {min} is below {NDVI_MIN}"));
}
if max > NDVI_MAX {
failures.push(format!("ndvi max {max} is above {NDVI_MAX}"));
}
if all_same {
failures.push(format!("every area has the same NDVI ({first})"));
}
if let Some(history) = history {
if mean < history.mean_min - NDVI_MEAN_MARGIN {
failures.push(format!(
"the national mean NDVI {mean:.3} is below {:.3} (the slot's 2019-2025 \
minimum {:.3} - {NDVI_MEAN_MARGIN})",
history.mean_min - NDVI_MEAN_MARGIN,
history.mean_min
));
}
if mean > history.mean_max + NDVI_MEAN_MARGIN {
failures.push(format!(
"the national mean NDVI {mean:.3} is above {:.3} (the slot's 2019-2025 \
maximum {:.3} + {NDVI_MEAN_MARGIN})",
history.mean_max + NDVI_MEAN_MARGIN,
history.mean_max
));
}
}
}
let release = text(input.current, "boundary_release");
let release = if release.is_empty() {
None
} else {
Some(release)
};
if release.as_deref() != Some(input.boundaries.0) {
failures.push(format!(
"the stage names boundary release {}, this run builds {}",
release.as_deref().unwrap_or("none"),
input.boundaries.0
));
}
let revision = input
.current
.get("boundary_tiles_revision")
.and_then(Value::as_u64)
.and_then(|value| u8::try_from(value).ok());
if revision != Some(input.boundaries.1) {
failures.push(format!(
"the stage names boundary tiles revision {}, this run builds {}",
revision.map_or_else(|| "none".to_owned(), |value| value.to_string()),
input.boundaries.1
));
}
Ok(failures)
}
pub fn period_values(csv: &str, period_end: &str) -> Result<Vec<f64>> {
let mut rows = crate::normals::parse_csv(csv)?;
if rows.is_empty() {
bail!("numbers.csv is empty");
}
let header = rows.remove(0);
let column = |name: &str| header.iter().position(|cell| cell.as_str() == name);
let (Some(end_at), Some(value_at)) = (column("period_end"), column("value")) else {
bail!("numbers.csv needs area_id, period_end and value");
};
let mut values = Vec::new();
for row in rows {
if row.get(end_at).map(String::as_str) != Some(period_end) {
continue;
}
let value = row.get(value_at).map_or("", String::as_str);
if value.is_empty() {
continue;
}
if let Ok(number) = value.parse::<f64>()
&& number.is_finite()
{
values.push(number);
}
}
Ok(values)
}
pub fn published_pointer(s: &crate::layout::Settings) -> Result<Option<Pointer>> {
let s3 = connect(None)?;
let key = current_key(s);
if s3.head(&key)?.is_none() {
return Ok(None);
}
let bytes = s3.get(&key)?;
let text = String::from_utf8(bytes).with_context(|| format!("{key} is not UTF-8"))?;
if text.trim().is_empty() {
return Ok(None);
}
let value: Value = serde_json::from_str(&text).with_context(|| {
format!("the pointer {key} has no build_id or period_end: fix it by hand")
})?;
let pointer = parse_pointer(&value).with_context(|| {
format!("the pointer {key} has no build_id or period_end: fix it by hand")
})?;
Ok(Some(pointer))
}
pub fn run(args: &BoundsArgs) -> Result<()> {
let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
let stage = s.stage_root.join(&args.build);
let prefix = build_prefix(&s, &args.build);
let dir = stage.join(&prefix);
let read = |name: &str| -> Result<Value> {
let path = dir.join(name);
read_json(&path).with_context(|| format!("reading {}", path.display()))
};
let series = read("series.json")?;
let index = read("index.json")?;
let current_path = stage.join(current_key(&s));
let current =
read_json(¤t_path).with_context(|| format!("reading {}", current_path.display()))?;
let numbers_path = dir.join("numbers.csv");
let numbers = fs::read_to_string(&numbers_path)
.with_context(|| format!("reading {}", numbers_path.display()))?;
let end = text(&index, "period_end");
let values = period_values(&numbers, &end)?;
let slots_path = slot_table_path(&s.repo, &s.dataset, &s.cc);
if !slots_path.is_file() {
bail!(
"no {} in {}: the bounds gate needs the measured slot history of {} \
(geolith dataset slots)",
slots_path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default(),
slots_path
.parent()
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or_default(),
s.cc
);
}
let slots = crate::slots::read_slots(&slots_path)?;
let pointer = published_pointer(&s)?;
let areas = index
.get("areas")
.and_then(Value::as_array)
.map_or(0, Vec::len);
let failures = bounds_failures(&BoundsInput {
dataset: &s.dataset,
build_id: &args.build,
areas,
series: &series,
index: &index,
values: &values,
slots: Some(&slots),
pointer: pointer.as_ref(),
boundaries: (&s.boundary_release, s.boundary_tiles_revision),
current: ¤t,
})?;
for failure in &failures {
eprintln!("bounds: {failure}");
}
if !failures.is_empty() {
bail!("{} fails {} bounds checks", args.build, failures.len());
}
println!("bounds: {} passes", args.build);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::slots::{SlotHistory, SlotTable};
use std::collections::BTreeMap;
fn history(mean_min: f64, mean_max: f64, wettest: Option<f64>) -> SlotHistory {
SlotHistory {
years: 30,
mean_min,
mean_median: (mean_min + mean_max) / 2.0,
mean_max,
median_min: mean_min,
median_max: mean_max,
min_share_under_1mm: wettest,
max_share_under_1mm: wettest,
max_area_mm: Some(200.0),
yearly_means: vec![mean_min, mean_max],
}
}
fn table(dataset: &str, slot: &str, history: SlotHistory) -> SlotTable {
SlotTable {
dataset: dataset.to_owned(),
unit: "mm".to_owned(),
slots: BTreeMap::from([(slot.to_owned(), history)]),
source: "test".to_owned(),
}
}
fn input<'a>(
dataset: &'a str,
values: &'a [f64],
slots: &'a SlotTable,
series: &'a Value,
index: &'a Value,
current: &'a Value,
) -> BoundsInput<'a> {
BoundsInput {
dataset,
build_id: "2026-11-20.20261120T0000Z",
areas: 4,
series,
index,
values,
slots: Some(slots),
pointer: None,
boundaries: ("2026-10-21.0", 1),
current,
}
}
fn fixtures() -> (Value, Value, Value) {
let series = serde_json::json!({"periods":[
{"period_end":"2026-11-10"},
{"period_end":"2026-11-15"}
]});
let index = serde_json::json!({
"build_id":"2026-11-20.20261120T0000Z",
"period_end":"2026-11-15"
});
let current = serde_json::json!({
"boundary_release":"2026-10-21.0",
"boundary_tiles_revision":1
});
(series, index, current)
}
#[test]
fn a_real_dry_season_passes() {
let slots = table("rainfall", "11-3", history(0.0, 3.0, Some(0.95)));
let (series, index, current) = fixtures();
let values = [0.0, 0.0, 0.0, 0.0];
let failures = bounds_failures(&input(
"rainfall", &values, &slots, &series, &index, ¤t,
))
.expect("bounds");
assert!(failures.is_empty(), "{failures:?}");
}
#[test]
fn all_zeros_in_a_monsoon_slot_fails() {
let slots = table("rainfall", "07-2", history(20.0, 60.0, Some(0.25)));
let series = serde_json::json!({"periods":[{"period_end":"2026-07-10"}]});
let index = serde_json::json!({
"build_id":"2026-11-20.20261120T0000Z",
"period_end":"2026-07-10"
});
let current = serde_json::json!({
"boundary_release":"2026-10-21.0",
"boundary_tiles_revision":1
});
let values = [0.0, 0.0, 0.0, 0.0];
let failures = bounds_failures(&input(
"rainfall", &values, &slots, &series, &index, ¤t,
))
.expect("bounds");
assert!(
failures
.iter()
.any(|failure| failure.contains("whose wettest 1991-2020 year still had only 25%")),
"{failures:?}"
);
}
#[test]
fn values_a_hundred_times_too_large_fail_the_ceiling() {
let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
let (series, index, current) = fixtures();
let values = [250.0, 250.0, 250.0, 250.0];
let failures = bounds_failures(&input(
"rainfall", &values, &slots, &series, &index, ¤t,
))
.expect("bounds");
assert!(
failures
.iter()
.any(|failure| failure.contains("is above 9.00 mm")),
"{failures:?}"
);
assert!(
failures
.iter()
.any(|failure| failure.contains("same rainfall")),
"{failures:?}"
);
}
#[test]
fn half_the_areas_missing_fails_the_floor() {
let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
let (series, index, current) = fixtures();
let values = [1.0, 2.0];
let failures = bounds_failures(&input(
"rainfall", &values, &slots, &series, &index, ¤t,
))
.expect("bounds");
assert!(
failures
.iter()
.any(|failure| failure.contains("only 2 of 4 areas carry a value")),
"{failures:?}"
);
}
#[test]
fn a_slot_without_history_fails_the_gate() {
let slots = table("rainfall", "11-1", history(1.0, 3.0, Some(0.5)));
let (series, index, current) = fixtures();
let values = [1.0, 2.0, 1.5, 2.5];
let failures = bounds_failures(&input(
"rainfall", &values, &slots, &series, &index, ¤t,
))
.expect("bounds");
assert!(
failures
.iter()
.any(|failure| failure.contains("no historical slot 11-3")),
"{failures:?}"
);
}
#[test]
fn ndvi_outside_its_physical_range_fails() {
let slots = table("ndvi", "11-3", history(0.4, 0.6, None));
let (series, index, current) = fixtures();
let values = [0.95, 0.5, 0.45, 0.55];
let failures = bounds_failures(&input("ndvi", &values, &slots, &series, &index, ¤t))
.expect("bounds");
assert!(
failures
.iter()
.any(|failure| failure.contains("ndvi max 0.95 is above 0.92")),
"{failures:?}"
);
}
#[test]
fn a_stage_of_another_boundary_release_fails() {
let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
let (series, index, _) = fixtures();
let current = serde_json::json!({
"boundary_release":"2026-06-17.0",
"boundary_tiles_revision":2
});
let values = [1.0, 2.0, 1.5, 2.5];
let failures = bounds_failures(&input(
"rainfall", &values, &slots, &series, &index, ¤t,
))
.expect("bounds");
assert!(
failures
.iter()
.any(|failure| failure.contains("names boundary release 2026-06-17.0")),
"{failures:?}"
);
assert!(
failures
.iter()
.any(|failure| failure.contains("boundary tiles revision 2")),
"{failures:?}"
);
}
#[test]
fn a_period_before_the_published_one_fails() {
let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
let (series, index, current) = fixtures();
let values = [1.0, 2.0, 1.5, 2.5];
let pointer = Pointer {
build_id: "2026-12-20.20261220T0000Z".to_owned(),
period_end: "2026-12-15".to_owned(),
};
let mut input = input("rainfall", &values, &slots, &series, &index, ¤t);
input.pointer = Some(&pointer);
let failures = bounds_failures(&input).expect("bounds");
assert!(
failures
.iter()
.any(|failure| failure.contains("is before the published 2026-12-15")),
"{failures:?}"
);
}
#[test]
fn the_new_periods_values_come_from_its_own_rows_only() {
let csv = "area_id,period_end,value\na,2026-11-10,1\nb,2026-11-15,2\nc,2026-11-15,\n\
d,2026-11-15,3\n";
assert_eq!(
period_values(csv, "2026-11-15").expect("values"),
vec![2.0, 3.0]
);
}
}