Skip to main content

sokf_core/cache/
sync.rs

1//! This module compares the walk of a run with the store and writes the
2//! results of the run back. It compares the stat that the walk took of
3//! each file with the `files` table of the store, decides which files the
4//! run must read, and writes the rows of the run in one transaction
5//! (CACHE-1_AC-11).
6
7use std::collections::{BTreeMap, BTreeSet, HashMap};
8
9use rusqlite::params;
10
11use super::{Cache, conn::Conn, hint, rows::DocRow};
12use crate::{FileKey, FileKind, RepoPath, Stat, Tree};
13
14/// `RACY_MARGIN` is the time, in nanoseconds, before the last sync within
15/// which the run reads a file again whatever its stat says. The run reads
16/// a file again when its modification time lies within this time of the
17/// last sync, because a filesystem might truncate the time to whole seconds
18/// (CACHE-1_AC-1).
19pub const RACY_MARGIN: i64 = 2_000_000_000;
20
21/// `FileState` says what the sync found a file to be.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum FileState {
24    /// The stat of the file equals the stat in the store, and its
25    /// modification time is earlier than the last sync by at least
26    /// `RACY_MARGIN`, so the run doesn't read the file.
27    Unchanged,
28    /// The run read the file, and its hash equals the hash in the store.
29    Kept,
30    /// The run read the file, and the file is new or its hash differs from
31    /// the hash in the store.
32    Changed,
33}
34
35/// `SyncStats` holds the counts of a run, for tests and diagnostics: what
36/// the sync found, and the work that the run did against the store
37/// (contract-cache CACHE-3_AC-4).
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub struct SyncStats {
40    /// The number of files that the sync judged unchanged by their stat,
41    /// without reading them. With a hint, the sync judges only the files at
42    /// or under the hinted paths.
43    pub unchanged: usize,
44    /// The number of files that the run read.
45    pub read: usize,
46    /// The number of files that the run read and found new, or whose hash
47    /// differs from the hash in the store.
48    pub changed: usize,
49    /// The number of files in the store that the walk no longer lists.
50    pub removed: usize,
51    /// The number of statements that the run ran against the store: each
52    /// run of a statement or of a batch counts as one, whatever number of
53    /// rows it reads or writes. The count
54    /// includes the statements of each `StoreView`, the view of the store
55    /// that `Cache::view` opens for the documents that the run doesn't
56    /// hold.
57    pub queries: u64,
58    /// The number of file rows that the sync holds in memory: one for each
59    /// file that the run must read. The files that the run has already read
60    /// are among these (CACHE-3_AC-2).
61    pub held: usize,
62}
63
64/// `Row` is one row of the `files` table.
65#[derive(Debug, Clone, PartialEq, Eq)]
66#[expect(
67    clippy::struct_field_names,
68    reason = "each field keeps the name of its column in the `files` table"
69)]
70pub(super) struct Row {
71    kind: u8,
72    root: Option<usize>,
73    stat: Stat,
74    hash: Option<u64>,
75    /// The hash of the stored row of the document, when the file is a
76    /// document that has one.
77    pub(super) row_hash: Option<u64>,
78}
79
80/// `Listed` is one walked file as the sync keeps it: its path, its kind,
81/// and its root.
82#[derive(Debug, Clone, PartialEq, Eq)]
83struct Listed {
84    path: RepoPath,
85    kind: u8,
86    root: Option<usize>,
87}
88
89/// `SyncState` holds the state of the sync of this run.
90#[derive(Debug, Default)]
91pub(super) struct SyncState {
92    /// The generation of the store when the run synced. The store counts its
93    /// commits, and a commit writes only while the count is unchanged.
94    generation: i64,
95    /// Every walked file, sorted by path.
96    listed: Vec<Listed>,
97    /// The files that the run must read, each with its row in the store
98    /// when the store has one. The map holds only the rows of these files.
99    pub(super) known: HashMap<RepoPath, Option<Row>>,
100    /// The files that the run read, by path, each with the row that the
101    /// commit writes for it.
102    walked: HashMap<RepoPath, Row>,
103    /// The candidate files that the walk lists. The store doesn't have
104    /// their stat, because they are new or their stat changed. A run
105    /// reads a candidate only when a check or a scan for markers needs it,
106    /// so the store keeps only the stat of a candidate, with no hash. When the
107    /// stat of a candidate differs from the stat in the store, the
108    /// documents that include or link it count as changed.
109    pub(super) candidates: BTreeMap<RepoPath, Stat>,
110    /// The number of files that the sync judged unchanged by their stat,
111    /// without reading them.
112    unchanged: usize,
113    /// The files that the run read, each with what the read found.
114    observed: BTreeMap<RepoPath, FileState>,
115    /// The rows to delete: those of the files that the walk no longer
116    /// lists.
117    pub(super) removed: Vec<RepoPath>,
118    /// The directories that the walk lists and the store didn't, each with
119    /// its root.
120    pub(super) dirs_added: Vec<(RepoPath, usize)>,
121    /// The directories that the store lists and the walk no longer does.
122    pub(super) dirs_removed: Vec<RepoPath>,
123    /// The rows of the documents that the run read.
124    pub(super) rows: BTreeMap<RepoPath, DocRow>,
125    /// The keys of each document that the run checked.
126    pub(super) keys_of: BTreeMap<RepoPath, Vec<crate::model::KeyEntry>>,
127    /// The anchors that the engine keeps in each document that the run
128    /// checked, for the units that break their rules, by slug.
129    pub(super) anchors_of: BTreeMap<RepoPath, BTreeSet<String>>,
130    /// The paths that each checked document plans, which the commit writes
131    /// in place of the document's rows in `plans`.
132    pub(super) plans_of: BTreeMap<RepoPath, BTreeSet<crate::model::Planned>>,
133    /// The output of each check that the run ran.
134    pub(super) outputs: BTreeMap<RepoPath, Vec<crate::Finding>>,
135    /// The queries of each check that the run ran.
136    pub(super) deps: BTreeMap<RepoPath, BTreeSet<String>>,
137    /// The citations of each document that the run checked.
138    pub(super) citations: BTreeMap<RepoPath, Vec<super::CitationRow>>,
139    /// The edges of each document that the run checked.
140    pub(super) edges: BTreeMap<RepoPath, Vec<crate::graph::RawEdge>>,
141    /// What each path that the run probed outside the walk names on disk.
142    pub(super) probes: BTreeMap<RepoPath, crate::walk::OnDisk>,
143    /// The asset pairings that the run found.
144    pub(super) assets: Option<Vec<super::AssetRow>>,
145    /// The schema files that the run found, by key.
146    pub(super) schemas: Option<Vec<super::SchemaRow>>,
147    /// The additional files that the run found, each with the schema that
148    /// governs it.
149    pub(super) additional: Option<Vec<super::AdditionalRow>>,
150    /// The hash of the formats file, when the run compared it.
151    pub(super) formats_hash: Option<u64>,
152    /// The fingerprint of the registry, one hash for each format and type,
153    /// when the formats file changed.
154    pub(super) formats: Option<Vec<(String, u64)>>,
155    /// The identities of every store, when the run compared them.
156    pub(super) identities: Option<Vec<crate::model::IdentityRow>>,
157    /// The markers of each file that the run scanned. They replace the rows
158    /// of the file in the store.
159    pub(super) markers: BTreeMap<RepoPath, Vec<crate::markers::MarkerRow>>,
160}
161
162impl Cache {
163    /// `sync` compares the walk with the store to decide which files this
164    /// run must read (CACHE-1_AC-1, CACHE-1_AC-24). The sync treats a file
165    /// as unchanged, and doesn't read it, when two conditions hold. Its
166    /// length and modification time equal those in the store. Its
167    /// modification time is earlier than the last sync by at least
168    /// `RACY_MARGIN`. The run reads any other file when a command needs it,
169    /// and the hash of the file decides whether it changed. The walk is
170    /// sorted by path, and the sync reads the rows of the store in the same
171    /// order. So one pass yields the unchanged, changed, added, and removed
172    /// files. The pass holds only the rows of the files that the run must
173    /// read. `sync`
174    /// also finds the directories that were added or removed.
175    // sokf-implements: CACHE-1_AC-1
176    // sokf-implements: CACHE-1_AC-24
177    pub fn sync(&self, tree: &Tree) {
178        let mut state = self.state.borrow_mut();
179        // Each run starts from an empty state, so that nothing of an earlier
180        // run on this cache leaks into it.
181        *state = SyncState {
182            generation: generation(self.conn()),
183            listed: tree
184                .files
185                .iter()
186                .map(|f| Listed {
187                    path: f.path.clone(),
188                    kind: kind_code(f.kind),
189                    root: f.root,
190                })
191                .collect(),
192            ..SyncState::default()
193        };
194        self.merge(tree, &mut state);
195        // The sync compares the directories too, so that the run treats the
196        // index of a directory that was added or removed as touched
197        // (CACHE-1_AC-18).
198        let known_dirs = self.stored_dirs();
199        let walked_dirs: BTreeSet<&RepoPath> = tree.dirs.iter().map(|d| &d.path).collect();
200        state.dirs_added = tree
201            .dirs
202            .iter()
203            .filter(|d| !known_dirs.contains_key(&d.path))
204            .map(|d| (d.path.clone(), d.root))
205            .collect();
206        state.dirs_removed = known_dirs
207            .into_keys()
208            .filter(|d| !walked_dirs.contains(d))
209            .collect();
210    }
211
212    /// `merge` compares the walk with the rows of the store, both in path
213    /// order. A file that is in both is unchanged when its stat equals the
214    /// stat in the store, its modification time is earlier than the last
215    /// sync by at least `RACY_MARGIN`, and the store has a hash for it or
216    /// it is a candidate. `merge` holds no row for an unchanged file. Any
217    /// other file in the walk is one that the run must read, and `merge`
218    /// holds it with its row from the store. `merge` records the path of a
219    /// row that the walk lacks as removed. `merge` also records each candidate that it holds, as the
220    /// field `candidates` of `SyncState` describes. When a caller gave the
221    /// run a hint, the list of the paths that changed, `merge` leaves the
222    /// work to `merge_hinted`.
223    // sokf-implements: CACHE-1_AC-26
224    // sokf-implements: CACHE-1_AC-29
225    fn merge(&self, tree: &Tree, state: &mut SyncState) {
226        // A hint that holds a whole root gets the walk of the repository,
227        // so the full merge compares it.
228        if let Some(hinted) = self.hint.borrow().as_deref()
229            && !self.is_fresh()
230        {
231            let scopes = hint::scopes(hinted);
232            if !hint::covers_root(&scopes, &tree.roots) {
233                self.merge_hinted(tree, scopes, state);
234                return;
235            }
236        }
237        let Ok(mut stmt) = self.conn().prepare(
238            "SELECT path, kind, root, len, mtime, hash, row_hash FROM files ORDER BY path",
239        ) else {
240            for f in &tree.files {
241                self.judge(state, f, None);
242            }
243            return;
244        };
245        let mut files = tree.files.iter().peekable();
246        // The sync streams the rows of the store and compares each in
247        // place: it copies a row only when the run must read its file
248        // (CACHE-3_AC-2).
249        if let Ok(mut rows) = stmt.query([]) {
250            while let Ok(Some(r)) = rows.next() {
251                let Ok(path) = r.get_ref(0).and_then(|v| Ok(v.as_str()?)) else {
252                    continue;
253                };
254                while let Some(f) = files.next_if(|f| f.path.as_str() < path) {
255                    self.judge(state, f, None);
256                }
257                let Some(f) = files.next_if(|f| f.path.as_str() == path) else {
258                    if let Some(p) = RepoPath::parse(path) {
259                        state.removed.push(p);
260                    }
261                    continue;
262                };
263                self.judge(state, f, row_of(r).ok());
264            }
265        }
266        for f in files {
267            self.judge(state, f, None);
268        }
269    }
270
271    /// `judge` decides whether the run must read a walked file, given its
272    /// row in the store. The file is unchanged when its stat equals the
273    /// stat in the store, its modification time is earlier than the last
274    /// sync by at least `RACY_MARGIN`, and the store has a hash for it or it
275    /// is a candidate. `judge` counts an unchanged file, and holds any other
276    /// file with its row, among the candidates too when it is one.
277    fn judge(&self, state: &mut SyncState, f: &crate::WalkedFile, row: Option<Row>) {
278        let unchanged = row.as_ref().is_some_and(|row| {
279            (row.hash.is_some() || f.kind == FileKind::Candidate)
280                && row.stat == f.stat
281                && self.outside_margin(f.stat)
282        });
283        if unchanged {
284            state.unchanged += 1;
285            return;
286        }
287        if f.kind == FileKind::Candidate {
288            state.candidates.insert(f.path.clone(), f.stat);
289        }
290        state.known.insert(f.path.clone(), row);
291    }
292
293    /// `merge_hinted` merges the walk with the store for a run that has a
294    /// hint. The walk of such a run builds its tree from the rows of the
295    /// store and lists again only each hinted path and the paths under it.
296    /// Only those paths can therefore differ from the store, so
297    /// `merge_hinted` compares only them (CACHE-1_AC-23).
298    // sokf-implements: CACHE-1_AC-47
299    // sokf-implements: CACHE-3_AC-12
300    fn merge_hinted(&self, tree: &Tree, scopes: BTreeSet<RepoPath>, state: &mut SyncState) {
301        let mut paths: BTreeSet<RepoPath> = BTreeSet::new();
302        for scope in scopes {
303            let (low, high) = hint::under(&scope);
304            let start = tree
305                .files
306                .partition_point(|f| f.path.as_str() < low.as_str());
307            paths.extend(
308                tree.files[start..]
309                    .iter()
310                    .take_while(|f| f.path.as_str() < high.as_str())
311                    .map(|f| f.path.clone()),
312            );
313            paths.extend(self.stored_under(&low, &high));
314            paths.insert(scope);
315        }
316        for path in &paths {
317            match (tree.file(path), self.file_row(path)) {
318                (Some(f), row) => self.judge(state, f, row),
319                (None, Some(_)) => state.removed.push(path.clone()),
320                (None, None) => {}
321            }
322        }
323    }
324
325    /// `file_row` returns the row of one file in the store.
326    fn file_row(&self, path: &RepoPath) -> Option<Row> {
327        self.conn()
328            .query_row(
329                "SELECT path, kind, root, len, mtime, hash, row_hash FROM files WHERE path = ?1",
330                [path.as_str()],
331                row_of,
332            )
333            .ok()
334    }
335
336    /// `stored_under` returns the paths of the files in the store that lie
337    /// between the bounds that `hint::under` returns for a directory.
338    fn stored_under(&self, low: &str, high: &str) -> Vec<RepoPath> {
339        self.conn()
340            .rows(
341                "SELECT path FROM files WHERE path >= ?1 AND path < ?2",
342                [low, high],
343                |r| r.get::<_, String>(0),
344            )
345            .iter()
346            .filter_map(|p| RepoPath::parse(p))
347            .collect()
348    }
349
350    /// `listed` returns the kind and the root of the walked file at `path`,
351    /// found by a binary search of the sorted list.
352    pub(super) fn listed(state: &SyncState, path: &RepoPath) -> Option<(u8, Option<usize>)> {
353        state
354            .listed
355            .binary_search_by(|l| l.path.cmp(path))
356            .ok()
357            .map(|i| (state.listed[i].kind, state.listed[i].root))
358    }
359
360    /// `dirs_changed` returns the directories that the walk lists and the
361    /// store didn't, and the directories that the store lists and the walk
362    /// no longer does.
363    pub fn dirs_changed(&self) -> (Vec<RepoPath>, Vec<RepoPath>) {
364        let state = self.state.borrow();
365        (
366            state.dirs_added.iter().map(|(p, _)| p.clone()).collect(),
367            state.dirs_removed.clone(),
368        )
369    }
370
371    /// `must_read` says whether a run must read `path` before it can trust
372    /// the hash in the store. The run must read the file when the file is
373    /// new, when its stat differs from the stat in the store, when its
374    /// modification time lies within `RACY_MARGIN` of the last sync, or
375    /// when the walk doesn't list it.
376    pub fn must_read(&self, path: &RepoPath) -> bool {
377        let state = self.state.borrow();
378        state.known.contains_key(path) || Self::listed(&state, path).is_none()
379    }
380
381    /// `observe` records that the run read a file. The hash in `key` decides
382    /// whether the file changed, and the commit writes the row of the file.
383    // sokf-implements: CACHE-1_AC-2
384    // sokf-implements: CACHE-1_AC-3
385    pub fn observe(&self, path: &RepoPath, key: &FileKey) -> FileState {
386        // The run can read a file that the sync didn't mark as one to read,
387        // such as a related document or the index of a touched directory.
388        // For such a file, `observe` fetches its row from the store, for two
389        // reasons. First, it can compare the hash that the run read with the
390        // row. Second, the commit then writes nothing that the store already
391        // has.
392        let held = self.state.borrow().known.get(path).cloned();
393        let known = if let Some(known) = held {
394            known
395        } else {
396            let row = if self.is_walked(path) {
397                self.file_row(path)
398            } else {
399                None
400            };
401            self.state
402                .borrow_mut()
403                .known
404                .insert(path.clone(), row.clone());
405            row
406        };
407        let mut state = self.state.borrow_mut();
408        let found = match &known {
409            Some(known) if known.hash == Some(key.hash) => FileState::Kept,
410            _ => FileState::Changed,
411        };
412        let (kind, root) =
413            Self::listed(&state, path).unwrap_or((kind_code(FileKind::Candidate), None));
414        state.walked.insert(
415            path.clone(),
416            Row {
417                kind,
418                root,
419                stat: key.stat(),
420                hash: Some(key.hash),
421                row_hash: known.and_then(|k| k.row_hash),
422            },
423        );
424        state.observed.insert(path.clone(), found);
425        found
426    }
427
428    /// `knowledge_of` returns the knowledge root that a walked file lies
429    /// under, if any.
430    pub fn knowledge_of(&self, path: &RepoPath) -> Option<usize> {
431        let state = self.state.borrow();
432        Self::listed(&state, path).and_then(|(_, root)| root)
433    }
434
435    /// `hash_of` returns the hash of a walked file: the hash that this run
436    /// read, the hash in the row of the store that the run holds, or, for a
437    /// file that the run didn't read, the hash that `hash_of` reads from
438    /// the store.
439    pub fn hash_of(&self, path: &RepoPath) -> Option<u64> {
440        let state = self.state.borrow();
441        if let Some(w) = state.walked.get(path) {
442            return w.hash;
443        }
444        if let Some(known) = state.known.get(path) {
445            return known.as_ref().and_then(|k| k.hash);
446        }
447        drop(state);
448        self.stored_hash(path)
449    }
450
451    /// `is_document` says whether the walk lists `path` as a document.
452    pub fn is_document(&self, path: &RepoPath) -> bool {
453        let state = self.state.borrow();
454        Self::listed(&state, path).is_some_and(|(kind, _)| kind == kind_code(FileKind::Document))
455    }
456
457    /// `is_schema` says whether the walk lists `path` as a schema document.
458    pub fn is_schema(&self, path: &RepoPath) -> bool {
459        let state = self.state.borrow();
460        Self::listed(&state, path).is_some_and(|(kind, _)| kind == kind_code(FileKind::Schema))
461    }
462
463    /// `removed` returns the files that the walk no longer lists.
464    pub fn removed(&self) -> Vec<RepoPath> {
465        self.state.borrow().removed.clone()
466    }
467
468    /// `removed_set` returns the files that the walk no longer lists, as a
469    /// set.
470    pub(super) fn removed_set(&self) -> BTreeSet<RepoPath> {
471        self.state.borrow().removed.iter().cloned().collect()
472    }
473
474    /// `is_new` says whether the store had no row for `path` before this
475    /// run.
476    pub fn is_new(&self, path: &RepoPath) -> bool {
477        let state = self.state.borrow();
478        match state.known.get(path) {
479            Some(known) => known.is_none(),
480            None => Self::listed(&state, path).is_none(),
481        }
482    }
483
484    /// `pending_candidates` returns the candidate files that the walk lists.
485    /// The store doesn't have their stat. Each is paired with a flag that
486    /// says whether the store has no row for it yet. The documents that
487    /// include or link such a file count as changed, although the run
488    /// doesn't read the file (CACHE-1_AC-26). For a candidate that the run
489    /// read, such as an additional file, the hash decides instead whether
490    /// the file changed.
491    // sokf-implements: CACHE-1_AC-26
492    // sokf-implements: CACHE-1_AC-43
493    pub fn pending_candidates(&self) -> Vec<(RepoPath, bool)> {
494        let state = self.state.borrow();
495        state
496            .candidates
497            .keys()
498            .filter(|p| !state.observed.contains_key(*p))
499            .map(|p| (p.clone(), state.known.get(p).is_some_and(Option::is_none)))
500            .collect()
501    }
502
503    /// `is_walked` says whether the walk lists `path`.
504    pub fn is_walked(&self, path: &RepoPath) -> bool {
505        Self::listed(&self.state.borrow(), path).is_some()
506    }
507
508    /// `changed_set` returns the files that this run read and found
509    /// changed, as a set.
510    pub fn changed_set(&self) -> BTreeSet<RepoPath> {
511        self.changed().into_iter().collect()
512    }
513
514    /// `changed` returns the files that this run read and found changed, in
515    /// path order.
516    pub fn changed(&self) -> Vec<RepoPath> {
517        self.state
518            .borrow()
519            .observed
520            .iter()
521            .filter(|(_, s)| **s == FileState::Changed)
522            .map(|(p, _)| p.clone())
523            .collect()
524    }
525
526    /// `stats` returns the counts of the sync of this run, and of its work
527    /// against the store.
528    // sokf-implements: CACHE-3_AC-4
529    pub fn stats(&self) -> SyncStats {
530        let state = self.state.borrow();
531        SyncStats {
532            unchanged: state.unchanged,
533            read: state.observed.len(),
534            changed: state
535                .observed
536                .values()
537                .filter(|s| **s == FileState::Changed)
538                .count(),
539            removed: state.removed.len(),
540            queries: self.conn().count(),
541            // Every file that the run read is in `known` too, so the rows
542            // that the sync holds are the rows of `known`.
543            held: state.known.len(),
544        }
545    }
546
547    /// `commit` writes the result of the run in one transaction: the rows
548    /// of every walked file and of the directories, the deletion of the
549    /// rows of the removed files, the rows, outputs, and markers that the
550    /// run produced, and the sync time. A failure is silent, and the next
551    /// run reads the files again (CACHE-1_AC-9).
552    // sokf-implements: CACHE-1_AC-9
553    // sokf-implements: CACHE-1_AC-11
554    // sokf-implements: CACHE-4_AC-1
555    // sokf-implements: CACHE-4_AC-2
556    pub fn commit(&self) {
557        let _ = self.try_commit();
558    }
559
560    fn try_commit(&self) -> rusqlite::Result<()> {
561        let mut state = self.state.borrow_mut();
562        // The `files` row of a document records the hash of the stored row
563        // of that document. Before it writes, the commit copies the hash of
564        // each new document row into the row that the run built for the
565        // file of that document.
566        let SyncState { rows, walked, .. } = &mut *state;
567        for (path, row) in rows.iter() {
568            if let Some(w) = walked.get_mut(path) {
569                w.row_hash = Some(row.hash());
570            }
571        }
572        let conn = self.conn();
573        conn.execute_batch("BEGIN IMMEDIATE")?;
574        // Another run committed after this run synced, so this run's rows
575        // rest on a store that no longer exists. Writing them would pair a
576        // file's new stat with rows that another run derived, and no later
577        // stat would show the mismatch. The run writes nothing, and the
578        // next run reads what changed.
579        // sokf-implements: CACHE-4_AC-3
580        let next = state.generation + 1;
581        if generation(conn) != state.generation {
582            return conn.execute_batch("ROLLBACK");
583        }
584        state.generation = next;
585        let state = &*state;
586        let result = (|| {
587            let mut delete = conn.prepare("DELETE FROM files WHERE path = ?1")?;
588            for path in &state.removed {
589                delete.execute([path.as_str()])?;
590            }
591            let mut delete_dir = conn.prepare("DELETE FROM dirs WHERE path = ?1")?;
592            for path in &state.dirs_removed {
593                delete_dir.execute([path.as_str()])?;
594            }
595            let mut put_dir =
596                conn.prepare("INSERT OR REPLACE INTO dirs (path, root) VALUES (?1, ?2)")?;
597            for (path, root) in &state.dirs_added {
598                put_dir.execute(params![path.as_str(), *root])?;
599            }
600            let mut upsert = conn.prepare(
601                "INSERT OR REPLACE INTO files (path, kind, root, len, mtime, hash, row_hash) \
602                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
603            )?;
604            let mut put = |path: &RepoPath, row: &Row| {
605                upsert.execute(params![
606                    path.as_str(),
607                    row.kind,
608                    row.root,
609                    row.stat.len,
610                    row.stat.mtime,
611                    row.hash.map(u64::cast_signed),
612                    row.row_hash.map(u64::cast_signed),
613                ])
614            };
615            for (path, row) in &state.walked {
616                if state
617                    .known
618                    .get(path)
619                    .is_some_and(|k| k.as_ref() == Some(row))
620                {
621                    continue;
622                }
623                put(path, row)?;
624            }
625            // The row of a candidate that the run didn't read is its stat
626            // alone.
627            for (path, stat) in &state.candidates {
628                if state.walked.contains_key(path) {
629                    continue;
630                }
631                let row = Row {
632                    kind: kind_code(FileKind::Candidate),
633                    root: Self::listed(state, path).and_then(|(_, root)| root),
634                    stat: *stat,
635                    hash: None,
636                    row_hash: None,
637                };
638                put(path, &row)?;
639            }
640            Self::commit_rows(conn, state)?;
641            Self::commit_outputs(conn, state)?;
642            Self::commit_markers(conn, state)?;
643            Self::commit_plans(conn, state)?;
644            conn.put_meta("synced_at", &self.now())?;
645            conn.put_meta("generation", &next)?;
646            Ok::<(), rusqlite::Error>(())
647        })();
648        match result {
649            // The next run on this cache, such as the check after a fix,
650            // compares its files with this sync. A store in memory stays
651            // fresh, so that each run with `--no-cache` checks everything.
652            // sokf-implements: CACHE-1_AC-51
653            Ok(()) => conn.execute_batch("COMMIT").map(|()| {
654                if self.file().is_some() {
655                    self.set_synced_at(self.now());
656                }
657            }),
658            Err(e) => {
659                let _ = conn.execute_batch("ROLLBACK");
660                Err(e)
661            }
662        }
663    }
664
665    /// `outside_margin` says whether the modification time of a stat is
666    /// earlier than the last sync by at least `RACY_MARGIN`. A stat without
667    /// a modification time, or a store without a sync time, is never
668    /// outside the margin.
669    fn outside_margin(&self, stat: Stat) -> bool {
670        match (stat.mtime, self.synced_at()) {
671            (Some(mtime), Some(synced)) => mtime.saturating_add(RACY_MARGIN) <= synced,
672            _ => false,
673        }
674    }
675
676    /// `stored_hash` returns the hash of `path` in the store.
677    fn stored_hash(&self, path: &RepoPath) -> Option<u64> {
678        self.conn()
679            .query_row(
680                "SELECT hash FROM files WHERE path = ?1",
681                [path.as_str()],
682                |r| r.get::<_, Option<i64>>(0),
683            )
684            .ok()
685            .flatten()
686            .map(i64::cast_unsigned)
687    }
688}
689
690/// `row_of` reads a row of the `files` table from the columns `path, kind,
691/// root, len, mtime, hash, row_hash`.
692fn row_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<Row> {
693    Ok(Row {
694        kind: r.get::<_, u8>(1)?,
695        root: r.get::<_, Option<usize>>(2)?,
696        stat: Stat {
697            len: r.get::<_, u64>(3)?,
698            mtime: r.get::<_, Option<i64>>(4)?,
699        },
700        hash: r.get::<_, Option<i64>>(5)?.map(i64::cast_unsigned),
701        row_hash: r.get::<_, Option<i64>>(6)?.map(i64::cast_unsigned),
702    })
703}
704
705/// `kind_code` returns the code that the store keeps for a `FileKind`.
706fn kind_code(kind: FileKind) -> u8 {
707    match kind {
708        FileKind::Manifest => 0,
709        FileKind::Index => 1,
710        FileKind::Schema => 2,
711        FileKind::Document => 3,
712        FileKind::Candidate => 4,
713    }
714}
715
716/// `kind_of` returns the `FileKind` of a code in the store. For an unknown
717/// code, it returns `FileKind::Candidate`.
718pub(super) fn kind_of(code: u8) -> FileKind {
719    match code {
720        0 => FileKind::Manifest,
721        1 => FileKind::Index,
722        2 => FileKind::Schema,
723        3 => FileKind::Document,
724        _ => FileKind::Candidate,
725    }
726}
727
728/// `generation` returns the number of commits that the store records, or 0
729/// for a store that records none.
730fn generation(conn: &Conn) -> i64 {
731    conn.meta("generation").unwrap_or(0)
732}
733
734#[cfg(test)]
735mod tests;