tinystore 0.1.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
use std::cell::Cell;
use std::collections::VecDeque;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use rusqlite::Connection;

use super::capture::{Capture, Logged, in_the_file, logged};
use super::connection::{execute, sql_error};
use super::given::own;
use super::{Committed, GroupLimits, Left, Settlers, Tx};
use crate::probe::FileProbe;
use crate::{Error, ErrorKind, Result};

pub(crate) type Work = Box<dyn FnOnce(&Tx<'_>) -> Result<()> + Send>;

/// What a submitted write calls with its answer, on the thread that commits it.
pub(crate) type Done = Box<dyn FnOnce(Result<()>) + Send>;

/// A leader gathers for at most a quarter of the last commit, counted from
/// its end, and never more than the limits' `gather`.
///
/// The callers a commit answers need tens of microseconds to wake and write
/// again, and a leader that took the queue at once left them all to the next
/// commit. 64 writers then made groups of 32 for good: the half that had
/// waited while the other half's commit ran, each half a commit, half the
/// writes a sync could carry (research rust-slice-2026-10-10). So a leader
/// waits for both halves, the writes that waited when the last commit ended
/// and the ones that commit answered.
const GATHER_SHARE: u32 = 4;

pub(crate) const BEGIN: &str = own!("begin immediate");
pub(crate) const COMMIT: &str = own!("commit");
pub(crate) const ROLLBACK: &str = own!("rollback");
const SAVEPOINT: &str = own!("savepoint grouped");
const RELEASE: &str = own!("release grouped");
const ROLLBACK_TO: &str = own!("rollback to grouped");

/// The writes waiting for a file's writer.
///
/// The first caller to find no leader commits every write queued behind it in
/// one transaction, each write in a savepoint, then hands the lead to the first
/// caller still waiting. A commit's sync is shared by the writes that arrived
/// while the last one ran, and no thread is started: callers take turns.
///
/// A submitted write has no caller waiting: it is answered through its `done`,
/// on the leader's thread, and a leader that finds one at the front of the
/// queue leads on, since nobody else would. So a host with one thread and many
/// writes in flight, an event loop, fills a commit without a thread a write.
///
/// research's design/group-commit-contract.md is the contract.
pub(crate) struct Group {
    queue: Mutex<Queue>,
    grew: Condvar,
    limits: GroupLimits,
    commits: AtomicU64,
    settlers: Arc<Settlers>,
    capture: Logged,
    probe: Option<FileProbe>,
}

#[derive(Default)]
struct Queue {
    waiting: VecDeque<Arc<Write>>,
    leading: bool,
    closed: bool,
    /// How many writes a gathering leader waits for: the write that makes
    /// them wakes it, and no other, since a wake a write would cost each
    /// caller more than its write.
    gathering: Option<usize>,
    /// The writes the next commit may expect: those that waited when the last
    /// commit ended, and the ones it answered, whose callers may be about to
    /// write again.
    expected: usize,
    last_held: Duration,
    last_ended: Option<Instant>,
}

/// One caller's write, from its queueing to its answer.
struct Write {
    bytes: usize,
    /// When it was queued, if it is measured.
    queued: Option<Instant>,
    /// Queued by a caller who waits for it, not by the store's own work.
    for_a_caller: bool,
    work: Mutex<Option<Work>>,
    /// A submitted write's answer goes here rather than to a waiting caller.
    done: Mutex<Option<Done>>,
    turn: Mutex<Turn>,
    changed: Condvar,
}

enum Turn {
    Waiting,
    Leading,
    /// Taken once, by the caller.
    Answered(Option<Answer>),
}

/// A write's answer, and the answers its caller passes on as it returns.
struct Answer {
    own: Result<()>,
    passed_on: Vec<(Arc<Write>, Result<()>)>,
}

impl Group {
    pub(crate) fn new(limits: GroupLimits, settlers: Arc<Settlers>, capture: Logged, probe: Option<FileProbe>) -> Self {
        let queue = Mutex::new(Queue::default());
        Self { queue, grew: Condvar::new(), limits, commits: AtomicU64::new(0), settlers, capture, probe }
    }

    #[cfg(test)]
    pub(crate) fn commits(&self) -> u64 {
        self.commits.load(Ordering::Relaxed)
    }

    #[cfg(test)]
    pub(crate) fn waiting(&self) -> usize {
        self.lock().waiting.len()
    }

    /// Runs `work` in a savepoint of a transaction it may share with the writes
    /// queued beside it, and returns once that transaction commits.
    ///
    /// A failed or panicking write rolls back its savepoint and fails alone. A
    /// write heavier than the group's bytes commits alone. A failed commit fails
    /// every write that ran in it with `OutcomeUnknown`.
    pub(crate) fn write(&self, writer: &Mutex<Connection>, bytes: usize, work: Work) -> Result<()> {
        let write = Arc::new(Write::new(bytes, work, self.queued()));
        let leads = self.enqueue(&write)?;
        if leads || write.wait_for_turn() {
            self.lead(writer, Some(&write));
        }
        write.take_answer()
    }

    /// Queues `work` and returns at once, `done` called with its answer once
    /// its commit ends. When no commit runs, this caller's thread commits the
    /// queue first, as long as submitted writes keep arriving at its front.
    pub(crate) fn submit(&self, writer: &Mutex<Connection>, bytes: usize, work: Work, done: Done) {
        let write = Arc::new(Write::submitted(bytes, work, done, self.queued()));
        match self.enqueue(&write) {
            Ok(true) => self.lead(writer, None),
            Ok(false) => {}
            Err(error) => write.answer(Err(error), Vec::new()),
        }
    }

    fn queued(&self) -> Option<Instant> {
        self.probe.as_ref().and_then(FileProbe::queued)
    }

    /// Refuses new writes and answers those still waiting; a commit under way
    /// finishes and answers its own.
    pub(crate) fn close(&self) {
        let waiting = {
            let mut queue = self.lock();
            queue.closed = true;
            std::mem::take(&mut queue.waiting)
        };
        for write in waiting {
            write.answer(Err(Error::closed("a grouped write")), Vec::new());
        }
        self.grew.notify_all();
    }

    /// Queues a write and says whether its caller leads.
    fn enqueue(&self, write: &Arc<Write>) -> Result<bool> {
        let mut queue = self.lock();
        if queue.closed {
            return Err(Error::closed("a grouped write"));
        }
        queue.waiting.push_back(Arc::clone(write));
        if queue.leading {
            if queue.gathering.is_some_and(|wanted| queue.waiting.len() >= wanted) {
                self.grew.notify_all();
            }
            return Ok(false);
        }
        queue.leading = true;
        Ok(true)
    }

    /// Commits batches until the write at the front has a caller of its own to
    /// lead, or the queue is empty. `own` is the write of the caller that
    /// leads, when it has one.
    fn lead(&self, writer: &Mutex<Connection>, own: Option<&Arc<Write>>) {
        loop {
            let connection = writer.lock().unwrap_or_else(PoisonError::into_inner);
            let batch = self.gather();
            let started = Instant::now();
            let waits = waits(&batch, started);
            // read while the writer is held, which a change of the file's home holds too
            let capture = logged(&self.capture);
            // A panic past the writes' own savepoints, in a settler or a hook,
            // must still reach `hand_off`, or no thread leads again.
            let committing = (&*self.settlers, capture.as_deref());
            let answers =
                catch_unwind(AssertUnwindSafe(|| commit(&connection, &batch, committing, &waits, self.probe.as_ref())))
                    .unwrap_or_else(|_| {
                        if !connection.is_autocommit() {
                            let _ = execute(&connection, ROLLBACK);
                        }
                        let panicked = Error::new(ErrorKind::OutcomeUnknown, "a grouped commit panicked");
                        batch.iter().map(|_| Err(panicked.duplicate())).collect()
                    });
            let held = started.elapsed();
            drop(connection);
            if !batch.is_empty() {
                self.commits.fetch_add(1, Ordering::Relaxed);
            }
            let leads_on = self.hand_off(batch.len(), held);
            answer_all(batch, answers, own);
            if !leads_on {
                return;
            }
        }
    }

    /// Waits a little for the writes the last commit lets it expect, then
    /// takes a batch from the front of the queue. A leader that comes long
    /// after that commit waits for nothing: its callers are not coming back
    /// together.
    fn gather(&self) -> Vec<Arc<Write>> {
        let mut queue = self.lock();
        let wanted = queue.expected.min(self.limits.writes);
        let window = (queue.last_held / GATHER_SHARE).min(self.limits.gather);
        let deadline = queue.last_ended.map_or_else(Instant::now, |ended| ended + window);
        queue.gathering = Some(wanted);
        while queue.waiting.len() < wanted && !queue.closed {
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                break;
            }
            queue = self.grew.wait_timeout(queue, left).unwrap_or_else(PoisonError::into_inner).0;
        }
        queue.gathering = None;
        self.take(&mut queue)
    }

    fn take(&self, queue: &mut Queue) -> Vec<Arc<Write>> {
        let mut batch = Vec::new();
        let mut bytes = 0usize;
        while let Some(next) = queue.waiting.front() {
            let full = batch.len() == self.limits.writes || bytes.saturating_add(next.bytes) > self.limits.bytes;
            if full && !batch.is_empty() {
                break;
            }
            bytes = bytes.saturating_add(next.bytes);
            batch.extend(queue.waiting.pop_front());
        }
        batch
    }

    /// Passes the lead to the caller of the write at the front, and says
    /// whether this thread leads on because that write was submitted.
    fn hand_off(&self, answered: usize, held: Duration) -> bool {
        let mut queue = self.lock();
        queue.expected = queue.waiting.len() + answered;
        queue.last_held = held;
        queue.last_ended = Some(Instant::now());
        match queue.waiting.front() {
            Some(next) if next.is_submitted() => true,
            Some(next) => {
                next.promote();
                false
            }
            None => {
                queue.leading = false;
                false
            }
        }
    }

    fn lock(&self) -> MutexGuard<'_, Queue> {
        self.queue.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

impl Write {
    fn new(bytes: usize, work: Work, queued: Option<Instant>) -> Self {
        let (done, turn) = (Mutex::new(None), Mutex::new(Turn::Waiting));
        let for_a_caller = !super::capture::is_own_work();
        Self { bytes, queued, for_a_caller, work: Mutex::new(Some(work)), done, turn, changed: Condvar::new() }
    }

    fn submitted(bytes: usize, work: Work, done: Done, queued: Option<Instant>) -> Self {
        Self { done: Mutex::new(Some(done)), ..Self::new(bytes, work, queued) }
    }

    fn is_submitted(&self) -> bool {
        self.done.lock().unwrap_or_else(PoisonError::into_inner).is_some()
    }

    /// Blocks until the write leads or is answered; true when it leads.
    fn wait_for_turn(&self) -> bool {
        let mut turn = self.lock_turn();
        loop {
            match *turn {
                Turn::Waiting => turn = self.changed.wait(turn).unwrap_or_else(PoisonError::into_inner),
                Turn::Leading => return true,
                Turn::Answered(_) => return false,
            }
        }
    }

    fn promote(&self) {
        let mut turn = self.lock_turn();
        if matches!(*turn, Turn::Waiting) {
            *turn = Turn::Leading;
            self.changed.notify_one();
        }
    }

    /// Answers the write, and gives its caller the answers it passes on. A
    /// submitted write has no caller to pass any on, and is given none.
    fn answer(&self, own: Result<()>, passed_on: Vec<(Arc<Write>, Result<()>)>) {
        let done = self.done.lock().unwrap_or_else(PoisonError::into_inner).take();
        if let Some(done) = done {
            return done(own);
        }
        *self.lock_turn() = Turn::Answered(Some(Answer { own, passed_on }));
        self.changed.notify_one();
    }

    fn take_work(&self) -> Option<Work> {
        self.work.lock().unwrap_or_else(PoisonError::into_inner).take()
    }

    /// The write's answer, once the answers given with it are passed on.
    fn take_answer(&self) -> Result<()> {
        let answer = match &mut *self.lock_turn() {
            Turn::Answered(answer) => answer.take(),
            _ => return Err(Error::internal("a grouped write ended without an answer")),
        };
        let Some(Answer { own, passed_on }) = answer else {
            return Err(Error::internal("a grouped write was answered twice"));
        };
        answer_in_halves(passed_on);
        own
    }

    fn lock_turn(&self) -> MutexGuard<'_, Turn> {
        self.turn.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Answers a commit's writes: a submitted one through its `done`, here, and
/// the callers that wait by waking them.
///
/// The writer does nothing a caller at a time. A wake costs tens of
/// microseconds where the processor it lands on sleeps, and a leader that
/// woke 64 callers one after another spent on it what their commit had
/// taken, so that half of them missed the next commit (research
/// rust-slice-2026-10-10). So the callers wake one another, in halves. The
/// leader's own write is given none to pass on, since its thread may lead
/// the next commit first.
fn answer_all(batch: Vec<Arc<Write>>, answers: Vec<Result<()>>, own: Option<&Arc<Write>>) {
    let mut callers = Vec::with_capacity(batch.len());
    for (write, answer) in batch.into_iter().zip(answers) {
        if write.is_submitted() || own.is_some_and(|own| Arc::ptr_eq(own, &write)) {
            write.answer(answer, Vec::new());
        } else {
            callers.push((write, answer));
        }
    }
    answer_in_halves(callers);
}

/// Answers callers with two wakes, however many they are: each half through
/// its first, whose caller answers the rest of its half the same way as it
/// returns. An answer travels with its wake, so no caller wakes to find none,
/// and the last is awake after as many wakes in a row as the callers halve
/// to one, six for 64.
fn answer_in_halves(mut callers: Vec<(Arc<Write>, Result<()>)>) {
    let second = callers.split_off(callers.len().div_ceil(2));
    for half in [callers, second] {
        let mut half = half.into_iter();
        if let Some((first, answer)) = half.next() {
            first.answer(answer, half.collect());
        }
    }
}

/// How long each measured write of a batch waited for the commit that began
/// at `started`.
fn waits(batch: &[Arc<Write>], started: Instant) -> Vec<Duration> {
    batch.iter().filter_map(|write| write.queued).map(|queued| started.saturating_duration_since(queued)).collect()
}

/// Runs a batch in one transaction, each write in a savepoint, and says how
/// each one ended. What the writes that succeeded asked to run once they
/// commit runs after the commit, in their order, the writer still held. A
/// commit that holds measured writes, whose `waits` are given, is told to the
/// probe.
fn commit(
    connection: &Connection,
    batch: &[Arc<Write>],
    (settlers, capture): (&Settlers, Option<&Capture>),
    waits: &[Duration],
    probe: Option<&FileProbe>,
) -> Vec<Result<()>> {
    if batch.is_empty() {
        return Vec::new();
    }
    if let Some(Err(refused)) = capture.map(Capture::refuse_a_write) {
        return batch.iter().map(|_| Err(refused.duplicate())).collect();
    }
    if let Err(error) = execute(connection, BEGIN) {
        let failure = sql_error("a grouped commit: its transaction", error);
        return batch.iter().map(|_| Err(failure.duplicate())).collect();
    }
    let committed = Committed::default();
    if let Err(failure) = Tx::new(connection, &committed, settlers).settle(Left::Before) {
        let _ = execute(connection, ROLLBACK);
        return batch.iter().map(|_| Err(failure.duplicate())).collect();
    }
    let undone = Cell::new(true);
    let answers: Vec<Result<()>> =
        batch.iter().map(|write| run(connection, write.take_work(), (&committed, settlers), &undone)).collect();
    // A failed write whose savepoint would not roll back is still in the
    // transaction: committing would keep it, so the whole batch goes.
    if !undone.get() {
        let _ = execute(connection, ROLLBACK);
        let failure = Error::internal("a grouped write's savepoint did not roll back; its batch rolled back");
        return batch.iter().map(|_| Err(failure.duplicate())).collect();
    }
    if let Some(capture) = capture {
        capture.arm(batch.iter().any(|write| write.for_a_caller));
    }
    let started = Instant::now();
    let finished = execute(connection, COMMIT);
    if let (Some(probe), true) = (probe, finished.is_ok()) {
        probe.committed(started.elapsed(), waits);
    }
    let Err(error) = finished else {
        let handed = capture.map_or(Ok(()), |capture| capture.committed(connection));
        if in_the_file(&handed) {
            committed.run();
        }
        let Err(handed) = handed else {
            return answers;
        };
        // the store's own writes take a commit no copy held as done, as they never waited for one
        let unheld = handed.kind() == ErrorKind::CommittedLocally;
        let answer_of = |(write, answer): (&Arc<Write>, Result<()>)| match answer {
            Ok(()) if unheld && !write.for_a_caller => Ok(()),
            answer => answer.and_then(|()| Err(handed.duplicate())),
        };
        return batch.iter().zip(answers).map(answer_of).collect();
    };
    if !connection.is_autocommit() {
        // The commit failed and left the transaction open: nothing of it stays.
        let _ = execute(connection, ROLLBACK);
    }
    let failure = sql_error("a grouped commit", error);
    let unknown = || Error::new(ErrorKind::OutcomeUnknown, "a grouped commit").with_source(failure.duplicate());
    answers.into_iter().map(|answer| answer.and_then(|()| Err(unknown()))).collect()
}

/// Runs one write in a savepoint, then settles what it left, keeping the
/// savepoint when both succeed and rolling it back when either fails or
/// panics, its hooks with it.
fn run(
    connection: &Connection,
    work: Option<Work>,
    (committed, settlers): (&Committed, &Settlers),
    undone: &Cell<bool>,
) -> Result<()> {
    let Some(work) = work else {
        return Err(Error::internal("a grouped write ran twice"));
    };
    execute(connection, SAVEPOINT).map_err(|error| sql_error("a grouped write: its savepoint", error))?;
    let mark = committed.mark();
    let tx = Tx::new(connection, committed, settlers);
    let outcome = catch_unwind(AssertUnwindSafe(|| work(&tx).and_then(|()| tx.settle(Left::Here))))
        .unwrap_or_else(|_| Err(Error::internal("a grouped write panicked")));
    if outcome.is_ok() {
        if let Err(error) = execute(connection, RELEASE) {
            undone.set(undone.get() && undo(connection));
            committed.take_back(mark);
            return Err(sql_error("a grouped write: its savepoint", error));
        }
        return Ok(());
    }
    undone.set(undone.get() && undo(connection));
    committed.take_back(mark);
    outcome
}

/// Rolls a write's savepoint back; says whether it did.
fn undo(connection: &Connection) -> bool {
    execute(connection, ROLLBACK_TO).and_then(|()| execute(connection, RELEASE)).is_ok()
}