noxu-cleaner 6.3.0

Log file garbage collection for Noxu DB
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
//! In-memory utilization tracking.
//!
//! Base and per-file utilization tracking for log space accounting.
//! tracks per-file utilization changes in memory between checkpoints.
//!
//! ## Property tests
//!
//! Oracle properties comparing the tracker against a brute-force scan over
//! the LN write/delete event log live in
//! `crates/noxu-cleaner/tests/prop_tests.rs` (Wave 11-E):
//! `prop_tracker_total_size_matches_writes`,
//! `prop_tracker_obsolete_count_matches_oracle`,
//! `prop_tracker_file_set_is_union`, `prop_tracker_clear_resets`.

use crate::db_file_summary::DbFileSummary;
use crate::tracked_file_summary::TrackedFileSummary;
use hashbrown::HashMap;

/// Which `BaseUtilizationTracker.countObsolete` variant to apply.
///
/// JE has three public obsolete-counting methods on `UtilizationTracker`,
/// differing only in `trackOffset` / `checkDupOffsets`:
///
/// | Variant | `trackOffset` | `checkDupOffsets` | JE method |
/// |---|---|---|---|
/// | `Exact` | true | true | `countObsoleteNode` |
/// | `Inexact` | false | false | `countObsoleteNodeInexact` |
/// | `DupsAllowed` | true | false | `countObsoleteNodeDupsAllowed` |
///
/// Cite: `UtilizationTracker.countObsoleteNode` /
/// `countObsoleteNodeInexact` / `countObsoleteNodeDupsAllowed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObsoleteKind {
    /// `countObsoleteNode`: exact LSN, track offset, assert no dup offset.
    Exact,
    /// `countObsoleteNodeInexact`: approximate LSN, do not track offset.
    Inexact,
    /// `countObsoleteNodeDupsAllowed`: track offset, allow double-count.
    DupsAllowed,
}

impl ObsoleteKind {
    /// Whether this variant tracks the obsolete LSN offset.
    fn track_offset(self) -> bool {
        matches!(self, ObsoleteKind::Exact | ObsoleteKind::DupsAllowed)
    }

    /// Whether this variant asserts the offset has not been counted before.
    fn check_dup_offsets(self) -> bool {
        matches!(self, ObsoleteKind::Exact)
    }
}

/// Tracks per-file utilization changes in memory.
///
/// The tracker maintains a map of file numbers to tracked summaries, accumulating changes
/// between checkpoints. When a checkpoint occurs, the tracked data is transferred to the
/// persistent UtilizationProfile.
///
/// CLN-9 (the per-DB axis): JE keeps the `DbFileSummary` map on each
/// `DatabaseImpl` and reaches it via `getDbFileSummary`. The global tracker
/// in noxu cannot reach `DatabaseImpl` (it would be a circular dependency:
/// `noxu-dbi` depends on `noxu-cleaner`), so the per-DB summaries are kept on
/// the tracker itself, keyed by `(db_id, file_num)`. This holds exactly the
/// same counters JE's `DbFileSummary` does; only the storage location differs.
#[derive(Debug)]
pub struct UtilizationTracker {
    /// Map of file_number -> TrackedFileSummary.
    tracked_files: HashMap<u32, TrackedFileSummary>,
    /// CLN-9: per-DB-per-file summaries, keyed by `db_id` then `file_num`.
    /// Mirrors JE's `DatabaseImpl.dbFileSummaries` (a `DbFileSummaryMap`).
    db_file_summaries: HashMap<u32, HashMap<u32, DbFileSummary>>,
    /// Bytes of tracked info (for memory budget).
    tracked_bytes: i64,
    /// Whether to track obsolete offset details.
    track_detail: bool,
}

impl UtilizationTracker {
    /// Creates a new utilization tracker.
    pub fn new(track_detail: bool) -> Self {
        Self {
            tracked_files: HashMap::new(),
            db_file_summaries: HashMap::new(),
            tracked_bytes: 0,
            track_detail,
        }
    }

    /// Counts a node that has become obsolete and tracks the LSN offset.
    ///
    /// JE `UtilizationTracker.countObsoleteNode`
    /// (`trackOffset=true, checkDupOffsets=true`): exact LSN, dedup-checked.
    ///
    /// `db_id` is the database that owned the node (CLN-9 per-DB axis); pass
    /// `None` only when no DB is associated (which JE asserts never happens
    /// for trackable types, but the global write path may not always know it).
    pub fn count_obsolete_node(
        &mut self,
        file_number: u32,
        offset: u32,
        size: i32,
        count_as_ln: bool,
        db_id: Option<u32>,
    ) {
        self.count_obsolete(
            file_number,
            offset,
            size,
            count_as_ln,
            db_id,
            ObsoleteKind::Exact,
        );
    }

