pigeonhole-db 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +16 -16
  3. data/Cargo.toml +5 -5
  4. data/lib/pigeonhole/version.rb +1 -1
  5. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/io-event-1.22.3/IO_Event.so +0 -0
  6. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/io-event-1.22.3/gem_make.out +6 -6
  7. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/io-event-1.22.3/mkmf.log +26 -26
  8. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/gem_make.out +6 -6
  9. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/json/ext/generator.so +0 -0
  10. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/json/ext/parser.so +0 -0
  11. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/mkmf.log +19 -19
  12. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/prism-1.9.0/gem_make.out +9 -9
  13. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/prism-1.9.0/mkmf.log +6 -6
  14. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/prism-1.9.0/prism/prism.so +0 -0
  15. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/rbs-4.2.0/gem_make.out +6 -6
  16. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/rbs-4.2.0/mkmf.log +7 -7
  17. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/rbs-4.2.0/rbs_extension.so +0 -0
  18. data/vendor/bundle/ruby/3.4.0/gems/io-event-1.22.3/ext/Makefile +3 -3
  19. data/vendor/bundle/ruby/3.4.0/gems/io-event-1.22.3/lib/IO_Event.so +0 -0
  20. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/ext/json/ext/generator/Makefile +3 -3
  21. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/ext/json/ext/parser/Makefile +3 -3
  22. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/lib/json/ext/generator.so +0 -0
  23. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/lib/json/ext/parser.so +0 -0
  24. data/vendor/bundle/ruby/3.4.0/gems/prism-1.9.0/ext/prism/Makefile +3 -3
  25. data/vendor/bundle/ruby/3.4.0/gems/prism-1.9.0/lib/prism/prism.so +0 -0
  26. data/vendor/bundle/ruby/3.4.0/gems/rbs-4.2.0/ext/rbs_extension/Makefile +3 -3
  27. data/vendor/bundle/ruby/3.4.0/gems/rbs-4.2.0/lib/rbs_extension.so +0 -0
  28. data/vendor/cache/Cargo.toml +2 -2
  29. data/vendor/cache/src/lib.rs +37 -0
  30. data/vendor/cache/src/loom_tests.rs +32 -0
  31. data/vendor/cache/src/s3fifo.rs +239 -11
  32. data/vendor/cache/src/sync.rs +4 -4
  33. data/vendor/compaction/Cargo.toml +6 -6
  34. data/vendor/compaction/src/cursor.rs +86 -4
  35. data/vendor/compaction/src/job.rs +24 -2
  36. data/vendor/engine/Cargo.toml +11 -11
  37. data/vendor/engine/src/admission.rs +3 -1
  38. data/vendor/engine/src/catalog.rs +39 -4
  39. data/vendor/engine/src/check.rs +59 -20
  40. data/vendor/engine/src/compact.rs +2 -2
  41. data/vendor/engine/src/engine/hooks.rs +144 -2
  42. data/vendor/engine/src/engine/info.rs +6 -0
  43. data/vendor/engine/src/engine.rs +1492 -50
  44. data/vendor/engine/src/external_registry.rs +447 -0
  45. data/vendor/engine/src/feed.rs +313 -84
  46. data/vendor/engine/src/feed_reader/catalog.rs +490 -0
  47. data/vendor/engine/src/feed_reader/history.rs +236 -0
  48. data/vendor/engine/src/feed_reader/read_ahead.rs +241 -0
  49. data/vendor/engine/src/feed_reader/token.rs +232 -0
  50. data/vendor/engine/src/feed_reader.rs +970 -852
  51. data/vendor/engine/src/feed_stop_loom.rs +73 -0
  52. data/vendor/engine/src/flush.rs +29 -4
  53. data/vendor/engine/src/io_count.rs +190 -0
  54. data/vendor/engine/src/large.rs +4 -1
  55. data/vendor/engine/src/lib.rs +16 -2
  56. data/vendor/engine/src/maintenance.rs +2 -2
  57. data/vendor/engine/src/manifest.rs +38 -6
  58. data/vendor/engine/src/nonblocking.rs +3 -3
  59. data/vendor/engine/src/options.rs +26 -0
  60. data/vendor/engine/src/punch.rs +282 -0
  61. data/vendor/engine/src/range_copy.rs +365 -0
  62. data/vendor/engine/src/read/keys.rs +37 -5
  63. data/vendor/engine/src/read/reduce.rs +1 -0
  64. data/vendor/engine/src/read.rs +7 -0
  65. data/vendor/engine/src/row_cache.rs +24 -0
  66. data/vendor/engine/src/shard/tablets.rs +127 -31
  67. data/vendor/engine/src/shard.rs +1006 -33
  68. data/vendor/engine/src/source.rs +105 -12
  69. data/vendor/engine/src/write.rs +310 -4
  70. data/vendor/format/Cargo.toml +1 -1
  71. data/vendor/format/src/shm.rs +10 -0
  72. data/vendor/format/src/superblock.rs +9 -2
  73. data/vendor/format/src/wal.rs +818 -16
  74. data/vendor/io/Cargo.toml +3 -3
  75. data/vendor/io/src/count.rs +76 -0
  76. data/vendor/io/src/file.rs +70 -0
  77. data/vendor/io/src/lib.rs +2 -0
  78. data/vendor/io/src/os/unix.rs +124 -0
  79. data/vendor/io/src/os/windows.rs +51 -0
  80. data/vendor/io/src/pread.rs +26 -0
  81. data/vendor/io/src/sim.rs +81 -9
  82. data/vendor/io/src/sys.rs +53 -0
  83. data/vendor/io/src/uring.rs +28 -0
  84. data/vendor/io/src/vfs.rs +4 -0
  85. data/vendor/memory/Cargo.toml +4 -4
  86. data/vendor/memory/src/hooks.rs +6 -0
  87. data/vendor/memory/src/ivf.rs +67 -1
  88. data/vendor/memory/src/lib.rs +4 -1
  89. data/vendor/memory/src/recall/pool.rs +872 -0
  90. data/vendor/memory/src/recall.rs +351 -273
  91. data/vendor/memory/src/store.rs +15 -0
  92. data/vendor/memtable/Cargo.toml +3 -3
  93. data/vendor/pager/Cargo.toml +3 -3
  94. data/vendor/pager/src/alloc.rs +430 -0
  95. data/vendor/pager/src/lib.rs +114 -0
  96. data/vendor/pigeonhole/Cargo.toml +6 -5
  97. data/vendor/pigeonhole/src/db.rs +91 -2
  98. data/vendor/pigeonhole/src/error.rs +2 -1
  99. data/vendor/pigeonhole/src/feed.rs +210 -6
  100. data/vendor/pigeonhole/src/lib.rs +3 -0
  101. data/vendor/pigeonhole/src/metrics.rs +37 -0
  102. data/vendor/pigeonhole/src/nonblocking.rs +94 -111
  103. data/vendor/pigeonhole/src/options.rs +69 -0
  104. data/vendor/pigeonhole/src/replication.rs +601 -11
  105. data/vendor/pigeonhole/src/write.rs +81 -0
  106. data/vendor/runtime/Cargo.toml +2 -2
  107. data/vendor/shm/Cargo.toml +3 -3
  108. data/vendor/shm/src/region.rs +20 -2
  109. data/vendor/sst/Cargo.toml +4 -4
  110. data/vendor/sst/src/blob.rs +85 -7
  111. data/vendor/sst/src/iter.rs +98 -2
  112. data/vendor/sst/src/lib.rs +11 -2
  113. data/vendor/sst/src/writer.rs +12 -2
  114. data/vendor/text/Cargo.toml +2 -2
  115. data/vendor/text/src/block.rs +638 -0
  116. data/vendor/text/src/error.rs +8 -3
  117. data/vendor/text/src/fuzzy.rs +1 -1
  118. data/vendor/text/src/index.rs +1055 -80
  119. data/vendor/text/src/layout.rs +63 -2
  120. data/vendor/text/src/lib.rs +5 -1
  121. data/vendor/text/src/maxscore.rs +481 -94
  122. data/vendor/text/src/merged.rs +470 -0
  123. data/vendor/text/src/search.rs +1278 -341
  124. data/vendor/text/src/stats.rs +431 -0
  125. data/vendor/vector/Cargo.toml +2 -2
  126. data/vendor/vector/src/hooks.rs +33 -4
  127. data/vendor/vector/src/index.rs +498 -69
  128. data/vendor/wal/Cargo.toml +3 -3
  129. data/vendor/wal/src/feed.rs +313 -19
  130. data/vendor/wal/src/recovery.rs +31 -1
  131. data/vendor/wal/src/stream.rs +28 -0
  132. metadata +15 -1
