Architecture & Spatial-First Geocoding
This document explains why texspace achieves higher accuracy than parse-first geocoders while running purely from static byte-range files in WebAssembly. For the byte-level archive layouts (TXGR, TXGS, TXGZ, TXGL, TXGO), see TXG_SPEC.md.
1. Spatial-First Intersection vs. Parse-First Geocoders#
Traditional open-source geocoders (libpostal / Pelias / Nominatim) follow a parse-first pipeline:
- Run an NLP tagger to guess
{housenumber, street, city, state, postcode}. - Issue structured queries against Elasticsearch or PostgreSQL using those guessed labels.
When a user enters a swapped field, an ambiguous city/street collision ("Washington St, Lincoln"), a wrong city alongside a valid ZIP ("4865 Mission St Apt 4B 94112 Oakland"), or messy scraped web text, an early tagging mistake cascades into a complete miss or false city fallback.
texspace implements TEXSPACE (Robust Location Search from Text Queries, Sengar et al., ACMGIS '07): intersect spatial footprints first, classify fields second:
raw query
├─ 0-RTT fast path: direct coords, DMS/DDM, S2, H3, Slippy z/x/y, Quadkey, Geohash, Plus Code, WKT, geo:, map URLs
├─ normalize text + extract sub-premise/unit/PO Box + mask parentheticals + non-Latin romanization
├─ Stage 1 (router.txg, 384 KiB root cached in 1 RTT):
│ exact span bitmasks + global admin prominence + bounded Damerau-Levenshtein typo rescue
├─ Stage 2-3 (selected shard(s) in parallel):
│ load ATTR leaf blocks + ADMIN_MACRO polygon block (and any mounted TXGO private overlays)
├─ Stage 4 (in-RAM S2 CellUnion DFS):
│ galloping S2 CellUnion intersection across non-overlapping query token spans -> top compact spatial focuses
├─ Stage 5-6 (Hilbert-clustered ENTS + ADDR + local ADMIN):
│ resolve 4-tier address precision: parcel -> rooftop -> building-snapped -> parity-aware interpolation
└─ Stage 7 (GBDT Ranker + Platt Calibration):
score coverage, compactness, directional/postcode/admin concordance, focus proximity -> calibrated confidenceBecause "4865 Mission St", "94112", and "San Francisco" share an S2 spatial intersection while "Oakland" does not overlap "94112", the engine cleanly pins the exact parcel 6272-015B and reports conflicting_tokens: ["oakland"] — without relying on fragile regex grammar rules.
2. Hilbert-Clustered Static Archives (TXG v2)#
All 74.8M entities and 450M+ rooftops across 128 geographic shards are sorted by S2 Level-30 Hilbert Cell ID (s2_cell_l30(lat, lon)):
- Single-hop fence directories: Every
router.txgand<shard>.txgembeds a compressed Root Block (bytes 0..root_end) mapping alphabetically sorted fence keys and Hilbert cell ranges directly to fixed byte offsets. Once the root is cached, every lookup resolves straight to a16–32 KBleaf block with zero intermediate B-tree RTTs. - Precomputed full-resolution admin hierarchy (
ENT_FLAG_SAME_PARENTS): At pack time, full-resolution point-in-polygon admin containment ([country, region, county, locality]) is precomputed onto every entity and cross-border rooftop (ADDR_FLAG_CUSTOM_LOCALITY). Along the Hilbert curve, ~98% of consecutive entities inherit their predecessor's parent vector in 0 bytes — guaranteeing that cross-border arterials like Mission St (San Francisco / Daly City) never suffer polygon-simplification drift. - High-ratio delta-E7 coordinates: Quantizing WGS84 coordinates to
i32(round(deg * 1e7), ~1.1 cm resolution) and ZigZag-varint delta encoding along Hilbert order packs rooftops to~4–6 bytes/addresscompressed — fitting the entire planet into 8.80 GB.
3. Pure-Rust Fuzzy Typo Tolerance (Zero Trigram Server)#
Standard trigram indexes explode wire transfer over HTTP Range. Instead, texspace-txg exploits the sorted alphabetical layout of ATTR and ADMIN leaf blocks (crates/txg/src/query/fuzzy.rs):
- Zero overhead on clean queries: An
exact_covered_masktracks which query tokens already matched verbatim; fuzzy probes never fire on already-covered spans. - In-block & adjacent-fence bounded Damerau-Levenshtein: When a non-numeric, non-postal token (
>= 5chars) misses exact lookup, the engine scans already-loaded blocks + up to 2 adjacent alphabetical neighbor fences in RAM (max_dist = 1for 5–7 chars,max_dist = 2for 8+ chars), preserving exact street suffixes ("mision st"→"mission st") and breaking distance ties by shard count / entity count ("california"beats obscure"californian"). - Early-character transposition probes: Swaps characters
(0, 1)and(1, 2)to catch leading-letter typos crossing alphabetical boundaries ("lnodon"→"london","dwoning st"→"downing st"). - Standalone major-place admin rescue: If a bare place query verbatim-matches only an obscure low-prominence village (
pop_q8 < 175, e.g."San Fransisco"in Ecuador),router.txgprobes adjacentADMINprominence blocks (50× denser thanATTR) and elevates the matching high-prominence city ("San Francisco",us_ca) into the ranker.
4. Non-Latin Scripts & Multilingual Normalization#
- Automatic deterministic romanization (
crates/text/src/romanize.rs): Chinese Hanzi (Pinyin), Japanese Kana (Hepburn), Korean Hangul, Cyrillic, Greek, Hebrew, Arabic, and Thai are romanized at index build time and focus-scoped query time. - CJK & European street handling: Native CJK address tokenization (
114臺北市內湖區瑞光路192號10樓), Germanic street decompounding (Friedrichstraße↔Friedrich Strasse), Romance article normalization (Rue de la Paix), UK/Canadian/Dutch fine-unit postal codes (SW1A 2AA,H3B 2Y5,1012 JS), and US highway / frontage-road aliases (E US 290 Hwy↔East United States Highway 290).
5. Direct Zero-Network Spatial Formats#
Both search() and autocomplete() (as well as parseDirect()) resolve all of the following in 0 Range requests:
| Format | Examples |
|---|---|
| Decimal coordinates | 37.7749, -122.4194 |
| DMS / DDM | 37°46'29.6"N 122°25'09.8"W |
| S2 Cell Token / ID | s2:8085808c |
| H3 Hex Index | h3:8928308280fffff |
| Slippy Map Tile | 14/2621/6331 |
| Bing Quadkey | qk:023010203330 |
| Geohash | gh:9q8yyk8y |
| Open Location Code (Plus Code) | 849VQHFQ+5W |
| WKT Point / Polygon | POINT(-122.4194 37.7749) |
geo: URI | geo:37.7749,-122.4194 |
| Map URLs | OpenStreetMap & Google Maps coordinate URLs |
6. Verified Accuracy & Performance#
Evaluated on the strictly independent 440-query, 9-country, 5-continent Third-Party Global Civic Holdout (eval/third_party_global_holdout_report.md, zero records sampled from Overture/OSM/OpenAddresses/GeoNames):
| Engine | Mode | Top-1 Pass | Top-3 Pass | Median Error | Misses | Latency (p50) | Cost / 1M |
|---|---|---|---|---|---|---|---|
texspace (Local SQLite) | Self-hosted | 95.2% | 96.6% | 12.7 m | 0.0% | 24.2 ms | $0 |
texspace (Serverless TXG v2 WASM) | 0 servers / HTTP 206 | 94.1% | 95.7% | 14.3 m | 0.0% | 37.9 ms (warm: 255 KB / 4 RTTs) | ~$0 |
| ArcGIS | Paid API | 95.0% | 96.8% | 12.0 m | 0.0% | 269.2 ms | $40–$500 |
| Google Maps | Paid API | 93.6% | 93.9% | 20.9 m | 0.0% | 170.7 ms | $5,000 |
| Mapbox v6 | Paid API | 87.5% | 90.0% | 19.6 m | 0.0% | 206.0 ms | $750–$5,000 |
| Pelias / Geocode Earth | Paid / Self-hosted | 76.6% | 77.0% | 23.4 m | 0.2% | 258.2 ms | $500–$1,000 |
| Photon | Self-hosted | 63.2% | 66.6% | 27.1 m | 24.8% | 813.5 ms | Free |