    /// Counts an obsolete node without tracking the (inexact) LSN offset.
    ///
    /// JE `UtilizationTracker.countObsoleteNodeInexact`
    /// (`trackOffset=false, checkDupOffsets=false`). Used for
    /// `isImmediatelyObsolete` deleted/embedded LNs (L-6) where the LSN is
    /// only approximate.
    pub fn count_obsolete_node_inexact(
        &mut self,
        file_number: u32,
        offset: u32,
        size: i32,
        count_as_ln: bool,
        db_id: Option<u32>,
    ) {
        self.count_obsolete(
            file_number,
            offset,
            size,
            count_as_ln,
            db_id,
            ObsoleteKind::Inexact,
        );
    }

    /// Counts an obsolete node, tracking the offset but allowing a duplicate.
    ///
    /// JE `UtilizationTracker.countObsoleteNodeDupsAllowed`
    /// (`trackOffset=true, checkDupOffsets=false`). Used where the same LSN
    /// offset may legitimately be counted twice: a BIN-delta `prevDeltaLsn`
    /// (L-5) and during recovery.
    pub fn count_obsolete_node_dups_allowed(
        &mut self,
        file_number: u32,
        offset: u32,
        size: i32,
        count_as_ln: bool,
        db_id: Option<u32>,
    ) {
        self.count_obsolete(
            file_number,
            offset,
            size,
            count_as_ln,
            db_id,
            ObsoleteKind::DupsAllowed,
        );
    }

    /// Shared obsolete-counting core.
    ///
    /// JE `BaseUtilizationTracker.countObsolete`. Updates both the per-FILE
    /// `FileSummary` and (when `db_id` is supplied) the per-DB
    /// `DbFileSummary`, then conditionally tracks the LSN offset.
    fn count_obsolete(
        &mut self,
        file_number: u32,
        offset: u32,
        size: i32,
        count_as_ln: bool,
        db_id: Option<u32>,
        kind: ObsoleteKind,
    ) {
        let track_detail = self.track_detail;
        let tracked =
            self.tracked_files.entry(file_number).or_insert_with(|| {
                TrackedFileSummary::new(file_number, track_detail)
            });

        // countPerFile: update the per-FILE summary counters.
        // JE BaseUtilizationTracker.countObsolete, countPerFile branch.
        let summary = tracked.get_summary_mut();
        if count_as_ln {
            summary.obsolete_ln_count += 1;
            // The size is OPTIONAL when tracking obsolete LNs — only
            // accumulate it (and the counted tally feeding the avg-LN-size
            // estimator) when a real size was supplied.
            // JE: countObsolete "The size is optional when tracking obsolete
            // LNs."
            if size > 0 {
                summary.obsolete_ln_size += size;
                summary.obsolete_ln_size_counted += 1;
            }
        } else {
            summary.obsolete_in_count += 1;
            // JE asserts size == 0 for obsolete INs ("not allowed").
            debug_assert_eq!(
                size, 0,
                "obsolete IN size must be 0 (JE BaseUtilizationTracker.countObsolete)"
            );
        }

        // trackOffset: record the offset (skip offset 0 = the file header,
        // which is always treated as obsolete). checkDupOffsets asserts the
        // offset was not already counted on the Exact path. [#15365]
        // JE: countObsolete, trackOffset branch -> fileSummary.trackObsolete.
        if kind.track_offset() && offset != 0 {
            if kind.check_dup_offsets() {
                debug_assert!(
                    !tracked.get_obsolete_offsets().contains(&offset),
                    "checkDupOffsets: offset {offset} in file {file_number} already counted obsolete (JE invariant)"
                );
            }
            tracked.add_obsolete_offset(offset);
        }

        // countPerDb: mirror the counters in the per-DB DbFileSummary (CLN-9).
        // JE: countObsolete, countPerDb branch -> getDbFileSummary.
        if let Some(db) = db_id {
            let db_summary = self
                .db_file_summaries
                .entry(db)
                .or_default()
                .entry(file_number)
                .or_default();
            if count_as_ln {
                db_summary.obsolete_ln_count += 1;
                if size > 0 {
                    db_summary.obsolete_ln_size += size;
                    db_summary.obsolete_ln_size_counted += 1;
                }
            } else {
                db_summary.obsolete_in_count += 1;
            }
        }

        // Update memory budget
        self.update_tracked_bytes();
    }

