//! Index reading (mmap) and the query path: hypothesis-based parsing of the input
//! (digit groups as house-number candidates; compound suffixes via a dictionary),
//! exact lookup + prefix lookup + typo tolerance (Levenshtein automaton).
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use crate::levenshtein::Levenshtein;
use anyhow::{Context, Result};
use fst::{Automaton, IntoStreamer, Map, Streamer};
use memmap2::Mmap;
use serde::Serialize;
use unicode_normalization::UnicodeNormalization;
use crate::index::*;
use crate::norm::normalize;
const PLACE_GROUP_RADIUS_KM: f64 = 40.0;
/// A fallback answer farther than this from every centroid of the locality the query names
/// is another town: "Friedrichstraße 100, Berlin" must not become Dortmund. Covers a city's
/// own districts (Spandau is ~14 km from the Berlin centroid).
const NAMED_LOCALITY_RADIUS_KM: f64 = 25.0;
/// A city named with its region in the tail ("Lexington, KY"): an answer stays within this
/// distance of where the sheet's `commune_regions` table puts that city in that region. Wide
/// enough for the largest municipalities (Houston, Jacksonville), narrower than most states.
const COMMUNE_REGION_RADIUS_KM: f64 = 75.0;
/// A city the table knows but the sheet has no commune for (New York: its communes are the
/// neighbourhoods) is every commune within this distance of its point: the size of one city,
/// not of its region — a neighbouring town's street is not an answer for it.
const COMMUNE_UMBRELLA_RADIUS_KM: f64 = 20.0;
/// Radius of the place whose address count weighs a cityless homonym (see `area_prominence`).
const HOMONYM_AREA_RADIUS_KM: f64 = 20.0;
/// House-number suffix that marks a *range point*: a point sampled from an address range
/// (US TIGER/Line, prep/us_tiger.py) instead of a real house. Never typed by users, never
/// printed; see `Index::range_marker_rep`.
const RANGE_MARKER: &str = "~";
/// Locality tail window: "La Cuesta, San Cristóbal de La Laguna, Tenerife, España" is 9
/// tokens, "Vandellòs i l'Hospitalet de l'Infant" alone 7.
const NAMED_LOCALITY_TAIL: usize = 12;
/// Longer names that may share the leading words of one place: "Oldenburg (Oldenb.), Stadt"
/// and "Oldenburg in Holstein, Stadt". More is a generic word: "Sant" starts dozens of
/// Catalan communes, "Centro" — Brazilian ones.
const NAMED_LOCALITY_LEAD_MAX: usize = 3;
/// The locality a query names, for the fallback guard: tail tokens and the communes found in
/// them, each with the token run that named it.
#[derive(Default)]
struct NamedLocality {
tail: Vec<String>,
communes: Vec<(u32, usize, usize)>,
}
/// Owns a file mapping so it is freed on Drop: opening a sheet no longer permanently
/// leaks the mmap, so repeated open/close (Python/DuckDB churn) reclaims memory. The Index holds it
/// in an `Arc`, so a test can assert the Index dropped its reference deterministically.
struct Mapping(Mmap);
impl std::ops::Deref for Mapping {
type Target = Mmap;
fn deref(&self) -> &Mmap {
&self.0
}
}
impl Mapping {
fn new(m: Mmap) -> Self {
Mapping(m)
}
}
/// Colloquial commune names -> official NORMALIZED forms (as stored in the index after
/// normalization: apostrophe/hyphen -> space). Users write "Den Haag" while the index only
/// stores "s gravenhage"; without the alias such queries go empty or fuzzy-match a house
/// tens of km away. Curated list of major cities; keys and values are already normalized.
fn commune_alias(name: &str) -> Option<&'static str> {
// the table ships with the data (SEC_RULES, see rules.rs); defaults in rules::defaults
crate::rules::rules().commune_alias(name)
}
// POI-layer cascade (opt-in secondary places index).
// The address index is ALWAYS queried first; the POI layer is consulted ONLY when the
// address top-1 is weak, and its answer is taken ONLY if its own top-1 is more
// confident — an exact house match is never overridden.
/// Is the address top-1 weak (i.e. may the POI layer be consulted)?
///
/// An exact house match is never weak, whatever its calibrated confidence: a distant
/// homonym elsewhere in the country lowers confidence without making the match itself
/// any less exact, and the POI layer must never override an exact address.
pub fn hit_is_weak(h: &Hit) -> bool {
if h.precision == "house" && h.flags.contains(&"street_exact") {
return false;
}
h.precision == "city"
|| h.confidence < 0.30
|| (h.flags.contains(&"street_fuzzy") && h.confidence < 0.60)
}
/// Query with an optional POI layer. Without `poi` the behavior is identical to
/// `addr.query()` (the cascade is strictly opt-in). POI answers carry a "poi_layer" flag.
/// Refuse mismatched address/POI pairs: a French POI layer loaded
/// over the Italian sheet would silently answer Italian queries with French
/// cafes. Applied at LOAD time in every binding — never on the hot query path.
/// Sheets without identity (lab builds, no --meta) only produce a warning:
/// refusing them would break legitimate local workflows.
pub fn check_pair(addr: &Index, poi: &Index) -> std::result::Result<(), String> {
match (addr.country(), poi.country()) {
(Some(a), Some(p)) if a != p => {
return Err(format!(
"POI layer is for country {p:?} but the address sheet is for {a:?} — wrong file pair"
));
}
(None, _) | (_, None) => {
eprintln!(
"warning: sheet without country identity (pre-v6 or no --meta) — pair not verified"
);
}
_ => {}
}
if let Some(l) = addr.layer() {
if l != "addresses" {
return Err(format!("expected an address sheet, got layer {l:?}"));
}
}
if let Some(l) = poi.layer() {
if l != "poi" {
return Err(format!("expected a POI layer as --poi, got layer {l:?}"));
}
}
Ok(())
}
/// An address query is short; bound the raw input BEFORE any normalization/transliteration so a
/// multi-megabyte string can't drive CPU/RAM amplification. A real query is far
/// under this; anything longer is truncated at a char boundary, then the 32-token cap applies.
pub const MAX_QUERY_BYTES: usize = 1024;
pub fn bound_query(raw: &str) -> &str {
if raw.len() <= MAX_QUERY_BYTES {
return raw;
}
let mut end = MAX_QUERY_BYTES;
while end > 0 && !raw.is_char_boundary(end) {
end -= 1;
}
&raw[..end]
}
/// Result-count ceiling. A caller (CLI/Python/DuckDB) that asks for k = usize::MAX must not be able
/// to drive Vec::with_capacity / sort cost without bound. No real query wants > 100.
pub const MAX_K: usize = 100;
/// Clamp the requested result count. k = 0 keeps its "zero results" contract; anything above the
/// ceiling is capped, so an interface can never turn a single call into an unbounded allocation.
pub fn bound_k(k: usize) -> usize {
k.min(MAX_K)
}
/// A valid WGS84 point: finite and within [-90,90] × [-180,180]. The public reverse boundary must
/// REJECT bad input rather than silently probe a garbage grid cell and return an empty "success"
/// — the same predicate the builder uses to drop bad rows.
pub fn validate_lat_lon(lat: f64, lon: f64) -> std::result::Result<(), String> {
if lat.is_finite() && lon.is_finite() && lat.abs() <= 90.0 && lon.abs() <= 180.0 {
Ok(())
} else {
Err(format!(
"reverse: coordinates out of range or non-finite (lat={lat}, lon={lon}); \
expected finite lat in [-90,90], lon in [-180,180]"
))
}
}
/// A valid WGS84 focus for forward geocoding. Kept separate from the reverse error text so a
/// public `query_near` caller never receives a misleading `reverse:` diagnostic.
pub fn validate_query_near(lat: f64, lon: f64) -> std::result::Result<(), String> {
if lat.is_finite() && lon.is_finite() && lat.abs() <= 90.0 && lon.abs() <= 180.0 {
Ok(())
} else {
Err(format!(
"query --near: coordinates out of range or non-finite (lat={lat}, lon={lon}); \
expected finite lat in [-90,90], lon in [-180,180]"
))
}
}
fn plausible_house_postcode(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 8
&& value.as_bytes()[0].is_ascii_digit()
&& value
.chars()
.all(|character| character.is_ascii_alphanumeric() || character == ' ')
}
fn is_safe_house_rep(token: &str) -> bool {
matches!(token, "bis" | "ter" | "quater" | "quinquies" | "sexies")
|| (token.chars().count() == 1 && token.chars().all(char::is_alphabetic))
}
fn compound_house_parts(token: &str) -> Option<(usize, &str)> {
let digits = token
.bytes()
.take_while(|byte| byte.is_ascii_digit())
.count();
((1..=4).contains(&digits)
&& token.len() > digits
&& token[digits..].chars().count() <= 4
&& token[digits..].chars().all(char::is_alphanumeric))
.then_some((digits, &token[digits..]))
}
fn is_five_digit_postcode(token: &str) -> bool {
token.len() == 5 && token.bytes().all(|byte| byte.is_ascii_digit())
}
/// Test-observer for the two real house-suffix syntax branches. It uses
/// the same predicates as `build_hyp` and the compound-token hypothesis; an
/// index-specific rep dictionary still decides whether a particular suffix is
/// present in a built sheet.
#[cfg(test)]
pub(crate) fn de_house_suffix_trace(raw: &str) -> Option<String> {
let normalized = normalize(raw);
let tokens: Vec<&str> = normalized.split_whitespace().collect();
for token in &tokens {
if let Some((digits, suffix)) = compound_house_parts(token) {
return Some(format!(
"{token} -> numero={} rep={suffix}",
&token[..digits]
));
}
}
for pair in tokens.windows(2) {
if (1..=4).contains(&pair[0].len())
&& pair[0].bytes().all(|byte| byte.is_ascii_digit())
&& is_safe_house_rep(pair[1])
{
return Some(format!(
"{} {} -> numero={} rep={}",
pair[0], pair[1], pair[0], pair[1]
));
}
}
None
}
/// Test-observer for the exact five-digit branch used by the free-form
/// parser. Leading zeroes remain present in this normalized token even though
/// lookup later compares the numeric value and returns the stored display form.
#[cfg(test)]
pub(crate) fn de_five_digit_postcode_trace(raw: &str) -> Option<String> {
normalize(raw)
.split_whitespace()
.find(|token| is_five_digit_postcode(token))
.map(|token| format!("PLZ token preserved: {token}"))
}
pub fn query_cascade(addr: &Index, poi: Option<&Index>, q: &str, k: usize) -> Vec<Hit> {
let k = bound_k(k); // cap result count at the public boundary
let q = bound_query(q); // and the input length, before either index normalizes it
let hits = addr.query(q, k);
escalate_to_poi(poi, hits, q, k)
}
/// Forward cascade with an explicit location hint. The address candidate set is widened with
/// streets from the existing spatial grid, while POI escalation keeps the same precedence as the
/// ordinary cascade. Coordinates are a strict public boundary, like reverse geocoding.
pub fn query_cascade_near(
addr: &Index,
poi: Option<&Index>,
q: &str,
k: usize,
lat: f64,
lon: f64,
) -> std::result::Result<Vec<Hit>, String> {
let k = bound_k(k);
let q = bound_query(q);
let hits = addr.query_near(q, k, lat, lon)?;
Ok(escalate_to_poi(poi, hits, q, k))
}
/// Structured-input variant of the cascade: the same POI
/// precedence as free-form, so a structured query for a POI (a named place, not a street) is not
/// silently unanswerable just because the caller pre-split the fields. The address index is tried
/// first; if its answer is weak (or empty) the POI layer is consulted with EVERY provided token
/// joined in a CANONICAL order (street number postcode city).
///
/// PARITY SCOPE (honest boundary): parity with free-form holds for ADDRESS resolution and for any
/// POI whose tokens appear in that canonical order. It does NOT hold when the caller's field
/// assignment REORDERS the tokens of an order-sensitive POI NAME: free-form "54 studio ville" ranks
/// "54 Studio", but structured {street:"studio", number:"54"} joins to "studio 54 ville" and can
/// rank "Studio 54" — same confidence, different place. Making POI matching order-insensitive (or
/// scoring supported permutations with a deterministic merge) is the fuller fix; until then the
/// public promise is deliberately narrowed to the canonical-order case, not "any input".
pub fn query_structured_cascade(
addr: &Index,
poi: Option<&Index>,
street: &str,
number: Option<&str>,
city: &str,
postcode: Option<&str>,
k: usize,
) -> Vec<Hit> {
// Bound EVERY structured field AND k at the public boundary: only street/city
// were capped downstream, so a multi-MB `number`/`postcode`, or the free-form `poi_q` join of
// the RAW fields, drove normalization/allocation before any cap. Bounding each field here caps
// the join too (≤ 4 × MAX_QUERY_BYTES), so the structured path amplifies no more than free-form.
let k = bound_k(k);
let street = bound_query(street);
let number = number.map(bound_query);
let city = bound_query(city);
let postcode = postcode.map(bound_query);
let hits: Vec<Hit> = addr
.query_structured(street, number, city, postcode, k)
.into_iter()
.map(|(h, _feats)| h)
.collect();
// CANONICAL-ORDER join: the POI escalation sees EVERY token the caller gave, in
// the canonical street-number-postcode-city order ("Damstraat 1 1012JS Amsterdam"). This gives
// parity for address resolution and canonical-order POIs; an order-sensitive POI name the caller
// split across fields can still diverge (see the parity-scope note above). An earlier fix joined city
// before postcode, which broke
// parity for order-sensitive postcode forms (NL): the two paths ranked different winners.
// With the identical token string, parity holds BY CONSTRUCTION for any input.
let poi_q = [street, number.unwrap_or(""), postcode.unwrap_or(""), city]
.iter()
.filter(|s| !s.is_empty())
.copied()
.collect::<Vec<_>>()
.join(" ");
escalate_to_poi(poi, hits, &poi_q, k)
}
/// Shared cascade tail: if `hits` from the address index is weak/empty and a POI layer exists,
/// query it with `poi_q` and prefer the POI answer when it is more confident.
fn escalate_to_poi(poi: Option<&Index>, hits: Vec<Hit>, poi_q: &str, k: usize) -> Vec<Hit> {
let Some(p) = poi else { return hits };
if !hits.first().is_none_or(hit_is_weak) {
return hits; // address answer is confident — skip the POI layer entirely
}
if poi_q.is_empty() {
return hits;
}
let mut ph = p.query(poi_q, k);
let better = match (ph.first(), hits.first()) {
(Some(pt), Some(at)) => pt.confidence > at.confidence,
(Some(_), None) => true,
_ => false,
};
if better {
for h in &mut ph {
h.flags.push("poi_layer");
}
return ph;
}
hits
}
pub struct StreetMeta {
pub lat_c: i32,
pub lon_c: i32,
pub commune_id: u32,
pub postcode: u32,
pub name_off: u32,
pub house_off: u64,
pub house_count: u32,
/// offset of the full postcode string in names (NL "1012XJ"); 0 = absent -> print numeric postcode
pub postcode_disp_off: u32,
}
// One query re-runs the fuzzy street search for every variant it tries (country variants,
// the retry without the neighbourhood), and each run used to rebuild the same Levenshtein
// automata: on the Brazilian sheet that was ~90 % of the time. The automaton is a pure function
// of (phrase, distance), so reusing it cannot change an answer; a failed build (too many
// states) is remembered too. The cache is per thread and emptied at the start of every
// top-level query, so its memory is bounded by one query's automata.
type LevCache = HashMap<(String, u32), Option<std::rc::Rc<Levenshtein>>>;
thread_local! {
static LEV_CACHE: std::cell::RefCell<LevCache> = std::cell::RefCell::new(HashMap::new());
}
const LEV_CACHE_MAX: usize = 256;
fn cached_levenshtein(phrase: &str, dist: u32) -> Option<std::rc::Rc<Levenshtein>> {
LEV_CACHE.with(|cache| {
let mut cache = cache.borrow_mut();
let key = (phrase.to_owned(), dist);
if let Some(found) = cache.get(&key) {
return found.clone();
}
if cache.len() >= LEV_CACHE_MAX {
cache.clear();
}
let built = Levenshtein::new(phrase, dist).ok().map(std::rc::Rc::new);
cache.insert(key, built.clone());
built
})
}
fn clear_levenshtein_cache() {
LEV_CACHE.with(|cache| cache.borrow_mut().clear());
}
#[cfg(test)]
fn levenshtein_cache_len() -> usize {
LEV_CACHE.with(|cache| cache.borrow().len())
}
#[derive(Debug)]
struct CityTail {
city: String,
retry: Option<String>,
/// The same query with the region segment removed (postal code kept): read only where a
/// region anchor holds the city, so a bare code ("…, Chicago, IL") gets a region-less
/// reading too, which the retry grammar does not build for it.
without_region: String,
/// The same query with the city and region segments removed and the postal code kept
/// ("1 Water Street, 12590"): read only when the city is no commune of the sheet and the
/// tail carries a postal code, so a hamlet or a neighbourhood the sheet does not name
/// ("New Hamburg", "S Portland") still reaches its street inside the code (US, 22.10.2026).
without_city: Option<String>,
/// The region the tail names, as the code the sheet lists in `regions` (None when the tail
/// names a region the sheet knows only by name, without "name=CODE").
region: Option<String>,
/// The region segment as written, normalized ("quebec" for "(Québec)"): a region word that
/// also names a commune (Québec City) is told from the city named in front of it.
region_word: String,
/// The city segment opened with the postal code (`postal_city` form): the region-less reading
/// drops the inner segments, and an answer from it stands only inside the code written.
postal_city: bool,
}
/// The segment without the country words that close it ("NV 89146 USA", "MD 20852 U.S."):
/// the words come from the sheet's countries_tail, and a segment of country words alone is
/// left to the junk rule.
fn strip_trailing_country_words(segment: &str) -> &str {
let mut end = segment.trim_end();
loop {
let Some((head, last)) = end.rsplit_once(' ') else {
return end;
};
if !is_country_word(&normalize(last)) {
return end;
}
end = head.trim_end();
}
}
/// A tail segment names the region: a code from `regions` (whitespace-separated) or, when the
/// sheet lists `region_names` (semicolon-separated, any case, e.g. "new york;washington"), a
/// full name — compared word by word, case-insensitively.
/// The words of a tail segment as `region_names` spells them: lowercase, accents and hyphens
/// gone ("Québec", "Île-du-Prince-Édouard" -> "quebec", "ile du prince edouard"; Canada, 29.10.2026:
/// an ASCII-only lowercase never matched an accented name).
fn region_segment_words(segment: &str) -> Vec<String> {
normalize(segment)
.split_whitespace()
.map(str::to_owned)
.collect()
}
fn region_matches(cfg: &HashMap<String, String>, segment: &str) -> bool {
let words = region_segment_words(segment);
if words.is_empty() {
return false;
}
if words.len() == 1
&& cfg.get("regions").is_some_and(|r| {
r.split_whitespace()
.any(|v| v.eq_ignore_ascii_case(&words[0]))
})
{
return true;
}
cfg.get("region_names").is_some_and(|names| {
names
.split(';')
.any(|name| region_name_words(name) == words)
})
}
/// A trailing segment the tail grammar ignores: country words only, a segment that opens with
/// one of the sheet's `junk_tail` words ("near the mall", "tel 000-0000"), or a phone number —
/// seven or more digits in several groups, which no postal code of the sheet has.
fn junk_tail_segment(cfg: &HashMap<String, String>, segment: &str) -> bool {
// A region segment is never junk, whatever word opens it ("FL 32202" under a junk word
// "floor" shortened the same way).
if region_matches(cfg, segment) || split_region_postal(cfg, segment).is_some() {
return false;
}
let words = normalize(segment);
let mut it = words.split(' ').filter(|w| !w.is_empty());
let Some(first) = it.next() else {
return false;
};
if std::iter::once(first).chain(it).all(is_country_word) {
return true;
}
if cfg
.get("junk_tail")
.is_some_and(|j| j.split_whitespace().any(|w| w == first))
{
return true;
}
// "18th and 19th Floor": numbers, connectors and designators only, with a designator
// among them.
let tokens: Vec<&str> = words.split(' ').filter(|w| !w.is_empty()).collect();
let junk_word = |w: &str| {
cfg.get("junk_tail")
.is_some_and(|j| j.split_whitespace().any(|x| x == w))
};
if tokens.iter().any(|w| junk_word(w))
&& tokens
.iter()
.all(|w| junk_word(w) || numbered_word(w) || matches!(*w, "and" | "&"))
{
return true;
}
// a phone number, never a postal code of the sheet's shape (five digits, or five plus the
// declared extension after a hyphen: "19095-1898" is a ZIP+4, not a phone)
if postal_segment(cfg, segment.trim()).is_some() {
return false;
}
let digits = segment.chars().filter(char::is_ascii_digit).count();
let groups = segment
.split(|c: char| !c.is_ascii_digit())
.filter(|g| !g.is_empty())
.count();
digits >= 7 && groups >= 2 && !segment.chars().any(|c| c.is_alphabetic())
}
/// A whole segment that is a postal code of the sheet: `postal_digits` digits, optionally split
/// by a hyphen at `postal_split`, optionally followed by a hyphen and `postal_extension` digits
/// ("62701", "19095-1898"). Returns the five-digit core.
fn postal_segment<'a>(cfg: &HashMap<String, String>, segment: &'a str) -> Option<&'a str> {
let digits_n = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let split = cfg.get("postal_split")?.parse::<usize>().ok()?;
let extension = cfg
.get("postal_extension")
.and_then(|v| v.parse::<usize>().ok())
.filter(|&n| n > 0);
let (core, rest) = match segment.split_once('-') {
Some((core, rest))
if core.len() == digits_n && core.bytes().all(|b| b.is_ascii_digit()) =>
{
(core, Some(rest))
}
_ => (segment, None),
};
let core_digits: String = core.chars().filter(char::is_ascii_digit).collect();
let core_ok = core_digits.len() == digits_n
&& (core == core_digits
|| (split > 0
&& split < digits_n
&& core == format!("{}-{}", &core_digits[..split], &core_digits[split..])));
if !core_ok {
return None;
}
match rest {
None => Some(core),
Some(ext) => (extension.is_some_and(|n| ext.len() == n)
&& ext.bytes().all(|b| b.is_ascii_digit()))
.then_some(core),
}
}
/// A postal code of the sheet's `postal_pattern` (city_tail): `A` a letter, `9` a digit, a space
/// optional in the query ("A9A 9A9": Canada "K1A 0B1", "k1a0b1"). Data-driven like `postal_digits`;
/// a sheet without the key has no such codes. Such a code is recognised and set aside only: the
/// sheet keeps no numeric postcode for it (prep/overture.py POSTAL_DIGITS_SQL, Canada 28.10.2026).
fn pattern_postal(cfg: &HashMap<String, String>, text: &str) -> bool {
let Some(pattern) = cfg.get("postal_pattern") else {
return false;
};
let shape: Vec<u8> = pattern.bytes().filter(|b| *b != b' ').collect();
let given: Vec<u8> = text.bytes().filter(|b| *b != b' ').collect();
!shape.is_empty()
&& shape.len() == given.len()
&& shape.iter().zip(&given).all(|(want, got)| match want {
b'A' => got.is_ascii_alphabetic(),
b'9' => got.is_ascii_digit(),
_ => false,
})
}
/// How many trailing words of `words` spell a `postal_pattern` code: two ("M5X 1A9"), one
/// ("M5X1A9"), or none.
fn pattern_postal_tail(cfg: &HashMap<String, String>, words: &[&str]) -> usize {
let n = words.len();
if n >= 2 && pattern_postal(cfg, &format!("{} {}", words[n - 2], words[n - 1])) {
2
} else if n >= 1 && pattern_postal(cfg, words[n - 1]) {
1
} else {
0
}
}
/// One `region_names` entry is "name" or "name=CODE"; these are the lowercase words of the name.
fn region_name_words(entry: &str) -> Vec<String> {
entry
.split('=')
.next()
.unwrap_or("")
.split_whitespace()
.map(str::to_ascii_lowercase)
.collect()
}
/// The code of the region a tail segment names: the code itself (any case) when it is listed in
/// `regions`, or the CODE of a `region_names` entry written "name=CODE". A name without a code
/// is a region for the grammar but anchors nothing.
fn region_code(cfg: &HashMap<String, String>, segment: &str) -> Option<String> {
let trimmed = segment.trim();
if !trimmed.contains(' ')
&& cfg.get("regions").is_some_and(|r| {
r.split_whitespace()
.any(|v| v.eq_ignore_ascii_case(trimmed))
})
{
return Some(trimmed.to_ascii_uppercase());
}
let words = region_segment_words(trimmed);
cfg.get("region_names")?.split(';').find_map(|entry| {
let (_, code) = entry.split_once('=')?;
(region_name_words(entry) == words).then(|| code.trim().to_ascii_uppercase())
})
}
/// Where the sheet puts a city of this name inside this region: every "REGION lat lon" entry of
/// `commune_regions` for the normalized city whose REGION is the code. Empty when the sheet
/// carries no table, no such city, or no such city in that region — then nothing is held.
/// The answer stands outside the region the query names, by the sheet's `commune_regions` table:
/// the table knows the town only in other regions ("st pascal, ON": Saint-Pascal is in Québec),
/// or the answer is farther than COMMUNE_REGION_RADIUS_KM from every point of the town in the
/// named region. False when the table does not know the town at all.
fn town_outside_region(hit: &Hit, city: &str, region: &str) -> bool {
let table = &crate::rules::rules().commune_regions;
if !table.contains_key(city)
&& !saint_commune_name(city).is_some_and(|full| table.contains_key(&full))
{
return false;
}
!commune_region_points(city, region)
.iter()
.any(|&(lat, lon)| Index::dist_km(lat, lon, hit.lat, hit.lon) <= COMMUNE_REGION_RADIUS_KM)
}
fn commune_region_points(city: &str, region: &str) -> Vec<(f64, f64)> {
let table = &crate::rules::rules().commune_regions;
// "st leonard, QC": the table names the town as the sheet does (see `saint_commune_name`)
let Some(entries) = table
.get(city)
.or_else(|| saint_commune_name(city).and_then(|full| table.get(&full)))
else {
return Vec::new();
};
entries
.split(';')
.filter_map(|entry| {
let mut it = entry.split_whitespace();
let code = it.next()?;
if !code.eq_ignore_ascii_case(region) {
return None;
}
Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?))
})
.collect()
}
/// The city named with its region in the running query's tail: its normalized name and its
/// points from `commune_regions` (see `commune_region_points`); empty when no region holds it.
#[derive(Default)]
struct CommuneRegionAnchor {
city: String,
points: Vec<(f64, f64)>,
/// The city's own name resolves to every commune under the umbrella, not only to the
/// communes carrying the name (the address lives next door under "ATL" or "Financial
/// District" while a commune "Atlanta" / "New York City" exists and lacks the street).
widen: bool,
}
thread_local! {
static COMMUNE_REGION_ANCHOR: std::cell::RefCell<CommuneRegionAnchor> = const {
std::cell::RefCell::new(CommuneRegionAnchor {
city: String::new(),
points: Vec::new(),
widen: false,
})
};
}
/// Restores the previous anchor when dropped.
struct CommuneRegionScope(CommuneRegionAnchor);
impl Drop for CommuneRegionScope {
fn drop(&mut self) {
COMMUNE_REGION_ANCHOR.with(|a| *a.borrow_mut() = std::mem::take(&mut self.0));
}
}
/// Make `points` the region anchor for this thread until the guard is dropped: every commune
/// lookup by name or prefix then keeps only the homonyms within COMMUNE_REGION_RADIUS_KM of
/// one of them, so "Lexington, KY" searches the Lexington of Kentucky and not the sixteen
/// others that outrank it (US, 22.10.2026).
#[must_use]
fn commune_region_scope(city: &str, points: Vec<(f64, f64)>) -> CommuneRegionScope {
commune_region_scope_widened(city, points, false)
}
/// The same anchor with the city's name widened to the whole umbrella (see `widen`).
#[must_use]
fn commune_region_scope_widened(
city: &str,
points: Vec<(f64, f64)>,
widen: bool,
) -> CommuneRegionScope {
let anchor = CommuneRegionAnchor {
city: city.to_owned(),
points,
widen,
};
CommuneRegionScope(
COMMUNE_REGION_ANCHOR.with(|a| std::mem::replace(&mut *a.borrow_mut(), anchor)),
)
}
/// Keep only the hits within COMMUNE_REGION_RADIUS_KM of one of the city's points in the named
/// region. A hit whose commune or postcode matched the query is no exception: the tail says
/// "Lexington, KY", and a Lexington elsewhere matched the name, not the place. With no points,
/// the hits are returned as they came.
fn within_commune_region(
mut hits: Vec<(Hit, [f32; N_FEATS])>,
points: &[(f64, f64)],
) -> Vec<(Hit, [f32; N_FEATS])> {
if points.is_empty() {
return hits;
}
hits.retain(|(hit, _)| {
points.iter().any(|&(lat, lon)| {
Index::dist_km(lat, lon, hit.lat, hit.lon) <= COMMUNE_REGION_RADIUS_KM
})
});
hits
}
/// A region named by a full name (not a code): the main parser cannot see the comma, so the
/// name glues to the city and the tail needs a retry without it.
fn region_is_name(cfg: &HashMap<String, String>, segment: &str) -> bool {
region_matches(cfg, segment)
&& !cfg.get("regions").is_some_and(|r| {
r.split_whitespace()
.any(|v| v.eq_ignore_ascii_case(segment.trim()))
})
}
/// The `region_postal` tail form, data-driven like `comma` and `hyphen`: one segment
/// `<region> <postal>` or `<region>` alone. The region must be listed in `regions`
/// (case-insensitive); the postal code is exactly `postal_digits` digits, optionally
/// followed by `-` and `postal_extension` digits when the sheet declares that key.
/// Every reader of the tail grammar (city tail, field retries, comma recovery) asks
/// this one helper, so they all agree on which segment names the city. A postal
/// segment on its own is stripped by the shared postal rule before the forms are tried,
/// exactly as under `comma`. Returns `(region, postal)`.
fn split_region_postal<'a>(
cfg: &HashMap<String, String>,
segment: &'a str,
) -> Option<(&'a str, Option<&'a str>)> {
if !cfg
.get("forms")?
.split_whitespace()
.any(|f| f == "region_postal")
{
return None;
}
let regions = cfg.get("regions")?;
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let extension = match cfg.get("postal_extension") {
Some(value) => Some(value.parse::<usize>().ok().filter(|&n| n > 0)?),
None => None,
};
let _ = regions;
let trimmed = segment.trim();
let words: Vec<&str> = trimmed.split_whitespace().collect();
let pattern_words = pattern_postal_tail(cfg, &words);
if pattern_words > 0 && pattern_words < words.len() {
// "ON M5X 1A9": the code is recognised and set aside; it is no key of the sheet.
let mut region = trimmed;
for _ in 0..pattern_words {
region = region.rsplit_once(' ')?.0.trim_end();
}
return region_matches(cfg, region).then_some((region, None));
}
let looks_postal = |w: &str| w.chars().next().is_some_and(|c| c.is_ascii_digit());
let (region, postal) = match trimmed.rsplit_once(' ') {
Some((head, last)) if looks_postal(last) => (head.trim(), Some(last)),
_ => (trimmed, None),
};
if region.is_empty() || !region_matches(cfg, region) {
return None;
}
let all_digits = |s: &str, n: usize| s.len() == n && s.bytes().all(|b| b.is_ascii_digit());
if let Some(postal) = postal {
let (main, rest) = postal
.split_once('-')
.map_or((postal, None), |(main, rest)| (main, Some(rest)));
let extension_ok = match (rest, extension) {
(None, _) => true,
(Some(rest), Some(n)) => all_digits(rest, n),
(Some(_), None) => false,
};
if !all_digits(main, digits) || !extension_ok {
return None;
}
}
Some((region, postal))
}
/// Under the `region_postal` form a last segment "<city words> <region> [<postal>]" is the
/// city and the region written without their comma ("Philadelphia PA 19122-6117", "NEW YORK NY
/// 10128"): the segment is split at the region word and the query is rebuilt with the comma.
/// Only when words precede the region and a segment (the street) precedes the city.
fn glued_city_region(
cfg: &HashMap<String, String>,
parts: &[&str],
end: usize,
has_form: &dyn Fn(&str) -> bool,
) -> Option<String> {
if !has_form("region_postal") || end == 0 {
return None;
}
let words: Vec<&str> = parts[end].split_whitespace().collect();
if words.len() < 2 {
return None;
}
let looks_postal = |w: &str| w.chars().next().is_some_and(|c| c.is_ascii_digit());
let pattern_words = pattern_postal_tail(cfg, &words);
let (tail_len, region_postal) = if pattern_words > 0 && words.len() >= pattern_words + 2 {
// "Toronto ON M5X 1A9": region word plus the one- or two-word code
let take = pattern_words + 1;
(take, words[words.len() - take..].join(" "))
} else if looks_postal(words[words.len() - 1]) && words.len() >= 3 {
(2, words[words.len() - 2..].join(" "))
} else {
(1, words[words.len() - 1].to_owned())
};
split_region_postal(cfg, ®ion_postal)?;
let city = words[..words.len() - tail_len].join(" ");
let mut rebuilt: Vec<String> = parts[..end].iter().map(|s| (*s).to_owned()).collect();
rebuilt.push(city);
rebuilt.push(region_postal);
Some(rebuilt.join(", "))
}
/// The city segment of a tail that still carries the street ("20 North Main Street Providence"):
/// on a sheet with city_tail `street_type_last` the segment opens with the house number, holds
/// a street type word, and the city is what follows the last type word once the direction
/// words and stray digits after it are set aside. Returns the query rebuilt with the comma.
fn street_glued_to_city(parts: &[&str], city_pos: usize) -> Option<String> {
if !street_type_last() {
return None;
}
let segment = parts[city_pos];
let toks: Vec<String> = segment
.split_whitespace()
.map(|t| t.trim_matches('.').to_owned())
.filter(|t| !t.is_empty())
.collect();
if toks.len() < 3 || !toks[0].starts_with(|c: char| c.is_ascii_digit()) {
return None;
}
let lower: Vec<String> = toks.iter().map(|t| t.to_ascii_lowercase()).collect();
let last_type = (1..lower.len())
.rev()
.find(|&i| is_street_type_word(&lower[i]))?;
let mut split = last_type + 1;
while split < lower.len()
&& (street_rewrite_word(&lower[split]) || lower[split].bytes().all(|b| b.is_ascii_digit()))
{
split += 1;
}
if split >= lower.len()
|| lower[split..]
.iter()
.any(|t| t.bytes().any(|b| b.is_ascii_digit()))
{
return None;
}
let mut rebuilt: Vec<String> = parts[..city_pos].iter().map(|s| (*s).to_owned()).collect();
rebuilt.push(toks[..split].join(" "));
rebuilt.push(toks[split..].join(" "));
rebuilt.extend(parts[city_pos + 1..].iter().map(|s| (*s).to_owned()));
Some(rebuilt.join(", "))
}
/// A unit designator at the end of the street segment ("702 W Idaho St Ste 312", "3880 E Rte
/// 66 #2") is no part of the street: the opening words come from the sheet's `junk_tail` key
/// (suite, ste, apt, unit, …) with their token, and a "#…" token stands alone. Only on a sheet
/// with a trailing type; returns the query without them, or None when nothing was cut.
/// A number or an ordinal ("2", "18th"), the way a floor or a suite is counted.
fn numbered_word(tok: &str) -> bool {
let w = normalize(tok);
let digits = w.trim_end_matches(|c: char| c.is_ascii_alphabetic());
!digits.is_empty()
&& digits.bytes().all(|b| b.is_ascii_digit())
&& matches!(&w[digits.len()..], "" | "st" | "nd" | "rd" | "th")
}
/// The query with the place written first moved behind the address, on a sheet with city_tail
/// `city_first` = 1. Three forms, tried in order, each only when the query opens with no digit:
/// "<place> (<address>) <rest>" with the address opening with a digit, "<place> - <address>",
/// and "<place>[,] <number> <words>" where the place is letters only. The result is
/// "<address>, <place>[, <rest>]". None for any other query.
fn city_first_reordered(raw: &str) -> Option<String> {
if crate::rules::rules()
.city_tail
.get("city_first")
.map(String::as_str)
!= Some("1")
{
return None;
}
let raw = raw.trim();
if raw.chars().next().is_none_or(|c| c.is_ascii_digit()) {
return None;
}
let clean = |s: &str| {
s.trim_matches(|c: char| c == ',' || c.is_whitespace())
.to_owned()
};
let join = |parts: [String; 3]| {
parts
.into_iter()
.filter(|p| !p.is_empty())
.collect::<Vec<_>>()
.join(", ")
};
// "<place> (<address>) <rest>"
if let Some(open) = raw.find('(') {
if let Some(close) = raw[open..].find(')').map(|c| open + c) {
let inner = raw[open + 1..close].trim();
if inner.starts_with(|c: char| c.is_ascii_digit()) && !raw[..open].contains('(') {
return Some(join([
clean(inner),
clean(&raw[..open]),
clean(&raw[close + 1..]),
]));
}
}
}
let letters_only = |s: &str| {
!s.trim().is_empty()
&& s.chars().all(|c| {
c.is_alphabetic() || c.is_whitespace() || matches!(c, ',' | '.' | '\'' | '-')
})
};
// "<place> - <address>"
if let Some(dash) = raw.find(" - ") {
let (head, addr) = (&raw[..dash], raw[dash + 3..].trim());
if !head.chars().any(|c| c.is_ascii_digit())
&& addr.starts_with(|c: char| c.is_ascii_digit())
{
return Some(join([clean(addr), clean(head), String::new()]));
}
}
// "<place>[,] <number> <words>"; "<number> - <words>" is the same number ("Surrey, BC 19540 - 94
// Avenue"), and a postal code of the sheet's pattern closing the address goes behind the place
// ("Calgary AB 5111 47 St NE T3J 0V4"), where the tail grammar sets it aside.
let start = raw.find(|c: char| c.is_ascii_digit())?;
let (head, addr) = (&raw[..start], &raw[start..]);
let mut words: Vec<&str> = addr.split_whitespace().collect();
// ... but not after a street type ("Highway 7 - 1200 Airport Blvd" names two roads)
let head_is_street = head
.split_whitespace()
.last()
.is_some_and(|w| is_street_type_word(&normalize(w)));
if words.len() >= 3
&& words[1] == "-"
&& !head_is_street
&& words[2].starts_with(|c: char| c.is_ascii_alphanumeric())
{
words.remove(1);
}
let cfg = &crate::rules::rules().city_tail;
let postal_words = pattern_postal_tail(cfg, &words);
let postal = if postal_words == 0 {
String::new()
} else if postal_words + 2 <= words.len() {
words.split_off(words.len() - postal_words).join(" ")
} else {
return None; // a number and a postal code, no street
};
let addr = words.join(" ");
if !letters_only(head)
|| addr.contains(" - ")
|| addr.contains('(')
|| words.len() < 2
|| words[1] == "-"
|| !words[0].chars().all(|c| c.is_ascii_alphanumeric())
|| !head.ends_with([' ', ','])
{
return None;
}
Some(join([clean(&addr), clean(head), postal]))
}
/// How far, in house numbers, a neighbour may stand from the number written and still settle the
/// city's own reading.
const NEIGHBOUR_NUMBER_SPAN: u64 = 100;
/// A neighbour (`near`) answer whose number differs from the query's leading house number by more
/// than `NEIGHBOUR_NUMBER_SPAN`. False for any other precision, or when either number is missing.
fn neighbour_far_from_written(hit: &Hit, raw: &str) -> bool {
let leading = |s: &str| -> Option<u64> {
let digits: String = s
.trim_start()
.chars()
.take_while(char::is_ascii_digit)
.collect();
digits.parse().ok()
};
if hit.precision != "near" {
return false;
}
match (leading(raw), hit.housenumber.as_deref().and_then(leading)) {
(Some(written), Some(got)) => written.abs_diff(got) > NEIGHBOUR_NUMBER_SPAN,
_ => false,
}
}
/// A city-first answer keeps the place written: an exact commune, or an exact street at a house, an
/// interpolation or a neighbour within `CITY_FIRST_MERGED_KM` of one of the named city's points.
fn city_first_keeps_place(hit: &Hit, city_points: &[(f64, f64)]) -> bool {
hit.flags.contains(&"commune_exact")
|| (hit.flags.contains(&"street_exact")
&& matches!(hit.precision, "house" | "interp" | "near")
&& city_points.iter().any(|&(lat, lon)| {
Index::dist_km(lat, lon, hit.lat, hit.lon) <= CITY_FIRST_MERGED_KM
}))
}
/// How far from the named city's own point a city-first answer in another commune may stand
/// (a merged city: Toronto's former municipalities reach about 25 km from its point).
const CITY_FIRST_MERGED_KM: f64 = 30.0;
/// How wide a bracket of two stored house numbers may be and still be interpolated: at most this
/// many numbers apart and closer than this many kilometres. 12 numbers and 0.3 km by default
/// (dense numbering); a sheet with sparser numbering widens both through city_tail
/// `interp_max_gap` and `interp_max_km` (Canada, rural numbering: 400 and 2.0; 29.10.2026).
fn interp_limits() -> (u32, f64) {
let cfg = &crate::rules::rules().city_tail;
let gap = cfg
.get("interp_max_gap")
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(12);
let km = cfg
.get("interp_max_km")
.and_then(|v| v.parse::<f64>().ok())
.filter(|km| km.is_finite() && *km > 0.0)
.unwrap_or(0.3);
(gap, km)
}
/// An answer on the street written, in the commune named, at a house, an interpolation or the
/// nearest house.
fn street_in_commune(hit: &Hit) -> bool {
hit.flags.contains(&"street_exact")
&& hit.flags.contains(&"commune_exact")
&& matches!(hit.precision, "house" | "interp" | "near")
}
/// The one quadrant answer to keep: of the readings whose top is the street in the named commune,
/// the only one at a house; with no house, the only one at all. Two such readings are no answer.
fn pick_quadrant(readings: Vec<Vec<(Hit, [f32; N_FEATS])>>) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let found: Vec<Vec<(Hit, [f32; N_FEATS])>> = readings
.into_iter()
.filter(|hits| hits.first().is_some_and(|(hit, _)| street_in_commune(hit)))
.collect();
let houses = found
.iter()
.filter(|hits| hits[0].0.precision == "house")
.count();
match (houses, found.len()) {
(1, _) => found
.into_iter()
.find(|hits| hits[0].0.precision == "house"),
(0, 1) => found.into_iter().next(),
_ => None,
}
}
/// The query once per quadrant of the sheet's city_tail `quadrant_suffixes`, the quadrant
/// appended to the street segment. None when the sheet has no such key, the tail names no city,
/// the street is not its own segment, or the street already carries a direction word.
fn quadrant_variants(raw: &str) -> Vec<String> {
let cfg = &crate::rules::rules().city_tail;
let Some(quadrants) = cfg.get("quadrant_suffixes") else {
return Vec::new();
};
let Some(tail) = city_tail(raw) else {
return Vec::new();
};
let Some((street, rest)) = raw.split_once(',') else {
return Vec::new();
};
let words = normalize(street);
let words: Vec<&str> = words.split_whitespace().collect();
let directions = [
"n", "s", "e", "w", "ne", "nw", "se", "sw", "north", "south", "east", "west",
];
if words.len() < 2
|| words.iter().any(|w| directions.contains(w))
|| words.ends_with(&tail.city.split_whitespace().collect::<Vec<_>>())
{
return Vec::new();
}
quadrants
.split_whitespace()
.map(|q| format!("{} {q},{rest}", street.trim_end()))
.collect()
}
/// "St. George", "St Paul": the sheet names the place "Saint …" while people shorten it the
/// way a street type is shortened; the same query with the city spelled out, read only when
/// the written form reaches nothing (US, 23.10.2026).
fn saint_city_variant(raw: &str) -> Option<String> {
let tail = city_tail(raw)?;
let rest = tail
.city
.strip_prefix("st ")
.or_else(|| tail.city.strip_prefix("st. "))?;
if rest.trim().is_empty() {
return None;
}
let mut segments: Vec<String> = raw.split(',').map(str::to_owned).collect();
let pos = segments
.iter()
.position(|s| normalize(s.trim()) == tail.city)?;
let seg = segments[pos].trim_start();
let lead = segments[pos].len() - seg.len();
let lower = seg.to_lowercase();
let cut = if lower.starts_with("st. ") {
4
} else if lower.starts_with("st ") {
3
} else {
return None;
};
segments[pos] = format!("{}Saint {}", &segments[pos][..lead], &seg[cut..]);
Some(segments.join(","))
}
/// "ste julie", "st georges": a town name opening with the short Saint/Sainte the way people write
/// it ("STE-JULIE, QC", "ST-GEORGES,QC"), spelled out as the sheet names the town ("sainte julie",
/// "saint georges"), on a sheet with city_tail `saint_communes` = 1. Read only after the name as
/// written finds no town, so a town named "St …" (St. Catharines) keeps its own spelling. None
/// otherwise (Canada, 30.10.2026).
fn saint_commune_name(name: &str) -> Option<String> {
if crate::rules::rules()
.city_tail
.get("saint_communes")
.map(String::as_str)
!= Some("1")
{
return None;
}
let (first, rest) = name.split_once(' ')?;
let full = match first {
"st" => "saint",
"ste" => "sainte",
_ => return None,
};
Some(format!("{full} {rest}"))
}
/// "9-2755 Denison St": on a sheet with city_tail `unit_hyphen` = 1 the leading "<unit>-<civic>" is
/// a unit number and the house number (Canada Post form), not the range the engine reads elsewhere
/// ("15-17": the first number). Read as a unit only when the second number is over 20 and over three
/// times the first, so "1300-1308" and "1-3" stay ranges; the unit is dropped (Canada, 29.10.2026).
fn unit_hyphen_civic(raw: &str) -> Option<String> {
if crate::rules::rules()
.city_tail
.get("unit_hyphen")
.map(String::as_str)
!= Some("1")
{
return None;
}
let body = raw.trim_start();
let lead = &raw[..raw.len() - body.len()];
let body = body.strip_prefix('#').map_or(body, str::trim_start);
let digits = |s: &str| s.bytes().take_while(u8::is_ascii_digit).count();
let unit_len = digits(body);
if !(1..=5).contains(&unit_len) {
return None;
}
let unit: u64 = body[..unit_len].parse().ok()?;
// one letter may follow the unit number ("12B-450 Main St")
let mut after_unit = &body[unit_len..];
if after_unit.starts_with(|c: char| c.is_ascii_alphabetic()) {
after_unit = &after_unit[1..];
}
let civic_part = after_unit.trim_start().strip_prefix('-')?.trim_start();
let civic_len = digits(civic_part);
if !(1..=6).contains(&civic_len) {
return None;
}
let civic: u64 = civic_part[..civic_len].parse().ok()?;
let rest = &civic_part[civic_len..];
// at most one letter of suffix on the civic number ("450B Main St"), then a word boundary
let rest = rest
.strip_prefix(|c: char| c.is_ascii_alphabetic())
.unwrap_or(rest);
let rest_ok = rest.starts_with([' ', ',']);
if civic <= 20 || civic <= 3 * unit || !rest_ok {
return None;
}
Some(format!("{lead}{civic_part}"))
}
/// "5300 No. 3 Road", "5515 47 A Avenue": on a sheet with city_tail `glue_road_numbers` = 1 a road
/// named by a number keeps its number in the name — "No3", "47A" — instead of the parser taking it
/// for the house number ("No. 3": 3) or splitting the letter off. Only in the street segment, only
/// right after the house number and right before a street type word, and not for a type the sheet
/// keys number first (`number_first_types`: "No 2 Highway" is "2 hwy"). Canada, 29.10.2026.
fn glue_road_numbers(raw: &str) -> Option<String> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("glue_road_numbers").map(String::as_str) != Some("1") {
return None;
}
let (street, rest) = raw.split_once(',').unwrap_or((raw, ""));
let words: Vec<&str> = street.split_whitespace().collect();
if words.len() < 4 {
return None;
}
let digits = |w: &str, max: usize| {
!w.is_empty() && w.len() <= max && w.bytes().all(|b| b.is_ascii_digit())
};
let house = |w: &str| {
let d = w.trim_end_matches(|c: char| c.is_ascii_alphabetic());
digits(d, 6) && w.len() - d.len() <= 1
};
let number_first: Vec<&str> = cfg
.get("number_first_types")
.map(|v| v.split_whitespace().collect())
.unwrap_or_default();
let type_word = |w: &str| {
let w = normalize(w);
is_street_type_word(&w)
&& !number_first
.iter()
.any(|t| sheet_short_form(&w, &|_, _| true) == *t)
};
if !house(words[0]) || !type_word(words[3]) {
return None;
}
let glued =
if matches!(words[1].to_ascii_lowercase().as_str(), "no" | "no.") && digits(words[2], 2) {
["No", words[2]].concat()
} else if digits(words[1], 3)
&& words[2].len() == 1
&& words[2].chars().all(|c| c.is_ascii_alphabetic())
{
[words[1], words[2]].concat()
} else {
return None;
};
let mut out = vec![words[0].to_owned(), glued];
out.extend(words[3..].iter().map(|w| (*w).to_owned()));
let street = out.join(" ");
Some(if rest.is_empty() && !raw.contains(',') {
street
} else {
[street.as_str(), rest].join(",")
})
}
/// The first group of a `postal_pattern` code alone ("B3J" of "A9A 9A9"): the forward sortation
/// area people write when they know no more.
fn pattern_postal_head(cfg: &HashMap<String, String>, word: &str) -> bool {
let Some((head, _)) = cfg.get("postal_pattern").and_then(|p| p.split_once(' ')) else {
return false;
};
let mut head_cfg = HashMap::new();
head_cfg.insert("postal_pattern".to_owned(), head.to_owned());
pattern_postal(&head_cfg, word)
}
/// "…, Toronto, ON M6S 1M7", "…, Montréal, Canada H3J 1N5", "…, Halifax, Nova Scotia, B3J":
/// the sheet keeps no postcode for a `postal_pattern` code (it is only set aside), yet its digits
/// read as a house number ("1M7" -> 1) and its place in a segment breaks the tail forms. Every
/// segment after the street loses such codes — the whole code, spaced or glued, or its first
/// group as the last word — and segments left empty go (Canada, 29.10.2026). None when nothing
/// is removed or the sheet declares no pattern.
fn strip_pattern_postals(raw: &str) -> Option<String> {
let cfg = &crate::rules::rules().city_tail;
cfg.get("postal_pattern")?;
let segments: Vec<&str> = raw.split(',').collect();
if segments.len() < 2 {
return None;
}
let mut kept = vec![segments[0].to_owned()];
let mut changed = false;
for segment in &segments[1..] {
let words: Vec<&str> = segment.split_whitespace().collect();
let mut out: Vec<&str> = Vec::new();
let mut i = 0;
while i < words.len() {
if i + 1 < words.len() && pattern_postal(cfg, &format!("{} {}", words[i], words[i + 1]))
{
i += 2;
changed = true;
} else if pattern_postal(cfg, words[i])
|| (i + 1 == words.len() && pattern_postal_head(cfg, words[i]))
{
i += 1;
changed = true;
} else {
out.push(words[i]);
i += 1;
}
}
if !out.is_empty() {
kept.push(format!(" {}", out.join(" ")));
}
}
changed.then(|| kept.join(","))
}
/// "1150 Station St Vancouver BC V6A 4C7", "12 rue Donnacona Québec (Québec) G1R 3Y7": written
/// with no comma, the closing `postal_pattern` code ("4C7" reads as a house number) and the region
/// before it ("Québec" reads as the city of Québec) leave no tail the grammar can split. The
/// query without them — and without country words around the code — is the street and the city
/// alone, which the main parser reads (Canada, 30.10.2026: 121 rows of the distorted set). None
/// when the query has a comma, closes with no such code (none on a sheet without the pattern),
/// or keeps fewer than three words.
fn commaless_postal_tail(raw: &str) -> Option<String> {
let cfg = &crate::rules::rules().city_tail;
if raw.contains(',') {
return None;
}
let mut words: Vec<&str> = strip_trailing_country_words(raw)
.split_whitespace()
.collect();
let postal = pattern_postal_tail(cfg, &words);
if postal == 0 {
return None;
}
words.truncate(words.len() - postal);
let joined = words.join(" ");
let mut words: Vec<&str> = strip_trailing_country_words(&joined)
.split_whitespace()
.collect();
// A region of up to three words ("Prince Edward Island").
if let Some(take) = (1..=3).rev().find(|&take| {
words.len() > take + 2 && region_matches(cfg, &words[words.len() - take..].join(" "))
}) {
words.truncate(words.len() - take);
}
(words.len() >= 3).then(|| words.join(" "))
}
fn strip_unit_designators(raw: &str) -> Option<String> {
if !street_type_last() {
return None;
}
let cfg = &crate::rules::rules().city_tail;
let junk = cfg.get("junk_tail")?;
let is_junk = |w: &str| junk.split_whitespace().any(|j| j == w);
let (head, tail) = match raw.split_once(',') {
Some((h, t)) => (h, Some(t)),
None => (raw, None),
};
let mut toks: Vec<&str> = head.split_whitespace().collect();
let mut cut = false;
// "2nd floor", "18th and 19th floor": an ordinal or a number in front of the designator
// belongs to it, and so does the connector such a pair leaves behind; a designator alone
// at the end ("Basement") is read past too (US, 23.10.2026).
let mut after_connector = false;
loop {
let n = toks.len();
if n >= 2 && toks[n - 1].starts_with('#') {
toks.pop();
cut = true;
} else if n >= 3
&& ((is_junk(&normalize(toks[n - 2]))
&& toks[n - 1].chars().count() <= 4
&& toks[n - 1].chars().all(|c| c.is_alphanumeric()))
|| (is_junk(&normalize(toks[n - 1])) && numbered_word(toks[n - 2])))
{
toks.truncate(n - 2);
cut = true;
} else if n >= 3 && is_junk(&normalize(toks[n - 1])) {
toks.pop();
cut = true;
} else if cut && n >= 3 && matches!(normalize(toks[n - 1]).as_str(), "and" | "&") {
toks.pop();
after_connector = true;
} else if after_connector && n >= 3 && numbered_word(toks[n - 1]) {
toks.pop();
after_connector = false;
} else {
break;
}
}
if !cut || toks.len() < 2 {
return None;
}
let mut out = toks.join(" ");
if let Some(t) = tail {
out.push(',');
out.push_str(t);
}
Some(out)
}
/// Punctuation the tail grammar reads past: a dotted initialism is one word ("U.S." is "US",
/// "N.Y." is "NY", "N.M." is "NM"), and a semicolon between segments is a comma.
/// "Academia 13, Centro Histórico, 6060", "Niza 23-A, 6600 Cuauhtémoc, Ciudad de México": a postal
/// code written without its leading zero (Mexico City codes start with 0; spreadsheets drop it).
/// Under the sheet's `postal_pad_zero` key a code one digit short of `postal_digits`, alone in one
/// of the last two segments or opening it before a name, gets the zero back. None when nothing
/// changes or the sheet declares no such key (Mexico, 31.10.2026: 126 rows of the clean set).
/// The parts `postal_street_suffix` reads: the street name words of the first segment before its
/// last house number (a leading type word or its short form set aside), the number, and the last
/// postal code written in a later segment (one digit short gets its zero back).
fn postal_street_suffix_query(raw: &str) -> Option<(String, u32, u32)> {
let cfg = &crate::rules::rules().city_tail;
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let marked = strip_number_marks(raw);
let raw = marked.as_deref().unwrap_or(raw);
let commas = restore_commas(raw);
let raw = commas.as_deref().unwrap_or(raw);
let parts: Vec<&str> = raw
.split(',')
.map(str::trim)
.filter(|p| !p.is_empty())
.collect();
let (street, rest) = parts.split_first()?;
let code = rest
.iter()
.flat_map(|p| p.split_whitespace())
.rfind(|t| {
(t.len() == digits || t.len() + 1 == digits) && t.bytes().all(|b| b.is_ascii_digit())
})?
.parse::<u32>()
.ok()?;
let words: Vec<String> = normalize(street)
.split_whitespace()
.map(str::to_owned)
.collect();
let at = words
.iter()
.rposition(|w| w.bytes().all(|b| b.is_ascii_digit()))?;
let number = words[at].parse::<u32>().ok()?;
let types = cfg
.get("bare_street_types")
.map(String::as_str)
.unwrap_or("");
let rewrites = &crate::rules::rules().street_rewrites;
let is_type = |w: &str| {
types.split_whitespace().any(|t| t == w)
|| rewrites
.iter()
.any(|(short, full)| short == w && types.split_whitespace().any(|t| t == full))
};
let skip = usize::from(words.first().is_some_and(|w| is_type(w)));
let name = words.get(skip..at)?.join(" ");
(!name.is_empty()).then_some((name, number, code))
}
/// The parts `postal_street_without_number` reads: the street name of the first segment when it
/// carries one of the sheet's `no_number_marks` ("s/n"; a number left is part of the name, "20 de
/// Noviembre"), its type word set aside, and
/// the last postal code written in a later segment.
fn postal_street_without_number_query(raw: &str) -> Option<(String, u32)> {
let cfg = &crate::rules::rules().city_tail;
let marks: Vec<String> = cfg
.get("no_number_marks")?
.split_whitespace()
.map(normalize)
.collect();
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let parts: Vec<&str> = raw
.split(',')
.map(str::trim)
.filter(|p| !p.is_empty())
.collect();
let (street, rest) = parts.split_first()?;
let code = rest
.iter()
.flat_map(|p| p.split_whitespace())
.rfind(|t| {
(t.len() == digits || t.len() + 1 == digits) && t.bytes().all(|b| b.is_ascii_digit())
})?
.parse::<u32>()
.ok()?;
let lowered = street.to_lowercase();
let mut words = Vec::new();
let mut marked = false;
for token in lowered.split_whitespace() {
let n = normalize(token);
if marks.contains(&n) {
marked = true;
} else if !n.is_empty() {
words.push(n);
}
}
if !marked {
return None;
}
let joined = words.join(" ");
let name = without_leading_type(&joined).to_owned();
(!name.is_empty()).then_some((name, code))
}
/// A normalized street name without its first word when that word is a street type of the sheet.
fn without_leading_type(full: &str) -> &str {
match full.split_once(' ') {
Some((first, rest)) if is_street_type_word(first) => rest,
_ => full,
}
}
/// Two strings one edit apart: one letter changed, inserted or dropped, or two neighbours swapped.
fn one_edit_apart(a: &str, b: &str) -> bool {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
if a == b || a.len().abs_diff(b.len()) > 1 {
return false;
}
if a.len() == b.len() {
let diff: Vec<usize> = (0..a.len()).filter(|&i| a[i] != b[i]).collect();
return diff.len() == 1
|| (diff.len() == 2
&& diff[1] == diff[0] + 1
&& a[diff[0]] == b[diff[1]]
&& a[diff[1]] == b[diff[0]]);
}
let (short, long) = if a.len() < b.len() {
(&a, &b)
} else {
(&b, &a)
};
(0..long.len()).any(|i| long[..i] == short[..i] && long[i + 1..] == short[i..])
}
/// How far a neighbour's number may stand from the one written for `postal_namesake_swap`.
const NAMESAKE_NUMBER_GAP: u32 = 10;
/// How many candidates `bare_street_near_code` reads before it filters by the code.
const NEAR_CODE_WIDTH: usize = 5;
/// "Abasolo #508, Centro, 26000", "…, Centro, C.P. 30450": the sheet's `number_mark` ("#") before a
/// house number and its `postal_prefix` word ("cp", written "C.P.", "CP", "C. P.") before a postal
/// code are no part of the address; both are dropped before anything is read. Each is dropped only
/// when digits follow (Mexico, 01.11.2026: the distorted set lost 12 and 9 hits to them).
fn strip_number_marks(raw: &str) -> Option<String> {
let cfg = &crate::rules::rules().city_tail;
let mark = cfg.get("number_mark").and_then(|m| m.chars().next());
let prefix: Vec<char> = cfg
.get("postal_prefix")
.map(|p| p.chars().collect())
.unwrap_or_default();
if mark.is_none() && prefix.is_empty() {
return None;
}
let chars: Vec<char> = raw.chars().collect();
let digit_at = |mut j: usize| {
while j < chars.len() && chars[j] == ' ' {
j += 1;
}
(j < chars.len() && chars[j].is_ascii_digit()).then_some(j)
};
let mut out = String::with_capacity(raw.len());
let mut i = 0;
while i < chars.len() {
if Some(chars[i]) == mark {
if let Some(next) = digit_at(i + 1) {
// "núm. # 5": the space after the mark goes with it
i = if out.ends_with(' ') || out.is_empty() {
next
} else {
i + 1
};
continue;
}
}
let word_start = i == 0 || matches!(chars[i - 1], ' ' | ',');
if word_start && !prefix.is_empty() {
if let Some(next) = postal_prefix_end(&chars, i, &prefix).and_then(digit_at) {
i = next;
continue;
}
}
out.push(chars[i]);
i += 1;
}
(out != raw).then_some(out)
}
/// "2ª Oriente Norte 236 Centro 29000": a query written without a single comma, ending with a postal
/// code, gets its commas back on a sheet with the `commaless_restore` key — before the code, and after
/// the last house number (digits with an optional letter, or "s/n") when words stand between it and
/// the code. The tail grammar reads commas; without them the colonia glues to the street (Mexico,
/// 01.11.2026: distorted set, 118 such rows).
fn restore_commas(raw: &str) -> Option<String> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("commaless_restore").map(String::as_str) != Some("1") || raw.contains(',') {
return None;
}
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let tokens: Vec<&str> = raw.split_whitespace().collect();
let (code, head) = tokens.split_last()?;
let is_code = (code.len() == digits || code.len() + 1 == digits)
&& code.bytes().all(|b| b.is_ascii_digit());
if !is_code || head.len() < 2 {
return None;
}
let is_number = |t: &str| {
let lower = t.to_lowercase();
if lower == "s/n" {
return true;
}
let d = t.bytes().take_while(u8::is_ascii_digit).count();
(1..=5).contains(&d) && t.len() - d <= 1 && t[d..].chars().all(char::is_alphabetic)
};
// the last number before the code, unless a "de" follows it ("20 de Noviembre" is a street name)
let number = (1..head.len()).rev().find(|&i| {
is_number(head[i])
&& head
.get(i + 1)
.is_none_or(|t| !t.eq_ignore_ascii_case("de"))
});
Some(match number {
Some(n) if n + 1 < head.len() => format!(
"{}, {}, {code}",
head[..=n].join(" "),
head[n + 1..].join(" ")
),
_ => format!("{}, {code}", head.join(" ")),
})
}
/// The end of a `postal_prefix` word written at `start`: its letters in any case, each may carry a
/// dot, a single space may stand between them ("C. P."). The caller requires digits next.
fn postal_prefix_end(chars: &[char], start: usize, prefix: &[char]) -> Option<usize> {
let mut j = start;
for (n, letter) in prefix.iter().enumerate() {
if n > 0
&& chars.get(j) == Some(&' ')
&& chars.get(j + 1).map(char::to_ascii_lowercase) == Some(*letter)
{
j += 1;
}
if chars.get(j).map(char::to_ascii_lowercase) != Some(*letter) {
return None;
}
j += 1;
if chars.get(j) == Some(&'.') {
j += 1;
}
}
Some(j)
}
fn pad_short_postal(raw: &str) -> Option<String> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("postal_pad_zero").map(String::as_str) != Some("1") {
return None;
}
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let mut parts: Vec<String> = raw.split(',').map(str::to_owned).collect();
let n = parts.len();
if n < 2 {
return None;
}
let mut changed = false;
for part in parts.iter_mut().skip(n.saturating_sub(2)) {
let trimmed = part.trim();
let (code, rest) = trimmed.split_once(' ').unwrap_or((trimmed, ""));
let short = code.len() + 1 == digits && code.bytes().all(|b| b.is_ascii_digit());
if short && (rest.is_empty() || rest.chars().next().is_some_and(char::is_alphabetic)) {
*part = format!(" 0{trimmed}");
changed = true;
}
}
changed.then(|| parts.join(","))
}
/// The readings of a cityless query whose last segment is a postal code ("Independencia 684,
/// Centro Histórico, 44100"): the street segment with the code alone, then the same with each of
/// the sheet's `bare_street_types` in front unless the street already opens with it. Empty when
/// the sheet declares no such types (every sheet but Mexico, 31.10.2026). A type written short
/// ("Av.") is spelled out instead.
fn bare_street_postal_variants(raw: &str) -> Vec<String> {
let cfg = &crate::rules::rules().city_tail;
let Some(types) = cfg.get("bare_street_types") else {
return Vec::new();
};
let parts: Vec<&str> = raw
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect();
if parts.len() < 2 {
return Vec::new();
}
let Some(code) = postal_segment(cfg, parts[parts.len() - 1]) else {
return Vec::new();
};
let street = parts[0];
let first = normalize(street)
.split_whitespace()
.next()
.unwrap_or("")
.to_owned();
let mut out = Vec::new();
if parts.len() > 2 {
out.push(format!("{street}, {code}"));
}
// "Av. Chapultepec 420": a type written short is spelled out from the sheet's street rewrites
// ("av" -> "avenida") instead of getting a second type in front (Mexico, 01.11.2026).
let expanded = crate::rules::rules()
.street_rewrites
.iter()
.find(|(short, full)| *short == first && types.split_whitespace().any(|t| t == full))
.map(|(_, full)| full.as_str());
if let Some(full) = expanded {
let rest = street.split_once(' ').map_or("", |(_, rest)| rest.trim());
out.push(format!("{full} {rest}, {code}"));
return out;
}
for t in types.split_whitespace() {
if first != t {
out.push(format!("{t} {street}, {code}"));
}
}
out
}
fn tidy_tail_punctuation(raw: &str) -> String {
let chars: Vec<char> = raw.chars().collect();
let mut out = String::with_capacity(raw.len());
let mut i = 0;
while i < chars.len() {
// "X.Y." or "X.Y" with single letters: drop the dots between and after them
let mut j = i;
let mut letters = 0;
while j + 1 < chars.len() && chars[j].is_alphabetic() && chars[j + 1] == '.' {
letters += 1;
j += 2;
}
let trailing_letter = letters >= 1
&& j < chars.len()
&& chars[j].is_alphabetic()
&& (j + 1 >= chars.len() || !chars[j + 1].is_alphanumeric());
if letters >= 2 || (letters >= 1 && trailing_letter) {
let end = if trailing_letter { j + 1 } else { j };
for &c in &chars[i..end] {
if c != '.' {
out.push(c);
}
}
i = end;
continue;
}
out.push(if chars[i] == ';' { ',' } else { chars[i] });
i += 1;
}
out
}
/// The answer's street differs from the street the query wrote only by words the sheet's
/// street rewrites know — a direction or a type word ("Peachtree Street" against "Peachtree
/// Street Northwest", "Park Street" against "South Park Street"). Under a region anchor such
/// a street counts as the exact one: people drop the direction, the sheet keeps it (US,
/// 23.10.2026). Data-driven: only a sheet with a trailing type and rewrites relaxes, and a
/// street with any other extra word ("Peachtree Center Avenue") does not qualify.
fn street_differs_only_by_rewrite_words(query_street: &str, hit_street: &str) -> bool {
if !street_type_last() {
return false;
}
let rewrites = &crate::rules::rules().street_rewrites;
let known =
|w: &str| is_street_type_word(w) || rewrites.iter().any(|(from, to)| from == w || to == w);
let query_norm = normalize(query_street);
let asked: HashSet<&str> = query_norm
.split(' ')
.filter(|w| !w.is_empty() && !w.bytes().all(|b| b.is_ascii_digit()) && !known(w))
.collect();
if asked.is_empty() {
return false;
}
let hit_norm = normalize(hit_street);
let given: Vec<&str> = hit_norm.split(' ').filter(|w| !w.is_empty()).collect();
// A direction the query does write must be in the answer too, as written or through its
// rewrite ("N Cottonwood" is not "South Cottonwood Street").
let same_word = |a: &str, b: &str| {
a == b
|| rewrites
.iter()
.any(|(from, to)| (from == a && to == b) || (from == b && to == a))
};
// The same for a type the query writes: "Madison Avenue" is not "Madison St".
let written_kept = query_norm
.split(' ')
.filter(|w| !w.is_empty() && known(w))
.all(|w| given.iter().any(|g| same_word(w, g)));
written_kept
&& asked.iter().all(|w| given.contains(w))
&& given.iter().all(|w| asked.contains(w) || known(w))
}
fn city_tail(raw: &str) -> Option<CityTail> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("enabled").map(String::as_str) != Some("1") {
return None;
}
let tidied = tidy_tail_punctuation(raw);
let raw: &str = &tidied;
let regions = cfg.get("regions")?;
let forms = cfg.get("forms")?;
let mut parts: Vec<&str> = raw.split(',').map(str::trim).collect();
// A trailing country ("…, New York City, NY, United States"), a phone number or an
// advertisement ("…, KENTUCKY, near the mall") is no part of the tail grammar: country
// words come from countries_tail, the opening words of junk from the sheet's `junk_tail`
// key, and a phone segment is digits in groups with no postal-code shape; such segments
// are dropped first.
while parts.len() > 1
&& parts
.last()
.is_some_and(|segment| junk_tail_segment(cfg, segment))
{
parts.pop();
}
// "…, Suite 1200, Indianapolis, IN": a junk segment between the street and the city is
// dropped as well; the first segment (the street) is never judged.
if parts.len() > 2 {
let inner: Vec<&str> = parts[1..parts.len() - 1]
.iter()
.copied()
.filter(|segment| !junk_tail_segment(cfg, segment))
.collect();
let last = parts[parts.len() - 1];
parts.truncate(1);
parts.extend(inner);
parts.push(last);
}
// "…, NV 89146 USA": the country glued to the postal segment is no part of it either. A
// segment that is a region name as a whole keeps its last word: "Ciudad de México" and
// "Estado de México" end with a country word of the sheet, and "Ciudad de" is no region
// (Mexico, 01.11.2026).
if let Some(last) = parts.last_mut() {
if !region_matches(cfg, last) {
*last = strip_trailing_country_words(last);
}
}
let mut end = parts.len().checked_sub(1)?;
let postal_digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let postal_split = cfg.get("postal_split")?.parse::<usize>().ok()?;
let last = parts[end];
let mut stripped_postal = None;
// A whole postal segment, with or without the declared extension ("…, PA, 19095-1898"):
// the retry keeps its five-digit core.
if let Some(core) = postal_segment(cfg, last) {
end = end.checked_sub(1)?;
stripped_postal = Some(core);
} else if pattern_postal(cfg, last.trim()) {
// "…, Toronto, ON, M5X 1A9": the code goes; the sheet keeps no numeric postcode for it.
end = end.checked_sub(1)?;
}
let _ = (postal_digits, postal_split);
let _ = regions;
let is_region = |s: &str| region_matches(cfg, s);
let has_form = |s: &str| forms.split_whitespace().any(|v| v == s);
let (city_pos, mut city, region_segment) = if has_form("comma") && is_region(parts[end]) {
let pos = end.checked_sub(1)?;
(pos, parts[pos], parts[end])
} else if let Some((region, _)) = split_region_postal(cfg, parts[end]) {
let pos = end.checked_sub(1)?;
(pos, parts[pos], region)
} else if let Some(glued) = glued_city_region(cfg, &parts, end, &has_form) {
// "…, Philadelphia PA 19122-6117": the city and the region share the last segment.
// Re-read with the comma the writer left out; the comma grammar does the rest.
return city_tail(&glued);
} else if has_form("hyphen") {
let (city, region) = parts[end].rsplit_once(" - ")?;
if !is_region(region.trim()) {
return None;
}
(end, city.trim(), region.trim())
} else {
return None;
};
// "20 North Main Street Providence, RI 02903": the street and the city share one segment.
// On a sheet whose type trails the name the city is what follows the last type word (and
// the direction after it); re-read with the comma the writer left out.
if let Some(split) = street_glued_to_city(&parts, city_pos) {
return city_tail(&split);
}
// "…, Zona Centro, 44100 Guadalajara, Jal.": under the `postal_city` form the city segment
// opens with the postal code. The code is the tail's postal code, and the region-less
// reading keeps the street, the city and the code only: an inner segment (a colonia the
// sheet keys nowhere, "Centro") read as a place sends the street to a commune of that name
// a thousand kilometres away (Mexico, 31.10.2026).
let mut city_postal = None;
if has_form("postal_city") {
if let Some((code, rest)) = city.split_once(' ') {
if code.len() == postal_digits
&& code.bytes().all(|b| b.is_ascii_digit())
&& rest.chars().any(char::is_alphabetic)
{
city_postal = Some(code);
city = rest.trim();
}
}
}
// An administrative name is not a postal code or an address fragment.
if city_pos == 0
|| !city.chars().any(char::is_alphabetic)
// A dot of an abbreviation inside the name ("St. Louis", "Ft. Meade") is a name still.
|| city
.nfc()
.any(|c| !(c.is_alphabetic() || c.is_whitespace() || matches!(c, '-' | '\'' | '’' | '.')))
|| city.contains("..")
{
return None;
}
let retry = if city_pos == 3
&& !parts[0].is_empty()
&& !parts[2].is_empty()
&& (parts[1].chars().any(|c| c.is_ascii_digit())
|| matches!(normalize(parts[1]).as_str(), "s n" | "sn"))
{
Some(
parts
.iter()
.enumerate()
.filter_map(|(i, s)| (i != 2).then_some(*s))
.collect::<Vec<_>>()
.join(", "),
)
} else if let (true, Some(postal)) = (
(has_form("comma") && is_region(parts[end]))
|| split_region_postal(cfg, parts[end]).is_some_and(|(_, p)| p.is_none()),
stripped_postal,
) {
// "<city>, <region>, <postal>": the same glue once commas are gone ("boston ma"), the same
// retry — region word out, postal code kept as its own segment (US, 21.10.2026: 634 rows).
let mut kept: Vec<&str> = parts[..end].to_vec();
kept.push(postal);
Some(kept.join(", "))
} else if has_form("comma") && region_is_name(cfg, parts[end]) && stripped_postal.is_none() {
// "<city>, <State Name>": the name glues to the city once commas are gone; retry without it.
Some(parts[..end].join(", "))
} else if let Some((_, Some(postal))) = split_region_postal(cfg, parts[end]) {
// Under the `region_postal` form the parser sees "<city> <region> <postal>" as one
// flat tail once commas are gone, and the region word glues to the city name
// ("boston ma"): the retry is the same query with the region word removed and the
// postal code kept as its own segment ("..., Boston, MA 02108" -> "..., Boston, 02108").
// A region alone ("..., Boston, MA") is the comma form and keeps its established path.
// Data-driven: only a sheet declaring the form reaches this branch (US, 20.10.2026).
let mut kept: Vec<&str> = parts[..end].to_vec();
kept.push(postal);
Some(kept.join(", "))
} else {
None
};
let tail_postal = match split_region_postal(cfg, parts[end]) {
Some((_, Some(postal))) => Some(postal),
_ => stripped_postal.or(city_postal),
};
let without_region = {
let mut kept: Vec<&str> = if city_postal.is_some() {
vec![parts[0], city]
} else {
parts[..city_pos + 1].to_vec()
};
if let Some(postal) = tail_postal {
kept.push(postal);
}
kept.join(", ")
};
let without_city = tail_postal.map(|postal| {
let mut kept: Vec<&str> = parts[..city_pos].to_vec();
kept.push(postal);
kept.join(", ")
});
Some(CityTail {
city: normalize(city),
retry,
region: region_code(cfg, region_segment),
region_word: normalize(region_segment),
without_region,
without_city,
postal_city: city_postal.is_some(),
})
}
// Field retries are separate from the frozen single-district retry grammar.
// Explicit recipient syntax is data owned by this sheet. Never drop a street
// field merely because another comma-delimited field resembles an address.
fn recipient_field_retry(raw: &str) -> Option<&str> {
let prefixes = &crate::rules::rules().recipient_prefixes;
if prefixes.is_empty() {
return None;
}
let (first, address) = raw.split_once(',')?;
let first = normalize(first);
let recognized = prefixes.iter().any(|prefix| {
let prefix = normalize(prefix);
!prefix.is_empty()
&& first
.strip_prefix(&prefix)
.is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
});
let address = address.trim();
(recognized && !address.is_empty()).then_some(address)
}
fn recipient_field_choose(
original: Vec<(Hit, [f32; N_FEATS])>,
raw: &str,
retry: impl FnOnce(&str) -> Vec<(Hit, [f32; N_FEATS])>,
) -> Vec<(Hit, [f32; N_FEATS])> {
empty_field_choose(original, || recipient_field_retry(raw), retry)
}
struct AddressFieldRetries {
city: String,
number: u32,
forms: Vec<String>,
}
fn empty_field_choose<Q: AsRef<str>>(
original: Vec<(Hit, [f32; N_FEATS])>,
rewrite: impl FnOnce() -> Option<Q>,
retry: impl FnOnce(&str) -> Vec<(Hit, [f32; N_FEATS])>,
) -> Vec<(Hit, [f32; N_FEATS])> {
if !original.is_empty() {
return original;
}
rewrite().map_or(original, |query| retry(query.as_ref()))
}
fn numeric_house_prefix(value: &str) -> Option<u32> {
let digits: String = value.chars().take_while(char::is_ascii_digit).collect();
(!digits.is_empty()).then(|| digits.parse().ok()).flatten()
}
// Number labels belong to the number field, never to street-name tokens.
fn field_number_unlabel(value: &str) -> &str {
let value = value.trim();
for label in ["n.º", "nº", "n°", "N.º", "Nº", "N°"] {
if let Some(rest) = value.strip_prefix(label) {
return rest.trim_start();
}
}
value
}
fn field_number_rewrite(raw: &str) -> String {
let mut parts: Vec<&str> = raw.split(',').collect();
if let Some(number) = parts.get_mut(1) {
*number = field_number_unlabel(number);
}
parts.join(",")
}
fn address_field_retries(raw: &str) -> Option<AddressFieldRetries> {
address_field_retries_anchored(&field_number_rewrite(raw))
}
// Unanchored input is deliberately limited to street + a separate number field.
// Additional comma fields may name a city; they must not silently lose its guard.
fn cityless_field_address(raw: &str) -> Option<(String, u32)> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("enabled").map(String::as_str) != Some("1") {
return None;
}
let parts: Vec<&str> = raw.split(',').map(str::trim).collect();
if parts.len() != 2 || !parts[0].chars().any(char::is_alphabetic) {
return None;
}
let field = field_number_unlabel(parts[1]);
let number = field.split_once(" - ").map_or(field, |(n, _)| n);
let number = number.split_once(" – ").map_or(number, |(n, _)| n);
let number = number.split_once(" — ").map_or(number, |(n, _)| n).trim();
let digits = number.chars().take_while(char::is_ascii_digit).count();
let suffix = &number[digits..];
if digits == 0
|| digits > 5
|| !(suffix.is_empty() || (suffix.len() == 1 && suffix.as_bytes()[0].is_ascii_alphabetic()))
{
return None;
}
// A region in the remaining payload is an explicit geographic anchor.
if cfg.get("regions").is_some_and(|regions| {
field.split_whitespace().any(|word| {
regions
.split_whitespace()
.any(|r| r.eq_ignore_ascii_case(word))
})
}) {
return None;
}
Some((prepared_query_key(parts[0]), numeric_house_prefix(number)?))
}
// Only explicit one-token type pairs in the sheet's street rules share a key.
// Linkers, numerals and inner-name rewrites never enter this equivalence graph.
fn field_street_type_aliases() -> HashMap<String, String> {
let rules = crate::rules::rules();
let mut graph: HashMap<&str, Vec<&str>> = HashMap::new();
for (from, to) in &rules.street_rewrites {
if from.split_whitespace().count() != 1
|| to.split_whitespace().count() != 1
|| !rules.is_street_type(from)
|| !rules.is_street_type(to)
{
continue;
}
graph.entry(from).or_default().push(to);
graph.entry(to).or_default().push(from);
}
let mut aliases = HashMap::new();
for &start in graph.keys() {
if aliases.contains_key(start) {
continue;
}
let mut group = Vec::new();
let mut pending = vec![start];
while let Some(word) = pending.pop() {
if group.contains(&word) {
continue;
}
group.push(word);
if let Some(next) = graph.get(word) {
pending.extend(next.iter().copied());
}
}
// Stable across rule order and direction, including transitive pairs.
let canonical = *group.iter().min().expect("nonempty type component");
for word in group {
aliases.insert(word.to_owned(), canonical.to_owned());
}
}
aliases
}
fn field_street_type_key(prepared: &str, aliases: &HashMap<String, String>) -> String {
let Some((kind, rest)) = prepared.split_once(' ') else {
return prepared.to_owned();
};
aliases.get(kind).map_or_else(
|| prepared.to_owned(),
|canonical| format!("{canonical} {rest}"),
)
}
fn address_field_retries_anchored(raw: &str) -> Option<AddressFieldRetries> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("enabled").map(String::as_str) != Some("1") {
return None;
}
let regions = cfg.get("regions")?;
let forms = cfg.get("forms")?;
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let split = cfg.get("postal_split")?.parse::<usize>().ok()?;
let postal = |value: &str| {
let d: String = value.chars().filter(char::is_ascii_digit).collect();
d.len() == digits
&& (value == d
|| (split < digits && value == format!("{}-{}", &d[..split], &d[split..])))
};
let _ = regions;
let region = |value: &str| region_matches(cfg, value);
let parts: Vec<&str> = raw.split(',').map(str::trim).collect();
// Locate the explicit city/region anchor even when unit payload follows it.
// Region names and postal shape still come from sheet rules, never country code.
let (region_pos, mut city_pos, mut city, region_name, separate_region) =
parts.iter().enumerate().rev().find_map(|(pos, part)| {
if forms.split_whitespace().any(|f| f == "comma") && region(part) {
let city_pos = pos.checked_sub(1)?;
Some((pos, city_pos, parts[city_pos], *part, true))
} else if let Some((code, _)) = split_region_postal(cfg, part) {
let city_pos = pos.checked_sub(1)?;
Some((pos, city_pos, parts[city_pos], code, true))
} else if forms.split_whitespace().any(|f| f == "hyphen") {
let (name, code) = part.rsplit_once(" - ")?;
region(code.trim()).then_some((pos, pos, name.trim(), code.trim(), false))
} else {
None
}
})?;
// A postal segment between city and UF is preserved in A, not mistaken for city.
if postal(city) {
city_pos = city_pos.checked_sub(1)?;
city = parts[city_pos];
}
if city_pos == 0
|| !city.chars().any(char::is_alphabetic)
|| city
.nfc()
.any(|c| !(c.is_alphabetic() || c.is_whitespace() || matches!(c, '-' | '\'' | '’')))
{
return None;
}
let house_token = |token: &str| {
let n = token.chars().take_while(char::is_ascii_digit).count();
let rest = &token[n..];
n > 0
&& n <= 5
&& (rest.is_empty() || (rest.len() == 1 && rest.as_bytes()[0].is_ascii_alphabetic()))
};
let separate_number = parts
.get(1)
.map(|p| p.split_once(" - ").map_or(*p, |(n, _)| n).trim());
let (address_end, number) = if separate_number.is_some_and(house_token) {
(2, numeric_house_prefix(separate_number?)?)
} else {
let token = parts[0].split_whitespace().last()?;
if !parts[0].contains(char::is_whitespace) || !house_token(token) {
return None;
}
(1, numeric_house_prefix(token)?)
};
if city_pos < address_end || parts[0].is_empty() {
return None;
}
let mut a = parts[..address_end].to_vec();
a.extend(
parts[address_end..city_pos]
.iter()
.filter(|p| postal(p))
.copied(),
);
a.extend_from_slice(&parts[city_pos..]);
let mut b = parts[..address_end].to_vec();
if address_end == 2 {
b[1] = separate_number?;
}
b.push(city);
// Keep the two accepted retries first, with their original byte surfaces.
let mut retries = vec![a.join(", "), b.join(", ")];
let mut push = |query: String| {
// Empty slots keep diagnostic form ids stable without repeating a search.
if query == raw || retries.contains(&query) {
retries.push(String::new());
} else {
retries.push(query);
}
};
let join = |p: Vec<&str>| p.join(", ");
// The query-visible probes retain the original number and city guard below.
let no_postal = join(parts.iter().copied().filter(|p| !postal(p)).collect());
push(no_postal); // no_postal
let without_region = |hyphen: bool| {
let mut p = Vec::new();
for (i, part) in parts.iter().enumerate() {
if i == city_pos {
p.push(if hyphen {
format!("{city} - {region_name}")
} else {
city.to_owned()
});
} else if i != region_pos || !separate_region {
p.push((*part).to_owned());
}
}
p.join(", ")
};
push(without_region(false)); // no_region
push(without_region(true)); // city_hyphen
let mut comma_city = parts.iter().map(|p| (*p).to_owned()).collect::<Vec<_>>();
if !separate_region {
comma_city[city_pos] = format!("{city}, {region_name}");
}
push(comma_city.join(", ")); // city_comma
for (kind, hyphen, prefix) in [(0, false, false), (1, true, false), (2, false, true)] {
let rewritten = parts
.iter()
.map(|part| {
if !postal(part) {
return (*part).to_owned();
}
let d: String = part.chars().filter(char::is_ascii_digit).collect();
if prefix && split > 0 && split < digits {
d[..split].to_owned()
} else if hyphen && split > 0 && split < digits {
format!("{}-{}", &d[..split], &d[split..])
} else {
d
}
})
.collect::<Vec<_>>()
.join(", ");
match kind {
0 => push(rewritten), // postal_plain
1 => push(rewritten), // postal_hyphen
_ => push(rewritten), // postal_prefix
}
}
push(join(
parts
.iter()
.enumerate()
.filter_map(|(i, p)| (i <= region_pos || postal(p)).then_some(*p))
.collect(),
)); // no_unit
// Separate an attached terminal number only; never infer one from street digits.
if address_end == 1 {
if let Some((street, number)) = parts[0].rsplit_once(char::is_whitespace) {
let mut split_parts = vec![street, number];
split_parts.extend_from_slice(&parts[1..]);
push(join(split_parts)); // separate_house
push(format!("{street}, {number}, {city}")); // clean_fields
}
}
Some(AddressFieldRetries {
city: normalize(city),
number,
forms: retries,
})
}
fn address_field_choose(
original: Vec<(Hit, [f32; N_FEATS])>,
tail: &AddressFieldRetries,
mut retry: impl FnMut(usize, &str) -> Vec<(Hit, [f32; N_FEATS])>,
) -> Vec<(Hit, [f32; N_FEATS])> {
if original.first().is_some_and(|(hit, _)| {
hit.precision == "house"
|| (matches!(hit.precision, "near" | "interp") && normalize(&hit.commune) == tail.city)
}) {
return original;
}
for (i, q) in tail.forms.iter().enumerate() {
if q.is_empty() {
continue;
}
let alternate = retry(i, q);
let accepted = alternate.first().is_some_and(|(hit, _)| {
hit.precision == "house"
&& hit.housenumber.as_deref().and_then(numeric_house_prefix) == Some(tail.number)
&& normalize(&hit.commune) == tail.city
});
crate::diagnosis::field_retry(i, accepted);
if accepted {
return alternate;
}
}
original
}
/// A score as a sort key with a total order: NaN sorts below every number. Rust's sort panics on
/// a comparator that is not a total order (US, 22.10.2026: 71 silent empties behind one).
fn score_key(score: f32) -> f32 {
if score.is_nan() {
f32::NEG_INFINITY
} else {
score
}
}
/// How good the first answer is, for choosing between two readings of one query: precision
/// (house > interpolation > neighbour > the rest), then an exact street, then an exact commune.
fn hits_quality(hits: &[(Hit, [f32; N_FEATS])]) -> (u8, bool, bool) {
hits.first().map_or((0, false, false), |(hit, _)| {
(
match hit.precision {
"house" => 3,
"interp" => 2,
"near" => 1,
_ => 0,
},
hit.flags.contains(&"street_exact"),
hit.flags.contains(&"commune_exact"),
)
})
}
/// The order of two readings of a place-first query: an exact street with a house, an
/// interpolation or a neighbour near the number written comes before any fuzzy one, then
/// `hits_quality`. "Ottawa, ON, 230
/// Queen Street" read as written lands on a house of Queen Mary ST (one edit away); read address
/// first it is an interpolation on Queen ST itself (Canada, 30.10.2026).
/// `address_first` is the reordered query: its leading number is the one written.
fn city_first_quality(
hits: &[(Hit, [f32; N_FEATS])],
address_first: &str,
) -> (bool, (u8, bool, bool)) {
(
strong_first(hits)
&& hits.first().is_some_and(|(hit, _)| {
hit.flags.contains(&"street_exact")
&& !neighbour_far_from_written(hit, address_first)
}),
hits_quality(hits),
)
}
fn strong_first(hits: &[(Hit, [f32; N_FEATS])]) -> bool {
hits.first()
.is_some_and(|(hit, _)| matches!(hit.precision, "house" | "interp" | "near"))
}
fn postal_retry(raw: &str) -> Option<String> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("enabled").map(String::as_str) != Some("1") {
return None;
}
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let split = cfg.get("postal_split")?.parse::<usize>().ok()?;
if split == 0 || split >= digits {
return None;
}
let bytes = raw.as_bytes();
let mut out = String::new();
let mut copied = 0;
let mut i = 0;
while i < bytes.len() {
if !bytes[i].is_ascii_digit() {
i += 1;
continue;
}
let start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
let blocked = |c: char| c == '-' || c.is_numeric();
if i - start == digits
&& !raw[..start].chars().next_back().is_some_and(blocked)
&& !raw[i..].chars().next().is_some_and(blocked)
{
out.push_str(&raw[copied..start + split]);
out.push('-');
copied = start + split;
}
}
if copied == 0 {
None
} else {
out.push_str(&raw[copied..]);
Some(out)
}
}
fn city_tail_choose(
original: Vec<(Hit, [f32; N_FEATS])>,
city: &str,
retry: impl FnOnce() -> Vec<(Hit, [f32; N_FEATS])>,
) -> Vec<(Hit, [f32; N_FEATS])> {
if strong_first(&original) {
return original;
}
let alternate = retry();
if alternate
.first()
.is_some_and(|(hit, _)| normalize(&hit.commune) == city)
{
return alternate;
}
if original
.first()
.is_some_and(|(hit, _)| normalize(&hit.commune) == city)
{
return original;
}
Vec::new()
}
/// "63, chemin des Pionniers Est, L'Islet (Québec)": the province word is also a commune
/// (Québec City), and a fuzzy street there is a strong first answer that outranks the named
/// town. When the strong answer sits in the commune the region word names, and not in the named
/// city, the retry without the region is read, and its answer in the named city wins; otherwise
/// the choice is `city_tail_choose`'s (Canada, 29.10.2026).
fn city_tail_choose_region(
original: Vec<(Hit, [f32; N_FEATS])>,
city: &str,
region_word: &str,
retry: impl FnOnce() -> Vec<(Hit, [f32; N_FEATS])>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let in_commune = |hits: &Vec<(Hit, [f32; N_FEATS])>, name: &str| {
hits.first()
.is_some_and(|(hit, _)| normalize(&hit.commune) == name)
};
if strong_first(&original) && city != region_word && in_commune(&original, region_word) {
let alternate = retry();
return if in_commune(&alternate, city) {
alternate
} else {
original
};
}
city_tail_choose(original, city, retry)
}
/// One answer. Serialized by hand (below) so every JSON surface also carries `weak`.
#[derive(Clone)]
pub struct Hit {
pub lat: f64,
pub lon: f64,
pub precision: &'static str,
pub score: f32,
/// calibrated confidence 0..1 (unlike the raw score it is comparable across queries,
/// suitable for threshold-based garbage cutoff).
pub confidence: f32,
pub street: String,
/// matched house number with its suffix ("27", "12bis"). For forward answers this
/// is the address actually used for the returned point: a near snap therefore reports
/// its stored neighbour rather than echoing the requested number. Street-only answers
/// leave it absent.
pub housenumber: Option<String>,
pub commune: String,
pub postcode: String,
/// match flags for output (explainability): street_exact/street_fuzzy,
/// commune_exact/commune_prefix, house_rep, pc_exact/pc_dept, ml.
/// City-only provenance: place_exact (exact commune name) or
/// place_prefix_group (prefix commune group); exactly one per city_hit.
pub flags: Vec<&'static str>,
/// administrative region (Who's on First, reverse point-in-polygon).
pub region: Option<String>,
pub distance_m: Option<f64>,
}
/// Field for field what `#[derive(Serialize)]` wrote, then `weak`: the engine's own verdict that
/// the answer needs a check before use (`hit_is_weak`, the rule of the POI cascade). It is computed
/// at output, never stored, so a later change of `confidence` or `flags` cannot leave it stale, and
/// it comes last so that dropping it gives back the bytes of earlier releases.
impl Serialize for Hit {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut out = serializer.serialize_struct("Hit", 13)?;
out.serialize_field("lat", &self.lat)?;
out.serialize_field("lon", &self.lon)?;
out.serialize_field("precision", &self.precision)?;
out.serialize_field("score", &self.score)?;
out.serialize_field("confidence", &self.confidence)?;
out.serialize_field("street", &self.street)?;
match &self.housenumber {
Some(number) => out.serialize_field("housenumber", number)?,
None => out.skip_field("housenumber")?,
}
out.serialize_field("commune", &self.commune)?;
out.serialize_field("postcode", &self.postcode)?;
if self.flags.is_empty() {
out.skip_field("flags")?;
} else {
out.serialize_field("flags", &self.flags)?;
}
match &self.region {
Some(region) => out.serialize_field("region", region)?,
None => out.skip_field("region")?,
}
match &self.distance_m {
Some(distance) => out.serialize_field("distance_m", distance)?,
None => out.skip_field("distance_m")?,
}
out.serialize_field("weak", &hit_is_weak(self))?;
out.end()
}
}
/// WOF administrative region: name + bbox + rings (lat,lon x1e7) for ray-casting PIP.
struct AdminRegion {
name: String,
min_lat: i32,
min_lon: i32,
max_lat: i32,
max_lon: i32,
rings: Vec<Vec<(i32, i32)>>,
}
/// Load the sibling "<stem>_admin.bin" (WOF region polygons) if present. Format: "WOFA" +
/// u32 n; per region: u8 len + name, bbox i32 x4, u16 n_rings; per ring: u16 n_pts + (i32,i32) x n.
/// The admin sidecar is loaded by DERIVING its name from the sheet (`<stem>_admin.bin`). A release
/// rename that moves the sheet but not the sidecar would silently drop regions, so
/// distinguish the cases and WARN when a mismatched sibling exists.
enum AdminSidecar {
Loaded(Vec<AdminRegion>),
MissingWithSibling { expected: String, found: String },
MissingClean,
NotWofa(String),
}
fn admin_sidecar(index_path: &Path) -> AdminSidecar {
let stem = index_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("");
let expected = format!("{stem}_admin.bin");
// country prefix (leading ISO-2) so an UNRELATED sidecar (e.g. uz_admin.bin next to rs.bin)
// never triggers a false rename warning — only a same-country orphan does.
let country = |n: &str| -> String { n.chars().take(2).collect::<String>().to_lowercase() };
let sheet_cc = country(stem);
let p = index_path.with_file_name(&expected);
match std::fs::read(&p) {
Ok(d) if d.len() > 8 && &d[..4] == b"WOFA" => AdminSidecar::Loaded(parse_admin_body(&d)),
Ok(_) => AdminSidecar::NotWofa(expected),
Err(_) => {
// scan for a mismatched sibling *_admin.bin OF THE SAME COUNTRY (a rename that forgot it)
if let Some(dir) = index_path.parent() {
if let Ok(rd) = std::fs::read_dir(dir) {
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
if name != expected
&& name.ends_with("_admin.bin")
&& country(&name) == sheet_cc
{
let mut buf = [0u8; 4];
let is_wofa = std::fs::File::open(e.path())
.and_then(|mut f| std::io::Read::read_exact(&mut f, &mut buf))
.is_ok()
&& &buf == b"WOFA";
if is_wofa {
return AdminSidecar::MissingWithSibling {
expected,
found: name,
};
}
}
}
}
}
AdminSidecar::MissingClean
}
}
}
fn load_admin(index_path: &Path) -> Vec<AdminRegion> {
match admin_sidecar(index_path) {
AdminSidecar::Loaded(v) => v,
AdminSidecar::MissingWithSibling { expected, found } => {
eprintln!(
"warning: {index_path:?} expected admin sidecar {expected} but it is missing; found \
{found} next to it — regions disabled. Rename the sidecar to match the sheet (release rename?)."
);
Vec::new()
}
AdminSidecar::NotWofa(name) => {
eprintln!("warning: {name} next to {index_path:?} is not a WOFA admin sidecar — regions disabled");
Vec::new()
}
AdminSidecar::MissingClean => Vec::new(),
}
}
/// Parse a validated (magic-checked) WOFA sidecar body into regions. A truncated or corrupt one
/// degrades to what parsed cleanly, never a panic — every read is bounds-checked.
fn parse_admin_body(data: &[u8]) -> Vec<AdminRegion> {
let mut o = 4usize;
let rd_u32 = |d: &[u8], o: usize| u32::from_le_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]);
let rd_i32 = |d: &[u8], o: usize| i32::from_le_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]);
let rd_u16 = |d: &[u8], o: usize| u16::from_le_bytes([d[o], d[o + 1]]) as usize;
let n = rd_u32(data, o) as usize;
o += 4;
let mut out = Vec::new();
for _ in 0..n {
if o >= data.len() {
break;
}
let nl = data[o] as usize;
o += 1;
if o + nl + 18 > data.len() {
break; // name + bbox + ring count do not fit
}
let name = String::from_utf8_lossy(&data[o..o + nl]).into_owned();
o += nl;
let (min_lat, min_lon, max_lat, max_lon) = (
rd_i32(data, o),
rd_i32(data, o + 4),
rd_i32(data, o + 8),
rd_i32(data, o + 12),
);
o += 16;
let nr = rd_u16(data, o);
o += 2;
let mut rings = Vec::new();
let mut truncated = false;
for _ in 0..nr {
if o + 2 > data.len() {
truncated = true;
break;
}
let np = rd_u16(data, o);
o += 2;
if o + np * 8 > data.len() {
truncated = true;
break;
}
let mut ring = Vec::with_capacity(np);
for _ in 0..np {
ring.push((rd_i32(data, o), rd_i32(data, o + 4)));
o += 8;
}
rings.push(ring);
}
if truncated {
break;
}
out.push(AdminRegion {
name,
min_lat,
min_lon,
max_lat,
max_lon,
rings,
});
}
out
}
/// Is the point (lat,lon x1e7) inside the region? Even-odd ray casting over all rings (holes/multipolygons).
fn point_in_rings(la: i32, lo: i32, rings: &[Vec<(i32, i32)>]) -> bool {
let mut inside = false;
for ring in rings {
let n = ring.len();
if n < 3 {
continue;
}
let mut j = n - 1;
for i in 0..n {
let (yi, xi) = ring[i];
let (yj, xj) = ring[j];
if (yi > la) != (yj > la) {
let xint = xi as i64
+ (la as i64 - yi as i64) * (xj as i64 - xi as i64) / (yj as i64 - yi as i64);
if (lo as i64) < xint {
inside = !inside;
}
}
j = i;
}
}
inside
}
/// Calibrated confidence 0..1 = P(result within 150 m). Logistic model with empirically
/// fitted coefficients; predicted probabilities track observed hit rates.
fn confidence_score(precision: &str, f: &Feats, _name_sim: i32) -> f32 {
let mut z = -2.748f32; // bias
z += match precision {
"house" => 0.965,
"interp" => 0.158,
"near" => -0.412,
"street" => -0.222,
_ => -0.506, // city
};
if f.street_exact {
z += 0.899;
}
if f.street_fuzzy {
z -= 0.410;
}
if f.commune_exact {
z += 2.360;
}
if f.commune_prefix {
z += 1.240;
}
if f.house_exact_rep {
z += 1.280;
}
if f.pc_exact {
z += 0.738;
}
if f.pc_dept {
z -= 0.515;
}
if f.from_ml {
z -= 0.270;
}
let c = 1.0 / (1.0 + (-z).exp());
(c * 100.0).round() / 100.0
}
/// Match flags for output (explainability): why this answer, what to filter out.
fn match_flags(f: &Feats) -> Vec<&'static str> {
let mut v = Vec::new();
if f.street_exact {
v.push("street_exact");
}
if f.street_fuzzy {
v.push("street_fuzzy");
}
if f.commune_exact {
v.push("commune_exact");
} else if f.commune_prefix {
v.push("commune_prefix");
}
if f.house_exact_rep {
v.push("house_rep");
}
if f.pc_exact {
v.push("pc_exact");
} else if f.pc_dept {
v.push("pc_dept");
}
if f.from_ml {
v.push("ml");
}
if f.de_street_type {
v.push("de_street_type");
}
v
}
/// Candidate features (order is fixed: SEC_RANK weights are indexed by position).
pub const N_FEATS: usize = 10;
// Internal selection evidence, removed before any public result is returned.
const DEFERRED_LOCALITY_DROP: &str = "__deferred_locality_drop";
#[derive(Clone, Copy, Default)]
pub struct Feats {
street_exact: bool,
street_fuzzy: bool,
commune_exact: bool,
commune_prefix: bool,
pc_exact: bool,
pc_dept: bool,
from_ml: bool,
house_found: bool,
house_exact_rep: bool,
numero_present: bool,
/// Explainability-only: a DE compound/split street-type variant supplied
/// the exact FST key. It is deliberately not an eleventh ranking feature.
de_street_type: bool,
}
impl Feats {
fn merge(&mut self, o: Feats) {
self.street_exact |= o.street_exact;
self.street_fuzzy |= o.street_fuzzy;
self.commune_exact |= o.commune_exact;
self.commune_prefix |= o.commune_prefix;
self.pc_exact |= o.pc_exact;
self.pc_dept |= o.pc_dept;
self.from_ml |= o.from_ml;
self.de_street_type |= o.de_street_type;
}
pub fn to_vec(&self) -> [f32; N_FEATS] {
let b = |x: bool| if x { 1.0 } else { 0.0 };
[
b(self.street_exact),
b(self.street_fuzzy),
b(self.commune_exact),
b(self.commune_prefix),
b(self.pc_exact),
b(self.pc_dept),
b(self.from_ml),
b(self.house_found),
b(self.house_exact_rep),
b(self.numero_present),
]
}
fn from_vec(v: &[f32; N_FEATS]) -> Self {
let b = |i: usize| v[i] > 0.5;
Self {
street_exact: b(0),
street_fuzzy: b(1),
commune_exact: b(2),
commune_prefix: b(3),
pc_exact: b(4),
pc_dept: b(5),
from_ml: b(6),
house_found: b(7),
house_exact_rep: b(8),
numero_present: b(9),
de_street_type: false,
}
}
/// Hand-tuned baseline score (used for hypothesis selection and when no trained weights are present).
fn legacy(&self) -> i32 {
let mut s = 0;
if self.street_exact {
s += 3;
}
if self.street_fuzzy && !self.street_exact {
s += 2;
}
if self.commune_exact {
s += 3;
}
if self.commune_prefix && !self.commune_exact {
s += 2;
}
if self.pc_exact {
s += 2;
}
if self.house_exact_rep {
s += 2;
} else if self.house_found {
s += 1;
}
s
}
}
/// Trained ranking weights (SEC_RANK section: 'GPRK' + n u8 + bias f32 + w f32 x n).
struct Rank {
bias: f32,
w: Vec<f32>,
}
impl Rank {
fn from_section(data: &[u8]) -> Option<Rank> {
if data.len() < 9 || &data[0..4] != b"GPRK" {
return None;
}
let n = data[4] as usize;
// n MUST equal the fixed feature count AND the section length must be EXACT: the old
// `< 9 + n*4` accepted a mutant that shrank n (10 -> 1) while keeping
// all weight bytes — score() then zips only the first n weights against the N_FEATS feature
// vector, silently changing every score/confidence with no error. Reject a wrong n or any
// short/over-long weight table.
if n != N_FEATS || data.len() != 9 + n * 4 {
return None;
}
let bias = f32::from_le_bytes(data[5..9].try_into().ok()?);
let w: Vec<f32> = (0..n)
.map(|i| f32::from_le_bytes(data[9 + i * 4..13 + i * 4].try_into().unwrap()))
.collect();
// reject a non-finite bias/weight: a NaN here propagates to every score and surfaces as
// `score:null` (CLI/DuckDB) / `nan` (Python) — the model must be finite.
if !bias.is_finite() || w.iter().any(|x| !x.is_finite()) {
return None;
}
Some(Rank { bias, w })
}
fn score(&self, f: &Feats) -> f32 {
let v = f.to_vec();
let mut s = self.bias;
for (wi, vi) in self.w.iter().zip(&v) {
s += wi * vi;
}
s
}
}
/// Build-time validation hook: does this byte slice parse as a SEC_RANK section? The
/// builder calls it so a corrupt `--rank` file fails the BUILD, instead of being embedded and then
/// silently dropped to `None` at open time (a sheet that quietly lost its trained ranking).
pub(crate) fn rank_section_is_valid(bytes: &[u8]) -> bool {
Rank::from_section(bytes).is_some()
}
/// Parse hypothesis: house number, suffix, remainder (street+commune) as token indices.
struct Hyp {
numero: Option<u32>,
rep: u32,
rest_idx: Vec<usize>,
from_ml: bool,
}
/// Per-query focus context. The nearby street ids are collected once and reused across parser
/// retries; this keeps every retry on the same deterministic candidate union.
struct QueryFocus {
lat: f64,
lon: f64,
streets: Vec<u32>,
}
/// Expansion of first-word street abbreviations (only adds a variant).
const ABBREV: &[(&str, &str)] = &[
("r", "rue"),
("av", "avenue"),
("avn", "avenue"),
("bd", "boulevard"),
("bld", "boulevard"),
("blvd", "boulevard"),
("pl", "place"),
("imp", "impasse"),
("chem", "chemin"),
("all", "allee"),
("sq", "square"),
("rte", "route"),
("crs", "cours"),
("fbg", "faubourg"),
("st", "saint"),
("ste", "sainte"),
("ln", "laan"),
("str", "straat"),
("v", "via"),
("vle", "viale"),
("pza", "piazza"),
("cso", "corso"),
("vic", "vicolo"),
("ул", "улица"),
("пр", "проспект"),
("просп", "проспект"),
("пер", "переулок"),
("наб", "набережная"),
("ш", "шоссе"),
("бул", "бульвар"),
("пл", "площадь"),
("кв", "квартал"),
("мкр", "микрорайон"),
("мкрн", "микрорайон"),
];
/// Is the word a street TYPE (not a distinguishing name)? Covers all scripts.
fn is_street_type_word(w: &str) -> bool {
crate::rules::rules().is_street_type(w)
}
/// A LEADING designator that can be stripped from the string start as a place type/prefix:
/// street types in any script plus housing-estate/microdistrict prefixes (and their
/// transliterations). The bare name then resolves on its own, whereas a leading type shifts
/// the name away from the string start so prefix Levenshtein / inverted-index lookups fail
/// to match. Distinguishing names are never stripped.
fn is_affix_word(w: &str) -> bool {
crate::rules::rules().is_affix(w)
}
/// Normalized, order-independent street-name key so the same name in different word
/// orders ("X street" vs "street X") counts as one name.
fn street_key(s: &str) -> String {
let mut t: Vec<String> = normalize(s)
.split(' ')
.filter(|w| !w.is_empty())
.map(|w| w.to_string())
.collect();
t.sort();
t.join(" ")
}
/// Original DE locality evidence retained across the suffix-recovery retry. The retry
/// deliberately removes the unrecognised tail before candidate lookup; without carrying
/// this evidence forward, otherwise identical street/house homonyms fall back to the
/// global anchor or commune prominence.
#[derive(Clone, Copy)]
struct DeRetainedLocality<'a> {
/// All normalized tokens after the rightmost explicit five-digit postcode.
postcode_tail: &'a str,
/// The exact one- or two-token slice removed by the successful c2 retry.
dropped_tail: &'a str,
/// Frozen from the original raw DE input before iterating query variants. House-range
/// and mixed-fraction spellings keep their established variant-quality winner and may
/// still use retained locality, but must not enter the independent postal-tail rule.
postal_tail_eligible: bool,
}
fn de_retained_locality<'a>(
postcode_tail: Option<&'a str>,
dropped_tail: &'a str,
postal_tail_eligible: bool,
) -> Option<DeRetainedLocality<'a>> {
postcode_tail.map(|postcode_tail| DeRetainedLocality {
postcode_tail,
dropped_tail,
postal_tail_eligible,
})
}
fn de_commune_core(commune: &str) -> String {
let normalized = normalize(commune);
let mut words: Vec<&str> = normalized
.split(' ')
.filter(|word| !word.is_empty())
.collect();
while words.first() == Some(&"stadt") {
words.remove(0);
}
while words.last() == Some(&"stadt") {
words.pop();
}
words.join(" ")
}
fn de_retained_locality_score(postcode_tail: &str, commune: &str) -> u8 {
let query = normalize(postcode_tail);
let candidate = de_commune_core(commune);
if query.is_empty() || candidate.is_empty() {
return 0;
}
if candidate == query {
return 2;
}
if candidate
.strip_prefix(&query)
.is_some_and(|suffix| suffix.starts_with(' '))
{
1
} else {
0
}
}
fn de_dropped_tail_reaches_commune(dropped_tail: &str, commune: &str) -> bool {
let commune = de_commune_core(commune);
let commune_words: std::collections::HashSet<&str> = commune.split(' ').collect();
normalize(dropped_tail)
.split(' ')
.any(|word| word.chars().count() >= 4 && commune_words.contains(word))
}
fn de_locality_qualifiers_match(query_tail: &str, commune: &str) -> bool {
let query = normalize(query_tail);
let candidate = de_commune_core(commune);
matches!(
(query.as_str(), candidate.as_str()),
("reichenbach vogt", "reichenbach im vogtland")
| ("sankt wendel", "st wendel")
| ("homburg saar", "homburg")
| ("kottmar ot eibau", "eibau")
| ("st peter ording", "sankt peter ording")
| ("burg auf fehmarn", "fehmarn")
)
}
/// Exact, postcode-bound relations between a user-facing locality and the
/// indexed postal locality. These are deliberately triples rather than two
/// independent allowlists: Berlin's city name must never cross-match every
/// district, and the same spelling in another postcode remains unrelated.
const DE_EXACT_LOCALITY_ALIASES: &[(&str, u32, &str)] = &[
("brandenburg an der havel", 14770, "brandenburg"),
("brandenburg an der havel", 14776, "brandenburg"),
("berlin", 13187, "pankow"),
("berlin", 13189, "pankow"),
("berlin", 13355, "gesundbrunnen"),
("berlin", 10317, "rummelsburg"),
("berlin", 13129, "blankenburg"),
("berlin", 13159, "blankenfelde"),
("berlin", 13127, "franzosisch buchholz"),
("berlin", 12165, "steglitz"),
("berlin", 12159, "friedenau"),
("berlin", 14052, "westend"),
("werder a d havel", 14542, "werder"),
("petershagen eggersdorf", 15345, "eggersdorf"),
("landkirchen", 23769, "fehmarn"),
("berlin kaulsdorf", 12621, "kaulsdorf"),
("zerkwitz", 3222, "lubbenau"),
("schwedt oder", 16303, "schwedt"),
("konigstein taunus", 61462, "konigstein im taunus"),
("freiburg breisgau", 79104, "freiburg im breisgau"),
("freiburg", 79115, "freiburg im breisgau"),
("oelsnitz vogtland", 8606, "oelsnitz vogtl"),
("frankenberg sachsen", 9669, "frankenberg sa"),
("lutherstadt wittenberg", 6886, "wittenberg"),
("wittenberg lutherstadt", 6886, "wittenberg"),
("weilheim teck", 73235, "weilheim an der teck"),
("berlin", 10587, "charlottenburg"),
("berlin", 10783, "schoneberg"),
("berlin", 13627, "charlottenburg nord"),
("berlin", 14059, "charlottenburg"),
("berlin", 14195, "lichterfelde"),
];
fn de_exact_locality_alias_matches(query_tail: &str, postcode: u32, commune: &str) -> bool {
let query = normalize(query_tail);
let candidate = de_commune_core(commune);
DE_EXACT_LOCALITY_ALIASES
.iter()
.any(|(expected_query, expected_postcode, expected_commune)| {
query == *expected_query
&& postcode == *expected_postcode
&& candidate == *expected_commune
})
}
fn de_is_exact_locality_alias_query(query_tail: &str, postcode: u32) -> bool {
let query = normalize(query_tail);
DE_EXACT_LOCALITY_ALIASES
.iter()
.any(|(expected_query, expected_postcode, _)| {
query == *expected_query && postcode == *expected_postcode
})
}
fn de_is_berlin_postal_locality(commune: &str) -> bool {
matches!(
de_commune_core(commune).as_str(),
"berlin"
| "adlershof"
| "charlottenburg"
| "dahlem"
| "kaulsdorf"
| "kreuzberg"
| "marienfelde"
| "mitte"
| "neukolln"
| "niederschoneweide"
| "nikolassee"
| "tempelhof"
| "wilmersdorf"
)
}
fn de_is_proven_berlin_postcode(postcode: u32) -> bool {
matches!(
postcode,
10115
| 10117
| 10178
| 10589
| 10715
| 10717
| 10969
| 12043
| 12101
| 12277
| 12439
| 12489
| 12621
| 14129
| 14195
)
}
#[cfg(test)]
thread_local! {
static DE_PREFIX_DROP_GUARD_CALLS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_ABBREVIATION_GUARD_CALLS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_POSTCODE_HOUSE_RESCUE_HOUSE_DECODES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_POSTCODE_HOUSE_RESCUE_FUZZY_CALLS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_POSTCODE_HOUSE_RESCUE_SUBSET_CALLS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT) };
static DE_P4_POSTCODE_BUCKET_SCAN_ROWS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_P4_POSTCODE_BUCKET_MATCHING_SIDS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_BLANK_POSTCODE_HOUSE_SCAN_ROWS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static DE_COUNTRY_VARIANT_PREPARED_SEARCH_CALLS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
type EsPreparedKey = (usize, String, usize, Option<usize>, Option<String>);
type EsPreparedResults = Vec<(Hit, [f32; N_FEATS])>;
thread_local! {
static ES_PREPARED_CACHE: std::cell::RefCell<Option<HashMap<EsPreparedKey, EsPreparedResults>>> = const { std::cell::RefCell::new(None) };
}
struct EsPreparedScope(Option<HashMap<EsPreparedKey, EsPreparedResults>>);
impl EsPreparedScope {
fn new() -> Self {
Self(ES_PREPARED_CACHE.with(|cache| cache.replace(Some(HashMap::new()))))
}
}
impl Drop for EsPreparedScope {
fn drop(&mut self) {
ES_PREPARED_CACHE.with(|cache| {
cache.replace(self.0.take());
});
}
}
/// Hard ceiling for the one narrow, post-failure exact-key scan. Common German street names can
/// exceed 4,000 locality postings; ordinary queries retain their 300-row cap, while this path
/// proves uniqueness or fails closed on the first row beyond this bound.
const DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT: usize = 8192;
fn de_postcode_house_rescue_scan_limit() -> usize {
#[cfg(test)]
{
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(std::cell::Cell::get)
}
#[cfg(not(test))]
{
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT
}
}
fn de_prefix_drop_preserves_postcode_locality(
hit: &Hit,
features: &[f32; N_FEATS],
postcode: u32,
postcode_tail: &str,
) -> bool {
#[cfg(test)]
DE_PREFIX_DROP_GUARD_CALLS.with(|calls| calls.set(calls.get().saturating_add(1)));
Feats::from_vec(features).pc_exact
|| Index::postcode_numeric_prefix(&hit.postcode) == Some(postcode)
|| de_retained_locality_score(postcode_tail, &hit.commune) != 0
}
fn de_postcode_context(q: &str) -> Option<(u32, String)> {
let tokens: Vec<&str> = q.split(' ').filter(|token| !token.is_empty()).collect();
let position = tokens
.iter()
.rposition(|token| is_five_digit_postcode(token))?;
let postcode = tokens[position].parse().ok()?;
let tail = tokens[position + 1..].join(" ");
(!tail.is_empty()).then_some((postcode, tail))
}
/// The exact normalization performed before every prepared lookup. Keeping this
/// in one helper lets the DE variant loop identify equivalent raw/base variants
/// without drifting from `query_feats_d` itself.
fn prepared_query_key(raw: &str) -> String {
expand_two_token(&fold_units(&crate::norm::fold_homoglyphs(&normalize(raw))))
}
fn de_house_range_separator(address: &str) -> bool {
address.char_indices().any(|(position, character)| {
if !matches!(character, '-' | '–' | '—') {
return false;
}
let left_endpoint = address[..position].split_whitespace().next_back();
let right_endpoint = address[position + character.len_utf8()..]
.split_whitespace()
.next();
left_endpoint.is_some_and(|endpoint| endpoint.chars().any(|ch| ch.is_ascii_digit()))
&& right_endpoint.is_some_and(|endpoint| endpoint.chars().any(|ch| ch.is_ascii_digit()))
})
}
fn de_capital_prior_candidate_allowed(
country: Option<&str>,
sorted_top_features: &[f32; N_FEATS],
candidate_precision: &str,
) -> bool {
// A weak cityless capital anchor may resolve equal-quality homonyms, but
// it must not replace an already exact German house with a snapped
// neighbour carrying a different number. Interpolation remains eligible:
// it can be the only useful address on a sparse street and has an explicit
// regression sentinel in the tests below.
!(country == Some("de")
&& candidate_precision == "near"
&& Feats::from_vec(sorted_top_features).house_exact_rep)
}
fn de_comma_postcode_house_rescue_query(raw: &str) -> Option<(String, u32, String)> {
if !crate::de::postal_tail_eligible(raw) {
return None;
}
// Parenthetical building labels with slash locality qualifiers belong to
// the audited P4 parser. Letting this generic comma rescue strip them
// would bypass P4's exact-core and fill-empty admission contract.
if de_parenthetical_locality_uses_slash_qualifier(raw) {
return None;
}
let mut segments = raw.split(',');
let address = segments.next()?.trim();
let locality = segments.next()?.trim();
let country = segments.next().map(str::trim);
if address.is_empty() || locality.is_empty() || segments.next().is_some() {
return None;
}
if country.is_some_and(|country| {
let country = normalize(country);
!matches!(country.as_str(), "deutschland" | "germany")
}) {
return None;
}
if address.contains('/') || de_house_range_separator(address) {
return None;
}
let locality = normalize(locality);
let mut tokens = locality.split_whitespace();
let postcode_token = tokens.next()?;
if !is_five_digit_postcode(postcode_token) {
return None;
}
let locality_tail = tokens.collect::<Vec<_>>().join(" ");
if locality_tail.is_empty() {
return None;
}
let normalized_address = normalize(address);
if !normalized_address
.split_whitespace()
.any(|token| token.bytes().any(|byte| byte.is_ascii_digit()))
{
return None;
}
Some((
format!("{address} {postcode_token}"),
postcode_token.parse().ok()?,
locality_tail,
))
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct DeCompactHousePairSpec {
query: String,
postcode: u32,
locality_tail: String,
effect: crate::de::Effect,
left: u32,
right: u32,
}
/// Parse one compact, literal two-endpoint house set immediately before an
/// explicit five-digit postcode. The strict Wave-A path proves both numbers
/// on one runtime street id; therefore even a small slash pair such as `1/3`
/// is no longer guessed from the left endpoint alone.
fn de_compact_house_pair_spec(raw: &str) -> Option<DeCompactHousePairSpec> {
let bytes = raw.as_bytes();
let mut parsed = None;
for start in 0..bytes.len().saturating_sub(4) {
if !bytes[start..start + 5].iter().all(u8::is_ascii_digit)
|| start
.checked_sub(1)
.is_some_and(|left| bytes[left].is_ascii_digit())
|| bytes.get(start + 5).is_some_and(u8::is_ascii_digit)
{
continue;
}
let postcode_token = &raw[start..start + 5];
let locality_raw = raw[start + 5..].trim();
if locality_raw.is_empty()
|| !locality_raw.chars().any(char::is_alphabetic)
|| locality_raw.chars().any(|character| {
character.is_ascii_digit() || matches!(character, ',' | ';' | '|' | '\n' | '\r')
})
{
continue;
}
let before_postcode = raw[..start].trim_end();
let address = before_postcode
.strip_suffix(',')
.unwrap_or(before_postcode)
.trim_end();
if address.is_empty()
|| address
.chars()
.any(|character| matches!(character, ',' | ';' | '|' | '\n' | '\r'))
{
continue;
}
let Some(split) = address.rfind(char::is_whitespace) else {
continue;
};
let street = address[..split].trim_end();
let pair = address[split..].trim();
if street.is_empty() || !street.chars().any(char::is_alphabetic) {
continue;
}
let mut separator = None;
for (position, character) in pair.char_indices() {
if matches!(character, '-' | '–' | '—' | '/') {
if separator.is_some() {
separator = None;
break;
}
separator = Some((position, character));
}
}
let Some((position, separator)) = separator else {
continue;
};
let left_raw = &pair[..position];
let right_raw = &pair[position + separator.len_utf8()..];
if left_raw.is_empty()
|| right_raw.is_empty()
|| left_raw.len() > 4
|| right_raw.len() > 4
|| !left_raw.bytes().all(|byte| byte.is_ascii_digit())
|| !right_raw.bytes().all(|byte| byte.is_ascii_digit())
{
continue;
}
let left: u32 = left_raw.parse().ok()?;
let right: u32 = right_raw.parse().ok()?;
if left == 0 || left >= right {
continue;
}
let effect = if separator == '/' {
crate::de::Effect::HouseSlash
} else {
crate::de::Effect::HouseRange
};
let locality = normalize(locality_raw);
if locality.is_empty() {
continue;
}
let candidate = DeCompactHousePairSpec {
query: format!("{street} {left_raw} {postcode_token}"),
postcode: postcode_token.parse().ok()?,
locality_tail: locality,
effect,
left,
right,
};
if parsed.replace(candidate).is_some() {
return None;
}
}
parsed
}
/// Legacy left-endpoint fallback remains deliberately conservative for small
/// slash pairs. Wave A uses `de_compact_house_pair_spec` directly and admits
/// those pairs only after proving the complete set against the runtime index.
fn de_compact_house_pair_left_rescue_query(
raw: &str,
) -> Option<(String, u32, String, crate::de::Effect)> {
let spec = de_compact_house_pair_spec(raw)?;
if spec.effect == crate::de::Effect::HouseSlash && (spec.left < 10 || spec.right < 10) {
return None;
}
Some((spec.query, spec.postcode, spec.locality_tail, spec.effect))
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct DeStrictSourceStreetTypoSpec {
normalized_street: String,
normalized_locality: String,
house_number: u32,
postcode: u32,
postcode_raw: String,
}
/// Product-field normalization used by the frozen Germany diagnostic roster.
/// It intentionally mirrors the offline analyzer instead of the broader search
/// normalizer: NFKC/lowercase, German umlauts to digraphs, `ß` to `ss`, and
/// ASCII alphanumeric words only. Retrieval may use broader variants, but an
/// admission predicate must compare this single projection on both sides.
fn de_product_normalize_text(raw: &str) -> String {
let mut normalized = String::with_capacity(raw.len());
let mut separated = true;
for character in raw.nfkc().flat_map(char::to_lowercase) {
let replacement = match character {
'ä' => Some("ae"),
'ö' => Some("oe"),
'ü' => Some("ue"),
'ß' => Some("ss"),
_ => None,
};
if let Some(replacement) = replacement {
normalized.push_str(replacement);
separated = false;
} else if character.is_ascii_alphanumeric() {
normalized.push(character);
separated = false;
} else if !separated && !normalized.is_empty() {
normalized.push(' ');
separated = true;
}
}
normalized.trim_end().to_string()
}
fn de_product_normalize_street(raw: &str) -> String {
let mut words: Vec<String> = de_product_normalize_text(raw)
.split_whitespace()
.map(|word| {
match word {
"str" | "strasse" => "strasse",
"pl" => "platz",
"al" => "allee",
"uf" => "ufer",
"wg" => "weg",
"g" => "gasse",
"ch" => "chaussee",
_ => word,
}
.to_string()
})
.collect();
if let Some(last) = words.last_mut() {
if last != "str" && last.ends_with("str") {
last.truncate(last.len() - 3);
last.push_str("strasse");
}
}
words.join(" ")
}
/// The audited c/o syntax contains one fused compound street token. Split it
/// only at a terminal product street-type word; arbitrary byte splits would
/// turn retrieval hypotheses into product predicate inputs.
fn de_product_normalize_compound_street(raw: &str) -> Option<String> {
let compact = de_product_normalize_street(raw);
if compact.is_empty() || compact.contains(' ') || compact.len() > 96 {
return None;
}
for suffix in [
"chaussee", "strasse", "allee", "gasse", "platz", "ring", "ufer", "weg",
] {
let Some(prefix) = compact.strip_suffix(suffix) else {
continue;
};
if prefix.len() >= 3 {
return Some(format!("{prefix} {suffix}"));
}
}
None
}
/// Product-visible German street lookup forms for the typed P4 surfaces.
/// These variants are a bounded locator, never admission fields: P4 separately
/// compares one canonical query projection with the canonical display street.
fn de_product_street_forms(raw_street: &str) -> Vec<String> {
let mut forms = Vec::new();
let mut seen = HashSet::new();
for variant in crate::de::query_variants(raw_street) {
let base = normalize(&variant.query).replace('ß', "ss");
if base.is_empty()
|| base.len() > 96
|| !base.is_ascii()
|| base.chars().any(|character| character.is_ascii_digit())
{
continue;
}
if seen.insert(base.clone()) {
forms.push(base.clone());
}
let words: Vec<&str> = base.split_whitespace().collect();
if let Some(last) = words.last() {
if *last == "str" && words.len() > 1 {
let mut expanded = words[..words.len() - 1].join(" ");
expanded.push_str(" strasse");
if seen.insert(expanded.clone()) {
forms.push(expanded);
}
} else if let Some(prefix) = last.strip_suffix("str") {
if prefix.chars().count() >= 2 {
let mut joined = words[..words.len() - 1].join(" ");
if !joined.is_empty() {
joined.push(' ');
}
joined.push_str(prefix);
joined.push_str("strasse");
if seen.insert(joined.clone()) {
forms.push(joined);
}
let mut split = words[..words.len() - 1].join(" ");
if !split.is_empty() {
split.push(' ');
}
split.push_str(prefix);
split.push_str(" strasse");
if seen.insert(split.clone()) {
forms.push(split);
}
}
}
}
for street_variant in crate::de::street_variants(&base) {
let street_variant = street_variant.replace('ß', "ss");
if street_variant.len() <= 96
&& street_variant.is_ascii()
&& seen.insert(street_variant.clone())
{
forms.push(street_variant);
}
}
}
let canonical = de_product_normalize_street(raw_street);
if !canonical.is_empty()
&& canonical.len() <= 96
&& canonical.is_ascii()
&& seen.insert(canonical.clone())
{
forms.push(canonical);
}
forms
}
/// Exact raw P3 surface: `street integer, five-digit-postcode locality`.
/// Suffixes, ranges, street digits and delivery noise deliberately have no
/// interpretation in this path.
fn de_strict_source_street_typo_spec(raw: &str) -> Option<DeStrictSourceStreetTypoSpec> {
if raw.len() > 256
|| raw.trim() != raw
|| raw
.chars()
.any(|character| matches!(character, '\n' | '\r' | '\t' | ';' | '|'))
{
return None;
}
let mut fields = raw.split(',');
let address = fields.next()?.trim();
let terminal = fields.next()?.trim();
if address.is_empty() || terminal.is_empty() || fields.next().is_some() {
return None;
}
let split = address.rfind(char::is_whitespace)?;
let street = address[..split].trim_end();
let house_raw = address[split..].trim();
if street.is_empty()
|| !street.chars().any(char::is_alphabetic)
|| street.chars().any(|character| character.is_ascii_digit())
|| house_raw.is_empty()
|| house_raw.len() > 4
|| house_raw.as_bytes().first() == Some(&b'0')
|| !house_raw.bytes().all(|byte| byte.is_ascii_digit())
{
return None;
}
let house_number = house_raw
.parse::<u32>()
.ok()
.filter(|number| *number != 0)?;
let mut terminal_tokens = terminal.split_whitespace();
let postcode_raw = terminal_tokens.next()?;
if !is_five_digit_postcode(postcode_raw) {
return None;
}
let locality_raw = terminal_tokens.collect::<Vec<_>>().join(" ");
if locality_raw.is_empty()
|| !locality_raw.chars().any(char::is_alphabetic)
|| locality_raw
.chars()
.any(|character| character.is_ascii_digit())
{
return None;
}
let normalized_street = de_product_normalize_street(street);
let normalized_locality = de_product_normalize_text(&locality_raw);
if normalized_street.is_empty() || normalized_locality.is_empty() {
return None;
}
Some(DeStrictSourceStreetTypoSpec {
normalized_street,
normalized_locality,
house_number,
postcode: postcode_raw.parse().ok()?,
postcode_raw: postcode_raw.to_string(),
})
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct DeStreetLocalityQualifierSpec {
normalized_street: String,
normalized_locality: String,
house_token: String,
postcode_raw: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct DeBlankPostcodeHouseSpec {
normalized_street: String,
normalized_locality: String,
house_number: u32,
house_suffix: String,
postcode: u32,
postcode_raw: String,
}
/// Exact Wave X2 surface: `street integer[suffix], five-digit-postcode locality`.
/// It is deliberately independent of P3: admitting a one-letter suffix here
/// must not widen the audited source-street typo mechanism.
fn de_street_locality_qualifier_spec(raw: &str) -> Option<DeStreetLocalityQualifierSpec> {
if raw.len() > 256
|| raw.trim() != raw
|| raw
.chars()
.any(|character| matches!(character, '\n' | '\r' | '\t' | ';' | '|'))
{
return None;
}
let mut fields = raw.split(',');
let address = fields.next()?.trim();
let terminal = fields.next()?.trim();
if address.is_empty() || terminal.is_empty() || fields.next().is_some() {
return None;
}
let split = address.rfind(char::is_whitespace)?;
let street = address[..split].trim_end();
let house_raw = address[split..].trim();
let digit_len = house_raw
.bytes()
.take_while(|byte| byte.is_ascii_digit())
.count();
let (house_number, house_suffix) = house_raw.split_at(digit_len);
if street.is_empty()
|| !street.chars().any(char::is_alphabetic)
|| street.chars().any(|character| character.is_ascii_digit())
|| house_number.is_empty()
|| house_number.len() > 4
|| house_number.as_bytes().first() == Some(&b'0')
|| !house_number.bytes().all(|byte| byte.is_ascii_digit())
|| house_number
.parse::<u32>()
.ok()
.is_none_or(|number| number == 0)
|| house_suffix.len() > 1
|| !house_suffix.bytes().all(|byte| byte.is_ascii_alphabetic())
{
return None;
}
let mut terminal_tokens = terminal.split_whitespace();
let postcode_raw = terminal_tokens.next()?;
if !is_five_digit_postcode(postcode_raw) {
return None;
}
let locality_raw = terminal_tokens.collect::<Vec<_>>().join(" ");
if locality_raw.is_empty()
|| !locality_raw.chars().any(char::is_alphabetic)
|| locality_raw
.chars()
.any(|character| character.is_ascii_digit())
{
return None;
}
let normalized_street = de_product_normalize_street(street);
let normalized_locality = de_product_normalize_text(&locality_raw);
if normalized_street.is_empty() || normalized_locality.is_empty() {
return None;
}
Some(DeStreetLocalityQualifierSpec {
normalized_street,
normalized_locality,
house_token: format!("{}{}", house_number, house_suffix.to_ascii_lowercase()),
postcode_raw: postcode_raw.to_string(),
})
}
/// Exact Wave O surface: `street integer[suffix], five-digit-postcode locality`.
/// The parser is intentionally disjoint from range/compound/delivery cleanup:
/// P5 may only arbitrate one literal address whose original fields are already
/// structurally complete.
fn de_blank_postcode_house_spec(raw: &str) -> Option<DeBlankPostcodeHouseSpec> {
if raw.contains(['(', ')', '/', '\\']) {
return None;
}
let parsed = de_street_locality_qualifier_spec(raw)?;
let digit_len = parsed
.house_token
.bytes()
.take_while(|byte| byte.is_ascii_digit())
.count();
let (house_number, house_suffix) = parsed.house_token.split_at(digit_len);
if house_number.is_empty()
|| house_suffix.len() > 1
|| !house_suffix.bytes().all(|byte| byte.is_ascii_alphabetic())
{
return None;
}
Some(DeBlankPostcodeHouseSpec {
normalized_street: parsed.normalized_street,
normalized_locality: parsed.normalized_locality,
house_number: house_number.parse().ok()?,
house_suffix: house_suffix.to_string(),
postcode: parsed.postcode_raw.parse().ok()?,
postcode_raw: parsed.postcode_raw,
})
}
/// Parse only a terminal source display qualifier: `base (locality)`.
/// Nested parentheses, empty parts and any trailing text fail closed.
fn de_source_street_locality_qualifier(display: &str) -> Option<(String, String)> {
if display.is_empty() || display.len() > 192 || display.trim() != display {
return None;
}
let without_close = display.strip_suffix(')')?;
let (base, qualifier) = without_close.rsplit_once(" (")?;
if base.is_empty()
|| qualifier.is_empty()
|| base.contains(['(', ')'])
|| qualifier.contains(['(', ')'])
|| qualifier.chars().any(char::is_control)
{
return None;
}
let normalized_base = de_product_normalize_street(base);
let normalized_qualifier = de_product_normalize_text(qualifier);
if normalized_base.is_empty() || normalized_qualifier.is_empty() {
return None;
}
Some((normalized_base, normalized_qualifier))
}
fn de_house_token_matches(hit: &Hit, expected: &str) -> bool {
hit.housenumber
.as_deref()
.is_some_and(|house| de_product_normalize_text(house).replace(' ', "") == expected)
}
fn de_locality_is_exact_or_query_prefix(query: &str, source: &str) -> bool {
query == source
|| source
.strip_prefix(query)
.is_some_and(|tail| tail.starts_with(' '))
}
fn de_compact_osa_distance(left: &str, right: &str) -> usize {
let left: Vec<u8> = left
.bytes()
.filter(|byte| !byte.is_ascii_whitespace())
.collect();
let right: Vec<u8> = right
.bytes()
.filter(|byte| !byte.is_ascii_whitespace())
.collect();
if left.len().abs_diff(right.len()) > 2 {
return 3;
}
let mut matrix = vec![vec![0usize; right.len() + 1]; left.len() + 1];
for (index, row) in matrix.iter_mut().enumerate() {
row[0] = index;
}
for (index, cell) in matrix[0].iter_mut().enumerate() {
*cell = index;
}
for i in 1..=left.len() {
for j in 1..=right.len() {
let substitution = usize::from(left[i - 1] != right[j - 1]);
let mut distance = (matrix[i - 1][j] + 1)
.min(matrix[i][j - 1] + 1)
.min(matrix[i - 1][j - 1] + substitution);
if i > 1 && j > 1 && left[i - 1] == right[j - 2] && left[i - 2] == right[j - 1] {
distance = distance.min(matrix[i - 2][j - 2] + 1);
}
matrix[i][j] = distance;
}
}
matrix[left.len()][right.len()]
}
/// Python `SequenceMatcher(None, a, b).ratio()` for the bounded (<100 byte),
/// no-junk ASCII street strings admitted above. Python's auto-junk branch is
/// inactive below 200 items, so recursively summing the earliest longest
/// contiguous matching blocks is equivalent and deterministic here.
fn de_sequence_matcher_ratio_at_least_090(left: &str, right: &str) -> bool {
let left = left.as_bytes();
let right = right.as_bytes();
if left.is_empty() || right.is_empty() || left.len() > 96 || right.len() > 96 {
return false;
}
let mut matched = 0usize;
let mut pending = vec![(0usize, left.len(), 0usize, right.len())];
while let Some((left_lo, left_hi, right_lo, right_hi)) = pending.pop() {
let mut previous = vec![0usize; right_hi - right_lo + 1];
let mut best = (left_lo, right_lo, 0usize);
for (left_index, left_byte) in left.iter().enumerate().take(left_hi).skip(left_lo) {
let mut current = vec![0usize; right_hi - right_lo + 1];
for (right_index, right_byte) in right.iter().enumerate().take(right_hi).skip(right_lo)
{
if left_byte != right_byte {
continue;
}
let offset = right_index - right_lo + 1;
current[offset] = previous[offset - 1] + 1;
let length = current[offset];
let left_start = left_index + 1 - length;
let right_start = right_index + 1 - length;
if length > best.2
|| (length == best.2
&& (left_start < best.0 || (left_start == best.0 && right_start < best.1)))
{
best = (left_start, right_start, length);
}
}
previous = current;
}
if best.2 == 0 {
continue;
}
matched += best.2;
if left_lo < best.0 && right_lo < best.1 {
pending.push((left_lo, best.0, right_lo, best.1));
}
let left_after = best.0 + best.2;
let right_after = best.1 + best.2;
if left_after < left_hi && right_after < right_hi {
pending.push((left_after, left_hi, right_after, right_hi));
}
}
matched.saturating_mul(20) >= 9usize.saturating_mul(left.len() + right.len())
}
fn de_p3_locality_compatible(query: &str, source: &str) -> bool {
query == source
|| query
.strip_prefix(source)
.is_some_and(|tail| tail.starts_with(' '))
|| source
.strip_prefix(query)
.is_some_and(|tail| tail.starts_with(' '))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DeAuditedCompoundShape {
VenueCommaHouseCommaStreet,
StreetHouseBalancedVenueParenthetical,
StreetHouseRangeBalancedAccessParenthetical,
CareOfPrefixThenStreetHouseLocality,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct DeAuditedCompoundSpec {
shape: DeAuditedCompoundShape,
street: String,
normalized_street: String,
primary_house: u32,
additional_houses: Vec<u32>,
postcode: u32,
postcode_raw: String,
normalized_locality: String,
}
fn de_audited_postcode_locality(value: &str) -> Option<(u32, String, String)> {
let value = value.trim();
let boundary = value.find(char::is_whitespace)?;
let postcode_raw = &value[..boundary];
let locality_raw = value[boundary..].trim();
if !is_five_digit_postcode(postcode_raw)
|| locality_raw.is_empty()
|| !locality_raw.chars().any(char::is_alphabetic)
|| locality_raw
.chars()
.any(|character| character.is_ascii_digit() || matches!(character, ',' | ';' | '|'))
{
return None;
}
Some((
postcode_raw.parse().ok()?,
postcode_raw.to_string(),
locality_raw.to_string(),
))
}
fn de_audited_locality(raw: &str) -> Option<String> {
match raw.matches('/').count() {
0 => {
let locality = de_product_normalize_text(raw);
(!locality.is_empty()).then_some(locality)
}
1 => {
let (left, right) = raw.split_once('/')?;
let left = de_product_normalize_text(left);
let right = de_product_normalize_text(right);
if left.is_empty() || right.is_empty() {
return None;
}
// Closed, product-visible German abbreviations from the audited
// syntaxes. Never invent both prepositions and let source data
// choose which query-locality field supposedly existed.
let connector = match right.as_str() {
"breisgau" => "im",
"teck" => "an der",
_ => return None,
};
Some(format!("{left} {connector} {right}"))
}
_ => None,
}
}
fn de_audited_parenthetical_spec(raw: &str) -> Option<DeAuditedCompoundSpec> {
if raw.chars().filter(|character| *character == '(').count() != 1
|| raw.chars().filter(|character| *character == ')').count() != 1
{
return None;
}
let close = raw.rfind("),")?;
let open = raw[..close].rfind('(')?;
if open == 0 || !raw[..open].ends_with(char::is_whitespace) {
return None;
}
if !raw
.get(close + 2..)
.and_then(|tail| tail.chars().next())
.is_some_and(char::is_whitespace)
{
return None;
}
let label = raw[open + 1..close].trim();
if label.is_empty() || label.len() > 80 || !label.chars().any(char::is_alphabetic) {
return None;
}
let address = raw[..open].trim_end();
if address.is_empty()
|| address.trim_start() != address
|| address
.chars()
.any(|character| matches!(character, ',' | ';' | '|'))
{
return None;
}
let split = address.rfind(char::is_whitespace)?;
let street = address[..split].trim_end();
let house_expression = address[split..].trim();
if street.is_empty()
|| !street.chars().any(char::is_alphabetic)
|| street.chars().any(|character| character.is_ascii_digit())
{
return None;
}
let (shape, primary_house, additional_houses) =
if let Some((left, right)) = house_expression.split_once('/') {
if house_expression.matches('/').count() != 1
|| left.as_bytes().first() == Some(&b'0')
|| right.as_bytes().first() == Some(&b'0')
|| normalize(label)
.split_whitespace()
.next()
.is_none_or(|word| word != "aufgang")
{
return None;
}
let left = left.parse::<u32>().ok().filter(|number| *number != 0)?;
let right = right.parse::<u32>().ok().filter(|number| *number > left)?;
(
DeAuditedCompoundShape::StreetHouseRangeBalancedAccessParenthetical,
left,
vec![right],
)
} else {
if house_expression.is_empty()
|| house_expression.len() > 4
|| house_expression.as_bytes().first() == Some(&b'0')
|| !house_expression.bytes().all(|byte| byte.is_ascii_digit())
{
return None;
}
(
DeAuditedCompoundShape::StreetHouseBalancedVenueParenthetical,
house_expression
.parse::<u32>()
.ok()
.filter(|number| *number != 0)?,
Vec::new(),
)
};
let (postcode, postcode_raw, locality_raw) =
de_audited_postcode_locality(raw[close + 2..].trim_start())?;
let normalized_street = de_product_normalize_street(street);
let normalized_locality = de_audited_locality(&locality_raw)?;
if normalized_street.is_empty() {
return None;
}
Some(DeAuditedCompoundSpec {
shape,
street: street.to_string(),
normalized_street,
primary_house,
additional_houses,
postcode,
postcode_raw,
normalized_locality,
})
}
fn de_parenthetical_locality_uses_slash_qualifier(raw: &str) -> bool {
crate::de::parenthetical_subaddress_commune(raw).is_some()
&& raw
.rsplit_once("),")
.is_some_and(|(_, locality)| locality.contains('/'))
}
fn de_audited_venue_spec(raw: &str) -> Option<DeAuditedCompoundSpec> {
let fields: Vec<&str> = raw.split(',').map(str::trim).collect();
if fields.len() != 8
|| fields.iter().any(|field| {
field.is_empty()
|| field.len() > 96
|| field
.chars()
.any(|character| matches!(character, '\n' | '\r' | '\t' | ';' | '|'))
})
|| fields[0]
.chars()
.any(|character| character.is_ascii_digit())
|| !fields[0].chars().any(char::is_alphabetic)
|| fields[1].is_empty()
|| fields[1].len() > 4
|| fields[1].as_bytes().first() == Some(&b'0')
|| !fields[1].bytes().all(|byte| byte.is_ascii_digit())
|| fields[2]
.chars()
.any(|character| character.is_ascii_digit())
|| !fields[2].chars().any(char::is_alphabetic)
{
return None;
}
let postcode_raw = *fields.last()?;
if !is_five_digit_postcode(postcode_raw) {
return None;
}
if fields[3..7].iter().any(|field| {
!field.chars().any(char::is_alphabetic)
|| field.chars().any(|character| character.is_ascii_digit())
}) {
return None;
}
let normalized_street = de_product_normalize_street(fields[2]);
// In the exact eight-field venue grammar, the third field before the
// terminal postcode is the city; the surrounding fields are administrative
// qualifiers and are never alternative query localities.
let normalized_locality = de_product_normalize_text(fields[5]);
if normalized_street.is_empty() || normalized_locality.is_empty() {
return None;
}
Some(DeAuditedCompoundSpec {
shape: DeAuditedCompoundShape::VenueCommaHouseCommaStreet,
street: fields[2].to_string(),
normalized_street,
primary_house: fields[1].parse().ok().filter(|number| *number != 0)?,
additional_houses: Vec::new(),
postcode: postcode_raw.parse().ok()?,
postcode_raw: postcode_raw.to_string(),
normalized_locality,
})
}
fn de_audited_care_of_spec(raw: &str) -> Option<DeAuditedCompoundSpec> {
if raw.len() > 384
|| !raw
.get(..3)
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("c/o"))
|| !raw
.get(3..)
.and_then(|tail| tail.chars().next())
.is_some_and(char::is_whitespace)
{
return None;
}
let mut fields = raw.split(',');
let left = fields.next()?.trim();
let terminal = fields.next()?.trim();
if fields.next().is_some() {
return None;
}
let (postcode, postcode_raw, locality_raw) = de_audited_postcode_locality(terminal)?;
let locality = de_product_normalize_text(&locality_raw);
let left = de_product_normalize_text(left.get(3..)?.trim_start());
let locality_suffix = format!(" {locality}");
let before_locality = left.strip_suffix(&locality_suffix)?.trim_end();
let mut tokens: Vec<&str> = before_locality.split_whitespace().collect();
let house_raw = tokens.pop()?;
let street = tokens.pop()?;
if tokens.is_empty()
|| street.is_empty()
|| !street.chars().any(char::is_alphabetic)
|| house_raw.is_empty()
|| house_raw.len() > 4
|| house_raw.as_bytes().first() == Some(&b'0')
|| !house_raw.bytes().all(|byte| byte.is_ascii_digit())
{
return None;
}
if tokens
.iter()
.any(|token| token.chars().any(|character| character.is_ascii_digit()))
{
return None;
}
let normalized_street = de_product_normalize_compound_street(street)?;
Some(DeAuditedCompoundSpec {
shape: DeAuditedCompoundShape::CareOfPrefixThenStreetHouseLocality,
street: street.to_string(),
normalized_street,
primary_house: house_raw.parse().ok().filter(|number| *number != 0)?,
additional_houses: Vec::new(),
postcode,
postcode_raw,
normalized_locality: locality,
})
}
fn de_audited_compound_spec(raw: &str) -> Option<DeAuditedCompoundSpec> {
if raw.len() > 512
|| raw.trim() != raw
|| raw
.chars()
.any(|character| matches!(character, '\n' | '\r' | '\t' | ';' | '|'))
{
return None;
}
let mut matches = Vec::new();
if let Some(spec) = de_audited_parenthetical_spec(raw) {
matches.push(spec);
}
if let Some(spec) = de_audited_venue_spec(raw) {
matches.push(spec);
}
if let Some(spec) = de_audited_care_of_spec(raw) {
matches.push(spec);
}
(matches.len() == 1).then(|| matches.pop().unwrap())
}
#[cfg(test)]
fn de_postcode_tail(q: &str) -> Option<String> {
de_postcode_context(q).map(|(_, tail)| tail)
}
type RankedHit = (Hit, [f32; N_FEATS], i32, u32, u32, u32);
struct DePostcodeHouseCandidate {
source_sid: u32,
hit: Hit,
features: [f32; N_FEATS],
}
impl DePostcodeHouseCandidate {
fn same_product_projection(&self, other: &Self) -> bool {
self.hit.precision == other.hit.precision
&& self.hit.street == other.hit.street
&& self.hit.housenumber == other.hit.housenumber
&& self.hit.postcode == other.hit.postcode
&& self.hit.commune == other.hit.commune
}
}
fn de_same_retained_address_evidence(a: &RankedHit, b: &RankedHit) -> bool {
a.0.score.to_bits() == b.0.score.to_bits()
&& a.1 == b.1
&& a.2 == b.2
&& a.3 == b.3
&& a.0.precision == b.0.precision
&& a.0.housenumber == b.0.housenumber
&& a.0.postcode == b.0.postcode
&& a.0.flags == b.0.flags
&& street_key(&a.0.street) == street_key(&b.0.street)
}
fn promote_de_retained_locality(
hits: &mut Vec<RankedHit>,
retained: DeRetainedLocality<'_>,
) -> bool {
let Some(top) = hits.first() else {
return false;
};
if top.1[0] <= 0.5 || de_retained_locality_score(retained.postcode_tail, &top.0.commune) != 0 {
return false;
}
let mut best_score = 0;
let mut best_positions = Vec::new();
for (position, candidate) in hits.iter().take(5).enumerate().skip(1) {
if !de_same_retained_address_evidence(candidate, top)
|| !de_dropped_tail_reaches_commune(retained.dropped_tail, &candidate.0.commune)
{
continue;
}
let score = de_retained_locality_score(retained.postcode_tail, &candidate.0.commune);
if score > best_score {
best_score = score;
best_positions.clear();
best_positions.push(position);
} else if score == best_score && score > 0 {
best_positions.push(position);
}
}
if best_positions.len() != 1 {
return false;
}
let chosen = hits.remove(best_positions[0]);
hits.insert(0, chosen);
hits[0].0.flags.push("de_retained_locality");
true
}
/// DE-only c2 tail tie-break for an explicit postcode that survived suffix recovery.
///
/// This is deliberately narrower than the general ranking model: it may only move the
/// unique exact-postcode homonym from the original ranks 2..=5 ahead of a non-postcode
/// winner when both answers are exact matches for the same ordered street spelling and
/// expose exactly the same precision without weakening any non-postal feature evidence.
/// Score and rendered house spelling are intentionally outside the gate; the selected hit
/// is moved intact.
fn promote_de_postal_tail(
hits: &mut Vec<RankedHit>,
is_de: bool,
is_c2_retry: bool,
has_focus: bool,
query_postcode: Option<u32>,
) -> bool {
let (Some(query_postcode), Some(top)) = (query_postcode, hits.first()) else {
return false;
};
let top_features = Feats::from_vec(&top.1);
if !is_de
|| !is_c2_retry
|| has_focus
|| top_features.pc_exact
|| !top_features.street_exact
|| top.0.flags.contains(&"de_retained_locality")
{
return false;
}
let top_street = normalize(&top.0.street);
let top_precision = top.0.precision;
let matching_positions: Vec<usize> =
hits.iter()
.take(5)
.enumerate()
.skip(1)
.filter_map(|(position, candidate)| {
let features = Feats::from_vec(&candidate.1);
let same_non_postal_features =
candidate.1.iter().zip(top.1.iter()).enumerate().all(
|(index, (candidate, top))| matches!(index, 4 | 5) || candidate == top,
);
(features.pc_exact
&& same_non_postal_features
&& candidate.0.postcode.parse::<u32>().ok() == Some(query_postcode)
&& normalize(&candidate.0.street) == top_street
&& candidate.0.precision == top_precision)
.then_some(position)
})
.collect();
if matching_positions.len() != 1 {
return false;
}
let chosen = hits.remove(matching_positions[0]);
hits.insert(0, chosen);
hits[0].0.flags.push("de_postal_tail");
true
}
fn apply_de_c2_tiebreaks(
hits: &mut Vec<RankedHit>,
retained_locality: Option<DeRetainedLocality<'_>>,
is_de: bool,
has_focus: bool,
query_postcode: Option<u32>,
) {
if !has_focus {
if let Some(retained) = retained_locality {
promote_de_retained_locality(hits, retained);
}
}
promote_de_postal_tail(
hits,
is_de,
retained_locality.is_some_and(|retained| retained.postal_tail_eligible),
has_focus,
query_postcode,
);
}
fn expand_first(phrase: &str) -> Option<String> {
let (first, tail) = phrase.split_once(' ')?;
let full = ABBREV.iter().find(|(a, _)| *a == first)?.1;
Some(format!("{full} {tail}"))
}
/// Expansion of a LAST-word abbreviation: in Russian-style addresses the street type
/// trails the name (abbreviated "prospekt"/"ulitsa" after the street name).
fn expand_last(phrase: &str) -> Option<String> {
let (head, last) = phrase.rsplit_once(' ')?;
let full = ABBREV.iter().find(|(a, _)| *a == last)?.1;
Some(format!("{head} {full}"))
}
/// Rotate the type word of a Cyrillic street name — BOTH directions, because source data
/// is inconsistent: the type may trail the name or lead it (genitive names), and queries
/// use either order. Produces the variant with the type word moved to the other end.
fn rotate_type_first(phrase: &str) -> Option<String> {
if let Some((first, tail)) = phrase.split_once(' ') {
if crate::rules::rules().types_cyr.iter().any(|t| t == first) {
return Some(format!("{tail} {first}"));
}
}
if let Some((head, last)) = phrase.rsplit_once(' ') {
if crate::rules::rules().types_cyr.iter().any(|t| t == last) {
return Some(format!("{last} {head}"));
}
}
None
}
/// Queries often omit the street type ("13 de la Paix") while the registry has it
/// ("rue de la Paix"). For a BARE name (no type word) generate typed variants for exact
/// key lookup. Cyrillic: type position is inconsistent, so pad both front and back;
/// Latin scripts: the type always leads, so pad the front only.
fn type_padded_variants(phrase: &str) -> Vec<String> {
let cyr = crate::norm::has_cyrillic(phrase);
let r = crate::rules::rules();
let types: &[String] = if cyr { &r.types_cyr } else { &r.types_latin };
// already has a type word — leave as is (canonical queries stay fast). A Latin type
// leads, so only the first word counts: "gran via" is a bare name ("Calle Gran Via").
let is_type = |w: &str| types.iter().any(|t| t == w);
let typed = if cyr {
phrase.split(' ').any(is_type)
} else {
phrase.split(' ').next().is_some_and(is_type)
};
if typed {
return Vec::new();
}
let mut out = Vec::with_capacity(types.len() * 2);
for t in types {
out.push(format!("{t} {phrase}")); // type in front (all languages)
if cyr {
out.push(format!("{phrase} {t}")); // trailing type — Cyrillic only
}
}
out
}
/// The type padding for rewritten bare-name variants that close with a direction, on a sheet with city_tail
/// `direction_trailing`: "6890 Notre-Dame Est" pads as written ("rue notre dame est") but the sheet
/// keys "rue notre dame e", the padded form of the variant "notre dame e" (Canada, 30.10.2026).
fn type_padded_direction_variants(variants: &[String]) -> Vec<String> {
let cfg = &crate::rules::rules().city_tail;
let Some(directions) = cfg.get("direction_trailing") else {
return Vec::new();
};
let directions: Vec<&str> = directions.split_whitespace().collect();
variants
.iter()
.filter(|v| {
v.rsplit(' ')
.next()
.is_some_and(|w| directions.contains(&w))
})
// a variant that already names a type ("st w" once "Dundas" is read as the town) is no
// bare name: padded, it is "park st w", another street
.filter(|v| !v.split(' ').any(is_street_type_word))
.flat_map(|v| type_padded_variants(v))
.collect()
}
/// Short form of a secondary house-number designator (Cyrillic korpus/stroenie/vladenie
/// markers), else None; the standalone "house" marker word is handled separately (dropped).
fn unit_designator(tok: &str) -> Option<&'static str> {
match tok {
"корпус" | "корп" | "копр" | "корпуса" | "кор" | "к" => Some("к"),
// the data stores the "stroenie" suffix as a single letter ("6 s3"), not "str"
"строение" | "стр" | "строения" | "с" => Some("с"),
"владение" | "влад" | "вл" => Some("вл"),
_ => None,
}
}
/// Typed noise pair: the word is dropped ONLY with a matching argument —
/// "porte gauche" yes, "Rue Porte Pinte" no (blind stop words would kill real streets).
fn noise_pair_ok(word: &str, arg: &str, prev_digitish: bool) -> bool {
let digit = !arg.is_empty() && arg.bytes().all(|b| b.is_ascii_digit());
let single = arg.chars().count() == 1 && arg.chars().all(|c| c.is_alphanumeric());
let roman = matches!(arg, "i" | "ii" | "iii" | "iv" | "v" | "vi");
match word {
"кв" | "квартира" | "оф" | "офис" | "пом" | "помещение" | "подъезд" | "эт" | "этаж"
| "комната" | "ком" | "int" | "interno" | "lokal" | "stan" | "sprat" | "xonadon"
| "kvartira" | "piano" => digit || roman,
"sc" | "scala" | "gebouw" => single,
"porte" => matches!(arg, "gauche" | "droite") || digit,
"appartement" | "appt" | "apt" | "app" | "bat" | "batiment" => digit || single,
"etage" | "hoog" | "verdieping" => prev_digitish || digit,
_ => false,
}
}
/// Single noise word — administrative markers (NOT street words).
/// "sh"/"shahri" is an Uzbek city marker ("Toshkent sh."): the city name itself stays.
/// "gorod" is a mid-string city marker: the name after it stays as well.
fn is_noise_word(tok: &str) -> bool {
crate::rules::rules().noise.contains(tok)
}
/// Region/district marker (e.g. "Chilonzor tumani"): drop the marker AND the name
/// before it (the commune appears later in the string).
fn is_region_marker(tok: &str) -> bool {
crate::rules::rules().region_markers.contains(tok)
}
/// Noise word appearing after the house number.
fn is_noise_word_after(tok: &str) -> bool {
crate::rules::rules().noise_after.contains(tok)
}
/// Trailing country names — stripped from the end of the string.
fn is_country_word(tok: &str) -> bool {
crate::rules::rules().countries_tail.contains(tok)
}
/// Spelled-out numerals -> digits (French date streets: "Douze Mai" -> "12 Mai",
/// "Quatorze Juillet" -> "14 Juillet"). Compounds ("dix sept") must precede simple ones.
const NUM_WORDS: &[(&str, &str)] = &[
("dix sept", "17"),
("dix huit", "18"),
("dix neuf", "19"),
("vingt cinq", "25"),
("premier", "1er"),
("une", "1"),
("un", "1"),
("deux", "2"),
("trois", "3"),
("quatre", "4"),
("cinq", "5"),
("six", "6"),
("sept", "7"),
("huit", "8"),
("neuf", "9"),
("dix", "10"),
("onze", "11"),
("douze", "12"),
("treize", "13"),
("quatorze", "14"),
("quinze", "15"),
("seize", "16"),
("vingt", "20"),
("trente", "30"),
];
/// Replace spelled-out numerals with digits; None if nothing changed.
fn num_words_to_digits(phrase: &str) -> Option<String> {
let mut s = format!(" {phrase} ");
let mut changed = false;
for (w, d) in NUM_WORDS {
let pat = format!(" {w} ");
if s.contains(&pat) {
s = s.replace(&pat, &format!(" {d} "));
changed = true;
}
}
if changed {
Some(s.trim().to_string())
} else {
None
}
}
#[cfg(test)]
thread_local! {
static STREET_DATA_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// English ordinal suffixes of a number: "104th" -> "104" and "37" -> "37th" (1st, 2nd, 3rd,
/// 11th–13th). One word per variant; a phrase with several numbers yields one variant per word.
fn ordinal_variants(phrase: &str) -> Vec<String> {
const SPELLED: &[(&str, &str)] = &[
("first", "1"),
("second", "2"),
("third", "3"),
("fourth", "4"),
("fifth", "5"),
("sixth", "6"),
("seventh", "7"),
("eighth", "8"),
("ninth", "9"),
("tenth", "10"),
("eleventh", "11"),
("twelfth", "12"),
];
let suffix = |n: u32| match (n % 100, n % 10) {
(11..=13, _) => "th",
(_, 1) => "st",
(_, 2) => "nd",
(_, 3) => "rd",
_ => "th",
};
let words: Vec<&str> = phrase.split(' ').filter(|w| !w.is_empty()).collect();
let with = |i: usize, replacement: &str| {
let mut w = words.clone();
w[i] = replacement;
w.join(" ")
};
let mut out = Vec::new();
for (i, word) in words.iter().enumerate() {
// "Fifth Avenue" is keyed "5 Ave": the spelled ordinal becomes the number in both
// written forms ("5", "5th").
if let Some((_, number)) = SPELLED.iter().find(|(w, _)| w == word) {
let n: u32 = number.parse().unwrap_or(0);
out.push(with(i, number));
out.push(with(i, &format!("{number}{}", suffix(n))));
continue;
}
let digits = word.bytes().take_while(u8::is_ascii_digit).count();
if digits == 0 || digits > 4 {
continue;
}
let (number, tail) = word.split_at(digits);
let replacement = if tail.is_empty() {
let n: u32 = number.parse().unwrap_or(0);
format!("{number}{}", suffix(n))
} else if matches!(tail, "st" | "nd" | "rd" | "th") {
number.to_owned()
} else {
continue;
};
out.push(with(i, &replacement));
}
out
}
/// A street name carries a query word when the word stands in it as written, through one of
/// the sheet's one-word rewrites ("s" -> "south", "street" -> "st"; a sheet lists both ways),
/// or as the same number without an ordinal suffix ("52nd" ~ "52").
fn name_covers_word(name_words: &HashSet<&str>, word: &str) -> bool {
if name_words.contains(word) {
return true;
}
let rewrites = &crate::rules::rules().street_rewrites;
if rewrites
.iter()
.any(|(from, to)| from == word && !to.contains(' ') && name_words.contains(to.as_str()))
{
return true;
}
fn bare(w: &str) -> Option<&str> {
let digits = w.bytes().take_while(u8::is_ascii_digit).count();
(digits > 0 && matches!(&w[digits..], "" | "st" | "nd" | "rd" | "th")).then(|| &w[..digits])
}
match bare(word) {
Some(number) => name_words.iter().any(|w| bare(w) == Some(number)),
None => false,
}
}
/// "One Campus Rd": on a sheet whose type trails the name the house number may open the query
/// as a word; the word becomes the digit so the number parser sees it ("1 Campus Rd"). Only the
/// first token, only when a word follows (a name like "One Tree Hill Road" keeps its first word
/// if the next token is a number word or digit).
fn spelled_house_number(raw: &str) -> Option<String> {
const WORDS: &[(&str, &str)] = &[
("one", "1"),
("two", "2"),
("three", "3"),
("four", "4"),
("five", "5"),
("six", "6"),
("seven", "7"),
("eight", "8"),
("nine", "9"),
("ten", "10"),
("eleven", "11"),
("twelve", "12"),
];
if !street_type_last() {
return None;
}
let trimmed = raw.trim_start();
let (first, rest) = trimmed.split_once(char::is_whitespace)?;
let digit = WORDS.iter().find(|(w, _)| first.eq_ignore_ascii_case(w))?.1;
let next = rest.trim_start().chars().next()?;
if !next.is_alphabetic()
|| WORDS.iter().any(|(w, _)| {
rest.trim_start()
.split(|c: char| !c.is_alphanumeric())
.next()
.is_some_and(|n| n.eq_ignore_ascii_case(w))
})
{
return None;
}
Some(format!("{digit} {}", rest.trim_start()))
}
/// The sheet declares that the street type trails the name (city_tail `street_type_last` = 1).
fn street_type_last() -> bool {
crate::rules::rules()
.city_tail
.get("street_type_last")
.is_some_and(|v| v == "1")
}
/// The sheet asks that equal-score homonyms of a cityless query be ordered by commune size
/// before distance to the sheet's anchor commune (city_tail `homonym_prominence` = 1). In a
/// country-sized sheet the anchor is one city among thousands, and "closer to it" says nothing
/// about which Main Street a bare address means; the number of addresses a commune holds does.
fn homonym_prominence_first() -> bool {
crate::rules::rules()
.city_tail
.get("homonym_prominence")
.is_some_and(|v| v == "1")
}
/// A word the sheet's street rewrites know as a street word ("n" -> "north"): on a sheet whose
/// type trails the name (city_tail `street_type_last` = 1) the word after a house number is
/// first a direction of the street ("174 N Mill St" is 174 North Mill Street before it is
/// 174N Mill Street). Data-driven: a sheet without the flag or the rewrite keeps its order.
fn street_rewrite_word(token: &str) -> bool {
street_type_last()
&& crate::rules::rules()
.street_rewrites
.iter()
.any(|(from, _)| from == token)
}
/// The longest short form a one-word rewrite of the sheet gives `word` ("highway" -> "hwy"), or the
/// word itself.
fn sheet_short_form(word: &str, one_word: &impl Fn(&str, &str) -> bool) -> String {
crate::rules::rules()
.street_rewrites
.iter()
.filter(|(from, to)| {
to == word && one_word(from, to) && from.len() < to.len() && !from.contains(' ')
})
.map(|(from, _)| from)
.max_by_key(|from| from.len())
.cloned()
.unwrap_or_else(|| word.to_owned())
}
/// The sheet's key for a numbered road on a sheet with city_tail `number_first_types` (the short
/// type words it keys number first: "7 hwy"): a phrase that is only a road number, its type and
/// an optional "no" in any order ("highway 7", "highway no 3", "no 2 highway") becomes
/// "<number> <type>". None otherwise (Canada, 29.10.2026).
fn number_first_key(phrase: &str, one_word: impl Fn(&str, &str) -> bool) -> Option<String> {
let types = crate::rules::rules()
.city_tail
.get("number_first_types")?
.split_whitespace()
.map(str::to_owned)
.collect::<Vec<_>>();
let words: Vec<&str> = phrase.split(' ').filter(|w| *w != "no").collect();
if words.len() != 2 {
return None;
}
let is_number =
|w: &str| !w.is_empty() && w.len() <= 4 && w.bytes().all(|b| b.is_ascii_digit());
let (number, kind) = if is_number(words[0]) {
(words[0], words[1])
} else if is_number(words[1]) {
(words[1], words[0])
} else {
return None;
};
let kind = sheet_short_form(kind, &one_word);
types
.contains(&kind)
.then(|| [number, kind.as_str()].join(" "))
}
/// The sheet's own key for a street phrase on a sheet with city_tail `direction_trailing`: a
/// leading "st"/"ste" before a name spelled Saint/Sainte, a leading direction moved to the end,
/// and every other word shortened to the longest short form a one-word rewrite of the sheet gives
/// it. None on a sheet without the key, for a phrase of fewer than three words, or for one that
/// opens with neither a direction nor "st"/"ste".
fn direction_trailing_key(phrase: &str, one_word: impl Fn(&str, &str) -> bool) -> Option<String> {
let directions = crate::rules::rules()
.city_tail
.get("direction_trailing")?
.split_whitespace()
.map(str::to_owned)
.collect::<Vec<_>>();
let short = |w: &str| sheet_short_form(w, &one_word);
let mut words: Vec<String> = phrase.split(' ').map(str::to_owned).collect();
if words.len() < 3 {
return None;
}
let saint = match words[0].as_str() {
"st" => Some("saint"),
"ste" => Some("sainte"),
_ => None,
};
if let Some(full) = saint {
words[0] = full.to_owned();
} else if directions.contains(&short(&words[0])) {
let direction = words.remove(0);
words.push(direction);
} else {
return None;
}
Some(
words
.iter()
.map(|w| {
if matches!(w.as_str(), "saint" | "sainte") {
w.clone()
} else {
short(w)
}
})
.collect::<Vec<_>>()
.join(" "),
)
}
/// The sheet's keys for a street phrase opening with a type word, on a sheet with city_tail
/// `type_first_siblings` = 1: the sheet keeps a type written in front by one short form ("boul.
/// Manseau", "av. des Pins O") while the writer used another of the same type ("Blvd Manseau",
/// "Ave des Pins Ouest"). Reaching it takes two rewrites of one kind (blvd -> boulevard -> boul),
/// and the staged rounds apply each kind once. Every other short form of the type's full word is
/// put in front, with the rest as written and with each word at its sheet short form
/// ("ouest" -> "o"). Empty without the key or when the first word is no short type word
/// (Canada, 30.10.2026).
fn type_first_sibling_keys(phrase: &str, one_word: impl Fn(&str, &str) -> bool) -> Vec<String> {
let rules = crate::rules::rules();
if rules
.city_tail
.get("type_first_siblings")
.map(String::as_str)
!= Some("1")
{
return Vec::new();
}
let Some((first, rest)) = phrase.split_once(' ') else {
return Vec::new();
};
let short_rest = rest
.split(' ')
.map(|w| sheet_short_form(w, &one_word))
.collect::<Vec<_>>()
.join(" ");
let shorter =
|from: &str, to: &str| one_word(from, to) && from.len() < to.len() && !from.contains(' ');
let mut keys: Vec<String> = Vec::new();
for (_, full) in rules
.street_rewrites
.iter()
.filter(|(from, to)| from == first && shorter(from, to) && is_street_type_word(to))
{
for (sibling, _) in rules
.street_rewrites
.iter()
.filter(|(from, to)| to == full && from != first && shorter(from, to))
{
for tail in [rest, short_rest.as_str()] {
let key = format!("{sibling} {tail}");
if !keys.contains(&key) {
keys.push(key);
}
}
}
}
keys
}
/// The words of a fuzzy lookup with street types and direction words at the sheet's short form,
/// on a sheet with city_tail `fuzzy_short_forms` = 1 ("ratchfrod street" -> "ratchfrod st",
/// "sherrbooke ouest" -> "sherrbooke o"). The sheet keys every street with its short type and
/// direction ("ratchford st"), so a typo in the name plus a type written out is two edits and a
/// rewrite — past the one edit the fuzzy search allows a short name. Directions are the sheet's
/// `direction_trailing` words. None without the key or when no word changes (Canada, 30.10.2026).
fn fuzzy_short_rest(rest: &[&str]) -> Option<Vec<String>> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("fuzzy_short_forms").map(String::as_str) != Some("1") {
return None;
}
let directions: Vec<&str> = cfg
.get("direction_trailing")
.map(|d| d.split_whitespace().collect())
.unwrap_or_default();
let one_word = |from: &str, to: &str| !from.contains(' ') && !to.contains(' ');
let mut changed = false;
let short: Vec<String> = rest
.iter()
.map(|w| {
let s = sheet_short_form(w, &one_word);
if s != *w && (is_street_type_word(w) || directions.contains(&s.as_str())) {
changed = true;
s
} else {
(*w).to_owned()
}
})
.collect();
changed.then_some(short)
}
/// Rule alternatives for a street lookup key after house-number extraction.
/// Two snapshot rounds compose a type with a numeral or linker rewrite.
fn street_data_variants(phrase: &str) -> Vec<String> {
#[cfg(test)]
STREET_DATA_CALLS.with(|n| n.set(n.get() + 1));
const MAX_VARIANTS: usize = 8;
let rules = &crate::rules::rules().street_rewrites;
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
// Rule shape supplies the kind; the engine carries no language-specific vocabulary.
let kind = |from: &str, to: &str| {
if digits(from) || digits(to) {
0
} else if to.starts_with(&format!("{from} ")) || from.starts_with(&format!("{to} ")) {
2
} else {
1
}
};
let particles = rules
.iter()
.filter_map(|(a, b)| {
if kind(a, b) != 2 {
return None;
}
let (short, long) = if a.len() < b.len() { (a, b) } else { (b, a) };
let suffix = long.strip_prefix(&format!("{short} "))?;
(!suffix.contains(' ')).then_some((short.as_str(), suffix))
})
.collect::<Vec<_>>();
let is_particle = |word: &str| particles.iter().any(|(_, p)| *p == word);
let doubled = |candidate: &str| {
particles.iter().any(|(ty, _)| {
candidate
.strip_prefix(&format!("{ty} "))
.is_some_and(|rest| {
let mut words = rest.split_whitespace();
words.next().is_some_and(&is_particle) && words.next().is_some_and(&is_particle)
})
})
};
let mut variants = vec![phrase.to_owned()];
// A sheet that keeps the direction after the type, every word abbreviated ("10th ave e",
// "hastings st w"; city_tail `direction_trailing` lists the sheet's direction words): the
// writer's "East 10th Avenue" or "West Hastings Street" reaches that key only with the
// direction moved and three words rewritten at once, past the variant cap of the staged
// rounds; and "St George Street" is Saint George. That one key comes after every staged
// variant, so it takes no slot of theirs (Canada, 29.10.2026).
let sheet_keys: Vec<String> = [
direction_trailing_key(phrase, |from, to| kind(from, to) == 1),
number_first_key(phrase, |from, to| kind(from, to) == 1),
]
.into_iter()
.flatten()
.chain(type_first_sibling_keys(phrase, |from, to| {
kind(from, to) == 1
}))
.filter(|key| key != phrase)
.collect();
let finish = |variants: Vec<String>| -> Vec<String> {
let mut out: Vec<String> = variants.into_iter().skip(1).collect();
for key in &sheet_keys {
if !out.contains(key) {
out.push(key.clone());
}
}
out
};
// Ordinal street numbers on a sheet whose type trails the name ("104th Street", "5th
// Avenue"): the sheet keys some with the suffix and some without ("E 104 St", "South 37th
// Street"), so the key is tried both ways. Composes with the rounds below; the house
// number is not part of the phrase, so only street words change.
if street_type_last() {
for variant in ordinal_variants(phrase) {
if !variants.contains(&variant) {
variants.push(variant);
}
}
// Every abbreviated word at once ("e 1st n st" -> "east 1st north street"): the
// staged rewrites below spell out one position each, and a name with two directions
// and a type reaches the variant cap before all three are written out (US,
// 23.10.2026, "126 E 1st N St, Mesquite").
// A type word is spelled out only where a type stands — last, or before a closing
// direction ("16th st n"), a road number ("county rd 352") or a one-letter name
// ("east ave m", Lancaster); inside the name "st" is Saint ("old st james st").
let words: Vec<&str> = phrase.split(' ').collect();
let n = words.len();
let spell = |w: &str| {
rules
.iter()
.find(|(from, to)| {
from.as_str() == w
&& kind(from, to) == 1
&& to.len() > from.len()
&& !to.contains(' ')
})
.map(|(_, to)| to.clone())
};
let expanded = words
.iter()
.enumerate()
.map(|(i, w)| match spell(w) {
Some(to) if !is_street_type_word(&to) => to,
Some(to)
if i + 1 == n
|| (i + 2 == n
&& (spell(words[n - 1]).is_some_and(|t| !is_street_type_word(&t))
|| digits(words[n - 1])
|| words[n - 1].chars().count() == 1)) =>
{
to
}
_ => (*w).to_owned(),
})
.collect::<Vec<_>>()
.join(" ");
if expanded != phrase && !variants.contains(&expanded) {
variants.push(expanded);
}
}
// Each kind is applied once, to the snapshot from preceding kinds only.
// Numerals come first, then types, then linkers: composition never feeds its own kind.
// A sheet whose street type trails the name (city_tail street_type_last=1, US) gets a
// fourth round: the same one-word type rewrites at the LAST word, composed with the
// leading-word round ("n main st" -> "north main st" -> "north main street"), and a
// fifth at the word BEFORE a trailing street word or a trailing number: the type sits
// there when a direction closes the name ("16th st nw" -> "16th st northwest" -> "16th
// street northwest") or when the road is numbered ("e rte 66" -> "e route 66").
let stages = if street_type_last() { 5 } else { 3 };
let is_street_word = |word: &str| rules.iter().any(|(from, to)| from == word || to == word);
for stage in 0..stages {
let bases = variants.clone();
for base in bases {
for (from, to) in rules {
let wanted = if stage >= 3 { 1 } else { stage };
if kind(from, to) != wanted {
continue;
}
let candidate = if stage == 3 {
let Some(head) = base.strip_suffix(&format!(" {from}")) else {
continue;
};
format!("{head} {to}")
} else if stage == 4 {
let Some((head, last)) = base.rsplit_once(' ') else {
continue;
};
// … or before a trailing number: numbered roads keep the type in the
// middle ("e rte 66" -> "e route 66", "county rd 352").
if !is_street_word(last) && !digits(last) {
continue;
}
let Some(head) = head.strip_suffix(&format!(" {from}")) else {
continue;
};
format!("{head} {to} {last}")
} else if stage == 0 {
let padded = format!(" {base} ");
let pattern = format!(" {from} ");
if !padded.contains(&pattern) {
continue;
}
padded
.replacen(&pattern, &format!(" {to} "), 1)
.trim()
.to_owned()
} else {
let Some(rest) = base.strip_prefix(&format!("{from} ")) else {
continue;
};
// Adding a linker in front of an existing linker would duplicate it.
if stage == 2
&& to.starts_with(&format!("{from} "))
&& rest.split_whitespace().next().is_some_and(&is_particle)
{
continue;
}
format!("{to} {rest}")
};
if !doubled(&candidate) && !variants.contains(&candidate) {
if variants.len() > MAX_VARIANTS {
return finish(variants);
}
variants.push(candidate);
}
}
}
}
finish(variants)
}
/// Serbian genitive street names: the registry stores "Kneza Mihaila" (genitive) while
/// people write the nominative "Knez Mihailova". Title -> +a (knez -> kneza), possessive
/// "-ova/-eva" -> "-a" (Mihailova -> Mihaila). Extra variant, Latin script only.
fn serbian_genitive_variant(phrase: &str) -> Option<String> {
let words: Vec<&str> = phrase.split(' ').collect();
if words.len() < 2 {
return None;
}
let mut changed = false;
let out: Vec<String> = words
.iter()
.map(|w| match *w {
// Serbian titles in street names + Russian transliterated forms (a Russian
// speaker writes the Serbian street in their own genitive: knjaza -> kneza,
// korolja -> kralja)
"knez" | "knjaz" | "knjaza" | "knjazja" => {
changed = true;
"kneza".into()
}
"kralj" | "korol" | "korolja" | "korolj" => {
changed = true;
"kralja".into()
}
"car" | "carja" => {
changed = true;
"cara".into()
}
"vojvoda" | "voevody" | "voevoda" => {
changed = true;
"vojvode".into()
}
s if (s.ends_with("ova") || s.ends_with("eva")) && s.chars().count() > 4 => {
changed = true;
format!("{}a", &s[..s.len() - 3])
}
s => s.to_string(),
})
.collect();
if changed {
Some(out.join(" "))
} else {
None
}
}
/// Levenshtein distance (for the name-similarity ranking tie-breaker).
fn lev(a: &[char], b: &[char]) -> usize {
let (n, m) = (a.len(), b.len());
if n == 0 {
return m;
}
if m == 0 {
return n;
}
let mut prev: Vec<usize> = (0..=m).collect();
let mut cur = vec![0usize; m + 1];
for i in 1..=n {
cur[0] = i;
for j in 1..=m {
let cost = usize::from(a[i - 1] != b[j - 1]);
cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
}
std::mem::swap(&mut prev, &mut cur);
}
prev[m]
}
/// Folds spelled-out secondary designators into compact suffix tokens ("korpus 3" -> "k3",
/// "stroenie 1" -> "str1", the bare "house" word is dropped): Cyrillic addresses spell
/// these out while the data stores them as part of the suffix ("32 k3"). Merges the
/// designator and its number into one token BEFORE parsing.
fn fold_units(q: &str) -> String {
let toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
let n0 = toks.len();
// position of the first digit group: floor/apartment noise lives AFTER the number,
// while before it "porte"/"piano"/"gauche" are parts of real street names
let first_digit = toks
.iter()
.position(|t| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()))
.unwrap_or(n0);
let mut out: Vec<String> = Vec::with_capacity(n0);
let mut i = 0;
while i < n0 {
let t = toks[i];
if t == "дом"
|| t == "uy"
|| t == "д" && i + 1 < n0 && toks[i + 1].bytes().all(|b| b.is_ascii_digit())
{
i += 1; // bare house-marker word; the adjacent number is the house number
continue;
}
// "korpus N" BEFORE the first digit group is just a number marker (block numbers
// are stored in the index as the numero). AFTER the house number it is left alone:
// "12 k 1" is the suffix (rep) form and takes its own path.
if i < first_digit
&& matches!(t, "к" | "корп" | "корпус" | "korpus")
&& i + 1 < n0
&& toks[i + 1]
.bytes()
.next()
.is_some_and(|b| b.is_ascii_digit())
{
i += 1;
continue;
}
if t == "тел" || t == "tel" || t == "phone" || t.starts_with('+') {
break; // phone numbers always trail; cut to the end
}
// CEDEX tail (French corporate mail): in "Lyon Cedex 03" the "cedex" token and the
// office number are not part of the address (BAN has no "cedex" entries). Drop both.
if t == "cedex" {
i += 1;
if i < n0 && toks[i].len() <= 2 && toks[i].bytes().all(|b| b.is_ascii_digit()) {
i += 1;
}
continue;
}
if t == "chez" && i == 0 {
i += 1; // "Chez M. Durand, ..." — only at the START (Rue de Chez Guillot is a street!)
continue;
}
if is_noise_word(t) {
i += 1;
continue;
}
// region/district marker (e.g. "Chilonzor tumani"): drop the marker AND the
// region name before it — the commune appears later in the string
if is_region_marker(t) {
out.pop();
i += 1;
continue;
}
// country word MID-STRING ("torcy france 77200") is dropped, EXCEPT as part of a
// street name ("Rue de France", "Via Italia" — country after a linker, plus the
// explicit Italian `via/corso italia` forms). Keep the new exception deliberately narrow:
// treating every country noun after every multilingual street type as a name changed
// established FR/NL/RU parsing behaviour.
if crate::rules::rules().countries_mid.contains(t)
&& !matches!(
out.last().map(|s| s.as_str()),
Some("de" | "du" | "des" | "di" | "della" | "del" | "da")
)
&& !matches!(
(out.last().map(String::as_str), t),
(Some("via" | "corso"), "italia")
)
{
i += 1;
continue;
}
// Roman-numeral floor right after a number: "73 ii" (from "73/II") — drop it
if i > first_digit
&& matches!(t, "i" | "ii" | "iii" | "iv" | "v" | "vi")
&& out
.last()
.is_some_and(|p| p.bytes().all(|b| b.is_ascii_digit()))
{
i += 1;
continue;
}
if i > first_digit && is_noise_word_after(t) {
i += 1;
continue;
}
// typed pairs: apartment/floor markers with an argument ("int 5", "sc b", "porte gauche", "2eme etage")
{
let arg = if i + 1 < n0 { toks[i + 1] } else { "" };
let prev_digitish = out
.last()
.is_some_and(|p| p.bytes().next().is_some_and(|b| b.is_ascii_digit()));
if noise_pair_ok(t, arg, prev_digitish) {
if matches!(t, "etage" | "hoog" | "verdieping")
&& prev_digitish
&& !arg.bytes().all(|b| b.is_ascii_digit())
{
out.pop(); // "2eme etage" / "3e verdieping" — drop the ordinal too
i += 1;
} else {
i += if !arg.is_empty() { 2 } else { 1 };
}
continue;
}
}
if let Some(short) = unit_designator(t) {
// fold the single-letter designator only when a number follows
// (otherwise it may be an initial in a street name)
if i + 1 < n0
&& toks[i + 1].bytes().all(|b| b.is_ascii_digit())
&& !toks[i + 1].is_empty()
{
out.push(format!("{short}{}", toks[i + 1]));
i += 2;
continue;
}
}
// "litera X" -> the letter becomes the suffix
if (t == "литера" || t == "лит") && i + 1 < n0 && toks[i + 1].chars().count() == 1
{
out.push(toks[i + 1].to_string());
i += 2;
continue;
}
out.push(t.to_string());
i += 1;
}
// trailing countries ("..., France", "..., Italia")
while out.len() > 2 && is_country_word(out.last().unwrap()) {
out.pop();
}
out.join(" ")
}
/// Expand two-token abbreviations in the prepared string.
fn expand_two_token(q: &str) -> String {
let mut s = q.to_string();
for (ab, full) in &crate::rules::rules().abbrev2 {
s = s.replace(&format!("{ab} "), &format!("{full} "));
}
s
}
/// French arrondissements: human spellings -> BAN canon, STRICTLY BY CONTEXT (hundreds of
/// streets have "Neme" in the name itself — "rue du 87eme" — so a global rewrite would corrupt them):
/// - "lyon 3eme" -> "lyon 3e" (otherwise the compound-token hypothesis reads "3eme" as
/// house number 3); also applies before "arrondissement";
/// - Roman numerals after a city or before "arrondissement": "paris xi"/"paris ive" -> "paris 11e"/"paris 4e";
/// - order "1er arrondissement paris" -> "paris 1er arrondissement" (exact BAN commune name);
/// - the same order with the formal preposition, "1er arrondissement de paris".
fn fr_arrondissement_rewrite(q: &str) -> Option<String> {
if !(q.contains("paris") || q.contains("lyon") || q.contains("marseille")) {
return None;
}
const ROMANS: [&str; 20] = [
"i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii", "xiii", "xiv",
"xv", "xvi", "xvii", "xviii", "xix", "xx",
];
let is_city = |t: &str| crate::rules::rules().fr_ord_cities.contains(t);
let mut toks: Vec<String> = q
.split(' ')
.filter(|t| !t.is_empty())
.map(str::to_string)
.collect();
let mut changed = false;
for i in 0..toks.len() {
let prev_city = i > 0 && is_city(&toks[i - 1]);
let next_arr = toks
.get(i + 1)
.is_some_and(|t| t.starts_with("arrondissement"));
if !prev_city && !next_arr {
continue;
}
let t = toks[i].clone();
// "3eme" -> "3e", and every first-ordinal spelling -> BAN's canonical "1er"
// (accented forms are already normalized to "3eme").
if let Some(num) = t
.strip_suffix("eme")
.or_else(|| t.strip_suffix("er"))
.or_else(|| t.strip_suffix('e'))
{
if !num.is_empty() && num.len() <= 2 && num.bytes().all(|b| b.is_ascii_digit()) {
let canonical = if num == "1" {
"1er".to_string()
} else {
format!("{num}e")
};
if toks[i] != canonical {
toks[i] = canonical;
changed = true;
}
continue;
}
}
// Roman numerals (with optional e/er/eme): "xi" -> "11e", "ive" -> "4e", "ier" -> "1er"
let core = t
.strip_suffix("eme")
.or_else(|| t.strip_suffix("er"))
.or_else(|| t.strip_suffix('e'))
.unwrap_or(&t);
if let Some(pos) = ROMANS.iter().position(|r| *r == core) {
let n = pos + 1;
toks[i] = if n == 1 {
"1er".to_string()
} else {
format!("{n}e")
};
changed = true;
}
}
let reorder_city_first =
toks.len() >= 4 && is_city(&toks[0]) && fr_ordinal_number(&toks[1]).is_some();
// "1er arrondissement paris" / "1er arrondissement de paris"
// -> "paris 1er arrondissement".
let mut i = 0;
while i + 2 < toks.len() {
let ord_core = toks[i].trim_end_matches(|c: char| c.is_ascii_alphabetic());
let city_match = if is_city(&toks[i + 2]) {
Some((i + 2, false))
} else if toks.get(i + 2).is_some_and(|t| t == "de")
&& toks.get(i + 3).is_some_and(|t| is_city(t))
{
Some((i + 3, true))
} else {
None
};
if toks[i + 1].starts_with("arrondissement")
&& !ord_core.is_empty()
&& ord_core.len() <= 2
&& ord_core.bytes().all(|b| b.is_ascii_digit())
&& toks[i].len() > ord_core.len()
{
if let Some((city_pos, had_de)) = city_match {
let city = toks.remove(city_pos);
if had_de {
toks.remove(i + 2);
}
toks.insert(i, city);
changed = true;
i += 3;
continue;
}
}
i += 1;
}
// City-first full address: "Paris 15e Rue du Hameau 37" (with an optional
// "arrondissement" label) -> street/house first, canonical commune last. Area-only
// "Paris 15e" is intentionally left alone for the city resolver.
if reorder_city_first {
let city = toks.remove(0);
let ordinal = toks.remove(0);
if toks
.first()
.is_some_and(|token| token.starts_with("arrondissement"))
{
toks.remove(0);
}
toks.push(city);
toks.push(ordinal);
toks.push("arrondissement".to_string());
changed = true;
}
if changed {
Some(toks.join(" "))
} else {
None
}
}
#[derive(Debug, PartialEq, Eq)]
enum FrPostcodeArea {
Match(String),
Conflict,
}
fn fr_ordinal_number(token: &str) -> Option<usize> {
let digits = token
.strip_suffix("eme")
.or_else(|| token.strip_suffix("er"))
.or_else(|| token.strip_suffix('e'))?;
if digits.is_empty() || digits.len() > 2 || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
digits.parse().ok()
}
/// Recognize the postcode-only administrative-area forms that cannot go through the normal
/// address parser (it otherwise interprets the postcode as a house number). This is deliberately
/// restricted to the three French cities whose postal codes encode an arrondissement.
///
/// A contradictory city/ordinal is rejected instead of silently returning the wrong district.
/// Queries with street-like tokens are left to the normal parser.
fn fr_arrondissement_postcode_area(q: &str) -> Option<FrPostcodeArea> {
let toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
let postcodes: Vec<(usize, &str)> = toks
.iter()
.enumerate()
.filter_map(|(i, t)| {
(t.len() == 5 && t.bytes().all(|b| b.is_ascii_digit())).then_some((i, *t))
})
.collect();
if postcodes.len() != 1 {
return None;
}
let (postcode_pos, postcode) = postcodes[0];
let postcode_num: usize = postcode.parse().ok()?;
let (city, ordinal) = match postcode_num {
75_001..=75_020 => ("paris", postcode_num - 75_000),
75_116 => ("paris", 16),
69_001..=69_009 => ("lyon", postcode_num - 69_000),
13_001..=13_016 => ("marseille", postcode_num - 13_000),
_ => return None,
};
let rest: Vec<&str> = toks
.iter()
.enumerate()
.filter_map(|(i, t)| (i != postcode_pos).then_some(*t))
.collect();
let canonical_ordinal = if ordinal == 1 {
"1er".to_string()
} else {
format!("{ordinal}e")
};
let canonical = format!("{city} {canonical_ordinal} arrondissement");
let matches_area_form = |area: &[&str]| {
let without_label: Vec<&str> = area
.iter()
.copied()
.filter(|t| !t.starts_with("arrondissement"))
.collect();
match without_label.as_slice() {
[] => true,
[one] if *one == city => true,
[one] => fr_ordinal_number(one) == Some(ordinal),
[first, second] if *first == city => fr_ordinal_number(second) == Some(ordinal),
[first, second] if *second == city => fr_ordinal_number(first) == Some(ordinal),
_ => false,
}
};
let is_area_token = |t: &&str| {
matches!(*t, "paris" | "lyon" | "marseille")
|| t.starts_with("arrondissement")
|| fr_ordinal_number(t).is_some()
};
let suffix = &toks[postcode_pos + 1..];
if !suffix.is_empty() && suffix.iter().all(is_area_token) && !matches_area_form(suffix) {
return Some(FrPostcodeArea::Conflict);
}
let mut area_start = postcode_pos;
while area_start > 0 && is_area_token(&toks[area_start - 1]) {
area_start -= 1;
}
let prefix_area = &toks[area_start..postcode_pos];
if prefix_area.len() >= 2 && !matches_area_form(prefix_area) {
return Some(FrPostcodeArea::Conflict);
}
let matches = matches_area_form(&rest);
if matches {
return Some(FrPostcodeArea::Match(canonical));
}
if !rest.is_empty() && rest.iter().all(is_area_token) {
Some(FrPostcodeArea::Conflict)
} else {
None
}
}
/// Whether the normalized query contains an explicit adjacent French city + arrondissement.
/// The pair may be before or after the street phrase; fallbacks must not drop it and return a
/// house from another district.
fn has_explicit_fr_arrondissement(q: &str) -> bool {
let toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
let is_city = |t: &str| matches!(t, "paris" | "lyon" | "marseille");
toks.windows(2)
.any(|pair| is_city(pair[0]) && fr_ordinal_number(pair[1]).is_some())
}
/// Canonical arrondissement explicitly constrained by a French query.
///
/// This is a postcondition for full-address parsing, not another parser: an encoded Paris,
/// Lyon or Marseille postcode, or an explicit trailing `city ordinal`, must be reflected by
/// the returned commune. Otherwise a perfectly matching street in another arrondissement
/// can win and silently discard the user's administrative constraint.
fn fr_arrondissement_constraint(q: &str) -> Option<FrPostcodeArea> {
let toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
let from_parts = |city: &str, ordinal: usize| -> Option<String> {
let max = match city {
"paris" => 20,
"lyon" => 9,
"marseille" => 16,
_ => return None,
};
if !(1..=max).contains(&ordinal) {
return None;
}
let ordinal = if ordinal == 1 {
"1er".to_string()
} else {
format!("{ordinal}e")
};
Some(format!("{city} {ordinal} arrondissement"))
};
let mut signals = Vec::new();
for token in &toks {
if token.len() != 5 || !token.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
let Ok(postcode) = token.parse::<usize>() else {
continue;
};
let area = match postcode {
75_001..=75_020 => from_parts("paris", postcode - 75_000),
75_116 => from_parts("paris", 16),
69_001..=69_009 => from_parts("lyon", postcode - 69_000),
13_001..=13_016 => from_parts("marseille", postcode - 13_000),
_ => None,
};
if let Some(area) = area {
signals.push(area);
}
}
if has_explicit_fr_arrondissement(q) {
for pair in toks.windows(2) {
if let Some(area) = fr_ordinal_number(pair[1]).and_then(|n| from_parts(pair[0], n)) {
signals.push(area);
}
}
}
let first = signals.first()?.clone();
if signals.iter().skip(1).any(|area| area != &first) {
Some(FrPostcodeArea::Conflict)
} else {
Some(FrPostcodeArea::Match(first))
}
}
/// Street-phrase variant with the LAST TWO words swapped: the Italian registry stores
/// "corso matteotti giacomo" (surname-first) while people write "corso giacomo matteotti",
/// so the exact key would miss and fuzzy matching would drift to a wrong street.
fn swap_last_two_variant(phrase: &str) -> Option<String> {
let w: Vec<&str> = phrase.split(' ').filter(|t| !t.is_empty()).collect();
if w.len() < 3 {
return None;
}
let mut v = w.clone();
let n = v.len();
v.swap(n - 2, n - 1);
Some(v.join(" "))
}
/// Phrase variant UNGLUING "letter(s)+digits" tokens ("c5" -> "c 5"): preprocessing glues
/// hyphenated block codes ("c-5" -> "c5") while the index stores them spaced ("c 5"), so
/// the exact key would be unreachable. Unglues short fused tokens.
fn unglue_variant(phrase: &str) -> Option<String> {
let mut changed = false;
let out: Vec<String> = phrase
.split(' ')
.filter(|t| !t.is_empty())
.map(|t| {
let alpha: String = t.chars().take_while(|c| c.is_alphabetic()).collect();
let rest = &t[alpha.len()..];
if !alpha.is_empty()
&& alpha.chars().count() <= 2
&& !rest.is_empty()
&& rest.len() <= 4
&& rest.bytes().all(|b| b.is_ascii_digit())
{
changed = true;
format!("{alpha} {rest}")
} else {
t.to_string()
}
})
.collect();
if changed {
Some(out.join(" "))
} else {
None
}
}
/// Phone-number run: in "Anna Visser 06 81 22 64 90" digit pairs would parse as house
/// numbers and the surname could match a street, yielding a confident bogus hit. A run of
/// >=4 consecutive short digit tokens never occurs in a real address (house+postcode+block
/// > are <=3 and separated by words) — cut the run; the remainder honestly yields empty/low.
fn strip_phone_runs(q: &str) -> Option<String> {
let toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
let is_short_num = |t: &str| t.len() <= 4 && t.bytes().all(|b| b.is_ascii_digit());
let mut keep = vec![true; toks.len()];
let mut changed = false;
let mut i = 0;
while i < toks.len() {
if is_short_num(toks[i]) {
let mut j = i;
while j < toks.len() && is_short_num(toks[j]) {
j += 1;
}
if j - i >= 4 {
keep[i..j].fill(false);
changed = true;
}
i = j;
} else {
i += 1;
}
}
if !changed {
return None;
}
Some(
toks.iter()
.zip(&keep)
.filter(|(_, k)| **k)
.map(|(t, _)| *t)
.collect::<Vec<_>>()
.join(" "),
)
}
#[derive(Default)]
struct DeBlankPostcodeDisplayProjection {
ranges: HashMap<(String, String), (usize, usize)>,
sids: Box<[u32]>,
}
impl DeBlankPostcodeDisplayProjection {
fn get(&self, display_street: &str, locality: &str) -> Option<&[u32]> {
let &(start, count) = self
.ranges
.get(&(display_street.to_string(), locality.to_string()))?;
self.sids.get(start..start.checked_add(count)?)
}
}
pub struct Index {
// Owned backing memory: the mapping and this file's rules are freed when the
// Index drops. Every `&'static` field below borrows from `_mmap`; they never escape the Index,
// so the lie is sound. Declared first, but field drop order is irrelevant — the borrowing
// fields' Drops never dereference the bytes.
_mmap: Arc<Mapping>,
_rules_owned: Option<Box<crate::rules::Rules>>,
/// Header version controls the conditional house-block grammar. v6 remains readable during
/// migration but never carries v7's local postcode dictionary or fifth house varint.
format_version: u8,
communes_fst: Map<&'static [u8]>,
streets_fst: Map<&'static [u8]>,
communes_meta: &'static [u8],
postings: &'static [u8],
streets_meta: &'static [u8],
houses: &'static [u8],
names: &'static [u8],
cells_dir: &'static [u8],
cells_post: &'static [u8],
words_fst: Map<&'static [u8]>,
word_postings: &'static [u8],
/// DE-only exact five-digit postcode → street-id associations. This
/// compact, immutable open-time projection lets typed product predicates
/// prove uniqueness independently of the street FST's source key.
de_postcode_streets: Box<[(u32, u32)]>,
/// DE-only normalized display-street → every source street id for display
/// identities that contain at least one wholly postcode-less street. P5
/// cannot use `streets_fst`: its key is the source `nom_voie_norm`, which
/// may legitimately differ from the product-visible display street.
de_blank_postcode_display_streets: DeBlankPostcodeDisplayProjection,
commune_coords: &'static [u8],
rep_lookup: HashMap<String, u32>,
/// Suffix by on-disk rep id. Index 0 is the empty suffix, so decoding a house's rep is
/// O(1); `rep_lookup` remains the separate query-text -> id parser dictionary.
rep_suffixes: Vec<String>,
/// Rep id of `RANGE_MARKER` when the sheet carries range points (prep/us_tiger.py):
/// sampled points of an address *range* rather than houses. find_house interpolates
/// between two of them whatever their number gap, and a hit on a marked number is an
/// interpolation, not a house. `None` on every sheet without range points.
range_marker_rep: Option<u32>,
parser: Option<crate::ml::Parser>,
rank: Option<Rank>,
/// This file's own rule tables (SEC_RULES), or the built-in defaults. Made current for
/// the thread while a query runs, so two files built from different rule versions —
/// a current sheet and an older one — never answer with each other's rules.
rules: &'static crate::rules::Rules,
es_particle_rules_may_supply_number: std::sync::OnceLock<bool>,
// Product-visible street names, not source FST keys; every source id is retained.
field_display_streets: std::sync::OnceLock<HashMap<String, Vec<u32>>>,
/// Five-digit postcode → street ids, built on first use by `postal_street_suffix` (Mexico).
postcode_roster: std::sync::OnceLock<Box<[(u32, u32)]>>,
field_title_streets: std::sync::OnceLock<HashMap<String, Vec<u32>>>,
/// Centroid of the most prominent commune in the index (the de-facto capital) — a weak
/// anchor for tie-breaking homonyms when the query names no city.
top_anchor: Option<(f64, f64)>,
/// Address count of every commune within `HOMONYM_AREA_RADIUS_KM` of each commune, by
/// commune id — the "size of the place" a cityless homonym is weighed by on a sheet with
/// city_tail `homonym_prominence` (a city cut into neighbourhood communes, New York, is
/// one place). Empty on every other sheet.
area_prominence: Vec<u32>,
/// WOF administrative-region polygons for reverse PIP — from the sibling _admin.bin.
admin: Vec<AdminRegion>,
/// SEC_META (v6): provenance + identity pairs; empty on sheets built without --meta.
meta: Vec<(String, String)>,
}
impl Index {
/// Open a sheet meant to be the PRIMARY address index, refusing a POI layer.
/// A POI-only sheet loaded as the main index would answer address queries with places; POI
/// sheets must be loaded via the cascade (`--poi` / `poi=` / `gridpin_load_poi`), never as
/// the primary. Address sheets and pre-v6 sheets (no `layer` meta) are accepted.
pub fn open_address(path: &Path) -> Result<Index> {
let idx = Index::open(path)?;
// Uniform layer policy: accept ONLY an `addresses` layer or a layer-less lab/pre-v6
// sheet. The old check rejected exactly `poi` but let an UNKNOWN/malformed layer (e.g.
// `bad_layer`) open as the main index. Symmetric to open_poi's whitelist.
if matches!(idx.layer(), Some(l) if l != "addresses") {
anyhow::bail!(
"{path:?} has layer {:?}, not an address sheet — load an `addresses` layer as the \
main index (a POI layer goes via --poi / gridpin_load_poi)",
idx.layer().unwrap_or("")
);
}
Ok(idx)
}
/// Open a sheet as a POI layer, refusing the wrong layer: the symmetric guard to
/// `open_address`. Loading an ADDRESS sheet as a POI layer used to be accepted (the POI loader
/// used the permissive `open`), so an address index could be attached where a POI was meant. A
/// layer-less lab build is still allowed, matching `open_address`'s leniency.
pub fn open_poi(path: &Path) -> Result<Index> {
let idx = Index::open(path)?;
if matches!(idx.layer(), Some(l) if l != "poi") {
anyhow::bail!(
"{path:?} is a '{}' sheet, not a POI layer — load the address sheet via the main \
index, not as a POI layer",
idx.layer().unwrap_or("")
);
}
Ok(idx)
}
pub fn open(path: &Path) -> Result<Index> {
let file = File::open(path).with_context(|| format!("cannot open {path:?}"))?;
// The mapping is OWNED by the returned Index and freed on Drop — no more
// permanent leak per open. SAFETY: `mmap` moves into the Index and lives as long as it; the
// mapped bytes sit at a fixed OS address that does not move with the Arc/Index, so the
// `&'static` derived below is valid for the Index's life and never exposed past it. On any
// early return, the local/moved `mmap` drops -> munmap, so a FAILED open frees too.
let mmap = Arc::new(Mapping::new(unsafe { Mmap::map(&file)? }));
let data: &'static [u8] = unsafe { std::mem::transmute::<&[u8], &'static [u8]>(&mmap[..]) };
// No panic must escape the read API: a semantic-corrupt sheet that passes
// bounds + TOC checks can still panic inside the fst crate during construction. The CLI
// has no other panic boundary, so catch it here and return a clean error instead.
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
Self::open_mapped(mmap, data, path)
}))
.map_err(|_| anyhow::anyhow!("{path:?}: corrupt index (panic while reading sections)"))?
}
fn open_mapped(mmap: Arc<Mapping>, data: &'static [u8], path: &Path) -> Result<Index> {
let secs = parse_sections(data)?;
let format_version = data[4];
let sl = |i: usize| -> &'static [u8] {
let (off, len) = secs[i];
&data[off as usize..(off + len) as usize]
};
// reps and cells are read from raw section bytes; a truncated or empty section must
// degrade gracefully (empty dict / no cells), never index out of bounds.
let reps_raw = sl(SEC_REPS);
let mut rep_lookup = HashMap::new();
let mut rep_suffixes = vec![String::new()]; // rep id 0 = no suffix
if reps_raw.len() >= 4 {
let cnt = read_u32(reps_raw, 0) as usize;
let mut p = 4usize;
for id in 1..=cnt {
if p >= reps_raw.len() {
break;
}
let l = reps_raw[p] as usize;
p += 1;
if p + l > reps_raw.len() {
break;
}
let s = std::str::from_utf8(&reps_raw[p..p + l])
.unwrap_or("")
.to_string();
p += l;
rep_lookup.insert(s.clone(), id as u32);
rep_suffixes.push(s);
}
}
let cells_raw = sl(SEC_CELLS);
let (cells_dir, cells_post): (&[u8], &[u8]) = if cells_raw.len() >= 4 {
let n_dir = read_u32(cells_raw, 0) as usize;
let body = &cells_raw[4..];
if n_dir.saturating_mul(12) <= body.len() {
body.split_at(n_dir * 12)
} else {
(&[], &[]) // corrupt cells directory — treat as no reverse-geo cells
}
} else {
(&[], &[])
};
// Strict open: an ABSENT optional section is fine (None), but a section that is
// PRESENT (non-empty) yet unparseable means the sheet is corrupt/tampered — fail the open
// instead of silently dropping the trained parser/ranking to None (a sheet that quietly
// lost a capability with no error). The build already validates these, so this only fires
// on a damaged/tampered file.
let parser_raw = sl(SEC_PARSER);
let parser = if parser_raw.is_empty() {
None
} else {
Some(
crate::ml::Parser::from_section(parser_raw).with_context(|| {
format!(
"{path:?}: SEC_PARSER is present but malformed — corrupt/tampered sheet"
)
})?,
)
};
let rank_raw = sl(SEC_RANK);
let rank = if rank_raw.is_empty() {
None
} else {
Some(Rank::from_section(rank_raw).with_context(|| {
format!("{path:?}: SEC_RANK is present but malformed — corrupt/tampered sheet")
})?)
};
// RULES-IN-DATA: this file's own tables, needed before their first use below (the capital
// anchor already reads rules().capitals). OWNED so it frees on Drop.
// SAFETY: same invariant as `mmap` — the box moves into the Index and outlives every use.
let rules_owned: Option<Box<crate::rules::Rules>> =
crate::rules::from_section_owned(sl(SEC_RULES));
let rules: &'static crate::rules::Rules = match &rules_owned {
Some(b) => unsafe {
std::mem::transmute::<&crate::rules::Rules, &'static crate::rules::Rules>(&**b)
},
None => crate::rules::defaults_static(),
};
let _rules_scope = crate::rules::scope(rules);
// CAPITAL ANCHOR. Capitals are fragmented in the data (e.g. Paris = 20
// arrondissements), so the single most-address-rich commune may be the wrong
// anchor. Two steps: (1) fallback = the single most prominent commune; (2) on top,
// a curated capital list (same approach as commune_alias): the FST key group
// "name" and "name ..." summed by prominence; the capital wins unless it is
// tiny (<1/20 of the fallback).
let cmeta = sl(SEC_COMMUNES_META);
let ccoord = sl(SEC_COMMUNE_COORDS);
let ncom = cmeta.len() / COMMUNE_META_SIZE;
let area_prominence = if rules
.city_tail
.get("homonym_prominence")
.is_some_and(|v| v == "1")
{
Self::area_prominence_table(cmeta, ccoord, ncom)
} else {
Vec::new()
};
let (mut top_id, mut top_prom) = (0usize, 0u32);
for id in 0..ncom {
let prom = read_u32(cmeta, id * COMMUNE_META_SIZE + 12);
if prom > top_prom {
top_prom = prom;
top_id = id;
}
}
let mut top_anchor = if top_prom > 0 && (top_id * 8 + 8) <= ccoord.len() {
let o = top_id * 8;
let (la, lo) = (
read_i32(ccoord, o) as f64 / 1e7,
read_i32(ccoord, o + 4) as f64 / 1e7,
);
if la != 0.0 || lo != 0.0 {
Some((la, lo))
} else {
None
}
} else {
None
};
{
let communes_fst_ref = Map::new(sl(SEC_COMMUNES_FST))?;
let postings_ref = sl(SEC_COMMUNE_POSTINGS);
let (mut best_sum, mut best_c) = (0u64, (0f64, 0f64));
for cap in crate::rules::rules().capitals.iter().map(|s| s.as_str()) {
let lo_key = cap.as_bytes().to_vec();
let mut hi_key = cap.as_bytes().to_vec();
hi_key.push(0xFF);
let mut stream = communes_fst_ref
.range()
.ge(&lo_key)
.lt(&hi_key)
.into_stream();
let (mut sum, mut wla, mut wlo) = (0u64, 0f64, 0f64);
while let Some((key, v)) = stream.next() {
// only the exact name or "name + space" ("paris 1er..."), not "parisot"
if key.len() > cap.len() && key[cap.len()] != b' ' {
continue;
}
let start = (v >> 16) as usize;
let count = (v & 0xFFFF) as usize;
// start/count come from an FST value: on a corrupt-but-parseable file
// they can point past the postings section — reading would panic at
// open time and take the host process with it
if (start + count) * 4 > postings_ref.len() {
continue;
}
for i in 0..count {
let cid = read_u32(postings_ref, (start + i) * 4) as usize;
if cid * COMMUNE_META_SIZE + 16 > cmeta.len() || cid * 8 + 8 > ccoord.len()
{
continue;
}
let prom = read_u32(cmeta, cid * COMMUNE_META_SIZE + 12) as u64;
let la = read_i32(ccoord, cid * 8) as f64 / 1e7;
let lo = read_i32(ccoord, cid * 8 + 4) as f64 / 1e7;
if la == 0.0 && lo == 0.0 {
continue;
}
sum += prom;
wla += la * prom as f64;
wlo += lo * prom as f64;
}
}
if sum > best_sum {
best_sum = sum;
best_c = (wla / sum as f64, wlo / sum as f64);
}
}
if best_sum > 0 && best_sum >= (top_prom as u64) / 20 {
top_anchor = Some(best_c);
}
}
// Content-shape invariants: a section whose TOC entry is intact but
// whose CONTENT is zeroed (a sparse hole from an interrupted copy) or points into the wrong
// section (swapped ids) used to open fine and answer a silent 0,0. Check record sizes divide
// and EVERY street record satisfies the builder's own invariants — offsets land inside their
// sections, commune id is in range, a street has >=1 house (the builder emits none with 0).
// ALL records, not a sample;
// this is bounded arithmetic per record, no allocation. Full BYTE integrity (tampering) is
// still the release sha256 manifest's job — this catches structural corruption. NOTE: an
// EMPTY display name is LEGAL (name() degrades to ""), so name_off may point at a 0-length
// entry — only its BOUNDS are checked, never non-emptiness (that false invariant bricked a
// legal sheet,).
{
let sm = sl(SEC_STREETS_META);
let cm = sl(SEC_COMMUNES_META);
let cc = sl(SEC_COMMUNE_COORDS);
let names_b = sl(SEC_NAMES);
let houses_b = sl(SEC_HOUSE_BLOCKS);
if sm.len() % crate::index::STREET_META_SIZE != 0 {
anyhow::bail!(
"{path:?}: streets_meta length is not a whole number of records — corrupt"
);
}
if cm.len() % crate::index::COMMUNE_META_SIZE != 0 {
anyhow::bail!(
"{path:?}: communes_meta length is not a whole number of records — corrupt"
);
}
let ncommunes = cm.len() / crate::index::COMMUNE_META_SIZE;
if cc.len() != ncommunes * 8 {
anyhow::bail!(
"{path:?}: commune_coords does not match the commune count — corrupt"
);
}
let nstreets = sm.len() / crate::index::STREET_META_SIZE;
for i in 0..nstreets {
let o = i * crate::index::STREET_META_SIZE;
let commune_id = read_u32(sm, o + 8) as usize;
let name_off = read_u32(sm, o + 16) as usize;
let house_off = read_u64(sm, o + 20) as usize;
let house_count = read_u32(sm, o + 28);
let postcode_disp_off = read_u32(sm, o + 32);
let house_end = if i + 1 < nstreets {
usize::try_from(read_u64(sm, (i + 1) * crate::index::STREET_META_SIZE + 20))
.ok()
} else {
Some(houses_b.len())
};
let bad = commune_id >= ncommunes
|| house_count == 0
|| house_off >= houses_b.len()
|| house_end.is_none_or(|end| house_off >= end || end > houses_b.len())
|| name_off >= names_b.len()
|| name_off + 1 + names_b[name_off] as usize > names_b.len();
if bad {
anyhow::bail!(
"{path:?}: street record {i} violates structural invariants — corrupt (zeroed or misdirected section content)"
);
}
// v7 sparse house-postcode prefix. Validate the bounded dictionary header for
// every encoded street at open, without scanning every house record (which would
// make opening a country sheet proportional to tens of millions of addresses).
if format_version >= 7 && postcode_disp_off == PC_DISP_AMBIGUOUS {
let house_end = house_end.expect("validated above");
let bounded_houses = &houses_b[..house_end];
let mut p = house_off;
let Some(count) = strict_varint(bounded_houses, &mut p) else {
anyhow::bail!(
"{path:?}: street record {i} has a malformed house-postcode dictionary count — corrupt"
);
};
if count == 0 || count > u64::from(house_count) {
anyhow::bail!(
"{path:?}: street record {i} has an invalid house-postcode dictionary size — corrupt"
);
}
let Some(table_len) = usize::try_from(count)
.ok()
.and_then(|value| value.checked_mul(4))
else {
anyhow::bail!(
"{path:?}: street record {i} house-postcode dictionary overflows — corrupt"
);
};
let Some(table_end) = p.checked_add(table_len) else {
anyhow::bail!(
"{path:?}: street record {i} house-postcode dictionary overflows — corrupt"
);
};
if table_end > house_end {
anyhow::bail!(
"{path:?}: street record {i} house-postcode dictionary is truncated — corrupt"
);
}
let mut previous_postcode: Option<&str> = None;
for entry in (p..table_end).step_by(4) {
let postcode_off = read_u32(houses_b, entry) as usize;
if postcode_off >= names_b.len()
|| postcode_off + 1 + names_b[postcode_off] as usize > names_b.len()
{
anyhow::bail!(
"{path:?}: street record {i} house-postcode dictionary points outside names — corrupt"
);
}
let postcode_len = names_b[postcode_off] as usize;
let postcode_bytes =
&names_b[postcode_off + 1..postcode_off + 1 + postcode_len];
let Ok(postcode) = std::str::from_utf8(postcode_bytes) else {
anyhow::bail!(
"{path:?}: street record {i} house-postcode dictionary is not UTF-8 — corrupt"
);
};
// the sheet's own code shape passes too ("V9Z 1K2"; builder plausible_display_pc)
if !(plausible_house_postcode(postcode)
|| pattern_postal(&rules.city_tail, postcode))
|| previous_postcode.is_some_and(|previous| previous >= postcode)
{
anyhow::bail!(
"{path:?}: street record {i} house-postcode dictionary is empty, implausible, duplicated, or unsorted — corrupt"
);
}
previous_postcode = Some(postcode);
}
}
}
}
// Hoist the fallible Map::new calls so a failure drops the `mmap`/`rules_owned` LOCALS
// (munmap + free) before any move into the struct — failed opens never leak.
let communes_fst = Map::new(sl(SEC_COMMUNES_FST))?;
let streets_fst = Map::new(sl(SEC_STREETS_FST))?;
let words_fst = Map::new(sl(SEC_WORDS))?;
// word_postings (13) may be legally EMPTY only when the words FST has NO keys (a sheet whose
// every street word is < 3 chars). A non-empty words FST with empty postings means the
// postings section was truncated/deleted — fuzzy search would silently return nothing
//. Reject rather than degrade silently.
if !words_fst.is_empty() && sl(SEC_WORD_POSTINGS).is_empty() {
anyhow::bail!(
"{path:?}: word_postings is empty but the words FST has {} keys — corrupt (fuzzy search would silently fail)",
words_fst.len()
);
}
// CONTENT check of section 13: a PRESENT but zeroed/corrupted payload
// used to pass open (only presence was verified) and silently kill fuzzy search. Decode
// EVERY word's postings list against the builder's invariants: a word is in the FST only
// BECAUSE it has ids (count >= 1, <= the builder cap), ids are strictly increasing
// (sorted + deduped deltas) and each stays under nstreets. A zeroed payload fails at the
// first word (count = 0); a partially-corrupted one breaks bounds/monotonicity.
{
let wp = sl(SEC_WORD_POSTINGS);
let sm = sl(SEC_STREETS_META);
let nstreets = (sm.len() / crate::index::STREET_META_SIZE) as u64;
// STRICT varint validator for section 13: unlike the lenient
// read_varint, `strict_varint` (index.rs) returns None on EOF-mid-varint, >10 bytes, OR
// payload overflow past bit 63 — so a corrupt word_postings section is refused at open.
let mut stream = words_fst.stream();
while let Some((word, off)) = stream.next() {
let mut p = off as usize;
let fail = |why: &str| -> anyhow::Error {
anyhow::anyhow!(
"{path:?}: word_postings entry for {:?} {why} — corrupt (fuzzy search would silently fail)",
String::from_utf8_lossy(word)
)
};
if p >= wp.len() {
return Err(fail("points past the section"));
}
let n = match strict_varint(wp, &mut p) {
Some(n) => n,
None => return Err(fail("has a malformed/unterminated street count varint")),
};
if n == 0 || n > 16384 {
return Err(fail("has a zero/oversized street count"));
}
let mut prev: u64 = 0;
for i in 0..n {
let delta = match strict_varint(wp, &mut p) {
Some(d) => d,
None => return Err(fail("is truncated mid-list (unterminated varint)")),
};
if i > 0 && delta == 0 {
return Err(fail("repeats a street id (deltas must be positive)"));
}
prev = match prev.checked_add(delta) {
Some(v) => v,
None => return Err(fail("overflows the street id accumulator")),
};
if prev >= nstreets {
return Err(fail("references a street id past the street table"));
}
}
}
}
let mut index = Index {
_mmap: mmap,
_rules_owned: rules_owned,
es_particle_rules_may_supply_number: std::sync::OnceLock::new(),
field_display_streets: std::sync::OnceLock::new(),
postcode_roster: std::sync::OnceLock::new(),
field_title_streets: std::sync::OnceLock::new(),
format_version,
communes_fst,
streets_fst,
communes_meta: sl(SEC_COMMUNES_META),
postings: sl(SEC_COMMUNE_POSTINGS),
streets_meta: sl(SEC_STREETS_META),
houses: sl(SEC_HOUSE_BLOCKS),
names: sl(SEC_NAMES),
cells_dir,
cells_post,
words_fst,
word_postings: sl(SEC_WORD_POSTINGS),
de_postcode_streets: Vec::new().into_boxed_slice(),
de_blank_postcode_display_streets: DeBlankPostcodeDisplayProjection::default(),
commune_coords: sl(SEC_COMMUNE_COORDS),
rep_lookup,
range_marker_rep: rep_suffixes
.iter()
.position(|s| s == RANGE_MARKER)
.map(|i| i as u32),
rep_suffixes,
parser,
rank,
rules,
top_anchor,
area_prominence,
admin: load_admin(path),
meta: decode_meta(sl(SEC_META)).unwrap_or_default(),
};
if index.country() == Some("de") {
index.de_postcode_streets = index.build_de_postcode_streets()?;
index.de_blank_postcode_display_streets =
index.build_de_blank_postcode_display_streets()?;
}
Ok(index)
}
/// Provenance/identity pairs from SEC_META (empty on pre-v6-style sheets).
pub fn meta(&self) -> &[(String, String)] {
&self.meta
}
/// Whether this sheet carries a usable trained parser / ranking: the build now
/// validates these sections, so a `true` here means the capability survived into the file.
pub fn has_parser(&self) -> bool {
self.parser.is_some()
}
pub fn has_rank(&self) -> bool {
self.rank.is_some()
}
fn meta_get(&self, key: &str) -> Option<&str> {
self.meta
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
}
/// ISO country code carried by the sheet (v6 identity).
pub fn country(&self) -> Option<&str> {
self.meta_get("country")
}
/// Layer kind carried by the sheet: "addresses" or "poi" (v6 identity).
pub fn layer(&self) -> Option<&str> {
self.meta_get("layer")
}
/// Administrative region of a point (lat,lon) via WOF polygons — bbox filter + ray-cast PIP.
fn admin_at(&self, lat: f64, lon: f64) -> Option<String> {
let (la, lo) = ((lat * 1e7) as i32, (lon * 1e7) as i32);
for r in &self.admin {
if la < r.min_lat || la > r.max_lat || lo < r.min_lon || lo > r.max_lon {
continue;
}
if point_in_rings(la, lo, &r.rings) {
return Some(r.name.clone());
}
}
None
}
fn name(&self, off: u32) -> &str {
// Bounds-safe: a corrupt sheet may carry a name_off past the names blob. Direct
// indexing panicked with "index out of bounds" and aborted the host;
// an out-of-range offset now degrades to an empty name.
let off = off as usize;
let Some(&l) = self.names.get(off) else {
return "";
};
self.names
.get(off + 1..off + 1 + l as usize)
.and_then(|b| std::str::from_utf8(b).ok())
.unwrap_or("")
}
fn street_meta(&self, id: u32) -> StreetMeta {
let b = self.streets_meta;
let o = id as usize * STREET_META_SIZE;
// street ids come from FST/postings values (file data): out-of-section ids on
// a corrupt sheet must degrade to an empty record, not panic the host
if o + STREET_META_SIZE > b.len() {
return StreetMeta {
lat_c: 0,
lon_c: 0,
commune_id: 0,
postcode: 0,
name_off: 0,
house_off: 0,
house_count: 0,
postcode_disp_off: 0,
};
}
StreetMeta {
lat_c: read_i32(b, o),
lon_c: read_i32(b, o + 4),
commune_id: read_u32(b, o + 8),
postcode: read_u32(b, o + 12),
name_off: read_u32(b, o + 16),
house_off: read_u64(b, o + 20),
house_count: read_u32(b, o + 28),
postcode_disp_off: read_u32(b, o + 32),
}
}
/// Build the global exact-postcode roster once while opening a DE sheet.
/// Unambiguous streets contribute their exact five-digit display postcode;
/// v7 mixed-postcode streets contribute every five-digit entry from their
/// validated local dictionary. Non-DE postcode grammars are deliberately
/// absent from this product-specific projection.
fn build_de_postcode_streets(&self) -> Result<Box<[(u32, u32)]>> {
let street_count = self.streets_meta.len() / STREET_META_SIZE;
let mut postings = Vec::with_capacity(street_count);
for raw_sid in 0..street_count {
let sid = u32::try_from(raw_sid)
.map_err(|_| anyhow::anyhow!("DE postcode roster exceeds u32 street ids"))?;
let metadata = self.street_meta(sid);
if metadata.postcode_disp_off == PC_DISP_AMBIGUOUS {
let Some((_, dictionary_byte, dictionary_count, _)) =
self.house_block_layout(sid, &metadata)
else {
anyhow::bail!("DE street {sid} has an unreadable mixed-postcode dictionary");
};
for id in 1..=dictionary_count {
let offset = self.house_postcode_offset(dictionary_byte, dictionary_count, id);
let postcode = self.name(offset);
if is_five_digit_postcode(postcode) {
postings.push((postcode.parse()?, sid));
}
}
continue;
}
if metadata.postcode_disp_off != 0 {
let postcode = self.name(metadata.postcode_disp_off);
if is_five_digit_postcode(postcode) {
postings.push((postcode.parse()?, sid));
}
} else if (1..=99_999).contains(&metadata.postcode) {
// Pre-display-postcode sheets preserve only the numeric value;
// DE's fixed width makes its five-digit rendering unambiguous.
postings.push((metadata.postcode, sid));
}
}
postings.sort_unstable();
postings.dedup();
Ok(postings.into_boxed_slice())
}
/// Build a collision-free display-street/locality projection only for
/// identities that have both exact typed-postcode roster support and a
/// wholly postcode-less source street. The final pass adds every postcode
/// state for those identities, including distinct commune ids with the
/// same product-visible locality, so P5 sees conflicting exact houses
/// instead of inspecting a blank row in isolation. Buckets retain one
/// overflow sentinel beyond the request ceiling; a caller then fails
/// closed without scanning a partial set.
fn build_de_blank_postcode_display_streets(&self) -> Result<DeBlankPostcodeDisplayProjection> {
if self.format_version < 7 {
return Ok(DeBlankPostcodeDisplayProjection::default());
}
let street_count = self.streets_meta.len() / STREET_META_SIZE;
let anchored_identities: HashSet<(String, String)> = self
.de_postcode_streets
.iter()
.filter_map(|&(_, sid)| {
let metadata = self.street_meta(sid);
let display = de_product_normalize_street(self.name(metadata.name_off));
let locality = de_product_normalize_text(self.commune_name(metadata.commune_id));
(!display.is_empty() && !locality.is_empty()).then_some((display, locality))
})
.collect();
let mut buckets: HashMap<(String, String), Vec<u32>> = HashMap::new();
for raw_sid in 0..street_count {
let sid = u32::try_from(raw_sid)
.map_err(|_| anyhow::anyhow!("DE blank-postcode roster exceeds u32 street ids"))?;
let metadata = self.street_meta(sid);
if metadata.postcode == 0 && metadata.postcode_disp_off == 0 {
let display = de_product_normalize_street(self.name(metadata.name_off));
let locality = de_product_normalize_text(self.commune_name(metadata.commune_id));
let identity = (display, locality);
if anchored_identities.contains(&identity) {
buckets.entry(identity).or_default();
}
}
}
drop(anchored_identities);
if buckets.is_empty() {
return Ok(DeBlankPostcodeDisplayProjection::default());
}
for raw_sid in 0..street_count {
let sid = u32::try_from(raw_sid)
.map_err(|_| anyhow::anyhow!("DE blank-postcode roster exceeds u32 street ids"))?;
let metadata = self.street_meta(sid);
let display = de_product_normalize_street(self.name(metadata.name_off));
let locality = de_product_normalize_text(self.commune_name(metadata.commune_id));
let Some(bucket) = buckets.get_mut(&(display, locality)) else {
continue;
};
if bucket.len() <= DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT {
bucket.push(sid);
}
}
let total = buckets.values().try_fold(0usize, |total, bucket| {
total
.checked_add(bucket.len())
.ok_or_else(|| anyhow::anyhow!("DE blank-postcode projection size overflow"))
})?;
let mut ranges = HashMap::with_capacity(buckets.len());
let mut sids = Vec::with_capacity(total);
for (identity, bucket) in buckets {
let start = sids.len();
let count = bucket.len();
sids.extend(bucket);
ranges.insert(identity, (start, count));
}
Ok(DeBlankPostcodeDisplayProjection {
ranges,
sids: sids.into_boxed_slice(),
})
}
/// Exact-postcode street bucket for the P3 uniqueness proof. A malformed
/// or pathologically broad bucket fails closed at the same audited ceiling
/// as the existing one-shot DE rescue scan.
fn de_postcode_street_bucket(&self, postcode: u32) -> Option<&[(u32, u32)]> {
let start = self
.de_postcode_streets
.partition_point(|&(candidate, _)| candidate < postcode);
let end = self
.de_postcode_streets
.partition_point(|&(candidate, _)| candidate <= postcode);
let bucket = &self.de_postcode_streets[start..end];
(!bucket.is_empty() && bucket.len() <= de_postcode_house_rescue_scan_limit())
.then_some(bucket)
}
/// Postcode for OUTPUT: the full string (NL "1012XJ", FR "75002") from the names table,
/// else the zero-padded numeric form, else empty (sources without postcodes).
fn postcode_out(&self, m: &StreetMeta) -> String {
// a street spanning >1 postcode has no house-accurate street value — emit empty, not a
// neighbour's postcode. name() is bounds-safe, so the sentinel never indexes.
if m.postcode_disp_off == PC_DISP_AMBIGUOUS {
return String::new();
}
if m.postcode_disp_off != 0 {
let d = self.name(m.postcode_disp_off);
if !d.is_empty() {
return d.to_string();
}
}
if m.postcode == 0 {
String::new()
} else {
format!("{:05}", m.postcode)
}
}
/// Decode the optional sparse house-postcode prefix of a v7 ambiguous street block.
/// Returns `(first_house_byte, dictionary_byte, dictionary_count)`. Dictionary entries are
/// fixed-width little-endian offsets into `SEC_NAMES`; each house then carries a local varint
/// id (0 = source row had no postcode, 1..=count = dictionary entry).
///
/// The routine is deliberately bounds-safe: house blocks are external file data, and a
/// truncated dictionary must degrade to no candidate rather than panic the host process.
fn house_block_layout(
&self,
street_id: u32,
m: &StreetMeta,
) -> Option<(usize, usize, u32, usize)> {
let mut pos = usize::try_from(m.house_off).ok()?;
let nstreets = self.streets_meta.len() / STREET_META_SIZE;
let street_index = usize::try_from(street_id).ok()?;
if street_index >= nstreets {
return None;
}
let house_end = if street_index + 1 < nstreets {
usize::try_from(read_u64(
self.streets_meta,
(street_index + 1) * STREET_META_SIZE + 20,
))
.ok()?
} else {
self.houses.len()
};
if pos >= house_end || house_end > self.houses.len() {
return None;
}
if self.format_version < 7 || m.postcode_disp_off != PC_DISP_AMBIGUOUS {
return Some((pos, 0, 0, house_end));
}
let count = u32::try_from(strict_varint(&self.houses[..house_end], &mut pos)?).ok()?;
// An encoded street always has at least one known postcode; it cannot have more
// distinct known values than address rows.
if count == 0 || count > m.house_count {
return None;
}
let dictionary_byte = pos;
let dictionary_len = usize::try_from(count).ok()?.checked_mul(4)?;
pos = pos.checked_add(dictionary_len)?;
if pos > house_end {
return None;
}
Some((pos, dictionary_byte, count, house_end))
}
fn house_postcode_offset(&self, dictionary_byte: usize, count: u32, id: u32) -> u32 {
if id == 0 || id > count {
return 0;
}
let Some(entry) = usize::try_from(id - 1)
.ok()
.and_then(|index| index.checked_mul(4))
.and_then(|delta| dictionary_byte.checked_add(delta))
else {
return 0;
};
if entry + 4 > self.houses.len() {
return 0;
}
read_u32(self.houses, entry)
}
/// Output postcode for the concrete represented address. Unambiguous streets retain their
/// compact street-level value. On a sparse house-accurate street, only the selected house's
/// own dictionary value is allowed; a missing/corrupt value stays empty and never falls back
/// to a neighbour or to the street majority.
fn postcode_for_house(&self, m: &StreetMeta, house_postcode_off: u32) -> String {
if m.postcode_disp_off != PC_DISP_AMBIGUOUS {
return self.postcode_out(m);
}
if house_postcode_off == 0 {
return String::new();
}
self.name(house_postcode_off).to_string()
}
/// Numeric query postcodes intentionally use the leading digit run: this mirrors the
/// query parser's established representation for values such as Dutch `1012AA` (1012),
/// while preserving the full display string for output.
fn postcode_numeric_prefix(postcode: &str) -> Option<u32> {
let digits: String = postcode
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
if digits.is_empty() {
None
} else {
digits.parse().ok().filter(|&postcode| postcode != 0)
}
}
/// Duplicate selection is deliberately narrower than feature reconciliation. Dresden's
/// duplicate discriminator is a fully numeric postcode; an alphanumeric suffix cannot be
/// reconstructed from the current numeric query feature and therefore must not reorder rows.
fn exact_house_postcode_matches(
&self,
m: &StreetMeta,
house_postcode_off: u32,
requested_postcode: u32,
) -> bool {
if m.postcode_disp_off != PC_DISP_AMBIGUOUS {
return m.postcode != 0 && m.postcode == requested_postcode;
}
house_postcode_off != 0
&& self.name(house_postcode_off).parse::<u32>().ok() == Some(requested_postcode)
}
fn exact_house_postcode_candidate(
&self,
sid: u32,
m: &StreetMeta,
requested_number: u32,
requested_rep: u32,
requested_postcode: u32,
) -> bool {
#[cfg(test)]
DE_POSTCODE_HOUSE_RESCUE_HOUSE_DECODES.with(|calls| {
calls.set(calls.get().saturating_add(1));
});
let Some((_, _, kind, _, _, postcode_off)) = self.find_house(
sid,
m,
requested_number,
requested_rep,
Some(requested_postcode),
) else {
return false;
};
kind == 2
&& Self::postcode_numeric_prefix(&self.postcode_for_house(m, postcode_off))
== Some(requested_postcode)
}
/// Cheaply reject a homonymous street whose compact house-postcode dictionary cannot
/// contain the requested postcode. The rescue still scans every bounded FST posting to
/// prove uniqueness, but it decodes a street's variable-length house rows only when this
/// metadata proof says an exact address is possible.
fn street_may_contain_postcode(
&self,
sid: u32,
m: &StreetMeta,
requested_postcode: u32,
) -> bool {
if m.postcode_disp_off != PC_DISP_AMBIGUOUS {
return m.postcode != 0 && m.postcode == requested_postcode;
}
let Some((_, dictionary_byte, dictionary_count, _)) = self.house_block_layout(sid, m)
else {
return false;
};
(1..=dictionary_count).any(|id| {
let postcode_off = self.house_postcode_offset(dictionary_byte, dictionary_count, id);
postcode_off != 0
&& self.name(postcode_off).parse::<u32>().ok() == Some(requested_postcode)
})
}
fn exact_house_postcode_candidate_cached(
&self,
cache: &mut HashMap<(u32, u32, u32, u32), bool>,
sid: u32,
m: &StreetMeta,
requested_number: u32,
requested_rep: u32,
requested_postcode: u32,
) -> bool {
let key = (sid, requested_number, requested_rep, requested_postcode);
if let Some(&cached) = cache.get(&key) {
return cached;
}
let exact = self.street_may_contain_postcode(sid, m, requested_postcode)
&& self.exact_house_postcode_candidate(
sid,
m,
requested_number,
requested_rep,
requested_postcode,
);
cache.insert(key, exact);
exact
}
/// Prove the complete literal house set on one street id. Every endpoint
/// uses the same suffix id and numeric postcode; `find_house` must return an
/// exact represented row (`kind == 2`) for each one. The cache remains
/// endpoint-specific so repeated DE variants do not re-decode house blocks.
// Frozen release: grouping house-set inputs would rewrite the validated resolver call sites.
#[allow(clippy::too_many_arguments)]
fn exact_house_postcode_set_candidate_cached(
&self,
cache: &mut HashMap<(u32, u32, u32, u32), bool>,
sid: u32,
m: &StreetMeta,
requested_number: u32,
requested_rep: u32,
additional_numbers: &[u32],
requested_postcode: u32,
) -> bool {
self.exact_house_postcode_candidate_cached(
cache,
sid,
m,
requested_number,
requested_rep,
requested_postcode,
) && additional_numbers.iter().all(|&number| {
self.exact_house_postcode_candidate_cached(
cache,
sid,
m,
number,
requested_rep,
requested_postcode,
)
})
}
/// The typed DE product predicates carry the full five-character postcode
/// field for every literal endpoint. The shared numeric resolver
/// deliberately accepts leading-digit prefixes for other countries, so
/// this proof reasserts the rendered postcode on every represented house.
// Frozen release: preserve the separate numeric/full-postcode inputs and existing call sites.
#[allow(clippy::too_many_arguments)]
fn exact_house_full_postcode_set_candidate_cached(
&self,
cache: &mut HashMap<(u32, u32, u32, u32), bool>,
sid: u32,
m: &StreetMeta,
requested_number: u32,
requested_rep: u32,
additional_numbers: &[u32],
requested_postcode: u32,
requested_postcode_raw: &str,
) -> bool {
if !self.exact_house_postcode_set_candidate_cached(
cache,
sid,
m,
requested_number,
requested_rep,
additional_numbers,
requested_postcode,
) {
return false;
}
std::iter::once(requested_number)
.chain(additional_numbers.iter().copied())
.all(|number| {
let Some((_, _, kind, got, got_rep, postcode_off)) =
self.find_house(sid, m, number, requested_rep, Some(requested_postcode))
else {
return false;
};
kind == 2
&& got == number
&& got_rep == requested_rep
&& self.postcode_for_house(m, postcode_off) == requested_postcode_raw
})
}
/// Count every physical represented row for one exact number+suffix.
/// `find_house` returns at the first match, which is correct for ordinary
/// ranking but cannot prove P5 uniqueness when duplicate source rows share
/// one street id. This decoder deliberately ignores coordinates after
/// consuming their varints: they neither select nor deduplicate a row.
fn de_exact_house_record_postcodes(
&self,
sid: u32,
metadata: &StreetMeta,
requested_number: u32,
requested_rep: u32,
row_budget: &mut usize,
) -> std::result::Result<Vec<String>, ()> {
if metadata.house_count == 0 {
return Ok(Vec::new());
}
let (mut position, postcode_dictionary, postcode_count, house_end) =
self.house_block_layout(sid, metadata).ok_or(())?;
let bounded_houses = &self.houses[..house_end];
let mut current_number = 0u32;
let mut matches = Vec::new();
for index in 0..metadata.house_count {
if *row_budget == 0 {
return Err(());
}
*row_budget -= 1;
#[cfg(test)]
DE_BLANK_POSTCODE_HOUSE_SCAN_ROWS.with(|rows| {
rows.set(rows.get().saturating_add(1));
});
let delta = strict_varint(bounded_houses, &mut position)
.and_then(|value| u32::try_from(value).ok())
.ok_or(())?;
current_number = if index == 0 {
delta
} else {
current_number.checked_add(delta).ok_or(())?
};
let rep = strict_varint(bounded_houses, &mut position)
.and_then(|value| u32::try_from(value).ok())
.ok_or(())?;
strict_varint(bounded_houses, &mut position).ok_or(())?;
strict_varint(bounded_houses, &mut position).ok_or(())?;
let postcode_off =
if self.format_version >= 7 && metadata.postcode_disp_off == PC_DISP_AMBIGUOUS {
let id = strict_varint(bounded_houses, &mut position)
.and_then(|value| u32::try_from(value).ok())
.ok_or(())?;
self.house_postcode_offset(postcode_dictionary, postcode_count, id)
} else {
0
};
if current_number == requested_number && rep == requested_rep {
matches.push(self.postcode_for_house(metadata, postcode_off));
}
if current_number > requested_number {
break;
}
}
Ok(matches)
}
fn commune_insee(&self, id: u32) -> &str {
let o = id as usize * COMMUNE_META_SIZE;
let raw = &self.communes_meta[o..o + 8];
let end = raw.iter().position(|&c| c == 0).unwrap_or(8);
std::str::from_utf8(&raw[..end]).unwrap_or("")
}
fn commune_name(&self, id: u32) -> &str {
let o = id as usize * COMMUNE_META_SIZE;
self.name(read_u32(self.communes_meta, o + 8))
}
/// Commune prominence = its address count (a population proxy): ranking tie-break when
/// score and name similarity are equal — a capital beats a village, a city center beats
/// a suburb. Indexes without the field store 0, which disables the tie-break.
fn commune_prominence(&self, id: u32) -> u32 {
read_u32(self.communes_meta, id as usize * COMMUNE_META_SIZE + 12)
}
/// The weight a homonym tie-break reads for a commune: the address count of its place
/// (`area_prominence`) on a sheet with city_tail `homonym_prominence`, else its own count.
fn homonym_weight(&self, id: u32) -> u32 {
self.area_prominence
.get(id as usize)
.copied()
.unwrap_or_else(|| self.commune_prominence(id))
}
/// Sum of the address counts of the communes within `HOMONYM_AREA_RADIUS_KM` of each
/// commune (the commune itself included), over a coarse grid so the pass stays linear.
fn area_prominence_table(cmeta: &[u8], ccoord: &[u8], ncom: usize) -> Vec<u32> {
const CELL_DEG: f64 = 0.25; // >= the radius in degrees of latitude at any latitude
let mut cells: HashMap<(i32, i32), Vec<u32>> = HashMap::new();
let coord = |id: usize| {
let o = id * 8;
if o + 8 > ccoord.len() {
return None;
}
let (la, lo) = (
read_i32(ccoord, o) as f64 / 1e7,
read_i32(ccoord, o + 4) as f64 / 1e7,
);
(la != 0.0 || lo != 0.0).then_some((la, lo))
};
for id in 0..ncom {
if let Some((la, lo)) = coord(id) {
cells
.entry((
(la / CELL_DEG).floor() as i32,
(lo / CELL_DEG).floor() as i32,
))
.or_default()
.push(id as u32);
}
}
(0..ncom)
.map(|id| {
let own = read_u32(cmeta, id * COMMUNE_META_SIZE + 12);
let Some((la, lo)) = coord(id) else {
return own;
};
let (cy, cx) = (
(la / CELL_DEG).floor() as i32,
(lo / CELL_DEG).floor() as i32,
);
// Longitude cells shrink towards the poles: widen the search east-west.
let span_x = (1.0 / la.to_radians().cos().abs().max(0.2)).ceil() as i32;
let mut sum = 0u64;
for dy in -1..=1 {
for dx in -span_x..=span_x {
if let Some(ids) = cells.get(&(cy + dy, cx + dx)) {
for &other in ids {
if let Some((ola, olo)) = coord(other as usize) {
if Self::dist_km(la, lo, ola, olo) <= HOMONYM_AREA_RADIUS_KM {
sum += read_u32(
cmeta,
other as usize * COMMUNE_META_SIZE + 12,
) as u64;
}
}
}
}
}
}
u32::try_from(sum).unwrap_or(u32::MAX)
})
.collect()
}
/// Commune centroid (the "city point") — for city-only queries.
fn commune_coord(&self, id: u32) -> (f64, f64) {
let o = id as usize * 8;
if o + 8 > self.commune_coords.len() {
return (0.0, 0.0);
}
(
read_i32(self.commune_coords, o) as f64 / 1e7,
read_i32(self.commune_coords, o + 4) as f64 / 1e7,
)
}
/// The locality part of a query: tokens after the last all-digit token (house number or
/// postcode), and every run of them that is a commune name or its leading whole words.
/// Nothing after a house number: the leading place (`named_locality_head`).
/// No digit token — no locality: street and place cannot be told apart. All homonyms and
/// same-named fragments are kept, so the anchor never picks a side.
fn named_locality_anchor(&self, toks: &[&str]) -> NamedLocality {
let Some(last_digit) = toks
.iter()
.rposition(|t| t.bytes().all(|b| b.is_ascii_digit()))
else {
return NamedLocality::default();
};
let tail = &toks[last_digit + 1..];
if tail.is_empty() {
return self.named_locality_head(toks, last_digit);
}
self.named_locality_runs(&tail[tail.len().saturating_sub(NAMED_LOCALITY_TAIL)..])
}
/// "Madrid, Gran Via 1": the query ends with a house number, so the place stands first —
/// the longest leading run that is a commune name, with a street word left before the
/// first number. A query ending with a postcode or a long code ("…, Rio de Janeiro - RJ,
/// 20520051") names its place before the code; its first words are a street ("Niteroi,
/// 100, …"), so a token longer than a house number (4 digits) reads nothing.
fn named_locality_head(&self, toks: &[&str], last_digit: usize) -> NamedLocality {
if toks[last_digit].len() > 4 {
return NamedLocality::default();
}
let first_digit = toks
.iter()
.position(|t| t.bytes().all(|b| b.is_ascii_digit()))
.unwrap_or(last_digit);
let longest = first_digit.saturating_sub(1).min(NAMED_LOCALITY_TAIL);
(1..=longest)
.rev()
.find(|&lead| {
!self
.communes_by_name_untraced(&toks[..lead].join(" "))
.is_empty()
})
.map(|lead| self.named_locality_runs(&toks[..lead]))
.unwrap_or_default()
}
/// After a prefix drop, does the remainder behind the type word name only places? Digits
/// (house number, postcode), region codes and type words do not count; every other word
/// must sit inside a run that names a commune. An empty remainder names nothing.
fn remainder_names_only_places(&self, rest: &[&str]) -> bool {
let cfg = &crate::rules::rules().city_tail;
let is_region = |w: &str| region_matches(cfg, w);
let is_word = |w: &str| {
!w.bytes().all(|b| b.is_ascii_digit()) && !is_street_type_word(w) && !is_region(w)
};
let words: Vec<usize> = (0..rest.len()).filter(|&i| is_word(rest[i])).collect();
if words.is_empty() {
return false;
}
let runs = self.named_locality_runs(rest);
words.iter().all(|&i| {
runs.communes
.iter()
.any(|&(_, start, end)| start <= i && i < end)
})
}
/// Every run of `tail` that is a commune name or its leading whole words.
fn named_locality_runs(&self, tail: &[&str]) -> NamedLocality {
let mut anchor = NamedLocality {
tail: tail.iter().map(|t| t.to_string()).collect(),
communes: Vec::new(),
};
for start in 0..tail.len() {
for end in start + 1..=tail.len() {
let run = tail[start..end].join(" ");
// exact name, and whole leading words of a longer official name: "Langenhagen,
// Stadt" next to a village "Langenhagen", "Oldenburg (Oldenb.), Stadt" — never
// "Oldenburger Land". A word that starts many names ("Sant", "Centro") is not
// one place.
let lead = format!("{run} ");
let mut found = self.communes_by_name_untraced(&run);
let longer: Vec<u32> = self
.communes_by_prefix_untraced(&run)
.into_iter()
.filter(|&id| normalize(self.commune_name(id)).starts_with(&lead))
.collect();
if longer.len() <= NAMED_LOCALITY_LEAD_MAX {
found.extend(longer);
}
for id in found {
if !anchor.communes.iter().any(|&(seen, _, _)| seen == id) {
anchor.communes.push((id, start, end));
}
}
}
}
anchor
}
/// A fallback answer stays only inside the locality the query names. Kept: the answer
/// matched the query's own commune or postcode; its commune starts with words the tail
/// names ("Oldenburg (Oldenb.), Stadt" for "Oldenburg"); or it lies within
/// NAMED_LOCALITY_RADIUS_KM of a named commune (city districts and fragments are separate
/// communes). A run that is part of a longer street of the answer names no place ("6 Place
/// de l'Iris"); a street that IS the city name is the defect itself ("Berlin 1" for
/// "Alexanderplatz 1, Berlin"). Without a named commune — no check.
fn near_named_locality(&self, hit: &Hit, anchor: &NamedLocality) -> bool {
if anchor.communes.is_empty()
|| hit.flags.contains(&"commune_exact")
|| hit.flags.contains(&"pc_exact")
{
return true;
}
if Self::commune_leads_with_named_words(&hit.commune, anchor) {
return true;
}
let street = normalize(&hit.street);
let street: Vec<&str> = street.split(' ').filter(|t| !t.is_empty()).collect();
let mut named = anchor
.communes
.iter()
.filter(|&&(_, start, end)| {
street.len() <= end - start
|| !anchor.tail[start..end]
.iter()
.all(|t| street.contains(&t.as_str()))
})
.peekable();
if named.peek().is_none() {
return true;
}
named.any(|&(id, _, _)| {
let (lat, lon) = self.commune_coord(id);
Self::dist_km(lat, lon, hit.lat, hit.lon) <= NAMED_LOCALITY_RADIUS_KM
})
}
/// The commune's name starts with whole words the tail names ("Oldenburg (Oldenb.), Stadt"
/// for "Oldenburg"); a single word shorter than 4 letters names nothing.
fn commune_leads_with_named_words(commune: &str, anchor: &NamedLocality) -> bool {
let commune = normalize(commune);
let commune: Vec<&str> = commune.split(' ').filter(|t| !t.is_empty()).collect();
for start in 0..anchor.tail.len() {
for end in start + 1..=anchor.tail.len() {
let run = &anchor.tail[start..end];
if (run.len() > 1 || run[0].len() >= 4)
&& commune.len() >= run.len()
&& run.iter().zip(&commune).all(|(a, b)| a == b)
{
return true;
}
}
}
false
}
/// A commune found only by the PREFIX of a boundary phrase is evidence of place only
/// inside the locality the query tail names. The "city first" variant moves the first
/// street word into the commune slot ("gran via 1 madrid" -> "via madrid gran"), and
/// "gran" prefixes Granada: a fuzzy "Avenida Madrid" in Granada beat the exact commune
/// Madrid named at the tail. Kept: the street's commune matched exactly, its postcode
/// matched the query's, its commune starts with words the tail names, or it lies within
/// NAMED_LOCALITY_RADIUS_KM of a named commune. Unlike the fallback check, a tail word
/// inside the candidate street is no excuse here: "Calle Barcelona" in Caspe for
/// "C. del Casp 34, barcelona" is the defect itself. Without a named commune — no check.
fn prefix_commune_within_named_locality(
&self,
sid: u32,
f: &Feats,
anchor: &NamedLocality,
) -> bool {
if !f.commune_prefix || f.commune_exact || f.pc_exact || anchor.communes.is_empty() {
return true;
}
let m = self.street_meta(sid);
if Self::commune_leads_with_named_words(self.commune_name(m.commune_id), anchor) {
return true;
}
let (lat, lon) = (m.lat_c as f64 / 1e7, m.lon_c as f64 / 1e7);
anchor.communes.iter().any(|&(id, _, _)| {
let (clat, clon) = self.commune_coord(id);
Self::dist_km(clat, clon, lat, lon) <= NAMED_LOCALITY_RADIUS_KM
})
}
/// Universal resolution of a bare place name (city/district/estate/arrondissement) -> point.
/// (1) Exact commune name -> its centroid (among homonyms, the most prominent one).
/// (2) Else the prefix commune group: "Lyon" -> "Lyon 1er...", i.e. an umbrella of
/// sub-units -> prominence-weighted mean centroid.
/// Country-agnostic: the data itself decides whether a district is a commune or a
/// prefix umbrella. Returns (lat, lon, name, prominence). Prominence = the commune's
/// address count (for an umbrella, the group sum): a large umbrella city scores high,
/// a specific settlement low. This is the anchor weight for the place fallback:
/// among resolved places the anchor is the most prominent one.
// The final flag records exact-name resolution (true), versus a prefix group.
fn resolve_place(&self, name: &str) -> Option<(f64, f64, String, u32, bool)> {
if name.is_empty() {
return None;
}
// (1) Exact commune name. Large cities may be split into same-named fragments by
// geo-cell splitting; taking a single fragment's centroid would shift the "city
// center". Homonyms within 40 km of the most prominent one are fragments of ONE
// city: take their weighted centroid and summed prominence. Distant true homonyms
// (hundreds of km apart) stay out of the group.
let ids = self.communes_by_name(name);
if let Some(&top) = ids.iter().max_by_key(|&&id| self.commune_prominence(id)) {
let (tla, tlo) = self.commune_coord(top);
if tla != 0.0 || tlo != 0.0 {
// merge ONLY same-named entries (same display name as the most prominent):
// communes_by_name may also return villages under a city umbrella, and
// merging those would pull the anchor toward the villages. City fragments
// share the display name and merge; distinct places do not.
let top_name = self.commune_name(top);
let (mut sla, mut slo, mut sw) = (0.0f64, 0.0f64, 0.0f64);
for &id in &ids {
let (la, lo) = self.commune_coord(id);
if (la == 0.0 && lo == 0.0)
|| Self::dist_km(tla, tlo, la, lo) > PLACE_GROUP_RADIUS_KM
|| self.commune_name(id) != top_name
{
continue;
}
let w = self.commune_prominence(id).max(1) as f64;
sla += la * w;
slo += lo * w;
sw += w;
}
return Some((sla / sw, slo / sw, top_name.to_string(), sw as u32, true));
}
}
// (2) prefix commune group (+SPACE so "lyon " does not match "lyonne")
let arr = self.communes_by_prefix(&format!("{name} "));
// Distant names sharing a prefix are separate places, not one centroid.
let &anchor = arr
.iter()
.filter(|&&id| self.commune_coord(id) != (0.0, 0.0))
.max_by_key(|&&id| self.commune_prominence(id))?;
let (anchor_lat, anchor_lon) = self.commune_coord(anchor);
let (mut sla, mut slo, mut sw) = (0.0f64, 0.0f64, 0.0f64);
for id in &arr {
let (la, lo) = self.commune_coord(*id);
if (la == 0.0 && lo == 0.0)
|| Self::dist_km(anchor_lat, anchor_lon, la, lo) > PLACE_GROUP_RADIUS_KM
{
continue;
}
let w = self.commune_prominence(*id).max(1) as f64;
sla += la * w;
slo += lo * w;
sw += w;
}
if sw > 0.0 {
return Some((sla / sw, slo / sw, name.to_string(), sw as u32, false));
}
None
}
/// resolve_place + transliteration both ways (mixed scripts): a Cyrillic query finds
/// Latin data (both Serbian Gaj and English digraphs) and vice versa.
fn resolve_place_translit(&self, phrase: &str) -> Option<(f64, f64, String, u32, bool)> {
let try_t = |f: fn(&str) -> String| -> Option<(f64, f64, String, u32, bool)> {
let t = normalize(&f(phrase));
if t != phrase {
self.resolve_place(&t)
} else {
None
}
};
self.resolve_place(phrase)
.or_else(|| try_t(crate::norm::translit_cyr_lat))
.or_else(|| try_t(crate::norm::translit_cyr_lat_en))
.or_else(|| try_t(crate::norm::translit_lat_cyr))
.filter(|&(la, lo, _, _, _)| la != 0.0 || lo != 0.0)
}
/// Distance between points in km (haversine).
fn dist_km(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
let r = 6371.0_f64;
let (p1, p2) = (lat1.to_radians(), lat2.to_radians());
let dp = (lat2 - lat1).to_radians();
let dl = (lon2 - lon1).to_radians();
let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2);
2.0 * r * a.sqrt().asin()
}
/// Resolve an explicit trailing geographic qualifier for a genuinely distant homonym:
/// `... Castro Bergamo`, `... Samone Trento`, `... San Teodoro Messina`.
///
/// The qualifier must itself resolve as a place, the immediately preceding commune name
/// must have centroids over 80 km apart, and the chosen homonym must be within 120 km of
/// the qualifier with at least a 25 km advantage over every other remote cluster. The
/// address query then runs without the qualifier and retains only hits assigned to the
/// selected 40 km homonym cluster. If that cluster has no matching address, return empty
/// rather than a confident address in a different province.
fn trailing_homonym_qualifier_retry(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
if toks.len() < 4 {
return None;
}
let max_qualifier = 3.min(toks.len().saturating_sub(3));
for qualifier_len in (1..=max_qualifier).rev() {
let qualifier_start = toks.len() - qualifier_len;
let qualifier = toks[qualifier_start..].join(" ");
let Some((anchor_lat, anchor_lon, _, _, _)) = self.resolve_place_translit(&qualifier)
else {
continue;
};
let max_commune = 4.min(qualifier_start.saturating_sub(2));
for commune_len in (1..=max_commune).rev() {
let commune_start = qualifier_start - commune_len;
let commune = toks[commune_start..qualifier_start].join(" ");
let ids = self.communes_by_name(&commune);
if ids.len() < 2 {
continue;
}
// `Oriolo Romano` is a complete commune, not homonym `Oriolo` qualified by
// place `Romano`. Preserve every exact full-commune interpretation.
let full_commune = toks[commune_start..].join(" ");
if !self.communes_by_name(&full_commune).is_empty() {
return None;
}
// Exact-name postings are file-controlled and may contain u16::MAX ids. Bound
// the quadratic distance check on adversarial/lab sheets; real IT max is 9.
if ids.len() > 40 {
return Some(Vec::new());
}
let coords: Vec<(u32, f64, f64)> = ids
.iter()
.filter_map(|&id| {
let (lat, lon) = self.commune_coord(id);
(lat != 0.0 || lon != 0.0).then_some((id, lat, lon))
})
.collect();
let remote_homonyms = coords.iter().enumerate().any(|(i, (_, alat, alon))| {
coords[i + 1..]
.iter()
.any(|(_, blat, blon)| Self::dist_km(*alat, *alon, *blat, *blon) > 80.0)
});
if !remote_homonyms {
continue;
}
let Some((selected_id, selected_lat, selected_lon, selected_distance)) = coords
.iter()
.map(|&(id, lat, lon)| {
(
id,
lat,
lon,
Self::dist_km(anchor_lat, anchor_lon, lat, lon),
)
})
.min_by(|a, b| a.3.partial_cmp(&b.3).unwrap_or(std::cmp::Ordering::Equal))
else {
continue;
};
if selected_distance > 120.0 {
return Some(Vec::new());
}
let selected_ids: Vec<u32> = coords
.iter()
.filter_map(|&(id, lat, lon)| {
(Self::dist_km(selected_lat, selected_lon, lat, lon) <= 40.0).then_some(id)
})
.collect();
debug_assert!(selected_ids.contains(&selected_id));
let second_distance = coords
.iter()
.filter(|(id, _, _)| !selected_ids.contains(id))
.map(|&(_, lat, lon)| Self::dist_km(anchor_lat, anchor_lon, lat, lon))
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
if second_distance.is_none_or(|distance| distance - selected_distance < 25.0) {
return Some(Vec::new());
}
let base = toks[..qualifier_start].join(" ");
let mut hits = self.query_feats_prepared(&base, k.max(10), focus);
hits.retain(|(hit, _)| {
if normalize(&hit.commune) != commune {
return false;
}
coords
.iter()
.min_by(|(_, alat, alon), (_, blat, blon)| {
Self::dist_km(*alat, *alon, hit.lat, hit.lon)
.partial_cmp(&Self::dist_km(*blat, *blon, hit.lat, hit.lon))
.unwrap_or(std::cmp::Ordering::Equal)
})
.is_some_and(|(id, _, _)| selected_ids.contains(id))
});
for (hit, features) in &mut hits {
// The base query may have been capped as `ambiguous_far` before the explicit
// qualifier selected one remote cluster. Recompute the original calibrated
// confidence from its features and remove that now-resolved warning.
let feats = Feats::from_vec(features);
hit.confidence = confidence_score(hit.precision, &feats, 0);
if hit.score < 0.0 {
hit.confidence = hit.confidence.min(0.4);
}
hit.flags.retain(|flag| *flag != "ambiguous_far");
hit.flags.push("geo_qualifier");
}
hits.truncate(k);
return Some(hits);
}
}
None
}
/// Wrap a city point into a single city-precision Hit.
fn city_hit(
lat: f64,
lon: f64,
commune: String,
exact_place: bool,
) -> Vec<(Hit, [f32; N_FEATS])> {
vec![(
Hit {
lat,
lon,
precision: "city",
score: 0.0,
confidence: 0.05, // calibrated: city-level hits rarely fall within 150 m
street: String::new(),
housenumber: None,
commune,
postcode: String::new(),
flags: vec![if exact_place {
"place_exact"
} else {
"place_prefix_group"
}],
region: None,
distance_m: None,
},
[0.0; N_FEATS],
)]
}
/// Commune ids by normalized name (all homonyms).
fn communes_by_name_raw(&self, name: &str) -> Vec<u32> {
match self.communes_fst.get(name.as_bytes()) {
None => Vec::new(),
Some(v) => {
let start = (v >> 16) as usize;
let count = (v & 0xFFFF) as usize;
// FST values come from the file: on a corrupt-but-parseable sheet they
// can point past the postings section — a panic here would take the
// host process (Python/DuckDB) down with it
if (start + count) * 4 > self.postings.len() {
return Vec::new();
}
(0..count)
.map(|i| read_u32(self.postings, (start + i) * 4))
.collect()
}
}
}
// A street type alone supplies no place evidence in an Italian address.
// Keep complete and multiword place names, including Piazza Armerina.
fn it_street_type_only(&self, name: &str) -> bool {
let name = name.trim();
self.country() == Some("it")
&& !name.contains(' ')
&& (is_street_type_word(name) || matches!(name, "piazzale" | "borgo"))
}
fn communes_by_name(&self, name: &str) -> Vec<u32> {
let ids = self.communes_by_name_untraced(name);
crate::diagnosis::area(name, &ids, "communes_by_name");
ids
}
/// Commune ids within the region anchor of the running query (all of them without one).
fn held_by_region(&self, ids: Vec<u32>) -> Vec<u32> {
COMMUNE_REGION_ANCHOR.with(|a| {
let points = &a.borrow().points;
if points.is_empty() {
return ids;
}
ids.into_iter()
.filter(|&id| self.within_points(id, points, COMMUNE_REGION_RADIUS_KM))
.collect()
})
}
fn within_points(&self, id: u32, points: &[(f64, f64)], radius_km: f64) -> bool {
let (lat, lon) = self.commune_coord(id);
points
.iter()
.any(|&(plat, plon)| Self::dist_km(plat, plon, lat, lon) <= radius_km)
}
/// The anchored city is not a commune of the sheet (New York: the sheet's communes are its
/// neighbourhoods), but the table knows where it is: every commune within the radius of
/// its points stands in for it. Only the anchored city's own name is read this way.
fn communes_under_anchor(&self, name: &str) -> Vec<u32> {
COMMUNE_REGION_ANCHOR.with(|a| {
let anchor = a.borrow();
if anchor.points.is_empty() || anchor.city != name {
return Vec::new();
}
let n = (self.commune_coords.len() / 8) as u32;
(0..n)
.filter(|&id| self.within_points(id, &anchor.points, COMMUNE_UMBRELLA_RADIUS_KM))
.collect()
})
}
fn communes_by_name_untraced(&self, name: &str) -> Vec<u32> {
let ids = self.communes_by_name_unheld(name);
let ids = self.held_by_region(ids);
let widened = COMMUNE_REGION_ANCHOR.with(|a| a.borrow().widen);
if ids.is_empty() || widened {
let under = self.communes_under_anchor(name);
if !under.is_empty() {
return under;
}
}
ids
}
fn communes_by_name_unheld(&self, name: &str) -> Vec<u32> {
if self.it_street_type_only(name) {
return Vec::new();
}
let name = commune_alias(name).unwrap_or(name);
let ids = self.communes_by_name_raw(name);
if !ids.is_empty() {
return ids;
}
if let Some(full) = saint_commune_name(name) {
let ids = self.communes_by_name_raw(&full);
if !ids.is_empty() {
return ids;
}
}
// ARTICLE ELISION (FR): users commonly drop "L'/La/Le/Les" ("Ile Rousse" for
// "L'Île-Rousse") or glue the article onto the name ("Lhay").
for art in ["l", "la", "le", "les"] {
let ids = self.communes_by_name_raw(&format!("{art} {name}"));
if !ids.is_empty() {
return ids;
}
}
if let Some(rest) = name.strip_prefix('l') {
if rest.chars().next().is_some_and(|c| c.is_alphabetic()) {
let ids = self.communes_by_name_raw(&format!("l {rest}"));
if !ids.is_empty() {
return ids;
}
}
}
// PLACE TYPE WORDS (e.g. Uzbek block markers): "name N kvartal" != commune name
// "name N" — strip district type words and retry (bridges kvartal/mavze synonyms).
let stripped: Vec<&str> = name
.split(' ')
.filter(|w| !crate::rules::rules().place_type_strip.contains(*w))
.collect();
if stripped.len() < name.split(' ').count() && !stripped.is_empty() {
return self.communes_by_name_raw(&stripped.join(" "));
}
Vec::new()
}
/// Communes by name prefix ("paris" -> all arrondissements) — fallback path.
fn communes_by_prefix(&self, name: &str) -> Vec<u32> {
let ids = self.communes_by_prefix_untraced(name);
crate::diagnosis::area(name, &ids, "communes_by_prefix");
ids
}
fn communes_by_prefix_untraced(&self, name: &str) -> Vec<u32> {
let ids = self.communes_by_prefix_unheld(name);
self.held_by_region(ids)
}
fn communes_by_prefix_unheld(&self, name: &str) -> Vec<u32> {
if self.it_street_type_only(name) {
return Vec::new();
}
// Count the supplied fragment before aliases or articles can lengthen it.
if name.chars().filter(|c| c.is_alphanumeric()).take(3).count() < 3 {
return Vec::new();
}
let name = commune_alias(name).unwrap_or(name);
let out = self.communes_by_prefix_raw(name);
if !out.is_empty() {
return out;
}
for art in ["l", "la", "le", "les"] {
let out = self.communes_by_prefix_raw(&format!("{art} {name}"));
if !out.is_empty() {
return out;
}
}
Vec::new()
}
fn communes_by_prefix_raw(&self, name: &str) -> Vec<u32> {
let lo = name.as_bytes().to_vec();
let mut hi = name.as_bytes().to_vec();
hi.push(0xFF);
let mut out = Vec::new();
let mut stream = self.communes_fst.range().ge(&lo).lt(&hi).into_stream();
while let Some((_, v)) = stream.next() {
let start = (v >> 16) as usize;
let count = (v & 0xFFFF) as usize;
if (start + count) * 4 > self.postings.len() {
continue; // corrupt posting span: skip this name, never panic
}
for i in 0..count {
out.push(read_u32(self.postings, (start + i) * 4));
if out.len() >= 40 {
return out;
}
}
}
out
}
/// House lookup within a street block. Returns
/// `(lat, lon, kind, number, rep, postcode_name_off)`, kind:
/// 4 = interpolated from range points ("interp" carrying the `range` flag),
/// 3 = interpolated between tight neighbors ("interp"),
/// 2 = exact house (number AND rep matched),
/// 1 = number matched, any rep,
/// 0 = number absent -> NEAREST-by-number neighbor on the same street (snapping to a
/// house instead of the street center: missing numbers with present neighbors are
/// common, and the neighbor is tens of meters off instead of hundreds or km).
/// Houses are sorted ascending (delta coding) -> lower/upper neighbor.
/// The final two elements identify the address represented by the returned point. A
/// near snap carries the stored neighbour's number and suffix; interpolation has no
/// stored house, so it carries the requested number and suffix. The number is also used
/// as a snap tie-breaker: on a split street, a near-snap to a distant number of another
/// fragment loses to a candidate whose number is closer to the requested one.
fn find_house(
&self,
street_id: u32,
m: &StreetMeta,
numero: u32,
rep: u32,
requested_postcode: Option<u32>,
) -> Option<(f64, f64, u8, u32, u32, u32)> {
let (mut pos, postcode_dictionary, postcode_count, house_end) =
self.house_block_layout(street_id, m)?;
let bounded_houses = &self.houses[..house_end];
let mut cur = 0u32;
let mut exact_rep: Option<(f64, f64, u32)> = None;
let mut num_only: Option<(f64, f64, u32, u32)> = None;
let mut lower: Option<(u32, u32, f64, f64, u32)> = None; // last house below requested
let mut upper: Option<(u32, u32, f64, f64, u32)> = None; // first house above requested
let mut lower_same_parity = None;
let mut upper_same_parity = None;
// A range point (prep/us_tiger.py) carrying the requested number: an interpolation
// answer, never a house. Real houses with that number are preferred below.
let mut range_hit: Option<(f64, f64, u32)> = None;
let is_range = |rid: u32| Some(rid) == self.range_marker_rep;
for i in 0..m.house_count {
let d = u32::try_from(strict_varint(bounded_houses, &mut pos)?).ok()?;
cur = if i == 0 { d } else { cur.checked_add(d)? };
let rid = u32::try_from(strict_varint(bounded_houses, &mut pos)?).ok()?;
let dlat = unzigzag(strict_varint(bounded_houses, &mut pos)?);
let dlon = unzigzag(strict_varint(bounded_houses, &mut pos)?);
let postcode_off =
if self.format_version >= 7 && m.postcode_disp_off == PC_DISP_AMBIGUOUS {
let id = u32::try_from(strict_varint(bounded_houses, &mut pos)?).ok()?;
self.house_postcode_offset(postcode_dictionary, postcode_count, id)
} else {
0
};
let lat_e7 = (m.lat_c as i64).checked_add(dlat)?;
let lon_e7 = (m.lon_c as i64).checked_add(dlon)?;
if !(-900_000_000..=900_000_000).contains(&lat_e7)
|| !(-1_800_000_000..=1_800_000_000).contains(&lon_e7)
{
return None;
}
let lat = lat_e7 as f64 / 1e7;
let lon = lon_e7 as f64 / 1e7;
if cur == numero {
if is_range(rid) {
if range_hit.is_none() {
range_hit = Some((lat, lon, postcode_off));
}
continue;
}
if rid == rep {
let postcode_matches = requested_postcode.is_some_and(|postcode| {
self.exact_house_postcode_matches(m, postcode_off, postcode)
});
if requested_postcode.is_none() || postcode_matches {
return Some((lat, lon, 2, cur, rid, postcode_off));
}
if exact_rep.is_none() {
exact_rep = Some((lat, lon, postcode_off));
}
}
if num_only.is_none() {
num_only = Some((lat, lon, rid, postcode_off));
}
} else if cur < numero {
lower = Some((cur, rid, lat, lon, postcode_off));
if cur % 2 == numero % 2 {
lower_same_parity = lower;
}
} else {
// Keep the nearest house for snapping, while looking for the same street side.
let house = Some((cur, rid, lat, lon, postcode_off));
if upper.is_none() {
upper = house;
}
if cur % 2 == numero % 2 {
upper_same_parity = house;
}
if num_only.is_some() || lower_same_parity.is_none() || upper_same_parity.is_some()
{
break;
}
}
}
if let Some((lat, lon, postcode_off)) = exact_rep {
return Some((lat, lon, 2, numero, rep, postcode_off));
}
if let Some((la, lo, rid, postcode_off)) = num_only {
return Some((la, lo, 1, numero, rid, postcode_off));
}
if let Some((la, lo, postcode_off)) = range_hit {
return Some((la, lo, 4, numero, rep, postcode_off));
}
// No exact number. If neighbors on BOTH sides are TIGHT (small number gap AND small
// distance — dense linear numbering) -> interpolate by number fraction (47 between
// 45 and 49 -> 0.5 of the segment), kind=3 "interp". In sparse data the bracket can
// be wide (5 and 200) and interpolation overshoots, so a wide/distant bracket falls
// back to the nearest neighbor (kind=0 "near"). Tightness threshold empirically tuned.
// Prefer a complete same-parity bracket. Without one, retain the ordinary bracket:
// some streets use sequential numbering, and the index does not encode that scheme.
// Two range points are sampled from one linear range, so their number gap is not a
// sign of sparse data: only the distance bound applies between them.
let bracket = lower_same_parity
.zip(upper_same_parity)
.or(lower.zip(upper));
if let Some(((ln, lrid, la, lo, lpc), (un, urid, ua, uo, upc))) = bracket {
let between_ranges = is_range(lrid) && is_range(urid);
let (max_gap, max_km) = interp_limits();
let linear = un - ln <= max_gap || between_ranges;
let tight = linear && Self::dist_km(la, lo, ua, uo) < max_km;
if tight && un > ln {
let frac = (numero - ln) as f64 / (un - ln) as f64;
// Interpolation does not represent either neighbor. Its postcode is known only
// when both bracketing source addresses agree on one non-empty value.
let postcode_off = if lpc != 0 && lpc == upc { lpc } else { 0 };
return Some((
la + frac * (ua - la),
lo + frac * (uo - lo),
if between_ranges { 4 } else { 3 },
numero,
rep,
postcode_off,
));
}
}
if let (Some((ln, lrid, la, lo, lpc)), Some((un, urid, ua, uo, upc))) = (lower, upper) {
// Wide bracket: snap to the nearest actual house, regardless of parity.
return Some(if numero - ln <= un - numero {
(la, lo, 0, ln, lrid, lpc)
} else {
(ua, uo, 0, un, urid, upc)
});
}
// only one neighbor on the same street
match (lower, upper) {
(Some((n, rid, la, lo, postcode_off)), None)
| (None, Some((n, rid, la, lo, postcode_off))) => {
Some((la, lo, 0, n, rid, postcode_off))
}
_ => None,
}
}
fn house_number(&self, number: u32, rep: u32) -> String {
if Some(rep) == self.range_marker_rep {
return number.to_string(); // the range marker is never part of an address
}
let suffix = self
.rep_suffixes
.get(rep as usize)
.map_or("", String::as_str);
format!("{number}{suffix}")
}
fn add_cand(cand: &mut HashMap<u32, Feats>, sid: u32, f: Feats) {
crate::diagnosis::street(sid, f.street_exact, f.commune_exact || f.commune_prefix);
cand.entry(sid).or_default().merge(f);
}
/// Candidate collection: scanning the "street | commune" boundary from the end.
// Frozen release: keep scan budgets and caches wired through the validated call sites.
#[allow(clippy::too_many_arguments)]
fn collect_candidates(
&self,
rest: &[&str],
postcode: Option<u32>,
numero: Option<u32>,
rep: u32,
from_ml: bool,
de_postcode_house_scan: bool,
de_postcode_house_additional_numbers: &[u32],
de_postcode_house_scan_budget: &mut usize,
de_postcode_house_seen_phrases: &mut HashSet<String>,
de_postcode_house_exact_cache: &mut HashMap<(u32, u32, u32, u32), bool>,
) -> (HashMap<u32, Feats>, bool) {
if crate::diagnosis::enabled() {
crate::diagnosis::parsed(&rest.join(" "), postcode, numero, rep, None);
}
let mut cand: HashMap<u32, Feats> = HashMap::new();
let mut de_postcode_house_scan_overflowed = false;
if rest.is_empty() {
return (cand, de_postcode_house_scan_overflowed);
}
// French commune names can run to 8 words ("Saint-Remy-en-Bouzemont-...")
let max_c = rest.len().saturating_sub(1).min(9);
for c in 0..=max_c {
let street_phrase = rest[..rest.len() - c].join(" ");
if crate::diagnosis::enabled() {
let commune = (c > 0).then(|| rest[rest.len() - c..].join(" "));
crate::diagnosis::boundary(&street_phrase, commune.as_deref(), postcode, numero);
}
// phrase variants: as is + expanded abbreviations + rotated type word
let mut phrases = vec![street_phrase];
if let Some(exp) = expand_first(&phrases[0]) {
phrases.push(exp);
}
if let Some(exp) = expand_last(&phrases[0]) {
phrases.push(exp); // trailing type abbreviation
}
if street_type_last() {
// sheet rules at both ends of the name (types, directions), data-driven
// every variant the rounds compose (MAX_VARIANTS + the phrase): the composed
// "e 104 st" for "east 104th street" stands eighth, and a cut at six lost it
for variant in street_data_variants(&phrases[0]).into_iter().take(10) {
if !phrases.contains(&variant) {
phrases.push(variant);
}
}
}
if let Some(nd) = num_words_to_digits(&phrases[0]) {
phrases.push(nd); // spelled-out numerals -> digits ("Douze Mai" -> "12 Mai")
}
if !crate::norm::has_cyrillic(&phrases[0]) {
if let Some(gen) = serbian_genitive_variant(&phrases[0]) {
phrases.push(gen); // Serbian genitive ("Knez Mihailova" -> "Kneza Mihaila")
}
}
for i in 0..phrases.len().min(2) {
if let Some(rot) = rotate_type_first(&phrases[i]) {
phrases.push(rot);
}
}
let mut de_street_phrases = HashSet::new();
if self.country() == Some("de") {
let bases = phrases.clone();
for base in bases {
for variant in crate::de::street_variants(&base) {
if !phrases.contains(&variant) {
de_street_phrases.insert(variant.clone());
phrases.push(variant);
}
}
}
}
if c == 0 {
// the whole string is the street; prefix search across all communes
for phrase in &phrases {
let de_house_postcode_scan = de_postcode_house_scan
&& self.country() == Some("de")
&& self.format_version >= 7
&& postcode.is_some()
&& numero.is_some();
if de_house_postcode_scan
&& !de_postcode_house_seen_phrases.insert(phrase.clone())
{
continue;
}
let mut lo = phrase.clone().into_bytes();
lo.push(KEY_SEP);
let mut hi = phrase.clone().into_bytes();
hi.push(KEY_SEP + 1);
let mut stream = self.streets_fst.range().ge(&lo).lt(&hi).into_stream();
let mut taken = 0;
while let Some((_, v)) = stream.next() {
if de_house_postcode_scan {
if *de_postcode_house_scan_budget == 0 {
de_postcode_house_scan_overflowed = true;
break;
}
*de_postcode_house_scan_budget -= 1;
#[cfg(test)]
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| {
rows.set(rows.get().saturating_add(1));
});
}
let sid = v as u32;
let m = self.street_meta(sid);
let exact_house_postcode = match (postcode, numero) {
(Some(requested_postcode), Some(requested_number))
if de_house_postcode_scan =>
{
self.exact_house_postcode_set_candidate_cached(
de_postcode_house_exact_cache,
sid,
&m,
requested_number,
rep,
de_postcode_house_additional_numbers,
requested_postcode,
)
}
_ => false,
};
let mut f = Feats {
street_exact: true,
from_ml,
de_street_type: de_street_phrases.contains(phrase),
..Default::default()
};
// The narrow rescue consumes only exact street+house+postcode rows.
// It still visits the complete bounded posting stream above, so a hidden
// duplicate or overflow fails closed, while irrelevant homonyms never
// reach ranking or house decoding a second time.
if de_house_postcode_scan {
if !exact_house_postcode {
continue;
}
f.pc_exact = true;
f.pc_dept = true;
Self::add_cand(&mut cand, sid, f);
continue;
}
if let Some(pc) = postcode {
// postcode==0 = "absent from the data" — do not filter these,
// or a query WITH a postcode would go empty where the same
// query without one succeeds
if m.postcode != 0
&& m.postcode / 1000 != pc / 1000
&& !exact_house_postcode
{
continue; // different part of the country — skip
}
if m.postcode != 0 {
f.pc_dept = true;
f.pc_exact = m.postcode == pc;
}
}
if taken >= 300 && !exact_house_postcode {
continue;
}
Self::add_cand(&mut cand, sid, f);
if taken < 300 {
taken += 1;
}
if taken >= 300 && !de_house_postcode_scan {
break;
}
}
}
} else {
let commune_phrase = rest[rest.len() - c..].join(" ");
let mut exact_commune = true;
let mut cids = self.communes_by_name(&commune_phrase);
if cids.is_empty() {
cids = self.communes_by_prefix(&commune_phrase);
exact_commune = false;
}
// bare name without a street type: pad with type-word variants
let mut ph = phrases.clone();
ph.extend(type_padded_variants(&phrases[0]));
for padded in type_padded_direction_variants(&phrases[1..]) {
if !ph.contains(&padded) {
ph.push(padded);
}
}
// last-two-words swap and unglue variants — cheap extra keys (one FST read each)
for extra in phrases
.iter()
.filter_map(|f| swap_last_two_variant(f))
.chain(phrases.iter().filter_map(|f| unglue_variant(f)))
.collect::<Vec<_>>()
{
if !ph.contains(&extra) {
ph.push(extra);
}
}
for cid in cids {
let insee = self.commune_insee(cid);
for phrase in &ph {
let mut key = phrase.clone().into_bytes();
key.push(KEY_SEP);
key.extend_from_slice(insee.as_bytes());
if let Some(v) = self.streets_fst.get(&key) {
let sid = v as u32;
let m = self.street_meta(sid);
let exact_house_postcode = if de_postcode_house_scan
&& self.country() == Some("de")
&& self.format_version >= 7
{
if *de_postcode_house_scan_budget == 0 {
de_postcode_house_scan_overflowed = true;
break;
}
*de_postcode_house_scan_budget -= 1;
#[cfg(test)]
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| {
rows.set(rows.get().saturating_add(1));
});
match (postcode, numero) {
(Some(requested_postcode), Some(requested_number)) => self
.exact_house_postcode_set_candidate_cached(
de_postcode_house_exact_cache,
sid,
&m,
requested_number,
rep,
de_postcode_house_additional_numbers,
requested_postcode,
),
_ => false,
}
} else {
false
};
if de_postcode_house_scan && !exact_house_postcode {
continue;
}
let mut f = Feats {
street_exact: true,
commune_exact: exact_commune,
commune_prefix: !exact_commune,
pc_exact: postcode
.is_some_and(|pc| m.postcode != 0 && m.postcode == pc),
pc_dept: postcode.is_some_and(|pc| {
m.postcode != 0 && m.postcode / 1000 == pc / 1000
}),
from_ml,
de_street_type: de_street_phrases.contains(phrase),
..Default::default()
};
if de_postcode_house_scan {
f.pc_exact = true;
f.pc_dept = true;
}
Self::add_cand(&mut cand, sid, f);
}
}
}
}
}
(cand, de_postcode_house_scan_overflowed)
}
/// street_ids whose normalized name contains the word (inverted index).
fn word_streets(&self, word: &str) -> Vec<u32> {
match self.words_fst.get(word.as_bytes()) {
None => Vec::new(),
Some(off) => {
let mut p = off as usize;
// offset and each varint must stay inside the section: FST values are
// file data, and running off the end would panic the host
if p >= self.word_postings.len() {
return Vec::new();
}
let n = read_varint(self.word_postings, &mut p) as usize;
let mut ids = Vec::with_capacity(n.min(1 << 20));
let mut prev = 0u32;
for _ in 0..n {
if p >= self.word_postings.len() {
break; // truncated postings: return what decoded cleanly
}
prev += read_varint(self.word_postings, &mut p) as u32;
ids.push(prev);
}
ids
}
}
}
/// "Street-word subset" fallback pass: when exact search is empty and the query holds
/// only PART of the street's words (suffix/middle) — e.g. "amir temur" -> "Amir Temur
/// shoh". Takes the significant street words from the query, pulls street_ids for each
/// via the inverted index, intersects them and filters by commune. Only with a known
/// commune (c>0) — country-wide it is far too diffuse.
fn collect_subset(
&self,
rest: &[&str],
postcode: Option<u32>,
numero: Option<u32>,
) -> HashMap<u32, Feats> {
let mut cand: HashMap<u32, Feats> = HashMap::new();
if rest.len() < 2 {
return cand;
}
let max_c = rest.len().saturating_sub(1).min(9);
for c in 1..=max_c {
let commune_phrase = rest[rest.len() - c..].join(" ");
let mut exact_commune = true;
let mut cids = self.communes_by_name(&commune_phrase);
if cids.is_empty() {
cids = self.communes_by_prefix(&commune_phrase);
exact_commune = false;
}
if cids.is_empty() {
continue;
}
let cidset: std::collections::HashSet<u32> = cids.into_iter().collect();
let (n_sets, _nontype, acc) = match self.subset_intersect(&rest[..rest.len() - c]) {
Some(v) => v,
None => continue, // no significant words / matched only via a street type
};
// commune filter
let mut sids: Vec<u32> = acc
.into_iter()
.filter(|&sid| cidset.contains(&self.street_meta(sid).commune_id))
.collect();
// Hallucination guard: a SINGLE word matching MANY streets in the commune is a
// type/frequent word or a fragment of one (normalization splits "ko'chasi" ->
// "ko chasi", and "chasi" matches every street), not a distinguishing name. A
// real name matches only a handful. In that case a confident house answer is
// not allowed.
// With a house number the number itself tells the streets apart: of the sixteen
// Boise streets carrying "grove" only "W Grove St" has a 619. Keep the streets
// where the requested number exists, as long as they stay a handful; a word that
// leaves many streets with that number is still a frequent word. Only on sheets
// whose type trails the name (city_tail `street_type_last`): elsewhere the
// relaxation cost Brazil five houses on three sets (US, 22.10.2026).
const SINGLE_MAX: usize = 8;
if n_sets == 1 && sids.len() > SINGLE_MAX {
let Some(number) = numero.filter(|_| street_type_last()) else {
continue;
};
sids.retain(|&sid| {
let m = self.street_meta(sid);
self.find_house(sid, &m, number, 0, None)
.is_some_and(|(_, _, kind, _, _, _)| kind >= 1 && kind != 4)
});
if sids.is_empty() || sids.len() > SINGLE_MAX {
continue;
}
}
sids.sort_unstable();
sids.truncate(200);
for sid in sids {
let m = self.street_meta(sid);
let f = Feats {
street_fuzzy: true, // word subset is not an exact string match
commune_exact: exact_commune,
commune_prefix: !exact_commune,
pc_exact: postcode.is_some_and(|pc| m.postcode != 0 && m.postcode == pc),
pc_dept: postcode
.is_some_and(|pc| m.postcode != 0 && m.postcode / 1000 == pc / 1000),
..Default::default()
};
Self::add_cand(&mut cand, sid, f);
}
}
cand
}
/// Intersect street_ids over the phrase's significant words (>=3 chars, not a type)
/// via the inverted index. Returns (set count, non-type set count, intersection); None
/// if no significant word has postings or only street-type words matched. Words at the
/// postings cap (types) are skipped; the rarest word seeds the result, and a word that
/// would zero the intersection is skipped (a variant spelling must not kill the answer).
fn subset_intersect(
&self,
toks: &[&str],
) -> Option<(usize, usize, std::collections::HashSet<u32>)> {
const CAP: usize = 16384;
let mut sets: Vec<Vec<u32>> = Vec::new();
let mut nontype = 0usize;
for tok in toks {
let is_sep = |ch: char| {
!ch.is_alphanumeric()
&& !matches!(
ch,
'\'' | '\u{2019}' | '\u{2018}' | '\u{02BB}' | '\u{02BC}' | '`'
)
};
for w0 in tok.split(is_sep) {
let w = normalize(w0);
if w.chars().count() < 3 {
continue;
}
let w = w.as_str();
let mut tried = vec![w.to_string()];
let cl = normalize(&crate::norm::translit_cyr_lat(w));
if cl != w && cl.chars().count() >= 3 {
tried.push(cl);
}
let lc = normalize(&crate::norm::translit_lat_cyr(w));
if lc != w && lc.chars().count() >= 3 {
tried.push(lc);
}
if tried.iter().any(|t| is_street_type_word(t)) {
continue;
}
// phonetic key: cross-language spelling variants (e.g. Kadyri ~ Qodiriy)
// share a "~"-prefixed key in the inverted index. Extra key, after the type check.
let pk = crate::norm::phonetic_key(w);
if pk.chars().count() >= 3 {
tried.push(format!("~{pk}"));
}
let mut best: Option<Vec<u32>> = None;
for t in &tried {
let ids = self.word_streets(t);
if ids.is_empty() || ids.len() >= CAP {
continue;
}
if best.as_ref().is_none_or(|b| ids.len() < b.len()) {
best = Some(ids);
}
}
if let Some(ids) = best {
nontype += 1;
sets.push(ids);
}
}
}
if sets.is_empty() || nontype == 0 {
return None;
}
sets.sort_by_key(|s| s.len());
let mut acc: std::collections::HashSet<u32> = sets[0].iter().copied().collect();
for s in &sets[1..] {
let other: std::collections::HashSet<u32> = s.iter().copied().collect();
let inter: std::collections::HashSet<u32> = acc.intersection(&other).copied().collect();
if !inter.is_empty() {
acc = inter;
}
}
Some((sets.len(), nontype, acc))
}
/// Single-edit variants over CHARACTERS (works for any script — byte-level edits would
/// break multi-byte scripts): deletions, adjacent transpositions, and optionally
/// full-alphabet replacements and insertions.
fn edit1_variants(phrase: &str, with_repl: bool) -> Vec<String> {
let chars: Vec<char> = phrase.chars().collect();
let n = chars.len();
let mut out: Vec<String> = Vec::new();
// deletions
for i in 0..n {
if chars[i] == ' ' {
continue;
}
let mut v = String::with_capacity(phrase.len());
v.extend(chars[..i].iter());
v.extend(chars[i + 1..].iter());
out.push(v);
}
// adjacent transpositions
for i in 0..n.saturating_sub(1) {
if chars[i] == ' ' || chars[i + 1] == ' ' || chars[i] == chars[i + 1] {
continue;
}
let mut v = chars.clone();
v.swap(i, i + 1);
out.push(v.into_iter().collect());
}
if with_repl && n <= 26 {
// full alphabet of the phrase's script: replacements AND insertions
// (a replacement typo is fixed by replacement, a deletion by insertion);
// too expensive on long phrases — capped at 26 characters
let cyr = chars.iter().any(|c| ('а'..='я').contains(c) || *c == 'ё');
let alphabet: &str = if cyr {
"абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
} else {
"abcdefghijklmnopqrstuvwxyz"
};
// replacements
for i in 0..n {
if chars[i] == ' ' {
continue;
}
for a in alphabet.chars() {
if a == chars[i] {
continue;
}
let mut v = chars.clone();
v[i] = a;
out.push(v.into_iter().collect());
}
}
// insertions (including the position after the last character)
for i in 0..=n {
if i > 0 && i < n && chars[i - 1] == ' ' && chars[i] == ' ' {
continue;
}
for a in alphabet.chars() {
let mut v: Vec<char> = Vec::with_capacity(n + 1);
v.extend_from_slice(&chars[..i]);
v.push(a);
v.extend_from_slice(&chars[i..]);
out.push(v.into_iter().collect());
}
}
}
out
}
/// Fuzzy candidate collection over the words as written and, when that finds nothing on a
/// sheet with city_tail `fuzzy_short_forms`, over the words at the sheet's short form (see
/// `fuzzy_short_rest`).
fn collect_fuzzy(
&self,
rest: &[&str],
postcode: Option<u32>,
from_ml: bool,
) -> HashMap<u32, Feats> {
let cand = self.collect_fuzzy_written(rest, postcode, from_ml);
if !cand.is_empty() {
return cand;
}
let Some(short) = fuzzy_short_rest(rest) else {
return cand;
};
// The edit budget is for the name: a street whose type or direction differs from the
// one written ("Diefenbaker Place" -> "Diefenbaker DR", "Whitehall Avenue" ->
// "Whitehall CRES") is another street, not a typo of this one.
let fixed: Vec<&str> = short
.iter()
.zip(rest)
.filter(|(s, w)| s.as_str() != **w)
.map(|(s, _)| s.as_str())
.collect();
let words: Vec<&str> = short.iter().map(String::as_str).collect();
let mut cand = self.collect_fuzzy_written(&words, postcode, from_ml);
cand.retain(|&sid, _| {
let name = normalize(self.name(self.street_meta(sid).name_off));
fixed.iter().all(|f| name.split(' ').any(|w| w == *f))
});
cand
}
/// Fuzzy candidate collection: single-edit variants via exact keys
/// + a Levenshtein automaton (1 edit for 5-11 chars, 2 for 12+).
fn collect_fuzzy_written(
&self,
rest: &[&str],
postcode: Option<u32>,
from_ml: bool,
) -> HashMap<u32, Feats> {
let mut cand: HashMap<u32, Feats> = HashMap::new();
if rest.is_empty() {
return cand;
}
let max_c = rest.len().saturating_sub(1).min(9);
for c in 0..=max_c {
let street_phrase = rest[..rest.len() - c].join(" ");
let dist = match street_phrase.chars().count() {
0..=4 => continue,
5..=11 => 1,
_ => 2,
};
// allowed communes, if the boundary carved them out
let mut exact_commune = true;
let allowed: Option<Vec<String>> = if c > 0 {
let phrase = rest[rest.len() - c..].join(" ");
let mut ids = self.communes_by_name(&phrase);
if ids.is_empty() {
ids = self.communes_by_prefix(&phrase);
exact_commune = false;
}
if ids.is_empty() {
continue;
}
Some(
ids.iter()
.map(|&id| self.commune_insee(id).to_string())
.collect(),
)
} else {
None
};
let mk_feats = |m: &StreetMeta| Feats {
street_fuzzy: true,
commune_exact: allowed.is_some() && exact_commune,
commune_prefix: allowed.is_some() && !exact_commune,
pc_exact: postcode.is_some_and(|pc| m.postcode != 0 && m.postcode == pc),
pc_dept: postcode
.is_some_and(|pc| m.postcode != 0 && m.postcode / 1000 == pc / 1000),
from_ml,
..Default::default()
};
// 1) single-edit variants — cheap, via exact keys; replacements
// only when communes are known (few keys to try)
for var in Self::edit1_variants(&street_phrase, allowed.is_some()) {
match &allowed {
Some(allow) => {
for insee in allow {
let mut key = var.clone().into_bytes();
key.push(KEY_SEP);
key.extend_from_slice(insee.as_bytes());
if let Some(v) = self.streets_fst.get(&key) {
let sid = v as u32;
let m = self.street_meta(sid);
Self::add_cand(&mut cand, sid, mk_feats(&m));
}
}
}
None => {
let mut lo = var.clone().into_bytes();
lo.push(KEY_SEP);
let mut hi = var.clone().into_bytes();
hi.push(KEY_SEP + 1);
let mut stream = self.streets_fst.range().ge(&lo).lt(&hi).into_stream();
let mut taken = 0;
while let Some((_, v)) = stream.next() {
let sid = v as u32;
let m = self.street_meta(sid);
if let Some(pc) = postcode {
// postcode==0 in data is not a filter (see collect_candidates)
if m.postcode != 0 && m.postcode / 1000 != pc / 1000 {
continue;
}
}
Self::add_cand(&mut cand, sid, mk_feats(&m));
taken += 1;
if taken >= 50 {
break;
}
}
}
}
}
// 2) Levenshtein automaton — extra recall for pure ASCII (on Unicode the
// automaton blows up in states and silently gives up)
if !cand.is_empty() {
if c > 0 {
break;
}
continue;
}
if !street_phrase.is_ascii() {
continue;
}
// Content-word gate: a phrase-level automaton matches "rue de la gare" ->
// "rue de la gagnerie..." through function words — a confident house on a
// DISSIMILAR street. Require at least one content word of the query (not a
// type/article, >=3 chars) to match a candidate name word within 1 edit.
// Declared BEFORE the `lev` automaton binding below, which shadows the
// distance function of the same name.
let q_content: Vec<Vec<char>> = street_phrase
.split(' ')
.filter(|w| w.chars().count() >= 3 && !is_affix_word(w))
.map(|w| w.chars().collect())
.collect();
let word_covered = |kname: &str| -> bool {
kname.split(' ').any(|kw| {
let kc: Vec<char> = kw.chars().collect();
q_content.iter().any(|qc| lev(&kc, qc) <= 1)
})
};
let Some(lev) = cached_levenshtein(&street_phrase, dist) else {
continue;
};
let mut stream = self.streets_fst.search((&*lev).starts_with()).into_stream();
let mut taken = 0;
while let Some((key, v)) = stream.next() {
let sep = match key.iter().position(|&b| b == KEY_SEP) {
Some(p) => p,
None => continue,
};
if !q_content.is_empty()
&& !word_covered(std::str::from_utf8(&key[..sep]).unwrap_or(""))
{
continue;
}
let insee = std::str::from_utf8(&key[sep + 1..]).unwrap_or("");
if let Some(ref allow) = allowed {
if !allow.iter().any(|a| a == insee) {
continue;
}
}
let sid = v as u32;
let m = self.street_meta(sid);
if let Some(pc) = postcode {
// postcode==0 in data is not a filter (see collect_candidates)
if allowed.is_none() && m.postcode != 0 && m.postcode / 1000 != pc / 1000 {
continue;
}
}
Self::add_cand(&mut cand, sid, mk_feats(&m));
taken += 1;
if taken >= 400 {
break;
}
}
if !cand.is_empty() && c > 0 {
break; // found with a known commune — good enough
}
}
cand
}
/// Hypothesis from digit token g0; greedy = consume the suffix too (up to 3 short
/// tokens glued without spaces, longest dictionary match wins).
fn build_hyp(&self, toks: &[&str], used: &[bool], g0: usize, greedy: bool) -> Hyp {
let numero: Option<u32> = toks[g0].parse().ok();
let mut consumed = vec![g0];
let mut rep: u32 = 0;
if greedy {
let mut s = String::new();
let mut extra: Vec<usize> = Vec::new();
let mut best: Option<(u32, usize)> = None;
let mut j = g0 + 1;
while j < toks.len() && !used[j] && extra.len() < 3 {
let t = toks[j];
let ok = !t.is_empty()
&& t.chars().count() <= 4
&& t.chars().all(|c| c.is_alphanumeric())
&& (t.chars().any(|c| c.is_ascii_digit()) || is_safe_house_rep(t));
if !ok {
break;
}
s.push_str(t);
extra.push(j);
if let Some(&rid) = self.rep_lookup.get(&s) {
best = Some((rid, extra.len()));
}
j += 1;
}
if let Some((rid, cnt)) = best {
rep = rid;
consumed.extend_from_slice(&extra[..cnt]);
}
}
let rest_idx = (0..toks.len())
.filter(|i| !used[*i] && !consumed.contains(i))
.collect();
Hyp {
numero,
rep,
rest_idx,
from_ml: false,
}
}
/// Hypothesis from the parsing model: token labels -> ready segmentation
/// (street and commune taken from labels, in street-then-commune order).
fn ml_hyp(&self, toks: &[&str], used: &[bool]) -> Option<Hyp> {
let parser = self.parser.as_ref()?;
let labels = parser.label(toks);
let mut street_idx: Vec<usize> = Vec::new();
let mut city_idx: Vec<usize> = Vec::new();
let mut numero: Option<u32> = None;
let mut rep_parts: Vec<&str> = Vec::new();
for i in 0..toks.len() {
if used[i] {
continue; // postcode already consumed
}
match labels[i] {
crate::ml::L_STREET => street_idx.push(i),
crate::ml::L_CITY => city_idx.push(i),
crate::ml::L_NUM => {
let d = toks[i].bytes().take_while(|b| b.is_ascii_digit()).count();
if numero.is_none() && d >= 1 {
numero = toks[i][..d].parse().ok();
if d < toks[i].len() {
rep_parts.push(&toks[i][d..]); // fused "12a"
}
} else {
// no leading digits (model misfired on an unfamiliar language)
// or a number already found — the token is more likely street
street_idx.push(i);
}
}
crate::ml::L_REP => rep_parts.push(toks[i]),
crate::ml::L_PC => {} // postcode already parsed by the heuristic
_ => street_idx.push(i),
}
}
if street_idx.is_empty() {
return None;
}
let rep = if rep_parts.is_empty() {
0
} else {
*self.rep_lookup.get(&rep_parts.concat()).unwrap_or(&0)
};
let mut rest_idx = street_idx;
rest_idx.extend(city_idx);
Some(Hyp {
numero,
rep,
rest_idx,
from_ml: true,
})
}
/// City aliases — ONLY if the target city exists in this index
/// (otherwise "2805 BG Gouda" would turn into "... beograd gouda").
fn expand_city_aliases(&self, q: &str) -> String {
let mut s = q.to_string();
for (alias, full) in &crate::rules::rules().city_alias {
let inside = format!(" {alias} ");
let tail = format!(" {alias}");
if !(s == *alias || s.ends_with(&tail) || s.contains(&inside)) {
continue;
}
if self.communes_fst.get(full.as_bytes()).is_none() {
continue;
}
if s == *alias {
s = (*full).to_string();
} else if let Some(rest) = s.strip_suffix(&tail) {
s = format!("{rest} {full}");
} else {
s = s.replace(&inside, &format!(" {full} "));
}
}
s
}
/// Conservative bare street+house surface from the ORIGINAL query. An explicit
/// comma context, postal token, city prefix or city suffix cannot be discarded
/// by later variant/retry parsing to enable the prominence prior.
fn de_cityless_street(raw: &str) -> Option<String> {
if raw.contains(',') {
return None;
}
let normalized = prepared_query_key(raw);
let mut tokens: Vec<_> = normalized.split_whitespace().collect();
let mut house = tokens.pop()?;
if house.len() == 1 && house.bytes().all(|c| c.is_ascii_alphabetic()) {
house = tokens.pop()?;
}
let digits = house.bytes().take_while(|c| c.is_ascii_digit()).count();
if digits == 0
|| digits > 4
|| !house[digits..].bytes().all(|c| c.is_ascii_alphabetic())
|| tokens.is_empty()
|| tokens.iter().any(|t| t.bytes().any(|c| c.is_ascii_digit()))
{
return None;
}
Some(street_key(&tokens.join(" ")))
}
/// One tie-break experiment: existing leaf address count before the weak
/// capital anchor, only for equal-quality bare DE house homonyms.
fn de_cityless_prominence(
hits: &mut [RankedHit],
country: Option<&str>,
original_street: Option<&str>,
focused: bool,
postcode: Option<u32>,
) {
let Some(top) = hits.first() else { return };
let key = street_key(&top.0.street);
let scope_allowed = country == Some("de")
&& !focused
&& postcode.is_none()
&& original_street == Some(key.as_str());
if !scope_allowed {
return;
}
let mut chosen = 0;
for (position, candidate) in hits.iter().enumerate().skip(1) {
let equal_address_evidence = top.0.precision == "house"
&& candidate.0.precision == "house"
&& top.1[0] > 0.5
&& candidate.1[0] > 0.5
&& street_key(&candidate.0.street) == key
&& candidate.0.score == top.0.score
&& candidate.2 == top.2
&& candidate.3 == top.3;
let more_prominent = candidate.4 > hits[chosen].4;
if equal_address_evidence && more_prominent {
chosen = position;
}
}
if chosen != 0 {
hits[..=chosen].rotate_right(1);
hits[0].0.flags.push("de_cityless_prominence");
}
}
pub fn query_feats(&self, raw: &str, k: usize) -> Vec<(Hit, [f32; N_FEATS])> {
if k == 0 {
return Vec::new(); // k=0 asks for zero results; the city-only fallback used to ignore it
}
let k = bound_k(k); // cap result count before it drives allocation/sort
let raw = bound_query(raw); // cap work before normalization
let _rules = crate::rules::scope(self.rules); // this file's tables, not another file's
let spelled = spelled_house_number(raw);
let raw = spelled.as_deref().unwrap_or(raw);
let mut hits = self.query_feats_street_data(raw, k, None);
hits = self.foreign_city_guard(raw, hits);
Self::strip_deferred_locality_drop(&mut hits);
Self::monotone_confidence(&mut hits);
hits
}
fn query_feats_near(
&self,
raw: &str,
k: usize,
lat: f64,
lon: f64,
) -> std::result::Result<Vec<(Hit, [f32; N_FEATS])>, String> {
validate_query_near(lat, lon)?;
if k == 0 {
return Ok(Vec::new());
}
let k = bound_k(k);
let raw = bound_query(raw);
let _rules = crate::rules::scope(self.rules);
let focus = QueryFocus {
lat,
lon,
streets: self.streets_around(lat, lon),
};
let mut hits = self.query_feats_street_data(raw, k, Some(&focus));
hits = self.foreign_city_guard(raw, hits);
Self::strip_deferred_locality_drop(&mut hits);
Self::monotone_confidence(&mut hits);
Ok(hits)
}
/// An optional vocabulary carried by this sheet guards only the first answer.
/// No fallback is attempted: uncertainty about the requested municipality abstains.
fn foreign_city_guard(
&self,
raw: &str,
hits: Vec<(Hit, [f32; N_FEATS])>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let Some((first, _)) = hits.first() else {
return hits;
};
if !matches!(first.precision, "house" | "interp" | "near" | "street") {
return hits;
}
let cfg = &self.rules.municipality_guard;
if cfg.is_empty() {
return hits;
}
let n = normalize(raw);
let toks: Vec<&str> = n.split_whitespace().collect();
let mut positions = Vec::new();
let mut off = 0;
for token in &toks {
let start = n[off..].find(token).unwrap() + off;
positions.push((start, start + token.len()));
off = start + token.len();
}
let words = |key: &str| -> HashSet<&str> {
cfg.get(key)
.map(|v| v.split_whitespace().collect())
.unwrap_or_default()
};
let streets = words("street_markers");
let districts = words("district_markers");
let regions = words("regions");
let mut street_ranges = Vec::new();
let mut district_ranges = Vec::new();
// The research grammar splits commas/semicolons/newlines and spaced dashes.
let chars: Vec<(usize, char)> = raw.char_indices().collect();
let mut boundaries = vec![0];
for (i, (pos, c)) in chars.iter().enumerate() {
if matches!(c, ',' | ';' | '\n')
|| (matches!(c, '-' | '–' | '—')
&& i > 0
&& i + 1 < chars.len()
&& chars[i - 1].1.is_whitespace()
&& chars[i + 1].1.is_whitespace())
{
boundaries.push(*pos);
boundaries.push(*pos + c.len_utf8());
}
}
boundaries.push(raw.len());
let mut offset = 0;
for pair in boundaries.windows(2) {
let z = normalize(&raw[pair[0]..pair[1]]);
if z.is_empty() {
continue;
}
let Some(relative) = n[offset..].find(&z) else {
continue;
};
let pos = offset + relative;
let ts: Vec<&str> = z.split_whitespace().collect();
let mut loc = 0;
let mut street = false;
let mut district = false;
for (i, t) in ts.iter().enumerate() {
let start = z[loc..].find(t).unwrap() + loc;
loc = start + t.len();
if !street && streets.contains(t) {
let end = ts[i + 1..]
.iter()
.find(|x| {
x.chars().next().is_some_and(|c| c.is_ascii_digit())
|| **x == "sn"
|| **x == "s"
})
.and_then(|x| z[loc..].find(x).map(|j| loc + j))
.unwrap_or(z.len());
street_ranges.push((pos + start, pos + end));
street = true;
}
if !district && districts.contains(t) {
district_ranges.push((pos + start, pos + z.len()));
district = true;
}
}
offset = pos + z.len();
}
let inside = |start: usize, ranges: &Vec<(usize, usize)>| {
ranges.iter().any(|(a, b)| *a <= start && start < *b)
};
let mut ufs: HashSet<String> = toks
.iter()
.enumerate()
.filter(|(i, t)| {
regions.contains(&t.to_uppercase().as_str())
&& !inside(positions[*i].0, &street_ranges)
})
.map(|(_, t)| t.to_uppercase())
.collect();
let phrase_in = |phrase: &str| format!(" {n} ").contains(&format!(" {phrase} "));
for (key, uf) in cfg {
if let Some(name) = key.strip_prefix("state:") {
if !cfg.contains_key(&format!("city:{name}")) && phrase_in(name) {
ufs.insert(uf.clone());
}
}
}
// (start, end, canonical name, permitted regions, exclusion).
let mut matches = Vec::new();
for i in 0..toks.len() {
for j in i..(i + 8).min(toks.len()) {
let name = &n[positions[i].0..positions[j].1];
let mut canonical = name.to_string();
if let Some(v) = cfg.get(&format!("alias:{name}")) {
canonical = v.clone();
}
if let Some(opts) = cfg.get(&format!("city:{canonical}")) {
matches.push((positions[i].0, positions[j].1, canonical, opts.clone(), 0u8));
}
}
}
let snapshot = matches.clone();
matches.retain(|m| {
!snapshot
.iter()
.any(|o| o.0 <= m.0 && o.1 >= m.1 && o.1 - o.0 > m.1 - m.0)
});
for m in &mut matches {
if inside(m.0, &street_ranges) {
m.4 = 1;
} else if inside(m.0, &district_ranges) {
m.4 = 2;
let tail = n[m.1..].trim();
let uf_tail = tail
.split_whitespace()
.next()
.is_some_and(|t| regions.contains(t.to_uppercase().as_str()))
&& tail
.split_whitespace()
.skip(1)
.all(|t| t.bytes().all(|c| c.is_ascii_digit()));
// A complete municipality field may itself begin with a district marker.
let complete = district_ranges.iter().any(|(a, b)| *a == m.0 && *b == m.1);
if uf_tail
|| (complete
&& ufs.len() == 1
&& m.3.split_whitespace().any(|uf| ufs.contains(uf)))
{
m.4 = 0;
}
}
if m.4 == 0 && !ufs.is_empty() && !m.3.split_whitespace().any(|uf| ufs.contains(uf)) {
m.4 = 3;
}
}
if ufs.is_empty() {
let snapshot = matches.clone();
for m in &mut matches {
if m.4 != 0 {
continue;
}
if let Some(uf) = cfg.get(&format!("state:{}", m.2)) {
if !snapshot.iter().any(|o| o.4 == 0 && o.2 == m.2 && o.0 > m.0)
&& snapshot.iter().any(|o| {
o.4 == 0
&& o.1 <= m.0
&& o.2 != m.2
&& o.3.split_whitespace().any(|u| u == uf)
})
{
m.4 = 4;
}
}
}
for m in &matches {
if m.4 == 4 {
ufs.insert(cfg[&format!("state:{}", m.2)].clone());
}
}
}
let mut cities = HashSet::new();
let mut names = HashSet::new();
for m in &matches {
if m.4 == 0 {
for uf in m.3.split_whitespace() {
if ufs.is_empty() || ufs.contains(uf) {
cities.insert((m.2.clone(), uf.to_string()));
names.insert(m.2.clone());
}
}
}
}
let mut ans = normalize(&first.commune);
if let Some(v) = cfg.get(&format!("alias:{ans}")) {
ans = v.clone();
}
// A city sharing its name with an explicit state remains possible when
// no municipality survives the UF filter (e.g. an island's homonym).
if names.is_empty()
&& cfg
.get(&format!("state:{ans}"))
.is_some_and(|uf| ufs.contains(uf))
&& !phrase_in(&ans)
{
return hits;
}
let reject = if !names.is_empty() && !names.contains(&ans) {
cities.len() == 1 && ufs.len() == 1
} else if !names.contains(&ans) {
matches.iter().any(|m| m.2 == ans && m.4 != 0)
|| phrase_in(&ans)
|| cfg
.get(&format!("state:{ans}"))
.is_some_and(|uf| ufs.contains(uf))
} else {
false
};
if reject {
Vec::new()
} else {
hits
}
}
fn de_effect_flags(effect: crate::de::Effect) -> &'static [&'static str] {
use crate::de::Effect;
match effect {
Effect::Orthography => &["de_umlaut"],
Effect::CityAlias => &["de_city_alias"],
Effect::OfficialCommuneAlias => &["de_official_commune_alias"],
Effect::Abbreviation => &["de_abbrev"],
Effect::AdminTail => &["de_admin_tail"],
Effect::RecipientPrefix => &["de_recipient_prefix"],
Effect::SubaddressTail => &["de_subaddress_tail"],
Effect::ParentheticalSubaddress => &["de_parenthetical_subaddress"],
Effect::AddressField => &["de_address_field"],
Effect::LocalityFirst => &["de_locality_first"],
Effect::MissingCommaPostcodeBoundary => &["de_missing_postcode_comma"],
Effect::Country => &["de_country"],
Effect::HouseRange => &["de_house_range"],
Effect::HouseSlash => &["de_house_slash"],
Effect::PostcodePrefix => &["de_country", "de_postcode"],
Effect::PostcodeZero => &["de_postcode"],
}
}
fn annotate_de_effects(hits: &mut [(Hit, [f32; N_FEATS])], effects: &[crate::de::Effect]) {
for (hit, _) in hits {
for effect in effects {
for flag in Self::de_effect_flags(*effect) {
if !hit.flags.contains(flag) {
hit.flags.push(flag);
}
}
}
}
}
fn strip_deferred_locality_drop(hits: &mut [(Hit, [f32; N_FEATS])]) {
for (hit, _) in hits {
hit.flags.retain(|flag| *flag != DEFERRED_LOCALITY_DROP);
}
}
fn de_variant_quality(hits: &[(Hit, [f32; N_FEATS])]) -> Option<(i32, u8, u8, f32)> {
let (hit, features) = hits.first()?;
let precision = match hit.precision {
"house" => 4,
"interp" => 3,
"near" => 2,
"street" => 1,
_ => 0,
};
Some((
if hit.flags.contains(&DEFERRED_LOCALITY_DROP) {
i32::MIN
} else {
Feats::from_vec(features).legacy()
},
precision,
u8::from(!hit.flags.contains(&"dropped_suffix")),
hit.score,
))
}
fn de_quality_is_better(candidate: (i32, u8, u8, f32), current: (i32, u8, u8, f32)) -> bool {
candidate.0 > current.0
|| (candidate.0 == current.0 && candidate.1 > current.1)
|| (candidate.0 == current.0 && candidate.1 == current.1 && candidate.2 > current.2)
|| (candidate.0 == current.0
&& candidate.1 == current.1
&& candidate.2 == current.2
&& candidate.3 > current.3)
}
fn de_official_commune_alias_candidate_is_exact(candidate: &[(Hit, [f32; N_FEATS])]) -> bool {
candidate.first().is_some_and(|(hit, _)| {
hit.precision == "house"
&& hit.flags.contains(&"street_exact")
&& hit.flags.contains(&"house_rep")
})
}
fn de_ludwigshafen_official_alias_candidate_position(
raw: &str,
candidate: &[(Hit, [f32; N_FEATS])],
) -> Option<usize> {
let spec = de_strict_source_street_typo_spec(raw)?;
if spec.normalized_locality != "ludwigshafen rhein" {
return None;
}
// `query_feats_d` is bounded at 20 for a hard commune. Hitting the cap
// cannot prove that another eligible address is not hidden below it.
if candidate.len() >= 20 {
return None;
}
let expected_house = spec.house_number.to_string();
let mut eligible =
candidate
.iter()
.enumerate()
.filter_map(|(position, (hit, features))| {
let features = Feats::from_vec(features);
(hit.precision == "house"
&& features.street_exact
&& features.house_exact_rep
// The product row may legitimately carry no postcode.
// Missing evidence is not a disagreement; a populated
// row still needs exact or department-level agreement.
&& (hit.postcode.is_empty() || features.pc_exact || features.pc_dept)
&& de_product_normalize_street(&hit.street) == spec.normalized_street
&& de_product_normalize_text(&hit.commune) == "ludwigshafen am rhein"
&& hit.housenumber.as_deref() == Some(expected_house.as_str()))
.then_some(position)
});
let position = eligible.next()?;
eligible.next().is_none().then_some(position)
}
/// Return the single rank in the bounded established result window that
/// satisfies the X2 product predicate. No score, coordinate, benchmark
/// outcome or roster identity participates in this decision.
fn de_street_locality_qualifier_position(
raw: &str,
current: &[(Hit, [f32; N_FEATS])],
) -> Option<usize> {
let spec = de_street_locality_qualifier_spec(raw)?;
let (top, top_features) = current.first()?;
let top_features = Feats::from_vec(top_features);
if top.precision != "house"
|| !top_features.street_exact
|| !top_features.house_exact_rep
|| !top_features.pc_dept
|| top_features.pc_exact
|| !is_five_digit_postcode(&top.postcode)
|| top.postcode == spec.postcode_raw
|| de_product_normalize_street(&top.street) != spec.normalized_street
|| !de_house_token_matches(top, &spec.house_token)
{
return None;
}
let mut eligible =
current
.iter()
.take(5)
.enumerate()
.skip(1)
.filter_map(|(position, (hit, features))| {
let features = Feats::from_vec(features);
let (base, qualifier) = de_source_street_locality_qualifier(&hit.street)?;
let source_commune = de_product_normalize_text(&hit.commune);
(hit.precision == "house"
&& features.street_exact
&& features.house_exact_rep
&& hit.postcode.is_empty()
&& de_house_token_matches(hit, &spec.house_token)
&& base == spec.normalized_street
&& qualifier == spec.normalized_locality
&& de_locality_is_exact_or_query_prefix(
&spec.normalized_locality,
&source_commune,
))
.then_some(position)
});
let position = eligible.next()?;
eligible.next().is_none().then_some(position)
}
/// A parenthetical building/subaddress label is an additive, fill-empty
/// hypothesis only. It may never replace an ordinary result, and even an
/// empty ordinary path is filled only by the top exact street+house in the
/// exact retained terminal commune core.
fn de_parenthetical_subaddress_may_fill(
current: &[(Hit, [f32; N_FEATS])],
candidate: &[(Hit, [f32; N_FEATS])],
expected_commune: Option<&str>,
) -> bool {
if !current.is_empty() {
return false;
}
let (Some(expected_commune), Some((hit, features))) = (expected_commune, candidate.first())
else {
return false;
};
let features = Feats::from_vec(features);
hit.precision == "house"
&& features.street_exact
&& features.house_exact_rep
&& de_commune_core(&hit.commune) == expected_commune
}
/// A comma-delimited recipient prefix is direct syntax evidence that every
/// token after the comma belongs to the address. When that exact cleanup
/// produces the same street+house quality as a generic candidate that had
/// to drop a street-name prefix, preserve the full typed street. This is a
/// deliberately narrow tie-break: it cannot promote fuzzy/near candidates
/// and it is unavailable without the exact recipient-prefix predicate.
fn de_recipient_cleanup_breaks_dropped_prefix_tie(
candidate: &[(Hit, [f32; N_FEATS])],
current: &[(Hit, [f32; N_FEATS])],
) -> bool {
let (Some((candidate_hit, candidate_features)), Some((current_hit, current_features))) =
(candidate.first(), current.first())
else {
return false;
};
let candidate_features = Feats::from_vec(candidate_features);
let current_features = Feats::from_vec(current_features);
!candidate_hit.flags.contains(&"dropped_prefix")
&& current_hit.flags.contains(&"dropped_prefix")
&& candidate_features.street_exact
&& candidate_features.house_exact_rep
&& current_features.street_exact
&& current_features.house_exact_rep
}
fn de_abbreviation_candidate_may_displace(
candidate: &[(Hit, [f32; N_FEATS])],
current: &[(Hit, [f32; N_FEATS])],
original_postcode_tail: Option<&str>,
) -> bool {
#[cfg(test)]
DE_ABBREVIATION_GUARD_CALLS.with(|calls| calls.set(calls.get().saturating_add(1)));
if current.is_empty() {
return true;
}
let Some((candidate_hit, candidate_features)) = candidate.first() else {
return false;
};
let candidate_features = Feats::from_vec(candidate_features);
let current_features = Feats::from_vec(¤t[0].1);
if candidate_hit.flags.contains(&"dropped_prefix") {
return candidate_features.street_exact
&& candidate_features.house_exact_rep
&& (candidate_features.pc_exact || candidate_features.commune_exact);
}
if candidate_features.commune_prefix
&& !candidate_features.commune_exact
&& !current_features.commune_prefix
&& !current_features.commune_exact
{
let precision = |hit: &Hit| match hit.precision {
"house" => 3,
"interp" => 2,
"near" => 1,
_ => 0,
};
let candidate_evidence = [
u8::from(candidate_features.pc_exact),
u8::from(candidate_features.street_exact),
u8::from(candidate_features.house_exact_rep),
precision(candidate_hit),
];
let current_evidence = [
u8::from(current_features.pc_exact),
u8::from(current_features.street_exact),
u8::from(current_features.house_exact_rep),
precision(¤t[0].0),
];
let no_regression = candidate_evidence
.iter()
.zip(current_evidence)
.all(|(candidate, current)| *candidate >= current);
let strict_gain = candidate_evidence
.iter()
.zip(current_evidence)
.any(|(candidate, current)| *candidate > current);
if no_regression && strict_gain {
return true;
}
// An abbreviation may expose the canonical street spelling without adding
// postcode evidence. When exact street+house evidence otherwise ties, only
// the locality text the user actually supplied may break that tie; the
// variant's synthetic commune_prefix bit alone is not sufficient.
let Some(postcode_tail) = original_postcode_tail else {
return false;
};
return no_regression
&& candidate_features.street_exact
&& candidate_features.house_exact_rep
&& de_retained_locality_score(postcode_tail, &candidate_hit.commune)
> de_retained_locality_score(postcode_tail, ¤t[0].0.commune);
}
true
}
fn de_has_complete_postcode_house_evidence(hits: &[(Hit, [f32; N_FEATS])]) -> bool {
hits.first().is_some_and(|(_, features)| {
let features = Feats::from_vec(features);
features.street_exact && features.house_exact_rep && features.pc_exact
})
}
/// Wave A is a post-failure correction, never a fill-empty fallback. The
/// ordinary path must already have produced an exact-street address-level
/// result. A represented house is eligible only when its postcode is not
/// the explicit query postcode; near/interp is eligible because a uniquely
/// proven exact indexed house is strictly stronger at the same address key.
fn de_strict_postcode_house_override_allowed(
hits: &[(Hit, [f32; N_FEATS])],
requested_postcode: u32,
) -> bool {
let Some((hit, features)) = hits.first() else {
return false;
};
let features = Feats::from_vec(features);
match hit.precision {
"house" => {
features.street_exact
&& features.house_exact_rep
&& Self::postcode_numeric_prefix(&hit.postcode) != Some(requested_postcode)
}
"near" | "interp" => {
Self::postcode_numeric_prefix(&hit.postcode) == Some(requested_postcode)
|| (features.street_exact
&& Self::postcode_numeric_prefix(&hit.postcode) != Some(requested_postcode))
}
_ => false,
}
}
fn de_should_try_postcode_house_rescue(raw: &str, hits: &[(Hit, [f32; N_FEATS])]) -> bool {
// A mechanically restored comma is only a structural hypothesis until
// the exact street+house+postcode rescue proves it against the sheet.
// Run that proof even when the ordinary parser happened to produce a
// complete hit, so the result never depends on index insertion order.
if crate::de::query_variants(raw).iter().any(|variant| {
variant
.effects
.contains(&crate::de::Effect::MissingCommaPostcodeBoundary)
}) {
return true;
}
if !Self::de_has_complete_postcode_house_evidence(hits) {
return true;
}
if !hits
.first()
.is_some_and(|(hit, _)| hit.flags.contains(&"dropped_prefix"))
{
return false;
}
de_comma_postcode_house_rescue_query(raw).is_some_and(|(_, postcode, locality)| {
de_is_exact_locality_alias_query(&locality, postcode)
})
}
fn de_postcode_house_locality_score(
locality_tail: &str,
hard_commune: Option<&str>,
requested_postcode: u32,
commune: &str,
) -> u8 {
if let Some(expected) = hard_commune {
let actual = de_commune_core(commune);
return if actual == expected
|| (expected == "frankfurt oder"
&& actual == "frankfurt"
&& requested_postcode == 15230)
{
4
} else {
0
};
}
let retained = de_retained_locality_score(locality_tail, commune);
if retained == 2 {
return 4;
}
let query = normalize(locality_tail);
let candidate = de_commune_core(commune);
if de_exact_locality_alias_matches(locality_tail, requested_postcode, commune) {
return 3;
}
if query == "berlin"
&& !de_is_exact_locality_alias_query(locality_tail, requested_postcode)
&& de_is_proven_berlin_postcode(requested_postcode)
&& de_is_berlin_postal_locality(commune)
{
return 3;
}
if retained != 0
|| de_locality_qualifiers_match(locality_tail, commune)
|| de_p3_locality_compatible(&query, &candidate)
{
return 1;
}
0
}
fn de_postcode_house_locality_compatible(
&self,
locality_tail: &str,
hard_commune: Option<&str>,
requested_postcode: u32,
hit: &Hit,
) -> bool {
Self::de_postcode_house_locality_score(
locality_tail,
hard_commune,
requested_postcode,
&hit.commune,
) != 0
}
/// Product-visible proof that the typed postcode contains at least one
/// indexed street in a compatible locality. The exact-postcode roster is
/// bounded by the same fail-closed scan ceiling as the house rescue.
fn de_postcode_has_locality_support(
&self,
requested_postcode: u32,
locality_tail: &str,
) -> bool {
self.de_postcode_street_bucket(requested_postcode)
.is_some_and(|bucket| {
bucket.iter().any(|&(_, sid)| {
let metadata = self.street_meta(sid);
Self::de_postcode_house_locality_score(
locality_tail,
None,
requested_postcode,
self.commune_name(metadata.commune_id),
) != 0
})
})
}
/// A near/interpolation matching the locality in a typed-postcode request
/// already carries product-visible locality evidence, even when that weak
/// hit has no display postcode. Wave N permits the strict exact-house
/// replacement only when its indexed commune is compatible with the same
/// typed locality. Wrong-postcode exact-house corrections remain the
/// independent P1 rule and do not acquire a synthetic constraint here.
fn de_typed_postcode_near_has_locality_evidence(
&self,
hits: &[(Hit, [f32; N_FEATS])],
requested_postcode: u32,
locality_tail: &str,
) -> bool {
hits.first().is_some_and(|(hit, features)| {
let features = Feats::from_vec(features);
let postcode_supports_locality = Self::postcode_numeric_prefix(&hit.postcode)
== Some(requested_postcode)
|| (hit.postcode.trim().is_empty()
&& self.de_postcode_has_locality_support(requested_postcode, locality_tail));
matches!(hit.precision, "near" | "interp")
&& features.street_exact
&& postcode_supports_locality
&& self.de_postcode_house_locality_compatible(
locality_tail,
None,
requested_postcode,
hit,
)
})
}
fn de_blank_postcode_current_top_is_strict(
current: &[(Hit, [f32; N_FEATS])],
spec: &DeBlankPostcodeHouseSpec,
) -> bool {
let Some((hit, features)) = current.first() else {
return false;
};
let features = Feats::from_vec(features);
let relies_on_disallowed_cleanup = [
"dropped_prefix",
"dropped_suffix",
"de_city_alias",
"de_official_commune_alias",
]
.iter()
.any(|flag| hit.flags.contains(flag));
matches!(hit.precision, "near" | "interp")
&& features.street_exact
&& features.commune_exact
&& features.pc_exact
&& !features.house_exact_rep
&& hit.postcode == spec.postcode_raw
&& de_product_normalize_street(&hit.street) == spec.normalized_street
&& de_product_normalize_text(&hit.commune) == spec.normalized_locality
&& !relies_on_disallowed_cleanup
}
/// Anchor P5 to one exact product-visible commune identity already proven
/// by the typed postcode roster. Prefix/alias/district compatibility is
/// intentionally absent: two commune ids with the same display name are
/// ambiguous and therefore fail closed.
fn de_blank_postcode_anchor_commune_id(&self, spec: &DeBlankPostcodeHouseSpec) -> Option<u32> {
let mut commune_ids: Vec<u32> = self
.de_postcode_street_bucket(spec.postcode)?
.iter()
.filter_map(|&(_, sid)| {
let metadata = self.street_meta(sid);
(de_product_normalize_street(self.name(metadata.name_off))
== spec.normalized_street
&& de_product_normalize_text(self.commune_name(metadata.commune_id))
== spec.normalized_locality)
.then_some(metadata.commune_id)
})
.collect();
commune_ids.sort_unstable();
commune_ids.dedup();
let [commune_id] = commune_ids.as_slice() else {
return None;
};
Some(*commune_id)
}
/// Wave O/P5: replace only a fully evidenced typed-postcode near/interp
/// with one physical exact-house row whose source postcode is genuinely
/// absent. Admission is driven by exact display fields, a single anchored
/// commune id, exact number+suffix, and full source-row uniqueness. No
/// non-request selector participates.
fn de_blank_postcode_exact_house_fallback(
&self,
raw: &str,
current: &[(Hit, [f32; N_FEATS])],
k: usize,
focus: Option<&QueryFocus>,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
if self.country() != Some("de") || self.format_version < 7 || focus.is_some() {
return None;
}
let spec = de_blank_postcode_house_spec(raw)?;
if !Self::de_blank_postcode_current_top_is_strict(current, &spec) {
return None;
}
let requested_rep = if spec.house_suffix.is_empty() {
0
} else {
*self.rep_lookup.get(&spec.house_suffix)?
};
let anchor_commune_id = self.de_blank_postcode_anchor_commune_id(&spec)?;
let candidate_sids = self
.de_blank_postcode_display_streets
.get(&spec.normalized_street, &spec.normalized_locality)?;
let scan_limit = de_postcode_house_rescue_scan_limit();
if candidate_sids.is_empty() || candidate_sids.len() > scan_limit {
return None;
}
let mut row_budget = scan_limit;
let mut exact_records: Vec<(u32, String)> = Vec::new();
for &sid in candidate_sids.iter() {
let metadata = self.street_meta(sid);
if de_product_normalize_street(self.name(metadata.name_off)) != spec.normalized_street
|| de_product_normalize_text(self.commune_name(metadata.commune_id))
!= spec.normalized_locality
{
continue;
}
let postcodes = self
.de_exact_house_record_postcodes(
sid,
&metadata,
spec.house_number,
requested_rep,
&mut row_budget,
)
.ok()?;
for postcode in postcodes {
exact_records.push((sid, postcode));
if exact_records.len() > 1 {
return None;
}
}
}
let [(sid, postcode)] = exact_records.as_slice() else {
return None;
};
let metadata = self.street_meta(*sid);
if metadata.commune_id != anchor_commune_id
|| !postcode.is_empty()
|| metadata.postcode != 0
|| metadata.postcode_disp_off != 0
{
return None;
}
let query_words: Vec<Vec<char>> = spec
.normalized_street
.split_whitespace()
.map(|word| word.chars().collect())
.collect();
let features = Feats {
street_exact: true,
commune_exact: true,
..Default::default()
};
let (mut hit, feature_vector, _, _, _, _) = self.make_hit(
*sid,
features,
Some(spec.house_number),
requested_rep,
None,
&query_words,
);
let made_features = Feats::from_vec(&feature_vector);
let expected_house = self.house_number(spec.house_number, requested_rep);
if hit.precision != "house"
|| hit.housenumber.as_deref() != Some(expected_house.as_str())
|| !hit.postcode.is_empty()
|| de_product_normalize_street(&hit.street) != spec.normalized_street
|| de_product_normalize_text(&hit.commune) != spec.normalized_locality
|| !made_features.street_exact
|| !made_features.commune_exact
|| !made_features.house_exact_rep
|| made_features.pc_exact
|| made_features.pc_dept
{
return None;
}
if !hit.flags.contains(&"de_blank_postcode_house_override") {
hit.flags.push("de_blank_postcode_house_override");
}
let mut exact = vec![(hit, feature_vector)];
exact.truncate(k);
Some(exact)
}
fn de_product_fallback_arbitration(
best: &mut Vec<(Hit, [f32; N_FEATS])>,
p3: Option<Vec<(Hit, [f32; N_FEATS])>>,
p4: Option<Vec<(Hit, [f32; N_FEATS])>>,
x2: Option<usize>,
p5: Option<Vec<(Hit, [f32; N_FEATS])>>,
) {
match (p3, p4, x2, p5) {
(Some(candidate), None, None, None)
| (None, Some(candidate), None, None)
| (None, None, None, Some(candidate)) => *best = candidate,
(None, None, Some(position), None) if position < best.len() => {
let mut chosen = best.remove(position);
if !chosen.0.flags.contains(&"de_street_locality_qualifier") {
chosen.0.flags.push("de_street_locality_qualifier");
}
best.insert(0, chosen);
}
// P3, P4, P5 and X2 are intended to be disjoint typed mechanisms.
// If a future parser change creates overlap, preserve the
// established result instead of choosing by order or data order.
_ => {}
}
}
fn de_p3_current_top_already_complete(
current: &[(Hit, [f32; N_FEATS])],
spec: &DeStrictSourceStreetTypoSpec,
) -> bool {
let expected_house = spec.house_number.to_string();
current.first().is_some_and(|(hit, _)| {
hit.precision == "house"
&& hit.housenumber.as_deref() == Some(expected_house.as_str())
&& hit.postcode == spec.postcode_raw
})
}
/// A strict P3 request may name a postcode for which an older or partial
/// index has no exact-postcode street roster at all. In that case P3
/// cannot manufacture the requested address, but it also must not retain
/// a same-house hit contradicted by both of the user's explicit locality
/// and postcode fields. An empty row postcode is unknown, not a
/// contradiction. This is deliberately a narrow fail-closed filter: a
/// hit compatible with either explicit field is preserved.
fn de_p3_filter_absent_postcode_conflicts(
current: &[(Hit, [f32; N_FEATS])],
spec: &DeStrictSourceStreetTypoSpec,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let expected_house = spec.house_number.to_string();
let mut removed = false;
let retained = current
.iter()
.filter_map(|(hit, features)| {
let same_house = hit.housenumber.as_deref() == Some(expected_house.as_str());
let postcode_conflicts =
!hit.postcode.is_empty() && hit.postcode != spec.postcode_raw;
let source_locality = de_product_normalize_text(&hit.commune);
let product_alias_proves_locality = hit.flags.contains(&"de_city_alias")
|| hit.flags.contains(&"de_official_commune_alias");
let locality_conflicts = !product_alias_proves_locality
&& !de_p3_locality_compatible(&spec.normalized_locality, &source_locality);
if same_house && postcode_conflicts && locality_conflicts {
removed = true;
None
} else {
Some((
Hit {
lat: hit.lat,
lon: hit.lon,
precision: hit.precision,
score: hit.score,
confidence: hit.confidence,
street: hit.street.clone(),
housenumber: hit.housenumber.clone(),
commune: hit.commune.clone(),
postcode: hit.postcode.clone(),
flags: hit.flags.clone(),
region: hit.region.clone(),
distance_m: hit.distance_m,
},
*features,
))
}
})
.collect();
removed.then_some(retained)
}
/// P3 is not the generic fuzzy collector. Its bounded exact-postcode
/// roster is independent of source FST keys; admission proves the exact
/// source house/postcode, compatible locality, one global display-street
/// identity, first codepoint, compact OSA 1..=2 and the frozen 0.90 ratio.
fn de_strict_source_street_typo_fallback(
&self,
raw: &str,
current: &[(Hit, [f32; N_FEATS])],
k: usize,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let spec = de_strict_source_street_typo_spec(raw)?;
if Self::de_p3_current_top_already_complete(current, &spec) {
return None;
}
let mut exact_cache = HashMap::new();
let mut candidates: HashMap<String, Vec<(u32, bool)>> = HashMap::new();
// The source FST key is intentionally absent from this loop: the
// product predicate is defined over display street + exact index
// metadata, and must see a qualifying identity even behind a stale or
// unrelated `nom_voie_norm` key.
let Some(postcode_streets) = self.de_postcode_street_bucket(spec.postcode) else {
return Self::de_p3_filter_absent_postcode_conflicts(current, &spec);
};
for &(_, sid) in postcode_streets {
let metadata = self.street_meta(sid);
let source_street = de_product_normalize_street(self.name(metadata.name_off));
if source_street.is_empty()
|| source_street.len() > 96
|| source_street == spec.normalized_street
|| source_street
.bytes()
.next()
.zip(spec.normalized_street.bytes().next())
.is_none_or(|(source, query)| source != query)
{
continue;
}
let distance = de_compact_osa_distance(&spec.normalized_street, &source_street);
if !(1..=2).contains(&distance)
|| !de_sequence_matcher_ratio_at_least_090(&spec.normalized_street, &source_street)
{
continue;
}
let source_commune = de_product_normalize_text(self.commune_name(metadata.commune_id));
if !de_p3_locality_compatible(&spec.normalized_locality, &source_commune)
|| !self.exact_house_full_postcode_set_candidate_cached(
&mut exact_cache,
sid,
&metadata,
spec.house_number,
0,
&[],
spec.postcode,
&spec.postcode_raw,
)
{
continue;
}
candidates
.entry(source_street)
.or_default()
.push((sid, source_commune == spec.normalized_locality));
}
if candidates.len() != 1 {
return None;
}
let mut identity = candidates.into_values().next()?;
identity.sort_by_key(|candidate| candidate.0);
identity.dedup_by_key(|candidate| candidate.0);
// The predicate requires one semantic street identity, not one physical
// row. Multiple exact rows with the same allowed display projection do
// not change admission; the lowest stable SID only chooses the output.
let (sid, commune_exact) = *identity.first()?;
let query_words: Vec<Vec<char>> = spec
.normalized_street
.split_whitespace()
.map(|word| word.chars().collect())
.collect();
let features = Feats {
street_fuzzy: true,
commune_exact,
commune_prefix: !commune_exact,
pc_exact: true,
pc_dept: true,
..Default::default()
};
let mut ranked = self.make_hit(
sid,
features,
Some(spec.house_number),
0,
Some(spec.postcode),
&query_words,
);
let made_features = Feats::from_vec(&ranked.1);
if ranked.0.precision != "house"
|| !made_features.house_exact_rep
|| !made_features.pc_exact
|| ranked.0.housenumber.as_deref() != Some(spec.house_number.to_string().as_str())
|| ranked.0.postcode != spec.postcode_raw
{
return None;
}
if !ranked.0.flags.contains(&"de_strict_source_street_typo") {
ranked.0.flags.push("de_strict_source_street_typo");
}
let mut exact = vec![(ranked.0, ranked.1)];
exact.truncate(k);
Some(exact)
}
/// P4 accepts only one of four typed raw syntaxes. Once parsed, it scans
/// the complete bounded typed-postcode bucket and re-proves exact display
/// street/locality plus the full house/set/postcode contract. Recall is
/// therefore independent of the spelling used by an internal source FST
/// key, while ambiguity and bucket overflow still fail closed.
fn de_audited_compound_fallback(
&self,
raw: &str,
k: usize,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let spec = de_audited_compound_spec(raw)?;
let mut street_forms = de_product_street_forms(&spec.street);
if !street_forms.contains(&spec.normalized_street) {
street_forms.push(spec.normalized_street.clone());
}
if street_forms.len() > 32 {
return None;
}
let commune_ids = self.communes_by_name(&spec.normalized_locality);
if commune_ids.is_empty() || commune_ids.len() > 16 {
return None;
}
if street_forms
.len()
.checked_mul(commune_ids.len())
.is_none_or(|attempts| attempts > 64)
{
return None;
}
let postcode_streets = self.de_postcode_street_bucket(spec.postcode)?;
let mut exact_cache = HashMap::new();
let mut candidate_sids = Vec::new();
for &(_, sid) in postcode_streets {
#[cfg(test)]
DE_P4_POSTCODE_BUCKET_SCAN_ROWS.with(|rows| {
rows.set(rows.get().saturating_add(1));
});
let metadata = self.street_meta(sid);
if de_product_normalize_text(self.commune_name(metadata.commune_id))
!= spec.normalized_locality
|| de_product_normalize_street(self.name(metadata.name_off))
!= spec.normalized_street
|| !self.exact_house_full_postcode_set_candidate_cached(
&mut exact_cache,
sid,
&metadata,
spec.primary_house,
0,
&spec.additional_houses,
spec.postcode,
&spec.postcode_raw,
)
{
continue;
}
#[cfg(test)]
DE_P4_POSTCODE_BUCKET_MATCHING_SIDS.with(|matches| {
matches.set(matches.get().saturating_add(1));
});
candidate_sids.push(sid);
}
candidate_sids.sort_unstable();
candidate_sids.dedup();
let [sid] = candidate_sids.as_slice() else {
return None;
};
let query_words: Vec<Vec<char>> = spec
.normalized_street
.split_whitespace()
.map(|word| word.chars().collect())
.collect();
let features = Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
};
let (mut hit, feature_vector, _, _, _, _) = self.make_hit(
*sid,
features,
Some(spec.primary_house),
0,
Some(spec.postcode),
&query_words,
);
let made_features = Feats::from_vec(&feature_vector);
let expected_house = spec.primary_house.to_string();
if hit.precision != "house"
|| hit.housenumber.as_deref() != Some(expected_house.as_str())
|| hit.postcode != spec.postcode_raw
|| de_product_normalize_text(&hit.commune) != spec.normalized_locality
|| de_product_normalize_street(&hit.street) != spec.normalized_street
|| !made_features.street_exact
|| !made_features.house_exact_rep
|| !made_features.pc_exact
{
return None;
}
if !hit.flags.contains(&"de_audited_compound") {
hit.flags.push("de_audited_compound");
}
if matches!(
spec.shape,
DeAuditedCompoundShape::StreetHouseRangeBalancedAccessParenthetical
) {
hit.flags.push("de_house_set_exact");
}
let mut exact = vec![(hit, feature_vector)];
exact.truncate(k);
Some(exact)
}
fn de_comma_postcode_house_rescue(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
if de_parenthetical_locality_uses_slash_qualifier(raw) {
return None;
}
// The parser itself remains deliberately narrow. Let the bounded DE
// structural variants first remove only proven recipient/subaddress
// noise or reorder the exact locality-first shape, then require the
// same unique exact street+house+postcode proof as a canonical query.
for variant in crate::de::query_variants(raw) {
let Some((query, postcode, locality_tail)) =
de_comma_postcode_house_rescue_query(&variant.query)
else {
continue;
};
let Some(mut exact) = self.de_postcode_house_rescue_parsed(
raw,
&query,
postcode,
&locality_tail,
k,
focus,
None,
&[],
false,
) else {
continue;
};
Self::annotate_de_effects(&mut exact, &variant.effects);
return Some(exact);
}
None
}
fn de_compact_house_pair_left_rescue(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let (query, postcode, locality_tail, effect) =
de_compact_house_pair_left_rescue_query(raw)?;
self.de_postcode_house_rescue_parsed(
raw,
&query,
postcode,
&locality_tail,
k,
focus,
Some(effect),
&[],
false,
)
}
/// A strict, product-only Wave-A override. It is intentionally narrower
/// than the delivery-cleanup rescue: only a canonical comma form or one
/// compact two-endpoint literal is admitted. Soft locality text may lose
/// only after the runtime index proves one unique exact street/house-set/PLZ
/// candidate; Frankfurt and variant-required communes remain hard guards.
fn de_strict_postcode_house_set_override(
&self,
raw: &str,
current: &[(Hit, [f32; N_FEATS])],
k: usize,
focus: Option<&QueryFocus>,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let mut exact = if let Some((query, postcode, locality_tail)) =
de_comma_postcode_house_rescue_query(raw)
{
if !Self::de_strict_postcode_house_override_allowed(current, postcode) {
return None;
}
let allow_soft_locality_override = !self.de_typed_postcode_near_has_locality_evidence(
current,
postcode,
&locality_tail,
);
self.de_postcode_house_rescue_parsed(
raw,
&query,
postcode,
&locality_tail,
k,
focus,
None,
&[],
allow_soft_locality_override,
)?
} else {
let spec = de_compact_house_pair_spec(raw)?;
if !Self::de_strict_postcode_house_override_allowed(current, spec.postcode) {
return None;
}
let allow_soft_locality_override = !self.de_typed_postcode_near_has_locality_evidence(
current,
spec.postcode,
&spec.locality_tail,
);
self.de_postcode_house_rescue_parsed(
raw,
&spec.query,
spec.postcode,
&spec.locality_tail,
k,
focus,
Some(spec.effect),
&[spec.right],
allow_soft_locality_override,
)?
};
for (hit, _) in &mut exact {
if !hit.flags.contains(&"de_exact_postcode_override") {
hit.flags.push("de_exact_postcode_override");
}
}
Some(exact)
}
// Frozen release: grouping parsed rescue inputs would rewrite the validated call sites.
#[allow(clippy::too_many_arguments)]
fn de_postcode_house_rescue_parsed(
&self,
raw: &str,
query: &str,
postcode: u32,
locality_tail: &str,
k: usize,
focus: Option<&QueryFocus>,
structural_effect: Option<crate::de::Effect>,
additional_exact_house_numbers: &[u32],
allow_soft_locality_override: bool,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let hard_commune = crate::de::frankfurt_qualifier(raw).or_else(|| {
let words: std::collections::HashSet<&str> = locality_tail.split_whitespace().collect();
if words.contains("frankfurt") && words.contains("oder") {
Some("frankfurt oder")
} else if words.contains("frankfurt") && words.contains("main") {
Some("frankfurt am main")
} else {
None
}
});
let mut exact: Vec<DePostcodeHouseCandidate> = Vec::new();
let mut scan_budget = de_postcode_house_rescue_scan_limit();
let mut prepared_seen = HashSet::new();
let mut seen_phrases = HashSet::new();
for variant in crate::de::query_variants(query) {
let prepared = prepared_query_key(&variant.query);
if !prepared_seen.insert(prepared.clone()) {
continue;
}
let mut candidate = match self.query_feats_prepared_postcode_house_rescue(
&prepared,
k.max(20),
focus,
additional_exact_house_numbers,
&mut scan_budget,
&mut seen_phrases,
) {
Ok(candidate) => candidate,
Err(()) => return None,
};
if let Some(expected) = variant.required_commune.as_deref() {
candidate.retain(|candidate| normalize(&candidate.hit.commune) == expected);
}
candidate.retain(|candidate| {
let hit = &candidate.hit;
let features = Feats::from_vec(&candidate.features);
features.street_exact
&& features.house_exact_rep
&& features.pc_exact
&& Self::postcode_numeric_prefix(&hit.postcode) == Some(postcode)
&& ((allow_soft_locality_override && hard_commune.is_none())
|| self.de_postcode_house_locality_compatible(
locality_tail,
hard_commune,
postcode,
hit,
))
});
let mut applied_effects = variant.effects.clone();
if let Some(effect) = structural_effect {
if !applied_effects.contains(&effect) {
applied_effects.push(effect);
}
}
for candidate in &mut candidate {
for effect in &applied_effects {
for flag in Self::de_effect_flags(*effect) {
if !candidate.hit.flags.contains(flag) {
candidate.hit.flags.push(flag);
}
}
}
}
for item in candidate {
if let Some(existing) = exact
.iter()
.find(|existing| existing.source_sid == item.source_sid)
{
if !existing.same_product_projection(&item) {
return None;
}
} else {
exact.push(item);
}
}
}
if structural_effect.is_none() && (!allow_soft_locality_override || hard_commune.is_some())
{
let strongest = exact
.iter()
.map(|candidate| {
Self::de_postcode_house_locality_score(
locality_tail,
hard_commune,
postcode,
&candidate.hit.commune,
)
})
.max()
.unwrap_or(0);
if strongest == 0 {
return None;
}
exact.retain(|candidate| {
Self::de_postcode_house_locality_score(
locality_tail,
hard_commune,
postcode,
&candidate.hit.commune,
) == strongest
});
}
if exact.len() != 1 {
return None;
}
if !exact[0].hit.flags.contains(&"de_postcode_house") {
exact[0].hit.flags.push("de_postcode_house");
}
if structural_effect.is_some() && !exact[0].hit.flags.contains(&"de_house_left_endpoint") {
exact[0].hit.flags.push("de_house_left_endpoint");
}
if !additional_exact_house_numbers.is_empty()
&& !exact[0].hit.flags.contains(&"de_house_set_exact")
{
exact[0].hit.flags.push("de_house_set_exact");
}
let only = exact.pop()?;
let mut out = vec![(only.hit, only.features)];
out.truncate(k);
Some(out)
}
/// The ordinary query remains first and wins ties. DE-only alternatives are
/// compared by the same legacy evidence (exact street/commune/postcode/house)
/// used to choose parse hypotheses, so a fallback can replace a weak fuzzy hit
/// but cannot dislodge an equally supported canonical spelling.
/// A two-letter uppercase annotation after an indexed locality is administrative
/// context, not a second locality. Keep unanchored tokens (including street words).
fn it_province_annotation(&self, raw: &str) -> Option<String> {
if self.country() != Some("it") {
return None;
}
let mut offset = 0;
let mut kept = 0;
let mut result = String::new();
for token in raw.split_whitespace() {
let start = offset + raw[offset..].find(token).unwrap();
offset = start + token.len();
let code = token.trim_matches(|c: char| !c.is_alphanumeric());
if code.len() != 2 || !code.bytes().all(|b| b.is_ascii_uppercase()) {
continue;
}
let before = normalize(&raw[..start]);
let words: Vec<_> = before.split_whitespace().collect();
let has_city = (1..=words.len().min(9)).any(|n| {
let city = words[words.len() - n..].join(" ");
!self.communes_by_name(&city).is_empty()
});
if !has_city {
continue;
}
result.push_str(&raw[kept..start]);
result.push(' ');
kept = offset;
}
if kept == 0 {
None
} else {
result.push_str(&raw[kept..]);
Some(result)
}
}
/// Keep the literal address first; Spanish linkers are optional only at
/// the seam between a street type and its name. Never strip inner words.
fn es_street_particle_variants(raw: &str) -> Vec<String> {
let (street, suffix) = match raw.split_once(',') {
Some((street, suffix)) => (street, Some(suffix)),
None => (raw, None),
};
let normalized = normalize(street);
let tokens: Vec<&str> = normalized.split_whitespace().collect();
if tokens.len() < 2 || !is_street_type_word(tokens[0]) {
return Vec::new();
}
let skip = match tokens[1] {
"de" if matches!(tokens.get(2), Some(&"la" | &"les" | &"los" | &"las" | &"l")) => 2,
"de" | "del" | "dels" | "d" => 1,
_ => 0,
};
let rest = tokens[1 + skip..].join(" ");
if rest.is_empty() {
return Vec::new();
}
[
"", "de", "del", "dels", "de la", "de les", "de los", "de las", "de l", "d",
]
.iter()
.map(|particle| {
let variant = if particle.is_empty() {
format!("{} {rest}", tokens[0])
} else {
format!("{} {particle} {rest}", tokens[0])
};
match suffix {
Some(suffix) => format!("{variant},{suffix}"),
None => variant,
}
})
.filter(|variant| variant.split(',').next().unwrap_or("") != normalized)
.collect()
}
/// The literal street and its seam variants under each synonym of the leading type
/// word. Synonyms are one-word street rules of the sheet whose both sides are street
/// types ("passeig" / "paseo"): the engine carries no language vocabulary here.
fn es_street_type_variants(raw: &str) -> Vec<String> {
let (street, suffix) = match raw.split_once(',') {
Some((street, suffix)) => (street, Some(suffix)),
None => (raw, None),
};
let normalized = normalize(street);
let Some((kind, _)) = normalized.split_once(' ') else {
return Vec::new();
};
let rules = crate::rules::rules();
let mut synonyms: Vec<&str> = Vec::new();
for (from, to) in &rules.street_rewrites {
let other = if from == kind {
to
} else if to == kind {
from
} else {
continue;
};
// A street type is one word, so multi-word linker rewrites never qualify.
if rules.is_street_type(kind)
&& rules.is_street_type(other)
&& !synonyms.contains(&other.as_str())
{
synonyms.push(other);
}
}
let mut forms = vec![normalized.clone()];
forms.extend(Self::es_street_particle_variants(street));
let mut out = Vec::new();
for synonym in synonyms {
for form in &forms {
let rest = &form[kind.len()..];
let variant = match suffix {
Some(suffix) => format!("{synonym}{rest},{suffix}"),
None => format!("{synonym}{rest}"),
};
if !out.contains(&variant) {
out.push(variant);
}
}
}
out
}
// A synonym retry runs only when the sheet has its own exact street name.
fn es_typed_variant_exists(&self, raw: &str) -> bool {
let normalized = normalize(raw.split(',').next().unwrap_or(raw));
let tokens: Vec<_> = normalized
.split_whitespace()
.take_while(|t| !t.starts_with(|c: char| c.is_ascii_digit()))
.collect();
if tokens.len() < 2 {
return false;
}
let mut lo = tokens.join(" ").into_bytes();
let mut hi = lo.clone();
lo.push(KEY_SEP);
hi.push(KEY_SEP + 1);
self.streets_fst
.range()
.ge(&lo)
.lt(&hi)
.into_stream()
.next()
.is_some()
}
fn es_particle_street_key(raw: &str, query: bool) -> String {
let normalized = normalize(if query {
raw.split(',').next().unwrap_or(raw)
} else {
raw
});
let mut tokens: Vec<&str> = normalized.split_whitespace().collect();
if query {
if let Some(house) = tokens
.iter()
.position(|t| t.starts_with(|c: char| c.is_ascii_digit()))
{
tokens.truncate(house);
}
}
if tokens.first().is_some_and(|t| is_street_type_word(t)) {
tokens.remove(0);
let skip = match tokens.first().copied() {
Some("de")
if matches!(tokens.get(1), Some(&"la" | &"les" | &"los" | &"las" | &"l")) =>
{
2
}
Some("de" | "del" | "dels" | "d") => 1,
_ => 0,
};
tokens.drain(..skip);
}
tokens.join(" ")
}
fn es_requested_commune(raw: &str) -> String {
let mut segments = raw.rsplit(',').map(normalize);
if raw.contains(',') {
for segment in &mut segments {
if matches!(
segment.split_whitespace().next(),
Some("tel" | "telefono" | "telephone" | "phone" | "fax")
) {
continue;
}
let tokens: Vec<_> = segment
.split_whitespace()
.filter(|t| {
!is_country_word(t)
&& !matches!(*t, "espana" | "spain")
&& !t.chars().all(|c| c.is_ascii_digit())
})
.collect();
if !tokens.is_empty() {
return tokens.join(" ");
}
}
return String::new();
}
let normalized = normalize(raw);
let tokens: Vec<_> = normalized.split_whitespace().collect();
let Some(number) = tokens
.iter()
.rposition(|t| t.starts_with(|c: char| c.is_ascii_digit()))
else {
return String::new();
};
tokens[number + 1..]
.iter()
.copied()
.filter(|t| !is_country_word(t) && !matches!(*t, "espana" | "spain"))
.collect::<Vec<_>>()
.join(" ")
}
fn es_particle_preserves_commune(raw: &str, _original: Option<&Hit>, candidate: &Hit) -> bool {
let requested = Self::es_requested_commune(raw);
!requested.is_empty() && normalize(&candidate.commune) == requested
}
fn es_literal_street(raw: &str) -> String {
let street = normalize(raw.split(',').next().unwrap_or(raw));
street
.split_whitespace()
.take_while(|token| !token.starts_with(|c: char| c.is_ascii_digit()))
.collect::<Vec<_>>()
.join(" ")
}
fn es_particle_original_exact(raw: &str, hit: &Hit) -> bool {
let requested_city = Self::es_requested_commune(raw);
let literal_street = Self::es_literal_street(raw);
!requested_city.is_empty()
&& normalize(&hit.commune) == requested_city
&& !literal_street.is_empty()
&& normalize(&hit.street) == literal_street
}
// Skip expensive retries when their exact street name is absent. This is
// only a filter on optional retries; the original result stays untouched.
fn es_particle_variant_exists(&self, raw: &str) -> bool {
let normalized = normalize(raw);
let tokens: Vec<_> = normalized.split_whitespace().collect();
let end = tokens
.iter()
.position(|t| t.starts_with(|c: char| c.is_ascii_digit()));
let Some(end) = end else {
return true;
};
if end <= 1 {
return false;
}
let name = tokens[1..end].join(" ");
crate::rules::rules()
.types_latin
.iter()
.map(String::as_str)
.chain(tokens.first().copied())
.any(|kind| {
let mut lo = format!("{kind} {name}").into_bytes();
let mut hi = lo.clone();
lo.push(KEY_SEP);
hi.push(KEY_SEP + 1);
self.streets_fst
.range()
.ge(&lo)
.lt(&hi)
.into_stream()
.next()
.is_some()
})
}
// An accepted retry must be a house. Every house-number hypothesis needs
// ASCII digits; changing a linker cannot supply them. Keep retries when
// rule expansions or the French Roman-ordinal rewrite could add a number.
// Number-word expansion in street lookup changes keys, not house hypotheses.
fn es_particle_may_have_house(&self, raw: &str) -> bool {
let may_supply_number = |text: &str| {
let normalized = crate::norm::fold_homoglyphs(&normalize(text));
normalized.bytes().any(|b| b.is_ascii_digit())
|| ["paris", "lyon", "marseille"]
.iter()
.any(|city| normalized.contains(city))
};
may_supply_number(raw)
|| *self.es_particle_rules_may_supply_number.get_or_init(|| {
self.rules
.city_alias
.iter()
.chain(self.rules.abbrev2.iter())
.any(|(_, expanded)| may_supply_number(expanded))
})
}
// A retry on the very same house must not reduce confidence. Ties keep
// the original path and, at the call site, its complete result list.
fn es_particle_keep_original(original: Option<&Hit>, candidate: &Hit) -> bool {
original.is_some_and(|original| {
original.lat == candidate.lat
&& original.lon == candidate.lon
&& original.housenumber == candidate.housenumber
&& original.confidence >= candidate.confidence
})
}
fn es_particle_retry(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
// The first search is byte-for-byte the accepted engine path. If its
// full street and city already match, article retries are fallback only.
let original = self.query_feats_d(raw, k, 0, focus, None, None, false, None);
if original
.first()
.is_some_and(|(hit, _)| Self::es_particle_original_exact(raw, hit))
{
return original;
}
let expected_street = Self::es_particle_street_key(raw, true);
if expected_street.is_empty() || !self.es_particle_may_have_house(raw) {
return original;
}
let _prepared_scope = (!crate::diagnosis::enabled()).then(EsPreparedScope::new);
// The written type first; a synonym type from the sheet's rules only after it.
let literal = Self::es_street_particle_variants(raw)
.into_iter()
.filter(|variant| self.es_particle_variant_exists(variant));
let synonym = Self::es_street_type_variants(raw)
.into_iter()
.filter(|variant| self.es_typed_variant_exists(variant));
for variant in literal.chain(synonym) {
let candidate = self.query_feats_d(&variant, k, 0, focus, None, None, false, None);
if candidate.first().is_some_and(|(hit, _)| {
hit.precision == "house"
&& Self::es_particle_street_key(&hit.street, false) == expected_street
&& Self::es_particle_preserves_commune(raw, original.first().map(|v| &v.0), hit)
}) {
if Self::es_particle_keep_original(original.first().map(|v| &v.0), &candidate[0].0)
{
return original;
}
return candidate;
}
}
original
}
// Rewrite only the street field; preserve the explicit house number and locality.
fn query_feats_street_data(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let original = self.query_feats_street_data_base(raw, k, focus);
let original = recipient_field_choose(original, raw, |clean| {
self.query_feats_street_data_base(clean, k, focus)
});
let original = self.query_feats_comma_fields(original, raw, k, focus);
let original = self.query_feats_geographic_fields(original, raw, k, focus);
self.query_feats_title_fields(original, raw, k, focus)
}
/// Recover separators only from an exact indexed street boundary and existing
/// number/postal/region grammar. Numerals belonging to the street stay intact.
fn comma_field_retry(&self, raw: &str) -> Option<String> {
if raw.contains(',') {
return None;
}
let cfg = &crate::rules::rules().city_tail;
if cfg.get("enabled").map(String::as_str) != Some("1") {
return None;
}
let digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let split = cfg.get("postal_split")?.parse::<usize>().ok()?;
let regions = cfg.get("regions")?;
let mut offset = 0;
let words = raw
.split_whitespace()
.map(|word| {
let start = offset + raw[offset..].find(word).expect("raw token");
offset = start + word.len();
(start, offset, word)
})
.collect::<Vec<_>>();
let postal = |word: &str| {
let d: String = word.chars().filter(char::is_ascii_digit).collect();
d.len() == digits
&& (word == d
|| (split < digits && word == format!("{}-{}", &d[..split], &d[split..])))
};
// Under the region_postal form the tail is the last word pair "<region> <postal>"
// (or a bare region as the last word); its postal word stays glued to the region.
let tail_pos = words
.len()
.checked_sub(2)
.filter(|&i| split_region_postal(cfg, &raw[words[i].0..words[i + 1].1]).is_some())
.or_else(|| {
words
.len()
.checked_sub(1)
.filter(|&i| split_region_postal(cfg, words[i].2).is_some())
});
let postals = words
.iter()
.enumerate()
.filter(|(i, w)| postal(w.2) && tail_pos.is_none_or(|t| *i < t))
.map(|(i, _)| i)
.collect::<Vec<_>>();
if postals.len() > 1 {
return None;
}
let postal_pos = postals.first().copied();
let region_pos = tail_pos.or_else(|| {
words.len().checked_sub(1).filter(|&i| {
regions
.split_whitespace()
.any(|r| r.eq_ignore_ascii_case(words[i].2))
})
});
let aliases = field_street_type_aliases();
let projection = self.field_street_projection();
let known_street = |street: &str| {
let street = prepared_query_key(street);
let mut forms = vec![street.clone()];
forms.extend(street_data_variants(&street));
forms.iter().any(|form| {
if projection.contains_key(&field_street_type_key(form, &aliases)) {
return true;
}
let Some((kind, name)) = form.split_once(' ') else {
return false;
};
if !is_street_type_word(kind) {
return false;
}
let rules = crate::rules::rules();
rules
.types_latin
.iter()
.chain(&rules.types_cyr)
.chain(&rules.types_extra)
.any(|kind| {
projection.contains_key(&field_street_type_key(
&format!("{kind} {name}"),
&aliases,
))
})
})
};
if known_street(raw) {
return None;
}
let limit = postal_pos.or(region_pos).unwrap_or(words.len());
let mut house = None;
for i in 1..limit {
let token = field_number_unlabel(words[i].2);
let n = token.chars().take_while(char::is_ascii_digit).count();
if n == 0
|| n > 5
|| !(token.len() == n
|| (token.len() == n + 1 && token.as_bytes()[n].is_ascii_alphabetic()))
{
continue;
}
let labeled =
token != words[i].2 || field_number_unlabel(words[i - 1].2) != words[i - 1].2;
let start = if labeled && field_number_unlabel(words[i - 1].2).is_empty() {
words[i - 1].0
} else {
words[i].0
};
let street = raw[..start].trim();
if is_street_type_word(&normalize(street)) {
continue;
}
if known_street(street) {
// The longest exact street prefix wins, never its initial numeral.
house = Some((start, words[i].1, labeled));
}
}
let (start, end, labeled) = house?;
let mut cuts = Vec::new();
if labeled {
cuts.push(start);
}
if !labeled || postal_pos.is_some() || region_pos.is_some() {
cuts.push(end);
}
if let Some(i) = postal_pos {
cuts.extend([words[i].0, words[i].1]);
}
if let Some(i) = region_pos {
cuts.push(words[i].0);
}
cuts.retain(|&p| p > 0 && p < raw.len());
cuts.sort_unstable();
cuts.dedup();
let mut parts = Vec::new();
let mut last = 0;
for p in cuts {
let part = raw[last..p].trim();
if !part.is_empty() {
parts.push(part);
}
last = p;
}
let part = raw[last..].trim();
if !part.is_empty() {
parts.push(part);
}
let query = parts.join(", ");
(query != raw && query.contains(',')).then_some(query)
}
fn query_feats_comma_fields(
&self,
original: Vec<(Hit, [f32; N_FEATS])>,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
empty_field_choose(
original,
|| self.comma_field_retry(raw),
|query| {
let (number, city) = if let Some(tail) = address_field_retries(query) {
(tail.number, Some(tail.city))
} else if let Some((_, number)) = cityless_field_address(query) {
(number, None)
} else {
return Vec::new();
};
let candidate = self.query_feats_street_data_base(query, k, focus);
let accepted = candidate.first().is_some_and(|(hit, _)| {
hit.precision == "house"
&& hit.housenumber.as_deref().and_then(numeric_house_prefix) == Some(number)
&& (hit.flags.contains(&"street_exact")
|| hit.flags.contains(&"street_fuzzy"))
&& city
.as_ref()
.is_none_or(|city| normalize(&hit.commune) == *city)
});
if accepted {
candidate
} else {
Vec::new()
}
},
)
}
fn field_street_projection(&self) -> &HashMap<String, Vec<u32>> {
let types = field_street_type_aliases();
self.field_display_streets.get_or_init(|| {
self.project_street_names(|name| {
Some(field_street_type_key(&prepared_query_key(name), &types))
})
})
}
/// "Sullivan 43, Col. San Rafael, 6470": the street is written with part of its name only, and the
/// sheet keeps it as "Calle James Sullivan". On a sheet with `postal_street_suffix`, a query that read
/// nothing at all takes the house of the one street inside the postal code written whose name ends
/// with the words written (a type word in front set aside), when that house number is there. Two
/// different streets ending so leave the query unanswered (Mexico, 01.11.2026).
///
/// Then, with `postal_near_digits` (n): "Omneda 4, Centro, 6000" — a letter swapped, and the sheet
/// keeps "Calle Moneda" under 06060. The one street under the codes sharing the first n digits whose
/// name without its type is the name written, or one edit away (a swap of two neighbours counts as
/// one; names shorter than five letters take no edit), answers with that house (Mexico, 01.11.2026).
fn postal_street_suffix(&self, raw: &str) -> Option<(Hit, [f32; N_FEATS])> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("postal_street_suffix").map(String::as_str) != Some("1") {
return None;
}
let (name, number, code) = postal_street_suffix_query(raw)?;
let roster = self.postcode_roster.get_or_init(|| {
self.build_de_postcode_streets()
.unwrap_or_else(|_| Vec::new().into_boxed_slice())
});
let tail = format!(" {name}");
if let Some(hit) =
self.unique_street_house(roster, code, code, number, |full| full.ends_with(&tail))
{
return Some(hit);
}
let near = cfg
.get("postal_near_digits")?
.parse::<u32>()
.ok()
.filter(|n| (1..5).contains(n))?;
let width = 10u32.pow(5 - near);
let low = code / width * width;
if let Some(hit) = self.unique_street_house(roster, low, low + width - 1, number, |full| {
let base = without_leading_type(full);
base == name || (name.chars().count() >= 5 && one_edit_apart(base, &name))
}) {
return Some(hit);
}
// "Hidalgo 197, Centro, 47600": the street is there under the code written, the house is not;
// its neighbour within a few numbers answers (Mexico, 01.11.2026).
self.named_street_near_number(&name, number, code, code, code)
}
/// "Plaza de la República s/n, Col. Tabacalera, 6030": no house number (the sheet's
/// `no_number_marks` say so), and the query read nothing or only a city. The one street inside
/// the postal code written whose name without its type is the name written answers as a street
/// (Mexico, 01.11.2026).
fn postal_street_without_number(&self, raw: &str) -> Option<(Hit, [f32; N_FEATS])> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("postal_street_suffix").map(String::as_str) != Some("1") {
return None;
}
let (name, code) = postal_street_without_number_query(raw)?;
let roster = self.postcode_roster.get_or_init(|| {
self.build_de_postcode_streets()
.unwrap_or_else(|_| Vec::new().into_boxed_slice())
});
let start = roster.partition_point(|&(pc, _)| pc < code);
let end = roster.partition_point(|&(pc, _)| pc <= code);
let mut matched: Option<String> = None;
let mut best: Option<(u32, u32)> = None;
for &(_, sid) in &roster[start..end] {
let full = normalize(self.name(self.street_meta(sid).name_off));
if without_leading_type(&full) != name {
continue;
}
match &matched {
Some(seen) if *seen != full => return None,
_ => matched = Some(full),
}
let houses = self.street_meta(sid).house_count;
if best.is_none_or(|(_, n)| houses > n) {
best = Some((sid, houses));
}
}
let (sid, _) = best?;
let f = Feats {
street_exact: true,
..Default::default()
};
let (hit, feats, _, _, _, _) = self.make_hit(sid, f, None, 0, Some(code), &[]);
Some((hit, feats))
}
/// "Benito Juárez 9 A, Col. San Ángel, 01000 Álvaro Obregón": the answer is a namesake street of the
/// same city under another postal code. With `postal_near_digits` (n), when the answer's postcode does
/// not share the first n digits of the code written and the one street of that name (its type set
/// aside) under those digits has the house, an interpolation or a neighbour within
/// `NAMESAKE_NUMBER_GAP` numbers, that answer replaces the namesake (Mexico, 01.11.2026).
fn postal_namesake_swap(&self, raw: &str, hit: &Hit) -> Option<(Hit, [f32; N_FEATS])> {
let cfg = &crate::rules::rules().city_tail;
if cfg.get("postal_street_suffix").map(String::as_str) != Some("1") {
return None;
}
let near = cfg
.get("postal_near_digits")?
.parse::<u32>()
.ok()
.filter(|n| (1..5).contains(n))?;
let (name, number, code) = postal_street_suffix_query(raw)?;
let width = 10u32.pow(5 - near);
let low = code / width * width;
if hit
.postcode
.parse::<u32>()
.is_ok_and(|pc| pc / width == code / width)
{
return None;
}
self.named_street_near_number(&name, number, code, low, low + width - 1)
}
/// The one street (by normalized name, its type set aside) under codes `low..=high` named `name`:
/// its house `number`, an interpolation, or a neighbour within `NAMESAKE_NUMBER_GAP` numbers.
/// Two different streets of the name, or a farther neighbour, give nothing.
fn named_street_near_number(
&self,
name: &str,
number: u32,
code: u32,
low: u32,
high: u32,
) -> Option<(Hit, [f32; N_FEATS])> {
let roster = self.postcode_roster.get_or_init(|| {
self.build_de_postcode_streets()
.unwrap_or_else(|_| Vec::new().into_boxed_slice())
});
let start = roster.partition_point(|&(pc, _)| pc < low);
let end = roster.partition_point(|&(pc, _)| pc <= high);
let mut matched: Option<String> = None;
let mut ids = Vec::new();
for &(_, sid) in &roster[start..end] {
let full = normalize(self.name(self.street_meta(sid).name_off));
if without_leading_type(&full) != name {
continue;
}
match &matched {
Some(seen) if *seen != full => return None,
_ => matched = Some(full),
}
if !ids.contains(&sid) {
ids.push(sid);
}
}
let rank = |p: &str| match p {
"house" => 0,
"interp" => 1,
_ => 2,
};
ids.iter()
.map(|&sid| {
let f = Feats {
street_exact: true,
..Default::default()
};
let (h, feats, _, _, _, _) =
self.make_hit(sid, f, Some(number), 0, Some(code), &[]);
(h, feats)
})
.filter(|(h, _)| match h.precision {
"house" | "interp" => true,
"near" => h
.housenumber
.as_deref()
.and_then(|n| {
n.trim_end_matches(|c: char| !c.is_ascii_digit())
.parse::<u32>()
.ok()
})
.is_some_and(|got| got.abs_diff(number) <= NAMESAKE_NUMBER_GAP),
_ => false,
})
.min_by_key(|(h, _)| rank(h.precision))
}
/// The house `number` of the one street (by normalized name) among the roster's streets under
/// codes `low..=high` whose name passes `keep`; none when two different names pass.
fn unique_street_house(
&self,
roster: &[(u32, u32)],
low: u32,
high: u32,
number: u32,
keep: impl Fn(&str) -> bool,
) -> Option<(Hit, [f32; N_FEATS])> {
let start = roster.partition_point(|&(pc, _)| pc < low);
let end = roster.partition_point(|&(pc, _)| pc <= high);
let mut matched: Option<String> = None;
let mut ids = Vec::new();
for &(_, sid) in &roster[start..end] {
let full = normalize(self.name(self.street_meta(sid).name_off));
if !keep(&full) {
continue;
}
match &matched {
Some(seen) if *seen != full => return None,
_ => matched = Some(full),
}
ids.push(sid);
}
if ids.is_empty() {
return None;
}
self.field_house_from_ids(&ids, number)
}
/// Group street ids by `key(name)`, each list in id order. The key is computed once per
/// distinct name text (every street stores its own copy; a US sheet repeats "Main Street" in thousands of communes) and on all
/// cores: built street by street, the first query that reached it took 20–40 s on the
/// US sheet. Plain scoped threads, not rayon: a batch worker building this inside a
/// rayon pool could steal another query that then waits on the same `OnceLock`.
fn project_street_names<F>(&self, key: F) -> HashMap<String, Vec<u32>>
where
F: Fn(&str) -> Option<String> + Sync,
{
let count = self.streets_meta.len() / STREET_META_SIZE;
let mut slot: HashMap<&str, usize> = HashMap::new();
let mut names: Vec<&str> = Vec::new();
let mut by_name: Vec<Vec<u32>> = Vec::new();
for sid in 0..count {
let sid = u32::try_from(sid).expect("validated street table");
let name = self.name(self.street_meta(sid).name_off);
let i = *slot.entry(name).or_insert_with(|| {
names.push(name);
by_name.push(Vec::new());
names.len() - 1
});
by_name[i].push(sid);
}
drop(slot);
let threads = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
let chunk = names.len().div_ceil(threads).max(1);
let keys: Vec<Option<String>> = std::thread::scope(|scope| {
let workers: Vec<_> = names
.chunks(chunk)
.map(|part| {
let key = &key;
scope.spawn(move || part.iter().map(|name| key(name)).collect::<Vec<_>>())
})
.collect();
workers
.into_iter()
.flat_map(|w| w.join().unwrap_or_else(|e| std::panic::resume_unwind(e)))
.collect()
});
let mut out: HashMap<String, Vec<u32>> = HashMap::new();
let mut merged = Vec::new();
for (key, ids) in keys.into_iter().zip(by_name) {
let Some(key) = key else { continue };
match out.entry(key) {
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(ids);
}
std::collections::hash_map::Entry::Occupied(mut slot) => {
slot.get_mut().extend(ids);
merged.push(slot.key().clone());
}
}
}
// Different names with one key: restore the id order of the street-by-street build.
for key in merged {
if let Some(ids) = out.get_mut(&key) {
ids.sort_unstable();
}
}
out
}
/// Recover a place only from fields following an explicit house number.
/// Sheet commune names are evidence; the rightmost longest match wins over
/// a district named after another place. No street tokens enter this scan.
fn geographic_field_retry(&self, raw: &str) -> Option<(String, u32, String)> {
if self.rules.city_tail.get("enabled").map(String::as_str) != Some("1") {
return None;
}
let (first, rest) = raw.split_once(',')?;
let first = first.trim();
let rest = field_number_unlabel(rest.trim());
let house = |s: &str| {
let n = s.chars().take_while(char::is_ascii_digit).count();
n > 0
&& n <= 5
&& (s.len() == n || (s.len() == n + 1 && s.as_bytes()[n].is_ascii_alphabetic()))
};
let digits = rest.chars().take_while(char::is_ascii_digit).count();
let suffix = usize::from(
rest.as_bytes()
.get(digits)
.is_some_and(u8::is_ascii_alphabetic),
);
let end = digits + suffix;
let (street, number_text, tail) = if house(&rest[..end])
&& rest[end..].starts_with(|c: char| {
c.is_whitespace() || matches!(c, ',' | '-' | '–' | '—' | '.')
}) {
(first, &rest[..end], &rest[end..])
} else {
let (street, number) = first.rsplit_once(char::is_whitespace)?;
if !house(number) {
return None;
}
(street.trim(), number, rest)
};
if street.is_empty() || !street.chars().any(char::is_alphabetic) {
return None;
}
let cfg = &self.rules.city_tail;
let regions = cfg.get("regions")?;
let region = |word: &str| {
regions
.split_whitespace()
.any(|r| r.eq_ignore_ascii_case(word))
};
let postal_digits = cfg.get("postal_digits")?.parse::<usize>().ok()?;
let postal_split = cfg.get("postal_split")?.parse::<usize>().ok()?;
let has_region = tail
.split([',', '-', '–', '—', '.'])
.any(|field| normalize(field).split_whitespace().any(region));
let has_postal = tail.split_whitespace().any(|word| {
let word = word.trim_matches(|c: char| !c.is_ascii_digit() && c != '-');
let digits: String = word.chars().filter(char::is_ascii_digit).collect();
digits.len() == postal_digits
&& (word == digits
|| (postal_split < postal_digits
&& word
== format!("{}-{}", &digits[..postal_split], &digits[postal_split..])))
});
let mut city = None;
let mut anchored = false;
let mut distinct_places = false;
for field in tail.split([',', '-', '–', '—', '.']) {
let normalized = normalize(field);
let words: Vec<&str> = normalized.split_whitespace().collect();
for (slot, chunk) in words.split(|word| region(word)).enumerate() {
if slot > 0 {
anchored = true;
}
let mut found = None;
for end in (1..=chunk.len()).rev() {
for start in 0..end {
let name = chunk[start..end].join(" ");
if name.chars().all(|c| {
c.is_alphabetic() || c.is_whitespace() || matches!(c, '\'' | '’')
}) && !self.communes_by_name_raw(&name).is_empty()
{
found = Some(name);
break;
}
}
if found.is_some() {
break;
}
}
if let Some(found) = found {
if anchored {
if city.as_ref() != Some(&found) {
return None;
}
} else {
distinct_places |= city.as_ref().is_some_and(|previous| previous != &found);
city = Some(found);
}
}
}
}
// Without a region anchor, multiple places around a postal field are
// ambiguous. Do not choose the district merely because it comes first.
if !has_region && has_postal && distinct_places {
return None;
}
let city = city?;
Some((
format!("{street}, {number_text}, {city}"),
numeric_house_prefix(number_text)?,
city,
))
}
fn query_feats_geographic_fields(
&self,
original: Vec<(Hit, [f32; N_FEATS])>,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
// The shared empty-only guard also protects the complete original list.
empty_field_choose(
original,
|| self.geographic_field_retry(raw).map(|(query, _, _)| query),
|query| {
let mut parts = query.rsplit(',').map(str::trim);
let city = normalize(parts.next().expect("retry city"));
let number = numeric_house_prefix(parts.next().expect("retry number"))
.expect("validated number");
let candidate = self.query_feats_street_data_base(query, k, focus);
if candidate.first().is_some_and(|(hit, _)| {
hit.precision == "house"
&& hit.housenumber.as_deref().and_then(numeric_house_prefix) == Some(number)
&& (hit.flags.contains(&"street_exact")
|| hit.flags.contains(&"street_fuzzy"))
&& normalize(&hit.commune) == city
}) {
candidate
} else {
Vec::new()
}
},
)
}
fn title_street_key(&self, street: &str, types: &HashMap<String, String>) -> Option<String> {
let titles = self.rules.city_tail.get("street_titles")?;
let aliases = self.rules.city_tail.get("street_title_aliases")?;
let prepared = prepared_query_key(street);
let mut words = Vec::new();
for (position, word) in prepared.split_whitespace().enumerate() {
let canonical = aliases
.split_whitespace()
.filter_map(|p| p.split_once(':'))
.find_map(|(short, full)| (short == word).then_some(full))
.unwrap_or(word);
// A type at the start stays a type. Only configured title words are optional.
if position > 0 && titles.split_whitespace().any(|t| t == canonical) {
continue;
}
words.push(canonical);
}
if words.len() < 2 {
return None;
}
Some(field_street_type_key(&words.join(" "), types))
}
fn query_feats_title_fields(
&self,
original: Vec<(Hit, [f32; N_FEATS])>,
raw: &str,
_k: usize,
_focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
if !original.is_empty() {
return original;
}
if !self.rules.city_tail.contains_key("street_titles") {
return original;
}
let parsed = self
.geographic_field_retry(raw)
.map(|(q, n, city)| {
(
q.split(',').next().unwrap().trim().to_owned(),
n,
Some(city),
)
})
.or_else(|| {
address_field_retries(raw).map(|tail| {
(
raw.split(',').next().unwrap().trim().to_owned(),
tail.number,
Some(tail.city),
)
})
})
.or_else(|| cityless_field_address(raw).map(|(street, n)| (street, n, None)));
let Some((street, number, city)) = parsed else {
return original;
};
let types = field_street_type_aliases();
let Some(key) = self.title_street_key(&street, &types) else {
return original;
};
let projection = self
.field_title_streets
.get_or_init(|| self.project_street_names(|name| self.title_street_key(name, &types)));
let Some(ids) = projection.get(&key) else {
return original;
};
let query_has_title = field_street_type_key(&prepared_query_key(&street), &types) != key;
let ids: Vec<u32> = ids
.iter()
.copied()
.filter(|sid| {
(query_has_title
|| field_street_type_key(
&prepared_query_key(self.name(self.street_meta(*sid).name_off)),
&types,
) != key)
&& city.as_ref().is_none_or(|c| {
normalize(self.commune_name(self.street_meta(*sid).commune_id)) == *c
})
})
.collect();
self.field_house_from_ids(&ids, number)
.map_or(original, |h| vec![h])
}
fn query_feats_street_data_base(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let original = self.query_feats_fields_retry(raw, k, focus);
let original = if original.is_empty() {
self.postal_street_suffix(raw)
.map_or(original, |hit| vec![hit])
} else {
original
};
let original = if original
.first()
.is_none_or(|(hit, _)| hit.precision == "city")
{
self.postal_street_without_number(raw)
.map_or(original, |hit| vec![hit])
} else {
original
};
let swapped = original
.first()
.filter(|(hit, _)| hit.precision != "city")
.and_then(|(hit, _)| self.postal_namesake_swap(raw, hit));
let original = swapped.map_or(original, |hit| vec![hit]);
if self.rules.street_rewrites.is_empty() {
return original;
}
let parts: Vec<&str> = raw.split(',').map(str::trim).collect();
if parts.len() < 2 {
return original;
}
let house_token = |s: &str| {
let n = s.chars().take_while(char::is_ascii_digit).count();
n > 0
&& n <= 5
&& (s.len() == n || (s.len() == n + 1 && s.as_bytes()[n].is_ascii_alphabetic()))
};
let second = parts[1]
.split_once(" - ")
.map_or(parts[1], |(n, _)| n)
.trim();
let (street, suffix, number) = if house_token(second) {
(
parts[0],
String::new(),
numeric_house_prefix(second).unwrap(),
)
} else if let Some((street, number)) = parts[0].rsplit_once(char::is_whitespace) {
if !house_token(number) {
return original;
}
(
street,
format!(" {number}"),
numeric_house_prefix(number).unwrap(),
)
} else {
return original;
};
// Ordinary candidates never contain data-driven street rewrites. Preserve the
// requested house before generating even one alternate street key.
if original.first().is_some_and(|(h, _)| {
h.precision == "house"
&& h.housenumber.as_deref().and_then(numeric_house_prefix) == Some(number)
}) {
return original;
}
let city = if let Some(tail) = address_field_retries(raw) {
tail.city
} else if (parts.len() == 3 && suffix.is_empty())
|| (parts.len() == 2 && !suffix.is_empty())
{
let city = parts.last().unwrap();
if !city.chars().any(char::is_alphabetic)
|| !city.chars().all(|c| {
c.is_alphabetic() || c.is_whitespace() || matches!(c, '-' | '\'' | '’')
})
{
return original;
}
normalize(city)
} else {
return original;
};
let number_text = if suffix.is_empty() {
second
} else {
suffix.trim()
};
let normalized_number = normalize(number_text);
let digits = normalized_number
.bytes()
.take_while(u8::is_ascii_digit)
.count();
let rep = *self
.rep_lookup
.get(&normalized_number[digits..])
.unwrap_or(&0);
let cids = self.communes_by_name(&city);
// Resolve exact alternate keys inside the explicit city. Re-parsing the
// whole address would consume a street numeral as the house number and
// repeat expensive fuzzy searches for every alternate.
for street in street_data_variants(&normalize(street)) {
let qwords: Vec<Vec<char>> = street
.split_whitespace()
.map(|w| w.chars().collect())
.collect();
let mut candidates = Vec::new();
for cid in &cids {
let mut key = street.clone().into_bytes();
key.push(KEY_SEP);
key.extend_from_slice(self.commune_insee(*cid).as_bytes());
if let Some(sid) = self.streets_fst.get(&key) {
let h = self.make_hit(
sid as u32,
Feats {
street_exact: true,
commune_exact: true,
..Default::default()
},
Some(number),
rep,
None,
&qwords,
);
if h.0.precision == "house"
&& h.0.housenumber.as_deref().and_then(numeric_house_prefix) == Some(number)
&& normalize(&h.0.commune) == city
{
candidates.push(h);
}
}
}
candidates.sort_by(|a, b| {
b.0.score
.total_cmp(&a.0.score)
.then(b.2.cmp(&a.2))
.then(a.3.cmp(&b.3))
.then(b.4.cmp(&a.4))
.then(a.5.cmp(&b.5))
});
candidates.truncate(k);
if !candidates.is_empty() {
let mut out: Vec<_> = candidates
.into_iter()
.map(|(h, f, _, _, _, _)| (h, f))
.collect();
Self::monotone_confidence(&mut out);
return out;
}
}
original
}
fn query_feats_fields_retry(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
// Retry forms share pure automata within this raw query; the next query starts empty.
clear_levenshtein_cache();
let unmarked = strip_number_marks(raw);
let raw: &str = unmarked.as_deref().unwrap_or(raw);
let commas = restore_commas(raw);
let raw: &str = commas.as_deref().unwrap_or(raw);
let padded = pad_short_postal(raw);
let raw: &str = padded.as_deref().unwrap_or(raw);
let original = self.query_feats_postal_retry(raw, k, focus);
let original = self.bare_street_postal_retry(raw, original, k, focus);
if let Some(tail) = address_field_retries(raw) {
return address_field_choose(original, &tail, |_, q| {
self.query_feats_postal_retry(q, k, focus)
});
}
if original
.first()
.is_some_and(|(hit, _)| hit.precision == "house")
{
return original;
}
let Some((street, number)) = cityless_field_address(raw) else {
return original;
};
self.cityless_field_house(&street, number)
.map_or(original, |hit| vec![hit])
}
/// A full-sheet uniqueness proof: all source ids for the display name and
/// all represented rows (including suffixes and duplicates) for the number.
/// Any malformed block or distant matching point rejects the fallback.
fn cityless_field_house(&self, street: &str, number: u32) -> Option<(Hit, [f32; N_FEATS])> {
let types = field_street_type_aliases();
let street_key = field_street_type_key(street, &types);
let projection = self.field_street_projection();
let ids = projection.get(&street_key)?;
self.field_house_from_ids(ids, number)
}
fn field_house_from_ids(&self, ids: &[u32], number: u32) -> Option<(Hit, [f32; N_FEATS])> {
let mut selected: Option<(u32, u32, f64, f64, u32)> = None;
for &sid in ids {
let m = self.street_meta(sid);
if m.house_count == 0 {
continue;
}
let (mut pos, dictionary, count, end) = self.house_block_layout(sid, &m)?;
let bounded = &self.houses[..end];
let mut current = 0u32;
for row in 0..m.house_count {
let delta = u32::try_from(strict_varint(bounded, &mut pos)?).ok()?;
current = if row == 0 {
delta
} else {
current.checked_add(delta)?
};
let rep = u32::try_from(strict_varint(bounded, &mut pos)?).ok()?;
let dlat = unzigzag(strict_varint(bounded, &mut pos)?);
let dlon = unzigzag(strict_varint(bounded, &mut pos)?);
let postcode =
if self.format_version >= 7 && m.postcode_disp_off == PC_DISP_AMBIGUOUS {
let id = u32::try_from(strict_varint(bounded, &mut pos)?).ok()?;
self.house_postcode_offset(dictionary, count, id)
} else {
0
};
if current != number {
continue;
}
let lat = (m.lat_c as i64).checked_add(dlat)?;
let lon = (m.lon_c as i64).checked_add(dlon)?;
if !(-900_000_000..=900_000_000).contains(&lat)
|| !(-1_800_000_000..=1_800_000_000).contains(&lon)
{
return None;
}
let (lat, lon) = (lat as f64 / 1e7, lon as f64 / 1e7);
if let Some((_, _, first_lat, first_lon, _)) = selected {
if Self::dist_km(first_lat, first_lon, lat, lon) > 0.150 {
return None;
}
} else {
selected = Some((sid, rep, lat, lon, postcode));
}
}
}
let (sid, rep, lat, lon, postcode) = selected?;
let f = Feats {
street_exact: true,
numero_present: true,
house_found: true,
house_exact_rep: rep == 0,
..Default::default()
};
let m = self.street_meta(sid);
let score = self
.rank
.as_ref()
.map_or(f.legacy() as f32, |rank| rank.score(&f))
+ 1.0;
let mut confidence = confidence_score("house", &f, 100);
if score < 0.0 {
confidence = confidence.min(0.4);
}
Some((
Hit {
lat,
lon,
precision: "house",
score,
confidence,
street: self.name(m.name_off).to_owned(),
housenumber: Some(self.house_number(number, rep)),
commune: self.commune_name(m.commune_id).to_owned(),
postcode: self.postcode_for_house(&m, postcode),
flags: match_flags(&f),
region: self.admin_at(lat, lon),
distance_m: None,
},
f.to_vec(),
))
}
fn query_feats_postal_retry(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let original = self.query_feats_city_tail(raw, k, focus);
if strong_first(&original) {
return original;
}
let Some(rewritten) = postal_retry(raw) else {
return original;
};
let alternate = self.query_feats_city_tail(&rewritten, k, focus);
if alternate.is_empty() {
original
} else {
alternate
}
}
/// "Independencia 684, Centro Histórico, 44100": no city, the postal code names the place,
/// the street is written without its type while the sheet keys "calle independencia". When
/// the answer is not inside the code written, the street segment is read with the postal
/// code alone, bare and then with each of the sheet's `bare_street_types`; an answer stands
/// only inside that code (Mexico, 31.10.2026: 791 rows of the clean set name the place by the
/// code only).
fn bare_street_postal_retry(
&self,
raw: &str,
hits: Vec<(Hit, [f32; N_FEATS])>,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
if hits
.first()
.is_some_and(|(hit, _)| hit.flags.contains(&"pc_exact"))
{
return hits;
}
let variants = bare_street_postal_variants(raw);
for variant in &variants {
let mut found = self.query_feats_city_tail(variant, k, focus);
found.retain(|(hit, _)| hit.flags.contains(&"pc_exact"));
if !found.is_empty() {
return found;
}
}
if hits.is_empty() {
return self.bare_street_near_code(raw, &variants, k, focus);
}
hits
}
/// "Moneda 4, Centro, 6000": nothing answered inside the code written, and the sheet keeps the
/// street under the next code (06060). On a sheet with `postal_near_digits` (n), a query that read
/// nothing at all takes an exact street with a house or an interpolation whose postcode shares the
/// code's first n digits. The candidates are read wider than `k` and cut to `k` after the filter:
/// the right street is rarely first among the namesakes of the whole sheet (Mexico, 01.11.2026).
fn bare_street_near_code(
&self,
raw: &str,
variants: &[String],
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let cfg = &crate::rules::rules().city_tail;
let Some(near) = cfg
.get("postal_near_digits")
.and_then(|n| n.parse::<usize>().ok())
else {
return Vec::new();
};
let Some(code) = raw
.rsplit(',')
.next()
.and_then(|last| postal_segment(cfg, last.trim()))
else {
return Vec::new();
};
let Some(prefix) = code.get(..near) else {
return Vec::new();
};
for variant in variants {
let street = variant.split(',').next().unwrap_or("");
let mut found = self.query_feats_city_tail(variant, k.max(NEAR_CODE_WIDTH), focus);
found.retain(|(hit, _)| {
(hit.flags.contains(&"street_exact")
|| street_differs_only_by_rewrite_words(street, &hit.street))
&& matches!(hit.precision, "house" | "interp")
&& hit.postcode.starts_with(prefix)
});
if !found.is_empty() {
found.truncate(k);
return found;
}
}
Vec::new()
}
fn query_feats_city_tail(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let hits = self.query_feats_city_tail_read(raw, k, focus);
if hits.is_empty() && street_type_last() {
if let Some(alt) = saint_city_variant(raw) {
return self.query_feats_city_tail_read(&alt, k, focus);
}
}
// A neighbour far from the number written settles nothing either ("9828 101A Avenue,
// Edmonton" -> 1680 on a 101A Avenue without the quadrant, 8 km off).
if !hits
.first()
.is_some_and(|(hit, _)| street_in_commune(hit) && !neighbour_far_from_written(hit, raw))
{
if let Some(found) = self.quadrant_retry(raw, k, focus) {
return found;
}
}
// "WINDSOR ONT (1453 PRINCE RD)", "OSHAWA, ON - 1200 AIRPORT BLVD.", "Burnaby BC, 7348
// Edmonds St": the place written before the address. The address-first form is read as
// well, and its answer replaces the written form's only when it keeps the place (exact
// commune: a reading that dropped the place finds a road of that name in another town)
// and is strictly better by `hits_quality` (Canada, 29.10.2026: ISED station locations).
let reordered = city_first_reordered(raw);
// Read as written the place has no region anchor: a bare town of that name in another
// province ("ST-LEONARD, QC." -> Saint-Léonard, New Brunswick) is no answer.
let hits = match reordered.as_deref().and_then(city_tail) {
Some(tail)
if !strong_first(&hits)
&& hits.first().is_some_and(|(hit, _)| {
tail.region
.as_deref()
.is_some_and(|region| town_outside_region(hit, &tail.city, region))
}) =>
{
Vec::new()
}
_ => hits,
};
if let Some(reordered) = reordered {
let alternate = self.query_feats_city_tail_read(&reordered, k, focus);
// The place is kept by an exact commune, or — a merged city the sheet splits into its
// former municipalities ("TORONTO (100 WINGARDEN CRT) ON" stands in Scarborough) —
// by an exact street with a house near a point the sheet's table gives for the named
// city in the named region (Canada, 29.10.2026).
let near_points = city_tail(&reordered).map_or_else(Vec::new, |tail| {
tail.region
.as_deref()
.map(|region| commune_region_points(&tail.city, region))
.unwrap_or_default()
});
if alternate
.first()
.is_some_and(|(hit, _)| city_first_keeps_place(hit, &near_points))
&& city_first_quality(&alternate, &reordered)
> city_first_quality(&hits, &reordered)
{
return alternate;
}
}
hits
}
/// "10025 105 Street, Edmonton": the sheet names every street of the city with its quadrant
/// ("105 St Nw") and the writer left it out. Each quadrant of the sheet's `quadrant_suffixes`
/// is appended to the street; the answer is taken only when exactly one quadrant reaches the
/// street in the named commune, a house before an interpolation or a neighbour — two
/// quadrants with the street ("14 Ave NW", "14 Ave SW") are no answer (Canada, 29.10.2026).
fn quadrant_retry(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let variants = quadrant_variants(raw);
if variants.is_empty() {
return None;
}
pick_quadrant(
variants
.iter()
.map(|alt| self.query_feats_city_tail_read(alt, k, focus))
.collect(),
)
}
fn query_feats_city_tail_read(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
// "702 W Idaho St Ste 312, Boise, ID 83702": the unit designator at the end of the
// street segment is read past before anything else.
if let Some(cleaned) = strip_unit_designators(raw) {
return self.query_feats_city_tail(&cleaned, k, focus);
}
if let Some(cleaned) = strip_pattern_postals(raw) {
return self.query_feats_city_tail(&cleaned, k, focus);
}
// The commaless form is read without its code and region; the answer stands only in an
// exact commune — the region it no longer carries cannot hold a homonym elsewhere.
if let Some(bare) = commaless_postal_tail(raw) {
let hits = self.query_feats_city_tail(&bare, k, focus);
if hits
.first()
.is_some_and(|(hit, _)| hit.flags.contains(&"commune_exact"))
{
return hits;
}
}
if let Some(civic) = unit_hyphen_civic(raw) {
return self.query_feats_city_tail(&civic, k, focus);
}
if let Some(glued) = glue_road_numbers(raw) {
return self.query_feats_city_tail(&glued, k, focus);
}
let Some(tail) = city_tail(raw) else {
return self.query_feats_country_variants(raw, k, focus);
};
// "Lexington, KY": the sheet's table says where a Lexington of Kentucky is; the commune
// lookups keep only the homonyms there, and answers elsewhere are the homonym, not the
// place (US, 21–22.10.2026).
let points = tail
.region
.as_deref()
.map(|region| commune_region_points(&tail.city, region))
.unwrap_or_default();
let _held = commune_region_scope(&tail.city, points.clone());
if !points.is_empty() {
// Under an umbrella (the city is no commune of the sheet within the region) only
// an exact street with a house, an interpolation or a neighbour is an answer: a
// fuzzy street or a bare place of some commune 15 km away is the neighbour, not
// the city. A street that differs from the one written only by a direction or a
// type word the sheet rewrites is the exact one.
let query_street = raw.split(',').next().unwrap_or("");
let strict = |hit: &Hit| {
hit.flags.contains(&"street_exact")
&& matches!(hit.precision, "house" | "interp" | "near")
};
let acceptable = |hit: &Hit| {
(hit.flags.contains(&"street_exact")
|| street_differs_only_by_rewrite_words(query_street, &hit.street))
&& matches!(hit.precision, "house" | "interp" | "near")
};
// Exact first: the relaxed streets are read only when no exact one is there
// ("1 Madison Avenue" keeps Madison Avenue over an East Madison Avenue).
let keep_acceptable = |hits: &mut Vec<(Hit, [f32; N_FEATS])>| {
if hits.iter().any(|(hit, _)| strict(hit)) {
hits.retain(|(hit, _)| strict(hit));
} else {
hits.retain(|(hit, _)| acceptable(hit));
}
};
let umbrella = self
.held_by_region(self.communes_by_name_unheld(&tail.city))
.is_empty();
let under_umbrella = |mut hits: Vec<(Hit, [f32; N_FEATS])>| {
if umbrella {
keep_acceptable(&mut hits);
}
hits
};
// With the region known, both readings are tried and the better answer wins: the
// region word itself reads as a place ("OREGON" prefixes Oregon City, "INDIANA"
// Indianapolis), and under the anchor such a neighbour is the only homonym left;
// yet the original form sometimes reaches a house the retry misses (a commune
// coded "ATL" under "…, Atlanta, Georgia"). A tie goes to the region-less retry.
let original = under_umbrella(within_commune_region(
self.query_feats_country_variants(raw, k, focus),
&points,
));
// The `postal_city` reading has dropped the inner segments (the colonia): it may land
// on a namesake street anywhere in the city, so only an answer inside the postal code
// written stands (Mexico, 31.10.2026: 202 of 324 new answers without the code were
// farther than 150 m).
let inside_code = |mut hits: Vec<(Hit, [f32; N_FEATS])>| {
if tail.postal_city {
hits.retain(|(hit, _)| hit.flags.contains(&"pc_exact"));
}
hits
};
let alternate = inside_code(under_umbrella(within_commune_region(
self.query_feats_country_variants(&tail.without_region, k, focus),
&points,
)));
let best =
if !alternate.is_empty() && hits_quality(&alternate) >= hits_quality(&original) {
alternate
} else if strong_first(&original) || alternate.is_empty() {
original
} else {
alternate
};
// The city is a commune of the sheet, yet the address may live next door under
// another name ("ATL" beside "Atlanta", "Financial District" beside "New York
// City"): when the city's own reading gives no exact street with a house, an
// interpolation or a neighbour, the umbrella is read too, under that acceptance,
// and the better answer wins. A neighbour on the exact street in the right city is
// kept over a house in the next town.
// An answer read off range points (`range`) does not settle the city either: the
// umbrella may hold the real house.
// Nor does a neighbour whose number is far from the one written ("3400 Eglinton Ave
// E, Toronto" -> 600 on the Toronto stretch; 3400 stands in Scarborough): the
// umbrella is read, and only a strictly better answer replaces it (Canada, 29.10.2026).
let accepted = |hits: &Vec<(Hit, [f32; N_FEATS])>| {
hits.first().is_some_and(|(hit, _)| {
acceptable(hit)
&& !hit.flags.contains(&"range")
&& !neighbour_far_from_written(hit, raw)
})
};
if umbrella && best.is_empty() {
// The city is no commune of the sheet under the anchor and nothing read: the
// postal code alone still names the place ("1 Water Street, 12590").
return self.city_tail_postal_only(&tail, k, focus, &points);
}
if umbrella || accepted(&best) {
return best;
}
drop(_held);
let _widened = commune_region_scope_widened(&tail.city, points.clone(), true);
let mut wide = inside_code(within_commune_region(
self.query_feats_country_variants(&tail.without_region, k, focus),
&points,
));
keep_acceptable(&mut wide);
return if !wide.is_empty() && hits_quality(&wide) > hits_quality(&best) {
wide
} else {
best
};
}
let original = self.query_feats_country_variants(raw, k, focus);
let chosen = city_tail_choose_region(
within_commune_region(original, &points),
&tail.city,
&tail.region_word,
|| {
within_commune_region(
tail.retry
.as_deref()
.map(|q| self.query_feats_country_variants(q, k, focus))
.unwrap_or_default(),
&points,
)
},
);
let chosen = if chosen.is_empty() {
self.postal_city_regionless(&tail, k, focus)
} else {
chosen
};
if chosen.is_empty() && self.communes_by_name(&tail.city).is_empty() {
return self.city_tail_postal_only(&tail, k, focus, &points);
}
// "4900 Meridian Street, Normal, AL 35762": no table point for this Normal, and the
// Normal of another state answers as a bare place. With a postal code in the tail an
// answer that is only a place, or whose postcode is not the one written, yields to the
// exact street inside that code when there is one (US, 23.10.2026).
// (An empty reading for a city the sheet knows stays empty: a conflicting code does
// not send the query to another town's house.)
let weak = chosen
.first()
.is_some_and(|(hit, _)| hit.precision == "city" || !hit.flags.contains(&"pc_exact"));
if weak && tail.without_city.is_some() {
let inside = self.city_tail_postal_only(&tail, k, focus, &points);
if !inside.is_empty() {
return inside;
}
}
chosen
}
/// "Tonalá 43, Col. Roma, 06700 Cuauhtémoc, Ciudad de México": the city has no table point,
/// and the colonia between the street and the city leaves the reading empty. Under the
/// `postal_city` form the region-less reading (street, city, code) is tried, and only a house
/// or an interpolation inside the code written is an answer: a neighbour or a bare street is
/// what dropping the colonia can fake, and so is a fuzzy street ("Miguel Palacios 12, …,
/// Xalapa-Enríquez" -> "Juan de la Luz Enríquez"), as in `city_tail_postal_only`
/// (Mexico, 01.11.2026).
fn postal_city_regionless(
&self,
tail: &CityTail,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
if !tail.postal_city {
return Vec::new();
}
let query_street = tail.without_region.split(',').next().unwrap_or("");
let mut hits = self.query_feats_country_variants(&tail.without_region, k, focus);
hits.retain(|(hit, _)| {
(hit.flags.contains(&"street_exact")
|| street_differs_only_by_rewrite_words(query_street, &hit.street))
&& hit.flags.contains(&"pc_exact")
&& matches!(hit.precision, "house" | "interp")
});
hits
}
/// The tail names a city the sheet has no commune for, and a postal code: the query is
/// read without the city, and only an exact street with a house, an interpolation or a
/// neighbour inside that code is an answer (the code is the place; a fuzzy street or a
/// bare place elsewhere is not). Data-driven: only a tail with a postal code builds the
/// reading (US, 22.10.2026: "New Hamburg", "S Portland").
fn city_tail_postal_only(
&self,
tail: &CityTail,
k: usize,
focus: Option<&QueryFocus>,
points: &[(f64, f64)],
) -> Vec<(Hit, [f32; N_FEATS])> {
let Some(query) = tail.without_city.as_deref() else {
return Vec::new();
};
let query_street = query.split(',').next().unwrap_or("");
let mut hits =
within_commune_region(self.query_feats_country_variants(query, k, focus), points);
hits.retain(|(hit, _)| {
(hit.flags.contains(&"street_exact")
|| street_differs_only_by_rewrite_words(query_street, &hit.street))
&& hit.flags.contains(&"pc_exact")
&& matches!(hit.precision, "house" | "interp" | "near")
});
hits
}
fn query_feats_country_variants(
&self,
raw: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
if self.country() == Some("es") {
return self.es_particle_retry(raw, k, focus);
}
if self.country() != Some("de") {
let annotated = self.it_province_annotation(raw);
let raw = annotated.as_deref().unwrap_or(raw);
return self.query_feats_d(raw, k, 0, focus, None, None, false, None);
}
let original_cityless_street = Self::de_cityless_street(raw);
// Only the exact typed X2 surface needs the already-ranked frozen
// top-5 window for a caller requesting top-1. Every other DE query
// retains its established caller-k work bound.
let product_k = if de_street_locality_qualifier_spec(raw).is_some() {
k.max(5)
} else {
k
};
// Freeze the user's normalized post-postcode locality before any DE variant or
// city-alias rewrite. Every variant may change the lookup query, but none may
// manufacture stronger retained-locality evidence than the text the user supplied.
let de_original_postcode_context = de_postcode_context(&normalize(raw));
let de_original_postcode = de_original_postcode_context
.as_ref()
.map(|(postcode, _)| *postcode);
let de_original_postcode_tail = de_original_postcode_context
.as_ref()
.map(|(_, tail)| tail.as_str());
let de_parenthetical_subaddress_commune = crate::de::parenthetical_subaddress_commune(raw);
let mut best: Vec<(Hit, [f32; N_FEATS])> = Vec::new();
let mut best_quality: Option<(i32, u8, u8, f32)> = None;
let frankfurt = crate::de::frankfurt_qualifier(raw);
let de_postal_tail_eligible = crate::de::postal_tail_eligible(raw);
let variants = crate::de::query_variants(raw);
let official_alias_constrained = variants.iter().any(|variant| {
variant
.effects
.contains(&crate::de::Effect::OfficialCommuneAlias)
&& variant.required_commune.is_some()
});
let alias_target = variants
.iter()
.find_map(|variant| variant.required_commune.clone());
let alias_constrained = alias_target.is_some();
let hard_commune = frankfurt.map(str::to_string).or(alias_target);
let search_k = if hard_commune.is_some() {
product_k.max(20)
} else {
product_k
};
// Raw and normalized DE variants usually converge to the exact same
// prepared query. A previous non-city result is reusable only when the
// variant effects and commune constraint are also identical. City/empty
// outcomes remain uncached because the final settlement fallback still
// inspects raw comma-delimited segments.
let mut reusable_prepared: Vec<(String, Vec<crate::de::Effect>, Option<String>)> =
Vec::new();
for variant in variants {
if variant
.required_commune
.as_deref()
.is_some_and(|target| self.communes_fst.get(target.as_bytes()).is_none())
{
continue;
}
let prepared = prepared_query_key(&variant.query);
if reusable_prepared.iter().any(|(seen, effects, required)| {
seen == &prepared
&& effects == &variant.effects
&& required == &variant.required_commune
}) {
continue;
}
#[cfg(test)]
DE_COUNTRY_VARIANT_PREPARED_SEARCH_CALLS
.with(|calls| calls.set(calls.get().saturating_add(1)));
let mut candidate = self.query_feats_d(
&variant.query,
search_k,
0,
focus,
de_original_postcode_tail,
de_original_postcode,
de_postal_tail_eligible,
original_cityless_street.as_deref(),
);
if candidate
.first()
.is_some_and(|(hit, _)| hit.precision != "city")
{
reusable_prepared.push((
prepared,
variant.effects.clone(),
variant.required_commune.clone(),
));
}
if variant.effects.contains(&crate::de::Effect::PostcodeZero) {
candidate.retain(|(_, features)| Feats::from_vec(features).pc_exact);
}
if let Some(expected) = hard_commune.as_deref() {
candidate.retain(|(hit, _)| normalize(&hit.commune) == expected);
}
if official_alias_constrained {
if hard_commune.as_deref() == Some("ludwigshafen am rhein") {
let Some(position) =
Self::de_ludwigshafen_official_alias_candidate_position(raw, &candidate)
else {
continue;
};
let chosen = candidate.remove(position);
candidate.insert(0, chosen);
} else if !Self::de_official_commune_alias_candidate_is_exact(&candidate) {
continue;
}
}
candidate.truncate(product_k);
if variant
.effects
.contains(&crate::de::Effect::ParentheticalSubaddress)
&& !Self::de_parenthetical_subaddress_may_fill(
&best,
&candidate,
de_parenthetical_subaddress_commune.as_deref(),
)
{
continue;
}
let Some(quality) = Self::de_variant_quality(&candidate) else {
continue;
};
if variant.effects.contains(&crate::de::Effect::Abbreviation)
&& !Self::de_abbreviation_candidate_may_displace(
&candidate,
&best,
de_original_postcode_tail,
)
{
continue;
}
if variant.effects.contains(&crate::de::Effect::PostcodeZero)
&& best_quality.is_some_and(|current| quality.1 < current.1)
{
// A four-digit token is ambiguous with a house number. Padding
// it may add exact-postcode evidence, but must never downgrade
// an existing house/near/interpolation answer to street level.
continue;
}
let proven_recipient_tie = best_quality.is_some_and(|current| {
quality == current
&& variant
.effects
.contains(&crate::de::Effect::RecipientPrefix)
&& Self::de_recipient_cleanup_breaks_dropped_prefix_tie(&candidate, &best)
});
if best_quality.is_none_or(|current| Self::de_quality_is_better(quality, current))
|| proven_recipient_tie
{
let mut applied_effects = variant.effects.clone();
if official_alias_constrained {
if !applied_effects.contains(&crate::de::Effect::OfficialCommuneAlias) {
applied_effects.push(crate::de::Effect::OfficialCommuneAlias);
}
} else if alias_constrained
&& !applied_effects.contains(&crate::de::Effect::CityAlias)
{
// Even an otherwise successful original spelling is admissible only
// because the exonym supplied this hard commune constraint.
applied_effects.push(crate::de::Effect::CityAlias);
}
Self::annotate_de_effects(&mut candidate, &applied_effects);
best = candidate;
best_quality = Some(quality);
}
}
let ludwigshafen_alias_selected = hard_commune.as_deref() == Some("ludwigshafen am rhein")
&& best
.first()
.is_some_and(|(hit, _)| hit.flags.contains(&"de_official_commune_alias"));
if !ludwigshafen_alias_selected && Self::de_should_try_postcode_house_rescue(raw, &best) {
if let Some(rescue) = self.de_comma_postcode_house_rescue(raw, k, focus) {
best = rescue;
} else if let Some(rescue) =
self.de_strict_postcode_house_set_override(raw, &best, k, focus)
{
best = rescue;
} else if !Self::de_has_complete_postcode_house_evidence(&best) {
if let Some(rescue) = self.de_compact_house_pair_left_rescue(raw, k, focus) {
best = rescue;
}
}
}
let x2 = Self::de_street_locality_qualifier_position(raw, &best);
let p3 = self.de_strict_source_street_typo_fallback(raw, &best, k);
let p4 = self.de_audited_compound_fallback(raw, k);
let p5 = self.de_blank_postcode_exact_house_fallback(raw, &best, k, focus);
Self::de_product_fallback_arbitration(&mut best, p3, p4, x2, p5);
if frankfurt.is_some() {
for (hit, _) in &mut best {
if !hit.flags.contains(&"de_frankfurt") {
hit.flags.push("de_frankfurt");
}
}
}
best.truncate(k);
best
}
/// Confidence is MONOTONE by rank: a lower-ranked answer cannot look "more confident"
/// than the one above it. The margin cutoff (and similar mechanics) lowers ONLY the
/// top-1 (ambiguous_far); without this clamp a consumer would see the contradiction
/// "top-1 0.2, top-2 0.6" and distrust the order. Ranking is untouched — only the
/// visible confidence is leveled down the list.
fn monotone_confidence(hits: &mut [(Hit, [f32; N_FEATS])]) {
let mut cap = f32::MAX;
for (h, _) in hits.iter_mut() {
if h.confidence > cap {
h.confidence = cap;
}
cap = h.confidence;
}
}
// Frozen release: retain each provenance flag and the validated recursive call sites.
#[allow(clippy::too_many_arguments)]
fn query_feats_d(
&self,
raw: &str,
k: usize,
depth: u8,
focus: Option<&QueryFocus>,
de_original_postcode_tail: Option<&str>,
de_original_postcode: Option<u32>,
de_postal_tail_eligible: bool,
original_cityless_street: Option<&str>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let normalized_raw = prepared_query_key(raw);
let q = self.expand_city_aliases(&normalized_raw);
// French arrondissements: context-gated rewrite of "3eme"/Roman/order forms to the canon
let q = fr_arrondissement_rewrite(&q).unwrap_or(q);
// phone-number runs: cut before parsing, else digit pairs become "houses"
let q = strip_phone_runs(&q).unwrap_or(q);
// In Paris/Lyon/Marseille the postcode itself identifies an arrondissement. Handle
// postcode-only and postcode+area queries before the address parser can mistake the
// five-digit code for a house number. Contradictory area hints fail closed.
if self.country() == Some("fr") {
match fr_arrondissement_postcode_area(&q) {
Some(FrPostcodeArea::Match(place)) => {
return self
.resolve_place_translit(&place)
.map(|(lat, lon, commune, _, exact)| {
Self::city_hit(lat, lon, commune, exact)
})
.unwrap_or_default();
}
Some(FrPostcodeArea::Conflict) => return Vec::new(),
None => {}
}
}
// city-only: the whole string (minus digits) EXACTLY matches a commune name -> the
// city point (precision "city"). Otherwise the engine fuzzes a bare city into a
// same-named street tens of km away ("Eindhoven" -> "Eindhovenlaan,
// s-Hertogenbosch"). Among homonyms, the most prominent one wins.
let city_phrase: String = q
.split(' ')
.filter(|t| !t.is_empty() && !t.bytes().all(|b| b.is_ascii_digit()))
.collect::<Vec<_>>()
.join(" ");
// with a DIGIT in the query this shortcut would swallow the house number whenever a
// street shares its name with a commune. With a digit the street path goes first;
// the city fallback (d) at the end still provides city-level coverage.
let has_digit_tok = q
.split(' ')
.any(|t| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()));
if !city_phrase.is_empty() && !has_digit_tok {
// Universal bare-place-name resolution -> a point (the center). Works for ANY
// country without lists: city, district, estate, arrondissement — each is
// either a commune or a prefix commune group. Transliteration both ways: a
// Cyrillic query finds Latin-script communes and vice versa.
if let Some((lat, lon, commune, _, exact)) = self.resolve_place_translit(&city_phrase) {
return Self::city_hit(lat, lon, commune, exact);
}
}
let fr_area_signal = if self.country() == Some("fr") {
fr_arrondissement_constraint(&q)
} else {
None
};
if fr_area_signal == Some(FrPostcodeArea::Conflict) {
return Vec::new();
}
let fr_area_constraint = match fr_area_signal {
Some(FrPostcodeArea::Match(area)) => Some(area),
_ => None,
};
// The unconstrained winner can sit in another arrondissement while a lower-ranked,
// valid candidate exists in the requested one (`1 rue de rivoli 75001 paris`).
// Pull a bounded candidate window before enforcing the hard postcondition, then restore
// the caller's k. Without this, k=1 becomes an accidental false-empty.
let prepared_k = if fr_area_constraint.is_some() {
k.max(20)
} else {
k
};
let mut hits =
self.query_feats_prepared_cityless(&q, prepared_k, focus, original_cityless_street);
if let Some(expected) = fr_area_constraint.as_deref() {
hits.retain(|(hit, _)| normalize(&hit.commune) == expected);
hits.truncate(k);
}
// A suffix immediately after a distant Italian homonym may be a geographic qualifier,
// not another street/city token. The ordinary full-query interpretation has precedence:
// only retry when it could not produce any exact-street + exact-commune candidate. This
// preserves addresses whose street happens to end in a homonymous place word, such as
// `Vicolo del Ponte, Macerata`.
let primary_has_exact_address = hits
.iter()
.any(|(_, features)| features[0] > 0.5 && features[2] > 0.5);
if depth == 0 && self.country() == Some("it") && !primary_has_exact_address {
if let Some(qualified) = self.trailing_homonym_qualifier_retry(&q, k, focus) {
return qualified;
}
}
if !hits.is_empty() {
// "city first + trailing number": see city_first_house_retry
if depth == 0 && hits[0].0.precision == "street" {
if let Some(h2) = self.city_first_house_retry(&q, k, focus) {
return h2;
}
}
return hits;
}
if fr_area_constraint.is_some() {
return Vec::new();
}
// unglue "c5" -> "c 5" on an EMPTY result: preprocessing glues hyphenated codes
// ("c-5" -> "c5") while the index (normalization splits hyphens) stores "c 5", so
// the exact key is unreachable ("kiet c-5", "Labzak"). Retry the unglued form.
if let Some(u) = unglue_variant(&q) {
let uq = fold_units(&u);
let h = self.query_feats_prepared(&uq, k, focus);
if !h.is_empty() {
// unglued form yielded only a street with a leading city — same refinement
if h[0].0.precision == "street" {
if let Some(h2) = self.city_first_house_retry(&uq, k, focus) {
return h2;
}
}
return h;
}
}
// cross-script fallback passes on an empty result:
// (a) Cyrillic -> Latin, Serbian Gaj mapping — for Serbian Latin-script data
if crate::norm::has_cyrillic(&q) {
let q2 = normalize(&crate::norm::translit_cyr_lat(&q));
if q2 != q {
let h = self.query_feats_prepared(&q2, k, focus);
if !h.is_empty() {
return h;
}
}
// (a2) Cyrillic -> Latin with ENGLISH digraphs — for Uzbek Latin-script data
// ("farobiy ko'chasi"); tried when the Serbian mapping (a) found nothing
let q2e = normalize(&crate::norm::translit_cyr_lat_en(&q));
if q2e != q && q2e != normalize(&crate::norm::translit_cyr_lat(&q)) {
let h = self.query_feats_prepared(&q2e, k, focus);
if !h.is_empty() {
return h;
}
}
}
// (b) Latin -> Cyrillic (for Cyrillic-script data):
// "bratsk mira 60" — a Latin query against Cyrillic street names
if crate::norm::has_latin(&q) {
let q3 = normalize(&crate::norm::translit_lat_cyr(&q));
if q3 != q {
let h = self.query_feats_prepared(&q3, k, focus);
if !h.is_empty() {
return h;
}
// transliteration + unglue: "kiet c-5" -> fused Cyrillic form -> spaced form
// (the commune itself is stored in Cyrillic with a spaced block code)
if let Some(u) = unglue_variant(&q3) {
let h = self.query_feats_prepared(&u, k, focus);
if !h.is_empty() {
return h;
}
}
}
}
// (b2) a single "j" is ambiguous between two Cyrillic letters. French-style name
// spellings use "j" for the "zh" sound ("Lejena"). Try the zh-variant (j -> zh)
// when the primary mapping (j -> y) is empty. Only affects words containing "j".
if q.contains('j') {
let q3b = normalize(&crate::norm::translit_lat_cyr(&q.replace('j', "zh")));
if q3b != q {
let h = self.query_feats_prepared(&q3b, k, focus);
if !h.is_empty() {
return h;
}
}
}
// (s) Serbian orthographic digraph dj -> d: normalization folds đ -> d (the index
// stores "karadordeva", see norm.rs), so bare "d" and the đ form match directly.
// That leaves the "dj" digraph ("Karadjordjeva", "Djusina") — on an empty primary
// path try dj -> d. Cheap, and only when "dj" is present.
if q.contains("dj") {
let swapped = q.replace("dj", "d");
if swapped != q {
let h = self.query_feats_prepared(&swapped, k, focus);
if !h.is_empty() {
return h;
}
}
}
// (c) junk before the address: drop leading words ("c/o Rossi, Corso Italia 10",
// "maps via ...", a venue name up front). Accepted on a house match; OR when the
// dropped prefix is a REAL commune / umbrella city: settlements under an umbrella
// live under their OWN commune name, and the umbrella prefix merely blocks the
// commune match — then a street-level result is accepted too. Fires only when the
// primary (commune-aware) path is ALREADY empty, so homonyms thousands of km away
// never reach here (their primary path is non-empty).
let toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
// The drops below search the street without the locality the query names. Their
// answers must stay in that locality: "Alexanderplatz 1, Berlin" must not become the
// street "Berlin 1" in a village, nor "Friedrichstraße 100, Berlin" the one in Dortmund.
let anchor = self.named_locality_anchor(&toks);
// (c0) LEADING TYPE WORD ("street X 12", "estate Y 6"): strip up to 3 affixes
// (place type/prefix) from the start and run the FULL ladder on the remainder
// (including transliteration, which the junk drop below lacks). A bare name
// resolves correctly, while a leading type shifts the name from the string start
// so prefix matching fails. Affixes only — distinguishing names are never
// stripped. One level of recursion (depth>0 does not repeat this).
if depth == 0 {
let mut d = 0;
while d + 1 < toks.len() && d < 3 && is_affix_word(toks[d]) {
d += 1;
}
if d > 0 {
let h = self.query_feats_d(
&toks[d..].join(" "),
k,
depth + 1,
focus,
de_original_postcode_tail,
de_original_postcode,
de_postal_tail_eligible,
original_cityless_street,
);
if !h.is_empty() {
return h;
}
}
}
// up to 8 leading words: a leading VENUE NAME can be long ("Coupole de l'Institut
// de France, 23 Quai de Conti..." is 6 junk tokens; the apostrophe adds an extra
// "l" token). The pass is house-gated, so the wide window is safe: accepted only
// if an EXACT house resolves after the drop.
let maxd = 8.min(toks.len().saturating_sub(2));
let mut deferred_prefix = None;
for drop in 1..=maxd {
let mut h = self.query_feats_prepared(&toks[drop..].join(" "), k, focus);
if let (Some(postcode), Some(postcode_tail)) =
(de_original_postcode, de_original_postcode_tail)
{
h.retain(|(hit, features)| {
de_prefix_drop_preserves_postcode_locality(
hit,
features,
postcode,
postcode_tail,
)
});
}
h.retain(|(hit, _)| self.near_named_locality(hit, &anchor));
let dropped_is_commune = !self.communes_by_name(&toks[..drop].join(" ")).is_empty();
if dropped_is_commune {
// the dropped head names the city ("Berlin, Friedrichstraße 100"): its
// settlements may answer, a same-named street in another town may not
let head = self.named_locality_runs(&toks[..drop]);
h.retain(|(hit, _)| self.near_named_locality(hit, &head));
}
if h.is_empty() {
continue;
}
// "city as street" guard: after the drop a remainder like "109 amsterdam" gets
// FUZZY-matched as a street ("Amsterdam" -> "Amsterdamseweg" 90 km away, a
// false house). Accept a house ONLY from an EXACT street (feats[0]=
// street_exact), not fuzzy. Real streets behind junk still pass (their street
// matches exactly), while fuzzy city-as-street is cut.
// feats: [street_exact, street_fuzzy, ...].
let house_exact = h
.iter()
.any(|(hit, f)| hit.precision == "house" && f[0] > 0.5);
// a numberless query with leading noise ("Hotel rue de Rivoli Paris") would die
// entirely under a house-only gate. If a street type (rue/via/...) follows the
// drop and the match is exact, accept street level too (conf cap/flag below).
// ... unless nothing of a street name survives the drop: on a sheet whose type
// trails the name (city_tail `street_type_last`) a remainder of the type word plus
// place and region names only ("st boise id 83702" for "619 Grove St, Boise, ID"
// once "619 grove" is gone) is the city written as a street ("Boise Street",
// Nampa), not an address; the drop then yields nothing. Where the type leads the
// name a place name after it is a street ("Via Roma"), and the guard stays off
// (US, 22.10.2026; Italy lost "Via Roma" in Premilcuore under the ungated guard).
let street_after_type = is_street_type_word(toks[drop])
&& !(street_type_last() && self.remainder_names_only_places(&toks[drop + 1..]))
&& h.iter()
.any(|(hit, f)| f[0] > 0.5 && hit.precision != "city");
if crate::diagnosis::enabled() {
crate::diagnosis::guard(
"prefix_drop",
h.len(),
house_exact || dropped_is_commune || street_after_type,
serde_json::json!({"house_exact": house_exact, "dropped_is_commune": dropped_is_commune,
"street_after_type": street_after_type, "top": h.first().map(|(hit, _)| hit)}),
);
}
if house_exact
|| dropped_is_commune
|| street_after_type
|| h.first().is_some_and(|(hit, _)| {
hit.flags.contains(&"commune_exact") && hit.flags.contains(&"pc_exact")
})
{
// the drop is not silent: "Jan van Harenstraat" -> "Van Harenstraat" must
// not come back looking perfect. Flag it and cap confidence; dropping a
// REAL umbrella commune is semantically clean and is not penalized.
if !dropped_is_commune {
let mut h = h;
for (hit, _) in h.iter_mut() {
hit.confidence = hit.confidence.min(0.6);
hit.flags.push("dropped_prefix");
}
// Keep the first bypass while checking longer prefix drops
// and an accepted tail drop for a stronger answer.
if !house_exact && !street_after_type {
if deferred_prefix.is_none() {
let mut h = h;
for (hit, _) in &mut h {
hit.flags.push(DEFERRED_LOCALITY_DROP);
}
deferred_prefix = Some(h);
}
continue;
}
return h;
}
return h;
}
}
// (c2) SYMMETRIC to the front drop: an unrecognized TAIL after the commune
// ("... Lyon Xyz", marketing suffixes). Drop 1-2 trailing tokens; same gate as the
// front drop: accept ONLY an exact street (feats[0]=street_exact), never fuzzy —
// and honestly flag/cap confidence. Digit tails are NOT touched (a trailing house
// number is a legitimate form; dropping it would swap a house for a street).
{
let maxtd = 2.min(toks.len().saturating_sub(2));
// A full commune at the tail is stronger evidence than an unrecognized suffix.
// Inspect the whole drop window BEFORE trying a shorter drop: otherwise
// "Via Falsa San Fratello" first removes only "fratello" and revives a
// same-named street in an unrelated commune.
if self.country() == Some("it")
&& (1..=maxtd).any(|tail_len| {
!self
.communes_by_name(&toks[toks.len() - tail_len..].join(" "))
.is_empty()
})
{
// An exact trailing commune blocks street search elsewhere, but can
// still answer an area query. Preserve the existing house-number guard.
let has_house = toks
.iter()
.any(|t| t.len() != 5 && t.bytes().all(|b| b.is_ascii_digit()));
if !has_house {
// IT commune names have at most 6 words (2026-09-20); allow 3 spare.
for tail_len in (1..=toks.len().min(9)).rev() {
let place = toks[toks.len() - tail_len..].join(" ");
if !self.communes_by_name(&place).is_empty() {
if let Some((lat, lon, commune, _, exact)) = self.resolve_place(&place)
{
return Self::city_hit(lat, lon, commune, exact);
}
}
}
}
return deferred_prefix.unwrap_or_default();
}
for drop in 1..=maxtd {
if toks[toks.len() - drop..]
.iter()
.any(|t| t.bytes().all(|b| b.is_ascii_digit()))
{
break;
}
let shortened = toks[..toks.len() - drop].join(" ");
let dropped_tail = toks[toks.len() - drop..].join(" ");
let retained = de_retained_locality(
de_original_postcode_tail,
&dropped_tail,
de_postal_tail_eligible,
);
let mut h = self
.query_feats_prepared_with_retained_locality(&shortened, k, focus, retained);
h.retain(|(hit, _)| self.near_named_locality(hit, &anchor));
// Nothing left inside the named locality: the street may still be there under
// a district commune (Berlin "Mitte"). Search again focused on the locality's
// most prominent centroid; the same locality check applies to the answer.
if h.is_empty() && focus.is_none() {
if let Some(&(id, _, _)) = anchor
.communes
.iter()
.max_by_key(|&&(id, _, _)| self.commune_prominence(id))
{
let (lat, lon) = self.commune_coord(id);
let local = QueryFocus {
lat,
lon,
streets: self.streets_around(lat, lon),
};
h = self.query_feats_prepared_with_retained_locality(
&shortened,
k,
Some(&local),
retained,
);
h.retain(|(hit, _)| self.near_named_locality(hit, &anchor));
}
}
if h.is_empty() {
continue;
}
let exact_ok = h
.iter()
.any(|(hit, f)| f[0] > 0.5 && hit.precision != "city");
if crate::diagnosis::enabled() {
crate::diagnosis::guard(
"suffix_drop",
h.len(),
exact_ok,
serde_json::json!({"exact_street_noncity": exact_ok, "top": h.first().map(|(hit, _)| hit)}),
);
}
if exact_ok
|| h.first().is_some_and(|(hit, _)| {
hit.flags.contains(&"commune_exact") && hit.flags.contains(&"pc_exact")
})
{
// A weaker tail locality must not replace the exact locality
// that justified the saved prefix bypass. Stop at this first
// accepted tail, even when a later drop could also answer.
if !h.first().is_some_and(|(hit, _)| {
hit.flags.contains(&"commune_exact") && hit.flags.contains(&"pc_exact")
}) {
if let Some(prefix) = deferred_prefix.take() {
return prefix;
}
}
let mut h = h;
for (hit, _) in h.iter_mut() {
hit.confidence = hit.confidence.min(0.6);
hit.flags.push("dropped_suffix");
if !exact_ok {
hit.flags.push(DEFERRED_LOCALITY_DROP);
}
}
h.truncate(k);
return h;
}
}
}
if let Some(h) = deferred_prefix {
return h;
}
// (d) LAST resort — degrade to a settlement. Everything failed but the string
// holds a place name: a city/district trailing a listing, OR a settlement with a
// house number but no streets. Take the last segments (including parenthesized
// aliases), strip settlement type words and try each as a place name. City level
// ONLY (resolve_place, no street search) — stray same-named streets never get
// here; a non-address stays empty. Segments come from raw (q has no commas/
// brackets left).
// candidate segments: non-empty and digit-free (filtered BEFORE take, so an
// umbrella city is not pushed out of the window by an empty bracket segment).
// a LEADING postcode is trimmed off a segment ("2513 AA Den Haag" -> "Den Haag")
// so that "postcode + city" still degrades to the city. Digits MID-segment still
// exclude it (a street+number segment must not become a city).
fn strip_leading_pc(s: &str) -> &str {
let t = s.trim_start();
let d = t.bytes().take_while(|b| b.is_ascii_digit()).count();
if !(4..=6).contains(&d) {
return s;
}
let mut rest = t[d..].trim_start();
let letters = rest.bytes().take_while(|b| b.is_ascii_alphabetic()).count();
if letters == 2 && rest.as_bytes().get(2).is_none_or(|b| *b == b' ') {
rest = rest[2..].trim_start(); // NL postcode letters ("AA")
}
if rest.is_empty() {
s
} else {
rest
}
}
let segs: Vec<&str> = raw
.split([',', ';', '|', '·', '(', ')', '\n'])
.map(|s| strip_leading_pc(s.trim()))
.filter(|s| !s.is_empty() && !s.bytes().any(|b| b.is_ascii_digit()))
.collect();
let mut places: Vec<(f64, f64, String, u32, bool)> = Vec::new();
for seg in segs.iter().rev().take(6) {
let segn = self
.expand_city_aliases(&fold_units(&crate::norm::fold_homoglyphs(&normalize(seg))));
let toks: Vec<&str> = segn.split(' ').filter(|w| !w.is_empty()).collect();
if toks.is_empty() || toks.len() > 4 {
continue;
}
// forms by decreasing specificity: full -> without junk suffixes -> without the type prefix
let a: Vec<&str> = toks
.iter()
.copied()
.filter(|w| !crate::rules::rules().place_junk.contains(*w))
.collect();
let b: Vec<&str> = a
.iter()
.copied()
.filter(|w| !crate::rules::rules().place_prefix.contains(*w))
.collect();
for form in [toks.join(" "), a.join(" "), b.join(" ")] {
if form.is_empty() {
continue;
}
if let Some(p) = self.resolve_place_translit(&form) {
places.push(p);
break; // first form of the segment that resolves
}
}
}
let has_exact_place = places.iter().any(|p| p.4);
if let Some(anchor) = places
.iter()
.filter(|p| !has_exact_place || p.4)
.max_by_key(|p| p.3)
.cloned()
{
// ANCHOR against false homonyms: among the resolved places the anchor is the
// most prominent exact name (an umbrella city), or a prefix group only when
// no exact name resolved. The answer is the MOST specific place
// (minimal prominence) within 50 km of the anchor; a distant homonym hundreds
// of km away is filtered out.
let best = places
.iter()
.filter(|p| Self::dist_km(p.0, p.1, anchor.0, anchor.1) <= 50.0)
.min_by_key(|p| p.3)
.unwrap_or(&anchor);
// if the query has a HOUSE NUMBER it is an address and the user expects a
// HOUSE; a rough settlement/city center kilometers away is a substitution, not
// help — staying silent is more honest. Place degradation applies only to AREA
// queries WITHOUT a number. This "has number -> stay silent" guard must NOT
// choke "postcode + city" ("2513 AA Den Haag"): a 4-6-digit group counts as a
// postcode, not a house number (house numbers longer than 3 digits are rare,
// postcodes shorter than 4 do not exist).
let has_number = q
.split(' ')
.any(|t| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()) && t.len() <= 3);
if !has_number {
return Self::city_hit(best.0, best.1, best.2.clone(), best.4);
}
}
hits
}
/// Build ONE candidate Hit (house/interp/near/street via find_house, score, name
/// similarity, confidence, flags). Factored out of the main loop for reuse by
/// structured input. Returns (Hit, features, name similarity, SNAP DELTA, commune
/// prominence). Snap delta = |requested number - returned number|: on a split street a
/// near-snap onto another fragment (house 290 for a query of 2205) loses the tie-break
/// to the fragment with a nearby number; 0 for exact house/interp, MAX for street level.
fn make_hit(
&self,
sid: u32,
mut f: Feats,
numero: Option<u32>,
rep: u32,
requested_postcode: Option<u32>,
qwords: &[Vec<char>],
) -> RankedHit {
let m = self.street_meta(sid);
f.numero_present = numero.is_some();
let mut snap_delta = 0u32;
// Answers derived from range points (prep/us_tiger.py) carry the `range` flag: an
// interpolation between two of them, or a snap onto one. They are answers, yet weaker
// than a real house, and the city-tail reading does not let them hide an exact house
// under the umbrella.
let mut range_point = false;
let (lat, lon, precision, housenumber, house_postcode_off) =
match numero.and_then(|nm| self.find_house(sid, &m, nm, rep, requested_postcode)) {
Some((la, lo, kind @ (3 | 4), got, got_rep, postcode_off)) => {
// Interpolation returns the requested address, not either bracketing house.
range_point = kind == 4;
(
la,
lo,
"interp",
Some(self.house_number(got, got_rep)),
postcode_off,
)
}
Some((la, lo, kind, got, got_rep, postcode_off)) if kind >= 1 => {
f.house_found = true;
f.house_exact_rep = kind == 2;
(
la,
lo,
"house",
Some(self.house_number(got, got_rep)),
postcode_off,
)
}
Some((la, lo, _, got, got_rep, postcode_off)) => {
snap_delta = numero.map_or(0, |nm| nm.abs_diff(got));
range_point = Some(got_rep) == self.range_marker_rep;
// A snap is the neighbour's address; never echo the number that missed.
(
la,
lo,
"near",
Some(self.house_number(got, got_rep)),
postcode_off,
)
}
None => {
if numero.is_some() {
snap_delta = u32::MAX; // a street with no neighbor at all is worse than any snap
}
(
m.lat_c as f64 / 1e7,
m.lon_c as f64 / 1e7,
"street",
None,
0,
)
}
};
let rendered_postcode = self.postcode_for_house(&m, house_postcode_off);
if self.format_version >= 7
&& m.postcode_disp_off == PC_DISP_AMBIGUOUS
&& housenumber.is_some()
{
if let Some(requested) = requested_postcode {
let represented = Self::postcode_numeric_prefix(&rendered_postcode);
f.pc_exact = requested != 0 && represented == Some(requested);
f.pc_dept = requested != 0
&& represented.is_some_and(|postcode| postcode / 1000 == requested / 1000);
}
}
let mut score = match &self.rank {
Some(r) => r.score(&f),
None => f.legacy() as f32,
};
if f.house_found {
score += 1.0; // a house beats a same-named street in another region
}
crate::diagnosis::ranked(
sid,
m.commune_id,
m.house_count,
numero,
precision,
score,
self.name(m.name_off),
self.commune_name(m.commune_id),
);
let name_norm = normalize(self.name(m.name_off));
let mut name_sim = 0i32;
for w in name_norm.split(' ').filter(|w| !w.is_empty()) {
let wc: Vec<char> = w.chars().collect();
for qw in qwords {
let maxlen = wc.len().max(qw.len()).max(1);
let sim = 100 - (lev(&wc, qw) * 100 / maxlen) as i32;
if sim > name_sim {
name_sim = sim;
}
}
}
// Tie-break below the best word: does the name carry every query word that the sheet
// knows how to rewrite (directions and type words: "s" <-> "south", "street" <-> "st")
// — as written, through the rewrite, or as the same number without its ordinal suffix?
// Homonyms of one street that differ only by direction ("South Broadway", "North
// Broadway") score alike on the key; the one naming the query's direction ranks first.
// A yes/no over the rewritable words only: the query also carries the city and the
// postcode, and a fully spelled key must not outrank an abbreviated one ("W 52 St")
// that says the same (US, 22.10.2026).
let name_words: HashSet<&str> = name_norm.split(' ').filter(|w| !w.is_empty()).collect();
let rewrites = &crate::rules::rules().street_rewrites;
let rewritable = |q: &str| {
rewrites.iter().any(|(from, to)| {
(from == q && !to.contains(' ')) || (to == q && !from.contains(' '))
})
};
let mut asked = 0usize;
let covered = qwords
.iter()
.map(|qw| qw.iter().collect::<String>())
.filter(|q| rewritable(q))
.all(|q| {
asked += 1;
name_covers_word(&name_words, &q)
});
let name_sim = name_sim * 2 + i32::from(covered && asked > 0);
// confidence cannot stay high with a NEGATIVE ranking score: garbage like "name +
// phone" could yield a confident house — the score is the primary quality signal
let mut confidence = confidence_score(precision, &f, name_sim);
if score < 0.0 {
confidence = confidence.min(0.4);
}
(
Hit {
lat,
lon,
precision,
score,
confidence,
street: self.name(m.name_off).to_string(),
housenumber,
commune: self.commune_name(m.commune_id).to_string(),
postcode: rendered_postcode,
flags: {
let mut flags = match_flags(&f);
if range_point {
flags.push("range");
}
flags
},
region: self.admin_at(lat, lon), // WOF region in forward answers too
distance_m: None,
},
f.to_vec(),
name_sim,
snap_delta,
self.homonym_weight(m.commune_id),
sid,
)
}
/// STRUCTURED INPUT: pre-parsed street/number/city/postcode fields use the
/// direct structured resolver first. A DE sheet also compares the canonical
/// field join with the country-scoped free-form fallbacks. The structured
/// result keeps ties, so ordinary exact input is unchanged while Munich,
/// umlaut/digraph and compound street-type behavior stays in parity with the
/// public free-form API.
pub fn query_structured(
&self,
street: &str,
number: Option<&str>,
city: &str,
postcode: Option<&str>,
k: usize,
) -> Vec<(Hit, [f32; N_FEATS])> {
if self.country() != Some("de") || k == 0 {
return self.query_structured_primary(street, number, city, postcode, k);
}
let k = bound_k(k);
let street = bound_query(street);
let number = number.map(bound_query);
let city = bound_query(city);
let postcode = postcode.map(bound_query);
let _rules = crate::rules::scope(self.rules);
let mut primary = self.query_structured_primary(street, number, city, postcode, k);
// The city field has an explicit boundary, so apply DE city/abbreviation
// variants directly instead of asking the free-form segmenter to infer it.
// Alias targets remain hard postconditions; an equal-quality alias result
// wins because the constraint itself was needed to interpret the field.
for variant in crate::de::query_variants(city).into_iter().skip(1) {
let mut candidate =
self.query_structured_primary(street, number, &variant.query, postcode, k);
if let Some(expected) = variant.required_commune.as_deref() {
candidate.retain(|(hit, _)| normalize(&hit.commune) == expected);
}
let (Some(candidate_quality), current_quality) = (
Self::de_variant_quality(&candidate),
Self::de_variant_quality(&primary),
) else {
continue;
};
let alias_tie = variant.effects.contains(&crate::de::Effect::CityAlias)
&& current_quality == Some(candidate_quality);
if current_quality
.is_none_or(|current| Self::de_quality_is_better(candidate_quality, current))
|| alias_tie
{
Self::annotate_de_effects(&mut candidate, &variant.effects);
primary = candidate;
}
}
let joined = [street, number.unwrap_or(""), postcode.unwrap_or(""), city]
.iter()
.filter(|value| !value.is_empty())
.copied()
.collect::<Vec<_>>()
.join(" ");
let mut fallback = self.query_feats_country_variants(&joined, k, None);
let use_fallback = match (
Self::de_variant_quality(&fallback),
Self::de_variant_quality(&primary),
) {
(Some(candidate), Some(current)) => Self::de_quality_is_better(candidate, current),
(Some(_), None) => true,
_ => false,
};
if use_fallback {
Self::strip_deferred_locality_drop(&mut fallback);
Self::monotone_confidence(&mut fallback);
fallback
} else {
primary
}
}
/// Direct structured resolver: no street/commune boundary guessing.
fn query_structured_primary(
&self,
street: &str,
number: Option<&str>,
city: &str,
postcode: Option<&str>,
k: usize,
) -> Vec<(Hit, [f32; N_FEATS])> {
if k == 0 {
return Vec::new(); // uniform k=0 contract
}
let k = bound_k(k); // cap result count even on a direct call
// bound EVERY structured field before normalization: number and
// postcode were unbounded, so a multi-MB value amplified inside normalize()/char-scan below.
let street = bound_query(street);
let city = bound_query(city);
let number = number.map(bound_query);
let postcode = postcode.map(bound_query);
let _rules = crate::rules::scope(self.rules);
let sn = self.expand_city_aliases(&fold_units(&crate::norm::fold_homoglyphs(&normalize(
street,
))));
let cn = self.expand_city_aliases(&crate::norm::fold_homoglyphs(&normalize(city)));
let pc: Option<u32> = postcode.and_then(|p| {
let d: String = p.chars().filter(|c| c.is_ascii_digit()).collect();
// Keep the FULL numeric postcode: the hard-coded 5-digit cap
// truncated UZ's 6-digit codes (200456 -> 20045) so they never matched the
// stored value. Cap at 9 digits only to stay within u32.
if d.len() >= 4 {
d[..d.len().min(9)].parse().ok()
} else {
None
}
});
let (numero, rep): (Option<u32>, u32) = match number {
Some(n) => {
let nn = normalize(n);
let d: String = nn.chars().take_while(|c| c.is_ascii_digit()).collect();
let rs: String = nn[d.len()..]
.chars()
.filter(|c| c.is_alphanumeric())
.collect();
(d.parse().ok(), *self.rep_lookup.get(&rs).unwrap_or(&0))
}
None => (None, 0),
};
crate::diagnosis::parsed(&sn, pc, numero, rep, Some(&cn));
// communes from the city field (exact -> prefix -> transliteration) — no boundary guessing
let mut exact_commune = true;
let mut cids = self.communes_by_name(&cn);
if cids.is_empty() {
cids = self.communes_by_prefix(&cn);
exact_commune = false;
}
if cids.is_empty() {
let ct = normalize(&crate::norm::translit_cyr_lat_en(&cn));
cids = self.communes_by_name(&ct);
exact_commune = !cids.is_empty();
if cids.is_empty() {
cids = self.communes_by_prefix(&ct);
}
}
if cids.is_empty() || sn.is_empty() {
return Vec::new();
}
// street-name variants: as is + expansions + type padding + rotation (as in collect_candidates)
let mut phrases = vec![sn.clone()];
if let Some(e) = expand_first(&sn) {
phrases.push(e);
}
if let Some(e) = expand_last(&sn) {
phrases.push(e);
}
if let Some(r) = rotate_type_first(&sn) {
phrases.push(r);
}
phrases.extend(type_padded_variants(&sn));
if street_type_last() {
// the sheet's rewrites at both ends of the name and ordinal numbers, composed
// ("east 104th street" -> "e 104 st"); data-driven like the boundary loop
for variant in street_data_variants(&sn) {
if !phrases.contains(&variant) {
phrases.push(variant);
}
}
}
let mut de_street_phrases = HashSet::new();
if self.country() == Some("de") {
for variant in crate::de::street_variants(&sn) {
if !phrases.contains(&variant) {
de_street_phrases.insert(variant.clone());
phrases.push(variant);
}
}
}
let mut cand: HashMap<u32, Feats> = HashMap::new();
for cid in &cids {
let insee = self.commune_insee(*cid);
for ph in &phrases {
let mut key = ph.clone().into_bytes();
key.push(KEY_SEP);
key.extend_from_slice(insee.as_bytes());
if let Some(v) = self.streets_fst.get(&key) {
let m = self.street_meta(v as u32);
Self::add_cand(
&mut cand,
v as u32,
Feats {
street_exact: true,
commune_exact: exact_commune,
commune_prefix: !exact_commune,
pc_exact: pc.is_some_and(|p| m.postcode != 0 && m.postcode == p),
pc_dept: pc
.is_some_and(|p| m.postcode != 0 && m.postcode / 1000 == p / 1000),
de_street_type: de_street_phrases.contains(ph),
..Default::default()
},
);
}
}
}
// exact path empty — fuzzy/subset within the same communes (rest = street + city)
if cand.is_empty() {
let rest: Vec<&str> = sn
.split(' ')
.chain(cn.split(' '))
.filter(|t| !t.is_empty())
.collect();
cand = self.collect_fuzzy(&rest, pc, false);
if cand.is_empty() {
cand = self.collect_subset(&rest, pc, numero);
}
}
if cand.is_empty() {
return Vec::new();
}
let qwords: Vec<Vec<char>> = sn
.split(' ')
.filter(|t| !t.is_empty())
.map(|s| s.chars().collect())
.collect();
// Candidates arrive from a hash map, whose order varies between processes. Order
// them by street id first: the sort below is stable, so candidates that tie on
// every ranking key then resolve identically on every run ("via roma" and "piazza
// roma" in Verona tie exactly, and the answer must not depend on the hasher seed).
let mut cand_v: Vec<(u32, Feats)> = cand.into_iter().collect();
cand_v.sort_by_key(|(sid, _)| *sid);
let mut hits: Vec<_> = cand_v
.into_iter()
.map(|(sid, f)| self.make_hit(sid, f, numero, rep, pc, &qwords))
.collect();
hits.sort_by(|a, b| {
score_key(b.0.score)
.total_cmp(&score_key(a.0.score))
.then(b.2.cmp(&a.2))
.then(a.3.cmp(&b.3))
.then(b.4.cmp(&a.4))
});
hits.truncate(k);
{
let mut out: Vec<(Hit, [f32; N_FEATS])> =
hits.into_iter().map(|(h, f, _, _, _, _)| (h, f)).collect();
Self::monotone_confidence(&mut out);
out
}
}
/// "City first + trailing number": the exact path expects the commune at the TAIL, and
/// the word fallback yields only a street even though the house exists. If the leading
/// phrase is a commune, retry the remainder (and its unglued form) and accept ONLY a
/// top-1 that is an exact house IN THAT SAME commune — homonyms in other cities are
/// cut by the comparison.
fn city_first_house_retry(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Option<Vec<(Hit, [f32; N_FEATS])>> {
let t2: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
for lead in [2usize, 1] {
if t2.len() < lead + 2 {
continue;
}
let city = t2[..lead].join(" ");
if self.communes_by_name(&city).is_empty() {
continue;
}
let rest = t2[lead..].join(" ");
let unglued = unglue_variant(&rest).map(|u| fold_units(&u));
for cand in std::iter::once(rest).chain(unglued) {
let h2 = self.query_feats_prepared(&cand, k, focus);
if h2.first().is_some_and(|(hit, f)| {
hit.precision == "house" && f[0] > 0.5 && normalize(&hit.commune) == city
}) {
return Some(h2);
}
}
}
None
}
fn query_feats_prepared(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
self.query_feats_prepared_with_retained_locality(q, k, focus, None)
}
fn query_feats_prepared_postcode_house_rescue(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
additional_exact_house_numbers: &[u32],
scan_budget: &mut usize,
seen_phrases: &mut HashSet<String>,
) -> Result<Vec<DePostcodeHouseCandidate>, ()> {
let mut overflowed = false;
let hits = self.query_feats_prepared_internal(
q,
k,
focus,
None,
true,
additional_exact_house_numbers,
scan_budget,
seen_phrases,
&mut overflowed,
None,
);
if overflowed {
Err(())
} else {
Ok(hits
.into_iter()
.map(
|(hit, features, _, _, _, source_sid)| DePostcodeHouseCandidate {
source_sid,
hit,
features,
},
)
.collect())
}
}
fn query_feats_prepared_with_retained_locality(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
retained_locality: Option<DeRetainedLocality<'_>>,
) -> Vec<(Hit, [f32; N_FEATS])> {
self.query_feats_prepared_context(q, k, focus, retained_locality, None)
}
fn query_feats_prepared_cityless(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
original_cityless_street: Option<&str>,
) -> Vec<(Hit, [f32; N_FEATS])> {
self.query_feats_prepared_context(q, k, focus, None, original_cityless_street)
}
fn query_feats_prepared_context(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
retained_locality: Option<DeRetainedLocality<'_>>,
original_cityless_street: Option<&str>,
) -> Vec<(Hit, [f32; N_FEATS])> {
let key = ES_PREPARED_CACHE.with(|cache| {
cache
.borrow()
.as_ref()
.filter(|_| retained_locality.is_none())
.map(|_| {
(
self as *const Self as usize,
q.to_owned(),
k,
focus.map(|f| f as *const QueryFocus as usize),
original_cityless_street.map(str::to_owned),
)
})
});
if let Some(key) = &key {
if let Some(hits) = ES_PREPARED_CACHE.with(|cache| {
cache
.borrow()
.as_ref()
.and_then(|memo| memo.get(key).cloned())
}) {
return hits;
}
}
let mut overflowed = false;
let mut scan_budget = 0;
let mut seen_phrases = HashSet::new();
let hits: Vec<_> = self
.query_feats_prepared_internal(
q,
k,
focus,
retained_locality,
false,
&[],
&mut scan_budget,
&mut seen_phrases,
&mut overflowed,
original_cityless_street,
)
.into_iter()
.map(|(hit, features, _, _, _, _)| (hit, features))
.collect();
if let Some(key) = key {
ES_PREPARED_CACHE.with(|cache| {
if let Some(memo) = cache.borrow_mut().as_mut() {
if memo.len() < 128 && hits.len() <= 64 {
memo.insert(key, hits.clone());
}
}
});
}
hits
}
// Frozen release: preserve the existing provenance, scan-budget and overflow call wiring.
#[allow(clippy::too_many_arguments)]
fn query_feats_prepared_internal(
&self,
q: &str,
k: usize,
focus: Option<&QueryFocus>,
retained_locality: Option<DeRetainedLocality<'_>>,
de_postcode_house_scan: bool,
de_postcode_house_additional_numbers: &[u32],
de_postcode_house_scan_budget: &mut usize,
de_postcode_house_seen_phrases: &mut HashSet<String>,
de_postcode_house_scan_overflowed: &mut bool,
original_cityless_street: Option<&str>,
) -> Vec<RankedHit> {
// input CAP (token bombs): the cascade is ~O(n^2), so hundreds of repeated tokens
// could pin a core for seconds. Real addresses are <= ~15 tokens: collapse repeats
// of a token (max 2 occurrences — "new york new york" survives), overall cap 32.
let mut toks: Vec<&str> = q.split(' ').filter(|t| !t.is_empty()).collect();
if toks.len() > 32 {
let mut cnt: HashMap<&str, u8> = HashMap::new();
toks.retain(|t| {
let c = cnt.entry(t).or_insert(0);
*c += 1;
*c <= 2
});
toks.truncate(32);
}
let toks = toks;
if toks.is_empty() {
return Vec::new();
}
let n = toks.len();
// 1) postcode — mark consumed tokens
let mut used = vec![false; n];
let mut postcode: Option<u32> = None;
// A five-digit token that opens the query on a sheet whose type trails the name is the
// house number, not a postal code: such addresses lead with the number ("11631 Moonmist
// Dr, Houston, TX 77072") and the code, when written, closes the tail (US, 23.10.2026:
// 108 of the 111 clean rows with a five-digit house number answered the street or
// nothing). Data-driven: a sheet without the flag keeps the postal reading.
let leading_house = street_type_last() && n > 1 && is_five_digit_postcode(toks[0]);
let mut i = 0;
while i < n {
let t = toks[i];
let all_digit = t.bytes().all(|b| b.is_ascii_digit());
if is_five_digit_postcode(t) && !(i == 0 && leading_house) {
// French/Italian postcode: 5 digits
postcode = Some(t.parse().unwrap_or(0));
used[i] = true;
} else if all_digit && t.len() == 6 {
// Uzbek postcode: 6 digits
postcode = Some(t.parse().unwrap_or(0));
used[i] = true;
} else if all_digit
&& t.len() == 4
&& i + 1 < n
&& toks[i + 1].len() == 2
&& toks[i + 1].bytes().all(|b| b.is_ascii_alphabetic())
// A sheet whose street rewrites know the two letters as a street word ("se" ->
// "southeast" under a trailing type) reads "3017 SE Milwaukie Avenue" as a
// house number and a direction, not as a Dutch postcode (US, 22.10.2026).
&& !street_rewrite_word(toks[i + 1])
{
// Dutch postcode as a pair: "1012 nz"
postcode = Some(t.parse().unwrap_or(0));
used[i] = true;
used[i + 1] = true;
i += 1;
} else if t.len() == 6
&& t.bytes().take(4).all(|b| b.is_ascii_digit())
&& t.bytes().skip(4).all(|b| b.is_ascii_alphabetic())
{
// Dutch postcode fused: "1012nz"
postcode = Some(t[..4].parse().unwrap_or(0));
used[i] = true;
}
i += 1;
}
// 2) digit groups — house-number candidates
let mut groups: Vec<usize> = Vec::new(); // first index of each group
let mut i = 0;
while i < n {
// Russian ORDINAL street prefix: normalization splits the hyphen ("6-ya" ->
// "6 ya"). The ordinal digit is PART of the street name, NOT a house number;
// otherwise the "6" gets stolen as a house and the street is never found
// (the index stores the split form).
let ordinal = i + 1 < n
&& matches!(
toks[i + 1],
"я" | "й" | "е" | "го" | "ой" | "ая" | "ого" | "ье"
);
let digit = !used[i]
&& !toks[i].is_empty()
&& (toks[i].len() <= 4 || (i == 0 && leading_house))
&& toks[i].bytes().all(|b| b.is_ascii_digit())
&& !ordinal;
if digit {
groups.push(i);
// skip the rest of the group
let mut j = i + 1;
while j < n
&& !used[j]
&& toks[j].len() <= 4
&& toks[j].bytes().all(|b| b.is_ascii_digit())
{
j += 1;
}
i = j;
} else {
i += 1;
}
}
// 3) hypotheses: each digit group (leading = French order, trailing = Dutch),
// each with and without greedy suffix consumption; model hypothesis;
// compound token; numberless
let mut hyps: Vec<Hyp> = Vec::new();
// all digit groups (up to 4): the house number can sit mid-string
// ("Yunusobod 17 mavzesi 13" — the street itself contains a number)
for &g0 in groups.iter().take(4) {
let greedy = self.build_hyp(&toks, &used, g0, true);
let no_greedy = self.build_hyp(&toks, &used, g0, false);
if no_greedy.rest_idx == greedy.rest_idx {
hyps.push(greedy);
continue;
}
// Selection stops at the first hypothesis with an exact street and commune, so the
// order decides. A suffix the sheet's street rewrites know ("174 N Mill St": "n" ->
// "north") is a direction of the street first and a house suffix second: the
// sheet keys some streets with the direction ("North Mill Street") and some
// without ("NORTH TEMPLE Street" under "15 E …"), so both hypotheses stay.
let suffix_is_street_word = no_greedy
.rest_idx
.iter()
.any(|i| !greedy.rest_idx.contains(i) && street_rewrite_word(toks[*i]));
if suffix_is_street_word {
hyps.push(no_greedy);
hyps.push(greedy);
} else {
hyps.push(greedy);
hyps.push(no_greedy);
}
}
// compound token ("12a", "7a", "599a1") — always an additional hypothesis:
// standalone digits in the string may be part of the street name
for ci in 0..n {
if used[ci] {
continue;
}
let t = toks[ci];
if let Some((d, suffix)) = compound_house_parts(t) {
let numero = t[..d].parse().ok();
// keep consuming suffixes after the compound token, but ONLY
// letter+digit mixes: the rep dictionary contains junk ("rue", "5")
// and greedy consumption of it would eat half the street
let mut rep_s = suffix.to_string();
let mut j = ci + 1;
while j < n && !used[j] && {
let w = toks[j];
w.bytes().any(|b| b.is_ascii_digit())
&& !w.bytes().all(|b| b.is_ascii_digit())
&& self.rep_lookup.contains_key(w)
} {
rep_s.push_str(toks[j]);
j += 1;
}
let rep = *self.rep_lookup.get(&rep_s).unwrap_or(&0);
let rest_idx = (0..n)
.filter(|i| !used[*i] && (*i < ci || *i >= j))
.collect();
hyps.push(Hyp {
numero,
rep,
rest_idx,
from_ml: false,
});
break;
}
}
if let Some(mh) = self.ml_hyp(&toks, &used) {
hyps.push(mh); // model hypothesis — after the heuristics (selection is by score)
}
// "city first" ("Amsterdam Dapperstraat 325"): a variant of each hypothesis with
// the first remainder word moved to the end. >=2 (not >=3), otherwise a city +
// ONE-word street would never get rotated.
let extra: Vec<Hyp> = hyps
.iter()
.filter(|h| h.rest_idx.len() >= 2)
.map(|h| {
let mut r = h.rest_idx[1..].to_vec();
r.push(h.rest_idx[0]);
Hyp {
numero: h.numero,
rep: h.rep,
rest_idx: r,
from_ml: h.from_ml,
}
})
.collect();
hyps.extend(extra);
hyps.truncate(14);
// numberless street (last)
hyps.push(Hyp {
numero: None,
rep: 0,
rest_idx: (0..n).filter(|i| !used[*i]).collect(),
from_ml: false,
});
// 4) hypothesis selection: exact candidates; best by maximum score
let rest_of = |h: &Hyp| -> Vec<&str> { h.rest_idx.iter().map(|&ix| toks[ix]).collect() };
// a prefix-found commune stays inside the locality the tail names; the anchor is read
// only when such a candidate appears
let named = std::cell::OnceCell::new();
let within_named = |cand: &mut HashMap<u32, Feats>| {
if cand
.values()
.any(|f| f.commune_prefix && !f.commune_exact && !f.pc_exact)
{
let anchor = named.get_or_init(|| self.named_locality_anchor(&toks));
cand.retain(|&sid, f| self.prefix_commune_within_named_locality(sid, f, anchor));
}
};
let mut best: Option<(usize, HashMap<u32, Feats>, i32)> = None;
let mut de_postcode_house_exact_cache = HashMap::new();
for (hi, h) in hyps.iter().enumerate() {
let rest = rest_of(h);
if rest.is_empty() {
continue;
}
let (mut cand, scan_overflowed) = self.collect_candidates(
&rest,
postcode,
h.numero,
h.rep,
h.from_ml,
de_postcode_house_scan,
de_postcode_house_additional_numbers,
de_postcode_house_scan_budget,
de_postcode_house_seen_phrases,
&mut de_postcode_house_exact_cache,
);
if scan_overflowed {
*de_postcode_house_scan_overflowed = true;
return Vec::new();
}
within_named(&mut cand);
let top = cand.values().map(|f| f.legacy()).max().unwrap_or(i32::MIN);
let better = match &best {
None => !cand.is_empty(),
Some((_, _, bs)) => top > *bs,
};
if better {
let stop = top >= 8;
best = Some((hi, cand, top));
if stop {
break; // exact street+commune — stop searching
}
}
}
// 5) typos — only when the exact passes are empty; among hypotheses pick the
// BEST by score (taking the first non-empty one misleads on streets with
// numbers in the name); the fuzzy path is expensive — cap the hypothesis count
if best.is_none() && !de_postcode_house_scan {
for (hi, h) in hyps.iter().enumerate().take(5) {
let rest = rest_of(h);
if rest.is_empty() {
continue;
}
#[cfg(test)]
DE_POSTCODE_HOUSE_RESCUE_FUZZY_CALLS.with(|calls| {
calls.set(calls.get().saturating_add(1));
});
let mut cand = self.collect_fuzzy(&rest, postcode, h.from_ml);
within_named(&mut cand);
let top = cand.values().map(|f| f.legacy()).max().unwrap_or(i32::MIN);
let better = match &best {
None => !cand.is_empty(),
Some((_, _, bs)) => top > *bs,
};
if better {
best = Some((hi, cand, top));
}
}
}
// 6) street-word subset — the LAST fallback (after exact and typo passes). Fires
// only when both are empty: e.g. "amir temur" -> "Amir Temur shoh". Runs last
// so it never overrides correct answers from the typo path ("Via Roma 1 Roma").
// Uses the street-word inverted index.
if best.is_none()
&& !de_postcode_house_scan
&& std::env::var_os("GRIDPIN_NO_SUBSET").is_none()
{
for (hi, h) in hyps.iter().enumerate().take(5) {
let rest = rest_of(h);
if rest.is_empty() {
continue;
}
#[cfg(test)]
DE_POSTCODE_HOUSE_RESCUE_SUBSET_CALLS.with(|calls| {
calls.set(calls.get().saturating_add(1));
});
let mut cand = self.collect_subset(&rest, postcode, h.numero);
within_named(&mut cand);
let top = cand.values().map(|f| f.legacy()).max().unwrap_or(i32::MIN);
let better = match &best {
None => !cand.is_empty(),
Some((_, _, bs)) => top > *bs,
};
if better {
best = Some((hi, cand, top));
}
}
}
let (numero, rep, cand) = match best {
Some((hi, cand, _)) => (hyps[hi].numero, hyps[hi].rep, cand),
None => return Vec::new(),
};
// The ordinary FST prefix scan is deliberately capped at 300 rows. With an explicit
// focus, recover same-name streets from the existing spatial grid that fell beyond that
// cap. A local street is accepted only when the ordinary search has already established
// the same normalized street-name key without a commune constraint: the point can widen
// a cityless homonym set, but cannot invent an unrelated address or override a named city.
let local_scored = focus
.map(|point| self.focus_candidates(&cand, postcode, point))
.unwrap_or_default();
// 7) houses, features and final sorting (trained weights or hand-tuned scores)
let mut scored: Vec<(u32, Feats)> = cand.into_iter().collect();
// HARD postcode disambiguation: with a postcode in the query, ALWAYS drop
// candidates from a FOREIGN department (pc/1000) that have a known non-zero
// postcode. p==0 (absent from the data) is kept. Fixes "35000 Rennes" -> a false
// Rennes-les-Bains (dept 11): if a right-department candidate exists, only it
// survives; if NONE does, candidates empty out and the outer junk drop retries
// without the venue prefix and finds the right street.
if let Some(pc) = postcode {
let dept = pc / 1000;
scored.retain(|(sid, features)| {
let m = self.street_meta(*sid);
let p = m.postcode;
p == 0
|| p / 1000 == dept
|| (de_postcode_house_scan
&& self.country() == Some("de")
&& self.format_version >= 7
&& features.street_exact
&& numero.is_some_and(|requested_number| {
self.exact_house_postcode_set_candidate_cached(
&mut de_postcode_house_exact_cache,
*sid,
&m,
requested_number,
rep,
de_postcode_house_additional_numbers,
pc,
)
}))
});
}
// A v7 mixed-postcode street stores the exact postcode at house level. The
// ordinary pre-ranking cap cannot see that evidence yet: it sorts StreetMeta
// before `make_hit` decodes the represented house, so a unique exact
// street+house+postcode can be cut behind prominent homonyms. Preserve that one
// causally complete candidate through the cap. Ambiguous duplicates fail closed:
// if more than one street has the same exact house/postcode, none receives this
// rescue and the established ranking remains authoritative.
let de_postcode_house_rescue = match (self.country(), postcode, numero) {
(Some("de"), Some(requested_postcode), Some(requested_number))
if de_postcode_house_scan && self.format_version >= 7 =>
{
let matches: Vec<u32> = scored
.iter()
.filter_map(|(sid, features)| {
let m = self.street_meta(*sid);
if !features.street_exact {
return None;
}
self.exact_house_postcode_set_candidate_cached(
&mut de_postcode_house_exact_cache,
*sid,
&m,
requested_number,
rep,
de_postcode_house_additional_numbers,
requested_postcode,
)
.then_some(*sid)
})
.collect();
(matches.len() == 1).then(|| matches[0])
}
_ => None,
};
// the pre-ranking truncation must not cut by street_id (= source CSV order), or at
// equal score only low-id candidates would survive and the top-1 would depend on
// -k. At equal score the PROMINENT commune survives; id is the last resort.
let mut scored: Vec<(u32, Feats, u32)> = scored
.into_iter()
.map(|(sid, f)| {
let prom = self.commune_prominence(self.street_meta(sid).commune_id);
(sid, f, prom)
})
.collect();
scored.sort_by(|a, b| {
b.1.legacy()
.cmp(&a.1.legacy())
.then(b.2.cmp(&a.2))
.then(a.0.cmp(&b.0))
});
let pre_rank_limit = k.max(10) * 3;
if scored.len() > pre_rank_limit {
if let Some(rescue_sid) = de_postcode_house_rescue {
if let Some(position) = scored
.iter()
.position(|(sid, _, _)| *sid == rescue_sid)
.filter(|position| *position >= pre_rank_limit)
{
let rescue = scored.remove(position);
scored.truncate(pre_rank_limit);
scored.push(rescue);
} else {
scored.truncate(pre_rank_limit);
}
} else {
scored.truncate(pre_rank_limit);
}
}
let mut scored: Vec<(u32, Feats)> =
scored.into_iter().map(|(sid, f, _)| (sid, f)).collect();
if focus.is_some() {
let mut seen: std::collections::HashSet<u32> =
scored.iter().map(|(sid, _)| *sid).collect();
for (sid, features) in local_scored {
if seen.insert(sid) {
scored.push((sid, features));
}
}
}
// query words (+both transliterations) for the name-similarity tie-breaker: at
// EQUAL score the candidate whose name is closer to the query ranks higher.
// Distinguishes fuzzy-match quality, which the score does not capture.
let qwords: Vec<Vec<char>> = q
.split(' ')
.filter(|t| !t.is_empty() && !t.bytes().all(|b| b.is_ascii_digit()))
.flat_map(|t| {
let mut v = vec![t.to_string()];
let cl = normalize(&crate::norm::translit_cyr_lat(t));
if cl != t && !cl.is_empty() {
v.push(cl);
}
let lc = normalize(&crate::norm::translit_lat_cyr(t));
if lc != t && !lc.is_empty() {
v.push(lc);
}
v
})
.map(|s| s.chars().collect())
.collect();
let mut hits: Vec<RankedHit> = Vec::new();
for (sid, f) in scored {
hits.push(self.make_hit(sid, f, numero, rep, postcode, &qwords));
}
// GEO ANCHOR for homonyms. If the query TAIL names a major city (resolving to a
// high-prominence center), then among candidates with the SAME street name the one
// CLOSEST to that center wins. Fixes "Kneza Mihaila ... beograd" -> Stari Grad
// (central Belgrade) rather than the Nova Pazova homonym 24 km away — works even
// when the province umbrella in the data is broken. Affects ONLY homonyms (one
// name across communes); distinct streets and queries without a trailing city are
// untouched.
// The city named with its region in the tail puts its own point here (the table's,
// see commune_region_scope): among equal homonyms the one nearest that point wins —
// Gramercy Park's Madison Ave over Irvington's for "…, New York, NY".
let held_point = COMMUNE_REGION_ANCHOR.with(|a| a.borrow().points.first().copied());
let (anchor, has_named_city): (Option<(f64, f64)>, bool) = if let Some(point) = held_point {
(Some(point), true)
} else {
let toks: Vec<&str> = q
.split(' ')
.filter(|t| t.chars().count() >= 3 && !t.bytes().all(|b| b.is_ascii_digit()))
.collect();
let mut best: Option<(f64, f64, u32)> = None;
for len in 1..=2.min(toks.len()) {
let phrase = toks[toks.len() - len..].join(" ");
if let Some((la, lo, _, prom, _)) = self.resolve_place_translit(&phrase) {
if prom >= 2000 && best.is_none_or(|(_, _, bp)| prom > bp) {
best = Some((la, lo, prom));
}
}
}
// no city named in the query -> weak capital anchor (the most prominent
// commune). The adist tie-break is continuous and comes AFTER score/name/
// postcode — it only flips EQUAL-SCORE homonyms toward the capital.
// House-level hits and explicitly named cities are untouched.
let named = best.is_some();
(best.map(|(la, lo, _)| (la, lo)).or(self.top_anchor), named)
};
// each candidate's distance to the city anchor (homonym tie-break)
let adist: Vec<f64> = match anchor {
Some((alat, alon)) => hits
.iter()
.map(|h| Self::dist_km(alat, alon, h.0.lat, h.0.lon))
.collect(),
None => vec![0.0; hits.len()],
};
// score first; name similarity as tie-break; THEN proximity to the city anchor
// (same-street homonyms in different cities have EQUAL score and name -> closer
// to "beograd" wins; house>near cases are unaffected since their scores differ);
// commune prominence last. The proximity comparison is continuous, so the total
// order stays intact (a "same street" condition would break it). Handles homonyms
// where prominence (address count) misleads (an administratively small center).
// Cityless query on a sheet that orders homonyms by commune size (city_tail
// `homonym_prominence`): size before anchor distance, and no capital prior below. With
// a named city the anchor is that city and distance to it stays first (US clean set:
// "1 Madison Avenue, New York City" went to Jersey City when size came first).
let prominence_first = homonym_prominence_first() && !has_named_city && focus.is_none();
let mut hd: Vec<_> = hits.into_iter().zip(adist).collect();
hd.sort_by(|(a, ad), (b, bd)| {
score_key(b.0.score)
.total_cmp(&score_key(a.0.score))
.then(b.2.cmp(&a.2))
// POSTCODE PROXIMITY: with a postcode in the query, among equal-score
// homonyms of the SAME department prefer the candidate whose postcode is
// CLOSEST to the requested one ("13001" -> Marseille 130xx, not Arles
// 13200). City postcodes are contiguous; another city in the same
// department means a distant postcode.
// A candidate without a postcode sorts after every candidate with one: "equal
// to everything" would make the order non-transitive (a sheet mixing houses
// with and without postcodes, Baltimore MD), and the sort panics.
.then_with(|| match postcode {
Some(qpc) => {
let gap = |pc: &str| match pc.parse::<u32>().unwrap_or(0) as i64 {
0 => i64::MAX,
p => (p - qpc as i64).abs(),
};
gap(&a.0.postcode).cmp(&gap(&b.0.postcode))
}
None => std::cmp::Ordering::Equal,
})
// snap delta: at equal score a house/neighbor whose number is CLOSER to
// the requested one beats a distant snap onto another fragment of a split
// street — BEFORE the geo anchor, since on a long street the centroid
// anchor pulls toward the wrong end
.then(a.3.cmp(&b.3))
// EXPLICIT FOCUS: strict distance tie-break only after every existing text/address
// quality discriminator is equal. No epsilon, score boost, or learned weight.
.then_with(|| match focus {
Some(point) => Self::dist_km(point.lat, point.lon, a.0.lat, a.0.lon)
.total_cmp(&Self::dist_km(point.lat, point.lon, b.0.lat, b.0.lon)),
None => std::cmp::Ordering::Equal,
})
.then_with(|| {
if prominence_first {
b.4.cmp(&a.4).then(ad.total_cmp(bd))
} else {
ad.total_cmp(bd).then(b.4.cmp(&a.4))
}
})
});
let mut hits: Vec<_> = hd.into_iter().map(|(h, _)| h).collect();
// CAPITAL PRIOR for cityless homonyms: no city named, the winner is a DISTANT
// homonym (another region whose house number exists -> house score > the capital's
// near), yet the SAME street exists near the capital anchor. A messy listing with
// no city is almost always about the capital. Promote the capital instance over
// the distant one. Narrow gate: (1) no city named (has_named_city false —
// otherwise the geo anchor already handled it), (2) the winner is FARTHER than
// 60 km from the capital, (3) a candidate with the SAME street name lies WITHIN
// 40 km of it. Houses near the capital (already closest) and non-homonyms are
// unaffected. In Germany, an exact postcode match on the already sorted winner is
// stronger evidence than this cityless prior: tail recovery can drop an unrecognized
// locality while retaining its postcode, and promoting the anchor then inverts the
// postcode-aware score order. A parsed postcode without an exact candidate is not
// enough to disable the prior (the anchor may still be the only nearby result).
// Keep the established behavior unchanged for every other country.
let german_sorted_top_has_exact_postcode = self.country() == Some("de")
&& postcode.is_some()
&& hits.first().is_some_and(|t| Feats::from_vec(&t.1).pc_exact);
if focus.is_none()
&& !has_named_city
&& !german_sorted_top_has_exact_postcode
&& !prominence_first
{
if let Some((alat, alon)) = anchor {
let top_far = hits
.first()
.is_some_and(|t| Self::dist_km(alat, alon, t.0.lat, t.0.lon) > 60.0);
if top_far {
let tkey = street_key(&hits[0].0.street);
// the capital candidate must be an EXACT street (f[0]=street_exact),
// not fuzzy — else a fuzzy capital homonym would oust a correct
// distant exact house.
let near_cap = hits.iter().position(|t| {
t.1[0] > 0.5
&& de_capital_prior_candidate_allowed(
self.country(),
&hits[0].1,
t.0.precision,
)
&& street_key(&t.0.street) == tkey
&& Self::dist_km(alat, alon, t.0.lat, t.0.lon) < 40.0
});
if let Some(pos) = near_cap {
if pos != 0 {
let chosen = hits.remove(pos);
hits.insert(0, chosen);
}
}
}
}
}
Self::de_cityless_prominence(
&mut hits,
self.country(),
original_cityless_street,
focus.is_some(),
postcode,
);
// DE retained-locality tie-break for the c2 suffix retry. Only replace the current
// winner when exactly one later homonym has stronger exact/prefix locality evidence
// from the original post-postcode tail, and every earlier address-quality comparator
// is byte-for-byte equal. The exact discarded slice must also reach that commune;
// this blocks shared-generic-token conflicts such as Gross Roge -> Roge Stadt.
// Explicit focus keeps its established ordering and never enters this path.
// DE exact-PLZ c2 tail tie-break. Run only after CAPITAL and retained-locality:
// an already exact-postcode winner or a retained-locality decision is final. The
// helper also fail-closes outside a DE suffix retry and under explicit focus.
apply_de_c2_tiebreaks(
&mut hits,
retained_locality,
self.country() == Some("de"),
focus.is_some(),
postcode,
);
// confidence MARGIN CUTOFF: a small top-1 vs top-2 SCORE gap plus a LARGE
// geographic spread means a high risk of a distant homonym. Lower the top-1
// confidence and set a flag — the ANSWER itself is unchanged (a downstream
// signal: "confident but ambiguous"). Hit rate is unaffected.
if hits.len() >= 2 {
let margin = hits[0].0.score - hits[1].0.score;
let spread = Self::dist_km(hits[0].0.lat, hits[0].0.lon, hits[1].0.lat, hits[1].0.lon);
if margin < 1.0 && spread > 50.0 {
hits[0].0.confidence = hits[0].0.confidence.min(0.2);
hits[0].0.flags.push("ambiguous_far");
}
}
hits.truncate(k);
hits
}
pub fn query(&self, raw: &str, k: usize) -> Vec<Hit> {
self.query_feats(raw, k)
.into_iter()
.map(|(h, _)| h)
.collect()
}
/// Forward geocoding with an explicit WGS84 focus. The point only widens cityless homonym
/// candidates from the sheet's spatial grid and breaks otherwise-equal ranking ties.
pub fn query_near(
&self,
raw: &str,
k: usize,
lat: f64,
lon: f64,
) -> std::result::Result<Vec<Hit>, String> {
self.query_feats_near(raw, k, lat, lon)
.map(|hits| hits.into_iter().map(|(hit, _)| hit).collect())
}
/// Same-name candidates from the focus grid that the bounded global FST scan did not expose.
/// Identity is the strict normalized display name, not the order-insensitive homonym key:
/// `Alpha Beta` must never confer exact-match evidence on `Beta Alpha`. Commune evidence is
/// intentionally never copied: only cityless global templates are valid.
fn focus_candidates(
&self,
global: &HashMap<u32, Feats>,
postcode: Option<u32>,
focus: &QueryFocus,
) -> Vec<(u32, Feats)> {
let mut templates: HashMap<String, Feats> = HashMap::new();
for (&sid, features) in global {
if features.commune_exact || features.commune_prefix {
continue;
}
let meta = self.street_meta(sid);
let template = Feats {
street_exact: features.street_exact,
street_fuzzy: features.street_fuzzy,
from_ml: features.from_ml,
..Default::default()
};
templates
.entry(normalize(self.name(meta.name_off)))
.or_default()
.merge(template);
}
if templates.is_empty() {
return Vec::new();
}
let mut local = Vec::new();
for &sid in &focus.streets {
let meta = self.street_meta(sid);
let Some(template) = templates.get(&normalize(self.name(meta.name_off))) else {
continue;
};
let mut features = *template;
if let Some(query_postcode) = postcode {
if meta.postcode != 0 && meta.postcode / 1000 != query_postcode / 1000 {
continue;
}
if meta.postcode != 0 {
features.pc_dept = true;
features.pc_exact = meta.postcode == query_postcode;
}
}
local.push((sid, features));
}
local
}
/// Streets in a grid cell (binary search over the directory).
fn streets_in_cell(&self, cell: u32, out: &mut Vec<u32>) {
let n = self.cells_dir.len() / 12;
let (mut lo, mut hi) = (0usize, n);
while lo < hi {
let mid = (lo + hi) / 2;
let c = read_u32(self.cells_dir, mid * 12);
if c < cell {
lo = mid + 1;
} else {
hi = mid;
}
}
if lo < n && read_u32(self.cells_dir, lo * 12) == cell {
let start = read_u32(self.cells_dir, lo * 12 + 4) as usize;
let count = read_u32(self.cells_dir, lo * 12 + 8) as usize;
// Bounds-guard the file-derived (start, count) against cells_post (adversarial finding):
// a corrupt/tampered SEC_CELLS could otherwise drive an out-of-bounds read that PANICS
// reverse(), where every sibling postings reader degrades to empty. Saturating math so a
// crafted overflow can't wrap.
if start.saturating_add(count).saturating_mul(4) > self.cells_post.len() {
return;
}
for i in 0..count {
out.push(read_u32(self.cells_post, (start + i) * 4));
}
}
}
/// Street ids in a square of spatial cells around a point, in deterministic id order.
fn streets_in_square(&self, lat: f64, lon: f64, ring: i64) -> Vec<u32> {
let base_la = ((lat + 90.0) / 0.01).floor() as i64;
let base_lo = ((lon + 180.0) / 0.01).floor() as i64;
let mut streets = Vec::new();
for dla in -ring..=ring {
for dlo in -ring..=ring {
let la = (base_la + dla).clamp(0, 17999) as u32;
let lo = (base_lo + dlo).clamp(0, 35999) as u32;
self.streets_in_cell(la * 36000 + lo, &mut streets);
}
}
streets.sort_unstable();
streets.dedup();
streets
}
/// Forward focus searches the complete allowed 9x9 neighborhood. Unlike reverse, it cannot
/// stop merely because three unrelated streets appeared in a smaller ring: the wanted homonym
/// may have its centroid in the next ring.
fn streets_around(&self, lat: f64, lon: f64) -> Vec<u32> {
self.streets_in_square(lat, lon, 4)
}
/// Approximate reverse geocoding: the nearest houses among streets indexed within ~10 km of the
/// point. A street is indexed at its centroid cell, so a closer house on a street whose centroid
/// falls farther away can be missed — this is NOT a guaranteed global nearest.
/// Each result carries precision/confidence and (for reverse) distance_m so the caller sees how
/// far the answer actually is.
/// Reverse geocode with STRICT validation: a NaN/out-of-range coordinate is an
/// `Err`, not a silent empty result — the single fallible entry point every interface
/// (CLI/py/DuckDB) routes through, so bad input behaves identically everywhere. `reverse`
/// is an alias with the SAME strict contract ( no public lenient variant
/// remains; the lenient layer is crate-private defense-in-depth only).
pub fn try_reverse(
&self,
lat: f64,
lon: f64,
k: usize,
) -> std::result::Result<Vec<Hit>, String> {
validate_lat_lon(lat, lon)?;
// Cap k like every other public entry: reverse passed RAW k through, so
// `-k usize::MAX` returned every candidate in the rings (15k+ rows on France) while forward
// was already bounded — the abuse bound must hold on ALL public interfaces.
Ok(self.reverse_lenient(lat, lon, bound_k(k)))
}
/// Reverse geocode. STRICT like every public entry point: invalid input
/// (NaN/out-of-range) is an error, never a silent empty vec — the lenient behaviour survives
/// only as the crate-private `reverse_lenient` defense-in-depth layer under the validator.
pub fn reverse(&self, lat: f64, lon: f64, k: usize) -> std::result::Result<Vec<Hit>, String> {
self.try_reverse(lat, lon, k)
}
/// Reverse geocode, LENIENT (crate-private): invalid input yields an empty vec. Kept as
/// defense-in-depth under the public strict API — a garbage cell must never be indexed even
/// if a future caller bypasses validation.
pub(crate) fn reverse_lenient(&self, lat: f64, lon: f64, k: usize) -> Vec<Hit> {
let _rules = crate::rules::scope(self.rules);
if k == 0 {
return Vec::new(); // "-k 0" must return nothing (the max(1) below is for internal calls)
}
let k = bound_k(k); // defense-in-depth: a direct crate-internal caller is bounded too
// Defense-in-depth: a NaN or out-of-range coordinate must yield nothing, never
// index a garbage cell (a NaN `as i64` cast is 0, silently the south pole). BOTH public
// entries (`reverse` = `try_reverse`) are strict Err on bad input; this
// lenient empty-vec layer is crate-private only, for a future caller that skips validation.
if validate_lat_lon(lat, lon).is_err() {
return Vec::new();
}
// widen rings 3x3 -> 5x5 -> 9x9 until we have enough candidates
let mut streets: Vec<u32> = Vec::new();
for ring in [1i64, 2, 4] {
streets = self.streets_in_square(lat, lon, ring);
if streets.len() >= 3 {
break;
}
}
// collect ALL houses of the candidate streets; dedup and truncation to k happen
// AFTER sorting — otherwise collapsed duplicate house numbers occupy slots, dedup
// trims them, and reverse -k N silently returns FEWER than N. The candidate set
// is small (~3 streets of the local cell).
let coslat = lat.to_radians().cos().max(0.01);
let mut all: Vec<(f64, u32, u32, u32, f64, f64, u32)> = Vec::new(); // + postcode name offset
for &sid in &streets {
let m = self.street_meta(sid);
let Some((mut pos, postcode_dictionary, postcode_count, house_end)) =
self.house_block_layout(sid, &m)
else {
continue; // corrupt house offset/dictionary: skip, never panic
};
let bounded_houses = &self.houses[..house_end];
let mut cur = 0u32;
for i in 0..m.house_count {
if pos >= self.houses.len() {
break; // truncated house block
}
let Some(d) = strict_varint(bounded_houses, &mut pos)
.and_then(|value| u32::try_from(value).ok())
else {
break;
};
let Some(next_cur) = (if i == 0 { Some(d) } else { cur.checked_add(d) }) else {
break;
};
cur = next_cur;
let Some(rid) = strict_varint(bounded_houses, &mut pos)
.and_then(|value| u32::try_from(value).ok())
else {
break;
};
let Some(dlat_raw) = strict_varint(bounded_houses, &mut pos) else {
break;
};
let Some(dlon_raw) = strict_varint(bounded_houses, &mut pos) else {
break;
};
let dlat = unzigzag(dlat_raw);
let dlon = unzigzag(dlon_raw);
let postcode_off =
if self.format_version >= 7 && m.postcode_disp_off == PC_DISP_AMBIGUOUS {
let Some(id) = strict_varint(bounded_houses, &mut pos)
.and_then(|value| u32::try_from(value).ok())
else {
break;
};
self.house_postcode_offset(postcode_dictionary, postcode_count, id)
} else {
0
};
let Some(hla_e7) = (m.lat_c as i64).checked_add(dlat) else {
break;
};
let Some(hlo_e7) = (m.lon_c as i64).checked_add(dlon) else {
break;
};
if !(-900_000_000..=900_000_000).contains(&hla_e7)
|| !(-1_800_000_000..=1_800_000_000).contains(&hlo_e7)
{
break;
}
let hla = hla_e7 as f64 / 1e7;
let hlo = hlo_e7 as f64 / 1e7;
let dy = (hla - lat) * 111_320.0;
let dx = (hlo - lon) * 111_320.0 * coslat;
let dist = (dx * dx + dy * dy).sqrt();
all.push((dist, sid, cur, rid, hla, hlo, postcode_off));
}
}
all.sort_by(|a, b| a.0.total_cmp(&b.0));
// dedup by (street, number, SUFFIX) BEFORE truncating to k: 12, 12A and 12bis
// are distinct addresses and must not collapse into one; the
// nearest among true duplicates survives, so -k N still returns N addresses
let mut seen: std::collections::HashSet<(u32, u32, u32)> = std::collections::HashSet::new();
all.into_iter()
.filter(|(_, sid, num, rid, ..)| seen.insert((*sid, *num, *rid)))
.take(k.max(1))
.map(|(dist, sid, num, rid, hla, hlo, postcode_off)| {
let m = self.street_meta(sid);
// same contract as forward: `street` is the pure street name; the house
// number ships in its own field
let street = self.name(m.name_off).to_string();
let housenumber = Some(self.house_number(num, rid));
Hit {
lat: hla,
lon: hlo,
// honest precision: "house" only when actually at a house; farther out
// "near"/"approximate" — else a house km away would be labeled "house"
precision: if dist <= 50.0 {
"house"
} else if dist <= 250.0 {
"near"
} else {
"approximate"
},
score: 0.0,
// honest confidence: decays with distance to the nearest house
confidence: (0.97 - dist / 500.0).clamp(0.1, 0.95) as f32,
street,
housenumber,
commune: self.commune_name(m.commune_id).to_string(),
postcode: self.postcode_for_house(&m, postcode_off),
flags: Vec::new(),
region: self.admin_at(hla, hlo),
distance_m: Some((dist * 10.0).round() / 10.0),
}
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scratch::Scratch;
// Keep the frozen fixtures' explicit fields; grouping them would rewrite the test call sites.
#[allow(clippy::too_many_arguments)]
fn retained_test_hit(
commune: &str,
street: &str,
housenumber: Option<&str>,
postcode: &str,
precision: &'static str,
score: f32,
features: [f32; N_FEATS],
flags: Vec<&'static str>,
name_similarity: i32,
snap_delta: u32,
) -> RankedHit {
(
Hit {
lat: 50.0,
lon: 8.0,
precision,
score,
confidence: 0.8,
street: street.to_owned(),
housenumber: housenumber.map(str::to_owned),
commune: commune.to_owned(),
postcode: postcode.to_owned(),
flags,
region: None,
distance_m: None,
},
features,
name_similarity,
snap_delta,
1,
0,
)
}
fn wave_b1_hits() -> Vec<RankedHit> {
let make = || {
retained_test_hit(
"Near",
"Teststraße",
Some("12"),
"",
"house",
8.0,
Feats {
street_exact: true,
..Feats::default()
}
.to_vec(),
vec![],
9,
0,
)
};
let mut a = make();
let mut b = make();
a.4 = 10;
b.0.commune = "Large".to_owned();
b.4 = 100;
vec![a, b]
}
#[test]
fn de_wave_b1_more_prominent_equal_house_wins_stably() {
let mut hits = wave_b1_hits();
let key = street_key("Teststraße");
Index::de_cityless_prominence(&mut hits, Some("de"), Some(&key), false, None);
assert_eq!(hits[0].0.commune, "Large");
assert_eq!(hits[1].0.commune, "Near");
assert!(hits[0].0.flags.contains(&"de_cityless_prominence"));
hits[1].4 = 100;
Index::de_cityless_prominence(&mut hits, Some("de"), Some(&key), false, None);
assert_eq!(hits[0].0.commune, "Large", "ties must retain prior order");
}
#[test]
fn de_wave_b1_scope_preserves_every_explicit_context() {
let key = street_key("Teststraße");
for (country, original, focused, pc) in [
(Some("nl"), Some(key.as_str()), false, None),
(Some("de"), None, false, None),
(Some("de"), Some("teststrasseberlin"), false, None),
(Some("de"), Some(key.as_str()), true, None),
(Some("de"), Some(key.as_str()), false, Some(12345)),
] {
let mut hits = wave_b1_hits();
let before = serde_json::to_string(&hits).unwrap();
Index::de_cityless_prominence(&mut hits, country, original, focused, pc);
assert_eq!(serde_json::to_string(&hits).unwrap(), before);
}
}
#[test]
fn de_wave_b1_address_quality_cannot_be_overridden() {
for case in 0..7 {
let mut hits = wave_b1_hits();
match case {
0 => hits[1].0.precision = "interp",
1 => hits[1].1[0] = 0.0,
2 => hits[1].0.street = "Otherstraße".to_owned(),
3 => hits[1].0.score -= 1.0,
4 => hits[1].2 -= 1,
5 => hits[1].3 += 1,
_ => hits[0].0.precision = "interp",
}
Index::de_cityless_prominence(
&mut hits,
Some("de"),
Some(&street_key("Teststraße")),
false,
None,
);
assert_eq!(hits[0].0.commune, "Near", "case {case}");
}
}
#[test]
fn de_wave_b1_original_surface_does_not_drop_city_or_postcode() {
for raw in ["Teststraße 12", "Teststraße 12a", "Teststraße 12 a"] {
assert_eq!(
Index::de_cityless_street(raw),
Some(street_key("Teststraße"))
);
}
for raw in [
"Teststraße 12, Berlin",
"Teststraße 12 Berlin",
"Teststraße 12 12345",
"Teststraße 12 12345 Berlin",
"Berlin Teststraße 12",
"Teststraße Berlin 12",
] {
assert_ne!(
Index::de_cityless_street(raw),
Some(street_key("Teststraße")),
"{raw}"
);
}
}
#[test]
fn de_retained_locality_core_is_exact_or_prefix_only() {
let retained = de_retained_locality(Some("groß roge"), "roge", true).unwrap();
assert_eq!(retained.postcode_tail, "groß roge");
assert_eq!(retained.dropped_tail, "roge");
assert!(de_retained_locality(None, "roge", true).is_none());
assert_eq!(
de_postcode_tail("x 11111 noise 22222 frankfurt").as_deref(),
Some("frankfurt")
);
assert!(de_postcode_tail("x 11111").is_none());
assert_eq!(de_retained_locality_score("lohne", "Lohne, Stadt"), 2);
assert_eq!(de_retained_locality_score("lohne", "Stadt Lohne"), 2);
assert_eq!(
de_retained_locality_score("frankfurt", "Frankfurt am Main"),
1
);
assert_eq!(de_retained_locality_score("frank", "Frankfurt"), 0);
assert_eq!(
de_retained_locality_score("neustadt weinstraße", "Neustadt an der Weinstraße"),
0
);
assert_eq!(de_retained_locality_score("groß roge", "Klein Roge"), 0);
assert!(de_dropped_tail_reaches_commune(
"frankfurt",
"Frankfurt am Main"
));
assert!(
de_dropped_tail_reaches_commune("roge", "Klein Roge"),
"the full post-postcode context, not this reachability gate alone, rejects the conflict"
);
}
#[test]
fn de_capital_prior_keeps_an_exact_house_over_a_near_anchor() {
let mut exact_house = [0.0; N_FEATS];
exact_house[0] = 1.0;
exact_house[8] = 1.0;
assert!(!de_capital_prior_candidate_allowed(
Some("de"),
&exact_house,
"near",
));
assert!(de_capital_prior_candidate_allowed(
Some("de"),
&exact_house,
"interp",
));
assert!(de_capital_prior_candidate_allowed(
Some("fr"),
&exact_house,
"near",
));
exact_house[8] = 0.0;
assert!(de_capital_prior_candidate_allowed(
Some("de"),
&exact_house,
"near",
));
}
#[test]
fn de_exact_locality_aliases_are_postcode_bound_without_cross_products() {
for (query, postcode, commune) in DE_EXACT_LOCALITY_ALIASES {
assert!(
de_exact_locality_alias_matches(query, *postcode, commune),
"missing exact alias {query:?} / {postcode} / {commune:?}"
);
assert!(de_is_exact_locality_alias_query(query, *postcode));
assert!(!de_exact_locality_alias_matches(
query,
postcode.saturating_add(1),
commune,
));
}
assert!(!de_exact_locality_alias_matches(
"Berlin",
13187,
"Gesundbrunnen"
));
assert!(!de_exact_locality_alias_matches(
"Landkirchen",
23769,
"Lübbenau"
));
assert!(!de_exact_locality_alias_matches(
"Zerkwitz", 3222, "Fehmarn"
));
}
#[test]
fn de_postcode_house_locality_aliases_are_explicit_and_bounded() {
for (query, indexed) in [
("reichenbach vogt", "Reichenbach im Vogtland"),
("sankt wendel", "St. Wendel"),
("homburg saar", "Homburg"),
("kottmar ot eibau", "Eibau"),
("st peter ording", "Sankt Peter-Ording"),
("burg auf fehmarn", "Fehmarn"),
] {
assert!(
de_locality_qualifiers_match(query, indexed),
"{query:?} must be compatible with {indexed:?}"
);
}
assert!(!de_locality_qualifiers_match(
"neustadt an der weinstraße",
"Neustadt am Rübenberge"
));
assert!(!de_locality_qualifiers_match(
"offenbach",
"Frankfurt am Main"
));
assert!(!de_locality_qualifiers_match(
"homburg saar",
"Bad Homburg vor der Höhe"
));
assert!(!de_locality_qualifiers_match("hallenberg", "Halle"));
for district in [
"Adlershof",
"Charlottenburg",
"Dahlem",
"Kaulsdorf",
"Kreuzberg",
"Marienfelde",
"Mitte",
"Neukölln",
"Niederschöneweide",
"Nikolassee",
"Tempelhof",
"Wilmersdorf",
] {
assert!(de_is_berlin_postal_locality(district));
}
assert!(!de_is_berlin_postal_locality("Offenbach"));
assert!(de_is_proven_berlin_postcode(10117));
assert!(!de_is_proven_berlin_postcode(12529));
}
#[test]
fn de_wave_n_locality_strength_preserves_audited_same_postcode_relations() {
for (query, postcode, commune, minimum) in [
("leer ostfriesland", 26789, "Leer", 1),
("berlin", 14195, "Lichterfelde", 3),
("lutherstadt wittenberg", 6886, "Wittenberg", 3),
("wittenberg lutherstadt", 6886, "Wittenberg", 3),
("forst lausitz", 3149, "Forst", 1),
("lubeck", 23552, "Lübeck, Hansestadt", 1),
("berlin", 10783, "Schöneberg", 3),
("berlin", 13627, "Charlottenburg-Nord", 3),
("berlin", 14059, "Charlottenburg", 3),
("weilheim teck", 73235, "Weilheim an der Teck", 3),
("konigstein taunus", 61462, "Königstein im Taunus", 3),
("freiburg breisgau", 79104, "Freiburg im Breisgau", 3),
("freiburg", 79115, "Freiburg im Breisgau", 1),
("bernburg saale", 6406, "Bernburg", 1),
("muhlhausen thuringen", 99974, "Mühlhausen", 1),
("berlin", 10587, "Charlottenburg", 3),
("oelsnitz vogtland", 8606, "Oelsnitz/Vogtl.", 3),
("frankenberg sachsen", 9669, "Frankenberg/Sa.", 3),
] {
let score = Index::de_postcode_house_locality_score(query, None, postcode, commune);
assert!(
score >= minimum,
"{query:?} / {postcode} must retain {commune:?}: score={score}"
);
}
assert_eq!(
Index::de_postcode_house_locality_score("kanzach", None, 88422, "Bad Buchau"),
0
);
assert!(
Index::de_postcode_house_locality_score(
"oelsnitz vogtland",
None,
8606,
"Oelsnitz/Vogtl."
) > Index::de_postcode_house_locality_score(
"oelsnitz vogtland",
None,
8606,
"Oelsnitz"
)
);
assert!(
Index::de_postcode_house_locality_score(
"frankenberg sachsen",
None,
9669,
"Frankenberg/Sa."
) > Index::de_postcode_house_locality_score(
"frankenberg sachsen",
None,
9669,
"Frankenberg"
)
);
for (query, postcode, commune) in [
("konigstein taunus", 61462, "Königstein im Taunus"),
("freiburg breisgau", 79104, "Freiburg im Breisgau"),
("freiburg", 79115, "Freiburg im Breisgau"),
("oelsnitz vogtland", 8606, "Oelsnitz/Vogtl."),
("frankenberg sachsen", 9669, "Frankenberg/Sa."),
("lutherstadt wittenberg", 6886, "Wittenberg"),
("wittenberg lutherstadt", 6886, "Wittenberg"),
("weilheim teck", 73235, "Weilheim an der Teck"),
("berlin", 10587, "Charlottenburg"),
("berlin", 10783, "Schöneberg"),
("berlin", 13627, "Charlottenburg-Nord"),
("berlin", 14059, "Charlottenburg"),
("berlin", 14195, "Lichterfelde"),
] {
assert_eq!(
Index::de_postcode_house_locality_score(query, None, postcode, commune),
3,
"the audited relation must be strong only on its exact postcode"
);
assert!(
Index::de_postcode_house_locality_score(query, None, 99999, commune) < 3,
"{query:?} -> {commune:?} must not retain strong evidence across postcodes"
);
}
assert!(
Index::de_postcode_house_locality_score("berlin", None, 10587, "Schöneberg") < 3,
"Berlin locality and postcode allowlists must not form an unproven cross-product"
);
}
#[test]
fn de_wave_n_new_berlin_relations_do_not_cross_product() {
let relations = [
(10587, "Charlottenburg"),
(10783, "Schöneberg"),
(13627, "Charlottenburg-Nord"),
(14059, "Charlottenburg"),
(14195, "Lichterfelde"),
];
let district_candidates = [
"Adlershof",
"Charlottenburg",
"Charlottenburg-Nord",
"Dahlem",
"Kaulsdorf",
"Kreuzberg",
"Lichterfelde",
"Marienfelde",
"Mitte",
"Neukölln",
"Niederschöneweide",
"Nikolassee",
"Schöneberg",
"Tempelhof",
"Wilmersdorf",
];
for (postcode, exact_commune) in relations {
assert_eq!(
Index::de_postcode_house_locality_score("berlin", None, postcode, exact_commune,),
3,
"the registered Berlin triple must remain strong: {postcode} -> {exact_commune}"
);
let exact_core = de_commune_core(exact_commune);
for commune in district_candidates {
if de_commune_core(commune) == exact_core {
continue;
}
assert!(
Index::de_postcode_house_locality_score("berlin", None, postcode, commune) < 3,
"an unregistered Berlin cross-product must stay weak: {postcode} -> {commune}"
);
}
}
}
#[test]
fn de_prefix_drop_requires_original_postcode_or_locality_evidence() {
let features = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let wrong = retained_test_hit(
"Celle, Stadt",
"Berlinstraße",
Some("8"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep", "de_street_type"],
17,
0,
);
assert!(!de_prefix_drop_preserves_postcode_locality(
&wrong.0, &wrong.1, 10117, "berlin"
));
let matching_locality = retained_test_hit(
"Frankfurt am Main",
"Domstraße",
Some("10"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
);
assert!(de_prefix_drop_preserves_postcode_locality(
&matching_locality.0,
&matching_locality.1,
60311,
"frankfurt"
));
let mut postcode_features = features;
postcode_features[4] = 1.0;
let matching_postcode = retained_test_hit(
"Charlottenburg",
"Testweg",
Some("1"),
"10117",
"house",
0.43,
postcode_features,
vec!["street_exact", "house_rep", "pc_exact"],
17,
0,
);
assert!(de_prefix_drop_preserves_postcode_locality(
&matching_postcode.0,
&matching_postcode.1,
10117,
"berlin"
));
}
#[test]
fn de_abbreviation_variant_cannot_trade_a_live_result_for_weaker_invented_context() {
let pair = |hit: RankedHit| (hit.0, hit.1);
let current_features = [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let current = vec![pair(retained_test_hit(
"Rinteln",
"Paul-Erdniß-Straße",
Some("1"),
"",
"house",
-1.03,
current_features,
vec!["street_fuzzy", "house_rep"],
0,
0,
))];
let mut invented_features = current_features;
invented_features[3] = 1.0;
let invented_commune = vec![pair(retained_test_hit(
"Straßenhaus",
"Paul-Mertgen-Straße",
Some("1"),
"",
"house",
99.0,
invented_features,
vec!["street_fuzzy", "commune_prefix", "house_rep"],
0,
0,
))];
assert!(!Index::de_abbreviation_candidate_may_displace(
&invented_commune,
¤t,
None,
));
let exact_address = vec![pair(retained_test_hit(
"Rinteln",
"Paul-Erdniß-Straße",
Some("1"),
"",
"house",
1.0,
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep"],
0,
0,
))];
let postcode_only = vec![pair(retained_test_hit(
"Straßenhaus",
"Other",
Some("1"),
"01067",
"house",
99.0,
[0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0],
vec!["commune_prefix", "pc_exact"],
0,
0,
))];
assert!(
!Index::de_abbreviation_candidate_may_displace(&postcode_only, &exact_address, None,),
"postcode-only evidence must not trade away exact street+house evidence"
);
let equal_invented = vec![pair(retained_test_hit(
"Straßenhaus",
"Paul-Erdniß-Straße",
Some("1"),
"",
"house",
99.0,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "commune_prefix", "house_rep"],
0,
0,
))];
assert!(
!Index::de_abbreviation_candidate_may_displace(
&equal_invented,
&exact_address,
Some("rinteln"),
),
"invented commune context needs a strict independent-address gain"
);
for (tail, commune, house) in [
("ahlden aller", "Ahlden (Aller), Flecken", "1"),
("bad iburg", "Bad Iburg, Stadt", "12"),
] {
let tied_wrong_locality = vec![pair(retained_test_hit(
"Wittenburg",
"Große Str.",
Some(house),
"",
"house",
0.43,
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep", "dropped_suffix"],
0,
0,
))];
let retained_candidate = vec![pair(retained_test_hit(
commune,
"Große Straße",
Some(house),
"",
"house",
0.08,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "commune_prefix", "house_rep"],
0,
0,
))];
assert!(
!Index::de_abbreviation_candidate_may_displace(
&retained_candidate,
&tied_wrong_locality,
None,
),
"a variant must not invent locality evidence without the original tail",
);
assert!(
Index::de_abbreviation_candidate_may_displace(
&retained_candidate,
&tied_wrong_locality,
Some(tail),
),
"original locality {tail:?} must break a tied exact-address arbitration",
);
}
let strict_improvement = vec![pair(retained_test_hit(
"Straßenhaus",
"Paul-Erdniß-Straße",
Some("1"),
"01067",
"house",
99.0,
[1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "commune_prefix", "house_rep", "pc_exact"],
0,
0,
))];
assert!(Index::de_abbreviation_candidate_may_displace(
&strict_improvement,
&exact_address,
None,
));
let dropped_name = vec![pair(retained_test_hit(
"Arnsberg",
"Stumpfstraße",
Some("2"),
"",
"house",
0.43,
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep", "dropped_prefix"],
0,
0,
))];
assert!(!Index::de_abbreviation_candidate_may_displace(
&dropped_name,
¤t,
Some("arnsberg"),
));
assert!(Index::de_abbreviation_candidate_may_displace(
&dropped_name,
&[],
Some("arnsberg"),
));
let strong_dropped = vec![pair(retained_test_hit(
"Dresden",
"Hauptstraße",
Some("1"),
"01067",
"house",
2.0,
[1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec![
"street_exact",
"commune_exact",
"house_rep",
"pc_exact",
"dropped_prefix",
],
0,
0,
))];
assert!(Index::de_abbreviation_candidate_may_displace(
&strong_dropped,
¤t,
None,
));
let exact = vec![pair(retained_test_hit(
"Rinteln",
"Paul-Erdniß-Straße",
Some("1"),
"",
"house",
0.43,
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep"],
0,
0,
))];
assert!(Index::de_abbreviation_candidate_may_displace(
&exact, ¤t, None,
));
}
#[test]
fn de_parenthetical_subaddress_admission_is_exact_commune_and_fill_empty_only() {
let pair = |hit: RankedHit| (hit.0, hit.1);
let exact = vec![pair(retained_test_hit(
"Zeven, Stadt",
"Am Markt",
Some("4"),
"",
"house",
1.0,
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep"],
0,
0,
))];
assert!(Index::de_parenthetical_subaddress_may_fill(
&[],
&exact,
Some("zeven")
));
assert!(
!Index::de_parenthetical_subaddress_may_fill(&exact, &exact, Some("zeven")),
"PARENTHETICAL_SUBADDRESS_FILL_EMPTY_OBSERVER: a live result is immutable"
);
assert!(!Index::de_parenthetical_subaddress_may_fill(
&[],
&exact,
Some("aachen")
));
assert!(!Index::de_parenthetical_subaddress_may_fill(
&[],
&exact,
None
));
let weak = |precision, features| {
vec![pair(retained_test_hit(
"Zeven, Stadt",
"Am Markt",
Some("4"),
"",
precision,
99.0,
features,
vec!["street_fuzzy"],
0,
0,
))]
};
assert!(!Index::de_parenthetical_subaddress_may_fill(
&[],
&weak("house", [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0]),
Some("zeven")
));
assert!(!Index::de_parenthetical_subaddress_may_fill(
&[],
&weak("interp", [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0]),
Some("zeven")
));
}
#[test]
fn de_abbreviation_guard_is_wired_into_country_variant_arbitration() {
let idx = forward_postcode_index_for_country(
"abbreviation-guard-wiring",
"wilhelm luckert strasse,001,berlin,10115,10115,4,,13.3889,52.5170,Wilhelm-Lückert-Straße,Berlin\n",
"de",
);
DE_ABBREVIATION_GUARD_CALLS.with(|calls| calls.set(0));
let hits = idx.query("Wilhelm-Lückert-str. 4, 10115 Berlin", 1);
assert_eq!(
hits.first().map(|hit| hit.street.as_str()),
Some("Wilhelm-Lückert-Straße")
);
assert!(
DE_ABBREVIATION_GUARD_CALLS.with(|calls| calls.get()) > 0,
"the production country-variant loop must consult the abbreviation guard"
);
}
#[test]
fn de_recipient_cleanup_tie_break_requires_exact_full_street_and_house() {
let pair = |hit: RankedHit| (hit.0, hit.1);
let current = vec![pair(retained_test_hit(
"Wesselburen",
"Dohrnstraße",
Some("5"),
"25764",
"house",
0.43,
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep", "dropped_prefix"],
0,
0,
))];
let exact_full_street = vec![pair(retained_test_hit(
"Charlottenburg-Nord",
"Max-Dohrn-Straße",
Some("5"),
"10589",
"house",
0.43,
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep"],
0,
0,
))];
assert!(Index::de_recipient_cleanup_breaks_dropped_prefix_tie(
&exact_full_street,
¤t,
));
let fuzzy = vec![pair(retained_test_hit(
"Charlottenburg-Nord",
"Max-Dorn-Straße",
Some("5"),
"10589",
"house",
-1.03,
[0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_fuzzy", "house_rep"],
0,
0,
))];
assert!(!Index::de_recipient_cleanup_breaks_dropped_prefix_tie(
&fuzzy, ¤t,
));
assert!(!Index::de_recipient_cleanup_breaks_dropped_prefix_tie(
&exact_full_street,
&[],
));
}
#[test]
fn de_country_variants_skip_equivalent_raw_and_normalized_base() {
let idx = forward_postcode_index_for_country(
"country-variant-prepared-dedup",
"mainweg,001,berlin,10115,10115,1,,13.3889,52.5170,Mainweg,Berlin\n",
"de",
);
let query = "Mainweg 1, 10115 Berlin";
assert_eq!(
crate::de::query_variants(query).len(),
2,
"the witness must generate distinct raw and normalized variants"
);
DE_COUNTRY_VARIANT_PREPARED_SEARCH_CALLS.with(|calls| calls.set(0));
let hits = idx.query(query, 1);
let top = hits.first().expect("the exact house must still resolve");
assert_eq!(top.street, "Mainweg");
assert_eq!(top.housenumber.as_deref(), Some("1"));
assert_eq!(
DE_COUNTRY_VARIANT_PREPARED_SEARCH_CALLS.with(|calls| calls.get()),
1,
"equivalent non-city variants must execute one prepared search"
);
}
#[test]
fn de_country_variants_keep_raw_sensitive_city_fallbacks() {
let idx = forward_postcode_index_for_country(
"country-variant-raw-city-fallback",
"mainweg,001,berlin,10115,10115,1,,13.3889,52.5170,Mainweg,Berlin\n",
"de",
);
DE_COUNTRY_VARIANT_PREPARED_SEARCH_CALLS.with(|calls| calls.set(0));
let hits = idx.query("Unindexed, Berlin", 1);
let top = hits
.first()
.expect("the raw comma segment must resolve Berlin");
assert_eq!(top.precision, "city");
assert_eq!(top.commune, "Berlin");
assert_eq!(
DE_COUNTRY_VARIANT_PREPARED_SEARCH_CALLS.with(|calls| calls.get()),
2,
"city/empty outcomes must not be reused because raw segments differ"
);
}
#[test]
fn de_abbreviation_retained_locality_breaks_exact_address_evidence_ties() {
let idx = forward_postcode_index_for_country(
"abbreviation-retained-locality-tie",
"grosse str,001,wittenburg,,,1,,11.0762461,53.5107681,Große Str.,Wittenburg\n\
grosse str,001,wittenburg,,,12,,11.0755349,53.5113574,Große Str.,Wittenburg\n\
grosse str,002,grabow,,,1,,11.5644688,53.2784453,Große Str.,Grabow\n\
grosse str,002,grabow,,,12,,11.5629185,53.2779808,Große Str.,Grabow\n\
grosse str,003,crivitz,,,1,,11.6507684,53.5765525,Große Str.,Crivitz\n\
grosse str,003,crivitz,,,12,,11.6505726,53.5770965,Große Str.,Crivitz\n\
grosse str,004,westerkappeln,,,1,,7.8774391,52.3146747,Große Str.,Westerkappeln\n\
grosse str,004,westerkappeln,,,12,,7.8776095,52.3132857,Große Str.,Westerkappeln\n\
grosse str,005,ibbenburen,,,1,,7.7152364,52.2766699,Große Str.,Ibbenbüren\n\
grosse str,005,ibbenburen,,,12,,7.7156456,52.2769733,Große Str.,Ibbenbüren\n\
grosse strasse,006,ahlden aller flecken,,,1,,9.5577655,52.7592260,Große Straße,Ahlden (Aller) Flecken\n\
grosse strasse,007,bad iburg stadt,,,12,,8.0452005,52.1568279,Große Straße,Bad Iburg Stadt\n",
"de",
);
for (query, expected_commune, expected_house) in [
(
"Große Str. 1, 29693 Ahlden (Aller)",
"Ahlden (Aller) Flecken",
"1",
),
("Große Str. 12, 49186 Bad Iburg", "Bad Iburg Stadt", "12"),
] {
let hits = idx.query(query, 5);
let top = hits
.first()
.unwrap_or_else(|| panic!("retained locality must resolve {query:?}"));
assert_eq!(top.street, "Große Straße", "wrong street for {query:?}");
assert_eq!(top.housenumber.as_deref(), Some(expected_house));
assert_eq!(top.commune, expected_commune, "wrong commune for {query:?}");
assert!(top.flags.contains(&"de_abbrev"));
}
}
#[test]
fn de_retained_locality_requires_every_prior_address_comparator_to_tie() {
let features = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let base = retained_test_hit(
"Wrong",
"Hamburger Allee",
Some("2"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
);
let same = retained_test_hit(
"Frankfurt am Main",
"Hamburger Allee",
Some("2"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
);
assert!(de_same_retained_address_evidence(&base, &same));
let cases = [
retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"",
"house",
0.44,
features,
vec!["street_exact", "house_rep"],
17,
0,
),
retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"",
"house",
0.43,
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep"],
17,
0,
),
retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
16,
0,
),
retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
1,
),
retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"",
"near",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
),
retained_test_hit(
"Target",
"Hamburger Allee",
Some("3"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
),
retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"60486",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
),
retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"",
"house",
0.43,
features,
vec!["street_exact"],
17,
0,
),
retained_test_hit(
"Target",
"Andere Straße",
Some("2"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
),
];
for candidate in &cases {
assert!(!de_same_retained_address_evidence(&base, candidate));
}
let positive_zero = retained_test_hit(
"Wrong",
"Hamburger Allee",
Some("2"),
"",
"house",
0.0,
features,
vec!["street_exact", "house_rep"],
17,
0,
);
let negative_zero = retained_test_hit(
"Target",
"Hamburger Allee",
Some("2"),
"",
"house",
-0.0,
features,
vec!["street_exact", "house_rep"],
17,
0,
);
assert!(!de_same_retained_address_evidence(
&positive_zero,
&negative_zero
));
}
fn retained_equal_hit(commune: &str, features: [f32; N_FEATS]) -> RankedHit {
retained_test_hit(
commune,
"Hamburger Allee",
Some("2"),
"",
"house",
0.43,
features,
vec!["street_exact", "house_rep"],
17,
0,
)
}
#[test]
fn de_retained_locality_promoter_is_fixed_to_the_preregistered_top_five() {
let features = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let mut hits = vec![
retained_equal_hit("Wrong", features),
retained_equal_hit("Other One", features),
retained_equal_hit("Other Two", features),
retained_equal_hit("Other Three", features),
retained_equal_hit("Frankfurt am Main", features),
retained_equal_hit("Frankfurt an der Oder", features),
];
assert!(promote_de_retained_locality(
&mut hits,
DeRetainedLocality {
postcode_tail: "frankfurt",
dropped_tail: "frankfurt",
postal_tail_eligible: true,
},
));
assert_eq!(hits[0].0.commune, "Frankfurt am Main");
assert!(hits[0].0.flags.contains(&"de_retained_locality"));
}
#[test]
fn de_retained_locality_promoter_rejects_fuzzy_or_unequal_address_evidence() {
let fuzzy = [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let mut fuzzy_hits = vec![
retained_equal_hit("Wrong", fuzzy),
retained_equal_hit("Frankfurt am Main", fuzzy),
];
assert!(!promote_de_retained_locality(
&mut fuzzy_hits,
DeRetainedLocality {
postcode_tail: "frankfurt",
dropped_tail: "frankfurt",
postal_tail_eligible: true,
},
));
assert_eq!(fuzzy_hits[0].0.commune, "Wrong");
let exact = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let mut unequal_hits = vec![
retained_equal_hit("Wrong", exact),
retained_test_hit(
"Frankfurt am Main",
"Hamburger Allee",
Some("3"),
"",
"house",
0.43,
exact,
vec!["street_exact", "house_rep"],
17,
0,
),
];
assert!(!promote_de_retained_locality(
&mut unequal_hits,
DeRetainedLocality {
postcode_tail: "frankfurt",
dropped_tail: "frankfurt",
postal_tail_eligible: true,
},
));
assert_eq!(unequal_hits[0].0.commune, "Wrong");
}
#[test]
fn de_retained_locality_promoter_requires_full_context_and_reachable_drop() {
let features = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let mut shared_tail = vec![
retained_equal_hit("Wrong", features),
retained_equal_hit("Roge Stadt", features),
];
assert!(!promote_de_retained_locality(
&mut shared_tail,
DeRetainedLocality {
postcode_tail: "groß roge",
dropped_tail: "roge",
postal_tail_eligible: true,
},
));
assert_eq!(shared_tail[0].0.commune, "Wrong");
let mut short_drop = vec![
retained_equal_hit("Wrong", features),
retained_equal_hit("Frankfurt am Main", features),
];
assert!(!promote_de_retained_locality(
&mut short_drop,
DeRetainedLocality {
postcode_tail: "frankfurt am",
dropped_tail: "am",
postal_tail_eligible: true,
},
));
assert_eq!(short_drop[0].0.commune, "Wrong");
}
#[test]
fn de_retained_locality_promoter_keeps_an_already_matching_top() {
let features = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let mut hits = vec![
retained_equal_hit("Frankfurt am Main", features),
retained_equal_hit("Frankfurt Stadt", features),
];
assert!(!promote_de_retained_locality(
&mut hits,
DeRetainedLocality {
postcode_tail: "frankfurt",
dropped_tail: "frankfurt",
postal_tail_eligible: true,
},
));
assert_eq!(hits[0].0.commune, "Frankfurt am Main");
assert!(!hits[0].0.flags.contains(&"de_retained_locality"));
}
#[test]
fn de_retained_locality_promoter_prefers_exact_over_prefix_evidence() {
let features = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let mut hits = vec![
retained_equal_hit("Wrong", features),
retained_equal_hit("Frankfurt am Main", features),
retained_equal_hit("Frankfurt Stadt", features),
];
assert!(promote_de_retained_locality(
&mut hits,
DeRetainedLocality {
postcode_tail: "frankfurt",
dropped_tail: "frankfurt",
postal_tail_eligible: true,
},
));
assert_eq!(hits[0].0.commune, "Frankfurt Stadt");
}
// Keep the frozen fixtures' explicit fields; grouping them would rewrite the test call sites.
#[allow(clippy::too_many_arguments)]
fn postal_tail_test_hit(
commune: &str,
street: &str,
housenumber: &str,
postcode: &str,
precision: &'static str,
pc_exact: bool,
house_exact_rep: bool,
score: f32,
) -> RankedHit {
let features = [
1.0,
0.0,
0.0,
0.0,
if pc_exact { 1.0 } else { 0.0 },
1.0,
0.0,
1.0,
if house_exact_rep { 1.0 } else { 0.0 },
1.0,
];
let mut flags = vec!["street_exact"];
if house_exact_rep {
flags.push("house_rep");
}
if pc_exact {
flags.push("pc_exact");
} else {
flags.push("pc_dept");
}
retained_test_hit(
commune,
street,
Some(housenumber),
postcode,
precision,
score,
features,
flags,
if pc_exact { 3 } else { 97 },
if pc_exact { 8 } else { 0 },
)
}
fn postal_tail_positive_at_rank(target_rank: usize) -> Vec<RankedHit> {
let mut hits = vec![postal_tail_test_hit(
"Top",
"Post Allee",
"15b",
"12346",
"house",
false,
false,
12.0,
)];
for rank in 2..=6 {
if rank == target_rank {
hits.push(postal_tail_test_hit(
"Target",
"Post-Allee",
"15a",
"12345",
"house",
true,
false,
-7.25,
));
} else {
hits.push(postal_tail_test_hit(
&format!("Filler {rank}"),
"Post Allee",
"15c",
"12347",
"house",
false,
false,
11.0 - rank as f32,
));
}
}
hits
}
#[test]
fn de_postal_tail_stably_promotes_unique_rank_two_three_or_five() {
for target_rank in [2, 3, 5] {
let mut hits = postal_tail_positive_at_rank(target_rank);
let original_order: Vec<String> =
hits.iter().map(|hit| hit.0.commune.clone()).collect();
assert!(promote_de_postal_tail(
&mut hits,
true,
true,
false,
Some(12345),
));
assert_eq!(hits[0].0.commune, "Target");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("15a"));
assert_eq!(hits[0].0.score, -7.25, "the hit must move intact");
assert!(hits[0].0.flags.contains(&"de_postal_tail"));
let expected_tail: Vec<String> = original_order
.into_iter()
.filter(|commune| commune != "Target")
.collect();
let actual_tail: Vec<String> =
hits[1..].iter().map(|hit| hit.0.commune.clone()).collect();
assert_eq!(actual_tail, expected_tail, "move-to-front must be stable");
}
}
#[test]
fn de_retained_locality_decision_precedes_and_blocks_postal_tail() {
let features = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
let initial = || {
vec![
retained_equal_hit("Wrong", features),
retained_equal_hit("Frankfurt am Main", features),
postal_tail_test_hit(
"Postal Target",
"Hamburger Allee",
"2",
"12345",
"house",
true,
true,
-8.0,
),
]
};
let mut postal_first = initial();
assert!(promote_de_postal_tail(
&mut postal_first,
true,
true,
false,
Some(12345),
));
assert_eq!(postal_first[0].0.commune, "Postal Target");
let mut production_order = initial();
apply_de_c2_tiebreaks(
&mut production_order,
Some(DeRetainedLocality {
postcode_tail: "frankfurt",
dropped_tail: "frankfurt",
postal_tail_eligible: true,
}),
true,
false,
Some(12345),
);
assert_eq!(production_order[0].0.commune, "Frankfurt am Main");
assert!(production_order[0]
.0
.flags
.contains(&"de_retained_locality"));
assert_eq!(production_order[0].0.commune, "Frankfurt am Main");
assert!(!production_order[0].0.flags.contains(&"de_postal_tail"));
}
#[test]
fn de_postal_tail_is_fixed_to_one_candidate_in_the_original_top_five() {
let mut rank_six = postal_tail_positive_at_rank(6);
let rank_six_order: Vec<String> =
rank_six.iter().map(|hit| hit.0.commune.clone()).collect();
assert!(!promote_de_postal_tail(
&mut rank_six,
true,
true,
false,
Some(12345),
));
assert_eq!(
rank_six
.iter()
.map(|hit| hit.0.commune.clone())
.collect::<Vec<_>>(),
rank_six_order
);
let mut duplicate = postal_tail_positive_at_rank(2);
duplicate[2] = postal_tail_test_hit(
"Duplicate Target",
"Post Allee",
"15d",
"12345",
"house",
true,
false,
-8.0,
);
let duplicate_order: Vec<String> =
duplicate.iter().map(|hit| hit.0.commune.clone()).collect();
assert!(!promote_de_postal_tail(
&mut duplicate,
true,
true,
false,
Some(12345),
));
assert_eq!(
duplicate
.iter()
.map(|hit| hit.0.commune.clone())
.collect::<Vec<_>>(),
duplicate_order
);
}
#[test]
fn de_postal_tail_fails_closed_at_every_context_and_evidence_gate() {
let assert_rejected = |mut hits: Vec<RankedHit>, is_de, is_c2, focus, postcode| {
let before: Vec<(String, Vec<&'static str>)> = hits
.iter()
.map(|hit| (hit.0.commune.clone(), hit.0.flags.clone()))
.collect();
assert!(!promote_de_postal_tail(
&mut hits, is_de, is_c2, focus, postcode,
));
assert_eq!(
hits.iter()
.map(|hit| (hit.0.commune.clone(), hit.0.flags.clone()))
.collect::<Vec<_>>(),
before
);
};
assert_rejected(
postal_tail_positive_at_rank(2),
false,
true,
false,
Some(12345),
);
assert_rejected(
postal_tail_positive_at_rank(2),
true,
false,
false,
Some(12345),
);
assert_rejected(
postal_tail_positive_at_rank(2),
true,
true,
true,
Some(12345),
);
assert_rejected(postal_tail_positive_at_rank(2), true, true, false, None);
let mut top_postcode = postal_tail_positive_at_rank(2);
top_postcode[0].1[4] = 1.0;
top_postcode[0].0.postcode = "12345".to_owned();
top_postcode[0].0.flags.push("pc_exact");
assert_rejected(top_postcode, true, true, false, Some(12345));
let mut retained = postal_tail_positive_at_rank(2);
retained[0].0.flags.push("de_retained_locality");
assert_rejected(retained, true, true, false, Some(12345));
let mut fuzzy_top = postal_tail_positive_at_rank(2);
fuzzy_top[0].1[0] = 0.0;
fuzzy_top[0].1[1] = 1.0;
assert_rejected(fuzzy_top, true, true, false, Some(12345));
let mut fuzzy_candidate = postal_tail_positive_at_rank(2);
fuzzy_candidate[1].1[0] = 0.0;
fuzzy_candidate[1].1[1] = 1.0;
assert_rejected(fuzzy_candidate, true, true, false, Some(12345));
let mut both_fuzzy = postal_tail_positive_at_rank(2);
for hit in &mut both_fuzzy[..2] {
hit.1[0] = 0.0;
hit.1[1] = 1.0;
hit.0.flags.retain(|flag| *flag != "street_exact");
hit.0.flags.push("street_fuzzy");
}
assert_rejected(both_fuzzy, true, true, false, Some(12345));
let mut reordered_street = postal_tail_positive_at_rank(2);
reordered_street[1].0.street = "Allee Post".to_owned();
assert_rejected(reordered_street, true, true, false, Some(12345));
let mut other_precision = postal_tail_positive_at_rank(2);
other_precision[1].0.precision = "near";
assert_rejected(other_precision, true, true, false, Some(12345));
let mut emitted_postcode_mismatch = postal_tail_positive_at_rank(2);
emitted_postcode_mismatch[1].0.postcode = "12346".to_owned();
assert_rejected(emitted_postcode_mismatch, true, true, false, Some(12345));
let mut missing_pc_feature = postal_tail_positive_at_rank(2);
assert_eq!(missing_pc_feature[1].0.postcode, "12345");
missing_pc_feature[1].1[4] = 0.0;
assert_rejected(missing_pc_feature, true, true, false, Some(12345));
for feature_index in [0, 1, 2, 3, 6, 7, 8, 9] {
let mut widened_mask = postal_tail_positive_at_rank(2);
widened_mask[1].1[feature_index] = if widened_mask[1].1[feature_index] > 0.5 {
0.0
} else {
1.0
};
assert_rejected(widened_mask, true, true, false, Some(12345));
}
let mut non_postal_weakening = postal_tail_positive_at_rank(2);
non_postal_weakening[0].1[8] = 1.0;
non_postal_weakening[0].0.housenumber = Some("15".to_owned());
non_postal_weakening[1].0.housenumber = Some("15a".to_owned());
assert_rejected(non_postal_weakening, true, true, false, Some(12345));
let mut foreign_wrapper = postal_tail_positive_at_rank(2);
apply_de_c2_tiebreaks(
&mut foreign_wrapper,
Some(DeRetainedLocality {
postcode_tail: "unmatched locality",
dropped_tail: "unmatched",
postal_tail_eligible: true,
}),
false,
false,
Some(12345),
);
assert_eq!(foreign_wrapper[0].0.commune, "Top");
assert!(foreign_wrapper
.iter()
.all(|hit| !hit.0.flags.contains(&"de_postal_tail")));
let mut house_effect_wrapper = postal_tail_positive_at_rank(2);
apply_de_c2_tiebreaks(
&mut house_effect_wrapper,
Some(DeRetainedLocality {
postcode_tail: "unmatched locality",
dropped_tail: "unmatched",
postal_tail_eligible: false,
}),
true,
false,
Some(12345),
);
assert_eq!(house_effect_wrapper[0].0.commune, "Top");
assert!(house_effect_wrapper
.iter()
.all(|hit| !hit.0.flags.contains(&"de_postal_tail")));
}
#[test]
fn commune_prefix_short_fragment_cannot_select_foreign_house() {
let idx = forward_housenumber_index(
"short-commune-prefix",
"calle raval,01001,el campo remoto,01001,7,,-0.78,38.68,Calle Raval,El Campo Remoto\n",
);
for query in ["7 raval el", "7 el raval", "angels 7 el raval"] {
let hits = idx.query(query, 1);
assert!(
!hits.iter().any(|h| h.flags.contains(&"commune_prefix")),
"short place fragment admitted for {query}"
);
}
}
#[test]
fn commune_prefix_minimum_counts_input_before_article_retry() {
let idx = forward_housenumber_index(
"commune-prefix-input-length",
"rue test,01001,eldorado,01001,7,,2.0,48.0,Rue Test,Eldorado\n\
rue test,01002,ялта,01002,7,,2.1,48.1,Rue Test,Ялта\n\
rue test,01003,la xy village,01003,7,,2.2,48.2,Rue Test,La Xy Village\n\
rue test,01004,la ile longue,01004,7,,2.3,48.3,Rue Test,La Ile Longue\n\
rue test,01005,e l village,01005,7,,2.4,48.4,Rue Test,E L Village\n\
rue test,01006,el,01006,7,,2.5,48.5,Rue Test,El\n",
);
for fragment in ["", "e", "el", "ял", "xy", "e l"] {
assert!(idx.communes_by_prefix(fragment).is_empty(), "{fragment:?}");
}
for fragment in ["eld", "ялт", "ile"] {
assert!(!idx.communes_by_prefix(fragment).is_empty(), "{fragment:?}");
}
assert!(!idx.communes_by_name("el").is_empty());
}
#[test]
fn it_street_type_cannot_confirm_commune() {
let idx = forward_postcode_index_for_country(
"it-type-place-negative",
"piazza cavour,3,bologna,,,1,,11.3,44.5,Piazza Cavour,Bologna\n\
via cavour,1,piazza armerina,,,1,,14.3,37.4,Via Cavour,Piazza Armerina\n\
via roma,2,viareggio,,,1,,10.2,43.9,Via Roma,Viareggio\n",
"it",
);
for fragment in ["piazza", "via", "corso", "piazza "] {
assert!(idx.communes_by_prefix(fragment).is_empty(), "{fragment}");
}
let hits = idx.query("Piazza Cavour 1", 1);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].commune, "Bologna");
assert!(!hits[0].flags.contains(&"commune_prefix"));
}
#[test]
fn it_street_type_keeps_complete_commune() {
let idx = forward_postcode_index_for_country(
"it-type-place-positive",
"via roma,1,piazza armerina,,,1,,14.3,37.4,Via Roma,Piazza Armerina\n\
via roma,2,viareggio,,,1,,10.2,43.9,Via Roma,Viareggio\n",
"it",
);
for query in ["Piazza Armerina, via Roma 1", "Via Roma 1 Piazza Armerina"] {
let hits = idx.query(query, 1);
assert_eq!(hits.len(), 1, "{query}");
assert_eq!(hits[0].commune, "Piazza Armerina", "{query}");
assert_eq!(hits[0].precision, "house");
assert_eq!(hits[0].housenumber.as_deref(), Some("1"));
}
assert!(!idx.communes_by_prefix("piazza ar").is_empty());
assert!(!idx.communes_by_name("viareggio").is_empty());
}
#[test]
fn it_missing_street_keeps_numberless_commune_fallback() {
let idx = forward_postcode_index_for_country(
"area-fallback",
"via assente,2,altrove,,,7,,16.0,39.0,Via Assente,Altrove\n\
via nota,1,valle serena,,,7,,11.0,44.0,Via Nota,Valle Serena\n",
"it",
);
for query in [
"Via Assente, Valle Serena (XX)",
"Sentiero Assente Valle Serena",
] {
let hits = idx.query(query, 1);
assert_eq!(hits.len(), 1, "{query}");
let hit = &hits[0];
assert_eq!(hit.precision, "city");
assert_eq!(hit.commune, "Valle Serena");
assert_eq!(hit.confidence, 0.05);
assert!(hit.street.is_empty());
assert!(hit.housenumber.is_none());
}
let found = idx.query("Via Nota 7, Valle Serena (XX)", 1);
assert_eq!(found[0].precision, "house");
assert_eq!(found[0].street, "Via Nota");
assert!(idx.query("Via Assente 7, Valle Serena (XX)", 1).is_empty());
assert!(idx
.query("Sentiero Sconosciuto, Luogo Inesistente", 1)
.is_empty());
}
#[test]
fn it_missing_street_distinguishes_long_house_from_postcode() {
let idx = forward_postcode_index_for_country(
"long-house-area-fallback",
"via assente,2,altrove,,,7,,16.0,39.0,Via Assente,Altrove\n\
via nota,1,valle serena,,,7,,11.0,44.0,Via Nota,Valle Serena\n",
"it",
);
assert!(idx.query("Via Assente 1234, Valle Serena", 1).is_empty());
assert!(idx.query("Via Assente 123456, Valle Serena", 1).is_empty());
let hits = idx.query("Via Assente 12345, Valle Serena", 1);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].precision, "city");
assert_eq!(hits[0].commune, "Valle Serena");
assert_eq!(hits[0].confidence, 0.05);
assert!(hits[0].street.is_empty());
assert!(hits[0].housenumber.is_none());
}
fn it_province_fixture(case: &str) -> Index {
forward_postcode_index_for_country(
case,
"via luigi zamboni,1,bologna,,,27,,11.35,44.49,Via Luigi Zamboni,Bologna\n\
via test,3,beta,,,27,,12.4,45.5,Via Test,Beta\n\
via test bo,2,alfa,,,27,,11.4,44.5,Via Test BO,Alfa\n\
via zamboni,4,omega,,,27,,15.35,40.49,Via Zamboni,Omega\n",
"it",
)
}
#[test]
fn it_province_parenthesized_keeps_exact_city() {
let idx = it_province_fixture("province-parentheses");
let h = idx.query("Via Zamboni 27 Bologna (BO)", 1);
assert_eq!(h.len(), 1);
assert_eq!(h[0].commune, "Bologna");
assert!(h[0].flags.contains(&"commune_exact"));
assert_eq!(h[0].housenumber.as_deref(), Some("27"));
}
#[test]
fn it_province_bare_keeps_exact_city() {
let idx = it_province_fixture("province-bare");
let h = idx.query("Via Zamboni 27 Bologna BO", 1);
assert_eq!(h.len(), 1);
assert_eq!(h[0].commune, "Bologna");
assert!(h[0].flags.contains(&"commune_exact"));
}
#[test]
fn it_province_without_adjacent_city_preserves_street_token() {
let idx = it_province_fixture("province-no-city");
let h = idx.query("Via Test 27 BO", 1);
assert_eq!(h.len(), 1);
assert_eq!(h[0].street, "Via Test BO");
assert_eq!(h[0].commune, "Alfa");
}
fn forward_housenumber_index(case: &str, rows: &str) -> Index {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-forward-housenumber-{case}-{}-{serial}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
let bin = dir.join("addresses.bin");
crate::builder::build(&csv, &bin, None, None, None, None, None).unwrap();
Index::open(&bin).unwrap()
}
fn forward_postcode_index(case: &str, rows: &str) -> Index {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-forward-postcode-{case}-{}-{serial}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
let bin = dir.join("addresses.bin");
crate::builder::build(&csv, &bin, None, None, None, None, None).unwrap();
Index::open(&bin).unwrap()
}
fn forward_postcode_index_for_country(case: &str, rows: &str, country: &str) -> Index {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-forward-postcode-country-{case}-{}-{serial}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
format!(
r#"{{"country":"{country}","layer":"addresses","license":"test","source_release":"test"}}"#
),
)
.unwrap();
let bin = dir.join("addresses.bin");
crate::builder::build(&csv, &bin, None, None, None, None, Some(&manifest)).unwrap();
Index::open(&bin).unwrap()
}
fn forward_postcode_index_for_country_with_rules(
case: &str,
rows: &str,
country: &str,
) -> Index {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-forward-postcode-country-rules-{case}-{}-{serial}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
format!(
r#"{{"country":"{country}","layer":"addresses","license":"test","source_release":"test"}}"#
),
)
.unwrap();
let bin = dir.join("addresses.bin");
let rules_dir = crate::rules::tests::write_fixture_rules(&dir.join("rules"));
crate::builder::build(
&csv,
&bin,
None,
None,
Some(&rules_dir),
None,
Some(&manifest),
)
.unwrap();
Index::open(&bin).unwrap()
}
fn de_wave_b_homonymous_p4_rows(
commune_count: usize,
source_street: &str,
source_display: &str,
) -> String {
let mut rows = (0..commune_count)
.map(|position| {
let insee = format!("{:03}", position + 1);
let (street, display) = if position == 0 {
(source_street.to_owned(), source_display.to_owned())
} else {
(
format!("zzdummy{position:02}"),
format!("ZZ Dummy {position:02}"),
)
};
format!(
"{street},{insee},bremen,28759,28759,1,,8.{position:07},53.{position:07},{display},Bremen"
)
})
.collect::<Vec<_>>();
rows.sort_unstable();
format!("{}\n", rows.join("\n"))
}
#[test]
fn de_prefix_drop_guard_reaches_postcode_locality_tail_end_to_end() {
let idx = forward_postcode_index_for_country(
"prefix-drop-postcode-locality",
"berlinstrasse,002,celle,29221,29221,8,,10.0577218,52.6307212,Berlinstraße,Celle\n\
franzosische strasse,001,mitte,10117,10117,8,,13.3864406,52.5144355,Französische Straße,Mitte\n",
"de",
);
let hits = idx.query("Französische Straße 8, 10117 Berlin", 5);
let top = hits
.first()
.expect("the postcode-preserving tail path must resolve");
assert_eq!(top.street, "Französische Straße");
assert_eq!(top.housenumber.as_deref(), Some("8"));
assert_eq!(top.postcode, "10117");
assert_eq!(top.commune, "Mitte");
assert!(top.flags.contains(&"dropped_suffix"));
assert!(
hits.iter().all(|hit| hit.commune != "Celle"),
"a generic prefix drop must not revive an exact house in the wrong postcode/locality"
);
DE_PREFIX_DROP_GUARD_CALLS.with(|calls| calls.set(0));
let wrong_only = idx.query_feats_d(
"venue berlinstrasse 8",
5,
0,
None,
Some("berlin"),
Some(10117),
true,
None,
);
assert!(
DE_PREFIX_DROP_GUARD_CALLS.with(|calls| calls.get()) > 0,
"the production prefix-drop loop must execute the postcode/locality guard"
);
assert!(
wrong_only.is_empty(),
"dropping an unknown prefix must not turn a contradictory postcode/locality into a house"
);
}
#[test]
fn de_unique_house_postcode_survives_the_pre_rank_homonym_cap() {
let mut rows =
String::from("dummy,998,berlin,10115,10115,1,,13.3900000,52.5100000,Dummy,Berlin\n");
for commune in 1..=340 {
for house in [44, 45, 46] {
rows.push_str(&format!(
"friedrichstrasse,{commune:03},ort{commune:03},,,{house},,{:.7},{:.7},Friedrichstraße,Ort {commune:03}\n",
10.0 + commune as f64 / 1000.0,
50.0 + commune as f64 / 1000.0,
));
}
}
rows.push_str(
"friedrichstrasse,999,zzztarget,10969,10969,44,,13.3900000,52.5100000,Friedrichstraße,Berlin Mitte\n\
friedrichstrasse,999,zzztarget,10117,10117,45,,13.3910000,52.5110000,Friedrichstraße,Berlin Mitte\n",
);
let idx = forward_postcode_index_for_country("house-postcode-rescue", &rows, "de");
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.set(0));
DE_POSTCODE_HOUSE_RESCUE_HOUSE_DECODES.with(|calls| calls.set(0));
// The locality is not a commune name of this sheet: a named commune would let the
// focused fallback find the house first; this observer is about the
// postcode rescue itself.
let top = idx
.query("Friedrichstraße 44, 10969 Mitte", 1)
.into_iter()
.next()
.expect("the unique exact house/postcode must survive the homonym cap");
assert_eq!(top.street, "Friedrichstraße");
assert_eq!(top.housenumber.as_deref(), Some("44"));
assert_eq!(top.postcode, "10969");
assert_eq!(top.commune, "Berlin Mitte");
assert!(top.flags.contains(&"pc_exact"));
let scanned = DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.get());
assert!(
scanned > 300,
"the narrow rescue must prove the exact candidate beyond the ordinary 300-row cap"
);
assert!(
scanned as usize <= DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT,
"all variants share one request-wide scan budget"
);
assert!(
DE_POSTCODE_HOUSE_RESCUE_HOUSE_DECODES.with(|calls| calls.get()) <= 2,
"hundreds of homonymous street postings must not trigger hundreds of house-block decodes"
);
// With the city named, the same house still answers (through the focused fallback).
let named = idx.query("Friedrichstraße 44, 10969 Berlin", 1);
assert_eq!(
named
.first()
.map(|hit| (hit.commune.as_str(), hit.postcode.as_str())),
Some(("Berlin Mitte", "10969"))
);
}
#[test]
fn de_wave_n_terminal_country_tail_is_structural_and_bounded() {
let parsed =
de_comma_postcode_house_rescue_query("Wiesentalstraße 10, 79115 Freiburg, Deutschland")
.expect(
"one terminal German country field must preserve the address/locality boundary",
);
assert_eq!(parsed.0, "Wiesentalstraße 10 79115");
assert_eq!(parsed.1, 79115);
assert_eq!(parsed.2, "freiburg");
assert!(de_comma_postcode_house_rescue_query(
"Wiesentalstraße 10, 79115 Freiburg, Deutschland, Europa"
)
.is_none());
assert!(de_comma_postcode_house_rescue_query(
"Wiesentalstraße 10, 79115 Freiburg, Targettown"
)
.is_none());
assert!(de_comma_postcode_house_rescue_query(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau"
)
.is_none());
}
#[test]
fn de_wave_n_malformed_parenthetical_qualifier_cannot_bypass_p4() {
let idx = forward_postcode_index_for_country(
"wave-n-parenthetical-qualifier-boundary",
"albertstrasse,001,freiburg im breisgau,79104,79104,25,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n",
"de",
);
let raw = "Albertstr. 25 (Otto-Krayer-Haus),79104 Freiburg/Breisgau";
assert!(de_parenthetical_locality_uses_slash_qualifier(raw));
assert!(
idx.de_comma_postcode_house_rescue(raw, 5, None).is_none(),
"the generic rescue itself must not own a malformed P4 qualifier surface"
);
let hits = idx.query(raw, 5);
assert!(
hits.iter().all(|hit| {
hit.precision != "house"
&& !hit.flags.contains(&"de_postcode_house")
&& !hit.flags.contains(&"de_audited_compound")
&& !hit.flags.contains(&"de_parenthetical_subaddress")
}),
"a malformed P4 surface must not reach an exact house through generic rescue: {} hits",
hits.len()
);
}
#[test]
fn de_wave_n_token_bound_locality_arbitration_selects_one_exact_house() {
let idx = forward_postcode_index_for_country(
"wave-n-token-bound-locality",
"grabenstrasse,001,oelsnitz,08606,08606,31,,12.1700000,50.4200000,Grabenstraße,Oelsnitz\n\
grabenstrasse,002,oelsnitz vogtl,08606,08606,31,,12.1800000,50.4300000,Grabenstraße,Oelsnitz/Vogtl.\n\
grabenstrasse,003,oelsnitz vogtland,08606,08606,24,,12.1600000,50.4100000,Grabenstraße,Oelsnitz/Vogtland\n",
"de",
);
let exact = idx
.de_postcode_house_rescue_parsed(
"Grabenstr. 31, 08606 Oelsnitz/Vogtland",
"Grabenstraße 31 08606",
8606,
"oelsnitz vogtland",
1,
None,
None,
&[],
false,
)
.expect("the token-bound query locality must leave one exact source identity");
assert_eq!(exact.len(), 1);
assert_eq!(exact[0].0.commune, "Oelsnitz/Vogtl.");
assert_eq!(exact[0].0.housenumber.as_deref(), Some("31"));
assert_eq!(exact[0].0.postcode, "08606");
}
#[test]
fn de_wave_n_duplicate_source_sids_fail_closed_independent_of_coordinates() {
for (case, second_coordinates) in [
("same-coordinates", "12.1800000,50.4300000"),
("different-coordinates", "12.1810000,50.4310000"),
] {
let rows = format!(
"grabenstrasse,001,oelsnitz vogtl,08606,08606,31,,12.1800000,50.4300000,Grabenstraße,Oelsnitz/Vogtl.\n\
grabenstrasse,002,oelsnitz vogtl,08606,08606,31,,{second_coordinates},Grabenstraße,Oelsnitz/Vogtl.\n"
);
let idx = forward_postcode_index_for_country(case, &rows, "de");
assert!(
idx.de_postcode_house_rescue_parsed(
"Grabenstr. 31, 08606 Oelsnitz/Vogtland",
"Grabenstraße 31 08606",
8606,
"oelsnitz vogtland",
1,
None,
None,
&[],
false,
)
.is_none(),
"two distinct eligible source SIDs must fail closed regardless of coordinates: {case}"
);
}
let suffix = forward_postcode_index_for_country(
"wave-n-duplicate-suffix-same-coordinates",
"grabenstrasse,001,oelsnitz vogtl,08606,08606,31,a,12.1800000,50.4300000,Grabenstraße,Oelsnitz/Vogtl.\n\
grabenstrasse,002,oelsnitz vogtl,08606,08606,31,a,12.1800000,50.4300000,Grabenstraße,Oelsnitz/Vogtl.\n",
"de",
);
assert!(
suffix
.de_postcode_house_rescue_parsed(
"Grabenstr. 31a, 08606 Oelsnitz/Vogtland",
"Grabenstraße 31a 08606",
8606,
"oelsnitz vogtland",
1,
None,
None,
&[],
false,
)
.is_none(),
"same-coordinate duplicate source SIDs must also fail closed for an exact suffix"
);
let range = forward_postcode_index_for_country(
"wave-n-duplicate-range-same-coordinates",
"paarstrasse,001,oelsnitz vogtl,08606,08606,1,,12.1800000,50.4300000,Paarstraße,Oelsnitz/Vogtl.\n\
paarstrasse,001,oelsnitz vogtl,08606,08606,3,,12.1810000,50.4310000,Paarstraße,Oelsnitz/Vogtl.\n\
paarstrasse,002,oelsnitz vogtl,08606,08606,1,,12.1800000,50.4300000,Paarstraße,Oelsnitz/Vogtl.\n\
paarstrasse,002,oelsnitz vogtl,08606,08606,3,,12.1810000,50.4310000,Paarstraße,Oelsnitz/Vogtl.\n",
"de",
);
assert!(
range
.de_postcode_house_rescue_parsed(
"Paarstraße 1/3, 08606 Oelsnitz/Vogtland",
"Paarstraße 1 08606",
8606,
"oelsnitz vogtland",
1,
None,
None,
&[3],
false,
)
.is_none(),
"same-coordinate duplicate source SIDs must fail closed for a complete endpoint set"
);
}
#[test]
fn de_wave_n_same_postcode_unrelated_locality_vetoes_soft_override() {
let idx = forward_postcode_index_for_country(
"wave-n-unrelated-locality-veto",
"alte poststrasse,003,kanzach,88422,88422,2,,9.5590000,48.0780000,Alte Poststraße,Kanzach\n\
riedlinger strasse,001,kanzach,,,13,,9.5580000,48.0770000,Riedlinger Straße,Kanzach\n\
riedlinger strasse,002,bad buchau,88422,88422,12,,9.6010000,48.0610000,Riedlinger Straße,Bad Buchau\n",
"de",
);
let top = idx
.query("Riedlinger Straße 12, 88422 Kanzach", 1)
.into_iter()
.next()
.expect("the established same-postcode locality result must remain available");
assert_eq!(top.commune, "Kanzach");
assert_eq!(top.postcode, "");
assert!(matches!(top.precision, "near" | "interp"));
assert!(!top.flags.contains(&"de_exact_postcode_override"));
}
#[test]
fn de_wave_n_explicit_wrong_postcode_near_remains_p1_override() {
let idx = forward_postcode_index_for_country(
"wave-n-explicit-wrong-postcode-near",
"teststrasse,001,querytown,22111,22111,13,,9.2100000,48.4900000,Teststraße,Querytown\n\
teststrasse,002,targettown,22222,22222,12,,9.2200000,48.5000000,Teststraße,Targettown\n",
"de",
);
let top = idx
.query("Teststraße 12, 22222 Querytown", 1)
.into_iter()
.next()
.expect("an explicit wrong-postcode near hit must keep the established P1 correction");
assert_eq!(top.precision, "house");
assert_eq!(top.housenumber.as_deref(), Some("12"));
assert_eq!(top.postcode, "22222");
assert_eq!(top.commune, "Targettown");
assert!(top.flags.contains(&"de_postcode_house"));
assert!(top.flags.contains(&"de_exact_postcode_override"));
}
#[test]
fn de_wave_n_country_tail_and_qualified_localities_reach_exact_houses() {
for (case, rows, query, expected_commune, expected_house, expected_postcode) in [
(
"freiburg-country-tail",
"wiesentalstrasse,001,freiburg,79115,79115,23,,7.8255000,47.9780000,Wiesentalstraße,Freiburg\n\
wiesentalstrasse,002,freiburg im breisgau,79115,79115,10,,7.8260000,47.9790000,Wiesentalstraße,Freiburg im Breisgau\n",
"Wiesentalstraße 10, 79115 Freiburg, Deutschland",
"Freiburg im Breisgau",
"10",
"79115",
),
(
"frankenberg-qualified",
"chemnitzer strasse,001,frankenberg sachsen,09669,09669,17,,13.0310000,50.9100000,Chemnitzer Straße,Frankenberg/Sachsen\n\
chemnitzer strasse,002,frankenberg,09669,09669,64,,13.0320000,50.9110000,Chemnitzer Straße,Frankenberg\n\
chemnitzer strasse,003,frankenberg sa,09669,09669,64,,13.0330000,50.9120000,Chemnitzer Straße,Frankenberg/Sa.\n",
"Chemnitzer Str. 64, 09669 Frankenberg/Sachsen",
"Frankenberg/Sa.",
"64",
"09669",
),
] {
let idx = forward_postcode_index_for_country(case, rows, "de");
let top = idx
.query(query, 1)
.into_iter()
.next()
.expect("the exact represented house must remain available");
assert_eq!(top.precision, "house", "{case}");
assert_eq!(top.housenumber.as_deref(), Some(expected_house), "{case}");
assert_eq!(top.postcode, expected_postcode, "{case}");
assert_eq!(top.commune, expected_commune, "{case}");
}
}
#[test]
fn de_wave_n_existing_same_postcode_locality_relations_remain_reachable() {
for (case, rows, postcode, locality, expected_commune) in [
(
"muhlhausen-regression",
"teststrasse,001,muhlhausen,99974,99974,12,,10.0000000,51.0000000,Teststraße,Mühlhausen\n\
teststrasse,002,targettown,99974,99974,12,,10.1000000,51.1000000,Teststraße,Targettown\n",
99974,
"muhlhausen thuringen",
"Mühlhausen",
),
(
"bernburg-regression",
"teststrasse,001,bernburg,06406,06406,12,,11.0000000,51.0000000,Teststraße,Bernburg\n\
teststrasse,002,targettown,06406,06406,12,,11.1000000,51.1000000,Teststraße,Targettown\n",
6406,
"bernburg saale",
"Bernburg",
),
(
"berlin-regression",
"teststrasse,001,charlottenburg,10587,10587,12,,13.3000000,52.5000000,Teststraße,Charlottenburg\n\
teststrasse,002,targettown,10587,10587,12,,13.4000000,52.6000000,Teststraße,Targettown\n",
10587,
"berlin",
"Charlottenburg",
),
] {
let idx = forward_postcode_index_for_country(case, rows, "de");
let query = format!("Teststraße 12 {postcode:05}");
let exact = idx
.de_postcode_house_rescue_parsed(
&query,
&query,
postcode,
locality,
1,
None,
None,
&[],
false,
)
.expect("the pre-Wave-N locality relation must retain one exact house");
assert_eq!(exact.len(), 1, "{case}");
assert_eq!(exact[0].0.commune, expected_commune, "{case}");
assert_eq!(exact[0].0.housenumber.as_deref(), Some("12"), "{case}");
assert_eq!(exact[0].0.postcode, format!("{postcode:05}"), "{case}");
}
}
#[test]
fn de_wave_a_unique_exact_postcode_overrides_only_an_address_level_soft_locality() {
let idx = forward_postcode_index_for_country(
"wave-a-postcode-override",
"teststrasse,001,querytown,22111,22111,1,,10.0000000,50.0000000,Teststraße,Querytown\n\
teststrasse,002,targettown,22222,22222,1,,11.0000000,51.0000000,Teststraße,Targettown\n",
"de",
);
let top = idx
.query("Teststraße 1, 22222 Querytown", 1)
.into_iter()
.next()
.expect("an address-level homonym must still return one candidate");
assert_eq!(top.precision, "house");
assert_eq!(top.housenumber.as_deref(), Some("1"));
assert_eq!(top.postcode, "22222");
assert_eq!(top.commune, "Targettown");
assert!(top.flags.contains(&"de_exact_postcode_override"));
let top_five = idx.query("Teststraße 1, 22222 Querytown", 5);
assert_eq!(top_five[0].postcode, "22222");
assert_eq!(top_five[0].commune, "Targettown");
let duplicate = forward_postcode_index_for_country(
"wave-a-postcode-override-duplicate",
"teststrasse,001,querytown,22111,22111,1,,10.0000000,50.0000000,Teststraße,Querytown\n\
teststrasse,002,targettown,22222,22222,1,,11.0000000,51.0000000,Teststraße,Targettown\n\
teststrasse,003,othertown,22222,22222,1,,12.0000000,52.0000000,Teststraße,Othertown\n",
"de",
);
let duplicate_top = duplicate
.query("Teststraße 1, 22222 Querytown", 1)
.into_iter()
.next()
.expect("the established result remains when exact PLZ candidates are ambiguous");
assert_eq!(duplicate_top.commune, "Querytown");
assert_ne!(duplicate_top.postcode, "22222");
assert!(!duplicate_top.flags.contains(&"de_exact_postcode_override"));
let suffix_isolated = forward_postcode_index_for_country(
"wave-a-postcode-override-suffix",
"teststrasse,001,querytown,22111,22111,1,,10.0000000,50.0000000,Teststraße,Querytown\n\
teststrasse,002,targettown,22222,22222,1,a,11.0000000,51.0000000,Teststraße,Targettown\n",
"de",
);
let suffix_top = suffix_isolated
.query("Teststraße 1, 22222 Querytown", 1)
.into_iter()
.next()
.expect("a suffix mismatch must leave the established result intact");
assert_eq!(suffix_top.commune, "Querytown");
assert!(!suffix_top.flags.contains(&"de_exact_postcode_override"));
let exact_suffix = forward_postcode_index_for_country(
"wave-a-postcode-override-exact-suffix",
"teststrasse,001,querytown,22111,22111,3,a,10.0000000,50.0000000,Teststraße,Querytown\n\
teststrasse,002,targettown,22222,22222,3,a,11.0000000,51.0000000,Teststraße,Targettown\n",
"de",
);
let suffix_target = exact_suffix
.query("Teststraße 3 a, 22222 Querytown", 1)
.into_iter()
.next()
.expect("an exact spaced suffix must stay part of the strict product key");
assert_eq!(suffix_target.housenumber.as_deref(), Some("3a"));
assert_eq!(suffix_target.postcode, "22222");
assert_eq!(suffix_target.commune, "Targettown");
assert!(suffix_target.flags.contains(&"de_exact_postcode_override"));
let frankfurt = forward_postcode_index_for_country(
"wave-a-postcode-override-frankfurt",
"domstrasse,001,frankfurt am main,15231,15231,10,,8.6800000,50.1100000,Domstraße,Frankfurt am Main\n\
domstrasse,002,frankfurt,15230,15230,10,,14.5500000,52.3470000,Domstraße,Frankfurt (Oder)\n",
"de",
);
let frankfurt_top = frankfurt
.query("Domstraße 10, 15230 Frankfurt am Main", 1)
.into_iter()
.next()
.expect("a hard Frankfurt qualifier must keep the established candidate");
assert_ne!(frankfurt_top.postcode, "15230");
assert!(!frankfurt_top.flags.contains(&"de_exact_postcode_override"));
}
#[test]
fn de_wave_a_suffixed_house_never_falls_back_to_the_bare_number() {
let idx = forward_postcode_index_for_country(
"wave-a-suffix-does-not-fall-back-to-bare",
"teststrasse,001,querytown,22111,22111,3,a,10.0000000,50.0000000,Teststraße,Querytown\n\
teststrasse,002,targettown,22222,22222,3,,11.0000000,51.0000000,Teststraße,Targettown\n",
"de",
);
let top = idx
.query("Teststraße 3a, 22222 Querytown", 1)
.into_iter()
.next()
.expect("the established exact-suffix result must remain available");
assert_eq!(top.housenumber.as_deref(), Some("3a"));
assert_eq!(top.commune, "Querytown");
assert_eq!(top.postcode, "22111");
assert!(
!top.flags.contains(&"de_exact_postcode_override"),
"a bare indexed house must not prove a suffixed product key"
);
let mut key = b"teststrasse".to_vec();
key.push(KEY_SEP);
key.extend_from_slice(b"002");
let target_sid = idx
.streets_fst
.get(&key)
.expect("the bare target street must exist") as u32;
let target_meta = idx.street_meta(target_sid);
let requested_rep = *idx
.rep_lookup
.get("a")
.expect("the requested suffix must have a runtime rep id");
assert!(
!idx.exact_house_postcode_candidate_cached(
&mut HashMap::new(),
target_sid,
&target_meta,
3,
requested_rep,
22222,
),
"the strict Wave-A admission proof itself must reject bare 3 for requested 3a"
);
}
#[test]
fn de_wave_a_bare_house_never_falls_forward_to_a_suffix() {
let idx = forward_postcode_index_for_country(
"wave-a-bare-does-not-fall-forward-to-suffix",
"teststrasse,001,querytown,22111,22111,3,,10.0000000,50.0000000,Teststraße,Querytown\n\
teststrasse,002,targettown,22222,22222,3,a,11.0000000,51.0000000,Teststraße,Targettown\n",
"de",
);
let top = idx
.query("Teststraße 3, 22222 Querytown", 1)
.into_iter()
.next()
.expect("the established bare-number result must remain available");
assert_eq!(top.housenumber.as_deref(), Some("3"));
assert_eq!(top.commune, "Querytown");
assert_eq!(top.postcode, "22111");
assert!(
!top.flags.contains(&"de_exact_postcode_override"),
"a suffixed indexed house must not prove a bare product key"
);
let mut key = b"teststrasse".to_vec();
key.push(KEY_SEP);
key.extend_from_slice(b"002");
let target_sid = idx
.streets_fst
.get(&key)
.expect("the suffixed target street must exist") as u32;
let target_meta = idx.street_meta(target_sid);
assert!(
!idx.exact_house_postcode_candidate_cached(
&mut HashMap::new(),
target_sid,
&target_meta,
3,
0,
22222,
),
"the strict Wave-A admission proof itself must reject suffixed 3a for requested bare 3"
);
}
#[test]
fn de_wave_a_override_gate_is_address_level_and_fail_closed() {
let pair = |hit: RankedHit| (hit.0, hit.1);
let make = |precision, postcode, features, flags| {
vec![pair(retained_test_hit(
"Querytown",
"Teststraße",
Some("1"),
postcode,
precision,
1.0,
features,
flags,
0,
0,
))]
};
assert!(!Index::de_strict_postcode_house_override_allowed(
&[],
22222
));
assert!(!Index::de_strict_postcode_house_override_allowed(
&make(
"street",
"22111",
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
vec!["street_exact"],
),
22222,
));
assert!(Index::de_strict_postcode_house_override_allowed(
&make(
"house",
"22111",
[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep"],
),
22222,
));
assert!(!Index::de_strict_postcode_house_override_allowed(
&make(
"house",
"22222",
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep", "pc_exact"],
),
22222,
));
assert!(Index::de_strict_postcode_house_override_allowed(
&make(
"near",
"22222",
[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
vec!["pc_exact"],
),
22222,
));
assert!(!Index::de_strict_postcode_house_override_allowed(
&make("near", "22111", [0.0; N_FEATS], vec![],),
22222,
));
}
#[test]
fn de_wave_a_exact_house_beyond_cap_beats_near_without_fuzzy_fallback() {
let mut rows = String::from(
"teststrasse,001,querytown region,22222,22222,2,,10.0000000,50.0000000,Teststraße,Querytown Region\n\
teststrasse,001,querytown region,22222,22222,4,,10.0010000,50.0010000,Teststraße,Querytown Region\n",
);
for commune in 2..=340 {
rows.push_str(&format!(
"teststrasse,{commune:03},ort{commune:03},22222,22222,2,,10.{commune:07},50.{commune:07},Teststraße,Ort {commune:03}\n"
));
}
rows.push_str(
"teststrasse,999,querytown,22222,22222,3,,11.0000000,51.0000000,Teststraße,Querytown\n",
);
let idx = forward_postcode_index_for_country("wave-a-exact-house-beyond-cap", &rows, "de");
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.set(0));
DE_POSTCODE_HOUSE_RESCUE_FUZZY_CALLS.with(|calls| calls.set(0));
DE_POSTCODE_HOUSE_RESCUE_SUBSET_CALLS.with(|calls| calls.set(0));
let direct = idx
.de_postcode_house_rescue_parsed(
"Teststraße 3, 22222 Querytown Region",
"Teststraße 3 22222",
22222,
"querytown region",
1,
None,
None,
&[],
false,
)
.expect("the bounded exact product scan must find the unique indexed house");
assert_eq!(direct[0].0.commune, "Querytown");
assert!(DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.get()) > 300);
assert_eq!(
DE_POSTCODE_HOUSE_RESCUE_FUZZY_CALLS.with(|calls| calls.get()),
0,
"the strict rescue must not open the fuzzy collector"
);
assert_eq!(
DE_POSTCODE_HOUSE_RESCUE_SUBSET_CALLS.with(|calls| calls.get()),
0,
"the strict rescue must not open the subset collector"
);
let top = idx
.query("Teststraße 3, 22222 Querytown Region", 1)
.into_iter()
.next()
.expect("the exact indexed house must beat a capped near result");
assert_eq!(top.precision, "house");
assert_eq!(top.housenumber.as_deref(), Some("3"));
assert_eq!(top.postcode, "22222");
assert_eq!(top.commune, "Querytown");
assert!(top.flags.contains(&"de_postcode_house"));
}
#[test]
fn de_wave_a_two_endpoint_house_set_is_same_sid_postcode_and_suffix_strict() {
let complete = forward_postcode_index_for_country(
"wave-a-house-set-complete",
"paarstrasse,001,querytown region,23552,23552,2,,10.0000000,50.0000000,Paarstraße,Querytown Region\n\
paarstrasse,001,querytown region,23552,23552,4,,10.0010000,50.0010000,Paarstraße,Querytown Region\n\
paarstrasse,999,querytown,23552,23552,1,,11.0000000,51.0000000,Paarstraße,Querytown\n\
paarstrasse,999,querytown,23552,23552,3,,11.0010000,51.0010000,Paarstraße,Querytown\n",
"de",
);
let top = complete
.query("Paarstraße 1/3, 23552 Querytown Region", 1)
.into_iter()
.next()
.expect("both exact endpoints on one SID must be eligible");
assert_eq!(top.precision, "house");
assert_eq!(top.housenumber.as_deref(), Some("1"));
assert_eq!(top.commune, "Querytown");
assert!(top.flags.contains(&"de_exact_postcode_override"));
assert!(top.flags.contains(&"de_house_set_exact"));
assert!(top.flags.contains(&"de_house_slash"));
for (name, target_rows) in [
(
"missing-right",
"paarstrasse,999,querytown,23552,23552,1,,11.0000000,51.0000000,Paarstraße,Querytown\n",
),
(
"split-sids",
"paarstrasse,998,querytown,23552,23552,1,,11.0000000,51.0000000,Paarstraße,Querytown\n\
paarstrasse,999,querytown,23552,23552,3,,11.0010000,51.0010000,Paarstraße,Querytown\n",
),
(
"right-wrong-postcode",
"paarstrasse,999,querytown,23552,23552,1,,11.0000000,51.0000000,Paarstraße,Querytown\n\
paarstrasse,999,querytown,23553,23553,3,,11.0010000,51.0010000,Paarstraße,Querytown\n",
),
(
"right-wrong-suffix",
"paarstrasse,999,querytown,23552,23552,1,,11.0000000,51.0000000,Paarstraße,Querytown\n\
paarstrasse,999,querytown,23552,23552,3,a,11.0010000,51.0010000,Paarstraße,Querytown\n",
),
(
"duplicate-full-sets",
"paarstrasse,998,querytown,23552,23552,1,,11.0000000,51.0000000,Paarstraße,Querytown\n\
paarstrasse,998,querytown,23552,23552,3,,11.0010000,51.0010000,Paarstraße,Querytown\n\
paarstrasse,999,querytown,23552,23552,1,,12.0000000,52.0000000,Paarstraße,Querytown\n\
paarstrasse,999,querytown,23552,23552,3,,12.0010000,52.0010000,Paarstraße,Querytown\n",
),
] {
let rows = format!(
"paarstrasse,001,querytown region,23552,23552,2,,10.0000000,50.0000000,Paarstraße,Querytown Region\n\
paarstrasse,001,querytown region,23552,23552,4,,10.0010000,50.0010000,Paarstraße,Querytown Region\n{target_rows}"
);
let idx = forward_postcode_index_for_country(name, &rows, "de");
let top = idx
.query("Paarstraße 1/3, 23552 Querytown Region", 1)
.into_iter()
.next()
.expect("the established near result must remain available");
assert_eq!(top.commune, "Querytown Region", "{name}");
assert!(!top.flags.contains(&"de_house_set_exact"), "{name}");
assert!(!top.flags.contains(&"de_exact_postcode_override"), "{name}");
}
}
#[test]
fn de_postcode_house_rescue_skips_fuzzy_and_subset_fallbacks() {
let mut rows = String::new();
for commune in 1..=340 {
rows.push_str(&format!(
"teststrasse,{commune:03},ort{commune:03},20202,20202,1,,10.{commune:07},50.{commune:07},Teststraße,Ort {commune:03}\n"
));
}
let idx = forward_postcode_index_for_country("postcode-house-no-fallbacks", &rows, "de");
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.set(0));
DE_POSTCODE_HOUSE_RESCUE_HOUSE_DECODES.with(|calls| calls.set(0));
DE_POSTCODE_HOUSE_RESCUE_FUZZY_CALLS.with(|calls| calls.set(0));
DE_POSTCODE_HOUSE_RESCUE_SUBSET_CALLS.with(|calls| calls.set(0));
assert!(idx
.de_comma_postcode_house_rescue("Teststraße 1, 10115 Alpha", 1, None)
.is_none());
assert!(DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.get()) > 300);
assert_eq!(
DE_POSTCODE_HOUSE_RESCUE_HOUSE_DECODES.with(|calls| calls.get()),
0,
"postcode metadata must reject every incompatible homonym before house decoding"
);
assert_eq!(
DE_POSTCODE_HOUSE_RESCUE_FUZZY_CALLS.with(|calls| calls.get()),
0,
"a rescue that ultimately requires street_exact must not run fuzzy collection"
);
assert_eq!(
DE_POSTCODE_HOUSE_RESCUE_SUBSET_CALLS.with(|calls| calls.get()),
0,
"a rescue that ultimately requires street_exact must not run subset collection"
);
}
#[test]
fn de_postcode_house_rescue_fails_closed_when_exact_key_scan_overflows() {
let hidden_duplicate = forward_postcode_index_for_country(
"postcode-house-hidden-duplicate",
"teststrasse,001,alpha,10115,10115,1,,13.3800000,52.5100000,Teststraße,Alpha\n\
teststrasse,002,beta,20202,20202,2,,9.9900000,53.5500000,Teststraße,Beta\n\
teststrasse,003,gamma,30303,30303,3,,11.5800000,48.1400000,Teststraße,Gamma\n\
teststrasse,004,zzzdelta,10115,10115,1,,13.3900000,52.5200000,Teststraße,ZZZ Delta\n",
"de",
);
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(|limit| limit.set(3));
assert!(hidden_duplicate
.de_comma_postcode_house_rescue("Teststraße 1, 10115 Alpha", 1, None)
.is_none());
let hidden_unique = forward_postcode_index_for_country(
"postcode-house-hidden-unique",
"teststrasse,001,alpha,11111,11111,1,,13.3800000,52.5100000,Teststraße,Alpha\n\
teststrasse,002,beta,20202,20202,2,,9.9900000,53.5500000,Teststraße,Beta\n\
teststrasse,003,gamma,30303,30303,3,,11.5800000,48.1400000,Teststraße,Gamma\n\
teststrasse,004,zzzdelta,10115,10115,1,,13.3900000,52.5200000,Teststraße,ZZZ Delta\n",
"de",
);
assert!(hidden_unique
.de_comma_postcode_house_rescue("Teststraße 1, 10115 ZZZ Delta", 1, None)
.is_none());
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT
.with(|limit| limit.set(DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT));
}
#[test]
fn de_comma_postcode_house_rescue_beats_a_locality_alias_mismatch() {
let idx = forward_postcode_index_for_country(
"postcode-house-locality-alias",
"wiesenstraße,001,reichenbach,,,16,,12.3000000,50.6100000,Wiesenstraße,Reichenbach\n\
wiesenstraße,002,reichenbach im vogtland,08468,08468,62,,12.3073686,50.6160174,Wiesenstraße,Reichenbach im Vogtland\n",
"de",
);
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.set(0));
let top = idx
.query("Wiesenstraße 62, 08468 Reichenbach (Vogt.)", 1)
.into_iter()
.next()
.expect("the explicit street, house and postcode must rescue the locality alias");
assert_eq!(top.street, "Wiesenstraße");
assert_eq!(top.housenumber.as_deref(), Some("62"));
assert_eq!(top.postcode, "08468");
assert_eq!(top.commune, "Reichenbach im Vogtland");
assert!(top.flags.contains(&"de_postcode_house"));
assert!(
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.get()) > 0,
"the alias mismatch must use the narrow extended scan"
);
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.set(0));
let ordinary = idx.query("Wiesenstraße 62, 08468 Reichenbach im Vogtland", 1);
assert_eq!(
ordinary.first().map(|hit| hit.postcode.as_str()),
Some("08468")
);
assert_eq!(
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.get()),
0,
"a complete ordinary query must never pay for the extended homonym scan"
);
assert!(
idx.de_comma_postcode_house_rescue("Wiesenstraße 62, 08468 Hamburg", 1, None,)
.is_none(),
"an exact postcode candidate must not erase an explicit contradictory locality"
);
}
#[test]
fn de_postcode_house_rescue_composes_with_bounded_delivery_cleanup() {
let idx = forward_postcode_index_for_country(
"postcode-house-delivery-cleanup",
"berliner straße,001,delmenhorst,,,121,,8.6536862,53.0422502,Berliner Straße,Delmenhorst\n\
berliner straße,002,pankow,13187,13187,121,,13.4121414,52.5686551,Berliner Straße,Pankow\n\
friedrichstraße,003,braunschweig,,,55,,10.5315859,52.2522607,Friedrichstraße,Braunschweig\n\
friedrichstraße,004,mitte,10117,10117,55,,13.3902408,52.5092760,Friedrichstraße,Mitte\n\
teststraße,006,berlin,10117,10117,70,,13.3913916,52.5087689,Teststraße,Berlin\n",
"de",
);
for (query, expected_street, expected_postcode, effect_flag) in [
(
"für den Empfang, Berliner Straße 121, 13187 Berlin",
"Berliner Straße",
"13187",
"de_recipient_prefix",
),
(
"Berlin, Friedrichstraße 55, 10117",
"Friedrichstraße",
"10117",
"de_locality_first",
),
(
"Teststraße 70,10117 Berlin,Tel. 030 49499637",
"Teststraße",
"10117",
"de_subaddress_tail",
),
] {
let (top, _) = idx
.de_comma_postcode_house_rescue(query, 1, None)
.unwrap_or_else(|| panic!("bounded cleanup must rescue {query:?}"))
.into_iter()
.next()
.unwrap_or_else(|| panic!("bounded cleanup must rescue {query:?}"));
assert_eq!(top.street, expected_street, "{query}");
assert_eq!(top.postcode, expected_postcode, "{query}");
assert!(
top.flags.contains(&"de_postcode_house"),
"{query}: {:?}",
top.flags
);
assert!(top.flags.contains(&effect_flag), "{query}: {:?}", top.flags);
}
assert!(idx
.de_comma_postcode_house_rescue(
"für den Empfang, Berliner Straße 121-123, 13187 Berlin",
1,
None,
)
.is_none());
}
#[test]
fn de_postcode_house_rescue_accepts_only_exact_postcode_locality_aliases() {
let idx = forward_postcode_index_for_country(
"postcode-house-exact-locality-aliases",
"havelweg,002,brandenburg,14770,14770,2,,12.5500000,52.4100000,Havelweg,Brandenburg\n\
kirchweg,003,fehmarn,23769,23769,3,,11.1900000,54.4400000,Kirchweg,Fehmarn\n\
pankower weg,001,pankow,13187,13187,1,,13.4100000,52.5700000,Pankower Weg,Pankow\n\
spreeweg,004,lubbenau,03222,03222,4,,13.9600000,51.8600000,Spreeweg,Lübbenau\n",
"de",
);
for (query, expected_commune) in [
("Pankower Weg 1, 13187 Berlin", "Pankow"),
("Havelweg 2, 14770 Brandenburg an der Havel", "Brandenburg"),
("Kirchweg 3, 23769 Landkirchen", "Fehmarn"),
("Spreeweg 4, 03222 Zerkwitz", "Lübbenau"),
] {
let rescued = idx
.de_comma_postcode_house_rescue(query, 1, None)
.unwrap_or_else(|| panic!("the exact alias must rescue {query:?}"));
assert_eq!(rescued[0].0.commune, expected_commune);
assert!(rescued[0].0.flags.contains(&"de_postcode_house"));
}
assert!(idx
.de_comma_postcode_house_rescue("Pankower Weg 1, 13187 Gesundbrunnen", 1, None)
.is_none());
assert!(idx
.de_comma_postcode_house_rescue("Kirchweg 3, 23769 Zerkwitz", 1, None)
.is_none());
let ranked = forward_postcode_index_for_country(
"postcode-house-exact-alias-ranked",
"pankower weg,001,berlin,13187,13187,1,,13.4000000,52.5600000,Pankower Weg,Berlin\n\
pankower weg,002,pankow,13187,13187,1,,13.4100000,52.5700000,Pankower Weg,Pankow\n",
"de",
);
let exact_locality = ranked
.de_comma_postcode_house_rescue("Pankower Weg 1, 13187 Berlin", 1, None)
.expect("exact locality must outrank a weaker audited district relation");
assert_eq!(exact_locality[0].0.commune, "Berlin");
let tied = forward_postcode_index_for_country(
"postcode-house-exact-alias-tied",
"pankower weg,001,berlin,13187,13187,1,,13.4000000,52.5600000,Pankower Weg,Berlin\n\
pankower weg,002,berlin,13187,13187,1,,13.4100000,52.5700000,Pankower Weg,Berlin\n",
"de",
);
assert!(tied
.de_comma_postcode_house_rescue("Pankower Weg 1, 13187 Berlin", 1, None)
.is_none());
}
#[test]
fn de_exact_alias_dropped_prefix_top_reopens_only_the_narrow_rescue() {
let pair = |hit: RankedHit| (hit.0, hit.1);
let complete_dropped = vec![pair(retained_test_hit(
"Werder",
"An der Havel",
Some("44"),
"14542",
"house",
1.0,
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
vec!["street_exact", "house_rep", "pc_exact", "dropped_prefix"],
0,
0,
))];
assert!(Index::de_should_try_postcode_house_rescue(
"Alpenstraße 44, 14542 Werder a.d.Havel",
&complete_dropped,
));
assert!(!Index::de_should_try_postcode_house_rescue(
"Alpenstraße 44, 14543 Werder a.d.Havel",
&complete_dropped,
));
let mut complete_without_drop = complete_dropped;
complete_without_drop[0]
.0
.flags
.retain(|flag| *flag != "dropped_prefix");
assert!(!Index::de_should_try_postcode_house_rescue(
"Alpenstraße 44, 14542 Werder a.d.Havel",
&complete_without_drop,
));
}
#[test]
fn de_comma_postcode_house_rescue_rejects_explicit_frankfurt_conflict() {
let idx = forward_postcode_index_for_country(
"postcode-house-frankfurt-conflict",
"collegienstrasse,003,frankfurt,15230,15230,10,,14.5500000,52.3470000,Collegienstraße,Frankfurt\n\
domstrasse,001,frankfurt am main,60311,60311,10,,8.6820000,50.1110000,Domstraße,Frankfurt am Main\n\
dummy,002,frankfurt oder,15230,15230,1,,14.5500000,52.3470000,Dummy,Frankfurt (Oder)\n\
teststrasse,004,frankfurt,60311,60311,10,,8.6820000,50.1110000,Teststraße,Frankfurt\n",
"de",
);
assert!(idx
.de_comma_postcode_house_rescue("Domstraße 10, 60311 Frankfurt am Main", 1, None,)
.is_some());
assert!(idx
.de_comma_postcode_house_rescue("Domstraße 10, 60311 Frankfurt an der Oder", 1, None,)
.is_none());
assert!(idx
.de_comma_postcode_house_rescue("Domstraße 10, 60311 Offenbach", 1, None,)
.is_none());
assert!(idx
.de_comma_postcode_house_rescue("Collegienstraße 10, 15230 Frankfurt/Oder", 1, None,)
.is_some());
assert!(idx
.de_comma_postcode_house_rescue("Teststraße 10, 60311 Frankfurt/Oder", 1, None,)
.is_none());
}
#[test]
fn de_comma_postcode_house_rescue_shape_is_narrow_and_range_safe() {
assert_eq!(
de_comma_postcode_house_rescue_query("Wiesenstr. 62, 08468 Reichenbach (Vogt.)"),
Some((
"Wiesenstr. 62 08468".to_string(),
8468,
"reichenbach vogt".to_string(),
))
);
assert_eq!(
de_comma_postcode_house_rescue_query("Olsdorfer Str. 6, 25826 St Peter-Ording"),
Some((
"Olsdorfer Str. 6 25826".to_string(),
25826,
"st peter ording".to_string(),
))
);
assert_eq!(
de_comma_postcode_house_rescue_query("Breite Str. 49, 23769 Burg auf Fehmarn"),
Some((
"Breite Str. 49 23769".to_string(),
23769,
"burg auf fehmarn".to_string(),
))
);
for rejected in [
"Wiesenstr. 62, 08468",
"Wiesenstr. 62-64, 08468 Reichenbach",
"Wiesenstr. 62 - 64, 08468 Reichenbach",
"Alaunplatz 3b - 3c, 01099 Dresden",
"Alaunplatz 3ab - 3ac, 01099 Dresden",
"Wiesenstr. 62/64, 08468 Reichenbach",
"Firma, Wiesenstr. 62, 08468 Reichenbach",
] {
assert_eq!(de_comma_postcode_house_rescue_query(rejected), None);
}
}
#[test]
fn de_compact_house_pair_left_parser_is_narrow_and_dirty_tolerant() {
for (raw, expected_query, expected_postcode, expected_locality, expected_effect) in [
(
"Hauptstraße 78/79, 12159 Berlin",
"Hauptstraße 78 12159",
12159,
"berlin",
crate::de::Effect::HouseSlash,
),
(
"Heerstraße 12–14 14052Berlin",
"Heerstraße 12 14052",
14052,
"berlin",
crate::de::Effect::HouseRange,
),
(
"Berliner Straße 46/48,16303 Schwedt/Oder",
"Berliner Straße 46 16303",
16303,
"schwedt oder",
crate::de::Effect::HouseSlash,
),
(
"Friedrichstraße 76—78 10117 Berlin",
"Friedrichstraße 76 10117",
10117,
"berlin",
crate::de::Effect::HouseRange,
),
] {
assert_eq!(
de_compact_house_pair_left_rescue_query(raw),
Some((
expected_query.to_owned(),
expected_postcode,
expected_locality.to_owned(),
expected_effect,
)),
"unexpected parse for {raw:?}"
);
}
assert_eq!(
de_compact_house_pair_spec("Mühlendamm 1/3, 23552 Lübeck"),
Some(DeCompactHousePairSpec {
query: "Mühlendamm 1 23552".to_owned(),
postcode: 23552,
locality_tail: "lubeck".to_owned(),
effect: crate::de::Effect::HouseSlash,
left: 1,
right: 3,
})
);
assert_eq!(
de_compact_house_pair_left_rescue_query("Mühlendamm 1/3, 23552 Lübeck"),
None,
"the legacy left-only fallback must not reinterpret a small slash pair"
);
for rejected in [
"Kapuzinerstraße 1/2, 48149 Münster",
"Berliner Straße 46/48/50, 16303 Schwedt/Oder",
"Alaunplatz 3b-3c, 01099 Dresden",
"Heerstraße 12 - 14, 14052 Berlin",
"Heerstraße 12 bis 14, 14052 Berlin",
"Heerstraße 12 und 14, 14052 Berlin",
"Heerstraße 14-12, 14052 Berlin",
"Heerstraße 12-14, 14052",
"Firma, Heerstraße 12-14, 14052 Berlin",
"Heerstraße 12-14, 14052 Berlin, Tel. 030 123456",
] {
assert_eq!(de_compact_house_pair_left_rescue_query(rejected), None);
}
}
#[test]
fn de_compact_house_pair_left_rescue_requires_unique_exact_address() {
let idx = forward_postcode_index_for_country(
"compact-house-pair-left",
"berliner strasse,001,schwedt,16303,16303,46,,14.2800000,53.0600000,Berliner Straße,Schwedt\n\
friedrichstrasse,002,mitte,10117,10117,76,,13.3900000,52.5100000,Friedrichstraße,Mitte\n\
hauptstrasse,003,friedenau,12159,12159,78,,13.3300000,52.4700000,Hauptstraße,Friedenau\n\
heerstrasse,004,westend,14052,14052,12,,13.2600000,52.5100000,Heerstraße,Westend\n",
"de",
);
for (query, expected_house, expected_commune, expected_effect_flag) in [
(
"Hauptstraße 78/79, 12159 Berlin",
"78",
"Friedenau",
"de_house_slash",
),
(
"Heerstraße 12–14, 14052 Berlin",
"12",
"Westend",
"de_house_range",
),
(
"Berliner Straße 46/48, 16303 Schwedt/Oder",
"46",
"Schwedt",
"de_house_slash",
),
(
"Friedrichstraße 76-78, 10117 Berlin",
"76",
"Mitte",
"de_house_range",
),
] {
let rescued = idx
.de_compact_house_pair_left_rescue(query, 1, None)
.unwrap_or_else(|| panic!("left endpoint must rescue {query:?}"));
let top = &rescued[0].0;
assert_eq!(top.housenumber.as_deref(), Some(expected_house));
assert_eq!(top.commune, expected_commune);
assert!(top.flags.contains(&expected_effect_flag));
assert!(top.flags.contains(&"de_house_left_endpoint"));
assert!(!top.flags.contains(&"de_postal_tail"));
}
let duplicate = forward_postcode_index_for_country(
"compact-house-pair-duplicate",
"hauptstrasse,001,berlin,12159,12159,78,,13.3200000,52.4600000,Hauptstraße,Berlin\n\
hauptstrasse,002,friedenau,12159,12159,78,,13.3300000,52.4700000,Hauptstraße,Friedenau\n",
"de",
);
assert!(duplicate
.de_compact_house_pair_left_rescue("Hauptstraße 78/79, 12159 Berlin", 1, None)
.is_none());
assert!(idx
.de_compact_house_pair_left_rescue("Hauptstraße 78/79, 14052 Berlin", 1, None)
.is_none());
assert!(idx
.de_compact_house_pair_left_rescue("Hauptstraße 78/79, 12159 Pankow", 1, None)
.is_none());
}
#[test]
fn de_compact_house_pair_rescue_reaches_unique_left_endpoint_beyond_ordinary_cap() {
let mut rows = String::new();
for commune in 1..=340 {
rows.push_str(&format!(
"hauptstrasse,{commune:03},ort{commune:03},20202,20202,1,,10.{commune:07},50.{commune:07},Hauptstraße,Ort {commune:03}\n"
));
}
rows.push_str(
"hauptstrasse,999,friedenau,12159,12159,78,,13.3300000,52.4700000,Hauptstraße,Friedenau\n",
);
let idx = forward_postcode_index_for_country("compact-house-pair-beyond-cap", &rows, "de");
DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.set(0));
let top = idx
.query("Hauptstraße 78/79, 12159 Berlin", 1)
.into_iter()
.next()
.expect("the unique exact left endpoint must survive the ordinary cap");
assert_eq!(top.housenumber.as_deref(), Some("78"));
assert_eq!(top.postcode, "12159");
assert_eq!(top.commune, "Friedenau");
assert!(top.flags.contains(&"de_house_left_endpoint"));
assert!(top.flags.contains(&"de_house_slash"));
assert!(!top.flags.contains(&"de_postal_tail"));
assert!(DE_POSTCODE_HOUSE_RESCUE_SCAN_ROWS.with(|rows| rows.get()) > 300);
}
#[test]
fn de_compact_house_pair_rescue_never_displaces_a_complete_current_result() {
let idx = forward_postcode_index_for_country(
"compact-house-pair-strong-current",
"starkstrasse,001,berlin,10115,10115,10,,13.3900000,52.5300000,Starkstraße,Berlin\n",
"de",
);
let top = idx
.query("Starkstraße 10-12, 10115 Berlin", 1)
.into_iter()
.next()
.expect("the ordinary compact-range rule must resolve the exact house");
assert_eq!(top.housenumber.as_deref(), Some("10"));
assert!(top.flags.contains(&"street_exact"));
assert!(top.flags.contains(&"house_rep"));
assert!(top.flags.contains(&"pc_exact"));
assert!(!top.flags.contains(&"de_house_left_endpoint"));
}
#[test]
fn v6_ambiguous_house_block_uses_legacy_grammar_end_to_end() {
let dir = std::env::temp_dir().join(format!(
"gridpin-v6-ambiguous-postcode-{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n\
legacy,001,ville,1012,1012AA,1,,4.9000,52.3700,Legacy,Ville\n\
legacy,001,ville,1012,1012AA,3,,4.9010,52.3710,Legacy,Ville\n",
)
.unwrap();
let v7 = dir.join("v7.bin");
crate::builder::build(&csv, &v7, None, None, None, None, None).unwrap();
let mut bytes = std::fs::read(&v7).unwrap();
let sections = parse_sections(&bytes).unwrap();
let street_meta = sections[SEC_STREETS_META].0 as usize;
bytes[4] = 6;
bytes[street_meta + 32..street_meta + 36].copy_from_slice(&PC_DISP_AMBIGUOUS.to_le_bytes());
let v6 = dir.join("v6.bin");
std::fs::write(&v6, bytes).unwrap();
let idx = Index::open(&v6).expect("v6 legacy ambiguous grammar must remain readable");
let exact = idx
.query_structured("legacy", Some("3"), "ville", None, 1)
.remove(0)
.0;
assert_eq!(exact.precision, "house");
assert_eq!(exact.housenumber.as_deref(), Some("3"));
assert_eq!(exact.postcode, "");
let reverse = idx.reverse(52.3710, 4.9010, 1).unwrap().remove(0);
assert_eq!(reverse.housenumber.as_deref(), Some("3"));
assert_eq!(reverse.postcode, "");
assert!(
parse_sections_for_repack(&std::fs::read(v6).unwrap()).is_err(),
"a readable v6 sheet must still never be relabeled by repack"
);
}
#[test]
fn v7_corrupt_house_data_cannot_cross_into_the_next_street_block() {
let dir = std::env::temp_dir().join(format!(
"gridpin-v7-postcode-block-boundary-{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n\
alpha,001,ville,1012,1012AA,1,,4.9000,52.3700,Alpha,Ville\n\
alpha,001,ville,1012,1012AB,3,,4.9010,52.3710,Alpha,Ville\n\
beta,001,ville,1013,1013AA,1,,4.9100,52.3800,Beta,Ville\n",
)
.unwrap();
let good = dir.join("good.bin");
crate::builder::build(&csv, &good, None, None, None, None, None).unwrap();
let mut bytes = std::fs::read(&good).unwrap();
let sections = parse_sections(&bytes).unwrap();
let streets_meta = sections[SEC_STREETS_META].0 as usize;
let houses = sections[SEC_HOUSE_BLOCKS].0 as usize;
let next_house_off = read_u64(&bytes, streets_meta + STREET_META_SIZE + 20) as usize;
bytes[houses + next_house_off - 1] = 0x80;
let corrupt = dir.join("corrupt.bin");
std::fs::write(&corrupt, bytes).unwrap();
let idx = Index::open(&corrupt).expect("dictionary header itself remains valid");
let hit = idx
.query_structured("alpha", Some("3"), "ville", None, 1)
.remove(0)
.0;
assert_ne!(
hit.precision, "house",
"an unterminated id must stop at alpha's boundary, not consume beta bytes"
);
assert_eq!(hit.postcode, "");
}
#[test]
fn v7_dictionary_cannot_point_at_an_arbitrary_name() {
let dir = std::env::temp_dir().join(format!(
"gridpin-v7-postcode-dictionary-name-{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n\
alpha,001,ville,1012,1012AA,1,,4.9000,52.3700,Alpha,Ville\n\
alpha,001,ville,1012,1012AB,3,,4.9010,52.3710,Alpha,Ville\n",
)
.unwrap();
let good = dir.join("good.bin");
crate::builder::build(&csv, &good, None, None, None, None, None).unwrap();
let mut bytes = std::fs::read(&good).unwrap();
let sections = parse_sections(&bytes).unwrap();
let street_meta = sections[SEC_STREETS_META].0 as usize;
let house_section = sections[SEC_HOUSE_BLOCKS].0 as usize;
let first_house = read_u64(&bytes, street_meta + 20) as usize;
let street_name_off = read_u32(&bytes, street_meta + 16);
// count is one byte for this two-postcode fixture; overwrite dictionary entry 1.
bytes[house_section + first_house + 1..house_section + first_house + 5]
.copy_from_slice(&street_name_off.to_le_bytes());
let corrupt = dir.join("corrupt.bin");
std::fs::write(&corrupt, bytes).unwrap();
let error = Index::open(&corrupt)
.err()
.expect("a street name must never be accepted as a postcode")
.to_string();
assert!(error.contains("house-postcode dictionary"), "{error}");
}
#[test]
fn v7_exact_house_postcodes_are_house_accurate_while_street_stays_empty() {
let idx = forward_postcode_index(
"exact-street",
"damrak,001,amsterdam,1012,1012AA,1,,4.9000,52.3700,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AB,3,,4.9010,52.3710,Damrak,Amsterdam\n",
);
for (number, expected) in [("1", "1012AA"), ("3", "1012AB")] {
let hit = idx
.query_structured("damrak", Some(number), "amsterdam", None, 1)
.remove(0)
.0;
assert_eq!(hit.precision, "house");
assert_eq!(hit.postcode, expected);
}
let street = idx
.query_structured("damrak", None, "amsterdam", None, 1)
.remove(0)
.0;
assert_eq!(street.precision, "street");
assert_eq!(
street.postcode, "",
"street-level postcode remains empty on a mixed-postcode street"
);
}
#[test]
fn v7_exact_house_postcode_drives_pc_exact_instead_of_street_majority() {
let idx = forward_postcode_index_for_country(
"house-pc-exact",
"guntzstrasse,001,dresden,1309,01309,2,,13.7400,51.0500,Güntzstraße,Dresden\n\
guntzstrasse,001,dresden,1309,01309,4,,13.7410,51.0510,Güntzstraße,Dresden\n\
guntzstrasse,001,dresden,1307,01307,22,,13.7420,51.0520,Güntzstraße,Dresden\n",
"de",
);
let (hit, features) = idx
.query_structured("guntzstrasse", Some("22"), "dresden", Some("01307"), 1)
.remove(0);
assert_eq!(hit.precision, "house");
assert_eq!(hit.housenumber.as_deref(), Some("22"));
assert_eq!(hit.postcode, "01307");
assert_eq!(features[4], 1.0, "the selected house postcode is exact");
assert_eq!(features[5], 1.0, "exact postcodes retain the dept feature");
assert_eq!(
hit.score, 11.0,
"house postcode refinement precedes scoring"
);
assert!(hit.flags.contains(&"pc_exact"));
assert!(!hit.flags.contains(&"pc_dept"));
let free = idx
.query("Güntzstraße 22, 01307 Dresden Unbekannt", 1)
.remove(0);
assert_eq!(free.precision, "house");
assert_eq!(free.housenumber.as_deref(), Some("22"));
assert_eq!(free.postcode, "01307");
assert!(free.flags.contains(&"pc_exact"));
assert!(!free.flags.contains(&"pc_dept"));
assert!(free.flags.contains(&"dropped_suffix"));
assert!(!free.flags.contains(&"de_postal_tail"));
let (street_majority_was_wrong, features) = idx
.query_structured("guntzstrasse", Some("22"), "dresden", Some("01309"), 1)
.remove(0);
assert_eq!(street_majority_was_wrong.postcode, "01307");
assert_eq!(
features[4], 0.0,
"the chosen house disproves street pc_exact"
);
assert_eq!(features[5], 1.0);
assert!(!street_majority_was_wrong.flags.contains(&"pc_exact"));
assert!(street_majority_was_wrong.flags.contains(&"pc_dept"));
}
#[test]
fn v7_duplicate_house_uses_query_postcode_to_choose_the_exact_row() {
let idx = forward_postcode_index(
"duplicate-house-postcode",
"hauptstrasse,001,dresden,1156,01156,1,,13.6000,51.0600,Hauptstraße,Dresden\n\
hauptstrasse,001,dresden,1097,01097,1,,13.7500,51.0700,Hauptstraße,Dresden\n\
hauptstrasse,001,dresden,1328,01328,1,,13.8000,51.0800,Hauptstraße,Dresden\n\
hauptstrasse,001,dresden,1156,01156,3,,13.6100,51.0610,Hauptstraße,Dresden\n",
);
let (hit, features) = idx
.query_structured("hauptstrasse", Some("1"), "dresden", Some("01097"), 1)
.remove(0);
assert_eq!(hit.precision, "house");
assert_eq!(hit.housenumber.as_deref(), Some("1"));
assert_eq!(hit.postcode, "01097");
assert_eq!(features[4], 1.0);
assert!(hit.flags.contains(&"pc_exact"));
let free = idx.query("hauptstrasse 1 01097 dresden", 1).remove(0);
assert_eq!(free.postcode, "01097");
assert!(free.flags.contains(&"pc_exact"));
let third = idx
.query_structured("hauptstrasse", Some("1"), "dresden", Some("01328"), 1)
.remove(0)
.0;
assert_eq!(third.postcode, "01328");
let (no_postcode, no_postcode_features) = idx
.query_structured("hauptstrasse", Some("1"), "dresden", None, 1)
.remove(0);
assert_eq!(no_postcode.postcode, "01156");
assert_eq!(no_postcode_features[8], 1.0);
assert!(no_postcode.flags.contains(&"house_rep"));
let (absent_postcode, absent_postcode_features) = idx
.query_structured("hauptstrasse", Some("1"), "dresden", Some("01098"), 1)
.remove(0);
assert_eq!(absent_postcode.postcode, "01156");
assert_eq!(absent_postcode_features[8], 1.0);
assert!(absent_postcode.flags.contains(&"house_rep"));
}
#[test]
fn v7_duplicate_postcode_selection_never_crosses_the_requested_suffix() {
let idx = forward_postcode_index(
"duplicate-house-suffix",
"hauptstrasse,001,dresden,1156,01156,1,,13.6000,51.0600,Hauptstraße,Dresden\n\
hauptstrasse,001,dresden,1097,01097,1,a,13.7500,51.0700,Hauptstraße,Dresden\n\
hauptstrasse,001,dresden,1156,01156,3,,13.6100,51.0610,Hauptstraße,Dresden\n",
);
let blank = idx
.query_structured("hauptstrasse", Some("1"), "dresden", Some("01097"), 1)
.remove(0)
.0;
assert_eq!(blank.housenumber.as_deref(), Some("1"));
assert_eq!(blank.postcode, "01156");
assert!(blank.flags.contains(&"house_rep"));
let suffixed = idx
.query_structured("hauptstrasse", Some("1a"), "dresden", Some("01097"), 1)
.remove(0)
.0;
assert_eq!(suffixed.housenumber.as_deref(), Some("1a"));
assert_eq!(suffixed.postcode, "01097");
}
#[test]
fn postcode_numeric_prefix_treats_zero_as_missing() {
assert_eq!(Index::postcode_numeric_prefix("00000"), None);
assert_eq!(Index::postcode_numeric_prefix(""), None);
assert_eq!(Index::postcode_numeric_prefix("01307"), Some(1307));
assert_eq!(Index::postcode_numeric_prefix("1012AA"), Some(1012));
}
#[test]
fn v7_missing_house_postcode_never_inherits_the_known_neighbor() {
let idx = forward_postcode_index(
"missing-known",
"damrak,001,amsterdam,0,,1,,4.9000,52.3700,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AA,3,,4.9010,52.3710,Damrak,Amsterdam\n",
);
let missing = idx
.query_structured("damrak", Some("1"), "amsterdam", None, 1)
.remove(0)
.0;
let known = idx
.query_structured("damrak", Some("3"), "amsterdam", None, 1)
.remove(0)
.0;
assert_eq!(missing.postcode, "");
assert_eq!(known.postcode, "1012AA");
let (missing_with_query_postcode, features) = idx
.query_structured("damrak", Some("1"), "amsterdam", Some("1012"), 1)
.remove(0);
assert_eq!(missing_with_query_postcode.postcode, "");
assert_eq!(features[4], 0.0);
assert_eq!(features[5], 0.0);
assert!(!missing_with_query_postcode.flags.contains(&"pc_exact"));
assert!(!missing_with_query_postcode.flags.contains(&"pc_dept"));
}
#[test]
fn v7_near_and_interpolation_postcodes_follow_the_represented_address() {
let near_idx = forward_postcode_index(
"near-postcode",
"damrak,001,amsterdam,1012,1012AA,10,,4.9000,52.3700,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AB,30,,4.9100,52.3800,Damrak,Amsterdam\n",
);
let near = near_idx
.query_structured("damrak", Some("17"), "amsterdam", None, 1)
.remove(0)
.0;
assert_eq!(near.precision, "near");
assert_eq!(near.housenumber.as_deref(), Some("10"));
assert_eq!(near.postcode, "1012AA");
let interp_idx = forward_postcode_index(
"interp-postcode",
"damrak,001,amsterdam,1012,1012AA,10,,4.9000,52.3700,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AA,20,,4.9010,52.3705,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AB,30,,4.9020,52.3710,Damrak,Amsterdam\n",
);
let same = interp_idx
.query_structured("damrak", Some("15"), "amsterdam", None, 1)
.remove(0)
.0;
let cross = interp_idx
.query_structured("damrak", Some("25"), "amsterdam", None, 1)
.remove(0)
.0;
assert_eq!(same.precision, "interp");
assert_eq!(same.postcode, "1012AA");
assert_eq!(cross.precision, "interp");
assert_eq!(cross.postcode, "");
let (cross_with_query_postcode, features) = interp_idx
.query_structured("damrak", Some("25"), "amsterdam", Some("1012"), 1)
.remove(0);
assert_eq!(cross_with_query_postcode.postcode, "");
assert_eq!(features[4], 0.0);
assert_eq!(features[5], 0.0);
assert!(!cross_with_query_postcode.flags.contains(&"pc_exact"));
}
#[test]
fn v7_same_number_suffixes_and_reverse_keep_each_house_postcode() {
let idx = forward_postcode_index(
"suffix-reverse",
"damrak,001,amsterdam,1012,1012AA,12,a,4.9000,52.3700,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AB,12,b,4.9010,52.3710,Damrak,Amsterdam\n",
);
for (number, expected) in [("12a", "1012AA"), ("12b", "1012AB")] {
let hit = idx
.query_structured("damrak", Some(number), "amsterdam", None, 1)
.remove(0)
.0;
assert_eq!(hit.housenumber.as_deref(), Some(number));
assert_eq!(hit.postcode, expected);
}
let reverse = idx.reverse(52.3700, 4.9000, 2).unwrap();
let by_number: std::collections::HashMap<&str, &str> = reverse
.iter()
.filter_map(|hit| {
hit.housenumber
.as_deref()
.map(|number| (number, hit.postcode.as_str()))
})
.collect();
assert_eq!(by_number.get("12a"), Some(&"1012AA"));
assert_eq!(by_number.get("12b"), Some(&"1012AB"));
}
#[test]
fn v7_truncated_house_postcode_id_never_panics_or_borrows_a_postcode() {
let dir = std::env::temp_dir().join(format!(
"gridpin-v7-truncated-postcode-{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
"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.9000,52.3700,Damrak,Amsterdam\n\
damrak,001,amsterdam,1012,1012AB,3,,4.9010,52.3710,Damrak,Amsterdam\n",
)
.unwrap();
let good = dir.join("good.bin");
crate::builder::build(&csv, &good, None, None, None, None, None).unwrap();
let mut bytes = std::fs::read(&good).unwrap();
let sections = parse_sections(&bytes).unwrap();
let (house_off, house_len) = sections[SEC_HOUSE_BLOCKS];
// The last byte is the second house's one-byte local postcode id. Turn it into an
// unterminated varint at the SEC_HOUSE_BLOCKS boundary; the following names section must
// never be read as continuation bytes.
bytes[(house_off + house_len - 1) as usize] = 0x80;
let corrupt = dir.join("corrupt.bin");
std::fs::write(&corrupt, bytes).unwrap();
let idx = Index::open(&corrupt).expect("bounded dictionary header remains openable");
let hits = idx.query_structured("damrak", Some("3"), "amsterdam", None, 1);
assert!(
hits.first().is_none_or(|(hit, _)| hit.postcode.is_empty()),
"a truncated house postcode id must fail closed, never borrow another postcode"
);
}
#[test]
fn forward_exact_house_forwards_the_stored_number_and_suffix() {
let idx = forward_housenumber_index(
"exact",
"rue test,001,ville,10000,12,a,7.4200,43.7300,Rue Test,Ville\n",
);
let hit = idx
.query_structured("rue test", Some("12a"), "ville", Some("10000"), 1)
.remove(0)
.0;
assert_eq!(hit.precision, "house");
assert_eq!(hit.housenumber.as_deref(), Some("12a"));
let street = idx
.query_structured("rue test", None, "ville", Some("10000"), 1)
.remove(0)
.0;
assert_eq!(street.precision, "street");
assert_eq!(
street.housenumber, None,
"street-only answers have no number"
);
}
#[test]
fn forward_near_house_forwards_the_snapped_stored_address() {
let idx = forward_housenumber_index(
"near",
"rue test,001,ville,10000,10,a,7.4200,43.7300,Rue Test,Ville\n\
rue test,001,ville,10000,30,b,7.4210,43.7310,Rue Test,Ville\n",
);
let hit = idx
.query_structured("rue test", Some("17"), "ville", Some("10000"), 1)
.remove(0)
.0;
assert_eq!(hit.precision, "near");
assert_eq!(hit.housenumber.as_deref(), Some("10a"));
}
#[test]
fn subset_recognized_type_cannot_override_distinguishing_names() {
let idx = forward_housenumber_index(
"subset-type-seed",
"avenue saffron amber,001,ville,10000,1,,7.4200,43.7300,Avenue Saffron Amber,Ville\n\
lane rue,001,ville,10000,1,,7.4210,43.7300,Lane Rue,Ville\n\
place saffron violet,001,ville,10000,1,,7.4220,43.7300,Place Saffron Violet,Ville\n",
);
let _rules = crate::rules::scope(idx.rules);
assert!(is_street_type_word("rue"));
assert_eq!(idx.word_streets("rue").len(), 1);
assert_eq!(idx.word_streets("saffron").len(), 2);
for words in [
vec!["rue", "saffron"],
vec!["saffron", "rue"],
vec!["saffron"],
] {
let (sets, nontype, ids) = idx.subset_intersect(&words).unwrap();
let names: std::collections::BTreeSet<_> = ids
.iter()
.map(|id| idx.name(idx.street_meta(*id).name_off))
.collect();
assert_eq!(
names,
["Avenue Saffron Amber", "Place Saffron Violet"].into()
);
assert_eq!((sets, nontype), (1, 1));
}
let (_, _, ids) = idx.subset_intersect(&["rue", "saffron", "amber"]).unwrap();
let names: Vec<_> = ids
.iter()
.map(|id| idx.name(idx.street_meta(*id).name_off))
.collect();
assert_eq!(names, ["Avenue Saffron Amber"]);
assert!(idx.subset_intersect(&["rue"]).is_none());
assert!(idx.subset_intersect(&["rue", "zzqzzqzz"]).is_none());
}
/// Range points of one street side (prep/us_tiger.py): numbers 100 and 198 about 150 m
/// apart, each with the range marker suffix; `marker` empty builds the same rows as houses.
fn range_point_rows(marker: &str) -> String {
let mut rows = String::new();
for (number, lon) in [(100, -87.5000), (198, -87.5018)] {
rows.push_str(&format!(
"main street,001,town,36530,{number},{marker},{lon},30.4000,Main Street,Town\n"
));
}
rows
}
#[test]
fn range_points_interpolate_across_a_wide_number_gap() {
let idx = forward_housenumber_index("range-wide", &range_point_rows("~"));
let hit = idx
.query_structured("main street", Some("149"), "town", None, 1)
.remove(0)
.0;
assert_eq!(hit.precision, "interp", "{}", hit.precision);
assert_eq!(hit.housenumber.as_deref(), Some("149"));
assert!(
(hit.lon - (-87.5009)).abs() < 1e-6,
"midpoint expected: {}",
hit.lon
);
}
#[test]
fn houses_with_the_same_wide_gap_still_snap_to_the_nearest_neighbour() {
let idx = forward_housenumber_index("range-houses", &range_point_rows(""));
let hit = idx
.query_structured("main street", Some("149"), "town", None, 1)
.remove(0)
.0;
assert_eq!(hit.precision, "near", "{}", hit.precision);
assert_eq!(hit.housenumber.as_deref(), Some("100"));
}
#[test]
fn a_marked_number_is_an_interpolation_without_the_marker_in_the_answer() {
let idx = forward_housenumber_index("range-exact", &range_point_rows("~"));
let hit = idx
.query_structured("main street", Some("198"), "town", None, 1)
.remove(0)
.0;
assert_eq!(hit.precision, "interp", "{}", hit.precision);
assert_eq!(hit.housenumber.as_deref(), Some("198"));
// A snap onto a range point prints the plain number as well.
let near = idx
.query_structured("main street", Some("260"), "town", None, 1)
.remove(0)
.0;
assert_eq!(near.precision, "near", "{}", near.precision);
assert_eq!(near.housenumber.as_deref(), Some("198"));
}
#[test]
fn a_real_house_beats_the_range_point_with_the_same_number() {
let mut rows = range_point_rows("~");
rows.push_str("main street,001,town,36530,198,,-87.5030,30.4005,Main Street,Town\n");
let idx = forward_housenumber_index("range-house-wins", &rows);
let hit = idx
.query_structured("main street", Some("198"), "town", None, 1)
.remove(0)
.0;
assert_eq!(hit.precision, "house", "{}", hit.precision);
assert!((hit.lon - (-87.5030)).abs() < 1e-6);
}
#[test]
fn forward_interpolation_prefers_the_requested_parity() {
for offset in [0, 1] {
let mut rows = String::new();
for (number, lon, lat) in [
(10, 7.4200, 43.7300),
(11, 7.4205, 43.7310),
(13, 7.4215, 43.7310),
(14, 7.4220, 43.7300),
] {
rows.push_str(&format!(
"rue test,001,ville,10000,{},,{lon},{lat},Rue Test,Ville\n",
number + offset
));
}
let idx = forward_housenumber_index("parity", &rows);
let requested = (12 + offset).to_string();
let hit = idx
.query_structured("rue test", Some(&requested), "ville", Some("10000"), 1)
.remove(0)
.0;
assert_eq!(hit.precision, "interp");
assert_eq!(hit.housenumber.as_deref(), Some(requested.as_str()));
assert!(
(hit.lat - 43.7300).abs() < 1e-6,
"wrong street side: {}",
hit.lat
);
assert!((hit.lon - 7.4210).abs() < 1e-6);
}
}
#[test]
fn forward_interpolation_wide_same_parity_bracket_snaps_to_nearest_house() {
let idx = forward_housenumber_index(
"parity-wide",
"rue test,001,ville,10000,2,,7.4200,43.7300,Rue Test,Ville\n\
rue test,001,ville,10000,11,a,7.4205,43.7310,Rue Test,Ville\n\
rue test,001,ville,10000,13,b,7.4215,43.7310,Rue Test,Ville\n\
rue test,001,ville,10000,24,,7.4220,43.7300,Rue Test,Ville\n",
);
let hit = idx
.query_structured("rue test", Some("12"), "ville", Some("10000"), 1)
.remove(0)
.0;
assert_eq!(hit.precision, "near");
assert_eq!(hit.housenumber.as_deref(), Some("11a"));
assert!((hit.lat - 43.7310).abs() < 1e-6);
assert!((hit.lon - 7.4205).abs() < 1e-6);
}
#[test]
fn a_sheet_widens_the_interpolation_bracket() {
// 12 between 2 and 24: 22 numbers apart, too wide for the default (12) but not for a
// sheet with city_tail interp_max_gap 400 / interp_max_km 2.0 (Canada, 29.10.2026)
let rows = "rue test,001,ville,10000,2,,7.4200,43.7300,Rue Test,Ville\n\
rue test,001,ville,10000,24,,7.4220,43.7300,Rue Test,Ville\n";
let build = |rules: Option<&str>| {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-interp-limits-{}-{serial}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
let rules_dir = rules.map(|tsv| {
let d = dir.join("rules");
std::fs::create_dir_all(&d).unwrap();
std::fs::write(d.join("city_tail.tsv"), tsv).unwrap();
d
});
let bin = dir.join("addresses.bin");
crate::builder::build(&csv, &bin, None, None, rules_dir.as_deref(), None, None)
.unwrap();
Index::open(&bin).unwrap()
};
let answer = |idx: &Index| {
idx.query_structured("rue test", Some("12"), "ville", Some("10000"), 1)
.remove(0)
.0
};
assert_eq!(answer(&build(None)).precision, "near");
let wide = answer(&build(Some("interp_max_gap\t400\ninterp_max_km\t2.0\n")));
assert_eq!(wide.precision, "interp");
assert!(
(wide.lon - (7.4200 + 0.0020 * 10.0 / 22.0)).abs() < 1e-6,
"{}",
wide.lon
);
// the gap widened but not the distance (the neighbours stand ~160 m apart): nearest house
let gap_only = answer(&build(Some("interp_max_gap\t400\ninterp_max_km\t0.1\n")));
assert_eq!(gap_only.precision, "near");
}
#[test]
fn fuzzy_search_reads_a_typo_with_the_type_at_the_sheet_short_form() {
// "Ratchfrod Street": the sheet keys "ratchford st"; the swap is one edit only once
// "street" is "st". The type itself is no edit: "Diefenbaker Place" is not the
// Diefenbaker DR two edits away (Canada, 30.10.2026).
let rows = "diefenbaker dr,001,amherst,0,10,,-64.2200,45.8300,Diefenbaker DR,Amherst\n\
ratchford st,001,amherst,0,10,,-64.2100,45.8300,Ratchford ST,Amherst\n\
thornbury st e,001,amherst,0,10,,-64.2300,45.8300,Thornbury ST E,Amherst\n";
let build = |key: bool| {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-fuzzy-short-{}-{serial}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
let d = dir.join("rules");
std::fs::create_dir_all(&d).unwrap();
let tail = if key {
"direction_trailing\tn s e w\nfuzzy_short_forms\t1\n"
} else {
"direction_trailing\tn s e w\n"
};
std::fs::write(d.join("city_tail.tsv"), tail).unwrap();
std::fs::write(
d.join("abbrev2.tsv"),
"street\tst\tstreet\nstreet\tstreet\tst\nstreet\tpl\tplace\nstreet\tplace\tpl\n\
street\tdr\tdrive\nstreet\tdrive\tdr\nstreet\te\teast\nstreet\teast\te\n\
street\tw\twest\nstreet\twest\tw\n",
)
.unwrap();
std::fs::write(d.join("street_types_latin.tsv"), "street\nplace\ndrive\n").unwrap();
let bin = dir.join("addresses.bin");
crate::builder::build(&csv, &bin, None, None, Some(&d), None, None).unwrap();
Index::open(&bin).unwrap()
};
let street = |idx: &Index, name: &str| {
idx.query_structured(name, Some("10"), "amherst", None, 1)
.first()
.map(|(hit, _)| hit.street.clone())
};
let fuzzy = |idx: &Index, rest: &[&str]| {
let _rules = crate::rules::scope(idx.rules);
idx.collect_fuzzy(rest, None, false).len()
};
let on = build(true);
assert_eq!(
street(&on, "ratchfrod street").as_deref(),
Some("Ratchford ST")
);
// the fuzzy search itself: another fallback may still read the name words alone
assert_eq!(fuzzy(&on, &["ratchfrod", "street"]), 1);
assert_eq!(fuzzy(&on, &["diefenbaker", "place"]), 0);
// every word set to its short form must stand in the street, the direction too
assert_eq!(fuzzy(&on, &["thornbry", "street", "east"]), 1);
assert_eq!(fuzzy(&on, &["thornbry", "street", "west"]), 0);
// the short form as written needs no key; the written-out type does
let off = build(false);
assert_eq!(fuzzy(&off, &["ratchfrod", "st"]), 1);
assert_eq!(fuzzy(&off, &["ratchfrod", "street"]), 0);
}
#[test]
fn fuzzy_short_rest_shortens_only_types_and_directions() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "fuzzy_short_forms".to_owned(), "1".to_owned()),
(23, "direction_trailing".to_owned(), "n s e w o".to_owned()),
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "o".to_owned(), "ouest".to_owned()),
(24, "ouest".to_owned(), "o".to_owned()),
(24, "mt".to_owned(), "mount".to_owned()),
(24, "mount".to_owned(), "mt".to_owned()),
(24, "1".to_owned(), "premier".to_owned()),
(24, "premier".to_owned(), "1".to_owned()),
(16, "street".to_owned(), String::new()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
let short = |rest: &[&str]| fuzzy_short_rest(rest);
assert_eq!(
short(&["ratchfrod", "street", "amherst"]),
Some(vec![
"ratchfrod".to_owned(),
"st".to_owned(),
"amherst".to_owned()
])
);
assert_eq!(
short(&["sherrbooke", "ouest"]),
Some(vec!["sherrbooke".to_owned(), "o".to_owned()])
);
// near-misses: a name word with a rewrite ("mount"), a number word, nothing to shorten
assert_eq!(short(&["mount", "pleasatn"]), None);
assert_eq!(short(&["premier", "avneue"]), None);
assert_eq!(short(&["ratchfrod", "st"]), None);
}
#[test]
fn fuzzy_short_rest_needs_the_sheet_key() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(16, "street".to_owned(), String::new()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
assert_eq!(fuzzy_short_rest(&["ratchfrod", "street"]), None);
}
#[test]
fn a_short_saint_town_is_found_under_its_full_name_only_with_the_sheet_key() {
// "2050 Bombardier, Ste-Julie": the sheet names the town "Sainte-Julie"; a town the sheet
// itself spells "St …" keeps that spelling (Canada, 30.10.2026).
let rows = "rue bombardier,001,sainte julie,0,2050,,-73.3400,45.5800,rue Bombardier,Sainte-Julie\n\
st paul st,002,st catharines,0,10,,-79.2400,43.1600,St. Paul ST,St Catharines\n";
let build = |key: bool| {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-saint-town-{}-{serial}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
let d = dir.join("rules");
std::fs::create_dir_all(&d).unwrap();
std::fs::write(
d.join("city_tail.tsv"),
if key { "saint_communes\t1\n" } else { "" },
)
.unwrap();
let bin = dir.join("addresses.bin");
crate::builder::build(&csv, &bin, None, None, Some(&d), None, None).unwrap();
Index::open(&bin).unwrap()
};
let towns = |idx: &Index, name: &str| {
let _rules = crate::rules::scope(idx.rules);
idx.communes_by_name_unheld(name).len()
};
let on = build(true);
assert_eq!(towns(&on, "ste julie"), 1);
assert_eq!(towns(&on, "sainte julie"), 1);
assert_eq!(towns(&on, "st catharines"), 1);
// near-misses: "st" is not "ste", no town after it
assert_eq!(towns(&on, "st julie"), 0);
let off = build(false);
assert_eq!(towns(&off, "ste julie"), 0);
}
#[test]
fn saint_commune_name_spells_out_st_and_ste() {
let on = vec![(23, "saint_communes".to_owned(), "1".to_owned())];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&on),
));
assert_eq!(
saint_commune_name("ste julie").as_deref(),
Some("sainte julie")
);
assert_eq!(
saint_commune_name("st georges").as_deref(),
Some("saint georges")
);
assert_eq!(saint_commune_name("saint georges"), None);
assert_eq!(saint_commune_name("stella"), None);
assert_eq!(saint_commune_name("st"), None);
let _off = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&[]),
));
assert_eq!(saint_commune_name("ste julie"), None);
}
#[test]
fn town_outside_region_reads_the_table() {
let entries = vec![
(23, "saint_communes".to_owned(), "1".to_owned()),
(
27,
"saint leonard".to_owned(),
"NB 47.1632 -67.9246;QC 45.5877 -73.5950".to_owned(),
),
(
27,
"saint pascal".to_owned(),
"QC 47.5181 -69.8030".to_owned(),
),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
let at = |lat: f64, lon: f64| {
let (mut hit, _) = quadrant_hit("city", vec!["place_exact"], "");
hit.lat = lat;
hit.lon = lon;
hit
};
// the New Brunswick town for "ST-LEONARD, QC": outside; the Montréal one: inside
assert!(town_outside_region(&at(47.17, -67.92), "st leonard", "QC"));
assert!(!town_outside_region(&at(45.59, -73.60), "st leonard", "QC"));
// known only in Québec, asked in Ontario: outside
assert!(town_outside_region(&at(47.52, -69.80), "st pascal", "ON"));
// a town the table does not know is never judged
assert!(!town_outside_region(&at(47.52, -69.80), "nowhere", "ON"));
}
#[test]
fn rewritten_bare_names_closing_with_a_direction_get_the_type_padding() {
let rules = |on: bool| {
let mut entries = vec![(23, "enabled".to_owned(), "1".to_owned())];
if on {
entries.push((23, "direction_trailing".to_owned(), "n s e w o".to_owned()));
}
entries.push((16, "rue".to_owned(), String::new()));
entries.push((16, "park".to_owned(), String::new()));
entries.push((17, "st".to_owned(), String::new()));
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let _scope = crate::rules::scope(rules(true));
let padded = |v: &[&str]| {
type_padded_direction_variants(&v.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>())
};
// "6890 Notre-Dame Est": the variant "notre dame e" is what the sheet keys with its type
let got = padded(&["notre dame e"]);
assert!(got.contains(&"rue notre dame e".to_owned()), "{got:?}");
// near-misses: no closing direction, a variant that already names a type ("st w" once
// "Dundas" is the town: padded it is "park st w"), a type in front
assert!(padded(&["notre dame"]).is_empty());
assert!(padded(&["st w"]).is_empty());
assert!(padded(&["rue notre dame e"]).is_empty());
let _off = crate::rules::scope(rules(false));
assert!(padded(&["notre dame e"]).is_empty());
}
#[test]
fn forward_interpolation_forwards_the_requested_address() {
let idx = forward_housenumber_index(
"interp",
"rue test,001,ville,10000,10,a,7.4200,43.7300,Rue Test,Ville\n\
rue test,001,ville,10000,20,b,7.4210,43.7305,Rue Test,Ville\n\
rue test,001,ville,10000,30,c,7.4220,43.7310,Rue Test,Ville\n",
);
let hit = idx
.query_structured("rue test", Some("15c"), "ville", Some("10000"), 1)
.remove(0)
.0;
assert_eq!(hit.precision, "interp");
assert_eq!(hit.housenumber.as_deref(), Some("15c"));
}
#[test]
fn forward_focus_injects_a_same_name_street_beyond_the_global_fst_cap() {
let mut rows = String::new();
for ordinal in 0..305u32 {
let (insee, commune, lon, lat) = if ordinal == 304 {
("99999".to_string(), "Wanted".to_string(), 7.7455, 48.5839)
} else {
(
format!("{ordinal:05}"),
format!("Global {ordinal:03}"),
2.0,
43.0,
)
};
rows.push_str(&format!(
"markt,{insee},{},10000,1,,{lon:.4},{lat:.4},Markt,{commune}\n",
normalize(&commune)
));
}
let idx = forward_housenumber_index("focus-ring-cap", &rows);
let ordinary = idx.query("1 markt", 100);
assert!(
ordinary.iter().all(|hit| hit.commune != "Wanted"),
"the fixture must place Wanted beyond the ordinary 300-row prefix cap"
);
let focused = idx.query_near("1 markt", 100, 48.5839, 7.7455).unwrap();
assert_eq!(
focused.first().map(|hit| hit.commune.as_str()),
Some("Wanted")
);
}
#[test]
fn forward_focus_keeps_the_global_fallback_for_an_unrelated_local_grid() {
let idx = forward_housenumber_index(
"focus-global-fallback",
"alpha,001,origin,75000,1,,2.3500,48.8500,Alpha,Origin\n\
beta,002,focus,67000,1,,7.7455,48.5839,Beta,Focus\n\
delta,002,focus,67000,1,,7.7460,48.5840,Delta,Focus\n\
gamma,002,focus,67000,1,,7.7465,48.5841,Gamma,Focus\n",
);
let focused = idx.query_near("1 alpha", 3, 48.5839, 7.7455).unwrap();
assert_eq!(
focused.first().map(|hit| hit.street.as_str()),
Some("Alpha")
);
assert_eq!(
focused.first().map(|hit| hit.commune.as_str()),
Some("Origin")
);
}
#[test]
fn forward_focus_does_not_turn_reordered_words_into_an_exact_homonym() {
let idx = forward_housenumber_index(
"focus-strict-street-identity",
"alpha beta,001,origin,75000,1,,2.3500,48.8500,Alpha Beta,Origin\n\
beta alpha,002,focus,67000,1,,7.7455,48.5839,Beta Alpha,Focus\n",
);
let ordinary = idx.query("1 alpha beta", 1);
let focused = idx.query_near("1 alpha beta", 1, 48.5839, 7.7455).unwrap();
assert_eq!(
ordinary.first().map(|hit| hit.street.as_str()),
Some("Alpha Beta")
);
assert_eq!(
focused.first().map(|hit| hit.street.as_str()),
Some("Alpha Beta")
);
}
#[test]
fn forward_focus_breaks_only_an_equal_quality_homonym_tie() {
let mut rows = String::new();
for number in 1..=10 {
rows.push_str(&format!(
"markt,001,far,10000,{number},,2.{number:04},43.0000,Markt,Far\n"
));
}
rows.push_str("markt,002,near,67000,1,,7.7455,48.5839,Markt,Near\n");
let idx = forward_housenumber_index("focus-distance-tie", &rows);
let ordinary = idx.query("1 markt", 2);
let focused = idx.query_near("1 markt", 2, 48.5839, 7.7455).unwrap();
assert_eq!(ordinary.len(), 2);
assert_eq!(focused.len(), 2);
assert_eq!(
ordinary[0].commune, "Far",
"fixture must expose the legacy order"
);
assert_eq!(focused[0].commune, "Near");
assert_eq!(ordinary[0].score, ordinary[1].score);
assert_eq!(focused[0].score, focused[1].score);
let ordinary_set: std::collections::BTreeSet<_> =
ordinary.iter().map(|hit| hit.commune.as_str()).collect();
let focused_set: std::collections::BTreeSet<_> =
focused.iter().map(|hit| hit.commune.as_str()).collect();
assert_eq!(
ordinary_set, focused_set,
"focus may reorder but not replace the global set"
);
}
#[test]
fn missing_admin_sidecar_after_rename_is_detected() {
// a release rename that moves the sheet but not the sidecar must be caught,
// not silently drop regions. admin_sidecar derives the expected name and flags a mismatch.
let dir = std::env::temp_dir().join(format!("gridpin-sidecar-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
// a valid WOFA sidecar named for the ORIGINAL sheet (rs.bin -> rs_admin.bin)
let mut wofa = b"WOFA".to_vec();
wofa.extend_from_slice(&0u32.to_le_bytes()); // n = 0 regions
wofa.extend_from_slice(&[0u8; 4]); // padding so len > 8
std::fs::write(dir.join("rs_admin.bin"), &wofa).unwrap();
std::fs::write(dir.join("rs.bin"), b"dummy").unwrap();
std::fs::write(dir.join("rs-2026.07.gpin"), b"dummy").unwrap();
// the correctly-named sheet loads its sidecar
assert!(matches!(
admin_sidecar(&dir.join("rs.bin")),
AdminSidecar::Loaded(_)
));
// the RENAMED sheet has no matching sidecar but a SAME-COUNTRY sibling exists -> flagged
assert!(matches!(
admin_sidecar(&dir.join("rs-2026.07.gpin")),
AdminSidecar::MissingWithSibling { .. }
));
// an UNRELATED-country sidecar next to a sheet must NOT false-warn
std::fs::write(dir.join("uz.bin"), b"dummy").unwrap();
assert!(matches!(
admin_sidecar(&dir.join("uz.bin")),
AdminSidecar::MissingClean
));
}
#[test]
fn open_owns_and_drops_its_mapping_no_leak() {
// an Index must OWN its mapping and free it on Drop, not leak it forever.
// Deterministic (immune to parallel tests): clone the Arc<Mapping> and watch strong_count.
let dir = std::env::temp_dir().join(format!("gridpin-h12-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("h12.csv");
std::fs::write(
&csv,
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n\
rue a,001,ville,10000,1,,7.42,43.73,Rue A,Ville\n",
)
.unwrap();
let bin = dir.join("h12.bin");
crate::builder::build(&csv, &bin, None, None, None, None, None).unwrap();
let idx = Index::open(&bin).unwrap();
let mapping = std::sync::Arc::clone(&idx._mmap); // our clone + the Index's = 2
assert_eq!(
std::sync::Arc::strong_count(&mapping),
2,
"the Index owns a live mapping"
);
assert!(
!idx.query("rue a 1 ville", 1).is_empty(),
"and it still queries"
);
drop(idx);
assert_eq!(
std::sync::Arc::strong_count(&mapping),
1,
"dropping the Index released its mapping -> the mmap is freed (no leak)"
);
// a FAILED open must not leak either: a corrupt sheet returns Err and drops its mapping
let mut bytes = std::fs::read(&bin).unwrap();
bytes[6] = 200; // corrupt the TOC
let bad = dir.join("h12-bad.bin");
std::fs::write(&bad, &bytes).unwrap();
assert!(
Index::open(&bad).is_err(),
"corrupt sheet fails to open (and freed its mapping)"
);
}
#[test]
fn rank_rejects_wrong_feature_count_or_length() {
// bypass: a GPRK whose n != N_FEATS, or with short/over-long weight bytes, must be
// rejected — else score() silently zips only n weights against the N_FEATS vector.
let build = |n: u8, weights: usize| -> Vec<u8> {
let mut v = b"GPRK".to_vec();
v.push(n);
v.extend_from_slice(&0f32.to_le_bytes()); // bias
for _ in 0..weights {
v.extend_from_slice(&0.5f32.to_le_bytes());
}
v
};
assert!(
rank_section_is_valid(&build(N_FEATS as u8, N_FEATS)),
"exact n + length loads"
);
assert!(
!rank_section_is_valid(&build(1, N_FEATS)),
"shrunk n (mutant) rejected"
);
assert!(
!rank_section_is_valid(&build(N_FEATS as u8, N_FEATS + 3)),
"trailing bytes rejected"
);
assert!(
!rank_section_is_valid(&build(N_FEATS as u8, N_FEATS - 1)),
"short weight table rejected"
);
}
#[test]
fn rank_rejects_nonfinite_bias_and_weights() {
// a NaN bias/weight would propagate to every score (score:null / nan).
let gprk = |bias: f32, w0: f32| -> Vec<u8> {
let mut v = b"GPRK".to_vec();
v.push(N_FEATS as u8); // n MUST equal N_FEATS
v.extend_from_slice(&bias.to_le_bytes());
v.extend_from_slice(&w0.to_le_bytes());
for _ in 1..N_FEATS {
v.extend_from_slice(&0f32.to_le_bytes());
}
v
};
assert!(
Rank::from_section(&gprk(0.0, 0.5)).is_some(),
"a finite model loads"
);
assert!(
Rank::from_section(&gprk(f32::NAN, 0.5)).is_none(),
"NaN bias rejected"
);
assert!(
Rank::from_section(&gprk(0.0, f32::INFINITY)).is_none(),
"non-finite weight rejected"
);
}
fn hit(precision: &'static str, confidence: f32, flags: Vec<&'static str>) -> Hit {
Hit {
lat: 0.0,
lon: 0.0,
precision,
score: 0.0,
confidence,
street: String::new(),
housenumber: None,
commune: String::new(),
postcode: String::new(),
flags,
region: None,
distance_m: None,
}
}
#[test]
fn every_serialized_hit_ends_with_the_weak_verdict_after_the_fields_of_earlier_releases() {
// A city answer is weak, an exact house is not; optional fields keep their old omission,
// and `weak` comes last so that dropping it returns the bytes of 0.6 and earlier.
let city = hit("city", 0.05, vec!["place_exact"]);
assert_eq!(
serde_json::to_string(&city).unwrap(),
r#"{"lat":0.0,"lon":0.0,"precision":"city","score":0.0,"confidence":0.05,"street":"","commune":"","postcode":"","flags":["place_exact"],"weak":true}"#
);
let mut house = hit("house", 0.2, vec!["street_exact"]);
house.housenumber = Some("27".into());
house.region = Some("R".into());
house.distance_m = Some(1.5);
assert_eq!(
serde_json::to_string(&house).unwrap(),
r#"{"lat":0.0,"lon":0.0,"precision":"house","score":0.0,"confidence":0.2,"street":"","housenumber":"27","commune":"","postcode":"","flags":["street_exact"],"region":"R","distance_m":1.5,"weak":false}"#
);
// Low confidence alone makes a street answer weak; the field follows the rule, not a constant.
assert!(serde_json::to_string(&hit("street", 0.2, vec![]))
.unwrap()
.ends_with(r#""weak":true}"#));
assert!(
serde_json::to_string(&hit("street", 0.8, vec!["street_exact"]))
.unwrap()
.ends_with(r#""weak":false}"#)
);
}
#[test]
fn locality_only_drop_is_deferred_but_exact_drop_keeps_priority() {
let features = [0.0; N_FEATS];
let ordinary = vec![(
hit(
"near",
0.27,
vec![
"street_fuzzy",
"commune_exact",
"pc_exact",
"de_subaddress_tail",
],
),
features,
)];
let ordinary_quality = Index::de_variant_quality(&ordinary).unwrap();
for drop_flag in ["dropped_prefix", "dropped_suffix"] {
let locality_only = vec![(
hit(
"interp",
0.4,
vec![
"street_fuzzy",
"commune_exact",
"pc_exact",
drop_flag,
"__deferred_locality_drop",
],
),
features,
)];
let deferred_quality = Index::de_variant_quality(&locality_only).unwrap();
assert!(
Index::de_quality_is_better(ordinary_quality, deferred_quality),
"{drop_flag}: ordinary answer must win over locality-only bypass"
);
assert!(
deferred_quality.0 > i32::MIN
|| Index::de_quality_is_better(
deferred_quality,
(i32::MIN, 0, 0, f32::NEG_INFINITY)
),
"{drop_flag}: bypass must remain selectable when alone"
);
let exact_drop = vec![(
hit(
"house",
0.8,
vec!["street_exact", "commune_exact", "pc_exact", drop_flag],
),
features,
)];
let exact_quality = Index::de_variant_quality(&exact_drop).unwrap();
assert!(
Index::de_quality_is_better(exact_quality, ordinary_quality),
"{drop_flag}: exact-street drop must not be deferred"
);
}
}
/// The POI cascade may only be consulted when the address top-1 is weak. An exact house
/// match must NEVER be weak, whatever its calibrated confidence — a distant homonym
/// lowers confidence without making the match less exact (regression guard for the POI
/// override bug).
#[test]
fn input_budget_bounds_k_and_every_structured_field() {
// k and every field are capped at the public boundary so no interface (CLI/Python/
// DuckDB) can turn one call into an unbounded allocation / normalization pass.
assert_eq!(bound_k(usize::MAX), MAX_K, "huge k is capped");
assert_eq!(bound_k(0), 0, "k=0 keeps the zero-results contract");
assert_eq!(bound_k(7), 7, "a normal k passes through");
// a multi-MB field is bounded to MAX_QUERY_BYTES BEFORE normalization
let huge = "9".repeat(4 * 1024 * 1024);
assert!(
bound_query(&huge).len() <= MAX_QUERY_BYTES,
"number/postcode field is bounded"
);
// bounding is at a char boundary (never panics mid-codepoint)
let huge_utf8 = "é".repeat(2 * 1024 * 1024); // 2 bytes/char
let b = bound_query(&huge_utf8);
assert!(b.len() <= MAX_QUERY_BYTES && huge_utf8.starts_with(b));
}
#[test]
fn num_words_to_digits_rewrites_french_numerals() {
assert_eq!(
num_words_to_digits("rue du quatre septembre").as_deref(),
Some("rue du 4 septembre")
);
assert_eq!(num_words_to_digits("avenue de la paix"), None); // nothing to rewrite
}
#[test]
fn french_arrondissement_rewrite_accepts_formal_de_only_in_context() {
assert_eq!(
fr_arrondissement_rewrite("37 rue du hameau 15e arrondissement de paris").as_deref(),
Some("37 rue du hameau paris 15e arrondissement")
);
assert_eq!(
fr_arrondissement_rewrite("3e arrondissement de lyon").as_deref(),
Some("lyon 3e arrondissement")
);
assert_eq!(
fr_arrondissement_rewrite("1eme arrondissement de paris").as_deref(),
Some("paris 1er arrondissement")
);
assert_eq!(
fr_arrondissement_rewrite("1e arrondissement de marseille").as_deref(),
Some("marseille 1er arrondissement")
);
assert_eq!(
fr_arrondissement_rewrite("15e arrondissement paris de test").as_deref(),
Some("paris 15e arrondissement de test"),
"a de after the direct city form is not the optional preposition"
);
assert_eq!(
fr_arrondissement_rewrite("paris 15e rue du hameau 37").as_deref(),
Some("rue du hameau 37 paris 15e arrondissement")
);
assert_eq!(
fr_arrondissement_rewrite("paris 14e arrondissement rue du hameau 37").as_deref(),
Some("rue du hameau 37 paris 14e arrondissement")
);
assert_eq!(
fr_arrondissement_rewrite("rue de paris"),
None,
"ordinary de + city text is not an arrondissement rewrite"
);
assert_eq!(
fr_arrondissement_rewrite("15e de paris"),
None,
"the arrondissement context word is mandatory"
);
}
#[test]
fn french_arrondissement_postcode_area_is_narrow_and_fail_closed() {
assert_eq!(
fr_arrondissement_postcode_area("75015"),
Some(FrPostcodeArea::Match(
"paris 15e arrondissement".to_string()
))
);
assert_eq!(
fr_arrondissement_postcode_area("paris 75015"),
Some(FrPostcodeArea::Match(
"paris 15e arrondissement".to_string()
))
);
assert_eq!(
fr_arrondissement_postcode_area("69003 lyon 3eme arrondissement"),
Some(FrPostcodeArea::Match("lyon 3e arrondissement".to_string()))
);
assert_eq!(
fr_arrondissement_postcode_area("13001 marseille 1er"),
Some(FrPostcodeArea::Match(
"marseille 1er arrondissement".to_string()
))
);
assert_eq!(
fr_arrondissement_postcode_area("75116 paris"),
Some(FrPostcodeArea::Match(
"paris 16e arrondissement".to_string()
))
);
assert_eq!(
fr_arrondissement_postcode_area("75015 paris 14e"),
Some(FrPostcodeArea::Conflict)
);
assert_eq!(
fr_arrondissement_postcode_area("75015 lyon"),
Some(FrPostcodeArea::Conflict)
);
assert_eq!(
fr_arrondissement_postcode_area("35000 rennes"),
None,
"ordinary French postcodes stay on the generic parser path"
);
assert_eq!(
fr_arrondissement_postcode_area("75015 rue de vaugirard"),
None,
"a full street query is not swallowed by the area shortcut"
);
assert_eq!(
fr_arrondissement_postcode_area("37 rue du hameau 75015 lyon"),
Some(FrPostcodeArea::Conflict),
"a trailing conflicting city on a full address fails closed"
);
assert_eq!(
fr_arrondissement_postcode_area("37 rue du hameau 75015 paris 14e"),
Some(FrPostcodeArea::Conflict),
"a trailing conflicting ordinal on a full address fails closed"
);
assert_eq!(
fr_arrondissement_postcode_area("37 rue de lyon 75015 paris"),
None,
"a city word inside the street name is not a conflict"
);
assert_eq!(
fr_arrondissement_postcode_area("37 rue du hameau paris 14e 75015"),
Some(FrPostcodeArea::Conflict),
"a conflicting area immediately before the postcode fails closed"
);
assert!(has_explicit_fr_arrondissement("37 rue du hameau paris 14e"));
assert!(has_explicit_fr_arrondissement(
"37 rue du hameau paris 14e arrondissement"
));
assert!(has_explicit_fr_arrondissement(
"paris 14e arrondissement 37 rue du hameau"
));
assert!(!has_explicit_fr_arrondissement(
"37 rue de lyon 75015 paris"
));
let matched = |area: &str| Some(FrPostcodeArea::Match(area.to_string()));
assert_eq!(
fr_arrondissement_constraint("1 rue du louvre paris 15e"),
matched("paris 15e arrondissement")
);
assert_eq!(
fr_arrondissement_constraint("37 rue du hameau 75014 paris"),
matched("paris 14e arrondissement")
);
assert_eq!(
fr_arrondissement_constraint("150 cours lafayette lyon 3e arrondissement"),
matched("lyon 3e arrondissement")
);
assert_eq!(
fr_arrondissement_constraint("paris 15e rue du hameau 37"),
matched("paris 15e arrondissement")
);
assert_eq!(
fr_arrondissement_constraint("1 rue du louvre 75116 paris"),
matched("paris 16e arrondissement")
);
assert_eq!(
fr_arrondissement_constraint(
"37 rue du hameau 75015 paris 14e arrondissement batiment a"
),
Some(FrPostcodeArea::Conflict),
"unrelated trailing tokens must not hide contradictory district signals"
);
assert_eq!(
fr_arrondissement_constraint("37 rue de lyon paris"),
None,
"ordinary city words in a street do not create a district constraint"
);
}
#[test]
fn trailing_geographic_qualifier_selects_only_the_distant_homonym_cluster() {
let dir =
std::env::temp_dir().join(format!("gridpin-homonym-qualifier-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("homonyms.csv");
std::fs::write(
&csv,
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n\
anchor ancora,AN,ancora,,1,,10.00,45.00,Anchor Ancora,Ancora\n\
anchor bergamo,BG,bergamo,,1,,9.67,45.70,Anchor Bergamo,Bergamo\n\
anchor centro,CE,centro,,1,,10.75,45.00,Anchor Centro,Centro\n\
anchor lecce,LE,lecce,,1,,18.17,40.35,Anchor Lecce,Lecce\n\
anchor macerata,MA,macerata,,1,,13.45,43.30,Anchor Macerata,Macerata\n\
anchor romano,RO,romano,,1,,12.50,42.00,Anchor Romano,Romano\n\
anchor torino,TO,torino,,1,,7.69,45.07,Anchor Torino,Torino\n\
via intera,OR,oriolo romano,,7,,12.14,42.16,Via Intera,Oriolo Romano\n\
via marker,O1,oriolo,,1,,10.00,45.00,Via Marker,Oriolo\n\
via marker,O2,oriolo,,1,,18.00,40.00,Via Marker,Oriolo\n\
via mezzo,M1,mezzo,,14,,10.00,45.00,Via Mezzo,Mezzo\n\
via mezzo,M2,mezzo,,14,,11.50,45.00,Via Mezzo,Mezzo\n\
via ponte,P1,ponte,,14,,10.00,45.00,Via Ponte,Ponte\n\
via ponte,P2,ponte,,14,,10.63,45.00,Via Ponte,Ponte\n\
via ponte,P3,ponte,,14,,18.00,40.00,Via Ponte,Ponte\n\
via solo,CS,castro,,8,,18.43,40.01,Via Solo,Castro\n\
via test,CB,castro,,14,,10.06,45.80,Via Test,Castro\n\
via test,CS,castro,,14,,18.43,40.01,Via Test,Castro\n\
vicolo del ponte,MA,macerata,,8,,13.45,43.30,Vicolo Del Ponte,Macerata\n",
)
.unwrap();
let bin = dir.join("homonyms.bin");
let manifest = dir.join("it-manifest.json");
std::fs::write(
&manifest,
r#"{"country":"it","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
crate::builder::build(&csv, &bin, None, None, None, None, Some(&manifest)).unwrap();
let idx = Index::open(&bin).unwrap();
let bergamo = idx.query("via test 14 castro bergamo", 2);
assert_eq!(bergamo.len(), 1);
assert!((bergamo[0].lat - 45.80).abs() < 0.001);
assert!(bergamo[0].flags.contains(&"geo_qualifier"));
let lecce = idx.query("via test 14 castro lecce", 2);
assert_eq!(lecce.len(), 1);
assert!((lecce[0].lat - 40.01).abs() < 0.001);
assert!(
idx.query("via solo 8 castro bergamo", 2).is_empty(),
"a street absent from the selected cluster fails closed"
);
assert!(
idx.query("via test 14 castro torino", 2).is_empty(),
"a qualifier far from every homonym fails closed"
);
let full_commune = idx.query("via intera 7 oriolo romano", 1);
assert_eq!(full_commune.len(), 1);
assert_eq!(full_commune[0].commune, "Oriolo Romano");
assert!(
idx.query("via mezzo 14 mezzo centro", 2).is_empty(),
"a qualifier midway between remote homonyms is not enough evidence"
);
let coherent_cluster = idx.query("via ponte 14 ponte ancora", 3);
assert_eq!(
coherent_cluster.len(),
1,
"a same-name municipality outside the selected 40 km cluster is removed"
);
assert!((coherent_cluster[0].lon - 10.00).abs() < 0.001);
let street_tail = idx.query("8 vicolo del ponte macerata", 1);
assert_eq!(street_tail.len(), 1);
assert_eq!(street_tail[0].commune, "Macerata");
let no_meta_bin = dir.join("homonyms-no-meta.bin");
crate::builder::build(&csv, &no_meta_bin, None, None, None, None, None).unwrap();
let no_meta_idx = Index::open(&no_meta_bin).unwrap();
assert!(
no_meta_idx
.query("via test 14 castro bergamo", 2)
.iter()
.all(|hit| !hit.flags.contains(&"geo_qualifier")),
"an Italy-specific heuristic must not alter a metadata-less custom sheet"
);
}
#[test]
fn suffix_fallback_and_country_street_names_preserve_explicit_address_parts() {
let dir = std::env::temp_dir().join(format!(
"gridpin-suffix-country-guards-{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("guards.csv");
std::fs::write(
&csv,
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n\
anchor san fratello,SF,san fratello,,1,,14.59,38.02,Anchor San Fratello,San Fratello\n\
anchor san giuliano terme,SGT,san giuliano terme,,1,,10.44,43.76,Anchor San Giuliano Terme,San Giuliano Terme\n\
anchor villasalto,VI,villasalto,,1,,9.50,39.49,Anchor Villasalto,Villasalto\n\
corso italia,GI,giarre,,123,,15.18,37.73,Corso Italia,Giarre\n\
via falsa,LA,latina,,12,,12.90,41.47,Via Falsa,Latina\n\
via italia,SGT,san giuliano terme,,7,,10.45,43.77,Via Italia,San Giuliano Terme\n\
via roma,RM,roma,,1,,12.50,41.90,Via Roma,Roma\n",
)
.unwrap();
let bin = dir.join("guards.bin");
let manifest = dir.join("it-manifest.json");
std::fs::write(
&manifest,
r#"{"country":"it","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
crate::builder::build(&csv, &bin, None, None, None, None, Some(&manifest)).unwrap();
let idx = Index::open(&bin).unwrap();
assert!(
idx.query("via falsa 12 san fratello", 1).is_empty(),
"a recognized two-token commune must block the trailing-suffix fallback"
);
assert!(
idx.query("via falsa 12 villasalto", 1).is_empty(),
"a recognized one-token commune must not be dropped for a house elsewhere"
);
let italia = idx.query("via italia 7 san giuliano terme", 1);
assert_eq!(italia.len(), 1);
assert_eq!(italia[0].street, "Via Italia");
assert_eq!(italia[0].commune, "San Giuliano Terme");
let corso_italia = idx.query("corso italia 123 giarre", 1);
assert_eq!(corso_italia.len(), 1);
assert_eq!(corso_italia[0].street, "Corso Italia");
assert_eq!(corso_italia[0].commune, "Giarre");
let italia_unit = idx.query("via italia 7 scala b san giuliano terme", 1);
assert_eq!(italia_unit.len(), 1);
assert_eq!(italia_unit[0].street, "Via Italia");
assert_eq!(italia_unit[0].precision, "house");
let roma = idx.query("via roma roma", 1);
assert_eq!(roma.len(), 1);
assert_eq!(roma[0].street, "Via Roma");
assert_eq!(roma[0].commune, "Roma");
assert_eq!(
fold_units("torcy france 77200"),
"torcy 77200",
"a country noun after an ordinary locality remains removable"
);
}
#[test]
fn serbian_genitive_variant_forms() {
// knez -> kneza (title), possessive -ova -> -a (Mihailova -> Mihaila)
assert_eq!(
serbian_genitive_variant("knez mihailova").as_deref(),
Some("kneza mihaila")
);
assert_eq!(serbian_genitive_variant("rue de rivoli"), None);
}
#[test]
fn strip_phone_runs_drops_number_runs_but_keeps_a_house_number() {
// a run of >=4 short numeric tokens is a phone number, stripped
assert_eq!(
strip_phone_runs("rue x 1 2 3 4 paris").as_deref(),
Some("rue x paris")
);
// a lone house number is NOT a phone run and must survive (regression: never eat it)
assert_eq!(strip_phone_runs("rue x 12 paris"), None);
assert_eq!(strip_phone_runs("12 rue de la paix"), None);
}
#[test]
fn exact_house_is_never_weak() {
// even at rock-bottom confidence, an exact house is strong
assert!(!hit_is_weak(&hit(
"house",
0.05,
vec!["street_exact", "house_rep"]
)));
assert!(!hit_is_weak(&hit(
"house",
0.20,
vec!["street_exact", "ambiguous_far"]
)));
}
#[test]
fn weak_cases_are_still_weak() {
assert!(
hit_is_weak(&hit("city", 0.9, vec![])),
"city precision is weak"
);
assert!(
hit_is_weak(&hit("house", 0.10, vec!["street_fuzzy"])),
"very low confidence is weak"
);
assert!(
hit_is_weak(&hit("street", 0.50, vec!["street_fuzzy"])),
"fuzzy street below 0.60 is weak"
);
}
#[test]
fn confident_answers_are_not_weak() {
assert!(!hit_is_weak(&hit("street", 0.80, vec!["street_exact"])));
assert!(
!hit_is_weak(&hit("house", 0.65, vec!["street_fuzzy", "house_rep"])),
"fuzzy but confident enough"
);
}
#[test]
fn de_wave_b_p3_strict_source_typos_cover_the_six_product_shapes() {
let cases = [
(
"ruesselheimerstrasse,001,kelsterbach,65450,65450,2,,8.5200000,50.0500000,Rüsselheimerstraße,Kelsterbach\n\
ruesselsheimer strasse,002,kelsterbach,65451,65451,2,,8.5300000,50.0600000,Rüsselsheimer Straße,Kelsterbach\n",
"Rüsselheimerstr. 2, 65451 Kelsterbach",
"Rüsselsheimer Straße",
"2",
"65451",
"Kelsterbach",
),
(
"kirchgase,001,obersulm eschenau,74181,74181,16,,9.3700000,49.1300000,Kirchgase,Obersulm-Eschenau\n\
kirchgasse,002,obersulm,74182,74182,16,,9.3800000,49.1400000,Kirchgasse,Obersulm\n",
"Kirchgase 16, 74182 Obersulm-Eschenau",
"Kirchgasse",
"16",
"74182",
"Obersulm",
),
(
"frankfurt strasse,001,muellrose,15298,15298,1,,14.4000000,52.2400000,Frankfurt Straße,Müllrose\n\
frankfurter strasse,002,muellrose,15299,15299,1,,14.4100000,52.2500000,Frankfurter Straße,Müllrose\n",
"Frankfurt Straße 1, 15299 Müllrose",
"Frankfurter Straße",
"1",
"15299",
"Müllrose",
),
(
"oppenhaeuser strasse,001,lachendorf,29330,29330,3,,10.2400000,52.6000000,Oppenhäuser Straße,Lachendorf\n\
oppershaeuser strasse,002,lachendorf,29331,29331,3,,10.2500000,52.6100000,Oppershäuser Straße,Lachendorf\n",
"Oppenhäuser Str. 3, 29331 Lachendorf",
"Oppershäuser Straße",
"3",
"29331",
"Lachendorf",
),
(
"robert schuman strasse,002,gersheim,66453,66453,2,,7.2400000,49.1500000,Robert-Schuman-Straße,Gersheim\n\
robert schumann strasse,001,gersheim reinheim,66452,66452,2,,7.2300000,49.1400000,Robert-Schumann-Straße,Gersheim-Reinheim\n",
"Robert Schumann Str. 2, 66453 Gersheim-Reinheim",
"Robert-Schuman-Straße",
"2",
"66453",
"Gersheim",
),
(
"probsteistrasse,001,viersen,41748,41748,15,,6.3800000,51.2700000,Probsteistraße,Viersen\n\
propsteistrasse,002,viersen,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Viersen\n",
"Probsteistr. 15, 41749 Viersen",
"Propsteistraße",
"15",
"41749",
"Viersen",
),
];
for (position, (rows, query, street, house, postcode, commune)) in
cases.into_iter().enumerate()
{
let idx =
forward_postcode_index_for_country(&format!("wave-b-p3-{position}"), rows, "de");
let top = idx
.query(query, 1)
.into_iter()
.next()
.unwrap_or_else(|| panic!("strict P3 source proof must resolve {query}"));
assert_eq!(top.precision, "house", "{query}");
assert_eq!(top.street, street, "{query}");
assert_eq!(top.housenumber.as_deref(), Some(house), "{query}");
assert_eq!(top.postcode, postcode, "{query}");
assert_eq!(top.commune, commune, "{query}");
assert!(
top.flags.contains(&"de_strict_source_street_typo"),
"the dedicated bounded P3 proof must own {query}: {:?}",
top.flags
);
}
}
#[test]
fn de_wave_b_p3_is_unique_exact_and_never_replaces_a_complete_top() {
let ambiguous = forward_postcode_index_for_country(
"wave-b-p3-ambiguous",
"probsteikstrasse,002,viersen,41749,41749,15,,6.4000000,51.2900000,Probsteikstraße,Viersen\n\
propsteistrasse,001,viersen,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Viersen\n",
"de",
);
assert!(
ambiguous
.query("Probsteistr. 15, 41749 Viersen", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"two qualifying source-street identities must fail closed"
);
let repeated_identity = forward_postcode_index_for_country(
"wave-b-p3-repeated-semantic-identity",
"propsteistrasse,001,viersen,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Viersen\n\
propsteistrasse,002,viersen,41749,41749,15,,6.4000000,51.2900000,Propsteistraße,Viersen\n",
"de",
);
assert!(
repeated_identity
.query("Probsteistr. 15, 41749 Viersen", 1)
.first()
.is_some_and(|hit| hit.flags.contains(&"de_strict_source_street_typo")),
"one semantic display-street identity may span multiple physical SIDs"
);
let already_exact = forward_postcode_index_for_country(
"wave-b-p3-complete-top",
"probsteistrasse,001,viersen,41749,41749,15,,6.3800000,51.2700000,Probsteistraße,Viersen\n\
propsteistrasse,002,viersen,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Viersen\n",
"de",
);
let exact_top = already_exact
.query("Probsteistraße 15, 41749 Viersen", 1)
.into_iter()
.next()
.expect("the ordinary exact address remains available");
assert_eq!(exact_top.street, "Probsteistraße");
assert!(!exact_top.flags.contains(&"de_strict_source_street_typo"));
let wrong_fields = forward_postcode_index_for_country(
"wave-b-p3-exact-fields",
"propsteistrasse,001,otherstadt,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Otherstadt\n\
propsteistrasse,002,viersen,41749,41749,15,a,6.4000000,51.2900000,Propsteistraße,Viersen\n",
"de",
);
assert!(
wrong_fields
.query("Probsteistr. 15, 41749 Viersen", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"locality and suffix are exact P3 product gates"
);
for (case, query_street, source_street) in [
("similarity", "muster", "master"),
(
"osa-three",
"abcdefghijklmnopqrstuvwxyzabcdefghijklstrasse",
"abcedfghijkymnopqrztuvwxyzabcdefghijklstrasse",
),
(
"first-codepoint",
"abcdefghijklmnopqrstuvwxyzabcdefghijklstrasse",
"bbcdefghijklmnopqrstuvwxyzabcdefghijklstrasse",
),
] {
if case == "osa-three" {
assert_eq!(
de_compact_osa_distance(query_street, source_street),
3,
"the negative must exercise the OSA admission guard"
);
assert!(
de_sequence_matcher_ratio_at_least_090(query_street, source_street),
"the independent ratio guard must pass in the OSA-only negative"
);
}
let rows = format!(
"{query_street},001,berlin,10114,10114,1,,13.3800000,52.5000000,{query_street},Berlin\n\
{source_street},002,berlin,10115,10115,1,,13.3900000,52.5100000,{source_street},Berlin\n"
);
let mut sorted = rows.lines().collect::<Vec<_>>();
sorted.sort_unstable();
let rows = format!("{}\n", sorted.join("\n"));
let idx = forward_postcode_index_for_country(&format!("wave-b-p3-{case}"), &rows, "de");
assert!(
idx.query(&format!("{query_street} 1, 10115 Berlin"), 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"P3 must enforce the independent {case} guard"
);
}
let canonical_osa = forward_postcode_index_for_country(
"wave-b-p3-canonical-osa",
"muehlenabcdefghijklstrasse,001,berlin,10114,10114,1,,13.3800000,52.5000000,Mühlenabcdefghijklstraße,Berlin\n\
muhlenabcxefgyijklstrasse,002,berlin,10115,10115,1,,13.3900000,52.5100000,Muhlenabcxefgyijklstraße,Berlin\n",
"de",
);
assert!(
canonical_osa
.query("Mühlenabcdefghijklstr. 1, 10115 Berlin", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"a favorable lookup-only orthography variant may not replace canonical OSA admission"
);
let key_display_mismatch = forward_postcode_index_for_country(
"wave-b-p3-key-display-mismatch",
"probsteistrasse,001,viersen,41748,41748,15,,6.3800000,51.2700000,Probsteistraße,Viersen\n\
propsteistrasse,002,viersen,41749,41749,15,,6.3900000,51.2800000,Unrelated Avenue,Viersen\n",
"de",
);
assert!(
key_display_mismatch
.query("Probsteistr. 15, 41749 Viersen", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"a close FST key may not stand in for the product-normalized display street"
);
let hidden_display_identity = forward_postcode_index_for_country(
"wave-b-p3-hidden-display-identity",
"probsteistrasse,001,viersen,41748,41748,15,,6.3800000,51.2700000,Probsteistraße,Viersen\n\
propsteistrasse,002,viersen,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Viersen\n\
zzzzweg,003,viersen,41749,41749,15,,6.4000000,51.2900000,Probsteikstraße,Viersen\n",
"de",
);
assert_eq!(
hidden_display_identity
.de_postcode_street_bucket(41749)
.expect("exact DE postcode bucket")
.len(),
2,
"the open-time roster must include both the near key and the hidden far key"
);
assert!(
hidden_display_identity
.query("Probsteistr. 15, 41749 Viersen", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"a second qualifying display identity behind an unrelated FST key must fail closed"
);
let previous_limit = DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(|limit| limit.replace(1));
assert!(
hidden_display_identity
.de_postcode_street_bucket(41749)
.is_none(),
"an oversized exact-postcode bucket must fail closed"
);
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(|limit| limit.set(previous_limit));
let hidden_unique_identity = forward_postcode_index_for_country(
"wave-b-p3-hidden-unique-display-identity",
"probsteistrasse,001,viersen,41748,41748,15,,6.3800000,51.2700000,Probsteistraße,Viersen\n\
zzzzweg,003,viersen,41749,41749,15,,6.4000000,51.2900000,Propsteistraße,Viersen\n",
"de",
);
let hidden_unique_top = hidden_unique_identity
.query("Probsteistr. 15, 41749 Viersen", 1)
.into_iter()
.next()
.expect("the bounded postcode roster must find the unique display identity");
assert_eq!(hidden_unique_top.street, "Propsteistraße");
assert!(hidden_unique_top
.flags
.contains(&"de_strict_source_street_typo"));
let mixed_postcodes = forward_postcode_index_for_country(
"wave-b-p3-mixed-postcode-roster",
"propsteistrasse,002,viersen,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Viersen\n\
propsteistrasse,002,viersen,41750,41750,16,,6.3910000,51.2810000,Propsteistraße,Viersen\n",
"de",
);
let mixed_bucket = mixed_postcodes
.de_postcode_street_bucket(41750)
.expect("v7 mixed-postcode dictionary must enter the roster");
assert_eq!(mixed_bucket.len(), 1);
let mixed_sid = mixed_bucket[0].1;
let mixed_metadata = mixed_postcodes.street_meta(mixed_sid);
assert!(
mixed_postcodes.exact_house_full_postcode_set_candidate_cached(
&mut HashMap::new(),
mixed_sid,
&mixed_metadata,
16,
0,
&[],
41750,
"41750",
)
);
assert!(
!mixed_postcodes.exact_house_full_postcode_set_candidate_cached(
&mut HashMap::new(),
mixed_sid,
&mixed_metadata,
15,
0,
&[],
41750,
"41750",
)
);
let locality_normalization = forward_postcode_index_for_country(
"wave-b-p3-locality-normalization",
"probsteistrasse,001,koeln,41748,41748,15,,6.3800000,51.2700000,Probsteistraße,Köln\n\
propsteistrasse,002,koln,41749,41749,15,,6.3900000,51.2800000,Propsteistraße,Koln\n",
"de",
);
assert!(
locality_normalization
.query("Probsteistr. 15, 41749 Köln", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"product normalization must distinguish umlaut digraphs from absent umlauts"
);
let lev4_uniqueness = forward_postcode_index_for_country(
"wave-b-p3-lev4-uniqueness",
"abcdefghijklmnopqrst,001,berlin,10114,10114,1,,13.3700000,52.4900000,abcdefghijklmnopqrst,Berlin\n\
abcdefghijklmnopqrsx,002,berlin,10115,10115,1,,13.3800000,52.5000000,abcdefghijklmnopqrsx,Berlin\n\
abcedfghijklmnoprqst,003,berlin,10115,10115,1,,13.3900000,52.5100000,abcedfghijklmnoprqst,Berlin\n",
"de",
);
assert_eq!(
de_compact_osa_distance("abcdefghijklmnopqrst", "abcedfghijklmnoprqst"),
2
);
assert!(
lev4_uniqueness
.query("abcdefghijklmnopqrst 1, 10115 Berlin", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_strict_source_street_typo")),
"the postcode roster must count both identities independently of FST distance"
);
}
#[test]
fn de_wave_b_p3_parser_osa_similarity_and_locality_are_bounded() {
let spec = de_strict_source_street_typo_spec("Rüsselheimerstr. 2, 65451 Kelsterbach")
.expect("the canonical simple P3 surface must parse");
assert_eq!(spec.normalized_street, "ruesselheimerstrasse");
assert_eq!(spec.normalized_locality, "kelsterbach");
assert_eq!(spec.house_number, 2);
assert_eq!(spec.postcode_raw, "65451");
for raw in [
"Haus 7 Straße 2, 65451 Kelsterbach",
"Teststraße 2a, 65451 Kelsterbach",
"Teststraße 2/3, 65451 Kelsterbach",
"Teststraße 0002, 65451 Kelsterbach",
"Teststraße 2, 6545 Kelsterbach",
"Teststraße 2, 65451 Kelsterbach, Deutschland",
"Teststraße 2, 65451 Kelsterbach\nEmpfang",
"Teststraße 2, 65451 Kelsterbach ",
] {
assert!(
de_strict_source_street_typo_spec(raw).is_none(),
"strict P3 parser must reject {raw:?}"
);
}
assert_eq!(
de_compact_osa_distance("probsteistrasse", "propsteistrasse"),
1
);
assert_eq!(
de_compact_osa_distance("frankfurt strasse", "frankfurter strasse"),
2
);
assert_eq!(de_compact_osa_distance("abcdefgh", "abcxyzgh"), 3);
assert!(de_sequence_matcher_ratio_at_least_090(
"ruesselheimerstrasse",
"ruesselsheimer strasse"
));
assert!(!de_sequence_matcher_ratio_at_least_090("muster", "master"));
assert!(de_sequence_matcher_ratio_at_least_090(
"abcdefghij",
"abcdefghix"
));
for (raw, expected) in [
("Rüsselheimerstr.", "ruesselheimerstrasse"),
("Kirchgase", "kirchgase"),
("Frankfurt Straße", "frankfurt strasse"),
("Oppenhäuser Str.", "oppenhaeuser strasse"),
("Robert Schumann Str.", "robert schumann strasse"),
("Probsteistr.", "probsteistrasse"),
] {
assert_eq!(de_product_normalize_street(raw), expected, "{raw}");
}
assert_eq!(de_product_normalize_text("Müllrose"), "muellrose");
assert!(de_p3_locality_compatible("obersulm eschenau", "obersulm"));
assert!(de_p3_locality_compatible("gersheim", "gersheim reinheim"));
assert!(!de_p3_locality_compatible("obersulm", "obersulmberg"));
}
#[test]
fn de_wave_b_p3_absent_postcode_roster_filters_only_double_conflicts() {
let idx = forward_postcode_index_for_country(
"wave-b-p3-absent-postcode-roster",
"probsteistrasse,001,aldenhoven,52457,52457,15,,6.2800000,50.9000000,Probsteistraße,Aldenhoven\n",
"de",
);
let current = |commune: &str, postcode: &str| {
let (hit, features, ..) = retained_test_hit(
commune,
"Probsteistraße",
Some("15"),
postcode,
"house",
1.0,
[0.0; N_FEATS],
vec!["street_exact", "house_rep"],
100,
0,
);
vec![(hit, features)]
};
let qualifier_cases = [
(
"Probsteistr. 15, 41749 Viersen/Rhein",
41749,
"Viersen am Rhein",
"slash",
),
(
"Probsteistr. 15, 79104 Freiburg (Breisgau)",
79104,
"Freiburg im Breisgau",
"parenthesis",
),
(
"Probsteistr. 15, 18609 Binz - OT Prora",
18609,
"Prora",
"OT",
),
(
"Probsteistr. 15, 74239 Hardthausen-Kochersteinsfeld",
74239,
"Kochersteinsfeld",
"hyphen",
),
];
for (query, postcode, commune, shape) in qualifier_cases {
assert!(
idx.de_postcode_street_bucket(postcode).is_none(),
"the {shape} observer must exercise the absent exact-postcode roster branch"
);
assert!(
idx.de_strict_source_street_typo_fallback(query, ¤t(commune, ""), 1)
.is_none(),
"a missing row postcode is unknown and must preserve the {shape} locality qualifier"
);
let filtered = idx
.de_strict_source_street_typo_fallback(query, ¤t(commune, "99999"), 1)
.expect("a non-empty conflicting postcode must still fail closed");
assert!(
filtered.is_empty(),
"the reverse-mutation observer must reject the {shape} qualifier when the row postcode contradicts the request"
);
}
let query = "Probsteistr. 15, 41749 Viersen";
assert!(
idx.de_strict_source_street_typo_fallback(query, ¤t("Viersen", ""), 1)
.is_none(),
"a same-locality result with absent postcode remains eligible"
);
assert!(
idx.de_strict_source_street_typo_fallback(query, ¤t("Aldenhoven", "41749"), 1,)
.is_none(),
"an exact-postcode result is not removed solely for locality disagreement"
);
}
#[test]
fn de_wave_b_p4_audited_compounds_cover_all_four_shapes() {
let idx = forward_postcode_index_for_country(
"wave-b-p4-five-surfaces",
"albertstrasse,002,freiburg im breisgau,79104,79104,25,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n\
campus ring,003,bremen,28759,28759,1,,8.6500000,53.1700000,Campus Ring,Bremen\n\
grosse meissner strasse,001,dresden,01097,01097,19,,13.7400000,51.0600000,Große Meißner Straße,Dresden\n\
marktplatz,005,weilheim an der teck,73235,73235,4,,9.5400000,48.6200000,Marktplatz,Weilheim an der Teck\n\
rheinstrasse,004,berlin,12161,12161,45,,13.3300000,52.4700000,Rheinstraße,Berlin\n\
rheinstrasse,004,berlin,12161,12161,46,,13.3310000,52.4710000,Rheinstraße,Berlin\n",
"de",
);
let cases = [
(
"Blockhaus, 19, Große Meißner Straße, Innere Neustadt, Neustadt, Dresden, Sachsen, 01097",
"Große Meißner Straße",
"19",
"01097",
"Dresden",
"grosse meissner strasse",
"dresden",
false,
),
(
"Albertstr. 25 ( Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
"Albertstraße",
"25",
"79104",
"Freiburg im Breisgau",
"albertstrasse",
"freiburg im breisgau",
false,
),
(
"c/o Jacobs University Bremen Campusring 1 Bremen, 28759 Bremen",
"Campus Ring",
"1",
"28759",
"Bremen",
"campus ring",
"bremen",
false,
),
(
"Rheinstr. 45/46 (Aufgang 6), 12161 Berlin",
"Rheinstraße",
"45",
"12161",
"Berlin",
"rheinstrasse",
"berlin",
true,
),
(
"Marktplatz 4 (Weilheimer \"Bürgerhaus\"), 73235 Weilheim/Teck",
"Marktplatz",
"4",
"73235",
"Weilheim an der Teck",
"marktplatz",
"weilheim an der teck",
false,
),
];
for (
query,
street,
house,
postcode,
commune,
normalized_street,
normalized_locality,
complete_set,
) in cases
{
let spec = de_audited_compound_spec(query).expect("P4 product fields must parse");
assert_eq!(spec.normalized_street, normalized_street, "{query}");
assert_eq!(spec.normalized_locality, normalized_locality, "{query}");
let top = idx
.query(query, 1)
.into_iter()
.next()
.unwrap_or_else(|| panic!("strict P4 source proof must resolve {query}"));
assert_eq!(top.precision, "house", "{query}");
assert_eq!(top.street, street, "{query}");
assert_eq!(top.housenumber.as_deref(), Some(house), "{query}");
assert_eq!(top.postcode, postcode, "{query}");
assert_eq!(top.commune, commune, "{query}");
assert!(
top.flags.contains(&"de_audited_compound"),
"the dedicated typed P4 proof must own {query}: {:?}",
top.flags
);
assert_eq!(
top.flags.contains(&"de_house_set_exact"),
complete_set,
"{query}"
);
}
}
#[test]
fn de_wave_b_p4_requires_complete_set_exact_locality_and_de_scope() {
let missing_endpoint = forward_postcode_index_for_country(
"wave-b-p4-missing-endpoint",
"rheinstrasse,004,berlin,12161,12161,45,,13.3300000,52.4700000,Rheinstraße,Berlin\n",
"de",
);
let mut rhein_key = b"rheinstrasse".to_vec();
rhein_key.push(KEY_SEP);
rhein_key.extend_from_slice(b"004");
let rhein_sid = missing_endpoint
.streets_fst
.get(&rhein_key)
.expect("fixture street") as u32;
let rhein_meta = missing_endpoint.street_meta(rhein_sid);
assert!(
!missing_endpoint.exact_house_postcode_set_candidate_cached(
&mut HashMap::new(),
rhein_sid,
&rhein_meta,
45,
0,
&[46],
12161,
),
"the low-level source proof must reject the missing right endpoint"
);
let mut direct_budget = DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT;
let mut direct_seen = HashSet::new();
let direct = missing_endpoint
.query_feats_prepared_postcode_house_rescue(
&prepared_query_key("rheinstrasse 45, 12161 berlin"),
20,
None,
&[46],
&mut direct_budget,
&mut direct_seen,
)
.expect("bounded direct scan must not overflow");
assert!(
direct.is_empty(),
"the prepared exact scan must preserve the complete endpoint set"
);
let missing_hits = missing_endpoint.query("Rheinstr. 45/46 (Aufgang 6), 12161 Berlin", 5);
assert!(
missing_hits
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"a range without endpoint 46 must fail closed"
);
let freiburg = forward_postcode_index_for_country(
"wave-b-p4-locality",
"albertstrasse,002,freiburg im breisgau,79104,79104,25,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n",
"de",
);
assert!(
freiburg
.query("Albertstr. 25 (Haus), 79104 Freiburg/Oder", 5)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"the bounded slash-locality alias must preserve its qualifier"
);
let invented_preposition = forward_postcode_index_for_country(
"wave-b-p4-no-invented-preposition",
"albertstrasse,002,freiburg an der breisgau,79104,79104,25,,7.8500000,48.0100000,Albertstraße,Freiburg an der Breisgau\n",
"de",
);
assert!(
invented_preposition
.query(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"slash locality must project one product locality, never both prepositions"
);
let venue_admin_decoy = forward_postcode_index_for_country(
"wave-b-p4-venue-admin-decoy",
"grosse meissner strasse,001,sachsen,01097,01097,19,,13.7400000,51.0600000,Große Meißner Straße,Sachsen\n",
"de",
);
assert!(
venue_admin_decoy
.query(
"Blockhaus, 19, Große Meißner Straße, Innere Neustadt, Neustadt, Dresden, Sachsen, 01097",
5,
)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"venue administrative qualifiers are not alternative query localities"
);
let display_mismatch = forward_postcode_index_for_country(
"wave-b-p4-display-mismatch",
"albertstrasse,002,freiburg im breisgau,79104,79104,25,,7.8500000,48.0100000,Alberta Straße,Freiburg im Breisgau\n",
"de",
);
assert!(
display_mismatch
.query(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"an exact retrieval key cannot replace normalized display-street equality"
);
let arbitrary_care_of_split = forward_postcode_index_for_country(
"wave-b-p4-care-of-split",
"campusri ng,003,bremen,28759,28759,1,,8.6500000,53.1700000,Campusri Ng,Bremen\n",
"de",
);
assert!(
arbitrary_care_of_split
.query(
"c/o Jacobs University Bremen Campusring 1 Bremen, 28759 Bremen",
5,
)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"c/o parsing may split only a terminal street-type word"
);
let non_de = forward_postcode_index_for_country(
"wave-b-p4-country-boundary",
"marktplatz,005,weilheim an der teck,73235,73235,4,,9.5400000,48.6200000,Marktplatz,Weilheim an der Teck\n",
"fr",
);
assert!(
non_de
.query(
"Marktplatz 4 (Weilheimer \"Bürgerhaus\"), 73235 Weilheim/Teck",
5,
)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"the audited compound fallback is DE-only"
);
let duplicate = forward_postcode_index_for_country(
"wave-b-p4-duplicate",
"albertstrasse,001,freiburg im breisgau,79104,79104,25,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n\
albertstrasse,002,freiburg im breisgau,79104,79104,25,,7.8600000,48.0200000,Albertstraße,Freiburg im Breisgau\n",
"de",
);
assert!(
duplicate
.query(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"two exact source candidates must fail closed"
);
assert!(
duplicate
.de_audited_compound_fallback(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.is_none(),
"the dedicated P4 admission path itself must reject duplicate source rows"
);
let wrong_endpoint_postcode = forward_postcode_index_for_country(
"wave-b-p4-endpoint-display-postcode",
"rheinstrasse,004,berlin,12161,12161,45,,13.3300000,52.4700000,Rheinstraße,Berlin\n\
rheinstrasse,004,berlin,12161,12161A,46,,13.3310000,52.4710000,Rheinstraße,Berlin\n",
"de",
);
assert!(
wrong_endpoint_postcode
.de_audited_compound_fallback("Rheinstr. 45/46 (Aufgang 6), 12161 Berlin", 5,)
.is_none(),
"every literal range endpoint must carry the full requested display postcode"
);
let wrong_primary_postcode = forward_postcode_index_for_country(
"wave-b-p4-primary-display-postcode",
"albertstrasse,002,freiburg im breisgau,79104,79104A,25,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n",
"de",
);
assert!(
wrong_primary_postcode
.de_audited_compound_fallback(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.is_none(),
"the primary house must carry the full requested display postcode"
);
let wrong_primary_house = forward_postcode_index_for_country(
"wave-b-p4-primary-house",
"albertstrasse,002,freiburg im breisgau,79104,79104,26,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n",
"de",
);
assert!(
wrong_primary_house
.de_audited_compound_fallback(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.is_none(),
"P4 must prove the exact primary house rather than a near/interpolated result"
);
let duplicate_same_coordinates = forward_postcode_index_for_country(
"wave-b-p4-duplicate-same-coordinates",
"albertstrasse,001,freiburg im breisgau,79104,79104,25,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n\
albertstrasse,002,freiburg im breisgau,79104,79104,25,,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n",
"de",
);
assert_eq!(
duplicate_same_coordinates
.query(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.iter()
.any(|hit| hit.flags.contains(&"de_audited_compound")),
duplicate
.query(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.iter()
.any(|hit| hit.flags.contains(&"de_audited_compound")),
"P4 admission must be invariant to equal versus different result coordinates"
);
let suffix_only = forward_postcode_index_for_country(
"wave-b-p4-suffix",
"albertstrasse,001,freiburg im breisgau,79104,79104,25,a,7.8500000,48.0100000,Albertstraße,Freiburg im Breisgau\n",
"de",
);
assert!(
suffix_only
.query(
"Albertstr. 25 (Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
5,
)
.iter()
.all(|hit| !hit.flags.contains(&"de_audited_compound")),
"a bare P4 house may not fall forward to a suffixed source house"
);
}
#[test]
fn de_wave_b_p4_commune_and_attempt_budgets_have_boundary_observers() {
let campus_query = "Campus Ring 1 (Haus), 28759 Bremen";
for (communes, admitted) in [(16usize, true), (17usize, false)] {
let idx = forward_postcode_index_for_country(
&format!("wave-b-p4-commune-budget-{communes}"),
&de_wave_b_homonymous_p4_rows(communes, "campus ring", "Campus Ring"),
"de",
);
let _rules = crate::rules::scope(idx.rules);
let spec = de_audited_compound_spec(campus_query).expect("typed P4 query");
let forms = de_product_street_forms(&spec.street);
assert_eq!(forms.len(), 1, "the commune boundary must be isolated");
assert_eq!(
idx.communes_by_name(&spec.normalized_locality).len(),
communes
);
assert_eq!(
idx.de_audited_compound_fallback(campus_query, 1).is_some(),
admitted,
"the 16/17 commune boundary must be observable"
);
}
let attempts_query = "Aastr Bbstr 1 (Haus), 28759 Bremen";
let attempts_spec =
de_audited_compound_spec(attempts_query).expect("typed P4 attempt-budget query");
for (communes, expected_attempts, admitted) in
[(9usize, 63usize, true), (10usize, 70usize, false)]
{
let idx = forward_postcode_index_for_country_with_rules(
&format!("wave-b-p4-attempt-budget-{communes}"),
&de_wave_b_homonymous_p4_rows(
communes,
&attempts_spec.normalized_street,
"Aastr Bbstr",
),
"de",
);
let _rules = crate::rules::scope(idx.rules);
let forms = de_product_street_forms(&attempts_spec.street);
assert_eq!(forms.len() * communes, expected_attempts);
assert!(forms.len() <= 32 && communes <= 16);
assert_eq!(
idx.de_audited_compound_fallback(attempts_query, 1)
.is_some(),
admitted,
"the 64-attempt boundary must be observable independently"
);
}
}
#[test]
fn de_wave_b_p4_street_form_budget_has_a_boundary_observer() {
let cases = [
(
"Aastr Bbstr Ccstr Ddstr Eestr Ffstr Ggstr Hhstr Iistr Jjstr",
31usize,
true,
),
(
"Aastr Bbstr Ccstr Ddstr Eestr Ffstr Ggstr Hhstr Iistr Jjstr Kkstr",
34usize,
false,
),
];
for (street, expected_forms, admitted) in cases {
let query = format!("{street} 1 (Haus), 28759 Bremen");
let spec = de_audited_compound_spec(&query).expect("typed P4 form-budget query");
let rows = format!(
"{},001,bremen,28759,28759,1,,8.6500000,53.1700000,{street},Bremen\n",
spec.normalized_street
);
let idx = forward_postcode_index_for_country_with_rules(
&format!("wave-b-p4-street-form-budget-{expected_forms}"),
&rows,
"de",
);
let _rules = crate::rules::scope(idx.rules);
let forms = de_product_street_forms(&spec.street);
assert_eq!(forms.len(), expected_forms);
assert_eq!(idx.communes_by_name(&spec.normalized_locality).len(), 1);
assert_eq!(
idx.de_audited_compound_fallback(&query, 1).is_some(),
admitted,
"the 32-form boundary must be observable"
);
}
}
#[test]
fn de_wave_p_p4_recall_does_not_depend_on_a_street_fst_projection() {
let mut idx = forward_postcode_index_for_country(
"wave-p-p4-fst-projection-independent",
"campus ring,002,bremen,28759,28759,1,,8.6500000,53.1700000,Campus Ring,Bremen\n\
zzdummy,001,bremen,28759,28759,1,,8.6600000,53.1800000,ZZ Dummy,Bremen\n",
"de",
);
let rules = idx.rules;
let _rules = crate::rules::scope(rules);
let query = "Campus Ring 1 (Haus), 28759 Bremen";
assert!(
idx.de_audited_compound_fallback(query, 1).is_some(),
"the clean fixture must prove that all non-corrupt product gates pass"
);
let mut source_key = b"campus ring".to_vec();
source_key.push(KEY_SEP);
source_key.extend_from_slice(b"002");
let sid = idx
.streets_fst
.get(&source_key)
.expect("clean source street") as u32;
let source_metadata = idx.street_meta(sid);
let mut mismatched_key = b"campus ring".to_vec();
mismatched_key.push(KEY_SEP);
mismatched_key.extend_from_slice(b"001");
let mut builder = fst::MapBuilder::memory();
builder.insert(&mismatched_key, sid as u64).unwrap();
let bytes: &'static [u8] = Box::leak(builder.into_inner().unwrap().into_boxed_slice());
idx.streets_fst = Map::new(bytes).unwrap();
let lookup_commune_id = idx
.communes_by_name("bremen")
.into_iter()
.find(|&commune_id| idx.commune_insee(commune_id) == "001")
.expect("mismatched lookup commune");
assert_ne!(source_metadata.commune_id, lookup_commune_id);
let recovered = idx
.de_audited_compound_fallback(query, 1)
.expect("exact display metadata must remain reachable without the FST projection");
assert_eq!(recovered.len(), 1);
assert_eq!(recovered[0].0.street, "Campus Ring");
assert_eq!(recovered[0].0.commune, "Bremen");
assert_eq!(recovered[0].0.housenumber.as_deref(), Some("1"));
assert_eq!(recovered[0].0.postcode, "28759");
assert!(recovered[0].0.flags.contains(&"de_audited_compound"));
}
#[test]
fn de_wave_p_p4_recovers_three_non_ascii_source_key_archetypes() {
let cases = [
(
"venue",
"Speicher, 19, Große Hafenstraße, Altquartier, Neustadt, Elbstadt, Sachsen, 01097",
"große hafenstraße,001,elbstadt,01097,01097,19,,11.1000000,51.1000000,Große Hafenstraße,Elbstadt\n",
"Große Hafenstraße",
"19",
"01097",
"Elbstadt",
false,
),
(
"parenthetical",
"Gartenstr. 25 (Haus A), 79104 Bergheim/Breisgau",
"gartenstraße,002,bergheim im breisgau,79104,79104,25,,11.2000000,51.2000000,Gartenstraße,Bergheim im Breisgau\n",
"Gartenstraße",
"25",
"79104",
"Bergheim im Breisgau",
false,
),
(
"range",
"Uferstr. 45/46 (Aufgang 6), 12161 Neustadt",
"uferstraße,003,neustadt,12161,12161,45,,11.3000000,51.3000000,Uferstraße,Neustadt\n\
uferstraße,003,neustadt,12161,12161,46,,11.3010000,51.3010000,Uferstraße,Neustadt\n",
"Uferstraße",
"45",
"12161",
"Neustadt",
true,
),
];
for (case, query, rows, street, house, postcode, locality, complete_set) in cases {
let idx = forward_postcode_index_for_country(&format!("wave-p-p4-{case}"), rows, "de");
let spec = de_audited_compound_spec(query).expect("the audited P4 shape must parse");
let commune_id = idx
.communes_by_name(&spec.normalized_locality)
.into_iter()
.next()
.expect("fixture locality");
let mut old_lookup_key = spec.normalized_street.as_bytes().to_vec();
old_lookup_key.push(KEY_SEP);
old_lookup_key.extend_from_slice(idx.commune_insee(commune_id).as_bytes());
assert!(
idx.streets_fst.get(&old_lookup_key).is_none(),
"{case} must be invisible to the former normalized-key lookup"
);
DE_P4_POSTCODE_BUCKET_SCAN_ROWS.with(|rows| rows.set(0));
let direct = idx
.de_audited_compound_fallback(query, 1)
.unwrap_or_else(|| panic!("bounded display-metadata recall must resolve {case}"));
assert_eq!(direct.len(), 1, "{case}");
assert!(
DE_P4_POSTCODE_BUCKET_SCAN_ROWS.with(|rows| rows.get()) > 0,
"{case} must traverse the runtime postcode bucket"
);
let top = idx
.query(query, 1)
.into_iter()
.next()
.unwrap_or_else(|| panic!("runtime arbitration must retain {case}"));
assert_eq!(top.precision, "house", "{case}");
assert_eq!(top.street, street, "{case}");
assert_eq!(top.housenumber.as_deref(), Some(house), "{case}");
assert_eq!(top.postcode, postcode, "{case}");
assert_eq!(top.commune, locality, "{case}");
assert!(top.flags.contains(&"de_audited_compound"), "{case}");
assert_eq!(
top.flags.contains(&"de_house_set_exact"),
complete_set,
"{case}"
);
}
}
#[test]
fn de_wave_p_p4_hidden_duplicate_sid_ambiguity_and_bucket_overflow_fail_closed() {
let query = "Gartenstr. 25 (Haus A), 79104 Bergheim/Breisgau";
let hidden_duplicate = forward_postcode_index_for_country(
"wave-p-p4-hidden-duplicate",
"gartenstrasse,001,bergheim im breisgau,79104,79104,25,,11.2000000,51.2000000,Gartenstraße,Bergheim im Breisgau\n\
gartenstraße,002,bergheim im breisgau,79104,79104,25,,11.9000000,51.9000000,Gartenstrasse,Bergheim im Breisgau\n",
"de",
);
assert_eq!(
hidden_duplicate
.de_postcode_street_bucket(79104)
.expect("two-SID postcode bucket")
.len(),
2
);
assert!(
hidden_duplicate
.de_audited_compound_fallback(query, 1)
.is_none(),
"two source SIDs with one product projection must fail closed"
);
let mut duplicate_posting = forward_postcode_index_for_country(
"wave-p-p4-duplicate-posting",
"gartenstraße,001,bergheim im breisgau,79104,79104,25,,11.2000000,51.2000000,Gartenstraße,Bergheim im Breisgau\n",
"de",
);
let posting = duplicate_posting.de_postcode_streets[0];
duplicate_posting.de_postcode_streets = vec![posting, posting].into_boxed_slice();
assert!(
duplicate_posting
.de_audited_compound_fallback(query, 1)
.is_some(),
"duplicate postings for one source SID must collapse before uniqueness"
);
let overflow = forward_postcode_index_for_country(
"wave-p-p4-postcode-overflow",
"gartenstrasse,001,bergheim im breisgau,79104,79104,25,,11.2000000,51.2000000,Gartenstraße,Bergheim im Breisgau\n\
nebenweg,002,anderstadt,79104,79104,9,,11.3000000,51.3000000,Nebenweg,Anderstadt\n",
"de",
);
let previous_limit = DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(|limit| limit.replace(1));
let result = overflow.de_audited_compound_fallback(query, 1);
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(|limit| limit.set(previous_limit));
assert!(
result.is_none(),
"an exact-postcode bucket above the shared audited ceiling must fail closed"
);
}
#[test]
fn de_wave_p_p4_incompatible_candidate_locality_is_vetoed_after_bucket_recall() {
let idx = forward_postcode_index_for_country(
"wave-p-p4-candidate-locality-veto",
"gartenstraße,001,anderstadt,79104,79104,25,,11.2000000,51.2000000,Gartenstraße,Anderstadt\n\
nebenweg,002,bergheim im breisgau,79104,79104,9,,11.3000000,51.3000000,Nebenweg,Bergheim im Breisgau\n",
"de",
);
let query = "Gartenstr. 25 (Haus A), 79104 Bergheim/Breisgau";
assert_eq!(
idx.communes_by_name("bergheim im breisgau").len(),
1,
"an exact query-locality anchor must make the post-recall veto observable"
);
DE_P4_POSTCODE_BUCKET_MATCHING_SIDS.with(|matches| matches.set(0));
assert!(
idx.de_audited_compound_fallback(query, 1).is_none(),
"an exact street/house/PLZ in another locality must fail closed"
);
assert_eq!(
DE_P4_POSTCODE_BUCKET_MATCHING_SIDS.with(|matches| matches.get()),
0,
"the incompatible SID must be vetoed during product-visible admission"
);
}
#[test]
fn de_wave_p_p4_row_order_and_non_product_metadata_do_not_select_a_candidate() {
let query = "Gartenstr. 25 (Haus A), 79104 Bergheim/Breisgau";
let rows = [
"gartenstraße,001,bergheim im breisgau,79104,79104,25,,11.2000000,51.2000000,Gartenstraße,Bergheim im Breisgau\n\
nebenweg,002,anderstadt,79104,79104,9,,11.3000000,51.3000000,Nebenweg,Anderstadt\n",
"gartenstraße,001,bergheim im breisgau,79104,79104,25,,18.8000000,58.8000000,Gartenstraße,Bergheim im Breisgau\n\
nebenweg,002,anderstadt,79104,79104,9,,19.9000000,59.9000000,Nebenweg,Anderstadt\n",
];
let mut projections = Vec::new();
for (variant, rows) in rows.into_iter().enumerate() {
let mut idx = forward_postcode_index_for_country(
&format!("wave-p-p4-order-{variant}"),
rows,
"de",
);
if variant == 1 {
idx.de_postcode_streets.reverse();
}
let hit = idx
.de_audited_compound_fallback(query, 1)
.expect("the unique product candidate must survive source order")
.remove(0)
.0;
projections.push((
hit.precision,
hit.street,
hit.housenumber,
hit.postcode,
hit.commune,
hit.flags,
));
}
assert_eq!(projections[0], projections[1]);
}
#[test]
fn de_wave_p_p4_overlap_preserves_the_established_answer() {
let idx = forward_postcode_index_for_country(
"wave-p-p4-overlap",
"gartenstraße,001,bergheim im breisgau,79104,79104,25,,11.2000000,51.2000000,Gartenstraße,Bergheim im Breisgau\n",
"de",
);
let p4 = idx
.de_audited_compound_fallback("Gartenstr. 25 (Haus A), 79104 Bergheim/Breisgau", 1)
.expect("P4 witness");
let (established_hit, established_features, ..) = retained_test_hit(
"Bergheim im Breisgau",
"Gartenstraße",
Some("24"),
"79104",
"near",
1.0,
[0.0; N_FEATS],
vec!["street_exact", "commune_exact", "pc_exact"],
24,
0,
);
let mut established = vec![(established_hit, established_features)];
let competing = idx
.de_audited_compound_fallback("Gartenstr. 25 (Haus A), 79104 Bergheim/Breisgau", 1)
.expect("second mechanism witness");
Index::de_product_fallback_arbitration(
&mut established,
None,
Some(p4),
None,
Some(competing),
);
assert_eq!(established.len(), 1);
assert_eq!(established[0].0.precision, "near");
assert_eq!(established[0].0.street, "Gartenstraße");
assert_eq!(established[0].0.housenumber.as_deref(), Some("24"));
assert_eq!(established[0].0.postcode, "79104");
assert!(!established[0].0.flags.contains(&"de_audited_compound"));
}
#[test]
fn de_wave_p_p4_runtime_path_and_forbidden_source_audit_are_nonvacuous() {
fn segment<'a>(source: &'a str, start_marker: &str, end_marker: &str) -> &'a str {
let start = source.find(start_marker).expect("P4 source start marker");
let end = source[start..]
.find(end_marker)
.map(|offset| start + offset)
.expect("P4 source end marker");
&source[start..end]
}
let source = include_str!("query.rs");
let p4_source = segment(
source,
"fn de_audited_compound_fallback",
"fn de_comma_postcode_house_rescue",
);
for forbidden in [
"streets_fst.get",
".lat",
".lon",
"dist_km(",
".distance_m",
".score",
".confidence",
"take(1)",
"candidate_sids.first",
"candidate_sids[0]",
"roster_id",
"ordinal",
"physical_id",
"truth_coordinate",
"result_coordinate",
"benchmark",
"outcome",
"competitor",
"distance_threshold",
"de_sequence_matcher",
] {
assert!(
!p4_source.contains(forbidden),
"P4 admission must not read forbidden selector {forbidden}"
);
}
for required in [
"de_postcode_street_bucket(spec.postcode)?",
"de_product_normalize_text(self.commune_name(metadata.commune_id))",
"de_product_normalize_street(self.name(metadata.name_off))",
"exact_house_full_postcode_set_candidate_cached",
"DE_P4_POSTCODE_BUCKET_SCAN_ROWS.with",
"DE_P4_POSTCODE_BUCKET_MATCHING_SIDS.with",
"candidate_sids.sort_unstable()",
"candidate_sids.dedup()",
"let [sid] = candidate_sids.as_slice()",
] {
assert!(
p4_source.contains(required),
"P4 source audit must observe guard {required}"
);
}
}
#[test]
fn de_wave_x_x1_promotes_only_the_unique_official_commune_alias_house() {
let idx = forward_postcode_index_for_country(
"wave-x-x1-official-alias",
"rathausplatz,001,ludwigshafen rhein,67061,67061,20,,8.4000000,49.4800000,Rathausplatz,Ludwigshafen Rhein\n\
rathausplatz,002,ludwigshafen am rhein,67059,67059,20,,8.4400000,49.4900000,Rathausplatz,Ludwigshafen am Rhein\n\
rathausplatz,003,ludwigshafen am rhein,67058,67058,21,,8.4500000,49.5000000,Rathausplatz,Ludwigshafen am Rhein\n",
"de",
);
let top = idx
.query("Rathausplatz 20, 67061 Ludwigshafen/Rhein", 1)
.into_iter()
.next()
.expect("the bounded official alias must retain one exact house");
assert_eq!(top.commune, "Ludwigshafen am Rhein");
assert_eq!(top.street, "Rathausplatz");
assert_eq!(top.housenumber.as_deref(), Some("20"));
assert_eq!(top.postcode, "67059");
assert!(top.flags.contains(&"street_exact"));
assert!(top.flags.contains(&"house_rep"));
assert!(top.flags.contains(&"pc_dept"));
assert!(top.flags.contains(&"de_official_commune_alias"));
let expanded = idx.query("Rathausplatz 20, 67061 Ludwigshafen/Rhein", 5);
assert_eq!(
expanded.first().map(|hit| hit.postcode.as_str()),
Some("67059")
);
assert!(
expanded
.iter()
.skip(1)
.any(|hit| hit.housenumber.as_deref() == Some("21")),
"promotion must preserve legitimate lower hard-commune alternatives"
);
let duplicate = forward_postcode_index_for_country(
"wave-x-x1-official-alias-duplicate",
"rathausplatz,001,ludwigshafen rhein,67061,67061,20,,8.4000000,49.4800000,Rathausplatz,Ludwigshafen Rhein\n\
rathausplatz,002,ludwigshafen am rhein,67059,67059,20,,8.4400000,49.4900000,Rathausplatz,Ludwigshafen am Rhein\n\
rathausplatz,003,ludwigshafen am rhein,67058,67058,20,,8.4500000,49.5000000,Rathausplatz,Ludwigshafen am Rhein\n",
"de",
);
let duplicate_top = duplicate
.query("Rathausplatz 20, 67061 Ludwigshafen/Rhein", 1)
.into_iter()
.next()
.expect("the established exact-postcode result remains available");
assert_eq!(duplicate_top.postcode, "67061");
assert!(!duplicate_top.flags.contains(&"de_official_commune_alias"));
}
#[test]
fn de_wave_regression_official_alias_treats_only_an_empty_postcode_as_unknown() {
let candidate = |postcode: &str, pc_dept: bool| {
let (hit, features, ..) = retained_test_hit(
"Ludwigshafen am Rhein",
"Rathausplatz",
Some("20"),
postcode,
"house",
1.0,
Feats {
street_exact: true,
pc_dept,
house_exact_rep: true,
..Default::default()
}
.to_vec(),
vec!["street_exact", "house_rep"],
100,
0,
);
vec![(hit, features)]
};
let query = "Rathausplatz 20, 67061 Ludwigshafen/Rhein";
assert_eq!(
Index::de_ludwigshafen_official_alias_candidate_position(query, &candidate("", false)),
Some(0),
"an empty row postcode is missing evidence, not contradictory evidence"
);
assert_eq!(
Index::de_ludwigshafen_official_alias_candidate_position(
query,
&candidate("67059", true)
),
Some(0),
"the existing same-department witness remains admissible"
);
assert!(
Index::de_ludwigshafen_official_alias_candidate_position(
query,
&candidate("99999", false)
)
.is_none(),
"a non-empty conflicting postcode must remain fail-closed"
);
}
#[test]
fn de_wave_x_x2_promotes_only_one_exact_street_locality_qualifier() {
let idx = forward_postcode_index_for_country(
"wave-x-x2-street-locality-qualifier",
"markt,001,quedlinburg,06485,06485,1,,11.1000000,51.7900000,Markt,Quedlinburg\n\
markt quedlinburg,002,quedlinburg welterbestadt,,,1,,11.1400000,51.8000000,Markt (Quedlinburg),\"Quedlinburg, Welterbestadt\"\n",
"de",
);
let top = idx
.query("Markt 1, 06484 Quedlinburg", 1)
.into_iter()
.next()
.expect("the unique qualified source street must be reachable");
assert_eq!(top.street, "Markt (Quedlinburg)");
assert_eq!(top.commune, "Quedlinburg, Welterbestadt");
assert_eq!(top.housenumber.as_deref(), Some("1"));
assert_eq!(top.postcode, "");
assert!(top.flags.contains(&"street_exact"));
assert!(top.flags.contains(&"house_rep"));
assert!(top.flags.contains(&"de_street_locality_qualifier"));
let duplicate = forward_postcode_index_for_country(
"wave-x-x2-street-locality-qualifier-duplicate",
"markt,001,quedlinburg,06485,06485,1,,11.1000000,51.7900000,Markt,Quedlinburg\n\
markt quedlinburg,002,quedlinburg welterbestadt,,,1,,11.1400000,51.8000000,Markt (Quedlinburg),\"Quedlinburg, Welterbestadt\"\n\
markt quedlinburg,003,quedlinburg welterbestadt nord,,,1,,11.1500000,51.8100000,Markt (Quedlinburg),\"Quedlinburg, Welterbestadt Nord\"\n",
"de",
);
let duplicate_top = duplicate
.query("Markt 1, 06484 Quedlinburg", 1)
.into_iter()
.next()
.expect("the established department-level result remains available");
assert_eq!(duplicate_top.street, "Markt");
assert_eq!(duplicate_top.postcode, "06485");
assert!(!duplicate_top
.flags
.contains(&"de_street_locality_qualifier"));
}
#[test]
fn de_wave_x_x1_rejects_an_index_key_display_street_mismatch() {
let idx = forward_postcode_index_for_country(
"wave-x-x1-display-mismatch",
"rathausplatz,001,ludwigshafen rhein,67061,67061,20,,8.4000000,49.4800000,Rathausplatz,Ludwigshafen Rhein\n\
rathausplatz,002,ludwigshafen am rhein,67059,67059,20,,8.4400000,49.4900000,Bürgerplatz,Ludwigshafen am Rhein\n",
"de",
);
let top = idx
.query("Rathausplatz 20, 67061 Ludwigshafen/Rhein", 1)
.into_iter()
.next()
.expect("the established exact-postcode result remains available");
assert_eq!(top.street, "Rathausplatz");
assert_eq!(top.postcode, "67061");
assert!(!top.flags.contains(&"de_official_commune_alias"));
}
#[test]
fn de_wave_x_x2_parsers_accept_only_the_typed_product_surfaces() {
let spec = de_street_locality_qualifier_spec("Markt 12A, 06484 Quedlinburg")
.expect("a one-letter exact house suffix is part of the typed surface");
assert_eq!(spec.normalized_street, "markt");
assert_eq!(spec.normalized_locality, "quedlinburg");
assert_eq!(spec.house_token, "12a");
assert_eq!(spec.postcode_raw, "06484");
for raw in [
"Markt 1-3, 06484 Quedlinburg",
"Markt 1/3, 06484 Quedlinburg",
"Markt 01, 06484 Quedlinburg",
"Markt 1, Quedlinburg",
"Markt 1, 06484 Quedlinburg, Sachsen-Anhalt",
"Quedlinburg, Markt 1, 06484",
] {
assert!(
de_street_locality_qualifier_spec(raw).is_none(),
"{raw} must stay outside the X2 parser"
);
}
assert_eq!(
de_source_street_locality_qualifier("Markt (Quedlinburg)"),
Some(("markt".to_string(), "quedlinburg".to_string()))
);
for display in [
"Markt",
"Markt ()",
"Markt ((Quedlinburg))",
"Markt (Quedlinburg) Zufahrt",
"Markt (Quedlinburg) ",
] {
assert!(
de_source_street_locality_qualifier(display).is_none(),
"{display} must not become a source qualifier"
);
}
}
#[test]
fn de_wave_x_x2_product_predicate_rejects_an_exact_postcode_top_and_suffix_mismatch() {
let make_hit = |street: &str, commune: &str, postcode: &str, house: &str| Hit {
lat: 0.0,
lon: 0.0,
precision: "house",
score: 0.0,
confidence: 0.0,
street: street.to_string(),
housenumber: Some(house.to_string()),
commune: commune.to_string(),
postcode: postcode.to_string(),
flags: Vec::new(),
region: None,
distance_m: None,
};
let top_features = Feats {
street_exact: true,
pc_exact: true,
pc_dept: true,
house_exact_rep: true,
..Default::default()
}
.to_vec();
let candidate_features = Feats {
street_exact: true,
house_exact_rep: true,
..Default::default()
}
.to_vec();
let mut current = vec![
(make_hit("Markt", "Quedlinburg", "06484", "1"), top_features),
(
make_hit("Markt (Quedlinburg)", "Quedlinburg, Welterbestadt", "", "1"),
candidate_features,
),
];
assert!(
Index::de_street_locality_qualifier_position("Markt 1, 06484 Quedlinburg", ¤t,)
.is_none(),
"an exact-postcode top is already final"
);
current[0].1[4] = 0.0;
current[0].0.postcode = "06485".to_string();
current[1].0.housenumber = Some("1a".to_string());
assert!(
Index::de_street_locality_qualifier_position("Markt 1, 06484 Quedlinburg", ¤t,)
.is_none(),
"the candidate house suffix must equal the typed suffix"
);
current[1].0.housenumber = Some("1".to_string());
assert_eq!(
Index::de_street_locality_qualifier_position("Markt 1, 06484 Quedlinburg", ¤t,),
Some(1),
"the same product-only window becomes admissible once both guards hold"
);
for street in ["Markt Nord", "Markt Süd", "Markt Ost"] {
current.push((make_hit(street, "Quedlinburg", "", "1"), candidate_features));
}
current.push((
make_hit(
"Markt (Quedlinburg)",
"Quedlinburg, Welterbestadt Süd",
"",
"1",
),
candidate_features,
));
assert_eq!(
Index::de_street_locality_qualifier_position("Markt 1, 06484 Quedlinburg", ¤t,),
Some(1),
"an eligible rank six is outside the fixed audited top-five window"
);
let rank_six = current.pop().expect("the rank-six witness exists");
current[4] = rank_six;
assert!(
Index::de_street_locality_qualifier_position("Markt 1, 06484 Quedlinburg", ¤t,)
.is_none(),
"the same duplicate at rank five must fail closed"
);
}
#[test]
fn de_wave_x_x2_preserves_exact_postcodes_and_rejects_nonempty_or_wrong_qualifiers() {
let canonical = forward_postcode_index_for_country(
"wave-x-x2-top-and-bare-guards",
"markt,001,quedlinburg,06485,06485,1,,11.1000000,51.7900000,Markt,Quedlinburg\n\
markt quedlinburg,002,quedlinburg welterbestadt,,,1,,11.1400000,51.8000000,Markt (Quedlinburg),\"Quedlinburg, Welterbestadt\"\n",
"de",
);
for query in ["Markt 1, 06485 Quedlinburg", "Markt 1"] {
let top = canonical
.query(query, 1)
.into_iter()
.next()
.expect("the established Markt result remains available");
assert_eq!(top.street, "Markt", "{query}");
assert!(!top.flags.contains(&"de_street_locality_qualifier"));
}
let populated = forward_postcode_index_for_country(
"wave-x-x2-populated-candidate-postcode",
"markt,001,quedlinburg,06485,06485,1,,11.1000000,51.7900000,Markt,Quedlinburg\n\
markt quedlinburg,002,quedlinburg welterbestadt,06486,06486,1,,11.1400000,51.8000000,Markt (Quedlinburg),\"Quedlinburg, Welterbestadt\"\n",
"de",
);
let populated_top = populated
.query("Markt 1, 06484 Quedlinburg", 1)
.into_iter()
.next()
.expect("the established department-level result remains available");
assert_eq!(populated_top.street, "Markt");
assert!(!populated_top
.flags
.contains(&"de_street_locality_qualifier"));
let wrong = forward_postcode_index_for_country(
"wave-x-x2-wrong-source-qualifier",
"markt,001,quedlinburg,06485,06485,1,,11.1000000,51.7900000,Markt,Quedlinburg\n\
markt quedlinburg,002,quedlinburg welterbestadt,,,1,,11.1400000,51.8000000,Markt (Gernrode),\"Quedlinburg, Welterbestadt\"\n",
"de",
);
let wrong_top = wrong
.query("Markt 1, 06484 Quedlinburg", 1)
.into_iter()
.next()
.expect("the established department-level result remains available");
assert_eq!(wrong_top.street, "Markt");
assert!(!wrong_top.flags.contains(&"de_street_locality_qualifier"));
let wrong_commune = forward_postcode_index_for_country(
"wave-x-x2-wrong-source-commune",
"markt,001,quedlinburg,06485,06485,1,,11.1000000,51.7900000,Markt,Quedlinburg\n\
markt quedlinburg,002,gernrode,,,1,,11.1400000,51.8000000,Markt (Quedlinburg),Gernrode\n",
"de",
);
let wrong_commune_top = wrong_commune
.query("Markt 1, 06484 Quedlinburg", 1)
.into_iter()
.next()
.expect("the established department-level result remains available");
assert_eq!(wrong_commune_top.street, "Markt");
assert!(!wrong_commune_top
.flags
.contains(&"de_street_locality_qualifier"));
let foreign = forward_postcode_index_for_country(
"wave-x-x2-foreign-country",
"markt,001,quedlinburg,06485,06485,1,,11.1000000,51.7900000,Markt,Quedlinburg\n\
markt quedlinburg,002,quedlinburg welterbestadt,,,1,,11.1400000,51.8000000,Markt (Quedlinburg),\"Quedlinburg, Welterbestadt\"\n",
"fr",
);
let foreign_top = foreign
.query("Markt 1, 06484 Quedlinburg", 1)
.into_iter()
.next()
.expect("the foreign sheet's established result remains available");
assert_eq!(foreign_top.street, "Markt");
assert!(!foreign_top.flags.contains(&"de_street_locality_qualifier"));
}
#[test]
fn de_wave_b_p4_parser_accepts_only_the_four_audited_shapes() {
let positives = [
(
"Blockhaus, 19, Große Meißner Straße, Innere Neustadt, Neustadt, Dresden, Sachsen, 01097",
DeAuditedCompoundShape::VenueCommaHouseCommaStreet,
vec![],
"grosse meissner strasse",
"dresden",
),
(
"Albertstr. 25 ( Otto-Krayer-Haus), 79104 Freiburg/Breisgau",
DeAuditedCompoundShape::StreetHouseBalancedVenueParenthetical,
vec![],
"albertstrasse",
"freiburg im breisgau",
),
(
"c/o Jacobs University Bremen Campusring 1 Bremen, 28759 Bremen",
DeAuditedCompoundShape::CareOfPrefixThenStreetHouseLocality,
vec![],
"campus ring",
"bremen",
),
(
"Rheinstr. 45/46 (Aufgang 6), 12161 Berlin",
DeAuditedCompoundShape::StreetHouseRangeBalancedAccessParenthetical,
vec![46],
"rheinstrasse",
"berlin",
),
(
"Marktplatz 4 (Weilheimer \"Bürgerhaus\"), 73235 Weilheim/Teck",
DeAuditedCompoundShape::StreetHouseBalancedVenueParenthetical,
vec![],
"marktplatz",
"weilheim an der teck",
),
];
for (raw, shape, additional_houses, normalized_street, normalized_locality) in positives {
let spec = de_audited_compound_spec(raw)
.unwrap_or_else(|| panic!("audited P4 surface must parse: {raw}"));
assert_eq!(spec.shape, shape, "{raw}");
assert_eq!(spec.additional_houses, additional_houses, "{raw}");
assert_eq!(spec.normalized_street, normalized_street, "{raw}");
assert_eq!(spec.normalized_locality, normalized_locality, "{raw}");
assert_eq!(spec.postcode_raw.len(), 5, "{raw}");
}
for raw in [
"Albertstr. 25 ((Haus)), 79104 Freiburg/Breisgau",
"Albertstr. 25(Haus), 79104 Freiburg/Breisgau",
"Albertstr. 025 (Haus), 79104 Freiburg/Breisgau",
"Albertstr. 25 (Haus),79104 Freiburg/Breisgau",
"Albertstr. 25 (Haus, 79104 Freiburg/Breisgau",
"Rheinstr. 45/46 (Haus 6), 12161 Berlin",
"Rheinstr. 45/46/47 (Aufgang 6), 12161 Berlin",
"Blockhaus, Große Meißner Straße, 19, Dresden, 01097",
"Blockhaus, 19a, Große Meißner Straße, Dresden, 01097",
"Blockhaus, 19, Große Meißner Straße, Innere Neustadt, 7, Dresden, Sachsen, 01097",
"c/o Campusring 1 Bremen, 28759 Bremen",
"c/oops Jacobs Campusring 1 Bremen, 28759 Bremen",
"c/o Jacobs Campusring 1 Hamburg, 28759 Bremen",
"c/o Jacobs Campusring 1 Bremen, 28759 Bremen, Deutschland",
"Marktplatz 4 (Haus), 7323 Weilheim/Teck",
"Marktplatz 4 (Haus), 73235 Weilheim/Teck/Bayern",
] {
assert!(
de_audited_compound_spec(raw).is_none(),
"typed P4 parser must reject {raw:?}"
);
}
}
#[test]
fn de_wave_o_blank_postcode_exact_house_replaces_typed_postcode_near() {
let idx = forward_postcode_index_for_country(
"wave-o-blank-house-near",
"ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
source-key-differs,001,probingen,,,12,,10.0010000,50.0010000,Ankerstraße,Probingen\n",
"de",
);
let top = idx
.query("Ankerstraße 12, 12345 Probingen", 1)
.into_iter()
.next()
.expect("the established typed-postcode near result must exist");
assert_eq!(top.precision, "house");
assert_eq!(top.street, "Ankerstraße");
assert_eq!(top.housenumber.as_deref(), Some("12"));
assert_eq!(top.commune, "Probingen");
assert_eq!(top.postcode, "");
assert!(top.flags.contains(&"de_blank_postcode_house_override"));
assert!(!top.flags.contains(&"pc_exact"));
assert!(!top.flags.contains(&"pc_dept"));
}
#[test]
fn de_wave_o_blank_postcode_exact_house_replaces_typed_postcode_interp() {
let idx = forward_postcode_index_for_country(
"wave-o-blank-house-interp",
"bogenstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Bogenstraße,Probingen\n\
bogenstrasse,001,probingen,12345,12345,14,,10.0010000,50.0010000,Bogenstraße,Probingen\n\
legacy-bogen-key,001,probingen,,,12,,10.0005000,50.0005000,Bogenstraße,Probingen\n",
"de",
);
let top = idx
.query("Bogenstraße 12, 12345 Probingen", 1)
.into_iter()
.next()
.expect("the established typed-postcode interpolation must exist");
assert_eq!(top.precision, "house");
assert_eq!(top.housenumber.as_deref(), Some("12"));
assert_eq!(top.postcode, "");
assert!(top.flags.contains(&"de_blank_postcode_house_override"));
}
#[test]
fn de_wave_o_blank_postcode_exact_suffix_is_preserved() {
let idx = forward_postcode_index_for_country(
"wave-o-blank-house-suffix",
"legacy-ufer-key,001,probingen,,,12,a,10.0005000,50.0005000,Uferweg,Probingen\n\
uferweg,001,probingen,12345,12345,10,a,10.0000000,50.0000000,Uferweg,Probingen\n\
uferweg,001,probingen,12345,12345,14,a,10.0010000,50.0010000,Uferweg,Probingen\n",
"de",
);
let top = idx
.query("Uferweg 12a, 12345 Probingen", 1)
.into_iter()
.next()
.expect("the established typed-postcode interpolation must exist");
assert_eq!(top.precision, "house");
assert_eq!(top.housenumber.as_deref(), Some("12a"));
assert_eq!(top.postcode, "");
assert!(top.flags.contains(&"de_blank_postcode_house_override"));
}
fn de_wave_o_base_index(case: &str, country: &str) -> Index {
forward_postcode_index_for_country(
case,
"a-legacy-source-key,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,14,,10.0010000,50.0010000,Ankerstraße,Probingen\n",
country,
)
}
fn de_wave_o_current(
precision: &'static str,
street: &str,
commune: &str,
postcode: &str,
features: Feats,
flags: Vec<&'static str>,
) -> Vec<(Hit, [f32; N_FEATS])> {
vec![(
Hit {
lat: 0.0,
lon: 0.0,
precision,
score: 0.0,
confidence: 0.0,
street: street.to_string(),
housenumber: Some("12".to_string()),
commune: commune.to_string(),
postcode: postcode.to_string(),
flags,
region: None,
distance_m: None,
},
features.to_vec(),
)]
}
fn de_wave_o_strict_current(precision: &'static str) -> Vec<(Hit, [f32; N_FEATS])> {
de_wave_o_current(
precision,
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec!["street_exact", "commune_exact", "pc_exact"],
)
}
#[test]
fn de_wave_o_parser_is_single_literal_and_two_field_only() {
for raw in [
"Ankerstraße 12, 12345 Probingen",
"Ankerstraße 12a, 12345 Probingen",
] {
assert!(
de_blank_postcode_house_spec(raw).is_some(),
"strict P5 surface must parse: {raw}"
);
}
for raw in [
"Ankerstraße 12/14, 12345 Probingen",
"Ankerstraße 12-14, 12345 Probingen",
"Ankerstraße 12 bis 14, 12345 Probingen",
"Ankerstraße 12 und 14, 12345 Probingen",
"Ankerstraße 12 (Haus), 12345 Probingen",
"c/o Ankerstraße 12, 12345 Probingen",
"Ankerstraße 12, 12345 Probingen, Deutschland",
"Ankerstraße 12, 12345",
"Ankerstraße 12, 1234 Probingen",
"Straße 7 12, 12345 Probingen",
" Ankerstraße 12, 12345 Probingen",
] {
assert!(
de_blank_postcode_house_spec(raw).is_none(),
"P5 must reject noncanonical or compound surface: {raw}"
);
}
}
#[test]
fn de_wave_o_current_top_requires_exact_original_fields() {
let idx = de_wave_o_base_index("wave-o-current-gates", "de");
let raw = "Ankerstraße 12, 12345 Probingen";
assert!(
idx.de_blank_postcode_exact_house_fallback(
raw,
&de_wave_o_strict_current("near"),
1,
None,
)
.is_some()
);
for (case, current) in [
("house", de_wave_o_strict_current("house")),
("street", de_wave_o_strict_current("street")),
(
"wrong-postcode",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12346",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec![],
),
),
(
"pc-dept-only",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_dept: true,
..Default::default()
},
vec![],
),
),
(
"incumbent-exact-house",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
house_exact_rep: true,
..Default::default()
},
vec![],
),
),
(
"fuzzy-street",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_fuzzy: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec![],
),
),
(
"mismatched-hit-street",
de_wave_o_current(
"near",
"Seitenstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec![],
),
),
(
"mismatched-hit-locality",
de_wave_o_current(
"near",
"Ankerstraße",
"Nebenstadt",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec![],
),
),
(
"locality-prefix",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_prefix: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec![],
),
),
(
"alias-derived",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec!["de_city_alias"],
),
),
(
"official-alias-derived",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec!["de_official_commune_alias"],
),
),
(
"dropped-prefix",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec!["dropped_prefix"],
),
),
(
"dropped-suffix",
de_wave_o_current(
"near",
"Ankerstraße",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec!["dropped_suffix"],
),
),
] {
assert!(
idx.de_blank_postcode_exact_house_fallback(raw, ¤t, 1, None)
.is_none(),
"strict current-top gate must reject {case}"
);
}
}
#[test]
fn de_wave_o_current_selector_values_do_not_affect_admission() {
let idx = de_wave_o_base_index("wave-o-current-selector-invariance", "de");
let mut baseline = de_wave_o_strict_current("near");
let mut altered = de_wave_o_strict_current("near");
baseline[0].0.lat = 0.0;
baseline[0].0.lon = 0.0;
baseline[0].0.score = 0.0;
baseline[0].0.confidence = 0.0;
baseline[0].0.distance_m = None;
altered[0].0.lat = 89.0;
altered[0].0.lon = -179.0;
altered[0].0.score = -10_000.0;
altered[0].0.confidence = 1.0;
altered[0].0.distance_m = Some(9_999_999.0);
let summarize = |candidate: Vec<(Hit, [f32; N_FEATS])>| {
candidate
.into_iter()
.map(|(hit, features)| {
(
hit.precision,
hit.street,
hit.housenumber,
hit.commune,
hit.postcode,
hit.flags,
features,
)
})
.collect::<Vec<_>>()
};
let first = idx
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&baseline,
1,
None,
)
.expect("baseline selector values must admit the strict P5 candidate");
let second = idx
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&altered,
1,
None,
)
.expect("changed selector-only values must preserve P5 admission");
assert_eq!(summarize(first), summarize(second));
}
#[test]
fn de_wave_o_p3_p5_overlap_preserves_the_established_answer() {
let idx = forward_postcode_index_for_country(
"wave-o-p3-p5-overlap",
"a-blank-exact-display,001,probingen,,,12,,10.0005000,50.0005000,Ankerstrase,Probingen\n\
ankerstrase,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstrase,Probingen\n\
ankerstrasse,001,probingen,12345,12345,12,,10.0007000,50.0007000,Ankerstraße,Probingen\n",
"de",
);
let raw = "Ankerstrase 12, 12345 Probingen";
let mut established = de_wave_o_current(
"near",
"Ankerstrase",
"Probingen",
"12345",
Feats {
street_exact: true,
commune_exact: true,
pc_exact: true,
pc_dept: true,
..Default::default()
},
vec!["street_exact", "commune_exact", "pc_exact"],
);
let p3 = idx
.de_strict_source_street_typo_fallback(raw, &established, 1)
.expect("the independent exact-postcode typo mechanism must be nonempty");
let p5 = idx
.de_blank_postcode_exact_house_fallback(raw, &established, 1, None)
.expect("the independent blank-postcode exact-house mechanism must be nonempty");
assert!(p3[0].0.flags.contains(&"de_strict_source_street_typo"));
assert!(p5[0].0.flags.contains(&"de_blank_postcode_house_override"));
Index::de_product_fallback_arbitration(&mut established, Some(p3), None, None, Some(p5));
assert_eq!(established.len(), 1);
assert_eq!(established[0].0.precision, "near");
assert_eq!(established[0].0.street, "Ankerstrase");
assert_eq!(established[0].0.postcode, "12345");
assert!(!established[0]
.0
.flags
.contains(&"de_strict_source_street_typo"));
assert!(!established[0]
.0
.flags
.contains(&"de_blank_postcode_house_override"));
}
#[test]
fn de_wave_o_distinct_source_sids_fail_closed_independent_of_coordinates() {
for (case, second_coordinates) in [
("same-coordinates", "10.0005000,50.0005000"),
("different-coordinates", "10.0007000,50.0007000"),
] {
let rows = format!(
"a-blank-key,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
b-blank-key,001,probingen,,,12,,{second_coordinates},Ankerstraße,Probingen\n"
);
let idx = forward_postcode_index_for_country(case, &rows, "de");
let top = idx
.query("Ankerstraße 12, 12345 Probingen", 1)
.into_iter()
.next()
.expect("the established near result must remain");
assert_eq!(top.precision, "near", "{case}");
assert_eq!(top.postcode, "12345", "{case}");
assert!(
!top.flags.contains(&"de_blank_postcode_house_override"),
"two source SIDs must fail closed regardless of coordinates: {case}"
);
}
}
#[test]
fn de_wave_o_duplicate_rows_inside_one_sid_fail_closed() {
for (case, second_coordinates) in [
("same-coordinates", "10.0005000,50.0005000"),
("different-coordinates", "10.0007000,50.0007000"),
] {
let rows = format!(
"a-blank-key,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
a-blank-key,001,probingen,,,12,,{second_coordinates},Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n"
);
let idx = forward_postcode_index_for_country(case, &rows, "de");
let candidate = idx.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
);
assert!(
candidate.is_none(),
"two represented rows inside one SID must fail closed: {case}"
);
}
}
#[test]
fn de_wave_o_any_competing_exact_house_postcode_fails_closed() {
for (case, competing_postcode) in [("typed-postcode", "12345"), ("wrong-postcode", "54321")]
{
let rows = format!(
"a-blank-key,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
z-competing-key,001,probingen,{competing_postcode},{competing_postcode},12,,10.0007000,50.0007000,Ankerstraße,Probingen\n"
);
let idx = forward_postcode_index_for_country(case, &rows, "de");
assert!(
idx.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none(),
"blank candidate plus {case} exact house must fail closed"
);
}
}
#[test]
fn de_wave_o_populated_only_exact_target_is_never_relabelled_blank() {
let idx = forward_postcode_index_for_country(
"wave-o-populated-only-target",
"a-blank-projection-seed,001,probingen,,,13,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
z-populated-target,001,probingen,54321,54321,12,,10.0007000,50.0007000,Ankerstraße,Probingen\n",
"de",
);
assert!(
idx.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none(),
"a blank row at another house may seed the projection but cannot relabel the populated exact target"
);
}
#[test]
fn de_wave_o_mixed_postcode_street_is_not_a_blank_source_candidate() {
let idx = forward_postcode_index_for_country(
"wave-o-mixed-postcode-negative",
"ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
legacy-mixed-key,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
legacy-mixed-key,001,probingen,12345,12345,14,,10.0007000,50.0007000,Ankerstraße,Probingen\n",
"de",
);
assert!(idx
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none());
}
#[test]
fn de_wave_o_candidate_requires_the_exact_anchored_commune_id() {
for (case, blank_commune_id, blank_commune) in [
("same-name-other-id", "002", "probingen"),
("prefix-only", "002", "probingen nord"),
] {
let rows = format!(
"a-blank-key,{blank_commune_id},{blank_commune},,,12,,10.0005000,50.0005000,Ankerstraße,{}\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n",
if blank_commune == "probingen" {
"Probingen"
} else {
"Probingen Nord"
}
);
let idx = forward_postcode_index_for_country(case, &rows, "de");
assert!(
idx.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none(),
"P5 must reject candidate locality relation {case}"
);
}
let duplicate_locality_identity = forward_postcode_index_for_country(
"wave-o-duplicate-locality-identity",
"a-blank-anchor,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
z-blank-homonym,002,probingen,,,12,,10.0007000,50.0007000,Ankerstraße,Probingen\n",
"de",
);
assert!(
duplicate_locality_identity
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none(),
"a second exact physical row behind the same locality display must fail closed"
);
let ambiguous_anchor = forward_postcode_index_for_country(
"wave-o-ambiguous-anchor",
"a-blank-anchor,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
z-second-anchor,002,probingen,12345,12345,20,,10.0007000,50.0007000,Ankerstraße,Probingen\n",
"de",
);
assert!(
ambiguous_anchor
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none(),
"two typed-postcode commune ids behind one display locality must fail closed"
);
let unrelated_homonym = forward_postcode_index_for_country(
"wave-o-unrelated-homonym",
"a-blank-anchor,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
z-unrelated-homonym,002,nebenstadt,,,12,,10.0007000,50.0007000,Ankerstraße,Nebenstadt\n",
"de",
);
assert!(
unrelated_homonym
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_some(),
"an unrelated locality homonym must not veto the unique anchored candidate"
);
}
#[test]
fn de_wave_o_bare_and_suffix_addresses_never_coalesce() {
for (case, query_house, blank_suffix) in [
("query-suffix-source-bare", "12a", ""),
("query-bare-source-suffix", "12", "a"),
] {
let rows = format!(
"a-blank-key,001,probingen,,,12,{blank_suffix},10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n"
);
let idx = forward_postcode_index_for_country(case, &rows, "de");
assert!(
idx.de_blank_postcode_exact_house_fallback(
&format!("Ankerstraße {query_house}, 12345 Probingen"),
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none(),
"exact suffix identity must be preserved: {case}"
);
}
}
#[test]
fn de_wave_o_source_order_and_single_sid_coordinates_do_not_change_admission() {
let mut outcomes = Vec::new();
for (case, blank_key, blank_coordinates) in [
("blank-before", "a-blank-key", "10.0005000,50.0005000"),
("blank-after", "z-blank-key", "11.5000000,51.5000000"),
] {
let mut rows = [
format!(
"{blank_key},001,probingen,,,12,,{blank_coordinates},Ankerstraße,Probingen"
),
"ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen"
.to_string(),
];
rows.sort();
let idx =
forward_postcode_index_for_country(case, &format!("{}\n", rows.join("\n")), "de");
let top = idx
.query("Ankerstraße 12, 12345 Probingen", 1)
.into_iter()
.next()
.expect("one exact blank source row must remain admissible");
outcomes.push((
top.precision,
top.street,
top.housenumber,
top.commune,
top.postcode,
top.flags.contains(&"de_blank_postcode_house_override"),
));
}
assert_eq!(outcomes[0], outcomes[1]);
assert!(outcomes[0].5);
}
#[test]
fn de_wave_o_non_de_focus_and_scan_overflow_remain_closed() {
let mut foreign = de_wave_o_base_index("wave-o-foreign", "fr");
foreign.de_postcode_streets = foreign.build_de_postcode_streets().unwrap();
foreign.de_blank_postcode_display_streets =
foreign.build_de_blank_postcode_display_streets().unwrap();
assert!(foreign
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none());
let mut legacy = de_wave_o_base_index("wave-o-pre-v7", "de");
legacy.format_version = 6;
assert!(legacy
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
)
.is_none());
let idx = de_wave_o_base_index("wave-o-focus-overflow", "de");
let focus = QueryFocus {
lat: 50.0,
lon: 10.0,
streets: Vec::new(),
};
assert!(idx
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
Some(&focus),
)
.is_none());
let mut bucket_overflow = forward_postcode_index_for_country(
"wave-o-bucket-overflow",
"a-blank-anchor,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n\
z-unrelated-locality,002,nebenstadt,,,99,,10.0007000,50.0007000,Ankerstraße,Nebenstadt\n",
"de",
);
let mut projected = bucket_overflow
.de_blank_postcode_display_streets
.get("ankerstrasse", "probingen")
.expect("the complete target projection must exist")
.to_vec();
assert_eq!(projected.len(), 2);
let unrelated_sid = (0..bucket_overflow.streets_meta.len() / STREET_META_SIZE)
.map(|sid| u32::try_from(sid).expect("test street id fits u32"))
.find(|sid| {
let metadata = bucket_overflow.street_meta(*sid);
de_product_normalize_text(bucket_overflow.commune_name(metadata.commune_id))
== "nebenstadt"
})
.expect("the unrelated-locality observer SID must exist");
projected.push(unrelated_sid);
bucket_overflow.de_blank_postcode_display_streets = DeBlankPostcodeDisplayProjection {
ranges: HashMap::from([(
("ankerstrasse".to_string(), "probingen".to_string()),
(0, projected.len()),
)]),
sids: projected.into_boxed_slice(),
};
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(|limit| limit.set(2));
let overflow = bucket_overflow.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
);
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT
.with(|limit| limit.set(DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT));
assert!(
overflow.is_none(),
"a display bucket above its independent SID ceiling must fail closed"
);
let row_overflow = forward_postcode_index_for_country(
"wave-o-row-overflow",
"a-blank-anchor,001,probingen,,,1,,10.0001000,50.0001000,Ankerstraße,Probingen\n\
a-blank-anchor,001,probingen,,,2,,10.0002000,50.0002000,Ankerstraße,Probingen\n\
a-blank-anchor,001,probingen,,,12,,10.0005000,50.0005000,Ankerstraße,Probingen\n\
ankerstrasse,001,probingen,12345,12345,10,,10.0000000,50.0000000,Ankerstraße,Probingen\n",
"de",
);
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT.with(|limit| limit.set(3));
let overflow = row_overflow.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("near"),
1,
None,
);
DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT
.with(|limit| limit.set(DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT));
assert!(
overflow.is_none(),
"cumulative physical house rows above their independent ceiling must fail closed"
);
}
#[test]
fn de_wave_o_runtime_path_and_forbidden_field_audit_are_nonvacuous() {
let idx = de_wave_o_base_index("wave-o-runtime-audit", "de");
DE_BLANK_POSTCODE_HOUSE_SCAN_ROWS.with(|rows| rows.set(0));
let candidate = idx
.de_blank_postcode_exact_house_fallback(
"Ankerstraße 12, 12345 Probingen",
&de_wave_o_strict_current("interp"),
1,
None,
)
.expect("strict P5 runtime path must produce one candidate");
assert_eq!(candidate.len(), 1);
assert!(DE_BLANK_POSTCODE_HOUSE_SCAN_ROWS.with(|rows| rows.get()) > 0);
fn segment<'a>(source: &'a str, start_marker: &str, end_marker: &str) -> &'a str {
let start = source.find(start_marker).expect("P5 source start marker");
let end = source[start..]
.find(end_marker)
.map(|offset| start + offset)
.expect("P5 source end marker");
&source[start..end]
}
let source = include_str!("query.rs");
let p5_source = [
segment(
source,
"fn de_blank_postcode_house_spec",
"fn de_source_street_locality_qualifier",
),
segment(
source,
"struct DeBlankPostcodeDisplayProjection",
"pub struct Index",
),
segment(
source,
"fn build_de_blank_postcode_display_streets",
"/// Exact-postcode street bucket",
),
segment(
source,
"fn de_exact_house_record_postcodes",
"fn commune_insee",
),
segment(
source,
"fn de_blank_postcode_current_top_is_strict",
"fn de_p3_current_top_already_complete",
),
segment(
source,
"let x2 = Self::de_street_locality_qualifier_position",
"if frankfurt.is_some()",
),
]
.join("\n");
for forbidden in [
".lat",
".lon",
"dist_km(",
".distance_m",
".score",
".confidence",
"take(1)",
"roster_id",
"ordinal",
"physical_id",
"truth_coordinate",
"result_coordinate",
"benchmark",
"competitor",
"distance_threshold",
] {
assert!(
!p5_source.contains(forbidden),
"P5 admission must not read forbidden selector {forbidden}"
);
}
for required in [
"metadata.commune_id != anchor_commune_id",
"candidate_sids.len() > scan_limit",
"exact_records.as_slice()",
"postcode.is_empty()",
"made_features.house_exact_rep",
"HashMap<(String, String), (usize, usize)>",
"anchored_identities.contains(&identity)",
"drop(anchored_identities)",
"bucket.len() <= DE_POSTCODE_HOUSE_RESCUE_SCAN_LIMIT_DEFAULT",
".get(&spec.normalized_street, &spec.normalized_locality)",
"match (p3, p4, x2, p5)",
"(None, None, None, Some(candidate))",
"Self::de_product_fallback_arbitration(&mut best, p3, p4, x2, p5)",
] {
assert!(
p5_source.contains(required),
"P5 source audit must observe guard {required}"
);
}
}
fn es_particle_fixture(country: &str, street: &str) -> Index {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"gridpin-es-particle-{}-{country}-{}-{serial}",
std::process::id(),
street.replace(' ', "-")
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("rows.csv");
let decoy = match country {
"fr" => "rue de la pais",
"it" => "via del corsa",
_ => "calle zzzzzzzz",
};
let mut rows = [
format!("{street},001,ciudad,28001,7,,-3.7,40.4,{street},Ciudad"),
format!("{decoy},001,ciudad,28001,7,,-4.7,41.4,{decoy},Ciudad"),
];
rows.sort();
std::fs::write(&csv, format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{}\n", rows.join("\n")
)).unwrap();
let rules = dir.join("rules");
std::fs::create_dir_all(&rules).unwrap();
std::fs::write(rules.join("street_types_latin.tsv"), "calle\nrue\nvia\n").unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(&manifest, format!(r#"{{"country":"{country}","layer":"addresses","license":"test","source_release":"test"}}"#)).unwrap();
let bin = dir.join("test.bin");
crate::builder::build(&csv, &bin, None, None, Some(&rules), None, Some(&manifest)).unwrap();
Index::open(&bin).unwrap()
}
#[test]
fn es_particles_bidirectional_house_and_apostrophes() {
for particle in [
"de", "del", "dels", "de la", "de les", "de los", "de las", "de l'", "de l’", "d'",
"d’",
] {
let idx = es_particle_fixture("es", "calle ejemplo");
{
let _scope = crate::rules::scope(idx.rules);
let forward = Index::es_street_particle_variants(&format!(
"Calle {particle} Ejemplo, 7, Ciudad"
));
assert!(
forward.contains(&"calle ejemplo, 7, Ciudad".to_string()),
"forward {particle}"
);
let reverse = Index::es_street_particle_variants("Calle Ejemplo, 7, Ciudad");
assert!(
reverse.contains(&format!("calle {} ejemplo, 7, Ciudad", normalize(particle))),
"reverse {particle}: {reverse:?}; normalized particle {:?}",
normalize(particle)
);
}
let query = format!("calle {particle} Ejemplo, 7, Ciudad");
let hits = idx.query(&query, 1);
assert_eq!(hits.len(), 1, "{query}");
assert_eq!(hits[0].precision, "house", "{query}");
assert_eq!(hits[0].street, "calle ejemplo", "{query}");
let street = format!("calle {} ejemplo", normalize(particle));
let idx = es_particle_fixture("es", &street);
let hits = idx.query("calle Ejemplo, 7, Ciudad", 1);
assert_eq!(hits.len(), 1, "reverse {particle}");
assert_eq!(hits[0].precision, "house", "reverse {particle}");
assert_eq!(hits[0].street, street, "reverse {particle}");
}
}
#[test]
fn es_particles_preserve_word_boundaries_and_inner_linkers() {
let idx = es_particle_fixture("es", "calle sant joan de deu");
let _scope = crate::rules::scope(idx.rules);
let variants = Index::es_street_particle_variants("Calle de Sant Joan de Déu, 7, Ciudad");
assert!(variants.contains(&"calle sant joan de deu, 7, Ciudad".to_string()));
assert!(variants.iter().all(|v| v.contains("sant joan de deu")));
let variants = Index::es_street_particle_variants("Calle Delicias, 7, Ciudad");
assert!(variants.iter().all(|v| v.contains("delicias")));
let hits = idx.query("Calle de Sant Joan de Déu, 7, Ciudad", 1);
assert_eq!(hits[0].street, "calle sant joan de deu");
assert_eq!(hits[0].precision, "house");
}
#[test]
fn es_particles_do_not_apply_to_foreign_indexes() {
for (country, street) in [("fr", "rue paix"), ("it", "via corso")] {
let idx = es_particle_fixture(country, street);
let query = if country == "fr" {
"Rue de la Paix, 7, Ciudad"
} else {
"Via del Corso, 7, Ciudad"
};
let _scope = crate::rules::scope(idx.rules);
let expected = idx.query_feats_d(query, 1, 0, None, None, None, false, None);
let actual = idx.query_feats_country_variants(query, 1, None);
let forced = idx.es_particle_retry(query, 1, None);
assert_ne!(
serde_json::to_value(forced.iter().map(|v| &v.0).collect::<Vec<_>>()).unwrap(),
serde_json::to_value(expected.iter().map(|v| &v.0).collect::<Vec<_>>()).unwrap(),
"fixture must distinguish an ES-only retry on {country}"
);
assert_eq!(
serde_json::to_value(actual.iter().map(|v| &v.0).collect::<Vec<_>>()).unwrap(),
serde_json::to_value(expected.iter().map(|v| &v.0).collect::<Vec<_>>()).unwrap()
);
}
}
#[test]
fn es_particles_required_address_shapes() {
let examples = [
(
"Carrer de Reding, 9, tarragona, España",
"calle reding",
"tarragona",
"9",
),
(
"C. del Centre, 6, garcia, España",
"calle centre",
"garcia",
"6",
),
(
"C. de la Presó, 13, reus, España",
"calle preso",
"reus",
"13",
),
(
"Plaça de Catalunya, 6, tremp, España",
"placa catalunya",
"tremp",
"6",
),
(
"C. de Sant Medir, 24, sant cugat del valles, España",
"calle sant medir",
"sant cugat del valles",
"24",
),
(
"Calle de Alcalá, 50, Madrid, España",
"calle alcala",
"madrid",
"50",
),
];
let dir = std::env::temp_dir().join(format!(
"gridpin-es-article-examples-{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("rows.csv");
let mut rows = Vec::new();
for (i, (_, street, city, house)) in examples.iter().enumerate() {
for name in [*street, "calle zzzzzzzz"] {
rows.push(format!(
"{name},{i:03},{city},28001,{house},,-3.7,40.4,{name},{city}"
));
}
}
rows.sort();
std::fs::write(&csv, format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{}\n", rows.join("\n")
)).unwrap();
let rules = dir.join("rules");
std::fs::create_dir_all(&rules).unwrap();
std::fs::write(
rules.join("street_types_latin.tsv"),
"calle\ncarrer\nc\nplaca\nplaza\n",
)
.unwrap();
std::fs::write(rules.join("countries_tail.tsv"), "espana\n").unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
r#"{"country":"es","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
let bin = dir.join("test.bin");
crate::builder::build(&csv, &bin, None, None, Some(&rules), None, Some(&manifest)).unwrap();
let idx = Index::open(&bin).unwrap();
for (query, street, city, house) in examples {
let hits = idx.query(query, 1);
assert!(!hits.is_empty(), "{query}");
assert_eq!(hits[0].street, street, "{query}");
assert_eq!(hits[0].commune, city, "{query}");
assert_eq!(hits[0].housenumber.as_deref(), Some(house), "{query}");
assert_eq!(hits[0].precision, "house", "{query}");
}
}
#[test]
fn es_particles_preserve_requested_city_at_every_precision() {
let idx = es_particle_fixture("es", "calle major");
let _scope = crate::rules::scope(idx.rules);
for precision in ["house", "interp", "near", "street", "city"] {
let mut original = hit(precision, 0.4, vec![]);
original.commune = "Ciudad".into();
let mut candidate = hit("house", 0.6, vec![]);
candidate.commune = "Ciudad Nueva".into();
assert!(
!Index::es_particle_preserves_commune(
"Calle Major, 14, Ciudad",
Some(&original),
&candidate
),
"{precision}"
);
candidate.commune = "Ciudad".into();
assert!(
Index::es_particle_preserves_commune(
"Calle Major, 14, Ciudad",
Some(&original),
&candidate
),
"same city {precision}"
);
original.commune = "Ciudad Nueva".into();
assert!(
Index::es_particle_preserves_commune(
"Calle Major, 14, Ciudad",
Some(&original),
&candidate
),
"wrong original city {precision}"
);
}
}
#[test]
fn es_particles_exact_original_is_a_fallback_boundary() {
let idx = es_particle_fixture("es", "calle ejemplo");
let _rules = crate::rules::scope(idx.rules);
let mut original = hit("house", 0.9, vec![]);
original.commune = "Madrid".into();
original.street = "Plaza San Juan De La Cruz".into();
let noisy = "Plaza San Juan De La Cruz 1, Madrid, Tel. +34 600 131 200";
assert_eq!(Index::es_requested_commune(noisy), "madrid");
assert_eq!(
Index::es_requested_commune("Carrer de Reding, 9, tarragona, España"),
"tarragona"
);
assert!(Index::es_particle_original_exact(noisy, &original));
original.street = "Plaza San Juan De La Cruz Nueva".into();
assert!(!Index::es_particle_original_exact(noisy, &original));
original.street = "Plaza San Juan De La Cruz".into();
original.commune = "Madrid Norte".into();
assert!(!Index::es_particle_original_exact(noisy, &original));
original.commune = "Madri".into();
assert!(!Index::es_particle_original_exact(noisy, &original));
original.commune = "Madrid".into();
original.flags = vec!["street_fuzzy"];
assert!(Index::es_particle_original_exact(noisy, &original));
}
/// Small ES sheet: `rows` are (normalized street, number, lon, lat) in commune "ciudad",
/// `rules` are (family, rows) rule files of the sheet.
fn es_type_fixture(rows: &[(&str, &str, f64, f64)], rules: &[(&str, &str)]) -> Index {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir =
std::env::temp_dir().join(format!("gridpin-es-type-{}-{serial}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let mut lines: Vec<String> = rows
.iter()
.map(|(street, number, lon, lat)| {
format!("{street},001,ciudad,28001,{number},,{lon},{lat},{street},Ciudad")
})
.collect();
lines.sort();
let csv = dir.join("rows.csv");
std::fs::write(&csv, format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{}\n", lines.join("\n")
)).unwrap();
let rules_dir = dir.join("rules");
std::fs::create_dir_all(&rules_dir).unwrap();
for (family, body) in rules {
std::fs::write(rules_dir.join(format!("{family}.tsv")), body).unwrap();
}
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
r#"{"country":"es","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
let bin = dir.join("test.bin");
crate::builder::build(
&csv,
&bin,
None,
None,
Some(&rules_dir),
None,
Some(&manifest),
)
.unwrap();
Index::open(&bin).unwrap()
}
const ES_TYPE_RULES: &str = "calle\npaseo\nplaza\nplaca\nvia\n";
// "Passeig de Gràcia 1": the sheet stores the Castilian "Paseo Gracia", and the main
// path answers house 1 of another "gracia" street. Read in either rule direction.
#[test]
fn es_type_synonym_retry_reaches_the_castilian_street() {
for pair in ["street\tpasseig\tpaseo\n", "street\tpaseo\tpasseig\n"] {
let idx = es_type_fixture(
&[
("paseo gracia", "1", -3.70, 40.40),
("placa vila de gracia", "1", -3.60, 40.50),
],
&[
("street_types_latin", ES_TYPE_RULES),
("street_types_extra", "passeig\n"),
("abbrev2", pair),
],
);
let hits = idx.query("Passeig de Gràcia 1, Ciudad", 1);
assert_eq!(hits.len(), 1, "{pair:?}");
assert_eq!(hits[0].street, "paseo gracia", "{pair:?}");
assert_eq!(hits[0].precision, "house", "{pair:?}");
assert_eq!(hits[0].housenumber.as_deref(), Some("1"), "{pair:?}");
}
}
// The written type is tried first: a synonym never displaces a house the literal
// street (with its seam particles) already reaches.
#[test]
fn es_type_synonym_retry_comes_after_the_written_type() {
let idx = es_type_fixture(
&[
("passeig gracia", "1", -3.70, 40.40),
("paseo gracia", "1", -3.60, 40.50),
],
&[
("street_types_latin", ES_TYPE_RULES),
("street_types_extra", "passeig\n"),
("abbrev2", "street\tpasseig\tpaseo\n"),
],
);
let hits = idx.query("Passeig de Gràcia 1, Ciudad", 1);
assert_eq!(hits[0].street, "passeig gracia");
assert_eq!(hits[0].precision, "house");
}
// Only one-word rules whose both sides are street types are synonyms; numerals,
// linkers and other rewrites never change the leading type.
#[test]
fn es_type_synonyms_are_one_word_type_pairs_only() {
let idx = es_type_fixture(
&[("paseo gracia", "1", -3.70, 40.40)],
&[
("street_types_latin", ES_TYPE_RULES),
("street_types_extra", "passeig\n"),
(
"abbrev2",
"street\tpasseig\tpaseo\nstreet\tpasseig\tvila\nstreet\tpasseig\tplaza mayor\nstreet\tcalle\tplaza\nstreet\tpg\tpaseo\n",
),
],
);
let _scope = crate::rules::scope(idx.rules);
let variants = Index::es_street_type_variants("Passeig de Gràcia 1, Ciudad");
assert!(
variants.contains(&"paseo de gracia 1, Ciudad".to_string()),
"{variants:?}"
);
assert!(
variants.contains(&"paseo gracia 1, Ciudad".to_string()),
"{variants:?}"
);
assert!(
variants.iter().all(|v| v.starts_with("paseo ")),
"only the declared type synonym: {variants:?}"
);
// a pair of two types that does not touch the written type is not a synonym of it
assert!(Index::es_street_type_variants("Paseo Gracia 1, Ciudad")
.iter()
.all(|v| v.starts_with("passeig ")));
// no type rule for the written type, no synonym
assert!(Index::es_street_type_variants("Plaza Gracia 1, Ciudad")
.iter()
.all(|v| v.starts_with("calle ")));
assert!(Index::es_street_type_variants("Rambla Gracia 1, Ciudad").is_empty());
// an abbreviation that is not itself a type word is not a type synonym
assert!(Index::es_street_type_variants("Pg Gracia 1, Ciudad").is_empty());
}
// A synonym retry runs only when the sheet has that exact typed name.
#[test]
fn es_type_synonym_retry_requires_the_exact_typed_name() {
let idx = es_type_fixture(
&[("paseo gracia", "1", -3.70, 40.40)],
&[
("street_types_latin", ES_TYPE_RULES),
("street_types_extra", "passeig\n"),
("abbrev2", "street\tpasseig\tpaseo\n"),
],
);
assert!(idx.es_typed_variant_exists("paseo gracia 1, Ciudad"));
assert!(!idx.es_typed_variant_exists("plaza gracia 1, Ciudad"));
assert!(!idx.es_typed_variant_exists("paseo gra 1, Ciudad"));
assert!(!idx.es_typed_variant_exists("paseo 1, Ciudad"));
}
// "Gran Via 1": "via" is a type word inside the name, not a leading type, so the bare
// name is padded ("Calle Gran Via"). A leading type still stops padding; Cyrillic
// types may trail, so any Cyrillic type word still counts.
#[test]
fn type_padding_counts_only_a_leading_latin_type() {
let idx = es_type_fixture(
&[
("calle gran via", "1", -3.70, 40.40),
("via gran", "1", -3.60, 40.50),
],
&[
("street_types_latin", ES_TYPE_RULES),
("street_types_cyr", "улица\n"),
],
);
{
let _scope = crate::rules::scope(idx.rules);
assert!(type_padded_variants("gran via").contains(&"calle gran via".to_string()));
assert!(type_padded_variants("via gran").is_empty());
assert!(type_padded_variants("ленина улица").is_empty());
assert!(type_padded_variants("улица ленина").is_empty());
assert!(!type_padded_variants("ленина").is_empty());
}
let hits = idx.query("Gran Via 1, Ciudad", 1);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].street, "calle gran via");
assert_eq!(hits[0].precision, "house");
}
#[test]
fn es_particles_prepared_cache_keeps_query_and_index_identity() {
let a = es_particle_fixture("es", "calle ejemplo");
let b = es_particle_fixture("es", "calle distinto");
let _rules = crate::rules::scope(a.rules);
let _scope = EsPreparedScope::new();
let q = "calle ejemplo 7 ciudad";
let first = a.query_feats_prepared_cityless(q, 1, None, None);
assert!(!first.is_empty());
let repeated = a.query_feats_prepared_cityless(q, 1, None, None);
assert_eq!(
serde_json::to_value(first.iter().map(|x| &x.0).collect::<Vec<_>>()).unwrap(),
serde_json::to_value(repeated.iter().map(|x| &x.0).collect::<Vec<_>>()).unwrap()
);
let other = b.query_feats_prepared_cityless("calle distinto 7 ciudad", 1, None, None);
assert_eq!(other[0].0.street, "calle distinto");
assert!(ES_PREPARED_CACHE.with(|cache| cache.borrow().as_ref().unwrap().len()) >= 2);
let absent = b.query_feats_prepared_cityless(q, 1, None, None);
assert!(absent.iter().all(|x| x.0.street != "calle ejemplo"));
}
fn es_observer_fixture(label: &str, rows: &[(&str, &str, &str, &str)], abbrev: &str) -> Index {
let dir = std::env::temp_dir().join(format!(
"gridpin-es-observer-{}-{label}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let mut csv_rows: Vec<_> = rows
.iter()
.enumerate()
.map(|(i, (street, city, id, number))| {
format!(
"{street},{id},{city},28001,{number},,{},40.4,{street},{city}",
-3.7 - i as f64 * 0.001
)
})
.collect();
csv_rows.sort_by_key(|row| {
let c: Vec<_> = row.split(',').collect();
(
c[0].to_string(),
c[1].to_string(),
c[4].parse::<u32>().unwrap_or(0),
)
});
let csv = dir.join("rows.csv");
std::fs::write(&csv, format!("nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{}\n",csv_rows.join("\n"))).unwrap();
let rules = dir.join("rules");
std::fs::create_dir_all(&rules).unwrap();
std::fs::write(rules.join("street_types_latin.tsv"), "calle\nrue\nvia\n").unwrap();
std::fs::write(rules.join("abbrev2.tsv"), abbrev).unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
r#"{"country":"es","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
let bin = dir.join("test.bin");
crate::builder::build(&csv, &bin, None, None, Some(&rules), None, Some(&manifest)).unwrap();
Index::open(&bin).unwrap()
}
fn es_observer_hits(hits: &[(Hit, [f32; N_FEATS])]) -> serde_json::Value {
serde_json::to_value(hits.iter().map(|x| &x.0).collect::<Vec<_>>()).unwrap()
}
#[test]
fn es_observer_accepts_same_street_house_with_number() {
let idx = es_observer_fixture(
"accept",
&[
("calle de sant joan", "ciudad", "001", "7"),
("calle sant joan de deu", "ciudad", "001", "8"),
],
"",
);
let _rules = crate::rules::scope(idx.rules);
let raw = "Calle Sant Joan, 7, Ciudad";
let original = idx.query_feats_d(raw, 1, 0, None, None, None, false, None);
assert_eq!(original[0].0.precision, "near");
assert_eq!(original[0].0.street, "calle sant joan de deu");
let actual = idx.query_feats_country_variants(raw, 1, None);
assert_eq!(actual[0].0.precision, "house");
assert_eq!(actual[0].0.street, "calle de sant joan");
assert_eq!(actual[0].0.commune, "ciudad");
assert_eq!(actual[0].0.housenumber.as_deref(), Some("7"));
let variant = idx.query_feats_d(
"Calle de Sant Joan, 7, Ciudad",
1,
0,
None,
None,
None,
false,
None,
);
assert_eq!(es_observer_hits(&actual), es_observer_hits(&variant));
assert_eq!(
serde_json::to_value(idx.query(raw, 1)).unwrap(),
es_observer_hits(&actual)
);
}
#[test]
fn es_observer_number_prefilter_and_abbreviation_expansion() {
let rows = [("calle de sant joan", "ciudad", "001", "7")];
let plain = es_observer_fixture("number-plain", &rows, "");
assert!(plain.es_particle_may_have_house("Calle Sant Joan, 7, Ciudad"));
assert!(!plain.es_particle_may_have_house("Calle Sant Joan, Ciudad"));
let expanded = es_observer_fixture("number-expanded", &rows, "numero\tsiete\t7\n");
assert!(expanded.es_particle_may_have_house("Calle Sant Joan, numero siete, Ciudad"));
let _rules = crate::rules::scope(plain.rules);
let raw = "Calle Sant Joan, Ciudad";
let original = plain.query_feats_d(raw, 1, 0, None, None, None, false, None);
assert_eq!(
es_observer_hits(&plain.query_feats_country_variants(raw, 1, None)),
es_observer_hits(&original)
);
}
#[test]
fn es_observer_rule_number_cache_belongs_to_each_index() {
let rows = [("calle ejemplo", "ciudad", "001", "7")];
let plain = es_observer_fixture("cache-plain", &rows, "");
let numbered = es_observer_fixture("cache-numbered", &rows, "numero\tsiete\t7\n");
let raw = "Calle Ejemplo, Ciudad";
for _ in 0..3 {
assert!(!plain.es_particle_may_have_house(raw));
assert!(numbered.es_particle_may_have_house(raw));
}
assert_eq!(
plain.es_particle_rules_may_supply_number.get(),
Some(&false)
);
assert_eq!(
numbered.es_particle_rules_may_supply_number.get(),
Some(&true)
);
}
fn es_observer_reject_precision(precision: &str, numbers: &[&str]) {
let mut rows: Vec<_> = numbers
.iter()
.map(|number| ("calle de sant joan", "ciudad", "001", *number))
.collect();
rows.push(("calle sant joan de deu", "ciudad", "001", "7"));
let idx = es_observer_fixture(precision, &rows, "");
let _rules = crate::rules::scope(idx.rules);
let raw = "Calle Sant Joan, 7, Ciudad";
let original = idx.query_feats_d(raw, 1, 0, None, None, None, false, None);
let variant = idx.query_feats_d(
"Calle de Sant Joan, 7, Ciudad",
1,
0,
None,
None,
None,
false,
None,
);
assert_eq!(variant[0].0.precision, precision);
assert_eq!(variant[0].0.street, "calle de sant joan");
assert_eq!(variant[0].0.commune, "ciudad");
assert_ne!(es_observer_hits(&original), es_observer_hits(&variant));
assert_eq!(
es_observer_hits(&idx.query_feats_country_variants(raw, 1, None)),
es_observer_hits(&original)
);
}
#[test]
fn es_observer_rejects_near_on_same_street() {
es_observer_reject_precision("near", &["8"]);
}
#[test]
fn es_observer_rejects_interpolation_on_same_street() {
es_observer_reject_precision("interp", &["5", "9"]);
}
#[test]
fn es_observer_rejects_street_precision_with_rule_prefilter_open() {
let idx = es_observer_fixture(
"street",
&[
("calle de sant joan", "ciudad", "001", "7"),
("calle sant joan de deu", "ciudad", "001", "8"),
],
"numero\tsiete\t7\n",
);
let _rules = crate::rules::scope(idx.rules);
let raw = "Calle Sant Joan, Ciudad";
assert!(idx.es_particle_may_have_house(raw));
let original = idx.query_feats_d(raw, 1, 0, None, None, None, false, None);
let candidate = idx.query_feats_d(
"Calle de Sant Joan, Ciudad",
1,
0,
None,
None,
None,
false,
None,
);
assert_eq!(candidate[0].0.precision, "street");
assert_eq!(candidate[0].0.street, "calle de sant joan");
assert_eq!(candidate[0].0.commune, "ciudad");
assert_ne!(es_observer_hits(&original), es_observer_hits(&candidate));
assert_eq!(
es_observer_hits(&idx.query_feats_country_variants(raw, 1, None)),
es_observer_hits(&original)
);
}
#[test]
fn es_observer_rejects_house_in_commune_with_shared_prefix() {
let idx = es_observer_fixture(
"commune-prefix",
&[
("calle de sant joan", "ciudad nueva", "002", "7"),
("calle sant joan de deu", "ciudad nueva", "002", "8"),
],
"",
);
let _rules = crate::rules::scope(idx.rules);
let raw = "Calle Sant Joan, 7, Ciudad";
let original = idx.query_feats_d(raw, 1, 0, None, None, None, false, None);
let candidate = idx.query_feats_d(
"Calle de Sant Joan, 7, Ciudad",
1,
0,
None,
None,
None,
false,
None,
);
assert_eq!(candidate[0].0.precision, "house");
assert_eq!(candidate[0].0.street, "calle de sant joan");
assert_eq!(candidate[0].0.commune, "ciudad nueva");
assert_ne!(es_observer_hits(&original), es_observer_hits(&candidate));
assert_eq!(
es_observer_hits(&idx.query_feats_country_variants(raw, 1, None)),
es_observer_hits(&original)
);
}
#[test]
fn es_observer_exact_original_blocks_better_particle_house() {
let idx = es_observer_fixture(
"exact-original",
&[
("calle de sant joan", "ciudad", "001", "7"),
("calle sant joan", "ciudad", "001", "8"),
],
"",
);
let _rules = crate::rules::scope(idx.rules);
let raw = "Calle Sant Joan, 7, Ciudad";
let original = idx.query_feats_d(raw, 1, 0, None, None, None, false, None);
assert_eq!(original[0].0.precision, "near");
assert_eq!(original[0].0.street, "calle sant joan");
assert_eq!(original[0].0.commune, "ciudad");
let candidate = idx.query_feats_d(
"Calle de Sant Joan, 7, Ciudad",
1,
0,
None,
None,
None,
false,
None,
);
assert_eq!(candidate[0].0.precision, "house");
assert_ne!(es_observer_hits(&original), es_observer_hits(&candidate));
assert_eq!(
es_observer_hits(&idx.query_feats_country_variants(raw, 1, None)),
es_observer_hits(&original)
);
}
#[test]
fn es_observer_rejects_house_on_other_street() {
// The exact variant exists in another commune, so the index-wide
// prefilter admits it. Local fuzzy search finds a different street.
let idx = es_observer_fixture(
"other-street",
&[
("calle de sant joan", "otra ciudad", "002", "7"),
("calle de sant joan de deu", "ciudad", "001", "7"),
("calle sant joan de mar", "ciudad", "001", "8"),
],
"",
);
let _rules = crate::rules::scope(idx.rules);
let raw = "Calle Sant Joan, 7, Ciudad";
let original = idx.query_feats_d(raw, 1, 0, None, None, None, false, None);
let candidate = idx.query_feats_d(
"Calle de Sant Joan, 7, Ciudad",
1,
0,
None,
None,
None,
false,
None,
);
assert_eq!(candidate[0].0.precision, "house");
assert_eq!(candidate[0].0.street, "calle de sant joan de deu");
assert_eq!(candidate[0].0.commune, "ciudad");
assert_ne!(es_observer_hits(&original), es_observer_hits(&candidate));
assert_eq!(
es_observer_hits(&idx.query_feats_country_variants(raw, 1, None)),
es_observer_hits(&original)
);
}
fn es_same_point_fixture(
label: &str,
rows: &[(&str, &str, &str, &str)],
abbrev: &str,
) -> Index {
let dir = std::env::temp_dir().join(format!(
"gridpin-es-same-point-{}-{label}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let mut csv_rows: Vec<_> = rows
.iter()
.enumerate()
.map(|(i, (street, city, id, number))| {
format!(
"{street},{id},{city},28001,{number},,{},40.4,{street},{city}",
-3.7 - i as f64 * 0.001
)
})
.collect();
csv_rows.sort_by_key(|row| {
let c: Vec<_> = row.split(',').collect();
(
c[0].to_string(),
c[1].to_string(),
c[4].parse::<u32>().unwrap_or(0),
)
});
let csv = dir.join("rows.csv");
std::fs::write(&csv, format!("nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{}\n",csv_rows.join("\n"))).unwrap();
let rules = dir.join("rules");
std::fs::create_dir_all(&rules).unwrap();
std::fs::write(
rules.join("street_types_latin.tsv"),
"calle\nrue\nvia\nc\nav\navenida\n",
)
.unwrap();
std::fs::write(rules.join("abbrev2.tsv"), abbrev).unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
r#"{"country":"es","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
let bin = dir.join("test.bin");
crate::builder::build(&csv, &bin, None, None, Some(&rules), None, Some(&manifest)).unwrap();
Index::open(&bin).unwrap()
}
#[test]
fn es_same_point_higher_original_keeps_entire_list() {
let idx = es_same_point_fixture(
"higher-original",
&[
("calle ejemplo", "ciudad", "001", "7"),
("calle ejemplo", "ciudad", "002", "7"),
("calle de ejemplo", "otro", "003", "7"),
],
"c\tejemplo\tcalle ejemplo\n",
);
let _rules = crate::rules::scope(idx.rules);
let raw = "C Ejemplo, 7, Ciudad";
let original = idx.query_feats_d(raw, 3, 0, None, None, None, false, None);
assert!(original.len() >= 2);
assert!(!Index::es_particle_original_exact(raw, &original[0].0));
let variant = Index::es_street_particle_variants(raw)
.into_iter()
.find(|v| idx.es_particle_variant_exists(v))
.unwrap();
let candidate = idx.query_feats_d(&variant, 3, 0, None, None, None, false, None);
let first = &candidate[0].0;
assert_eq!(first.precision, "house");
assert_eq!(
Index::es_particle_street_key(&first.street, false),
Index::es_particle_street_key(raw, true)
);
assert!(Index::es_particle_preserves_commune(
raw,
Some(&original[0].0),
first
));
assert_eq!(
(original[0].0.lat, original[0].0.lon),
(first.lat, first.lon)
);
assert_eq!(original[0].0.housenumber, first.housenumber);
assert!(original[0].0.confidence > first.confidence);
let actual = idx.query_feats_country_variants(raw, 3, None);
assert_eq!(es_observer_hits(&actual), es_observer_hits(&original));
assert_eq!(
actual.iter().map(|v| v.1).collect::<Vec<_>>(),
original.iter().map(|v| v.1).collect::<Vec<_>>()
);
}
fn es_same_point_hit(confidence: f32, score: f32) -> Hit {
let mut result = hit("house", confidence, vec![]);
result.lat = 40.4;
result.lon = -3.7;
result.housenumber = Some("1".into());
result.score = score;
result
}
#[test]
fn es_same_point_higher_candidate_wins_despite_lower_score() {
let original = es_same_point_hit(0.6, 10.0);
let candidate = es_same_point_hit(0.94, 5.0);
assert!(!Index::es_particle_keep_original(
Some(&original),
&candidate
));
}
#[test]
fn es_same_point_equal_confidence_keeps_original_despite_lower_score() {
let original = es_same_point_hit(0.94, 5.0);
let candidate = es_same_point_hit(0.94, 10.0);
assert!(Index::es_particle_keep_original(
Some(&original),
&candidate
));
}
#[test]
fn es_same_point_different_house_uses_candidate() {
let original = es_same_point_hit(0.94, 10.0);
let mut candidate = es_same_point_hit(0.6, 5.0);
candidate.housenumber = Some("1A".into());
assert!(!Index::es_particle_keep_original(
Some(&original),
&candidate
));
}
#[test]
fn es_same_point_lat_five_metres_uses_candidate() {
let original = es_same_point_hit(0.94, 10.0);
let mut candidate = es_same_point_hit(0.6, 5.0);
candidate.lat += 0.000045;
assert!(!Index::es_particle_keep_original(
Some(&original),
&candidate
));
}
#[test]
fn es_same_point_lon_five_metres_uses_candidate() {
let original = es_same_point_hit(0.94, 10.0);
let mut candidate = es_same_point_hit(0.6, 5.0);
candidate.lon += 0.000059;
assert!(!Index::es_particle_keep_original(
Some(&original),
&candidate
));
}
#[test]
fn es_same_point_empty_original_uses_candidate() {
let candidate = es_same_point_hit(0.6, 5.0);
assert!(!Index::es_particle_keep_original(None, &candidate));
}
fn city_tail_fixture_rules() -> &'static crate::rules::Rules {
let entries = [
("enabled", "1"),
("regions", "XY XZ"),
("forms", "comma hyphen"),
("postal_digits", "8"),
("postal_split", "5"),
]
.into_iter()
.map(|(k, v)| (23, k.to_owned(), v.to_owned()))
.collect::<Vec<_>>();
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
fn city_tail_witness(
precision: &'static str,
commune: &str,
marker: f64,
) -> (Hit, [f32; N_FEATS]) {
let mut h = hit(precision, 0.7, vec![]);
h.commune = commune.to_owned();
h.lat = marker;
(h, [0.0; N_FEATS])
}
#[test]
fn city_tail_forms_and_lexical_boundaries() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
for (q, expected_retry) in [
(
"Rua Azul, 1, Alto, Vila - XY, 12345678",
"Rua Azul, 1, Vila - XY, 12345678",
),
(
"Rua Azul, 1, Alto, Vila, XY, 12345-678",
"Rua Azul, 1, Vila, XY, 12345-678",
),
("Rua Azul, S/N, Alto, Vila - XY", "Rua Azul, S/N, Vila - XY"),
("Rua Azul, 1, Alto, Vila, XZ", "Rua Azul, 1, Vila, XZ"),
] {
let tail = city_tail(q).unwrap();
assert_eq!(tail.city, "vila");
assert_eq!(tail.retry.as_deref(), Some(expected_retry), "{q}");
}
for q in [
"Rua Azul, 1, Alto, Vila - ZZ",
"Rua Azul, 1, Vila",
"Rua Azul, 1, 12345678, XY",
"Rua Azul, 1, s/n - Vila, XY",
"Rua Azul, 1, Vila - XY, extra",
"Rua Azul, 1, Vila - XY, 123456789",
] {
assert!(city_tail(q).is_none(), "{q}");
}
assert!(city_tail("Rua Azul, 1, Vila - XY").unwrap().retry.is_none());
assert!(city_tail("Rua Azul, complement, Alto, Vila - XY")
.unwrap()
.retry
.is_none());
}
#[test]
fn city_tail_retry_rejects_extra_segments() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
for q in [
"Rua Azul, 1, Bloco B, Alto, Vila - XY",
"Rua Azul, 1, Bloco B, Apto 2, Alto, Vila - XY",
] {
assert!(city_tail(q).unwrap().retry.is_none(), "{q}");
}
}
#[test]
fn city_tail_retry_rejects_empty_street() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
assert!(city_tail(", 1, Alto, Vila - XY").unwrap().retry.is_none());
}
#[test]
fn city_tail_retry_rejects_empty_district() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
assert!(city_tail("Rua Azul, 1, , Vila - XY")
.unwrap()
.retry
.is_none());
}
#[test]
fn city_tail_retry_accepts_sn_but_not_sna() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
assert_eq!(
city_tail("Rua Azul, SN, Alto, Vila - XY")
.unwrap()
.retry
.as_deref(),
Some("Rua Azul, SN, Vila - XY")
);
assert!(city_tail("Rua Azul, SNA, Alto, Vila - XY")
.unwrap()
.retry
.is_none());
}
#[test]
fn city_tail_absent_data_disables_parser() {
let _scope = crate::rules::scope(crate::rules::defaults_static());
assert!(city_tail("Rua Azul, 1, Alto, Vila - XY, 12345678").is_none());
}
// Tail grammar with the region and the postal code in one segment ("Springfield, IL 62701").
// Two-letter regions, five postal digits, optional four-digit extension; nothing here
// names a country, the form is enabled by the sheet's `forms` key alone.
fn region_postal_fixture_rules(
forms: &str,
extension: Option<&str>,
) -> &'static crate::rules::Rules {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "IL CA NY".to_owned()),
(23, "forms".to_owned(), forms.to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "0".to_owned()),
];
if let Some(extension) = extension {
entries.push((23, "postal_extension".to_owned(), extension.to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn region_postal_tail_accepts_region_postal_region_alone_and_case() {
let _scope = crate::rules::scope(region_postal_fixture_rules("region_postal", Some("4")));
for q in [
"Main St 1, Springfield, IL 62701",
"Main St 1, Springfield, IL 62701-1234",
"Main St 1, Springfield, il 62701",
"Main St 1, Springfield, IL 62701",
"Main St 1, Springfield, IL",
"Main St 1, Springfield, IL, 62701",
] {
let tail = city_tail(q).unwrap_or_else(|| panic!("{q}"));
assert_eq!(tail.city, "springfield", "{q}");
let expected = match q {
"Main St 1, Springfield, IL" => None, // region alone: the comma form, no retry
"Main St 1, Springfield, IL, 62701" => Some("Main St 1, Springfield, 62701"), // postal segment of its own
"Main St 1, Springfield, IL 62701-1234" => {
Some("Main St 1, Springfield, 62701-1234")
}
_ => Some("Main St 1, Springfield, 62701"),
};
assert_eq!(tail.retry.as_deref(), expected, "{q}");
}
let tail = city_tail("Main St, 1, Downtown, Springfield, IL 62701-1234").unwrap();
assert_eq!(tail.city, "springfield");
assert_eq!(
tail.retry.as_deref(),
Some("Main St, 1, Springfield, IL 62701-1234")
);
}
// The `postal_city` form ("…, Zona Centro, 44100 Guadalajara, Jal.", Mexico): the city segment
// opens with the postal code. Regions JAL and CMX, five postal digits.
fn postal_city_fixture_rules(forms: &str) -> &'static crate::rules::Rules {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "JAL CMX".to_owned()),
(
23,
"region_names".to_owned(),
"jalisco=JAL;cdmx=CMX".to_owned(),
),
(23, "forms".to_owned(), forms.to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
];
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn a_region_named_with_the_country_word_keeps_that_word() {
// "…, 06700 Cuauhtémoc, Ciudad de México": the region name ends with "México", a country
// word of the sheet; stripped, "Ciudad de" is no region and the tail is not read at all
// (Mexico, 01.11.2026). A country word after a region code still goes.
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX MEX".to_owned()),
(
23,
"region_names".to_owned(),
"ciudad de mexico=CMX;cdmx=CMX;estado de mexico=MEX".to_owned(),
),
(
23,
"forms".to_owned(),
"comma region_postal postal_city".to_owned(),
),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(11, "mexico".to_owned(), String::new()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
for (q, region) in [
(
"Tonalá 43, Col. Roma, 06700 Cuauhtémoc, Ciudad de México",
"CMX",
),
("Juárez 100, 50000 Toluca, Estado de México", "MEX"),
("Tonalá 43, 06700 Cuauhtémoc, CDMX México", "CMX"),
] {
let tail = city_tail(q).unwrap_or_else(|| panic!("{q}"));
assert_eq!(tail.region.as_deref(), Some(region), "{q}");
assert!(tail.postal_city, "{q}");
}
}
#[test]
fn postal_city_regionless_reading_answers_only_an_exact_street_house_inside_the_code() {
// Called directly: on the fixture the main path answers these queries by itself (6.14).
let mut idx = forward_postcode_index_for_country(
"postal-city-regionless",
"sonora,001,cuauhtemoc,06100,06100,206,,-99.170,19.412,Sonora,Cuauhtémoc\n\
tonala,001,cuauhtemoc,06700,06700,43,,-99.160,19.410,Tonalá,Cuauhtémoc\n\
tonala,001,cuauhtemoc,06700,06700,49,,-99.161,19.411,Tonalá,Cuauhtémoc\n",
"xx",
);
idx.rules = postal_city_fixture_rules("comma region_postal postal_city");
let _scope = crate::rules::scope(idx.rules);
let read = |q: &str| {
let tail = city_tail(q).unwrap_or_else(|| panic!("{q}"));
idx.postal_city_regionless(&tail, 1, None)
.first()
.map(|(h, _)| (h.street.clone(), h.housenumber.clone(), h.precision))
};
assert_eq!(
read("Tonalá 43, Col. Roma, 06700 Cuauhtémoc, CDMX"),
Some(("Tonalá".to_owned(), Some("43".to_owned()), "house"))
);
// another code of the same city: nothing
assert_eq!(read("Tonalá 43, Col. Roma, 06760 Cuauhtémoc, CDMX"), None);
// a number far past the street's houses reaches only a neighbour: nothing
assert_eq!(read("Tonalá 4100, Col. Roma, 06700 Cuauhtémoc, CDMX"), None);
// a street the sheet only matches loosely: nothing
assert_eq!(read("Tonalán 43, Col. Roma, 06700 Cuauhtémoc, CDMX"), None);
// no code in the city segment: no postal city, no reading
assert_eq!(read("Tonalá 43, Col. Roma, Cuauhtémoc, CDMX"), None);
// the code beside the region, not in the city segment: still no postal city
assert_eq!(read("Tonalá 43, Cuauhtémoc, CMX 06700"), None);
}
#[test]
fn postal_city_tail_sets_the_code_aside_and_drops_inner_segments_from_the_regionless_reading() {
let _scope =
crate::rules::scope(postal_city_fixture_rules("comma region_postal postal_city"));
for (q, city, without_region) in [
(
"Calle Morelos 108, Zona Centro, 44100 Guadalajara, Jal.",
"guadalajara",
"Calle Morelos 108, Guadalajara, 44100",
),
(
"Seminario 16, Centro, Cuauhtémoc, 06060 Ciudad de México, CDMX",
"ciudad de mexico",
"Seminario 16, Ciudad de México, 06060",
),
(
"Calle Morelos 108, 44100 Guadalajara, Jalisco",
"guadalajara",
"Calle Morelos 108, Guadalajara, 44100",
),
] {
let tail = city_tail(q).unwrap_or_else(|| panic!("{q}"));
assert_eq!(tail.city, city, "{q}");
assert!(tail.postal_city, "{q}");
assert_eq!(tail.without_region, without_region, "{q}");
assert_eq!(
tail.without_city
.as_deref()
.map(|w| w.ends_with(", 44100") || w.ends_with(", 06060")),
Some(true),
"{q}"
);
}
// A city segment with no code keeps the inner segments and is no postal_city tail.
let tail = city_tail("Calle Morelos 108, Zona Centro, Guadalajara, Jal.").unwrap();
assert!(!tail.postal_city);
assert_eq!(
tail.without_region,
"Calle Morelos 108, Zona Centro, Guadalajara"
);
// Near misses: four digits and six digits are no postal code of the sheet.
assert!(city_tail("Calle Morelos 108, Zona Centro, 4410 Guadalajara, Jal.").is_none());
assert!(city_tail("Calle Morelos 108, Zona Centro, 441000 Guadalajara, Jal.").is_none());
// Without the form the segment is no city (digits), as before.
let _scope = crate::rules::scope(postal_city_fixture_rules("comma region_postal"));
assert!(city_tail("Calle Morelos 108, Zona Centro, 44100 Guadalajara, Jal.").is_none());
}
#[test]
fn bare_street_postal_variants_read_the_street_with_the_code_bare_and_typed() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "JAL".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(
23,
"bare_street_types".to_owned(),
"calle avenida".to_owned(),
),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
assert_eq!(
bare_street_postal_variants("Independencia 684, Centro Histórico, 44100"),
[
"Independencia 684, 44100",
"calle Independencia 684, 44100",
"avenida Independencia 684, 44100",
]
);
// No inner segment: nothing to drop; a street that opens with a type is not typed twice.
assert_eq!(
bare_street_postal_variants("Calle Abasolo 508, 26000"),
["avenida Calle Abasolo 508, 26000"]
);
// Near misses: a city after the code, four digits, a code only.
assert!(bare_street_postal_variants("Abasolo 508, Centro, Piedras Negras").is_empty());
assert!(bare_street_postal_variants("Seminario 16, Centro, 6060").is_empty());
assert!(bare_street_postal_variants("44100").is_empty());
// A sheet that declares no types reads nothing new.
let _scope = crate::rules::scope(postal_city_fixture_rules("comma"));
assert!(bare_street_postal_variants("Independencia 684, Centro, 44100").is_empty());
}
#[test]
fn one_edit_apart_counts_a_change_an_insertion_a_drop_and_a_swap_of_neighbours() {
for (a, b) in [
("moneda", "omneda"),
("moneda", "moneta"),
("moneda", "monedas"),
("moneda", "moned"),
("regina", "regnia"),
] {
assert!(one_edit_apart(a, b), "{a} {b}");
assert!(one_edit_apart(b, a), "{b} {a}");
}
for (a, b) in [
("moneda", "moneda"),
("moneda", "omndea"),
("moneda", "mondea x"),
("moneda", "adenom"),
("moneda", "monedaxx"),
] {
assert!(!one_edit_apart(a, b), "{a} {b}");
}
}
#[test]
fn postal_street_near_code_takes_the_one_street_one_edit_away_under_the_same_first_digits() {
let fixture = |case: &str, extra: &str| {
let mut idx = forward_postcode_index_for_country(
case,
&format!(
"calle moneda,001,cuauhtemoc,06060,06060,4,,-99.130,19.434,Calle Moneda,Cuauhtémoc\n\
{extra}\
calle pino,001,cuauhtemoc,06060,06060,9,,-99.131,19.434,Calle Pino,Cuauhtémoc\n"
),
"xx",
);
idx.rules = postal_suffix_rules(true, true);
idx
};
let read = |idx: &Index, q: &str| {
let _scope = crate::rules::scope(idx.rules);
idx.postal_street_suffix(q)
.map(|(h, _)| (h.street.clone(), h.housenumber.clone()))
};
let moneda = Some(("Calle Moneda".to_owned(), Some("4".to_owned())));
let idx = fixture("near-edit", "");
// a swap of neighbours, the code of a neighbour under the same first three digits
assert_eq!(read(&idx, "Omneda 4, Centro, 6000"), moneda);
// the neighbour code is below the one written
assert_eq!(read(&idx, "Omneda 4, Centro, 06099"), moneda);
// the same name under the neighbour code
assert_eq!(read(&idx, "C. Moneda 4, Centro, 06000"), moneda);
// other first digits, two edits, a short name with an edit, a number the street lacks: nothing
assert_eq!(read(&idx, "Omneda 4, Centro, 06100"), None);
assert_eq!(read(&idx, "Omndea 4, Centro, 06000"), None);
assert_eq!(read(&idx, "Pnio 9, Centro, 06000"), None);
assert_eq!(read(&idx, "Omneda 6, Centro, 06000"), None);
// the short name itself still answers
assert_eq!(
read(&idx, "Pino 9, Centro, 06000"),
Some(("Calle Pino".to_owned(), Some("9".to_owned())))
);
// two different streets one edit away: nothing
let two = fixture(
"near-edit-two",
"calle moneta,001,cuauhtemoc,06060,06060,4,,-99.1301,19.4341,Calle Moneta,Cuauhtémoc\n",
);
assert_eq!(read(&two, "Monexa 4, Centro, 06000"), None);
// without postal_near_digits only the exact code is read
let mut exact = fixture("near-edit-off", "");
exact.rules = postal_suffix_rules(true, false);
assert_eq!(read(&exact, "Omneda 4, Centro, 06000"), None);
}
#[test]
fn postal_street_without_number_answers_the_one_street_of_the_code_as_a_street() {
let rows = |extra: &str| {
format!(
"plaza de la republica,001,cuauhtemoc,06030,06030,1,,-99.154,19.436,Plaza de la República,Cuauhtémoc\n\
plaza de la republica,002,otra,64000,64000,1,,-100.3,25.67,Plaza de la República,Otra\n\
{extra}"
)
};
let rules = |marks: bool| {
let mut all = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "postal_street_suffix".to_owned(), "1".to_owned()),
(16, "plaza".to_owned(), String::new()),
(16, "privada".to_owned(), String::new()),
(16, "calle".to_owned(), String::new()),
];
if marks {
all.push((23, "no_number_marks".to_owned(), "s/n sn".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&all))
};
let read = |idx: &Index, q: &str| {
let _scope = crate::rules::scope(idx.rules);
idx.postal_street_without_number(q)
.map(|(h, _)| (h.street.clone(), h.precision, h.postcode.clone()))
};
let mut idx = forward_postcode_index_for_country("sn-one", &rows(""), "xx");
idx.rules = rules(true);
let street = Some((
"Plaza de la República".to_owned(),
"street",
"06030".to_owned(),
));
assert_eq!(
read(&idx, "Plaza de la República s/n, Col. Tabacalera, 6030"),
street
);
assert_eq!(
read(&idx, "Plaza de la República SN, Col. Tabacalera, 06030"),
street
);
// a number written, no mark, another code, a name not the street's: nothing
assert_eq!(
read(&idx, "Plaza de la República 3, Col. Tabacalera, 06030"),
None
);
assert_eq!(
read(&idx, "Plaza de la República, Col. Tabacalera, 06030"),
None
);
assert_eq!(
read(&idx, "Plaza de la República s/n, Col. Tabacalera, 06031"),
None
);
assert_eq!(
read(&idx, "Plaza República s/n, Col. Tabacalera, 06030"),
None
);
// two different streets of that name inside the code: nothing
let mut two = forward_postcode_index_for_country(
"sn-two",
&rows("privada de la republica,001,cuauhtemoc,06030,06030,1,,-99.155,19.437,Privada de la República,Cuauhtémoc\n"),
"xx",
);
two.rules = rules(true);
assert_eq!(
read(&two, "Plaza de la República s/n, Col. Tabacalera, 06030"),
None
);
// a number inside the name is part of it ("20 de Noviembre")
let mut dated = forward_postcode_index_for_country(
"sn-dated",
"calle 20 de noviembre,001,durango,28510,28510,5,,-103.7,19.2,Calle 20 de Noviembre,Durango\n",
"xx",
);
dated.rules = rules(true);
assert_eq!(
read(&dated, "Calle 20 de Noviembre s/n, Centro, 28510"),
Some((
"Calle 20 de Noviembre".to_owned(),
"street",
"28510".to_owned()
))
);
// without the marks key: nothing
idx.rules = rules(false);
assert_eq!(
read(&idx, "Plaza de la República s/n, Col. Tabacalera, 6030"),
None
);
}
#[test]
fn postal_namesake_swap_takes_the_street_of_the_own_code_over_a_namesake() {
let rows = |extra: &str| {
format!(
"calle benito juarez,001,alvaro obregon,01000,01000,9,,-99.190,19.346,Calle Benito Juárez,Álvaro Obregón\n\
calle benito juarez,002,otra,01710,01710,9,,-99.230,19.380,Calle Benito Juárez,Otra\n\
{extra}"
)
};
let read = |idx: &Index, q: &str, answered: &str| {
let _scope = crate::rules::scope(idx.rules);
let far = idx.query("Calle Benito Juárez 9, Otra", 1)[0].clone();
assert_eq!(far.postcode, "01710");
let mut hit = far;
hit.postcode = answered.to_owned();
idx.postal_namesake_swap(q, &hit)
.map(|(h, _)| (h.postcode.clone(), h.housenumber.clone(), h.precision))
};
let mut idx = forward_postcode_index_for_country("namesake", &rows(""), "xx");
idx.rules = postal_suffix_rules(true, true);
let q = "Benito Juárez 9 A, Col. San Ángel, 01000 Álvaro Obregón";
assert_eq!(
read(&idx, q, "01710"),
Some(("01000".to_owned(), Some("9".to_owned()), "house"))
);
// the answer already under the first three digits of the code written: kept
assert_eq!(read(&idx, q, "01020"), None);
// the own street lacks the number and its neighbour is far: kept
assert_eq!(
read(
&idx,
"Benito Juárez 90, Col. San Ángel, 01000 Álvaro Obregón",
"01710"
),
None
);
// two different streets of that name under the digits: kept
let mut two = forward_postcode_index_for_country(
"namesake-two",
&rows("privada benito juarez,001,alvaro obregon,01090,01090,9,,-99.191,19.347,Privada Benito Juárez,Álvaro Obregón\n"),
"xx",
);
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(
23,
"bare_street_types".to_owned(),
"calle avenida".to_owned(),
),
(23, "postal_street_suffix".to_owned(), "1".to_owned()),
(23, "postal_near_digits".to_owned(), "3".to_owned()),
(16, "calle".to_owned(), String::new()),
];
entries.push((16, "privada".to_owned(), String::new()));
two.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
assert_eq!(read(&two, q, "01710"), None);
// without postal_near_digits: kept
idx.rules = postal_suffix_rules(true, false);
assert_eq!(read(&idx, q, "01710"), None);
}
#[test]
fn postal_street_suffix_takes_a_close_neighbour_on_the_one_street_of_the_exact_code() {
let mut idx = forward_postcode_index_for_country(
"near-number",
"calle hidalgo,001,tepatitlan,47600,47600,180,,-102.760,20.810,Calle Hidalgo,Tepatitlán\n\
calle hidalgo,001,tepatitlan,47600,47600,185,,-102.761,20.811,Calle Hidalgo,Tepatitlán\n",
"xx",
);
idx.rules = postal_suffix_rules(true, true);
let read = |idx: &Index, q: &str| {
let _scope = crate::rules::scope(idx.rules);
idx.postal_street_suffix(q)
.map(|(h, _)| (h.housenumber.clone(), h.precision))
};
// five numbers past the last house: its neighbour
assert_eq!(
read(&idx, "Hidalgo 190, Centro, 47600"),
Some((Some("185".to_owned()), "near"))
);
// ten numbers is the limit; eleven is too far
assert!(read(&idx, "Hidalgo 195, Centro, 47600").is_some());
assert_eq!(read(&idx, "Hidalgo 196, Centro, 47600"), None);
// another code (the same first digits): only the exact code takes a neighbour
assert_eq!(read(&idx, "Hidalgo 190, Centro, 47610"), None);
}
fn postal_suffix_rules(suffix: bool, near: bool) -> &'static crate::rules::Rules {
let mut all = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(
23,
"bare_street_types".to_owned(),
"calle avenida".to_owned(),
),
(24, "c".to_owned(), "calle".to_owned()),
(16, "calle".to_owned(), String::new()),
];
if suffix {
all.push((23, "postal_street_suffix".to_owned(), "1".to_owned()));
}
if near {
all.push((23, "postal_near_digits".to_owned(), "3".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&all))
}
#[test]
fn postal_street_suffix_takes_the_one_street_of_the_code_ending_with_the_name_written() {
let rows = |second: &str| {
format!(
"calle james sullivan,001,cuauhtemoc,06470,06470,43,,-99.161,19.433,Calle James Sullivan,Cuauhtémoc\n\
{second}\
calle sullivan,002,otra,77535,77535,43,,-86.8,21.1,Calle Sullivan,Otra\n"
)
};
let rules = |on: bool| {
let mut all = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(
23,
"bare_street_types".to_owned(),
"calle avenida".to_owned(),
),
(24, "c".to_owned(), "calle".to_owned()),
];
if on {
all.push((23, "postal_street_suffix".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&all))
};
let mut idx = forward_postcode_index_for_country("suffix-one", &rows(""), "xx");
idx.rules = rules(true);
let read = |idx: &Index, q: &str| {
let _scope = crate::rules::scope(idx.rules);
idx.postal_street_suffix(q)
.map(|(h, _)| (h.street.clone(), h.housenumber.clone(), h.postcode.clone()))
};
let house = Some((
"Calle James Sullivan".to_owned(),
Some("43".to_owned()),
"06470".to_owned(),
));
assert_eq!(read(&idx, "Sullivan 43, Col. San Rafael, 6470"), house);
assert_eq!(read(&idx, "C. Sullivan 43, Col. San Rafael, 06470"), house);
// another code, a number the street does not have, a name the street does not end with: nothing
assert_eq!(read(&idx, "Sullivan 43, Col. San Rafael, 06480"), None);
assert_eq!(read(&idx, "Sullivan 45, Col. San Rafael, 06470"), None);
assert_eq!(read(&idx, "James 43, Col. San Rafael, 06470"), None);
// the whole name with its type answers the same street
assert_eq!(read(&idx, "Calle James Sullivan 43, 06470"), house);
// two different streets of the code end with the name: nothing
let mut two = forward_postcode_index_for_country(
"suffix-two",
&rows("calle maria sullivan,001,cuauhtemoc,06470,06470,43,,-99.1611,19.4331,Calle María Sullivan,Cuauhtémoc\n"),
"xx",
);
two.rules = rules(true);
assert_eq!(read(&two, "Sullivan 43, Col. San Rafael, 06470"), None);
// a name ending with the letters but not the word: nothing
let mut glued = forward_postcode_index_for_country(
"suffix-word",
"calle osullivan,001,cuauhtemoc,06470,06470,43,,-99.161,19.433,Calle Osullivan,Cuauhtémoc\n",
"xx",
);
glued.rules = rules(true);
assert_eq!(read(&glued, "Sullivan 43, Col. San Rafael, 06470"), None);
// without the key: nothing
idx.rules = rules(false);
assert_eq!(read(&idx, "Sullivan 43, Col. San Rafael, 06470"), None);
}
#[test]
fn bare_street_postal_variants_spell_out_a_short_type_of_the_sheet() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(
23,
"bare_street_types".to_owned(),
"calle avenida".to_owned(),
),
(24, "av".to_owned(), "avenida".to_owned()),
(24, "blvd".to_owned(), "boulevard".to_owned()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
assert_eq!(
bare_street_postal_variants("Av. Chapultepec 420, Col. Roma Norte, 06700"),
vec![
"Av. Chapultepec 420, 06700".to_owned(),
"avenida Chapultepec 420, 06700".to_owned()
]
);
assert_eq!(
bare_street_postal_variants("Av Chapultepec 420, 06700"),
vec!["avenida Chapultepec 420, 06700".to_owned()]
);
// a short word that spells no type of `bare_street_types` keeps the typed variants
assert_eq!(
bare_street_postal_variants("Blvd. Reyes Heroles 302, 50110"),
vec![
"calle Blvd. Reyes Heroles 302, 50110".to_owned(),
"avenida Blvd. Reyes Heroles 302, 50110".to_owned()
]
);
}
#[test]
fn bare_street_near_code_takes_an_exact_house_under_a_code_with_the_same_first_digits() {
// Called directly (6.14): "Moneda 4, Centro, 06000" while the sheet keeps the street under 06060.
let mut idx = forward_postcode_index_for_country(
"near-code",
"calle moneda,001,cuauhtemoc,06060,06060,4,,-99.130,19.434,Calle Moneda,Cuauhtémoc\n\
calle moneda,001,cuauhtemoc,06060,06060,8,,-99.131,19.434,Calle Moneda,Cuauhtémoc\n",
"xx",
);
let rules = |near: Option<&str>| {
let mut all = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "bare_street_types".to_owned(), "calle".to_owned()),
];
if let Some(n) = near {
all.push((23, "postal_near_digits".to_owned(), n.to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&all))
};
idx.rules = rules(Some("3"));
let read = |idx: &Index, q: &str| {
let _scope = crate::rules::scope(idx.rules);
idx.bare_street_near_code(q, &bare_street_postal_variants(q), 1, None)
.first()
.map(|(h, _)| (h.housenumber.clone(), h.precision, h.postcode.clone()))
};
assert_eq!(
read(&idx, "Moneda 4, Centro, 06000"),
Some((Some("4".to_owned()), "house", "06060".to_owned()))
);
// the first three digits differ: nothing
assert_eq!(read(&idx, "Moneda 4, Centro, 06100"), None);
// a number far past the street's houses reaches only a neighbour: nothing
assert_eq!(read(&idx, "Moneda 4100, Centro, 06000"), None);
// a street the sheet only matches loosely: nothing
assert_eq!(read(&idx, "Monedas 4, Centro, 06000"), None);
// four digits asked: 0600 is not 0606
idx.rules = rules(Some("4"));
assert_eq!(read(&idx, "Moneda 4, Centro, 06000"), None);
// without the key: nothing
idx.rules = rules(None);
assert_eq!(read(&idx, "Moneda 4, Centro, 06000"), None);
}
#[test]
fn restore_commas_splits_after_the_house_number_and_before_the_code() {
let rules = |on: bool| {
let mut all = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
];
if on {
all.push((23, "commaless_restore".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&all))
};
let _scope = crate::rules::scope(rules(true));
for (q, want) in [
(
"2ª Oriente Norte 236 Centro 29000",
Some("2ª Oriente Norte 236, Centro, 29000"),
),
(
"Av. 20 de Noviembre s/n Barrio El Cerrillo 29220",
Some("Av. 20 de Noviembre s/n, Barrio El Cerrillo, 29220"),
),
(
"Calle 86 B 499A Centro 97000",
Some("Calle 86 B 499A, Centro, 97000"),
),
(
"Academia 13 Centro Histórico 6060",
Some("Academia 13, Centro Histórico, 6060"),
),
// the number ends the street part: only the code is set apart
("Pino Suárez 30 06060", Some("Pino Suárez 30, 06060")),
(
"Real de Asientos Aguascalientes 20726",
Some("Real de Asientos Aguascalientes, 20726"),
),
// a comma already written, a code too long or too short, one word only: kept
("Pino Suárez 30, Centro 06060", None),
("Pino Suárez 30 Centro 606", None),
("Pino Suárez 30 Centro 060600", None),
("Centro 06060", None),
// the first word is never the house number, nor a number before "de"
("5 de Mayo Centro 41900", Some("5 de Mayo Centro, 41900")),
(
"Calle 5 de Mayo 12 Centro 41900",
Some("Calle 5 de Mayo 12, Centro, 41900"),
),
(
"12 Centro Histórico 41900",
Some("12 Centro Histórico, 41900"),
),
(
"Av. 16 de Septiembre Centro 41900",
Some("Av. 16 de Septiembre Centro, 41900"),
),
] {
assert_eq!(restore_commas(q).as_deref(), want, "{q}");
}
let _scope = crate::rules::scope(rules(false));
assert_eq!(restore_commas("2ª Oriente Norte 236 Centro 29000"), None);
}
#[test]
fn strip_number_marks_drops_the_mark_and_the_postal_prefix_only_before_digits() {
let rules = |entries: &[(&str, &str)]| {
let mut all = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
];
all.extend(
entries
.iter()
.map(|(k, v)| (23, (*k).to_owned(), (*v).to_owned())),
);
crate::rules::from_section(&crate::rules::serialize_entries(&all))
};
let _scope = crate::rules::scope(rules(&[("number_mark", "#"), ("postal_prefix", "cp")]));
for (q, want) in [
(
"Abasolo #508, Centro, 26000",
Some("Abasolo 508, Centro, 26000"),
),
(
"5 de Mayo núm. # 5, Centro, 41900",
Some("5 de Mayo núm. 5, Centro, 41900"),
),
(
"2a. Av. Oriente, Centro, C.P. 30450",
Some("2a. Av. Oriente, Centro, 30450"),
),
(
"Juárez 1, CP 06700 Cuauhtémoc",
Some("Juárez 1, 06700 Cuauhtémoc"),
),
("Juárez 1, c. p. 06700", Some("Juárez 1, 06700")),
("Juárez 1, C.P.06700", Some("Juárez 1, 06700")),
// not before digits: kept
("Local #A, Centro, 26000", None),
("Juárez 1, C.P. Centro", None),
// the prefix inside a word, or a longer word: kept
("Calle Cpo 1, 26000", None),
("Calle CPU 12, 26000", None),
("Calle Marcp 12, 26000", None),
] {
assert_eq!(strip_number_marks(q).as_deref(), want, "{q}");
}
// without the keys nothing is touched
let _scope = crate::rules::scope(rules(&[]));
assert_eq!(strip_number_marks("Abasolo #508, Centro, C.P. 26000"), None);
// each key alone does its own part only
let _scope = crate::rules::scope(rules(&[("number_mark", "#")]));
assert_eq!(
strip_number_marks("Abasolo #508, C.P. 26000").as_deref(),
Some("Abasolo 508, C.P. 26000")
);
let _scope = crate::rules::scope(rules(&[("postal_prefix", "cp")]));
assert_eq!(
strip_number_marks("Abasolo #508, C.P. 26000").as_deref(),
Some("Abasolo #508, 26000")
);
}
#[test]
fn pad_short_postal_restores_the_leading_zero_in_the_last_two_segments() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "CMX".to_owned()),
(23, "forms".to_owned(), "comma".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "postal_pad_zero".to_owned(), "1".to_owned()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
assert_eq!(
pad_short_postal("Academia 13, Centro Histórico, 6060").as_deref(),
Some("Academia 13, Centro Histórico, 06060")
);
assert_eq!(
pad_short_postal("Niza 23-A, 6600 Cuauhtémoc, Ciudad de México").as_deref(),
Some("Niza 23-A, 06600 Cuauhtémoc, Ciudad de México")
);
// Near misses: a house number in the street segment, five digits, three digits, digits glued to
// a letter, and a single segment stay as written.
assert!(pad_short_postal("Calle 1234, Centro, 06060").is_none());
assert!(pad_short_postal("Academia 13, Centro, 06060").is_none());
assert!(pad_short_postal("Academia 13, Centro, 606").is_none());
assert!(pad_short_postal("Academia 13, Centro, 6060A").is_none());
assert!(pad_short_postal("6060").is_none());
// Only the last two segments: an earlier segment opening with four digits is part of the
// address; a code followed by digits is no code before a name.
assert!(pad_short_postal("Calle 5 Norte 12, 1234 Interior, Centro, 06060").is_none());
assert!(pad_short_postal("Academia 13, Centro, 6060 2B").is_none());
// A sheet without the key keeps the code as written.
let _scope = crate::rules::scope(postal_city_fixture_rules("comma"));
assert!(pad_short_postal("Academia 13, Centro Histórico, 6060").is_none());
}
#[test]
fn region_postal_tail_reads_a_city_glued_to_its_region() {
let _scope = crate::rules::scope(region_postal_fixture_rules("region_postal", Some("4")));
// The comma between city and region is missing: the segment splits at the region.
for (q, retry) in [
(
"Main St 1, Springfield IL 62701",
"Main St 1, Springfield, 62701",
),
(
"Main St 1, Springfield IL 62701-1234",
"Main St 1, Springfield, 62701-1234",
),
(
"Main St 1, NEW SPRINGFIELD IL 62701",
"Main St 1, NEW SPRINGFIELD, 62701",
),
] {
let tail = city_tail(q).unwrap_or_else(|| panic!("{q}"));
assert!(tail.city.ends_with("springfield"), "{q}: {}", tail.city);
assert_eq!(tail.region.as_deref(), Some("IL"), "{q}");
assert_eq!(tail.retry.as_deref(), Some(retry), "{q}");
}
let tail = city_tail("Main St 1, Springfield IL").unwrap();
assert_eq!(
(tail.city.as_str(), tail.region.as_deref()),
("springfield", Some("IL"))
);
// Nothing before the region, or no street segment before the city: not a glued tail.
assert!(city_tail("Main St 1, IL 62701").is_none_or(|t| t.city != "main st 1"));
assert!(city_tail("Springfield IL 62701").is_none());
// A word that is no region keeps the segment whole.
assert!(city_tail("Main St 1, Springfield Heights 62701").is_none());
// The comma-only form does not glue.
let _scope = crate::rules::scope(region_postal_fixture_rules("comma", None));
assert!(city_tail("Main St 1, Springfield IL 62701").is_none());
}
/// The Canadian pack (rules/ca/city_tail.tsv, inlined; where the file exists it must match):
/// `postal_pattern` "A9A 9A9" reads the alphanumeric code with or without its space, in the region
/// segment, glued to the city or as a segment of its own, and sets it aside -- the retry never
/// carries it, because the sheet keeps no numeric postcode for it (E1.5, 28.10.2026).
fn ca_city_tail_rules() -> &'static crate::rules::Rules {
let tsv: String = [
"# Generated Canadian additions from ca_overlay.json.\n",
"city_first\t1\n",
"direction_trailing\tn s e w ne nw se sw o\n",
"enabled\t1\n",
"forms\tcomma region_postal\n",
"fuzzy_short_forms\t1\n",
"glue_road_numbers\t1\n",
"homonym_prominence\t1\n",
"interp_max_gap\t400\n",
"interp_max_km\t2.0\n",
"junk_tail\tnear next behind opposite across beside tel phone fax suite apt unit floor room rm bldg basement app bureau\n",
"number_first_types\thwy\n",
"postal_digits\t6\n",
"postal_pattern\tA9A 9A9\n",
"postal_split\t3\n",
"quadrant_suffixes\tNW NE SW SE\n",
"region_names\talberta=AB;british columbia=BC;colombie britannique=BC;ile du prince edouard=PE;manitoba=MB;new brunswick=NB;newfoundland=NL;newfoundland and labrador=NL;northwest territories=NT;nouveau brunswick=NB;nouvelle ecosse=NS;nova scotia=NS;nunavut=NU;ontario=ON;prince edward island=PE;quebec=QC;saskatchewan=SK;terre neuve et labrador=NL;territoires du nord ouest=NT;yukon=YT\n",
"regions\tAB BC MB NB NL NS NT NU ON PE QC SK YT\n",
"saint_communes\t1\n",
"street_type_last\t1\n",
"type_first_siblings\t1\n",
"unit_hyphen\t1\n",
]
.concat();
let pack = concat!(env!("CARGO_MANIFEST_DIR"), "/../rules/ca/city_tail.tsv");
if let Ok(file) = std::fs::read_to_string(pack) {
assert_eq!(file, tsv, "inline copy of rules/ca/city_tail.tsv is stale");
}
let entries: Vec<(u8, String, String)> = tsv
.lines()
.filter(|l| !l.starts_with('#') && !l.trim().is_empty())
.map(|l| {
let (k, v) = l.split_once('\t').unwrap();
(23, k.to_owned(), v.to_owned())
})
.collect();
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn ca_postal_pattern_reads_spaced_glued_and_lower_case_codes() {
let _scope = crate::rules::scope(ca_city_tail_rules());
let cfg = &crate::rules::rules().city_tail;
assert_eq!(split_region_postal(cfg, "ON M5X 1A9"), Some(("ON", None)));
assert_eq!(split_region_postal(cfg, "qc h2x1y4"), Some(("qc", None)));
assert_eq!(
split_region_postal(cfg, "Ontario M5X 1A9"),
Some(("Ontario", None))
);
assert!(pattern_postal(cfg, "K1A 0B1") && pattern_postal(cfg, "k1a0b1"));
}
#[test]
fn ca_postal_pattern_rejects_near_misses() {
// every position of the shape: a digit where a letter is due, a letter where a digit is
// due, one character short or long, a US ZIP (near-misses, not absence)
let _scope = crate::rules::scope(ca_city_tail_rules());
let cfg = &crate::rules::rules().city_tail;
for bad in [
"1A1 1A1", "M55 1A9", "MXX 1A9", "M5X AA9", "M5X 1A", "M5X 1A9B", "02108", "M5X-1A9",
] {
assert!(!pattern_postal(cfg, bad), "{bad}");
assert_eq!(
split_region_postal(cfg, &format!("ON {bad}")),
None,
"{bad}"
);
}
assert_eq!(split_region_postal(cfg, "XX M5X 1A9"), None); // not a region of the sheet
}
fn quadrant_hit(
precision: &'static str,
flags: Vec<&'static str>,
street: &str,
) -> (Hit, [f32; N_FEATS]) {
(
Hit {
lat: 53.5,
lon: -113.5,
precision,
score: 1.0,
confidence: 0.9,
street: street.to_owned(),
housenumber: None,
commune: "Edmonton".to_owned(),
postcode: String::new(),
flags,
region: None,
distance_m: None,
},
[0.0; N_FEATS],
)
}
#[test]
fn ca_quadrant_variants_append_each_quadrant_to_the_street() {
let _scope = crate::rules::scope(ca_city_tail_rules());
assert_eq!(
quadrant_variants("10025 105th Street, Edmonton AB"),
vec![
"10025 105th Street NW, Edmonton AB",
"10025 105th Street NE, Edmonton AB",
"10025 105th Street SW, Edmonton AB",
"10025 105th Street SE, Edmonton AB",
]
);
// a direction already written, in every form; no city; the street glued to the city
for none in [
"10025 105 Street NW, Edmonton AB",
"10025 105 Street nw, Edmonton AB",
"10025 105 Street N, Edmonton AB",
"10025 North 105 Street, Edmonton AB",
"10025 105 Street",
"10025 105 Street Edmonton, AB",
"10220 Jasper Avenue Edmonton, AB",
] {
assert!(quadrant_variants(none).is_empty(), "{none}");
}
// the glued street and city are read as such by the tail, so only the guard holds them
assert_eq!(
city_tail("10220 Jasper Avenue Edmonton, AB").map(|t| t.city),
Some("edmonton".to_owned())
);
assert!(quadrant_variants("10220 Jasper Avenue Edmonton, AB").is_empty());
}
#[test]
fn quadrant_variants_need_the_sheet_key() {
// a sheet that reads the same tail but names no quadrants
let _scope = crate::rules::scope(city_tail_fixture_rules());
assert!(city_tail("10025 105th Street, Edmonton, XY").is_some());
assert!(quadrant_variants("10025 105th Street, Edmonton, XY").is_empty());
}
#[test]
fn pick_quadrant_takes_the_only_street_in_the_commune() {
let exact = vec!["street_exact", "commune_exact"];
let house = || vec![quadrant_hit("house", exact.clone(), "105 St Nw")];
let near = || vec![quadrant_hit("near", exact.clone(), "105 St Sw")];
let pick =
|r: Vec<Vec<(Hit, [f32; N_FEATS])>>| pick_quadrant(r).map(|h| h[0].0.street.clone());
// one house among nothing, and a house over a neighbour on another quadrant
assert_eq!(
pick(vec![vec![], house(), vec![], vec![]]).as_deref(),
Some("105 St Nw")
);
assert_eq!(pick(vec![near(), house()]).as_deref(), Some("105 St Nw"));
// no house: the only neighbour; two neighbours or two houses: no answer
assert_eq!(pick(vec![vec![], near()]).as_deref(), Some("105 St Sw"));
assert_eq!(pick(vec![near(), near()]), None);
assert_eq!(pick(vec![house(), house()]), None);
// near-misses of "the street in the commune": a fuzzy street, a commune by prefix, a
// street without a house, a bare place
for (precision, flags) in [
("house", vec!["street_fuzzy", "commune_exact"]),
("house", vec!["street_exact", "commune_prefix"]),
("street", exact.clone()),
("city", vec!["place_exact"]),
] {
assert_eq!(
pick(vec![vec![quadrant_hit(precision, flags.clone(), "x")]]),
None,
"{precision} {flags:?}"
);
}
assert_eq!(pick(vec![]), None);
}
#[test]
fn ca_pattern_postcodes_leave_every_segment_after_the_street() {
let _scope = crate::rules::scope(ca_city_tail_rules());
for (raw, want) in [
(
"2223 Bloor Street West, Toronto, ON M6S 1M7",
"2223 Bloor Street West, Toronto, ON",
),
(
"2223 Bloor Street West, Toronto M6S1M7",
"2223 Bloor Street West, Toronto",
),
(
"2490 rue Notre-Dame Ouest, Montréal, Canada H3J 1N5",
"2490 rue Notre-Dame Ouest, Montréal, Canada",
),
(
"1588 Barrington Street, Halifax, Nova Scotia, B3J",
"1588 Barrington Street, Halifax, Nova Scotia",
),
(
"2041 boul. René-Lévesque, Québec (QC) G1V 0B6",
"2041 boul. René-Lévesque, Québec (QC)",
),
] {
assert_eq!(strip_pattern_postals(raw).as_deref(), Some(want), "{raw}");
}
// near-misses: a digit where a letter is due, the first group not last, the street
// segment itself, no code at all
for raw in [
"1 Main Street, Toronto, ON M55 1A9",
"1 Main Street, Halifax, B3J Plaza",
"B3J 1Z7 Main Street",
"1 Main Street, Toronto, ON",
] {
assert_eq!(strip_pattern_postals(raw), None, "{raw}");
}
}
#[test]
fn pattern_postcodes_stay_on_a_sheet_without_the_pattern() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
assert_eq!(
strip_pattern_postals("1 Main Street, Toronto, ON M6S 1M7"),
None
);
}
#[test]
fn city_tail_choose_region_asks_the_retry_before_the_region_commune() {
let exact = vec!["street_exact", "commune_exact"];
let at = |precision: &'static str, commune: &str| {
let (mut hit, f) = quadrant_hit(precision, exact.clone(), "x");
hit.commune = commune.to_owned();
vec![(hit, f)]
};
let commune =
|hits: Vec<(Hit, [f32; N_FEATS])>| hits.first().map(|(h, _)| h.commune.clone());
let choose = |original, retry: Vec<(Hit, [f32; N_FEATS])>| {
commune(city_tail_choose_region(
original,
"l islet",
"quebec",
|| retry,
))
};
// a strong answer in the commune the region word names yields to the retry in the city
assert_eq!(
choose(at("near", "Québec"), at("house", "L'Islet")),
Some("L'Islet".to_owned())
);
// the retry elsewhere or empty: the strong answer stays
assert_eq!(
choose(at("near", "Québec"), at("house", "Lévis")),
Some("Québec".to_owned())
);
assert_eq!(
choose(at("house", "Québec"), Vec::new()),
Some("Québec".to_owned())
);
// near-misses: a strong answer in another commune than the region word, or a weak one in
// the region commune — the frozen choice holds (strong elsewhere wins, retry unread)
assert_eq!(
commune(city_tail_choose_region(
at("near", "Lévis"),
"l islet",
"quebec",
|| { panic!("read") }
)),
Some("Lévis".to_owned())
);
assert_eq!(
choose(at("street", "Québec"), at("house", "L'Islet")),
Some("L'Islet".to_owned())
);
assert_eq!(choose(at("street", "Québec"), Vec::new()), None);
// the city named like the region (Québec, Québec): nothing to tell apart
assert_eq!(
commune(city_tail_choose_region(
at("near", "Québec"),
"quebec",
"quebec",
|| { panic!("read") }
)),
Some("Québec".to_owned())
);
}
fn direction_trailing_rules(with_key: bool) -> &'static crate::rules::Rules {
let mut entries: Vec<(u8, String, String)> = [("enabled", "1"), ("street_type_last", "1")]
.iter()
.map(|(k, v)| (23, (*k).to_owned(), (*v).to_owned()))
.collect();
if with_key {
entries.push((23, "direction_trailing".to_owned(), "n s e w".to_owned()));
}
for (from, to) in [
("e", "east"),
("w", "west"),
("n", "north"),
("av", "avenue"),
("ave", "avenue"),
("st", "street"),
] {
entries.push((24, from.to_owned(), to.to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn direction_trailing_key_moves_the_direction_and_shortens_every_word() {
let _scope = crate::rules::scope(direction_trailing_rules(true));
let key = |p: &str| direction_trailing_key(p, |_, _| true);
assert_eq!(key("east 10th avenue").as_deref(), Some("10th ave e"));
assert_eq!(
key("west hastings street").as_deref(),
Some("hastings st w")
);
assert_eq!(key("w hastings st").as_deref(), Some("hastings st w"));
assert_eq!(key("st george street").as_deref(), Some("saint george st"));
assert_eq!(key("ste anne street").as_deref(), Some("sainte anne st"));
// the key comes after every staged variant
let variants = street_data_variants("east 10th avenue");
assert_eq!(variants.last().map(String::as_str), Some("10th ave e"));
// near-misses: no leading direction or saint, a two-word phrase, a name word that only
// looks like a direction elsewhere ("eastern"), a direction already last
for none in [
"king street west",
"east avenue",
"eastern avenue east",
"10th avenue e",
"main street",
] {
assert_eq!(key(none), None, "{none}");
}
}
#[test]
fn direction_trailing_key_needs_the_sheet_key() {
let _scope = crate::rules::scope(direction_trailing_rules(false));
assert_eq!(
direction_trailing_key("east 10th avenue", |_, _| true),
None
);
assert!(!street_data_variants("east 10th avenue").contains(&"10th ave e".to_owned()));
}
fn city_first_rules(on: bool) -> &'static crate::rules::Rules {
let mut entries = vec![(23, "enabled".to_owned(), "1".to_owned())];
if on {
entries.push((23, "city_first".to_owned(), "1".to_owned()));
}
entries.push((16, "highway".to_owned(), String::new()));
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn city_first_reordered_puts_the_address_before_the_place() {
let _scope = crate::rules::scope(city_first_rules(true));
for (raw, want) in [
(
"WINDSOR ONT (1453 PRINCE RD)",
"1453 PRINCE RD, WINDSOR ONT",
),
("LONDON (251 PLATTS LANE) ON", "251 PLATTS LANE, LONDON, ON"),
("LINDSAY, ON (180 KENT ST.)", "180 KENT ST., LINDSAY, ON"),
(
"OSHAWA, ON - 1200 AIRPORT BLVD.",
"1200 AIRPORT BLVD., OSHAWA, ON",
),
("Burnaby BC, 7348 Edmonds St", "7348 Edmonds St, Burnaby BC"),
(
"ABBOTSFORD BC 3911 MT LEHMAN RD",
"3911 MT LEHMAN RD, ABBOTSFORD BC",
),
(
"Surrey, BC 19540 - 94 Avenue",
"19540 94 Avenue, Surrey, BC",
),
] {
assert_eq!(city_first_reordered(raw).as_deref(), Some(want), "{raw}");
}
// near-misses: the address already first, a parenthesis without a number, a dash with a
// number before it, a lone number, a place glued to the number, nothing to reorder
for raw in [
"1453 Prince Rd, Windsor, ON",
"Windsor (near the airport) ON",
"Highway 7 - 1200 Airport Blvd",
"Windsor ON 1453",
"Windsor1453 Prince Rd",
"Windsor, ON",
] {
assert_eq!(city_first_reordered(raw), None, "{raw}");
}
}
#[test]
fn city_first_reordered_moves_a_closing_postal_code_behind_the_place() {
let _scope = crate::rules::scope(ca_city_tail_rules());
assert_eq!(
city_first_reordered("Calgary AB 5111 47 St NE T3J 0V4").as_deref(),
Some("5111 47 St NE, Calgary AB, T3J 0V4")
);
assert_eq!(
city_first_reordered("Calgary AB 5111 47 St NE T3J0V4").as_deref(),
Some("5111 47 St NE, Calgary AB, T3J0V4")
);
// near-misses: a code that is the whole address, a code-like word inside the street,
// a number dash with nothing after it
assert_eq!(city_first_reordered("Calgary AB 5111 T3J 0V4"), None);
assert_eq!(
city_first_reordered("Calgary AB 5111 A1A Street").as_deref(),
Some("5111 A1A Street, Calgary AB")
);
assert_eq!(city_first_reordered("Surrey, BC 19540 -"), None);
}
#[test]
fn city_first_reordered_needs_the_sheet_key() {
let _scope = crate::rules::scope(city_first_rules(false));
assert_eq!(city_first_reordered("WINDSOR ONT (1453 PRINCE RD)"), None);
}
#[test]
fn city_first_quality_puts_an_exact_street_before_a_fuzzy_house() {
let one = |precision: &'static str, flag: &'static str, number: &str| {
let (mut hit, feats) = quadrant_hit(precision, vec![flag], "Queen ST");
hit.housenumber = Some(number.to_owned());
vec![(hit, feats)]
};
let q = |hits: &[(Hit, [f32; N_FEATS])]| {
city_first_quality(hits, "230 Queen Street, Ottawa, ON")
};
// "Ottawa, ON, 230 Queen Street": the exact street's interpolation beats a fuzzy house
assert!(q(&one("interp", "street_exact", "230")) > q(&one("house", "street_fuzzy", "230")));
assert!(q(&one("near", "street_exact", "236")) > q(&one("house", "street_fuzzy", "230")));
// between two exact streets, or two fuzzy ones, precision still decides
assert!(q(&one("house", "street_exact", "230")) > q(&one("interp", "street_exact", "230")));
assert!(q(&one("house", "street_fuzzy", "230")) > q(&one("interp", "street_fuzzy", "230")));
// near-misses: a bare street, a neighbour far from the number written
assert!(q(&one("street", "street_exact", "")) < q(&one("house", "street_fuzzy", "230")));
assert!(q(&one("near", "street_exact", "11530")) < q(&one("house", "street_fuzzy", "230")));
assert!(q(&[]) < q(&one("house", "street_fuzzy", "230")));
}
#[test]
fn neighbour_far_from_written_counts_house_numbers() {
let near = |number: &str, precision: &'static str| {
let (mut hit, _) = quadrant_hit(precision, vec!["street_exact"], "Eglinton AVE E");
hit.housenumber = Some(number.to_owned());
hit
};
// a neighbour 2 800 numbers away does not settle; one at the span does
assert!(neighbour_far_from_written(
&near("600", "near"),
"3400 Eglinton Ave E, Toronto"
));
assert!(!neighbour_far_from_written(
&near("3500", "near"),
"3400 Eglinton Ave E, Toronto"
));
assert!(neighbour_far_from_written(
&near("3501", "near"),
"3400 Eglinton Ave E, Toronto"
));
assert!(!neighbour_far_from_written(
&near("3300", "near"),
"3400 Eglinton Ave E, Toronto"
));
// suffixes are read by their digits
assert!(!neighbour_far_from_written(
&near("3402A", "near"),
"3400B Eglinton Ave E"
));
// near-misses: another precision, no number written, no number stored
assert!(!neighbour_far_from_written(
&near("600", "house"),
"3400 Eglinton Ave E, Toronto"
));
assert!(!neighbour_far_from_written(
&near("600", "interp"),
"3400 Eglinton Ave E, Toronto"
));
assert!(!neighbour_far_from_written(
&near("600", "near"),
"Eglinton Ave E, Toronto"
));
let mut bare = near("600", "near");
bare.housenumber = None;
assert!(!neighbour_far_from_written(
&bare,
"3400 Eglinton Ave E, Toronto"
));
}
#[test]
fn ca_unit_hyphen_reads_unit_and_civic_number() {
let _scope = crate::rules::scope(ca_city_tail_rules());
for (raw, want) in [
(
"9-2755 Denison St, Markham, ON",
"2755 Denison St, Markham, ON",
),
("23-789 Yonge Street, Toronto", "789 Yonge Street, Toronto"),
("12B-450 Main St", "450 Main St"),
(
"#102-11442 168 Street NW, Edmonton",
"11442 168 Street NW, Edmonton",
),
("7 - 2425 Clover Ave", "2425 Clover Ave"),
("1-1749 Portage Ave.", "1749 Portage Ave."),
("3-450B Main St", "450B Main St"),
] {
assert_eq!(unit_hyphen_civic(raw).as_deref(), Some(want), "{raw}");
}
// ranges and other near-misses: close numbers, a civic of 20 or less, the civic exactly
// three times the unit, two letters after the unit, a civic glued to a word, no hyphen
for raw in [
"1300-1308 de Portland",
"1-3 rue du Val-Marie",
"2-20 Main St",
"10-30 Main St",
"12BC-450 Main St",
"9-2755Denison St",
"9 2755 Denison St",
"Denison St 9-2755",
] {
assert_eq!(unit_hyphen_civic(raw), None, "{raw}");
}
}
#[test]
fn unit_hyphen_needs_the_sheet_key() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
assert_eq!(unit_hyphen_civic("9-2755 Denison St, Markham, XY"), None);
}
fn number_first_rules(with_key: bool) -> &'static crate::rules::Rules {
let mut entries: Vec<(u8, String, String)> = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "street_type_last".to_owned(), "1".to_owned()),
];
if with_key {
entries.push((23, "number_first_types".to_owned(), "hwy".to_owned()));
}
for (from, to) in [("hwy", "highway"), ("rd", "road")] {
entries.push((24, from.to_owned(), to.to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn number_first_key_puts_the_road_number_before_its_type() {
let _scope = crate::rules::scope(number_first_rules(true));
let key = |p: &str| number_first_key(p, |_, _| true);
for (phrase, want) in [
("highway 7", "7 hwy"),
("highway no 3", "3 hwy"),
("no 2 highway", "2 hwy"),
("hwy 11", "11 hwy"),
("7 highway", "7 hwy"),
] {
assert_eq!(key(phrase).as_deref(), Some(want), "{phrase}");
}
// the key comes after every staged variant
assert_eq!(
street_data_variants("highway 7").last().map(String::as_str),
Some("7 hwy")
);
// near-misses: a type the sheet does not key number first, a named highway, two numbers,
// a five-digit number, no number
for none in [
"no 3 road",
"trans canada highway",
"highway 7 8",
"highway 12345",
"highway",
"east bay highway",
] {
assert_eq!(key(none), None, "{none}");
}
}
#[test]
fn number_first_key_needs_the_sheet_key() {
let _scope = crate::rules::scope(number_first_rules(false));
assert_eq!(number_first_key("highway 7", |_, _| true), None);
}
fn glue_rules(with_key: bool) -> &'static crate::rules::Rules {
let mut entries: Vec<(u8, String, String)> = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "number_first_types".to_owned(), "hwy".to_owned()),
];
if with_key {
entries.push((23, "glue_road_numbers".to_owned(), "1".to_owned()));
}
for t in ["road", "rd", "avenue", "ave", "highway", "hwy", "street"] {
entries.push((16, t.to_owned(), String::new()));
}
entries.push((24, "hwy".to_owned(), "highway".to_owned()));
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn glue_road_numbers_keeps_the_road_number_in_the_name() {
let _scope = crate::rules::scope(glue_rules(true));
for (raw, want) in [
(
"5300 No. 3 Road, Richmond, BC",
"5300 No3 Road, Richmond, BC",
),
("3700 No 3 Rd, Richmond BC", "3700 No3 Rd, Richmond BC"),
("9371 no 5 rd", "9371 No5 rd"),
(
"5515 47 A Avenue, Wetaskiwin",
"5515 47A Avenue, Wetaskiwin",
),
("12B 47 A Avenue, Wetaskiwin", "12B 47A Avenue, Wetaskiwin"),
] {
assert_eq!(glue_road_numbers(raw).as_deref(), Some(want), "{raw}");
}
// near-misses: a highway (keyed number first), no type after, a three-digit "No", a
// two-letter suffix, no house number first, the pattern outside the street segment
for raw in [
"8740 No 2 Highway, Great Village",
"5300 No. 3 Richmond",
"5300 No. 123 Road",
"5515 47 AB Avenue",
"No. 3 Road 5300",
"Richmond, 5300 No. 3 Road",
"5515 1234 A Avenue",
"Main No 3 Road, Richmond",
] {
assert_eq!(glue_road_numbers(raw), None, "{raw}");
}
}
#[test]
fn glue_road_numbers_needs_the_sheet_key() {
let _scope = crate::rules::scope(glue_rules(false));
assert_eq!(glue_road_numbers("5300 No. 3 Road, Richmond, BC"), None);
}
fn interp_rules(entries: &[(&str, &str)]) -> &'static crate::rules::Rules {
let mut all = vec![(23, "enabled".to_owned(), "1".to_owned())];
all.extend(
entries
.iter()
.map(|(k, v)| (23, (*k).to_owned(), (*v).to_owned())),
);
crate::rules::from_section(&crate::rules::serialize_entries(&all))
}
#[test]
fn interp_limits_default_to_dense_numbering() {
let _scope = crate::rules::scope(interp_rules(&[]));
assert_eq!(interp_limits(), (12, 0.3));
}
#[test]
fn interp_limits_come_from_the_sheet() {
let _scope = crate::rules::scope(ca_city_tail_rules());
assert_eq!(interp_limits(), (400, 2.0));
// near-misses: an unreadable, a zero or a negative distance keep the default
for (gap, km, want) in [
("x", "2.0", (12, 2.0)),
("400", "nan", (400, 0.3)),
("400", "0", (400, 0.3)),
("400", "-1.0", (400, 0.3)),
("-5", "2.0", (12, 2.0)),
] {
let _inner = crate::rules::scope(interp_rules(&[
("interp_max_gap", gap),
("interp_max_km", km),
]));
assert_eq!(interp_limits(), want, "{gap} {km}");
}
}
#[test]
fn city_first_keeps_a_merged_city_within_reach_of_its_point() {
let at = |precision: &'static str, flags: Vec<&'static str>, lat: f64, lon: f64| {
let (mut hit, _) = quadrant_hit(precision, flags, "Wingarden CRT");
hit.lat = lat;
hit.lon = lon;
hit
};
let toronto = [(43.7064, -79.3986)];
let exact = vec!["street_exact"];
// Scarborough, ~20 km from Toronto's point: kept; the exact commune is kept anywhere
assert!(city_first_keeps_place(
&at("house", exact.clone(), 43.80, -79.25),
&toronto
));
assert!(city_first_keeps_place(
&at("street", vec!["commune_exact"], 49.0, -100.0),
&toronto
));
// near-misses: 40 km off, a fuzzy street, a bare street, no city point at all
assert!(!city_first_keeps_place(
&at("house", exact.clone(), 44.0, -79.0),
&toronto
));
assert!(!city_first_keeps_place(
&at("house", vec!["street_fuzzy"], 43.80, -79.25),
&toronto
));
assert!(!city_first_keeps_place(
&at("street", exact.clone(), 43.80, -79.25),
&toronto
));
assert!(!city_first_keeps_place(
&at("house", exact, 43.80, -79.25),
&[]
));
}
#[test]
fn commaless_postal_tail_sets_aside_the_code_the_region_and_the_country() {
let _scope = crate::rules::scope(ca_city_tail_rules());
let bare = |q: &str| commaless_postal_tail(q);
assert_eq!(
bare("1150 Station St Vancouver BC V6A 4C7").as_deref(),
Some("1150 Station St Vancouver")
);
assert_eq!(
bare("12 rue Donnacona Québec (Québec) G1R 3Y7").as_deref(),
Some("12 rue Donnacona Québec")
);
assert_eq!(
bare("2072 rue Gignac Shawinigan (Québec) G9N6V7").as_deref(),
Some("2072 rue Gignac Shawinigan")
);
assert_eq!(
bare("1 Tower Rd Prince George British Columbia V2N 4Z9").as_deref(),
Some("1 Tower Rd Prince George")
);
assert_eq!(
bare("165 Richmond St Charlottetown Prince Edward Island C1A 1J1").as_deref(),
Some("165 Richmond St Charlottetown")
);
// no region: only the code goes
assert_eq!(
bare("4141 Living Arts Dr Mississauga L5B 4B8").as_deref(),
Some("4141 Living Arts Dr Mississauga")
);
// near-misses: a comma, no code, a code that is no pattern code, too little left, a
// region that would leave too little
assert_eq!(bare("1150 Station St, Vancouver BC V6A 4C7"), None);
assert_eq!(bare("1150 Station St Vancouver BC"), None);
assert_eq!(bare("1150 Station St Vancouver BC 12345"), None);
assert_eq!(bare("1150 Station V6A 4C7"), None);
assert_eq!(
bare("1150 Station BC V6A 4C7").as_deref(),
Some("1150 Station BC")
);
}
#[test]
fn commaless_postal_tail_sets_aside_country_words_around_the_code() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "postal_pattern".to_owned(), "A9A 9A9".to_owned()),
(23, "regions".to_owned(), "BC ON".to_owned()),
(23, "region_names".to_owned(), "ontario=ON".to_owned()),
(11, "canada".to_owned(), String::new()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
assert_eq!(
commaless_postal_tail("6393 NW Marine Drive Vancouver BC Canada V6T 1Z2").as_deref(),
Some("6393 NW Marine Drive Vancouver")
);
assert_eq!(
commaless_postal_tail("131 Farnham Avenue Toronto Ontario M4V 1H7 Canada").as_deref(),
Some("131 Farnham Avenue Toronto")
);
}
#[test]
fn commaless_postal_tail_needs_the_sheet_pattern() {
let _scope = crate::rules::scope(city_first_rules(true));
assert_eq!(
commaless_postal_tail("1150 Station St Vancouver BC V6A 4C7"),
None
);
}
fn type_first_rules(on: bool) -> &'static crate::rules::Rules {
let mut entries = vec![(23, "enabled".to_owned(), "1".to_owned())];
if on {
entries.push((23, "type_first_siblings".to_owned(), "1".to_owned()));
}
for (from, to) in [
("blvd", "boulevard"),
("boulevard", "blvd"),
("boul", "boulevard"),
("boulevard", "boul"),
("av", "avenue"),
("avenue", "av"),
("ave", "avenue"),
("avenue", "ave"),
("o", "ouest"),
("ouest", "o"),
("n", "nord"),
("nord", "n"),
("no", "nord"),
("nord", "no"),
] {
entries.push((24, from.to_owned(), to.to_owned()));
}
entries.push((16, "boulevard".to_owned(), String::new()));
entries.push((16, "avenue".to_owned(), String::new()));
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn a_type_written_in_front_reaches_the_sheet_sibling_short_form() {
let _scope = crate::rules::scope(type_first_rules(true));
let one_word = |from: &str, to: &str| !from.contains(' ') && !to.contains(' ');
assert_eq!(
type_first_sibling_keys("blvd manseau", one_word),
vec!["boul manseau".to_owned()]
);
assert_eq!(
type_first_sibling_keys("ave des pins ouest", one_word),
vec!["av des pins ouest".to_owned(), "av des pins o".to_owned()]
);
// the staged variants carry the key after their own
let variants = street_data_variants("blvd manseau");
assert_eq!(variants.last().map(String::as_str), Some("boul manseau"));
assert!(variants.contains(&"boulevard manseau".to_owned()));
// near-misses: a short form that is no type ("o" for ouest), the full word, the type
// trailing, one word alone
assert!(type_first_sibling_keys("o street", one_word).is_empty());
assert!(type_first_sibling_keys("n chemin", one_word).is_empty());
assert!(type_first_sibling_keys("boulevard manseau", one_word).is_empty());
assert!(type_first_sibling_keys("manseau blvd", one_word).is_empty());
assert!(type_first_sibling_keys("blvd", one_word).is_empty());
}
#[test]
fn type_first_sibling_keys_need_the_sheet_key() {
let _scope = crate::rules::scope(type_first_rules(false));
let one_word = |from: &str, to: &str| !from.contains(' ') && !to.contains(' ');
assert!(type_first_sibling_keys("blvd manseau", one_word).is_empty());
assert!(!street_data_variants("blvd manseau").contains(&"boul manseau".to_owned()));
}
#[test]
fn ca_accented_region_names_are_regions_with_their_code() {
// "Lévis (Québec) G6V 4A4": the writer's accents and hyphens, the rule's plain words
// (Canada E3.1, 29.10.2026: 219 rows of the clean set, GridPin 52 against 146 and 148)
let _scope = crate::rules::scope(ca_city_tail_rules());
let cfg = &crate::rules::rules().city_tail;
for (name, code) in [
("Québec", "QC"),
("QUÉBEC", "QC"),
("Île-du-Prince-Édouard", "PE"),
("Colombie-Britannique", "BC"),
("Nouvelle-Écosse", "NS"),
] {
assert!(region_matches(cfg, name), "{name}");
assert_eq!(region_code(cfg, name).as_deref(), Some(code), "{name}");
}
// near-misses: one letter more, a city named after the province, a word left over
for bad in ["Québecc", "Québec City", "Ville de Québec", "Lévis", "Île"] {
assert!(!region_matches(cfg, bad), "{bad}");
assert_eq!(region_code(cfg, bad), None, "{bad}");
}
assert_eq!(
split_region_postal(cfg, "Québec G6V 4A4"),
Some(("Québec", None))
);
let tail = city_tail("18, rue Notre Dame, Lévis (Québec) G6V 4A4").unwrap();
assert_eq!(
(tail.city.as_str(), tail.region.as_deref()),
("levis", Some("QC"))
);
}
#[test]
fn ca_city_tail_finds_the_city_in_every_tail_form_and_drops_the_code() {
let _scope = crate::rules::scope(ca_city_tail_rules());
for q in [
"100 King St W, Toronto, ON M5X 1A9",
"100 King St W, Toronto ON M5X 1A9",
"100 King St W, Toronto, ON, M5X 1A9",
"100 King St W, Toronto, ON M5X1A9",
"100 King St W, Toronto ON m5x1a9",
] {
let tail = city_tail(q).unwrap_or_else(|| panic!("{q}"));
assert_eq!(tail.city, "toronto", "{q}");
assert_eq!(tail.region.as_deref(), Some("ON"), "{q}");
for kept in [
tail.retry.as_deref().unwrap_or(""),
tail.without_region.as_str(),
] {
assert!(
!kept.to_lowercase().contains("m5x"),
"{q} kept the code: {kept}"
);
}
}
}
#[test]
fn a_sheet_without_postal_pattern_reads_no_alphanumeric_code() {
// the US pack has no postal_pattern: "ON M5X 1A9" is no region segment there
let _scope = crate::rules::scope(region_postal_fixture_rules("comma region_postal", None));
let cfg = &crate::rules::rules().city_tail;
assert!(!pattern_postal(cfg, "M5X 1A9"));
assert_eq!(split_region_postal(cfg, "IL M5X 1A9"), None);
}
#[test]
fn region_postal_live_us_pack_parses_city_state_zip_tail() {
// The generated pack rules/us/city_tail.tsv as the sheet carries it (class 23). The rules tree is
// not part of the public export, so the pack is inlined; where the file exists it must match.
let tsv: String = [
"# Generated United States additions from us_overlay.json.\n",
"enabled\t1\n",
"forms\tcomma region_postal\n",
"homonym_prominence\t1\n",
"junk_tail\tnear next behind opposite across beside tel phone fax suite ste apt unit floor room rm bldg basement\n",
"postal_digits\t5\n",
"postal_extension\t4\n",
"postal_split\t5\n",
"region_names\talabama=AL;alaska=AK;arizona=AZ;arkansas=AR;california=CA;colorado=CO;connecticut=CT;delaware=DE;florida=FL;georgia=GA;hawaii=HI;idaho=ID;illinois=IL;indiana=IN;iowa=IA;kansas=KS;kentucky=KY;louisiana=LA;maine=ME;maryland=MD;massachusetts=MA;michigan=MI;minnesota=MN;mississippi=MS;missouri=MO;montana=MT;nebraska=NE;nevada=NV;new hampshire=NH;new jersey=NJ;new mexico=NM;new york=NY;north carolina=NC;north dakota=ND;ohio=OH;oklahoma=OK;oregon=OR;pennsylvania=PA;rhode island=RI;south carolina=SC;south dakota=SD;tennessee=TN;texas=TX;utah=UT;vermont=VT;virginia=VA;washington=WA;west virginia=WV;wisconsin=WI;wyoming=WY;district of columbia=DC\n",
"regions\tAK AL AR AZ CA CO CT DC DE FL GA HI IA ID IL IN KS KY LA MA MD ME MI MN MO MS MT NC ND NE NH NJ NM NV NY OH OK OR PA RI SC SD TN TX UT VA VT WA WI WV WY\n",
"street_type_last\t1\n",
]
.concat();
let pack = concat!(env!("CARGO_MANIFEST_DIR"), "/../rules/us/city_tail.tsv");
if let Ok(file) = std::fs::read_to_string(pack) {
assert_eq!(file, tsv, "inline copy of rules/us/city_tail.tsv is stale");
}
let entries: Vec<(u8, String, String)> = tsv
.lines()
.filter(|l| !l.starts_with('#') && !l.trim().is_empty())
.map(|l| {
let (k, v) = l.split_once('\t').unwrap();
(23, k.to_owned(), v.to_owned())
})
.collect();
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
let cfg = &crate::rules::rules().city_tail;
eprintln!("cfg = {:?}", cfg);
assert_eq!(
split_region_postal(cfg, "MA 02108"),
Some(("MA", Some("02108")))
);
assert_eq!(
split_region_postal(cfg, "il 62701"),
Some(("il", Some("62701")))
);
let tail = city_tail("1 Beacon Street, Boston, MA 02108").unwrap();
assert_eq!(tail.city, "boston");
assert_eq!(
tail.retry.as_deref(),
Some("1 Beacon Street, Boston, 02108")
);
let tail = city_tail("1 Beacon Street, Boston, MA 02108-1234").unwrap();
assert_eq!(
tail.retry.as_deref(),
Some("1 Beacon Street, Boston, 02108-1234")
);
assert!(city_tail("1 Beacon Street, Boston, MA")
.unwrap()
.retry
.is_none());
let tail = city_tail("1 Beacon Street, Boston, MA, 02108").unwrap();
assert_eq!(
(tail.city.as_str(), tail.retry.as_deref()),
("boston", Some("1 Beacon Street, Boston, 02108"))
);
}
#[test]
fn street_data_variants_rewrite_the_last_word_only_when_the_sheet_says_the_type_trails() {
let pairs = |flag: Option<&str>| {
let mut entries = vec![
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "n".to_owned(), "north".to_owned()),
(24, "north".to_owned(), "n".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
];
if let Some(v) = flag {
entries.push((23, "enabled".to_owned(), "1".to_owned()));
entries.push((23, "street_type_last".to_owned(), v.to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
{
let _scope = crate::rules::scope(pairs(Some("1")));
let v = street_data_variants("n main st");
assert!(v.contains(&"north main st".to_owned()), "{v:?}");
assert!(v.contains(&"n main street".to_owned()), "{v:?}");
assert!(
v.contains(&"north main street".to_owned()),
"composition {v:?}"
);
assert!(street_data_variants("main st").contains(&"main street".to_owned()));
// The type before a trailing direction is rewritten too, composed with the
// direction ("16th st nw": DC, "Peachtree rd ne": Atlanta).
let v = street_data_variants("16th st n");
assert!(v.contains(&"16th st north".to_owned()), "{v:?}");
assert!(v.contains(&"16th street n".to_owned()), "{v:?}");
assert!(v.contains(&"16th street north".to_owned()), "{v:?}");
// ... but not deeper inside the name, and not before a plain name word: "st"
// there is a name ("st james"), only a trailing street word opens the round.
let v = street_data_variants("old st james st");
assert!(!v.contains(&"old street james st".to_owned()), "{v:?}");
let v = street_data_variants("main st james");
assert!(!v.contains(&"main street james".to_owned()), "{v:?}");
}
for flag in [None, Some("0")] {
let _scope = crate::rules::scope(pairs(flag));
let v = street_data_variants("main st");
assert!(!v.contains(&"main street".to_owned()), "{flag:?}: {v:?}");
assert!(street_data_variants("n main st").contains(&"north main st".to_owned()));
let v = street_data_variants("16th st n");
assert!(!v.contains(&"16th street n".to_owned()), "{flag:?}: {v:?}");
}
}
#[test]
fn region_names_in_the_tail_are_regions_and_get_a_retry_without_the_name() {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "IL NY WA".to_owned()),
(
23,
"region_names".to_owned(),
"illinois;new york;washington".to_owned(),
),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
let cfg = &crate::rules::rules().city_tail;
assert!(
region_matches(cfg, "WASHINGTON")
&& region_matches(cfg, "New York")
&& region_matches(cfg, "ny")
);
assert!(!region_matches(cfg, "Washington Heights") && !region_matches(cfg, "York"));
assert_eq!(
split_region_postal(cfg, "New York 12590"),
Some(("New York", Some("12590")))
);
let t = city_tail("Main St 1, Seattle, WASHINGTON").unwrap();
assert_eq!(
(t.city.as_str(), t.retry.as_deref()),
("seattle", Some("Main St 1, Seattle"))
);
let t = city_tail("Main St 1, New Hamburg, New York 12590").unwrap();
assert_eq!(
(t.city.as_str(), t.retry.as_deref()),
("new hamburg", Some("Main St 1, New Hamburg, 12590"))
);
let t = city_tail("Main St 1, Albany, NY").unwrap();
assert_eq!((t.city.as_str(), t.retry.as_deref()), ("albany", None)); // a code keeps its path
entries.retain(|(_, k, _)| k != "region_names");
let _scope2 = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
assert!(city_tail("Main St 1, Seattle, WASHINGTON").is_none()); // without the key nothing changes
}
#[test]
fn region_codes_come_from_the_code_list_or_from_name_equals_code_entries() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "KY MA".to_owned()),
(
23,
"region_names".to_owned(),
"kentucky=KY;massachusetts=MA;new york".to_owned(),
),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
let cfg = &crate::rules::rules().city_tail;
assert_eq!(region_code(cfg, "ky").as_deref(), Some("KY"));
assert_eq!(region_code(cfg, "KENTUCKY").as_deref(), Some("KY"));
assert_eq!(region_code(cfg, "Massachusetts ").as_deref(), Some("MA"));
// a name without "=CODE" is still a region for the grammar, but anchors nothing
assert!(region_matches(cfg, "New York") && region_code(cfg, "New York").is_none());
assert!(region_code(cfg, "Kentucky Heights").is_none() && region_code(cfg, "KX").is_none());
let t = city_tail("174 N Mill St, Lexington, KENTUCKY").unwrap();
assert_eq!(
(t.city.as_str(), t.region.as_deref()),
("lexington", Some("KY"))
);
let t = city_tail("174 N Mill St, Lexington, MA 02420").unwrap();
assert_eq!(
(t.city.as_str(), t.region.as_deref()),
("lexington", Some("MA"))
);
let t = city_tail("174 N Mill St, Lexington, New York").unwrap();
assert_eq!((t.city.as_str(), t.region.as_deref()), ("lexington", None));
}
fn commune_regions_hit(lat: f64, lon: f64, commune: &str) -> (Hit, [f32; N_FEATS]) {
(
Hit {
lat,
lon,
precision: "house",
score: 1.0,
confidence: 0.9,
street: "Mill Street".to_owned(),
housenumber: Some("174".to_owned()),
commune: commune.to_owned(),
postcode: String::new(),
flags: vec!["commune_exact"],
region: None,
distance_m: None,
},
[0.0; N_FEATS],
)
}
#[test]
fn commune_regions_hold_the_named_region_and_let_unknown_pairs_through() {
let entries = vec![(
27,
"lexington".to_owned(),
"KY 38.0464 -84.4970;MA 42.4473 -71.2245;KY 37.0 -86.0".to_owned(),
)];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
let ky = commune_region_points("lexington", "KY");
assert_eq!(ky, vec![(38.0464, -84.4970), (37.0, -86.0)]);
assert_eq!(
commune_region_points("lexington", "ma"),
vec![(42.4473, -71.2245)]
);
// no such city in that region, no such city, no table: nothing to hold
assert!(commune_region_points("lexington", "NC").is_empty());
assert!(commune_region_points("boston", "MA").is_empty());
let hits = vec![
commune_regions_hit(42.44, -71.23, "Lexington"), // Massachusetts
commune_regions_hit(38.03, -84.50, "Lexington"), // Kentucky, 2 km off the point
commune_regions_hit(38.60, -84.49, "Georgetown"), // 61 km north, same region
commune_regions_hit(35.82, -80.25, "Lexington"), // North Carolina
];
let kept = within_commune_region(hits.clone(), &ky);
assert_eq!(
kept.iter().map(|(h, _)| h.lat).collect::<Vec<_>>(),
vec![38.03, 38.60]
);
// an exact commune flag is no exception: the name matched, the place did not
assert!(kept.iter().all(|(h, _)| h.flags.contains(&"commune_exact")));
assert_eq!(within_commune_region(hits.clone(), &[]).len(), 4);
// the radius is 75 km: a point just inside stays, just outside goes
let edge = vec![
commune_regions_hit(38.0464 + 74.0 / 111.0, -84.4970, "A"),
commune_regions_hit(38.0464 + 76.0 / 111.0, -84.4970, "B"),
];
let kept = within_commune_region(edge, &[(38.0464, -84.4970)]);
assert_eq!(kept.len(), 1);
assert_eq!(kept[0].0.commune, "A");
}
#[test]
fn a_street_glued_to_its_city_is_split_at_the_last_type_word_on_a_trailing_type_sheet() {
// "20 North Main Street Providence, RI 02903": the segment before the state opens with
// the house number and holds a type word; the city is what follows the last type word,
// the direction after it and stray digits set aside. Only with `street_type_last`.
let rules = |type_last: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "RI DC CA".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "postal_extension".to_owned(), "4".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(24, "nw".to_owned(), "northwest".to_owned()),
(24, "northwest".to_owned(), "nw".to_owned()),
];
if type_last {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
{
let _scope = crate::rules::scope(rules(true));
let tail = city_tail("20 North Main Street Providence, RI 02903-2723").unwrap();
assert_eq!(
(tail.city.as_str(), tail.region.as_deref()),
("providence", Some("RI"))
);
assert_eq!(
tail.retry.as_deref(),
Some("20 North Main Street, Providence, 02903-2723")
);
// The direction after the type stays with the street.
let tail = city_tail("201 18th Street NW Washington, DC 20006").unwrap();
assert_eq!(tail.city, "washington");
assert_eq!(
tail.retry.as_deref(),
Some("201 18th Street NW, Washington, 20006")
);
// Stray digits between street and city (a ZIP+4 fragment) are set aside too.
let tail = city_tail("1100 Anacapa Street 21107 Santa Barbara, CA 93121").unwrap();
assert_eq!(tail.city, "santa barbara");
// No type word in the segment, or no house number in front: not a glued street.
assert!(city_tail("Providence Plantation, RI 02903").is_none());
assert!(city_tail("North Main Street Providence, RI 02903").is_none());
// A plain city segment keeps its established reading.
let tail = city_tail("20 North Main Street, Providence, RI 02903").unwrap();
assert_eq!(tail.city, "providence");
}
let _scope = crate::rules::scope(rules(false));
assert!(city_tail("20 North Main Street Providence, RI 02903").is_none());
}
#[test]
fn dotted_initialisms_and_semicolons_are_read_past_by_the_tail_grammar() {
assert_eq!(
tidy_tail_punctuation("…, Washington, D.C. 20037"),
"…, Washington, DC 20037"
);
assert_eq!(
tidy_tail_punctuation("4 Plaza, New York 10001, N.Y."),
"4 Plaza, New York 10001, NY"
);
assert_eq!(
tidy_tail_punctuation("679 Geary St, San Francisco, U.S."),
"679 Geary St, San Francisco, US"
);
assert_eq!(
tidy_tail_punctuation("400 Rusk Street; Houston, TX"),
"400 Rusk Street, Houston, TX"
);
// An ordinary abbreviation with one dot keeps its dot for the normaliser.
assert_eq!(
tidy_tail_punctuation("11 Divinity Ave. Cambridge, MA"),
"11 Divinity Ave. Cambridge, MA"
);
assert_eq!(
tidy_tail_punctuation("Charles E. Young Drive"),
"Charles E. Young Drive"
);
let _scope = crate::rules::scope(region_postal_fixture_rules(
"comma region_postal",
Some("4"),
));
let tail = city_tail("Main St 1; Springfield, IL 62701").unwrap();
assert_eq!(tail.city, "springfield");
let tail = city_tail("Main St 1, Springfield, I.L. 62701").unwrap();
assert_eq!(
(tail.city.as_str(), tail.region.as_deref()),
("springfield", Some("IL"))
);
}
#[test]
fn region_postal_tail_rejects_near_misses() {
let _scope = crate::rules::scope(region_postal_fixture_rules("region_postal", Some("4")));
for q in [
"Main St 1, Springfield, XX 62701",
"Main St 1, Springfield, IL 6270",
"Main St 1, Springfield, IL 627011",
"Main St 1, Springfield, IL 62701-123",
"Main St 1, Springfield, IL 62701-12345",
"Main St 1, Springfield, IL 62701-",
"Main St 1, Springfield, IL 62701 Apt 4",
"Main St 1, Springfield, 62701 IL",
"Main St 1, Springfield, 62701",
// "Main St 1, Springfield IL 62701" is no longer a near miss: the city glued to
// its region is read since 22.10.2026 (region_postal_tail_reads_a_city_glued…).
"Springfield, IL 62701",
"Main St 1, 62701, IL 62701",
] {
assert!(city_tail(q).is_none(), "{q}");
}
}
#[test]
fn region_postal_extension_requires_declared_width() {
{
let _scope = crate::rules::scope(region_postal_fixture_rules("region_postal", None));
assert_eq!(
city_tail("Main St 1, Springfield, IL 62701").unwrap().city,
"springfield"
);
assert!(city_tail("Main St 1, Springfield, IL 62701-1234").is_none());
}
{
let _scope =
crate::rules::scope(region_postal_fixture_rules("region_postal", Some("3")));
assert_eq!(
city_tail("Main St 1, Springfield, IL 62701-123")
.unwrap()
.city,
"springfield"
);
assert!(city_tail("Main St 1, Springfield, IL 62701-1234").is_none());
}
}
#[test]
fn region_postal_form_must_be_declared() {
{
// Same regions and postal width, comma form only: the glued tail is not a city.
let _scope = crate::rules::scope(region_postal_fixture_rules("comma", Some("4")));
assert!(city_tail("Main St 1, Springfield, IL 62701").is_none());
assert!(address_field_retries("Main St 1, Springfield, IL 62701").is_none());
assert_eq!(
city_tail("Main St 1, Springfield, IL").unwrap().city,
"springfield"
);
}
{
let _scope = crate::rules::scope(city_tail_fixture_rules());
assert!(city_tail("Rua Azul 1, Vila, XY 12345678").is_none());
assert!(address_field_retries("Rua Azul 1, Vila, XY 12345678").is_none());
}
}
#[test]
fn region_postal_field_retries_anchor_same_city() {
let _scope = crate::rules::scope(region_postal_fixture_rules("region_postal", Some("4")));
for (raw, first, second) in [
(
"Main St 12, Apt 4, Springfield, IL 62701",
"Main St 12, Springfield, IL 62701",
"Main St 12, Springfield",
),
(
"Main St, 12, Apt 4, Springfield, IL 62701-1234",
"Main St, 12, Springfield, IL 62701-1234",
"Main St, 12, Springfield",
),
(
"Main St 12, Springfield, il 62701",
"Main St 12, Springfield, il 62701",
"Main St 12, Springfield",
),
(
"Main St 12, Apt 4, Springfield, IL",
"Main St 12, Springfield, IL",
"Main St 12, Springfield",
),
] {
let tail = address_field_retries(raw).unwrap_or_else(|| panic!("{raw}"));
assert_eq!(tail.number, 12, "{raw}");
assert_eq!(tail.city, "springfield", "{raw}");
assert_eq!(tail.forms[0], first, "{raw}");
assert_eq!(tail.forms[1], second, "{raw}");
// The clean form reaches a house in the tail's city; another city is refused.
let result = address_field_choose(Vec::new(), &tail, |_, q| {
if q == second {
vec![field_witness("house", "12", "Springfield", 2.0)]
} else {
Vec::new()
}
});
assert_eq!(result[0].0.lat, 2.0, "{raw}");
let result = address_field_choose(Vec::new(), &tail, |_, _| {
vec![field_witness("house", "12", "Chicago", 3.0)]
});
assert!(result.is_empty(), "{raw}");
}
for raw in [
"Main St 12, Apt 4, Springfield, XX 62701",
"Main St 12, Apt 4, Springfield, IL 62701-123",
"Main St 12, Apt 4, Springfield, IL 62701 Apt 4",
] {
assert!(address_field_retries(raw).is_none(), "{raw}");
}
}
#[test]
fn region_postal_comma_recovery_restores_anchor() {
let mut idx = es_observer_fixture(
"region-postal-comma",
&[("main street", "springfield", "001", "12")],
"",
);
idx.rules = region_postal_fixture_rules("region_postal", Some("4"));
let _scope = crate::rules::scope(idx.rules);
// A bare trailing region is the old word-level path; the base parser already answers it.
assert_eq!(
idx.comma_field_retry("Main Street 12 Springfield IL")
.as_deref(),
Some("Main Street 12, Springfield, IL")
);
for (raw, cut) in [
(
"Main Street 12 Springfield IL 62701",
"Main Street 12, Springfield, IL 62701",
),
(
"Main Street 12 Springfield IL 62701-1234",
"Main Street 12, Springfield, IL 62701-1234",
),
] {
assert_eq!(idx.comma_field_retry(raw).as_deref(), Some(cut), "{raw}");
assert!(
idx.query_feats_street_data_base(raw, 3, None).is_empty(),
"{raw}"
);
let hits = idx.query_feats_street_data(raw, 3, None);
assert!(!hits.is_empty(), "{raw}");
assert_eq!(hits[0].0.precision, "house", "{raw}");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("12"), "{raw}");
assert_eq!(normalize(&hits[0].0.commune), "springfield", "{raw}");
}
for raw in [
"Main Street 12 Chicago IL 62701",
"Main Street 99 Springfield IL 62701",
"Main Street 12 Springfield XX 62701",
] {
let before = idx.query_feats_street_data_base(raw, 3, None);
assert_eq!(
es_observer_hits(&idx.query_feats_street_data(raw, 3, None)),
es_observer_hits(&before),
"{raw}"
);
}
}
#[test]
fn region_postal_readers_agree_on_city() {
let mut idx = es_observer_fixture(
"region-postal-readers",
&[("main street", "springfield", "001", "12")],
"",
);
idx.rules = region_postal_fixture_rules("region_postal", Some("4"));
let _scope = crate::rules::scope(idx.rules);
let raw = "Main Street, 12, Downtown, Springfield, IL 62701-1234";
let tail = city_tail(raw).unwrap();
assert_eq!(tail.city, "springfield");
assert_eq!(
tail.retry.as_deref(),
Some("Main Street, 12, Springfield, IL 62701-1234")
);
let fields = address_field_retries(raw).unwrap();
assert_eq!((fields.number, fields.city.as_str()), (12, "springfield"));
let (query, number, city) = idx.geographic_field_retry(raw).unwrap();
assert_eq!(
(query.as_str(), number, city.as_str()),
("Main Street, 12, springfield", 12, "springfield")
);
let hits = idx.query_feats_street_data(raw, 3, None);
assert_eq!(hits[0].0.precision, "house");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("12"));
assert_eq!(normalize(&hits[0].0.commune), "springfield");
}
#[test]
fn region_postal_title_path_sees_same_city() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "IL CA NY".to_owned()),
(23, "forms".to_owned(), "region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "0".to_owned()),
(23, "postal_extension".to_owned(), "4".to_owned()),
(23, "street_titles".to_owned(), "doctor".to_owned()),
(
23,
"street_title_aliases".to_owned(),
"dr:doctor".to_owned(),
),
(16, "avenue".to_owned(), String::new()),
];
let mut idx = es_observer_fixture(
"region-postal-title",
&[("avenue doctor main", "springfield", "001", "12")],
"",
);
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
let _scope = crate::rules::scope(idx.rules);
let hits = idx.query_feats_title_fields(
Vec::new(),
"Avenue Main, 12, Springfield, IL 62701-1234",
3,
None,
);
assert!(!hits.is_empty());
assert_eq!(hits[0].0.precision, "house");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("12"));
assert_eq!(normalize(&hits[0].0.commune), "springfield");
assert!(idx
.query_feats_title_fields(
Vec::new(),
"Avenue Main, 12, Chicago, IL 62701-1234",
3,
None
)
.is_empty());
}
#[test]
fn region_postal_small_sheet_retry_reaches_house_and_rejects_wrong_place() {
let mut idx = forward_postcode_index_for_country(
"region-postal",
"main st,001,springfield,62701,62701,1,,8.0,50.0,Main St,Springfield\nmain st,001,springfield,62701,62701,3,,8.0002,50.0002,Main St,Springfield\noak ave,002,downtown,62702,62702,10,,18.0,40.0,Oak Ave,Downtown\n",
"xx",
);
let before = idx.query("Main St, 1, Downtown, Springfield, IL 62701-1234", 3);
idx.rules = region_postal_fixture_rules("region_postal", Some("4"));
for (number, precision) in [("1", "house"), ("3", "house")] {
let result = idx.query(
&format!("Main St, {number}, Downtown, Springfield, IL 62701-1234"),
3,
);
assert_eq!(result[0].precision, precision, "{number}");
assert_eq!(result[0].commune, "Springfield", "{number}");
assert_eq!(result[0].street, "Main St", "{number}");
assert_eq!(result[0].housenumber.as_deref(), Some(number), "{number}");
}
assert!(before.is_empty() || before[0].commune != "Springfield");
// The tail names Springfield: the Oak Ave house in Downtown is never offered.
let wrong = idx.query("Oak Ave, Downtown, Springfield, IL 62701", 3);
assert!(
wrong.iter().all(|h| h.commune != "Downtown"),
"{}",
serde_json::to_string(&wrong).unwrap()
);
}
#[test]
fn region_anchor_holds_commune_lookups_and_reads_a_bare_code_without_it() {
// Two Lexingtons with the same house; North Carolina carries more addresses and
// outranks Kentucky in every reading. The tail names Kentucky by a bare code, for
// which the retry grammar builds no region-less query: the anchor must narrow the
// commune lookup itself and read the query without the code.
let mut rows = String::from(
"main street,001,lexington,40507,40507,1,,-84.49,38.05,Main Street,Lexington\n",
);
for n in 1..=3 {
rows.push_str(&format!(
"main street,002,lexington,27295,27295,{n},,-80.26,35.84,Main Street,Lexington\n"
));
}
// "Kyle", 20 km from the Kentucky Lexington, also has a 1 Main Street: the original
// reading sees "ky" as the start of a place and would take that house by prefix.
rows.push_str("main street,003,kyle,40510,40510,1,,-84.30,38.10,Main Street,Kyle\n");
// "Kentucky Heights", 30 km away, also has the house: with the state written in full
// the original reading takes it by prefix ("kentucky" starts the name) — the
// region-less reading is what reaches Lexington (Oregon City for "Portland, OREGON").
rows.push_str(
"main street,004,kentucky heights,40511,40511,1,,-84.20,38.20,Main Street,Kentucky Heights\n",
);
// Atlanta: the exact house lives under a commune coded "ATL"; the commune "Atlanta"
// has only a look-alike street. The original reading reaches the house by dropping
// the tail; the region-less reading gets a fuzzy neighbour — the better answer wins.
rows.push_str(
"peachtree street,005,atl,30303,30303,1,,-84.3880,33.7580,Peachtree Street,ATL\n\
peachtree view,006,atlanta,30305,30305,1,,-84.3370,33.8600,Peachtree View,Atlanta\n",
);
let mut idx = forward_postcode_index_for_country("region-anchor", &rows, "xx");
let rules = |table: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "GA KY NC".to_owned()),
(
23,
"region_names".to_owned(),
"georgia=GA;kentucky=KY".to_owned(),
),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "street".to_owned(), String::new()),
];
if table {
entries.push((
27,
"lexington".to_owned(),
"KY 38.0464 -84.4970;NC 35.8240 -80.2534".to_owned(),
));
entries.push((27, "atlanta".to_owned(), "GA 33.7490 -84.3880".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.lat, h.precision, h.commune.clone()))
};
idx.rules = rules(true);
let ky = top(&idx, "1 Main Street, Lexington, KY").expect("an answer");
assert!(
(ky.0 - 38.05).abs() < 0.01 && ky.1 == "house" && ky.2 == "Lexington",
"Kentucky, not Kyle: {ky:?}"
);
let full = top(&idx, "1 Main Street, Lexington, Kentucky").expect("an answer");
assert!(
(full.0 - 38.05).abs() < 0.01 && full.2 == "Lexington",
"Lexington, not Kentucky Heights by prefix: {full:?}"
);
let atl = top(&idx, "1 Peachtree Street, Atlanta, Georgia").expect("an answer");
assert!(
(atl.0 - 33.758).abs() < 0.001 && atl.1 == "house",
"the exact house under ATL beats the fuzzy neighbour under Atlanta: {atl:?}"
);
let nc = top(&idx, "1 Main Street, Lexington, NC").expect("an answer");
assert!((nc.0 - 35.84).abs() < 0.01, "North Carolina: {nc:?}");
// the anchor at lookup time: under the Kentucky points only the Kentucky commune is found
{
let _scope = crate::rules::scope(rules(true));
let _held = commune_region_scope("lexington", commune_region_points("lexington", "KY"));
let ids = idx.communes_by_name("lexington");
assert_eq!(ids.len(), 1, "{ids:?}");
assert!((idx.commune_coord(ids[0]).0 - 38.05).abs() < 0.01);
}
assert_eq!(idx.communes_by_name("lexington").len(), 2, "scope dropped");
// the tail keeps a region-less reading for the bare code
{
let _scope = crate::rules::scope(rules(true));
let t = city_tail("1 Main Street, Lexington, KY").unwrap();
assert_eq!(t.without_region, "1 Main Street, Lexington");
assert!(t.retry.is_none());
let t = city_tail("1 Main Street, Lexington, KY 40507").unwrap();
assert_eq!(t.without_region, "1 Main Street, Lexington, 40507");
}
// without the table nothing holds: the prominent homonym answers either code
idx.rules = rules(false);
let any = top(&idx, "1 Main Street, Lexington, KY").expect("an answer");
assert!((any.0 - 35.84).abs() < 0.01, "no table, no anchor: {any:?}");
}
#[test]
fn a_table_city_absent_from_the_sheet_is_an_umbrella_of_the_communes_around_its_point() {
// No commune "New York" in the sheet: its neighbourhoods are the communes. The table
// puts New York at (40.7143, -74.0060); East Harlem (9 km) and Downtown Brooklyn
// (3 km) are under the umbrella, Yonkers Mills (30 km) is not. Under an umbrella a
// fuzzy street or a bare place is no answer.
let rows = "\
e 104 st,001,east harlem,10029,10029,177,,-73.9462,40.7906,E 104 St,East Harlem\n\
fulton street,002,downtown brooklyn,11201,11201,1,,-73.9900,40.6930,Fulton Street,Downtown Brooklyn\n\
fulton street,003,yonkers mills,10701,10701,9,,-73.8990,40.9312,Fulton Street,Yonkers Mills\n\
park avenue,001,east harlem,10029,10029,2000,,-73.9440,40.7920,Park Avenue,East Harlem\n";
let mut idx = forward_postcode_index_for_country("umbrella", rows, "xx");
let rules = |table: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "NY".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(16, "avenue".to_owned(), String::new()),
];
if table {
entries.push((27, "new york".to_owned(), "NY 40.7143 -74.0060".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.commune.clone(), h.precision, h.housenumber.clone()))
};
idx.rules = rules(true);
let harlem = top(&idx, "177 E 104 St, New York, NY").expect("an answer");
assert_eq!(
(harlem.0.as_str(), harlem.1, harlem.2.as_deref()),
("East Harlem", "house", Some("177")),
"{harlem:?}"
);
let brooklyn = top(&idx, "1 Fulton Street, New York, NY 11201").expect("an answer");
assert_eq!(brooklyn.0, "Downtown Brooklyn", "{brooklyn:?}");
// 9 Fulton Street exists only in Yonkers Mills, 30 km out: not an answer for New York;
// the neighbour on Downtown Brooklyn's exact street (house 1) answers instead
assert_eq!(
top(&idx, "9 Fulton Street, New York, NY"),
Some(("Downtown Brooklyn".to_owned(), "near", Some("1".to_owned())))
);
// a look-alike street under the umbrella is no answer either (fuzzy "Park Avenu")
assert!(top(&idx, "2000 Parc Avenu, New York, NY").is_none());
// the umbrella is the table's: without it the city is unknown and nothing answers
idx.rules = rules(false);
assert!(top(&idx, "177 E 104 St, New York, NY").is_none());
// the umbrella reads only the anchored city's own name
{
let _scope = crate::rules::scope(rules(true));
let _held = commune_region_scope("new york", vec![(40.7143, -74.0060)]);
assert_eq!(idx.communes_by_name("new york").len(), 2);
assert!(idx.communes_by_name("old york").is_empty());
}
}
#[test]
fn ordinal_street_numbers_are_tried_with_and_without_their_suffix() {
assert_eq!(
ordinal_variants("east 104th street"),
vec!["east 104 street"]
);
assert_eq!(ordinal_variants("s 37 st"), vec!["s 37th st"]);
assert_eq!(ordinal_variants("1 avenue"), vec!["1st avenue"]);
assert_eq!(ordinal_variants("22 avenue"), vec!["22nd avenue"]);
assert_eq!(ordinal_variants("103 street"), vec!["103rd street"]);
assert_eq!(ordinal_variants("11 street"), vec!["11th street"]);
assert_eq!(ordinal_variants("112 street"), vec!["112th street"]);
assert!(ordinal_variants("main street").is_empty());
assert!(
ordinal_variants("12345 street").is_empty(),
"a long code is no ordinal"
);
assert!(ordinal_variants("104thx street").is_empty());
// one word per variant: two numbers give two variants, never both changed at once
assert_eq!(
ordinal_variants("5th and 6 street"),
vec!["5 and 6 street", "5th and 6th street"]
);
// The sheet keys some streets with the suffix and some without, in abbreviated or full
// words; the composed variants reach both ("e 104 st" is the eighth of the list).
let rows = "\
e 104 st,001,harlem,10029,10029,177,,-73.9462,40.7906,E 104 St,Harlem\n\
south 37th street,002,omaha,68105,68105,830,,-95.9680,41.2480,South 37th Street,Omaha\n";
let mut idx = forward_postcode_index_for_country("ordinals", rows, "xx");
let rules = |flag: bool| {
let mut entries = vec![
(24, "east".to_owned(), "e".to_owned()),
(24, "e".to_owned(), "east".to_owned()),
(24, "s".to_owned(), "south".to_owned()),
(24, "south".to_owned(), "s".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "st".to_owned(), "street".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
];
if flag {
entries.push((23, "enabled".to_owned(), "1".to_owned()));
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.street.clone(), h.housenumber.clone(), h.precision))
};
idx.rules = rules(true);
assert_eq!(
top(&idx, "177 East 104th Street, Harlem"),
Some(("E 104 St".to_owned(), Some("177".to_owned()), "house"))
);
assert_eq!(
top(&idx, "830 S 37 St, Omaha"),
Some((
"South 37th Street".to_owned(),
Some("830".to_owned()),
"house"
))
);
{
let _scope = crate::rules::scope(rules(true));
let v = street_data_variants("east 104th street");
assert!(v.contains(&"e 104 st".to_owned()), "{v:?}");
assert!(v.len() <= 10, "{v:?}");
}
// without the flag no ordinal variants: the sheet's spelling must match as written
idx.rules = rules(false);
assert!(top(&idx, "177 East 104th Street, Harlem").is_none());
{
let _scope = crate::rules::scope(rules(false));
assert!(
!street_data_variants("east 104th street").contains(&"east 104 street".to_owned())
);
}
}
#[test]
fn spelled_ordinals_become_numbers_in_both_written_forms() {
assert_eq!(
ordinal_variants("fifth avenue"),
vec!["5 avenue", "5th avenue"]
);
assert_eq!(
ordinal_variants("first street"),
vec!["1 street", "1st street"]
);
assert_eq!(
ordinal_variants("second avenue"),
vec!["2 avenue", "2nd avenue"]
);
assert_eq!(
ordinal_variants("third street"),
vec!["3 street", "3rd street"]
);
assert_eq!(
ordinal_variants("twelfth street"),
vec!["12 street", "12th street"]
);
assert!(ordinal_variants("fifty street").is_empty());
}
#[test]
fn a_trailing_country_segment_is_dropped_before_the_city_tail_is_read() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "NY".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(11, "usa".to_owned(), String::new()),
(11, "united".to_owned(), String::new()),
(11, "states".to_owned(), String::new()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
for q in [
"1 Madison Avenue, New York City, NY, United States",
"1 Madison Avenue, New York City, NY, USA",
"1 Madison Avenue, New York City, NY, United States, USA",
] {
let t = city_tail(q).unwrap_or_else(|| panic!("{q}"));
assert_eq!(
(t.city.as_str(), t.region.as_deref()),
("new york city", Some("NY")),
"{q}"
);
assert_eq!(t.without_region, "1 Madison Avenue, New York City", "{q}");
}
// a last segment that is not a country keeps its place; a country alone is no tail
assert_eq!(
city_tail("1 Madison Avenue, New York City, NY")
.unwrap()
.city,
"new york city"
);
assert!(city_tail("1 Madison Avenue, United States").is_none());
}
#[test]
fn under_the_region_anchor_the_homonym_nearest_the_city_point_wins_and_a_neighbour_counts() {
// "Madison Avenue" exists in Gramercy Park (3 km from the New York point) and in
// Irvington (15 km); both have house 1 and neither commune is "new york". Nearest
// to the point wins. "W 50 St" in Times Square has no house 153: the neighbour on
// the exact street is still an answer under the umbrella.
let rows = "\
madison ave,001,irvington,07111,07111,1,,-74.2349,40.7323,Madison Ave,Irvington\n\
madison ave,002,gramercy park,10010,10010,1,,-73.9876,40.7411,Madison Ave,Gramercy Park\n\
w 50 st,003,times square,10020,10020,159,,-73.9820,40.7610,W 50 St,Times Square\n";
let mut idx = forward_postcode_index_for_country("nearest-homonym", rows, "xx");
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "NY".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "ave".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(27, "new york".to_owned(), "NY 40.7143 -74.0060".to_owned()),
];
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
let top = |q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.commune.clone(), h.housenumber.clone(), h.precision))
};
assert_eq!(
top("1 Madison Ave, New York, NY"),
Some(("Gramercy Park".to_owned(), Some("1".to_owned()), "house"))
);
assert_eq!(
top("153 W 50 St, New York, NY"),
Some(("Times Square".to_owned(), Some("159".to_owned()), "near"))
);
}
#[test]
fn the_query_direction_breaks_the_tie_between_north_and_south_of_one_street() {
// North Broadway stands first in the sheet; both have house 1701 and score alike.
let rows = "\
north broadway street,001,town,66762,66762,1701,,-94.7058,37.4230,North Broadway Street,Town\n\
south broadway street,001,town,66762,66762,1701,,-94.7038,37.3913,South Broadway Street,Town\n";
let mut idx = forward_postcode_index_for_country("direction-tie", rows, "xx");
let entries = vec![
(24, "s".to_owned(), "south".to_owned()),
(24, "south".to_owned(), "s".to_owned()),
(24, "n".to_owned(), "north".to_owned()),
(24, "north".to_owned(), "n".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "st".to_owned(), "street".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(23, "enabled".to_owned(), "1".to_owned()),
(23, "street_type_last".to_owned(), "1".to_owned()),
];
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
let top = |q: &str| idx.query(q, 1).first().map(|h| h.street.clone());
assert_eq!(
top("1701 S Broadway, Town").as_deref(),
Some("South Broadway Street")
);
assert_eq!(
top("1701 N Broadway St, Town").as_deref(),
Some("North Broadway Street")
);
assert_eq!(
top("1701 South Broadway, Town").as_deref(),
Some("South Broadway Street")
);
// no direction in the query: the sheet's order decides, as before
assert_eq!(
top("1701 Broadway, Town").as_deref(),
Some("North Broadway Street")
);
{
let _scope = crate::rules::scope(idx.rules);
let name: HashSet<&str> = ["south", "broadway", "street"].into_iter().collect();
assert!(name_covers_word(&name, "south"));
assert!(name_covers_word(&name, "s"), "through the rewrite");
assert!(
name_covers_word(&name, "st"),
"through the rewrite st -> street"
);
assert!(!name_covers_word(&name, "n") && !name_covers_word(&name, "north"));
let numbered: HashSet<&str> = ["w", "52", "st"].into_iter().collect();
assert!(name_covers_word(&numbered, "52nd") && name_covers_word(&numbered, "52"));
assert!(!name_covers_word(&numbered, "53rd"));
}
}
#[test]
fn junk_tails_and_zip_plus_four_segments_are_read_by_the_city_tail() {
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "PA KY".to_owned()),
(23, "region_names".to_owned(), "kentucky=KY".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "postal_extension".to_owned(), "4".to_owned()),
(23, "junk_tail".to_owned(), "near tel phone".to_owned()),
(11, "usa".to_owned(), String::new()),
];
let _scope = crate::rules::scope(crate::rules::from_section(
&crate::rules::serialize_entries(&entries),
));
let cfg = &crate::rules::rules().city_tail;
// postal segments: five digits, ZIP+4; not a phone, not a longer code
assert_eq!(postal_segment(cfg, "19095"), Some("19095"));
assert_eq!(postal_segment(cfg, "19095-1898"), Some("19095"));
assert_eq!(postal_segment(cfg, "19095-189"), None);
assert_eq!(postal_segment(cfg, "190951898"), None);
assert_eq!(postal_segment(cfg, "(000) 000-0000"), None);
// junk: opening word from the key, a phone number, a country; never a postal code
assert!(junk_tail_segment(cfg, "near the mall"));
assert!(junk_tail_segment(cfg, "Tel. (000) 000-0000"));
assert!(junk_tail_segment(cfg, "(000) 000-0000"));
assert!(junk_tail_segment(cfg, "USA"));
assert!(!junk_tail_segment(cfg, "19095-1898"));
assert!(!junk_tail_segment(cfg, "Louisville"));
assert!(!junk_tail_segment(cfg, "Nearby Heights"));
assert!(
!junk_tail_segment(cfg, "Route 66 Mile 1234567"),
"digits with words are an address"
);
// "…, PA, 19095-1898": the ZIP+4 is a postal segment, Pennsylvania the region
let t = city_tail("1299 Church Rd, Wyncote, PA, 19095-1898").unwrap();
assert_eq!(
(t.city.as_str(), t.region.as_deref()),
("wyncote", Some("PA"))
);
assert_eq!(t.retry.as_deref(), Some("1299 Church Rd, Wyncote, 19095"));
assert_eq!(t.without_region, "1299 Church Rd, Wyncote, 19095");
// an advertisement or a phone after the state is dropped before the grammar
for q in [
"174 N Mill St, Lexington, KENTUCKY, near the mall",
"174 N Mill St, Lexington, KENTUCKY, Tel. (000) 000-0000",
"174 N Mill St, Lexington, KENTUCKY, near the mall, USA",
] {
let t = city_tail(q).unwrap_or_else(|| panic!("{q}"));
assert_eq!(
(t.city.as_str(), t.region.as_deref()),
("lexington", Some("KY")),
"{q}"
);
assert_eq!(t.without_region, "174 N Mill St, Lexington", "{q}");
}
// a tail that is only junk leaves no city
assert!(city_tail("174 N Mill St, near the mall").is_none());
}
#[test]
fn a_weak_answer_in_the_named_city_yields_to_an_exact_house_under_the_umbrella() {
// The commune "Atlanta" (its rows 30 km north of downtown) carries only a misspelt
// look-alike ("Peachtree Streat"); the exact "Peachtree Street"
// with house 1 lives next door under "ATL" (12 km) and, more prominently, in Savannah
// (300 km). The table puts Atlanta between its commune and "ATL" (16 km from each):
// under the umbrella the house in "ATL" is read; without it the fallback stays
// within 25 km of the commune "Atlanta" and never reaches "ATL". "Boston" has the
// exact street with a neighbour house: that neighbour is kept over the next town.
let rows = "\
cherry streat,006,macon,31201,31201,1,,-83.6324,32.8407,Cherry Streat,Macon\n\
cherry street,007,payne city,31204,31204,500,,-83.6700,32.8600,Cherry Street,Payne City\n\
huntington avenue,003,boston,02115,02115,340,,-71.0850,42.3410,Huntington Avenue,Boston\n\
huntington avenue,004,hyde park,02136,02136,343,,-71.1250,42.2550,Huntington Avenue,Hyde Park\n\
peachtree streat,002,atlanta,30305,30305,1,,-84.3400,34.0300,Peachtree Streat,Atlanta\n\
peachtree street,001,atl,30303,30303,1,,-84.3880,33.7580,Peachtree Street,ATL\n\
peachtree street,005,savannah,31401,31401,1,,-81.0998,32.0809,Peachtree Street,Savannah\n\
peachtree street,005,savannah,31401,31401,2,,-81.0990,32.0810,Peachtree Street,Savannah\n\
peachtree street,005,savannah,31401,31401,3,,-81.0980,32.0812,Peachtree Street,Savannah\n";
let mut idx = forward_postcode_index_for_country("umbrella-widen", rows, "xx");
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "GA MA".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "avenue".to_owned(), String::new()),
(27, "atlanta".to_owned(), "GA 33.9000 -84.3600".to_owned()),
(27, "boston".to_owned(), "MA 42.3584 -71.0598".to_owned()),
(27, "macon".to_owned(), "GA 32.8407 -83.6324".to_owned()),
];
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
let top = |q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.commune.clone(), h.street.clone(), h.precision))
};
assert_eq!(
top("1 Peachtree Street, Atlanta, GA"),
Some(("ATL".to_owned(), "Peachtree Street".to_owned(), "house"))
);
assert_eq!(
top("343 Huntington Avenue, Boston, MA"),
Some(("Boston".to_owned(), "Huntington Avenue".to_owned(), "near"))
);
// the umbrella answer must be better: Macon's fuzzy house 1 outranks a mere neighbour
// (house 500) on the exact street in Payne City
assert_eq!(
top("1 Cherry Street, Macon, GA"),
Some(("Macon".to_owned(), "Cherry Streat".to_owned(), "house"))
);
// without a table point for the city nothing widens: the look-alike stays
let mut idx2 = forward_postcode_index_for_country("umbrella-widen-off", rows, "xx");
let mut without: Vec<_> = entries.clone();
without.retain(|(class, key, _)| !(*class == 27 && key == "atlanta"));
idx2.rules = crate::rules::from_section(&crate::rules::serialize_entries(&without));
let plain = idx2.query("1 Peachtree Street, Atlanta, GA", 1);
assert!(
plain.first().is_none_or(|h| h.commune != "ATL"),
"{:?}",
plain.first().map(|h| h.commune.clone())
);
}
#[test]
fn a_range_point_answer_in_the_named_city_does_not_hide_the_house_under_the_umbrella() {
// Same geography as above, but the commune "Atlanta" now holds range points of the
// exact "Peachtree Street" (TIGER, suffix "~") spanning house 1: read alone they give
// an interpolation flagged `range`, which must not stop the umbrella from showing the
// real house 1 in "ATL". Without the table point for Atlanta the range answer stays.
let rows = "\
peachtree street,001,atl,30303,30303,1,,-84.3880,33.7580,Peachtree Street,ATL\n\
peachtree street,002,atlanta,30305,30305,1,~,-84.3400,34.0300,Peachtree Street,Atlanta\n\
peachtree street,002,atlanta,30305,30305,99,~,-84.3410,34.0310,Peachtree Street,Atlanta\n\
peachtree street,005,savannah,31401,31401,1,,-81.0998,32.0809,Peachtree Street,Savannah\n";
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "GA".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "street".to_owned(), String::new()),
(27, "atlanta".to_owned(), "GA 33.9000 -84.3600".to_owned()),
];
let mut idx = forward_postcode_index_for_country("umbrella-range", rows, "xx");
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
let top = idx.query("1 Peachtree Street, Atlanta, GA", 1).remove(0);
assert_eq!((top.commune.as_str(), top.precision), ("ATL", "house"));
// The range answer itself is honest about its origin.
let alone = idx.query("50 Peachtree Street, Atlanta, GA", 1).remove(0);
assert_eq!(
(alone.commune.as_str(), alone.precision),
("Atlanta", "interp")
);
assert!(alone.flags.contains(&"range"), "{:?}", alone.flags);
assert_eq!(alone.housenumber.as_deref(), Some("50"));
// A snap onto a range point (beyond the range's end) is flagged too.
let snapped = idx.query("260 Peachtree Street, Atlanta, GA", 1).remove(0);
assert_eq!(
(snapped.commune.as_str(), snapped.precision),
("Atlanta", "near")
);
assert!(snapped.flags.contains(&"range"), "{:?}", snapped.flags);
assert_eq!(snapped.housenumber.as_deref(), Some("99"));
let mut idx2 = forward_postcode_index_for_country("umbrella-range-off", rows, "xx");
let mut without = entries.clone();
without.retain(|(class, key, _)| !(*class == 27 && key == "atlanta"));
idx2.rules = crate::rules::from_section(&crate::rules::serialize_entries(&without));
let plain = idx2.query("1 Peachtree Street, Atlanta, GA", 1).remove(0);
assert_eq!(
(plain.commune.as_str(), plain.precision),
("Atlanta", "interp")
);
}
#[test]
fn a_cityless_homonym_goes_to_the_larger_commune_when_the_sheet_says_so() {
// The sheet's anchor is "Capital" (20 addresses, the most prominent commune). "Oak
// Street 10" exists in Smallville (one address, 20 km from the anchor) and in Bigtown
// (seven addresses, 300 km away). Equal score and name: the anchor distance picks
// Smallville; with city_tail `homonym_prominence` the commune size picks Bigtown.
let mut rows = String::new();
for n in 1..=20 {
rows.push_str(&format!(
"elm street,001,capital,10000,10000,{n},,-80.0000,40.{:04},Elm Street,Capital\n",
n * 10
));
}
rows.push_str(
"oak street,002,bigtown,30000,30000,10,,-80.0000,43.0000,Oak Street,Bigtown\n",
);
rows.push_str(
"oak street,003,smallville,20000,20000,10,,-80.2000,40.1000,Oak Street,Smallville\n",
);
for n in 1..=6 {
rows.push_str(&format!(
"pine street,002,bigtown,30000,30000,{n},,-80.0010,43.00{n:02},Pine Street,Bigtown\n"
));
}
let plain = vec![(23, "enabled".to_owned(), "1".to_owned())];
let mut by_size = plain.clone();
by_size.push((23, "homonym_prominence".to_owned(), "1".to_owned()));
let mut idx = forward_postcode_index_for_country("homonym-size", &rows, "xx");
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&plain));
let top = idx.query("10 Oak Street", 2).remove(0);
assert_eq!(
(top.commune.as_str(), top.precision),
("Smallville", "house")
);
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&by_size));
let top = idx.query("10 Oak Street", 2).remove(0);
assert_eq!((top.commune.as_str(), top.precision), ("Bigtown", "house"));
// A named city keeps its own reading.
let named = idx.query("10 Oak Street, Smallville", 1).remove(0);
assert_eq!(
(named.commune.as_str(), named.precision),
("Smallville", "house")
);
}
#[test]
fn the_homonym_weight_is_the_size_of_the_place_not_of_the_commune_alone() {
// Midtown (three addresses) and Downtown (six, 5 km away) are one place of nine;
// Bigtown (seven) is 300 km from both and from the anchor Capital. By its own count
// Bigtown would win; by the place's count Midtown does. Without the flag the anchor
// distance decides (Capital is nearest to Midtown here too, so Midtown either way is
// not the observer): the flagged reading is compared with the own-count reading only.
let mut rows = String::new();
for n in 1..=20 {
rows.push_str(&format!(
"elm street,001,capital,10000,10000,{n},,-80.0000,40.{:04},Elm Street,Capital\n",
n * 10
));
}
for n in 1..=6 {
rows.push_str(&format!(
"main street,004,downtown,20100,20100,{n},,-80.0500,36.00{n:02},Main Street,Downtown\n"
));
}
rows.push_str(
"oak street,002,bigtown,30000,30000,10,,-80.0000,43.0000,Oak Street,Bigtown\n",
);
rows.push_str(
"oak street,003,midtown,20000,20000,10,,-80.0000,36.0000,Oak Street,Midtown\n",
);
for n in 1..=6 {
rows.push_str(&format!(
"pine street,002,bigtown,30000,30000,{n},,-80.0010,43.00{n:02},Pine Street,Bigtown\n"
));
}
for n in 1..=2 {
rows.push_str(&format!(
"pine street,003,midtown,20000,20000,{n},,-80.0010,36.00{n:02},Pine Street,Midtown\n"
));
}
// The table is built when the sheet opens, from the sheet's own rules section: build
// the fixture with a rules directory that carries the flag.
let dir = std::env::temp_dir().join(format!(
"gridpin-homonym-area-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(dir.join("rules")).unwrap();
let _scratch = Scratch::keep(&dir);
let csv = dir.join("addresses.csv");
std::fs::write(
&csv,
format!(
"nom_voie_norm,code_insee,nom_commune_norm,code_postal,code_postal_display,numero,rep,lon,lat,nom_voie,nom_commune\n{rows}"
),
)
.unwrap();
std::fs::write(
dir.join("rules/city_tail.tsv"),
"enabled\t1\nhomonym_prominence\t1\n",
)
.unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
r#"{"country":"xx","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
let bin = dir.join("addresses.bin");
crate::builder::build(
&csv,
&bin,
None,
None,
Some(&dir.join("rules")),
None,
Some(&manifest),
)
.unwrap();
let idx = Index::open(&bin).unwrap();
assert_eq!(
idx.area_prominence.len(),
4,
"table built for the flagged sheet"
);
let top = idx.query("10 Oak Street", 2).remove(0);
assert_eq!((top.commune.as_str(), top.precision), ("Midtown", "house"));
}
#[test]
fn a_prefix_drop_that_leaves_only_the_type_and_the_city_is_no_street() {
// Boise has no "Grove Street" but a dozen streets with the word "grove" (so the
// word-subset pass declines them as a frequent word); Nampa has a "Boise Street".
// Dropping "619 grove" leaves "st boise": the city written as a street, never an
// answer. A remainder that keeps a street word ("hotel" dropped before "main street
// springfield") is still read.
let mut lines = vec![
"boise street,002,nampa,83651,83651,5,,-116.4000,43.6000,Boise Street,Nampa".to_owned(),
"main street,003,springfield,62701,62701,7,,-89.6500,39.8000,Main Street,Springfield"
.to_owned(),
"w grove st,001,boise,83702,83702,619,,-116.2000,43.6100,W Grove St,Boise".to_owned(),
];
for (i, name) in [
"n maple grove rd",
"s maple grove rd",
"n lakegrove ln",
"e foxgrove dr",
"s grove ave",
"n ashgrove ln",
"w groveview ln",
"s atwell grove ave",
"n maple grove ct",
"w eagle grove st",
]
.iter()
.enumerate()
{
// Every one of them has a house 100: that number tells nothing apart.
lines.push(format!(
"{name},001,boise,83702,83702,100,,-116.21{i:02},43.6100,{name},Boise"
));
}
lines.sort();
let rows = lines.join("\n") + "\n";
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "ID IL".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "street_type_last".to_owned(), "1".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
];
let mut idx = forward_postcode_index_for_country("drop-type-city", &rows, "xx");
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
// A street Boise does not have at all: the fuzzy passes find nothing, the prefix drop
// is left with "st boise", and Nampa's "Boise Street" must not answer.
let junk = idx.query("619 Zorbas St, Boise", 1);
assert!(
junk.first().is_none_or(|h| h.commune != "Nampa"),
"{:?}",
junk.first().map(|h| (h.street.clone(), h.commune.clone()))
);
// The real "W Grove St" still answers the query that omits the direction.
let grove = idx.query("619 Grove St, Boise", 1).remove(0);
assert_eq!(
(grove.commune.as_str(), grove.street.as_str()),
("Boise", "W Grove St")
);
// Without the type word only the word-subset pass can read "grove"; it meets eleven
// Boise streets with that word, more than its cap, and the house number tells them
// apart: only "W Grove St" has a 619. Without a number the cap holds.
let by_number = idx.query("619 Grove, Boise", 1).remove(0);
assert_eq!(
(
by_number.commune.as_str(),
by_number.street.as_str(),
by_number.precision
),
("Boise", "W Grove St", "house")
);
// (A number shared by all ten streets reaches a house through the exact word pass of
// this small fixture before the subset pass is consulted; the cap after the number
// filter is therefore not observable here and is judged on the sets.)
let kept = idx.query("Hotel Main Street, Springfield", 1).remove(0);
assert_eq!(
(kept.commune.as_str(), kept.street.as_str()),
("Springfield", "Main Street")
);
// The helper itself: places and regions only, or a street word survives (the region
// codes come from the sheet's rules, scoped as a query scopes them).
let _scope = crate::rules::scope(idx.rules);
assert!(idx.remainder_names_only_places(&["boise", "id", "83702"]));
assert!(idx.remainder_names_only_places(&["boise"]));
assert!(!idx.remainder_names_only_places(&["main", "street", "springfield"]));
assert!(!idx.remainder_names_only_places(&[]));
assert!(!idx.remainder_names_only_places(&["83702"]));
}
#[test]
fn a_leading_number_word_is_the_house_number_on_a_trailing_type_sheet() {
let on = crate::rules::from_section(&crate::rules::serialize_entries(&[
(23, "enabled".to_owned(), "1".to_owned()),
(23, "street_type_last".to_owned(), "1".to_owned()),
]));
let off = crate::rules::from_section(&crate::rules::serialize_entries(&[(
23,
"enabled".to_owned(),
"1".to_owned(),
)]));
{
let _scope = crate::rules::scope(on);
assert_eq!(
spelled_house_number("One Campus Rd, Staten Island, NY").as_deref(),
Some("1 Campus Rd, Staten Island, NY")
);
assert_eq!(
spelled_house_number("TWELVE Oaks Lane").as_deref(),
Some("12 Oaks Lane")
);
assert_eq!(
spelled_house_number(" ten Main Street").as_deref(),
Some("10 Main Street")
);
// a number word followed by a digit or another number word is not a house number
assert!(spelled_house_number("One 5th Avenue").is_none());
assert!(spelled_house_number("One Two Three Road").is_none());
assert!(spelled_house_number("Main Street 1").is_none());
assert!(spelled_house_number("One").is_none());
}
{
let _scope = crate::rules::scope(off);
assert!(spelled_house_number("One Campus Rd, Staten Island, NY").is_none());
}
}
#[test]
fn hits_quality_orders_precision_then_exact_street_then_exact_commune() {
let mk = |precision: &'static str, flags: Vec<&'static str>| {
let mut w = city_tail_witness(precision, "Town", 1.0);
w.0.flags = flags;
vec![w]
};
let house_exact = mk("house", vec!["street_exact", "commune_exact"]);
let house_fuzzy = mk("house", vec!["street_fuzzy", "commune_exact"]);
let near_exact = mk("near", vec!["street_exact", "commune_exact"]);
let interp = mk("interp", vec!["street_exact"]);
assert!(hits_quality(&house_exact) > hits_quality(&house_fuzzy));
assert!(hits_quality(&house_fuzzy) > hits_quality(&interp));
assert!(hits_quality(&interp) > hits_quality(&near_exact));
assert!(hits_quality(&near_exact) > hits_quality(&[]));
assert_eq!(hits_quality(&[]), (0, false, false));
}
#[test]
fn ranking_with_a_postcode_is_a_total_order_when_some_houses_lack_one() {
// Same street name in several communes, houses with and without a postcode: the
// postcode-proximity tie-break used to call "no postcode" equal to everything, the
// order was not transitive, and the sort panicked — a silent empty answer behind the
// CLI's panic boundary (Baltimore MD, 22.10.2026: 31 + 38 rows of the US sets).
let mut rows = String::new();
for (i, (insee, pc)) in [
("001", "21218"),
("002", ""),
("003", "21202"),
("004", ""),
("005", "21210"),
("006", ""),
("007", "21230"),
("008", ""),
("009", "21201"),
("010", ""),
("011", "21250"),
("012", ""),
]
.iter()
.enumerate()
{
rows.push_str(&format!(
"main street,{insee},town {i},{pc},{pc},10,,{},{},Main Street,Town {i}\n",
-76.60 + i as f64 * 0.01,
39.30 + i as f64 * 0.01
));
}
let idx = forward_postcode_index_for_country("total-order", &rows, "xx");
let hits = idx.query("10 Main Street, 21218", 5);
assert!(
!hits.is_empty(),
"the ranking must answer, not panic into silence"
);
let order: Vec<(String, String)> = hits
.iter()
.map(|h| (h.commune.clone(), h.postcode.clone()))
.collect();
assert_eq!(hits[0].postcode, "21218", "{order:?}");
// candidates without a postcode sort after every candidate with one
let first_blank = order.iter().position(|(_, pc)| pc.is_empty());
let last_coded = order.iter().rposition(|(_, pc)| !pc.is_empty());
if let (Some(blank), Some(coded)) = (first_blank, last_coded) {
assert!(coded < blank, "{order:?}");
}
// a postcode of the same area that matches nobody exactly: the coded candidates score
// alike and the tie-break orders them, the closest postcode first (a postcode of another
// area would reject the coded candidates outright and never reach the tie-break)
let hits = idx.query("10 Main Street, 21299", 12);
let order: Vec<String> = hits.iter().map(|h| h.postcode.clone()).collect();
assert!(order.len() >= 6, "{order:?}");
assert_eq!(order[0], "21250", "closest to 21299 first: {order:?}");
assert_eq!(order[1], "21230", "{order:?}");
let blanks: Vec<usize> = (0..order.len()).filter(|&i| order[i].is_empty()).collect();
let coded: Vec<usize> = (0..order.len()).filter(|&i| !order[i].is_empty()).collect();
if let (Some(b), Some(c)) = (blanks.iter().min(), coded.iter().max()) {
assert!(c < b, "{order:?}");
}
assert_eq!(score_key(f32::NAN), f32::NEG_INFINITY);
assert_eq!(score_key(2.5), 2.5);
}
#[test]
fn direction_after_the_house_number_is_tried_as_a_street_word_before_a_suffix() {
// Two Lexingtons: Kentucky keys the street with its direction, North Carolina without;
// Salt Lake City keeps the direction as a house suffix ("15 e"). The sheet declares the
// trailing type and the rewrite "n" -> "north"; nothing is special-cased by country.
let mut idx = forward_postcode_index_for_country(
"direction-first",
"mill street,002,lexington,27295,27295,174,,-80.26,35.84,Mill Street,Lexington\n\
north mill st,001,lexington,40507,40507,174,,-84.49,38.05,North Mill St,Lexington\n\
north temple street,003,salt lake city,84150,84150,15,,-111.80,40.70,North Temple Street,Salt Lake City\n\
north temple street,003,salt lake city,84150,84150,15,e,-111.89,40.77,North Temple Street,Salt Lake City\n\
oak avenue,004,elsewhere,10000,10000,7,n,-70.00,40.00,Oak Avenue,Elsewhere\n",
"xx",
);
let rules = |flag: bool| {
let mut entries = vec![
(24, "n".to_owned(), "north".to_owned()),
(24, "north".to_owned(), "n".to_owned()),
(24, "e".to_owned(), "east".to_owned()),
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
];
if flag {
entries.push((23, "enabled".to_owned(), "1".to_owned()));
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let top = |idx: &Index, q: &str| {
idx.query(q, 1).first().map(|h| {
(
h.commune.clone(),
h.street.clone(),
h.housenumber.clone(),
h.lat,
h.precision,
)
})
};
idx.rules = rules(true);
let ky = top(&idx, "174 N Mill St, Lexington").expect("an answer");
assert_eq!(ky.0, "Lexington");
assert_eq!(ky.1, "North Mill St", "{ky:?}");
assert!(
(ky.3 - 38.05).abs() < 0.01,
"Kentucky, not North Carolina: {ky:?}"
);
// the suffix hypothesis is second, not gone: "15 e" is still the house 15e, not 15
let slc = top(&idx, "15 E North Temple St, Salt Lake City").expect("an answer");
assert_eq!(
(slc.0.as_str(), slc.2.as_deref(), slc.4),
("Salt Lake City", Some("15e"), "house"),
"{slc:?}"
);
assert!((slc.3 - 40.77).abs() < 0.001, "house 15e, not 15: {slc:?}");
// the word is a street word only under the flag, and only when the sheet rewrites it
{
let _scope = crate::rules::scope(rules(true));
assert!(street_rewrite_word("n") && !street_rewrite_word("mill"));
}
{
let _scope = crate::rules::scope(rules(false));
assert!(!street_rewrite_word("n"));
}
// without the flag the sheet keeps the old order: the suffix hypothesis answers first
idx.rules = rules(false);
let nc = top(&idx, "174 N Mill St, Lexington").expect("an answer");
assert!(
(nc.3 - 35.84).abs() < 0.01,
"flag off keeps the old order: {nc:?}"
);
}
#[test]
fn a_house_number_before_a_two_letter_direction_is_not_a_dutch_postcode_on_a_trailing_type_sheet(
) {
// "3017 SE Milwaukie Avenue": four digits and two letters have the shape of a Dutch
// postcode ("1012 NZ"), and that reading used to swallow the house number. A sheet
// whose street rewrites know the two letters as a street word ("se" -> "southeast",
// under a trailing type) reads them as house number and direction. Data-driven: the
// same query on a sheet without the flag keeps the Dutch reading.
let mut idx = forward_postcode_index_for_country(
"direction-two-letters",
"north temple street,003,salt lake city,84150,84150,15,e,-111.89,40.77,North Temple Street,Salt Lake City\n\
south mill street,001,portland,97202,97202,174,,-122.66,45.51,South Mill Street,Portland\n\
southeast milwaukie avenue,001,portland,97202,97202,3017,,-122.65,45.50,Southeast Milwaukie Avenue,Portland\n\
southeast milwaukie avenue,001,portland,97202,97202,3019,,-122.65,45.50,Southeast Milwaukie Avenue,Portland\n",
"xx",
);
let rules = |flag: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "OR UT".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "postal_extension".to_owned(), "4".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(16, "avenue".to_owned(), String::new()),
(16, "ave".to_owned(), String::new()),
(24, "se".to_owned(), "southeast".to_owned()),
(24, "southeast".to_owned(), "se".to_owned()),
(24, "s".to_owned(), "south".to_owned()),
(24, "south".to_owned(), "s".to_owned()),
(24, "ave".to_owned(), "avenue".to_owned()),
(24, "avenue".to_owned(), "ave".to_owned()),
];
if flag {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.street.clone(), h.housenumber.clone(), h.precision))
};
idx.rules = rules(true);
for q in [
"3017 SE Milwaukie Avenue, Portland, OR 97202",
"3017 SE Milwaukie Avenue",
"3017 SE Milwaukie Ave, Portland",
] {
assert_eq!(
top(&idx, q),
Some((
"Southeast Milwaukie Avenue".to_owned(),
Some("3017".to_owned()),
"house"
)),
"{q}"
);
}
// One letter never had the Dutch shape and keeps working.
assert_eq!(
top(&idx, "174 S Mill Street, Portland, OR 97202"),
Some((
"South Mill Street".to_owned(),
Some("174".to_owned()),
"house"
))
);
// Without the flag the sheet knows no street words, and the pair stays a postcode:
// the house number is gone and no house answers.
idx.rules = rules(false);
let nl = top(&idx, "3017 SE Milwaukie Avenue, Portland, OR 97202");
assert_ne!(
nl.as_ref().and_then(|h| h.1.clone()).as_deref(),
Some("3017"),
"{nl:?}"
);
}
#[test]
fn unit_segments_country_words_dotted_names_and_an_unknown_city_with_a_postal_code() {
// Four forms of one sheet (US, 22.10.2026), all data-driven: a junk segment between the
// street and the city ("Suite 200", from junk_tail), country words glued to the postal
// segment ("20852 USA", from countries_tail), a dot inside the city name ("St. Louis"),
// and a city the sheet has no commune for ("New Hamburg") read by its postal code alone.
let mut idx = forward_postcode_index_for_country(
"tail-forms",
"greene street,001,augusta,30901,30901,1301,,-81.97,33.47,Greene Street,Augusta\n\
marinelli road,002,rockville,20852,20852,5500,,-77.11,39.05,Marinelli Road,Rockville\n\
meridian street north,007,huntsville,35762,35762,4900,,-86.57,34.79,Meridian Street North,Huntsville\n\
north 7th street,003,st louis,63101,63101,411,,-90.19,38.63,North 7th Street,St Louis\n\
other road,006,nearby,12591,12591,5,,-73.90,41.60,Other Road,Nearby\n\
water street,004,wappingers falls,12590,12590,1,,-73.93,41.59,Water Street,Wappingers Falls\n\
water street,005,elsewhere,10001,10001,1,,-74.00,40.75,Water Street,Elsewhere\n\
west park street,008,normal,61761,61761,1,,-88.99,40.51,West Park Street,Normal\n",
"xx",
);
let entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "AL GA IL MD MO NY".to_owned()),
(
23,
"region_names".to_owned(),
"new york=NY;georgia=GA".to_owned(),
),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(23, "postal_extension".to_owned(), "4".to_owned()),
(23, "street_type_last".to_owned(), "1".to_owned()),
(23, "junk_tail".to_owned(), "near tel suite ga".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "road".to_owned(), String::new()),
(11, "usa".to_owned(), String::new()),
(11, "us".to_owned(), String::new()),
(24, "n".to_owned(), "north".to_owned()),
(24, "north".to_owned(), "n".to_owned()),
];
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&entries));
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.commune.clone(), h.housenumber.clone(), h.precision))
};
let house =
|commune: &str, n: &str| Some((commune.to_owned(), Some(n.to_owned()), "house"));
// "Normal, AL" is no commune of the sheet and has no table point; the Normal of Illinois
// answers as a bare place. The postal code of the tail names the Alabama street (kept
// under Huntsville), written without its direction.
assert_eq!(
top(&idx, "4900 Meridian Street, Normal, AL 35762"),
house("Huntsville", "4900")
);
// the tail grammar itself
{
let _scope = crate::rules::scope(idx.rules);
let tail = city_tail("1301 Greene Street, Suite 200, Augusta, GA 30901").unwrap();
assert_eq!(tail.city, "augusta");
assert_eq!(tail.without_region, "1301 Greene Street, Augusta, 30901");
let tail = city_tail("5500 Marinelli Road, Rockville, MD 20852 USA").unwrap();
assert_eq!(
(tail.city.as_str(), tail.region.as_deref()),
("rockville", Some("MD"))
);
let tail = city_tail("411 N 7th Street, St. Louis, MO 63101").unwrap();
assert_eq!(tail.city, "st louis");
let tail = city_tail("1 Water Street, New Hamburg, New York 12590").unwrap();
assert_eq!(tail.without_city.as_deref(), Some("1 Water Street, 12590"));
assert!(city_tail("1 Water Street, New Hamburg, NY")
.unwrap()
.without_city
.is_none());
assert_eq!(strip_trailing_country_words("MD 20852 USA"), "MD 20852");
// a region segment is never junk, even when a junk word spells like its code
let cfg = &idx.rules.city_tail;
assert!(!junk_tail_segment(cfg, "GA 30901"));
assert!(!junk_tail_segment(cfg, "GA"));
assert!(junk_tail_segment(cfg, "Suite 200"));
assert_eq!(strip_trailing_country_words("20852"), "20852");
}
assert_eq!(
top(&idx, "1301 Greene Street, Suite 200, Augusta, GA 30901"),
house("Augusta", "1301")
);
for q in [
"5500 Marinelli Road, Rockville, MD 20852 USA",
"5500 Marinelli Road, Rockville, MD 20852 U.S.",
] {
assert_eq!(top(&idx, q), house("Rockville", "5500"), "{q}");
}
assert_eq!(
top(&idx, "411 N 7th Street, St. Louis, MO 63101"),
house("St Louis", "411")
);
// the unknown city: the postal code picks Wappingers Falls, not the Water Street of 10001
for q in [
"1 Water Street, New Hamburg, New York 12590",
"1 Water Street, New Hamburg, NY 12590",
] {
assert_eq!(top(&idx, q), house("Wappingers Falls", "1"), "{q}");
}
// without a postal code the unknown city stays unknown; a code the sheet lacks answers
// nothing; a code the sheet has but without that street answers nothing either (the
// Water Street of 12590 or 10001 is not inside 12591)
assert_eq!(top(&idx, "1 Water Street, New Hamburg, NY"), None);
assert_eq!(top(&idx, "1 Water Street, New Hamburg, NY 99999"), None);
assert_eq!(top(&idx, "1 Water Street, New Hamburg, NY 12591"), None);
// a city the sheet does know keeps its own reading: a conflicting code does not send the
// query to another town's house
assert_eq!(top(&idx, "1 Water Street, Elsewhere, NY 12590"), None);
}
#[test]
fn a_street_written_without_its_direction_is_the_exact_street_under_a_region_anchor() {
// Atlanta is an umbrella (its houses live under "ATL"); the sheet keeps the direction
// the writer dropped. "303 Peachtree Street" reaches the neighbour on Peachtree Street
// Northwest, not Peachtree Center Avenue (an extra word that is no rewrite); in Little
// Rock, a commune of the sheet, "1500 Park Street" is the house on South Park Street
// instead of the bare place or the exact "Park Street" of North Little Rock next door. Without the trailing-type flag the umbrella keeps its
// strict reading.
let mut idx = forward_postcode_index_for_country(
"direction-omitted",
"madison avenue,004,midtown,10010,10010,1,,-73.9870,40.7410,Madison Avenue,Midtown\n\
madison avenue north,005,harlem,10035,10035,1,,-73.9350,40.8050,Madison Avenue North,Harlem\n\
park street,003,north little rock,72114,72114,1500,,-92.2600,34.7700,Park Street,North Little Rock\n\
peachtree center avenue,001,atl,30303,30303,303,,-84.3870,33.7600,Peachtree Center Avenue,ATL\n\
peachtree street northwest,001,atl,30308,30308,300,,-84.3880,33.7580,Peachtree Street Northwest,ATL\n\
south park street,002,little rock,72202,72202,1500,,-92.2900,34.7300,South Park Street,Little Rock\n",
"xx",
);
let rules = |flag: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "GA AR NY".to_owned()),
(
23,
"region_names".to_owned(),
"georgia=GA;arkansas=AR;new york=NY".to_owned(),
),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "avenue".to_owned(), String::new()),
(24, "nw".to_owned(), "northwest".to_owned()),
(24, "northwest".to_owned(), "nw".to_owned()),
(24, "s".to_owned(), "south".to_owned()),
(24, "south".to_owned(), "s".to_owned()),
(24, "n".to_owned(), "north".to_owned()),
(24, "north".to_owned(), "n".to_owned()),
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "ave".to_owned(), "avenue".to_owned()),
(24, "avenue".to_owned(), "ave".to_owned()),
(27, "atlanta".to_owned(), "GA 33.7490 -84.3880".to_owned()),
(
27,
"little rock".to_owned(),
"AR 34.7465 -92.2896".to_owned(),
),
(
27,
"new york city".to_owned(),
"NY 40.7128 -74.0060".to_owned(),
),
];
if flag {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.street.clone(), h.housenumber.clone(), h.precision))
};
{
let _scope = crate::rules::scope(rules(true));
assert!(street_differs_only_by_rewrite_words(
"303 Peachtree Street",
"PEACHTREE Street Northwest"
));
assert!(street_differs_only_by_rewrite_words(
"1500 Park Street",
"South Park Street"
));
assert!(!street_differs_only_by_rewrite_words(
"303 Peachtree Street",
"Peachtree Center Avenue"
));
assert!(!street_differs_only_by_rewrite_words(
"303 Street",
"South Street"
));
// a direction the query writes must survive, as written or rewritten
assert!(!street_differs_only_by_rewrite_words(
"1801 N Cottonwood",
"South Cottonwood Street"
));
assert!(street_differs_only_by_rewrite_words(
"1801 N Cottonwood",
"North Cottonwood Street"
));
// a type the query writes is part of the name: Avenue is not St, Boulevard not Plz
assert!(!street_differs_only_by_rewrite_words(
"1 Madison Avenue",
"Madison St"
));
assert!(!street_differs_only_by_rewrite_words(
"33-09 Queens Boulevard",
"Queens Plz S"
));
}
{
let _scope = crate::rules::scope(rules(false));
assert!(!street_differs_only_by_rewrite_words(
"303 Peachtree Street",
"Peachtree Street Northwest"
));
}
idx.rules = rules(true);
assert_eq!(
top(&idx, "303 Peachtree Street, Atlanta, Georgia"),
Some((
"Peachtree Street Northwest".to_owned(),
Some("300".to_owned()),
"near"
))
);
assert_eq!(
top(&idx, "1500 Park Street, Little Rock, AR 72202"),
Some((
"South Park Street".to_owned(),
Some("1500".to_owned()),
"house"
))
);
// Exact first: under the New York umbrella both Madison Avenues carry house 1; the exact
// one answers, whatever order the relaxed one would take.
assert_eq!(
top(&idx, "1 Madison Avenue, New York City, NY"),
Some(("Madison Avenue".to_owned(), Some("1".to_owned()), "house"))
);
idx.rules = rules(false);
assert_ne!(
top(&idx, "303 Peachtree Street, Atlanta, Georgia").map(|h| h.2),
Some("near"),
"without the flag the umbrella keeps its strict reading"
);
}
#[test]
fn a_leading_five_digit_number_is_the_house_on_a_trailing_type_sheet() {
// "11631 Moonmist Dr, Houston, TX 77072": the five digits that open the query used to be
// read as a postal code (the French/Italian shape), and the house was never looked up.
// On a sheet with a trailing type the opening number is the house; the ZIP still closes
// the tail. A sheet without the flag keeps the postal reading; a code alone stays a code.
let mut idx = forward_postcode_index_for_country(
"leading-five",
"main street,002,houston,77036,77036,7650,,-95.52,29.70,Main Street,Houston\n\
moonmist drive,001,houston,77072,77072,11631,,-95.5846,29.7082,Moonmist Drive,Houston\n",
"xx",
);
let rules = |flag: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "TX".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "drive".to_owned(), String::new()),
(16, "dr".to_owned(), String::new()),
(24, "dr".to_owned(), "drive".to_owned()),
(24, "drive".to_owned(), "dr".to_owned()),
];
if flag {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.housenumber.clone(), h.precision, h.postcode.clone()))
};
idx.rules = rules(true);
for q in [
"11631 Moonmist Dr, Houston, TX 77072",
"11631 Moonmist Drive, 77072",
"11631 Moonmist Dr, Houston",
] {
assert_eq!(
top(&idx, q),
Some((Some("11631".to_owned()), "house", "77072".to_owned())),
"{q}"
);
}
// a four-digit house keeps working, a code alone is still a code
assert_eq!(
top(&idx, "7650 Main Street, Houston, TX 77036").map(|h| h.1),
Some("house")
);
let code = idx.query("77072", 1);
assert!(
code.first().is_none_or(|h| h.housenumber.is_none()),
"{:?}",
code.first().map(|h| (h.housenumber.clone(), h.precision))
);
// without the flag the opening five digits stay a postal code: no house 11631
idx.rules = rules(false);
assert_ne!(
top(&idx, "11631 Moonmist Dr, Houston, TX 77072").and_then(|h| h.0),
Some("11631".to_owned())
);
}
#[test]
fn floor_designators_a_lone_basement_and_a_numbered_designator_segment_are_read_past() {
let rules = |flag: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "NJ AZ".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(
23,
"junk_tail".to_owned(),
"suite ste floor basement".to_owned(),
),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(16, "ave".to_owned(), String::new()),
];
if flag {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
let _scope = crate::rules::scope(rules(true));
assert_eq!(
strip_unit_designators("138 Nassau St 2nd floor, Princeton, NJ 08542").as_deref(),
Some("138 Nassau St, Princeton, NJ 08542")
);
assert_eq!(
strip_unit_designators("22 Front St 2nd Floor, Worcester, MA 01608").as_deref(),
Some("22 Front St, Worcester, MA 01608")
);
assert_eq!(
strip_unit_designators("143 Newark Ave Basement, Jersey City, NJ 07302").as_deref(),
Some("143 Newark Ave, Jersey City, NJ 07302")
);
assert_eq!(
strip_unit_designators("2 N Central Ave 18th and 19th Floor, Phoenix, AZ").as_deref(),
Some("2 N Central Ave, Phoenix, AZ")
);
// a number that is no designator count, and a street that ends in a plain word
assert!(strip_unit_designators("138 Nassau St 2nd, Princeton, NJ").is_none());
// an ordinal before a plain street word is the street's own number, not a floor
assert!(strip_unit_designators("500 W 2nd St, Boise, ID").is_none());
assert!(strip_unit_designators("138 Nassau Street, Princeton, NJ").is_none());
// the designator segment of its own is read past by the tail grammar
let tail = city_tail("Two North Central Ave, 18th and 19th Floor, Phoenix, AZ 85004")
.expect("tail");
assert_eq!(tail.city, "phoenix");
assert_eq!(tail.without_region, "Two North Central Ave, Phoenix, 85004");
let cfg = &crate::rules::rules().city_tail;
assert!(junk_tail_segment(cfg, "18th and 19th Floor"));
assert!(junk_tail_segment(cfg, "Floor 2"));
assert!(!junk_tail_segment(cfg, "18th Street"));
assert!(!junk_tail_segment(cfg, "18th and 19th"));
}
#[test]
fn two_directions_and_a_type_are_spelled_out_in_one_variant() {
let rules = |flag: bool| {
let mut entries = vec![
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "n".to_owned(), "north".to_owned()),
(24, "north".to_owned(), "n".to_owned()),
(24, "e".to_owned(), "east".to_owned()),
(24, "east".to_owned(), "e".to_owned()),
(16, "st".to_owned(), String::new()),
(16, "street".to_owned(), String::new()),
(24, "ave".to_owned(), "avenue".to_owned()),
(24, "avenue".to_owned(), "ave".to_owned()),
(16, "ave".to_owned(), String::new()),
(16, "avenue".to_owned(), String::new()),
];
if flag {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
{
let _scope = crate::rules::scope(rules(true));
let variants = street_data_variants("e 1st n st");
assert!(
variants.iter().any(|v| v == "east 1st north street"),
"{variants:?}"
);
// a type word inside the name is Saint, not a type: only the closing one is spelled out
let v = street_data_variants("old st james st");
assert!(!v.iter().any(|x| x.starts_with("old street")), "{v:?}");
// a type before a closing direction is spelled out with it
assert!(street_data_variants("e 1st st n")
.iter()
.any(|x| x == "east 1st street north"));
// … and before a one-letter name or a road number
assert!(street_data_variants("e ave m")
.iter()
.any(|x| x == "east avenue m"));
// nothing to spell out: no extra variant
assert!(!street_data_variants("east 1st north street")
.iter()
.any(|v| v == "east 1st north street"));
}
{
let _scope = crate::rules::scope(rules(false));
let variants = street_data_variants("e 1st n st");
assert!(
!variants.iter().any(|v| v == "east 1st north street"),
"{variants:?}"
);
}
}
#[test]
fn a_city_shortened_to_st_is_read_again_as_saint() {
let mut idx = forward_postcode_index_for_country(
"saint-city",
"main street,002,stockton,95202,95202,1,,-121.29,37.95,Main Street,Stockton\n\
south main street,001,saint george,84770,84770,1,,-113.58,37.10,South Main Street,Saint George\n",
"xx",
);
let rules = |flag: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "UT CA".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "s".to_owned(), "south".to_owned()),
(24, "south".to_owned(), "s".to_owned()),
];
if flag {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
{
let _scope = crate::rules::scope(rules(true));
assert_eq!(
saint_city_variant("1 S Main St, St. George, UT 84770").as_deref(),
Some("1 S Main St, Saint George, UT 84770")
);
assert_eq!(
saint_city_variant("1 S Main St, St George, UT 84770").as_deref(),
Some("1 S Main St, Saint George, UT 84770")
);
assert!(saint_city_variant("1 Main St, Stockton, CA 95202").is_none());
assert!(saint_city_variant("1 S Main St, Saint George, UT 84770").is_none());
}
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.housenumber.clone(), h.precision))
};
idx.rules = rules(true);
assert_eq!(
top(&idx, "1 S Main St, St. George, UT 84770"),
Some((Some("1".to_owned()), "house"))
);
assert_eq!(
top(&idx, "1 S Main St, Saint George, UT 84770"),
Some((Some("1".to_owned()), "house"))
);
// a sheet whose type leads the name keeps the written city
idx.rules = rules(false);
assert_eq!(top(&idx, "1 S Main St, St. George, UT 84770"), None);
}
#[test]
fn a_unit_designator_at_the_end_of_the_street_segment_is_read_past() {
let mut idx = forward_postcode_index_for_country(
"unit-tail",
"east route 66,002,flagstaff,86004,86004,3880,,-111.60,35.20,East Route 66,Flagstaff\n\
west idaho street,001,boise,83702,83702,702,,-116.20,43.61,West Idaho Street,Boise\n",
"xx",
);
let rules = |flag: bool| {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "ID AZ".to_owned()),
(23, "forms".to_owned(), "comma region_postal".to_owned()),
(23, "postal_digits".to_owned(), "5".to_owned()),
(23, "postal_split".to_owned(), "5".to_owned()),
(
23,
"junk_tail".to_owned(),
"near tel suite ste apt unit".to_owned(),
),
(16, "street".to_owned(), String::new()),
(16, "st".to_owned(), String::new()),
(16, "route".to_owned(), String::new()),
(24, "st".to_owned(), "street".to_owned()),
(24, "street".to_owned(), "st".to_owned()),
(24, "w".to_owned(), "west".to_owned()),
(24, "west".to_owned(), "w".to_owned()),
(24, "e".to_owned(), "east".to_owned()),
(24, "east".to_owned(), "e".to_owned()),
(24, "rte".to_owned(), "route".to_owned()),
(24, "route".to_owned(), "rte".to_owned()),
(16, "rte".to_owned(), String::new()),
];
if flag {
entries.push((23, "street_type_last".to_owned(), "1".to_owned()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
};
{
let _scope = crate::rules::scope(rules(true));
assert_eq!(
strip_unit_designators("702 W Idaho St Ste 312, Boise, ID 83702").as_deref(),
Some("702 W Idaho St, Boise, ID 83702")
);
assert_eq!(
strip_unit_designators("3880 E Route 66 #2, Flagstaff, AZ 86004").as_deref(),
Some("3880 E Route 66, Flagstaff, AZ 86004")
);
assert_eq!(
strip_unit_designators("702 W Idaho St Apt 4B").as_deref(),
Some("702 W Idaho St")
);
// nothing to cut, a word that is no designator, a designator without its token
assert!(strip_unit_designators("702 W Idaho St, Boise").is_none());
assert!(strip_unit_designators("702 W Idaho St Floor 312, Boise").is_none());
assert!(strip_unit_designators("702 Ste, Boise").is_none());
}
{
let _scope = crate::rules::scope(rules(false));
assert!(strip_unit_designators("702 W Idaho St Ste 312, Boise, ID 83702").is_none());
}
let top = |idx: &Index, q: &str| {
idx.query(q, 1)
.first()
.map(|h| (h.housenumber.clone(), h.precision))
};
idx.rules = rules(true);
assert_eq!(
top(&idx, "702 W Idaho St Ste 312, Boise, ID 83702"),
Some((Some("702".to_owned()), "house"))
);
assert_eq!(
top(&idx, "3880 E Route 66 #2, Flagstaff, AZ 86004"),
Some((Some("3880".to_owned()), "house"))
);
// the type word before a trailing road number is rewritten too ("Rte" -> "Route")
assert_eq!(
top(&idx, "3880 E Rte 66 #2, Flagstaff, AZ 86004"),
Some((Some("3880".to_owned()), "house"))
);
{
let _scope = crate::rules::scope(rules(true));
assert!(street_data_variants("e rte 66").contains(&"e route 66".to_owned()));
}
}
#[test]
fn city_tail_every_precision_and_strong_original_priority() {
for precision in ["house", "interp", "near", "street", "city", "unknown"] {
let original = vec![city_tail_witness(precision, "Elsewhere", 1.0)];
let result = city_tail_choose(original, "vila", || {
vec![city_tail_witness("house", "Vila", 2.0)]
});
assert_eq!(
result[0].0.lat,
if matches!(precision, "house" | "interp" | "near") {
1.0
} else {
2.0
},
"{precision}"
);
}
}
#[test]
fn city_tail_strong_original_does_not_run_retry() {
let original = vec![city_tail_witness("house", "Elsewhere", 1.0)];
let bytes = serde_json::to_vec(&original[0].0).unwrap();
let result = city_tail_choose(original, "vila", || {
panic!("strong original must finish selection")
});
assert_eq!(bytes, serde_json::to_vec(&result[0].0).unwrap());
}
#[test]
fn city_tail_exact_city_rejects_prefix_and_checks_only_first() {
let weak = || vec![city_tail_witness("street", "Elsewhere", 1.0)];
for other in ["Vila Nova", "Nova Vila", "Vilas"] {
assert!(city_tail_choose(weak(), "vila", || vec![city_tail_witness(
"house", other, 2.0
)])
.is_empty());
}
assert!(city_tail_choose(weak(), "vila", || vec![
city_tail_witness("house", "Vila Nova", 2.0),
city_tail_witness("house", "Vila", 3.0)
])
.is_empty());
assert!(city_tail_choose(
vec![
city_tail_witness("street", "Vila Nova", 1.0),
city_tail_witness("house", "Vila", 3.0)
],
"vila",
Vec::new
)
.is_empty());
}
#[test]
fn city_tail_retry_wins_before_held_original_and_retains_ranked_bytes() {
let original = vec![city_tail_witness("street", "Vila", 1.0)];
let result = city_tail_choose(original, "vila", || {
vec![city_tail_witness("near", "Vila", 2.0)]
});
assert_eq!(result[0].0.lat, 2.0);
let original = vec![city_tail_witness("city", "Vila", 1.0)];
let bytes = serde_json::to_vec(&original[0].0).unwrap();
let result = city_tail_choose(original, "vila", || {
vec![city_tail_witness("house", "Vila Nova", 2.0)]
});
assert_eq!(bytes, serde_json::to_vec(&result[0].0).unwrap());
}
#[test]
fn city_tail_small_sheet_preserves_without_tail_or_data() {
let idx = forward_postcode_index_for_country("city-tail", "rua azul,001,vila,12345,12345,1,,8.0,50.0,Rua Azul,Vila\nrua azul,001,vila,12345,12345,3,,8.0002,50.0002,Rua Azul,Vila\nrua verde,002,alto,54321,54321,10,,18.0,40.0,Rua Verde,Alto\n", "xx");
let _scope = crate::rules::scope(idx.rules);
for q in [
"Rua Azul 1, Vila",
"Rua Azul 2, Vila",
"Rua Azul 99, Vila",
"Rua Azul, Vila",
"Vila",
"Rua Azul, 1, Alto, Vila - XY, 12345678",
"Rua Verde, Alto, Vila - XY",
] {
let original = idx.query_feats_country_variants(q, 3, None);
let mut direct = original;
Index::strip_deferred_locality_drop(&mut direct);
Index::monotone_confidence(&mut direct);
let expected = direct.into_iter().map(|v| v.0).collect::<Vec<_>>();
assert_eq!(
serde_json::to_vec(&idx.query(q, 3)).unwrap(),
serde_json::to_vec(&expected).unwrap(),
"{q}"
);
}
}
#[test]
fn city_tail_small_sheet_activates_retry_and_rejects_wrong_place() {
let mut idx = forward_postcode_index_for_country("city-tail-active", "rua azul,001,vila,12345,12345,1,,8.0,50.0,Rua Azul,Vila\nrua azul,001,vila,12345,12345,3,,8.0002,50.0002,Rua Azul,Vila\nrua verde,002,alto,54321,54321,10,,18.0,40.0,Rua Verde,Alto\n", "xx");
assert!(idx.query("Rua Azul, 1, Alto, Vila - XY", 3).is_empty());
let old = idx.query("Rua Verde, Alto, Vila - XY", 3);
assert_eq!(old[0].commune, "Alto");
idx.rules = city_tail_fixture_rules();
for (number, precision) in [("1", "house"), ("2", "interp"), ("99", "near")] {
let result = idx.query(&format!("Rua Azul, {number}, Alto, Vila - XY"), 3);
assert_eq!(result[0].precision, precision);
assert_eq!(result[0].commune, "Vila");
assert_eq!(result[0].street, "Rua Azul");
}
assert!(idx.query("Rua Verde, Alto, Vila - XY", 3).is_empty());
assert!(idx.query("Rua Azul, Alto, Vila - XY", 3).is_empty());
}
#[test]
fn city_tail_decomposed_accents_cannot_bypass_holding() {
let mut idx = forward_postcode_index_for_country("city-tail-unicode", "rua azul,001,vila,12345,12345,1,,8.0,50.0,Rua Azul,Vila\nrua verde,002,alto,54321,54321,10,,18.0,40.0,Rua Verde,Alto\n", "xx");
let composed = "Rua Verde, Alto, Vilà - XY";
let decomposed: String = composed.nfd().collect();
assert_eq!(idx.query(&decomposed, 3)[0].commune, "Alto");
idx.rules = city_tail_fixture_rules();
assert!(idx.query(composed, 3).is_empty());
assert!(idx.query(&decomposed, 3).is_empty());
}
#[test]
fn field_retry_recovers_multiple_payload_segments_and_split_number() {
let mut idx = forward_postcode_index_for_country(
"field-retry",
"rua azul,001,vila,12345,12345,41,,8.0,50.0,Rua Azul,Vila\n",
"xx",
);
idx.rules = city_tail_fixture_rules();
for q in [
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul, 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, Bloco B, Centro, 54321-678, Vila, XY",
] {
let result = idx.query(q, 3);
assert!(!result.is_empty(), "{q}");
assert_eq!(result[0].precision, "house", "{q}");
assert_eq!(result[0].housenumber.as_deref(), Some("41"), "{q}");
assert_eq!(result[0].commune, "Vila", "{q}");
}
}
fn field_witness(
precision: &'static str,
number: &str,
city: &str,
marker: f64,
) -> (Hit, [f32; N_FEATS]) {
let mut h = city_tail_witness(precision, city, marker);
h.0.housenumber = Some(number.to_owned());
h
}
#[test]
fn field_retry_guards_every_precision_number_city_and_rank() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
let tail =
address_field_retries("Rua Azul 12, Bloco, Centro, 12345-678, Vila, XY").unwrap();
let original = || vec![field_witness("city", "12", "Vila", 1.0)];
let bytes = serde_json::to_vec(&original()[0].0).unwrap();
for precision in ["near", "interp", "street", "city"] {
let result = address_field_choose(original(), &tail, |_, _| {
vec![field_witness(precision, "12", "Vila", 2.0)]
});
assert_eq!(
serde_json::to_vec(&result[0].0).unwrap(),
bytes,
"{precision}"
);
}
for number in ["13", "120"] {
let result = address_field_choose(original(), &tail, |_, _| {
vec![field_witness("house", number, "Vila", 2.0)]
});
assert_eq!(serde_json::to_vec(&result[0].0).unwrap(), bytes, "{number}");
}
for city in ["Vila Nova", "Nova Vila", "Vilas"] {
let result = address_field_choose(original(), &tail, |_, _| {
vec![field_witness("house", "12", city, 2.0)]
});
assert_eq!(serde_json::to_vec(&result[0].0).unwrap(), bytes, "{city}");
}
let result = address_field_choose(original(), &tail, |_, _| {
vec![
field_witness("house", "120", "Vila", 2.0),
field_witness("house", "12", "Vila", 3.0),
]
});
assert_eq!(serde_json::to_vec(&result[0].0).unwrap(), bytes);
let result = address_field_choose(original(), &tail, |_, _| {
vec![field_witness("house", "12A", "Vilà", 2.0)]
});
assert_eq!(result[0].0.lat, 2.0);
}
#[test]
fn field_retry_keeps_every_strong_original_and_stops_at_first_accepted() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
let tail =
address_field_retries("Rua Azul 12, Bloco, Centro, 12345-678, Vila, XY").unwrap();
for precision in ["house", "near", "interp"] {
let result = address_field_choose(
vec![field_witness(precision, "120", "Vila", 1.0)],
&tail,
|_, _| panic!("strong original"),
);
assert_eq!(result[0].0.lat, 1.0);
}
let mut calls = Vec::new();
let result = address_field_choose(Vec::new(), &tail, |i, _| {
calls.push(i);
vec![field_witness("house", "12", "Vila", 2.0)]
});
assert_eq!(calls, [0]);
assert_eq!(result[0].0.lat, 2.0);
calls.clear();
let result = address_field_choose(Vec::new(), &tail, |i, _| {
calls.push(i);
if i == 0 {
Vec::new()
} else {
vec![field_witness("house", "12", "Vila", 3.0)]
}
});
assert_eq!(calls, [0, 1]);
assert_eq!(result[0].0.lat, 3.0);
}
#[test]
fn field_retry_preserves_whole_strong_original() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
let tail =
address_field_retries("Rua Azul 12, Bloco, Centro, 12345-678, Vila, XY").unwrap();
for (precision, city) in [
("house", "Outra Vila"),
("near", "Vila"),
("interp", "Vilà"),
] {
let mut original = vec![
field_witness(precision, "120", city, 1.0),
field_witness("house", "12", "Vila", 2.0),
];
original[0].1.fill(0.25);
original[1].1.fill(0.75);
let expected_hits =
serde_json::to_vec(&original.iter().map(|(hit, _)| hit).collect::<Vec<_>>())
.unwrap();
let expected_features = original.iter().map(|(_, f)| *f).collect::<Vec<_>>();
let result = address_field_choose(original, &tail, |_, _| {
panic!("strong original must bypass every retry: {precision} {city}")
});
assert_eq!(
serde_json::to_vec(&result.iter().map(|(hit, _)| hit).collect::<Vec<_>>(),)
.unwrap(),
expected_hits
);
assert_eq!(
result.iter().map(|(_, f)| *f).collect::<Vec<_>>(),
expected_features
);
}
}
#[test]
fn field_retry_accepts_first_matching_house_with_whole_payload() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
let mut tail =
address_field_retries("Rua Azul 12, Bloco, Centro, 12345-678, Vila, XY").unwrap();
tail.forms = vec![
String::new(),
"wrong number".into(),
"wrong city".into(),
"accepted".into(),
"must not run".into(),
];
let mut accepted = vec![
field_witness("house", "12A", "Vilà", 4.0),
field_witness("house", "120", "Outra Vila", 5.0),
];
accepted[0].1.fill(0.25);
accepted[1].1.fill(0.75);
let expected_hits =
serde_json::to_vec(&accepted.iter().map(|(hit, _)| hit).collect::<Vec<_>>()).unwrap();
let expected_features = accepted.iter().map(|(_, f)| *f).collect::<Vec<_>>();
let mut calls = Vec::new();
let result = address_field_choose(
vec![field_witness("street", "12", "Vila", 1.0)],
&tail,
|i, _| {
calls.push(i);
match i {
1 => vec![
field_witness("house", "120", "Vila", 2.0),
field_witness("house", "12", "Vila", 2.5),
],
2 => vec![field_witness("house", "12", "Vilas", 3.0)],
3 => accepted.clone(),
_ => panic!("empty or later form was searched"),
}
},
);
assert_eq!(calls, [1, 2, 3]);
assert_eq!(
serde_json::to_vec(&result.iter().map(|(hit, _)| hit).collect::<Vec<_>>(),).unwrap(),
expected_hits
);
assert_eq!(
result.iter().map(|(_, f)| *f).collect::<Vec<_>>(),
expected_features
);
}
#[test]
fn field_retry_forms_preserve_number_postal_and_old_retry() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
for q in [
"Rua Azul, 41, Bloco, Centro, 12345-678, Vila, XY",
"Rua Azul, 41, Bloco, Centro, Vila, 12345-678, XY",
] {
let tail = address_field_retries(q).unwrap();
assert_eq!(tail.number, 41);
assert_eq!(tail.forms[1], "Rua Azul, 41, Vila");
assert!(tail.forms[0].starts_with("Rua Azul, 41, "));
assert!(tail.forms[0].contains("12345-678"));
if let Some(old) = city_tail(q) {
assert!(old.retry.is_none());
}
}
}
#[test]
fn field_retry_house_number_width_and_suffix() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
for separate in [false, true] {
for (token, number) in [
("1", 1),
("12", 12),
("123", 123),
("1234", 1234),
("12345", 12345),
("1234A", 1234),
] {
let address = if separate {
format!("Rua Azul, {token}")
} else {
format!("Rua Azul {token}")
};
let query = format!("{address}, Bloco, Vila, XY");
let tail = address_field_retries(&query)
.unwrap_or_else(|| panic!("expected field retries for {query}"));
assert_eq!(tail.number, number, "{query}");
assert_eq!(tail.forms[0], format!("{address}, Vila, XY"), "{query}");
assert_eq!(tail.forms[1], format!("{address}, Vila"), "{query}");
}
let query = if separate {
"Rua Azul, 123456, Bloco, Vila, XY"
} else {
"Rua Azul 123456, Bloco, Vila, XY"
};
assert!(address_field_retries(query).is_none(), "{query}");
}
}
#[test]
fn field_retry_hyphen_city_and_number_payload_reach_house() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
let raw = "Rua Azul, 41 - Centro, Vila - XY, 12345-678";
let tail = address_field_retries(raw).expect("number before district payload");
assert_eq!(tail.number, 41);
assert_eq!(tail.city, normalize("Vila"));
for expected in [
"Rua Azul, 41 - Centro, Vila, 12345-678",
"Rua Azul, 41, Vila",
] {
assert!(tail.forms.iter().any(|q| q == expected), "{expected}");
let result = address_field_choose(Vec::new(), &tail, |_, q| {
if q == expected {
vec![field_witness("house", "41", "Vila", 2.0)]
} else {
Vec::new()
}
});
assert_eq!(result[0].0.lat, 2.0);
}
}
#[test]
fn field_retry_original_city_controls_near_and_interp_only() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
let tail = address_field_retries("Rua Azul 41, Centro, Vila, XY").unwrap();
for precision in ["near", "interp"] {
for city in ["Vila Nova", "Vil", "Outra"] {
let result = address_field_choose(
vec![field_witness(precision, "41", city, 1.0)],
&tail,
|_, _| vec![field_witness("house", "41", "Vila", 2.0)],
);
assert_eq!(result[0].0.lat, 2.0, "{precision}/{city}");
}
let result = address_field_choose(
vec![field_witness(precision, "42", "VILA", 1.0)],
&tail,
|_, _| panic!("same city {precision}"),
);
assert_eq!(result[0].0.lat, 1.0);
}
for city in ["Vila", "Vila Nova", "Outra"] {
let result = address_field_choose(
vec![field_witness("house", "42", city, 1.0)],
&tail,
|_, _| panic!("original house {city}"),
);
assert_eq!(result[0].0.lat, 1.0);
}
for city in ["Vila Nova", "Vil"] {
let original = vec![field_witness("near", "41", "Outra", 1.0)];
let result = address_field_choose(original, &tail, |_, _| {
vec![field_witness("house", "41", city, 2.0)]
});
assert_eq!(result[0].0.lat, 1.0, "candidate {city}");
}
}
fn street_fallback_mechanism_witness(label: &str, input: &str, target: &str, rules: &str) {
let idx = es_observer_fixture(
label,
&[
(input, "ciudad", "001", "42"),
(target, "ciudad", "001", "41"),
],
rules,
);
let _scope = crate::rules::scope(idx.rules);
let raw = format!("{input}, 41, Ciudad");
let ordinary = idx.query_feats_fields_retry(&raw, 1, None);
assert!(
!ordinary.first().is_some_and(
|(h, _)| h.precision == "house" && h.housenumber.as_deref() == Some("41")
),
"ordinary: {:?}",
es_observer_hits(&ordinary)
);
let actual = idx.query(&raw, 1);
assert_eq!(actual[0].precision, "house");
assert_eq!(actual[0].housenumber.as_deref(), Some("41"));
assert_eq!(actual[0].street, target);
assert_eq!(actual[0].commune, "ciudad");
assert_eq!(actual[0].lat, 40.4);
assert_eq!(actual[0].lon, -3.701);
}
#[test]
fn street_fallback_type_recovers_missing_house() {
street_fallback_mechanism_witness(
"fallback-type",
"boulevard azul",
"avenida azul",
"street\tboulevard\tavenida\n",
);
}
#[test]
fn street_fallback_particle_recovers_missing_house() {
street_fallback_mechanism_witness(
"fallback-particle",
"rua de azul",
"rua azul",
"street\trua de\trua\n",
);
}
#[test]
fn street_fallback_wrong_house_number_still_retries() {
let idx = es_observer_fixture(
"fallback-wrong-number",
&[
("avenida", "ciudad", "001", "25"),
("avenida vinte e cinco", "ciudad", "001", "41"),
],
"street\t25\tvinte e cinco\n",
);
let _scope = crate::rules::scope(idx.rules);
let raw = "Avenida 25, 41, Ciudad";
let ordinary = idx.query_feats_fields_retry(raw, 1, None);
eprintln!("ORDINARY: {}", es_observer_hits(&ordinary));
let actual = idx.query(raw, 1);
eprintln!("ACTUAL: {}", serde_json::to_string(&actual).unwrap());
assert_eq!(ordinary[0].0.precision, "house");
assert_eq!(ordinary[0].0.housenumber.as_deref(), Some("25"));
assert_eq!(ordinary[0].0.street, "avenida");
assert_eq!(ordinary[0].0.commune, "ciudad");
assert_eq!(ordinary[0].0.lat, 40.4);
assert_eq!(ordinary[0].0.lon, -3.7);
assert_eq!(actual[0].precision, "house");
assert_eq!(actual[0].housenumber.as_deref(), Some("41"));
assert_eq!(actual[0].street, "avenida vinte e cinco");
assert_eq!(actual[0].commune, "ciudad");
assert_eq!(actual[0].lat, 40.4);
assert_eq!(actual[0].lon, -3.701);
}
#[test]
fn street_fallback_numeral_recovers_missing_house() {
let idx = es_observer_fixture(
"fallback-numeral",
&[("avenida vinte e cinco", "ciudad", "001", "41")],
"street\t25\tvinte e cinco\n",
);
let _scope = crate::rules::scope(idx.rules);
let raw = "Avenida 25, 41, Ciudad";
let ordinary = idx.query_feats_fields_retry(raw, 1, None);
assert!(
!ordinary.first().is_some_and(
|(h, _)| h.precision == "house" && h.housenumber.as_deref() == Some("41")
)
);
let actual = idx.query(raw, 1);
assert_eq!(actual[0].precision, "house");
assert_eq!(actual[0].housenumber.as_deref(), Some("41"));
assert_eq!(actual[0].street, "avenida vinte e cinco");
assert_eq!(actual[0].commune, "ciudad");
assert_eq!(actual[0].lat, 40.4);
assert_eq!(actual[0].lon, -3.7);
}
#[test]
fn street_fallback_preserves_ordinary_equal_score_house() {
let idx = es_observer_fixture(
"fallback-equal",
&[
("rua livramento", "ciudad", "001", "515"),
("rua do livramento", "otra", "002", "515"),
],
"street\trua\trua do\n",
);
let _scope = crate::rules::scope(idx.rules);
let ordinary = idx.query_feats_fields_retry("Rua Livramento, 515", 1, None);
assert_eq!(ordinary[0].0.street, "rua livramento");
assert_eq!(ordinary[0].0.commune, "ciudad");
assert_eq!(ordinary[0].0.precision, "house");
let alternate = idx.query_feats_fields_retry("Rua do Livramento, 515", 1, None);
assert_eq!(alternate[0].0.score, ordinary[0].0.score);
let actual = idx.query_feats_street_data("Rua Livramento, 515", 1, None);
assert_eq!(es_observer_hits(&actual), es_observer_hits(&ordinary));
}
#[test]
fn street_fallback_does_not_expand_when_requested_house_found() {
let idx = es_observer_fixture(
"fallback-no-work",
&[("rua azul", "ciudad", "001", "41")],
"street\trua\trua de\n",
);
for raw in ["Rua Azul, 41", "Rua Azul, 41, Ciudad"] {
STREET_DATA_CALLS.with(|n| n.set(0));
let hits = idx.query(raw, 1);
assert_eq!(hits[0].precision, "house");
assert_eq!(hits[0].housenumber.as_deref(), Some("41"));
assert_eq!(STREET_DATA_CALLS.with(|n| n.get()), 0, "{raw}");
}
}
#[test]
fn street_data_rules_find_numerals_types_and_keep_house_number() {
let rules = "street\t02\tdois\nstreet\tdois\t02\nstreet\t25\tvinte e cinco\nstreet\tr\trua\nstreet\trua de\trua\n";
for (label, street, query, house) in [
("digits", "avenida dois", "Avenida 02, 41, Ciudad", "41"),
("words", "avenida 02", "Avenida Dois, 41, Ciudad", "41"),
("type", "rua azul", "R. Azul, 41, Ciudad", "41"),
("particle", "rua azul", "Rua de Azul, 41, Ciudad", "41"),
("combined", "rua azul", "R. de Azul, 41, Ciudad", "41"),
(
"date",
"rua vinte e cinco de marco",
"Rua 25 de Março, 41, Ciudad",
"41",
),
("house", "rua azul", "Rua Azul, 02, Ciudad", "2"),
] {
let idx = es_observer_fixture(label, &[(street, "ciudad", "001", house)], rules);
let hits = idx.query(query, 1);
assert!(!hits.is_empty(), "{label}");
assert_eq!(
hits[0].precision, "house",
"{label}: {} / {:?} / {:?}",
hits[0].street, hits[0].housenumber, hits[0].flags
);
assert_eq!(hits[0].housenumber.as_deref(), Some(house), "{label}");
assert_eq!(hits[0].street, street, "{label}");
if matches!(label, "words" | "type" | "particle" | "combined") {
assert_eq!(hits[0].commune, "ciudad");
assert_eq!(hits[0].lat, 40.4);
assert_eq!(hits[0].lon, -3.7);
} else {
assert!(
hits[0].flags.contains(&"street_exact"),
"{label}: {:?}",
hits[0].flags
);
}
}
}
#[test]
fn street_data_rules_stay_in_street_and_in_their_sheet() {
let idx = es_observer_fixture("no-rules", &[("avenida dois", "ciudad", "001", "41")], "");
let hits = idx.query("Avenida 02, 41, Ciudad", 1);
assert!(hits
.first()
.is_none_or(|h| !h.flags.contains(&"street_exact")));
let idx = es_observer_fixture(
"house-is-not-street",
&[("rua azul", "ciudad", "001", "2")],
"street\t2\tdois\n",
);
let hits = idx.query("Rua Azul, 2, Ciudad", 1);
assert_eq!(hits[0].housenumber.as_deref(), Some("2"));
assert_eq!(hits[0].precision, "house");
}
fn bounded_street_fixture(pairs: Vec<(&str, &str)>) -> &'static crate::rules::Rules {
let entries = pairs
.into_iter()
.map(|(a, b)| (24, a.to_owned(), b.to_owned()))
.collect::<Vec<_>>();
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn street_bounded_particles_and_six_keys() {
let mut pairs = vec![
("r", "rua"),
("rua", "r"),
("av", "avenida"),
("avenida", "av"),
("02", "dois"),
("7", "sete"),
("28", "vinte e oito"),
("25", "vinte e cinco"),
];
for (a, b) in [
("rua", "rua de"),
("rua", "rua da"),
("rua", "rua do"),
("rua", "rua dos"),
("rua", "rua das"),
("avenida", "avenida de"),
("avenida", "avenida da"),
("avenida", "avenida do"),
("avenida", "avenida dos"),
("avenida", "avenida das"),
] {
pairs.push((a, b));
pairs.push((b, a));
}
let _scope = crate::rules::scope(bounded_street_fixture(pairs));
// Five street keys from the authorized remaining set, plus the reported defect.
for key in [
"rua azul",
"avenida 02",
"avenida 7 de setembro",
"avenida para",
"centro administrativo 28 de janeiro",
"r direita",
] {
let variants = street_data_variants(key);
println!("bounded {key}: {} {variants:?}", variants.len());
assert!(!variants.is_empty(), "{key}");
assert!(variants.len() <= 8, "{key}: {}", variants.len());
for v in &variants {
let words = v.split_whitespace().collect::<Vec<_>>();
let particle = |w: &str| ["de", "da", "do", "dos", "das"].contains(&w);
assert!(
!(words.len() > 2 && particle(words[1]) && particle(words[2])),
"{key}: {v}"
);
}
}
assert!(street_data_variants("rua de azul").contains(&"rua azul".to_owned()));
assert!(!street_data_variants("rua de azul")
.iter()
.any(|v| v.starts_with("rua da de")));
}
#[test]
fn street_bounded_each_kind_once() {
let _scope = crate::rules::scope(bounded_street_fixture(vec![
("r", "rua"),
("rua", "avenida"),
("2", "dois"),
("dois", "02"),
("rua de", "rua"),
]));
let variants = street_data_variants("r de 2");
assert!(variants.contains(&"rua dois".to_owned()), "{variants:?}");
assert!(
!variants
.iter()
.any(|v| v.contains("avenida") || v.contains("02")),
"{variants:?}"
);
}
#[test]
fn street_bounded_cap_is_enforced_without_particles() {
let pairs = vec![
("avenida", "alpha"),
("avenida", "beta"),
("avenida", "gamma"),
("avenida", "delta"),
("avenida", "epsilon"),
("avenida", "zeta"),
("avenida", "eta"),
("avenida", "theta"),
("avenida", "iota"),
("avenida", "kappa"),
];
let _scope = crate::rules::scope(bounded_street_fixture(pairs));
let variants = street_data_variants("avenida azul");
assert_eq!(variants.len(), 8, "{variants:?}");
assert!(variants.contains(&"alpha azul".to_owned()));
}
#[test]
fn street_bounded_date_and_house_25_are_distinct() {
let idx = es_observer_fixture(
"bounded-date-house",
&[("rua vinte e cinco de marco", "ciudad", "001", "25")],
"street\t25\tvinte e cinco\nstreet\tr\trua\nstreet\trua\trua de\nstreet\trua de\trua\n",
);
let hits = idx.query("R. 25 de Março, 25, Ciudad", 1);
assert_eq!(hits[0].precision, "house");
assert_eq!(hits[0].housenumber.as_deref(), Some("25"));
assert_eq!(hits[0].street, "rua vinte e cinco de marco");
}
fn field_retry_new_forms_cases() -> Vec<(&'static str, &'static str, &'static str)> {
vec![
(
"no_district",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, 12345-678, Vila, XY",
),
(
"address_city",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, Vila",
),
(
"no_postal",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, Bloco B, Centro, Vila, XY",
),
(
"no_region",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila",
),
(
"city_hyphen",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila - XY",
),
(
"city_comma",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila - XY",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
),
(
"postal_plain",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, Bloco B, Centro, 12345678, Vila, XY",
),
(
"postal_hyphen",
"Rua Azul 41, Bloco B, Centro, 12345678, Vila, XY",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
),
(
"postal_prefix",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul 41, Bloco B, Centro, 12345, Vila, XY",
),
(
"no_unit",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY, Sala 7",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
),
(
"separate_house",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul, 41, Bloco B, Centro, 12345-678, Vila, XY",
),
(
"clean_fields",
"Rua Azul 41, Bloco B, Centro, 12345-678, Vila, XY",
"Rua Azul, 41, Vila",
),
]
}
#[test]
fn field_retry_new_forms_each_reaches_guarded_answer() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
for (slot, (name, raw, expected)) in field_retry_new_forms_cases().into_iter().enumerate() {
let tail = address_field_retries(raw).unwrap_or_else(|| panic!("{name}"));
assert_eq!(
tail.forms.get(slot).map(String::as_str),
Some(expected),
"{name}"
);
assert_eq!(tail.number, 41, "{name}");
assert_eq!(tail.city, "vila", "{name}");
assert!(
tail.forms.iter().any(|q| q == expected),
"{name}: {:?}",
tail.forms
);
let mut seen = false;
let result = address_field_choose(Vec::new(), &tail, |_, q| {
if q == expected {
seen = true;
vec![field_witness("house", "41", "Vila", 2.0)]
} else {
Vec::new()
}
});
assert!(seen, "{name}");
assert_eq!(result[0].0.lat, 2.0, "{name}");
}
}
#[test]
fn field_retry_new_forms_each_rejects_near_misses_and_keeps_strong() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
for (name, raw, expected) in field_retry_new_forms_cases() {
let tail = address_field_retries(raw).unwrap_or_else(|| panic!("{name}"));
for (precision, number, city) in [
("house", "42", "Vila"),
("house", "410", "Vila"),
("house", "41", "Vila Nova"),
("house", "41", "Nova Vila"),
("near", "41", "Vila"),
("interp", "41", "Vila"),
("street", "41", "Vila"),
("city", "41", "Vila"),
] {
let original = vec![field_witness("city", "41", "Vila", 1.0)];
let bytes = serde_json::to_vec(&original[0].0).unwrap();
let result = address_field_choose(original, &tail, |_, q| {
if q == expected {
vec![field_witness(precision, number, city, 2.0)]
} else {
Vec::new()
}
});
assert_eq!(
serde_json::to_vec(&result[0].0).unwrap(),
bytes,
"{name}: {precision}/{number}/{city}"
);
}
for precision in ["house", "interp", "near"] {
let original = vec![field_witness(precision, "41", "Vila", 1.0)];
let bytes = serde_json::to_vec(&original[0].0).unwrap();
let result =
address_field_choose(original, &tail, |_, _| panic!("{name}: strong original"));
assert_eq!(serde_json::to_vec(&result[0].0).unwrap(), bytes, "{name}");
}
}
}
fn lev_observer_accepts<A: Automaton>(a: &A, bytes: &[u8]) -> bool {
let mut state = a.start();
for &byte in bytes {
state = a.accept(&state, byte);
}
a.is_match(&state)
}
#[test]
fn levenshtein_storage_matches_fst_on_index_and_utf8() {
let terms = [
"a",
"azul",
"calle mayor",
"avenida sol",
"rue de l'été",
"улица мира",
"é",
"ñ",
"東京",
"🦀",
"abcdefghijkl",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmn",
];
let mut words: Vec<String> = terms.iter().map(|s| (*s).to_owned()).collect();
if let Ok(path) = std::env::var("GRIDPIN_AUTOMATON_INDEX") {
let index = Index::open(Path::new(&path)).unwrap();
let mut stream = index.streets_fst.stream();
let mut ordinal = 0;
while let Some((key, _)) = stream.next() {
if ordinal % 101 == 0 {
let name = key.split(|&b| b == KEY_SEP).next().unwrap();
words.push(std::str::from_utf8(name).unwrap().to_owned());
}
ordinal += 1;
}
assert!(words.len() > terms.len(), "index sample must not be empty");
}
// A portable FST fixture remains active when no deployed index is supplied.
words.sort();
words.dedup();
let index = fst::Set::from_iter(&words).unwrap();
for phrase in [
"",
"a",
"abcde",
"avenida sol",
"abcdefghijkl",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmn",
"é",
"rue de l'été",
"улица мира",
"東京",
"🦀",
] {
for distance in 0..=2 {
let actual = Levenshtein::new(phrase, distance);
let expected = fst::automaton::Levenshtein::new(phrase, distance);
match (actual, expected) {
(Ok(a), Ok(b)) => {
let found_a = index.search(&a).into_stream().into_strs().unwrap();
let found_b = index.search(&b).into_stream().into_strs().unwrap();
assert_eq!(found_a, found_b, "{phrase:?}/{distance}");
let mut candidates = vec![
phrase.to_owned(),
format!("{phrase}a"),
format!("é{phrase}"),
format!("{phrase}я"),
phrase.chars().skip(1).collect::<String>(),
"zzzz".to_owned(),
];
candidates.extend(words.iter().cloned());
for candidate in candidates {
assert_eq!(
lev_observer_accepts(&a, candidate.as_bytes()),
lev_observer_accepts(&b, candidate.as_bytes()),
"{phrase:?}/{distance}: {candidate:?}"
);
}
for bytes in [
&[0xff][..],
&[0xc0, 0x80],
&[0xed, 0xa0, 0x80],
&[0xf4, 0x90, 0x80, 0x80],
] {
assert_eq!(
lev_observer_accepts(&a, bytes),
lev_observer_accepts(&b, bytes)
);
}
}
(Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
(a, b) => {
panic!("construction differs for {phrase:?}/{distance}: {a:?} vs {b:?}")
}
}
}
}
}
#[test]
fn levenshtein_storage_preserves_state_limit_refusal() {
let long_phrase = "abcdefghijklmnopqrstuvwxyz".repeat(20);
let phrase = long_phrase.as_str();
let expected = fst::automaton::Levenshtein::new(phrase, 2).unwrap_err();
let actual = Levenshtein::new(phrase, 2).unwrap_err();
assert_eq!(actual.to_string(), expected.to_string());
assert!(expected.to_string().contains("10000"));
// At distance zero even this long phrase succeeds; blanket refusal is not valid.
let exact = Levenshtein::new(phrase, 0).unwrap();
assert!(lev_observer_accepts(&exact, phrase.as_bytes()));
assert!(!lev_observer_accepts(&exact, b""));
}
#[test]
fn levenshtein_storage_exact_limit_decision() {
// At distance zero each four-byte scalar adds one prefix state and
// three UTF-8 intermediate states: 1 + 4 * 2,500 = 10,001 states.
// Observe refusal versus success, not just the printed error limit.
let below = "\u{1f980}".repeat(2_499);
assert!(fst::automaton::Levenshtein::new(&below, 0).is_ok());
assert!(Levenshtein::new(&below, 0).is_ok());
let phrase = "\u{1f980}".repeat(2_500);
assert!(fst::automaton::Levenshtein::new(&phrase, 0).is_err());
assert!(fst::automaton::Levenshtein::new_with_limit(&phrase, 0, 10_001).is_ok());
assert!(Levenshtein::new(&phrase, 0).is_err());
}
fn automaton_matches(lev: &Levenshtein, text: &str) -> bool {
let mut state = lev.start();
for b in text.bytes() {
state = lev.accept(&state, b);
}
lev.is_match(&state)
}
#[test]
fn levenshtein_cache_keys_on_phrase_and_distance() {
clear_levenshtein_cache();
let one = cached_levenshtein("rua azul", 1).unwrap();
let two = cached_levenshtein("rua azul", 2).unwrap();
// two edits away: only the distance-2 automaton accepts it
assert!(!automaton_matches(&one, "rua axxl"));
assert!(automaton_matches(&two, "rua axxl"));
let other = cached_levenshtein("rua verde", 1).unwrap();
assert!(automaton_matches(&other, "rua verd"));
assert!(!automaton_matches(&other, "rua azul"));
// a repeated request returns the very same automaton, not a rebuild
assert!(std::rc::Rc::ptr_eq(
&one,
&cached_levenshtein("rua azul", 1).unwrap()
));
}
#[test]
fn levenshtein_cache_is_emptied_and_bounded() {
clear_levenshtein_cache();
cached_levenshtein("rua azul", 1);
cached_levenshtein("rua verde", 1);
assert_eq!(levenshtein_cache_len(), 2);
clear_levenshtein_cache();
assert_eq!(levenshtein_cache_len(), 0);
for i in 0..=LEV_CACHE_MAX {
cached_levenshtein(&format!("rua {i:04}"), 1);
}
assert!(levenshtein_cache_len() <= LEV_CACHE_MAX);
clear_levenshtein_cache();
}
#[test]
fn levenshtein_cache_starts_empty_for_every_query() {
let idx = forward_postcode_index_for_country(
"lev-cache",
"rua azul,001,vila,12345,12345,1,,8.0,50.0,Rua Azul,Vila\n",
"xx",
);
let _scope = crate::rules::scope(idx.rules);
clear_levenshtein_cache();
let stale = cached_levenshtein("left over from another query", 1);
assert!(stale.is_some() && levenshtein_cache_len() == 1);
idx.query("Rua Azull 1, Vila", 1);
LEV_CACHE.with(|cache| {
assert!(!cache
.borrow()
.contains_key(&("left over from another query".to_owned(), 1)));
});
clear_levenshtein_cache();
}
fn postal_fallback_fixture(case: &str) -> Index {
let mut idx = forward_postcode_index_for_country(case, "rua azul,001,vila,12345,12345,1,,8.0,50.0,Rua Azul,Vila\nrua azul,001,vila,12345,12345,3,,8.0002,50.0002,Rua Azul,Vila\nrua azul,002,alto,54321,54321,10,,18.0,40.0,Rua Azul,Alto\n", "xx");
idx.rules = city_tail_fixture_rules();
idx
}
fn postal_fallback_direct(idx: &Index, q: &str) -> Vec<Hit> {
let _scope = crate::rules::scope(idx.rules);
let mut hits = idx.query_feats_country_variants(q, 3, None);
Index::strip_deferred_locality_drop(&mut hits);
Index::monotone_confidence(&mut hits);
hits.into_iter().map(|v| v.0).collect()
}
#[test]
fn postal_fallback_eight_digits_recovers_empty() {
let idx = postal_fallback_fixture("postal-eight");
let raw = "Rua Azul 1, 12345678";
assert!(postal_fallback_direct(&idx, raw).is_empty());
let expected = idx.query("Rua Azul 1, 12345-678", 3);
assert_eq!(expected[0].precision, "house");
assert_eq!(
serde_json::to_vec(&idx.query(raw, 3)).unwrap(),
serde_json::to_vec(&expected).unwrap()
);
}
#[test]
fn postal_fallback_near_miss_tokens_preserve_original() {
let idx = postal_fallback_fixture("postal-boundaries");
for token in [
"1234567",
"123456789",
"12345-678",
"12345678-9",
"9-12345678",
"-12345678",
"12345678-",
] {
let q = format!("Rua Azul 1, {token}");
assert_eq!(
serde_json::to_vec(&idx.query(&q, 3)).unwrap(),
serde_json::to_vec(&postal_fallback_direct(&idx, &q)).unwrap(),
"{token}"
);
}
}
#[test]
fn postal_fallback_preserves_each_strong_precision() {
let idx = postal_fallback_fixture("postal-strong");
for (number, precision) in [("1", "house"), ("2", "interp"), ("99", "near")] {
let q = format!("Rua Azul {number}, 54321678, Vila");
let original = postal_fallback_direct(&idx, &q);
assert_eq!(original[0].precision, precision);
assert_eq!(original[0].commune, "Vila");
let alternate = idx.query(&q.replace("54321678", "54321-678"), 3);
assert_eq!(alternate[0].commune, "Alto");
assert_eq!(
serde_json::to_vec(&idx.query(&q, 3)).unwrap(),
serde_json::to_vec(&original).unwrap(),
"{precision}"
);
}
}
#[test]
fn postal_fallback_replaces_street_and_city() {
let idx = postal_fallback_fixture("postal-weak");
for (q, rewritten, precision) in [
(
"Rua Azul, 54321678, Vila",
"Rua Azul, 54321-678, Vila",
"street",
),
(
"Rua Azul, S/N, Bairro, 12345678, Vila, XY",
"Rua Azul, S/N, Bairro, 12345-678, Vila, XY",
"city",
),
] {
let original = postal_fallback_direct(&idx, q);
assert_eq!(original[0].precision, precision);
let expected = idx.query(rewritten, 3);
assert!(!expected.is_empty());
assert_ne!(
serde_json::to_vec(&original).unwrap(),
serde_json::to_vec(&expected).unwrap()
);
assert_eq!(
serde_json::to_vec(&idx.query(q, 3)).unwrap(),
serde_json::to_vec(&expected).unwrap(),
"{precision}"
);
}
}
#[test]
fn postal_fallback_empty_alternate_retains_weak_original() {
let idx = postal_fallback_fixture("postal-empty-alternate");
let q = "Rua Azul, 99999678, Vila Alto";
let original = postal_fallback_direct(&idx, q);
assert_eq!(original[0].precision, "street");
assert!(idx.query("Rua Azul, 99999-678, Vila Alto", 3).is_empty());
assert_eq!(
serde_json::to_vec(&idx.query(q, 3)).unwrap(),
serde_json::to_vec(&original).unwrap()
);
}
#[test]
fn postal_fallback_absent_data_preserves_original() {
let mut idx = postal_fallback_fixture("postal-absent");
idx.rules = crate::rules::defaults_static();
assert!(idx.query("Rua Azul 1, 12345678", 3).is_empty());
assert!(!idx.query("Rua Azul 1, 12345-678", 3).is_empty());
}
#[test]
fn postal_fallback_shared_strength_checks_top_not_any() {
for weak in ["street", "city", "unknown"] {
let result = city_tail_choose(
vec![
city_tail_witness(weak, "Vila", 1.0),
city_tail_witness("house", "Vila", 2.0),
],
"vila",
|| vec![city_tail_witness("street", "Vila", 3.0)],
);
assert_eq!(result[0].0.lat, 3.0, "{weak}");
}
}
#[test]
fn field_retry_number_labels_keep_city_guard() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
for label in ["nº", "n°", "n.º"] {
let raw = format!("Rua Azul, {label} 12, Centro, Vila, XY");
let tail = address_field_retries(&raw).expect("explicit labeled number");
assert_eq!(tail.number, 12);
assert_eq!(tail.city, "vila");
let rejected = address_field_choose(Vec::new(), &tail, |_, _| {
vec![field_witness("house", "13", "Vila", 1.0)]
});
assert!(rejected.is_empty());
let wrong_city = address_field_choose(Vec::new(), &tail, |_, _| {
vec![field_witness("house", "12", "Outra", 1.0)]
});
assert!(wrong_city.is_empty());
}
}
#[test]
fn field_retry_cityless_unique_labeled_house() {
let idx = es_observer_fixture("182-unique", &[("rua azul", "vila", "001", "12")], "");
let _scope = crate::rules::scope(city_tail_fixture_rules());
for label in ["nº", "n°", "n.º"] {
let hits =
idx.query_feats_fields_retry(&format!("Rua Azul, {label} 12 - Centro"), 3, None);
assert!(!hits.is_empty(), "{label}");
assert_eq!(hits[0].0.precision, "house");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("12"));
assert_eq!(normalize(&hits[0].0.street), "rua azul");
}
}
#[test]
fn field_retry_cityless_rejects_distant_homonyms_and_duplicate_records() {
for (label, city, id) in [
("182-homonym", "outra", "002"),
("182-duplicate", "vila", "001"),
] {
let idx = es_observer_fixture(
label,
&[
("rua azul", "vila", "001", "12"),
("rua branca", "vila", "001", "1"),
("rua cinza", "vila", "001", "1"),
("rua azul", city, id, "12"),
],
"",
);
let _scope = crate::rules::scope(city_tail_fixture_rules());
let raw = "Rua Azul, nº 12 - Centro";
let original = idx.query_feats_postal_retry(raw, 3, None);
assert!(original.first().is_none_or(|h| h.0.precision != "house"));
assert_eq!(
es_observer_hits(&idx.query_feats_fields_retry(raw, 3, None)),
es_observer_hits(&original)
);
}
}
#[test]
fn field_retry_cityless_wrong_number_never_replaces_original() {
let idx = es_observer_fixture("182-number", &[("rua azul", "vila", "001", "13")], "");
let _scope = crate::rules::scope(city_tail_fixture_rules());
let raw = "Rua Azul, nº 12 - Centro";
let original = idx.query_feats_postal_retry(raw, 3, None);
assert_eq!(
es_observer_hits(&idx.query_feats_fields_retry(raw, 3, None)),
es_observer_hits(&original)
);
}
#[test]
fn field_retry_number_labels_preserve_strong_original() {
let _scope = crate::rules::scope(city_tail_fixture_rules());
let tail = address_field_retries("Rua Azul, nº 12, Centro, Vila, XY").unwrap();
let original = vec![field_witness("house", "13", "Outra", 1.0)];
let saved = es_observer_hits(&original);
let actual =
address_field_choose(original, &tail, |_, _| panic!("strong original is frozen"));
assert_eq!(es_observer_hits(&actual), saved);
}
fn field_retry_type_rules(pairs: bool) -> &'static crate::rules::Rules {
let mut entries = vec![
(23, "enabled".to_owned(), "1".to_owned()),
(23, "regions".to_owned(), "XY XZ".to_owned()),
];
for kind in [
"av",
"avenida",
"r",
"rua",
"al",
"alameda",
"pca",
"praca",
"xy",
"xylophone",
] {
entries.push((16, kind.to_owned(), String::new()));
}
if pairs {
for (short, full) in [
("av", "avenida"),
("r", "rua"),
("al", "alameda"),
("pca", "praca"),
("xy", "xylophone"),
] {
entries.push((24, short.to_owned(), full.to_owned()));
entries.push((24, full.to_owned(), short.to_owned()));
}
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn field_retry_type_abbreviation_from_sheet_reaches_unique_house() {
for (label, short, full) in [
("185-av", "Av.", "avenida"),
("185-r", "R.", "rua"),
("185-al", "Al.", "alameda"),
("185-pca", "Pça.", "praca"),
("185-generic", "XY.", "xylophone"),
] {
let street = format!("{full} azul");
let mut idx = es_observer_fixture(label, &[(&street, "vila", "001", "12")], "");
idx.rules = field_retry_type_rules(true);
let _scope = crate::rules::scope(idx.rules);
let raw = format!("{short} Azul, nº 12 - Centro");
let hits = idx.query_feats_fields_retry(&raw, 3, None);
assert!(!hits.is_empty(), "{raw}");
assert_eq!(hits[0].0.precision, "house", "{raw}");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("12"), "{raw}");
assert_eq!(normalize(&hits[0].0.street), street, "{raw}");
}
}
#[test]
fn field_retry_type_abbreviation_checks_every_city_and_spelling() {
for (label, second_street, second_city) in [
("185-homonyms", "avenida azul", "outra"),
("185-alias-homonyms", "av azul", "outra"),
("185-duplicates", "avenida azul", "vila"),
] {
let mut idx = es_observer_fixture(
label,
&[
("avenida azul", "vila", "001", "12"),
("rua branca", "vila", "001", "1"),
("rua cinza", "vila", "001", "1"),
(second_street, second_city, "002", "12"),
],
"",
);
idx.rules = field_retry_type_rules(true);
let _scope = crate::rules::scope(idx.rules);
let (street, number) = cityless_field_address("Av. Azul, nº 12 - Centro").unwrap();
assert!(
idx.cityless_field_house(&street, number).is_none(),
"{label}"
);
let raw = "Av. Azul, nº 12 - Centro";
let original = idx.query_feats_postal_retry(raw, 3, None);
assert!(
original.first().is_none_or(|h| h.0.precision != "house"),
"{label}"
);
assert_eq!(
es_observer_hits(&idx.query_feats_fields_retry(raw, 3, None)),
es_observer_hits(&original),
"{label}"
);
}
}
#[test]
fn street_name_projection_equals_the_street_by_street_build() {
// The builder orders streets by normalised name, then commune: two spellings of one name
// alternate across communes, so one key gets interleaved ids. Add an aliased type, a
// repeated name and a name without key: the per-name build must give the same lists, in
// id order, as one street at a time.
let dir =
std::env::temp_dir().join(format!("gridpin-street-projection-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _scratch = Scratch::keep(&dir);
let rows = [
("av azul", "001", "vila", "Av Azul"),
("avenida azul", "001", "vila", "Avenida Azul"),
("avenida azul", "002", "outra", "AVENIDA AZUL"),
("avenida azul", "003", "terceira", "Avenida Azul"),
("avenida azul", "004", "quarta", "AVENIDA AZUL"),
("rua branca", "001", "vila", "Rua Branca"),
("rua cinza", "001", "vila", "Rua Cinza"),
];
let body: Vec<String> = rows
.iter()
.enumerate()
.map(|(i, (norm, id, city, display))| {
format!(
"{norm},{id},{city},28001,12,,{},40.4,{display},{city}",
-3.7 - i as f64 * 0.001
)
})
.collect();
let csv = dir.join("rows.csv");
std::fs::write(&csv, format!("nom_voie_norm,code_insee,nom_commune_norm,code_postal,numero,rep,lon,lat,nom_voie,nom_commune\n{}\n", body.join("\n"))).unwrap();
let rules = dir.join("rules");
std::fs::create_dir_all(&rules).unwrap();
std::fs::write(rules.join("street_types_latin.tsv"), "calle\nrue\nvia\n").unwrap();
let manifest = dir.join("manifest.json");
std::fs::write(
&manifest,
r#"{"country":"es","layer":"addresses","license":"test","source_release":"test"}"#,
)
.unwrap();
let bin = dir.join("test.bin");
crate::builder::build(&csv, &bin, None, None, Some(&rules), None, Some(&manifest)).unwrap();
let mut idx = Index::open(&bin).unwrap();
idx.rules = field_retry_type_rules(true);
let _scope = crate::rules::scope(idx.rules);
let types = field_street_type_aliases();
let key = |name: &str| {
(normalize(name) != "rua cinza")
.then(|| field_street_type_key(&prepared_query_key(name), &types))
};
let mut expected: HashMap<String, Vec<u32>> = HashMap::new();
for sid in 0..idx.streets_meta.len() / STREET_META_SIZE {
let sid = u32::try_from(sid).unwrap();
if let Some(k) = key(idx.name(idx.street_meta(sid).name_off)) {
expected.entry(k).or_default().push(sid);
}
}
assert_eq!(expected.len(), 2, "{expected:?}");
assert!(expected.values().any(|ids| ids.len() == 5), "{expected:?}");
assert_eq!(idx.project_street_names(key), expected);
}
#[test]
fn field_retry_type_abbreviation_without_sheet_pair_stays_literal() {
let mut idx =
es_observer_fixture("185-no-pair", &[("avenida azul", "vila", "001", "12")], "");
idx.rules = field_retry_type_rules(false);
let _scope = crate::rules::scope(idx.rules);
let (street, number) = cityless_field_address("Av. Azul, nº 12").unwrap();
assert!(idx.cityless_field_house(&street, number).is_none());
assert!(idx.cityless_field_house("avenida azul", number).is_some());
}
#[test]
fn field_retry_type_abbreviation_preserves_strong_original() {
let mut idx = es_observer_fixture(
"185-strong",
&[
("av azul", "vila", "001", "13"),
("avenida azul", "outra", "002", "13"),
],
"",
);
idx.rules = field_retry_type_rules(true);
let _scope = crate::rules::scope(idx.rules);
let raw = "Av. Azul, 13";
let original = idx.query_feats_postal_retry(raw, 3, None);
assert_eq!(original[0].0.precision, "house");
assert_eq!(original[0].0.housenumber.as_deref(), Some("13"));
assert_eq!(
es_observer_hits(&idx.query_feats_fields_retry(raw, 3, None)),
es_observer_hits(&original)
);
}
fn field_retry_recipient_rules(enabled: bool) -> &'static crate::rules::Rules {
let mut entries = vec![
(23, "enabled".into(), "1".into()),
(23, "regions".into(), "MG AC".into()),
(23, "forms".into(), "comma hyphen".into()),
(23, "postal_digits".into(), "8".into()),
(23, "postal_split".into(), "5".into()),
(16, "avenida".into(), String::new()),
(16, "av".into(), String::new()),
(24, "av".into(), "avenida".into()),
(24, "avenida".into(), "av".into()),
];
if enabled {
for prefix in ["A/C", "Aos cuidados de"] {
entries.push((25, prefix.into(), String::new()));
}
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn field_retry_recipient_recovers_names_beyond_generator_template() {
let mut idx = es_observer_fixture(
"189-recipient",
&[("avenida afonso pena", "belo horizonte", "001", "867")],
"",
);
idx.rules = field_retry_recipient_rules(true);
let _scope = crate::rules::scope(idx.rules);
for prefix in [
"A/C Recepção",
"A/C João da Silva",
"Aos cuidados de Maria Souza",
] {
let raw = format!("{prefix}, Av. Afonso Pena, nº 867");
let hits = idx.query_feats_street_data(&raw, 3, None);
assert!(!hits.is_empty(), "{raw}");
assert_eq!(hits[0].0.precision, "house", "{raw}");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("867"), "{raw}");
assert_eq!(normalize(&hits[0].0.commune), "belo horizonte", "{raw}");
}
}
#[test]
fn field_retry_recipient_requires_initial_whole_word_from_sheet() {
let _scope = crate::rules::scope(field_retry_recipient_rules(true));
for raw in [
"Rua X, 10, Rio Branco, AC",
"Rua A/C 10, Av. Afonso Pena, nº 867",
"Avenida Afonso Pena, 867",
"Recepção, Av. Afonso Pena, nº 867",
"A/Carlos, Av. Afonso Pena, nº 867",
"Aos cuidados demais, Av. Afonso Pena, nº 867",
"A/C João da Silva sem vírgula",
] {
assert!(recipient_field_retry(raw).is_none(), "{raw}");
}
for raw in [
"A/C Recepção, Av. Afonso Pena, nº 867",
"A/C João da Silva, Av. Afonso Pena, nº 867",
"Aos cuidados de Maria Souza, Av. Afonso Pena, nº 867",
] {
assert_eq!(
recipient_field_retry(raw),
Some("Av. Afonso Pena, nº 867"),
"{raw}"
);
}
drop(_scope);
let _scope = crate::rules::scope(field_retry_recipient_rules(false));
assert!(recipient_field_retry("A/C Recepção, Av. Afonso Pena, nº 867").is_none());
}
#[test]
fn field_retry_recipient_keeps_every_nonempty_original() {
let _scope = crate::rules::scope(field_retry_recipient_rules(true));
for precision in ["house", "interp", "near", "street", "city"] {
let original = vec![
field_witness(precision, "9", "Outra", 1.0),
field_witness("house", "867", "Belo Horizonte", 2.0),
];
let saved = es_observer_hits(&original);
let got = recipient_field_choose(
original,
"A/C Recepção, Av. Afonso Pena, nº 867",
|_| panic!("nonempty original must not retry"),
);
assert_eq!(es_observer_hits(&got), saved, "{precision}");
}
}
#[test]
fn field_retry_recipient_reuses_existing_address_guards() {
let mut idx = es_observer_fixture(
"189-guards",
&[("avenida afonso pena", "belo horizonte", "001", "867")],
"",
);
idx.rules = field_retry_recipient_rules(true);
let _scope = crate::rules::scope(idx.rules);
for q in [
"Av. Afonso Pena, nº 868",
"Av. Afonso Pena, nº 867, Outra, MG",
"Av. Afonso Pena, nº 867, Belo Horizonte, MG",
] {
let clean = idx.query_feats_street_data(q, 3, None);
let restored = idx.query_feats_street_data(&format!("A/C João da Silva, {q}"), 3, None);
assert_eq!(es_observer_hits(&restored), es_observer_hits(&clean), "{q}");
}
}
fn field_retry_comma_rules() -> &'static crate::rules::Rules {
let mut entries = vec![
(23, "enabled".into(), "1".into()),
(23, "regions".into(), "SC XY XZ".into()),
(23, "forms".into(), "comma hyphen".into()),
(23, "postal_digits".into(), "8".into()),
(23, "postal_split".into(), "5".into()),
];
for kind in ["alameda", "rua", "avenida", "av"] {
entries.push((16, kind.into(), String::new()));
}
entries.push((24, "av".into(), "avenida".into()));
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn field_retry_comma_restores_anchored_house() {
let mut idx = es_observer_fixture(
"192-anchors",
&[("alameda duque de caxias", "blumenau", "001", "78")],
"",
);
idx.rules = field_retry_comma_rules();
let _scope = crate::rules::scope(idx.rules);
let hits = idx.query_feats_street_data(
"Alameda Duque de Caxias 78 Centro 89015-010 Blumenau SC",
3,
None,
);
assert!(!hits.is_empty());
assert_eq!(hits[0].0.precision, "house");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("78"));
assert_eq!(normalize(&hits[0].0.street), "alameda duque de caxias");
assert_eq!(normalize(&hits[0].0.commune), "blumenau");
}
#[test]
fn field_retry_comma_restores_labeled_house() {
let mut idx = es_observer_fixture(
"192-label",
&[("avenida joao machado", "vila", "001", "348")],
"",
);
idx.rules = field_retry_comma_rules();
let _scope = crate::rules::scope(idx.rules);
let hits = idx.query_feats_street_data("Av. João Machado n° 348", 3, None);
assert!(!hits.is_empty());
assert_eq!(hits[0].0.precision, "house");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("348"));
assert_eq!(normalize(&hits[0].0.street), "avenida joao machado");
}
#[test]
fn field_retry_comma_preserves_numeral_street_name() {
let mut idx = es_observer_fixture(
"192-numeral",
&[
("rua 7 de setembro", "vila", "001", "100"),
("rua 7", "outra", "002", "7"),
],
"",
);
idx.rules = field_retry_comma_rules();
let _scope = crate::rules::scope(idx.rules);
let hits =
idx.query_feats_street_data("Rua 7 de Setembro 100 Centro 12345-678 Vila XY", 3, None);
assert!(!hits.is_empty());
assert_eq!(hits[0].0.housenumber.as_deref(), Some("100"));
assert_eq!(normalize(&hits[0].0.street), "rua 7 de setembro");
}
#[test]
fn field_retry_comma_keeps_comma_query_and_nonempty_original() {
let mut idx = es_observer_fixture("192-frozen", &[("rua azul", "vila", "001", "12")], "");
idx.rules = field_retry_comma_rules();
let _scope = crate::rules::scope(idx.rules);
for raw in ["Rua Azul, 12, Vila, XY", "Rua Azul 12", "Rua Azul"] {
let before = idx.query_feats_street_data_base(raw, 3, None);
assert!(!before.is_empty(), "{raw}");
assert_eq!(
es_observer_hits(&idx.query_feats_street_data(raw, 3, None)),
es_observer_hits(&before),
"{raw}"
);
}
}
#[test]
fn field_retry_comma_rejects_missing_house_and_wrong_city() {
let mut idx = es_observer_fixture("192-guards", &[("rua azul", "vila", "001", "12")], "");
idx.rules = field_retry_comma_rules();
let _scope = crate::rules::scope(idx.rules);
for raw in [
"Rua Azul Centro",
"Rua Azul 99 Centro 12345-678 Vila XY",
"Rua Azul 12 Centro 12345-678 Outra XY",
] {
let before = idx.query_feats_street_data_base(raw, 3, None);
assert_eq!(
es_observer_hits(&idx.query_feats_street_data(raw, 3, None)),
es_observer_hits(&before),
"{raw}"
);
}
}
fn field_retry_geo_rules() -> &'static crate::rules::Rules {
let mut entries = vec![
(23, "enabled".into(), "1".into()),
(23, "regions".into(), "CE SP GO XY".into()),
(23, "forms".into(), "comma hyphen".into()),
(23, "postal_digits".into(), "8".into()),
(23, "postal_split".into(), "5".into()),
];
for kind in ["rua", "avenida", "av"] {
entries.push((16, kind.into(), String::new()));
}
entries.push((24, "av".into(), "avenida".into()));
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn field_retry_geo_dash_postal_reaches_house() {
let mut idx = es_observer_fixture(
"195-fortaleza",
&[("avenida da abolicao", "fortaleza", "001", "3207")],
"",
);
idx.rules = field_retry_geo_rules();
let _scope = crate::rules::scope(idx.rules);
let hits = idx.query_feats_street_data(
"Av. da Abolição, 3207 – Meireles - Fortaleza - CE CEP 60165-081",
3,
None,
);
assert!(!hits.is_empty());
assert_eq!(hits[0].0.precision, "house");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("3207"));
assert_eq!(normalize(&hits[0].0.commune), "fortaleza");
assert_eq!(normalize(&hits[0].0.street), "avenida da abolicao");
}
#[test]
fn field_retry_geo_labeled_number_reaches_house() {
let mut idx = es_observer_fixture(
"195-carlos",
&[("rua dona alexandrina", "sao carlos", "001", "1478")],
"",
);
idx.rules = field_retry_geo_rules();
let _scope = crate::rules::scope(idx.rules);
let hits = idx.query_feats_street_data(
"Rua Dona Alexandrina, nº 1478, Centro - São Carlos - SP",
3,
None,
);
assert!(!hits.is_empty());
assert_eq!(hits[0].0.precision, "house");
assert_eq!(hits[0].0.housenumber.as_deref(), Some("1478"));
assert_eq!(normalize(&hits[0].0.commune), "sao carlos");
assert_eq!(normalize(&hits[0].0.street), "rua dona alexandrina");
}
#[test]
fn field_retry_geo_last_commune_avoids_district_homonym() {
let mut idx = es_observer_fixture(
"195-last",
&[
("rua azul", "campinas", "001", "395"),
("rua azul", "goiania", "002", "395"),
],
"",
);
idx.rules = field_retry_geo_rules();
let _scope = crate::rules::scope(idx.rules);
let hits =
idx.query_feats_street_data("Rua Azul, 395, Campinas, 74520-100, Goiânia, GO", 3, None);
assert!(hits
.first()
.is_none_or(|(h, _)| normalize(&h.commune) == "goiania"));
let raw = "Rua Azul, nº 395 – Campinas – 74520-100 – Goiânia – GO";
assert!(idx.query_feats_street_data_base(raw, 3, None).is_empty());
let hits = idx.query_feats_street_data(raw, 3, None);
assert_eq!(
normalize(&hits.first().expect("city after district").0.commune),
"goiania"
);
}
#[test]
fn field_retry_geo_city_in_street_is_not_tail() {
let mut idx = es_observer_fixture(
"195-street",
&[("rua fortaleza", "fortaleza", "001", "10")],
"",
);
idx.rules = field_retry_geo_rules();
let _scope = crate::rules::scope(idx.rules);
for raw in [
"Rua Fortaleza, 10",
"Rua Fortaleza, 10, Centro, XY",
"Rua Fortaleza, nº 10 – Meireles - CE",
] {
let before = idx.query_feats_street_data_base(raw, 3, None);
assert_eq!(
es_observer_hits(&idx.query_feats_street_data(raw, 3, None)),
es_observer_hits(&before),
"{raw}"
);
}
}
#[test]
fn field_retry_geo_no_known_commune_preserves_answer() {
let mut idx =
es_observer_fixture("195-unknown", &[("rua azul", "fortaleza", "001", "10")], "");
idx.rules = field_retry_geo_rules();
let _scope = crate::rules::scope(idx.rules);
let raw = "Rua Azul, nº 10 – Meireles - CE";
let before = idx.query_feats_street_data_base(raw, 3, None);
assert_eq!(
es_observer_hits(&idx.query_feats_street_data(raw, 3, None)),
es_observer_hits(&before)
);
}
#[test]
fn field_retry_geo_preserves_every_nonempty_original() {
let mut idx = es_observer_fixture(
"195-nonempty",
&[("rua azul", "fortaleza", "001", "10")],
"",
);
idx.rules = field_retry_geo_rules();
let _scope = crate::rules::scope(idx.rules);
for precision in ["house", "interp", "near", "street", "city"] {
let original = vec![
field_witness(precision, "10", "fortaleza", 1.0),
field_witness("house", "11", "outra", 2.0),
];
let expected = es_observer_hits(&original);
let mut called = false;
let hits = empty_field_choose(
original,
|| {
called = true;
Some("Rua Azul, 10, Fortaleza")
},
|_| Vec::new(),
);
assert!(!called, "{precision}");
assert_eq!(es_observer_hits(&hits), expected);
}
}
#[test]
fn field_retry_geo_anchor_rejects_conflicting_suffix() {
let mut idx = es_observer_fixture(
"195-anchor",
&[
("rua azul", "campinas", "001", "395"),
("rua azul", "goiania", "002", "395"),
],
"",
);
idx.rules = field_retry_geo_rules();
let _scope = crate::rules::scope(idx.rules);
for raw in [
"Rua Azul, nº 395 – Campinas – GO – Goiânia",
"Rua Azul, nº 395 – Campinas – 74520-100 – Goiânia",
] {
assert!(idx.geographic_field_retry(raw).is_none(), "{raw}");
let original = idx.query_feats_street_data_base(raw, 3, None);
assert_eq!(
es_observer_hits(&idx.query_feats_street_data(raw, 3, None)),
es_observer_hits(&original),
"{raw}"
);
}
}
#[allow(dead_code)]
trait TitleRetryBeforeImplementation {
fn query_feats_title_fields(
&self,
original: Vec<(Hit, [f32; N_FEATS])>,
_raw: &str,
_k: usize,
_focus: Option<&QueryFocus>,
) -> Vec<(Hit, [f32; N_FEATS])> {
original
}
}
impl TitleRetryBeforeImplementation for Index {}
fn field_retry_title_rules() -> &'static crate::rules::Rules {
let mut entries = vec![
(23, "enabled".into(), "1".into()),
(23, "regions".into(), "PA PB PR PE SP XY".into()),
(23, "postal_digits".into(), "8".into()),
(23, "postal_split".into(), "5".into()),
(
23,
"street_titles".into(),
"almirante doutor coronel marechal padre dom general".into(),
),
];
entries.push((
23,
"street_title_aliases".into(),
"alm:almirante dr:doutor cel:coronel mal:marechal pe:padre".into(),
));
for word in ["av", "avenida", "r", "rua"] {
entries.push((16, word.into(), String::new()));
}
for (a, b) in [("av", "avenida"), ("r", "rua")] {
entries.push((24, a.into(), b.into()));
}
crate::rules::from_section(&crate::rules::serialize_entries(&entries))
}
#[test]
fn field_retry_title_abbreviation_and_optional_title_reach_house() {
for (slot, (street, query, city, num)) in [
(
"avenida almirante barroso",
"Av. Alm. Barroso, 2305, Belém",
"belem",
"2305",
),
(
"avenida marechal floriano peixoto",
"Avenida Floriano Peixoto 825, Campina Grande",
"campina grande",
"825",
),
("rua coronel azul", "Rua Cel. Azul, 12, Vila", "vila", "12"),
("rua dr azul", "Rua Doutor Azul, 12, Vila", "vila", "12"),
("rua azul", "Rua Doutor Azul, 12, Vila", "vila", "12"),
]
.into_iter()
.enumerate()
{
let mut idx = es_observer_fixture(
&format!("198-positive-{slot}"),
&[(street, city, "001", num)],
"",
);
idx.rules = field_retry_title_rules();
let _scope = crate::rules::scope(idx.rules);
let hits = idx.query_feats_title_fields(Vec::new(), query, 3, None);
assert!(!hits.is_empty(), "{query}");
assert_eq!(hits[0].0.precision, "house", "{query}");
assert_eq!(hits[0].0.housenumber.as_deref(), Some(num));
assert_eq!(normalize(&hits[0].0.street), street);
assert_eq!(normalize(&hits[0].0.commune), city);
}
}
#[test]
fn field_retry_title_keeps_name_number_city_and_region() {
let mut idx = es_observer_fixture(
"198-negative",
&[
("rua coronel veiga", "general carneiro", "001", "12"),
("rua padre azul", "vila", "002", "12"),
("rua doutor azul", "padre vila", "003", "12"),
],
"",
);
idx.rules = field_retry_title_rules();
let _scope = crate::rules::scope(idx.rules);
for q in [
"Rua Coronel Viana, 12, General Carneiro, PR",
"Rua Coronel Veiga, 13, General Carneiro, PR",
] {
let hits = idx.query_feats_title_fields(Vec::new(), q, 3, None);
assert!(hits.is_empty(), "{q}");
}
let mut cityidx = es_observer_fixture(
"198-city-region",
&[
("rua doutor azul", "padre vila", "003", "12"),
("rua verde", "vila", "004", "99"),
],
"",
);
cityidx.rules = field_retry_title_rules();
for q in ["Rua Azul, 12, Vila, PE", "Rua Azul, 12, Vila"] {
assert!(
cityidx
.query_feats_title_fields(Vec::new(), q, 3, None)
.is_empty(),
"{q}"
);
}
let q = "Rua Coronel Veiga, 12, General Carneiro, PR";
let hits = idx.query_feats_title_fields(Vec::new(), q, 3, None);
assert_eq!(normalize(&hits[0].0.commune), "general carneiro");
}
#[test]
fn field_retry_title_preserves_whole_nonempty_answer() {
let mut idx = es_observer_fixture(
"198-preserve",
&[
("rua azul", "vila", "001", "12"),
("rua doutor azul", "outra", "002", "12"),
],
"",
);
idx.rules = field_retry_title_rules();
let _scope = crate::rules::scope(idx.rules);
for q in ["Rua Azul, 12, Vila", "Rua Doutor Azul, 12, Outra"] {
let original = idx.query_feats_street_data_base(q, 3, None);
assert!(!original.is_empty());
assert_eq!(
es_observer_hits(&idx.query_feats_title_fields(original.clone(), q, 3, None)),
es_observer_hits(&original)
);
}
}
#[allow(dead_code)]
trait ForeignCityBeforeImplementation {
fn foreign_city_guard(
&self,
_raw: &str,
hits: Vec<(Hit, [f32; N_FEATS])>,
) -> Vec<(Hit, [f32; N_FEATS])> {
hits
}
}
impl ForeignCityBeforeImplementation for Index {}
fn foreign_city_fixture() -> Index {
static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let label = format!(
"202-foreign-city-{}",
SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
);
let mut idx =
es_observer_fixture(&label, &[("rua azul", "rio de janeiro", "001", "10")], "");
let mut rows = vec![];
for (name, regions) in [
("rio de janeiro", "RJ"),
("comendador levy gasparian", "RJ"),
("niteroi", "RJ"),
("duque de caxias", "RJ"),
("jardim", "CE MS"),
("vila bela da santissima trindade", "MT"),
("fundao", "ES"),
("lages", "SC"),
("paracambi", "RJ"),
("rio branco", "AC MT"),
("blumenau", "SC"),
("bonito", "BA MS PE"),
("campinas", "SP"),
("sao paulo", "SP"),
] {
rows.push((26, format!("city:{name}"), regions.to_string()));
}
for (name, uf) in [
("rio de janeiro", "RJ"),
("sao paulo", "SP"),
("santa catarina", "SC"),
] {
rows.push((26, format!("state:{name}"), uf.to_string()));
}
rows.push((26, "regions".into(), "AC BA CE ES MS MT PE RJ SC SP".into()));
rows.push((26, "street_markers".into(), "rua ru r avenida av alameda al travessa tv estrada rodovia praca pca pc largo beco viela".into()));
rows.push((
26,
"district_markers".into(),
"bairro vila jardim jd distrito setor parque pq residencial loteamento colonia col"
.into(),
));
idx.rules = crate::rules::from_section(&crate::rules::serialize_entries(&rows));
idx
}
#[test]
fn foreign_city_rejects_only_first_precise_response() {
let idx = foreign_city_fixture();
for (query, city) in [
(
"Praça João Werneck 173, Comendador Levy Gasparian, Rio de Janeiro, Brasil",
"Rio de Janeiro",
),
(
"R. Nossa Senhora de Fátima, n° 10 - Bairro Niterói",
"Niterói",
),
("Av. Duque de Caxias, s/n", "Duque de Caxias"),
("Rua Azul, 10, Campinas SP", "Rio de Janeiro"),
] {
for precision in ["house", "interp", "near", "street"] {
let hits = vec![
field_witness(precision, "10", city, 1.0),
field_witness("house", "10", "Campinas", 2.0),
];
assert!(
idx.foreign_city_guard(query, hits).is_empty(),
"{query} / {precision}"
);
}
let city_hit = vec![field_witness("city", "", city, 1.0)];
assert_eq!(
es_observer_hits(&idx.foreign_city_guard(query, city_hit.clone())),
es_observer_hits(&city_hit)
);
}
let hits = vec![
field_witness("house", "10", "Campinas", 1.0),
field_witness("house", "10", "Rio de Janeiro", 2.0),
];
assert_eq!(
es_observer_hits(&idx.foreign_city_guard("Rua Azul 10 Campinas SP", hits.clone())),
es_observer_hits(&hits)
);
}
#[test]
fn foreign_city_near_misses_preserve_all_ranked_bytes() {
let idx = foreign_city_fixture();
for (query, city) in [
(
"MS, Rua Ten. Ari Rodrigues 252, Centro, 79240-000, Jardim",
"Jardim",
),
(
"MT, Rua Azul 10, Vila Bela da Santíssima Trindade",
"Vila Bela da Santíssima Trindade",
),
(
"Avenida Pedro Calmon, nº 550 – Ilha do Fundão/RJ",
"Rio de Janeiro",
),
("Av. Rio Branco, 100, Rio Branco - AC", "Rio Branco"),
(
"Alameda Duque de Caxias 78 Centro 89015-010 Blumenau SC",
"Blumenau",
),
("Rua Azul 10 Bonito", "Rio de Janeiro"),
("Rua Azul 10 Campinas", "Rio de Janeiro"),
("Rua Azul 10 Campinas SP Niterói RJ", "Blumenau"),
("Rua Azul 10 Campinas São Paulo SP", "Blumenau"),
("Rua Azul 10 Campinas SP", "Campinas"),
] {
for precision in ["house", "interp", "near", "street", "city"] {
let hits = vec![
field_witness(precision, "10", city, 1.0),
field_witness("house", "11", "Duque de Caxias", 2.0),
];
assert_eq!(
es_observer_hits(&idx.foreign_city_guard(query, hits.clone())),
es_observer_hits(&hits),
"{query} / {precision}"
);
}
}
let mut plain = foreign_city_fixture();
plain.rules = crate::rules::defaults_static();
let hits = vec![field_witness("house", "10", "Rio de Janeiro", 1.0)];
assert_eq!(
es_observer_hits(&plain.foreign_city_guard("Rua Azul 10 Campinas SP", hits.clone())),
es_observer_hits(&hits)
);
assert!(idx
.foreign_city_guard("Rua Azul 10 Campinas SP", vec![])
.is_empty());
}
#[test]
fn foreign_city_inferred_region_excludes_foreign_district_homonym() {
let idx = foreign_city_fixture();
let q = "Rua Anibal Cardoso, S/N Lages, Paracambi - Rio de Janeiro";
for precision in ["house", "interp", "near", "street"] {
assert!(
idx.foreign_city_guard(
q,
vec![field_witness(precision, "", "Rio de Janeiro", 1.0)]
)
.is_empty(),
"{precision}"
);
}
for (q, city) in [
("Rua Anibal Cardoso, S/N, Lages - SC", "Lages"),
("Rua Anibal Cardoso, Lages, Paracambi", "Rio de Janeiro"),
] {
for precision in ["house", "interp", "near", "street", "city"] {
let original = vec![
field_witness(precision, "", city, 1.0),
field_witness("house", "11", "Outra", 2.0),
];
assert_eq!(
es_observer_hits(&idx.foreign_city_guard(q, original.clone())),
es_observer_hits(&original),
"{q}"
);
}
}
}
/// Berlin keeps its houses under district communes, as in the German sheet: the city name
/// itself is a small commune, the streets live in "Mitte" and "Charlottenburg".
fn named_locality_index(case: &str) -> Index {
let mut rows = [
(
"pariser platz",
"11000",
"Berlin",
"1",
13.3777,
52.5163,
"Pariser Platz",
),
(
"rathausstrasse",
"11000",
"Berlin",
"15",
13.4088,
52.5186,
"Rathausstrasse",
),
(
"friedrichstrasse",
"11001",
"Mitte",
"100",
13.3884,
52.5204,
"Friedrichstrasse",
),
(
"alexanderplatz",
"11001",
"Mitte",
"1",
13.4127,
52.5213,
"Alexanderplatz",
),
(
"kurfurstendamm",
"11002",
"Charlottenburg",
"21",
13.3300,
52.5043,
"Kurfurstendamm",
),
(
"lindenweg",
"11003",
"Weststadt",
"5",
13.0700,
52.5175,
"Lindenweg",
),
(
"birkenweg",
"11004",
"Fernstadt",
"5",
12.9650,
52.5175,
"Birkenweg",
),
(
"friedrichstrasse",
"05913",
"Dortmund",
"100",
7.4538,
51.5075,
"Friedrichstrasse",
),
(
"hansastrasse",
"05913",
"Dortmund",
"1",
7.4600,
51.5140,
"Hansastrasse",
),
(
"hansastrasse",
"05913",
"Dortmund",
"2",
7.4601,
51.5141,
"Hansastrasse",
),
(
"hansastrasse",
"05913",
"Dortmund",
"3",
7.4602,
51.5142,
"Hansastrasse",
),
(
"hansastrasse",
"05913",
"Dortmund",
"4",
7.4603,
51.5143,
"Hansastrasse",
),
(
"place de berlin",
"07000",
"Lyonnet",
"6",
4.8300,
45.7600,
"Place de Berlin",
),
(
"lindenweg",
"05914",
"Hagen",
"5",
7.4700,
51.3600,
"Lindenweg",
),
(
"birkenweg",
"05915",
"Iserlohn",
"5",
7.7000,
51.3800,
"Birkenweg",
),
(
"berlin",
"01059",
"Klein Bennebek",
"1",
9.4229,
54.4040,
"Berlin",
),
(
"ostweg",
"20000",
"Weitstadt",
"1",
10.0000,
50.0000,
"Ostweg",
),
(
"westweg",
"20000",
"Weitstadt",
"7",
10.8400,
50.0000,
"Westweg",
),
(
"neuer markt",
"30000",
"Hafenstadt, Hansestadt",
"1",
12.1400,
54.0900,
"Neuer Markt",
),
(
"kaiserweg",
"40000",
"Anderswo",
"3",
9.8800,
53.3300,
"Kaiserweg",
),
(
"torweg",
"50000",
"Moorstadter Heide",
"1",
11.0000,
53.0000,
"Torweg",
),
(
"kaiserweg",
"60000",
"Irgendwo",
"9",
7.0000,
50.0000,
"Kaiserweg",
),
(
"torweg",
"70001",
"Sant Adria",
"1",
2.2200,
41.4300,
"Torweg",
),
(
"torweg", "70002", "Sant Boi", "1", 2.0400, 41.3400, "Torweg",
),
(
"torweg",
"70003",
"Sant Cugat",
"1",
2.0800,
41.4700,
"Torweg",
),
(
"torweg",
"70004",
"Sant Feliu",
"1",
2.0500,
41.3800,
"Torweg",
),
(
"breitenweg",
"80001",
"Neustadt an der Weinstrasse",
"71",
8.1400,
49.3500,
"Breitenweg",
),
(
"dorfweg", "80002", "Neustadt", "1", 11.0000, 52.0000, "Dorfweg",
),
(
"dorfweg",
"80003",
"Neustadt am Rennsteig",
"1",
10.9000,
50.6000,
"Dorfweg",
),
(
"dorfweg",
"80004",
"Neustadt bei Coburg",
"1",
11.1000,
50.3000,
"Dorfweg",
),
(
"dorfweg",
"80005",
"Neustadt in Holstein",
"1",
10.8000,
54.1000,
"Dorfweg",
),
(
"kaiserweg",
"40001",
"Bad Irgendwo",
"5",
7.5000,
50.5000,
"Kaiserweg",
),
(
"calle uno",
"38001",
"San Cristobal de la Laguna",
"5",
-16.3100,
28.4800,
"Calle Uno",
),
(
"calle uno",
"38002",
"Lejos",
"5",
-3.7000,
40.4000,
"Calle Uno",
),
("plaza", "38003", "Espana", "1", -4.0000, 40.0000, "Plaza"),
(
"dorfweg", "40002", "Bad Ems", "1", 7.7100, 50.3300, "Dorfweg",
),
(
"dorfweg",
"40003",
"Bad Kreuznach",
"1",
7.8700,
49.8400,
"Dorfweg",
),
(
"dorfweg", "40004", "Bad Tolz", "1", 11.5600, 47.7600, "Dorfweg",
),
];
// the builder takes rows sorted by (street, code, number)
rows.sort_by(|a, b| (a.0, a.1, a.3).cmp(&(b.0, b.1, b.3)));
let mut csv = String::new();
for (street, code, commune, number, lon, lat, display) in rows {
// one postcode: the query's own postcode evidence for a fallback answer
let postcode = if commune == "Anderswo" { "40000" } else { "" };
csv.push_str(&format!(
"{street},{code},{},{postcode},{number},,{lon:.4},{lat:.4},{display},\"{commune}\"\n",
normalize(commune)
));
}
forward_housenumber_index(case, &csv)
}
fn named_locality_top(idx: &Index, query: &str) -> Option<(String, String)> {
idx.query(query, 1)
.first()
.map(|hit| (hit.street.clone(), hit.commune.clone()))
}
#[test]
fn named_locality_fallback_finds_the_street_in_a_district_of_the_named_city() {
let idx = named_locality_index("district");
for (query, street, district) in [
("Friedrichstrasse 100, Berlin", "Friedrichstrasse", "Mitte"),
("Alexanderplatz 1, Berlin", "Alexanderplatz", "Mitte"),
(
"Kurfurstendamm 21, Berlin",
"Kurfurstendamm",
"Charlottenburg",
),
] {
assert_eq!(
named_locality_top(&idx, query),
Some((street.to_string(), district.to_string())),
"{query}"
);
// no candidate from another town, at any rank
for hit in idx.query(query, 5) {
assert!(
!["Dortmund", "Klein Bennebek"].contains(&hit.commune.as_str()),
"{query} -> {} {}",
hit.street,
hit.commune
);
}
}
}
#[test]
fn named_locality_fallback_is_silent_rather_than_another_town() {
let idx = named_locality_index("silent");
// Fernstadt is 29 km from the Berlin centroid, Iserlohn hundreds: both are other towns
assert_eq!(named_locality_top(&idx, "Birkenweg 5, Berlin"), None);
// the city named by the leading words of an official name ("Hafenstadt, Hansestadt")
assert_eq!(named_locality_top(&idx, "Kaiserweg 3, Hafenstadt"), None);
}
#[test]
fn named_locality_fallback_keeps_a_neighbour_within_the_radius() {
let idx = named_locality_index("radius");
// Weststadt is 22 km from the Berlin centroid; Hagen has the same street far away
assert_eq!(
named_locality_top(&idx, "Lindenweg 5, Berlin"),
Some(("Lindenweg".to_string(), "Weststadt".to_string()))
);
}
#[test]
fn named_locality_fallback_keeps_the_named_commune_beyond_the_radius() {
let idx = named_locality_index("same-name");
// Westweg lies 30 km from the Weitstadt centroid; the commune itself is the one named
assert_eq!(
named_locality_top(&idx, "Westweg 7 Weitstadt Xyzzy"),
Some(("Westweg".to_string(), "Weitstadt".to_string()))
);
}
#[test]
fn named_locality_needs_whole_leading_words_of_a_commune_name() {
let idx = named_locality_index("whole-words");
// "Moorstadt" only starts "Moorstadter Heide": no named locality, the fallback is as before
assert_eq!(
named_locality_top(&idx, "Kaiserweg 9, Moorstadt"),
Some(("Kaiserweg".to_string(), "Irgendwo".to_string()))
);
}
#[test]
fn named_locality_fallback_searches_again_focused_on_the_named_city() {
let idx = named_locality_index("focus");
// a single candidate: unfocused it is the more prominent Dortmund, which the locality
// check removes; the focused search finds the Berlin district
let hits = idx.query("Friedrichstrasse 100, Berlin", 1);
assert_eq!(hits.first().map(|hit| hit.commune.as_str()), Some("Mitte"));
assert_eq!(
idx.query("Friedrichstrasse 100", 1)
.first()
.map(|hit| hit.commune.as_str()),
Some("Dortmund"),
"the fixture must rank Dortmund first without a named city"
);
}
#[test]
fn named_locality_word_inside_a_longer_street_names_no_place() {
let idx = named_locality_index("street-word");
// "Berlin" is part of the street "Place de Berlin": the query names no other place
assert_eq!(
named_locality_top(&idx, "Hotel 6 Place de Berlin"),
Some(("Place de Berlin".to_string(), "Lyonnet".to_string()))
);
}
#[test]
fn named_locality_ignores_a_word_that_starts_many_commune_names() {
let idx = named_locality_index("generic-word");
// four communes start with "Sant": the word names no single place, the fallback is
// as before (the Catalan name of a Basque city must not anchor on Catalonia)
assert_eq!(
named_locality_top(&idx, "Kaiserweg 9, Sant Sebastia"),
Some(("Kaiserweg".to_string(), "Irgendwo".to_string()))
);
}
#[test]
fn named_locality_keeps_an_answer_matching_the_query_postcode_or_commune() {
let idx = named_locality_index("own-evidence");
// the fallback keeps the query's own postcode evidence over the named city
assert_eq!(
named_locality_top(&idx, "Kaiserweg 3, 40000 Hafenstadt"),
Some(("Kaiserweg".to_string(), "Anderswo".to_string()))
);
let anchor = idx.named_locality_anchor(&["kaiserweg", "3", "hafenstadt"]);
let mut hit = idx.query("Kaiserweg 3 40000", 1).remove(0);
assert_eq!(hit.commune, "Anderswo");
for (flags, kept) in [
(vec!["street_exact", "pc_exact"], true),
(vec!["street_exact", "commune_exact"], true),
(vec!["street_exact", "pc_dept"], false),
(vec!["street_exact", "commune_prefix"], false),
(vec!["street_exact"], false),
] {
hit.flags = flags.clone();
assert_eq!(idx.near_named_locality(&hit, &anchor), kept, "{flags:?}");
}
}
#[test]
fn named_locality_keeps_a_commune_whose_name_starts_with_the_named_words() {
let idx = named_locality_index("leading-words");
// "Neustadt" alone is a far village, and four longer names start with it (too many to
// be one place): the answer's own commune starts with the named word. Likewise four
// names start with "Bad".
assert_eq!(
named_locality_top(&idx, "Breitenweg 71, Neustadt Weinstrasse"),
Some((
"Breitenweg".to_string(),
"Neustadt an der Weinstrasse".to_string()
))
);
// a short leading word ("Bad") names no commune by itself
assert_eq!(
named_locality_top(&idx, "Kaiserweg 5, Bad Hafenstadt"),
None
);
}
#[test]
fn named_locality_reads_a_long_locality_tail() {
let idx = named_locality_index("long-tail");
// nine tokens after the last number, as in the Canary schools set; "Espana" is a far
// commune of its own, the named city starts seven tokens before the end
let toks = [
"calle",
"uno",
"5",
"38320",
"la",
"cuesta",
"san",
"cristobal",
"de",
"la",
"laguna",
"tenerife",
"espana",
];
let anchor = idx.named_locality_anchor(&toks);
let hits = idx.query("Calle Uno 5", 5);
for (commune, kept) in [("San Cristobal de la Laguna", true), ("Lejos", false)] {
let mut hit = hits
.iter()
.find(|hit| hit.commune == commune)
.cloned()
.unwrap_or_else(|| panic!("fixture must hold Calle Uno 5 in {commune}"));
hit.flags = vec!["street_exact", "house_rep"];
assert_eq!(idx.near_named_locality(&hit, &anchor), kept, "{commune}");
}
}
#[test]
fn named_locality_holds_when_the_city_comes_first() {
let idx = named_locality_index("city-first");
// dropping the leading city must not let a same-named street in another town answer
for hit in idx.query("Berlin Friedrichstrasse 100", 5) {
assert_ne!(hit.commune, "Dortmund", "{} {}", hit.street, hit.commune);
}
// a settlement under the dropped city still answers
assert_eq!(
named_locality_top(&idx, "Berlin Kurfurstendamm 21"),
Some(("Kurfurstendamm".to_string(), "Charlottenburg".to_string()))
);
}
/// Granada is found only by the prefix "gran" of the street word the "city first" variant
/// moves into the commune slot of "Gran Via 1, Madrid". `granada_street` is the one street
/// of Granada a pass can reach from "via madrid"; with `madrid` the tail names a commune.
fn prefix_commune_index(case: &str, granada_street: (&str, &str), madrid: bool) -> Index {
let (key, display) = granada_street;
let mut rows = vec![format!(
"{key},18087,granada,18012,1,,-3.6046,37.1847,{display},Granada\n"
)];
if madrid {
rows.push(
"paseo prado,28079,madrid,28014,1,,-3.6921,40.4138,Paseo Prado,Madrid\n".into(),
);
}
rows.sort();
forward_housenumber_index(case, &rows.concat())
}
/// Main-path answers only (no dropping fallbacks): the check lives in hypothesis selection.
fn prefix_commune_main_path(idx: &Index, prepared: &str) -> Vec<String> {
idx.query_feats_prepared(prepared, 5, None)
.into_iter()
.map(|(hit, _)| format!("{} | {} | {:?}", hit.street, hit.commune, hit.flags))
.collect()
}
#[test]
fn prefix_commune_from_a_street_word_cannot_leave_the_named_city_in_any_pass() {
// exact pass ("via madrid"), typo pass ("via madrd") and street-word subset pass
// ("calle real de madrid"): each reaches Granada only through the prefix "gran"
for (case, street) in [
("exact", ("via madrid", "Via Madrid")),
("fuzzy", ("via madrd", "Via Madrd")),
("subset", ("calle real de madrid", "Calle Real De Madrid")),
] {
// without a commune Madrid the tail names no place, and the pass reaches Granada
let unnamed = prefix_commune_index(&format!("{case}-unnamed"), street, false);
let reached = prefix_commune_main_path(&unnamed, "gran via 1 madrid");
assert!(
reached
.iter()
.any(|a| a.contains("| Granada |") && a.contains("commune_prefix")),
"{case}: fixture must reach Granada by prefix, got {reached:?}"
);
let idx = prefix_commune_index(case, street, true);
let named = prefix_commune_main_path(&idx, "gran via 1 madrid");
assert!(
!named.iter().any(|a| a.contains("| Granada |")),
"{case}: {named:?}"
);
}
}
#[test]
fn prefix_commune_check_keeps_own_evidence_and_the_named_place() {
let idx = forward_housenumber_index(
"prefix-commune-check",
"calle mayor,28079,madrid,28013,1,,-3.7038,40.4168,Calle Mayor,Madrid\n\
via madrid,18087,granada,18012,1,,-3.6046,37.1847,Via Madrid,Granada\n\
via madrid,19130,guadalajara,19001,1,,-3.1669,40.6324,Via Madrid,Guadalajara\n\
via madrid,28058,getafe,28901,1,,-3.7325,40.3057,Via Madrid,Getafe\n\
via madrid,28092,madrid sur,28900,1,,-2.50,39.50,Via Madrid,Madrid Sur\n\
via madrid,28093,madrid norte,28910,1,,-2.40,41.20,Via Madrid,Madrid Norte\n\
via madrid,28094,madrid este,28920,1,,-2.20,40.40,Via Madrid,Madrid Este\n\
via madrid,28095,madrid oeste,28930,1,,-4.90,40.40,Via Madrid,Madrid Oeste\n",
);
let anchor = idx.named_locality_anchor(&["gran", "via", "1", "madrid"]);
let sid = |commune: &str| {
(0..(idx.streets_meta.len() / STREET_META_SIZE) as u32)
.find(|&sid| idx.commune_name(idx.street_meta(sid).commune_id) == commune)
.unwrap_or_else(|| panic!("fixture street in {commune}"))
};
let prefix = Feats {
street_fuzzy: true,
commune_prefix: true,
..Default::default()
};
// near misses of the evidence fields: only exact commune or exact postcode excuse it
for (features, kept) in [
(prefix, false),
(
Feats {
commune_exact: true,
..prefix
},
true,
),
(
Feats {
pc_exact: true,
pc_dept: true,
..prefix
},
true,
),
(
Feats {
pc_dept: true,
..prefix
},
false,
),
(
Feats {
commune_prefix: false,
..prefix
},
true,
),
] {
assert_eq!(
idx.prefix_commune_within_named_locality(sid("Granada"), &features, &anchor),
kept,
"{:?}",
features.to_vec()
);
}
// four communes start with "Madrid" (too many for the anchor to hold them, so the radius
// cannot keep them): a commune starting with the named word is the named place even
// 140 km away; one 12 km away is too; one 60 km away is not
for (commune, kept) in [
("Madrid Sur", true),
("Getafe", true),
("Guadalajara", false),
("Granada", false),
] {
assert_eq!(
idx.prefix_commune_within_named_locality(sid(commune), &prefix, &anchor),
kept,
"{commune}"
);
}
// no number, no locality: street and place cannot be told apart
let none = idx.named_locality_anchor(&["gran", "via", "madrid"]);
assert!(idx.prefix_commune_within_named_locality(sid("Granada"), &prefix, &none));
}
#[test]
fn named_locality_head_is_read_only_when_a_house_number_ends_the_query() {
let idx = forward_housenumber_index(
"named-locality-head",
"calle luna,28093,madrid norte,28910,1,,-2.40,41.20,Calle Luna,Madrid Norte\n\
calle mar,28094,madrid este,28920,1,,-2.20,40.40,Calle Mar,Madrid Este\n\
calle mayor,28079,madrid,28013,1,,-3.7038,40.4168,Calle Mayor,Madrid\n\
calle rio,28095,madrid oeste,28930,1,,-4.90,40.40,Calle Rio,Madrid Oeste\n\
calle sol,28092,madrid sur,28900,1,,-2.50,39.50,Calle Sol,Madrid Sur\n\
via madrid,18087,granada,18012,1,,-3.6046,37.1847,Via Madrid,Granada\n\
via madrid,28096,pueblo sur,28940,1,,-2.45,39.55,Via Madrid,Pueblo Sur\n",
);
let sid = |commune: &str| {
(0..(idx.streets_meta.len() / STREET_META_SIZE) as u32)
.find(|&sid| idx.commune_name(idx.street_meta(sid).commune_id) == commune)
.unwrap_or_else(|| panic!("fixture street in {commune}"))
};
let prefix = Feats {
street_fuzzy: true,
commune_prefix: true,
..Default::default()
};
let granada_kept = |toks: &[&str]| {
let anchor = idx.named_locality_anchor(toks);
idx.prefix_commune_within_named_locality(sid("Granada"), &prefix, &anchor)
};
// the city first, a house number last: the leading commune is the named place
assert!(!granada_kept(&["madrid", "gran", "via", "1"]));
assert!(!granada_kept(&["madrid", "gran", "via", "1234"]));
// only the leading name is the place: a street named after another city names none
assert!(!granada_kept(&[
"madrid", "camino", "de", "granada", "viejo", "1"
]));
// near misses: a code longer than a house number ends the query (a postcode or a
// Brazilian CEP), or words follow the number, or no street word is left before it
for toks in [
&["madrid", "gran", "via", "12345"][..],
&["madrid", "gran", "via", "20520051"],
&["madrid", "gran", "via", "1", "bajo"],
&["madrid", "1"],
&["madrid", "3", "1"],
&["gran", "via", "1"],
] {
assert!(granada_kept(toks), "{toks:?}");
}
// the longest leading commune name: "Madrid Sur" names its own place (Pueblo Sur is
// 7 km from it), not only "Madrid", whose longer names are too many to count
let anchor = idx.named_locality_anchor(&["madrid", "sur", "gran", "via", "1"]);
assert!(idx.prefix_commune_within_named_locality(sid("Pueblo Sur"), &prefix, &anchor));
let anchor = idx.named_locality_anchor(&["madrid", "gran", "via", "1"]);
assert!(!idx.prefix_commune_within_named_locality(sid("Pueblo Sur"), &prefix, &anchor));
}
#[test]
fn prefix_commune_cannot_leave_the_city_named_first() {
// "Madrid, Gran 1": the city first, a house number last. Without a commune Madrid the
// pass reaches Granada by the prefix "gran"; with it the head names the place
let unnamed = prefix_commune_index("head-unnamed", ("via madrid", "Avenida Madrid"), false);
let reached = prefix_commune_main_path(&unnamed, "madrid gran 1");
assert!(
reached
.iter()
.any(|a| a.contains("| Granada |") && a.contains("commune_prefix")),
"fixture must reach Granada by prefix, got {reached:?}"
);
let idx = prefix_commune_index("head-named", ("via madrid", "Avenida Madrid"), true);
let named = prefix_commune_main_path(&idx, "madrid gran 1");
assert!(
!named.iter().any(|a| a.contains("| Granada |")),
"{named:?}"
);
}
#[test]
fn prefix_drop_keeps_the_answer_in_the_city_named_first() {
// "Madrid, Gran Via 1" with no Gran Via indexed: dropping "madrid gran" leaves "via 1",
// a street type plus a number, which an exact street "Via" in a far town answers
let index = |case: &str, via_commune: (&str, &str, &str, f64, f64)| {
let (insee, norm, name, lon, lat) = via_commune;
let mut rows = [
"paseo prado,28079,madrid,28014,1,,-3.6921,40.4138,Paseo Prado,Madrid\n"
.to_string(),
format!("via,{insee},{norm},29601,1,,{lon},{lat},Via,{name}\n"),
];
rows.sort();
forward_housenumber_index(case, &rows.concat())
};
let far = index(
"drop-far",
("29069", "marbella", "Marbella", -4.8858, 36.5101),
);
let answers: Vec<String> = far
.query("Madrid, Gran Via 1", 3)
.iter()
.map(|hit| format!("{} | {}", hit.street, hit.commune))
.collect();
assert!(
!answers.iter().any(|a| a.ends_with("| Marbella")),
"{answers:?}"
);
// the same drop answers when nothing names a place first, or the street is in the city
assert_eq!(
far.query("Plaza Gran Via 1", 1)
.first()
.map(|hit| hit.commune.as_str()),
Some("Marbella")
);
let near = index("drop-near", ("28058", "getafe", "Getafe", -3.7325, 40.3057));
assert_eq!(
near.query("Madrid, Gran Via 1", 1)
.first()
.map(|hit| hit.commune.as_str()),
Some("Getafe")
);
}
}