diffctx 1.12.3

Selects the minimum code an LLM needs to review a git diff: walks the dependency graph outward from changed lines and stops when extra context stops paying for itself
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::sync::Arc;

use rustc_hash::{FxHashMap, FxHashSet};

use crate::config::limits::UTILITY;
use crate::config::selection::selection;
use crate::interval::IntervalIndex;
use crate::types::{Fragment, FragmentId};
use crate::utility::needs::InformationNeed;
use crate::utility::scoring::{
    UtilityState, apply_fragment, compute_density, marginal_gain, utility_value,
};

const SENTINEL_TOKEN_COUNT: u32 = 1_000_000_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionReason {
    TopK,
    NoCandidates,
    BudgetExhausted,
    NoUtility,
    StoppedByTau,
    BestSingleton,
}

impl SelectionReason {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::TopK => "topk",
            Self::NoCandidates => "no_candidates",
            Self::BudgetExhausted => "budget_exhausted",
            Self::NoUtility => "no_utility",
            Self::StoppedByTau => "stopped_by_tau",
            Self::BestSingleton => "best_singleton",
        }
    }
}

pub struct SelectionResult {
    pub selected: Vec<Fragment>,
    pub reason: SelectionReason,
    pub used_tokens: u32,
    pub utility: f64,
    /// Greedy iterations actually executed (number of `apply_fragment`
    /// calls in `run_greedy_loop_heap`). Diagnoses lazy-heap blowup:
    /// expected ≈ output size, pathological ≫ output size when
    /// stale-version rejections dominate.
    pub greedy_iters: usize,
    /// Additive certificate for adaptive stopping: an upper bound
    /// (`tau * peak_density * remaining_budget`) on the utility that
    /// continuing the same greedy to the feasibility frontier could
    /// still have added. 0 when the loop ended for any other reason.
    pub stopping_certificate: f64,
}

struct HeapEntry {
    neg_density: f64,
    frag_id: FragmentId,
    version: u32,
}

impl PartialEq for HeapEntry {
    fn eq(&self, other: &Self) -> bool {
        self.neg_density.to_bits() == other.neg_density.to_bits() && self.frag_id == other.frag_id
    }
}

impl Eq for HeapEntry {}

