waratah_stats/geo_cell_histogram.rs
1//! Sparse geo cell-count histogram for `GeoCandidateScan` row estimates.
2//!
3//! A fixed level-11 S2 bucket grid (see
4//! [`GEO_HISTOGRAM_BUCKET_LEVEL`](waratah_storage::GEO_HISTOGRAM_BUCKET_LEVEL),
5//! 6 × 4^11 ≈ 25.2M cells) carrying **Put posting counts** per bucket,
6//! collected by the O partition's `geo_index` CF collector the same way the
7//! temporal histogram is collected on `temporal_index`. All bucket
8//! derivation is bit-twiddling on the u64 cell id (no S2 library), so the
9//! storage partition stays S2-blind by contract.
10//!
11//! # Count semantics (locked, Sep 2026 design thread)
12//!
13//! Counts are **posting multiplicity**, not distinct terms: a geometry with
14//! twelve postings under one L11 bucket adds twelve to it. This biases
15//! estimates UP, which is the safe side for broadcast-vs-shuffle and
16//! build-arm placement. Postings coarser than
17//! [`GEO_HISTOGRAM_COARSE_FLOOR_LEVEL`] (level 9) do not expand into
18//! `4^(11 − level)` buckets (a face posting would be 4.2M increments); they
19//! ride the `coarse` map keyed by their native cell id, so one continent
20//! polygon stays one entry. Level 8 is deliberately on the coarse side
21//! (count-once): its `4^3 = 64`-bucket expansion multiplied a small posting
22//! population into half the fine map's wire mass on real corpora
23//! (2026-10-27 `waratah geo census` on bellendena-geo-10m: 18.6k L8
24//! postings = 1.19M of 2.37M incidences), while the count-once rung prices
25//! the same posting as one candidate — the estimate's actual unit. A
26//! geometry re-ingested at a new commit_ts adds
27//! new Put rows, and Deletes never decrement — the over-count persists
28//! until a geo rebuild wipes the index (geo index versions are distinct
29//! `(cell, term, commit_ts)` keys and nothing collapses them before that),
30//! the same permanent-over-count contract as `total_puts`.
31//!
32//! # Wire trimming and the remainder summary
33//!
34//! The full map lives in SST blobs (full fidelity). At the transport
35//! boundary ([`StatsProfile::capped_geo_histogram_for_wire`](crate::StatsProfile::capped_geo_histogram_for_wire))
36//! fine entries are kept largest-count-first under a sub-budget, and the
37//! dropped mass is summarized per level-8 parent bucket (total + dropped
38//! cell count) in [`GeoCellHistogram::remainder`]. The remainder itself
39//! obeys the same rank-and-keep discipline under its own sub-budget
40//! (`GEO_REMAINDER_WIRE_BUDGET_BYTES`): largest-total parents first, and
41//! beyond the budget the smallest-mass parents are dropped and read EMPTY.
42//! The coarse map rides its own transport frame with its own budget and the
43//! same rank-and-keep discipline
44//! ([`GeoCellHistogram::capped_coarse_map`]) — see that method for the
45//! down-bias caveat, the ONE deliberately under-biased trim in the package.
46//! The estimator's absent-entry contract: a bucket present in `fine` reads
47//! its exact count; an absent bucket whose L8 parent has remainder mass
48//! reads the parent's average; an absent bucket with no parent mass reads
49//! zero (empty space stays empty). One cross-shard shape completes the
50//! contract: a bucket kept in one shard's `fine` but dropped into another
51//! shard's remainder estimates from the KEEPING shard alone after the merge
52//! (the estimator never prices a present bucket) — an under-estimate
53//! bounded by that parent's dropped total, the same advisory class as the
54//! remainder-tail drop. The beyond-remainder-budget drop trades
55//! the last accuracy notch for a hard wire bound — an under-estimate on
56//! the advisory path only; SPARQL results are unaffected (§10).
57
58use std::collections::BTreeMap;
59
60use waratah_storage::{
61 GEO_HISTOGRAM_COARSE_FLOOR_LEVEL, geo_cell_level, geo_l8_parent_index, geo_l11_bucket_range,
62};
63
64use crate::StatsError;
65
66/// Self-contained section version inside a `StatsProfile` v4 blob (see
67/// `serde_bin`); bumped only when this section's own layout changes.
68const SELF_VERSION: u16 = 1;
69
70/// Wire size of one kept fine entry: a packed `u64` (`bucket << 32 | count`).
71pub const GEO_FINE_WIRE_ENTRY_BYTES: usize = 8;
72
73/// Wire size of one kept coarse entry: native u64 cell id + u64 count.
74pub const GEO_COARSE_WIRE_ENTRY_BYTES: usize = 12;
75
76/// Wire size of one remainder entry: u32 parent + u64 total + u32 cells.
77pub const GEO_REMAINDER_WIRE_ENTRY_BYTES: usize = 16;
78
79/// Dropped-mass summary of one level-8 parent bucket.
80///
81/// `cells` counts dropped FINE entries under the parent; `total` is their
82/// summed posting count. Coarse entries are never dropped by the trim (they
83/// always ship), so a remainder bucket always carries its own cell evidence:
84/// `total > 0` with `cells == 0` is a corrupt shape and is rejected at
85/// decode. `total == 0` with `cells == 0` is the trivial empty bucket.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
87pub struct RemainderBucket {
88 /// Summed posting count of the mass dropped under this parent.
89 pub total: u64,
90 /// Number of dropped fine entries under this parent.
91 pub cells: u32,
92}
93
94/// Per-rung accounting of one [`GeoCellHistogram::estimate_ranges`] call —
95/// the census `--window` decomposition. `estimate_ranges` delegates to
96/// [`GeoCellHistogram::estimate_ranges_breakdown`], so the ladder logic
97/// has one home and the report can name where an over-count sits.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
99pub struct EstimateRangesBreakdown {
100 /// Fine buckets present inside the ranges.
101 pub fine_buckets: u64,
102 /// Their summed counts (exact posting multiplicity).
103 pub fine_mass: u64,
104 /// Absent-bucket mass inside the ranges (L8-parent per-cell averages
105 /// from the remainder summary; zero for a postings-exact histogram,
106 /// where every absent bucket is genuinely empty).
107 pub absent_run_mass: u64,
108 /// Coarse entries whose L11 span intersects any range.
109 pub coarse_entries: u64,
110 /// Their summed counts (count-once per entry).
111 pub coarse_mass: u64,
112 /// `fine_mass + absent_run_mass + coarse_mass` before the clamp.
113 pub raw_total: u64,
114 /// Whether the §10 clamp-1 fired (a zero raw estimate over a non-empty
115 /// covering).
116 pub clamped: bool,
117 /// `raw_total`, clamped ≥ 1 for a non-empty covering.
118 pub total: u64,
119}
120
121impl RemainderBucket {
122 /// Per-absent-bucket estimate for this parent: the average dropped mass,
123 /// rounded up (over-estimate). Zero total mass reads zero — a parent
124 /// with no dropped mass must not supply density.
125 fn per_cell(&self) -> u64 {
126 if self.cells == 0 {
127 return 0;
128 }
129 self.total.div_ceil(u64::from(self.cells))
130 }
131
132 fn merge(&mut self, other: &Self) {
133 self.total = self.total.saturating_add(other.total);
134 self.cells = self.cells.saturating_add(other.cells);
135 }
136}
137
138/// Sparse level-11 cell-count histogram (see the module docs).
139///
140/// Maps are [`BTreeMap`]s so the estimate can sum a query range without
141/// enumerating it: a coarse query cell's descendants are contiguous in the
142/// dense index (one S2 cell never spans a face), so range sums cost
143/// `O(log n + hits)`, never `O(width)`.
144///
145/// The fine/coarse split exists because "counting" means different work at
146/// different posting levels. A posting whose cell is at level 9–10
147/// *expands*: its cell contains 4–16 L11 buckets, so observation writes a
148/// +1 into each — the geometry's footprint is flattened into per-bucket
149/// counts at collection time, bounded at 16 increments (the reason the
150/// floor is level 9; level 8 was moved onto the coarse side 2026-10 — its
151/// 64-bucket expansion multiplied a small posting population into half
152/// the fine map's wire mass on real corpora, see the module docs). A
153/// posting below the floor would demand up to
154/// `4^(11 − level)` increments — a face-level posting covers every L11 cell
155/// on one face, ≈ 4.2M — so instead of flattening it, observation stores
156/// ONE coarse entry keyed by the cell id at its NATIVE level, and the
157/// estimate defers the geometry→bucket mapping to plan time: each coarse
158/// entry contributes its count once when its L11 span (recomputed from the
159/// id by [`waratah_storage::geo_l11_bucket_range`]) intersects any query
160/// range. One huge geometry is one candidate, not thousands.
161#[derive(Debug, Clone, PartialEq, Eq, Default)]
162pub struct GeoCellHistogram {
163 /// Level-11 dense bucket index → Put posting count (saturating `u32`).
164 ///
165 /// Receives every posting at level ≥
166 /// [`GEO_HISTOGRAM_COARSE_FLOOR_LEVEL`] via expansion. All keys are the
167 /// SAME level, which is what makes the fixed dense `u32` encoding
168 /// (`face ‖ 22 Hilbert bits`) unambiguous: bucket index N means the
169 /// same cell to every producer and consumer.
170 pub fine: BTreeMap<u32, u32>,
171 /// Native u64 cell id → count for postings coarser than the fine floor
172 /// (levels 0–8, the floor being count-once INCLUSIVE since the 2026-10
173 /// move; entries are never expanded — see the struct docs).
174 ///
175 /// Keys stay at their NATIVE level deliberately: coarse keys span
176 /// MIXED levels (unlike the uniform fine grid), so a compressed u32
177 /// would have to carry the level alongside the face/digits to stay
178 /// unambiguous — a codec every touch point (collector, overlay, merge,
179 /// wire, estimate) would need, while the native u64 id carries its own
180 /// level intrinsically (the sentinel's bit position IS the level) and
181 /// plugs straight into `geo_l11_bucket_range` / `geo_cell_level`. The
182 /// 4-byte saving per entry buys nothing at this map's size: entries
183 /// exist only for genuinely huge geometries, so the map is empty on
184 /// regional data and a handful of entries at global scale.
185 pub coarse: BTreeMap<u64, u32>,
186 /// Dropped-mass summary per level-8 parent (wire trim only; empty while
187 /// the map is untrimmed).
188 pub remainder: BTreeMap<u32, RemainderBucket>,
189}
190
191impl GeoCellHistogram {
192 /// Observe one geo posting row (Put-only by contract — the collector and
193 /// the apply-path overlay both filter on the op before calling this).
194 ///
195 /// Level ≥ 9 postings expand into their (≤ 16) L11 descendant buckets
196 /// (level 8 and below ride the coarse map — see the struct docs);
197 /// malformed cell ids are ignored (the collector ignores undecodable
198 /// rows the same way).
199 pub fn observe_posting(&mut self, cell_id: u64) {
200 let Some(level) = geo_cell_level(cell_id) else {
201 return;
202 };
203 if level >= GEO_HISTOGRAM_COARSE_FLOOR_LEVEL {
204 let (lo, hi) = geo_l11_bucket_range(cell_id).expect("level checked");
205 for idx in lo..=hi {
206 let slot = self.fine.entry(idx).or_insert(0);
207 *slot = slot.saturating_add(1);
208 }
209 } else {
210 let slot = self.coarse.entry(cell_id).or_insert(0);
211 *slot = slot.saturating_add(1);
212 }
213 }
214
215 /// Algebraic merge: per-key saturating adds on all three maps. Order
216 /// independent — saturating add is `min(a + b, u32::MAX)`, and `min` is
217 /// associative, so shard roll-ups are order independent.
218 pub fn merge(&mut self, other: &Self) {
219 for (idx, count) in &other.fine {
220 let slot = self.fine.entry(*idx).or_insert(0);
221 *slot = slot.saturating_add(*count);
222 }
223 for (cell_id, count) in &other.coarse {
224 let slot = self.coarse.entry(*cell_id).or_insert(0);
225 *slot = slot.saturating_add(*count);
226 }
227 for (parent, bucket) in &other.remainder {
228 self.remainder.entry(*parent).or_default().merge(bucket);
229 }
230 }
231
232 /// Whether no posting was ever observed (merge identity).
233 pub fn is_empty(&self) -> bool {
234 self.fine.is_empty() && self.coarse.is_empty() && self.remainder.is_empty()
235 }
236
237 /// Summed bucket incidences (fine + coarse values, before any trim).
238 /// NOT the posting count: a coarse-floor posting expanded into N L11
239 /// buckets contributes N here. Debug/telemetry value only — the
240 /// estimator never reads it.
241 pub fn total_bucket_mass(&self) -> u64 {
242 let fine: u64 = self.fine.values().map(|c| u64::from(*c)).sum();
243 let coarse: u64 = self.coarse.values().map(|c| u64::from(*c)).sum();
244 fine + coarse
245 }
246
247 /// Wire-trimmed copy: coarse entries pass through untouched here (their
248 /// frame has its own trim, [`Self::capped_coarse_map`]), then fine
249 /// entries largest-count-first (bucket index ascending tie-break,
250 /// deterministic) while the fine side fits `max_fine_bytes`. Dropped
251 /// fine mass is summarized per L8 parent into `remainder`; the
252 /// remainder then obeys the same rank-and-keep discipline under
253 /// `max_remainder_bytes` — largest-total parents first, and beyond the
254 /// budget the smallest-mass parents are dropped and read EMPTY
255 /// (bounded under-estimate, advisory path only).
256 ///
257 /// An input that already carries a `remainder` (a re-trim at the rollup
258 /// boundary, or a merged profile of trimmed shards) passes it through:
259 /// this round's drops merge INTO it, they never replace it — otherwise
260 /// a second trim would silently discard the first round's summarized
261 /// mass.
262 ///
263 /// Call only at transport boundaries; SST blobs and shard merges stay
264 /// full-fidelity.
265 #[must_use]
266 pub fn capped_for_wire(&self, max_fine_bytes: usize, max_remainder_bytes: usize) -> Self {
267 let mut out = Self {
268 coarse: self.coarse.clone(),
269 remainder: self.remainder.clone(),
270 ..Self::default()
271 };
272 let max_fine_entries = max_fine_bytes / GEO_FINE_WIRE_ENTRY_BYTES;
273 let mut ranked: Vec<(u32, u32)> = self
274 .fine
275 .iter()
276 .map(|(&idx, &count)| (idx, count))
277 .collect();
278 // Count descending, index ascending: deterministic truncation point.
279 ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
280 for (idx, count) in ranked.into_iter().take(max_fine_entries) {
281 out.fine.insert(idx, count);
282 }
283 for (idx, count) in &self.fine {
284 if out.fine.contains_key(idx) {
285 continue;
286 }
287 let bucket = out.remainder.entry(geo_l8_parent_index(*idx)).or_default();
288 bucket.total = bucket.total.saturating_add(u64::from(*count));
289 bucket.cells = bucket.cells.saturating_add(1);
290 }
291 // The remainder's own budget: same discipline, same determinism, and
292 // the dropped tail simply reads empty (the estimator already prices
293 // an absent parent at zero).
294 let max_remainder_entries = max_remainder_bytes / GEO_REMAINDER_WIRE_ENTRY_BYTES;
295 if out.remainder.len() > max_remainder_entries {
296 let mut ranked: Vec<(u32, RemainderBucket)> = out
297 .remainder
298 .iter()
299 .map(|(&parent, &bucket)| (parent, bucket))
300 .collect();
301 ranked.sort_by(|a, b| b.1.total.cmp(&a.1.total).then_with(|| a.0.cmp(&b.0)));
302 out.remainder = ranked.into_iter().take(max_remainder_entries).collect();
303 }
304 out
305 }
306
307 /// The coarse map trimmed for its own transport frame: rank-and-keep
308 /// under `max_coarse_bytes` — count descending, native cell id ascending
309 /// tie-break, deterministic — the same discipline the fine map and
310 /// remainder obey.
311 ///
312 /// **The down-bias caveat (the one deliberately under-biased trim in
313 /// the stats package):** unlike dropped fine mass, a dropped coarse
314 /// entry has NO summary to fall back on — it reads EMPTY in every
315 /// window touching its span, so over-budget coarse maps under-estimate
316 /// candidate counts, the UNSAFE direction for broadcast-vs-shuffle.
317 /// Every other trim in this package degrades through a summary (the
318 /// remainder) or biases up; this one is accepted because the coarse
319 /// population is postings of genuinely huge geometries (few entries per
320 /// corpus) and the budget is set with headroom over the census-measured
321 /// population. If a corpus ever saturates this budget, the fix is a
322 /// coarse-side summary (the remainder's twin), not a bigger frame —
323 /// re-derive the trade-off rather than trimming deeper.
324 ///
325 /// Idempotent and merge-stable: re-trimming a kept subset under the
326 /// same budget keeps it; a merged pair of trimmed maps re-trims to the
327 /// top-K of the union.
328 #[must_use]
329 pub fn capped_coarse_map(&self, max_coarse_bytes: usize) -> BTreeMap<u64, u32> {
330 let max_coarse_entries = max_coarse_bytes / GEO_COARSE_WIRE_ENTRY_BYTES;
331 if self.coarse.len() <= max_coarse_entries {
332 return self.coarse.clone();
333 }
334 let mut ranked: Vec<(u64, u32)> = self
335 .coarse
336 .iter()
337 .map(|(&id, &count)| (id, count))
338 .collect();
339 ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
340 ranked
341 .into_iter()
342 .take(max_coarse_entries)
343 .collect::<BTreeMap<_, _>>()
344 }
345
346 /// Wire size of this histogram's serialization (what the transport
347 /// budget accounting charges for the section; matches `encode_body`).
348 pub fn wire_bytes(&self) -> usize {
349 2 // SELF_VERSION
350 + 4 + self.fine.len() * GEO_FINE_WIRE_ENTRY_BYTES
351 + 4 + self.coarse.len() * GEO_COARSE_WIRE_ENTRY_BYTES
352 + 4 + self.remainder.len() * GEO_REMAINDER_WIRE_ENTRY_BYTES
353 }
354
355 /// Estimated Put postings for a query covering given as **disjoint**
356 /// inclusive level-11 dense-index ranges (see
357 /// `waratah_geo::covering::covering_l11_ranges`).
358 ///
359 /// Ladder, per range: present fine buckets read exact counts; absent
360 /// runs read their L8 parent's average when the parent carries remainder
361 /// mass (zero when it does not — empty space estimates empty, including
362 /// a parent dropped by the remainder's own wire budget); coarse entries
363 /// intersecting any range add their count once each. Clamped to ≥ 1 for
364 /// a non-empty covering — estimates order plans, never prune (§10).
365 #[must_use]
366 pub fn estimate_ranges(&self, ranges: &[(u32, u32)]) -> u64 {
367 self.estimate_ranges_breakdown(ranges).total
368 }
369
370 /// Per-rung accounting of one [`Self::estimate_ranges`] call — the
371 /// census `--window` decomposition. `estimate_ranges` delegates here,
372 /// so the ladder logic has one home.
373 #[must_use]
374 pub fn estimate_ranges_breakdown(&self, ranges: &[(u32, u32)]) -> EstimateRangesBreakdown {
375 let mut breakdown = EstimateRangesBreakdown::default();
376 for &(lo, hi) in ranges {
377 if lo > hi {
378 continue;
379 }
380 let mut next = lo;
381 for (&idx, &count) in self.fine.range(lo..=hi) {
382 if idx > next {
383 breakdown.absent_run_mass += self.absent_run(next, idx - 1);
384 }
385 breakdown.fine_buckets += 1;
386 breakdown.fine_mass += u64::from(count);
387 next = idx.saturating_add(1);
388 }
389 if next <= hi {
390 breakdown.absent_run_mass += self.absent_run(next, hi);
391 }
392 }
393 // Coarse entries: one candidate geometry each; count once when its
394 // L11 span intersects any query range.
395 for (&cell_id, &count) in &self.coarse {
396 if count == 0 {
397 continue;
398 }
399 let Some((clo, chi)) = geo_l11_bucket_range(cell_id) else {
400 continue;
401 };
402 if ranges.iter().any(|&(lo, hi)| clo <= hi && lo <= chi) {
403 breakdown.coarse_entries += 1;
404 breakdown.coarse_mass += u64::from(count);
405 }
406 }
407 breakdown.raw_total =
408 breakdown.fine_mass + breakdown.absent_run_mass + breakdown.coarse_mass;
409 // §10: never zero for a non-empty covering.
410 if breakdown.raw_total == 0 && ranges.iter().any(|&(lo, hi)| lo <= hi) {
411 breakdown.clamped = true;
412 breakdown.total = 1;
413 } else {
414 breakdown.total = breakdown.raw_total;
415 }
416 breakdown
417 }
418
419 /// Absent-bucket mass for `[lo, hi]`: per L8 parent overlap, the
420 /// parent's per-cell average (zero when the parent has no remainder —
421 /// the parent is either fully kept or genuinely empty).
422 fn absent_run(&self, lo: u32, hi: u32) -> u64 {
423 let mut total: u64 = 0;
424 let mut parent = geo_l8_parent_index(lo);
425 loop {
426 let p_start = parent << 6;
427 let p_end = p_start | 0x3F;
428 let overlap_lo = lo.max(p_start);
429 let overlap_hi = hi.min(p_end);
430 if overlap_lo <= overlap_hi
431 && let Some(bucket) = self.remainder.get(&parent)
432 {
433 let absent = u64::from(overlap_hi - overlap_lo + 1);
434 total += absent.saturating_mul(bucket.per_cell());
435 }
436 if p_end >= hi {
437 break;
438 }
439 parent += 1;
440 }
441 total
442 }
443
444 /// Serialize as a self-versioned section (an appendable trailer of the
445 /// profile blob, like [`TickHistogram`](crate::TickHistogram)).
446 pub fn encode_body(&self, out: &mut Vec<u8>) {
447 out.extend_from_slice(&SELF_VERSION.to_le_bytes());
448 out.extend_from_slice(&(self.fine.len() as u32).to_le_bytes());
449 // Packed u64: bucket index in the high 32 bits, count in the low.
450 for (&idx, &count) in &self.fine {
451 out.extend_from_slice(&((u64::from(idx) << 32) | u64::from(count)).to_le_bytes());
452 }
453 out.extend_from_slice(&(self.coarse.len() as u32).to_le_bytes());
454 for (&cell_id, &count) in &self.coarse {
455 out.extend_from_slice(&cell_id.to_le_bytes());
456 out.extend_from_slice(&count.to_le_bytes());
457 }
458 out.extend_from_slice(&(self.remainder.len() as u32).to_le_bytes());
459 for (&parent, bucket) in &self.remainder {
460 out.extend_from_slice(&parent.to_le_bytes());
461 out.extend_from_slice(&bucket.total.to_le_bytes());
462 out.extend_from_slice(&bucket.cells.to_le_bytes());
463 }
464 }
465
466 /// Decode a section produced by [`Self::encode_body`]; consumes exactly
467 /// its own bytes (trailing input belongs to the caller).
468 pub fn decode_body(buf: &mut &[u8]) -> Result<Self, StatsError> {
469 let corrupt = |what: &str| StatsError::Corrupt(format!("geo cell histogram: {what}"));
470 if buf.len() < 2 {
471 return Err(corrupt("truncated version"));
472 }
473 let version = u16::from_le_bytes(buf[..2].try_into().expect("2-byte slice"));
474 *buf = &buf[2..];
475 if version != SELF_VERSION {
476 return Err(corrupt(&format!("unsupported section version {version}")));
477 }
478 let take_u32 = |buf: &mut &[u8]| -> Result<u32, StatsError> {
479 if buf.len() < 4 {
480 return Err(corrupt("truncated length"));
481 }
482 let v = u32::from_le_bytes(buf[..4].try_into().expect("4-byte slice"));
483 *buf = &buf[4..];
484 Ok(v)
485 };
486 let fine_len = take_u32(buf)? as usize;
487 let mut fine = BTreeMap::new();
488 for _ in 0..fine_len {
489 if buf.len() < GEO_FINE_WIRE_ENTRY_BYTES {
490 return Err(corrupt("truncated fine entry"));
491 }
492 let packed = u64::from_le_bytes(
493 buf[..GEO_FINE_WIRE_ENTRY_BYTES]
494 .try_into()
495 .expect("8-byte slice"),
496 );
497 *buf = &buf[GEO_FINE_WIRE_ENTRY_BYTES..];
498 fine.insert((packed >> 32) as u32, (packed & 0xFFFF_FFFF) as u32);
499 }
500 let coarse_len = take_u32(buf)? as usize;
501 let mut coarse = BTreeMap::new();
502 for _ in 0..coarse_len {
503 if buf.len() < GEO_COARSE_WIRE_ENTRY_BYTES {
504 return Err(corrupt("truncated coarse entry"));
505 }
506 let cell_id = u64::from_le_bytes(buf[..8].try_into().expect("8-byte slice"));
507 let count = u32::from_le_bytes(buf[8..12].try_into().expect("4-byte slice"));
508 *buf = &buf[GEO_COARSE_WIRE_ENTRY_BYTES..];
509 coarse.insert(cell_id, count);
510 }
511 let remainder_len = take_u32(buf)? as usize;
512 let mut remainder = BTreeMap::new();
513 for _ in 0..remainder_len {
514 if buf.len() < GEO_REMAINDER_WIRE_ENTRY_BYTES {
515 return Err(corrupt("truncated remainder entry"));
516 }
517 let parent = u32::from_le_bytes(buf[..4].try_into().expect("4-byte slice"));
518 let total = u64::from_le_bytes(buf[4..12].try_into().expect("8-byte slice"));
519 let cells = u32::from_le_bytes(
520 buf[12..GEO_REMAINDER_WIRE_ENTRY_BYTES]
521 .try_into()
522 .expect("4-byte slice"),
523 );
524 *buf = &buf[GEO_REMAINDER_WIRE_ENTRY_BYTES..];
525 if total > 0 && cells == 0 {
526 return Err(corrupt("remainder mass without cell evidence"));
527 }
528 remainder.insert(parent, RemainderBucket { total, cells });
529 }
530 Ok(Self {
531 fine,
532 coarse,
533 remainder,
534 })
535 }
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541 use waratah_storage::{GEO_HISTOGRAM_BUCKET_LEVEL, geo_l8_parent_index, geo_l11_bucket_index};
542
543 /// A level-30 leaf cell id with a known face and 60-bit Hilbert
544 /// position. The L11 digit field is position bits 38..59, so positions
545 /// below 2^38 share bucket 0 within a face.
546 fn leaf(face: u64, pos: u64) -> u64 {
547 // Leaf layout: face<<61 | pos<<1 | 1.
548 (face << 61) | (pos << 1) | 1
549 }
550
551 #[test]
552 fn estimate_ranges_breakdown_decomposes_the_ladder() {
553 let mut hist = GeoCellHistogram::default();
554 hist.fine.insert(5, 3);
555 hist.fine.insert(7, 1);
556 // Parent 0 carries dropped mass: per-cell average ceil(12/4) = 3.
557 hist.remainder.insert(
558 0,
559 RemainderBucket {
560 total: 12,
561 cells: 4,
562 },
563 );
564 // An L8 coarse cell on face 0: its L11 span (0, 63) intersects.
565 hist.coarse.insert(1u64 << (60 - 2 * 8), 4);
566
567 let b = hist.estimate_ranges_breakdown(&[(5, 7)]);
568 assert_eq!(b.fine_buckets, 2);
569 assert_eq!(b.fine_mass, 4);
570 // Bucket 6 is absent: parent 0's per-cell average supplies 3.
571 assert_eq!(b.absent_run_mass, 3);
572 assert_eq!(b.coarse_entries, 1);
573 assert_eq!(b.coarse_mass, 4);
574 assert_eq!(b.raw_total, 11);
575 assert_eq!(b.total, 11);
576 assert!(!b.clamped);
577 // `estimate_ranges` is the plain delegation: same number.
578 assert_eq!(hist.estimate_ranges(&[(5, 7)]), 11);
579
580 // A range with no mass at all: raw 0 → the §10 clamp-1 fires.
581 let empty = hist.estimate_ranges_breakdown(&[(100, 200)]);
582 assert_eq!(empty.raw_total, 0);
583 assert!(empty.clamped);
584 assert_eq!(empty.total, 1);
585 }
586
587 #[test]
588 fn bucket_math_landmark_values() {
589 // Face 0, all-zero Hilbert prefix: bucket index 0.
590 assert_eq!(geo_l11_bucket_index(leaf(0, 0)), 0);
591 // Face 1 shifts by 2^22.
592 assert_eq!(geo_l11_bucket_index(leaf(1, 0)), 1 << 22);
593 // Leaf positions differing inside the L11 digit field (pos bits
594 // 38..59) land in different L11 buckets; differing below bit 38 (or
595 // in finer digits) do not.
596 assert_ne!(
597 geo_l11_bucket_index(leaf(0, 1 << 38)),
598 geo_l11_bucket_index(leaf(0, 0))
599 );
600 assert_eq!(
601 geo_l11_bucket_index(leaf(0, 1 << 37)),
602 geo_l11_bucket_index(leaf(0, 0))
603 );
604 assert_eq!(
605 geo_l11_bucket_index(leaf(0, 1)),
606 geo_l11_bucket_index(leaf(0, 0))
607 );
608 // L8 parent groups 64 consecutive L11 buckets.
609 assert_eq!(geo_l8_parent_index((1 << 22) + 63), 1 << 16);
610 assert_eq!(geo_l8_parent_index((1 << 22) + 64), (1 << 16) + 1);
611 }
612
613 #[test]
614 fn observe_level_30_posting_lands_in_one_bucket() {
615 let mut hist = GeoCellHistogram::default();
616 hist.observe_posting(leaf(0, 123));
617 hist.observe_posting(leaf(0, 456)); // same L11 bucket
618 hist.observe_posting(leaf(0, 1 << 38)); // different L11 bucket
619 assert_eq!(hist.fine.len(), 2);
620 assert_eq!(hist.total_bucket_mass(), 3);
621 }
622
623 #[test]
624 fn observe_coarse_posting_expands_bounded() {
625 // The floor is inclusive-count-once at level 8: a level-9 posting
626 // expands to 4^2 = 16 fine buckets, while level 8 itself rides the
627 // coarse map as ONE entry (its 64-bucket expansion multiplied a
628 // small posting population into half the fine map's mass on real
629 // corpora — see the module docs).
630 let level9 = leaf(0, 0) & !((1u64 << (60 - 18)) - 1) | (1u64 << (60 - 18));
631 let mut hist = GeoCellHistogram::default();
632 hist.observe_posting(level9);
633 assert_eq!(hist.fine.len(), 16);
634 assert_eq!(hist.total_bucket_mass(), 16);
635 // A level-8 posting (now on the coarse side) stays ONE entry.
636 let level8 = 1u64 << (60 - 16);
637 hist.observe_posting(level8);
638 assert_eq!(hist.coarse.len(), 1);
639 assert_eq!(hist.fine.len(), 16);
640 assert_eq!(hist.total_bucket_mass(), 17);
641 // A level-4 posting (below the floor since the beginning) is also
642 // one coarse entry.
643 let level4 = 1u64 << (60 - 8);
644 hist.observe_posting(level4);
645 assert_eq!(hist.coarse.len(), 2);
646 assert_eq!(hist.total_bucket_mass(), 18);
647 }
648
649 #[test]
650 fn coarse_frame_rank_and_keep_is_deterministic_and_idempotent() {
651 let mut hist = GeoCellHistogram::default();
652 // Three coarse entries: counts 10 / 10 / 3; the two 10s tie and
653 // break by cell id ascending. Budget for TWO entries.
654 hist.coarse.insert(0x4000_0000_0000_0001, 10);
655 hist.coarse.insert(0x2000_0000_0000_0001, 10);
656 hist.coarse.insert(0x8000_0000_0000_0001, 3);
657 let kept = hist.capped_coarse_map(2 * GEO_COARSE_WIRE_ENTRY_BYTES);
658 assert_eq!(kept.len(), 2);
659 assert!(
660 kept.contains_key(&0x2000_0000_0000_0001),
661 "tie breaks by id ascending"
662 );
663 assert!(
664 kept.contains_key(&0x4000_0000_0000_0001),
665 "both count-10 entries survive"
666 );
667 assert!(
668 !kept.contains_key(&0x8000_0000_0000_0001),
669 "the count-3 tail drops"
670 );
671 // Idempotent: re-trimming the kept subset under the same budget is
672 // a no-op, and a merged pair of trimmed maps re-trims to the top-K
673 // of the union.
674 let again = GeoCellHistogram {
675 coarse: kept.clone(),
676 ..GeoCellHistogram::default()
677 }
678 .capped_coarse_map(2 * GEO_COARSE_WIRE_ENTRY_BYTES);
679 assert_eq!(kept, again);
680 let mut merged = GeoCellHistogram {
681 coarse: kept,
682 ..GeoCellHistogram::default()
683 };
684 let mut other = GeoCellHistogram::default();
685 other.coarse.insert(0x8000_0000_0000_0001, 9);
686 merged.merge(&other);
687 let retrimmed = merged.capped_coarse_map(2 * GEO_COARSE_WIRE_ENTRY_BYTES);
688 assert_eq!(retrimmed.len(), 2);
689 assert!(
690 !retrimmed.contains_key(&0x8000_0000_0000_0001),
691 "re-trim keeps the top-K of the merged union: 9 loses to the two 10s"
692 );
693 assert!(retrimmed.contains_key(&0x2000_0000_0000_0001));
694 assert!(retrimmed.contains_key(&0x4000_0000_0000_0001));
695 }
696
697 #[test]
698 fn merge_is_saturating_and_order_independent() {
699 let idx = 7u32;
700 let mut a = GeoCellHistogram::default();
701 a.fine.insert(idx, u32::MAX - 1);
702 let mut b = GeoCellHistogram::default();
703 b.fine.insert(idx, 5);
704 let mut ab = a.clone();
705 ab.merge(&b);
706 let mut ba = b.clone();
707 ba.merge(&a);
708 assert_eq!(ab, ba);
709 assert_eq!(ab.fine[&idx], u32::MAX, "saturates at u32::MAX");
710 }
711
712 #[test]
713 fn cap_keeps_largest_and_summarizes_dropped_mass() {
714 let mut hist = GeoCellHistogram::default();
715 // Bucket 100 gets 10 postings; 130 gets 5; 131 gets 1. 130 and 131
716 // share L8 parent 2 (both in 128..192); 100 sits under parent 1.
717 for _ in 0..10 {
718 *hist.fine.entry(100).or_insert(0) += 1;
719 }
720 for _ in 0..5 {
721 *hist.fine.entry(130).or_insert(0) += 1;
722 }
723 *hist.fine.entry(131).or_insert(0) += 1;
724 // Budget for one entry keeps bucket 100; the rest becomes remainder.
725 let capped = hist.capped_for_wire(GEO_FINE_WIRE_ENTRY_BYTES, usize::MAX);
726 assert_eq!(capped.fine.len(), 1);
727 assert_eq!(capped.fine[&100], 10);
728 assert_eq!(capped.remainder.len(), 1);
729 let rb = &capped.remainder[&geo_l8_parent_index(130)];
730 assert_eq!(rb.total, 6);
731 assert_eq!(rb.cells, 2);
732 // The capped copy merges into a full profile without losing identity.
733 let mut merged = hist.clone();
734 merged.merge(&capped);
735 assert_eq!(merged.fine[&100], 20);
736 assert_eq!(merged.remainder[&geo_l8_parent_index(130)].total, 6);
737 }
738
739 #[test]
740 fn estimate_ladder_exact_parent_average_and_empty() {
741 let mut hist = GeoCellHistogram::default();
742 for _ in 0..8 {
743 hist.observe_posting(leaf(0, 0)); // bucket 0, count 8
744 }
745 // 4 absent buckets with mass 12 → parent-0 average 3.
746 hist.remainder.insert(
747 0,
748 RemainderBucket {
749 total: 12,
750 cells: 4,
751 },
752 );
753 // Range fully covering bucket 0: exact count.
754 assert_eq!(hist.estimate_ranges(&[(0, 0)]), 8);
755 // Range covering absent buckets only: 4 absent × parent avg 3.
756 assert_eq!(hist.estimate_ranges(&[(4, 7)]), 12);
757 // Mixed: bucket 0 exact + 3 absent × 3.
758 assert_eq!(hist.estimate_ranges(&[(0, 3)]), 8 + 9);
759 // Absent with NO parent mass: empty space reads empty, then the
760 // §10 clamp floors the covering at 1.
761 let mut empty_region = GeoCellHistogram::default();
762 empty_region
763 .remainder
764 .insert(9, RemainderBucket { total: 0, cells: 0 });
765 assert_eq!(empty_region.estimate_ranges(&[(600, 603)]), 1);
766 // Parent 9 has a zero-mass remainder entry, so no avg mass flows in;
767 // the clamp, not the remainder, supplies the 1.
768 }
769
770 #[test]
771 fn estimate_range_over_kept_and_dropped_matches_total_mass() {
772 // Mass conservation: a range spanning kept + dropped buckets under
773 // one parent estimates close to the true total (the remainder
774 // average reconstructs the dropped mass).
775 let mut hist = GeoCellHistogram::default();
776 for i in 0..32u32 {
777 for _ in 0..i {
778 *hist.fine.entry(i).or_insert(0) += 1;
779 }
780 }
781 // Buckets 0..32 hold sum(0..31) = 496 postings.
782 let capped = hist.capped_for_wire(8 * GEO_FINE_WIRE_ENTRY_BYTES, usize::MAX);
783 // Whole-parent range: kept sums (220) + every absent bucket (56)
784 // priced at the dropped-cell average (12) — the remainder cannot
785 // tell "dropped by the budget" from "never observed", so the
786 // estimate runs over the 496 true mass by the empty buckets' share.
787 let est = capped.estimate_ranges(&[(0, 63)]);
788 assert!(
789 (496..=1500).contains(&est),
790 "whole-parent estimate {est} must over-cover the 496 true mass"
791 );
792 }
793
794 #[test]
795 fn coarse_entry_counts_once_across_intersecting_ranges() {
796 let mut hist = GeoCellHistogram::default();
797 let level4 = 1u64 << (60 - 8);
798 hist.observe_posting(level4);
799 let (lo, hi) = geo_l11_bucket_range(level4).unwrap();
800 // Two disjoint ranges both inside the coarse span: one geometry.
801 let mid = lo + (hi - lo) / 2;
802 assert_eq!(
803 hist.estimate_ranges(&[(lo, mid), (mid + 1, hi)]),
804 1,
805 "one coarse geometry is one candidate, not two"
806 );
807 // A range outside the span does not see it.
808 assert_eq!(
809 hist.estimate_ranges(&[(hi + 1, hi + 2)]),
810 1,
811 "§10 clamp only"
812 );
813 }
814
815 #[test]
816 fn serde_round_trip() {
817 let mut hist = GeoCellHistogram::default();
818 hist.observe_posting(leaf(0, 5));
819 hist.observe_posting(leaf(1, 5));
820 hist.observe_posting(1u64 << (60 - 2 * 8)); // level-8 posting (count-once coarse since the floor move)
821 hist.observe_posting(1u64 << (60 - 2 * 8)); // twice
822 hist.observe_posting(1u64 << (60 - 2 * 4)); // level-4 coarse entry
823 let capped = hist.capped_for_wire(4 * GEO_FINE_WIRE_ENTRY_BYTES, usize::MAX);
824 let mut bytes = Vec::new();
825 capped.encode_body(&mut bytes);
826 let mut cursor = bytes.as_slice();
827 let decoded = GeoCellHistogram::decode_body(&mut cursor).unwrap();
828 assert!(cursor.is_empty(), "decode consumes exactly its own bytes");
829 assert_eq!(decoded, capped);
830 // And the untrimmed histogram round-trips too.
831 let mut full = Vec::new();
832 hist.encode_body(&mut full);
833 let decoded_full = GeoCellHistogram::decode_body(&mut full.as_slice()).unwrap();
834 assert_eq!(decoded_full, hist);
835 assert_eq!(
836 decoded_full.total_bucket_mass(),
837 5,
838 "2 leaf fine + 3 coarse entries (2×L8 count-once + 1×L4)"
839 );
840 }
841
842 #[test]
843 fn bucket_level_is_eleven() {
844 assert_eq!(GEO_HISTOGRAM_BUCKET_LEVEL, 11);
845 }
846
847 #[test]
848 fn remainder_budget_keeps_largest_parents_and_drops_tail_to_empty() {
849 // Fine budget of one entry keeps bucket 0 (count 10); every other
850 // bucket drops into its parent. Parents 1..5 carry totals 1..5, the
851 // remainder budget keeps only two — the largest totals survive and
852 // the dropped parents price as EMPTY (clamp floor), not average.
853 // Bucket 0 (parent 0, count 10) is the fine side's only keep; each
854 // parent 1..=5 owns buckets parent*64.. and contributes exactly one
855 // dropped bucket of count = parent.
856 let mut hist = GeoCellHistogram::default();
857 *hist.fine.entry(0).or_insert(0) += 10;
858 for parent in 1u32..=5 {
859 *hist.fine.entry(parent * 64).or_insert(0) += parent;
860 }
861 let capped = hist.capped_for_wire(
862 GEO_FINE_WIRE_ENTRY_BYTES,
863 2 * GEO_REMAINDER_WIRE_ENTRY_BYTES,
864 );
865 // Parents 5 and 4 carry the largest totals; 1..3 dropped.
866 assert_eq!(capped.remainder.len(), 2);
867 assert!(capped.remainder.contains_key(&5));
868 assert!(capped.remainder.contains_key(&4));
869 // An absent bucket under dropped parent 1 reads EMPTY: only bucket
870 // 0's exact 10 plus the clamp would appear — a covering over parent
871 // 1's buckets estimates the floor, not an average.
872 let est = capped.estimate_ranges(&[(64, 64)]);
873 assert_eq!(est, 1, "dropped-from-remainder parent prices empty");
874 // Parent 5's absent bucket still reads its average (count 5, cells 1).
875 let est = capped.estimate_ranges(&[(5 * 64, 5 * 64)]);
876 assert_eq!(est, 5);
877 // Determinism: same inputs, same kept set.
878 let again = hist.capped_for_wire(
879 GEO_FINE_WIRE_ENTRY_BYTES,
880 2 * GEO_REMAINDER_WIRE_ENTRY_BYTES,
881 );
882 assert_eq!(capped, again);
883 }
884
885 #[test]
886 fn retrim_carries_prior_remainder_mass() {
887 // The rollup shape: shard profiles are trimmed at the partition, the
888 // compute boundary merges them and trims AGAIN. A re-trim must merge
889 // this round's drops into the input's remainder, not replace it.
890 let mut full = GeoCellHistogram::default();
891 *full.fine.entry(0).or_insert(0) += 10;
892 *full.fine.entry(200).or_insert(0) += 7;
893 let once = full.capped_for_wire(GEO_FINE_WIRE_ENTRY_BYTES, usize::MAX);
894 assert_eq!(once.fine.len(), 1);
895 assert_eq!(once.remainder[&geo_l8_parent_index(200)].total, 7);
896 // Re-trim the already-trimmed profile: no new fine drops (the kept
897 // entry still fits), so the remainder must survive unchanged — the
898 // pre-fix code rebuilt it from nothing and silently lost the 7.
899 let twice = once.capped_for_wire(GEO_FINE_WIRE_ENTRY_BYTES, usize::MAX);
900 assert_eq!(twice.remainder, once.remainder);
901 // And a merge-then-retrim keeps both shards' summarized mass.
902 let mut merged = once.clone();
903 merged.merge(&once);
904 let retrimmed = merged.capped_for_wire(GEO_FINE_WIRE_ENTRY_BYTES, usize::MAX);
905 assert_eq!(
906 retrimmed.remainder[&geo_l8_parent_index(200)].total,
907 14,
908 "merged remainder mass survives the re-trim"
909 );
910 }
911
912 #[test]
913 fn wire_bytes_matches_encoded_length() {
914 let mut hist = GeoCellHistogram::default();
915 hist.observe_posting(leaf(0, 3));
916 hist.observe_posting(leaf(1, 3));
917 hist.observe_posting(1u64 << (60 - 2 * 4));
918 // Fine budget of ONE entry: the trim drops the second fine bucket
919 // and populates a remainder, so the byte accounting is pinned for
920 // all three non-empty sections, not just the no-remainder shape.
921 let capped = hist.capped_for_wire(GEO_FINE_WIRE_ENTRY_BYTES, 256);
922 assert!(
923 !capped.remainder.is_empty() && !capped.fine.is_empty() && !capped.coarse.is_empty(),
924 "the shape under test must populate fine, coarse, AND remainder"
925 );
926 let mut bytes = Vec::new();
927 capped.encode_body(&mut bytes);
928 assert_eq!(
929 capped.wire_bytes(),
930 bytes.len(),
931 "wire accounting must match the serialized section byte-for-byte"
932 );
933 }
934
935 #[test]
936 fn decode_rejects_remainder_mass_without_cells() {
937 let mut hist = GeoCellHistogram::default();
938 hist.remainder
939 .insert(9, RemainderBucket { total: 5, cells: 0 });
940 let mut bytes = Vec::new();
941 hist.encode_body(&mut bytes);
942 let err = GeoCellHistogram::decode_body(&mut bytes.as_slice());
943 assert!(err.is_err(), "total > 0 with cells == 0 is corrupt");
944 }
945}