silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
//! What a run derived from a file, kept for a later run that reads the same inputs.

use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};

use serde::de::DeserializeOwned;
use serde::Serialize;

/// The layout of an entry file. A file of another layout reads as empty.
const FORMAT: &[u8; 8] = b"sxcache1";

struct Store {
    /// The entries of this build.
    dir: PathBuf,
    /// The directory of every build's entries.
    builds: PathBuf,
    /// The build of the running binary, so a build never reads what another derived.
    build: blake3::Hash,
    verify: bool,
}

/// How many other builds keep their entries: an upgrade, or two checkouts on two versions,
/// leaves the entries of the builds no run uses any more.
const KEPT_BUILDS: usize = 2;

/// Marks the entries of this build as used now, and removes those of every build but the
/// `KEPT_BUILDS` other ones a run used last.
fn drop_other_builds(store: &Store) {
    // ยง faq86xmas.h@ks4vr
    let used = store.dir.join("used");
    if std::fs::create_dir_all(&store.dir).is_err() || std::fs::write(&used, b"").is_err() {
        return;
    }
    let Ok(dirs) = std::fs::read_dir(&store.builds) else {
        return;
    };
    let mut others: Vec<(std::time::SystemTime, PathBuf)> = dirs
        .flatten()
        .map(|dir| dir.path())
        .filter(|dir| *dir != store.dir && dir.is_dir())
        .map(|dir| {
            let at = std::fs::metadata(dir.join("used"))
                .or_else(|_| std::fs::metadata(&dir))
                .and_then(|m| m.modified())
                .unwrap_or(std::time::UNIX_EPOCH);
            (at, dir)
        })
        .collect();
    others.sort();
    others.reverse();
    for (_, dir) in others.into_iter().skip(KEPT_BUILDS) {
        let _ = std::fs::remove_dir_all(dir);
    }
}

static STORE: OnceLock<Option<Store>> = OnceLock::new();
static ENTRIES: OnceLock<Mutex<HashMap<blake3::Hash, Arc<Entry>>>> = OnceLock::new();

/// Opens the store of the repository that holds `root`, once per run. A run outside git, one
/// with `SILCROW_CACHE=off` keep no store.
pub fn open(root: &Path) {
    // ยง faq86xmas.b@1kbz8
    STORE.get_or_init(|| {
        // ยง one faq86xmas.f@qz675
        if std::env::var_os("SILCROW_CACHE").is_some_and(|v| v == "off") {
            return None;
        }
        let out = crate::workspace::git(root)
            .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let common = PathBuf::from(String::from_utf8(out.stdout).ok()?.trim());
        let build = blake3::Hash::from_hex(env!("SILCROW_BUILD")).expect("build.rs writes a hash");
        let builds = common.join("silcrow").join("cache");
        Some(Store {
            dir: builds.join(&build.to_hex()[..16]),
            builds,
            build,
            verify: std::env::var_os("SILCROW_CACHE_VERIFY").is_some(),
        })
    });
}

fn store() -> Option<&'static Store> {
    STORE.get().and_then(Option::as_ref)
}

/// What a run derived from one file, by the query that derived it.
pub struct Entry {
    key: blake3::Hash,
    /// Read from the store on first use.
    stored: OnceLock<HashMap<Vec<u8>, Vec<u8>>>,
    derived: Mutex<HashMap<Vec<u8>, Vec<u8>>>,
    used: Mutex<HashSet<Vec<u8>>>,
}

impl std::fmt::Debug for Entry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Entry({})", self.key.to_hex())
    }
}

/// The entry of the file at `rel` holding `text`, shared by every reader of the run, or none
/// without a store.
pub fn entry(rel: &Path, text: &str) -> Option<Arc<Entry>> {
    // ยง faq86xmas.a@6jsyp
    let key = key(&store()?.build, rel, text);
    let entries = ENTRIES.get_or_init(Default::default);
    let mut entries = entries.lock().expect("cache entries");
    Some(Arc::clone(entries.entry(key).or_insert_with(|| {
        Arc::new(Entry {
            key,
            stored: OnceLock::new(),
            derived: Mutex::new(HashMap::new()),
            used: Mutex::new(HashSet::new()),
        })
    })))
}