    /// Tracks an obsolete log entry (legacy shim).
    ///
    /// Equivalent to [`Self::count_obsolete_node_dups_allowed`] with no
    /// `db_id`: it tracks the offset but does NOT fire the exact-path dedup
    /// assertion, matching the pre-CLN-10 accumulator semantics relied on by
    /// the property tests and other call sites that may legitimately repeat
    /// an offset. New code that knows the LSN is exact-and-unique should call
    /// [`Self::count_obsolete_node`] instead.
    ///
    /// # Arguments
    /// * `file_number` - The file containing the obsolete entry
    /// * `offset` - The offset of the obsolete entry
    /// * `size` - The size of the obsolete entry
    /// * `count_as_ln` - Whether to count this as an LN (vs IN)
    pub fn track_obsolete(
        &mut self,
        file_number: u32,
        offset: u32,
        size: i32,
        count_as_ln: bool,
    ) {
        self.count_obsolete_node_dups_allowed(
            file_number,
            offset,
            size,
            count_as_ln,
            None,
        );
    }

    /// Counts all active bytes in a database as obsolete (CLN-11).
    ///
    /// Called when a database is removed or truncated: the still-active
    /// amounts in each of the DB's files (total minus already-counted
    /// obsolete) become reclaimable. JE
    /// `BaseUtilizationTracker.countObsoleteDb`.
    ///
    /// Includes the [#19144] self-heal: when a DB becomes obsolete, the size
    /// of all its obsolete LNs can finally be counted accurately, because
    /// every LN byte in the DB is now obsolete — so `obsoleteLNSizeCounted`
    /// is bumped to cover both the LNs becoming obsolete now and those that
    /// went obsolete earlier with their size uncounted.
    ///
    /// After counting, the DB's per-DB summaries are dropped (JE deletes the
    /// MapLN; the per-DB map goes away with it).
    pub fn count_obsolete_db(&mut self, db_id: u32) {
        let Some(per_file) = self.db_file_summaries.remove(&db_id) else {
            return;
        };
        let track_detail = self.track_detail;
        for (file_num, db_summary) in per_file {
            let tracked =
                self.tracked_files.entry(file_num).or_insert_with(|| {
                    TrackedFileSummary::new(file_num, track_detail)
                });
            let summary = tracked.get_summary_mut();

            // Active = total - already-counted-obsolete.
            let ln_obsolete_count =
                db_summary.total_ln_count - db_summary.obsolete_ln_count;
            let ln_obsolete_size =
                db_summary.total_ln_size - db_summary.obsolete_ln_size;
            let in_obsolete_count =
                db_summary.total_in_count - db_summary.obsolete_in_count;
            summary.obsolete_ln_count += ln_obsolete_count;
            summary.obsolete_ln_size += ln_obsolete_size;
            summary.obsolete_in_count += in_obsolete_count;

            // [#19144] obsolete-LN-size self-heal.
            let ln_obsolete_size_counted = ln_obsolete_count
                + (db_summary.obsolete_ln_count
                    - db_summary.obsolete_ln_size_counted);
            summary.obsolete_ln_size_counted += ln_obsolete_size_counted;
        }
        self.update_tracked_bytes();
    }

    /// Counts a new log entry.
    ///
    /// Equivalent to [`Self::count_new_log_entry_db`] with no `db_id`.
    ///
    /// # Arguments
    /// * `file_number` - The file containing the new entry
    /// * `size` - The size of the entry
    /// * `is_ln` - Whether this is an LN entry
    /// * `is_in` - Whether this is an IN entry
    pub fn count_new_log_entry(
        &mut self,
        file_number: u32,
        size: i32,
        is_ln: bool,
        is_in: bool,
    ) {
        self.count_new_log_entry_db(file_number, size, is_ln, is_in, None);
    }

