zodiacal 0.4.1

A blind astrometry plate-solving library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! `LiveIndex` — stateful in-memory index whose loaded cell set can
//! grow and shrink at runtime.
//!
//! Plan 3 of the deployment-mode roadmap (`plans/03-live-index.md`),
//! refined per user input to use a [`KdForest`] of per-cell sub-trees
//! instead of rebuilding one big tree on every cell change. Cell
//! add/drop is now O(1) for tree maintenance; query cost grows linearly
//! with the number of loaded cells (typically <100 in realtime use).
//!
//! For the existing `solve()` path which expects a concrete `Index`
//! with flat star/quad/code vectors, `LiveIndex::as_index()` flattens
//! the forest on demand. That cost is paid lazily — only when a solve
//! actually needs it, not on every membership change.

use std::collections::{HashMap, HashSet};
use std::io;
use std::time::{Duration, Instant};

use crate::geom::sphere::radec_to_xyz;
use crate::kdtree::{KdForest, KdTree};
use crate::quads::{Code, DIMCODES, DIMQUADS, Quad};
use crate::solver::SkyRegion;

use super::source::{HealpixCell, IndexFragment, IndexSource};
use super::{Index, IndexStar};

/// Per-cell payload tracked by `LiveIndex`. Star indices in `quads` are
/// local to this cell's `stars` (they were already remapped to that
/// frame by `IndexSource::load_cells`).
struct LoadedCell {
    stars: Vec<IndexStar>,
    quads: Vec<Quad>,
    codes: Vec<Code>,
    /// Reserved for future LRU/eviction policy (currently never read).
    #[allow(dead_code)]
    last_used: Instant,
}

/// Stateful in-memory subset of an `IndexSource`. The loaded cell set
/// can be grown via [`Self::ensure_region`] and shrunk via
/// [`Self::drop_outside`]. Internally maintains a forest of per-cell
/// KdTrees so add/drop don't require an O(N log N) rebuild.
pub struct LiveIndex<S: IndexSource> {
    source: S,
    loaded: HashMap<HealpixCell, LoadedCell>,
    star_forest: KdForest<3>,
    code_forest: KdForest<{ DIMCODES }>,
    /// Bumped on every membership change; surfaces to consumers via
    /// `build_generation()` so they can detect when their cached view
    /// is stale.
    build_generation: u64,
}

#[derive(Debug, Clone)]
pub struct EnsureReport {
    pub cells_added: usize,
    pub stars_added: usize,
    pub elapsed: Duration,
}

#[derive(Debug, Clone)]
pub struct DropReport {
    pub cells_dropped: usize,
    pub stars_dropped: usize,
    pub elapsed: Duration,
}

impl<S: IndexSource> LiveIndex<S> {
    pub fn open(source: S) -> Self {
        Self {
            source,
            loaded: HashMap::new(),
            star_forest: KdForest::new(),
            code_forest: KdForest::new(),
            build_generation: 0,
        }
    }

    pub fn source(&self) -> &S {
        &self.source
    }

    pub fn build_generation(&self) -> u64 {
        self.build_generation
    }

    pub fn loaded_cells(&self) -> impl Iterator<Item = &HealpixCell> {
        self.loaded.keys()
    }

    pub fn loaded_star_count(&self) -> usize {
        self.loaded.values().map(|c| c.stars.len()).sum()
    }

    pub fn loaded_quad_count(&self) -> usize {
        self.loaded.values().map(|c| c.quads.len()).sum()
    }

    pub fn loaded_cell_count(&self) -> usize {
        self.loaded.len()
    }

    /// Borrow as a `KdForest<3>` over star unit-vectors. Useful when a
    /// consumer wants to query the live tree directly without
    /// flattening to a concrete `Index`.
    pub fn star_forest(&self) -> &KdForest<3> {
        &self.star_forest
    }

    pub fn code_forest(&self) -> &KdForest<{ DIMCODES }> {
        &self.code_forest
    }

    /// Ensure all cells intersecting `region` are loaded. Existing cells
    /// are kept; only the delta is loaded from the source.
    pub fn ensure_region(&mut self, region: &SkyRegion) -> io::Result<EnsureReport> {
        let start = Instant::now();
        let wanted = self.source.cells_intersecting(region);
        let to_add: Vec<HealpixCell> = wanted
            .into_iter()
            .filter(|c| !self.loaded.contains_key(c))
            .collect();
        if to_add.is_empty() {
            return Ok(EnsureReport {
                cells_added: 0,
                stars_added: 0,
                elapsed: start.elapsed(),
            });
        }
        let stars_added = self.add_cells(&to_add)?;
        Ok(EnsureReport {
            cells_added: to_add.len(),
            stars_added,
            elapsed: start.elapsed(),
        })
    }