/// The key of the entry of the file at `rel` holding `text`, read by the build `build`, whose
/// sources hold the hashing scheme too.
fn key(build: &blake3::Hash, rel: &Path, text: &str) -> blake3::Hash {
    let mut hasher = blake3::Hasher::new();
    hasher.update(FORMAT);
    hasher.update(build.as_bytes());
    let rel = rel.to_string_lossy();
    hasher.update(&(rel.len() as u64).to_le_bytes());
    hasher.update(rel.as_bytes());
    hasher.update(text.as_bytes());
    hasher.finalize()
}

/// The answer to `query` about the file at `rel` holding `text`, reused when a run already
/// derived it, else derived by `derive`.
pub fn memo<Q, T>(rel: &Path, text: &str, query: &Q, derive: impl FnOnce() -> T) -> T
where
    Q: Serialize + Debug,
    T: Serialize + DeserializeOwned + PartialEq + Debug,
{
    match entry(rel, text) {
        Some(entry) => entry.memo(query, derive),
        None => derive(),
    }
}

/// Reads the entry of the file at `rel` holding `text` now, so a run that asks for it later in
/// one thread does not wait on the disk then.
pub fn preload(rel: &Path, text: &str) {
    if let Some(entry) = entry(rel, text) {
        entry.stored();
    }
}

impl Entry {
    fn path(&self, store: &Store) -> PathBuf {
        let hex = self.key.to_hex();
        store.dir.join(&hex[..2]).join(hex.as_str())
    }

    fn stored(&self) -> &HashMap<Vec<u8>, Vec<u8>> {
        // ยง faq86xmas.c@yq98p
        self.stored.get_or_init(|| {
            store()
                .and_then(|store| std::fs::read(self.path(store)).ok())
                .and_then(|bytes| decode(&bytes, &self.key))
                .unwrap_or_default()
        })
    }

    /// The answer to `query`, reused when a run already derived it from this file, else
    /// derived by `derive` and kept.
    pub fn memo<Q, T>(&self, query: &Q, derive: impl FnOnce() -> T) -> T
    where
        Q: Serialize + Debug,
        T: Serialize + DeserializeOwned + PartialEq + Debug,
    {
        let Ok(at) = bincode::serialize(query) else {
            return derive();
        };
        let found = self
            .derived
            .lock()
            .expect("cache entry")
            .get(&at)
            .cloned()
            .or_else(|| self.stored().get(&at).cloned());
        if let Some(value) = found.and_then(|bytes| bincode::deserialize::<T>(&bytes).ok()) {
            self.used.lock().expect("cache entry").insert(at);
            // ยง faq86xmas.f@nem2e
            if store().is_some_and(|store| store.verify) {
                let fresh = derive();
                assert!(
                    fresh == value,
                    "silcrow cache: entry {} answers {query:?} with {value:?}, and deriving it again gives {fresh:?}",
                    self.key.to_hex()
                );
            }
            // ยง end faq86xmas.f
            return value;
        }
        let value = derive();
        if let Ok(bytes) = bincode::serialize(&value) {
            self.used.lock().expect("cache entry").insert(at.clone());
            self.derived.lock().expect("cache entry").insert(at, bytes);
        }
        value
    }

    /// Writes the entry when the run derived something new: what it derived and what it reused,
    /// so an answer no later run asks for again leaves with the next write.
    /// Whether the run derived something new for this entry, which it then writes.
    fn write(&self, store: &Store) -> bool {
        // ยง faq86xmas.d@r30r3
        let derived = self.derived.lock().expect("cache entry");
        if derived.is_empty() {
            return false;
        }
        let used = self.used.lock().expect("cache entry");
        let mut kept: Vec<(&Vec<u8>, &Vec<u8>)> = self
            .stored()
            .iter()
            .filter(|(query, _)| used.contains(*query) && !derived.contains_key(*query))
            .chain(derived.iter())
            .collect();
        kept.sort();
        write_whole(&self.path(store), &self.key, &kept);
        // ยง end faq86xmas.d
        true
    }
}

/// How long an entry no run used stays in the store.
const KEPT_UNUSED: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);

