Internals · Architecture

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:

  1. Run an NLP tagger to guess {housenumber, street, city, state, postcode}.
  2. 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:

text
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 confidence

Because "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.txg and <shard>.txg embeds 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 a 16–32 KB leaf 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/address compressed — 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):

  1. Zero overhead on clean queries: An exact_covered_mask tracks which query tokens already matched verbatim; fuzzy probes never fire on already-covered spans.
  2. In-block & adjacent-fence bounded Damerau-Levenshtein: When a non-numeric, non-postal token (>= 5 chars) misses exact lookup, the engine scans already-loaded blocks + up to 2 adjacent alphabetical neighbor fences in RAM (max_dist = 1 for 5–7 chars, max_dist = 2 for 8+ chars), preserving exact street suffixes ("mision st" → "mission st") and breaking distance ties by shard count / entity count ("california" beats obscure "californian").
  3. 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").
  4. 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.txg probes adjacent ADMIN prominence blocks (50× denser than ATTR) 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:

FormatExamples
Decimal coordinates37.7749, -122.4194
DMS / DDM37°46'29.6"N 122°25'09.8"W
S2 Cell Token / IDs2:8085808c
H3 Hex Indexh3:8928308280fffff
Slippy Map Tile14/2621/6331
Bing Quadkeyqk:023010203330
Geohashgh:9q8yyk8y
Open Location Code (Plus Code)849VQHFQ+5W
WKT Point / PolygonPOINT(-122.4194 37.7749)
geo: URIgeo:37.7749,-122.4194
Map URLsOpenStreetMap & 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):

EngineModeTop-1 PassTop-3 PassMedian ErrorMissesLatency (p50)Cost / 1M
texspace (Local SQLite)Self-hosted95.2%96.6%12.7 m0.0%24.2 ms$0
texspace (Serverless TXG v2 WASM)0 servers / HTTP 20694.1%95.7%14.3 m0.0%37.9 ms (warm: 255 KB / 4 RTTs)~$0
ArcGISPaid API95.0%96.8%12.0 m0.0%269.2 ms$40–$500
Google MapsPaid API93.6%93.9%20.9 m0.0%170.7 ms$5,000
Mapbox v6Paid API87.5%90.0%19.6 m0.0%206.0 ms$750–$5,000
Pelias / Geocode EarthPaid / Self-hosted76.6%77.0%23.4 m0.2%258.2 ms$500–$1,000
PhotonSelf-hosted63.2%66.6%27.1 m24.8%813.5 msFree