use std::collections::{BTreeSet, HashMap};
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::Path;
use anyhow::{bail, Context, Result};
use fst::MapBuilder;
use crate::index::*;
fn env_u64(key: &str, default: u64) -> u64 {
std::env::var(key)
.ok()
.and_then(|v| v.parse().ok())
.filter(|&n| n > 0)
.unwrap_or(default)
}
const DEFAULT_MAX_UNCOMPRESSED: u64 = 32 << 30; const DEFAULT_MAX_RATIO: u64 = 100;
struct LimitReader<R> {
inner: R,
read: u64,
max_bytes: u64,
compressed_len: u64, max_ratio: u64,
}
impl<R: Read> LimitReader<R> {
fn new(inner: R, compressed_len: u64) -> Self {
Self {
inner,
read: 0,
max_bytes: env_u64("GRIDPIN_MAX_UNCOMPRESSED_BYTES", DEFAULT_MAX_UNCOMPRESSED),
compressed_len,
max_ratio: env_u64("GRIDPIN_MAX_RATIO", DEFAULT_MAX_RATIO),
}
}
}
impl<R: Read> Read for LimitReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = self.inner.read(buf)?;
self.read += n as u64;
if self.read > self.max_bytes {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"decompressed input exceeds {} byte cap (possible decompression bomb); \
raise GRIDPIN_MAX_UNCOMPRESSED_BYTES for a legitimately larger sheet",
self.max_bytes
),
));
}
if self.compressed_len > 0 && self.read > self.compressed_len.saturating_mul(self.max_ratio)
{
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"decompression ratio exceeds {}x of the {}-byte input (possible bomb); \
raise GRIDPIN_MAX_RATIO if intended",
self.max_ratio, self.compressed_len
),
));
}
Ok(n)
}
}
struct House {
numero: u32,
rep_id: u32,
lat: f64,
lon: f64,
postcode: String,
}
#[derive(Default)]
struct Counts {
rows: u64,
streets: u64,
communes: u64,
empty_streets: u64, bad_coords: u64, bad_number: u64, }
fn plausible_pc(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 8
&& s.as_bytes()[0].is_ascii_digit()
&& s.chars().all(|c| c.is_ascii_alphanumeric() || c == ' ')
}
fn push_name(names: &mut Vec<u8>, s: &str) -> Result<u32> {
let bytes = s.as_bytes();
if bytes.len() > 255 {
bail!(
"display name is {} bytes — the names section encodes length in one u8 (max 255): {:?}",
bytes.len(),
s.chars().take(40).collect::<String>()
);
}
let off = names.len() as u32;
names.push(bytes.len() as u8);
names.extend_from_slice(bytes);
Ok(off)
}
fn write_house_block(
out: &mut Vec<u8>,
names: &mut Vec<u8>,
houses: &[House],
lat_c: i32,
lon_c: i32,
voie: &str,
insee: &str,
) -> Result<bool> {
let effective: BTreeSet<&str> = houses.iter().map(|h| h.postcode.as_str()).collect();
let has_known = effective.iter().any(|p| !p.is_empty());
let house_accurate = has_known && effective.len() > 1;
let local_postcodes: Vec<&str> = if house_accurate {
effective.into_iter().filter(|p| !p.is_empty()).collect()
} else {
Vec::new()
};
if house_accurate {
write_varint(out, local_postcodes.len() as u64);
for postcode in &local_postcodes {
out.extend_from_slice(&push_name(names, postcode)?.to_le_bytes());
}
}
let mut prev = 0u32;
for (i, h) in houses.iter().enumerate() {
if i > 0 && h.numero < prev {
bail!(
"input not sorted by numero within street {:?} (insee {:?}): {} after {}",
voie,
insee,
h.numero,
prev
);
}
let delta = if i == 0 {
h.numero as u64
} else {
(h.numero - prev) as u64
};
prev = h.numero;
write_varint(out, delta);
write_varint(out, h.rep_id as u64);
let hla = (h.lat * 1e7).round() as i64;
let hlo = (h.lon * 1e7).round() as i64;
write_varint(out, zigzag(hla - lat_c as i64));
write_varint(out, zigzag(hlo - lon_c as i64));
if house_accurate {
let postcode_id = if h.postcode.is_empty() {
0
} else {
local_postcodes
.binary_search(&h.postcode.as_str())
.expect("house postcode is in its local dictionary")
+ 1
};
write_varint(out, postcode_id as u64);
}
}
Ok(house_accurate)
}
pub fn unique_tmp_path(out_path: &Path) -> std::path::PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
let base = out_path
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| "out".into());
out_path.with_file_name(format!(
".{base}.tmp.{}.{}",
std::process::id(),
TMP_SEQ.fetch_add(1, Ordering::Relaxed)
))
}
pub fn finalize_replace(tmp: &Path, out_path: &Path) -> std::io::Result<()> {
match std::fs::rename(tmp, out_path) {
Ok(()) => sync_parent_dir(out_path),
Err(e) => {
let _ = std::fs::remove_file(tmp);
Err(e)
}
}
}
#[cfg(unix)]
fn sync_parent_dir(path: &Path) -> std::io::Result<()> {
let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
let dir = parent.unwrap_or_else(|| Path::new("."));
std::fs::File::open(dir)?.sync_all()
}
#[cfg(not(unix))]
fn sync_parent_dir(_path: &Path) -> std::io::Result<()> {
Ok(())
}
pub fn write_atomic(out_path: &Path, chunks: &[&[u8]]) -> std::io::Result<()> {
let tmp = unique_tmp_path(out_path);
let write = || -> std::io::Result<()> {
let mut f = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
for c in chunks {
f.write_all(c)?;
}
f.flush()?;
f.sync_all()
};
if let Err(e) = write() {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
finalize_replace(&tmp, out_path) }
pub fn write_atomic_validated(
out_path: &Path,
chunks: &[&[u8]],
validate: impl FnOnce(&Path) -> Result<()>,
) -> Result<()> {
let tmp = unique_tmp_path(out_path);
let write = || -> std::io::Result<()> {
let mut f = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
for c in chunks {
f.write_all(c)?;
}
f.flush()?;
f.sync_all()
};
if let Err(e) = write() {
let _ = std::fs::remove_file(&tmp);
return Err(e).with_context(|| format!("writing temp for {out_path:?}"));
}
if let Err(e) = validate(&tmp) {
let _ = std::fs::remove_file(&tmp); return Err(e);
}
finalize_replace(&tmp, out_path).with_context(|| format!("publishing {out_path:?}"))
}
fn file_hash_hex(path: &Path) -> Result<String> {
use blake2::digest::{Update, VariableOutput};
use std::io::Read;
let mut f = std::io::BufReader::new(
File::open(path).with_context(|| format!("cannot open input {path:?} to hash"))?,
);
let mut hasher = blake2::Blake2bVar::new(32).expect("blake2b-32");
let mut buf = [0u8; 1 << 16];
loop {
let n = f.read(&mut buf)?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
let mut out = [0u8; 32];
hasher
.finalize_variable(&mut out)
.expect("blake2b-32 output");
Ok(out.iter().map(|b| format!("{b:02x}")).collect())
}
pub fn meta_from_manifest(path: &Path) -> Result<Vec<(String, String)>> {
let raw: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(path).with_context(|| format!("cannot read manifest {path:?}"))?,
)
.with_context(|| format!("manifest {path:?} is not valid JSON"))?;
let obj = raw.as_object().context("manifest must be a JSON object")?;
let mut pairs = Vec::new();
for (k, v) in obj {
let val = match v {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
};
pairs.push((k.clone(), val));
}
let get = |key: &str| pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
let country = get("country")
.context("manifest is missing `country`")?
.to_lowercase();
let layer = get("layer").context("manifest is missing `layer` (addresses|poi)")?;
if !matches!(layer.as_str(), "addresses" | "poi") {
bail!("manifest `layer` must be `addresses` or `poi`, got {layer:?}");
}
pairs.retain(|(k, _)| k != "country");
pairs.push(("country".to_string(), country));
for key in ["license", "source_release"] {
let present = pairs.iter().any(|(k, v)| k == key && !v.trim().is_empty());
if !present {
bail!("manifest is missing required key `{key}` (v6 provenance)");
}
}
for k in [
"meta_schema",
"builder_version",
"builder_target",
"builder_git",
] {
pairs.retain(|(kk, _)| kk != k);
}
pairs.push(("meta_schema".to_string(), "1".to_string()));
pairs.push((
"builder_version".to_string(),
env!("CARGO_PKG_VERSION").to_string(),
));
pairs.push((
"builder_target".to_string(),
format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
));
pairs.push((
"builder_git".to_string(),
option_env!("GRIDPIN_GIT_SHA")
.unwrap_or("unknown")
.to_string(),
));
if pairs.len() > 1024 {
bail!(
"manifest has {} keys — SEC_META allows at most 1024",
pairs.len()
);
}
for (k, v) in &pairs {
if k.len() > u16::MAX as usize {
let preview: String = k.chars().take(32).collect();
bail!("manifest key {preview:?}... is longer than 65535 bytes");
}
if v.len() > u32::MAX as usize {
bail!("manifest value for {k:?} is longer than 4 GiB");
}
}
Ok(pairs)
}
#[allow(unused_assignments)]
pub fn build(
input: &Path,
out_path: &Path,
model_path: Option<&Path>,
rank_path: Option<&Path>,
rules_dir: Option<&Path>,
mark: Option<&str>,
meta_path: Option<&Path>,
) -> Result<()> {
let meta_sec: Vec<u8> = match meta_path {
Some(p) => {
let mut pairs = meta_from_manifest(p)?;
pairs.retain(|(k, _)| k != "input_blake2b256");
pairs.push(("input_blake2b256".to_string(), file_hash_hex(input)?));
if pairs.len() > 1024 {
bail!(
"manifest yields {} SEC_META pairs after provenance stamping — the decoder caps at 1024",
pairs.len()
);
}
encode_meta(&pairs)
}
None if std::env::var("GRIDPIN_REQUIRE_META").is_ok() => bail!(
"refusing to build a release sheet without --meta (provenance/identity required); \
pass --meta <manifest.json>"
),
None => {
eprintln!("warning: building WITHOUT --meta — the sheet will carry no provenance/country identity");
Vec::new()
}
};
let t0 = std::time::Instant::now();
let file = File::open(input).with_context(|| format!("cannot open {input:?}"))?;
let is_gz = input.extension().is_some_and(|e| e == "gz");
let compressed_len = if is_gz {
file.metadata().map(|m| m.len()).unwrap_or(0)
} else {
0
};
let reader: Box<dyn std::io::Read> = if is_gz {
Box::new(LimitReader::new(
flate2::read::GzDecoder::new(file),
compressed_len,
))
} else {
Box::new(LimitReader::new(file, 0))
};
let mut rdr = csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(std::io::BufReader::with_capacity(1 << 20, reader));
let headers = rdr.headers()?.clone();
let col = |name: &str| -> Result<usize> {
headers
.iter()
.position(|h| h == name)
.with_context(|| format!("CSV is missing column {name}"))
};
let c_voie_n = col("nom_voie_norm")?;
let c_insee = col("code_insee")?;
let c_commune_n = col("nom_commune_norm")?;
let c_cp = col("code_postal")?;
let c_numero = col("numero")?;
let c_rep = col("rep")?;
let c_lon = col("lon")?;
let c_lat = col("lat")?;
let c_voie = col("nom_voie")?;
let c_commune = col("nom_commune")?;
let c_prov: Option<usize> = headers.iter().position(|h| h == "provincia_norm");
let c_cp_disp: Option<usize> = headers.iter().position(|h| h == "code_postal_display");
let mut streets_fst = MapBuilder::memory();
let mut streets_meta: Vec<u8> = Vec::new();
let mut house_blocks: Vec<u8> = Vec::new();
let mut names: Vec<u8> = Vec::new();
let mut communes_meta: Vec<u8> = Vec::new();
let mut commune_house_count: Vec<u32> = Vec::new();
let mut commune_lat_sum: Vec<f64> = Vec::new();
let mut commune_lon_sum: Vec<f64> = Vec::new();
let mut commune_ids: HashMap<String, u32> = HashMap::new(); let mut commune_names: Vec<(String, u32)> = Vec::new(); let mut reps: Vec<String> = Vec::new();
let mut rep_ids: HashMap<String, u32> = HashMap::new();
let mut cells: Vec<(u32, u32)> = Vec::new(); let mut word_post: HashMap<String, Vec<u32>> = HashMap::new();
let mut cur_key: Option<(String, String)> = None; let mut cur_houses: Vec<House> = Vec::new();
let mut cur_display = String::new();
let mut cur_commune_id = 0u32;
let mut cur_cps: HashMap<String, u32> = HashMap::new(); let mut street_id = 0u64;
let mut n = Counts::default();
macro_rules! flush_street {
() => {
if let Some((voie, insee)) = cur_key.take() {
if cur_houses.is_empty() {
cur_cps.clear();
n.empty_streets += 1;
let _ = (&voie, &insee);
} else {
let (mut sla, mut slo) = (0f64, 0f64);
for h in &cur_houses {
sla += h.lat;
slo += h.lon;
}
let cnt = cur_houses.len() as f64;
let lat_c = (sla / cnt * 1e7).round() as i32;
let lon_c = (slo / cnt * 1e7).round() as i32;
cells.push((cell_of(sla / cnt, slo / cnt), street_id as u32));
let cp_disp: String = cur_cps
.iter()
.filter(|(p, _)| !p.is_empty())
.max_by_key(|(p, c)| (**c, std::cmp::Reverse((*p).clone())))
.map(|(p, _)| p.clone())
.unwrap_or_default();
let postcode: u32 = cp_disp
.chars()
.take_while(|c| c.is_ascii_digit())
.collect::<String>()
.parse()
.unwrap_or(0);
let house_off = house_blocks.len() as u64;
let house_accurate = write_house_block(
&mut house_blocks,
&mut names,
&cur_houses,
lat_c,
lon_c,
&voie,
&insee,
)?;
let name_off = push_name(&mut names, &cur_display)?;
let pc_disp_off: u32 = if house_accurate {
PC_DISP_AMBIGUOUS
} else if cp_disp.is_empty() {
0
} else {
push_name(&mut names, &cp_disp)?
};
streets_meta.extend_from_slice(&lat_c.to_le_bytes());
streets_meta.extend_from_slice(&lon_c.to_le_bytes());
streets_meta.extend_from_slice(&cur_commune_id.to_le_bytes());
streets_meta.extend_from_slice(&postcode.to_le_bytes());
streets_meta.extend_from_slice(&name_off.to_le_bytes());
streets_meta.extend_from_slice(&house_off.to_le_bytes());
streets_meta.extend_from_slice(&(cur_houses.len() as u32).to_le_bytes());
streets_meta.extend_from_slice(&pc_disp_off.to_le_bytes());
let mut key = Vec::with_capacity(voie.len() + 1 + insee.len());
key.extend_from_slice(voie.as_bytes());
key.push(KEY_SEP);
key.extend_from_slice(insee.as_bytes());
streets_fst.insert(&key, street_id)?;
for w in voie.split(|c: char| !c.is_alphanumeric()) {
if w.chars().count() >= 3 {
word_post.entry(w.to_string()).or_default().push(street_id as u32);
let pk = crate::norm::phonetic_key(w);
if pk.chars().count() >= 3 && pk != w {
word_post.entry(format!("~{pk}")).or_default().push(street_id as u32);
}
}
}
street_id += 1;
n.streets += 1;
if let Some(cnt) = commune_house_count.get_mut(cur_commune_id as usize) {
*cnt = cnt.saturating_add(cur_houses.len() as u32);
}
let ci = cur_commune_id as usize;
if ci < commune_lat_sum.len() {
commune_lat_sum[ci] += lat_c as f64 * cur_houses.len() as f64;
commune_lon_sum[ci] += lon_c as f64 * cur_houses.len() as f64;
}
cur_houses.clear();
cur_cps.clear();
}
}
};
}
for rec in rdr.records() {
let rec = rec?;
let voie_n = rec.get(c_voie_n).unwrap_or("");
let insee = rec.get(c_insee).unwrap_or("");
if voie_n.is_empty() || insee.is_empty() {
continue;
}
let lat: f64 = rec.get(c_lat).unwrap_or("").parse().unwrap_or(f64::NAN);
let lon: f64 = rec.get(c_lon).unwrap_or("").parse().unwrap_or(f64::NAN);
if !(lat.is_finite() && lon.is_finite() && lat.abs() <= 90.0 && lon.abs() <= 180.0) {
n.bad_coords += 1;
continue;
}
let num_raw = rec.get(c_numero).unwrap_or("");
let numero: u32 = if num_raw.is_empty() {
0
} else {
match num_raw.parse() {
Ok(v) => v,
Err(_) => {
n.bad_number += 1;
continue;
}
}
};
let key_changed = match &cur_key {
Some((v, i)) => v != voie_n || i != insee,
None => true,
};
if key_changed {
flush_street!();
let insee_s = insee.to_string();
cur_commune_id = match commune_ids.get(&insee_s) {
Some(id) => *id,
None => {
let id = commune_ids.len() as u32;
commune_ids.insert(insee_s.clone(), id);
let cname = rec.get(c_commune).unwrap_or("");
let cname_n = rec.get(c_commune_n).unwrap_or("");
let name_off = push_name(&mut names, cname)?;
let mut insee_b = [0u8; 8];
let ib = insee_s.as_bytes();
if ib.len() > 8 {
bail!(
"code_insee {insee_s:?} is {} bytes — the format stores 8",
ib.len()
);
}
insee_b[..ib.len()].copy_from_slice(ib);
communes_meta.extend_from_slice(&insee_b);
communes_meta.extend_from_slice(&name_off.to_le_bytes());
communes_meta.extend_from_slice(&0u32.to_le_bytes()); commune_house_count.push(0);
commune_lat_sum.push(0.0);
commune_lon_sum.push(0.0);
commune_names.push((cname_n.to_string(), id));
if let Some(cp) = c_prov {
for prov in rec.get(cp).unwrap_or("").split('|') {
if !prov.is_empty() && prov != cname_n {
commune_names.push((prov.to_string(), id));
}
}
}
n.communes += 1;
id
}
};
cur_key = Some((voie_n.to_string(), insee.to_string()));
cur_display = rec.get(c_voie).unwrap_or("").to_string();
}
let rep_s = rec.get(c_rep).unwrap_or("");
let rep_id = if rep_s.is_empty() {
0u32
} else {
match rep_ids.get(rep_s) {
Some(id) => *id,
None => {
let id = (reps.len() + 1) as u32;
reps.push(rep_s.to_string());
rep_ids.insert(rep_s.to_string(), id);
id
}
}
};
let cp_disp_s: &str = c_cp_disp.and_then(|c| rec.get(c)).unwrap_or("");
let cp_num: &str = match rec.get(c_cp).unwrap_or("") {
"0" => "",
s => s,
};
let cp_key: &str = if plausible_pc(cp_disp_s) {
cp_disp_s
} else {
cp_num
};
if let Some(c) = cur_cps.get_mut(cp_key) {
*c += 1;
} else {
cur_cps.insert(cp_key.to_string(), 1);
}
cur_houses.push(House {
numero,
rep_id,
lat,
lon,
postcode: cp_key.to_string(),
});
n.rows += 1;
}
flush_street!();
for (id, &cnt) in commune_house_count.iter().enumerate() {
let off = id * COMMUNE_META_SIZE + 12;
communes_meta[off..off + 4].copy_from_slice(&cnt.to_le_bytes());
}
let mut commune_coords: Vec<u8> = Vec::with_capacity(commune_house_count.len() * 8);
for id in 0..commune_house_count.len() {
let cnt = commune_house_count[id].max(1) as f64;
let lat_c = (commune_lat_sum[id] / cnt).round() as i32;
let lon_c = (commune_lon_sum[id] / cnt).round() as i32;
commune_coords.extend_from_slice(&lat_c.to_le_bytes());
commune_coords.extend_from_slice(&lon_c.to_le_bytes());
}
let streets_fst_bytes = streets_fst.into_inner()?;
const WORD_POST_CAP: usize = 16384; let mut words_sorted: Vec<(String, Vec<u32>)> = word_post.into_iter().collect();
words_sorted.sort_by(|a, b| a.0.cmp(&b.0)); let mut words_fst = MapBuilder::memory();
let mut word_postings: Vec<u8> = Vec::new();
for (w, mut ids) in words_sorted {
ids.sort_unstable();
ids.dedup();
if ids.len() > WORD_POST_CAP {
ids.truncate(WORD_POST_CAP);
}
let off = word_postings.len() as u64;
write_varint(&mut word_postings, ids.len() as u64);
let mut prev = 0u32;
for id in ids {
write_varint(&mut word_postings, (id - prev) as u64);
prev = id;
}
words_fst.insert(w.as_bytes(), off)?;
}
let words_fst_bytes = words_fst.into_inner()?;
commune_names.sort();
let mut communes_fst = MapBuilder::memory();
let mut postings: Vec<u8> = Vec::new();
let mut i = 0;
while i < commune_names.len() {
let mut j = i + 1;
while j < commune_names.len() && commune_names[j].0 == commune_names[i].0 {
j += 1;
}
let start = (postings.len() / 4) as u64;
for cn in &commune_names[i..j] {
postings.extend_from_slice(&cn.1.to_le_bytes());
}
let count = (j - i) as u64;
if !commune_names[i].0.is_empty() {
communes_fst.insert(commune_names[i].0.as_bytes(), (start << 16) | count)?;
}
i = j;
}
let communes_fst_bytes = communes_fst.into_inner()?;
let mut reps_sec: Vec<u8> = Vec::new();
reps_sec.extend_from_slice(&(reps.len() as u32).to_le_bytes());
for r in &reps {
let b = r.as_bytes();
if b.len() > 255 {
bail!("rep/house-number suffix {r:?} is {} bytes — the reps section encodes length in one u8 (max 255)", b.len());
}
reps_sec.push(b.len() as u8);
reps_sec.extend_from_slice(b);
}
cells.sort_unstable();
let mut cells_dir: Vec<u8> = Vec::new();
let mut cells_post: Vec<u8> = Vec::new();
{
let mut i = 0;
while i < cells.len() {
let mut j = i;
let start = (cells_post.len() / 4) as u32;
while j < cells.len() && cells[j].0 == cells[i].0 {
cells_post.extend_from_slice(&cells[j].1.to_le_bytes());
j += 1;
}
cells_dir.extend_from_slice(&cells[i].0.to_le_bytes());
cells_dir.extend_from_slice(&start.to_le_bytes());
cells_dir.extend_from_slice(&((j - i) as u32).to_le_bytes());
i = j;
}
}
let mut cells_sec: Vec<u8> = Vec::new();
cells_sec.extend_from_slice(&((cells_dir.len() / 12) as u32).to_le_bytes());
cells_sec.extend_from_slice(&cells_dir);
cells_sec.extend_from_slice(&cells_post);
let model_sec: Vec<u8> = match model_path {
Some(p) => {
let bytes =
std::fs::read(p).with_context(|| format!("cannot read parser model {p:?}"))?;
if !crate::ml::Parser::section_is_valid(&bytes) {
bail!("parser model {p:?} is not a valid SEC_PARSER section — it would be silently dropped at open time");
}
bytes
}
None => Vec::new(),
};
let rank_sec: Vec<u8> = match rank_path {
Some(p) => {
let bytes =
std::fs::read(p).with_context(|| format!("cannot read ranking weights {p:?}"))?;
if !crate::query::rank_section_is_valid(&bytes) {
bail!("ranking weights {p:?} are not a valid SEC_RANK section — they would be silently dropped at open time");
}
bytes
}
None => Vec::new(),
};
let rules_sec: Vec<u8> = match rules_dir {
Some(d) => {
#[allow(unused_mut)]
let mut entries = crate::rules::entries_from_tsv_dir(d)
.with_context(|| format!("cannot read rules from {d:?}"))?;
eprintln!("rules-in-data: {} entries from {:?}", entries.len(), d);
#[cfg(feature = "watermark")]
if let Some(m) = mark {
entries.sort();
crate::mark::apply_to_rule_entries(&mut entries, m);
}
crate::rules::serialize_entries(&entries)
}
None => Vec::new(),
};
#[cfg(feature = "watermark")]
let mark_sec: Vec<u8> = match mark {
Some(m) => {
names.extend_from_slice(&crate::mark::tail_bytes(m));
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
eprintln!("watermark: \"{m}\" applied");
crate::mark::build_section(m, ts)
}
None => Vec::new(),
};
#[cfg(not(feature = "watermark"))]
let mark_sec: Vec<u8> = {
if mark.is_some() {
eprintln!("note: --mark ignored (this build has no watermark support)");
}
Vec::new()
};
let sections: Vec<(u8, &Vec<u8>)> = vec![
(SEC_COMMUNES_FST as u8, &communes_fst_bytes),
(SEC_COMMUNES_META as u8, &communes_meta),
(SEC_COMMUNE_POSTINGS as u8, &postings),
(SEC_STREETS_FST as u8, &streets_fst_bytes),
(SEC_STREETS_META as u8, &streets_meta),
(SEC_HOUSE_BLOCKS as u8, &house_blocks),
(SEC_NAMES as u8, &names),
(SEC_REPS as u8, &reps_sec),
(SEC_CELLS as u8, &cells_sec),
(SEC_PARSER as u8, &model_sec),
(SEC_RANK as u8, &rank_sec),
(SEC_WORDS as u8, &words_fst_bytes),
(SEC_WORD_POSTINGS as u8, &word_postings),
(SEC_COMMUNE_COORDS as u8, &commune_coords),
(SEC_RULES as u8, &rules_sec),
(SEC_MARK as u8, &mark_sec),
(SEC_META as u8, &meta_sec),
];
let mut toc: Vec<(u8, u64, u64)> = Vec::new();
let mut off = header_size() as u64;
for (id, data) in §ions {
toc.push((*id, off, data.len() as u64));
off += data.len() as u64;
}
let mut header = Vec::new();
write_header(&mut header, &toc);
let chunks: Vec<&[u8]> = std::iter::once(header.as_slice())
.chain(sections.iter().map(|(_, d)| d.as_slice()))
.collect();
write_atomic_validated(out_path, &chunks, |tmp| {
crate::query::Index::open(tmp).map(|_| ()).map_err(|e| {
anyhow::anyhow!(
"build produced a sheet the reader rejects ({e}) — degenerate input? (0 usable rows / all rows dropped)"
)
})
})?;
let total = off as f64 / 1e6;
eprintln!(
"== build finished in {:.1} s ==",
t0.elapsed().as_secs_f64()
);
eprintln!(
"rows: {} · streets: {} · communes: {} · rep dictionary: {}",
n.rows,
n.streets,
n.communes,
reps.len()
);
if n.empty_streets > 0 {
eprintln!(
"dropped {} street(s) whose every row had unparseable coordinates",
n.empty_streets
);
}
let mb = |b: &Vec<u8>| b.len() as f64 / 1e6;
eprintln!("sections, MB:");
eprintln!(" communes_fst {:8.1}", mb(&communes_fst_bytes));
eprintln!(" communes_meta {:8.1}", mb(&communes_meta));
eprintln!(" commune_postings {:8.1}", mb(&postings));
eprintln!(" streets_fst {:8.1}", mb(&streets_fst_bytes));
eprintln!(" streets_meta {:8.1}", mb(&streets_meta));
eprintln!(" house_blocks {:8.1}", mb(&house_blocks));
eprintln!(" names {:8.1}", mb(&names));
eprintln!(" reps {:8.3}", mb(&reps_sec));
eprintln!(" cells {:8.1}", mb(&cells_sec));
eprintln!(" parser_model {:8.1}", mb(&model_sec));
eprintln!(" rank {:8.3}", mb(&rank_sec));
eprintln!("TOTAL: {total:.1} MB -> {out_path:?}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
static CAP_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
const HDR: &str = "nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n";
fn tag_of(_rows: &str) -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static N: AtomicU64 = AtomicU64::new(0);
N.fetch_add(1, Ordering::Relaxed)
}
fn build_csv(rows: &str) -> Result<std::path::PathBuf> {
let dir = std::env::temp_dir().join(format!("gridpin-builder-test-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let tag = tag_of(rows);
let src = dir.join(format!("in-{tag}.csv"));
let out = dir.join(format!("out-{tag}.bin"));
std::fs::write(&src, format!("{HDR}{rows}"))?;
build(&src, &out, None, None, None, None, None)?;
Ok(out)
}
fn test_house(numero: u32, postcode: &str) -> House {
House {
numero,
rep_id: 0,
lat: 0.0,
lon: 0.0,
postcode: postcode.to_string(),
}
}
#[test]
fn v7_sparse_house_postcode_block_is_exact_and_deterministic() {
let houses = [test_house(10, "1012AB"), test_house(12, "1012AA")];
let mut names = vec![1, b'x'];
let mut block = Vec::new();
assert!(write_house_block(&mut block, &mut names, &houses, 0, 0, "street", "001").unwrap());
assert_eq!(
names,
[&[1, b'x'][..], &[6], b"1012AA", &[6], b"1012AB"].concat()
);
assert_eq!(
block,
vec![
2, 2, 0, 0, 0, 9, 0, 0, 0, 10, 0, 0, 0, 2, 2, 0, 0, 0, 1, ]
);
let mut names2 = vec![1, b'x'];
let mut block2 = Vec::new();
write_house_block(&mut block2, &mut names2, &houses, 0, 0, "street", "001").unwrap();
assert_eq!(names2, names);
assert_eq!(block2, block);
}
#[test]
fn v7_missing_plus_known_uses_sentinel_grammar_but_uniform_values_do_not() {
let mut names = vec![1, b'x'];
let mut block = Vec::new();
assert!(write_house_block(
&mut block,
&mut names,
&[test_house(1, ""), test_house(2, "1012AA")],
0,
0,
"street",
"001",
)
.unwrap());
assert_eq!(
block,
vec![
1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, ]
);
for postcode in ["", "1012AA"] {
let mut uniform_names = vec![1, b'x'];
let mut uniform_block = Vec::new();
assert!(!write_house_block(
&mut uniform_block,
&mut uniform_names,
&[test_house(1, postcode), test_house(2, postcode)],
0,
0,
"street",
"001",
)
.unwrap());
assert_eq!(
uniform_block,
vec![1, 0, 0, 0, 1, 0, 0, 0],
"all-missing and one-known-value streets keep the old four-varint grammar"
);
assert_eq!(uniform_names, vec![1, b'x']);
}
}
#[test]
fn v7_missing_plus_known_build_sets_sentinel_and_house_ids() {
let out = build_csv(
"pc mix,001,ville,,1,,1.0,1.0,Pc Mix,Ville\n\
pc mix,001,ville,1012AA,2,,1.1,1.1,Pc Mix,Ville\n",
)
.expect("mixed missing/known postcode sheet builds and self-checks");
let data = std::fs::read(out).unwrap();
let sections = parse_sections(&data).unwrap();
let (streets_off, streets_len) = sections[SEC_STREETS_META];
assert_eq!(streets_len, STREET_META_SIZE as u64);
let street = &data[streets_off as usize..(streets_off + streets_len) as usize];
assert_eq!(read_u32(street, 32), PC_DISP_AMBIGUOUS);
let house_off = read_u64(street, 20) as usize;
let (blocks_off, blocks_len) = sections[SEC_HOUSE_BLOCKS];
let blocks = &data[blocks_off as usize..(blocks_off + blocks_len) as usize];
let mut p = house_off;
assert_eq!(strict_varint(blocks, &mut p), Some(1));
p += 4; let mut ids = Vec::new();
for _ in 0..2 {
for _ in 0..4 {
strict_varint(blocks, &mut p).expect("four legacy house fields");
}
ids.push(strict_varint(blocks, &mut p).expect("v7 local postcode id"));
}
assert_eq!(ids, vec![0, 1]);
}
#[test]
fn a_rejected_rebuild_preserves_the_last_known_good_sheet() {
let good = build_csv("zzq good,001,ville,10000,1,,7.42,43.73,Zzq Good,Ville\n")
.expect("good build");
let dir = good.parent().unwrap();
let target = dir.join("lastknowngood.bin");
std::fs::copy(&good, &target).unwrap();
let before = std::fs::read(&target).unwrap();
assert!(
crate::query::Index::open(&target).is_ok(),
"precondition: the target opens"
);
let dir2 = std::env::temp_dir().join(format!("gridpin-h08r6-{}", std::process::id()));
std::fs::create_dir_all(&dir2).unwrap();
let _scratch2 = crate::scratch::Scratch::keep(&dir2);
let empty = dir2.join("empty.csv");
std::fs::write(&empty, HDR).unwrap();
let err = build(&empty, &target, None, None, None, None, None)
.expect_err("a degenerate rebuild must fail");
assert!(
err.to_string().contains("reader rejects") || err.to_string().contains("degenerate"),
"clear self-check error, got: {err}"
);
let after = std::fs::read(&target).unwrap();
assert_eq!(
before, after,
"the last-known-good sheet is byte-for-byte unchanged after a rejected rebuild"
);
assert!(
crate::query::Index::open(&target).is_ok(),
"and it still opens"
);
}
#[test]
fn empty_display_name_is_legal_not_bricked() {
let out = build_csv("zzq place,001,ville,10000,1,,7.42,43.73,,Ville\n")
.expect("a blank display name is legal and must build+self-check");
let idx = crate::query::Index::open(&out).expect("and it opens");
assert!(
!idx.query("zzq place 1 ville", 1).is_empty(),
"and it answers"
);
}
#[test]
fn mid_sheet_zeroed_record_is_rejected_not_only_sampled() {
let mut rows = String::new();
for i in 0..400 {
rows.push_str(&format!(
"zzqstreet{i:03},001,ville,10000,1,,7.42,43.73,ZzqStreet{i:03},Ville\n"
));
}
let out = build_csv(&rows).expect("build");
let mut data = std::fs::read(&out).unwrap();
let nsec = data[5] as usize;
let (mut off, mut len) = (0usize, 0usize);
for i in 0..nsec {
let p = 6 + i * 17;
if data[p] as usize == crate::index::SEC_STREETS_META {
off = u64::from_le_bytes(data[p + 1..p + 9].try_into().unwrap()) as usize;
len = u64::from_le_bytes(data[p + 9..p + 17].try_into().unwrap()) as usize;
}
}
let rec = 200 * crate::index::STREET_META_SIZE;
assert!(rec < len, "record 200 exists");
for b in &mut data[off + rec..off + rec + crate::index::STREET_META_SIZE] {
*b = 0;
}
let mutant = out.parent().unwrap().join("mut-mid-zeroed.bin");
std::fs::write(&mutant, &data).unwrap();
assert!(
crate::query::Index::open(&mutant).is_err(),
"a zeroed mid-sheet record must be rejected (all records checked, not sampled)"
);
}
#[test]
fn deleting_the_word_postings_toc_entry_is_rejected() {
let out = build_csv("zzq bazaar,001,ville,10000,1,,7.42,43.73,Zzq Bazaar,Ville\n")
.expect("build");
let clean = std::fs::read(&out).unwrap();
let nsec = clean[5] as usize;
let mut data = Vec::new();
data.extend_from_slice(&clean[0..5]);
data.push((nsec - 1) as u8); let mut body_start = 6 + nsec * 17;
for i in 0..nsec {
let p = 6 + i * 17;
if clean[p] as usize != crate::index::SEC_WORD_POSTINGS {
data.extend_from_slice(&clean[p..p + 17]);
}
}
let _ = &mut body_start;
data.extend_from_slice(&clean[6 + nsec * 17..]);
let dir = out.parent().unwrap();
let mutant = dir.join("mut-no-postings-toc.bin");
std::fs::write(&mutant, &data).unwrap();
assert!(
crate::query::Index::open(&mutant).is_err(),
"a sheet missing the word_postings TOC entry must be rejected, not silently lose fuzzy"
);
}
#[test]
fn zeroed_word_postings_payload_is_rejected_at_open() {
let out = build_csv("zzq bazaar,001,ville,10000,1,,7.42,43.73,Zzq Bazaar,Ville\n")
.expect("build");
let mut data = std::fs::read(&out).unwrap();
let nsec = data[5] as usize;
let mut zeroed = false;
for i in 0..nsec {
let p = 6 + i * 17;
if data[p] as usize == crate::index::SEC_WORD_POSTINGS {
let off = u64::from_le_bytes(data[p + 1..p + 9].try_into().unwrap()) as usize;
let len = u64::from_le_bytes(data[p + 9..p + 17].try_into().unwrap()) as usize;
assert!(len > 0, "precondition: this sheet has real postings");
data[off..off + len].fill(0); zeroed = true;
}
}
assert!(zeroed, "precondition: found the section to zero");
let dir = out.parent().unwrap();
let mutant = dir.join("mut-zeroed-postings.bin");
std::fs::write(&mutant, &data).unwrap();
let err = crate::query::Index::open(&mutant);
assert!(
err.is_err(),
"a zeroed word_postings payload must be rejected at open, not silently lose fuzzy"
);
let mut data2 = std::fs::read(&out).unwrap();
for i in 0..nsec {
let p = 6 + i * 17;
if data2[p] as usize == crate::index::SEC_WORD_POSTINGS {
let off = u64::from_le_bytes(data2[p + 1..p + 9].try_into().unwrap()) as usize;
data2[off] = 0x7f; }
}
let mutant2 = dir.join("mut-truncated-postings.bin");
std::fs::write(&mutant2, &data2).unwrap();
assert!(
crate::query::Index::open(&mutant2).is_err(),
"an oversized count/truncated list must be rejected at open"
);
}
#[test]
fn continuation_varint_at_eof_in_word_postings_is_rejected() {
let out = build_csv("zzq bazaar,001,ville,10000,1,,7.42,43.73,Zzq Bazaar,Ville\n")
.expect("build");
let mut data = std::fs::read(&out).unwrap();
let nsec = data[5] as usize;
let mut mutated = false;
for i in 0..nsec {
let p = 6 + i * 17;
if data[p] as usize == crate::index::SEC_WORD_POSTINGS {
let off = u64::from_le_bytes(data[p + 1..p + 9].try_into().unwrap()) as usize;
let len = u64::from_le_bytes(data[p + 9..p + 17].try_into().unwrap()) as usize;
assert!(len >= 2, "precondition: real postings");
data[off + len - 1] = 0x80; mutated = true;
}
}
assert!(mutated, "precondition: found the section");
let dir = out.parent().unwrap();
let mutant = dir.join("mut-eof-varint.bin");
std::fs::write(&mutant, &data).unwrap();
assert!(
crate::query::Index::open(&mutant).is_err(),
"a continuation varint at EOF must be rejected at open, not decoded as 0"
);
}
#[test]
fn short_word_street_builds_and_answers_no_false_reject() {
let out = build_csv("yu li,001,ville,10000,1,,7.42,43.73,Yu Li,Ville\n").expect("build");
let idx = crate::query::Index::open(&out).expect("a legal short-word sheet must open");
assert!(!idx.query("yu li 1 ville", 1).is_empty(), "and it answers");
}
#[test]
fn degenerate_input_fails_at_build_not_at_open() {
let err = build_csv("").expect_err("an empty input must not produce a sheet");
let msg = err.to_string();
assert!(
msg.contains("reader rejects") || msg.contains("rows") || msg.contains("empty"),
"clear degenerate-input error, got: {msg}"
);
}
#[test]
fn zeroed_section_content_and_swapped_ids_are_rejected_at_open() {
let out = build_csv("zzq bazaar,001,ville,10000,1,,7.42,43.73,Zzq Bazaar,Ville\n")
.expect("build");
let clean = std::fs::read(&out).unwrap();
let dir = out.parent().unwrap();
let nsec = clean[5] as usize;
let find = |data: &[u8], id: u8| -> (usize, u64, u64) {
for i in 0..nsec {
let p = 6 + i * 17;
if data[p] == id {
let off = u64::from_le_bytes(data[p + 1..p + 9].try_into().unwrap());
let len = u64::from_le_bytes(data[p + 9..p + 17].try_into().unwrap());
return (p, off, len);
}
}
panic!("section {id} not in TOC");
};
let mut zeroed = clean.clone();
let (_, off, len) = find(&zeroed, crate::index::SEC_STREETS_META as u8);
zeroed[off as usize..(off + len) as usize].fill(0);
let mz = dir.join("mut-zeroed-content.bin");
std::fs::write(&mz, &zeroed).unwrap();
assert!(
crate::query::Index::open(&mz).is_err(),
"zeroed streets_meta content must be rejected, not answer 0,0"
);
let mut swapped = clean.clone();
let (p6, _, _) = find(&swapped, crate::index::SEC_HOUSE_BLOCKS as u8);
let (p7, _, _) = find(&swapped, crate::index::SEC_NAMES as u8);
swapped[p6] = crate::index::SEC_NAMES as u8;
swapped[p7] = crate::index::SEC_HOUSE_BLOCKS as u8;
let ms = dir.join("mut-swapped-ids.bin");
std::fs::write(&ms, &swapped).unwrap();
assert!(
crate::query::Index::open(&ms).is_err(),
"swapped section ids must be rejected, not answer NUL garbage"
);
}
#[test]
fn every_required_section_zeroed_out_is_rejected_at_open() {
let out = build_csv("zzq bazaar,001,ville,10000,1,,7.42,43.73,Zzq Bazaar,Ville\n")
.expect("build must succeed");
let clean = std::fs::read(&out).unwrap();
assert!(
!crate::query::Index::open(&out)
.unwrap()
.query("zzq bazaar 1 ville", 1)
.is_empty(),
"control sheet must answer"
);
let dir = out.parent().unwrap();
let nsec = clean[5] as usize;
for &req in &crate::index::REQUIRED_SECTIONS {
let mut data = clean.clone();
let mut found = false;
for i in 0..nsec {
let p = 6 + i * 17;
if data[p] as usize == req {
data[p + 9..p + 17].copy_from_slice(&0u64.to_le_bytes()); found = true;
break;
}
}
assert!(
found,
"section {req} present in the TOC of a freshly built sheet"
);
let mutant = dir.join(format!("mutant-{req}.bin"));
std::fs::write(&mutant, &data).unwrap();
let err = crate::query::Index::open(&mutant)
.err()
.unwrap_or_else(|| panic!("zeroed required section {req} must fail open"))
.to_string();
assert!(
err.contains("missing or empty"),
"section {req}: clear corruption error, got: {err}"
);
}
}
#[test]
fn street_with_only_bad_coordinates_is_dropped_not_ghosted() {
let out = build_csv(
"bad st,001,ville,10000,1,,x,y,Bad St,Ville\n\
bad st,001,ville,10000,2,,,,Bad St,Ville\n\
good st,001,ville,10000,1,,7.42,43.73,Good St,Ville\n",
)
.expect("build must succeed");
let idx = crate::query::Index::open(&out).expect("open");
assert!(!idx.query("good st 1 ville", 1).is_empty());
assert!(
idx.query("bad st 1 ville", 1).is_empty(),
"ghost street must not exist"
);
}
#[test]
fn unsorted_house_numbers_fail_loudly() {
let err = build_csv(
"rue a,001,ville,10000,5,,7.42,43.73,Rue A,Ville\n\
rue a,001,ville,10000,3,,7.42,43.73,Rue A,Ville\n",
)
.expect_err("must fail");
assert!(err.to_string().contains("not sorted"), "{err}");
}
#[test]
fn open_rejects_a_corrupt_toc_without_aborting() {
let out = build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build");
let mut bytes = std::fs::read(&out).unwrap();
bytes[6] = 200;
let corrupt = out.with_extension("badtoc.bin");
std::fs::write(&corrupt, &bytes).unwrap();
let r = crate::query::Index::open(&corrupt);
assert!(
r.is_err(),
"a corrupt TOC must return Err from open, not open a broken sheet"
);
}
#[test]
fn gz_decompression_bomb_is_rejected_streaming() {
use std::io::Write as _;
let dir = std::env::temp_dir().join(format!("gridpin-bomb-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let src = dir.join("bomb.csv.gz");
let mut enc = flate2::write::GzEncoder::new(
std::fs::File::create(&src).unwrap(),
flate2::Compression::best(),
);
enc.write_all(b"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n").unwrap();
for _ in 0..1000 {
enc.write_all(b"rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n")
.unwrap();
}
enc.finish().unwrap();
let out = dir.join("bomb.bin");
let _cap_guard = CAP_ENV_LOCK.lock().unwrap();
std::env::set_var("GRIDPIN_MAX_UNCOMPRESSED_BYTES", "4096");
let res = build(&src, &out, None, None, None, None, None);
std::env::remove_var("GRIDPIN_MAX_UNCOMPRESSED_BYTES");
let err = res.expect_err("an over-cap decompressed stream must fail the build");
assert!(
err.to_string().contains("decompress") || err.to_string().contains("cap"),
"{err}"
);
}
#[test]
fn a_large_under_cap_gz_input_still_builds() {
use std::io::Write as _;
let _cap_guard = CAP_ENV_LOCK.lock().unwrap();
let dir = std::env::temp_dir().join(format!("gridpin-m10-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let src = dir.join("big.csv.gz");
let mut enc = flate2::write::GzEncoder::new(
std::fs::File::create(&src).unwrap(),
flate2::Compression::fast(),
);
enc.write_all(HDR.as_bytes()).unwrap();
for n in 1..=20_000 {
writeln!(enc, "rue a,001,ville,10000,{n},,7.42,43.73,Rue A,Ville").unwrap();
}
enc.finish().unwrap();
let out = dir.join("big.bin");
build(&src, &out, None, None, None, None, None).expect("a large under-cap gz builds fine");
let idx = crate::query::Index::open(&out).unwrap();
assert!(
!idx.query("rue a 1 ville", 1).is_empty(),
"the built sheet answers"
);
}
#[test]
fn cascade_precedence_matrix_and_structured_freeform_parity() {
use crate::query::{query_cascade, query_structured_cascade};
let addr_p = build_csv_meta(
"rue de la paix,001,ville,10000,1,,7.42,43.73,Rue de la Paix,Ville\n",
"fr",
"addresses",
);
let poi_p = build_csv_meta(
"zzqcafe gridpin,001,ville,10000,1,,7.43,43.74,ZzqCafe Gridpin,Ville\n",
"fr",
"poi",
);
let addr = crate::query::Index::open_address(&addr_p).unwrap();
let poi = crate::query::Index::open_poi(&poi_p).unwrap();
let flagged =
|hs: &[crate::query::Hit]| hs.first().is_some_and(|h| h.flags.contains(&"poi_layer"));
let ff = query_cascade(&addr, Some(&poi), "rue de la paix 1 ville", 3);
let st = query_structured_cascade(
&addr,
Some(&poi),
"rue de la paix",
Some("1"),
"ville",
None,
3,
);
assert!(
!ff.is_empty() && !st.is_empty(),
"confident address answers on both paths"
);
assert!(
!flagged(&ff) && !flagged(&st),
"a confident address is never overridden by POI"
);
assert_eq!(ff[0].street, st[0].street, "parity: same winner street");
let ff = query_cascade(&addr, Some(&poi), "zzqcafe gridpin ville", 3);
let st =
query_structured_cascade(&addr, Some(&poi), "zzqcafe gridpin", None, "ville", None, 3);
assert!(
flagged(&ff) && flagged(&st),
"both paths escalate to the POI layer"
);
assert_eq!(ff[0].street, st[0].street, "parity: same POI winner");
let stn = query_structured_cascade(
&addr,
Some(&poi),
"zzqcafe gridpin",
Some("99"),
"ville",
None,
3,
);
assert!(
flagged(&stn),
"a structured number does not break POI escalation"
);
let addr_tie = build_csv_meta(
"zzq bazaar,001,ville,10000,1,,7.42,43.73,Zzq Bazaar,Ville\n",
"fr",
"addresses",
);
let poi_tie = build_csv_meta(
"zzq bazaar,001,ville,10000,1,,7.42,43.73,Zzq Bazaar,Ville\n",
"fr",
"poi",
);
let a2 = crate::query::Index::open_address(&addr_tie).unwrap();
let p2 = crate::query::Index::open_poi(&poi_tie).unwrap();
let ff = query_cascade(&a2, Some(&p2), "zzq bazar ville", 3); if !ff.is_empty() {
assert!(
!flagged(&ff),
"an equal-confidence POI must not displace the address (tie keeps address)"
);
}
let st = query_structured_cascade(&a2, Some(&p2), "zzq bazar", None, "ville", None, 3);
if !st.is_empty() {
assert!(
!flagged(&st),
"tie keeps the address on the structured path too"
);
}
let ff = query_cascade(&addr, None, "wwqx never exists 123", 3);
let st = query_structured_cascade(&addr, None, "wwqx never exists", None, "nulle", None, 3);
assert!(
ff.is_empty() || ff[0].precision == "city",
"free-form nonsense yields nothing house-like"
);
assert!(
st.is_empty() || st[0].precision == "city",
"structured nonsense yields nothing house-like"
);
}
#[test]
fn structured_number_reaches_the_poi_escalation_like_freeform() {
use crate::query::{query_cascade, query_structured_cascade};
let addr_p = build_csv_meta(
"rue de la paix,001,ville,10000,1,,7.42,43.73,Rue de la Paix,Ville\n",
"fr",
"addresses",
);
let poi_p = build_csv_meta(
"studio 54,001,ville,10000,1,,7.43,43.74,Studio 54,Ville\n\
studio 55,001,ville,10000,1,,7.44,43.75,Studio 55,Ville\n",
"fr",
"poi",
);
let addr = crate::query::Index::open_address(&addr_p).unwrap();
let poi = crate::query::Index::open_poi(&poi_p).unwrap();
let ff = query_cascade(&addr, Some(&poi), "studio 54 ville", 3);
let st =
query_structured_cascade(&addr, Some(&poi), "studio", Some("54"), "ville", None, 3);
assert!(
!ff.is_empty() && !st.is_empty(),
"both paths escalate to the POI layer"
);
assert_eq!(ff[0].street, "Studio 54", "free-form finds the named place");
assert_eq!(
ff[0].street, st[0].street,
"PARITY: the structured number reaches the POI query — same winner as free-form"
);
assert!(
st[0].flags.contains(&"poi_layer"),
"the structured answer is the POI answer"
);
}
#[test]
fn structured_freeform_parity_holds_for_nl_postcode_forms() {
use crate::query::{query_cascade, query_structured_cascade};
let addr_p = build_csv_meta(
"rue de la paix,001,ville,10000,1,,7.42,43.73,Rue de la Paix,Ville\n",
"fr",
"addresses",
);
let poi_p = build_csv_meta(
"studio 54,001,ville,10000,1,,7.43,43.74,Studio 54,Ville\n\
studio 55,001,ville,10000,1,,7.44,43.75,Studio 55,Ville\n",
"fr",
"poi",
);
let addr = crate::query::Index::open_address(&addr_p).unwrap();
let poi = crate::query::Index::open_poi(&poi_p).unwrap();
for pc in ["1012", "1012 nz"] {
let ff = query_cascade(&addr, Some(&poi), &format!("studio 54 {pc} ville"), 3);
let st = query_structured_cascade(
&addr,
Some(&poi),
"studio",
Some("54"),
"ville",
Some(pc),
3,
);
assert_eq!(
ff.first().map(|h| h.street.clone()),
st.first().map(|h| h.street.clone()),
"parity must hold for postcode form {pc:?} (including both-empty)"
);
}
}
#[test]
fn structured_query_consults_the_poi_cascade() {
let addr_p = build_csv_meta(
"rue de la paix,001,ville,10000,1,,7.42,43.73,Rue de la Paix,Ville\n",
"fr",
"addresses",
);
let poi_p = build_csv_meta(
"zzqcafe gridpin,001,ville,10000,1,,7.43,43.74,ZzqCafe Gridpin,Ville\n",
"fr",
"poi",
);
let addr = crate::query::Index::open_address(&addr_p).unwrap();
let poi = crate::query::Index::open_poi(&poi_p).unwrap();
let hits = crate::query::query_structured_cascade(
&addr,
Some(&poi),
"zzqcafe gridpin",
None,
"ville",
None,
3,
);
assert!(!hits.is_empty(), "a structured POI query returns a result");
assert!(
hits[0].flags.contains(&"poi_layer"),
"answered by the POI layer: {:?}",
hits[0].flags
);
let none = crate::query::query_structured_cascade(
&addr,
None,
"zzqcafe gridpin",
None,
"ville",
None,
3,
);
assert!(
none.iter().all(|h| !h.flags.contains(&"poi_layer")),
"no POI layer -> no poi_layer answer"
);
}
#[test]
fn structured_input_contract_is_bounded_and_honors_k() {
let out = build_csv_meta(
"rue de la paix,001,ville,10000,1,,7.42,43.73,Rue de la Paix,Ville\n",
"fr",
"addresses",
);
let idx = crate::query::Index::open(&out).unwrap();
let no_city = idx.query_structured("rue de la paix", Some("1"), "", None, 3);
assert!(
no_city.len() <= 3,
"k is honored for a city-less structured query"
);
let big = "x ".repeat(5000);
let t0 = std::time::Instant::now();
let huge = idx.query_structured(&big, None, &big, None, 3);
assert!(
t0.elapsed().as_secs() < 2,
"an oversized structured field must not amplify CPU"
);
assert!(
huge.len() <= 3,
"k is honored even for a garbage oversized query"
);
assert!(
!idx.query_structured("rue de la paix", Some("1"), "ville", Some("10000"), 3)
.is_empty(),
"a valid structured query resolves"
);
}
#[test]
fn manifest_requires_license_and_source_release_and_stamps_version() {
let dir = std::env::temp_dir().join(format!("gridpin-m05-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let write = |name: &str, json: &str| {
let p = dir.join(name);
std::fs::write(&p, json).unwrap();
p
};
let e = meta_from_manifest(&write(
"nolic.json",
r#"{"country":"fr","layer":"addresses","source_release":"x"}"#,
))
.unwrap_err();
assert!(e.to_string().contains("license"), "{e}");
let e = meta_from_manifest(&write(
"norel.json",
r#"{"country":"fr","layer":"addresses","license":"x"}"#,
))
.unwrap_err();
assert!(e.to_string().contains("source_release"), "{e}");
let pairs = meta_from_manifest(&write(
"ok.json",
r#"{"country":"fr","layer":"addresses","license":"x","source_release":"y"}"#,
))
.unwrap();
assert!(
pairs.iter().any(|(k, v)| k == "meta_schema" && v == "1"),
"schema stamped"
);
assert!(
pairs.iter().any(|(k, _)| k == "builder_version"),
"builder version stamped"
);
}
#[test]
fn overlong_display_name_is_rejected_not_truncated() {
let long = "a".repeat(256);
let err = build_csv(&format!(
"rue a,001,ville,10000,1,,7.42,43.73,{long},Ville\n"
))
.expect_err("a 256-byte name must fail the build");
assert!(err.to_string().contains("max 255"), "{err}");
}
#[test]
fn huge_query_is_bounded_and_fast() {
use crate::query::{bound_query, MAX_QUERY_BYTES};
let big = "a".repeat(5_000_000);
assert_eq!(bound_query(&big).len(), MAX_QUERY_BYTES, "input is capped");
assert!(
bound_query("rue a 1 ville").len() < MAX_QUERY_BYTES,
"a normal query is untouched"
);
let cyr = "я".repeat(2000); let bounded = bound_query(&cyr);
assert!(bounded.len() <= MAX_QUERY_BYTES && cyr.starts_with(bounded));
let out = build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build");
let idx = crate::query::Index::open(&out).unwrap();
let t0 = std::time::Instant::now();
let hits = idx.query(&big, 5);
assert!(
t0.elapsed().as_secs() < 2,
"a huge query must not amplify CPU"
);
assert!(hits.len() <= 5);
}
#[test]
fn validate_lat_lon_rejects_nonfinite_and_out_of_range() {
use crate::query::validate_lat_lon;
for (la, lo) in [(48.86, 2.33), (-90.0, -180.0), (90.0, 180.0)] {
assert!(
validate_lat_lon(la, lo).is_ok(),
"({la},{lo}) is a valid point"
);
}
for (la, lo) in [
(f64::NAN, 0.0),
(0.0, f64::INFINITY),
(f64::NEG_INFINITY, 0.0),
(91.0, 0.0),
(0.0, 181.0),
(-90.001, 0.0),
] {
assert!(
validate_lat_lon(la, lo).is_err(),
"({la},{lo}) must be rejected"
);
}
}
fn build_csv_meta(rows: &str, country: &str, layer: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("gridpin-builder-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let tag = format!("{country}-{layer}-{}", tag_of(rows));
let src = dir.join(format!("in-{tag}.csv"));
let out = dir.join(format!("out-{tag}.bin"));
let man = dir.join(format!("man-{tag}.json"));
std::fs::write(&src, format!("{HDR}{rows}")).unwrap();
std::fs::write(
&man,
format!(
"{{\"country\": \"{country}\", \"layer\": \"{layer}\", \"license\": \"test\", \"source_release\": \"test\"}}"
),
)
.unwrap();
build(&src, &out, None, None, None, None, Some(&man)).unwrap();
out
}
#[test]
fn check_pair_refuses_mismatched_country_and_layer() {
let fr = crate::query::Index::open(&build_csv_meta(
"rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n",
"fr",
"addresses",
))
.unwrap();
let it = crate::query::Index::open(&build_csv_meta(
"via a,002,roma,00100,1,,12.5,41.9,Via A,Roma\n",
"it",
"addresses",
))
.unwrap();
let frpoi = crate::query::Index::open(&build_csv_meta(
"rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n",
"fr",
"poi",
))
.unwrap();
assert!(
crate::query::check_pair(&fr, &it).is_err(),
"IT layer over FR must fail"
);
assert!(
crate::query::check_pair(&fr, &frpoi).is_ok(),
"FR + FR-poi is a valid pair"
);
assert!(crate::query::check_pair(&fr, &it).is_err());
}
#[test]
fn open_address_refuses_a_poi_sheet_as_the_primary_index() {
let poi = build_csv_meta(
"cafe,001,ville,10000,1,,7.42,43.73,Cafe,Ville\n",
"fr",
"poi",
);
assert!(
crate::query::Index::open_address(&poi).is_err(),
"a POI sheet must not open as the primary address index"
);
let addr = build_csv_meta(
"rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n",
"fr",
"addresses",
);
assert!(
crate::query::Index::open_address(&addr).is_ok(),
"an address sheet opens fine"
);
let bare = build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build");
assert!(
crate::query::Index::open_address(&bare).is_ok(),
"a no-meta sheet opens fine"
);
}
#[test]
fn open_poi_refuses_an_address_sheet_as_a_poi_layer() {
let addr = build_csv_meta(
"rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n",
"fr",
"addresses",
);
assert!(
crate::query::Index::open_poi(&addr).is_err(),
"an address sheet must not open as a POI layer"
);
let poi = build_csv_meta(
"cafe,001,ville,10000,1,,7.42,43.73,Cafe,Ville\n",
"fr",
"poi",
);
assert!(
crate::query::Index::open_poi(&poi).is_ok(),
"a real POI layer opens fine"
);
let bare = build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build");
assert!(
crate::query::Index::open_poi(&bare).is_ok(),
"a no-meta sheet opens fine"
);
}
#[test]
fn every_public_reverse_entry_is_strict_on_bad_coords() {
let out = build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build");
let idx = crate::query::Index::open(&out).unwrap();
for (la, lo) in [
(f64::NAN, 7.42),
(43.73, f64::INFINITY),
(91.0, 0.0),
(0.0, 181.0),
] {
assert!(
idx.try_reverse(la, lo, 5).is_err(),
"try_reverse must error on ({la},{lo})"
);
assert!(
idx.reverse(la, lo, 5).is_err(),
"public reverse is STRICT too on ({la},{lo})"
);
assert!(
idx.reverse_lenient(la, lo, 5).is_empty(),
"the private lenient layer yields nothing on ({la},{lo})"
);
}
assert!(
idx.try_reverse(43.73, 7.42, 5).is_ok(),
"a valid coord is Ok"
);
assert!(
!idx.reverse(43.73, 7.42, 5).unwrap().is_empty(),
"a valid coord near the data still answers"
);
}
#[test]
fn build_validates_parser_and_rank_sections() {
let dir = std::env::temp_dir().join(format!("gridpin-m01-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let src = dir.join("in.csv");
std::fs::write(
&src,
format!("{HDR}rue de test,001,ville,10000,1,,7.42,43.73,Rue de Test,Ville\n"),
)
.unwrap();
let parser = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../ml/parser_v0.bin"));
let rank = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../ml/rank_v0.bin"));
let good = dir.join("good.bin");
build(&src, &good, Some(parser), Some(rank), None, None, None)
.expect("committed models build");
let idx = crate::query::Index::open(&good).unwrap();
assert!(
idx.has_parser(),
"the trained parser survives into the sheet"
);
assert!(
idx.has_rank(),
"the trained ranking survives into the sheet"
);
let bad_rank = dir.join("bad_rank.bin");
std::fs::write(&bad_rank, b"not a GPRK section at all").unwrap();
let out = dir.join("bad.bin");
let err = build(&src, &out, None, Some(&bad_rank), None, None, None).unwrap_err();
assert!(
err.to_string().contains("SEC_RANK"),
"a corrupt --rank must fail the build: {err}"
);
}
#[test]
fn build_rejects_a_manifest_that_overflows_the_meta_cap() {
let dir = std::env::temp_dir().join(format!("gridpin-meta1025-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let src = dir.join("in.csv");
std::fs::write(
&src,
format!("{HDR}rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n"),
)
.unwrap();
let mut m = String::from(
"{\"country\":\"fr\",\"layer\":\"addresses\",\"license\":\"t\",\"source_release\":\"t\"",
);
for i in 0..1016 {
m.push_str(&format!(",\"k{i}\":\"v\""));
}
m.push('}');
let man = dir.join("big.json");
std::fs::write(&man, &m).unwrap();
let out = dir.join("out.bin");
let err = build(&src, &out, None, None, None, None, Some(&man))
.expect_err("a 1025-pair meta must be rejected");
assert!(
err.to_string().contains("1024"),
"must cite the 1024 cap: {err}"
);
}
#[test]
fn reverse_survives_a_corrupt_cell_count_without_oob_panic() {
let out = build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build");
let mut bytes = std::fs::read(&out).unwrap();
assert_eq!(&bytes[0..4], b"GPC0");
let nsec = bytes[5] as usize;
let mut cells_off = None;
let mut p = 6;
for _ in 0..nsec {
let id = bytes[p];
let off = u64::from_le_bytes(bytes[p + 1..p + 9].try_into().unwrap()) as usize;
if id == crate::index::SEC_CELLS as u8 {
cells_off = Some(off);
}
p += 17;
}
let cells_off = cells_off.expect("SEC_CELLS present");
let count_off = cells_off + 4 + 8;
bytes[count_off..count_off + 4].copy_from_slice(&u32::MAX.to_le_bytes());
let bad = out.with_extension("corruptcell.bin");
std::fs::write(&bad, &bytes).unwrap();
let idx = crate::query::Index::open(&bad).expect("opens (section bounds still valid)");
let _ = idx.reverse(43.73, 7.42, 3); }
#[test]
fn open_rejects_a_present_but_corrupt_parser_section() {
let dir = std::env::temp_dir().join(format!("gridpin-m01open-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let src = dir.join("in.csv");
std::fs::write(
&src,
format!("{HDR}rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n"),
)
.unwrap();
let parser = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../ml/parser_v0.bin"));
let good = dir.join("good.bin");
build(&src, &good, Some(parser), None, None, None, None).unwrap();
assert!(
crate::query::Index::open(&good).unwrap().has_parser(),
"sanity: opens with a parser"
);
let mut bytes = std::fs::read(&good).unwrap();
let pos = bytes
.windows(4)
.position(|w| w == b"GPML")
.expect("parser magic present");
bytes[pos] = b'X'; let bad = dir.join("bad.bin");
std::fs::write(&bad, &bytes).unwrap();
let err = crate::query::Index::open(&bad)
.err()
.expect("corrupt parser must fail open")
.to_string();
assert!(
err.contains("SEC_PARSER"),
"a corrupt parser section must fail open: {err}"
);
}
#[test]
fn build_stamps_input_hash_and_target_provenance() {
let dir = std::env::temp_dir().join(format!("gridpin-m05prov-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let src = dir.join("in.csv");
std::fs::write(
&src,
format!("{HDR}rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n"),
)
.unwrap();
let man = dir.join("man.json");
std::fs::write(
&man,
r#"{"country":"fr","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
let out = dir.join("out.bin");
build(&src, &out, None, None, None, None, Some(&man)).unwrap();
let idx = crate::query::Index::open(&out).unwrap();
let get = |k: &str| {
idx.meta()
.iter()
.find(|(kk, _)| kk == k)
.map(|(_, v)| v.clone())
};
let expect = file_hash_hex(&src).unwrap();
assert_eq!(
get("input_blake2b256").as_deref(),
Some(expect.as_str()),
"input hash recorded"
);
assert!(
get("builder_target").is_some_and(|t| t.contains('-')),
"build target recorded"
);
assert!(get("builder_version").is_some(), "builder version recorded");
assert!(
get("builder_git").is_some(),
"git commit provenance recorded"
);
let out2 = dir.join("out2.bin");
build(&src, &out2, None, None, None, None, Some(&man)).unwrap();
let idx2 = crate::query::Index::open(&out2).unwrap();
let h2 = idx2
.meta()
.iter()
.find(|(k, _)| k == "input_blake2b256")
.map(|(_, v)| v.clone());
assert_eq!(
h2.as_deref(),
Some(expect.as_str()),
"same input -> same hash"
);
}
#[test]
fn finalize_replace_publishes_durably_for_repack_and_batch_paths() {
let dir =
std::env::temp_dir().join(format!("gridpin-m03fin-{}/nested", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(
&std::env::temp_dir().join(format!("gridpin-m03fin-{}", std::process::id())),
);
let tmp = dir.join(".t.tmp");
let out = dir.join("published.bin");
std::fs::write(&tmp, b"repack-bytes").unwrap();
finalize_replace(&tmp, &out).expect("finalize publishes durably");
assert_eq!(std::fs::read(&out).unwrap(), b"repack-bytes");
assert!(!tmp.exists(), "the temp was renamed away");
}
#[test]
fn write_atomic_publishes_into_a_subdir_and_overwrites() {
let dir =
std::env::temp_dir().join(format!("gridpin-m03-{}/nested/deep", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(
&std::env::temp_dir().join(format!("gridpin-m03-{}", std::process::id())),
);
let out = dir.join("f.bin");
write_atomic(&out, &[b"hello ", b"world"]).expect("first write");
assert_eq!(std::fs::read(&out).unwrap(), b"hello world");
write_atomic(&out, &[b"second"]).expect("rename-replace over an existing file");
assert_eq!(std::fs::read(&out).unwrap(), b"second");
}
#[test]
fn bad_coordinates_and_house_numbers_are_dropped_not_coerced() {
let out = build_csv(
"rue ok,001,ville,10000,5,,7.42,43.73,Rue OK,Ville\n\
rue bad,002,ville,10000,7,,999,999,Rue Bad,Ville\n\
rue num,003,ville,10000,abc,,7.42,43.73,Rue Num,Ville\n",
)
.expect("build");
let idx = crate::query::Index::open(&out).unwrap();
let bad = idx.query("rue bad 7 ville", 1);
assert!(
bad.first().is_none_or(|h| h.precision != "house"),
"row with lat/lon 999 must be dropped, not returned as a house"
);
let num = idx.query("rue num ville", 1);
assert!(
num.first().is_none_or(|h| h.precision != "house"),
"row with house number 'abc' must be dropped, not coerced to 0"
);
assert_eq!(idx.query("rue ok 5 ville", 1)[0].precision, "house");
}
#[test]
fn dropped_first_row_does_not_poison_commune_name() {
let out = build_csv(
"rue a,001,wrong,10000,1,,nan,nan,Rue A,Wrong\n\
rue a,001,town,10000,3,,7.42,43.73,Rue A,Town\n",
)
.expect("build");
let idx = crate::query::Index::open(&out).unwrap();
assert_eq!(
idx.query("rue a 3 town", 1)[0].commune,
"Town",
"commune must be named from the accepted row, not the dropped one"
);
}
#[test]
fn k_zero_returns_no_hits_on_any_path() {
let out = build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build");
let idx = crate::query::Index::open(&out).unwrap();
assert!(
idx.query("ville", 0).is_empty(),
"city-only path must honor k=0"
);
assert!(
idx.query("rue a 1 ville", 0).is_empty(),
"house path must honor k=0"
);
assert!(idx
.query_structured("rue a", Some("1"), "ville", None, 0)
.is_empty());
}
#[test]
fn structured_postcode_keeps_all_six_digits() {
let out = build_csv(
"centralnaya,001,tashkent,200456,10,,69.24,41.31,Centralnaya,Tashkent\n\
centralnaya,002,tashkent,100123,10,,69.30,41.35,Centralnaya,Tashkent\n",
)
.expect("build");
let idx = crate::query::Index::open(&out).unwrap();
let hit = idx.query_structured("centralnaya", Some("10"), "tashkent", Some("200456"), 1);
assert!(!hit.is_empty());
assert!(
(hit[0].0.lon - 69.24).abs() < 0.02,
"6-digit postcode must not be truncated to 5 (got lon {})",
hit[0].0.lon
);
}
#[test]
fn mixed_postcode_street_is_house_accurate_but_street_level_stays_empty() {
let dir = std::env::temp_dir().join(format!("gridpin-h10-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = crate::scratch::Scratch::keep(&dir);
let src = dir.join("h10.csv");
std::fs::write(
&src,
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n\
damrak,001,amsterdam,1012,1012AA,1,,4.90,52.37,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AB,3,,4.90,52.37,Damrak,Amsterdam\n",
)
.unwrap();
let out = dir.join("h10.bin");
build(&src, &out, None, None, None, None, None).expect("build");
let idx = crate::query::Index::open(&out).unwrap();
let house = idx.query("damrak 1 amsterdam", 1);
assert!(!house.is_empty(), "the house still resolves");
assert_eq!(house[0].postcode, "1012AA");
let street = idx.query("damrak amsterdam", 1);
assert!(!street.is_empty(), "the street still resolves");
assert_eq!(
street[0].postcode, "",
"a mixed-postcode street emits no postcode, not a neighbour's"
);
}
#[test]
fn poi_cascade_consulted_only_when_address_is_weak() {
let addr = crate::query::Index::open(
&build_csv("rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n").expect("build addr"),
)
.unwrap();
let poi = crate::query::Index::open(
&build_csv("cafe central,001,ville,10000,1,,7.43,43.74,Cafe Central,Ville\n")
.expect("build poi"),
)
.unwrap();
let strong = crate::query::query_cascade(&addr, Some(&poi), "rue a 1 ville", 1);
assert!(!strong.is_empty());
assert!(
!strong[0].flags.contains(&"poi_layer"),
"confident address must skip POI"
);
let via_poi = crate::query::query_cascade(&addr, Some(&poi), "cafe central ville", 1);
assert!(
!via_poi.is_empty(),
"POI should answer when the address layer cannot"
);
assert!(
via_poi[0].flags.contains(&"poi_layer"),
"a POI-sourced hit must carry poi_layer"
);
let no_poi = crate::query::query_cascade(&addr, None, "cafe central ville", 1);
assert!(no_poi
.first()
.is_none_or(|h| !h.flags.contains(&"poi_layer")));
}
#[test]
fn corrupt_sheet_stays_recoverable_never_ub_or_abort() {
let prev_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {})); let out = build_csv(
"avenue des champs,001,paris,75008,10,,2.307,48.872,Avenue des Champs,Paris\n\
rue de la paix,001,paris,75002,1,,2.331,48.869,Rue de la Paix,Paris\n\
rue de la paix,001,paris,75002,3,bis,2.332,48.870,Rue de la Paix,Paris\n",
)
.expect("build");
let good = std::fs::read(&out).unwrap();
let dir = out.parent().unwrap();
let mut variants: Vec<Vec<u8>> = Vec::new();
for cut in [
300usize,
500,
700,
good.len() / 2,
good.len() - 1,
good.len() - 20,
] {
if cut < good.len() {
variants.push(good[..cut].to_vec());
}
}
for off in (300..good.len()).step_by(37) {
let mut v = good.clone();
v[off] ^= 0xFF;
variants.push(v);
}
for (i, bytes) in variants.iter().enumerate() {
let bad = dir.join(format!("corrupt-{i}.bin"));
std::fs::write(&bad, bytes).unwrap();
let path = bad.clone();
let r = std::panic::catch_unwind(move || {
if let Ok(idx) = crate::query::Index::open(&path) {
let _ = idx.query("rue de la paix 1 paris", 3);
let _ = idx.reverse(48.869, 2.331, 3); }
});
let _ = (r, i);
}
std::panic::set_hook(prev_hook);
}
#[test]
fn reverse_precision_bands_and_distinct_k() {
let out = build_csv(
"rue a,001,ville,10000,1,,7.4200,43.7300,Rue A,Ville\n\
rue a,001,ville,10000,3,,7.4200,43.7330,Rue A,Ville\n",
)
.expect("build");
let idx = crate::query::Index::open(&out).unwrap();
let hits = idx.reverse(43.7300, 7.4200, 2).unwrap();
assert_eq!(hits.len(), 2, "two distinct houses");
assert_eq!(hits[0].precision, "house", "0 m from house 1");
assert_eq!(
hits[1].precision, "approximate",
"~334 m from house 3 (>250m band)"
);
assert!(
hits[0].confidence > hits[1].confidence,
"confidence decays with distance"
);
}
#[test]
fn reverse_dedups_true_duplicates_still_returns_k_distinct() {
let out = build_csv(
"rue a,001,ville,10000,5,,7.4200,43.7300,Rue A,Ville\n\
rue a,001,ville,10000,5,,7.4201,43.7301,Rue A,Ville\n\
rue a,001,ville,10000,7,,7.4202,43.7302,Rue A,Ville\n",
)
.expect("build");
let idx = crate::query::Index::open(&out).unwrap();
let hits = idx.reverse(43.7300, 7.4200, 2).unwrap();
let nums: Vec<_> = hits
.iter()
.map(|h| h.housenumber.clone().unwrap())
.collect();
assert_eq!(
nums.len(),
nums.iter().collect::<std::collections::HashSet<_>>().len(),
"no duplicate address in the reverse result: {nums:?}"
);
}
#[test]
fn query_structured_resolves_prebound_fields() {
let out =
build_csv("rue de la paix,001,paris,75002,1,,2.331,48.869,Rue de la Paix,Paris\n")
.expect("build");
let idx = crate::query::Index::open(&out).unwrap();
let hits = idx.query_structured("rue de la paix", Some("1"), "paris", Some("75002"), 1);
assert!(!hits.is_empty(), "structured query must resolve the house");
assert_eq!(hits[0].0.precision, "house");
}
#[test]
fn reverse_contract_keeps_suffixed_houses_distinct() {
let out = build_csv(
"rue a,001,ville,10000,12,,7.4200,43.7300,Rue A,Ville\n\
rue a,001,ville,10000,12,a,7.4201,43.7301,Rue A,Ville\n",
)
.expect("build must succeed");
let idx = crate::query::Index::open(&out).expect("open");
let hits = idx.reverse(43.7300, 7.4200, 3).unwrap();
assert_eq!(hits.len(), 2, "12 and 12A must both survive dedup");
assert!(
hits.iter().all(|h| h.street == "Rue A"),
"street must be the pure name"
);
let nums: Vec<_> = hits
.iter()
.map(|h| h.housenumber.clone().unwrap())
.collect();
assert!(
nums.contains(&"12".to_string()) && nums.contains(&"12a".to_string()),
"{nums:?}"
);
}
#[test]
fn overlong_insee_fails_loudly_instead_of_truncating() {
let err = build_csv("rue a,123456789,ville,10000,1,,7.42,43.73,Rue A,Ville\n")
.expect_err("must fail");
assert!(err.to_string().contains("8"), "{err}");
}
}