Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 13.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Merging indexes, so that a store with many sealed segments needs few
5//! index reads.
6//!
7//! Sealing gives each segment an index of its own. Once a writer has sealed
8//! enough that `merge_threshold` segment indexes are there, its next sync,
9//! or the end of its next transaction, merges them into a merged index,
10//! `seg/<name>.midx`, under an exclusive, non-blocking lock on
11//! `seg/merge.lock`, so that one process merges at a time while the others
12//! go on. A merge:
13//!
14//! 1. lists the directory, and reads the heads of the merged indexes;
15//! 2. takes every segment index that no merged index covers, then the
16//! merged indexes that hold at most twice as many entries as it took so
17//! far, smallest first, so that every merged index left holds more than
18//! twice what the new one does: an entry is written again a number of
19//! times that grows with the logarithm of the store's size, not with it;
20//! 3. reads them whole, checking every entry; an index found damaged is
21//! made again from its segments' records;
22//! 4. writes the merged index, one copy of each object, the best ranked and
23//! the first of equals, through a temporary file, a flush and a rename,
24//! then flushes the directory;
25//! 5. removes the journals that sealers which died left next to the
26//! indexes it took, flushes the directory, and only then removes the
27//! indexes it took, with any that an earlier merge cut short left behind.
28//!
29//! A segment with a journal and no index of its own is open, and writers
30//! take it over; merging removes a segment's journal before its index, and
31//! makes the first durable before the second, so that a merged segment
32//! never looks open, not even after a power loss.
33//!
34//! A merge cut short at any point leaves a store that reads the same: until
35//! the new index is in place the old ones serve, and afterwards an index
36//! left behind covers segments that the new one covers too. Readers prefer
37//! the index that covers more, and the next merge removes the rest.
38
39use std::collections::{BTreeMap, HashMap};
40use std::fs::{self, File, OpenOptions, TryLockError};
41use std::io;
42use std::sync::atomic::Ordering;
43
44use super::sources::Source;
45use super::{INDEX_STORAGE, Listing, Segments, list, segment_path};
46use crate::error::{Error, io_error};
47use crate::fsutil::{publish_file, random_name, remove_stale_temps, sync_dir};
48use crate::index::{self, Covered, IndexError, MAX_COVERED, Numbered};
49use crate::journal::{ENTRY_LEN, Entry};
50use crate::{record, scan};
51
52/// The lock a merge holds, in `seg/`.
53const LOCK: &str = "merge.lock";
54
55/// An index a merge can take.
56#[derive(Debug)]
57struct Input {
58 /// Its file name in `seg/`.
59 file: String,
60 /// The segment it is the index of, or `None` for a merged index.
61 own: Option<String>,
62 /// The segments it covers, as far as known before reading it.
63 covered: Vec<String>,
64 /// How many entries it holds, about.
65 entries: u64,
66}
67
68impl Segments {
69 /// Merges indexes if sealing left enough of them since this handle last
70 /// did. Returns whether it merged.
71 pub fn merge_if_due(&self) -> Result<bool, Error> {
72 if !self.merge_due.swap(false, Ordering::AcqRel) {
73 return Ok(false);
74 }
75 self.merge(false)
76 }
77
78 /// Merges segment indexes into a merged index once at least
79 /// `merge_threshold` of them are there, or, with `all`, every index
80 /// into one. Returns whether it merged; `false` too when another process
81 /// is merging. See the module documentation.
82 pub fn merge(&self, all: bool) -> Result<bool, Error> {
83 let lock_path = self.dir.join(LOCK);
84 let lock = OpenOptions::new()
85 .write(true)
86 .create(true)
87 .truncate(false)
88 .open(&lock_path)
89 .map_err(io_error("create", &lock_path))?;
90 match lock.try_lock() {
91 Ok(()) => {}
92 Err(TryLockError::WouldBlock) => return Ok(false),
93 Err(TryLockError::Error(err)) => return Err(io_error("lock", &lock_path)(err)),
94 }
95 let listing = list(&self.dir)?;
96 let (inputs, leftovers) = self.inputs(&listing)?;
97 let own = inputs.iter().filter(|input| input.own.is_some()).count();
98 let threshold = self.merge_threshold.max(2);
99 let taken = if all {
100 take_all(inputs)
101 } else if own >= threshold {
102 take(inputs)
103 } else {
104 Vec::new()
105 };
106 let merged = taken.len() >= 2;
107 let mut covered = Vec::new();
108 if merged {
109 self.need_storage(INDEX_STORAGE)?;
110 let entries;
111 (covered, entries) = self.read_inputs(&taken)?;
112 remove_stale_temps(&self.dir);
113 publish_file(
114 &self.dir,
115 &format!("{}.midx", random_name(&self.dir)?),
116 &index::encode(&covered, &entries),
117 self.durability,
118 &[],
119 )?;
120 #[cfg(test)]
121 failpoints::check("published")?;
122 }
123 // Journals first, durably: a segment with a journal and no index of
124 // its own is open.
125 let gone: Vec<&Input> = taken.iter().filter(|_| merged).chain(&leftovers).collect();
126 let mut removed = false;
127 let segments = covered
128 .iter()
129 .map(|segment| segment.name.as_str())
130 .chain(gone.iter().filter_map(|input| input.own.as_deref()));
131 for name in segments {
132 removed |= remove(&self.path(name, "jrn"))?;
133 }
134 if removed {
135 sync_dir(&self.dir, self.durability)?;
136 }
137 #[cfg(test)]
138 failpoints::check("journals removed")?;
139 for input in &gone {
140 remove(&self.dir.join(&input.file))?;
141 }
142 drop(lock);
143 if !gone.is_empty() {
144 self.rescan()?;
145 }
146 Ok(merged)
147 }
148
149 /// The indexes a merge can take, and those an earlier merge left
150 /// behind: segment indexes that a merged index covers, and merged
151 /// indexes whose segments a larger one covers.
152 fn inputs(&self, listing: &Listing) -> Result<(Vec<Input>, Vec<Input>), Error> {
153 let mut merged = Vec::new();
154 for name in &listing.merged {
155 let file = format!("{name}.midx");
156 // One that cannot be read is left alone: lookups scan its
157 // segments, and fsck reports it.
158 if let Some(Ok(source)) = Source::open_merged(&self.dir, &file)? {
159 let covered: Vec<String> = source.covered.iter().map(|(n, _)| n.clone()).collect();
160 let entries = file_len(&self.dir.join(&file))? / ENTRY_LEN;
161 let key = (covered.len(), file.clone());
162 merged.push((
163 key,
164 Input {
165 file,
166 own: None,
167 covered,
168 entries,
169 },
170 ));
171 }
172 }
173 // Each segment goes to the best merged index that covers it.
174 let mut best: HashMap<&str, usize> = HashMap::new();
175 for (at, (key, input)) in merged.iter().enumerate() {
176 for segment in &input.covered {
177 let better = best
178 .get(segment.as_str())
179 .is_none_or(|&other| merged[other].0 < *key);
180 if better {
181 best.insert(segment.as_str(), at);
182 }
183 }
184 }
185 let mut leftovers = Vec::new();
186 let mut keep = vec![false; merged.len()];
187 for &at in best.values() {
188 keep[at] = true;
189 }
190 let mut inputs = Vec::new();
191 for (name, files) in &listing.segments {
192 if !files.idx || !files.seg {
193 continue;
194 }
195 let file = format!("{name}.idx");
196 let entries = file_len(&self.dir.join(&file))? / ENTRY_LEN;
197 let input = Input {
198 file,
199 own: Some(name.clone()),
200 covered: vec![name.clone()],
201 entries,
202 };
203 if best.contains_key(name.as_str()) {
204 leftovers.push(input);
205 } else {
206 inputs.push(input);
207 }
208 }
209 for ((_, input), keep) in merged.into_iter().zip(keep) {
210 if keep {
211 inputs.push(input);
212 } else {
213 leftovers.push(input);
214 }
215 }
216 Ok((inputs, leftovers))
217 }
218
219 /// Reads the indexes a merge takes, and returns the segments they cover
220 /// and their entries, one copy of each object.
221 fn read_inputs(&self, taken: &[Input]) -> Result<(Vec<Covered>, Vec<Numbered>), Error> {
222 let mut covered: BTreeMap<String, u64> = BTreeMap::new();
223 let mut entries: Vec<(Entry, String, usize)> = Vec::new();
224 for input in taken {
225 let path = self.dir.join(&input.file);
226 let bytes = fs::read(&path).map_err(io_error("read", &path))?;
227 match index::decode(&bytes, input.own.as_deref()) {
228 Ok(decoded) => {
229 for (entry, segment) in decoded.entries {
230 let name = decoded.covered[usize::from(segment)].name.clone();
231 entries.push((entry, name, entries.len()));
232 }
233 for segment in decoded.covered {
234 covered.insert(segment.name, segment.len);
235 }
236 }
237 Err(IndexError::Newer(detail)) => {
238 return Err(Error::NewerStore {
239 path,
240 detail: format!("it holds {detail}"),
241 });
242 }
243 // Damaged: the records describe themselves.
244 Err(IndexError::Damaged(_)) => {
245 for name in &input.covered {
246 let len = self.scan_into(name, &mut entries)?;
247 covered.insert(name.clone(), len);
248 }
249 }
250 }
251 }
252 let numbers: HashMap<&str, u16> = covered
253 .keys()
254 .enumerate()
255 .map(|(number, name)| (name.as_str(), number as u16))
256 .collect();
257 entries.sort_by(|(a, _, a_order), (b, _, b_order)| {
258 (a.id, record::rank(a.codec), a_order).cmp(&(b.id, record::rank(b.codec), b_order))
259 });
260 entries.dedup_by_key(|(entry, _, _)| entry.id);
261 let entries = entries
262 .iter()
263 .map(|(entry, name, _)| (*entry, numbers[name.as_str()]))
264 .collect();
265 let covered = covered
266 .into_iter()
267 .map(|(name, len)| Covered { name, len })
268 .collect();
269 Ok((covered, entries))
270 }
271
272 /// Adds the entries of a segment's records, found by scanning it, and
273 /// returns its length.
274 fn scan_into(
275 &self,
276 name: &str,
277 entries: &mut Vec<(Entry, String, usize)>,
278 ) -> Result<u64, Error> {
279 let path = segment_path(&self.dir, name, "seg");
280 let file = File::open(&path).map_err(io_error("open", &path))?;
281 let len = file.metadata().map_err(io_error("read", &path))?.len();
282 scan::scan(&file, len, |offset, found| {
283 let entry = Entry::new(offset, &found.header, found.crc);
284 entries.push((entry, name.to_owned(), entries.len()));
285 })
286 .map_err(io_error("read", &path))?;
287 Ok(len)
288 }
289}
290
291/// What a merge takes when enough segment indexes are there: all of them,
292/// then the merged indexes no larger than twice what it took so far,
293/// smallest first, as long as the segments they cover fit in one index.
294fn take(inputs: Vec<Input>) -> Vec<Input> {
295 let (own, mut merged): (Vec<Input>, Vec<Input>) =
296 inputs.into_iter().partition(|input| input.own.is_some());
297 let mut taken: Vec<Input> = own.into_iter().take(MAX_COVERED).collect();
298 let mut entries: u64 = taken.iter().map(|input| input.entries).sum();
299 let mut segments = taken.len();
300 merged.sort_by_key(|input| input.entries);
301 for input in merged {
302 if input.entries > entries.saturating_mul(2) || segments + input.covered.len() > MAX_COVERED
303 {
304 break;
305 }
306 entries += input.entries;
307 segments += input.covered.len();
308 taken.push(input);
309 }
310 taken
311}
312
313/// Every index, as far as the segments fit in one.
314fn take_all(inputs: Vec<Input>) -> Vec<Input> {
315 let mut segments = 0;
316 let mut taken = Vec::new();
317 for input in inputs {
318 if segments + input.covered.len() > MAX_COVERED {
319 break;
320 }
321 segments += input.covered.len();
322 taken.push(input);
323 }
324 taken
325}
326
327fn file_len(path: &std::path::Path) -> Result<u64, Error> {
328 Ok(fs::metadata(path).map_err(io_error("read", path))?.len())
329}
330
331/// Removes a file, and says whether it was there.
332fn remove(path: &std::path::Path) -> Result<bool, Error> {
333 match fs::remove_file(path) {
334 Ok(()) => Ok(true),
335 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false),
336 Err(err) => Err(io_error("remove", path)(err)),
337 }
338}
339
340/// Points where a test can cut a merge short, as a crash would.
341#[cfg(test)]
342pub(crate) mod failpoints {
343 use std::cell::RefCell;
344 use std::io;
345
346 use crate::error::Error;
347
348 thread_local! {
349 static ARMED: RefCell<Option<&'static str>> = const { RefCell::new(None) };
350 }
351
352 /// Makes merges on this thread stop at `point`, until disarmed.
353 pub(crate) fn arm(point: Option<&'static str>) {
354 ARMED.with(|armed| *armed.borrow_mut() = point);
355 }
356
357 pub(super) fn check(point: &'static str) -> Result<(), Error> {
358 if ARMED.with(|armed| *armed.borrow() == Some(point)) {
359 return Err(Error::Io {
360 action: "continue past",
361 path: point.into(),
362 source: io::Error::other("a test cut the merge short here"),
363 });
364 }
365 Ok(())
366 }
367}