Skip to content

Commit e643a18

Browse files
committed
feat: add the rebuildable record index
Answering "what are this change's heads?" or "which statements are about this revision?" would otherwise mean reading every record. The index keeps each change's revisions and heads (more than one head is divergence), statements by subject, and the order the node received its records in, in one append-only file, index/log, made of checked frames. Committing a batch appends its records' entries before publishing them, and the batch sync makes them durable together, so indexing costs no sync of its own. A mark appended afterwards, unsynced, says the batch was published; opening the index checks the records of unmarked batches against the store. Appenders cut off a frame a crash left partial, and any other damage, or a missing index, rebuilds it from the store, keeping the arrival order the old log still knows. Batches hold a shared lock that a rebuild takes exclusively, so a rebuild never misses one. DurableWrite gains sync_with, to sync a file written in place with a batch. On Linux, batches of up to two files now sync each file at once instead of with syncfs: a record and the index log would otherwise wait on every other process's writes, which stalled single writes for up to a second on a busy disk. The store rejects records that don't decode, which the index couldn't use.
1 parent 579bb2a commit e643a18

8 files changed

Lines changed: 1313 additions & 44 deletions

File tree

‎apps/origin-src/benches/store.rs‎

Lines changed: 146 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
//! Store throughput: durable writes with and without batching, verified
2-
//! reads, and target appends. Run on a real disk: syncs cost nothing on a
3-
//! RAM-backed file system.
2+
//! reads, target appends, and the record index. Run on a real disk: syncs
3+
//! cost nothing on a RAM-backed file system.
44
5+
use std::fs::File;
6+
use std::io;
7+
use std::path::Path;
58
use std::slice;
69

710
use divan::counter::{BytesCount, ItemsCount};
811
use divan::{Bencher, black_box};
9-
use origin_platform::Native;
10-
use origin_shared::{AcceptanceBody, EncodedObject, NodeKey, Record, TargetName, Tree, TreeId};
12+
use origin_platform::{
13+
CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Native, Platform, ReadAt,
14+
};
15+
use origin_shared::{
16+
AcceptanceBody, Base, ChangeId, EncodedObject, Kind, NodeKey, Record, RecordId, Revision,
17+
Statement, TargetName, Tree, TreeId, Verdict,
18+
};
19+
use origin_src::index::Index;
1120
use origin_src::store::Store;
1221