    /// Counts the addition of a new log entry in both the per-FILE and (when
    /// `db_id` is supplied) the per-DB summaries.
    ///
    /// JE `BaseUtilizationTracker.countNew`.
    pub fn count_new_log_entry_db(
        &mut self,
        file_number: u32,
        size: i32,
        is_ln: bool,
        is_in: bool,
        db_id: Option<u32>,
    ) {
        let track_detail = self.track_detail;
        let tracked =
            self.tracked_files.entry(file_number).or_insert_with(|| {
                TrackedFileSummary::new(file_number, track_detail)
            });

        let summary = tracked.get_summary_mut();
        summary.total_count += 1;
        summary.total_size += size;

        if is_ln {
            summary.total_ln_count += 1;
            summary.total_ln_size += size;
            if size > summary.max_ln_size {
                summary.max_ln_size = size;
            }
        }

        if is_in {
            summary.total_in_count += 1;
            summary.total_in_size += size;
        }

        // Per-DB axis (CLN-9): JE countNew updates the DbFileSummary too.
        if let Some(db) = db_id {
            let db_summary = self
                .db_file_summaries
                .entry(db)
                .or_default()
                .entry(file_number)
                .or_default();
            if is_ln {
                db_summary.total_ln_count += 1;
                db_summary.total_ln_size += size;
            }
            if is_in {
                db_summary.total_in_count += 1;
                db_summary.total_in_size += size;
            }
        }

        self.update_tracked_bytes();
    }

    /// Returns the per-DB-per-file summary for a database/file, if tracked.
    pub fn get_db_file_summary(
        &self,
        db_id: u32,
        file_number: u32,
    ) -> Option<&DbFileSummary> {
        self.db_file_summaries.get(&db_id)?.get(&file_number)
    }

    /// Returns a reference to the tracked summary for a file.
    pub fn get_tracked_summary(
        &self,
        file_number: u32,
    ) -> Option<&TrackedFileSummary> {
        self.tracked_files.get(&file_number)
    }

    /// Returns a mutable reference to the tracked summary for a file.
    pub fn get_tracked_summary_mut(
        &mut self,
        file_number: u32,
    ) -> Option<&mut TrackedFileSummary> {
        self.tracked_files.get_mut(&file_number)
    }

    /// Returns a reference to all tracked files.
    pub fn get_tracked_files(&self) -> &HashMap<u32, TrackedFileSummary> {
        &self.tracked_files
    }

    /// Returns a mutable reference to all tracked files.
    pub fn get_tracked_files_mut(
        &mut self,
    ) -> &mut HashMap<u32, TrackedFileSummary> {
        &mut self.tracked_files
    }

    /// Removes and returns all tracked files, clearing the tracker.
    ///
    /// This is typically called when transferring tracked data to the utilization profile.
    pub fn remove_all_tracked_files(
        &mut self,
    ) -> HashMap<u32, TrackedFileSummary> {
        self.tracked_bytes = 0;
        std::mem::take(&mut self.tracked_files)
    }

    /// Returns the bytes of tracked information (for memory budget).
    pub fn get_bytes_tracked(&self) -> i64 {
        self.tracked_bytes
    }

    /// Returns the number of files being tracked.
    pub fn get_tracked_file_count(&self) -> usize {
        self.tracked_files.len()
    }

    /// Clears all tracked information.
    pub fn clear(&mut self) {
        self.tracked_files.clear();
        self.db_file_summaries.clear();
        self.tracked_bytes = 0;
    }

    /// Updates the tracked bytes count based on current tracked files.
    fn update_tracked_bytes(&mut self) {
        self.tracked_bytes =
            self.tracked_files.values().map(|t| t.memory_size() as i64).sum();
    }
}

