Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 17.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! History queries answered with derived data: the history of paths, here,
5//! ancestry in [`ancestry`](crate::ancestry), and blame in
6//! [`blame`](crate::blame).
7//!
8//! A [`History`] reads objects, finds derived records through a
9//! [`DerivedIndex`], computes the values that are missing, stores them as
10//! records and remembers every value it used. It records the new records in
11//! the index by batches, and at the end when [`History::flush`] is called; a
12//! value computed and never recorded is only computed again later.
13//!
14//! # Changed paths
15//!
16//! The derived function `changed-paths`, version 1, of a changeset is its
17//! first parent and a Bloom filter (see `bloom.rs`) of the paths its change
18//! list names and of their parent directories:
19//!
20//! ```text
21//! u8 1 if there is a first parent, else 0
22//! [32] the first parent, if there is one
23//! uv the number of entries, then the filter's bytes
24//! ```
25//!
26//! It depends on the changeset alone, so the walk down a first-parent chain
27//! reads one small record per changeset, and reads a change list only when
28//! the filter says that the changeset may touch the path.
29
30use core::fmt;
31use std::collections::{HashMap, HashSet};
32use std::rc::Rc;
33
34use braid_format::codec::{Reader, put_id};
35use braid_format::{Change, ChangeOp, DecodeError, Kind, ObjectId, Objects};
36
37use crate::access::{read_changes, read_changeset};
38use crate::ancestry::GraphNode;
39use crate::blame::Runs;
40use crate::bloom::{Filter, PathHash};
41use crate::derived::{DerivedIndex, DerivedKey, encode_record, record_value};
42use crate::error::{Error, store_error};
43
44/// The derived function of changed-path records.
45const CHANGED_PATHS: &str = "changed-paths";
46
47/// The version of its encoding.
48const CHANGED_PATHS_VERSION: u64 = 1;
49
50/// New records are recorded in the index once this many wait.
51const RECORD_BATCH: usize = 4096;
52
53/// History queries over the objects of `O`, with the derived data found
54/// through `I`, computed when missing.
55///
56/// A `History` keeps every derived value it reads or computes in memory, so
57/// a query never reads the same value twice; drop it to free them. Call
58/// [`flush`](Self::flush) before dropping it to record the new values in the
59/// index.
60pub struct History<'o, O, I> {
61 pub(crate) objects: &'o O,
62 index: I,
63 /// Commit graph data, by changeset.
64 pub(crate) nodes: HashMap<ObjectId, Rc<GraphNode>>,
65 /// Changed-path records, by changeset.
66 paths: HashMap<ObjectId, Rc<ChangedPaths>>,
67 /// Blame records, by changeset and path.
68 pub(crate) blames: HashMap<(ObjectId, Vec<u8>), Rc<Runs>>,
69 /// Records stored and not recorded in the index yet.
70 pending: Vec<(DerivedKey, ObjectId)>,
71 /// Records this history computed and stored.
72 computed: u64,
73}
74
75impl<O, I> fmt::Debug for History<'_, O, I> {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.debug_struct("History")
78 .field("nodes", &self.nodes.len())
79 .field("paths", &self.paths.len())
80 .field("blames", &self.blames.len())
81 .field("pending", &self.pending.len())
82 .field("computed", &self.computed)
83 .finish_non_exhaustive()
84 }
85}
86
87/// What [`History::derive`] did.
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89pub struct DeriveReport {
90 /// Changesets reachable from the heads.
91 pub changesets: u64,
92 /// Records computed and stored; the others were there already.
93 pub computed: u64,
94}
95
96impl<'o, O: Objects, I: DerivedIndex> History<'o, O, I> {
97 /// A history over `objects`, finding and recording derived records
98 /// through `index`.
99 pub fn new(objects: &'o O, index: I) -> Self {
100 History {
101 objects,
102 index,
103 nodes: HashMap::new(),
104 paths: HashMap::new(),
105 blames: HashMap::new(),
106 pending: Vec::new(),
107 computed: 0,
108 }
109 }
110
111 /// The objects this history reads.
112 pub fn objects(&self) -> &'o O {
113 self.objects
114 }
115
116 /// How many derived records this history computed and stored.
117 pub fn computed(&self) -> u64 {
118 self.computed
119 }
120
121 /// Records in the index every record stored since the last flush.
122 pub fn flush(&mut self) -> Result<(), Error> {
123 if self.pending.is_empty() {
124 return Ok(());
125 }
126 self.index.record(&self.pending).map_err(store_error)?;
127 self.pending.clear();
128 Ok(())
129 }
130
131 /// The value of `key`, from its record, if the index knows the record
132 /// and `decode` accepts its value. Anything else is a miss.
133 pub(crate) fn load<T>(
134 &mut self,
135 key: &DerivedKey,
136 decode: impl FnOnce(&[u8]) -> Option<T>,
137 ) -> Result<Option<T>, Error> {
138 let Some(record) = self.index.find(key).map_err(store_error)? else {
139 return Ok(None);
140 };
141 let payload = match self.objects.get(&record).map_err(store_error)? {
142 Some((Kind::Derived, payload)) if ObjectId::hash(Kind::Derived, &payload) == record => {
143 payload
144 }
145 _ => return Ok(None),
146 };
147 Ok(record_value(key, &payload).and_then(decode))
148 }
149
150 /// Stores `value` as the record of `key`.
151 pub(crate) fn save(&mut self, key: DerivedKey, value: &[u8]) -> Result<(), Error> {
152 let record = self
153 .objects
154 .put(Kind::Derived, &encode_record(&key, value))
155 .map_err(store_error)?;
156 self.pending.push((key, record));
157 self.computed += 1;
158 if self.pending.len() >= RECORD_BATCH {
159 self.flush()?;
160 }
161 Ok(())
162 }
163
164 /// The changed-path record of a changeset.
165 pub(crate) fn changed_paths(&mut self, id: ObjectId) -> Result<Rc<ChangedPaths>, Error> {
166 if let Some(record) = self.paths.get(&id) {
167 return Ok(Rc::clone(record));
168 }
169 let key = DerivedKey::new(CHANGED_PATHS, CHANGED_PATHS_VERSION, &[id], b"");
170 let record = match self.load(&key, ChangedPaths::decode)? {
171 Some(record) => record,
172 None => {
173 let changeset = read_changeset(self.objects, id)?;
174 let changes = read_changes(self.objects, id, &changeset)?;
175 let record = ChangedPaths {
176 first_parent: changeset.parents.first().copied(),
177 filter: Filter::build(changes.iter().map(|change| change.path.as_slice())),
178 };
179 self.save(key, &record.encode())?;
180 record
181 }
182 };
183 let record = Rc::new(record);
184 self.paths.insert(id, Rc::clone(&record));
185 Ok(record)
186 }
187
188 /// The changesets on the first-parent chain of `head`, newest first,
189 /// whose change list touches one of `paths`: changes the path itself or
190 /// anything below it. At most `limit` of them.
191 ///
192 /// A path is given from the repository's root, without a leading or
193 /// trailing `/`; the empty path matches every changeset that changes
194 /// something. Like `git log --first-parent -- <path>`, a changeset counts
195 /// when it differs from its first parent there, and renames are not
196 /// followed.
197 ///
198 /// The walk reads one changed-path record per changeset, and the change
199 /// list of a changeset only when its filter may hold one of the paths: the
200 /// cost follows the length of the chain walked, in filter checks, plus the
201 /// changesets that touch the paths.
202 pub fn path_log(
203 &mut self,
204 head: ObjectId,
205 paths: &[&[u8]],
206 limit: usize,
207 ) -> Result<Vec<ObjectId>, Error> {
208 let wanted: Vec<(&[u8], PathHash)> = paths
209 .iter()
210 .map(|path| (*path, PathHash::of(path)))
211 .collect();
212 let mut found = Vec::new();
213 let mut next = Some(head);
214 while let Some(id) = next {
215 if found.len() >= limit {
216 break;
217 }
218 let record = self.changed_paths(id)?;
219 let maybe = wanted.iter().any(|(path, hash)| {
220 if path.is_empty() {
221 !record.filter.is_empty()
222 } else {
223 record.filter.may_contain(*hash)
224 }
225 });
226 if maybe {
227 let changeset = read_changeset(self.objects, id)?;
228 let changes = read_changes(self.objects, id, &changeset)?;
229 if wanted.iter().any(|(path, _)| touches(&changes, path)) {
230 found.push(id);
231 }
232 }
233 next = record.first_parent;
234 }
235 Ok(found)
236 }
237
238 /// The first changeset, from `from` down its first-parent chain, whose
239 /// change list names exactly `path`, with what it does there.
240 pub(crate) fn last_change(
241 &mut self,
242 from: Option<ObjectId>,
243 path: &[u8],
244 hash: PathHash,
245 ) -> Result<Option<(ObjectId, ChangeOp)>, Error> {
246 let mut next = from;
247 while let Some(id) = next {
248 let record = self.changed_paths(id)?;
249 if record.filter.may_contain(hash) {
250 let changeset = read_changeset(self.objects, id)?;
251 let changes = read_changes(self.objects, id, &changeset)?;
252 if let Ok(at) = changes.binary_search_by(|change| change.path.as_slice().cmp(path))
253 {
254 return Ok(Some((id, changes[at].op.clone())));
255 }
256 }
257 next = record.first_parent;
258 }
259 Ok(None)
260 }
261
262 /// Computes the derived data of every changeset reachable from `heads`
263 /// that is missing: commit graph data and changed-path records. Blame
264 /// records, per file, are computed when asked for. Records everything
265 /// in the index before returning.
266 pub fn derive(&mut self, heads: &[ObjectId]) -> Result<DeriveReport, Error> {
267 let before = self.computed;
268 let mut seen: HashSet<ObjectId> = HashSet::new();
269 let mut stack = heads.to_vec();
270 while let Some(id) = stack.pop() {
271 if !seen.insert(id) {
272 continue;
273 }
274 let node = self.node(id)?;
275 self.changed_paths(id)?;
276 stack.extend(node.parents.iter().filter(|parent| !seen.contains(*parent)));
277 }
278 self.flush()?;
279 Ok(DeriveReport {
280 changesets: seen.len() as u64,
281 computed: self.computed - before,
282 })
283 }
284}
285
286/// Whether a sorted change list touches `path`: names it, or a path below
287/// it. The empty path is touched by any change.
288pub(crate) fn touches(changes: &[Change], path: &[u8]) -> bool {
289 if path.is_empty() {
290 return !changes.is_empty();
291 }
292 if changes
293 .binary_search_by(|change| change.path.as_slice().cmp(path))
294 .is_ok()
295 {
296 return true;
297 }
298 // Paths below `path` sort together, from `path/` on.
299 let mut below = path.to_vec();
300 below.push(b'/');
301 let at = changes.partition_point(|change| change.path.as_slice() < below.as_slice());
302 changes
303 .get(at)
304 .is_some_and(|change| change.path.starts_with(&below))
305}
306
307/// The changed-path record of a changeset.
308#[derive(Clone, Debug, PartialEq, Eq)]
309pub(crate) struct ChangedPaths {
310 /// The first parent.
311 pub(crate) first_parent: Option<ObjectId>,
312 /// The filter of the paths the change list names, and their directories.
313 pub(crate) filter: Filter,
314}
315
316impl ChangedPaths {
317 fn encode(&self) -> Vec<u8> {
318 let mut out = Vec::new();
319 match &self.first_parent {
320 Some(parent) => {
321 out.push(1);
322 put_id(&mut out, parent);
323 }
324 None => out.push(0),
325 }
326 self.filter.encode(&mut out);
327 out
328 }
329
330 fn decode(value: &[u8]) -> Option<ChangedPaths> {
331 let read = || -> Result<ChangedPaths, DecodeError> {
332 let mut reader = Reader::new(value);
333 let at = reader.position();
334 let first_parent = match reader.u8()? {
335 0 => None,
336 1 => Some(reader.id()?),
337 _ => {
338 return Err(DecodeError::Invalid {
339 at,
340 what: "first parent flag",
341 });
342 }
343 };
344 let filter = Filter::decode(&mut reader)?;
345 reader.finish()?;
346 Ok(ChangedPaths {
347 first_parent,
348 filter,
349 })
350 };
351 read().ok()
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358 use crate::derived::MemoryIndex;
359 use crate::testing::{Repo, delete};
360
361 fn log(repo: &Repo, head: ObjectId, path: &str) -> Vec<ObjectId> {
362 let index = MemoryIndex::new();
363 let mut history = History::new(&repo.objects, &index);
364 history
365 .path_log(head, &[path.as_bytes()], usize::MAX)
366 .unwrap()
367 }
368
369 #[test]
370 fn touching_is_by_path_or_below_it() {
371 let repo = Repo::new();
372 let changes = vec![
373 repo.set("a", "1"),
374 repo.set("a-b/c", "2"),
375 repo.set("a.txt", "3"),
376 repo.set("a/x/y", "4"),
377 repo.set("b", "5"),
378 ];
379 for (path, expected) in [
380 ("a", true),
381 ("a/x", true),
382 ("a/x/y", true),
383 ("a/y", false),
384 ("a-b", true),
385 ("a-", false),
386 ("b", true),
387 ("c", false),
388 ("", true),
389 ] {
390 assert_eq!(touches(&changes, path.as_bytes()), expected, "{path}");
391 }
392 assert!(!touches(&[], b""));
393 assert!(!touches(&[repo.set("ab", "1")], b"a"));
394 }
395
396 #[test]
397 fn records_round_trip() {
398 let parent = ObjectId::hash(Kind::Changeset, b"p");
399 for record in [
400 ChangedPaths {
401 first_parent: Some(parent),
402 filter: Filter::build([&b"a/b"[..]]),
403 },
404 ChangedPaths {
405 first_parent: None,
406 filter: Filter::Empty,
407 },
408 ] {
409 assert_eq!(ChangedPaths::decode(&record.encode()), Some(record));
410 }
411 assert_eq!(ChangedPaths::decode(&[2, 0]), None);
412 assert_eq!(ChangedPaths::decode(&[0, 0, 0]), None);
413 }
414
415 #[test]
416 fn the_log_of_a_path_follows_first_parents() {
417 let repo = Repo::new();
418 let root = repo.commit(&[], vec![repo.set("a/f", "1"), repo.set("b", "1")]);
419 let edit = repo.commit(&[root], vec![repo.set("a/f", "2")]);
420 let other = repo.commit(&[edit], vec![repo.set("b", "2")]);
421 // A side branch changes a/g; the merge brings it to the first
422 // parent's history, so the merge touches a.
423 let side = repo.commit(&[root], vec![repo.set("a/g", "1")]);
424 let merge = repo.commit(&[other, side], vec![repo.set("a/g", "1")]);
425 let gone = repo.commit(&[merge], vec![delete("a/f")]);
426 let empty = repo.commit(&[gone], Vec::new());
427 let back = repo.commit(&[empty], vec![repo.set("a/f", "3")]);
428
429 assert_eq!(log(&repo, back, "a/f"), [back, gone, edit, root]);
430 assert_eq!(log(&repo, back, "a/g"), [merge]);
431 assert_eq!(log(&repo, back, "a"), [back, gone, merge, edit, root]);
432 assert_eq!(log(&repo, back, "b"), [other, root]);
433 assert_eq!(log(&repo, back, "a/f/x"), []);
434 assert_eq!(log(&repo, back, "c"), []);
435 assert_eq!(log(&repo, back, ""), [back, gone, merge, other, edit, root]);
436 // The side branch is not on the first-parent chain.
437 assert_eq!(log(&repo, side, "a/g"), [side]);
438
439 let index = MemoryIndex::new();
440 let mut history = History::new(&repo.objects, &index);
441 assert_eq!(
442 history.path_log(back, &[b"b", b"a/g"], usize::MAX).unwrap(),
443 [merge, other, root]
444 );
445 assert_eq!(history.path_log(back, &[b"a"], 2).unwrap(), [back, gone]);
446 assert_eq!(history.path_log(back, &[b"a"], 0).unwrap(), []);
447 assert_eq!(
448 history
449 .last_change(Some(back), b"a/f", PathHash::of(b"a/f"))
450 .unwrap()
451 .map(|(id, _)| id),
452 Some(back)
453 );
454 assert_eq!(
455 history
456 .last_change(Some(empty), b"a/f", PathHash::of(b"a/f"))
457 .unwrap(),
458 Some((gone, ChangeOp::Delete))
459 );
460 }
461
462 #[test]
463 fn records_are_stored_once_and_reused() {
464 let repo = Repo::new();
465 let root = repo.commit(&[], vec![repo.set("f", "1")]);
466 let head = repo.commit(&[root], vec![repo.set("f", "2")]);
467 let index = MemoryIndex::new();
468 let mut first = History::new(&repo.objects, &index);
469 assert_eq!(first.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
470 assert_eq!(first.computed(), 2);
471 // Not in the index until flushed.
472 assert!(index.is_empty());
473 first.flush().unwrap();
474 assert_eq!(index.len(), 2);
475
476 let mut second = History::new(&repo.objects, &index);
477 assert_eq!(second.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
478 assert_eq!(second.computed(), 0);
479
480 // A record that is gone, or another value under the key, is computed
481 // again.
482 let key = DerivedKey::new(CHANGED_PATHS, CHANGED_PATHS_VERSION, &[head], b"");
483 let elsewhere = repo.objects.put(Kind::Derived, b"not a record").unwrap();
484 index
485 .record(&[(key, ObjectId::hash(Kind::Derived, b"gone"))])
486 .unwrap();
487 let mut third = History::new(&repo.objects, &index);
488 assert_eq!(third.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
489 assert_eq!(third.computed(), 1);
490 index.record(&[(key, elsewhere)]).unwrap();
491 let mut fourth = History::new(&repo.objects, &index);
492 assert_eq!(fourth.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
493 assert_eq!(fourth.computed(), 1);
494 }
495}