@@ -526,6 +526,8 @@ struct Shared {
526
526
  /// The IVF index's rebalancer, kept for [`Store::take_rebalancer`] when opened with
527
527
  /// [`OpenOptions::own_rebalancer`].
528
528
  rebalancer: Mutex<Option<pigeonhole_vector::Rebalancer>>,
529
+ /// The namespace counts the store's recalls read, by snapshot (#2040).
530
+ ns_counts: crate::ivf::NsCounts,
529
531
  }
530
532
 
531
533
  impl std::fmt::Debug for Store {
@@ -761,6 +763,7 @@ impl Store {
761
763
  own,
762
764
  ivf_pending: Mutex::new(std::collections::VecDeque::new()),
763
765
  rebalancer: Mutex::new(None),
766
+ ns_counts: crate::ivf::NsCounts::default(),
764
767
  }),
765
768
  }
766
769
  }
@@ -865,6 +868,7 @@ impl Store {
865
868
  Rows::W(&self.table),
866
869
  Idx::W(&self.index),
867
870
  self.ivf.as_ref(),
871
+ Some(&self.shared.ns_counts),
868
872
  self.model.as_ref().filter(|_| self.embeds),
869
873
  Snap::W(&self.db),
870
874
  namespaces,
@@ -1327,6 +1331,16 @@ impl Store {
1327
1331
  }
1328
1332
  }
