~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

A log's age is read from its files: the first write after 2 W compacts

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:store/settled
crates/pds-server/src/store.rs+7−3
@@ -478,7 +478,10 @@ pub(crate) fn hold(dir: &Path) -> Result<std::fs::File, String> {
}
/// When an account's log is compacted: past its checkpoint's size or
/// `log_floor`, or once its generation began more than twice the window ago.
/// `log_floor`, or once its generation began more than twice the window ago,
/// as its files tell (`pds_store::Policy::max_age`): so the first write
/// after `2 W` of quiet compacts it, though the server was started again, or
/// the store let go and loaded again, meanwhile (`spec/STORE.md`, "Settled").
pub(crate) fn policy(c: &Config) -> Policy {
Policy {
floor: c.log_floor,
@@ -487,8 +490,9 @@ pub(crate) fn policy(c: &Config) -> Policy {
}
}
/// When the service log is compacted: as an account's, but that it grows
/// to no more than `SERVICE_CAP`, however large its checkpoint.
/// When the service log is compacted: as an account's, by age too across a
/// start, but that it grows to no more than `SERVICE_CAP`, however large its
/// checkpoint.
pub(crate) fn service_policy(c: &Config) -> Policy {
Policy {
cap: Some(SERVICE_CAP),
crates/pds-store/src/generations.rs+108−7
@@ -25,6 +25,13 @@
//! standard error, deletes the `.tmp` and leaves the logs as they are, for the
//! next to fold them all, and none is made due for 10 seconds after.
//!
//! A generation's **age**, for compacting by age (`Policy::max_age`), runs
//! from when its log was made, as its files tell when the log is opened
//! (`began`), not from the open: a log older than its policy's age when it
//! is opened, as after a start or a log let go and opened again, is
//! compacted on its first append, as it would have been had this process
//! held it all along. A start reads no file for it but the logs it opens.
//!
//! A sealed log holds no room, which goes before its seal is written. One
//! whose room could not be given back has zeros after its seal: it is
//! sealed and whole all the same, to a start, which cuts them off, and to
@@ -205,7 +212,11 @@ pub struct Policy {
/// once `L` is more than `max(min(C, cap), floor)`. `None` for no cap,
/// `L` growing to `C` whatever that is.
pub cap: Option<u64>,
/// By age, once its generation began more than this ago; never if `None`.
/// By age, once its generation began more than this ago; never if
/// `None`. When it began is told by its files when the log is opened
/// (`Wal::open_log_with`), so its age runs on across a start, or a log
/// let go and opened again: one older than this when opened is
/// compacted on its first append.
pub max_age: Option<Duration>,
}
@@ -453,6 +464,39 @@ fn remove(path: &Path) -> io::Result<bool> {
}
}
/// How long the current generation of a log being opened has run, as its
/// files tell, given the last log `replay` kept: for its age to go on from
/// there (`Policy::max_age`), across a start or a log let go and opened
/// again. A generation begins as its log is made, by the compaction that
/// sealed the one before or by the log's first open. So of a log appended
/// to, it began at the earlier of its file's birth, where the file system
/// keeps one, and its last change: its birth, unless its times were set
/// or copied, and never later than its last frame. Of a log the open makes
/// after one ending with its seal, at that one's last change, its seal; of
/// one it makes with none before, now. Nothing is written for it, and no
/// frame rests on it: a time a power cut or a clock set back made wrong
/// starts a compaction sooner or later than due, never more. A time that
/// cannot be read, or is after now, is now.
fn began(layout: &Layout, last: Option<Kept>) -> Duration {
let Some(k) = last else {
return Duration::ZERO;
};
let Ok(meta) = std::fs::metadata(layout.log(k.generation)) else {
return Duration::ZERO;
};
let changed = meta.modified().ok();
let at = if k.sealed {
changed
} else {
match (meta.created().ok(), changed) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
};
at.and_then(|t| std::time::SystemTime::now().duration_since(t).ok())
.unwrap_or(Duration::ZERO)
}
impl Wal {
/// Start a log with generations, given its checkpoint's generation `c`
/// (`0` if there is none) and its size in bytes (`0` if none), which the
@@ -466,8 +510,9 @@ impl Wal {
/// to the last log, or if it ends with its seal (or there is none), to a
/// new one of the next generation. Every log kept, and the directory, is
/// durable before this returns. Answers every frame after the checkpoint,
/// seals stripped. The current generation begins now, for compacting by
/// age. Given `pool`, the log is one of the pool's.
/// seals stripped. The current generation's age, for compacting by age,
/// goes on from what its files tell (`began`). Given `pool`, the log is
/// one of the pool's.
pub fn open_log(
layout: &Layout,
c: u64,
@@ -559,6 +604,9 @@ impl Wal {
// The log appended to: the last kept, unless it ends with its seal.
let last = kept.last().copied();
let appending = last.filter(|k| !k.sealed);
// How long its generation has run, read before anything mended
// changes a file's times.
let before = began(layout, last);
// Files said to be durable, found as a log at rest: no byte is
// written to them here, and so nothing is synced.
let at_rest = durable
@@ -604,6 +652,7 @@ impl Wal {
};
inner.checkpoint = c;
inner.checkpoint_bytes = checkpoint_bytes;
inner.before = before;
if at_rest {
// No file is held: opened and locked as a frame is first
// appended, if it is then as it was found.
@@ -768,7 +817,7 @@ impl Shared {
let by_age = self
.policy
.max_age
.is_some_and(|age| inner.began.elapsed() > age);
.is_some_and(|age| inner.before + inner.began.elapsed() > age);
if !by_size && !by_age {
return None;
}
@@ -876,6 +925,7 @@ impl Shared {
inner.path = next;
inner.generation += 1;
inner.began = Instant::now();
inner.before = Duration::ZERO;
self.written.fetch_add(1, Ordering::SeqCst);
Ok(())
}
@@ -1374,7 +1424,8 @@ mod tests {
}
/// By age: once its generation began more than `max_age` ago, when a
/// compaction made its log or the log started.
/// compaction made its log or the log was first made, whether or not
/// it was started again meanwhile.
#[test]
fn compacts_by_age() {
let dir = scratch("age");
@@ -1399,22 +1450,72 @@ mod tests {
wal.wait_compacted();
assert_eq!(wal.generation(), 1);
drop(wal);
older();
// Started again at once, the generation young still: no compaction.
let (wal, state) = start(&layout, policy).unwrap();
assert_eq!(state, nums(0..3));
wal.set_fold(Arc::new(Entries));
wal.append(&[json!(3)]).unwrap();
wal.wait_compacted();
assert_eq!(wal.generation(), 1);
drop(wal);
// Started again once it is older, though nothing held it meanwhile:
// its first append compacts.
older();
let (wal, state) = start(&layout, policy).unwrap();
assert_eq!(state, nums(0..4));
wal.set_fold(Arc::new(Entries));
wal.append(&[json!(4)]).unwrap();
wal.wait_compacted();
assert_eq!((wal.checkpoint_generation(), wal.generation()), (2, 2));
wal.append(&[json!(5)]).unwrap();
wal.wait_compacted();
assert_eq!(wal.generation(), 2);
drop(wal);
assert_eq!(start(&layout, NEVER).unwrap().1, nums(0..5));
assert_eq!(start(&layout, NEVER).unwrap().1, nums(0..6));
let _ = std::fs::remove_dir_all(&dir);
}
/// A log opened older than `max_age`, as its files tell, is compacted
/// on its first append, and one younger is not: of a log appended to,
/// by its file's birth or last change, whichever is earlier; of one the
/// open makes after a sealed one, by that one's last change, its seal.
#[test]
fn compacts_by_age_its_files_tell() {
let policy = Policy {
floor: u64::MAX,
cap: None,
max_age: Some(Duration::from_secs(60)),
};
let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
for (sealed, old) in [(false, false), (false, true), (true, false), (true, true)] {
let dir = scratch(&format!("age-files-{sealed}-{old}"));
std::fs::create_dir_all(&dir).unwrap();
let layout = Layout::new(&dir, "repo");
put_log(&layout, 0, &nums(0..2), sealed);
if old {
let f = OpenOptions::new().write(true).open(layout.log(0)).unwrap();
f.set_times(std::fs::FileTimes::new().set_modified(hour_ago))
.unwrap();
}
let (wal, state) = start(&layout, policy).unwrap();
assert_eq!(state, nums(0..2));
let g = u64::from(sealed);
assert_eq!(wal.generation(), g);
wal.set_fold(Arc::new(Entries));
wal.append(&[json!(2)]).unwrap();
wal.wait_compacted();
let due = u64::from(old);
assert_eq!(
(wal.checkpoint_generation(), wal.generation()),
(if old { g + 1 } else { 0 }, g + due),
"sealed {sealed}, old {old}"
);
drop(wal);
assert_eq!(start(&layout, NEVER).unwrap().1, nums(0..3));
let _ = std::fs::remove_dir_all(&dir);
}
}
/// Writes go on while a compaction folds, to the next log, each durable;
/// and no other compaction starts meanwhile, though one is due.
#[test]
crates/pds-store/src/lib.rs+5−1
@@ -1138,9 +1138,12 @@ struct Inner {
/// Whether the log's files are let go (`Wal::close`, or the `Wal`
/// dropped): it opens no file again.
shut: bool,
/// The current log's generation, and when it began.
/// The current log's generation, and when it began: `began` in this
/// process, less `before`, how long it had run already when this
/// process opened the log, as its files tell (`generations`).
generation: u64,
began: Instant,
before: Duration,
/// The bytes of the sealed logs from the checkpoint's generation on.
sealed: u64,
/// The checkpoint's generation (`0` with none), and its bytes.
@@ -1178,6 +1181,7 @@ impl Inner {
shut: false,
generation: 0,
began: Instant::now(),
before: Duration::ZERO,
sealed: 0,
checkpoint: 0,
checkpoint_bytes: 0,
harness/checks/store.mjs+39−19
@@ -1,17 +1,17 @@
// The store (spec/STORE.md): a run of its own. A few accounts' records
// rewritten again and again, with blobs and space records, the server killed
// while it reorganizes its data, every read compared with the reference as
// everywhere; then the data directory's size held to the settled bound, and
// the starts to their time. How the server lays its data out is its own:
// only the directory's size, and its files being made, removed or
// shortened, are seen.
// everywhere; then the data directory's size held to the settled bound, once
// across a start of the server and once without, and the starts to their
// time. How the server lays its data out is its own: only the directory's
// size, and its files being made, removed or shortened, are seen.
import { existsSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { isDeepStrictEqual } from 'node:util'
import { BACKFILL_MS, CHECK_EVERY, CRASH_EVERY, ONLY, STEPS } from '../lib/args.mjs'
import { BACKFILL_MS, CHECK_EVERY, CRASH_EVERY, FIREHOSE, ONLY, STEPS } from '../lib/args.mjs'
import { below, chance, pick, rand } from '../lib/random.mjs'
import { cand, dataDir, ref, server, wait } from '../lib/processes.mjs'
import { cand, dataDir, ref, server, wait, waitReady } from '../lib/processes.mjs'
import { ADMIN_PASSWORD } from '../lib/env.mjs'
import { fail } from '../lib/plc.mjs'
import { count, differ, run } from '../lib/report.mjs'
@@ -21,7 +21,7 @@ import { createAccount, createFirstAccounts, createSession } from './accounts.mj
import { blobRecord, getBlob, listBlobs, uploadBlob } from './blobs.mjs'
import { crash, crashes } from './crashes.mjs'
import { getBlocks, getGoneBlocks, syncGetRecord } from './federation.mjs'
import { startFirehose, windowReplay } from './firehose.mjs'
import { resubscribe, startFirehose, windowReplay } from './firehose.mjs'
import { checkRepos } from './repository.mjs'
import { refreshSession } from './sessions.mjs'
@@ -431,9 +431,34 @@ export async function storeRun() {
}
await checkRepos()
// Settled: a quiet 2 W, then a write to each account, and within 10 s the
// data directory within three times the live state and the constants.
// Settled across a start: a burst of rewrites, every key of every account
// eight times, so that the events in the window are many times the live
// state; a quiet 2 W, the server killed and started again, and then a
// write to each account with nothing read before it, so that each
// account's state is first read for that write. First, as the check
// without a start (below) leaves nothing to settle.
for (let round = 0; round < 8; round++) for (const acct of accounts) for (const key of KEYS) await rewrite(acct, key)
await wait(2 * BACKFILL_MS + 1000)
await server.kill()
server.start()
await waitReady(server, cand.url)
if (FIREHOSE) resubscribe()
await settled('after a start')
// Settled: a quiet 2 W, then a write to each account.
await wait(2 * BACKFILL_MS + 1000)
const report = await settled('')
// Out of the window now: all but the latest writes' events.
await windowReplay()
const last = await restart(base)
await checkRepos()
await windowReplay()
return { report, base, last }
}
/// spec/STORE.md, "Bounds", "Settled": a write to each account, after 2 W
/// with none, and within 10 s the data directory within three times the
/// live state and the constants. Answers the report's lines.
async function settled(why) {
for (const acct of accounts) await rewrite(acct, 'flush', { $type: C, batch: nextBatch(), text: 'flush' })
const lives = []
for (const acct of accounts) lives.push(await live(acct))
@@ -446,19 +471,14 @@ export async function storeRun() {
files = filesOf()
}
const size = sizeOf(files)
const what = `data directory, settled${why ? ` ${why}` : ''}`
if (size > bound) {
const largest = Object.fromEntries([...files].sort((x, y) => y[1] - x[1]).slice(0, 10))
await fail(cand, 'data directory, settled', { live: liveBytes, accounts: accounts.length, largest }, `at most ${bound} bytes: three times the live state, ${liveBytes}, ${PER_ACCOUNT} for each account and ${SERVER_SLACK}, within ${SETTLE_MS} ms`, `${size} bytes`)
await fail(cand, what, { live: liveBytes, accounts: accounts.length, largest }, `at most ${bound} bytes: three times the live state, ${liveBytes}, ${PER_ACCOUNT} for each account and ${SERVER_SLACK}, within ${SETTLE_MS} ms`, `${size} bytes`)
}
count('data directory settled', true)
const report = [
count(what, true)
return [
...lives.map((l, i) => `<did:${accounts[i].n}> ${l.bytes} live (repo ${l.repo}, blobs ${l.blobs}, spaces ${l.space})`),
`data directory ${size} bytes, bound ${bound}: ${(size / liveBytes).toFixed(2)}x the live state`,
`${what}: ${size} bytes, bound ${bound}: ${(size / liveBytes).toFixed(2)}x the live state`,
]
// Out of the window now: all but the latest writes' events.
await windowReplay()
const last = await restart(base)
await checkRepos()
await windowReplay()
return { report, base, last }
}
spec/STORE.md+11−6
@@ -131,9 +131,10 @@ The **data directory's size** is the sum of the sizes of the files in
none of their bytes, and the live state counts them all the same; the
bucket holds what `BLOBS.md` says.
- **Settled.** When no write has come for `2 W`, and then one comes to each
account, within 10 seconds the data directory's size is at most three
times the accounts' live states, plus 128 KiB (131072 bytes) for each
- **Settled.** When no write has come for `2 W`, whether or not the server
was started again meanwhile, and then one comes to each account, within
10 seconds the data directory's size is at most three times the
accounts' live states, plus 128 KiB (131072 bytes) for each
account, for what the server keeps of it besides (its sessions, app
passwords, mail, preferences and OAuth sessions), plus 1 MiB (1048576
bytes) for what it keeps of no one account (its keys, invite codes,
@@ -263,9 +264,13 @@ checks what those crashes check, the space repos, takedowns and preferences
too, with the firehose carrying on from its last event; and the start must
answer within the bound above of the first.
At the end it waits `2 W` and a second, writes once to each account, and,
within 10 seconds, the data directory's size, but for the server's log the
harness keeps there, must be within the settled bound. Then the server is
At the end it rewrites every key of every account eight times, at once,
then waits `2 W` and a second, kills the server and starts it again, and,
reading nothing first, writes once to each account; within 10
seconds the data directory's size, but for the server's log the harness
keeps there, must be within the settled bound. Then it waits `2 W` and a
second again, writes once to each account, and holds the size to the
bound the same way, the server not started again. Then the server is
killed and started once more, the start timed, and every account checked
again. The run reports the data directory's size against the accounts' live
states, and the starts' times.