impl Default for UtilizationTracker {
    fn default() -> Self {
        Self::new(true)
    }
}

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

    #[test]
    fn test_new() {
        let tracker = UtilizationTracker::new(true);
        assert_eq!(tracker.get_tracked_file_count(), 0);
        assert_eq!(tracker.get_bytes_tracked(), 0);
    }

    #[test]
    fn test_track_obsolete_ln() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.track_obsolete(1, 100, 50, true);

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().obsolete_ln_count, 1);
        assert_eq!(tracked.get_summary().obsolete_ln_size, 50);
        assert_eq!(tracked.get_summary().obsolete_ln_size_counted, 1);
        assert_eq!(tracked.obsolete_offset_count(), 1);
    }

    /// CLN-F3: when an obsolete LN is tracked with size 0 ("the size is
    /// optional"), the count is incremented but the size and counted tallies
    /// that feed the avg-LN-size estimator must stay unchanged.
    ///
    /// JE: BaseUtilizationTracker.countObsoleteNode (~184-189) guards
    /// `obsoleteLNSize`/`obsoleteLNSizeCounted` on `size > 0`.
    #[test]
    fn test_track_obsolete_ln_size_zero_does_not_count_size() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.track_obsolete(1, 100, 0, true);

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(
            tracked.get_summary().obsolete_ln_count,
            1,
            "count still increments for a size-0 obsolete LN"
        );
        assert_eq!(
            tracked.get_summary().obsolete_ln_size,
            0,
            "CLN-F3: size must NOT accumulate when size <= 0"
        );
        assert_eq!(
            tracked.get_summary().obsolete_ln_size_counted,
            0,
            "CLN-F3: counted must NOT increment when size <= 0"
        );
    }

    #[test]
    fn test_track_obsolete_in() {
        let mut tracker = UtilizationTracker::new(true);
        // JE asserts size == 0 for obsolete INs ("not allowed").
        tracker.track_obsolete(1, 100, 0, false);

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().obsolete_in_count, 1);
        assert_eq!(tracked.get_summary().obsolete_ln_count, 0);
    }

    #[test]
    fn test_count_new_ln_entry() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry(1, 100, true, false);

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().total_count, 1);
        assert_eq!(tracked.get_summary().total_size, 100);
        assert_eq!(tracked.get_summary().total_ln_count, 1);
        assert_eq!(tracked.get_summary().total_ln_size, 100);
        assert_eq!(tracked.get_summary().max_ln_size, 100);
    }

    #[test]
    fn test_count_new_in_entry() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry(1, 200, false, true);

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().total_count, 1);
        assert_eq!(tracked.get_summary().total_size, 200);
        assert_eq!(tracked.get_summary().total_in_count, 1);
        assert_eq!(tracked.get_summary().total_in_size, 200);
    }

    #[test]
    fn test_max_ln_size_tracking() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry(1, 50, true, false);
        tracker.count_new_log_entry(1, 100, true, false);
        tracker.count_new_log_entry(1, 75, true, false);

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().max_ln_size, 100);
    }

    #[test]
    fn test_multiple_files() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry(1, 100, true, false);
        tracker.count_new_log_entry(2, 200, true, false);
        tracker.count_new_log_entry(3, 300, true, false);

        assert_eq!(tracker.get_tracked_file_count(), 3);
        assert!(tracker.get_tracked_summary(1).is_some());
        assert!(tracker.get_tracked_summary(2).is_some());
        assert!(tracker.get_tracked_summary(3).is_some());
    }

    #[test]
    fn test_track_detail_disabled() {
        let mut tracker = UtilizationTracker::new(false);
        tracker.track_obsolete(1, 100, 50, true);

        let tracked = tracker.get_tracked_summary(1).unwrap();
        // Counters should be updated
        assert_eq!(tracked.get_summary().obsolete_ln_count, 1);
        // But offsets should not be tracked
        assert_eq!(tracked.obsolete_offset_count(), 0);
    }

    #[test]
    fn test_remove_all_tracked_files() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry(1, 100, true, false);
        tracker.count_new_log_entry(2, 200, true, false);

        let tracked_files = tracker.remove_all_tracked_files();
        assert_eq!(tracked_files.len(), 2);
        assert_eq!(tracker.get_tracked_file_count(), 0);
        assert_eq!(tracker.get_bytes_tracked(), 0);
    }

    #[test]
    fn test_clear() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry(1, 100, true, false);
        tracker.track_obsolete(1, 100, 50, true);

        tracker.clear();

        assert_eq!(tracker.get_tracked_file_count(), 0);
        assert_eq!(tracker.get_bytes_tracked(), 0);
    }

    #[test]
    fn test_get_tracked_files_mut() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry(1, 100, true, false);

        {
            let files = tracker.get_tracked_files_mut();
            if let Some(tracked) = files.get_mut(&1) {
                tracked.get_summary_mut().total_count += 10;
            }
        }

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().total_count, 11);
    }

    #[test]
    fn test_bytes_tracked_increases() {
        let mut tracker = UtilizationTracker::new(true);
        let initial_bytes = tracker.get_bytes_tracked();

        tracker.count_new_log_entry(1, 100, true, false);
        let after_entry = tracker.get_bytes_tracked();
        assert!(after_entry > initial_bytes);

        tracker.track_obsolete(1, 100, 50, true);
        let after_obsolete = tracker.get_bytes_tracked();
        assert!(after_obsolete >= after_entry);
    }

    #[test]
    fn test_accumulate_entries_same_file() {
        let mut tracker = UtilizationTracker::new(true);

        for i in 0..10 {
            tracker.count_new_log_entry(1, 100, true, false);
            // Offsets must be non-zero: JE never tracks the file-header
            // offset 0 as obsolete.
            tracker.track_obsolete(1, (i + 1) * 100, 50, true);
        }

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().total_count, 10);
        assert_eq!(tracked.get_summary().obsolete_ln_count, 10);
        assert_eq!(tracked.obsolete_offset_count(), 10);
    }

    /// JE `countObsoleteNode` (Exact): tracks the offset and updates the
    /// per-DB DbFileSummary.
    #[test]
    fn test_count_obsolete_node_exact_with_db() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_new_log_entry_db(1, 80, true, false, Some(7));
        tracker.count_obsolete_node(1, 200, 80, true, Some(7));

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().obsolete_ln_count, 1);
        assert_eq!(tracked.obsolete_offset_count(), 1, "exact tracks offset");

        let db = tracker.get_db_file_summary(7, 1).unwrap();
        assert_eq!(db.total_ln_count, 1);
        assert_eq!(db.obsolete_ln_count, 1);
        assert_eq!(db.obsolete_ln_size, 80);
    }

    /// JE `countObsoleteNodeInexact`: does NOT track the offset (LSN is
    /// approximate) but still bumps the obsolete counters. Used for deleted /
    /// embedded LNs counted obsolete at write time (L-6).
    #[test]
    fn test_count_obsolete_node_inexact_skips_offset() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_obsolete_node_inexact(1, 200, 80, true, Some(7));

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(tracked.get_summary().obsolete_ln_count, 1);
        assert_eq!(
            tracked.obsolete_offset_count(),
            0,
            "inexact must NOT track the (approximate) offset"
        );
    }

    /// JE `countObsoleteNodeDupsAllowed`: the same offset may be counted
    /// twice (BIN-delta prevDeltaLsn = L-5, recovery) without firing the
    /// dedup assertion. Both counts land, and the offset is tracked twice.
    #[test]
    fn test_count_obsolete_node_dups_allowed() {
        let mut tracker = UtilizationTracker::new(true);
        tracker.count_obsolete_node_dups_allowed(1, 200, 80, true, Some(7));
        // Counting the SAME offset again must not panic on the Exact dedup
        // assertion, because DupsAllowed sets checkDupOffsets=false.
        tracker.count_obsolete_node_dups_allowed(1, 200, 80, true, Some(7));

        let tracked = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(
            tracked.get_summary().obsolete_ln_count,
            2,
            "both counts land (double-count is legitimate here)"
        );
        assert_eq!(
            tracked.obsolete_offset_count(),
            2,
            "dups-allowed tracks the offset each time"
        );
    }

    /// JE `countObsoleteDb` ([#19144]): on DB remove/truncate, the still-active
    /// bytes (total - already-obsolete) become obsolete, and the obsolete-LN
    /// size is healed so every LN byte is counted.
    #[test]
    fn test_count_obsolete_db() {
        let mut tracker = UtilizationTracker::new(true);
        // DB 7 writes 3 LNs of 100 bytes each into file 1; one already went
        // obsolete (with size counted).
        tracker.count_new_log_entry_db(1, 100, true, false, Some(7));
        tracker.count_new_log_entry_db(1, 100, true, false, Some(7));
        tracker.count_new_log_entry_db(1, 100, true, false, Some(7));
        tracker.count_obsolete_node(1, 300, 100, true, Some(7));

        // Before remove: 1 of 3 LNs obsolete.
        let before = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(before.get_summary().obsolete_ln_count, 1);

        tracker.count_obsolete_db(7);

        // After remove: all 3 LNs obsolete, all 300 bytes counted.
        let after = tracker.get_tracked_summary(1).unwrap();
        assert_eq!(after.get_summary().obsolete_ln_count, 3);
        assert_eq!(after.get_summary().obsolete_ln_size, 300);
        assert_eq!(after.get_summary().obsolete_ln_size_counted, 3);
        // Per-DB summaries are dropped after counting.
        assert!(tracker.get_db_file_summary(7, 1).is_none());
    }

    #[test]
    fn test_default() {
        let tracker = UtilizationTracker::default();
        assert_eq!(tracker.get_tracked_file_count(), 0);
    }
}