/// Removes the entries this run did not use and no run wrote for `KEPT_UNUSED`, once the store
/// holds several times what the run used: a file edited many times leaves one entry per text.
/// An entry another run still reads is derived again by it, which costs it time only.
fn collect_garbage(store: &Store, live: &HashSet<String>) {
    // ยง faq86xmas.h@z0mkx
    let Ok(dirs) = std::fs::read_dir(&store.dir) else {
        return;
    };
    let mut files = Vec::new();
    for dir in dirs.flatten() {
        if dir.file_name().len() != 2 {
            continue;
        }
        if let Ok(inner) = std::fs::read_dir(dir.path()) {
            files.extend(inner.flatten().map(|file| file.path()));
        }
    }
    if files.len() <= 4 * live.len() + 1024 {
        return;
    }
    let now = std::time::SystemTime::now();
    for file in files {
        let name = file
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();
        let old = std::fs::metadata(&file)
            .and_then(|m| m.modified())
            .is_ok_and(|at| now.duration_since(at).is_ok_and(|age| age > KEPT_UNUSED));
        if old && !live.contains(name) {
            let _ = std::fs::remove_file(&file);
        }
    }
}

/// What an earlier run of this binary left under `name` to start from, which a run only uses
/// where any start gives the same result, none without a store or such a run.
pub fn hint(name: &str) -> Option<Vec<u8>> {
    // ยง faq86xmas.g@93m4e
    let store = store()?;
    let key = hint_key(store, name);
    decode(&std::fs::read(hint_path(store, &key)).ok()?, &key)?.remove(name.as_bytes())
}

/// Leaves `value` under `name` for a later run of this binary.
pub fn set_hint(name: &str, value: &[u8]) {
    let Some(store) = store() else {
        return;
    };
    let key = hint_key(store, name);
    let body = vec![(name.as_bytes().to_vec(), value.to_vec())];
    write_whole(&hint_path(store, &key), &key, &body);
}

fn hint_key(store: &Store, name: &str) -> blake3::Hash {
    let mut hasher = blake3::Hasher::new();
    hasher.update(FORMAT);
    hasher.update(store.build.as_bytes());
    hasher.update(name.as_bytes());
    hasher.finalize()
}

fn hint_path(store: &Store, key: &blake3::Hash) -> PathBuf {
    store.dir.join("hints").join(key.to_hex().as_str())
}

/// Writes the pairs `body` as the whole entry `key` at `path`, replacing it at once.
fn write_whole<K: Serialize, V: Serialize>(path: &Path, key: &blake3::Hash, body: &[(K, V)]) {
    // ยง faq86xmas.d@xr0df
    let Ok(body) = bincode::serialize(body) else {
        return;
    };
    let Some(dir) = path.parent() else {
        return;
    };
    if std::fs::create_dir_all(dir).is_err() {
        return;
    }
    let mut bytes = Vec::with_capacity(body.len() + 72);
    bytes.extend_from_slice(FORMAT);
    bytes.extend_from_slice(key.as_bytes());
    bytes.extend_from_slice(blake3::hash(&body).as_bytes());
    bytes.extend_from_slice(&body);
    // A run that reads the entry while this one writes it reads the old file or the new one.
    let Ok(mut file) = tempfile::NamedTempFile::new_in(dir) else {
        return;
    };
    if std::io::Write::write_all(&mut file, &bytes).is_ok() {
        let _ = file.persist(path);
    }
}

/// The answers an entry file holds, or none when it is not one whole entry of `key` in this
/// layout.
fn decode(bytes: &[u8], key: &blake3::Hash) -> Option<HashMap<Vec<u8>, Vec<u8>>> {
    let rest = bytes.strip_prefix(FORMAT.as_slice())?;
    let (own, rest) = rest.split_at_checked(32)?;
    let (sum, body) = rest.split_at_checked(32)?;
    if own != key.as_bytes() || sum != blake3::hash(body).as_bytes() {
        return None;
    }
    let pairs: Vec<(Vec<u8>, Vec<u8>)> = bincode::deserialize(body).ok()?;
    Some(pairs.into_iter().collect())
}