1329
1333
 
1334
+ /// The namespace counter reads the store's recalls made (an inspection helper for
1335
+ /// `hooks`, #2040).
1336
+ #[cfg(feature = "__unstable-hooks")]
1337
+ pub(crate) fn ns_count_reads(&self) -> u64 {
1338
+ self.shared
1339
+ .ns_counts
1340
+ .reads
1341
+ .load(std::sync::atomic::Ordering::Relaxed)
1342
+ }
1343
+
1330
1344
  /// The IVF records waiting to settle (an inspection helper for `hooks`).
1331
1345
  #[cfg(feature = "__unstable-hooks")]
1332
1346
  pub(crate) fn ivf_pending_len(&self) -> usize {
@@ -1640,6 +1654,7 @@ impl ReadStore {
1640
1654
  Rows::R(&self.table),
1641
1655
  Idx::R(&self.index),
1642
1656
  self.ivf.as_ref(),
1657
+ None,
1643
1658
  self.model.as_ref().filter(|_| self.embeds),
1644
1659
  Snap::R(&self.reader),
1645
1660
  namespaces,
@@ -2,10 +2,10 @@
2
2
 
3
3
  [dependencies.pigeonhole-format]
4
4
  path = "../format"
5
- version = "=3.0.2"
5
+ version = "=3.1.0"
6
6
  [dependencies.pigeonhole-io]
7
7
  path = "../io"
8
- version = "=3.0.2"
8
+ version = "=3.1.0"
9
9
  [lints.rust.unexpected_cfgs]
10
10
  check-cfg = ["cfg(loom)", "cfg(engine_loom)", "cfg(io_loom)", "cfg(pigeonhole_sim)"]
11
11
  level = "warn"
@@ -20,5 +20,5 @@ name = "pigeonhole-memtable"
20
20
  readme = "README.md"
21
21
  repository = "https://github.com/CodingAnarchy/pigeonhole"
22
22
  rust-version = "1.96"
23
- version = "3.0.2"
23
+ version = "3.1.0"
24
24
  [target."cfg(loom)"]
@@ -2,10 +2,10 @@
2
2
 
3
3
  [dependencies.pigeonhole-format]
4
4
  path = "../format"
5
- version = "=3.0.2"
5
+ version = "=3.1.0"
6
6
  [dependencies.pigeonhole-io]
7
7
  path = "../io"
8
- version = "=3.0.2"
8
+ version = "=3.1.0"
9
9
  [lints.rust.unexpected_cfgs]
10
10
  check-cfg = ["cfg(loom)", "cfg(engine_loom)", "cfg(io_loom)", "cfg(pigeonhole_sim)"]
11
11
  level = "warn"
@@ -20,4 +20,4 @@ name = "pigeonhole-pager"
20
20
  readme = "README.md"
21
21
  repository = "https://github.com/CodingAnarchy/pigeonhole"
22
22
  rust-version = "1.96"
23
- version = "3.0.2"
23
+ version = "3.1.0"
@@ -49,6 +49,9 @@ pub(crate) enum LoadError {
49
49
  PastEnd,
50
50
  }
51
51
 
52
+ /// `[from, to)` unit ranges, in order (the holes of a punch pass, D333).
53
+ pub(crate) type UnitRanges = Vec<(u64, u64)>;
54
+
52
55
  #[derive(Debug, Clone)]
53
56
  pub(crate) struct Alloc {
54
57
  free: FreeLists,
@@ -66,6 +69,12 @@ pub(crate) struct Alloc {
66
69
  /// and the file length (units) from which it does.
67
70
  ahead_class: u8,
68
71
  ahead_from: u64,
72
+ /// Free space known to be a hole (D333): `[from, to)` in units, disjoint and not
73
+ /// adjacent, always inside free blocks. An allocation takes its range out.
74
+ punched: BTreeMap<u64, u64>,
75
+ /// The block a punch pass took out of the free map ([`Alloc::take_for_punch`]), held as
76
+ /// a placeholder until [`Alloc::end_punch`]: `(unit, class)`.
77
+ punching: Option<(u64, u8)>,
69
78
  }
70
79
 
71
80
  /// A region `Alloc::clear_for` could clear: occupied units, first unit, and occupants as
@@ -140,6 +149,8 @@ impl Alloc {
140
149
  held: BTreeMap::new(),
141
150
  ahead_class: Extent::MAX_CLASS,
142
151
  ahead_from: AHEAD_FROM_UNITS,
152
+ punched: BTreeMap::new(),
153
+ punching: None,
143
154
  };
144
155
  a.free_range(1, a.frontier);
145
156
  a
@@ -169,6 +180,8 @@ impl Alloc {
169
180
  held: BTreeMap::new(),
170
181
  ahead_class: Extent::MAX_CLASS,
171
182
  ahead_from: AHEAD_FROM_UNITS,
183
+ punched: BTreeMap::new(),
184
+ punching: None,
172
185
  };
173
186
  let mut next = 1;
174
187
  for (u, class) in extents {
@@ -232,6 +245,7 @@ impl Alloc {
232
245
  }
233
246
 
234
247
  fn mark_used(&mut self, unit: u64, class: u8) -> Extent {
248
+ self.unpunch(unit, unit + units(class));
235
249
  self.used.insert(
236
250
  unit,
237
251
  Used {
@@ -291,7 +305,10 @@ impl Alloc {
291
305
  /// the file inline, and the file is long enough ([`AHEAD_FROM_UNITS`] by default: a
292
306
  /// small database never grows ahead).
293
307
  pub(crate) fn wants_ahead(&self) -> bool {
308
+ // A block mid-punch is free space for this: it is back in the map in a moment.
309
+ let punching = self.punching.is_some_and(|(_, k)| k >= self.ahead_class);
294
310
  self.frontier >= self.ahead_from
311
+ && !punching
295
312
  && (self.ahead_class..=Extent::MAX_CLASS).all(|k| self.free[k as usize].is_empty())
296
313
  }
297
314
 
@@ -485,9 +502,164 @@ impl Alloc {
485
502
  for set in &mut self.free {
486
503
  set.split_off(&end);
487
504
  }
505
+ self.unpunch(end, u64::MAX);
488
506
  self.frontier = end;
489
507
  }
490
508
 
509
+ /// Takes `[from, to)` out of the punched set: it is about to hold data, or leaves the
510
+ /// file.
511
+ fn unpunch(&mut self, from: u64, to: u64) {
512
+ let first = self
513
+ .punched
514
+ .range(..from)
515
+ .next_back()
516
+ .filter(|&(_, &end)| end > from)
517
+ .map(|(&start, _)| start)
518
+ .unwrap_or(from);
519
+ let inside: Vec<(u64, u64)> = self
520
+ .punched
521
+ .range(first..to)
522
+ .map(|(&a, &b)| (a, b))
523
+ .collect();
524
+ for (a, b) in inside {
525
+ self.punched.remove(&a);
526
+ if a < from {
527
+ self.punched.insert(a, from);
528
+ }
529
+ if b > to {
530
+ self.punched.insert(to, b);
531
+ }
532
+ }
533
+ }
534
+
535
+ /// Adds `[from, to)` to the punched set, merging with touching ranges.
536
+ fn add_punched(&mut self, mut from: u64, mut to: u64) {
537
+ if let Some((&a, &b)) = self.punched.range(..=from).next_back()
538
+ && b >= from
539
+ {
540
+ from = a;
541
+ to = to.max(b);
542
+ self.punched.remove(&a);
543
+ }
544
+ while let Some((&a, &b)) = self.punched.range(from..=to).next() {
545
+ to = to.max(b);
546
+ self.punched.remove(&a);
547
+ }
548
+ self.punched.insert(from, to);
549
+ }
550
+
551
+ /// The first unit past the lowest `reserve` units of free space, in whole blocks: the
552
+ /// lowest block that starts once the blocks below it hold `reserve` units. `None` if the
553
+ /// free space never reaches it. Walks the free lists in address order (a merge of the
554
+ /// per-class sets), visiting only the blocks inside the reserve.
555
+ fn punch_cutoff(&self, reserve: u64) -> Option<u64> {
556
+ let mut iters: Vec<_> = (0..CLASSES)
557
+ .map(|k| self.free[k].iter().copied().peekable())
558
+ .collect();
559
+ let mut kept = 0;
560
+ loop {
561
+ let (k, u) = iters
562
+ .iter_mut()
563
+ .enumerate()
564
+ .filter_map(|(k, it)| it.peek().map(|&u| (k, u)))
565
+ .min_by_key(|&(_, u)| u)?;
566
+ if kept >= reserve {
567
+ return Some(u);
568
+ }
569
+ iters[k].next();
570
+ kept += units(k as u8);
571
+ }
572
+ }
573
+
574
+ /// Whether all of `[from, to)` is punched (one range covers it: ranges never touch).
575
+ fn all_punched(&self, from: u64, to: u64) -> bool {
576
+ self.punched
577
+ .range(..=from)
578
+ .next_back()
579
+ .is_some_and(|(_, &end)| end >= to)
580
+ }
581
+
582
+ /// The parts of `[from, to)` not yet punched.
583
+ fn unpunched(&self, from: u64, to: u64) -> Vec<(u64, u64)> {
584
+ let mut out = Vec::new();
585
+ let mut at = from;
586
+ let first = self
587
+ .punched
588
+ .range(..from)
589
+ .next_back()
590
+ .filter(|&(_, &end)| end > from)
591
+ .map(|(&start, _)| start)
592
+ .unwrap_or(from);
593
+ for (&a, &b) in self.punched.range(first..to) {
594
+ if a > at {
595
+ out.push((at, a));
596
+ }
597
+ at = at.max(b);
598
+ }
599
+ if at < to {
600
+ out.push((at, to));
601
+ }
602
+ out
603
+ }
604
+
605
+ /// Takes one free block out of the free map for a punch pass (D333): of the free blocks
606
+ /// past the lowest `reserve` units of free space, the largest with space not yet
607
+ /// punched (the highest on a tie). It is held as a placeholder, so nothing is allocated
608
+ /// in it, nothing moves or truncates it, and no region is cleared around it, until
609
+ /// [`end_punch`](Self::end_punch). Returns it as `(unit, class)` with the unit ranges
610
+ /// still to punch, or `None` if there is none or a pass already holds one.
611
+ pub(crate) fn take_for_punch(&mut self, reserve: u64) -> Option<(u64, u8, UnitRanges)> {
612
+ if self.punching.is_some() {
613
+ return None;
614
+ }
615
+ // Bounded under the allocator lock (simp724's S1 on #2033): the walk to the
616
+ // reserve's end visits only the blocks inside the reserve, and the pick then goes
617
+ // from the largest class down, each from its highest block, stopping at the first
618
+ // with space not yet punched.
619
+ let cutoff = self.punch_cutoff(reserve)?;
620
+ let (unit, class) = (0..CLASSES as u8).rev().find_map(|k| {
621
+ self.free[k as usize]
622
+ .range(cutoff..)
623
+ .rev()
624
+ .find(|&&u| !self.all_punched(u, u + units(k)))
625
+ .map(|&u| (u, k))
626
+ })?;
627
+ let ranges = self.unpunched(unit, unit + units(class));
628
+ self.free[class as usize].remove(&unit);
629
+ self.used.insert(
630
+ unit,
631
+ Used {
632
+ class,
633
+ retired: None,
634
+ published: false,
635
+ placeholder: true,
636
+ },
637
+ );
638
+ self.used_units += units(class);
639
+ self.punching = Some((unit, class));
640
+ Some((unit, class, ranges))
641
+ }
642
+
643
+ /// Returns the block [`take_for_punch`](Self::take_for_punch) took to the free map,
644
+ /// recording `[from, to)` ranges of it as punched (those the filesystem took back).
645
+ pub(crate) fn end_punch(&mut self, punched: &[(u64, u64)]) {
646
+ let Some((unit, class)) = self.punching.take() else {
647
+ return;
648
+ };
649
+ let used = self.used.remove(&unit).expect("the punching block is held");
650
+ debug_assert!(used.placeholder && used.class == class);
651
+ self.used_units -= units(class);
652
+ self.free_block(unit, class);
653
+ for &(a, b) in punched {
654
+ self.add_punched(a, b);
655
+ }
656
+ }
657
+
658
+ /// Units of free space known to be holes.
659
+ pub(crate) fn punched_units(&self) -> u64 {
660
+ self.punched.iter().map(|(a, b)| b - a).sum()
661
+ }
662
+
491
663
  /// Live extents past the point the live set would end at if packed toward the start of
492
664
  /// the file, largest first. Retired extents are not moved: reclaiming them frees their
493
665
  /// space.
@@ -702,6 +874,44 @@ impl Alloc {
702
874
  }
703
875
  assert_eq!(used, self.used_units);
704
876
  assert_eq!(retired, self.retired_units);
877
+ // The block a pass holds is a placeholder in the used map and in no free list.
878
+ if let Some((u, k)) = self.punching {
879
+ let x = self.used.get(&u).expect("the punching block is held");
880
+ assert!(x.placeholder && x.class == k, "punching block {u}: {x:?}");
881
+ assert!(
882
+ (0..CLASSES).all(|c| !self.free[c].contains(&u)),
883
+ "punching block {u} is also free"
884
+ );
885
+ }
886
+ // Holes lie in free space only, as disjoint, non-touching ranges.
887
+ let mut prev = 0;
888
+ for (&a, &b) in &self.punched {
889
+ assert!(
890
+ a < b && (prev == 0 || a > prev),
891
+ "punched ranges {a}..{b} after {prev}"
892
+ );
893
+ prev = b;
894
+ let mut at = a;
895
+ while at < b {
896
+ // The block a pass holds keeps its holes while it is out of the free map.
897
+ if let Some((u, k)) = self.punching
898
+ && (u..u + units(k)).contains(&at)
899
+ {
900
+ at = u + units(k);
901
+ continue;
902
+ }
903
+ let (k, u) = (0..CLASSES)
904
+ .find_map(|k| {
905
+ self.free[k]
906
+ .range(..=at)
907
+ .next_back()
908
+ .filter(|&&u| at < u + (1 << k))
909
+ .map(|&u| (k, u))
910
+ })
911
+ .unwrap_or_else(|| panic!("punched unit {at} is not free"));
912
+ at = u + (1 << k);
913
+ }
914
+ }
705
915
  spans.sort_unstable();
706
916
  let mut next = 0;
707
917
  for (s, e) in spans {
@@ -998,6 +1208,226 @@ mod tests {
998
1208
  a.check();
999
1209
  }
1000
1210
 
1211
+ /// Units 1..64 free in blocks of every size: 1, 2..4, 4..8, 8..16, 16..32, 32..64.
1212
+ fn free_ladder() -> Alloc {
1213
+ let a = Alloc::empty(64);
1214
+ a.check();
1215
+ a
1216
+ }
1217
+
1218
+ #[test]
1219
+ fn a_punch_takes_the_largest_block_past_the_reserve_and_records_its_holes() {
1220
+ let mut a = free_ladder();
1221
+ // Nothing kept: the largest block, 32..64.
1222
+ let (unit, class, todo) = a.take_for_punch(0).unwrap();
1223
+ assert_eq!((unit, class, &todo[..]), (32, 5, &[(32, 64)][..]));
1224
+ a.check();
1225
+ assert!(a.take_for_punch(0).is_none(), "one block at a time");
1226
+ assert_eq!(a.alloc_free(5), None, "held while it is punched");
1227
+ a.end_punch(&todo);
1228
+ a.check();
1229
+ assert_eq!(a.punched_units(), 32);
1230
+ // Punched already: the next pass takes the next largest.
1231
+ let (unit, _, todo) = a.take_for_punch(0).unwrap();
1232
+ assert_eq!(unit, 16);
1233
+ a.end_punch(&todo);
1234
+ assert_eq!(a.punched_units(), 48);
1235
+ // The holes coalesced with the rest of the free map: one 32..64 block again, which an
1236
+ // allocation fills, taking it out of the holes.
1237
+ assert_eq!(a.alloc_free(5), Some(ext(32, 5)));
1238
+ a.check();
1239
+ assert_eq!(a.punched_units(), 16);
1240
+ }
1241
+
1242
+ #[test]
1243
+ fn the_reserve_keeps_the_lowest_free_space_unpunched() {
1244
+ let mut a = free_ladder();
1245
+ // 16 units kept: blocks 1, 2..4, 4..8 and 8..16 (15 units) and then 16..32 (the
1246
+ // block that reaches 16) are the reserve; only 32..64 may be punched.
1247
+ let (unit, _, todo) = a.take_for_punch(16).unwrap();
1248
+ assert_eq!(unit, 32);
1249
+ a.end_punch(&todo);
1250
+ assert!(
1251
+ a.take_for_punch(16).is_none(),
1252
+ "everything past the reserve is a hole"
1253
+ );
1254
+ // All of it kept: nothing to punch.
1255
+ assert!(free_ladder().take_for_punch(64).is_none());
1256
+ }
1257
+
1258
+ #[test]
1259
+ fn a_failed_punch_records_nothing_and_a_partial_one_its_part() {
1260
+ let mut a = free_ladder();
1261
+ let (_, _, todo) = a.take_for_punch(0).unwrap();
1262
+ a.end_punch(&[]);
1263
+ a.check();
1264
+ assert_eq!(a.punched_units(), 0);
1265
+ let (_, _, again) = a.take_for_punch(0).unwrap();
1266
+ assert_eq!(again, todo, "tried again");
1267
+ a.end_punch(&[(32, 40)]);
1268
+ let (unit, _, rest) = a.take_for_punch(0).unwrap();
1269
+ assert_eq!(
1270
+ (unit, &rest[..]),
1271
+ (32, &[(40, 64)][..]),
1272
+ "only what is left"
1273
+ );
1274
+ a.end_punch(&rest);
1275
+ a.check();
1276
+ }
1277
+
1278
+ #[test]
1279
+ fn allocations_and_truncation_take_space_out_of_the_holes() {
1280
+ let mut a = free_ladder();
1281
+ let (_, _, todo) = a.take_for_punch(0).unwrap();
1282
+ a.end_punch(&todo);
1283
+ // A small allocation splits the punched block: only its unit leaves the holes.
1284
+ let x = a.alloc_lowest(0).unwrap();
1285
+ assert_eq!(x, ext(1, 0));
1286
+ let y = a.alloc_free(3).unwrap();
1287
+ assert_eq!(y, ext(8, 3), "the smallest free class, not the hole");
1288
+ assert_eq!(a.punched_units(), 32);
1289
+ let z = a.alloc_lowest(4).unwrap();
1290
+ assert_eq!(z, ext(16, 4));
1291
+ let w = a.alloc_free(2).unwrap();
1292
+ assert_eq!(w, ext(4, 2));
1293
+ let v = a.alloc_free(1).unwrap();
1294
+ assert_eq!(v, ext(2, 1));
1295
+ // The next allocation of class 2 splits 32..64: 32..36 holds data now.
1296
+ assert_eq!(a.alloc_free(2), Some(ext(32, 2)));
1297
+ assert_eq!(a.punched_units(), 28);
1298
+ a.check();
1299
+ // Truncating drops the tail's holes with it.
1300
+ a.release_live(ext(32, 2));
1301
+ a.truncate(a.used_end());
1302
+ a.check();
1303
+ assert_eq!(a.punched_units(), 0);
1304
+ assert_eq!(a.frontier(), 32);
1305
+ }
1306
+
1307
+ /// simp724's C2 on #2013: every user of the placeholder flag treats a block mid-punch as
1308
+ /// allocated.
1309
+ #[test]
1310
+ fn a_block_mid_punch_is_neither_moved_nor_truncated_nor_cleared_around() {
1311
+ // Live at 1 and 2..4; 4..8, 8..16 and the tail 16..32 free.
1312
+ let mut a = Alloc::load(32, [ext(1, 0), ext(2, 1)]).unwrap();
1313
+ let (unit, class, todo) = a.take_for_punch(0).unwrap();
1314
+ assert_eq!((unit, class), (16, 4), "the tail");
1315
+ // A shrink names no extent to move (the block is not live data) and cannot cut the
1316
+ // file below it while it is held.
1317
+ assert!(a.shrink_plan().is_empty());
1318
+ assert_eq!(a.used_end(), 32);
1319
+ a.truncate(a.used_end());
1320
+ a.check();
1321
+ assert_eq!(a.frontier(), 32);
1322
+ // No region is cleared around it: a 16-unit extent above finds 16..32 occupied by a
1323
+ // placeholder it may not move.
1324
+ let mut b = Alloc::load(64, [ext(1, 0), ext(32, 4)]).unwrap();
1325
+ let (u, k, t) = b.take_for_punch(0).unwrap();
1326
+ assert_eq!((u, k), (48, 4));
1327
+ b.end_punch(&t);
1328
+ let (u, k, _) = b.take_for_punch(0).unwrap();
1329
+ assert_eq!((u, k), (16, 4));
1330
+ assert!(b.clear_for(ext(32, 4), &|_| true, 16, 512).is_none());
1331
+ b.check();
1332
+ // Once returned, the tail truncates as before, holes and all.
1333
+ a.end_punch(&todo);
1334
+ a.truncate(a.used_end());
1335
+ a.check();
1336
+ assert_eq!((a.frontier(), a.punched_units()), (4, 0));
1337
+ }
1338
+
1339
+ /// The pick `take_for_punch` must make, the obvious way: every free block in address
1340
+ /// order, the ones past the reserve, the largest (then highest) with space not punched.
1341
+ fn naive_punch_pick(a: &Alloc, reserve: u64) -> Option<(u64, u8, UnitRanges)> {
1342
+ if a.punching.is_some() {
1343
+ return None;
1344
+ }
1345
+ let mut blocks: Vec<(u64, u8)> = (0..CLASSES)
1346
+ .flat_map(|k| a.free[k].iter().map(move |&u| (u, k as u8)))
1347
+ .collect();
1348
+ blocks.sort_unstable();
1349
+ let mut kept = 0;
1350
+ blocks
1351
+ .into_iter()
1352
+ .skip_while(|&(_, k)| {
1353
+ let keep = kept < reserve;
1354
+ kept += units(k);
1355
+ keep
1356
+ })
1357
+ .filter_map(|(u, k)| {
1358
+ let todo = a.unpunched(u, u + units(k));
1359
+ (!todo.is_empty()).then_some((u, k, todo))
1360
+ })
1361
+ .max_by_key(|&(u, k, _)| (k, u))
1362
+ }
1363
+
1364
+ #[derive(Debug, Clone)]
1365
+ enum PunchOp {
1366
+ Alloc(u8),
1367
+ Release(usize),
1368
+ Punch { reserve: u64, keep: usize },
1369
+ Truncate,
1370
+ }
1371
+
1372
+ fn punch_op() -> impl proptest::strategy::Strategy<Value = PunchOp> {
1373
+ use proptest::prelude::*;
1374
+ prop_oneof![
1375
+ 3 => (0u8..6).prop_map(PunchOp::Alloc),
1376
+ 2 => any::<usize>().prop_map(PunchOp::Release),
1377
+ 3 => (0u64..96, 0usize..4).prop_map(|(reserve, keep)| PunchOp::Punch { reserve, keep }),
1378
+ 1 => Just(PunchOp::Truncate),
1379
+ ]
1380
+ }
1381
+
1382
+ proptest::proptest! {
1383
+ /// simp724's S1 on #2033: the bounded pick agrees with the naive one on any free
1384
+ /// map, holes and all.
1385
+ #[test]
1386
+ fn the_bounded_punch_pick_matches_the_naive_one(
1387
+ ops in proptest::collection::vec(punch_op(), 1..80),
1388
+ ) {
1389
+ let mut a = Alloc::empty(128);
1390
+ let mut live: Vec<Extent> = Vec::new();
1391
+ for op in ops {
1392
+ match op {
1393
+ PunchOp::Alloc(k) => live.extend(a.alloc_lowest(k)),
1394
+ PunchOp::Release(i) if !live.is_empty() => {
1395
+ let x = live.swap_remove(i % live.len());
1396
+ proptest::prop_assert!(a.release_live(x));
1397
+ }
1398
+ PunchOp::Release(_) => {}
1399
+ PunchOp::Punch { reserve, keep } => {
1400
+ let want = naive_punch_pick(&a, reserve);
1401
+ let got = a.take_for_punch(reserve);
1402
+ proptest::prop_assert_eq!(&got, &want);
1403
+ a.check();
1404
+ if let Some((_, _, todo)) = got {
1405
+ // Record all, some or none of it (a failed or partial punch).
1406
+ a.end_punch(&todo[..keep.min(todo.len())]);
1407
+ }
1408
+ }
1409
+ PunchOp::Truncate => a.truncate(a.used_end()),
1410
+ }
1411
+ a.check();
1412
+ }
1413
+ }
1414
+ }
1415
+
1416
+ #[test]
1417
+ fn a_block_mid_punch_does_not_make_the_file_grow_ahead() {
1418
+ // Exactly one free block of the ahead class: taking it for a punch is not a reason
1419
+ // to grow.
1420
+ let mut a = Alloc::load(8, [ext(1, 0), ext(2, 1)]).unwrap();
1421
+ a.set_ahead(2, 0);
1422
+ assert!(!a.wants_ahead());
1423
+ let (unit, class, todo) = a.take_for_punch(0).unwrap();
1424
+ assert_eq!((unit, class), (4, 2));
1425
+ assert!(!a.wants_ahead());
1426
+ a.end_punch(&todo);
1427
+ assert!(!a.wants_ahead());
1428
+ a.check();
1429
+ }
1430
+
1001
1431
  #[test]
1002
1432
  fn a_small_file_does_not_grow_ahead() {
1003
1433
  let a = Alloc::empty(3);