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
@@ -0,0 +1,447 @@
1
+ //! The registry of transactions prepared for an external coordinator (D329, ICR 0140),
2
+ //! `Shared::external`: which xids are reserved by a prepare in flight or in doubt here, and
3
+ //! the in-doubt limits.
4
+ //!
5
+ //! - **A prepare** reserves its xid ([`reserve`](ExternalRegistry::reserve)) before it
6
+ //! submits, under the lock that checks for the xid and the limits, so two prepares of one
7
+ //! xid can't both log, and concurrent prepares can't pass a limit together.
8
+ //! - **The coordinator** replaces the reservation with the xid's entry
9
+ //! ([`install`](ExternalRegistry::install)) once every share is logged, before it answers
10
+ //! the caller, so a `decide` after the prepare returned always finds it. It removes the
11
+ //! entry once decided ([`remove`](ExternalRegistry::remove)).
12
+ //! - **A prepare that didn't log** drops its reservation
13
+ //! ([`unreserve`](ExternalRegistry::unreserve)); an installed entry stays.
14
+ //! - **`decide`** looks the xid up ([`lookup`](ExternalRegistry::lookup)) and submits to the
15
+ //! coordinator after the lock is released. A reservation is not in doubt yet (`Busy`, ask
16
+ //! again). Two decides of one xid both reach the coordinator, whose shard thread orders
17
+ //! them: the second finds it decided.
18
+ //!
19
+ //! - **A read hold** (`hold_reads`, ICR 0140 amendment 1) counts against the share limit
20
+ //! while it is live ([`reserve_hold`](ExternalRegistry::reserve_hold),
21
+ //! [`release_hold`](ExternalRegistry::release_hold)), so holds and prepares can't pass it
22
+ //! together. Its token comes from the reservations' counter, so it is unique too.
23
+ //!
24
+ //! One lock, `entries`, a leaf: nothing is sent or waited on under it. The limits are fixed
25
+ //! at open. Loom-modelled (`loom_tests`).
26
+
27
+ #[cfg(engine_loom)]
28
+ use loom::sync::Mutex;
29
+ #[cfg(not(engine_loom))]
30
+ use std::sync::Mutex;
31
+
32
+ use std::collections::BTreeMap;
33
+ use std::sync::PoisonError;
34
+
35
+ use pigeonhole_format::Seqno;
36
+
37
+ use crate::error::{Error, Result};
38
+ use pigeonhole_runtime::ShardId;
39
+
40
+ /// An xid in doubt: its commit's id, the shard that holds its decision, when it was
41
+ /// prepared (the engine's monotonic clock), and its batches' bytes.
42
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
43
+ pub(crate) struct ExternalEntry {
44
+ pub id: Seqno,
45
+ pub coordinator: ShardId,
46
+ pub prepared_at: u64,
47
+ pub bytes: u64,
48
+ }
49
+
50
+ /// What [`ExternalRegistry::lookup`] finds for an xid.
51
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52
+ pub(crate) enum Lookup {
53
+ /// Neither reserved nor in doubt: decided already, or never prepared.
54
+ Absent,
55
+ /// A prepare of it is in flight.
56
+ Reserved,
57
+ InDoubt(ExternalEntry),
58
+ }
59
+
60
+ /// A slot: a prepare's reservation (its bytes, and the token that prepare holds), or an
61
+ /// entry in doubt.
62
+ #[derive(Debug, Clone, Copy)]
63
+ enum Slot {
64
+ Reserved { bytes: u64, token: u64 },
65
+ InDoubt(ExternalEntry),
66
+ }
67
+
68
+ impl Slot {
69
+ fn bytes(&self) -> u64 {
70
+ match self {
71
+ Slot::Reserved { bytes, .. } => *bytes,
72
+ Slot::InDoubt(e) => e.bytes,
73
+ }
74
+ }
75
+ }
76
+
77
+ /// The registry's state, under its one lock.
78
+ #[derive(Debug, Default)]
79
+ struct Table {
80
+ slots: BTreeMap<Vec<u8>, Slot>,
81
+ /// The last reservation's token: each one is new, so a prepare's late `unreserve` can't
82
+ /// drop a later prepare's reservation of the same xid (perf2's S3 on #2000). A read
83
+ /// hold's token comes from it too.
84
+ last_token: u64,
85
+ /// Read holds live now (ICR 0140 amendment 1): counted with `slots` against the share
86
+ /// limit.
87
+ holds: usize,
88
+ }
89
+
90
+ /// See the module documentation.
91
+ #[derive(Debug)]
92
+ pub(crate) struct ExternalRegistry {
93
+ entries: Mutex<Table>,
94
+ /// The most xids reserved or in doubt, and the most bytes of their batches; 0 for none
95
+ /// (`EngineOptions::in_doubt_limits`, fixed at open).
96
+ limits: (usize, u64),
97
+ }
98
+
99
+ impl Default for ExternalRegistry {
100
+ fn default() -> Self {
101
+ Self::new((0, 0))
102
+ }
103
+ }
104
+
105
+ impl ExternalRegistry {
106
+ /// An empty registry with the in-doubt `limits` (`EngineOptions::in_doubt_limits`).
107
+ pub(crate) fn new(limits: (usize, u64)) -> Self {
108
+ Self {
109
+ entries: Mutex::new(Table::default()),
110
+ limits,
111
+ }
112
+ }
113
+
114
+ fn table(&self) -> impl std::ops::DerefMut<Target = Table> + '_ {
115
+ self.entries.lock().unwrap_or_else(PoisonError::into_inner)
116
+ }
117
+
118
+ /// Reserves `xid` for a prepare of `bytes`. `InvalidArgument` if it is reserved or in
119
+ /// doubt already; `Busy` past a limit (prepares in flight count). The byte limit counts
120
+ /// this prepare's own bytes, so nothing reserved or in doubt passes it, except that a
121
+ /// prepare alone is always admitted: one larger than the limit could otherwise never
122
+ /// prepare (perf2's N2 on #2000).
123
+ /// The answer is the reservation's token, for [`unreserve`](Self::unreserve).
124
+ pub(crate) fn reserve(&self, xid: &[u8], bytes: u64) -> Result<u64> {
125
+ let mut table = self.table();
126
+ let entries = &mut table.slots;
127
+ if entries.contains_key(xid) {
128
+ return Err(Error::InvalidArgument(
129
+ "this xid is prepared here already: decide it first".to_owned(),
130
+ ));
131
+ }
132
+ let (max_shares, max_bytes) = self.limits;
133
+ let held: u64 = entries.values().map(Slot::bytes).sum();
134
+ let over_bytes = max_bytes > 0 && !entries.is_empty() && held + bytes > max_bytes;
135
+ if (max_shares > 0 && entries.len() + table.holds >= max_shares) || over_bytes {
136
+ return Err(Error::Busy);
137
+ }
138
+ table.last_token += 1;
139
+ let token = table.last_token;
140
+ table
141
+ .slots
142
+ .insert(xid.to_vec(), Slot::Reserved { bytes, token });
143
+ Ok(token)
144
+ }
145
+
146
+ /// Counts a read hold against the share limit (`Busy` past it) and answers its token.
147
+ pub(crate) fn reserve_hold(&self) -> Result<u64> {
148
+ let mut table = self.table();
149
+ let max_shares = self.limits.0;
150
+ if max_shares > 0 && table.slots.len() + table.holds >= max_shares {
151
+ return Err(Error::Busy);
152
+ }
153
+ table.holds += 1;
154
+ table.last_token += 1;
155
+ Ok(table.last_token)
156
+ }
157
+
158
+ /// A read hold ended (released, or its engine closed): it no longer counts.
159
+ pub(crate) fn release_hold(&self) {
160
+ let mut table = self.table();
161
+ table.holds = table.holds.saturating_sub(1);
162
+ }
163
+
164
+ /// Read holds live now: a range drop waits while any is (D331, #2089 landing after
165
+ /// #2076).
166
+ pub(crate) fn holds(&self) -> usize {
167
+ self.table().holds
168
+ }
169
+
170
+ /// Drops `xid`'s reservation `token`, if it is still that one: a prepare that logged
171
+ /// every share left its entry in its place, and a later prepare's reservation of the
172
+ /// same xid has a token of its own.
173
+ pub(crate) fn unreserve(&self, xid: &[u8], token: u64) {
174
+ let mut table = self.table();
175
+ if matches!(table.slots.get(xid), Some(Slot::Reserved { token: t, .. }) if *t == token) {
176
+ table.slots.remove(xid);
177
+ }
178
+ }
179
+
180
+ /// Records `xid` in doubt (the coordinator, every share logged; recovery's reinstall),
181
+ /// in place of its reservation if any.
182
+ pub(crate) fn install(&self, xid: &[u8], entry: ExternalEntry) {
183
+ self.table()
184
+ .slots
185
+ .insert(xid.to_vec(), Slot::InDoubt(entry));
186
+ }
187
+
188
+ /// Forgets `xid` once decided.
189
+ pub(crate) fn remove(&self, xid: &[u8]) {
190
+ self.table().slots.remove(xid);
191
+ }
192
+
193
+ /// What is known of `xid` here.
194
+ pub(crate) fn lookup(&self, xid: &[u8]) -> Lookup {
195
+ match self.table().slots.get(xid) {
196
+ None => Lookup::Absent,
197
+ Some(Slot::Reserved { .. }) => Lookup::Reserved,
198
+ Some(Slot::InDoubt(e)) => Lookup::InDoubt(*e),
199
+ }
200
+ }
201
+
202
+ /// Every xid in doubt, with its entry (reservations aren't).
203
+ pub(crate) fn in_doubt(&self) -> Vec<(Vec<u8>, ExternalEntry)> {
204
+ self.table()
205
+ .slots
206
+ .iter()
207
+ .filter_map(|(xid, s)| match s {
208
+ Slot::InDoubt(e) => Some((xid.clone(), *e)),
209
+ Slot::Reserved { .. } => None,
210
+ })
211
+ .collect()
212
+ }
213
+
214
+ /// Whether any xid is in doubt.
215
+ pub(crate) fn any_in_doubt(&self) -> bool {
216
+ self.table()
217
+ .slots
218
+ .values()
219
+ .any(|s| matches!(s, Slot::InDoubt(_)))
220
+ }
221
+ }
222
+
223
+ #[cfg(all(test, not(engine_loom)))]
224
+ mod tests {
225
+ use super::ExternalRegistry;
226
+ use crate::error::Error;
227
+
228
+ #[test]
229
+ fn the_byte_limit_counts_the_prepares_own_bytes_and_admits_one_alone() {
230
+ // perf2's N2 on #2000.
231
+ let r = ExternalRegistry::new((0, 10));
232
+ r.reserve(b"big", 25).unwrap();
233
+ assert!(matches!(r.reserve(b"small", 1), Err(Error::Busy)));
234
+ let big = r.lookup(b"big");
235
+ assert_eq!(big, super::Lookup::Reserved);
236
+ r.remove(b"big");
237
+ r.reserve(b"a", 6).unwrap();
238
+ assert!(
239
+ matches!(r.reserve(b"b", 5), Err(Error::Busy)),
240
+ "6 + 5 is over 10"
241
+ );
242
+ r.reserve(b"c", 4).unwrap();
243
+ }
244
+
245
+ #[test]
246
+ fn read_holds_count_against_the_share_limit_with_prepares() {
247
+ // ICR 0140 amendment 1: a live hold takes a share's place in the limit.
248
+ let r = ExternalRegistry::new((2, 0));
249
+ let a = r.reserve_hold().unwrap();
250
+ r.reserve(b"x", 1).unwrap();
251
+ assert!(matches!(r.reserve_hold(), Err(Error::Busy)));
252
+ assert!(matches!(r.reserve(b"y", 1), Err(Error::Busy)));
253
+ r.release_hold();
254
+ let b = r.reserve_hold().unwrap();
255
+ assert_ne!(a, b, "each hold's token is new");
256
+ assert_eq!(r.holds(), 1);
257
+ }
258
+ }
259
+
260
+ #[cfg(all(test, engine_loom))]
261
+ mod loom_tests {
262
+ use super::{ExternalEntry, ExternalRegistry, Lookup};
263
+ use crate::error::Error;
264
+ use loom::sync::Arc;
265
+ use loom::thread;
266
+ use pigeonhole_runtime::ShardId;
267
+
268
+ fn entry(id: u64) -> ExternalEntry {
269
+ ExternalEntry {
270
+ id,
271
+ coordinator: ShardId(0),
272
+ prepared_at: 0,
273
+ bytes: 1,
274
+ }
275
+ }
276
+
277
+ /// A prepare as `Inner::prepare_external` runs it against the registry: reserve, then
278
+ /// (every share logged) the coordinator installs the entry, then the reservation is
279
+ /// dropped if still one. `Ok(true)` if it prepared.
280
+ fn prepare(r: &ExternalRegistry, xid: &[u8], id: u64, logs: bool) -> Result<bool, Error> {
281
+ let token = r.reserve(xid, 1)?;
282
+ if logs {
283
+ r.install(xid, entry(id));
284
+ }
285
+ r.unreserve(xid, token);
286
+ Ok(logs)
287
+ }
288
+
289
+ #[test]
290
+ fn loom_two_prepares_of_one_xid_never_both_log() {
291
+ // Two prepares of xid "x" race. In every interleaving at most one reserves and logs;
292
+ // the other is refused (`InvalidArgument`), or, if it came after the first had
293
+ // logged, refused too: "x" is in doubt. The entry left is the winner's.
294
+ loom::model(|| {
295
+ let r = Arc::new(ExternalRegistry::default());
296
+ let spawn = |id| {
297
+ let r = Arc::clone(&r);
298
+ thread::spawn(move || prepare(&r, b"x", id, true))
299
+ };
300
+ let (a, b) = (spawn(1), spawn(2));
301
+ let (a, b) = (a.join().unwrap(), b.join().unwrap());
302
+ let won: Vec<u64> = [(a, 1), (b, 2)]
303
+ .into_iter()
304
+ .filter_map(|(res, id)| match res {
305
+ Ok(true) => Some(id),
306
+ Err(Error::InvalidArgument(_)) => None,
307
+ other => panic!("{other:?}"),
308
+ })
309
+ .collect();
310
+ assert_eq!(won.len(), 1, "exactly one prepare logs");
311
+ assert_eq!(r.lookup(b"x"), Lookup::InDoubt(entry(won[0])));
312
+ });
313
+ }
314
+
315
+ #[test]
316
+ fn loom_a_decide_racing_a_prepare_never_sees_it_decided_while_it_is_in_doubt() {
317
+ // A decide looks "x" up while its prepare runs. It sees it absent (before the
318
+ // reservation), reserved (`Busy`: ask again), or in doubt with the prepare's id:
319
+ // never absent once in doubt, so a decide after the prepare answered can't miss it.
320
+ // A prepare that fails (logs nothing) leaves nothing behind.
321
+ loom::model(|| {
322
+ let r = Arc::new(ExternalRegistry::default());
323
+ let p = {
324
+ let r = Arc::clone(&r);
325
+ thread::spawn(move || {
326
+ prepare(&r, b"x", 7, true).unwrap();
327
+ prepare(&r, b"y", 8, false).unwrap();
328
+ })
329
+ };
330
+ let first = r.lookup(b"x");
331
+ let second = r.lookup(b"x");
332
+ assert!(
333
+ matches!(
334
+ first,
335
+ Lookup::Absent | Lookup::Reserved | Lookup::InDoubt(_)
336
+ ),
337
+ "{first:?}"
338
+ );
339
+ if let Lookup::InDoubt(e) = first {
340
+ assert_eq!(e.id, 7);
341
+ assert_eq!(second, first, "once in doubt it stays until decided");
342
+ }
343
+ p.join().unwrap();
344
+ assert_eq!(r.lookup(b"x"), Lookup::InDoubt(entry(7)));
345
+ assert_eq!(r.lookup(b"y"), Lookup::Absent);
346
+ assert_eq!(r.in_doubt().len(), 1);
347
+ });
348
+ }
349
+
350
+ #[test]
351
+ fn loom_a_read_hold_and_a_prepare_never_pass_the_limit_together() {
352
+ // ICR 0140 amendment 1: with a limit of one share, a read hold and a prepare race.
353
+ // At most one is admitted; the other answers `Busy`. Once the winner is done, the
354
+ // limit is free again.
355
+ loom::model(|| {
356
+ let r = Arc::new(ExternalRegistry::new((1, 0)));
357
+ let h = {
358
+ let r = Arc::clone(&r);
359
+ thread::spawn(move || r.reserve_hold().is_ok())
360
+ };
361
+ let p = r.reserve(b"x", 1);
362
+ let held = h.join().unwrap();
363
+ match p {
364
+ Ok(_) => assert!(!held, "both passed the limit"),
365
+ Err(Error::Busy) => assert!(held, "both refused"),
366
+ Err(e) => panic!("{e:?}"),
367
+ }
368
+ if held {
369
+ r.release_hold();
370
+ } else {
371
+ r.remove(b"x");
372
+ }
373
+ assert!(r.reserve_hold().is_ok());
374
+ });
375
+ }
376
+
377
+ #[test]
378
+ fn loom_two_decides_and_the_coordinators_removal() {
379
+ // Two decides of "x" look it up while the coordinator, having decided it, removes
380
+ // it. Each sees it in doubt or absent; one that saw it absent never sees it again,
381
+ // and neither ever sees a reservation.
382
+ loom::model(|| {
383
+ let r = Arc::new(ExternalRegistry::default());
384
+ r.install(b"x", entry(3));
385
+ let decide = || {
386
+ let r = Arc::clone(&r);
387
+ thread::spawn(move || {
388
+ let a = r.lookup(b"x");
389
+ let b = r.lookup(b"x");
390
+ assert!(!matches!(a, Lookup::Reserved) && !matches!(b, Lookup::Reserved));
391
+ if a == Lookup::Absent {
392
+ assert_eq!(b, Lookup::Absent);
393
+ }
394
+ })
395
+ };
396
+ let (d1, d2) = (decide(), decide());
397
+ r.remove(b"x");
398
+ d1.join().unwrap();
399
+ d2.join().unwrap();
400
+ assert!(!r.any_in_doubt());
401
+ });
402
+ }
403
+
404
+ #[test]
405
+ fn loom_a_late_unreserve_never_drops_a_later_prepares_reservation() {
406
+ // perf2's S3 on #2000. Prepare A of "x" logged (its entry installed) but hasn't run
407
+ // its `unreserve` yet; meanwhile "x" is decided (removed) and prepare B reserves it.
408
+ // A's late `unreserve` must leave B's reservation, so a third prepare of "x" is still
409
+ // refused while B is in flight.
410
+ loom::model(|| {
411
+ let r = Arc::new(ExternalRegistry::default());
412
+ let a = r.reserve(b"x", 1).unwrap();
413
+ r.install(b"x", entry(1));
414
+ let late = {
415
+ let r = Arc::clone(&r);
416
+ thread::spawn(move || r.unreserve(b"x", a))
417
+ };
418
+ r.remove(b"x");
419
+ let b = r.reserve(b"x", 1);
420
+ late.join().unwrap();
421
+ if b.is_ok() {
422
+ assert_eq!(r.lookup(b"x"), Lookup::Reserved, "B's reservation stands");
423
+ assert!(matches!(r.reserve(b"x", 1), Err(Error::InvalidArgument(_))));
424
+ }
425
+ });
426
+ }
427
+
428
+ #[test]
429
+ fn loom_concurrent_prepares_never_pass_the_limit_together() {
430
+ // A limit of one xid: two prepares of different xids race, and at most one is in
431
+ // doubt or reserved at a time, so one of them is refused `Busy` unless the other
432
+ // failed and dropped its reservation first.
433
+ loom::model(|| {
434
+ let r = Arc::new(ExternalRegistry::new((1, 0)));
435
+ let spawn = |xid: &'static [u8], id| {
436
+ let r = Arc::clone(&r);
437
+ thread::spawn(move || prepare(&r, xid, id, true))
438
+ };
439
+ let (a, b) = (spawn(b"a", 1), spawn(b"b", 2));
440
+ let res = [a.join().unwrap(), b.join().unwrap()];
441
+ let logged = res.iter().filter(|r| matches!(r, Ok(true))).count();
442
+ let busy = res.iter().filter(|r| matches!(r, Err(Error::Busy))).count();
443
+ assert_eq!((logged, busy), (1, 1), "{res:?}");
444
+ assert_eq!(r.in_doubt().len(), 1);
445
+ });
446
+ }
447
+ }