use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::Path;
use crate::error::{
DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, NumberResultExt as _,
Result,
};
use serde_json::Value;
use crate::cli::VerifyArgs;
use crate::config::DatasetConfig;
use crate::downloads::{CheckReport, check_parquet};
use crate::exit::Exit;
use crate::layout::{
Settings, boundaries_dir, boundaries_prefix, build_prefix, complete_stages, files_under,
is_public, read_json, settings, sha256_hex,
};
use crate::normals::parse_csv;
use crate::period::missing_season;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
pub build_id: String,
pub areas: usize,
pub warnings: Vec<String>,
pub failures: Vec<String>,
}
fn non_empty(value: Option<&Value>) -> bool {
value
.and_then(Value::as_str)
.is_some_and(|text| !text.is_empty())
}
fn attribution_of(value: &Value) -> Option<&str> {
value
.get("attribution")
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
}
fn pmtiles_metadata(path: &Path) -> Result<Value> {
let mut file = fs::File::open(path).io_at(IoOp::Open, path)?;
let mut header = [0_u8; 127];
file.read_exact(&mut header)
.io_step(format!("reading the header of {}", path.display()))?;
if &header[..7] != b"PMTiles" || header[7] != 3 {
return Err(DatasetError::stage("not a PMTiles v3 archive"));
}
let offset = u64::from_le_bytes(
header[24..32]
.try_into()
.expect("eight bytes of the header"),
);
let length = u64::from_le_bytes(
header[32..40]
.try_into()
.expect("eight bytes of the header"),
);
file.seek(SeekFrom::Start(offset)).io_at(IoOp::Seek, path)?;
let mut raw = vec![0_u8; usize::try_from(length).number_of("metadata length")?];
file.read_exact(&mut raw).io_at(IoOp::Stat, path)?;
let text = match header[97] {
1 => raw,
2 => {
let mut out = Vec::new();
flate2::read::GzDecoder::new(raw.as_slice())
.read_to_end(&mut out)
.io_step("gunzipping the metadata")?;
out
}
other => {
return Err(DatasetError::stage(format!(
"PMTiles internal compression {other} not supported"
)));
}
};
serde_json::from_slice(&text).json_of("the metadata is not JSON")
}
fn csv_table(text: &str) -> Result<(Vec<String>, Vec<Vec<String>>)> {
let mut rows = parse_csv(text)?;
if rows.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let header = rows.remove(0);
rows.retain(|row| row.len() > 1 || row.first().is_some_and(|cell| !cell.is_empty()));
Ok((header, rows))
}
fn csv_rows(path: &Path) -> Result<usize> {
let text = fs::read_to_string(path).io_at(IoOp::Read, path)?;
Ok(text
.lines()
.filter(|line| !line.trim().is_empty() && !line.trim_start().starts_with('#'))
.skip(1)
.count())
}
fn csv_cell(row: &[String], column: usize) -> Option<&str> {
row.get(column).map(String::as_str)
}
fn attribution_failure(
key: &str,
path: &Path,
expected: Option<&str>,
checks: &mut HashMap<String, CheckReport>,
) -> Option<String> {
let extension = key.rsplit('.').next().unwrap_or_default();
let wrong = |value: Option<&str>| {
value.is_some_and(|text| !text.is_empty())
&& expected.is_some_and(|want| value != Some(want))
};
match extension {
"json" | "geojson" => {
let value = match read_json(path) {
Ok(value) => value,
Err(error) => return Some(format!("cannot read {key}: {error}")),
};
let attribution = attribution_of(&value);
if wrong(attribution) {
return Some(format!("other attribution in {key}"));
}
if attribution.is_none() {
return Some(format!("no attribution in {key}"));
}
None
}
"csv" => {
let text = match fs::read_to_string(path) {
Ok(text) => text,
Err(error) => return Some(format!("cannot read {key}: {error}")),
};
let (header, rows) = match csv_table(&text) {
Ok(table) => table,
Err(error) => return Some(format!("cannot read {key}: {error}")),
};
let Some(column) = header.iter().position(|name| name == "attribution") else {
return Some(format!("no attribution on every row of {key}"));
};
if rows.iter().any(|row| {
csv_cell(row, column).is_some_and(|text| {
!text.is_empty() && expected.is_some_and(|want| text != want)
})
}) {
return Some(format!("other attribution on a row of {key}"));
}
if rows.is_empty()
|| rows
.iter()
.any(|row| csv_cell(row, column).is_none_or(str::is_empty))
{
return Some(format!("no attribution on every row of {key}"));
}
None
}
"pmtiles" | "parquet" => {
let attribution = if extension == "pmtiles" {
match pmtiles_metadata(path) {
Ok(value) => attribution_of(&value).map(str::to_owned),
Err(error) => return Some(format!("cannot read {key}: {error}")),
}
} else {
let report = match checks.get(key) {
Some(report) => report.clone(),
None => match check_parquet(path) {
Ok(report) => {
checks.insert(key.to_owned(), report.clone());
report
}
Err(error) => return Some(format!("cannot read {key}: {error}")),
},
};
report.attribution
};
if wrong(attribution.as_deref()) {
return Some(format!("other attribution in the metadata of {key}"));
}
if attribution.is_none_or(|text| text.is_empty()) {
return Some(format!("no attribution in the metadata of {key}"));
}
None
}
_ => None,
}
}
fn series_failures(dir: &Path, prefix: &str, index: &Value) -> Vec<String> {
let rows = index
.get("areas")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let key = format!("{prefix}series.json");
let path = dir.join(&key);
if !path.is_file() {
return if rows.iter().any(|row| row.get("value_class").is_some()) {
vec![format!("missing {key} (index.json carries classes)")]
} else {
Vec::new()
};
}
let series = match read_json(&path) {
Ok(series) => series,
Err(error) => return vec![format!("cannot read {key}: {error}")],
};
let mut failures = Vec::new();
let ids: Vec<&Value> = rows.iter().filter_map(|row| row.get("id")).collect();
let listed = series
.get("areas")
.and_then(Value::as_array)
.map_or_else(Vec::new, |areas| areas.iter().collect());
if serde_json::to_string(&listed).ok() != serde_json::to_string(&ids).ok() {
failures.push(format!("{key} areas are not the index.json ids in order"));
}
for period in series
.get("periods")
.and_then(Value::as_array)
.map_or(&[][..], Vec::as_slice)
{
let end = period
.get("period_end")
.and_then(Value::as_str)
.unwrap_or_default();
for field in ["value", "comparison"] {
let text = period.get(field).and_then(Value::as_str);
if text.is_none_or(|text| text.chars().count() != ids.len()) {
failures.push(format!("{key} {end} {field} has not one class per area"));
}
}
if let Some(tiles) = period.get("tiles").and_then(Value::as_str)
&& !dir.join(prefix).join(tiles).exists()
{
failures.push(format!("{key} {end} names {tiles}, not staged"));
}
}
failures
}
fn parquet_rows(
key: &str,
dir: &Path,
checks: &mut HashMap<String, CheckReport>,
failures: &mut Vec<String>,
) -> Option<i64> {
let path = dir.join(key);
if !path.exists() {
return None;
}
if let Some(report) = checks.get(key) {
return Some(report.rows);
}
match check_parquet(&path) {
Ok(report) => {
let rows = report.rows;
checks.insert(key.to_owned(), report);
Some(rows)
}
Err(error) => {
failures.push(format!("cannot read {key}: {error}"));
None
}
}
}
pub fn check(dir: &Path, s: &Settings) -> Result<Report> {
let build_id = dir
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let prefix = build_prefix(s, &build_id);
let mut failures: Vec<String> = Vec::new();
let area_file = |area_id: &str| {
dir.join(&prefix)
.join("areas")
.join(format!("{area_id}.json"))
.is_file()
};
let country = s.country_config();
let upper = s.cc.to_uppercase();
let india = s.cc.eq_ignore_ascii_case("in");
let mut excluded = Vec::new();
if let Ok(index) = read_json(&dir.join(&prefix).join("index.json"))
&& let Some(rows) = index.get("excluded").and_then(Value::as_array)
{
for row in rows {
if let Some(id) = row.get("id").and_then(Value::as_str) {
excluded.push(id.to_owned());
}
}
}
let mut areas = 0_usize;
let geojson = s
.data_root
.join("datasets/boundaries")
.join(&s.cc)
.join(boundaries_dir(s))
.join("areas.geojson");
let mut region_counts: BTreeMap<String, usize> = BTreeMap::new();
let features = match read_json(&geojson) {
Ok(collection) => collection
.get("features")
.and_then(Value::as_array)
.cloned(),
Err(error) => {
failures.push(format!("cannot read {}: {error}", geojson.display()));
None
}
};
if let Some(features) = features {
let mut stateless = Vec::new();
for feature in &features {
let props = feature.get("properties").cloned().unwrap_or(Value::Null);
if props.get("country").and_then(Value::as_str) != Some(upper.as_str()) {
continue;
}
let Some(id) = props.get("id").and_then(Value::as_str) else {
continue;
};
areas += 1;
if !area_file(id) && !excluded.iter().any(|excluded| excluded == id) {
failures.push(format!("missing area file {prefix}areas/{id}.json"));
}
let region = props.get("region_code").and_then(Value::as_str);
let parent = props.get("parent_name").and_then(Value::as_str);
if india && (region.is_none_or(str::is_empty) || parent.is_none_or(str::is_empty)) {
stateless.push(id.to_owned());
} else if india && let Some(region) = region.filter(|text| !text.is_empty()) {
*region_counts.entry(region.to_owned()).or_default() += 1;
}
}
if areas == 0 {
failures.push(format!("no {upper} areas in areas.geojson"));
}
if let Ok(report) = read_json(&geojson.with_file_name("areas-report.json"))
&& let Some(expected) = report
.get("invariants")
.and_then(|invariants| invariants.get("areas"))
.and_then(Value::as_u64)
&& expected != u64::try_from(areas).unwrap_or(u64::MAX)
{
failures.push(format!(
"areas.geojson holds {areas} {upper} areas, its areas-report.json asserts {expected}"
));
}
if !stateless.is_empty() {
failures.push(format!(
"{} districts without a state in areas.geojson: {}",
stateless.len(),
stateless.join(", ")
));
}
}
if india {
let report_path = geojson.with_file_name("areas-report.json");
match read_json(&report_path) {
Ok(report) => {
let regions = report
.get("india_regions")
.and_then(Value::as_object)
.cloned()
.unwrap_or_default();
let allowed: Vec<String> = report
.get("india_districtless_allowed")
.and_then(Value::as_array)
.map_or_else(Vec::new, |codes| {
codes
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect()
});
if regions.is_empty() {
failures.push(format!("no india_regions in {}", report_path.display()));
}
for (code, count) in ®ions {
let count = count.as_u64().unwrap_or_default();
if count == 0 && !allowed.iter().any(|allowed| allowed == code) {
failures.push(format!("coded Indian region {code} has no district"));
}
let actual =
u64::try_from(*region_counts.get(code).unwrap_or(&0)).unwrap_or(u64::MAX);
if actual != count {
failures.push(format!(
"areas.geojson has {actual} districts in {code}, areas-report.json says {count}"
));
}
}
for code in region_counts.keys() {
if !regions.contains_key(code) {
failures.push(format!(
"region {code} of areas.geojson is not a coded Indian region of areas-report.json"
));
}
}
}
Err(error) => failures.push(format!("cannot read {}: {error}", report_path.display())),
}
}
for key in [
format!("{prefix}tiles.pmtiles"),
format!("{prefix}index.json"),
format!("{prefix}numbers.csv"),
format!("{prefix}numbers.parquet"),
format!("{}areas.pmtiles", boundaries_prefix(s)),
format!("{}areas.parquet", boundaries_prefix(s)),
format!("{}LICENSE.txt", boundaries_prefix(s)),
] {
if !dir.join(&key).exists() {
failures.push(format!("missing {key}"));
}
}
let index = read_json(&dir.join(&prefix).join("index.json")).unwrap_or(Value::Null);
let expected = attribution_of(&index).map(str::to_owned);
failures.extend(series_failures(dir, &prefix, &index));
let mut checks: HashMap<String, CheckReport> = HashMap::new();
let mut seasons: Vec<Value> = Vec::new();
let mut any_code = false;
let mut codes_unacknowledged = false;
let top = s.key_top();
let staged: Vec<String> = if dir.join(top).exists() {
files_under(&dir.join(top))?
.into_iter()
.map(|relative| format!("{top}/{relative}"))
.collect()
} else {
Vec::new()
};
for key in &staged {
if !is_public(s, &build_id, key) {
failures.push(format!("not public: {key}"));
}
let path = dir.join(key);
let boundaries = key.starts_with(&boundaries_prefix(s));
if let Some(failure) = attribution_failure(
key,
&path,
if boundaries {
None
} else {
expected.as_deref()
},
&mut checks,
) {
failures.push(failure);
} else if key.starts_with(&format!("{prefix}areas/")) {
let area = read_json(&path).unwrap_or(Value::Null);
if india && !non_empty(area.get("state")) {
failures.push(format!("state is null in {key}"));
}
if area.get("lgd_code").is_some_and(|code| !code.is_null()) {
if !non_empty(area.get("codes_attribution")) {
failures.push(format!("lgd_code without codes_attribution in {key}"));
codes_unacknowledged = true;
} else {
any_code = true;
}
}
seasons.push(area);
}
}
let numbers_parquet = format!("{prefix}numbers.parquet");
let numbers_rows = parquet_rows(&numbers_parquet, dir, &mut checks, &mut failures);
let numbers_csv = dir.join(&prefix).join("numbers.csv");
if let Some(numbers_rows) = numbers_rows
&& numbers_csv.exists()
{
let text = fs::read_to_string(&numbers_csv).io_at(IoOp::Read, &numbers_csv)?;
let csv = csv_table(&text)?.1.len();
if numbers_rows != i64::try_from(csv).unwrap_or(i64::MAX) {
failures.push(format!(
"{numbers_parquet} has {numbers_rows} rows, numbers.csv has {csv}"
));
}
}
let areas_parquet = format!("{}areas.parquet", boundaries_prefix(s));
let areas_rows = parquet_rows(&areas_parquet, dir, &mut checks, &mut failures);
let boundaries_areas = read_json(&geojson).ok().and_then(|collection| {
collection
.get("features")
.and_then(Value::as_array)
.map(Vec::len)
});
if let (Some(areas_rows), Some(boundaries_areas)) = (areas_rows, boundaries_areas)
&& areas_rows != i64::try_from(boundaries_areas).unwrap_or(i64::MAX)
{
failures.push(format!(
"{areas_parquet} has {areas_rows} rows, areas.geojson has {boundaries_areas} areas"
));
}
let license = dir.join(boundaries_prefix(s)).join("LICENSE.txt");
if let Ok(text) = fs::read_to_string(&license) {
let licence_id = country
.as_ref()
.map_or("ODbL-1.0", |config| config.boundaries.licence_id.as_str());
let words: &[&str] = match licence_id {
"ODbL-1.0" => &["ODbL", "OpenStreetMap"],
"CC0-1.0" => &["CC0"],
"CC-BY-4.0" => &["CC BY 4.0"],
other => &[other],
};
for word in words {
if !text.contains(word) {
failures.push(format!(
"{}LICENSE.txt does not name {word}",
boundaries_prefix(s)
));
}
}
}
if (any_code || codes_unacknowledged)
&& let Ok(index) = read_json(&dir.join(&prefix).join("index.json"))
&& !non_empty(index.get("codes_attribution"))
{
failures.push(format!(
"lgd codes without codes_attribution in {prefix}index.json"
));
}
let mut stage_files: Vec<(String, u64, String)> = Vec::new();
let mut stage_read = false;
match read_json(&dir.join("stage.json")) {
Ok(stage) => match stage.get("files").and_then(Value::as_array) {
Some(files) => {
for file in files {
let key = file
.get("key")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let bytes = file
.get("bytes")
.and_then(Value::as_u64)
.unwrap_or_default();
let sha256 = file
.get("sha256")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
stage_files.push((key, bytes, sha256));
}
stage_read = true;
}
None => failures.push("cannot read stage.json: no files list".to_owned()),
},
Err(error) => failures.push(format!("cannot read stage.json: {error}")),
}
let listed: Vec<&str> = stage_files.iter().map(|(key, _, _)| key.as_str()).collect();
let empty: Vec<String> = Vec::new();
for key in if stage_read { &staged } else { &empty } {
if !listed.contains(&key.as_str()) {
failures.push(format!("stage.json does not list {key}"));
}
}
for (key, bytes, sha256) in &stage_files {
let path = dir.join(key);
if !path.exists() {
failures.push(format!("stage.json lists missing {key}"));
} else if fs::metadata(&path).io_at(IoOp::Read, &path)?.len() != *bytes {
failures.push(format!("size of {key} differs from stage.json"));
} else if sha256_hex(&path)? != *sha256 {
failures.push(format!("sha256 of {key} differs from stage.json"));
}
}
match read_json(&dir.join(&prefix).join("index.json")) {
Ok(index) => {
let published = index
.get("published")
.and_then(Value::as_array)
.map_or_else(Vec::new, |ids| {
ids.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect()
});
match csv_rows(&s.published_csv) {
Ok(rows) => {
if published.len() != rows {
failures.push(format!(
"index.json published has {} ids, {} has {rows} rows",
published.len(),
s.published_csv.display()
));
}
for area_id in &published {
if !area_file(area_id) {
failures.push(format!(
"published area {area_id} has no areas/{area_id}.json"
));
}
}
}
Err(error) => failures.push(format!("cannot check published: {error}")),
}
}
Err(error) => failures.push(format!("cannot check published: {error}")),
}
let previous = complete_stages(&s.stage_root)
.into_iter()
.rfind(|other| other < &build_id);
if let Some(previous) = previous {
let prev_areas = s
.stage_root
.join(&previous)
.join(build_prefix(s, &previous))
.join("areas");
if let Ok(entries) = fs::read_dir(&prev_areas) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let id = name.strip_suffix(".json").unwrap_or(&name);
if !area_file(id) {
failures.push(format!("area {id} of {previous} is missing"));
}
}
}
}
let mut warnings = Vec::new();
let config_path = s
.repo
.join("packages/dataset-builder/data/datasets")
.join(format!("{}.json", s.dataset));
if let Ok(config) = DatasetConfig::load(&config_path)
&& let Some(area) = seasons.iter().find(|area| {
non_empty(area.get("season_start"))
&& area.get("season_value").is_some_and(Value::is_null)
&& area.get("period_end").and_then(Value::as_str).is_some()
})
{
let start = area
.get("season_start")
.and_then(Value::as_str)
.unwrap_or_default();
let end = area
.get("period_end")
.and_then(Value::as_str)
.unwrap_or_default();
let source = s.data_root.join("datasets").join(&s.dataset).join("src");
let missing = missing_season(&config, &source, start, end)?;
for key in &missing {
warnings.push(format!("SEASON-MISSING {key}"));
}
if missing.is_empty() {
warnings.push(format!("SEASON-STALE {build_id}"));
}
}
Ok(Report {
build_id,
areas,
warnings,
failures,
})
}
pub fn run(args: &VerifyArgs) -> Result<()> {
let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
let id = args
.build_id
.clone()
.or_else(|| complete_stages(&s.stage_root).last().cloned());
let Some(id) = id else {
println!(
"VERIFY FAIL no complete stage in {}",
s.stage_root.display()
);
return Err(Exit(1).into());
};
let dir = s.stage_root.join(&id);
if !dir.join("stage.json").is_file() {
println!(
"VERIFY FAIL no complete stage {id} in {}",
s.stage_root.display()
);
return Err(Exit(1).into());
}
let report = check(&dir, &s)?;
for warning in &report.warnings {
println!("{warning}");
}
for failure in &report.failures {
println!("VERIFY FAIL {failure}");
}
if !report.failures.is_empty() {
return Err(Exit(1).into());
}
println!("VERIFY OK {id} {} areas", report.areas);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_csv_without_an_attribution_column_has_no_attribution() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("numbers.csv");
fs::write(&path, "id,value\na,1\n").expect("write");
let failure = attribution_failure("numbers.csv", &path, None, &mut HashMap::new())
.expect("a failure");
assert_eq!(failure, "no attribution on every row of numbers.csv");
}
#[test]
fn a_csv_with_the_attribution_on_every_row_passes() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("numbers.csv");
fs::write(&path, "id,attribution\na,CHIRPS\nb,CHIRPS\n").expect("write");
assert!(
attribution_failure("numbers.csv", &path, Some("CHIRPS"), &mut HashMap::new())
.is_none()
);
}
#[test]
fn a_json_with_another_attribution_is_refused() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("index.json");
fs::write(&path, r#"{"attribution":"Mine"}"#).expect("write");
let failure = attribution_failure("index.json", &path, Some("Theirs"), &mut HashMap::new())
.expect("a failure");
assert_eq!(failure, "other attribution in index.json");
}
#[test]
fn a_build_id_must_be_dated() {
assert!(crate::layout::is_build_id("2026-11-20.20261121T2329Z"));
assert!(!crate::layout::is_build_id("2026-11-20"));
}
}