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
@@ -77,6 +77,23 @@ pub struct FamilyInfo {
77
77
  pub options: FamilyOptions,
78
78
  }
79
79
 
80
+ /// One tablet as [`Engine::tablets`] reports it (D332, ICR 0142). Not part of the stable API.
81
+ #[doc(hidden)]
82
+ #[derive(Debug, Clone, PartialEq)]
83
+ #[non_exhaustive]
84
+ pub struct TabletStats {
85
+ /// Its table's name.
86
+ pub table: String,
87
+ /// Inclusive start row; empty is unbounded.
88
+ pub start: Vec<u8>,
89
+ /// Exclusive end row; `None` is unbounded.
90
+ pub end: Option<Vec<u8>>,
91
+ /// Bytes of the SSTs it references, a shared SST's divided among its tablets.
92
+ pub bytes: u64,
93
+ /// Its shard's moving average of rows written to it per balancer interval.
94
+ pub write_load: f64,
95
+ }
96
+
80
97
  /// A table as the catalog knows it. Immutable; adding a family publishes a new `TableInfo`.
81
98
  #[derive(Debug, Clone, PartialEq, Eq)]
82
99
  #[non_exhaustive]
@@ -195,6 +212,18 @@ pub struct Metrics {
195
212
  /// submitted to the I/O backend), and the nanoseconds their `fallocate`s took on the
196
213
  /// allocating thread.
197
214
  pub file_growths_ahead: (u64, u64),
215
+ /// Free blocks punched (given back to the filesystem, D333) since open, and the
216
+ /// nanoseconds the punches took on the background worker.
217
+ pub file_punches: (u64, u64),
218
+ /// Bytes those punches gave back.
219
+ pub file_punch_bytes: u64,
220
+ /// Gauge: free bytes that are holes now. The file's length less this is about what it
221
+ /// occupies on disk.
222
+ pub file_punched_bytes: u64,
223
+ /// Punch passes started, and punches that failed. A filesystem that cannot punch fails
224
+ /// once, and punching stops until the next open; any other failure ends its pass, and the
225
+ /// next waits for new free space.
226
+ pub file_punch_passes: (u64, u64),
198
227
  /// File reads made synchronously inside async reads: a separated value too large to
199
228
  /// cache (D196, #398), a block the cache could not keep, or a read that missed too
200
229
  /// often. Zero when async reads never block their executor thread.
@@ -220,6 +249,13 @@ pub struct Metrics {
220
249
  /// `GroupSync` member: a `Sync` commit's own sync isn't in it. Published at each group
221
250
  /// sync's start and finish (D316 A3, ICR 0116).
222
251
  pub group_sync_nanos: u64,
252
+ /// Bytes this database's files read since open, at their size on disk, readahead
253
+ /// included (D332, ICR 0142). The engine's own estimate of its device reads: reads the
254
+ /// OS page cache served count too, and metadata such as the manifest is included.
255
+ pub device_read_bytes: u64,
256
+ /// Bytes this database's files wrote since open: the WAL's, flushes' and compactions'
257
+ /// (D332, ICR 0142). Syncs, writeback hints and punches count nothing.
258
+ pub device_write_bytes: u64,
223
259
  /// Nanoseconds the compaction pool's threads spent in slices of the shards' flushes and
224
260
  /// compactions, summed over shards (D256). Its rise over an interval, divided by the
225
261
  /// interval, is how many threads' worth of pool work the store did; zero with the pool
@@ -709,6 +745,137 @@ fn block_cache(bytes: usize, _shards: usize) -> Arc<BlockCache> {
709
745
  /// The `(tablet, family)` slots one record writes on one shard.
710
746
  type Slots = Vec<(TabletId, FamilyId)>;
711
747
 
748
+ /// An external PREPARE's fields at replay (D329): what reinstalling it needs beside its batch.
749
+ struct ExternalStash {
750
+ xid: Arc<[u8]>,
751
+ participants: Vec<StreamId>,
752
+ /// The rows it read on its shard, for its read holds.
753
+ read: Vec<(TableId, Vec<u8>)>,
754
+ }
755
+
756
+ /// The tablets in-doubt external shares hold, each with the shard whose stream logged the
757
+ /// share (D329, perf2's M1 on #2000). Tablet owners aren't persisted: a reopen places every
758
+ /// tablet again, so a tablet that moved before a prepare would land on another shard than
759
+ /// the share's holds, and its writes would pass them. Open pins these tablets to the
760
+ /// logging shard before it places the rest. A read-only pre-pass over the WAL with
761
+ /// recovery's own in-doubt rule, run only when tablet changes are on and the file has
762
+ /// `incompat` bit 2. `Unsupported` if two in-doubt shares from different streams touch one
763
+ /// tablet, which no run of this build leaves (a tablet change touching an in-doubt share
764
+ /// is given up).
765
+ fn external_pins(
766
+ vfs: &VfsRef,
767
+ path: &Path,
768
+ db_id: [u8; 16],
769
+ catalog: &Catalog,
770
+ shards: usize,
771
+ silent_ok: bool,
772
+ ) -> Result<HashMap<TabletId, ShardId>> {
773
+ // Each external PREPARE: (stream, id) -> (coordinator, participants, rows).
774
+ #[allow(clippy::type_complexity)]
775
+ let mut shares: HashMap<
776
+ (StreamId, Seqno),
777
+ (StreamId, Vec<StreamId>, Vec<(TableId, Vec<u8>)>),
778
+ > = HashMap::new();
779
+ let mut prepared: HashSet<(StreamId, Seqno)> = HashSet::new();
780
+ let mut decided: HashMap<(StreamId, Seqno), Vec<StreamId>> = HashMap::new();
781
+ let mut aborted: HashSet<(StreamId, Seqno)> = HashSet::new();
782
+ for stream in discover_streams(vfs, path)? {
783
+ let checkpoint = catalog
784
+ .checkpoints
785
+ .get(&stream)
786
+ .copied()
787
+ .unwrap_or_default();
788
+ let mut rec = Recovery::open_read_only(vfs, path, stream, db_id, checkpoint)?;
789
+ rec.accept_silent(silent_ok);
790
+ // Tagged batches only behind `incompat` bit 2 (D329 2b): this pass runs only with it.
791
+ rec.accept_xid(true);
792
+ while let Some((_, record)) = rec.next_record()? {
793
+ match record {
794
+ WalRecord::Prepare { seqno, .. } => {
795
+ prepared.insert((stream, seqno));
796
+ }
797
+ WalRecord::ExternalPrepare {
798
+ seqno,
799
+ coordinator,
800
+ share,
801
+ } => {
802
+ prepared.insert((stream, seqno));
803
+ let mut rows = Vec::new();
804
+ if let Some(batch) = share.batch() {
805
+ for m in batch.iter() {
806
+ let m = m?;
807
+ rows.push((m.table, m.row.to_vec()));
808
+ }
809
+ }
810
+ for r in share.reads() {
811
+ let r = r?;
812
+ rows.push((r.table, r.row.to_vec()));
813
+ }
814
+ shares.insert(
815
+ (stream, seqno),
816
+ (coordinator, share.participants().iter().collect(), rows),
817
+ );
818
+ }
819
+ WalRecord::Commit {
820
+ seqno,
821
+ participants,
822
+ }
823
+ | WalRecord::Decision {
824
+ seqno,
825
+ participants,
826
+ ..
827
+ } => {
828
+ decided.insert((stream, seqno), participants.iter().collect());
829
+ }
830
+ WalRecord::ExternalAbort { seqno, share, .. } => {
831
+ aborted.insert((stream, seqno));
832
+ // Its shares are settled: drop the rows of those read already (perf2's
833
+ // nit), so the pass keeps rows of undecided shares only.
834
+ for p in share.participants().iter() {
835
+ shares.remove(&(p, seqno));
836
+ }
837
+ }
838
+ _ => {}
839
+ }
840
+ }
841
+ }
842
+ let map = TabletMap::build(1, &catalog.tablets());
843
+ let mut pins: HashMap<TabletId, ShardId> = HashMap::new();
844
+ for ((stream, seqno), (coordinator, participants, rows)) in &shares {
845
+ // Recovery's rule: in doubt when every participant's PREPARE is here and neither a
846
+ // complete decision nor an abort is.
847
+ let complete = decided
848
+ .get(&(*coordinator, *seqno))
849
+ .is_some_and(|ps| ps.iter().all(|p| prepared.contains(&(*p, *seqno))));
850
+ let in_doubt = !complete
851
+ && !aborted.contains(&(*coordinator, *seqno))
852
+ && participants
853
+ .iter()
854
+ .all(|p| prepared.contains(&(*p, *seqno)));
855
+ // A stream past the shard count is a layout change, which open refuses later.
856
+ if !in_doubt || stream.0 as usize >= shards {
857
+ continue;
858
+ }
859
+ let shard = ShardId(stream.0 as u16);
860
+ for (table, row) in rows {
861
+ let Some((tablet, _)) = map.route(*table, row) else {
862
+ continue;
863
+ };
864
+ match pins.insert(tablet, shard) {
865
+ Some(other) if other != shard => {
866
+ return Err(Error::Unsupported(
867
+ "in-doubt external transactions logged by two shards touch one tablet, \
868
+ which this build never leaves: decide them with the build that \
869
+ prepared them",
870
+ ));
871
+ }
872
+ _ => {}
873
+ }
874
+ }
875
+ }
876
+ Ok(pins)
877
+ }
878
+
712
879
  /// A replayed record of one stream, kept until every stream is read and the cross-shard
713
880
  /// decisions are resolved.
714
881
  struct ReplayedRecord {
@@ -947,6 +1114,14 @@ impl Engine {
947
1114
  "memtable_budget must be at least 128 KiB".to_owned(),
948
1115
  ));
949
1116
  }
1117
+ // Every file of the database counts its bytes (D332, ICR 0142).
1118
+ let io = Arc::new(pigeonhole_io::IoCounters::new());
1119
+ let mut options = options;
1120
+ // The backend itself, for the clock reads on the commit path and the runtime's: only
1121
+ // opens need the counting wrapper, and a clock read through it costs an extra call
1122
+ // (#2063's callgrind: about 40 instructions a commit).
1123
+ let clock_vfs = Arc::clone(&options.vfs);
1124
+ options.vfs = crate::io_count::CountingVfs::wrap(Arc::clone(&options.vfs), Arc::clone(&io));
950
1125
  let vfs = Arc::clone(&options.vfs);
951
1126
  let registry = Arc::new(options.merge_operators.clone());
952
1127
 
@@ -1031,9 +1206,16 @@ impl Engine {
1031
1206
  // What the change feed's last session recorded (D310's amendment): an unset shard
1032
1207
  // count takes its stream count, and an open that doesn't mention the feed its
1033
1208
  // settings, so neither ends the feed's history by accident.
1209
+ // With the feed set, it's read too, but only for its retention: reported beside this
1210
+ // session's (`FeedStorage::previous_retention_bytes`) and kept by `feed_keep_last`
1211
+ // (#1786). A failed read there means no previous retention, never a failed open
1212
+ // (simp724's S1 on #1917): `open_session` reads the sidecar itself. Not on a
1213
+ // read-only open, which writes no session (feed1248's N2).
1034
1214
  let last_session =
1035
1215
  if options.shards == 0 || (options.feed.is_none() && options.feed_inherit) {
1036
1216
  crate::feed::last_session(&vfs, path, db_id)?
1217
+ } else if options.feed.is_some() && !options.read_only {
1218
+ crate::feed::last_session(&vfs, path, db_id).unwrap_or(None)
1037
1219
  } else {
1038
1220
  None
1039
1221
  };
@@ -1106,10 +1288,25 @@ impl Engine {
1106
1288
  options.feed = Some(inherited);
1107
1289
  }
1108
1290
  }
1291
+ if options.feed_keep_last
1292
+ && let Some(f) = options.feed.as_mut()
1293
+ && let Some(last) = &last_session
1294
+ {
1295
+ f.retention_bytes = f.retention_bytes.max(last.retention_bytes);
1296
+ }
1109
1297
  let feed = if no_writes {
1110
1298
  None
1111
1299
  } else {
1112
- crate::feed::open_session(&vfs, path, db_id, &catalog, &options, shards, opened_root)?
1300
+ crate::feed::open_session(
1301
+ &vfs,
1302
+ path,
1303
+ db_id,
1304
+ &catalog,
1305
+ &options,
1306
+ shards,
1307
+ opened_root,
1308
+ last_session.as_ref().map(|l| l.retention_bytes),
1309
+ )?
1113
1310
  };
1114
1311
  if let Some(f) = &feed {
1115
1312
  let weak = Arc::downgrade(f);
@@ -1159,6 +1356,11 @@ impl Engine {
1159
1356
  } else {
1160
1357
  ShmRegion::open(&vfs, &file, identity, db_id, ShmRole::Writer, &shm_config)?
1161
1358
  };
1359
+ // Where the session publishes a stop of its sidecar appends for reader processes,
1360
+ // and a stop this open's own root commits already made (D315 amendment, #1869).
1361
+ if let Some(f) = &feed {
1362
+ f.publish_to(shm.clone());
1363
+ }
1162
1364
  // A new generation, so new zero slots: reader processes re-attach, which clears their
1163
1365
  // caches (D281; every writer open, a recovery's and a handover's too, builds one).
1164
1366
  let row_epochs = Arc::new(crate::row_cache::RowEpochs::new(shm.row_epochs()));
@@ -1183,9 +1385,36 @@ impl Engine {
1183
1385
  // chunk size shrinks when they do not (#104). Off, tablets stay where `shard_for`
1184
1386
  // puts them, and the chunks are sized the same way for the slots that gives (#283).
1185
1387
  let arena_len = shm.arena(0).2;
1388
+ // In-doubt external shares hold their tablets on the shard that logged them (D329,
1389
+ // perf2's M1 on #2000). Whether tablet changes are on is this open's choice, and an
1390
+ // earlier open's may have moved a tablet, so the pre-pass runs whenever the file may
1391
+ // hold external PREPAREs; a read-only open holds nothing, and skips it.
1392
+ // Whether the WAL may hold feed-silent batches (D331, ICR 0141): their mark is taken
1393
+ // only with `incompat` bit 3, set before the first was appended.
1394
+ let silent_ok =
1395
+ pager.features().incompat & pigeonhole_format::wal::INCOMPAT_FEED_SILENT != 0;
1396
+ let pins = if !no_writes
1397
+ && pager.features().incompat & pigeonhole_format::wal::INCOMPAT_EXTERNAL_PREPARE != 0
1398
+ {
1399
+ external_pins(&vfs, path, db_id, &catalog, shards, silent_ok)?
1400
+ } else {
1401
+ HashMap::new()
1402
+ };
1403
+ if !options.tablet_changes
1404
+ && pins
1405
+ .iter()
1406
+ .any(|(&tablet, &shard)| crate::catalog::shard_for(tablet, shards) != shard)
1407
+ {
1408
+ // Off, every tablet goes to `shard_for`'s shard: one an in-doubt share holds
1409
+ // elsewhere (moved by an earlier open) can't be placed there.
1410
+ return Err(Error::Unsupported(
1411
+ "an in-doubt external transaction holds a tablet a tablet change moved: open \
1412
+ with tablet changes on, and decide it first",
1413
+ ));
1414
+ }
1186
1415
  let chunk = if options.tablet_changes {
1187
1416
  let base = arena_chunk_size(arena_len, 0);
1188
- let placed = catalog.place(shards, max_slots(arena_len, base));
1417
+ let placed = catalog.place(shards, max_slots(arena_len, base), &pins);
1189
1418
  arena_chunk_size(arena_len, placed)
1190
1419
  } else {
1191
1420
  arena_chunk_size(arena_len, catalog.max_slots_per_shard(shards))
@@ -1222,6 +1451,8 @@ impl Engine {
1222
1451
  metrics: (0..shards).map(|_| ShardMetrics::default()).collect(),
1223
1452
  flushed_through: (0..shards).map(|_| Padded(AtomicU64::new(0))).collect(),
1224
1453
  loads: (0..shards).map(|_| LoadSlot::default()).collect(),
1454
+ tablet_loads: (0..shards).map(|_| ArcSwap::default()).collect(),
1455
+ io: Arc::clone(&io),
1225
1456
  balance: BalanceConfig {
1226
1457
  enabled: options.tablet_changes,
1227
1458
  interval_nanos: options.balance_interval_nanos,
@@ -1244,6 +1475,7 @@ impl Engine {
1244
1475
  n => n,
1245
1476
  },
1246
1477
  feed: feed.clone(),
1478
+ clock_vfs: Arc::clone(&clock_vfs),
1247
1479
  ..Shared::base(
1248
1480
  &vfs,
1249
1481
  &shm,
@@ -1345,6 +1577,11 @@ impl Engine {
1345
1577
  let mut max_seqno = 0;
1346
1578
  let mut recoveries: Vec<(StreamId, Recovery)> = Vec::new();
1347
1579
  let mut stashed: Vec<(StreamId, Seqno, u64, StreamId, Vec<u8>)> = Vec::new();
1580
+ // D329: each external PREPARE's xid, participant streams and logged reads, by
1581
+ // `(stream, id)` (its batch is in `stashed`), and each external abort's
1582
+ // `(coordinator stream, id)`.
1583
+ let mut external: HashMap<(StreamId, Seqno), ExternalStash> = HashMap::new();
1584
+ let mut external_aborts: HashSet<(StreamId, Seqno)> = HashSet::new();
1348
1585
  // `(coordinator stream, seqno) -> participant streams` of every COMMIT decision.
1349
1586
  // With the seqno and timestamp a DECISION applies the commit at (D263);
1350
1587
  // `None` for a 0.3.0 COMMIT, whose PREPAREs apply at their own.
@@ -1367,6 +1604,10 @@ impl Engine {
1367
1604
  } else {
1368
1605
  Recovery::open(&vfs, path, stream, db_id, checkpoint)?
1369
1606
  };
1607
+ rec.accept_silent(silent_ok);
1608
+ rec.accept_xid(
1609
+ pager.features().incompat & pigeonhole_format::wal::INCOMPAT_EXTERNAL_PREPARE != 0,
1610
+ );
1370
1611
  let mut records = Vec::new();
1371
1612
  while let Some((end, record)) = rec.next_record()? {
1372
1613
  match record {
@@ -1434,6 +1675,76 @@ impl Engine {
1434
1675
  kind: ReplayedRecordKind::Commit,
1435
1676
  });
1436
1677
  }
1678
+ WalRecord::ExternalPrepare {
1679
+ seqno,
1680
+ coordinator,
1681
+ share,
1682
+ } => {
1683
+ let Some(batch) = share.batch() else {
1684
+ return Err(Error::Corruption(
1685
+ "an external PREPARE without its batch".into(),
1686
+ ));
1687
+ };
1688
+ // What recovery relies on (perf2's N1 on #2000): the xid that encode
1689
+ // never writes empty, and this stream and the coordinator among the
1690
+ // participants (else the share would be held with no `Coord` and no
1691
+ // registry entry, for good).
1692
+ let participants: Vec<StreamId> = share.participants().iter().collect();
1693
+ if share.xid().is_empty()
1694
+ || !participants.contains(&stream)
1695
+ || !participants.contains(&coordinator)
1696
+ {
1697
+ return Err(Error::Corruption(
1698
+ "an external PREPARE whose xid is empty, or whose stream or \
1699
+ coordinator isn't among its participants"
1700
+ .into(),
1701
+ ));
1702
+ }
1703
+ let mut read = Vec::new();
1704
+ for r in share.reads() {
1705
+ let r = r?;
1706
+ read.push((r.table, r.row.to_vec()));
1707
+ }
1708
+ stashed.push((stream, seqno, 0, coordinator, batch.as_bytes().to_vec()));
1709
+ external.insert(
1710
+ (stream, seqno),
1711
+ ExternalStash {
1712
+ xid: share.xid().into(),
1713
+ participants,
1714
+ read,
1715
+ },
1716
+ );
1717
+ records.push(ReplayedRecord {
1718
+ end,
1719
+ seqno,
1720
+ kind: ReplayedRecordKind::Prepare { coordinator },
1721
+ });
1722
+ }
1723
+ WalRecord::ExternalAbort { seqno, .. } => {
1724
+ external_aborts.insert((stream, seqno));
1725
+ // An abort's record: its id is aborted (`log_replayed`, no apply).
1726
+ records.push(ReplayedRecord {
1727
+ end,
1728
+ seqno,
1729
+ kind: ReplayedRecordKind::Commit,
1730
+ });
1731
+ }
1732
+ // A range drop (D331): nothing to apply. A drop whose manifest commit is
1733
+ // durable put a fresh tablet over the range, flushed through its seqno,
1734
+ // so the range's earlier writes replay into nothing: every write of the
1735
+ // range has a lower seqno, since its caller keeps the range unserved
1736
+ // while it drops, so none can be in flight below the seqno and land
1737
+ // after it (simp724). One whose commit isn't durable is run again by its
1738
+ // caller, which keeps the range unserved and its drop-pending row until
1739
+ // the drop completes. Never needed past a checkpoint: the re-run writes
1740
+ // its own record.
1741
+ WalRecord::RangeDrop { seqno, .. } => {
1742
+ records.push(ReplayedRecord {
1743
+ end,
1744
+ seqno,
1745
+ kind: ReplayedRecordKind::Commit,
1746
+ });
1747
+ }
1437
1748
  // `WalRecord::decode` returns no other type in this build.
1438
1749
  _ => return Err(Error::Corruption("wal record type".into())),
1439
1750
  }
@@ -1482,6 +1793,25 @@ impl Engine {
1482
1793
  }
1483
1794
  applied_slots.insert((*stream, *seqno), (apply_seqno, per_shard));
1484
1795
  }
1796
+ // D329: an external PREPARE with no decision and no abort, whose every participant's
1797
+ // PREPARE is here, is in doubt: kept, held again, and decided by the caller. One
1798
+ // with a participant's record missing (a torn tail below its durability) is dropped
1799
+ // as aborted, as a D263 PREPARE is.
1800
+ let in_doubt: Vec<(StreamId, Seqno, StreamId)> = stashed
1801
+ .iter()
1802
+ .filter(|(stream, seqno, _, coordinator, _)| {
1803
+ external.get(&(*stream, *seqno)).is_some_and(|e| {
1804
+ !complete(*coordinator, *seqno)
1805
+ && !external_aborts.contains(&(*coordinator, *seqno))
1806
+ && e.participants
1807
+ .iter()
1808
+ .all(|p| prepared.contains(&(*p, *seqno)))
1809
+ })
1810
+ })
1811
+ .map(|(stream, seqno, _, coordinator, _)| (*stream, *seqno, *coordinator))
1812
+ .collect();
1813
+ let in_doubt_ids: HashSet<(StreamId, Seqno)> =
1814
+ in_doubt.iter().map(|(s, id, _)| (*s, *id)).collect();
1485
1815
  let next = first_seqno(catalog.counters.seqno_ceiling, max_seqno);
1486
1816
  // The allocator starts above every recovered seqno, and shm mirrors it (D271); its
1487
1817
  // timestamp is seeded once replay has raised the floors (below).
@@ -1516,6 +1846,15 @@ impl Engine {
1516
1846
  }
1517
1847
  on.into_iter().collect()
1518
1848
  };
1849
+ // D329: an in-doubt share's records must stay in their streams, which a changed layout
1850
+ // or a spilled replay checkpoints past (`flush_recovered`). Refused rather than
1851
+ // losing it: open with the shard count it was written with, and decide it.
1852
+ if !no_writes && !same_layout && !in_doubt.is_empty() {
1853
+ return Err(Error::Unsupported(
1854
+ "this database has externally prepared transactions in doubt: open it with \
1855
+ the shard count and memory it was written with, and decide them first",
1856
+ ));
1857
+ }
1519
1858
  if no_writes {
1520
1859
  // A read-only open (ICR 0059) keeps what it replayed in its memtables, whatever
1521
1860
  // the layout (replay routes each record to the shard owning its rows), and
@@ -1523,6 +1862,30 @@ impl Engine {
1523
1862
  // as they are for the next writable open to replay.
1524
1863
  drop(replayed);
1525
1864
  drop(recoveries);
1865
+ // D329: its shares in doubt are listed (`in_doubt`), for an operator to see; no
1866
+ // share is held, and `decide` is refused (`ReadOnly`), so nothing else is.
1867
+ let now = shared.clock_vfs.monotonic_nanos();
1868
+ for (stream, seqno, coordinator) in &in_doubt {
1869
+ if stream != coordinator {
1870
+ continue;
1871
+ }
1872
+ if let (Some(e), Some((.., bytes))) = (
1873
+ external.get(&(*stream, *seqno)),
1874
+ stashed
1875
+ .iter()
1876
+ .find(|(s, id, ..)| s == stream && id == seqno),
1877
+ ) {
1878
+ shared.external.install(
1879
+ &e.xid,
1880
+ crate::shard::ExternalEntry {
1881
+ id: *seqno,
1882
+ coordinator: ShardId(coordinator.0 as u16),
1883
+ prepared_at: now,
1884
+ bytes: bytes.len() as u64,
1885
+ },
1886
+ );
1887
+ }
1888
+ }
1526
1889
  } else if same_layout {
1527
1890
  for ((stream, records), (_, rec)) in replayed.into_iter().zip(&recoveries) {
1528
1891
  let i = stream.0 as usize;
@@ -1556,6 +1919,7 @@ impl Engine {
1556
1919
  slots,
1557
1920
  applied: applied
1558
1921
  .map(|(s, _)| (*s, holders_of(coordinator, r.seqno))),
1922
+ in_doubt: in_doubt_ids.contains(&(stream, r.seqno)),
1559
1923
  }
1560
1924
  }
1561
1925
  ReplayedRecordKind::Commit => ReplayedKind::Commit {
@@ -1583,6 +1947,45 @@ impl Engine {
1583
1947
  states[i].set_wal(Box::new(wal));
1584
1948
  have_wal[i] = true;
1585
1949
  }
1950
+ // D329: each in-doubt share is held again on its shard, and its coordinator
1951
+ // awaits `decide`, before any shard admits a write.
1952
+ let now = shared.clock_vfs.monotonic_nanos();
1953
+ for (stream, seqno, coordinator) in &in_doubt {
1954
+ let (Some(e), Some((.., bytes))) = (
1955
+ external.get(&(*stream, *seqno)),
1956
+ stashed
1957
+ .iter()
1958
+ .find(|(s, id, ..)| s == stream && id == seqno),
1959
+ ) else {
1960
+ continue;
1961
+ };
1962
+ let participants: Vec<ShardId> =
1963
+ e.participants.iter().map(|p| ShardId(p.0 as u16)).collect();
1964
+ let batch = BatchBuilder::from_batch(pigeonhole_format::wal::BatchRef::new(bytes)?);
1965
+ states[stream.0 as usize].reinstall_external_share(
1966
+ *seqno,
1967
+ batch,
1968
+ &e.read,
1969
+ participants.clone(),
1970
+ Arc::clone(&e.xid),
1971
+ );
1972
+ if stream == coordinator {
1973
+ states[stream.0 as usize].reinstall_external_coord(
1974
+ *seqno,
1975
+ participants,
1976
+ Arc::clone(&e.xid),
1977
+ );
1978
+ shared.external.install(
1979
+ &e.xid,
1980
+ crate::shard::ExternalEntry {
1981
+ id: *seqno,
1982
+ coordinator: ShardId(coordinator.0 as u16),
1983
+ prepared_at: now,
1984
+ bytes: bytes.len() as u64,
1985
+ },
1986
+ );
1987
+ }
1988
+ }
1586
1989
  } else {
1587
1990
  flush_recovered(
1588
1991
  &shared,
@@ -1734,7 +2137,8 @@ impl Engine {
1734
2137
  .saturating_sub(64 * 1024)
1735
2138
  .min(64 << 20)
1736
2139
  .min((options.memtable_budget / 2) as usize);
1737
- let mut config = RuntimeConfig::new(Arc::clone(&vfs));
2140
+ // The runtime opens no file: it reads the clock, through the backend itself.
2141
+ let mut config = RuntimeConfig::new(Arc::clone(&shared.clock_vfs));
1738
2142
  config.shards = shards;
1739
2143
  config.pin_threads = options.pin_threads;
1740
2144
  config.compaction_threads = options.compaction_threads;
@@ -1829,7 +2233,8 @@ impl Engine {
1829
2233
  }
1830
2234
 
1831
2235
  /// Opens a read-only handle in another process (Phase 4): attaches to the live region,
1832
- /// claims a reader slot, loads the manifest named in the region header.
2236
+ /// claims a reader slot, loads the manifest named in the region header, under a pin of
2237
+ /// that slot (#2085). [`Error::Busy`] if the writer restarted while it loaded: open again.
1833
2238
  ///
1834
2239
  /// The handle is read-only, but the process opens the database file **read-write**
1835
2240
  /// (decision D36): the shm-init and last-one-out presence locks are exclusive byte-range
@@ -1859,10 +2264,35 @@ impl Engine {
1859
2264
  let shards = shm.shard_count() as usize;
1860
2265
  let opened_in = pigeonhole_io::sys::process_id();
1861
2266
  let slot = claim_slot(&shm, vfs.current_process(), &file, opened_in)?;
1862
- let (catalog, _) = manifest::load(&opened, shards, Arc::clone(&registry))?;
1863
- let manifest_version = opened.root().manifest_version;
1864
- let manifest_file = opened.file().clone();
1865
- let pager = Arc::new(opened.finish([])?);
2267
+ let pins = crate::snapshot::ReaderPins::new(slot);
2268
+ // The manifest is read under a pin, as a snapshot reads one (#2085): the root
2269
+ // `Pager::open` read named extents a writer committing since could already have
2270
+ // retired, freed and written over. Pinned first, the root read again is at or above
2271
+ // the pinned view's manifest version, so the writer keeps its extents until the
2272
+ // release below.
2273
+ let (_, key) = pins.take(&shm, false);
2274
+ let loaded = (|| -> Result<_> {
2275
+ let pager = Arc::new(opened.finish([])?);
2276
+ pager.reload_root()?;
2277
+ let root = pager.root();
2278
+ #[cfg(feature = "test-hooks")]
2279
+ hooks::run_reader_open(&vfs);
2280
+ let (catalog, _) = manifest::load_root(
2281
+ pager.file(),
2282
+ &root,
2283
+ pager.features().incompat,
2284
+ shards,
2285
+ Arc::clone(&registry),
2286
+ )?;
2287
+ Ok((pager, catalog, root.manifest_version))
2288
+ })();
2289
+ pins.release(key);
2290
+ // A writer that restarted meanwhile (a new region generation) doesn't see this
2291
+ // generation's pin and may have reused the extents anyway: retryable, as a reader
2292
+ // snapshot that finds its writer gone re-attaches, never `Corruption` (#2085).
2293
+ let (pager, catalog, manifest_version) =
2294
+ loaded.map_err(|e| if shm.is_stale() { Error::Busy } else { e })?;
2295
+ let manifest_file = pager.file().clone();
1866
2296
  open_data_file(&vfs, path, &pager, options.direct_io, false)?;
1867
2297
  let cache = block_cache(options.block_cache_bytes, shards);
1868
2298
  // The read-only pager is kept by the manifest writer (which never commits here).
@@ -1886,7 +2316,7 @@ impl Engine {
1886
2316
  shm: Mutex::new(Attachment {
1887
2317
  row_cache: reader_row_cache(&options, &shm),
1888
2318
  shm,
1889
- pins: crate::snapshot::ReaderPins::new(slot),
2319
+ pins,
1890
2320
  }),
1891
2321
  catalog: Mutex::new((manifest_version, Arc::new(catalog), manifest_file)),
1892
2322
  view: Mutex::new(None),
@@ -2012,6 +2442,61 @@ impl Engine {
2012
2442
  self.inner.drop_table(table)
2013
2443
  }
2014
2444
 
2445
+ /// Drops rows `[start, end)` of `table` (`end` `None`: to the table's end) outright, with
2446
+ /// no delete markers (D331, ICR 0141): a range move's source at its cleanup, its target
2447
+ /// at an abort. A later write of the range at an older timestamp is visible, as if the
2448
+ /// rows had never been there; a live snapshot still reads them. The range must be
2449
+ /// unserved while this runs, **with no write of it in flight**: the caller stops and
2450
+ /// joins every writer of the range first (a source's range fence; a target's copy and
2451
+ /// catch-up, at an abort), since a write landing around the drop's seqno would apply
2452
+ /// live into the fresh tablet but be skipped on replay (simp724's M2 on #2089). The
2453
+ /// caller runs it again after a crash until it returns: each step does nothing once
2454
+ /// done. Feed-silent; a replica's follower runs it too.
2455
+ ///
2456
+ /// `ReadOnly` on a replica; `Busy` (retry) while an externally prepared transaction is
2457
+ /// in doubt or the balancer keeps changing the range's tablets; `Unsupported` with
2458
+ /// tablet changes off; `InvalidArgument` for an end at or before the start.
2459
+ pub fn drop_range(&self, table: TableId, start: &[u8], end: Option<&[u8]>) -> Result<()> {
2460
+ if is_reserved_table(table) {
2461
+ return Err(Error::InvalidArgument(
2462
+ "a replica's state table can't be dropped".to_owned(),
2463
+ ));
2464
+ }
2465
+ self.inner.refuse_on_replica()?;
2466
+ self.inner.drop_range(table, start, end)
2467
+ }
2468
+
2469
+ /// One chunk of rows `[after, end)` of `table` (`end` `None`: to the table's end) at
2470
+ /// `snapshot`, for a range move's copy (D331 PR 4a, ICR 0141): exactly what a
2471
+ /// compaction would write for them at the snapshot, every version and marker a reader
2472
+ /// there could need, a counter or aggregate family's operands folded into their base.
2473
+ /// The chunk ends at a row boundary once it holds `max_bytes`; its `next` is the row to
2474
+ /// ask for next, `None` once the range is done. Reads without filling the block cache.
2475
+ /// A target writes it back with [`WriteBatch::push_logged`] in one commit.
2476
+ pub fn copy_range(
2477
+ &self,
2478
+ snapshot: &Snapshot,
2479
+ table: TableId,
2480
+ after: &[u8],
2481
+ end: Option<&[u8]>,
2482
+ max_bytes: usize,
2483
+ ) -> Result<crate::RangeChunk> {
2484
+ self.inner.check_open()?;
2485
+ let now = self.inner.shared.clock_vfs.now_micros();
2486
+ crate::range_copy::copy_range(snapshot, now, table, after, end, max_bytes)
2487
+ }
2488
+
2489
+ /// [`drop_range`](Self::drop_range) on a replica (D331): its primary's drop, which its
2490
+ /// follower applies in feed order. `InvalidArgument` on a primary.
2491
+ pub fn apply_range_drop(&self, table: TableId, start: &[u8], end: Option<&[u8]>) -> Result<()> {
2492
+ if !self.inner.replica.load(Ordering::Relaxed) {
2493
+ return Err(Error::InvalidArgument(
2494
+ "only a replica applies its primary's range drop".to_owned(),
2495
+ ));
2496
+ }
2497
+ self.inner.drop_range(table, start, end)
2498
+ }
2499
+
2015
2500
  /// Applies one catalog change a primary's feed delivered (D315 PR 3), **with the
2016
2501
  /// primary's ids**, so a replica's tables and families keep them: a table created with
2017
2502
  /// its families, a family added, or a table dropped, as the change's `edits` hold them. A
@@ -2037,10 +2522,24 @@ impl Engine {
2037
2522
  ///
2038
2523
  /// [`REPLICA_TABLE`]: pigeonhole_format::manifest::REPLICA_TABLE
2039
2524
  pub fn apply_replicated(
2525
+ &self,
2526
+ batch: WriteBatch,
2527
+ state: &[u8],
2528
+ max_ts: Timestamp,
2529
+ ) -> Result<CommitInfo> {
2530
+ self.apply_replicated_with(batch, state, max_ts, None)
2531
+ }
2532
+
2533
+ /// [`apply_replicated`](Self::apply_replicated) for a run of one spanning commit's share
2534
+ /// (D329 2b): committed tagged with `xid`, so this replica's own feed delivers it as
2535
+ /// the primary's does. Not part of the stable API.
2536
+ #[doc(hidden)]
2537
+ pub fn apply_replicated_with(
2040
2538
  &self,
2041
2539
  mut batch: WriteBatch,
2042
2540
  state: &[u8],
2043
2541
  max_ts: Timestamp,
2542
+ xid: Option<&[u8]>,
2044
2543
  ) -> Result<CommitInfo> {
2045
2544
  if batch.is_empty() || !batch.logged() || !batch.row_deletes.is_empty() {
2046
2545
  return Err(Error::InvalidArgument(
@@ -2049,7 +2548,77 @@ impl Engine {
2049
2548
  }
2050
2549
  self.push_replication_state(&mut batch, state)?;
2051
2550
  self.inner.shared.clock.seed_ts(max_ts);
2052
- self.commit(batch, Some(Durability::GroupSync))
2551
+ self.inner.shared.refuse_blocking_on_driver("commit")?;
2552
+ self.inner
2553
+ .commit_blocking_with(batch, Some(Durability::GroupSync), xid)
2554
+ }
2555
+
2556
+ /// Commits `batch`, every mutation [`push_logged`](WriteBatch::push_logged), on a
2557
+ /// primary (D331 PR 4, ICR 0141): a range move's target writes the source's changes
2558
+ /// exactly as the source logged them, with the source's kinds, timestamps and stored
2559
+ /// values, in its own ids. The timestamp floor isn't raised: the target raises it once,
2560
+ /// before it serves the range ([`raise_ts_floor`](Self::raise_ts_floor)). Refused on a
2561
+ /// replica (`ReadOnly`), which takes logged mutations only through
2562
+ /// [`apply_replicated`](Self::apply_replicated), and, `InvalidArgument`, for a batch that
2563
+ /// is empty, isn't logged or deletes rows.
2564
+ pub fn commit_logged(
2565
+ &self,
2566
+ batch: WriteBatch,
2567
+ durability: Option<Durability>,
2568
+ ) -> Result<CommitInfo> {
2569
+ if self.inner.replica.load(Ordering::Relaxed) {
2570
+ return Err(replica_refusal());
2571
+ }
2572
+ if batch.is_empty() || !batch.logged() || !batch.row_deletes.is_empty() {
2573
+ return Err(Error::InvalidArgument(
2574
+ "a logged commit is a non-empty batch of logged mutations".to_owned(),
2575
+ ));
2576
+ }
2577
+ self.commit(batch, durability)
2578
+ }
2579
+
2580
+ /// Holds the change feed's retained history from now on (D331, ICR 0141): a feed token
2581
+ /// from now, or of a snapshot opened after it (not one opened before), resumes until the
2582
+ /// hold is dropped, or until the database retains more than `cap_bytes` of history, when
2583
+ /// the hold lapses ([`FeedRetentionHold::lapsed`]) and retention trims as before. It
2584
+ /// keeps each WAL stream from its checkpoint, where a snapshot's token starts reading. A
2585
+ /// range move takes one before its copy's first snapshot, so its catch-up from that
2586
+ /// snapshot's token finds the history there however long the copy takes, or the move
2587
+ /// learns it can't. The WAL grows by the writes made while it holds. `InvalidArgument`
2588
+ /// without the change feed; `Busy` before every stream has opened. Not part of the stable
2589
+ /// API.
2590
+ #[doc(hidden)]
2591
+ pub fn hold_feed_retention(&self, cap_bytes: u64) -> Result<FeedRetentionHold> {
2592
+ let shared = &self.inner.shared;
2593
+ let Some(feed) = &shared.feed else {
2594
+ return Err(Error::InvalidArgument(
2595
+ "a retention hold needs the change feed".to_owned(),
2596
+ ));
2597
+ };
2598
+ // Every stream opens with the database; one not open yet is a moment's wait
2599
+ // (simp724's N1 on #2055).
2600
+ let hold = feed.hold_retention(cap_bytes).ok_or(Error::Busy)?;
2601
+ Ok(FeedRetentionHold {
2602
+ shared: Arc::clone(shared),
2603
+ hold,
2604
+ })
2605
+ }
2606
+
2607
+ /// Raises the timestamp floor (D271's `H`) to at least `ts`, durably (D331, ICR 0141): a
2608
+ /// range move's target, before it serves the range, raises it past every timestamp it
2609
+ /// copied from the source, so a default timestamp it hands out later sorts after them all,
2610
+ /// whatever the two nodes' clocks. The floor is committed to the manifest before this
2611
+ /// returns: replay recovers only commit timestamps, not a copy's explicit ones. Refused
2612
+ /// on a replica, whose floor follows its primary's applies. Not part of the stable API.
2613
+ #[doc(hidden)]
2614
+ pub fn raise_ts_floor(&self, ts: Timestamp) -> Result<()> {
2615
+ self.inner.refuse_on_replica()?;
2616
+ self.inner.shared.clock.seed_ts(ts);
2617
+ self.inner.catalog_change(move |catalog| {
2618
+ catalog.counters.ts_floor = catalog.counters.ts_floor.max(ts);
2619
+ Ok(vec![catalog.counters_edit()])
2620
+ })?;
2621
+ Ok(())
2053
2622
  }
2054
2623
 
2055
2624
  /// The most bytes of logged changes one replicated commit should carry (D315 PR 3;
@@ -2102,6 +2671,16 @@ impl Engine {
2102
2671
  self.inner.promote()
2103
2672
  }
2104
2673
 
2674
+ /// The digest of this database's catalog (#1853 part C2): its table ids, but a replica's
2675
+ /// state table, and its id counters, as a feed of every table's
2676
+ /// [`FeedReader::catalog_digest`](crate::FeedReader::catalog_digest) reports them at its
2677
+ /// position. A replica that applied everything its primary's feed delivered has the
2678
+ /// digest that feed reports; a different one means a schema change the feed never
2679
+ /// delivered.
2680
+ pub fn catalog_digest(&self) -> u64 {
2681
+ crate::feed_reader::catalog_digest_of(&self.inner.catalog())
2682
+ }
2683
+
2105
2684
  /// The replica's state cell, as the last apply stored it; `None` before the first.
2106
2685
  pub fn replication_state(&self) -> Result<Option<Vec<u8>>> {
2107
2686
  if self
@@ -2242,6 +2821,45 @@ impl Engine {
2242
2821
  self.inner.commit_blocking(batch, durability)
2243
2822
  }
2244
2823
 
2824
+ /// Decides the externally prepared transaction `xid` (D329, ICR 0140; [`Txn::prepare`]):
2825
+ /// `commit` applies its shares and answers the commit's seqno, an abort drops them and
2826
+ /// answers its id; `None` when `xid` isn't in doubt here (decided already, or never
2827
+ /// prepared). Idempotent.
2828
+ pub fn decide(&self, xid: &[u8], commit: bool) -> Result<Option<CommitInfo>> {
2829
+ self.inner.shared.refuse_blocking_on_driver("decide")?;
2830
+ self.inner.decide(xid, commit)
2831
+ }
2832
+
2833
+ /// [`decide`](Self::decide) without waiting (D329): `None` when `xid` isn't in doubt
2834
+ /// here; otherwise the [`PendingCommit`] resolves as `decide` returns, except that a
2835
+ /// decide another call won meanwhile resolves with seqno 0. It never blocks, so a thread
2836
+ /// that drives a shard may call it (D88).
2837
+ pub fn submit_decide(&self, xid: &[u8], commit: bool) -> Result<Option<PendingCommit>> {
2838
+ Ok(self
2839
+ .inner
2840
+ .submit_decide(xid, commit)?
2841
+ .map(PendingCommit::from))
2842
+ }
2843
+
2844
+ /// The externally prepared transactions in doubt here (D329): each xid, with how long
2845
+ /// ago it was prepared, in nanoseconds.
2846
+ pub fn in_doubt(&self) -> Vec<(Vec<u8>, u64)> {
2847
+ self.inner.in_doubt()
2848
+ }
2849
+
2850
+ /// [`in_doubt`](Self::in_doubt), with each share's batch bytes (what it keeps in the
2851
+ /// WAL, as the in-doubt limit counts it): `(xid, nanoseconds since prepared, bytes)`.
2852
+ pub fn in_doubt_shares(&self) -> Vec<(Vec<u8>, u64, u64)> {
2853
+ let now = self.inner.shared.vfs.monotonic_nanos();
2854
+ self.inner
2855
+ .shared
2856
+ .external
2857
+ .in_doubt()
2858
+ .into_iter()
2859
+ .map(|(xid, e)| (xid, now.saturating_sub(e.prepared_at), e.bytes))
2860
+ .collect()
2861
+ }
2862
+
2245
2863
  /// [`commit`](Self::commit), returning each counter cell `batch` incremented or set,
2246
2864
  /// after this commit (D314): its value as a read at the commit's seqno sees it, with a TTL judged at
2247
2865
  /// the commit's timestamp, in the order the batch first wrote each cell. `batch`
@@ -2262,6 +2880,7 @@ impl Engine {
2262
2880
  None,
2263
2881
  None,
2264
2882
  Some(Arc::clone(&out)),
2883
+ None,
2265
2884
  NoAdmission,
2266
2885
  )? {
2267
2886
  Routed::Sent {
@@ -2294,6 +2913,7 @@ impl Engine {
2294
2913
  None,
2295
2914
  None,
2296
2915
  Some(Arc::clone(&out)),
2916
+ None,
2297
2917
  NoAdmission,
2298
2918
  )? {
2299
2919
  Routed::Sent {
@@ -2567,14 +3187,22 @@ impl Engine {
2567
3187
  let inner = &self.inner;
2568
3188
  let Some(a) = &inner.admission else {
2569
3189
  return inner
2570
- .route_and_send_with(batch, durability, None, None, returning, NoAdmission)
3190
+ .route_and_send_with(batch, durability, None, None, returning, None, NoAdmission)
2571
3191
  .and_then(|routed| inner.submission(routed))
2572
3192
  .map(PendingCommit::from);
2573
3193
  };
2574
3194
  // D236: routed once; the charge goes to the shard the request is sent to (a
2575
3195
  // cross-shard commit's coordinator), on that shard's own count.
2576
3196
  let bytes = crate::admission::batch_bytes(&batch);
2577
- match inner.route_and_send_with(batch, durability, None, None, returning, (&**a, bytes))? {
3197
+ match inner.route_and_send_with(
3198
+ batch,
3199
+ durability,
3200
+ None,
3201
+ None,
3202
+ returning,
3203
+ None,
3204
+ (&**a, bytes),
3205
+ )? {
2578
3206
  Routed::Held(prepared) => {
2579
3207
  let shard = usize::from(prepared.target.0);
2580
3208
  let admit = crate::Admit::new(Some(a), shard, bytes);
@@ -2655,6 +3283,7 @@ impl Engine {
2655
3283
  snapshot,
2656
3284
  reads: Vec::new(),
2657
3285
  batch: WriteBatch::new(),
3286
+ xid: None,
2658
3287
  })
2659
3288
  }
2660
3289
 
@@ -2711,7 +3340,7 @@ impl Engine {
2711
3340
  rc,
2712
3341
  &snapshot.view,
2713
3342
  snapshot.seqno,
2714
- inner.shared.vfs.now_micros(),
3343
+ inner.shared.clock_vfs.now_micros(),
2715
3344
  table,
2716
3345
  family,
2717
3346
  row,
@@ -2748,7 +3377,7 @@ impl Engine {
2748
3377
  if view.released {
2749
3378
  return Err(Error::Closed);
2750
3379
  }
2751
- let clock = || inner.shared.vfs.now_micros();
3380
+ let clock = || inner.shared.clock_vfs.now_micros();
2752
3381
  if let Some(rc) = &inner.shared.row_cache
2753
3382
  && let Some(got) = crate::row_cache::get_through(
2754
3383
  rc,
@@ -2781,7 +3410,7 @@ impl Engine {
2781
3410
  ) -> Result<Option<RowData>> {
2782
3411
  snapshot.check_process()?;
2783
3412
  let families = families_in_order(&snapshot.view, table, &spec.families)?;
2784
- let now = self.inner.shared.vfs.now_micros();
3413
+ let now = self.inner.shared.clock_vfs.now_micros();
2785
3414
  snapshot.checked(read::read_row(snapshot, table, row, &families, spec, now))
2786
3415
  }
2787
3416
 
@@ -2800,7 +3429,7 @@ impl Engine {
2800
3429
  ) -> Result<bool> {
2801
3430
  snapshot.check_process()?;
2802
3431
  let families = families_in_order(&snapshot.view, table, families)?;
2803
- let now = self.inner.shared.vfs.now_micros();
3432
+ let now = self.inner.shared.clock_vfs.now_micros();
2804
3433
  snapshot.checked(read::read_row_into(
2805
3434
  &snapshot.view,
2806
3435
  snapshot.seqno,
@@ -2830,7 +3459,7 @@ impl Engine {
2830
3459
  ) -> Result<bool> {
2831
3460
  snapshot.check_process()?;
2832
3461
  let families = families_in_order(&snapshot.view, table, families)?;
2833
- let now = self.inner.shared.vfs.now_micros();
3462
+ let now = self.inner.shared.clock_vfs.now_micros();
2834
3463
  snapshot.checked(crate::row_cache::read_row_cached(
2835
3464
  rc,
2836
3465
  &snapshot.view,
@@ -3017,7 +3646,7 @@ impl Engine {
3017
3646
  }
3018
3647
  if let Some((view, seqno)) = inner.latest_view()? {
3019
3648
  let families = families_in_order(&view, table, families)?;
3020
- let now = inner.shared.vfs.now_micros();
3649
+ let now = inner.shared.clock_vfs.now_micros();
3021
3650
  if let Some(rc) = &inner.shared.row_cache
3022
3651
  && crate::row_cache::serves_spec(spec)
3023
3652
  {
@@ -3047,7 +3676,7 @@ impl Engine {
3047
3676
  pub fn scan(&self, snapshot: &Snapshot, table: TableId, spec: ScanSpec) -> Result<ScanCursor> {
3048
3677
  snapshot.check_process()?;
3049
3678
  let families = families_in_order(&snapshot.view, table, &spec.read.families)?;
3050
- let now = self.inner.shared.vfs.now_micros();
3679
+ let now = self.inner.shared.clock_vfs.now_micros();
3051
3680
  Ok(ScanCursor::new(
3052
3681
  snapshot.clone(),
3053
3682
  table,
@@ -3077,7 +3706,7 @@ impl Engine {
3077
3706
  {
3078
3707
  snapshot.check_process()?;
3079
3708
  let families = families_in_order(&snapshot.view, table, &spec.read.families)?;
3080
- let now = self.inner.shared.vfs.now_micros();
3709
+ let now = self.inner.shared.clock_vfs.now_micros();
3081
3710
  let may_fan_out = self
3082
3711
  .inner
3083
3712
  .shared
@@ -3111,7 +3740,7 @@ impl Engine {
3111
3740
  {
3112
3741
  snapshot.check_process()?;
3113
3742
  let families = families_in_order(&snapshot.view, table, &spec.read.families)?;
3114
- let now = self.inner.shared.vfs.now_micros();
3743
+ let now = self.inner.shared.clock_vfs.now_micros();
3115
3744
  let may_fan_out = self
3116
3745
  .inner
3117
3746
  .shared
@@ -3142,7 +3771,7 @@ impl Engine {
3142
3771
  ) -> Result<crate::KeyCursor> {
3143
3772
  snapshot.check_process()?;
3144
3773
  let families = families_in_order(&snapshot.view, table, &read.families)?;
3145
- let now = self.inner.shared.vfs.now_micros();
3774
+ let now = self.inner.shared.clock_vfs.now_micros();
3146
3775
  crate::KeyCursor::new(
3147
3776
  snapshot.clone(),
3148
3777
  table,
@@ -3167,7 +3796,7 @@ impl Engine {
3167
3796
  spec: &crate::TraverseSpec,
3168
3797
  ) -> Result<crate::Traversal> {
3169
3798
  snapshot.check_process()?;
3170
- let now = self.inner.shared.vfs.now_micros();
3799
+ let now = self.inner.shared.clock_vfs.now_micros();
3171
3800
  let may_fan_out = self
3172
3801
  .inner
3173
3802
  .shared
@@ -3199,7 +3828,7 @@ impl Engine {
3199
3828
  table,
3200
3829
  seeds,
3201
3830
  spec,
3202
- self.inner.shared.vfs.now_micros(),
3831
+ self.inner.shared.clock_vfs.now_micros(),
3203
3832
  Arc::clone(&self.inner.shared),
3204
3833
  ))
3205
3834
  }
@@ -3261,7 +3890,7 @@ impl Engine {
3261
3890
  table,
3262
3891
  families.into_vec(),
3263
3892
  read,
3264
- self.inner.shared.vfs.now_micros(),
3893
+ self.inner.shared.clock_vfs.now_micros(),
3265
3894
  Arc::clone(keys),
3266
3895
  Arc::clone(&self.inner.shared),
3267
3896
  )?;
@@ -3337,7 +3966,7 @@ impl Engine {
3337
3966
  table,
3338
3967
  families.into_vec(),
3339
3968
  read,
3340
- self.inner.shared.vfs.now_micros(),
3969
+ self.inner.shared.clock_vfs.now_micros(),
3341
3970
  Arc::clone(keys),
3342
3971
  Arc::clone(&self.inner.shared),
3343
3972
  )?;
@@ -3528,6 +4157,36 @@ impl Engine {
3528
4157
  .sum()
3529
4158
  }
3530
4159
 
4160
+ /// Resizes this database's block cache to `block_bytes` and its row cache to `row_bytes`
4161
+ /// (#1761: `phdb serve` re-splitting a node's `--engine-memory` as partitions open and
4162
+ /// close). A shrink evicts unpinned entries down to the new size before returning, a few
4163
+ /// at a time with each cache shard's lock released between them; pinned blocks (open
4164
+ /// readers, SSTs' top indexes and filters) stay until released, so usage can stay over
4165
+ /// the new size by what is pinned. A grow evicts nothing. A cache that was off at open (0
4166
+ /// bytes) stays off: the row cache's watermarks exist only when it was on. In a reader
4167
+ /// process it resizes only that process's block cache (its row cache is its attachment's).
4168
+ /// Synchronous: call it off async workers.
4169
+ pub fn set_cache_capacities(&self, block_bytes: usize, row_bytes: usize) {
4170
+ self.inner.shared.cache.set_capacity(block_bytes);
4171
+ if let Some(rc) = &self.inner.shared.row_cache {
4172
+ rc.set_capacity(row_bytes);
4173
+ }
4174
+ }
4175
+
4176
+ /// The block and row caches' configured capacities in bytes. A row cache that is off
4177
+ /// reports 0, and so does a reader process's: its row cache is its attachment's (D281),
4178
+ /// which this neither reports nor resizes (perf2's N1 on #1890).
4179
+ pub fn cache_capacities(&self) -> (usize, usize) {
4180
+ (
4181
+ self.inner.shared.cache.capacity(),
4182
+ self.inner
4183
+ .shared
4184
+ .row_cache
4185
+ .as_ref()
4186
+ .map_or(0, |rc| rc.capacity()),
4187
+ )
4188
+ }
4189
+
3531
4190
  /// What the row cache did since open (D201); all zero when it is off. In a reader process,
3532
4191
  /// its cache since the last attach to a writer generation (D281). A method rather than [`Metrics`] fields, which would break struct literals.
3533
4192
  pub fn row_cache_stats(&self) -> RowCacheStats {
@@ -3711,6 +4370,51 @@ impl Engine {
3711
4370
  rt.as_ref().map(|rt| rt.driver_trace()).unwrap_or_default()
3712
4371
  }
3713
4372
 
4373
+ /// Every tablet's row range, SST bytes and write load (D332, ICR 0142): for a cluster
4374
+ /// balancer choosing a split key. The bytes of an SST two tablets share (after a split,
4375
+ /// until compaction rewrites it) count once, divided between them. The write load is
4376
+ /// each tablet's moving average of rows written per balancer interval, as the shard that
4377
+ /// holds it now last published it: 0 until it has, after a move between shards too (the
4378
+ /// source shard's entry, stale, is never read), or with `tablet_changes` off. Not part
4379
+ /// of the stable API.
4380
+ #[doc(hidden)]
4381
+ pub fn tablets(&self) -> Vec<TabletStats> {
4382
+ let shared = &self.inner.shared;
4383
+ let view = shared.view.load();
4384
+ let loads: Vec<HashMap<TabletId, f64>> = shared
4385
+ .tablet_loads
4386
+ .iter()
4387
+ .map(|l| l.load().iter().copied().collect())
4388
+ .collect();
4389
+ let refs = view.catalog.sst_refs();
4390
+ view.tablets
4391
+ .iter()
4392
+ .map(|t| TabletStats {
4393
+ table: view
4394
+ .catalog
4395
+ .table(t.table)
4396
+ .map(|i| i.name.clone())
4397
+ .unwrap_or_default(),
4398
+ start: t.start.clone(),
4399
+ end: t.end.clone(),
4400
+ bytes: crate::shard::shared_bytes(&view, t, &refs),
4401
+ write_load: loads
4402
+ .get(usize::from(t.shard.0))
4403
+ .and_then(|l| l.get(&t.id))
4404
+ .copied()
4405
+ .unwrap_or(0.0),
4406
+ })
4407
+ .collect()
4408
+ }
4409
+
4410
+ /// Bytes this database's files have read and written since open, as its `CountingVfs`
4411
+ /// counts them (D332, ICR 0142): `Metrics::device_read_bytes` and `device_write_bytes`
4412
+ /// without the rest of [`Engine::metrics`]. Not part of the stable API.
4413
+ #[doc(hidden)]
4414
+ pub fn device_bytes(&self) -> (u64, u64) {
4415
+ self.inner.shared.io.totals()
4416
+ }
4417
+
3714
4418
  /// Per-shard commits, tablets and tablet changes, indexed by shard (a bench hook,
3715
4419
  /// issue #51).
3716
4420
  #[doc(hidden)]
@@ -3845,6 +4549,7 @@ impl Engine {
3845
4549
  }
3846
4550
  }
3847
4551
  }
4552
+ (m.device_read_bytes, m.device_write_bytes) = shared.io.totals();
3848
4553
  for s in &shared.metrics {
3849
4554
  let limit = s.memtable_limit.load(Ordering::Relaxed);
3850
4555
  m.memtable_limit += limit;
@@ -3884,8 +4589,17 @@ impl Engine {
3884
4589
  );
3885
4590
  m.file_growths = (pager.growths, pager.growth_nanos);
3886
4591
  m.file_growths_ahead = (pager.growths_ahead, pager.ahead_nanos);
4592
+ m.file_punches = (pager.punches, pager.punch_nanos);
4593
+ m.file_punch_bytes = pager.punch_bytes;
4594
+ m.file_punched_bytes = pager.punched_bytes;
4595
+ if let Some(p) = &shared.punch {
4596
+ m.file_punch_passes = (
4597
+ p.passes.load(Ordering::Relaxed),
4598
+ p.refusals.load(Ordering::Relaxed),
4599
+ );
4600
+ }
3887
4601
  m.async_sync_reads = shared.async_sync_reads.load(Ordering::Relaxed);
3888
- m.default_ts_lead_micros = shared.clock.lead(shared.vfs.now_micros());
4602
+ m.default_ts_lead_micros = shared.clock.lead(shared.clock_vfs.now_micros());
3889
4603
  m.block_cache = shared.cache.hits_and_misses();
3890
4604
  m.block_cache_pinned = shared.cache.pinned() as u64;
3891
4605
  m.block_cache_capacity = shared.cache.capacity() as u64;
@@ -4104,6 +4818,31 @@ impl Engine {
4104
4818
  }
4105
4819
  }
4106
4820
 
4821
+ /// A change-feed retention hold ([`Engine::hold_feed_retention`], D331): released when
4822
+ /// dropped. Not part of the stable API.
4823
+ #[doc(hidden)]
4824
+ #[derive(Debug)]
4825
+ pub struct FeedRetentionHold {
4826
+ shared: Arc<Shared>,
4827
+ hold: Arc<crate::feed::RetentionHold>,
4828
+ }
4829
+
4830
+ impl FeedRetentionHold {
4831
+ /// Whether it lapsed at its cap: retention trims again, and a reader that relied on it
4832
+ /// may find its position gone (its feed then expires).
4833
+ pub fn lapsed(&self) -> bool {
4834
+ self.hold.lapsed()
4835
+ }
4836
+ }
4837
+
4838
+ impl Drop for FeedRetentionHold {
4839
+ fn drop(&mut self) {
4840
+ if let Some(feed) = &self.shared.feed {
4841
+ feed.release_retention(&self.hold);
4842
+ }
4843
+ }
4844
+ }
4845
+
4107
4846
  /// What [`Engine::close_for_reopen`] keeps for [`Engine::open_with`]: the writer lock, the
4108
4847
  /// presence and the handle they live on, and the path they belong to (D265). Dropping it
4109
4848
  /// releases the locks but runs no last-one-out cleanup: the WAL files and the shm region
@@ -4254,7 +4993,7 @@ fn spill_recovered(
4254
4993
  states: &mut [ShardState],
4255
4994
  spill: &mut Spilled,
4256
4995
  ) -> Result<()> {
4257
- let created = shared.vfs.now_micros();
4996
+ let created = shared.clock_vfs.now_micros();
4258
4997
  for state in states.iter_mut() {
4259
4998
  for ((tablet, family), reader, bytes, max_seqno) in state.take_memtables() {
4260
4999
  let Some(meta) = catalog.family(family) else {
@@ -5205,6 +5944,195 @@ impl Inner {
5205
5944
  .ok_or_else(|| Error::TableNotFound(format!("table {}", table.0)))
5206
5945
  }
5207
5946
 
5947
+ /// Drops `[start, end)` of `table` (D331, ICR 0141; FORMAT §10.3's Range Drop): every
5948
+ /// entry of the range goes, with no delete markers, so a later write of the range at an
5949
+ /// older timestamp is visible. The caller keeps the range unserved until this returns
5950
+ /// and runs it again after a crash until it does: each step does nothing once done.
5951
+ ///
5952
+ /// 1. Splits the table's tablets at `start` and `end`, through the shards' tablet
5953
+ /// changes (which freeze and flush the tablets they split, so nothing outside the
5954
+ /// range is lost).
5955
+ /// 2. Writes a Range Drop on every stream at one seqno, held from readers until every
5956
+ /// stream has it, then released with nothing applied.
5957
+ /// 3. One manifest commit drops the tablets inside the range and puts one fresh tablet
5958
+ /// over it, flushed through that seqno in every family: replay never brings an
5959
+ /// earlier write of the range back, and a later one routes to the fresh tablet. The
5960
+ /// shards then retire the dropped tablets' memtables. A live snapshot keeps its view,
5961
+ /// and with it the dropped tablets' SSTs and memtables.
5962
+ /// 4. Raises every row-cache slot to the seqno, so no cached row of the range is served.
5963
+ ///
5964
+ /// `Busy` (retry) while an externally prepared transaction is in doubt (D329: one may
5965
+ /// hold rows of the range), or when the balancer changed the range's tablets between
5966
+ /// the split and the drop three times running; `Unsupported` with tablet changes off.
5967
+ fn drop_range(&self, table: TableId, start: &[u8], end: Option<&[u8]>) -> Result<()> {
5968
+ if self.read_only {
5969
+ return Err(Error::ReadOnly);
5970
+ }
5971
+ self.check_open()?;
5972
+ let mut range = Vec::new();
5973
+ pigeonhole_format::wal::DroppedRange::encode(&mut range, table, start, end)
5974
+ .map_err(|e| Error::InvalidArgument(e.to_string()))?;
5975
+ if !self.shared.balance.enabled {
5976
+ return Err(Error::Unsupported("a range drop needs tablet changes"));
5977
+ }
5978
+ if self.shared.view.load().catalog.table(table).is_none() {
5979
+ return Err(Error::TableNotFound(format!("table {}", table.0)));
5980
+ }
5981
+ // D329 (simp724): a share in doubt may hold rows of the range, and its commit would
5982
+ // write them back. Tablet-granular checks exist only on the shards; the coarse
5983
+ // refusal is retryable and rare.
5984
+ // A read hold (D329 2b) on rows of the range would lose its continuity: wait for it
5985
+ // as for a share in doubt (simp724's S1 on #2089).
5986
+ if !self.in_doubt().is_empty() || self.shared.external.holds() > 0 {
5987
+ return Err(Error::Busy);
5988
+ }
5989
+ self.flag_silent()?;
5990
+ for _ in 0..3 {
5991
+ self.split_at(table, start)?;
5992
+ if let Some(end) = end {
5993
+ self.split_at(table, end)?;
5994
+ }
5995
+ let seqno = self.log_range_drop(&range)?;
5996
+ match self.drop_inside(table, start, end, seqno) {
5997
+ Err(Error::Busy) => continue,
5998
+ r => r?,
5999
+ }
6000
+ if let Some(epochs) = &self.shared.row_epochs {
6001
+ epochs.raise_all(seqno);
6002
+ }
6003
+ return Ok(());
6004
+ }
6005
+ // The range's tablets kept changing under the drop: the caller drops it again.
6006
+ Err(Error::Busy)
6007
+ }
6008
+
6009
+ /// Splits `table`'s tablet holding `key` at `key`, unless `key` already starts one.
6010
+ fn split_at(&self, table: TableId, key: &[u8]) -> Result<()> {
6011
+ if key.is_empty() {
6012
+ return Ok(());
6013
+ }
6014
+ let view = self.shared.view.load_full();
6015
+ let Some(t) = view
6016
+ .tablets()
6017
+ .tablets_of(table)
6018
+ .iter()
6019
+ .find(|t| t.start.as_slice() <= key && t.end.as_deref().is_none_or(|e| key < e))
6020
+ else {
6021
+ return Err(Error::TableNotFound(format!("table {}", table.0)));
6022
+ };
6023
+ if t.start == key {
6024
+ return Ok(());
6025
+ }
6026
+ let op = crate::shard::TabletOpKind::Split {
6027
+ tablet: t.id,
6028
+ keys: vec![key.to_vec()],
6029
+ owners: vec![t.shard, t.shard],
6030
+ };
6031
+ self.tablet_op(t.shard, op)?.wait()
6032
+ }
6033
+
6034
+ /// Writes a Range Drop of `range` (encoded) on every stream at one seqno, held from
6035
+ /// readers until every stream has it written, then released.
6036
+ fn log_range_drop(&self, range: &[u8]) -> Result<Seqno> {
6037
+ let now = self.shared.clock_vfs.now_micros();
6038
+ let (seqno, _) = self.shared.clock.reserve_decision(now, &self.shared.shm);
6039
+ let mut waits = Vec::new();
6040
+ let mut sent = Ok(());
6041
+ for i in 0..self.shared.shards {
6042
+ let (tx, rx) = completion();
6043
+ match self
6044
+ .shared
6045
+ .submitter(ShardId(i as u16))
6046
+ .submit(ShardMsg::RangeDrop {
6047
+ seqno,
6048
+ range: range.to_vec(),
6049
+ reply: tx,
6050
+ }) {
6051
+ Ok(()) => waits.push(rx),
6052
+ Err(e) => {
6053
+ sent = Err(Error::from(e));
6054
+ break;
6055
+ }
6056
+ }
6057
+ }
6058
+ let written = sent.and_then(|()| {
6059
+ waits
6060
+ .into_iter()
6061
+ .try_for_each(|rx| rx.wait().unwrap_or(Err(Error::Closed)))
6062
+ });
6063
+ self.shared.clock.release(seqno, &self.shared.shm);
6064
+ self.shared.wake_visible();
6065
+ written.map(|()| seqno)
6066
+ }
6067
+
6068
+ /// Drops the tablets inside `[start, end)` and puts one fresh tablet over the range,
6069
+ /// flushed through `seqno` in every family. `Busy` if a tablet of the table straddles
6070
+ /// a bound (the balancer merged or split since `split_at`).
6071
+ fn drop_inside(
6072
+ &self,
6073
+ table: TableId,
6074
+ start: &[u8],
6075
+ end: Option<&[u8]>,
6076
+ seqno: Seqno,
6077
+ ) -> Result<()> {
6078
+ let (lo, hi) = (start.to_vec(), end.map(<[u8]>::to_vec));
6079
+ let inside = Arc::new(Mutex::new(Vec::new()));
6080
+ let out = Arc::clone(&inside);
6081
+ self.catalog_change(move |catalog| {
6082
+ let overlaps = |s: &[u8], e: Option<&[u8]>| {
6083
+ hi.as_deref().is_none_or(|h| s < h) && e.is_none_or(|e| lo.as_slice() < e)
6084
+ };
6085
+ let mut dropped = Vec::new();
6086
+ for t in catalog.tablets().into_iter().filter(|t| t.table == table) {
6087
+ if !overlaps(&t.start, t.end.as_deref()) {
6088
+ continue;
6089
+ }
6090
+ let within = t.start.as_slice() >= lo.as_slice()
6091
+ && match (&hi, &t.end) {
6092
+ (None, _) => true,
6093
+ (Some(h), Some(e)) => e <= h,
6094
+ (Some(_), None) => false,
6095
+ };
6096
+ if !within {
6097
+ // A tablet straddles a bound: the balancer changed them since the split.
6098
+ return Err(Error::Busy);
6099
+ }
6100
+ dropped.push(t.id);
6101
+ }
6102
+ let fresh = catalog.alloc_tablet();
6103
+ let mut edits: Vec<Edit> = dropped
6104
+ .iter()
6105
+ .map(|&tablet| Edit::DropTablet { tablet })
6106
+ .collect();
6107
+ edits.push(Edit::PutTablet {
6108
+ tablet: fresh,
6109
+ table,
6110
+ start: lo.clone(),
6111
+ end: hi.clone(),
6112
+ });
6113
+ edits.extend(
6114
+ catalog
6115
+ .family_ids_of(table)
6116
+ .into_iter()
6117
+ .map(|family| Edit::SetFlushed {
6118
+ tablet: fresh,
6119
+ family,
6120
+ seqno,
6121
+ }),
6122
+ );
6123
+ // A flush already holding one of their memtables skips its edits at its commit
6124
+ // (the range's rows are dropped), rather than be refused as for a split's.
6125
+ catalog.note_range_dropped(&dropped);
6126
+ *out.lock().unwrap_or_else(PoisonError::into_inner) = dropped;
6127
+ Ok(edits)
6128
+ })?;
6129
+ let tablets = std::mem::take(&mut *inside.lock().unwrap_or_else(PoisonError::into_inner));
6130
+ self.shared.broadcast(|| ShardMsg::DropTablets {
6131
+ tablets: tablets.clone(),
6132
+ });
6133
+ Ok(())
6134
+ }
6135
+
5208
6136
  fn drop_table(&self, table: TableId) -> Result<()> {
5209
6137
  let dropped = self.catalog().tablet_ids_of(table);
5210
6138
  self.catalog_change(move |catalog| {
@@ -5237,6 +6165,19 @@ impl Inner {
5237
6165
  /// Separates the puts of `builder` above the inline limit into blob files (#230). Waits
5238
6166
  /// for a manifest commit when there is one; the waiting thread drives that commit
5239
6167
  /// itself (`manifest::commit_from_thread`, as `shrink` does), so it may drive a shard.
6168
+ /// Tags routed batch `builder` with `xid`, a spanning commit's (D329 2b), as its last
6169
+ /// step, behind `incompat` bit 2. Rebuilds after it (large values, the split into
6170
+ /// shares, a retry) carry it; the counter pass in `route` runs before it, on a batch with
6171
+ /// no trailer yet. Nothing for an untagged batch.
6172
+ #[inline]
6173
+ fn tag_routed(&self, xid: Option<&[u8]>, builder: &mut BatchBuilder) -> Result<()> {
6174
+ if let Some(xid) = xid {
6175
+ self.flag_external()?;
6176
+ builder.tag_xid(xid)?;
6177
+ }
6178
+ Ok(())
6179
+ }
6180
+
5240
6181
  fn separate_large(
5241
6182
  &self,
5242
6183
  builder: BatchBuilder,
@@ -5247,11 +6188,18 @@ impl Inner {
5247
6188
  /// Validates and routes a batch: per-shard parts in first-appearance order.
5248
6189
  fn route(&self, mut batch: WriteBatch, view: &View) -> Result<(BatchBuilder, Shards)> {
5249
6190
  if batch.logged() {
6191
+ if batch.builder.is_silent() {
6192
+ self.flag_silent()?;
6193
+ }
5250
6194
  return route_logged(batch, view);
5251
6195
  }
6196
+ // A replica refuses its own writes before a silent one's bit is set.
5252
6197
  if self.replica.load(Ordering::Relaxed) {
5253
6198
  return Err(replica_refusal());
5254
6199
  }
6200
+ if batch.builder.is_silent() {
6201
+ self.flag_silent()?;
6202
+ }
5255
6203
  let catalog = &view.catalog;
5256
6204
  for rd in std::mem::take(&mut batch.row_deletes) {
5257
6205
  let info = catalog
@@ -5288,17 +6236,7 @@ impl Inner {
5288
6236
  if meta.options.kind.is_aggregate() {
5289
6237
  fixed_ts |= check_counter_write(&m, meta, catalog)?;
5290
6238
  counter_writes += usize::from(matches!(m.kind, Kind::Put | Kind::Merge));
5291
- converts |= match (meta.options.kind, m.kind) {
5292
- (FamilyKind::Hll | FamilyKind::Bloom, Kind::Merge) => true,
5293
- (
5294
- FamilyKind::SumF64
5295
- | FamilyKind::MeanVar
5296
- | FamilyKind::Histogram
5297
- | FamilyKind::Quantiles,
5298
- Kind::Put,
5299
- ) => m.value.first() == Some(&(ValueTag::F64 as u8)),
5300
- _ => false,
5301
- };
6239
+ converts |= counter_write_converts(meta.options.kind, &m);
5302
6240
  } else if m.kind == Kind::Put
5303
6241
  && (meta.options.kind == FamilyKind::Vector
5304
6242
  || m.value.first() == Some(&(ValueTag::Vector as u8)))
@@ -5344,7 +6282,11 @@ impl Inner {
5344
6282
  }
5345
6283
  }
5346
6284
  if fixed_ts || counter_writes > 1 || converts {
5347
- return Ok((prepare_counter_writes(&batch.builder, catalog)?, shards));
6285
+ let combines = counter_writes > 1 || converts;
6286
+ return Ok((
6287
+ prepare_counter_writes(&batch.builder, catalog, combines)?,
6288
+ shards,
6289
+ ));
5348
6290
  }
5349
6291
  Ok((batch.builder, shards))
5350
6292
  }
@@ -5356,10 +6298,362 @@ impl Inner {
5356
6298
  validate: Option<Arc<Validate>>,
5357
6299
  predicate: Option<(TableId, Vec<u8>, Predicate)>,
5358
6300
  ) -> Result<Submission> {
5359
- let routed = self.route_and_send(batch, durability, validate, predicate, NoAdmission)?;
6301
+ self.submit_with(batch, durability, validate, predicate, None)
6302
+ }
6303
+
6304
+ /// [`submit`](Self::submit) for a transaction that may be a spanning commit's share
6305
+ /// (D329 2b, `xid`). Inlined, so `submit`'s constant `None` folds away (perf2 on #2076).
6306
+ #[inline(always)]
6307
+ pub(crate) fn submit_with(
6308
+ &self,
6309
+ batch: WriteBatch,
6310
+ durability: Option<Durability>,
6311
+ validate: Option<Arc<Validate>>,
6312
+ predicate: Option<(TableId, Vec<u8>, Predicate)>,
6313
+ xid: Option<&[u8]>,
6314
+ ) -> Result<Submission> {
6315
+ let routed =
6316
+ self.route_and_send(batch, durability, validate, predicate, xid, NoAdmission)?;
5360
6317
  self.submission(routed)
5361
6318
  }
5362
6319
 
6320
+ /// Submits `batch` (validated by `validate`) for preparing as transaction `xid` of an
6321
+ /// external coordinator (D329, ICR 0140), without waiting: every share is logged as an
6322
+ /// external PREPARE and holds its rows, and the commit's decision waits for
6323
+ /// [`Engine::decide`], across a close and a reopen. It always takes the cross-shard path,
6324
+ /// even for one shard. Off the commit paths: nothing on them changes. Also the
6325
+ /// reservation's token, for the blocking form's prompt release.
6326
+ pub(crate) fn submit_prepare_external(
6327
+ &self,
6328
+ batch: WriteBatch,
6329
+ durability: Durability,
6330
+ validate: Option<Arc<Validate>>,
6331
+ xid: &[u8],
6332
+ ) -> Result<(Submission, u64)> {
6333
+ if self.read_only {
6334
+ return Err(Error::ReadOnly);
6335
+ }
6336
+ self.check_writable()?;
6337
+ if xid.is_empty() || xid.len() > pigeonhole_format::key::MAX_KEY_PART {
6338
+ return Err(Error::InvalidArgument(
6339
+ "an external xid is 1 byte to 64 KiB".to_owned(),
6340
+ ));
6341
+ }
6342
+ // A share in doubt is logged, but a `None` decision writes no record: its abort or
6343
+ // commit would be lost to any crash, and the share come back in doubt after the
6344
+ // caller heard its outcome (found by the model-check harness).
6345
+ if durability == Durability::None {
6346
+ return Err(Error::InvalidArgument(
6347
+ "an external prepare and its decision are logged: Buffered at least".to_owned(),
6348
+ ));
6349
+ }
6350
+ let view = self.shared.view.load();
6351
+ let (builder, mut shards) = self.route(batch, &view)?;
6352
+ let (builder, large) = self.separate_large(builder)?;
6353
+ if large.is_some() {
6354
+ // A large value's blob file is kept only by its commit's success; an in-doubt
6355
+ // share would need it kept across a reopen too (not in ICR 0140's first part).
6356
+ return Err(Error::InvalidArgument(
6357
+ "a prepared transaction can't hold a value over the inline limit".to_owned(),
6358
+ ));
6359
+ }
6360
+ if let Some(reads) = validate.as_ref().map(|v| &v.reads) {
6361
+ for r in reads {
6362
+ if let Some((_, shard)) = view.tablets().route(r.table, &r.row)
6363
+ && !shards.contains(&shard)
6364
+ {
6365
+ shards.push(shard);
6366
+ }
6367
+ }
6368
+ }
6369
+ // A branch that only read (D329 2a) logs its read set with an empty batch, and holds
6370
+ // those rows until decided, as any share does: its shards are the reads' shards.
6371
+ if shards.is_empty() {
6372
+ return Err(Error::InvalidArgument(
6373
+ "an external prepare needs reads or writes".to_owned(),
6374
+ ));
6375
+ }
6376
+ // Reserved under the lock that checks the xid and the limits (ICR 0140): two prepares of
6377
+ // one xid can't both log, nor concurrent ones pass a limit together. The request
6378
+ // holds the reservation from here: any error below drops it, and with it the
6379
+ // reservation (`ExternalReq`'s drop).
6380
+ let token = self
6381
+ .shared
6382
+ .external
6383
+ .reserve(xid, builder.batch().as_bytes().len() as u64)?;
6384
+ let ext = Arc::new(crate::shard::ExternalReq {
6385
+ xid: xid.into(),
6386
+ reservation: Some((Arc::downgrade(&self.shared.external), token)),
6387
+ });
6388
+ self.flag_external()?;
6389
+ let parts = split_by_shard(&view, &builder, &shards)?;
6390
+ let target = shards[0];
6391
+ let (tx, waiter) = crate::write::commit_completion();
6392
+ let msg = ShardMsg::Coordinate(Box::new(CoordinateReq {
6393
+ external: Some(ext),
6394
+ parts,
6395
+ durability,
6396
+ reply: tx,
6397
+ submitted_at: self.shared.clock_vfs.monotonic_nanos(),
6398
+ validate,
6399
+ map_version: view.tablets.version(),
6400
+ epoch: 0,
6401
+ first_seqno: 0,
6402
+ prev_shards: Vec::new(),
6403
+ attempts: 0,
6404
+ wait: None,
6405
+ }));
6406
+ self.shared.submitter(target).submit(msg)?;
6407
+ Ok((
6408
+ Submission {
6409
+ waiter,
6410
+ shared: self.shard_ref(target),
6411
+ spins: false,
6412
+ },
6413
+ token,
6414
+ ))
6415
+ }
6416
+
6417
+ /// Validates and holds a read-only transaction's `validate.reads` in memory (ICR 0140
6418
+ /// amendment 1, D329 PR 2a): each shard owning some checks them against the snapshot
6419
+ /// and holds them; nothing is logged. The answer's token and shards are for
6420
+ /// [`release_reads`](Self::release_reads). `Conflict` if a read changed since the
6421
+ /// snapshot or overlaps an undecided write; `Busy` past the in-doubt share limit (live
6422
+ /// holds count), or for a read whose tablet is moving. Refused on a replica, and on a
6423
+ /// read-only open (`ReadOnly`).
6424
+ pub(crate) fn hold_reads(&self, validate: Arc<Validate>) -> Result<(u64, Vec<ShardId>)> {
6425
+ let mut sub = self.submit_hold_reads(validate)?;
6426
+ let answers: Vec<_> = sub
6427
+ .waiting
6428
+ .iter_mut()
6429
+ .map(|(shard, rx)| (*shard, rx.take().expect("not yet answered").wait()))
6430
+ .collect();
6431
+ for (shard, answer) in answers {
6432
+ sub.answered(shard, answer);
6433
+ }
6434
+ self.finish_hold(sub)
6435
+ }
6436
+
6437
+ /// [`hold_reads`](Self::hold_reads) without waiting (#2059): sends each shard its reads
6438
+ /// and returns the answers to come. [`finish_hold`](Self::finish_hold) turns them into
6439
+ /// the hold, or releases what was held and returns the refusal.
6440
+ pub(crate) fn submit_hold_reads(&self, validate: Arc<Validate>) -> Result<HoldSubmission> {
6441
+ if self.read_only || self.replica.load(Ordering::Relaxed) {
6442
+ return Err(Error::ReadOnly);
6443
+ }
6444
+ self.check_writable()?;
6445
+ if validate.reads.is_empty() {
6446
+ return Err(Error::InvalidArgument("a read hold needs reads".to_owned()));
6447
+ }
6448
+ let view = self.shared.view.load();
6449
+ type Routed = (Vec<crate::write::ReadKey>, Vec<TabletId>);
6450
+ let mut by_shard: BTreeMap<ShardId, Routed> = BTreeMap::new();
6451
+ for r in &validate.reads {
6452
+ // A read the view can't route is of a table dropped since it was read: changed,
6453
+ // so nothing can hold it (perf2's nit on #2062).
6454
+ let Some((tablet, shard)) = view.tablets().route(r.table, &r.row) else {
6455
+ return Err(Error::Conflict);
6456
+ };
6457
+ let (reads, tablets) = by_shard.entry(shard).or_default();
6458
+ reads.push(r.clone());
6459
+ tablets.push(tablet);
6460
+ }
6461
+ drop(view);
6462
+ let token = self.shared.external.reserve_hold()?;
6463
+ let mut sub = HoldSubmission {
6464
+ token,
6465
+ waiting: Vec::with_capacity(by_shard.len()),
6466
+ held: Vec::with_capacity(by_shard.len()),
6467
+ failed: None,
6468
+ };
6469
+ for (shard, (reads, tablets)) in by_shard {
6470
+ let (tx, rx) = completion();
6471
+ let msg = ShardMsg::HoldReads(Box::new(crate::shard::HoldReadsReq {
6472
+ token,
6473
+ validate: Arc::clone(&validate),
6474
+ reads,
6475
+ tablets,
6476
+ reply: tx,
6477
+ }));
6478
+ match self.shared.submitter(shard).submit(msg) {
6479
+ Ok(()) => sub.waiting.push((shard, Some(rx))),
6480
+ Err(e) => {
6481
+ sub.failed = Some(Error::from(e));
6482
+ break;
6483
+ }
6484
+ }
6485
+ }
6486
+ Ok(sub)
6487
+ }
6488
+
6489
+ /// The hold `sub` built once every shard answered: its token and shards, or the refusal,
6490
+ /// with what any shard held released (without waiting, so a shard's driver may call it).
6491
+ pub(crate) fn finish_hold(&self, sub: HoldSubmission) -> Result<(u64, Vec<ShardId>)> {
6492
+ debug_assert!(sub.waiting.iter().all(|(_, rx)| rx.is_none()));
6493
+ match sub.failed {
6494
+ None => Ok((sub.token, sub.held)),
6495
+ Some(e) => {
6496
+ self.release_reads(sub.token, &sub.held, false);
6497
+ Err(e)
6498
+ }
6499
+ }
6500
+ }
6501
+
6502
+ /// Ends read hold `token` on `shards` (ICR 0140 amendment 1); with `wait`, answers
6503
+ /// whether every shard still held it (`false` once the hold was lost to a close or a
6504
+ /// recovery). With `wait`, never called on a thread that drives a shard
6505
+ /// ([`ReadHold::release`](crate::ReadHold::release) refuses that first). Without it (a
6506
+ /// dropped hold), it doesn't wait, and its answer means nothing. The hold stops counting
6507
+ /// against the limit either way.
6508
+ pub(crate) fn release_reads(&self, token: u64, shards: &[ShardId], wait: bool) -> bool {
6509
+ debug_assert!(!wait || !self.shared.drivers.current_drives());
6510
+ let (mut held, waiting) = self.submit_release_reads(token, shards, wait);
6511
+ for rx in waiting {
6512
+ held &= rx.wait() == Some(true);
6513
+ }
6514
+ held && wait
6515
+ }
6516
+
6517
+ /// Sends [`release_reads`](Self::release_reads)'s messages without waiting (#2059):
6518
+ /// whether every shard took its message, and, with `answers`, the shards' answers to
6519
+ /// come (each `true` if that shard still held it). The hold stops counting against the
6520
+ /// limit here.
6521
+ pub(crate) fn submit_release_reads(
6522
+ &self,
6523
+ token: u64,
6524
+ shards: &[ShardId],
6525
+ answers: bool,
6526
+ ) -> (bool, Vec<Waiter<bool>>) {
6527
+ self.shared.external.release_hold();
6528
+ let mut sent = true;
6529
+ let mut waiting = Vec::new();
6530
+ for &shard in shards {
6531
+ let (reply, rx) = if answers {
6532
+ let (tx, rx) = completion();
6533
+ (Some(tx), Some(rx))
6534
+ } else {
6535
+ (None, None)
6536
+ };
6537
+ if self
6538
+ .shared
6539
+ .submitter(shard)
6540
+ .submit(ShardMsg::ReleaseReads(Box::new((token, reply))))
6541
+ .is_err()
6542
+ {
6543
+ sent = false;
6544
+ } else if let Some(rx) = rx {
6545
+ waiting.push(rx);
6546
+ }
6547
+ }
6548
+ (sent, waiting)
6549
+ }
6550
+
6551
+ /// [`submit_prepare_external`](Self::submit_prepare_external), waited for. The answer in,
6552
+ /// this prepare's reservation goes at once, so the caller may prepare the xid again
6553
+ /// straight after a refusal, without waiting for the coordination's last handle.
6554
+ pub(crate) fn prepare_external(
6555
+ &self,
6556
+ batch: WriteBatch,
6557
+ durability: Durability,
6558
+ validate: Option<Arc<Validate>>,
6559
+ xid: &[u8],
6560
+ ) -> Result<CommitInfo> {
6561
+ let (mut sub, token) = self.submit_prepare_external(batch, durability, validate, xid)?;
6562
+ let prepared = crate::write::wait_blocking(&self.shared, &mut sub.waiter, false);
6563
+ // Unless every share was logged (the coordinator replaced the reservation with the
6564
+ // xid's entry before it answered), this prepare's reservation goes; a later
6565
+ // prepare's of the same xid has its own token and stays (perf2's S3).
6566
+ self.shared.external.unreserve(xid, token);
6567
+ prepared
6568
+ }
6569
+
6570
+ /// Decides the externally prepared transaction `xid` (D329, ICR 0140): `commit` applies
6571
+ /// its shares (`Some` with the commit's seqno once applied), and otherwise they are
6572
+ /// dropped (`Some` with its id). `None` when `xid` isn't in doubt here: decided already,
6573
+ /// or never prepared. Idempotent.
6574
+ pub(crate) fn decide(&self, xid: &[u8], commit: bool) -> Result<Option<CommitInfo>> {
6575
+ let Some(mut sub) = self.submit_decide(xid, commit)? else {
6576
+ return Ok(None);
6577
+ };
6578
+ let info = crate::write::wait_blocking(&self.shared, &mut sub.waiter, false)?;
6579
+ Ok((info.seqno != 0).then_some(info))
6580
+ }
6581
+
6582
+ /// [`decide`](Self::decide) without waiting: `None` when `xid` isn't in doubt here.
6583
+ /// The submission resolves with seqno 0 if another decide of it won meanwhile.
6584
+ pub(crate) fn submit_decide(&self, xid: &[u8], commit: bool) -> Result<Option<Submission>> {
6585
+ if self.read_only {
6586
+ return Err(Error::ReadOnly);
6587
+ }
6588
+ self.check_writable()?;
6589
+ let entry = match self.shared.external.lookup(xid) {
6590
+ crate::external_registry::Lookup::InDoubt(e) => e,
6591
+ crate::external_registry::Lookup::Absent => return Ok(None),
6592
+ // A prepare of it is still in flight: not in doubt yet, nor decided. The caller
6593
+ // asks again once the prepare has answered.
6594
+ crate::external_registry::Lookup::Reserved => return Err(Error::Busy),
6595
+ };
6596
+ let (tx, waiter) = crate::write::commit_completion();
6597
+ self.shared
6598
+ .submitter(entry.coordinator)
6599
+ .submit(ShardMsg::ExternalDecide {
6600
+ id: entry.id,
6601
+ commit,
6602
+ reply: tx,
6603
+ })?;
6604
+ Ok(Some(Submission {
6605
+ waiter,
6606
+ shared: self.shard_ref(entry.coordinator),
6607
+ spins: false,
6608
+ }))
6609
+ }
6610
+
6611
+ /// The externally prepared transactions in doubt here (D329): each one's xid, and how
6612
+ /// long ago (the engine's monotonic clock) it was prepared, in nanoseconds.
6613
+ pub(crate) fn in_doubt(&self) -> Vec<(Vec<u8>, u64)> {
6614
+ let now = self.shared.clock_vfs.monotonic_nanos();
6615
+ self.shared
6616
+ .external
6617
+ .in_doubt()
6618
+ .into_iter()
6619
+ .map(|(xid, e)| (xid, now.saturating_sub(e.prepared_at)))
6620
+ .collect()
6621
+ }
6622
+
6623
+ /// Sets `incompat` bit 2 in both superblock pages before the first external PREPARE
6624
+ /// (D329): once per database, under the manifest writer's lock.
6625
+ fn flag_external(&self) -> Result<()> {
6626
+ if self.shared.external_flagged.load(Ordering::Acquire) {
6627
+ return Ok(());
6628
+ }
6629
+ // Through the writer, under its exclusion: never beside a root commit in flight
6630
+ // (the race #2089's crash sweep found for bit 3).
6631
+ manifest::commit_from_thread(
6632
+ &self.shared,
6633
+ manifest::ReqKind::Incompat(pigeonhole_format::wal::INCOMPAT_EXTERNAL_PREPARE),
6634
+ )?;
6635
+ self.shared.external_flagged.store(true, Ordering::Release);
6636
+ Ok(())
6637
+ }
6638
+
6639
+ /// Sets `incompat` bit 3 in both superblock pages before the first feed-silent batch is
6640
+ /// routed (D331, ICR 0141), so every record carrying the mark is behind it: once per
6641
+ /// database, under the manifest writer's lock. Sticky (FORMAT §8.2).
6642
+ #[cold]
6643
+ #[inline(never)]
6644
+ fn flag_silent(&self) -> Result<()> {
6645
+ if self.shared.silent_flagged.load(Ordering::Acquire) {
6646
+ return Ok(());
6647
+ }
6648
+ // Through the writer, under its exclusion: never beside a root commit in flight.
6649
+ manifest::commit_from_thread(
6650
+ &self.shared,
6651
+ manifest::ReqKind::Incompat(pigeonhole_format::wal::INCOMPAT_FEED_SILENT),
6652
+ )?;
6653
+ self.shared.silent_flagged.store(true, Ordering::Release);
6654
+ Ok(())
6655
+ }
6656
+
5363
6657
  /// Routes `batch` and sends its request to its shard (a cross-shard commit's
5364
6658
  /// coordinator). With `admit` (an async commit's admission and bytes), it first charges
5365
6659
  /// that shard (D236), so the commit is routed once; without room it builds the request
@@ -5375,15 +6669,20 @@ impl Inner {
5375
6669
  durability: Option<Durability>,
5376
6670
  validate: Option<Arc<Validate>>,
5377
6671
  predicate: Option<(TableId, Vec<u8>, Predicate)>,
6672
+ xid: Option<&[u8]>,
5378
6673
  admit: A,
5379
6674
  ) -> Result<Routed<A::Charge>> {
5380
- self.route_and_send_with(batch, durability, validate, predicate, None, admit)
6675
+ self.route_and_send_with(batch, durability, validate, predicate, None, xid, admit)
5381
6676
  }
5382
6677
 
5383
6678
  /// [`route_and_send`](Self::route_and_send), for a commit that may return its
5384
6679
  /// incremented counters (D314): `returning` is `None` on every other path, a constant the
5385
6680
  /// inlined body folds away.
5386
6681
  #[inline(always)]
6682
+ #[expect(
6683
+ clippy::too_many_arguments,
6684
+ reason = "each is a constant at its inlined call sites, which fold away (returning, xid)"
6685
+ )]
5387
6686
  pub(crate) fn route_and_send_with<A: Admitter>(
5388
6687
  &self,
5389
6688
  batch: WriteBatch,
@@ -5391,6 +6690,7 @@ impl Inner {
5391
6690
  validate: Option<Arc<Validate>>,
5392
6691
  predicate: Option<(TableId, Vec<u8>, Predicate)>,
5393
6692
  returning: Option<crate::shard::ReturnSlot>,
6693
+ xid: Option<&[u8]>,
5394
6694
  admit: A,
5395
6695
  ) -> Result<Routed<A::Charge>> {
5396
6696
  if self.read_only {
@@ -5401,7 +6701,11 @@ impl Inner {
5401
6701
  // One tablet map for the whole routing: its version goes with a cross-shard commit,
5402
6702
  // which a participant moving a tablet refuses and the coordinator retries.
5403
6703
  let view = self.shared.view.load();
5404
- let (builder, mut shards) = self.route(batch, &view)?;
6704
+ let (mut builder, mut shards) = self.route(batch, &view)?;
6705
+ // A spanning commit's share (D329 2b): `xid` comes with the commit, not on the
6706
+ // batch, so a `WriteBatch` moved through every commit carries nothing for it; `None`
6707
+ // on every other path, a constant the inlined body folds away (perf2's N1 on #2076).
6708
+ self.tag_routed(xid, &mut builder)?;
5405
6709
  let (builder, large) = self.separate_large(builder)?;
5406
6710
  // Every shard that owns a row the transaction read validates it at PREPARE, so two
5407
6711
  // transactions cannot each read what the other writes (write skew).
@@ -5414,7 +6718,7 @@ impl Inner {
5414
6718
  }
5415
6719
  }
5416
6720
  }
5417
- let submitted_at = self.shared.vfs.monotonic_nanos();
6721
+ let submitted_at = self.shared.clock_vfs.monotonic_nanos();
5418
6722
  let (tx, waiter) = crate::write::commit_completion();
5419
6723
  if let Some(large) = large {
5420
6724
  large.settle_on(&tx, crate::large::commit_succeeded);
@@ -5473,6 +6777,7 @@ impl Inner {
5473
6777
  let parts = split_by_shard(&view, &builder, &shards)?;
5474
6778
  let target = shards[0];
5475
6779
  let msg = ShardMsg::Coordinate(Box::new(CoordinateReq {
6780
+ external: None,
5476
6781
  parts,
5477
6782
  durability,
5478
6783
  reply: tx,
@@ -5510,7 +6815,19 @@ impl Inner {
5510
6815
  batch: WriteBatch,
5511
6816
  durability: Option<Durability>,
5512
6817
  ) -> Result<CommitInfo> {
5513
- match self.route_and_send(batch, durability, None, None, NoAdmission)? {
6818
+ self.commit_blocking_with(batch, durability, None)
6819
+ }
6820
+
6821
+ /// [`commit_blocking`](Self::commit_blocking) for a replica's run of a spanning commit's
6822
+ /// share (D329 2b, `xid`). Inlined, so `commit_blocking`'s constant `None` folds away.
6823
+ #[inline(always)]
6824
+ fn commit_blocking_with(
6825
+ &self,
6826
+ batch: WriteBatch,
6827
+ durability: Option<Durability>,
6828
+ xid: Option<&[u8]>,
6829
+ ) -> Result<CommitInfo> {
6830
+ match self.route_and_send(batch, durability, None, None, xid, NoAdmission)? {
5514
6831
  // Caller-runs (D321): the commit's shard, which this thread may run itself while
5515
6832
  // its spinning wait goes on. A cross-shard commit's coordinator refuses it (only
5516
6833
  // single-shard commits are a caller's to run).
@@ -5614,7 +6931,7 @@ impl Inner {
5614
6931
  [s] => *s,
5615
6932
  _ => unreachable!("one row routes to one shard"),
5616
6933
  };
5617
- let submitted_at = self.shared.vfs.monotonic_nanos();
6934
+ let submitted_at = self.shared.clock_vfs.monotonic_nanos();
5618
6935
  let (tx, rx) = completion();
5619
6936
  if let Some(large) = large {
5620
6937
  large.settle_on(&tx, crate::large::check_succeeded);
@@ -5725,7 +7042,7 @@ impl Inner {
5725
7042
  rc,
5726
7043
  &snapshot.view,
5727
7044
  snapshot.seqno,
5728
- self.shared.vfs.now_micros(),
7045
+ self.shared.clock_vfs.now_micros(),
5729
7046
  table,
5730
7047
  family,
5731
7048
  row,
@@ -5737,7 +7054,7 @@ impl Inner {
5737
7054
  snapshot.checked(get_in::<false>(
5738
7055
  &snapshot.view,
5739
7056
  snapshot.seqno,
5740
- || self.shared.vfs.now_micros(),
7057
+ || self.shared.clock_vfs.now_micros(),
5741
7058
  table,
5742
7059
  family,
5743
7060
  row,
@@ -6422,6 +7739,24 @@ fn family_name(catalog: &Catalog, table: TableId, family: FamilyId) -> String {
6422
7739
  }
6423
7740
  }
6424
7741
 
7742
+ /// Whether a counter-family write is rewritten before the WAL (D294, D298): an HLL or bloom
7743
+ /// input (an element, written as its one-element state), or an `f64` put into a state kind
7744
+ /// (the state of that one input). [`prepare_counter_writes`]' pass-through path relies on
7745
+ /// there being none.
7746
+ fn counter_write_converts(kind: FamilyKind, m: &Mutation<'_>) -> bool {
7747
+ match (kind, m.kind) {
7748
+ (FamilyKind::Hll | FamilyKind::Bloom, Kind::Merge) => true,
7749
+ (
7750
+ FamilyKind::SumF64
7751
+ | FamilyKind::MeanVar
7752
+ | FamilyKind::Histogram
7753
+ | FamilyKind::Quantiles,
7754
+ Kind::Put,
7755
+ ) => m.value.first() == Some(&(ValueTag::F64 as u8)),
7756
+ _ => false,
7757
+ }
7758
+ }
7759
+
6425
7760
  /// `(table, family, row, qualifier, timestamp)` of a cell in a batch.
6426
7761
  type CellKey<'a> = (TableId, FamilyId, &'a [u8], &'a [u8], Timestamp);
6427
7762
 
@@ -6431,7 +7766,64 @@ type CellKey<'a> = (TableId, FamilyId, &'a [u8], &'a [u8], Timestamp);
6431
7766
  /// combines into that write with the family's aggregation (a sum, min or max), in write
6432
7767
  /// order. Deletes do not stop a combination; D34 then collapses what is left of one cell to
6433
7768
  /// the last write.
6434
- fn prepare_counter_writes(batch: &BatchBuilder, catalog: &Catalog) -> Result<BatchBuilder> {
7769
+ ///
7770
+ /// Tags `to`, a batch rebuilt from `from`, with `from`'s xid if it has one (D329 2b): the
7771
+ /// rebuild's last step, so its pushes never meet the trailer. One bit test for an untagged
7772
+ /// batch.
7773
+ #[inline]
7774
+ pub(crate) fn carry_xid(from: &BatchBuilder, to: &mut BatchBuilder) -> Result<()> {
7775
+ // One byte's test for an untagged batch (perf2's N1 on #2076); the copy out of line.
7776
+ if from.is_tagged() {
7777
+ return carry_xid_cold(from, to);
7778
+ }
7779
+ Ok(())
7780
+ }
7781
+
7782
+ #[cold]
7783
+ #[inline(never)]
7784
+ fn carry_xid_cold(from: &BatchBuilder, to: &mut BatchBuilder) -> Result<()> {
7785
+ match from.batch().xid() {
7786
+ Some(xid) => Ok(to.tag_xid(xid)?),
7787
+ None => Ok(()),
7788
+ }
7789
+ }
7790
+
7791
+ /// `combines`: the batch has two or more counter puts or operands, or a write to convert. Without
7792
+ /// one, the only change is the fixed timestamp, and the batch is copied straight through: no
7793
+ /// map, no list of writes, and the copy sized once (#1795: a lone `incr`'s rebuilt batch grew
7794
+ /// from `BatchBuilder::new`'s 4 bytes, a calloc and a realloc per commit that glibc 2.43 served
7795
+ /// at a cost varying run to run with the heap's state).
7796
+ fn prepare_counter_writes(
7797
+ batch: &BatchBuilder,
7798
+ catalog: &Catalog,
7799
+ combines: bool,
7800
+ ) -> Result<BatchBuilder> {
7801
+ // Runs inside `route`, before `tag_routed`: the batch has no xid trailer to carry yet.
7802
+ debug_assert!(!batch.is_tagged(), "a tagged batch before routing");
7803
+ // Each write may gain an 8-byte timestamp.
7804
+ let mut out = BatchBuilder::with_capacity(batch.batch().as_bytes().len() + 8 * batch.len());
7805
+ if batch.is_silent() {
7806
+ out.mark_silent();
7807
+ }
7808
+ if !combines {
7809
+ for m in batch.batch().iter() {
7810
+ let mut m = m?;
7811
+ let aggregate = catalog
7812
+ .family(m.family)
7813
+ .is_some_and(|f| f.options.kind.is_aggregate());
7814
+ if aggregate && matches!(m.kind, Kind::Put | Kind::Merge) {
7815
+ m.ts.get_or_insert(COUNTER_TS);
7816
+ }
7817
+ debug_assert!(
7818
+ !catalog
7819
+ .family(m.family)
7820
+ .is_some_and(|f| counter_write_converts(f.options.kind, &m)),
7821
+ "a write to convert reached the pass-through path"
7822
+ );
7823
+ out.push(m.table, m.family, m.kind, m.row, m.qualifier, m.ts, m.value)?;
7824
+ }
7825
+ return Ok(out);
7826
+ }
6435
7827
  struct Write<'a> {
6436
7828
  m: Mutation<'a>,
6437
7829
  /// The value of a combined write, replacing `m.value`.
@@ -6530,7 +7922,6 @@ fn prepare_counter_writes(batch: &BatchBuilder, catalog: &Catalog) -> Result<Bat
6530
7922
  latest.insert(key, writes.len());
6531
7923
  writes.push(Write { m, value: own });
6532
7924
  }
6533
- let mut out = BatchBuilder::new();
6534
7925
  for w in &writes {
6535
7926
  let m = &w.m;
6536
7927
  let value = w.value.as_deref().unwrap_or(m.value);
@@ -7078,6 +8469,7 @@ impl Shared {
7078
8469
  ) -> Self {
7079
8470
  Shared {
7080
8471
  vfs: Arc::clone(vfs),
8472
+ clock_vfs: Arc::clone(vfs),
7081
8473
  shm: shm.clone(),
7082
8474
  reader_reclaim_at: AtomicU64::new(0),
7083
8475
  reader_slots_reclaimed: AtomicU64::new(0),
@@ -7091,6 +8483,13 @@ impl Shared {
7091
8483
  manifest_queue: Default::default(),
7092
8484
  manifest_busy: AtomicBool::new(false),
7093
8485
  pager: Arc::clone(pager),
8486
+ punch: options.punch_freed.then(|| {
8487
+ crate::punch::Punch::new(
8488
+ options.punch_tuning.unwrap_or_default(),
8489
+ options.memtable_budget,
8490
+ shards,
8491
+ )
8492
+ }),
7094
8493
  cache: Arc::clone(cache),
7095
8494
  row_cache: None,
7096
8495
  row_epochs: None,
@@ -7114,6 +8513,13 @@ impl Shared {
7114
8513
  // The writer's open fills it as its last step (`held`).
7115
8514
  locks: Mutex::new(None),
7116
8515
  keep_locks: AtomicBool::new(false),
8516
+ external_flagged: AtomicBool::new(false),
8517
+ silent_flagged: AtomicBool::new(
8518
+ pager.features().incompat & pigeonhole_format::wal::INCOMPAT_FEED_SILENT != 0,
8519
+ ),
8520
+ external: Arc::new(crate::external_registry::ExternalRegistry::new(
8521
+ options.in_doubt_limits,
8522
+ )),
7117
8523
  arena_discard: AtomicU8::new(crate::shard::ARENAS_PENDING),
7118
8524
  close_done: AtomicBool::new(false),
7119
8525
  application_owned: false,
@@ -7130,6 +8536,8 @@ impl Shared {
7130
8536
  clock: Default::default(),
7131
8537
  flushed_through: Vec::new(),
7132
8538
  loads: Vec::new(),
8539
+ tablet_loads: Vec::new(),
8540
+ io: Arc::default(),
7133
8541
  balance: BalanceConfig::default(),
7134
8542
  view_capacity,
7135
8543
  tablet_epoch: AtomicU64::new(0),
@@ -7394,3 +8802,37 @@ impl std::future::Future for PendingReturning {
7394
8802
  }
7395
8803
  }
7396
8804
  }
8805
+
8806
+ /// A read hold's requests in flight (#2059, [`Inner::submit_hold_reads`]): the hold's token,
8807
+ /// each asked shard with its answer to come (`None` once answered), the shards that hold it,
8808
+ /// and the refusal so far. A conflict wins over another shard's transient refusal, since
8809
+ /// retrying can't help.
8810
+ #[derive(Debug)]
8811
+ pub(crate) struct HoldSubmission {
8812
+ pub(crate) token: u64,
8813
+ pub(crate) waiting: Vec<(ShardId, Option<Waiter<Result<()>>>)>,
8814
+ pub(crate) held: Vec<ShardId>,
8815
+ pub(crate) failed: Option<Error>,
8816
+ }
8817
+
8818
+ impl HoldSubmission {
8819
+ /// Notes `shard`'s answer (`None`: its notifier went unanswered, a closing shard).
8820
+ pub(crate) fn answered(&mut self, shard: ShardId, answer: Option<Result<()>>) {
8821
+ match answer {
8822
+ Some(Ok(())) => self.held.push(shard),
8823
+ Some(Err(e)) => {
8824
+ if !matches!(self.failed, Some(Error::Conflict)) {
8825
+ self.failed = Some(e);
8826
+ }
8827
+ }
8828
+ None => {
8829
+ self.failed.get_or_insert(Error::Closed);
8830
+ }
8831
+ }
8832
+ }
8833
+
8834
+ /// Every shard asked: the ones answered and the ones still to answer.
8835
+ pub(crate) fn asked(&self) -> Vec<ShardId> {
8836
+ self.waiting.iter().map(|(s, _)| *s).collect()
8837
+ }
8838
+ }