impl PartialOrd for HeapEntry {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for HeapEntry {
    fn cmp(&self, other: &Self) -> Ordering {
        other
            .neg_density
            .total_cmp(&self.neg_density)
            .then_with(|| other.frag_id.cmp(&self.frag_id))
    }
}

struct SelectionState {
    selected: Vec<Fragment>,
    selected_ids: IntervalIndex,
    remaining_budget: u32,
    utility_state: UtilityState,
}

fn drop_redundant_signatures(candidates: &[Fragment], budget: u32) -> Vec<Fragment> {
    let mut full_token_by_loc: FxHashMap<(Arc<str>, u32), u32> = FxHashMap::default();
    for f in candidates {
        if !f.kind.is_signature() {
            // Keep the LARGEST co-located full fragment, not the last one seen.
            // Two non-signature fragments can share a start line (a class header
            // `Definition` at [10,12] and the full class at [10,300]), and with a
            // plain `insert` whichever came last in the candidate vec won the
            // slot. When the small header won, the class's stub was filtered out
            // as "redundant" precisely when the full class did not fit and the
            // stub was its only affordable representation — and the outcome
            // depended on vec order rather than on anything meaningful.
            full_token_by_loc
                .entry((f.id.path.clone(), f.start_line()))
                .and_modify(|t| *t = (*t).max(f.token_count))
                .or_insert(f.token_count);
        }
    }
    candidates
        .iter()
        .filter(|f| {
            if !f.kind.is_signature() {
                return true;
            }
            let key = (f.id.path.clone(), f.start_line());
            full_token_by_loc
                .get(&key)
                .copied()
                .unwrap_or(SENTINEL_TOKEN_COUNT)
                > budget
        })
        .cloned()
        .collect()
}

fn compute_r_cap(
    rel: &FxHashMap<FragmentId, f64>,
    core_ids: Option<&FxHashSet<FragmentId>>,
) -> f64 {
    let values: Vec<f64> = rel
        .iter()
        .filter(|(fid, v)| **v > 0.0 && core_ids.map_or(true, |c| !c.contains(*fid)))
        .map(|(_, v)| *v)
        .collect();

    if values.len() < 2 {
        return if let Some(&v) = values.first() {
            v.max(selection().r_cap_min)
        } else {
            1.0
        };
    }

    let mut sorted = values.clone();
    sorted.sort_by(|a, b| a.total_cmp(b));
    let mid = sorted.len() / 2;
    let med = if sorted.len() % 2 == 0 {
        (sorted[mid - 1] + sorted[mid]) / 2.0
    } else {
        sorted[mid]
    };

    let mean: f64 = values.iter().sum::<f64>() / values.len() as f64;
    let variance: f64 =
        values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (values.len() - 1) as f64;
    let std = variance.sqrt();

    (med + UTILITY.r_cap_sigma * std).max(1e-9)
}

fn build_signature_lookup(
    fragments: &[Fragment],
    core_fragments: &[Fragment],
    core_excerpts: Option<&FxHashMap<FragmentId, Fragment>>,
) -> FxHashMap<FragmentId, Fragment> {
    let mut sig_by_loc: FxHashMap<(Arc<str>, u32), Fragment> = FxHashMap::default();
    for f in fragments {
        if f.kind.is_signature() {
            sig_by_loc.insert((f.id.path.clone(), f.start_line()), f.clone());
        }
    }
    let mut sig_lookup = FxHashMap::default();
    for cf in core_fragments {
        let key = (cf.id.path.clone(), cf.start_line());
        if let Some(sig) = sig_by_loc.get(&key) {
            sig_lookup.insert(cf.id.clone(), sig.clone());
            continue;
        }
        // Kinds without a signature (chunk, section) fall back to the excerpt
        // around the hunk; without it an oversized core is skipped outright and
        // the change signal disappears from the output (#103).
        if let Some(excerpt) = core_excerpts.and_then(|e| e.get(&cf.id)) {
            sig_lookup.insert(cf.id.clone(), excerpt.clone());
        }
    }
    sig_lookup
}

fn select_core_fragments(
    core_fragments: &[Fragment],
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    state: &mut SelectionState,
    budget_tokens: u32,
    sig_lookup: &FxHashMap<FragmentId, Fragment>,
) {
    let core_budget = (budget_tokens as f64 * selection().core_budget_fraction) as u32;
    // Counter for cores placed; the first pass keeps `core_used <= core_budget`,
    // but the rescue pass below intentionally allows it to exceed `core_budget`
    // up to `budget_tokens`. Don't assume the tighter bound past this scope.
    let mut core_used = 0u32;

    let mut sorted_core: Vec<&Fragment> = core_fragments.iter().collect();
    sorted_core.sort_by(|a, b| {
        let ra = rel.get(&a.id).copied().unwrap_or(0.0);
        let rb = rel.get(&b.id).copied().unwrap_or(0.0);
        rb.total_cmp(&ra)
    });

    let place_fragment =
        |frag: &Fragment, core_used: &mut u32, state: &mut SelectionState, rel_score: f64| {
            state.selected.push(frag.clone());
            state.selected_ids.add_id(&frag.id);
            state.remaining_budget = state.remaining_budget.saturating_sub(frag.token_count);
            *core_used += frag.token_count;
            apply_fragment(frag, rel_score, needs, &mut state.utility_state);
        };

    let mut skipped: Vec<&Fragment> = Vec::new();
    for frag in &sorted_core {
        if state.selected_ids.is_superset_of(frag) {
            continue;
        }
        if core_used + frag.token_count > core_budget {
            if let Some(sig) = sig_lookup.get(&frag.id) {
                if !state.selected_ids.contains(&sig.id)
                    && core_used + sig.token_count <= core_budget
                {
                    let rel_score = rel.get(&frag.id).copied().unwrap_or(0.0);
                    place_fragment(sig, &mut core_used, state, rel_score);
                    continue;
                }
            }
            skipped.push(frag);
            continue;
        }

        let rel_score = rel.get(&frag.id).copied().unwrap_or(0.0);
        place_fragment(frag, &mut core_used, state, rel_score);
    }

    // Bug #2 fix: cores that didn't fit the core_budget reservation must not be
    // demoted to ordinary greedy candidates without a chance to be placed first.
    // Sweep skipped cores cheapest-first against the *full* remaining budget
    // (not just the core slice) so seeds aren't dropped purely because the
    // highest-relevance core happened to be heavy.
    if !skipped.is_empty() {
        skipped.sort_by(|a, b| a.token_count.cmp(&b.token_count));
        for frag in skipped {
            if state.remaining_budget == 0 {
                break;
            }
            if state.selected_ids.is_superset_of(frag) {
                continue;
            }
            if frag.token_count <= state.remaining_budget {
                let rel_score = rel.get(&frag.id).copied().unwrap_or(0.0);
                place_fragment(frag, &mut core_used, state, rel_score);
            } else if let Some(sig) = sig_lookup.get(&frag.id) {
                if !state.selected_ids.contains(&sig.id)
                    && sig.token_count <= state.remaining_budget
                {
                    let rel_score = rel.get(&frag.id).copied().unwrap_or(0.0);
                    place_fragment(sig, &mut core_used, state, rel_score);
                }
            }
        }
    }
}

fn build_initial_heap(
    candidates: &[Fragment],
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    state: &UtilityState,
    id_to_frag: &mut FxHashMap<FragmentId, Fragment>,
) -> BinaryHeap<HeapEntry> {
    let mut heap = BinaryHeap::new();
    for frag in candidates {
        if frag.token_count > 0 {
            let density = compute_density(
                frag,
                rel.get(&frag.id).copied().unwrap_or(0.0),
                needs,
                state,
            );
            heap.push(HeapEntry {
                neg_density: -density,
                frag_id: frag.id.clone(),
                version: 0,
            });
            id_to_frag.insert(frag.id.clone(), frag.clone());
        }
    }
    heap
}

fn find_best_candidate_heap(
    heap: &mut BinaryHeap<HeapEntry>,
    current_version: u32,
    id_to_frag: &FxHashMap<FragmentId, Fragment>,
    selected_ids: &IntervalIndex,
    remaining_budget: u32,
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    state: &UtilityState,
) -> (Option<Fragment>, f64, u32) {
    let cv = current_version;
    while let Some(entry) = heap.pop() {
        let frag = match id_to_frag.get(&entry.frag_id) {
            Some(f) => f,
            None => continue,
        };
        if frag.token_count > remaining_budget {
            continue;
        }
        if selected_ids.overlaps(frag) {
            continue;
        }
        if entry.version < cv {
            let new_density = compute_density(
                frag,
                rel.get(&frag.id).copied().unwrap_or(0.0),
                needs,
                state,
            );
            heap.push(HeapEntry {
                neg_density: -new_density,
                frag_id: frag.id.clone(),
                version: cv,
            });
            continue;
        }
        let actual_density = -entry.neg_density;
        if actual_density <= 0.0 {
            return (None, 0.0, cv);
        }
        return (Some(frag.clone()), actual_density, cv + 1);
    }
    (None, 0.0, cv)
}

fn find_best_singleton(
    non_core: &[Fragment],
    base_selected_ids: &IntervalIndex,
    base_budget: u32,
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    base_state: &UtilityState,
) -> (Option<Fragment>, f64) {
    let mut best_singleton = None;
    let mut best_gain = 0.0;
    for f in non_core {
        if f.token_count > base_budget {
            continue;
        }
        if base_selected_ids.overlaps(f) {
            continue;
        }
        let gain = marginal_gain(f, rel.get(&f.id).copied().unwrap_or(0.0), needs, base_state);
        if gain > best_gain {
            best_gain = gain;
            best_singleton = Some(f.clone());
        }
    }
    (best_singleton, best_gain)
}

/// Paper-aligned strict Khuller H₁: `argmax_{f ∈ F, |f| ≤ B} U({f})`.
/// Iterates the FULL ground set (including core), gates on the FULL
/// budget B (not the residual after partial-core packing), and evaluates
/// each candidate as a lone selection against an empty utility state.
///
/// This is the comparator that, together with the greedy chain, gives
/// the `(1-1/e)/2` approximation guarantee from Khuller-Moss-Naor 1999
/// for monotone submodular maximization under a knapsack constraint.
/// Restricting H₁ to `non_core` with budget `B − cost(packed_core)`
/// (the prior `find_best_singleton`) is a strict relaxation that
/// excludes any single high-utility fragment with `|f| > B − β_core·B`.
fn find_best_singleton_full_set(
    fragments: &[Fragment],
    budget_tokens: u32,
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    empty_state: &UtilityState,
) -> (Option<Fragment>, f64) {
    let mut best = None;
    let mut best_gain = 0.0;
    for f in fragments {
        if f.token_count == 0 || f.token_count > budget_tokens {
            continue;
        }
        let gain = marginal_gain(
            f,
            rel.get(&f.id).copied().unwrap_or(0.0),
            needs,
            empty_state,
        );
        if gain > best_gain {
            best_gain = gain;
            best = Some(f.clone());
        }
    }
    (best, best_gain)
}

fn init_selection_state(
    core_ids: &FxHashSet<FragmentId>,
    rel: &FxHashMap<FragmentId, f64>,
    budget_tokens: u32,
    file_importance: Option<&FxHashMap<Arc<str>, f64>>,
) -> SelectionState {
    let mut utility_state = UtilityState::default();
    utility_state.r_cap = compute_r_cap(rel, Some(core_ids));
    utility_state.changed_dirs = core_ids
        .iter()
        .filter_map(|cid| {
            std::path::Path::new(cid.path.as_ref())
                .parent()
                .map(|p| p.to_path_buf())
        })
        .collect();
    if let Some(fi) = file_importance {
        utility_state.file_importance.clone_from(fi);
    }
    SelectionState {
        selected: Vec::new(),
        selected_ids: IntervalIndex::new(),
        remaining_budget: budget_tokens,
        utility_state,
    }
}

fn run_greedy_loop_heap(
    heap: &mut BinaryHeap<HeapEntry>,
    id_to_frag: &FxHashMap<FragmentId, Fragment>,
    state: &mut SelectionState,
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    tau: f64,
    _initial_budget: u32,
) -> (usize, f64, usize) {
    let mut current_version = 0u32;
    let mut peak_density: f64 = 0.0;
    let mut loop_iters: usize = 0;

    while !heap.is_empty() && state.remaining_budget > 0 {
        loop_iters += 1;
        let (best_frag, best_density, new_version) = find_best_candidate_heap(
            heap,
            current_version,
            id_to_frag,
            &state.selected_ids,
            state.remaining_budget,
            rel,
            needs,
            &state.utility_state,
        );
        current_version = new_version;

        let best_frag = match best_frag {
            Some(f) => f,
            None => break,
        };
        if best_density <= 0.0 {
            break;
        }

        if best_density > peak_density {
            peak_density = best_density;
        } else if peak_density > 0.0 && best_density < tau * peak_density {
            break;
        }

        state.selected.push(best_frag.clone());
        state.selected_ids.add_id(&best_frag.id);
        state.remaining_budget = state.remaining_budget.saturating_sub(best_frag.token_count);
        let rel_score = rel.get(&best_frag.id).copied().unwrap_or(0.0);
        apply_fragment(&best_frag, rel_score, needs, &mut state.utility_state);
    }

    let threshold = tau * peak_density;
    (state.selected.len(), threshold, loop_iters)
}

fn setup_and_select_core(
    fragments: &[Fragment],
    core_ids: &FxHashSet<FragmentId>,
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    budget_tokens: u32,
    file_importance: Option<&FxHashMap<Arc<str>, f64>>,
    core_excerpts: Option<&FxHashMap<FragmentId, Fragment>>,
) -> (SelectionState, Vec<Fragment>, Vec<Fragment>, bool) {
    let mut core_fragments: Vec<Fragment> = fragments
        .iter()
        .filter(|f| core_ids.contains(&f.id))
        .cloned()
        .collect();
    core_fragments.sort_by(|a, b| {
        let ta = if a.token_count > 0 {
            a.token_count
        } else {
            SENTINEL_TOKEN_COUNT
        };
        let tb = if b.token_count > 0 {
            b.token_count
        } else {
            SENTINEL_TOKEN_COUNT
        };
        ta.cmp(&tb)
            .then(a.line_count().cmp(&b.line_count()))
            .then(a.start_line().cmp(&b.start_line()))
    });

    let non_core_fragments: Vec<Fragment> = fragments
        .iter()
        .filter(|f| !core_ids.contains(&f.id))
        .cloned()
        .collect();

    let sig_lookup = build_signature_lookup(fragments, &core_fragments, core_excerpts);
    let mut state = init_selection_state(core_ids, rel, budget_tokens, file_importance);
    select_core_fragments(
        &core_fragments,
        rel,
        needs,
        &mut state,
        budget_tokens,
        &sig_lookup,
    );

    let selected_core_ids: FxHashSet<FragmentId> =
        state.selected.iter().map(|f| f.id.clone()).collect();
    let skipped_core: Vec<FragmentId> = core_ids
        .iter()
        .filter(|id| !selected_core_ids.contains(*id))
        .cloned()
        .collect();

    let mut non_core_with_skipped = non_core_fragments;
    if !skipped_core.is_empty() {
        let skipped_set: FxHashSet<FragmentId> = skipped_core.into_iter().collect();
        for cf in &core_fragments {
            if skipped_set.contains(&cf.id) {
                non_core_with_skipped.push(cf.clone());
            }
        }
    }

    let should_return_early = state.remaining_budget == 0;
    let selected_copy = state.selected.clone();
    (
        state,
        non_core_with_skipped,
        selected_copy,
        should_return_early,
    )
}

pub fn lazy_greedy_select(
    fragments: Vec<Fragment>,
    core_ids: &FxHashSet<FragmentId>,
    rel: &FxHashMap<FragmentId, f64>,
    needs: &[InformationNeed],
    budget_tokens: u32,
    tau: f64,
    file_importance: Option<&FxHashMap<Arc<str>, f64>>,
    core_excerpts: Option<&FxHashMap<FragmentId, Fragment>>,
) -> SelectionResult {
    if fragments.is_empty() {
        return SelectionResult {
            selected: Vec::new(),
            reason: SelectionReason::NoCandidates,
            used_tokens: 0,
            utility: 0.0,
            greedy_iters: 0,
            stopping_certificate: 0.0,
        };
    }

    let (mut state, non_core_fragments, _selected_core, should_return_early) =
        setup_and_select_core(
            &fragments,
            core_ids,
            rel,
            needs,
            budget_tokens,
            file_importance,
            core_excerpts,
        );

    if should_return_early {
        let used = budget_tokens - state.remaining_budget;
        return SelectionResult {
            selected: state.selected,
            reason: SelectionReason::BudgetExhausted,
            used_tokens: used,
            utility: utility_value(&state.utility_state),
            greedy_iters: 0,
            stopping_certificate: 0.0,
        };
    }

    let base_state = state.utility_state.copy();
    let base_selected = state.selected.clone();
    let base_budget = state.remaining_budget;

    let candidates: Vec<Fragment> = non_core_fragments
        .iter()
        .filter(|f| !state.selected_ids.overlaps(f))
        .cloned()
        .collect();
    let candidates = drop_redundant_signatures(&candidates, state.remaining_budget);

    let mut id_to_frag: FxHashMap<FragmentId, Fragment> = FxHashMap::default();
    let mut heap = build_initial_heap(
        &candidates,
        rel,
        needs,
        &state.utility_state,
        &mut id_to_frag,
    );

    let (_, threshold, greedy_iters) = run_greedy_loop_heap(
        &mut heap,
        &id_to_frag,
        &mut state,
        rel,
        needs,
        tau,
        budget_tokens,
    );

    let greedy_utility = utility_value(&state.utility_state);

    let mut base_selected_ids = IntervalIndex::new();
    for f in &base_selected {
        base_selected_ids.add_id(&f.id);
    }

    let (best_singleton, best_gain) = find_best_singleton(
        &non_core_fragments,
        &base_selected_ids,
        base_budget,
        rel,
        needs,
        &base_state,
    );

    let empty_state = init_selection_state(core_ids, rel, budget_tokens, file_importance);
    let (full_singleton, full_singleton_gain) = find_best_singleton_full_set(
        &fragments,
        budget_tokens,
        rel,
        needs,
        &empty_state.utility_state,
    );

    let mut best_alt_utility = greedy_utility;
    let mut best_alt: Option<(Vec<Fragment>, u32)> = None;

    if let Some(ref singleton) = best_singleton {
        let u = utility_value(&base_state) + best_gain;
        if u > best_alt_utility {
            best_alt_utility = u;
            let used = budget_tokens - (base_budget - singleton.token_count);
            let mut sel = base_selected.clone();
            sel.push(singleton.clone());
            best_alt = Some((sel, used));
        }
    }

    if let Some(ref full) = full_singleton {
        let u = utility_value(&empty_state.utility_state) + full_singleton_gain;
        // Additive on top of the core selection, never a replacement for it.
        // This branch used to return `vec![full]` outright, so a single heavy
        // fragment whose standalone utility beat the greedy chain's discarded
        // every changed-code fragment — the one thing the output exists to
        // carry. `ensure_changed_files_represented` could not reliably undo it
        // either: it only had `budget - full.token_count` left and only picks a
        // fragment that fits. The two utilities are also measured from
        // different baselines (this one from an empty state, `greedy_utility`
        // from the core base), so the comparison can only ever be a heuristic
        // nudge — not grounds for dropping the core.
        if u > best_alt_utility && full.token_count <= base_budget {
            best_alt_utility = u;
            let mut sel = base_selected.clone();
            if !sel.iter().any(|f| f.id == full.id) {
                sel.push(full.clone());
            }
            let used = budget_tokens - (base_budget - full.token_count);
            best_alt = Some((sel, used));
        }
    }

    if let Some((sel, used)) = best_alt {
        return SelectionResult {
            selected: sel,
            reason: SelectionReason::BestSingleton,
            used_tokens: used,
            utility: best_alt_utility,
            greedy_iters,
            stopping_certificate: 0.0,
        };
    }

    let used = budget_tokens - state.remaining_budget;
    let reason = if state.remaining_budget == 0 {
        SelectionReason::BudgetExhausted
    } else if greedy_utility <= 0.0 {
        SelectionReason::NoUtility
    } else if state.selected.is_empty() || state.selected.len() == base_selected.len() {
        SelectionReason::NoCandidates
    } else if threshold > 0.0 && !heap.is_empty() {
        SelectionReason::StoppedByTau
    } else {
        SelectionReason::NoCandidates
    };

    let stopping_certificate = if matches!(reason, SelectionReason::StoppedByTau) {
        threshold * f64::from(state.remaining_budget)
    } else {
        0.0
    };

    SelectionResult {
        selected: state.selected,
        reason,
        used_tokens: used,
        utility: greedy_utility,
        greedy_iters,
        stopping_certificate,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::FragmentKind;

    fn frag(path: &str, start: u32, end: u32, kind: FragmentKind, tokens: u32) -> Fragment {
        let mut identifiers = FxHashSet::default();
        identifiers.insert(format!("sym_{path}_{start}"));
        Fragment {
            id: FragmentId::new(Arc::from(path), start, end),
            kind,
            content: Arc::from(format!("// {path}:{start}-{end}\n")),
            identifiers,
            token_count: tokens,
            symbol_name: Some(format!("sym_{start}")),
        }
    }

    fn rel_map(frags: &[Fragment], score: f64) -> FxHashMap<FragmentId, f64> {
        frags.iter().map(|f| (f.id.clone(), score)).collect()
    }

    fn cost_of(selected: &[Fragment]) -> u32 {
        selected.iter().map(|f| f.token_count).sum()
    }

    /// The budget is a hard contract (`cost(C) <= B`); four separate call sites
    /// gate on it and none of them was asserted. A `pick_smallest_fitting` that
    /// returns a non-fitting candidate is one `if` away, and the oracle corpus
    /// can never catch it because its budget is always >=2.5x the whole repo.
    #[test]
    fn selection_never_exceeds_the_budget() {
        let frags: Vec<Fragment> = (0..12)
            .map(|i| {
                frag(
                    "a.rs",
                    1 + i * 50,
                    40 + i * 50,
                    FragmentKind::Function,
                    30 + i * 17,
                )
            })
            .collect();
        let core: FxHashSet<FragmentId> = std::iter::once(frags[0].id.clone()).collect();
        let rel = rel_map(&frags, 0.7);

        for budget in [1u32, 7, 30, 31, 60, 200, 1_000] {
            let result =
                lazy_greedy_select(frags.clone(), &core, &rel, &[], budget, 0.12, None, None);
            assert!(
                cost_of(&result.selected) <= budget,
                "budget {budget} overrun: cost {} via {:?}",
                cost_of(&result.selected),
                result.reason
            );
            assert!(
                result.used_tokens <= budget,
                "reported used_tokens {} exceeds budget {budget}",
                result.used_tokens
            );
        }
    }

    #[test]
    fn selected_fragments_never_overlap_and_are_never_duplicated() {
        let frags: Vec<Fragment> = (0..8)
            .map(|i| frag("a.rs", 1 + i * 10, 12 + i * 10, FragmentKind::Function, 25))
            .collect();
        let core: FxHashSet<FragmentId> = std::iter::once(frags[0].id.clone()).collect();
        let rel = rel_map(&frags, 0.9);
        let result = lazy_greedy_select(frags, &core, &rel, &[], 400, 0.12, None, None);

        let ids: FxHashSet<FragmentId> = result.selected.iter().map(|f| f.id.clone()).collect();
        assert_eq!(
            ids.len(),
            result.selected.len(),
            "duplicate fragment selected"
        );
    }

    /// `find_best_singleton_full_set` used to return `vec![full]`, discarding
    /// every core fragment. The core IS the changed code, so a selection that
    /// drops all of it answers a different question than the one asked.
    #[test]
    fn a_winning_singleton_never_evicts_the_core_selection() {
        // A heavy, highly relevant non-core fragment is the shape that makes the
        // full-set singleton win.
        let core_frag = frag("changed.rs", 1, 8, FragmentKind::Function, 20);
        let heavy = frag("other.rs", 1, 400, FragmentKind::Class, 900);
        let filler = frag("other.rs", 500, 520, FragmentKind::Function, 40);
        let frags = vec![core_frag.clone(), heavy.clone(), filler];

        let core: FxHashSet<FragmentId> = std::iter::once(core_frag.id.clone()).collect();
        let mut rel = FxHashMap::default();
        rel.insert(core_frag.id.clone(), 0.05);
        rel.insert(heavy.id.clone(), 1.0);
        rel.insert(frags[2].id.clone(), 0.1);

        let result = lazy_greedy_select(frags, &core, &rel, &[], 2_000, 0.12, None, None);
        assert!(
            result.selected.iter().any(|f| core.contains(&f.id)),
            "no core fragment survived; reason was {:?}",
            result.reason
        );
        assert!(cost_of(&result.selected) <= 2_000);
    }

    #[test]
    fn empty_ground_set_reports_no_candidates() {
        let result = lazy_greedy_select(
            Vec::new(),
            &FxHashSet::default(),
            &FxHashMap::default(),
            &[],
            1_000,
            0.12,
            None,
            None,
        );
        assert!(result.selected.is_empty());
        assert_eq!(result.reason, SelectionReason::NoCandidates);
        assert_eq!(result.used_tokens, 0);
    }

    /// Keyed on `(path, start_line)`, this used to be last-write-wins, so a
    /// small co-located sibling could delete the stub that was the only
    /// affordable representation of an oversized fragment.
    #[test]
    fn drop_redundant_signatures_is_independent_of_candidate_order() {
        let header = frag("a.rs", 10, 12, FragmentKind::Definition, 40);
        let whole = frag("a.rs", 10, 300, FragmentKind::Class, 4_000);
        let stub = frag("a.rs", 10, 11, FragmentKind::ClassSignature, 15);

        let forward =
            drop_redundant_signatures(&[header.clone(), whole.clone(), stub.clone()], 500);
        let backward = drop_redundant_signatures(&[whole, header, stub], 500);

        let kinds = |v: &[Fragment]| -> Vec<FragmentKind> { v.iter().map(|f| f.kind).collect() };
        assert!(
            kinds(&forward).contains(&FragmentKind::ClassSignature),
            "the stub for an unaffordable class was dropped: {:?}",
            kinds(&forward)
        );
        let mut a: Vec<FragmentKind> = kinds(&forward);
        let mut b: Vec<FragmentKind> = kinds(&backward);
        a.sort_by_key(|k| format!("{k:?}"));
        b.sort_by_key(|k| format!("{k:?}"));
        assert_eq!(a, b, "verdict depended on candidate order");
    }

    #[test]
    fn drop_redundant_signatures_removes_a_stub_whose_full_fragment_fits() {
        let whole = frag("a.rs", 10, 40, FragmentKind::Class, 100);
        let stub = frag("a.rs", 10, 11, FragmentKind::ClassSignature, 15);
        let kept = drop_redundant_signatures(&[whole, stub], 500);
        assert!(
            !kept.iter().any(|f| f.kind.is_signature()),
            "stub survived even though the full fragment fits the budget"
        );
    }
    /// tau is the adaptive stop: once a candidate's density falls below
    /// `tau * peak_density` the loop stops instead of spending the rest of the
    /// budget. The whole oracle corpus runs at tau=0.0, which makes the
    /// predicate unreachable, so deleting the rule failed no test. This runs at
    /// the shipped default so the assertion covers the real operating point.
    #[test]
    fn tau_stops_the_greedy_loop_before_the_budget_is_spent() {
        // Descending relevance against escalating cost gives sharply
        // descending density, which is what the stop rule reacts to.
        let frags: Vec<Fragment> = (0..6)
            .map(|i| {
                frag(
                    "a.rs",
                    1 + i * 20,
                    10 + i * 20,
                    FragmentKind::Function,
                    20 + i * i * 120,
                )
            })
            .collect();
        let core: FxHashSet<FragmentId> = std::iter::once(frags[0].id.clone()).collect();
        let mut rel = FxHashMap::default();
        for (i, f) in frags.iter().enumerate() {
            rel.insert(f.id.clone(), 1.0 / (1.0 + 3.0 * i as f64));
        }

        let budget = 10_000;
        let default_tau = lazy_greedy_select(
            frags.clone(),
            &core,
            &rel,
            &[],
            budget,
            crate::config::limits::DEFAULT_STOPPING_THRESHOLD,
            None,
            None,
        );
        let no_tau = lazy_greedy_select(frags, &core, &rel, &[], budget, 0.0, None, None);

        assert_eq!(
            default_tau.reason,
            SelectionReason::StoppedByTau,
            "the adaptive stop did not fire at the shipped default"
        );
        assert!(
            default_tau.selected.len() < no_tau.selected.len(),
            "tau={} selected {} fragments, same as tau=0.0 — the rule is inert",
            crate::config::limits::DEFAULT_STOPPING_THRESHOLD,
            default_tau.selected.len()
        );
        assert!(
            default_tau.used_tokens < no_tau.used_tokens,
            "the stop saved no budget: {} vs {}",
            default_tau.used_tokens,
            no_tau.used_tokens
        );
        assert!(
            default_tau.stopping_certificate > 0.0,
            "StoppedByTau must carry a positive certificate"
        );
        assert_eq!(
            no_tau.stopping_certificate, 0.0,
            "tau=0.0 cannot produce a stopping certificate"
        );
    }
}