    /// Drop all cells NOT intersecting `region`.
    pub fn drop_outside(&mut self, region: &SkyRegion) -> DropReport {
        let start = Instant::now();
        let keep: HashSet<HealpixCell> =
            self.source.cells_intersecting(region).into_iter().collect();
        let to_drop: Vec<HealpixCell> = self
            .loaded
            .keys()
            .filter(|c| !keep.contains(c))
            .copied()
            .collect();
        let mut stars_dropped = 0;
        for cell in &to_drop {
            stars_dropped += self.remove_cell(cell);
        }
        DropReport {
            cells_dropped: to_drop.len(),
            stars_dropped,
            elapsed: start.elapsed(),
        }
    }

    /// Drop the specified cells. `HealpixCell` carries `(depth, id)`;
    /// only cells matching exactly are removed.
    pub fn drop_cells(&mut self, cells: &[HealpixCell]) -> DropReport {
        let start = Instant::now();
        let mut dropped_count = 0;
        let mut stars_dropped = 0;
        for cell in cells {
            let removed = self.remove_cell(cell);
            if removed > 0 {
                dropped_count += 1;
                stars_dropped += removed;
            }
        }
        DropReport {
            cells_dropped: dropped_count,
            stars_dropped,
            elapsed: start.elapsed(),
        }
    }

    /// Replace the loaded set with exactly the cells covering `region`.
    /// Atomic from the caller's perspective: if the load fails, the
    /// previous loaded set is preserved.
    pub fn set_region(&mut self, region: &SkyRegion) -> io::Result<EnsureReport> {
        let start = Instant::now();
        let wanted: HashSet<HealpixCell> =
            self.source.cells_intersecting(region).into_iter().collect();
        let to_add: Vec<HealpixCell> = wanted
            .iter()
            .filter(|c| !self.loaded.contains_key(c))
            .copied()
            .collect();
        let to_drop: Vec<HealpixCell> = self
            .loaded
            .keys()
            .filter(|c| !wanted.contains(c))
            .copied()
            .collect();

        // Add first so a load failure leaves us in the prior state.
        let stars_added = if to_add.is_empty() {
            0
        } else {
            self.add_cells(&to_add)?
        };
        for cell in &to_drop {
            self.remove_cell(cell);
        }
        Ok(EnsureReport {
            cells_added: to_add.len(),
            stars_added,
            elapsed: start.elapsed(),
        })
    }

    /// Stage all sub-trees + per-cell payload into a local vector. If
    /// any cell load fails, return Err *without* having mutated `self`.
    /// Then commit everything in one pass on success.
    ///
    /// Loading is per-cell because `IndexSource::load_cells` returns the
    /// union as a single `IndexFragment` without per-cell offsets. For
    /// `ZdclFile` that means N+1 walks of the quads block where 1 would
    /// suffice — accepted in v1 since add/drop happens at human
    /// timescales. Extend `IndexFragment` with per-cell offsets if this
    /// ever becomes a hotspot.
    fn add_cells(&mut self, cells: &[HealpixCell]) -> io::Result<usize> {
        let mut staged: Vec<(HealpixCell, LoadedCell, KdTree<3>, KdTree<{ DIMCODES }>)> =
            Vec::with_capacity(cells.len());
        let mut total_stars_added = 0;

        for &cell in cells {
            let frag: IndexFragment = self.source.load_cells(std::slice::from_ref(&cell))?;
            let n_stars = frag.stars.len();
            if n_stars == 0 && frag.quads.is_empty() {
                continue;
            }
            let star_points: Vec<[f64; 3]> = frag
                .stars
                .iter()
                .map(|s| radec_to_xyz(s.ra, s.dec))
                .collect();
            let star_indices: Vec<usize> = (0..n_stars).collect();
            let star_tree = KdTree::<3>::build(star_points, star_indices);

            let code_indices: Vec<usize> = (0..frag.codes.len()).collect();
            let code_tree = KdTree::<{ DIMCODES }>::build(frag.codes.clone(), code_indices);

            staged.push((
                cell,
                LoadedCell {
                    stars: frag.stars,
                    quads: frag.quads,
                    codes: frag.codes,
                    last_used: Instant::now(),
                },
                star_tree,
                code_tree,
            ));
            total_stars_added += n_stars;
        }

        // Commit phase — only runs if every cell loaded successfully.
        for (cell, payload, star_tree, code_tree) in staged {
            self.star_forest.insert(cell.id, star_tree);
            self.code_forest.insert(cell.id, code_tree);
            self.loaded.insert(cell, payload);
        }
        if total_stars_added > 0 {
            self.build_generation += 1;
        }
        Ok(total_stars_added)
    }

