Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-store/src/shared.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-store / src / shared.rs` 531 lines ยท 20340 bytes Raw Blame History 1 //! Group commit for concurrent submitters (leader and followers). 2 //! 3 //! Each submitter runs the stateless half of an ingest ([`SynapseStore::prepare_ingest`]: 4 //! signature check, blob digests, WAL v2 payload encoding with its SHA-256 and CRC-32C) 5 //! on its own thread with no lock held, then joins a bounded queue. Whoever finds no 6 //! active leader becomes the leader: it takes up to `max_batch_records` queued 7 //! submissions, checks them against committed state in queue order (so the outcome is 8 //! the same as committing them one after another), writes the accepted ones as one WAL v2 9 //! batch with one `fdatasync`, applies them, and only then fills every waiter's result. 10 //! A waiter is acknowledged only after the batch holding its record is durable, and the 11 //! WAL sequence order equals queue order equals acknowledgment order. 12 //! 13 //! Readers keep reading committed state while a batch is being written: the store's 14 //! read lock is not held during the write and sync. 15 16 use super::*; 17 use std::collections::VecDeque; 18 use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; 19 use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; 20 use std::time::{Duration, Instant}; 21 22 /// Counters for batches committed through a [`SharedStore`]. 23 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] 24 pub struct GroupCommitStats { 25 /// Batches made durable. 26 pub batches: u64, 27 /// Records in those batches. 28 pub records: u64, 29 /// Largest batch seen. 30 pub max_batch_records: u64, 31 /// Batches whose write or sync failed (every waiter in them got an error). 32 pub failed_batches: u64, 33 } 34 35 type Slot = Arc>>>; 36 37 struct Pending { 38 prepared: PreparedIngest, 39 slot: Slot, 40 } 41 42 #[derive(Default)] 43 struct Queue { 44 items: VecDeque, 45 leader_active: bool, 46 shutdown: bool, 47 } 48 49 /// A [`SynapseStore`] shared between threads, with group commit for ingests. 50 /// 51 /// With `FsyncPolicy::GroupCommit` concurrent [`SharedStore::submit`] calls are batched. 52 /// With the legacy policies submissions are committed one at a time in queue order, 53 /// exactly as `SynapseStore::ingest_changeset` would (one record, one sync). 54 pub struct SharedStore { 55 state: RwLock, 56 /// Held by whoever writes the WAL (batch leaders and exclusive operations). 57 commit_gate: Mutex<()>, 58 queue: Mutex, 59 queue_cv: Condvar, 60 v2: bool, 61 /// Record codec the store wrote with when last seen (frame flags byte). Submitters 62 /// encode with it; a commit re-encodes a record if the codec changed meanwhile. 63 codec_hint: AtomicU8, 64 max_batch: usize, 65 max_delay: Duration, 66 max_queue: usize, 67 limits: StoreLimits, 68 stats: Mutex, 69 /// Set when a leader panicked mid-batch: every later write is refused. 70 broken: AtomicBool, 71 /// WAL sequence of every acknowledgment, in the order the results were released. 72 #[cfg(test)] 73 ack_log: Mutex>, 74 } 75 76 fn lock(m: &Mutex) -> MutexGuard<'_, T> { 77 m.lock().unwrap_or_else(|e| e.into_inner()) 78 } 79 80 fn refusal(code: RefusalCode, msg: impl Into) -> SynapseError { 81 SynapseError::new(code, msg) 82 } 83 84 /// Fills a batch's unfilled slots and releases leadership if the leader unwinds. 85 struct LeaderGuard<'a> { 86 shared: &'a SharedStore, 87 slots: Vec, 88 armed: bool, 89 } 90 91 impl Drop for LeaderGuard<'_> { 92 fn drop(&mut self) { 93 if !self.armed { 94 return; 95 } 96 self.shared.broken.store(true, Ordering::SeqCst); 97 for s in &self.slots { 98 let mut g = lock(s); 99 if g.is_none() { 100 *g = Some(Err(refusal( 101 RefusalCode::IoFailure, 102 "group commit leader failed mid-batch; the outcome is unknown (the batch may be durable): reopen, then retry with the same idempotency key", 103 ))); 104 } 105 } 106 let mut q = lock(&self.shared.queue); 107 q.leader_active = false; 108 self.shared.queue_cv.notify_all(); 109 } 110 } 111 112 impl SharedStore { 113 /// Share an opened store. 114 pub fn new(store: SynapseStore) -> Self { 115 let (max_batch, max_delay) = match store.fsync_policy() { 116 FsyncPolicy::GroupCommit { 117 max_batch_records, 118 max_batch_delay_us, 119 } => ( 120 max_batch_records.max(1) as usize, 121 Duration::from_micros(u64::from(max_batch_delay_us)), 122 ), 123 _ => (1, Duration::ZERO), 124 }; 125 Self { 126 v2: store.is_wal_v2(), 127 codec_hint: AtomicU8::new(store.record_codec().frame_flags()), 128 max_batch, 129 max_delay, 130 max_queue: store.limits().max_inflight_admissions.max(1), 131 limits: store.limits().clone(), 132 state: RwLock::new(store), 133 commit_gate: Mutex::new(()), 134 queue: Mutex::new(Queue::default()), 135 queue_cv: Condvar::new(), 136 stats: Mutex::new(GroupCommitStats::default()), 137 broken: AtomicBool::new(false), 138 #[cfg(test)] 139 ack_log: Mutex::new(Vec::new()), 140 } 141 } 142 143 /// Open a store and share it. 144 pub fn open( 145 root_dir: impl AsRef, 146 fsync_policy: FsyncPolicy, 147 recovery_policy: RecoveryPolicy, 148 limits: StoreLimits, 149 ) -> SynapseResult { 150 SynapseStore::open(root_dir, fsync_policy, recovery_policy, limits).map(Self::new) 151 } 152 153 /// Open a store on a raw block device ([`SynapseStore::open_block_device`]). 154 pub fn open_block_device( 155 cfg: &crate::BlockDeviceConfig, 156 fsync_policy: FsyncPolicy, 157 recovery_policy: RecoveryPolicy, 158 limits: StoreLimits, 159 ) -> SynapseResult { 160 SynapseStore::open_block_device(cfg, fsync_policy, recovery_policy, limits).map(Self::new) 161 } 162 163 /// Read committed state. Not blocked by a batch write in progress. 164 pub fn read(&self) -> RwLockReadGuard<'_, SynapseStore> { 165 self.state.read().unwrap_or_else(|e| e.into_inner()) 166 } 167 168 fn write_state(&self) -> RwLockWriteGuard<'_, SynapseStore> { 169 self.state.write().unwrap_or_else(|e| e.into_inner()) 170 } 171 172 /// Run `f` with exclusive access, after any batch in progress has finished. 173 pub fn with_exclusive(&self, f: impl FnOnce(&mut SynapseStore) -> R) -> R { 174 let _gate = lock(&self.commit_gate); 175 let mut st = self.write_state(); 176 let r = f(&mut st); 177 self.codec_hint 178 .store(st.record_codec().frame_flags(), Ordering::Relaxed); 179 r 180 } 181 182 /// Exclusive access without locking (the borrow checker proves no one else has it). 183 pub fn get_mut(&mut self) -> &mut SynapseStore { 184 self.state.get_mut().unwrap_or_else(|e| e.into_inner()) 185 } 186 187 /// Unwrap the store. 188 pub fn into_inner(self) -> SynapseStore { 189 self.state.into_inner().unwrap_or_else(|e| e.into_inner()) 190 } 191 192 /// Group commit counters so far. 193 pub fn stats(&self) -> GroupCommitStats { 194 *lock(&self.stats) 195 } 196 197 /// WAL sequence of every group-commit acknowledgment, in release order (tests only). 198 #[cfg(test)] 199 pub(crate) fn ack_log(&self) -> Vec { 200 lock(&self.ack_log).clone() 201 } 202 203 /// Refuse new submissions, let every queued one finish (commit or refusal), then 204 /// return. Submissions after this call get `BackpressureOverCapacity`. 205 pub fn shutdown(&self) { 206 let mut q = lock(&self.queue); 207 q.shutdown = true; 208 self.queue_cv.notify_all(); 209 while q.leader_active || !q.items.is_empty() { 210 if !q.leader_active { 211 // Queued work with no leader (its submitters will lead it; wake them). 212 self.queue_cv.notify_all(); 213 } 214 q = self 215 .queue_cv 216 .wait_timeout(q, Duration::from_millis(10)) 217 .unwrap_or_else(|e| e.into_inner()) 218 .0; 219 } 220 } 221 222 fn admission_refusal(&self, q: &Queue) -> Option { 223 if self.broken.load(Ordering::SeqCst) { 224 return Some(refusal( 225 RefusalCode::IoFailure, 226 "group commit leader failed mid-batch; the store refuses writes until reopened", 227 )); 228 } 229 if q.shutdown { 230 return Some(refusal( 231 RefusalCode::BackpressureOverCapacity, 232 "store is shutting down and admits no new submissions", 233 )); 234 } 235 if q.items.len() >= self.max_queue { 236 return Some(refusal( 237 RefusalCode::BackpressureOverCapacity, 238 format!( 239 "admission queue at capacity ({}/{})", 240 q.items.len(), 241 self.max_queue 242 ), 243 )); 244 } 245 None 246 } 247 248 /// Submit a changeset. Returns after the record is durable (or refused). Safe to call 249 /// from many threads at once; concurrent calls share one WAL sync per batch. 250 /// 251 /// A refusal is not proof that nothing was committed. When the batch rollback fails 252 /// (the store is then poisoned) or the leader dies after its write, the caller gets 253 /// `IoFailure` although the batch may already be durable. Clients must reopen and 254 /// retry with the same idempotency key; the retry returns `IdempotentDuplicate` if the 255 /// first attempt did land, and commits exactly once otherwise. 256 pub fn submit( 257 &self, 258 envelope: ChangesetEnvelope, 259 blobs: &[(BlobDigest, Vec)], 260 ) -> SynapseResult { 261 // 1. Backpressure (queue bound, shutdown, and the store's simulated in-flight count). 262 if let Some(e) = self.admission_refusal(&lock(&self.queue)) { 263 return Err(e); 264 } 265 { 266 let st = self.read(); 267 if st.inflight_admissions >= st.limits.max_inflight_admissions { 268 return Err(refusal( 269 RefusalCode::BackpressureOverCapacity, 270 format!( 271 "admission queue at capacity ({}/{})", 272 st.inflight_admissions, st.limits.max_inflight_admissions 273 ), 274 )); 275 } 276 } 277 // 2. Stateless half, in parallel on the caller's thread. 278 let codec = RecordCodec::from_frame_flags(self.codec_hint.load(Ordering::Relaxed)) 279 .unwrap_or(RecordCodec::BinaryV2); 280 let prepared = 281 SynapseStore::prepare_ingest(&self.limits, envelope, blobs, self.v2.then_some(codec))?; 282 283 let slot: Slot = Arc::new(Mutex::new(None)); 284 let mut q = lock(&self.queue); 285 if let Some(e) = self.admission_refusal(&q) { 286 return Err(e); 287 } 288 q.items.push_back(Pending { 289 prepared, 290 slot: Arc::clone(&slot), 291 }); 292 if !self.max_delay.is_zero() { 293 // A lingering leader waits for the batch to fill. 294 self.queue_cv.notify_all(); 295 } 296 loop { 297 if let Some(result) = lock(&slot).take() { 298 return result; 299 } 300 if !q.leader_active { 301 q.leader_active = true; 302 q = self.lead(q, &slot); 303 continue; 304 } 305 q = self.queue_cv.wait(q).unwrap_or_else(|e| e.into_inner()); 306 } 307 } 308 309 /// Commit batches until `my_slot` is filled or the queue is empty. Called and returns 310 /// with the queue lock held; leadership is released on return. 311 fn lead<'a>(&'a self, mut q: MutexGuard<'a, Queue>, my_slot: &Slot) -> MutexGuard<'a, Queue> { 312 loop { 313 if !self.max_delay.is_zero() && q.items.len() < self.max_batch && !q.shutdown { 314 let deadline = Instant::now() + self.max_delay; 315 while q.items.len() < self.max_batch && !q.shutdown { 316 let now = Instant::now(); 317 if now >= deadline { 318 break; 319 } 320 q = self 321 .queue_cv 322 .wait_timeout(q, deadline - now) 323 .unwrap_or_else(|e| e.into_inner()) 324 .0; 325 } 326 } 327 let n = q.items.len().min(self.max_batch); 328 let batch: Vec = q.items.drain(..n).collect(); 329 drop(q); 330 if !batch.is_empty() { 331 let mut guard = LeaderGuard { 332 shared: self, 333 slots: batch.iter().map(|p| Arc::clone(&p.slot)).collect(), 334 armed: true, 335 }; 336 self.commit_batch(batch); 337 guard.armed = false; 338 } 339 q = lock(&self.queue); 340 if lock(my_slot).is_some() || q.items.is_empty() { 341 q.leader_active = false; 342 self.queue_cv.notify_all(); 343 return q; 344 } 345 // Followers whose results are ready can return while this leader goes on. 346 self.queue_cv.notify_all(); 347 } 348 } 349 350 fn commit_batch(&self, mut batch: Vec) { 351 let _gate = lock(&self.commit_gate); 352 if !self.v2 { 353 // Legacy policies: one record and one sync at a time, in queue order. 354 let mut st = self.write_state(); 355 for p in batch { 356 let r = st.ingest_prepared(p.prepared); 357 *lock(&p.slot) = Some(r); 358 } 359 return; 360 } 361 362 let mut st = self.write_state(); 363 if let Err(e) = st.check_writable() { 364 drop(st); 365 for p in &batch { 366 *lock(&p.slot) = Some(Err(e.clone())); 367 } 368 return; 369 } 370 371 // Stateful checks in queue order against committed state plus the records 372 // accepted earlier in this batch (same outcome as committing one by one). 373 let mut overlay = BatchOverlay::default(); 374 let mut planned = Vec::with_capacity(batch.len()); 375 let mut accepted = Vec::new(); 376 let mut seq = st.committed_seq; 377 self.codec_hint 378 .store(st.record_codec().frame_flags(), Ordering::Relaxed); 379 for (i, p) in batch.iter_mut().enumerate() { 380 let mut pl = st.plan_ingest(&p.prepared, &overlay); 381 if matches!(pl, Planned::Accept) { 382 if let Err(error) = st.conform_v2(&mut p.prepared, &mut overlay) { 383 pl = Planned::Refused { 384 error, 385 depends_on_batch: false, 386 }; 387 } else { 388 seq = seq.next(); 389 let env = &p.prepared.envelope; 390 overlay.idempotency.insert( 391 (env.repo_id.clone(), env.idempotency_key), 392 (seq, p.prepared.changeset_id), 393 ); 394 overlay 395 .changesets 396 .insert(p.prepared.changeset_id, env.repo_id.clone()); 397 for m in &env.mutations { 398 if let MutationOp::Upsert { blob_digest, .. } = &m.op { 399 overlay.blobs.insert(*blob_digest); 400 } 401 } 402 accepted.push(i); 403 } 404 } 405 planned.push(pl); 406 } 407 408 // Outcomes that do not depend on this batch are final now. 409 for (p, pl) in batch.iter().zip(&planned) { 410 let r = match pl { 411 Planned::Duplicate { 412 wal_seq, 413 changeset_id, 414 depends_on_batch: false, 415 } => Ok(IngestOutcome::IdempotentDuplicate { 416 wal_seq: *wal_seq, 417 changeset_id: *changeset_id, 418 }), 419 Planned::Refused { 420 error, 421 depends_on_batch: false, 422 } => Err(error.clone()), 423 _ => continue, 424 }; 425 *lock(&p.slot) = Some(r); 426 } 427 if accepted.is_empty() { 428 return; 429 } 430 431 let mut ticket = match st.v2_begin() { 432 Ok(t) => t, 433 Err(e) => { 434 drop(st); 435 self.fail_dependent(&batch, &planned, &e); 436 return; 437 } 438 }; 439 drop(st); 440 441 // One write and one fdatasync for the whole batch, with no store lock held. 442 let result = { 443 let encoded: Vec<&wal2::EncodedRecord> = accepted 444 .iter() 445 .map(|&i| batch[i].prepared.encoded.as_ref().expect("checked above")) 446 .collect(); 447 SynapseStore::v2_write(&mut ticket, &encoded) 448 }; 449 450 let mut st = self.write_state(); 451 match st.v2_finish(ticket, result) { 452 Ok(placed) => { 453 let mut outcomes = Vec::with_capacity(accepted.len()); 454 for (k, &i) in accepted.iter().enumerate() { 455 let p = &batch[i].prepared; 456 let enc = p.encoded.as_ref().expect("checked above"); 457 st.apply_v2_ingest(&placed[k], p.record(), enc); 458 outcomes.push(IngestOutcome::Committed { 459 wal_seq: placed[k].seq, 460 changeset_id: p.changeset_id, 461 frame_sha256: placed[k].frame_sha256, 462 durability: DurabilityGuarantee::FsyncBeforeAck, 463 }); 464 } 465 drop(st); 466 { 467 let mut s = lock(&self.stats); 468 s.batches += 1; 469 s.records += accepted.len() as u64; 470 s.max_batch_records = s.max_batch_records.max(accepted.len() as u64); 471 } 472 for (&i, outcome) in accepted.iter().zip(outcomes) { 473 #[cfg(test)] 474 if let IngestOutcome::Committed { wal_seq, .. } = &outcome { 475 lock(&self.ack_log).push(*wal_seq); 476 } 477 *lock(&batch[i].slot) = Some(Ok(outcome)); 478 } 479 for (p, pl) in batch.iter().zip(&planned) { 480 let r = match pl { 481 Planned::Duplicate { 482 wal_seq, 483 changeset_id, 484 depends_on_batch: true, 485 } => Ok(IngestOutcome::IdempotentDuplicate { 486 wal_seq: *wal_seq, 487 changeset_id: *changeset_id, 488 }), 489 Planned::Refused { 490 error, 491 depends_on_batch: true, 492 } => Err(error.clone()), 493 _ => continue, 494 }; 495 *lock(&p.slot) = Some(r); 496 } 497 } 498 Err(e) => { 499 drop(st); 500 lock(&self.stats).failed_batches += 1; 501 self.fail_dependent(&batch, &planned, &e); 502 } 503 } 504 } 505 506 /// The batch write failed: every accepted record gets `e`, and every outcome that 507 /// relied on a record of this batch gets a retryable `IoFailure` (its basis is gone). 508 fn fail_dependent(&self, batch: &[Pending], planned: &[Planned], e: &SynapseError) { 509 for (p, pl) in batch.iter().zip(planned) { 510 let r = match pl { 511 Planned::Accept => e.clone(), 512 Planned::Duplicate { 513 depends_on_batch: true, 514 .. 515 } 516 | Planned::Refused { 517 depends_on_batch: true, 518 .. 519 } => refusal( 520 RefusalCode::IoFailure, 521 format!( 522 "an earlier record in the same batch was not committed ({}); retry", 523 e.message 524 ), 525 ), 526 _ => continue, 527 }; 528 *lock(&p.slot) = Some(Err(r)); 529 } 530 } 531 }