Modern Apps git

← Modern-Apps.git

networklocation: add altitude to beacon stores and lookups

Commit
010a62e329379c7dc49dfce3cf73d06c1a5b9c1d
Author
Vayun Mathur <[email protected]>
When
2026-10-30 02:31 UTC (1 month ago)
Parents
d79dcf4
The offline beacon pipeline had no altitude anywhere: shards, the
WPSDB2 store payload, the native reader, and BeaconFix all carried only
lat/lon plus horizontal accuracy. Upcoming crawl data includes altitude
(Apple's WiFi location.5, present on essentially every WiFi fix), so
this threads it through the whole path.

- Shards (record.rs): altitude and a flags byte occupy the former zero
  pad, so pre-altitude shards still read as "unknown". 40 B/record is
  unchanged.
- Store (store.rs): new payload kind 2, lat(35) | lon(36) | acc(16) |
  alt(16) = 103 bits. Altitude is metres biased by 32768 with 0 as the
  unknown sentinel; kind-1 stores (87 bits) stay readable and report
  NaN altitude. verify_store checks altitude too.
- Builder (gsloc.rs): decodes location.5 for WiFi. Cell responses have
  no altitude field at all (verified on the wire: cell locations carry
  only fields 1-4, 11, 12), so cells always read altitude-unknown; the
  bulk CSV dumps have none either.
- App (wpsdb.rs, wpsdb_part1.rs): the reader accepts both kinds; the
  JNI lookup now returns [lat, lon, accuracy, altitude], NaN meaning
  unknown. BeaconFix.altitudeMeters is a Double? (null = unknown).
- The solver stays 2D and LocationProviderImpl still declares
  supportsAltitude = false; this is storage/lookup/data-model support
  only. Rejected a 3D solver change as out of scope.

Also fixed a pre-existing rand 0.10 API break in the crate's tests
(gen_range -> random_range, and the Rng -> RngExt import after the
trait split) which blocked all test compilation, unrelated to altitude
but required to verify anything.

Verified: cargo test in wps_harvest (100 passed), cargo test in
networklocation/src/main/rust (22 passed, incl. altitude round-trips,
kind-1 NaN back-compat, cell NaN), :networklocation:compileDevKotlin,
:networklocation:lint, and ./check networklocation (detekt, lint,
cargo check/clippy/doc) all green.

Diff

networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.ktindex c0062d8d47..35a81c4f8b 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.kt@@ -55,12 +55,17 @@ sealed interface BeaconId { /**  * A beacon whose coordinates are known (from the offline stores or the local cache).  * [accuracyMeters] is the beacon's own horizontal accuracy radius.+ *+ * [altitudeMeters] is the beacon's altitude when the source reported one (kind-2 WiFi+ * records; Apple's `location.5`), or null when it did not — always the case for cells and+ * for kind-1 stores. The solver is 2D and does not consume it yet.  */ data class BeaconFix(     val id: BeaconId,     val latitude: Double,     val longitude: Double,     val accuracyMeters: Double,+    val altitudeMeters: Double? = null, )  /** An estimated device position: the output of the Rust weighted-centroid solver. */
networklocation/src/main/java/com/vayunmathur/networklocation/WpsStoreNative.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/WpsStoreNative.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/WpsStoreNative.ktindex 18a43f4ee1..928346d181 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/WpsStoreNative.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/WpsStoreNative.kt@@ -29,9 +29,11 @@ object WpsStoreNative {     external fun open(fd: Int, offset: Long, length: Long): Long      /**-     * `[lat, lon, accuracyMeters]` for the 128-bit key ([keyHi], [keyLo]), or null if the-     * store does not contain it. A negative accuracy means the store holds no radius for that-     * beacon; callers substitute their own conservative default.+     * `[lat, lon, accuracyMeters, altitudeMeters]` for the 128-bit key ([keyHi], [keyLo]), or+     * null if the store does not contain it. A negative accuracy means the store holds no+     * radius for that beacon; callers substitute their own conservative default. A NaN+     * altitude means the store holds no altitude for that beacon — always the case for kind-1+     * stores and for cell records, since the cell response has no altitude field.      */     external fun lookup(handle: Long, keyHi: Long, keyLo: Long): DoubleArray? 
networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.ktindex 43889dad9c..1f95f895ea 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt@@ -95,7 +95,7 @@ class OfflineBeaconStore(context: Context) {         if (BeaconKeys.isRandomizedMac(key)) return null         val r = WpsStoreNative.lookup(wifiHandle, 0L, key) ?: return null         if (r.size < MIN_LOOKUP_FIELDS) return null-        return BeaconFix(id, r[0], r[1], accuracyOf(r[2]))+        return BeaconFix(id, r[0], r[1], accuracyOf(r[2]), altitudeOf(r[ALTITUDE_FIELD]))     }      /** Resolve cell towers present in the offline store. Absent towers are omitted. */@@ -112,7 +112,7 @@ class OfflineBeaconStore(context: Context) {                     BeaconKeys.cellKeyLo(id),                 ) ?: continue                 if (r.size >= MIN_LOOKUP_FIELDS) {-                    out[id] = BeaconFix(id, r[0], r[1], accuracyOf(r[2]))+                    out[id] = BeaconFix(id, r[0], r[1], accuracyOf(r[2]), altitudeOf(r[ALTITUDE_FIELD]))                 }             }             return out@@ -161,10 +161,17 @@ class OfflineBeaconStore(context: Context) {          */         const val UNKNOWN_ACCURACY_METERS = 100.0 -        /** Native lookup fields: latitude, longitude, accuracy. */-        const val MIN_LOOKUP_FIELDS = 3+        /** Native lookup fields: latitude, longitude, accuracy, altitude. */+        const val MIN_LOOKUP_FIELDS = 4++        /** Index of the altitude element in the native lookup result. */+        const val ALTITUDE_FIELD = 3          fun accuracyOf(stored: Double): Double =             if (stored < 0.0) UNKNOWN_ACCURACY_METERS else stored++        /** The native reader reports an absent altitude as NaN; null is the Kotlin shape. */+        fun altitudeOf(stored: Double): Double? =+            stored.takeUnless { it.isNaN() }     } }
networklocation/src/main/rust/src/lib.rs
diff --git a/networklocation/src/main/rust/src/lib.rs b/networklocation/src/main/rust/src/lib.rsindex 744851ae82..242d0be179 100644--- a/networklocation/src/main/rust/src/lib.rs+++ b/networklocation/src/main/rust/src/lib.rs@@ -168,7 +168,7 @@ pub fn estimate_position(measurements: &[Measurement]) -> Option<EstimatedPositi mod tests {     use log::info;     use rand::rngs::SmallRng;-    use rand::{Rng, SeedableRng};+    use rand::{RngExt, SeedableRng};     use std::ops::Range;      use crate::coordinate::Coordinate;@@ -182,17 +182,17 @@ mod tests {         real_position: Position,         random: &mut SmallRng,     ) -> Measurement {-        let x = random.gen_range(x_range);-        let y = random.gen_range(y_range);-        let z = random.gen_range(z_range);-        let x_six_sigma_squared: f64 = random.gen_range(3000.0..5000.0);-        let y_six_sigma_squared: f64 = random.gen_range(3000.0..5000.0);-        let z_six_sigma_squared: f64 = random.gen_range(50.0..100.0);+        let x = random.random_range(x_range);+        let y = random.random_range(y_range);+        let z = random.random_range(z_range);+        let x_six_sigma_squared: f64 = random.random_range(3000.0..5000.0);+        let y_six_sigma_squared: f64 = random.random_range(3000.0..5000.0);+        let z_six_sigma_squared: f64 = random.random_range(50.0..100.0);         let distance = ((x - real_position.x.value).powi(2)             + (y - real_position.y.value).powi(2)             + (z - real_position.z.value).powi(2))         .sqrt()-            + random.gen_range(10.0..100.0);+            + random.random_range(10.0..100.0);          Measurement {             position: Position {@@ -215,21 +215,21 @@ mod tests {             let mut random = SmallRng::seed_from_u64(s);              let real_position = Position {-                x: Coordinate::new_real(random.gen_range(-10000.0..10000.0), 0.0),-                y: Coordinate::new_real(random.gen_range(-10000.0..10000.0), 0.0),-                z: Coordinate::new_real(random.gen_range(-10000.0..10000.0), 0.0),+                x: Coordinate::new_real(random.random_range(-10000.0..10000.0), 0.0),+                y: Coordinate::new_real(random.random_range(-10000.0..10000.0), 0.0),+                z: Coordinate::new_real(random.random_range(-10000.0..10000.0), 0.0),             };              let mut measurements = vec![];              for i in 0..9 {                 let mut measurement = generate_random_measurement(-                    real_position.x.value - random.gen_range(0.0..1000.0)-                        ..real_position.x.value + random.gen_range(0.0..1000.0),-                    real_position.y.value - random.gen_range(0.0..1000.0)-                        ..real_position.y.value + random.gen_range(0.0..1000.0),-                    real_position.z.value - random.gen_range(0.0..1000.0)-                        ..real_position.z.value + random.gen_range(0.0..1000.0),+                    real_position.x.value - random.random_range(0.0..1000.0)+                        ..real_position.x.value + random.random_range(0.0..1000.0),+                    real_position.y.value - random.random_range(0.0..1000.0)+                        ..real_position.y.value + random.random_range(0.0..1000.0),+                    real_position.z.value - random.random_range(0.0..1000.0)+                        ..real_position.z.value + random.random_range(0.0..1000.0),                     real_position,                     &mut random,                 );@@ -296,21 +296,21 @@ mod tests {             let mut random = SmallRng::seed_from_u64(s);              let real_position = Position {-                x: Coordinate::new_real(random.gen_range(0.0..10000.0), 0.0),-                y: Coordinate::new_real(random.gen_range(0.0..10000.0), 0.0),-                z: Coordinate::new_real(random.gen_range(0.0..10000.0), 0.0),+                x: Coordinate::new_real(random.random_range(0.0..10000.0), 0.0),+                y: Coordinate::new_real(random.random_range(0.0..10000.0), 0.0),+                z: Coordinate::new_real(random.random_range(0.0..10000.0), 0.0),             };              let mut measurements = vec![];              for i in 0..9 {                 let mut measurement = generate_random_measurement(-                    real_position.x.value - random.gen_range(0.0..1000.0)-                        ..real_position.x.value + random.gen_range(0.0..1000.0),-                    real_position.y.value - random.gen_range(0.0..1000.0)-                        ..real_position.y.value + random.gen_range(0.0..1000.0),-                    real_position.z.value - random.gen_range(0.0..1000.0)-                        ..real_position.z.value + random.gen_range(0.0..1000.0),+                    real_position.x.value - random.random_range(0.0..1000.0)+                        ..real_position.x.value + random.random_range(0.0..1000.0),+                    real_position.y.value - random.random_range(0.0..1000.0)+                        ..real_position.y.value + random.random_range(0.0..1000.0),+                    real_position.z.value - random.random_range(0.0..1000.0)+                        ..real_position.z.value + random.random_range(0.0..1000.0),                     real_position,                     &mut random,                 );
networklocation/src/main/rust/src/wpsdb.rs
diff --git a/networklocation/src/main/rust/src/wpsdb.rs b/networklocation/src/main/rust/src/wpsdb.rsindex e4088e2324..7880a53cd0 100644--- a/networklocation/src/main/rust/src/wpsdb.rs+++ b/networklocation/src/main/rust/src/wpsdb.rs@@ -19,9 +19,15 @@ //! 40 high[high_len] //!    zeros_len:u64,   zeros[zeros_len]      (u64 each: zeros before bit b << sample_log2) //!    low_len:u64,     low[low_len]          (n * l bits, bit-packed)-//!    payload_len:u64, payload[payload_len]  (n * 87 bits, bit-packed)+//!    payload_len:u64, payload[payload_len]  (n * record_bits bits, bit-packed) //! ``` //!+//! Two payload kinds exist. Kind 1 is 87 bits: lat(35) | lon(36) | accuracy(16). Kind 2+//! appends altitude(16) — metres biased by 32768, 0 meaning "unknown" — for 103 bits. Both+//! are read; the builder writes kind 2. WiFi records carry altitude (Apple's `location.5`);+//! cell records do not (the cell response has no altitude field), so their slot reads as+//! unknown.+//! //! Membership and index come from the Elias–Fano upper bitvector (`high`). At world scale //! that vector is hundreds of MB, far too much to hold in an always-bound system service, so //! it is **mmap'd** rather than read: random `select0` probes hit the page cache and the@@ -54,11 +60,15 @@ const MAGIC: &[u8; 8] = b"WPSDB2\x00\x00"; const HIGH_OFF: u64 = 40;  // --------------------------------------------------------------------------- payload codec-// One record is 87 bits, LSB-first: lat(35) | lon(36) | accuracy(16).+// Kind-1 record is 87 bits, LSB-first: lat(35) | lon(36) | accuracy(16).+// Kind-2 appends altitude(16): metres biased by 32768, 0 meaning "unknown", for 103 bits. const LAT_BITS: u32 = 35; const LON_BITS: u32 = 36; const ACC_BITS: u32 = 16;-const RECORD_BITS: u32 = LAT_BITS + LON_BITS + ACC_BITS;+const ALT_BITS: u32 = 16;++/// Added to a metres altitude to make room for the "unknown" zero in a `u16` slot.+const ALT_BIAS: i64 = 32768;  /// Bias that maps `lat * 1e8` from [-90, 90] onto [0, 180e8], which fits 35 bits. const LAT_BIAS: i64 = 90_00_000_000;@@ -73,6 +83,12 @@ const ACC_UNKNOWN: u64 = 0xFFFF; const ACC_UNKNOWN_OUT: f64 = -1.0;  const PAYLOAD_LATLON_E8_ACC16: u8 = 1;+const PAYLOAD_LATLON_E8_ACC16_ALT16: u8 = 2;++/// What `lookup` reports when the store holds no altitude for the beacon (kind-1 stores, and+/// kind-2 records whose altitude slot is the unknown sentinel). NaN cannot be mistaken for a+/// real altitude, and `Double.isNaN` is the natural Kotlin test.+const ALT_UNKNOWN_OUT: f64 = f64::NAN;  /// `l` is the Elias–Fano low-part width. Capped so a low value always fits a `u64`, which is /// what the bit reader returns. The builder applies the same cap; exceeding it only ever@@ -133,6 +149,8 @@ pub struct Reader {     /// `zero_samples[b]` = number of zero bits in `high[0 .. b << sample_log2)`.     zero_samples: Vec<u64>,     sample_log2: u8,+    /// Payload record width in bits: 87 for kind 1, 103 for kind 2 (with altitude).+    record_bits: u32,     low_off: u64,     payload_off: u64, }@@ -171,7 +189,12 @@ impl Reader {         let sample_log2 = src.rd_u8(12)?;          // Reject anything this build cannot decode rather than silently mis-reading it.-        if payload_kind != PAYLOAD_LATLON_E8_ACC16 || l > MAX_L {+        let record_bits = match payload_kind {+            PAYLOAD_LATLON_E8_ACC16 => LAT_BITS + LON_BITS + ACC_BITS,+            PAYLOAD_LATLON_E8_ACC16_ALT16 => LAT_BITS + LON_BITS + ACC_BITS + ALT_BITS,+            _ => return None,+        };+        if l > MAX_L {             return None;         }         // `index` shifts a key right by `l` into a u64 bucket number.@@ -219,7 +242,7 @@ impl Reader {         let payload_len_off = low_off + low_len;         let payload_len = src.rd_u64(payload_len_off)?;         let payload_off = payload_len_off + 8;-        if payload_len < (n * RECORD_BITS as u64).div_ceil(8) {+        if payload_len < (n * record_bits as u64).div_ceil(8) {             return None;         } @@ -243,6 +266,7 @@ impl Reader {             high,             zero_samples,             sample_log2,+            record_bits,             low_off,             payload_off,         })@@ -304,23 +328,29 @@ impl Reader {         self.read_bits(self.low_off, i * self.l as u64, self.l as u32)     } -    /// Decode record `i`. One positional read covers the whole 87-bit record, so a lookup+    /// Decode record `i`. One positional read covers the whole record, so a lookup     /// costs a single `pread` here rather than one per field.-    fn record(&self, i: u64) -> Option<(f64, f64, f64)> {-        let bit_index = i * RECORD_BITS as u64;+    fn record(&self, i: u64) -> Option<(f64, f64, f64, f64)> {+        let bit_index = i * self.record_bits as u64;         let first_bit = (bit_index & 7) as u32;         let byte_pos = self.payload_off + (bit_index >> 3);-        let nbytes = ((first_bit + RECORD_BITS).div_ceil(8)) as usize;+        let nbytes = ((first_bit + self.record_bits).div_ceil(8)) as usize;         let buf = self.src.read(byte_pos, nbytes)?;          let lat_u = extract_bits(&buf, first_bit, LAT_BITS);         let lon_u = extract_bits(&buf, first_bit + LAT_BITS, LON_BITS);         let acc_u = extract_bits(&buf, first_bit + LAT_BITS + LON_BITS, ACC_BITS);+        let alt = if self.record_bits == LAT_BITS + LON_BITS + ACC_BITS + ALT_BITS {+            let alt_u = extract_bits(&buf, first_bit + LAT_BITS + LON_BITS + ACC_BITS, ALT_BITS);+            if alt_u == 0 { ALT_UNKNOWN_OUT } else { (alt_u as i64 - ALT_BIAS) as f64 }+        } else {+            ALT_UNKNOWN_OUT+        };          let lat = (lat_u as i64 - LAT_BIAS) as f64 / COORD_SCALE;         let lon = (lon_u as i64 - LON_BIAS) as f64 / COORD_SCALE;         let acc = if acc_u == ACC_UNKNOWN { ACC_UNKNOWN_OUT } else { acc_u as f64 };-        Some((lat, lon, acc))+        Some((lat, lon, acc, alt))     }      /// Elias–Fano index of `key`, or `None` if `key` is not in the set.@@ -360,9 +390,10 @@ impl Reader {         None     } -    /// Look up `key`; returns `(lat, lon, accuracy_m)` or `None` for an unknown key.-    /// A negative accuracy means the source did not report one.-    pub fn lookup(&self, key: u128) -> Option<(f64, f64, f64)> {+    /// Look up `key`; returns `(lat, lon, accuracy_m, altitude_m)` or `None` for an unknown+    /// key. A negative accuracy means the source did not report one; a NaN altitude means the+    /// store holds none for that beacon (all kind-1 stores, and cell records generally).+    pub fn lookup(&self, key: u128) -> Option<(f64, f64, f64, f64)> {         let i = self.index(key)?;         self.record(i)     }
networklocation/src/main/rust/src/wpsdb_part1.rs
diff --git a/networklocation/src/main/rust/src/wpsdb_part1.rs b/networklocation/src/main/rust/src/wpsdb_part1.rsindex 1faf5a5887..66d974cf41 100644--- a/networklocation/src/main/rust/src/wpsdb_part1.rs+++ b/networklocation/src/main/rust/src/wpsdb_part1.rs@@ -1,6 +1,7 @@-/// `lookup(handle, keyHi, keyLo) -> double[3]` (`[lat, lon, accuracyMeters]`), or null for an-/// unknown key. The key is 128 bits split across two longs: a 48-bit WiFi MAC leaves `keyHi`-/// zero, an 84-bit cell key does not. A negative accuracy means the store had none.+/// `lookup(handle, keyHi, keyLo) -> double[4]` (`[lat, lon, accuracyMeters, altitudeMeters]`),+/// or null for an unknown key. The key is 128 bits split across two longs: a 48-bit WiFi MAC+/// leaves `keyHi` zero, an 84-bit cell key does not. A negative accuracy means the store had+/// none; a NaN altitude means the same (all kind-1 stores, and cell records generally). #[no_mangle] pub extern "system" fn Java_com_vayunmathur_networklocation_WpsStoreNative_lookup<'l>(     mut env: EnvUnowned<'l>,@@ -16,12 +17,12 @@ pub extern "system" fn Java_com_vayunmathur_networklocation_WpsStoreNative_looku         let reader = unsafe { &*(handle as *const Handle) };         let key = ((key_hi as u64 as u128) << 64) | (key_lo as u64 as u128);         match reader.lookup(key) {-            Some((lat, lon, acc)) => {-                let arr = match env.new_double_array(3) {+            Some((lat, lon, acc, alt)) => {+                let arr = match env.new_double_array(4) {                     Ok(a) => a,                     Err(_) => return Ok(std::ptr::null_mut()),                 };-                if arr.set_region(env, 0, &[lat, lon, acc]).is_err() {+                if arr.set_region(env, 0, &[lat, lon, acc, alt]).is_err() {                     return Ok(std::ptr::null_mut());                 }                 Ok(arr.into_raw())
networklocation/src/main/rust/src/wpsdb_part2.rs
diff --git a/networklocation/src/main/rust/src/wpsdb_part2.rs b/networklocation/src/main/rust/src/wpsdb_part2.rsindex 470e3c26f2..d92f2ae406 100644--- a/networklocation/src/main/rust/src/wpsdb_part2.rs+++ b/networklocation/src/main/rust/src/wpsdb_part2.rs@@ -48,11 +48,14 @@ mod tests {         l     } -    /// Write a valid `WPSDB2` to `path`. `records` need not be sorted or unique.+    /// Write a valid `WPSDB2` to `path`. `records` need not be sorted or unique. The altitude+    /// slot is written only for kind 2: `Some(metres)` lands in the record, `None` writes the+    /// unknown sentinel.     fn write_fixture(         path: &std::path::Path,         universe_bits: u8,-        records: &[(u128, i64, i64, u64)],+        payload_kind: u8,+        records: &[(u128, i64, i64, u64, Option<i64>)],         sample_log2: u8,     ) {         let mut recs = records.to_vec();@@ -99,17 +102,20 @@ mod tests {         }          let mut payload = BitWriter::new();-        for &(_, lat_e8, lon_e8, acc) in &recs {+        for &(_, lat_e8, lon_e8, acc, alt) in &recs {             payload.push((lat_e8 + LAT_BIAS) as u64, LAT_BITS);             payload.push((lon_e8 + LON_BIAS) as u64, LON_BITS);             payload.push(acc, ACC_BITS);+            if payload_kind == PAYLOAD_LATLON_E8_ACC16_ALT16 {+                payload.push((alt.unwrap_or(-ALT_BIAS) + ALT_BIAS) as u64, ALT_BITS);+            }         }          let mut out: Vec<u8> = Vec::new();         out.extend_from_slice(MAGIC);         out.push(1); // key_kind         out.push(universe_bits);-        out.push(PAYLOAD_LATLON_E8_ACC16);+        out.push(payload_kind);         out.push(l);         out.push(sample_log2);         out.extend_from_slice(&[0, 0, 0]);@@ -175,7 +181,7 @@ mod tests {         *state     } -    fn wifi_records(count: usize) -> Vec<(u128, i64, i64, u64)> {+    fn wifi_records(count: usize) -> Vec<(u128, i64, i64, u64, Option<i64>)> {         let mut state = 0x1234_5678_9abc_def0u64;         (0..count)             .map(|i| {@@ -183,7 +189,8 @@ mod tests {                 let lat = (lcg(&mut state) % 18_000_000_000) as i64 - LAT_BIAS;                 let lon = (lcg(&mut state) % 36_000_000_000) as i64 - LON_BIAS;                 let acc = if i % 17 == 0 { ACC_UNKNOWN } else { (i % 500) as u64 };-                (key, lat, lon, acc)+                let alt = if i % 13 == 0 { None } else { Some((i % 9000) as i64 - 500) };+                (key, lat, lon, acc, alt)             })             .collect()     }@@ -194,7 +201,7 @@ mod tests {     fn header_is_parsed() {         let f = Fixture::new("header");         let recs = wifi_records(500);-        write_fixture(&f.path(), 48, &recs, 12);+        write_fixture(&f.path(), 48, PAYLOAD_LATLON_E8_ACC16_ALT16, &recs, 12);         let r = Reader::open_path(f.path()).expect("fixture must open");         assert_eq!(r.universe_bits, 48);         assert!(r.n > 0 && r.n <= 500);@@ -202,22 +209,22 @@ mod tests {         assert!(r.l <= MAX_L);     } -    /// Every key round-trips through `index()`, and `lookup` decodes exactly the coordinate-    /// and accuracy the builder wrote — including the "no accuracy" sentinel.+    /// Every key round-trips through `index()`, and `lookup` decodes exactly the coordinate,+    /// accuracy and altitude the builder wrote — including both "unknown" sentinels.     #[test]     fn known_keys_resolve_exactly() {         let f = Fixture::new("known");         let mut recs = wifi_records(2000);         recs.sort_by_key(|r| r.0);         recs.dedup_by_key(|r| r.0);-        write_fixture(&f.path(), 48, &recs, 12);+        write_fixture(&f.path(), 48, PAYLOAD_LATLON_E8_ACC16_ALT16, &recs, 12);         let r = Reader::open_path(f.path()).unwrap();          assert_eq!(reconstruct(&r), recs.iter().map(|x| x.0).collect::<Vec<_>>()); -        for (i, &(key, lat_e8, lon_e8, acc)) in recs.iter().enumerate() {+        for (i, &(key, lat_e8, lon_e8, acc, alt)) in recs.iter().enumerate() {             assert_eq!(r.index(key), Some(i as u64), "index mismatch for {key:#x}");-            let (lat, lon, got_acc) = r.lookup(key).expect("known key resolves");+            let (lat, lon, got_acc, got_alt) = r.lookup(key).expect("known key resolves");             // e8 is exact in f64 (well under 2^53), so this is an equality check, not epsilon.             assert_eq!(lat, lat_e8 as f64 / COORD_SCALE, "lat mismatch for {key:#x}");             assert_eq!(lon, lon_e8 as f64 / COORD_SCALE, "lon mismatch for {key:#x}");@@ -226,17 +233,39 @@ mod tests {             } else {                 assert_eq!(got_acc, acc as f64, "accuracy mismatch for {key:#x}");             }+            match alt {+                Some(m) => assert_eq!(got_alt, m as f64, "altitude mismatch for {key:#x}"),+                None => assert!(got_alt.is_nan(), "unknown altitude must be NaN for {key:#x}"),+            }             assert!((-90.0..=90.0).contains(&lat));             assert!((-180.0..=180.0).contains(&lon));         }     } +    /// Kind-1 stores (no altitude slot) stay readable; their altitude reports as NaN.+    #[test]+    fn kind1_stores_read_with_nan_altitude() {+        let f = Fixture::new("kind1");+        let recs = wifi_records(500);+        write_fixture(&f.path(), 48, PAYLOAD_LATLON_E8_ACC16, &recs, 12);+        let r = Reader::open_path(f.path()).unwrap();+        for &(key, lat_e8, lon_e8, acc, _) in &recs {+            let (lat, lon, got_acc, got_alt) = r.lookup(key).expect("known key resolves");+            assert_eq!(lat, lat_e8 as f64 / COORD_SCALE);+            assert_eq!(lon, lon_e8 as f64 / COORD_SCALE);+            if acc != ACC_UNKNOWN {+                    assert_eq!(got_acc, acc as f64);+            }+            assert!(got_alt.is_nan(), "kind 1 has no altitude slot");+        }+    }+     /// Random unknown keys are all rejected — zero false positives.     #[test]     fn unknown_keys_rejected() {         let f = Fixture::new("unknown");         let recs = wifi_records(2000);-        write_fixture(&f.path(), 48, &recs, 12);+        write_fixture(&f.path(), 48, PAYLOAD_LATLON_E8_ACC16_ALT16, &recs, 12);         let r = Reader::open_path(f.path()).unwrap();          let known: HashMap<u128, ()> = reconstruct(&r).into_iter().map(|k| (k, ())).collect();@@ -257,43 +286,44 @@ mod tests {     fn cell_scale_keys_resolve() {         let f = Fixture::new("cell");         let mut state = 0x0f0f_0f0f_0f0f_0f0fu64;-        let mut recs: Vec<(u128, i64, i64, u64)> = (0..1000)+        let mut recs: Vec<(u128, i64, i64, u64, Option<i64>)> = (0..1000)             .map(|_| {                 let hi = (lcg(&mut state) & ((1u64 << 20) - 1)) as u128;                 let key = (hi << 64) | lcg(&mut state) as u128;-                (key, 37_77_000_000i64, -122_41_000_000i64, 250)+                (key, 37_77_000_000i64, -122_41_000_000i64, 250, None)             })             .collect();         recs.sort_by_key(|r| r.0);         recs.dedup_by_key(|r| r.0);-        write_fixture(&f.path(), 84, &recs, 12);+        write_fixture(&f.path(), 84, PAYLOAD_LATLON_E8_ACC16_ALT16, &recs, 12);          let r = Reader::open_path(f.path()).unwrap();         assert_eq!(r.l, MAX_L, "an 84-bit universe at this n must hit the l cap");         for (i, &(key, ..)) in recs.iter().enumerate() {             assert_eq!(r.index(key), Some(i as u64), "cell key {key:#x} rejected");         }-        let (lat, lon, acc) = r.lookup(recs[0].0).unwrap();+        let (lat, lon, acc, alt) = r.lookup(recs[0].0).unwrap();         assert_eq!((lat, lon, acc), (37.77, -122.41, 250.0));+        assert!(alt.is_nan(), "cell records carry no altitude");     }      /// Extremes must survive the bias, and a store whose payload straddles byte boundaries-    /// (87 bits is coprime with 8) must decode every record, not just aligned ones.+    /// (87 and 103 bits are both coprime with 8) must decode every record, not just aligned ones.     #[test]     fn coordinate_extremes_and_bit_alignment() {         let f = Fixture::new("extremes");-        let recs: Vec<(u128, i64, i64, u64)> = vec![-            (1, -LAT_BIAS, -LON_BIAS, 0),-            (2, LAT_BIAS, LON_BIAS, 65534),-            (3, 0, 0, ACC_UNKNOWN),-            (4, 1, -1, 1),-            (5, -LAT_BIAS + 1, LON_BIAS - 1, 12345),-            (6, 45_00_000_001, -93_26_543_210, 7),+        let recs: Vec<(u128, i64, i64, u64, Option<i64>)> = vec![+            (1, -LAT_BIAS, -LON_BIAS, 0, Some(-ALT_BIAS + 1)),+            (2, LAT_BIAS, LON_BIAS, 65534, Some(ALT_BIAS - 1)),+            (3, 0, 0, ACC_UNKNOWN, None),+            (4, 1, -1, 1, Some(0)),+            (5, -LAT_BIAS + 1, LON_BIAS - 1, 12345, Some(-430)),+            (6, 45_00_000_001, -93_26_543_210, 7, Some(8848)),         ];-        write_fixture(&f.path(), 48, &recs, 6);+        write_fixture(&f.path(), 48, PAYLOAD_LATLON_E8_ACC16_ALT16, &recs, 6);         let r = Reader::open_path(f.path()).unwrap();-        for &(key, lat_e8, lon_e8, acc) in &recs {-            let (lat, lon, got) = r.lookup(key).expect("key resolves");+        for &(key, lat_e8, lon_e8, acc, alt) in &recs {+            let (lat, lon, got, got_alt) = r.lookup(key).expect("key resolves");             assert_eq!(lat, lat_e8 as f64 / COORD_SCALE);             assert_eq!(lon, lon_e8 as f64 / COORD_SCALE);             if acc == ACC_UNKNOWN {@@ -301,6 +331,10 @@ mod tests {             } else {                 assert_eq!(got, acc as f64);             }+            match alt {+                Some(m) => assert_eq!(got_alt, m as f64, "altitude mismatch for key {key}"),+                None => assert!(got_alt.is_nan()),+            }         }         assert_eq!(r.lookup(1).unwrap().0, -90.0);         assert_eq!(r.lookup(2).unwrap().1, 180.0);@@ -360,10 +394,11 @@ mod tests {                         Some(idx),                         "known key {key:#x} did not resolve to its own index"                     );-                    let (lat, lon, acc) = r.lookup(key).expect("known key resolves");+                    let (lat, lon, acc, alt) = r.lookup(key).expect("known key resolves");                     assert!((-90.0..=90.0).contains(&lat), "lat out of range: {lat}");                     assert!((-180.0..=180.0).contains(&lon), "lon out of range: {lon}");                     assert!(acc < 0.0 || (0.0..=65534.0).contains(&acc), "implausible acc: {acc}");+                    assert!(alt.is_nan() || (-32767.0..=32767.0).contains(&alt), "implausible alt: {alt}");                     checked += 1;                 }                 idx += 1;@@ -395,7 +430,7 @@ mod tests {     fn truncated_store_is_rejected() {         let f = Fixture::new("trunc");         let recs = wifi_records(300);-        write_fixture(&f.path(), 48, &recs, 12);+        write_fixture(&f.path(), 48, PAYLOAD_LATLON_E8_ACC16_ALT16, &recs, 12);         let full = std::fs::read(f.path()).unwrap();         for cut in [8usize, 24, 40, full.len() / 2, full.len() - 1] {             std::fs::write(f.path(), &full[..cut]).unwrap();
scripts/networklocation/wps_harvest/README.md
diff --git a/scripts/networklocation/wps_harvest/README.md b/scripts/networklocation/wps_harvest/README.mdindex a55ea71d9e..d27c9168cd 100644--- a/scripts/networklocation/wps_harvest/README.md+++ b/scripts/networklocation/wps_harvest/README.md@@ -31,7 +31,12 @@ The store this writes keeps, per beacon: - **coordinates as integer degrees x 1e8** — bit-exact against what the source reported, since   gs-loc returns e8 integers and the CSV dumps are parsed as exact decimals rather than through   `f64`;-- **its own horizontal accuracy**, in metres.+- **its own horizontal accuracy**, in metres;+- **its altitude**, in metres, when the source reports one. Apple's WiFi fixes carry it+  (`location.5`; essentially always present, -1 when not). Cell responses have no altitude+  field at all (verified on the wire: cell locations carry only fields 1–4, 11, 12), so cell+  records always read as unknown. The payload is kind 2: lat(35) | lon(36) | acc(16) | alt(16)+  = 103 bits; kind-1 stores (87 bits, no altitude) stay readable and report NaN altitude.  The format it replaces quantized to a **20 m grid** and stored **no accuracy at all**, so the device substituted one constant for every beacon. That mattered more than it sounds: the
scripts/networklocation/wps_harvest/src/bin/wps_cellcrawl.rs
diff --git a/scripts/networklocation/wps_harvest/src/bin/wps_cellcrawl.rs b/scripts/networklocation/wps_harvest/src/bin/wps_cellcrawl.rsindex 37276d5a54..78aaddd107 100644--- a/scripts/networklocation/wps_harvest/src/bin/wps_cellcrawl.rs+++ b/scripts/networklocation/wps_harvest/src/bin/wps_cellcrawl.rs@@ -16,7 +16,7 @@ use std::time::Duration;  use wps_harvest::gsloc::{CellFix, Client}; use wps_harvest::keys::{self, CellId, RadioType};-use wps_harvest::record::{Record, RecordWriter, Source, ACC_UNKNOWN};+use wps_harvest::record::{ALT_UNKNOWN, Record, RecordWriter, Source, ACC_UNKNOWN};  const USAGE: &str = "\ Usage: wps_cellcrawl --out SHARD --seed MCC,MNC,TAC,CID [--seed ...] [options]@@ -108,7 +108,7 @@ fn to_record(f: &CellFix) -> Option<Record> {     } else {         f.accuracy_m.min(i32::from(ACC_UNKNOWN - 1)) as u16     };-    let r = Record { key: keys::cell_key(&id), lat_e8: f.lat_e8, lon_e8: f.lon_e8, accuracy_m, source: Source::Gsloc };+    let r = Record { key: keys::cell_key(&id), lat_e8: f.lat_e8, lon_e8: f.lon_e8, accuracy_m, altitude_m: ALT_UNKNOWN, source: Source::Gsloc };     r.in_range().then_some(r) } 
scripts/networklocation/wps_harvest/src/bin/wps_crawl.rs
diff --git a/scripts/networklocation/wps_harvest/src/bin/wps_crawl.rs b/scripts/networklocation/wps_harvest/src/bin/wps_crawl.rsindex 233e112365..f807821c96 100644--- a/scripts/networklocation/wps_harvest/src/bin/wps_crawl.rs+++ b/scripts/networklocation/wps_harvest/src/bin/wps_crawl.rs@@ -179,6 +179,7 @@ fn to_record(fix: &gsloc::WifiFix) -> Option<Record> {         lat_e8: fix.lat_e8,         lon_e8: fix.lon_e8,         accuracy_m: clamp_accuracy(fix.accuracy_m),+        altitude_m: fix.altitude_m,         source: Source::Gsloc,     };     r.in_range().then_some(r)@@ -421,8 +422,10 @@ mod tests {             lat_e8: 37_77493000,             lon_e8: -122_41942000,             accuracy_m: 35,+            altitude_m: 44,         };         assert_eq!(to_record(&good).unwrap().accuracy_m, 35);+        assert_eq!(to_record(&good).unwrap().altitude_m, 44);          let randomized = gsloc::WifiFix { bssid: "aa:bb:cc:dd:ee:ff".to_string(), ..good.clone() };         assert_eq!(to_record(&randomized), None);@@ -441,6 +444,7 @@ mod tests {             lat_e8: 0,             lon_e8: 0,             accuracy_m: 10_000_000,+            altitude_m: 0,         };         assert_eq!(to_record(&fix).unwrap().accuracy_m, 65534);     }
scripts/networklocation/wps_harvest/src/gsloc.rs
diff --git a/scripts/networklocation/wps_harvest/src/gsloc.rs b/scripts/networklocation/wps_harvest/src/gsloc.rsindex ef493fb924..b1f5e76b5c 100644--- a/scripts/networklocation/wps_harvest/src/gsloc.rs+++ b/scripts/networklocation/wps_harvest/src/gsloc.rs@@ -40,6 +40,21 @@ const F_WIFI_DEVICES: u32 = 2; const F_CELL_RESPONSE: u32 = 22; const F_CELL_REQUEST: u32 = 25; +/// Altitude (Apple's `location.5`) meaning "not reported": Apple sends -1.+pub const ALT_NOT_REPORTED: i64 = -1;++/// Clamp a source-reported altitude into the store's `i16` metres, mapping Apple's -1+/// "not reported" to [`crate::record::ALT_UNKNOWN`]. Saturates rather than wrapping: nothing+/// real sits outside ±32 km, so saturation can only trigger on garbage, which then reads as+/// extreme rather than plausible.+pub fn clamp_altitude(metres: i64) -> i16 {+    if metres == ALT_NOT_REPORTED {+        i16::MIN+    } else {+        metres.clamp(i16::MIN as i64 + 1, i16::MAX as i64) as i16+    }+}+ /// A beacon Apple knows the location of. #[derive(Debug, Clone, PartialEq, Eq)] pub struct WifiFix {@@ -51,6 +66,9 @@ pub struct WifiFix {     pub lon_e8: i64,     /// Horizontal accuracy in metres.     pub accuracy_m: i32,+    /// Altitude in metres, or [`crate::record::ALT_UNKNOWN`]. Present on essentially every+    /// WiFi fix (Apple's `location.5`); cell responses have no altitude field at all.+    pub altitude_m: i16, }  /// A cell tower Apple knows the location of.@@ -224,10 +242,15 @@ pub fn frame(payload: &[u8]) -> Vec<u8> {  /// A location submessage. `None` when the beacon is unknown, which Apple signals by returning /// -180 degrees in both axes rather than by omitting the field.-fn parse_location(body: &[u8]) -> Option<(i64, i64, i32)> {+///+/// Returns `(lat, lon, accuracy_m, altitude_m)`. Only WiFi carries fields 5/6 (altitude and+/// vertical accuracy); cell locations top out at field 4, so their altitude reads as+/// "not reported" without any special-casing.+fn parse_location(body: &[u8]) -> Option<(i64, i64, i32, i16)> {     let mut lat = None;     let mut lon = None;     let mut acc: i64 = -1;+    let mut alt: i64 = ALT_NOT_REPORTED;     let mut r = proto::Reader::new(body);     while let Some((field, v)) = r.next() {         if let Field::Varint(raw) = v {@@ -235,6 +258,7 @@ fn parse_location(body: &[u8]) -> Option<(i64, i64, i32)> {                 1 => lat = Some(raw as i64),                 2 => lon = Some(raw as i64),                 3 => acc = raw as i64,+                5 => alt = raw as i64,                 _ => {}             }         }@@ -246,7 +270,7 @@ fn parse_location(body: &[u8]) -> Option<(i64, i64, i32)> {     // Accuracy is int64 on the wire but only ever a plausible radius in metres; clamp rather     // than truncate so a hostile or garbled value cannot wrap into something small and     // confident-looking.-    Some((lat, lon, acc.clamp(-1, i32::MAX as i64) as i32))+    Some((lat, lon, acc.clamp(-1, i32::MAX as i64) as i32, clamp_altitude(alt))) }  fn parse_wifi(body: &[u8]) -> Vec<WifiFix> {@@ -267,8 +291,8 @@ fn parse_wifi(body: &[u8]) -> Vec<WifiFix> {                 _ => {}             }         }-        if let (Some(bssid), Some((lat_e8, lon_e8, accuracy_m))) = (bssid, loc) {-            out.push(WifiFix { bssid: bssid.to_ascii_lowercase(), lat_e8, lon_e8, accuracy_m });+        if let (Some(bssid), Some((lat_e8, lon_e8, accuracy_m, altitude_m))) = (bssid, loc) {+            out.push(WifiFix { bssid: bssid.to_ascii_lowercase(), lat_e8, lon_e8, accuracy_m, altitude_m });         }     }     out@@ -295,7 +319,7 @@ fn parse_cells(body: &[u8]) -> Vec<CellFix> {                 _ => {}             }         }-        if let (Some(mcc), Some(mnc), Some(cell_id), Some(area), Some((lat_e8, lon_e8, acc))) =+        if let (Some(mcc), Some(mnc), Some(cell_id), Some(area), Some((lat_e8, lon_e8, acc, _))) =             (mcc, mnc, cell_id, area, loc)         {             out.push(CellFix { mcc, mnc, cell_id, area, lat_e8, lon_e8, accuracy_m: acc });@@ -347,16 +371,17 @@ mod tests {     }      /// Build the response body the parser expects: `AppleWLoc { wifi_devices }`.-    fn wifi_response(entries: &[(&str, Option<(i64, i64, i64)>)]) -> Vec<u8> {+    fn wifi_response(entries: &[(&str, Option<(i64, i64, i64, i64)>)]) -> Vec<u8> {         let mut body = Vec::new();         for (bssid, loc) in entries {             let mut dev = Vec::new();             proto::put_bytes(&mut dev, 1, bssid.as_bytes());-            if let Some((lat, lon, acc)) = loc {+            if let Some((lat, lon, acc, alt)) = loc {                 let mut l = Vec::new();                 proto::put_int(&mut l, 1, *lat);                 proto::put_int(&mut l, 2, *lon);                 proto::put_int(&mut l, 3, *acc);+                proto::put_int(&mut l, 5, *alt);                 proto::put_bytes(&mut dev, 2, &l);             }             proto::put_bytes(&mut body, F_WIFI_DEVICES, &dev);@@ -367,24 +392,40 @@ mod tests {     #[test]     fn wifi_responses_decode_and_normalize_case() {         let body = wifi_response(&[-            ("AA:BB:CC:DD:EE:01", Some((37_77493000, -122_41942000, 35))),-            ("aa:bb:cc:dd:ee:02", Some((51_50735000, -0_12776000, 120))),+            ("AA:BB:CC:DD:EE:01", Some((37_77493000, -122_41942000, 35, 12))),+            ("aa:bb:cc:dd:ee:02", Some((51_50735000, -0_12776000, 120, 44))),         ]);         let fixes = parse_wifi(&body);         assert_eq!(fixes.len(), 2);         assert_eq!(fixes[0].bssid, "aa:bb:cc:dd:ee:01");         assert_eq!(fixes[0].lat_e8, 37_77493000);         assert_eq!(fixes[0].accuracy_m, 35);+        assert_eq!(fixes[0].altitude_m, 12);         assert_eq!(fixes[1].lon_e8, -0_12776000);+        assert_eq!(fixes[1].altitude_m, 44);+    }++    #[test]+    fn altitude_decodes_and_its_absence_is_unknown() {+        // Apple's "not reported" is -1; a missing field 5 reads the same way.+        let body = wifi_response(&[+            ("aa:bb:cc:dd:ee:01", Some((37_00000000, -122_00000000, 30, ALT_NOT_REPORTED))),+            ("aa:bb:cc:dd:ee:02", Some((37_00000000, -122_00000000, 30, -430))),+        ]);+        let fixes = parse_wifi(&body);+        assert_eq!(fixes[0].altitude_m, i16::MIN, "-1 means altitude unknown");+        assert_eq!(fixes[1].altitude_m, -430, "below sea level survives (Dead Sea)");+        assert_eq!(clamp_altitude(i64::MAX), i16::MAX);+        assert_eq!(clamp_altitude(i64::MIN + 1), i16::MIN + 1);     }      #[test]     fn beacons_apple_does_not_know_are_dropped() {         let body = wifi_response(&[             // Apple's "not found": -180 degrees in both axes.-            ("aa:bb:cc:dd:ee:01", Some((NOT_FOUND_E8, NOT_FOUND_E8, 500))),+            ("aa:bb:cc:dd:ee:01", Some((NOT_FOUND_E8, NOT_FOUND_E8, 500, 10))),             ("aa:bb:cc:dd:ee:02", None),-            ("aa:bb:cc:dd:ee:03", Some((37_00000000, -122_00000000, 50))),+            ("aa:bb:cc:dd:ee:03", Some((37_00000000, -122_00000000, 50, 10))),         ]);         let fixes = parse_wifi(&body);         assert_eq!(fixes.len(), 1, "only the one real fix survives");@@ -395,7 +436,7 @@ mod tests {     /// it as one, as the old client did, threw away real fixes.     #[test]     fn a_missing_accuracy_does_not_discard_a_real_fix() {-        let body = wifi_response(&[("aa:bb:cc:dd:ee:04", Some((37_00000000, -122_00000000, -1)))]);+        let body = wifi_response(&[("aa:bb:cc:dd:ee:04", Some((37_00000000, -122_00000000, -1, 10)))]);         let fixes = parse_wifi(&body);         assert_eq!(fixes.len(), 1);         assert_eq!(fixes[0].accuracy_m, -1, "reported as unknown, not dropped");@@ -438,8 +479,8 @@ mod tests {     #[test]     fn a_truncated_response_yields_what_decoded_rather_than_failing() {         let body = wifi_response(&[-            ("aa:bb:cc:dd:ee:01", Some((37_00000000, -122_00000000, 30))),-            ("aa:bb:cc:dd:ee:02", Some((38_00000000, -121_00000000, 40))),+            ("aa:bb:cc:dd:ee:01", Some((37_00000000, -122_00000000, 30, 10))),+            ("aa:bb:cc:dd:ee:02", Some((38_00000000, -121_00000000, 40, 10))),         ]);         for cut in 1..body.len() {             let fixes = parse_wifi(&body[..cut]);
scripts/networklocation/wps_harvest/src/lib.rs
diff --git a/scripts/networklocation/wps_harvest/src/lib.rs b/scripts/networklocation/wps_harvest/src/lib.rsindex 68afe27baa..af5a5ae680 100644--- a/scripts/networklocation/wps_harvest/src/lib.rs+++ b/scripts/networklocation/wps_harvest/src/lib.rs@@ -16,10 +16,11 @@ //! ## Where the accuracy comes from //! //! The store this writes keeps each beacon's coordinates as integer degrees x 1e8 — bit-exact-//! against what the source reported — and its own horizontal accuracy. The format it replaces-//! quantized to a 20 m grid and carried no accuracy at all, so the device substituted one-//! constant for every beacon and the solver's uncertainty weighting, which is fully-//! implemented, had nothing to work with.+//! against what the source reported — and its own horizontal accuracy, plus its altitude in+//! metres when the source reports one (Apple's WiFi `location.5`; cell responses have no+//! altitude field). The format it replaces quantized to a 20 m grid and carried no accuracy+//! at all, so the device substituted one constant for every beacon and the solver's+//! uncertainty weighting, which is fully implemented, had nothing to work with.  #![deny(missing_docs)] 
scripts/networklocation/wps_harvest/src/quality.rs
diff --git a/scripts/networklocation/wps_harvest/src/quality.rs b/scripts/networklocation/wps_harvest/src/quality.rsindex 33f1812cf2..2ecb85c1d5 100644--- a/scripts/networklocation/wps_harvest/src/quality.rs+++ b/scripts/networklocation/wps_harvest/src/quality.rs@@ -146,13 +146,13 @@ pub fn clamp_accuracy(meters: i32) -> u16 { #[cfg(test)] mod tests {     use super::*;-    use crate::record::Source;+    use crate::record::{ALT_UNKNOWN, Source};      const SF_LAT: i64 = 37_77493000;     const SF_LON: i64 = -122_41942000;      fn rec(key: u128, lat: i64, lon: i64, acc: u16, source: Source) -> Record {-        Record { key, lat_e8: lat, lon_e8: lon, accuracy_m: acc, source }+        Record { key, lat_e8: lat, lon_e8: lon, accuracy_m: acc, altitude_m: ALT_UNKNOWN, source }     }      fn wifi(lat: i64, lon: i64, acc: u16) -> Record {
scripts/networklocation/wps_harvest/src/record.rs
diff --git a/scripts/networklocation/wps_harvest/src/record.rs b/scripts/networklocation/wps_harvest/src/record.rsindex aad253a863..32e9a746aa 100644--- a/scripts/networklocation/wps_harvest/src/record.rs+++ b/scripts/networklocation/wps_harvest/src/record.rs@@ -7,7 +7,11 @@  use std::io::{self, Read, Write}; -/// Bytes on disk per record: key(16) + lat(8) + lon(8) + accuracy(2) + source(1) + pad(5).+/// Bytes on disk per record: key(16) + lat(8) + lon(8) + accuracy(2) + source(1)+/// + altitude(2) + pad(2) + flags(1).+///+/// The altitude slot and flag byte reuse what was the zero pad, so a shard written before+/// altitude existed still reads cleanly: its flags byte is 0, meaning "altitude unknown". pub const RECORD_BYTES: usize = 40;  /// `lat * 1e8`, the range the store's 35-bit latitude field covers.@@ -22,6 +26,13 @@ pub const LON_E8_MAX: i64 = 180_00_000_000; /// Stored accuracy meaning "the source did not report one". pub const ACC_UNKNOWN: u16 = 0xFFFF; +/// Stored altitude meaning "the source did not report one" (or the shard predates altitude,+/// which reads as flags = 0). Metres are otherwise well inside `i16` (Dead Sea to Everest).+pub const ALT_UNKNOWN: i16 = i16::MIN;++/// Flags byte bit: the altitude slot holds a real measurement.+const FLAG_ALTITUDE_PRESENT: u8 = 1;+ /// Where an observation came from. Kept per record so the merge can prefer a source and so a /// disagreement between sources is attributable rather than anonymous. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]@@ -56,6 +67,9 @@ pub struct Record {     pub lon_e8: i64,     /// Horizontal accuracy in metres, or [`ACC_UNKNOWN`].     pub accuracy_m: u16,+    /// Altitude in metres (Apple's `location.5`), or [`ALT_UNKNOWN`]. Cells and the bulk+    /// CSV dumps have no altitude; WiFi from gs-loc does.+    pub altitude_m: i16,     /// Which dataset or crawl produced it.     pub source: Source, }@@ -77,7 +91,10 @@ impl Record {         out[24..32].copy_from_slice(&self.lon_e8.to_le_bytes());         out[32..34].copy_from_slice(&self.accuracy_m.to_le_bytes());         out[34] = self.source as u8;-        out[35..40].fill(0);+        let has_alt = self.altitude_m != ALT_UNKNOWN;+        out[35..37].copy_from_slice(&self.altitude_m.to_le_bytes());+        out[37..39].fill(0);+        out[39] = if has_alt { FLAG_ALTITUDE_PRESENT } else { 0 };     }      /// Deserialize from exactly [`RECORD_BYTES`], or `None` if the source byte is unknown.@@ -88,11 +105,17 @@ impl Record {         a.copy_from_slice(&buf[16..24]);         let mut b = [0u8; 8];         b.copy_from_slice(&buf[24..32]);+        let altitude_m = if buf[39] & FLAG_ALTITUDE_PRESENT != 0 {+            i16::from_le_bytes([buf[35], buf[36]])+        } else {+            ALT_UNKNOWN+        };         Some(Record {             key: u128::from_le_bytes(k),             lat_e8: i64::from_le_bytes(a),             lon_e8: i64::from_le_bytes(b),             accuracy_m: u16::from_le_bytes([buf[32], buf[33]]),+            altitude_m,             source: Source::from_wire(buf[34])?,         })     }@@ -189,6 +212,7 @@ mod tests {             lat_e8: 37_77_493_000,             lon_e8: -122_41_942_000,             accuracy_m: 35,+            altitude_m: 12,             source: Source::Gsloc,         }     }@@ -215,6 +239,26 @@ mod tests {         }     } +    #[test]+    fn altitude_round_trips_and_absence_is_distinct_from_zero() {+        for alt in [ALT_UNKNOWN, -430, 0, 55, 8848] {+            let r = Record { altitude_m: alt, ..sample() };+            let mut buf = [0u8; RECORD_BYTES];+            r.write_into(&mut buf);+            assert_eq!(Record::read_from(&buf).unwrap().altitude_m, alt, "altitude {alt}");+        }+    }++    #[test]+    fn a_pre_altitude_shard_reads_as_altitude_unknown() {+        // Old layout: everything past `source` was zero pad.+        let r = Record { altitude_m: 250, ..sample() };+        let mut buf = [0u8; RECORD_BYTES];+        r.write_into(&mut buf);+        buf[35..40].fill(0);+        assert_eq!(Record::read_from(&buf).unwrap().altitude_m, ALT_UNKNOWN);+    }+     #[test]     fn out_of_range_coordinates_are_detected() {         assert!(sample().in_range());
scripts/networklocation/wps_harvest/src/seed.rs
diff --git a/scripts/networklocation/wps_harvest/src/seed.rs b/scripts/networklocation/wps_harvest/src/seed.rsindex 15c69d908e..70fb275ce6 100644--- a/scripts/networklocation/wps_harvest/src/seed.rs+++ b/scripts/networklocation/wps_harvest/src/seed.rs@@ -23,7 +23,7 @@ use std::io::{self, BufRead};  use crate::keys::{self, CellId, RadioType}; use crate::quality::clamp_accuracy;-use crate::record::{Record, Source, ACC_UNKNOWN};+use crate::record::{ALT_UNKNOWN, Record, Source, ACC_UNKNOWN};  /// Column aliases accepted for each field, lowercased. const MAC_NAMES: &[&str] = &["bssid", "mac", "macaddress", "mac_address"];@@ -154,7 +154,7 @@ impl Schema {             }         }; -        let record = Record { key, lat_e8, lon_e8, accuracy_m, source };+        let record = Record { key, lat_e8, lon_e8, accuracy_m, altitude_m: ALT_UNKNOWN, source };         Ok(record.in_range().then_some(record))     } }
scripts/networklocation/wps_harvest/src/sort.rs
diff --git a/scripts/networklocation/wps_harvest/src/sort.rs b/scripts/networklocation/wps_harvest/src/sort.rsindex 141215b17a..50460efe95 100644--- a/scripts/networklocation/wps_harvest/src/sort.rs+++ b/scripts/networklocation/wps_harvest/src/sort.rs@@ -177,7 +177,7 @@ impl Drop for Merge { #[cfg(test)] mod tests {     use super::*;-    use crate::record::Source;+    use crate::record::{ALT_UNKNOWN, Source};      struct TempDir(PathBuf);     impl TempDir {@@ -200,6 +200,7 @@ mod tests {             lat_e8: 37_00000000,             lon_e8: -122_00000000,             accuracy_m: acc,+            altitude_m: ALT_UNKNOWN,             source: Source::Gsloc,         }     }
scripts/networklocation/wps_harvest/src/store.rs
diff --git a/scripts/networklocation/wps_harvest/src/store.rs b/scripts/networklocation/wps_harvest/src/store.rsindex 1f3c6a50e2..6756e4bae1 100644--- a/scripts/networklocation/wps_harvest/src/store.rs+++ b/scripts/networklocation/wps_harvest/src/store.rs@@ -26,15 +26,19 @@ use std::fs::File; use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use crate::record::{Record, LAT_E8_MIN, LON_E8_MIN};+use crate::record::{ALT_UNKNOWN, Record, LAT_E8_MIN, LON_E8_MIN};  const MAGIC: &[u8; 8] = b"WPSDB2\x00\x00";  const LAT_BITS: u32 = 35; const LON_BITS: u32 = 36; const ACC_BITS: u32 = 16;+const ALT_BITS: u32 = 16; -const PAYLOAD_LATLON_E8_ACC16: u8 = 1;+/// Payload: lat(35) | lon(36) | accuracy(16) | altitude(16), LSB-first — 103 bits.+/// Altitude is metres biased by 32768 (two's complement in 16 bits), 0 meaning "unknown".+/// Kind-1 stores (87 bits, no altitude) remain readable; new builds always write kind 2.+const PAYLOAD_LATLON_E8_ACC16_ALT16: u8 = 2;  /// Cap on the Elias-Fano low width, so a low value always fits the reader's `u64`. Exceeding /// it would only ever lengthen `high`, so the cap costs nothing at real record counts.@@ -250,6 +254,8 @@ where         payload.push((r.lat_e8 - LAT_E8_MIN) as u64, LAT_BITS)?;         payload.push((r.lon_e8 - LON_E8_MIN) as u64, LON_BITS)?;         payload.push(u64::from(r.accuracy_m), ACC_BITS)?;+        // Altitude biased so "unknown" (i16::MIN) lands on 0 and real metres on 1..=65535.+        payload.push((i64::from(r.altitude_m) - i64::from(ALT_UNKNOWN)) as u64, ALT_BITS)?;          written += 1;     }@@ -274,7 +280,7 @@ where      let mut out = BufWriter::new(File::create(out_path)?);     out.write_all(MAGIC)?;-    out.write_all(&[kind as u8, universe_bits, PAYLOAD_LATLON_E8_ACC16, l])?;+    out.write_all(&[kind as u8, universe_bits, PAYLOAD_LATLON_E8_ACC16_ALT16, l])?;     out.write_all(&[sample_log2, 0, 0, 0])?;     out.write_all(&n.to_le_bytes())?;     out.write_all(&high_len_bits.to_le_bytes())?;@@ -407,6 +413,7 @@ where             let lat = payload.take(LAT_BITS)? as i64 + LAT_E8_MIN;             let lon = payload.take(LON_BITS)? as i64 + LON_E8_MIN;             let acc = payload.take(ACC_BITS)? as u16;+            let alt = payload.take(ALT_BITS)? as i64 + i64::from(ALT_UNKNOWN);              let w = want                 .next()@@ -419,6 +426,12 @@ where                     w.key, w.lat_e8, w.lon_e8, w.accuracy_m                 )));             }+            if alt != i64::from(w.altitude_m) {+                return Err(invalid(format!(+                    "record {idx} altitude mismatch: got {alt}, want {}",+                    w.altitude_m+                )));+            }             if key >= (1u128 << universe_bits) {                 return Err(invalid(format!("record {idx} key escapes the universe")));             }
scripts/networklocation/wps_harvest/src/store_extra.rs
diff --git a/scripts/networklocation/wps_harvest/src/store_extra.rs b/scripts/networklocation/wps_harvest/src/store_extra.rsindex 7a570ae71d..1f2f09ef19 100644--- a/scripts/networklocation/wps_harvest/src/store_extra.rs+++ b/scripts/networklocation/wps_harvest/src/store_extra.rs@@ -6,7 +6,7 @@ #[cfg(test)] mod tests {     use crate::keys;-    use crate::record::{Record, Source, ACC_UNKNOWN, LAT_E8_MIN, LON_E8_MIN};+    use crate::record::{ALT_UNKNOWN, Record, Source, ACC_UNKNOWN, LAT_E8_MIN, LON_E8_MIN};     use crate::store::{         KeyKind, DEFAULT_SAMPLE_LOG2, MAX_L, choose_l, verify_store, write_store,     };@@ -46,6 +46,7 @@ mod tests {                 lat_e8: (lcg(&mut state) % 18_000_000_000) as i64 + LAT_E8_MIN,                 lon_e8: (lcg(&mut state) % 36_000_000_000) as i64 + LON_E8_MIN,                 accuracy_m: if i % 13 == 0 { ACC_UNKNOWN } else { (i % 900) as u16 },+                altitude_m: (i % 9000) as i16 - 500,                 source: Source::Gsloc,             })             .collect();@@ -83,6 +84,7 @@ mod tests {                 lat_e8: 37_77_493_000,                 lon_e8: -122_41_942_000,                 accuracy_m: 900,+                altitude_m: ALT_UNKNOWN,                 source: Source::OpenCellId,             })             .collect();