    fn remove_cell(&mut self, cell: &HealpixCell) -> usize {
        let stars_removed = match self.loaded.remove(cell) {
            Some(c) => c.stars.len(),
            None => return 0,
        };
        self.star_forest.remove(cell.id);
        self.code_forest.remove(cell.id);
        self.build_generation += 1;
        stars_removed
    }

    /// Flatten the loaded cells into a single `Index` with rebuilt
    /// flat KdTrees. Used by callers that need the existing concrete-
    /// `Index` solver/refine APIs.
    ///
    /// **Cost: O(N log N)** in the loaded star count from the tree
    /// rebuilds. Call sparingly; the realtime path queries the
    /// `KdForest`s directly.
    ///
    /// Cells are flattened in `cell.id` ascending order so the
    /// resulting `Index.stars` ordering — and hence quad indices — is
    /// deterministic across runs (HashMap iteration order is not).
    pub fn as_index(&self) -> Index {
        let mut stars: Vec<IndexStar> = Vec::with_capacity(self.loaded_star_count());
        let mut quads: Vec<Quad> = Vec::with_capacity(self.loaded_quad_count());
        let mut codes: Vec<Code> = Vec::with_capacity(self.loaded_quad_count());

        let mut cells_sorted: Vec<&HealpixCell> = self.loaded.keys().collect();
        cells_sorted.sort_by_key(|c| (c.depth, c.id));

        for key in cells_sorted {
            let cell = &self.loaded[key];
            let base = stars.len();
            for s in &cell.stars {
                stars.push(s.clone());
            }
            for q in &cell.quads {
                let mut new_ids = [0usize; DIMQUADS];
                for (i, &sid) in q.star_ids.iter().enumerate() {
                    new_ids[i] = sid + base;
                }
                quads.push(Quad { star_ids: new_ids });
            }
            for c in &cell.codes {
                codes.push(*c);
            }
        }

        let star_points: Vec<[f64; 3]> = stars.iter().map(|s| radec_to_xyz(s.ra, s.dec)).collect();
        let star_idx: Vec<usize> = (0..stars.len()).collect();
        let star_tree = KdTree::<3>::build(star_points, star_idx);
        let code_idx: Vec<usize> = (0..codes.len()).collect();
        let code_tree = KdTree::<{ DIMCODES }>::build(codes, code_idx);

        let (scale_lower, scale_upper) = self.source.scale_range();
        Index {
            star_tree,
            stars,
            code_tree,
            quads,
            scale_lower,
            scale_upper,
            metadata: self.source.metadata().cloned(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::index::{HealpixCell, IndexFragment, IndexMetadata, IndexSource};
    use crate::kdtree::KdQueryable;
    use crate::quads::{DIMQUADS, Quad};
    use std::sync::Mutex;

    /// In-memory `IndexSource` for tests: stores a flat list of
    /// (HealpixCell, stars, quads, codes) and answers `cells_intersecting`
    /// by comparing each cell's first-star RA/Dec against the region.
    struct MockSource {
        cells: Vec<MockCell>,
        scale_lower: f64,
        scale_upper: f64,
        load_count: Mutex<usize>,
    }

    struct MockCell {
        cell: HealpixCell,
        center_ra: f64,
        center_dec: f64,
        stars: Vec<IndexStar>,
        quads: Vec<Quad>,
        codes: Vec<Code>,
    }

    impl IndexSource for MockSource {
        fn cells_intersecting(&self, region: &SkyRegion) -> Vec<HealpixCell> {
            self.cells
                .iter()
                .filter(|c| region.contains(c.center_ra, c.center_dec))
                .map(|c| c.cell)
                .collect()
        }
        fn load_cells(&self, cells: &[HealpixCell]) -> io::Result<IndexFragment> {
            let mut count = self.load_count.lock().unwrap();
            *count += 1;
            drop(count);
            let mut stars = Vec::new();
            let mut quads = Vec::new();
            let mut codes = Vec::new();
            for cell in cells {
                if let Some(mc) = self.cells.iter().find(|c| c.cell == *cell) {
                    let base = stars.len();
                    stars.extend(mc.stars.iter().cloned());
                    for q in &mc.quads {
                        let mut new_ids = [0usize; DIMQUADS];
                        for (i, &sid) in q.star_ids.iter().enumerate() {
                            new_ids[i] = sid + base;
                        }
                        quads.push(Quad { star_ids: new_ids });
                    }
                    codes.extend(mc.codes.iter().copied());
                }
            }
            Ok(IndexFragment {
                stars,
                quads,
                codes,
                scale_lower: self.scale_lower,
                scale_upper: self.scale_upper,
                metadata: None,
            })
        }
        fn cell_depth(&self) -> u8 {
            5
        }
        fn metadata(&self) -> Option<&IndexMetadata> {
            None
        }
        fn star_count(&self) -> usize {
            self.cells.iter().map(|c| c.stars.len()).sum()
        }
        fn quad_count(&self) -> usize {
            self.cells.iter().map(|c| c.quads.len()).sum()
        }
        fn scale_range(&self) -> (f64, f64) {
            (self.scale_lower, self.scale_upper)
        }
    }

    fn make_mock_source() -> MockSource {
        let mut cells = Vec::new();
        // Three cells at three different positions on the sky.
        for (cell_id, (ra, dec)) in [
            (0u64, (0.5_f64, 0.3_f64)),
            (1u64, (1.5, -0.1)),
            (2u64, (3.0, 0.5)),
        ] {
            let mut stars = Vec::new();
            for i in 0..6 {
                let frac = i as f64 / 6.0;
                stars.push(IndexStar {
                    catalog_id: cell_id * 1000 + i as u64,
                    ra: ra + frac * 0.005,
                    dec: dec + frac * 0.005,
                    mag: 5.0 + frac,
                });
            }
            cells.push(MockCell {
                cell: HealpixCell {
                    depth: 5,
                    id: cell_id,
                },
                center_ra: ra,
                center_dec: dec,
                stars,
                quads: Vec::new(),
                codes: Vec::new(),
            });
        }
        MockSource {
            cells,
            scale_lower: 0.001,
            scale_upper: 0.05,
            load_count: Mutex::new(0),
        }
    }

    #[test]
    fn open_starts_empty() {
        let live = LiveIndex::open(make_mock_source());
        assert_eq!(live.loaded_cell_count(), 0);
        assert_eq!(live.loaded_star_count(), 0);
        assert_eq!(live.build_generation(), 0);
    }

    #[test]
    fn ensure_region_loads_intersecting_cells() {
        let mut live = LiveIndex::open(make_mock_source());
        // Region covering cells 0 and 1 (both around RA~0.5..1.5).
        let region = SkyRegion::from_radians(starfield::Equatorial::new(1.0, 0.1), 0.6);
        let report = live.ensure_region(&region).unwrap();
        assert_eq!(report.cells_added, 2);
        assert_eq!(report.stars_added, 12);
        assert_eq!(live.loaded_star_count(), 12);
        assert_eq!(live.build_generation(), 1);
    }

    #[test]
    fn ensure_region_idempotent() {
        let mut live = LiveIndex::open(make_mock_source());
        let region = SkyRegion::from_radians(starfield::Equatorial::new(0.5, 0.3), 0.05);
        let r1 = live.ensure_region(&region).unwrap();
        let gen_after_first = live.build_generation();
        let r2 = live.ensure_region(&region).unwrap();
        assert!(r1.cells_added > 0);
        assert_eq!(r2.cells_added, 0);
        assert_eq!(r2.stars_added, 0);
        assert_eq!(live.build_generation(), gen_after_first);
    }

    #[test]
    fn drop_outside_compacts() {
        let mut live = LiveIndex::open(make_mock_source());
        // Load everything.
        let all_sky =
            SkyRegion::from_radians(starfield::Equatorial::new(0.0, 0.0), std::f64::consts::PI);
        live.ensure_region(&all_sky).unwrap();
        assert_eq!(live.loaded_cell_count(), 3);

        // Drop everything outside a tight region around cell 0.
        let tight = SkyRegion::from_radians(starfield::Equatorial::new(0.5, 0.3), 0.05);
        let report = live.drop_outside(&tight);
        assert!(report.cells_dropped >= 2);
        assert!(live.loaded_cell_count() <= 1);
    }

    #[test]
    fn set_region_replaces_membership() {
        let mut live = LiveIndex::open(make_mock_source());
        let region_a = SkyRegion::from_radians(starfield::Equatorial::new(0.5, 0.3), 0.05);
        live.set_region(&region_a).unwrap();
        let cells_before: HashSet<HealpixCell> = live.loaded_cells().copied().collect();

        let region_b = SkyRegion::from_radians(starfield::Equatorial::new(3.0, 0.5), 0.05);
        live.set_region(&region_b).unwrap();
        let cells_after: HashSet<HealpixCell> = live.loaded_cells().copied().collect();

        assert_ne!(cells_before, cells_after);
        assert!(!cells_after.is_empty());
    }

    #[test]
    fn build_generation_increments_on_change() {
        let mut live = LiveIndex::open(make_mock_source());
        let g0 = live.build_generation();
        let region = SkyRegion::from_radians(starfield::Equatorial::new(0.5, 0.3), 0.05);
        live.ensure_region(&region).unwrap();
        let g1 = live.build_generation();
        assert!(g1 > g0);
        // Idempotent ensure should not bump.
        live.ensure_region(&region).unwrap();
        assert_eq!(g1, live.build_generation());
        // Drop should bump.
        let nowhere = SkyRegion::from_radians(starfield::Equatorial::new(5.0, 1.5), 0.001);
        live.drop_outside(&nowhere);
        assert!(live.build_generation() > g1);
    }

    #[test]
    fn star_forest_query_unions_subtrees() {
        let mut live = LiveIndex::open(make_mock_source());
        let all_sky =
            SkyRegion::from_radians(starfield::Equatorial::new(0.0, 0.0), std::f64::consts::PI);
        live.ensure_region(&all_sky).unwrap();

        // The forest should expose a union view across all sub-trees.
        let total_via_forest = live.star_forest().len();
        assert_eq!(total_via_forest, live.loaded_star_count());

        // A nearest query should find a hit somewhere across the forest.
        let center = radec_to_xyz(0.5, 0.3);
        let hit = live.star_forest().nearest(&center);
        assert!(hit.is_some());
    }

    /// IndexSource that fails on `load_cells` for one specific cell id.
    /// Used to verify atomicity guarantees in `add_cells` / `set_region`.
    struct FailingSource {
        inner: MockSource,
        fail_on_cell_id: u64,
    }
    impl IndexSource for FailingSource {
        fn cells_intersecting(&self, region: &SkyRegion) -> Vec<HealpixCell> {
            self.inner.cells_intersecting(region)
        }
        fn load_cells(&self, cells: &[HealpixCell]) -> io::Result<IndexFragment> {
            for c in cells {
                if c.id == self.fail_on_cell_id {
                    return Err(io::Error::other(format!(
                        "simulated failure on cell {}",
                        c.id
                    )));
                }
            }
            self.inner.load_cells(cells)
        }
        fn cell_depth(&self) -> u8 {
            self.inner.cell_depth()
        }
        fn metadata(&self) -> Option<&IndexMetadata> {
            self.inner.metadata()
        }
        fn star_count(&self) -> usize {
            self.inner.star_count()
        }
        fn quad_count(&self) -> usize {
            self.inner.quad_count()
        }
        fn scale_range(&self) -> (f64, f64) {
            self.inner.scale_range()
        }
    }

    #[test]
    fn add_cells_failure_leaves_state_untouched() {
        // Configure: source has 3 cells; load_cells fails when called
        // for cell id 2. Ensure a region covering all cells, then
        // verify state == empty (atomic failure).
        let source = FailingSource {
            inner: make_mock_source(),
            fail_on_cell_id: 2,
        };
        let mut live = LiveIndex::open(source);
        let all_sky =
            SkyRegion::from_radians(starfield::Equatorial::new(0.0, 0.0), std::f64::consts::PI);
        let cells = live.source().cells_intersecting(&all_sky);
        assert!(
            cells.iter().any(|c| c.id == 2),
            "test fixture must include the failing cell"
        );

        let result = live.ensure_region(&all_sky);
        assert!(result.is_err(), "load should fail");
        // Atomicity: nothing committed.
        assert_eq!(live.loaded_cell_count(), 0);
        assert_eq!(live.loaded_star_count(), 0);
        assert_eq!(live.build_generation(), 0);
    }

    #[test]
    fn set_region_failure_preserves_prior_state() {
        // Load cell 0 first, then attempt to swap to a region covering
        // cell 2 (which fails). Cell 0 should still be present and
        // build_generation unchanged from after the first load.
        let source = FailingSource {
            inner: make_mock_source(),
            fail_on_cell_id: 2,
        };
        let mut live = LiveIndex::open(source);
        let region_a = SkyRegion::from_radians(starfield::Equatorial::new(0.5, 0.3), 0.05);
        live.set_region(&region_a).unwrap();
        let gen_before = live.build_generation();
        let cells_before: HashSet<HealpixCell> = live.loaded_cells().copied().collect();

        let region_b = SkyRegion::from_radians(starfield::Equatorial::new(3.0, 0.5), 0.05);
        let result = live.set_region(&region_b);
        assert!(result.is_err(), "load on cell 2 should fail");
        // Prior state preserved, no drops happened.
        let cells_after: HashSet<HealpixCell> = live.loaded_cells().copied().collect();
        assert_eq!(cells_before, cells_after);
        assert_eq!(live.build_generation(), gen_before);
    }

    #[test]
    fn drop_cells_removes_only_the_named_ones() {
        let mut live = LiveIndex::open(make_mock_source());
        let all_sky =
            SkyRegion::from_radians(starfield::Equatorial::new(0.0, 0.0), std::f64::consts::PI);
        live.ensure_region(&all_sky).unwrap();
        let before = live.loaded_cell_count();
        let target = HealpixCell { depth: 5, id: 1 };
        let report = live.drop_cells(&[target]);
        assert_eq!(report.cells_dropped, 1);
        assert_eq!(live.loaded_cell_count(), before - 1);
        assert!(live.loaded_cells().all(|c| *c != target));
    }

    #[test]
    fn drop_cells_ignores_unknown_cells() {
        let mut live = LiveIndex::open(make_mock_source());
        let region = SkyRegion::from_radians(starfield::Equatorial::new(0.5, 0.3), 0.05);
        live.ensure_region(&region).unwrap();
        let before = live.loaded_cell_count();
        let unknown = HealpixCell { depth: 5, id: 9999 };
        let report = live.drop_cells(&[unknown]);
        assert_eq!(report.cells_dropped, 0);
        assert_eq!(report.stars_dropped, 0);
        assert_eq!(live.loaded_cell_count(), before);
    }

    #[test]
    fn kd_forest_insert_replaces_existing_tag() {
        // Inserting a tag that's already present should drop the prior
        // sub-tree first, not duplicate it.
        let pts_a: Vec<[f64; 2]> = vec![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]];
        let pts_b: Vec<[f64; 2]> = vec![[10.0, 10.0]];
        let tree_a = KdTree::<2>::build(pts_a, vec![0, 1, 2]);
        let tree_b = KdTree::<2>::build(pts_b, vec![0]);

        let mut forest: KdForest<2> = KdForest::new();
        forest.insert(42, tree_a);
        assert_eq!(forest.len(), 3);
        forest.insert(42, tree_b); // same tag — should replace
        assert_eq!(forest.len(), 1);
        assert_eq!(forest.sub_tree_count(), 1);
        // Confirm only the replacement's content is present.
        let near_origin = forest.range_search(&[0.0, 0.0], 0.5);
        assert!(near_origin.is_empty());
        let near_b = forest.range_search(&[10.0, 10.0], 0.5);
        assert_eq!(near_b.len(), 1);
    }

    #[test]
    fn as_index_flattens_loaded_set() {
        let mut live = LiveIndex::open(make_mock_source());
        let region =
            SkyRegion::from_radians(starfield::Equatorial::new(0.0, 0.0), std::f64::consts::PI);
        live.ensure_region(&region).unwrap();

        let idx = live.as_index();
        assert_eq!(idx.stars.len(), live.loaded_star_count());
        assert_eq!(idx.star_tree.len(), idx.stars.len());
        // Quad indices in the flattened Index must be in-bounds for stars.
        for q in &idx.quads {
            for &sid in &q.star_ids {
                assert!(sid < idx.stars.len());
            }
        }
    }
}