1322
fn main() {
@@ -26,8 +35,13 @@ fn content(len: usize, seed: usize) -> Vec<u8> {
2635

2736
/// An initialized store in a new temporary directory.
2837
fn store() -> (tempfile::TempDir, Store) {
38+
store_on(Native::default())
39+
}
40+
41+
/// An initialized store on `platform` in a new temporary directory.
42+
fn store_on<P: Platform>(platform: P) -> (tempfile::TempDir, Store<P>) {
2943
let dir = tempfile::tempdir().unwrap();
30-
let store = Store::new(dir.path().join(".origin"), Native::default());
44+
let store = Store::new(dir.path().join(".origin"), platform);
3145
store.init().unwrap();
3246
(dir, store)
3347
}
@@ -120,3 +134,130 @@ fn append(bencher: Bencher<'_, '_>) {
120134
store.append(&main, &acceptance).unwrap()
121135
});
122136
}
137+
138+
/// `count` records, as a busy repository receives them: a revision of one
139+
/// of a hundred changes, evolving from that change's previous one, then nine
140+
/// statements about it.
141+
fn records(count: usize) -> Vec<EncodedObject> {
142+
let snapshot = TreeId::from(Tree::default().encode().id());
143+
let mut heads = vec![None; 100];
144+
let mut revision = None;
145+
(0..count)
146+
.map(|i| {
147+
if i % 10 == 0 {
148+
let change = i / 10 % heads.len();
149+
let encoded = Revision {
150+
change: ChangeId::from_bytes([u8::try_from(change).unwrap(); 16]),
151+
predecessors: heads[change].into_iter().collect(),
152+
base: Base::Acceptance(EncodedObject::blob(b"main").id().into()),
153+
deps: Vec::new(),
154+
snapshot,
155+
description: EncodedObject::blob(&content(64, i)).id().into(),
156+
author: "user:bench".parse().unwrap(),
157+
}
158+
.encode();
159+
heads[change] = Some(encoded.id().into());
160+
revision = Some(encoded.id().into());
161+
encoded
162+
} else {
163+
Statement {
164+
subject: RecordId::Revision(revision.unwrap()),
165+
kind: Kind::new(format!("ci.check-{i}")).unwrap(),
166+
verdict: Some(Verdict::Pass),
167+
issuer: "node:ci-1".parse().unwrap(),
168+
inputs: None,
169+
payload: None,
170+
supersedes: None,
171+
}
172+
.encode()
173+
}
174+
})
175+
.collect()
176+
}
177+
178+
/// The native platform without syncs, to measure what syncs hide.
179+
#[derive(Clone, Copy, Debug, Default)]
180+
struct NoSync;
181+
182+
impl Durability for NoSync {
183+
fn sync_file(&self, _: &File) -> io::Result<()> {
184+
Ok(())
185+
}
186+
187+
fn sync_dir(&self, _: &Path) -> io::Result<()> {
188+
Ok(())
189+
}
190+
191+
fn sync_batch<'f>(&self, _: impl IntoIterator<Item = &'f Path>) -> Result<(), Error> {
192+
Ok(())
193+
}
194+
}
195+
196+
impl FileLock for NoSync {}
197+
198+
impl ReadAt for NoSync {}
199+
200+
impl CloneFile for NoSync {
201+
fn cannot_clone(&self, error: &io::Error) -> bool {
202+
Native::default().cannot_clone(error)
203+
}
204+
}
205+
206+
impl FileSystem for NoSync {
207+
fn file_system(&self, path: &Path) -> io::Result<FsKind> {
208+
Native::default().file_system(path)
209+
}
210+
}
211+
212+
/// Writing new records in one batch, which indexes them, against blobs of
213+
/// the same content, which aren't indexed: the difference is what indexing
214+
/// costs, which [`NoSync`] shows apart from the syncs. One record is what
215+
/// issuing a statement costs.
216+
#[divan::bench(
217+
types = [Native, NoSync],
218+
consts = [true, false],
219+
args = [1, 1_000, 20_000],
220+
sample_count = 10,
221+
sample_size = 1,
222+
)]
223+
fn write_records<P: Platform + Default, const INDEXED: bool>(
224+
bencher: Bencher<'_, '_>,
225+
count: usize,
226+
) {
227+
let objects: Vec<_> = records(count)
228+
.into_iter()
229+
.map(|record| {
230+
if INDEXED {
231+
record
232+
} else {
233+
EncodedObject::blob(record.bytes())
234+
}
235+
})
236+
.collect();
237+
bencher
238+
.counter(ItemsCount::new(count))
239+
.with_inputs(|| store_on(P::default()))
240+
.bench_local_refs(|(_, store)| store.write_all(&objects).unwrap());
241+
}
242+
243+
/// Opening the index of 20k records written in batches of a hundred.
244+
#[divan::bench(sample_count = 20)]
245+
fn open_index(bencher: Bencher<'_, '_>) {
246+
let (_dir, store) = store();
247+
for batch in records(20_000).chunks(100) {
248+
store.write_all(batch).unwrap();
249+
}
250+
bencher
251+
.counter(ItemsCount::new(20_000_usize))
252+
.bench(|| Index::open(&store).unwrap());
253+
}
254+
255+
/// Rebuilding the index of 20k records from the store.
256+
#[divan::bench(sample_count = 10)]
257+
fn rebuild_index(bencher: Bencher<'_, '_>) {
258+
let (_dir, store) = store();
259+
store.write_all(&records(20_000)).unwrap();
260+
bencher
261+
.counter(ItemsCount::new(20_000_usize))
262+
.bench(|| Index::rebuild(&store).unwrap());
263+
}

0 commit comments

Comments
 (0)