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
@@ -19,7 +19,7 @@
19
19
 
20
20
  use pigeonhole_format::hash::FastMap;
21
21
  use std::path::{Path, PathBuf};
22
- use std::sync::atomic::{AtomicU64, Ordering};
22
+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
23
23
  use std::sync::{Arc, Mutex, OnceLock, PoisonError};
24
24
 
25
25
  use pigeonhole_format::BlobFileId;
@@ -330,6 +330,8 @@ pub(crate) fn last_of(entries: &[FeedEntry]) -> Option<LastSession> {
330
330
  /// The change feed's session at open (D310): `None` with the feed off, after appending
331
331
  /// "fed: none" to an existing sidecar. With it on: the retention per stream (`bytes / N`,
332
332
  /// at least two segments), a random session id, and the session's sidecar entry, synced.
333
+ /// `previous_retention` is the last session's, for `DbInfo` (#1786).
334
+ #[allow(clippy::too_many_arguments)]
333
335
  pub(crate) fn open_session(
334
336
  vfs: &VfsRef,
335
337
  path: &Path,
@@ -338,6 +340,7 @@ pub(crate) fn open_session(
338
340
  options: &EngineOptions,
339
341
  shards: usize,
340
342
  opened: OpenedRoot,
343
+ previous_retention: Option<u64>,
341
344
  ) -> Result<Option<Arc<Feed>>> {
342
345
  let opened_at = opened.sequence;
343
346
  let Some(cfg) = &options.feed else {
@@ -389,6 +392,7 @@ pub(crate) fn open_session(
389
392
  .ok_or_else(|| Error::Corruption("the feed sidecar could not be created".into()))?;
390
393
  let mut feed = Feed::new(session, retain, cfg.max_age_micros, tables, shards);
391
394
  feed.retain_bytes_per_stream = cfg.retention_bytes / streams;
395
+ feed.previous_retention_bytes = previous_retention;
392
396
  if let Some(us) = cfg.sync_interval_micros {
393
397
  feed.sync_interval_nanos = us.saturating_mul(1_000).max(1);
394
398
  }
@@ -447,6 +451,61 @@ struct Held {
447
451
  claimed: Vec<BlobFileId>,
448
452
  }
449
453
 
454
+ /// Wakers by reader key, with a flag that lets a wake with none registered cost one load.
455
+ ///
456
+ /// The waiter and the waker each store, then load, across two atomics: the waiter stores
457
+ /// the flag ([`register`](Self::register)) and then loads what it waits for; the waker
458
+ /// stores that and then loads the flag ([`wake_all`](Self::wake_all)). Each has a SeqCst
459
+ /// fence between its store and its load, so one of them sees the other.
460
+ #[derive(Debug, Default)]
461
+ struct WakerList {
462
+ wakers: Mutex<FastMap<u64, std::task::Waker>>,
463
+ /// Whether `wakers` may be non-empty.
464
+ any: std::sync::atomic::AtomicBool,
465
+ }
466
+
467
+ impl WakerList {
468
+ /// Registers `waker` under `key`, replacing its last one. The caller re-checks what it
469
+ /// waits for afterwards.
470
+ fn register(&self, key: u64, waker: &std::task::Waker) {
471
+ let mut w = self.wakers.lock().unwrap_or_else(PoisonError::into_inner);
472
+ w.insert(key, waker.clone());
473
+ self.any.store(true, Ordering::SeqCst);
474
+ drop(w);
475
+ // Pairs with the fence in `wake_all`: the caller's re-check can't be ordered before
476
+ // the flag's store.
477
+ std::sync::atomic::fence(Ordering::SeqCst);
478
+ }
479
+
480
+ /// Forgets `key`'s waker.
481
+ fn forget(&self, key: u64) {
482
+ let mut w = self.wakers.lock().unwrap_or_else(PoisonError::into_inner);
483
+ if w.remove(&key).is_some() && w.is_empty() {
484
+ self.any.store(false, Ordering::SeqCst);
485
+ }
486
+ }
487
+
488
+ /// Wakes every waker, after the caller stored what they wait for. Out of line: its
489
+ /// callers are on the shard's settle, which pays the fence and one load when none waits.
490
+ #[inline(never)]
491
+ fn wake_all(&self) {
492
+ // The caller's store before the flag's load: store then load on different atomics
493
+ // needs a SeqCst fence on each side (`register`).
494
+ std::sync::atomic::fence(Ordering::SeqCst);
495
+ if !self.any.load(Ordering::SeqCst) {
496
+ return;
497
+ }
498
+ let woken: Vec<std::task::Waker> = {
499
+ let mut w = self.wakers.lock().unwrap_or_else(PoisonError::into_inner);
500
+ self.any.store(false, Ordering::SeqCst);
501
+ w.drain().map(|(_, waker)| waker).collect()
502
+ };
503
+ for waker in woken {
504
+ waker.wake();
505
+ }
506
+ }
507
+ }
508
+
450
509
  /// The change feed's writer-side state, in `Shared::feed` while the feed is on.
451
510
  #[derive(Debug)]
452
511
  pub(crate) struct Feed {
@@ -461,6 +520,8 @@ pub(crate) struct Feed {
461
520
  /// The retention in effect, for the whole database: the request, rounded up to whole
462
521
  /// segments per stream and raised to two of them (`DatabaseInfo` reports it).
463
522
  pub retention_bytes: u64,
523
+ /// The retention the sidecar's last session requested, if there was one (#1786).
524
+ pub previous_retention_bytes: Option<u64>,
464
525
  /// Retention age, microseconds of the VFS clock.
465
526
  pub age_micros: Option<u64>,
466
527
  /// The tables this session feeds.
@@ -472,6 +533,12 @@ pub(crate) struct Feed {
472
533
  pub sync_interval_nanos: u64,
473
534
  /// Each stream's feed marks, set as its stream opens.
474
535
  marks: Vec<OnceLock<Arc<FeedMarks>>>,
536
+ /// Retention holds (D331, ICR 0141), oldest first. A leaf lock: taken by
537
+ /// `hold_retention` and a hold's release, and by a shard's feed maintenance only while
538
+ /// `retention_hold_count` isn't 0. Each stream's mark holds the oldest epoch any hold
539
+ /// keeps, stored under it.
540
+ retention_holds: Mutex<Vec<Arc<RetentionHold>>>,
541
+ retention_hold_count: AtomicUsize,
475
542
  held: Mutex<Held>,
476
543
  /// Bytes of the held files (`DatabaseInfo`).
477
544
  held_bytes: AtomicU64,
@@ -493,29 +560,29 @@ pub(crate) struct Feed {
493
560
  /// every table in this process expire on seeing it; the manifest pump freezes the catalog
494
561
  /// hold (`catalog_hold_frozen`) so no feed's frontier passes a change that has no entry.
495
562
  appends_stopped: std::sync::atomic::AtomicBool,
563
+ /// The writer's shared-memory region, once the open built it (after this session): where
564
+ /// a stop is published for reader processes, whose feeds of every table expire on it
565
+ /// (D315 amendment, #1869). See [`Feed::stop_appends`] and [`Feed::publish_to`].
566
+ shm: OnceLock<pigeonhole_shm::ShmRegion>,
496
567
  /// The catalog hold is frozen for the rest of the session (set once, by the manifest
497
568
  /// pump, after `appends_stopped`): never released.
498
569
  catalog_hold_frozen: std::sync::atomic::AtomicBool,
499
570
  /// Async feed readers waiting for one of the feed's own holds (WRITTEN/SYNCED) to let
500
571
  /// go (D310 PR 5a), by reader key. The watermark registries wake a reader whose frontier
501
572
  /// waits on the visible or durable watermark, but a hold releasing moves the frontier
502
- /// without a publish there, so the shard wakes these when it releases one.
503
- hold_waiters: Mutex<FastMap<u64, std::task::Waker>>,
504
- /// Whether `hold_waiters` may be non-empty: the shard's release checks this alone, so a
505
- /// release with no async feed waiting costs one load.
506
- has_hold_waiters: std::sync::atomic::AtomicBool,
573
+ /// without a publish there, so the shard wakes these when it releases one. A release
574
+ /// with no async feed waiting costs the list's one load.
575
+ hold_waiters: WakerList,
507
576
  /// Feeds of every table waiting for a catalog change, which moves no seqno, by reader
508
577
  /// key (the idle-catalog fix after #1515): woken by `manifest::release_catalog` and on
509
578
  /// close, never by the shards' settles, so an idle feed of every table costs the shards
510
579
  /// nothing (simp724's P1 on #1539).
511
- catalog_waiters: Mutex<FastMap<u64, std::task::Waker>>,
512
- /// Whether `catalog_waiters` may be non-empty.
513
- has_catalog_waiters: std::sync::atomic::AtomicBool,
580
+ catalog_waiters: WakerList,
581
+ /// Catalog changes of this session whose Root entry is written (`catalog_roots`).
582
+ catalog_roots: AtomicU64,
514
583
  /// A hold seam (`Engine::delay_root_observer`, #1504): nanoseconds each root commit's
515
584
  /// observer waits before it records the root, widening the window between a durable
516
585
  /// superblock and its sidecar entry. 0 (the default) waits nothing.
517
- /// Catalog changes of this session whose Root entry is written (`catalog_roots`).
518
- catalog_roots: AtomicU64,
519
586
  #[cfg(feature = "test-hooks")]
520
587
  pub(crate) root_observer_delay_nanos: AtomicU64,
521
588
  /// A hold seam (`Engine::delay_root_intent`, D315 amendment): nanoseconds each root
@@ -523,6 +590,43 @@ pub(crate) struct Feed {
523
590
  /// window between the intent and the superblock. 0 (the default) waits nothing.
524
591
  #[cfg(feature = "test-hooks")]
525
592
  pub(crate) root_intent_delay_nanos: AtomicU64,
593
+ /// A fault seam (`Engine::fail_next_sidecar_sync`, #1869): the next sidecar sync
594
+ /// completes as failed, once, though the VFS's succeeded.
595
+ #[cfg(feature = "test-hooks")]
596
+ pub(crate) fail_next_sidecar_sync: std::sync::atomic::AtomicBool,
597
+ /// A fault seam (`Engine::before_next_root_write`, #1869): runs once, in the root-commit
598
+ /// observer, after the root's intent landed and before its Root entry is written, so a
599
+ /// test fails that write alone.
600
+ #[cfg(feature = "test-hooks")]
601
+ pub(crate) before_root_write: OnceHook,
602
+ }
603
+
604
+ /// A test's one-shot callback (`Feed::before_root_write`).
605
+ #[cfg(feature = "test-hooks")]
606
+ #[derive(Default)]
607
+ pub(crate) struct OnceHook(Mutex<Option<Box<dyn FnOnce() + Send>>>);
608
+
609
+ #[cfg(feature = "test-hooks")]
610
+ impl OnceHook {
611
+ /// Arms `f` for the next run, replacing one not yet run.
612
+ pub(crate) fn arm(&self, f: Box<dyn FnOnce() + Send>) {
613
+ *self.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(f);
614
+ }
615
+
616
+ /// Runs the armed callback, if any, once.
617
+ fn run(&self) {
618
+ let f = self.0.lock().unwrap_or_else(PoisonError::into_inner).take();
619
+ if let Some(f) = f {
620
+ f();
621
+ }
622
+ }
623
+ }
624
+
625
+ #[cfg(feature = "test-hooks")]
626
+ impl std::fmt::Debug for OnceHook {
627
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
628
+ f.write_str("OnceHook")
629
+ }
526
630
  }
527
631
 
528
632
  /// A catalog change staged for its root commit's `Catalog` sidecar entry (D315).
@@ -569,11 +673,14 @@ impl Feed {
569
673
  retain_segments,
570
674
  retain_bytes_per_stream: 0,
571
675
  retention_bytes: 0,
676
+ previous_retention_bytes: None,
572
677
  age_micros,
573
678
  tables,
574
679
  flush_interval_nanos: FLUSH_INTERVAL_NANOS,
575
680
  sync_interval_nanos: SYNC_INTERVAL_NANOS,
576
681
  marks: (0..streams).map(|_| OnceLock::new()).collect(),
682
+ retention_holds: Mutex::default(),
683
+ retention_hold_count: AtomicUsize::new(0),
577
684
  held: Mutex::default(),
578
685
  held_bytes: AtomicU64::new(0),
579
686
  sidecar: Mutex::new(None),
@@ -582,23 +689,28 @@ impl Feed {
582
689
  checkpoints: (0..streams).map(|_| Mutex::default()).collect(),
583
690
  staged_catalog: Mutex::default(),
584
691
  appends_stopped: std::sync::atomic::AtomicBool::new(false),
692
+ shm: OnceLock::new(),
585
693
  catalog_hold_frozen: std::sync::atomic::AtomicBool::new(false),
586
- hold_waiters: Mutex::default(),
587
- has_hold_waiters: std::sync::atomic::AtomicBool::new(false),
588
- catalog_waiters: Mutex::default(),
589
- has_catalog_waiters: std::sync::atomic::AtomicBool::new(false),
694
+ hold_waiters: WakerList::default(),
695
+ catalog_waiters: WakerList::default(),
590
696
  catalog_roots: AtomicU64::new(0),
591
697
  #[cfg(feature = "test-hooks")]
592
698
  root_observer_delay_nanos: AtomicU64::new(0),
593
699
  #[cfg(feature = "test-hooks")]
594
700
  root_intent_delay_nanos: AtomicU64::new(0),
701
+ #[cfg(feature = "test-hooks")]
702
+ fail_next_sidecar_sync: std::sync::atomic::AtomicBool::new(false),
703
+ #[cfg(feature = "test-hooks")]
704
+ before_root_write: OnceHook::default(),
595
705
  }
596
706
  }
597
707
 
598
708
  /// Stream `stream`'s checkpoint moved to `at`, past records of keys at most `key`
599
709
  /// (`ShardState::ckpt_key`). Called before the stream's own checkpoint mark is stored,
600
710
  /// so a reader that loaded the mark finds an entry at least that new. At most two
601
- /// entries per segment: the first, and the latest.
711
+ /// entries per segment: the first, and the latest. The first is never replaced:
712
+ /// [`hold_retention`](Self::hold_retention)'s guarantee rests on it (a snapshot opened
713
+ /// after a hold starts at an entry in the held epoch or later; feed1248 on #2109).
602
714
  pub(crate) fn note_checkpoint(
603
715
  &self,
604
716
  stream: usize,
@@ -734,92 +846,42 @@ impl Feed {
734
846
  /// Registers `waker` (reader `key`, replacing its last one) to be woken when a hold lets
735
847
  /// go. The caller loads the frontier again afterwards: a release that published before
736
848
  /// this registration is seen there; one after it finds the waker.
849
+ ///
850
+ /// The list's fence pairs with the one in `wake_hold_waiters`: the caller's re-check of
851
+ /// the frontier (an Acquire load of WRITTEN/SYNCED) can't be ordered before the flag's
852
+ /// store, so either it sees the shard's release or the shard sees the flag.
737
853
  pub(crate) fn wait_for_hold(&self, key: u64, waker: &std::task::Waker) {
738
- let mut w = self
739
- .hold_waiters
740
- .lock()
741
- .unwrap_or_else(PoisonError::into_inner);
742
- w.insert(key, waker.clone());
743
- self.has_hold_waiters.store(true, Ordering::SeqCst);
744
- drop(w);
745
- // Pairs with the fence in `wake_hold_waiters`: the caller's re-check of the frontier
746
- // (an Acquire load of WRITTEN/SYNCED) can't be ordered before this store, so either
747
- // it sees the shard's release or the shard sees this flag.
748
- std::sync::atomic::fence(Ordering::SeqCst);
854
+ self.hold_waiters.register(key, waker);
749
855
  }
750
856
 
751
857
  /// Registers `waker` (reader `key`, a feed of every table) to be woken when a catalog
752
858
  /// change's hold is released, as [`wait_for_hold`](Self::wait_for_hold) for the shards'
753
859
  /// holds: the caller re-checks [`catalog_roots`](Self::catalog_roots) afterwards.
754
860
  pub(crate) fn wait_for_catalog(&self, key: u64, waker: &std::task::Waker) {
755
- let mut w = self
756
- .catalog_waiters
757
- .lock()
758
- .unwrap_or_else(PoisonError::into_inner);
759
- w.insert(key, waker.clone());
760
- self.has_catalog_waiters.store(true, Ordering::SeqCst);
761
- drop(w);
762
- // Pairs with the fence in `wake_catalog_waiters`.
763
- std::sync::atomic::fence(Ordering::SeqCst);
861
+ self.catalog_waiters.register(key, waker);
764
862
  }
765
863
 
766
864
  /// Forgets reader `key`'s wakers, on both lists (the reader is dropped, or delivered).
767
865
  pub(crate) fn forget_hold_waiter(&self, key: u64) {
768
- for (list, flag) in [
769
- (&self.hold_waiters, &self.has_hold_waiters),
770
- (&self.catalog_waiters, &self.has_catalog_waiters),
771
- ] {
772
- let mut w = list.lock().unwrap_or_else(PoisonError::into_inner);
773
- if w.remove(&key).is_some() && w.is_empty() {
774
- flag.store(false, Ordering::SeqCst);
775
- }
776
- }
866
+ self.hold_waiters.forget(key);
867
+ self.catalog_waiters.forget(key);
777
868
  }
778
869
 
779
870
  /// After a catalog change's hold is released (`release_catalog`, its Root entry and
780
871
  /// `catalog_roots` stored first): wakes every feed of every table waiting for one, as
781
872
  /// [`wake_hold_waiters`](Self::wake_hold_waiters) does for the shards' holds.
782
- #[inline(never)]
873
+ #[inline]
783
874
  pub(crate) fn wake_catalog_waiters(&self) {
784
- std::sync::atomic::fence(Ordering::SeqCst);
785
- if !self.has_catalog_waiters.load(Ordering::SeqCst) {
786
- return;
787
- }
788
- let woken: Vec<std::task::Waker> = {
789
- let mut w = self
790
- .catalog_waiters
791
- .lock()
792
- .unwrap_or_else(PoisonError::into_inner);
793
- self.has_catalog_waiters.store(false, Ordering::SeqCst);
794
- w.drain().map(|(_, waker)| waker).collect()
795
- };
796
- for waker in woken {
797
- waker.wake();
798
- }
875
+ self.catalog_waiters.wake_all();
799
876
  }
800
877
 
801
878
  /// After a shard let one of its holds go (its WRITTEN or SYNCED store published first):
802
- /// wakes every async reader waiting on a hold. One load when none waits; out of line, so
803
- /// the shard's settle stays small (perf287's codegen lesson on #1297).
804
- #[inline(never)]
879
+ /// wakes every async reader waiting on a hold. One load when none waits; the list's
880
+ /// wake is out of line, so the shard's settle stays small (perf287's codegen lesson on
881
+ /// #1297).
882
+ #[inline]
805
883
  pub(crate) fn wake_hold_waiters(&self) {
806
- // The release's WRITTEN/SYNCED store (Release) before the flag's load: store then
807
- // load on different atomics needs a SeqCst fence on each side (`wait_for_hold`).
808
- std::sync::atomic::fence(Ordering::SeqCst);
809
- if !self.has_hold_waiters.load(Ordering::SeqCst) {
810
- return;
811
- }
812
- let woken: Vec<std::task::Waker> = {
813
- let mut w = self
814
- .hold_waiters
815
- .lock()
816
- .unwrap_or_else(PoisonError::into_inner);
817
- self.has_hold_waiters.store(false, Ordering::SeqCst);
818
- w.drain().map(|(_, waker)| waker).collect()
819
- };
820
- for waker in woken {
821
- waker.wake();
822
- }
884
+ self.hold_waiters.wake_all();
823
885
  }
824
886
 
825
887
  /// Stream `stream`'s marks, once its stream is open.
@@ -872,7 +934,7 @@ impl Feed {
872
934
  if let Err(e) = appended {
873
935
  crate::shard::trace!("feed: sidecar append of intent {sequence} failed: {e}");
874
936
  *sidecar = None;
875
- self.appends_stopped.store(true, Ordering::Release);
937
+ self.stop_appends();
876
938
  }
877
939
  drop(sidecar);
878
940
  #[cfg(feature = "test-hooks")]
@@ -895,6 +957,7 @@ impl Feed {
895
957
  if delay > 0 {
896
958
  std::thread::sleep(std::time::Duration::from_nanos(delay));
897
959
  }
960
+ self.before_root_write.run();
898
961
  }
899
962
  // A catalog change whose intent didn't append it (no intent hook ran): its entry
900
963
  // goes first, in the same append as the Root entry.
@@ -936,7 +999,7 @@ impl Feed {
936
999
  if let Err(e) = written {
937
1000
  crate::shard::trace!("feed: sidecar write of root {sequence} failed: {e}");
938
1001
  *sidecar = None;
939
- self.appends_stopped.store(true, Ordering::Release);
1002
+ self.stop_appends();
940
1003
  return;
941
1004
  }
942
1005
  if catalog {
@@ -970,6 +1033,35 @@ impl Feed {
970
1033
  self.appends_stopped.load(Ordering::Acquire)
971
1034
  }
972
1035
 
1036
+ /// Stops the session's sidecar appends (D315; simp724 on #1493): terminal. Also
1037
+ /// publishes the stop in the writer's shared-memory region for reader processes (D315
1038
+ /// amendment, #1869), if the open has built it yet; [`publish_to`](Self::publish_to)
1039
+ /// publishes a stop made before then.
1040
+ fn stop_appends(&self) {
1041
+ self.appends_stopped.store(true, Ordering::SeqCst);
1042
+ // A Dekker pair with `publish_to`'s set-then-load (SeqCst both sides): either this
1043
+ // load sees the region, or that load sees the stop, so a stop made as the open
1044
+ // attaches the region is published once at least.
1045
+ std::sync::atomic::fence(Ordering::SeqCst);
1046
+ if let Some(shm) = self.shm.get() {
1047
+ shm.publish_feed_appends_stopped();
1048
+ }
1049
+ }
1050
+
1051
+ /// Gives the session the writer's shared-memory region, once the open built it (D315
1052
+ /// amendment, #1869), and publishes a stop already made: root commits of this open
1053
+ /// (`finish`'s upgrade) may have stopped the appends before the region existed.
1054
+ pub(crate) fn publish_to(&self, shm: pigeonhole_shm::ShmRegion) {
1055
+ let set = self.shm.set(shm);
1056
+ debug_assert!(set.is_ok(), "a session is handed its region once");
1057
+ std::sync::atomic::fence(Ordering::SeqCst);
1058
+ if self.appends_stopped.load(Ordering::SeqCst)
1059
+ && let Some(shm) = self.shm.get()
1060
+ {
1061
+ shm.publish_feed_appends_stopped();
1062
+ }
1063
+ }
1064
+
973
1065
  /// Marks the catalog hold frozen for the rest of the session: the hold `release_catalog`
974
1066
  /// would have let go stays up.
975
1067
  pub(crate) fn freeze_catalog_hold(&self) {
@@ -1019,13 +1111,22 @@ impl Feed {
1019
1111
  let again = Arc::clone(&file);
1020
1112
  // `sync_all`: an append grows the file, and its new length must be durable with it.
1021
1113
  drop(file.submit_sync_all().map(move |r| {
1114
+ #[cfg(feature = "test-hooks")]
1115
+ let r = if this.fail_next_sidecar_sync.swap(false, Ordering::AcqRel) {
1116
+ Err(pigeonhole_io::Error::new(
1117
+ pigeonhole_io::ErrorKind::Other,
1118
+ "injected sidecar sync failure",
1119
+ ))
1120
+ } else {
1121
+ r
1122
+ };
1022
1123
  if let Err(e) = &r {
1023
1124
  // Fail closed (simp724): no retry, and no append that a later sync could
1024
1125
  // report clean over pages the kernel dropped. The next open finds the
1025
1126
  // sequence ahead of the last entry and expires every token.
1026
1127
  crate::shard::trace!("feed: sidecar sync failed, no more appends: {e}");
1027
1128
  *this.sidecar.lock().unwrap_or_else(PoisonError::into_inner) = None;
1028
- this.appends_stopped.store(true, Ordering::Release);
1129
+ this.stop_appends();
1029
1130
  let mut st = this
1030
1131
  .sidecar_sync
1031
1132
  .lock()
@@ -1066,6 +1167,92 @@ impl Feed {
1066
1167
  self.sidecar_syncs.load(Ordering::Relaxed)
1067
1168
  }
1068
1169
 
1170
+ /// Holds every stream's history from its checkpoint's segment on (D331, ICR 0141), until
1171
+ /// the hold is released or the database retains more than `cap` bytes of history, when
1172
+ /// it lapses: it's dropped and marked so, and retention trims as before. `None` until
1173
+ /// every stream is open.
1174
+ ///
1175
+ /// **From the checkpoint, not the head** (found by #2107's tests): a token taken from a
1176
+ /// snapshot doesn't know the snapshot's place in each stream's log, so it starts the
1177
+ /// stream's scan at its checkpoint then, which can be segments behind the head. A token
1178
+ /// from now, or of a snapshot opened after the hold (more exactly, whose checkpoint
1179
+ /// start is read after the hold's), starts each stream at or past that stream's
1180
+ /// checkpoint at the hold, since checkpoints only move forward: so the hold covers it. A
1181
+ /// snapshot opened before the hold may carry an older checkpoint, and its token isn't
1182
+ /// covered (simp724): take the hold first. What it keeps beyond a head-only hold is the
1183
+ /// stream's unflushed log at the hold, which the memtable budget bounds.
1184
+ ///
1185
+ /// Retention never trims a segment at or past a stream's checkpoint, so the hold starts
1186
+ /// at history the stream has; it takes effect at each stream's next retention pass. A
1187
+ /// pass between the epochs' read and their publication (simp724 on the fix) can only
1188
+ /// trim segments behind a checkpoint that moved on meanwhile, below every later token's
1189
+ /// start: the hold then names a trimmed epoch, which keeps everything from the floor on,
1190
+ /// and no token taken after it is affected.
1191
+ pub(crate) fn hold_retention(&self, cap: u64) -> Option<Arc<RetentionHold>> {
1192
+ let mut holds = self
1193
+ .retention_holds
1194
+ .lock()
1195
+ .unwrap_or_else(PoisonError::into_inner);
1196
+ let epochs = self
1197
+ .marks
1198
+ .iter()
1199
+ .map(|m| m.get().map(|m| m.checkpoint().epoch().clamp(1, m.head())))
1200
+ .collect::<Option<Vec<u32>>>()?;
1201
+ let hold = Arc::new(RetentionHold {
1202
+ epochs,
1203
+ cap,
1204
+ lapsed: AtomicBool::new(false),
1205
+ });
1206
+ holds.push(Arc::clone(&hold));
1207
+ self.publish_holds(&holds);
1208
+ Some(hold)
1209
+ }
1210
+
1211
+ /// Lets `hold` go (a no-op once it lapsed).
1212
+ pub(crate) fn release_retention(&self, hold: &Arc<RetentionHold>) {
1213
+ let mut holds = self
1214
+ .retention_holds
1215
+ .lock()
1216
+ .unwrap_or_else(PoisonError::into_inner);
1217
+ holds.retain(|h| !Arc::ptr_eq(h, hold));
1218
+ self.publish_holds(&holds);
1219
+ }
1220
+
1221
+ /// Lapses every hold whose cap the retained history has passed (a shard's feed
1222
+ /// maintenance, before its retention pass). One load while nothing holds.
1223
+ pub(crate) fn enforce_retention_caps(&self) {
1224
+ if self.retention_hold_count.load(Ordering::Acquire) == 0 {
1225
+ return;
1226
+ }
1227
+ let retained = self.retained_bytes();
1228
+ let mut holds = self
1229
+ .retention_holds
1230
+ .lock()
1231
+ .unwrap_or_else(PoisonError::into_inner);
1232
+ let before = holds.len();
1233
+ holds.retain(|h| {
1234
+ let keep = retained <= h.cap;
1235
+ if !keep {
1236
+ h.lapsed.store(true, Ordering::Release);
1237
+ }
1238
+ keep
1239
+ });
1240
+ if holds.len() != before {
1241
+ self.publish_holds(&holds);
1242
+ }
1243
+ }
1244
+
1245
+ /// Stores each stream's oldest held epoch in its marks, under the holds' lock.
1246
+ fn publish_holds(&self, holds: &[Arc<RetentionHold>]) {
1247
+ for (s, m) in self.marks.iter().enumerate() {
1248
+ if let Some(m) = m.get() {
1249
+ m.set_hold(holds.iter().map(|h| h.epochs[s]).min());
1250
+ }
1251
+ }
1252
+ self.retention_hold_count
1253
+ .store(holds.len(), Ordering::Release);
1254
+ }
1255
+
1069
1256
  /// The WAL bytes retained as history, over every stream.
1070
1257
  pub(crate) fn retained_bytes(&self) -> u64 {
1071
1258
  self.marks
@@ -1213,6 +1400,23 @@ impl Feed {
1213
1400
  /// Drops the held blob files the history has passed (from a shard's maintenance): one
1214
1401
  /// manifest request at a time, computed against the catalog at commit, so a file whose
1215
1402
  /// hold came from a commit that failed (still live there) is left alone.
1403
+ /// A retention hold ([`Feed::hold_retention`], D331): each stream's epoch it keeps history
1404
+ /// from, its cap, and whether it lapsed at the cap.
1405
+ #[derive(Debug)]
1406
+ pub(crate) struct RetentionHold {
1407
+ epochs: Vec<u32>,
1408
+ cap: u64,
1409
+ lapsed: AtomicBool,
1410
+ }
1411
+
1412
+ impl RetentionHold {
1413
+ /// Whether it lapsed: the history it kept passed its cap, so retention trims again and a
1414
+ /// reader it was for may find its position gone.
1415
+ pub(crate) fn lapsed(&self) -> bool {
1416
+ self.lapsed.load(Ordering::Acquire)
1417
+ }
1418
+ }
1419
+
1216
1420
  pub(crate) fn release_held(shared: &Arc<Shared>, shard: ShardId) {
1217
1421
  let Some(feed) = &shared.feed else {
1218
1422
  return;
@@ -1325,4 +1529,29 @@ mod tests {
1325
1529
  Some(want)
1326
1530
  );
1327
1531
  }
1532
+
1533
+ /// #1869: a stop made before the open hands the session its region (a root commit of
1534
+ /// the open's own `finish`) is published when it does, and one made after is published
1535
+ /// at once. Mutation-checked: without `publish_to`'s check, the first case fails.
1536
+ #[test]
1537
+ fn a_stop_is_published_whether_it_comes_before_or_after_the_region() {
1538
+ for stop_first in [true, false] {
1539
+ let feed = Feed::new(1, 2, None, FeedTables::All, 1);
1540
+ let shm =
1541
+ pigeonhole_shm::ShmRegion::in_memory([1; 16], &pigeonhole_shm::ShmConfig::new(1));
1542
+ if stop_first {
1543
+ feed.stop_appends();
1544
+ assert!(!shm.feed_appends_stopped(), "no region yet");
1545
+ }
1546
+ feed.publish_to(shm.clone());
1547
+ assert_eq!(shm.feed_appends_stopped(), stop_first, "{stop_first}");
1548
+ if !stop_first {
1549
+ feed.stop_appends();
1550
+ }
1551
+ assert!(
1552
+ feed.appends_stopped() && shm.feed_appends_stopped(),
1553
+ "{stop_first}"
1554
+ );
1555
+ }
1556
+ }
1328
1557
  }