/// Writes every entry the run derived something new for. A write that fails costs a later
/// run time only.
pub fn flush() {
    if std::env::var_os("SILCROW_CACHE_TRACE").is_some() {
        eprintln!(
            "silcrow cache: {} file(s) parsed",
            crate::span::PARSES.load(std::sync::atomic::Ordering::Relaxed)
        );
    }
    let Some(store) = store() else {
        return;
    };
    let Some(entries) = ENTRIES.get() else {
        return;
    };
    let entries: Vec<Arc<Entry>> = entries
        .lock()
        .expect("cache entries")
        .values()
        .cloned()
        .collect();
    let live: HashSet<String> = entries.iter().map(|e| e.key.to_hex().to_string()).collect();
    let wrote = crate::par::map_many(entries, |entry| entry.write(store));
    if wrote.into_iter().any(|wrote| wrote) {
        collect_garbage(store, &live);
    }
    drop_other_builds(store);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_key_moves_with_the_build_the_path_and_the_text() {
        let build = blake3::hash(b"one build");
        let at = |build: &blake3::Hash, rel: &str, text: &str| key(build, Path::new(rel), text);
        let base = at(&build, "src/a.rs", "fn a() {}");
        assert_ne!(
            base,
            at(&blake3::hash(b"another build"), "src/a.rs", "fn a() {}")
        );
        assert_ne!(base, at(&build, "src/b.rs", "fn a() {}"));
        assert_ne!(base, at(&build, "src/a.rs", "fn b() {}"));
        // The path and the text do not run into each other.
        assert_ne!(at(&build, "src/a.rs", "x"), at(&build, "src/a.r", "sx"));
        assert_eq!(base, at(&build, "src/a.rs", "fn a() {}"));
    }

    #[test]
    fn a_run_keeps_the_entries_of_the_two_builds_used_last_besides_its_own() {
        let dir = tempfile::tempdir().unwrap();
        let builds = dir.path().to_path_buf();
        let at = |name: &str, age: u64| {
            let used = builds.join(name).join("used");
            std::fs::create_dir_all(used.parent().unwrap()).unwrap();
            std::fs::write(&used, b"").unwrap();
            let file = std::fs::File::options().write(true).open(&used).unwrap();
            file.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(age))
                .unwrap();
        };
        for (name, age) in [
            ("old", 300),
            ("older", 400),
            ("recent", 100),
            ("second", 200),
        ] {
            at(name, age);
        }
        let store = Store {
            dir: builds.join("own"),
            builds: builds.clone(),
            build: blake3::hash(b"build"),
            verify: false,
        };
        drop_other_builds(&store);
        let mut left: Vec<String> = std::fs::read_dir(&builds)
            .unwrap()
            .map(|d| d.unwrap().file_name().to_string_lossy().to_string())
            .collect();
        left.sort();
        assert_eq!(left, ["own", "recent", "second"]);
    }

    #[test]
    fn a_store_far_past_what_a_run_used_drops_old_entries_the_run_did_not_use() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store {
            dir: dir.path().to_path_buf(),
            builds: dir.path().to_path_buf(),
            build: blake3::hash(b"build"),
            verify: false,
        };
        let old = std::time::SystemTime::now() - KEPT_UNUSED * 2;
        let mut names = Vec::new();
        for i in 0..1100 {
            let name = blake3::hash(format!("{i}").as_bytes()).to_hex().to_string();
            let path = dir.path().join(&name[..2]).join(&name);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, b"x").unwrap();
            if i % 2 == 0 {
                let file = std::fs::File::options().write(true).open(&path).unwrap();
                file.set_modified(old).unwrap();
            }
            names.push((name, path));
        }
        let live: HashSet<String> = names[..10].iter().map(|(n, _)| n.clone()).collect();
        collect_garbage(&store, &live);
        for (i, (name, path)) in names.iter().enumerate() {
            let kept = live.contains(name) || i % 2 == 1;
            assert_eq!(path.exists(), kept, "{i}");
        }
    }

    #[test]
    fn an_entry_reads_back_only_whole_and_under_its_own_key() {
        let key = blake3::hash(b"entry");
        let body = bincode::serialize(&vec![(b"q".to_vec(), b"a".to_vec())]).unwrap();
        let mut bytes = FORMAT.to_vec();
        bytes.extend_from_slice(key.as_bytes());
        bytes.extend_from_slice(blake3::hash(&body).as_bytes());
        bytes.extend_from_slice(&body);
        assert_eq!(decode(&bytes, &key).unwrap()[&b"q".to_vec()], b"a".to_vec());
        assert!(decode(&bytes[..bytes.len() - 1], &key).is_none());
        assert!(decode(&bytes, &blake3::hash(b"other")).is_none());
        let mut flipped = bytes.clone();
        flipped[8] ^= 1;
        assert!(decode(&flipped, &key).is_none());
        assert!(decode(b"sxcache0", &key).is_none());
    }
}