interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-api / src / advisory.rs

1265 lines · 49668 bytes Raw Blame History
1//! Pre-submit Crumb and claim advisory for changesets (ADR 0004, deliverable D3).
2//!
3//! For each path a changeset would mutate, report the Directory Crumb context of the path
4//! at the base snapshot, unexpired claims held by other agents in the shared coordination
5//! plane, overlapping open proposals, open proposals that rewrite a `.crumb` in the path's
6//! chain, the context's invariants as guidance, and whether the `.crumb` chain changed
7//! between the base and both the newest visible changeset and the canonical head.
8//!
9//! Advisory only. Nothing here blocks, authorizes, or writes: one `Capability::Read`
10//! authorization (with its audit entry), reads through `materialize_virtual_tree` and
11//! `read_blob_bytes`, and a read-only `CoordStore::sniff` (no lock taken, nothing written).
12//! Synapse source conflicts at submit stay the only hard refusal.
13
14use crate::tree::ALLOC_OVERHEAD_BYTES;
15use crate::{is_file_dir_prefix_collision, SynapseService, TreeTarget, VirtualTreeEntry};
16use serde::{Deserialize, Serialize};
17use std::collections::{BTreeMap, BTreeSet, VecDeque};
18use std::mem::size_of;
19use std::sync::Arc;
20use synapse_auth::{AuthenticatedRequest, BoundaryKind, Capability};
21use synapse_coord::{CoordStore, Holder, LockView, PathOracle, Workspace};
22use synapse_core::{
23 validate_repo_relative_path, ChangesetId, RefusalCode, SynapseError, SynapseResult, TreeDigest,
24 WalSeq,
25};
26use synapse_crumb::{CrumbContext, CrumbContextDigest, ROOT_DIR};
27
28/// Most paths one advisory request may name. More is refused with `QuotaTooManyPaths`.
29pub const MAX_ADVISORY_PATHS: usize = 256;
30
31/// Workspace label used for the read-only coordination query. It never matches a real
32/// worktree, so it only affects `Sniff::other_workspaces`, which the advisory ignores.
33const ADVISORY_WORKSPACE: &str = "/synapse/advisory";
34
35/// Request payload for [`SynapseService::changeset_advisory`].
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct ChangesetAdvisoryPayload {
38 /// Snapshot the changeset would be built on.
39 pub base: TreeTarget,
40 /// Snapshot to compare `.crumb` chains against. `None`: the most recently committed
41 /// visible changeset (promoted or not). The canonical head is compared separately.
42 pub latest: Option<TreeTarget>,
43 /// Repository-relative paths the changeset would mutate (at most [`MAX_ADVISORY_PATHS`]).
44 pub paths: Vec<String>,
45 /// The caller's agent name in the coordination plane. Its own claims are not reported.
46 /// Self-declared: it can only hide claims from the caller's own report.
47 pub agent: String,
48 pub snapshot_seq: Option<WalSeq>,
49}
50
51/// Whether the shared coordination plane was consulted.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum CoordinationStatus {
54 /// No `CoordStore` was supplied; claims are not reported.
55 NotSupplied,
56 Read,
57 /// The store could not be read; claims are not reported. The advisory still answers.
58 Unavailable {
59 reason: String,
60 },
61}
62
63/// Whether the `.crumb` chain of a path's directory differs between base and latest.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum Staleness {
66 /// Same chain digest at base and latest (or base is the latest snapshot).
67 Current,
68 /// The chain changed after the base: the context below may be out of date.
69 Stale { latest_digest: CrumbContextDigest },
70 /// No latest snapshot to compare with.
71 Unknown,
72}
73
74/// One invariant, surfaced as guidance. Nothing enforces it (ADR 0004 section 2.2).
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct GuidanceNote {
77 /// Directory whose `.crumb` states the invariant.
78 pub dir: String,
79 pub text: String,
80}
81
82/// A visible changeset outside the base and canonical lineages that touches the path.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct OverlappingProposal {
85 pub changeset_id: ChangesetId,
86 pub author_did: String,
87 pub committed_seq: WalSeq,
88 /// The proposal's mutated path that overlaps (same path, or file/directory collision).
89 pub mutated_path: String,
90}
91
92/// Advisory for one mutated path.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct PathAdvisory {
95 pub path: String,
96 /// Context of the path's directory at the base snapshot.
97 pub context: CrumbContext,
98 pub digest: CrumbContextDigest,
99 /// Unexpired claims by other agents on the path or a directory containing it.
100 pub claims: Vec<LockView>,
101 pub overlapping_proposals: Vec<OverlappingProposal>,
102 /// Open proposals that change a `.crumb` in the path's chain (the path's directory or
103 /// any ancestor), whether or not they touch the path. Each also adds a guidance note.
104 pub pending_crumb_changes: Vec<OverlappingProposal>,
105 /// Invariants of the nearest crumb, then inherited ones (closest ancestor first).
106 /// Then one note per entry of `pending_crumb_changes`.
107 pub guidance: Vec<GuidanceNote>,
108 /// Base chain against `compared_to`.
109 pub staleness: Staleness,
110 /// Base chain against the canonical head (`Unknown` unless `canonical` is `Promoted`).
111 pub canonical_staleness: Staleness,
112}
113
114/// The canonical head the advisory compared against.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum CanonicalStatus {
117 /// No canonical head, or its promoted changeset is not visible at the snapshot.
118 NoHead,
119 /// The changeset the canonical head promotes.
120 Promoted(TreeTarget),
121 /// `snapshot_seq` is older than the committed state. The store keeps only the current
122 /// head, so the head at that snapshot is not known and is not used.
123 NotAtSnapshot,
124}
125
126/// Result of [`SynapseService::changeset_advisory`]. Grants nothing.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct ChangesetAdvisory {
129 /// Snapshot the staleness check compared against (`None`: nothing to compare with).
130 pub compared_to: Option<TreeTarget>,
131 /// Canonical head used for `canonical_staleness` and to settle its lineage.
132 pub canonical: CanonicalStatus,
133 pub coordination: CoordinationStatus,
134 /// One entry per requested path, in request order.
135 pub paths: Vec<PathAdvisory>,
136}
137
138/// Most materialized snapshots one service keeps for advisory and Crumb reads.
139pub const SNAPSHOT_VIEW_CACHE_ENTRIES: usize = 4;
140
141/// The view cache may keep at most `max_bytes / SNAPSHOT_VIEW_CACHE_SHARE` accounted bytes,
142/// where `max_bytes` is the service's configured tree cache bound ([`crate::TreeCacheConfig`]).
143/// A view larger than that is built for the call and not kept.
144pub const SNAPSHOT_VIEW_CACHE_SHARE: usize = 4;
145
146/// A materialized snapshot shared by the advisory and Crumb reads of one service (issue #94):
147/// the virtual tree, and the set of its paths plus every ancestor directory. Keyed by the
148/// snapshot's [`TreeDigest`], which binds every path, mode, blob digest and size of the tree
149/// (the Git blob OID is a function of the blob content), so a view is never stale: a
150/// different tree has a different key. Visibility of the target at the requested
151/// `snapshot_seq` is still checked on every call by resolving the digest.
152pub(crate) struct SnapshotView {
153 tree: BTreeMap<String, VirtualTreeEntry>,
154 paths: BTreeSet<String>,
155 /// Accounted heap bytes, see [`view_bytes`].
156 bytes: usize,
157}
158
159impl SnapshotView {
160 fn new(tree: BTreeMap<String, VirtualTreeEntry>) -> Self {
161 let mut paths = BTreeSet::new();
162 for path in tree.keys() {
163 let mut p = path.as_str();
164 paths.insert(p.to_string());
165 while let Some((parent, _)) = p.rsplit_once('/') {
166 if !paths.insert(parent.to_string()) {
167 break;
168 }
169 p = parent;
170 }
171 }
172 let bytes = view_bytes(&tree, &paths);
173 Self { tree, paths, bytes }
174 }
175
176 pub(crate) fn tree(&self) -> &BTreeMap<String, VirtualTreeEntry> {
177 &self.tree
178 }
179
180 /// Every path of the tree plus its ancestor directories.
181 fn paths(&self) -> &BTreeSet<String> {
182 &self.paths
183 }
184}
185
186/// Accounted heap bytes of a view's tree map and path set: every string's text plus its
187/// allocation, and every B-tree slot charged at 11/5 of its size (std B-tree nodes hold 11
188/// entries and, except the root, at least 5) plus a node-header share. An estimate in the
189/// style of [`crate::TreeNode::heap_bytes`], not a measurement.
190fn view_bytes(tree: &BTreeMap<String, VirtualTreeEntry>, paths: &BTreeSet<String>) -> usize {
191 const NODE_SHARE: usize = 8;
192 let text = |s: &str| s.len() + ALLOC_OVERHEAD_BYTES;
193 let tree_slot = (size_of::<(String, VirtualTreeEntry)>() + NODE_SHARE) * 11 / 5;
194 let path_slot = (size_of::<String>() + NODE_SHARE) * 11 / 5;
195 let arc = 2 * size_of::<usize>() + size_of::<SnapshotView>() + ALLOC_OVERHEAD_BYTES;
196 let tree_bytes: usize = tree
197 .iter()
198 .map(|(k, e)| tree_slot + text(k) + text(&e.path))
199 .sum();
200 let path_bytes: usize = paths.iter().map(|p| path_slot + text(p)).sum();
201 arc + tree_bytes + path_bytes
202}
203
204/// The snapshot views one [`SynapseService`] keeps: at most [`SNAPSHOT_VIEW_CACHE_ENTRIES`]
205/// views and at most its byte budget (a share of the tree cache bound), oldest evicted
206/// first. A field of the service, so it is freed with it and never shared between services.
207/// Which calls hit depends on this service's earlier reads; the answers do not, since a view
208/// is a pure function of its key.
209#[derive(Default)]
210pub(crate) struct SnapshotViewCache {
211 /// Oldest first.
212 entries: VecDeque<(TreeDigest, Arc<SnapshotView>)>,
213 /// Sum of the kept views' accounted bytes.
214 bytes: usize,
215 /// Trees materialized for a view (cache misses).
216 builds: u64,
217}
218
219impl SnapshotViewCache {
220 fn get(&self, root: TreeDigest) -> Option<Arc<SnapshotView>> {
221 self.entries
222 .iter()
223 .find(|(d, _)| *d == root)
224 .map(|(_, v)| Arc::clone(v))
225 }
226
227 /// Keep `view` if it fits `budget`, evicting the oldest views to make room.
228 fn insert(&mut self, root: TreeDigest, view: &Arc<SnapshotView>, budget: usize) {
229 if view.bytes > budget {
230 return;
231 }
232 while self.entries.len() >= SNAPSHOT_VIEW_CACHE_ENTRIES || self.bytes + view.bytes > budget
233 {
234 let Some((_, old)) = self.entries.pop_front() else {
235 break;
236 };
237 self.bytes -= old.bytes;
238 }
239 self.bytes += view.bytes;
240 self.entries.push_back((root, Arc::clone(view)));
241 }
242
243 /// Drop every view (the tree cache bound changed).
244 pub(crate) fn clear(&mut self) {
245 self.entries.clear();
246 self.bytes = 0;
247 }
248}
249
250/// Test view of the snapshot view cache.
251#[cfg(test)]
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub(crate) struct SnapshotViewStats {
254 pub entries: usize,
255 pub bytes: usize,
256 pub budget: usize,
257 pub builds: u64,
258}
259
260#[cfg(test)]
261impl SynapseService {
262 pub(crate) fn snapshot_view_stats(&self) -> SnapshotViewStats {
263 let c = &self.snapshot_views;
264 assert_eq!(
265 c.bytes,
266 c.entries.iter().map(|(_, v)| v.bytes).sum::<usize>()
267 );
268 SnapshotViewStats {
269 entries: c.entries.len(),
270 bytes: c.bytes,
271 budget: self.snapshot_view_budget(),
272 builds: c.builds,
273 }
274 }
275
276 /// Weak handles to the views this service keeps.
277 pub(crate) fn snapshot_view_handles(&self) -> Vec<std::sync::Weak<SnapshotView>> {
278 self.snapshot_views
279 .entries
280 .iter()
281 .map(|(_, v)| Arc::downgrade(v))
282 .collect()
283 }
284}
285
286impl SynapseService {
287 /// Byte budget of the view cache: [`SNAPSHOT_VIEW_CACHE_SHARE`] of the tree cache bound.
288 fn snapshot_view_budget(&self) -> usize {
289 self.tree_store().config().max_bytes / SNAPSHOT_VIEW_CACHE_SHARE
290 }
291
292 /// The materialized `target` at `snapshot_seq`: from this service's view cache when the
293 /// same tree was materialized before, else built once with `materialize_virtual_tree`.
294 /// Same tree, same errors: the digest lookup runs the same visibility checks.
295 pub(crate) fn snapshot_view(
296 &mut self,
297 target: TreeTarget,
298 snapshot_seq: Option<WalSeq>,
299 ) -> SynapseResult<Arc<SnapshotView>> {
300 let root = self.tree_digest(target, snapshot_seq)?;
301 if let Some(view) = self.snapshot_views.get(root) {
302 return Ok(view);
303 }
304 let view = Arc::new(SnapshotView::new(
305 self.materialize_virtual_tree(target, snapshot_seq)?,
306 ));
307 let budget = self.snapshot_view_budget();
308 self.snapshot_views.builds += 1;
309 self.snapshot_views.insert(root, &view, budget);
310 Ok(view)
311 }
312}
313
314/// Answers `exists` from a snapshot (files and their ancestor directories), so claim keys
315/// resolve the way `crumb.c` resolves them against a checkout.
316struct SnapshotOracle(Arc<SnapshotView>);
317
318impl PathOracle for SnapshotOracle {
319 fn exists(&self, rel: &str) -> bool {
320 self.0.paths().contains(rel)
321 }
322}
323
324impl SynapseService {
325 /// Pre-submit advisory for the paths a changeset would mutate (`Capability::Read`).
326 ///
327 /// `coord` is the shared coordination plane to read claims from; `None` skips claims.
328 /// Refuses more than [`MAX_ADVISORY_PATHS`] paths (`QuotaTooManyPaths`), invalid paths
329 /// (`PathInvalid`) and repeated paths (`PathDuplicate`). A path absent from the base is
330 /// allowed (a new file) and gets the context of its parent directory.
331 pub fn changeset_advisory(
332 &mut self,
333 req: &AuthenticatedRequest<ChangesetAdvisoryPayload>,
334 coord: Option<&CoordStore>,
335 now_ms: u64,
336 ) -> SynapseResult<ChangesetAdvisory> {
337 self.auth.authorize(
338 BoundaryKind::Api,
339 "changeset_advisory",
340 &self.repo_id,
341 Capability::Read,
342 req,
343 now_ms,
344 )?;
345 let payload = &req.payload;
346 if payload.paths.len() > MAX_ADVISORY_PATHS {
347 return Err(SynapseError::new(
348 RefusalCode::QuotaTooManyPaths,
349 format!(
350 "advisory names {} paths, more than {MAX_ADVISORY_PATHS}",
351 payload.paths.len()
352 ),
353 ));
354 }
355 let mut seen = BTreeSet::new();
356 for p in &payload.paths {
357 validate_repo_relative_path(p)?;
358 if !seen.insert(p.as_str()) {
359 return Err(SynapseError::new(
360 RefusalCode::PathDuplicate,
361 format!("path {p} named twice"),
362 ));
363 }
364 }
365
366 // Pin one snapshot so every read below sees the same state.
367 let committed = self.store.committed_seq();
368 let snap = Some(payload.snapshot_seq.unwrap_or(committed));
369 let visible = self
370 .store
371 .list_changesets(Some(&self.repo_id), None, snap)?;
372 // The store keeps only the current canonical head, with no history, so it is the
373 // head at the pinned snapshot only when that snapshot is the committed state.
374 let canonical = if snap == Some(committed) {
375 match self
376 .store
377 .canonical_head(&self.repo_id)
378 .and_then(|h| h.promoted_changeset_id)
379 .filter(|id| visible.iter().any(|cs| cs.changeset_id == *id))
380 {
381 Some(id) => CanonicalStatus::Promoted(TreeTarget::Changeset(id)),
382 None => CanonicalStatus::NoHead,
383 }
384 } else {
385 CanonicalStatus::NotAtSnapshot
386 };
387 let promoted = match canonical {
388 CanonicalStatus::Promoted(TreeTarget::Changeset(id)) => Some(id),
389 _ => None,
390 };
391
392 let base_view = self.snapshot_view(payload.base, snap)?;
393 let base_tree = base_view.tree();
394 let compared_to = payload.latest.or_else(|| {
395 visible
396 .last()
397 .map(|cs| TreeTarget::Changeset(cs.changeset_id))
398 });
399 let latest_tree = match compared_to {
400 Some(t) if t != payload.base => Some(self.snapshot_view(t, snap)?),
401 _ => None,
402 };
403 let canonical_tree = match canonical {
404 CanonicalStatus::Promoted(t) if t != payload.base && Some(t) != compared_to => {
405 Some(self.snapshot_view(t, snap)?)
406 }
407 _ => None,
408 };
409
410 // Changesets already in the base snapshot or the canonical lineage are not open.
411 let mut settled = BTreeSet::new();
412 if let TreeTarget::Changeset(id) = payload.base {
413 self.collect_lineage(id, snap, &mut settled)?;
414 }
415 if let Some(id) = promoted {
416 self.collect_lineage(id, snap, &mut settled)?;
417 }
418 let open: Vec<_> = visible
419 .iter()
420 .filter(|cs| !settled.contains(&cs.changeset_id))
421 .collect();
422
423 // One oracle over the base snapshot serves the store query and the claim keys.
424 let oracle_ws = Workspace::with_oracle(
425 ADVISORY_WORKSPACE,
426 Holder::default(),
427 Box::new(SnapshotOracle(Arc::clone(&base_view))),
428 );
429 let (coordination, locks) = match coord {
430 None => (CoordinationStatus::NotSupplied, Vec::new()),
431 Some(store) => match store.sniff(&oracle_ws, &payload.agent, ROOT_DIR) {
432 // A lock record without a holder is malformed; it names no one to ask.
433 Ok(s) => (
434 CoordinationStatus::Read,
435 s.locks
436 .into_iter()
437 .filter(|l| !l.holder.is_empty())
438 .collect(),
439 ),
440 Err(e) => (
441 CoordinationStatus::Unavailable {
442 reason: e.to_string(),
443 },
444 Vec::new(),
445 ),
446 },
447 };
448
449 let mut out = Vec::with_capacity(payload.paths.len());
450 for path in &payload.paths {
451 let dir = context_dir(base_tree, path);
452 let context = self.resolve_crumb_context(base_tree, &dir, snap)?;
453 let digest = context.digest();
454 let staleness = match (&compared_to, &latest_tree) {
455 (None, _) => Staleness::Unknown,
456 (Some(_), None) => Staleness::Current,
457 (Some(_), Some(lt)) => self.staleness_against(lt.tree(), &dir, digest, snap)?,
458 };
459 let canonical_staleness = match canonical {
460 CanonicalStatus::Promoted(t) if t == payload.base => Staleness::Current,
461 CanonicalStatus::Promoted(_) => match &canonical_tree {
462 Some(ct) => self.staleness_against(ct.tree(), &dir, digest, snap)?,
463 // The canonical changeset is `compared_to`: same answer.
464 None => staleness.clone(),
465 },
466 _ => Staleness::Unknown,
467 };
468
469 // Same key rule as `crumb claim` from the repository root.
470 let key = oracle_ws
471 .target_key(path, ROOT_DIR)
472 .map_err(|e| SynapseError::new(RefusalCode::PathInvalid, e.to_string()))?;
473 let claims = locks
474 .iter()
475 .filter(|l| l.holder != payload.agent && claim_covers(&l.key, &key))
476 .cloned()
477 .collect();
478
479 let overlapping_proposals = open_mutations(&open, |m| {
480 m == path || is_file_dir_prefix_collision(m, path)
481 });
482 let chain = crumb_chain(&dir);
483 let pending_crumb_changes = open_mutations(&open, |m| chain.contains(m));
484
485 let mut guidance = guidance_notes(&context);
486 guidance.extend(pending_crumb_changes.iter().map(|p| {
487 GuidanceNote {
488 dir: p
489 .mutated_path
490 .rsplit_once('/')
491 .map_or(ROOT_DIR, |(d, _)| d)
492 .to_string(),
493 text: format!(
494 "open proposal {} changes {}; this guidance may change",
495 p.changeset_id, p.mutated_path
496 ),
497 }
498 }));
499 out.push(PathAdvisory {
500 path: path.clone(),
501 context,
502 digest,
503 claims,
504 overlapping_proposals,
505 pending_crumb_changes,
506 guidance,
507 staleness,
508 canonical_staleness,
509 });
510 }
511 Ok(ChangesetAdvisory {
512 compared_to,
513 canonical,
514 coordination,
515 paths: out,
516 })
517 }
518
519 /// Compare `digest` (the base context of `dir`) with the context of `dir` in `tree`.
520 fn staleness_against(
521 &self,
522 tree: &BTreeMap<String, VirtualTreeEntry>,
523 dir: &str,
524 digest: CrumbContextDigest,
525 snap: Option<WalSeq>,
526 ) -> SynapseResult<Staleness> {
527 let latest_digest = self.resolve_crumb_context(tree, dir, snap)?.digest();
528 Ok(if latest_digest == digest {
529 Staleness::Current
530 } else {
531 Staleness::Stale { latest_digest }
532 })
533 }
534
535 /// Add `start` and every changeset it transitively builds on to `out`.
536 fn collect_lineage(
537 &self,
538 start: ChangesetId,
539 snap: Option<WalSeq>,
540 out: &mut BTreeSet<ChangesetId>,
541 ) -> SynapseResult<()> {
542 let mut stack = vec![start];
543 while let Some(id) = stack.pop() {
544 if out.insert(id) {
545 let cs = self
546 .store
547 .get_changeset_in_repo(&self.repo_id, id, None, snap)?;
548 stack.extend(cs.envelope.parent_changesets.iter().copied());
549 }
550 }
551 Ok(())
552 }
553}
554
555/// Directory whose context applies: the path if it is a directory in `tree`, else its
556/// parent (a file, or a path the changeset would create).
557fn context_dir(tree: &BTreeMap<String, VirtualTreeEntry>, path: &str) -> String {
558 let prefix = format!("{path}/");
559 let is_dir = tree
560 .range(prefix.clone()..)
561 .next()
562 .is_some_and(|(k, _)| k.starts_with(&prefix));
563 if is_dir {
564 return path.to_string();
565 }
566 path.rsplit_once('/')
567 .map_or(ROOT_DIR.to_string(), |(parent, _)| parent.to_string())
568}
569
570/// A claim on `lock_key` covers `key` when it names the same path or a directory above it.
571fn claim_covers(lock_key: &str, key: &str) -> bool {
572 lock_key == ROOT_DIR
573 || lock_key == key
574 || key
575 .strip_prefix(lock_key)
576 .is_some_and(|rest| rest.starts_with('/'))
577}
578
579/// Every open proposal mutation whose path satisfies `hit`, in commit order.
580fn open_mutations(
581 open: &[&synapse_store::StoredChangeset],
582 hit: impl Fn(&str) -> bool,
583) -> Vec<OverlappingProposal> {
584 open.iter()
585 .flat_map(|cs| {
586 cs.envelope
587 .mutations
588 .iter()
589 .filter(|m| hit(&m.path))
590 .map(move |m| OverlappingProposal {
591 changeset_id: cs.changeset_id,
592 author_did: cs.envelope.author_did.clone(),
593 committed_seq: cs.committed_seq,
594 mutated_path: m.path.clone(),
595 })
596 })
597 .collect()
598}
599
600/// The `.crumb` paths of `dir` and every directory above it, root included.
601fn crumb_chain(dir: &str) -> BTreeSet<String> {
602 let mut out = BTreeSet::from([".crumb".to_string()]);
603 let mut d = dir;
604 while d != ROOT_DIR && !d.is_empty() {
605 out.insert(format!("{d}/.crumb"));
606 d = d.rsplit_once('/').map_or(ROOT_DIR, |(p, _)| p);
607 }
608 out
609}
610
611fn guidance_notes(context: &CrumbContext) -> Vec<GuidanceNote> {
612 let own = context.nearest().and_then(|e| {
613 e.crumb().map(|c| {
614 c.invariants()
615 .iter()
616 .map(move |i| (e.dir.as_str(), i.as_str()))
617 })
618 });
619 own.into_iter()
620 .flatten()
621 .chain(context.inherited_invariants())
622 .map(|(dir, text)| GuidanceNote {
623 dir: dir.to_string(),
624 text: text.to_string(),
625 })
626 .collect()
627}
628
629#[cfg(test)]
630mod tests {
631 use super::*;
632 use crate::{FsyncPolicy, RecoveryPolicy, StoreLimits, SubmitChangesetPayload};
633 use ed25519_dalek::SigningKey;
634 use std::fs;
635 use std::path::PathBuf;
636 use synapse_auth::AgentCapabilityGrant;
637 use synapse_coord::{ClaimOutcome, NoOracle};
638 use synapse_core::{
639 encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, FileMode, GitOid, IdempotencyKey,
640 MutationOp, PathMutation, RepoId, SYNAPSE_ENVELOPE_VERSION,
641 };
642 use synapse_store::IngestOutcome;
643
644 const ROOT: &[u8] =
645 br#"{"schema_version":"1.0.0","name":"root","purpose":"Root.","invariants":["root rule"]}"#;
646 const SRC: &[u8] = br#"{"schema_version":"1.0.0","name":"src","purpose":"Sources.","invariants":["src rule"]}"#;
647 const T0: i64 = 1_800_000_000;
648
649 struct Fixture {
650 svc: SynapseService,
651 auth: SigningKey,
652 repo: RepoId,
653 nonce: u8,
654 dir: PathBuf,
655 base: TreeTarget,
656 }
657
658 impl Fixture {
659 fn new(label: &str) -> Self {
660 let dir = std::env::temp_dir().join(format!(
661 "synapse-api-advisory-{label}-{}-{}",
662 std::process::id(),
663 std::time::SystemTime::now()
664 .duration_since(std::time::UNIX_EPOCH)
665 .unwrap()
666 .as_nanos()
667 ));
668 let repo = RepoId::new("aien-spark/synapse").unwrap();
669 let mut svc = SynapseService::open(
670 dir.join("svc"),
671 repo.clone(),
672 FsyncPolicy::EveryCommit,
673 RecoveryPolicy::StrictFailClosed,
674 StoreLimits::default(),
675 )
676 .unwrap();
677 let auth = SigningKey::from_bytes(&[10u8; 32]);
678 svc.register_authority(encode_did_key_ed25519(&auth.verifying_key().to_bytes()));
679 let oid = GitOid([1; 20]);
680 let files = [
681 (".crumb", ROOT),
682 ("src/.crumb", SRC),
683 ("src/a.rs", b"fn a() {}\n".as_slice()),
684 ("src/b.rs", b"fn b() {}\n".as_slice()),
685 ("docs/x.md", b"# x\n".as_slice()),
686 ];
687 svc.register_base_tree(
688 oid,
689 files
690 .iter()
691 .map(|(p, b)| (p.to_string(), FileMode::Regular644, b.to_vec()))
692 .collect(),
693 )
694 .unwrap();
695 Self {
696 svc,
697 auth,
698 repo,
699 nonce: 0,
700 dir,
701 base: TreeTarget::BaseGitCommit(oid),
702 }
703 }
704
705 fn grant(&mut self, agent: &SigningKey, caps: Vec<Capability>) -> AgentCapabilityGrant {
706 self.nonce += 1;
707 AgentCapabilityGrant::issue(
708 &self.auth,
709 [self.nonce; 32],
710 self.repo.clone(),
711 encode_did_key_ed25519(&agent.verifying_key().to_bytes()),
712 caps,
713 1024 * 1024,
714 100,
715 60_000,
716 10,
717 100_000,
718 )
719 }
720
721 /// Submit a changeset on the base by `agent` upserting `path` with `bytes`.
722 fn propose(
723 &mut self,
724 agent: &SigningKey,
725 label: &str,
726 path: &str,
727 bytes: &[u8],
728 ) -> ChangesetId {
729 let digest = BlobDigest::compute(bytes);
730 let mut env = ChangesetEnvelope {
731 version: SYNAPSE_ENVELOPE_VERSION,
732 repo_id: self.repo.clone(),
733 base_git_oid: GitOid([1; 20]),
734 parent_changesets: vec![],
735 author_did: String::new(),
736 idempotency_key: IdempotencyKey::from_label(label),
737 created_at_ms: 100,
738 intent_summary: label.to_string(),
739 mutations: vec![PathMutation {
740 path: path.to_string(),
741 op: MutationOp::Upsert {
742 mode: FileMode::Regular644,
743 blob_digest: digest,
744 size_bytes: bytes.len() as u64,
745 },
746 }],
747 evidence_receipts: vec![],
748 signature: vec![],
749 };
750 env.sign(agent);
751 let grant = self.grant(agent, vec![Capability::Propose]);
752 let now = 1000 + u64::from(self.nonce);
753 let req = AuthenticatedRequest::sign_new(
754 agent,
755 grant,
756 self.repo.clone(),
757 Capability::Propose,
758 [self.nonce; 32],
759 now,
760 0,
761 SubmitChangesetPayload {
762 envelope: env,
763 blobs: vec![(digest, bytes.to_vec())],
764 },
765 )
766 .unwrap();
767 match self.svc.submit(&req, now).unwrap() {
768 IngestOutcome::Committed { changeset_id, .. } => changeset_id,
769 other => panic!("unexpected {other:?}"),
770 }
771 }
772
773 fn advise_as(
774 &mut self,
775 caps: Vec<Capability>,
776 agent: &str,
777 paths: &[&str],
778 coord: Option<&CoordStore>,
779 ) -> SynapseResult<ChangesetAdvisory> {
780 let key = SigningKey::from_bytes(&[20u8; 32]);
781 let grant = self.grant(&key, caps);
782 let now = 1000 + u64::from(self.nonce);
783 let req = AuthenticatedRequest::sign_new(
784 &key,
785 grant,
786 self.repo.clone(),
787 Capability::Read,
788 [self.nonce; 32],
789 now,
790 0,
791 ChangesetAdvisoryPayload {
792 base: self.base,
793 latest: None,
794 paths: paths.iter().map(|p| p.to_string()).collect(),
795 agent: agent.to_string(),
796 snapshot_seq: None,
797 },
798 )?;
799 self.svc.changeset_advisory(&req, coord, now)
800 }
801
802 fn advise(&mut self, paths: &[&str], coord: Option<&CoordStore>) -> ChangesetAdvisory {
803 self.advise_as(vec![Capability::Read], "alice", paths, coord)
804 .unwrap()
805 }
806
807 fn coord(&self, now: i64) -> CoordStore {
808 CoordStore::open(self.dir.join("coord")).with_clock(move || now)
809 }
810 }
811
812 impl Drop for Fixture {
813 fn drop(&mut self) {
814 let _ = fs::remove_dir_all(&self.dir);
815 }
816 }
817
818 fn claim(store: &CoordStore, agent: &str, target: &str, ttl: i64) {
819 let ws = Workspace::with_oracle(
820 format!("/synapse/ws/{agent}"),
821 Holder::synapse("lane", "00112233445566778899", "aabbccddeeff00112233"),
822 Box::new(NoOracle),
823 );
824 let out = store
825 .claim(&ws, agent, ROOT_DIR, target, "edit", Some(ttl))
826 .unwrap();
827 assert!(matches!(out, ClaimOutcome::Claimed { .. }), "{out:?}");
828 }
829
830 fn bob() -> SigningKey {
831 SigningKey::from_bytes(&[30u8; 32])
832 }
833
834 #[test]
835 fn same_file_collision_reports_the_open_proposal() {
836 let mut fx = Fixture::new("same");
837 let cs = fx.propose(&bob(), "bob-a", "src/a.rs", b"fn a2() {}\n");
838 let adv = fx.advise(&["src/a.rs"], None);
839 let p = &adv.paths[0];
840 assert_eq!(p.overlapping_proposals.len(), 1);
841 assert_eq!(p.overlapping_proposals[0].changeset_id, cs);
842 assert_eq!(p.overlapping_proposals[0].mutated_path, "src/a.rs");
843 assert_eq!(
844 p.overlapping_proposals[0].author_did,
845 encode_did_key_ed25519(&bob().verifying_key().to_bytes())
846 );
847 assert_eq!(adv.coordination, CoordinationStatus::NotSupplied);
848 assert_eq!(adv.compared_to, Some(TreeTarget::Changeset(cs)));
849 assert_eq!(p.staleness, Staleness::Current);
850 }
851
852 #[test]
853 fn separate_files_do_not_overlap() {
854 let mut fx = Fixture::new("separate");
855 fx.propose(&bob(), "bob-b", "src/b.rs", b"fn b2() {}\n");
856 let adv = fx.advise(&["src/a.rs", "docs/x.md"], None);
857 assert!(adv.paths.iter().all(|p| p.overlapping_proposals.is_empty()));
858 }
859
860 #[test]
861 fn proposal_in_the_base_lineage_is_not_open() {
862 let mut fx = Fixture::new("lineage");
863 let cs = fx.propose(&bob(), "bob-a", "src/a.rs", b"fn a2() {}\n");
864 fx.base = TreeTarget::Changeset(cs);
865 let adv = fx.advise(&["src/a.rs"], None);
866 assert!(adv.paths[0].overlapping_proposals.is_empty());
867 }
868
869 #[test]
870 fn context_digest_and_guidance_come_from_the_base() {
871 let mut fx = Fixture::new("context");
872 let adv = fx.advise(&["src/new.rs", "src"], None);
873 let new_file = &adv.paths[0];
874 assert_eq!(new_file.context.target_dir(), "src");
875 assert_eq!(new_file.digest, new_file.context.digest());
876 let notes: Vec<(&str, &str)> = new_file
877 .guidance
878 .iter()
879 .map(|n| (n.dir.as_str(), n.text.as_str()))
880 .collect();
881 assert_eq!(notes, [("src", "src rule"), (".", "root rule")]);
882 // A directory path resolves to itself, so it shares the file's context.
883 assert_eq!(adv.paths[1].digest, new_file.digest);
884 // No changesets yet: nothing to compare with.
885 assert_eq!(adv.compared_to, None);
886 assert_eq!(new_file.staleness, Staleness::Unknown);
887 }
888
889 #[test]
890 fn claim_held_by_another_agent_is_reported() {
891 let mut fx = Fixture::new("claim");
892 let store = fx.coord(T0);
893 claim(&store, "bob", "src/a.rs", 600);
894 claim(&store, "carol", "docs", 600);
895 let adv = fx.advise(&["src/a.rs", "src/b.rs", "docs/x.md"], Some(&store));
896 assert_eq!(adv.coordination, CoordinationStatus::Read);
897 assert_eq!(adv.paths[0].claims.len(), 1);
898 assert_eq!(adv.paths[0].claims[0].holder, "bob");
899 assert_eq!(adv.paths[0].claims[0].key, "src/a.rs");
900 assert!(adv.paths[1].claims.is_empty());
901 // A directory claim covers the files under it.
902 assert_eq!(adv.paths[2].claims.len(), 1);
903 assert_eq!(adv.paths[2].claims[0].holder, "carol");
904 }
905
906 #[test]
907 fn expired_claim_is_ignored() {
908 let mut fx = Fixture::new("expired");
909 claim(&fx.coord(T0), "bob", "src/a.rs", 60);
910 let live = fx.advise(&["src/a.rs"], Some(&fx.coord(T0 + 60)));
911 assert_eq!(live.paths[0].claims.len(), 1);
912 let later = fx.advise(&["src/a.rs"], Some(&fx.coord(T0 + 61)));
913 assert_eq!(later.coordination, CoordinationStatus::Read);
914 assert!(later.paths[0].claims.is_empty());
915 }
916
917 #[test]
918 fn own_claim_is_not_reported_as_conflict() {
919 let mut fx = Fixture::new("own");
920 let store = fx.coord(T0);
921 claim(&store, "alice", "src/a.rs", 600);
922 let mine = fx.advise(&["src/a.rs"], Some(&store));
923 assert!(mine.paths[0].claims.is_empty());
924 let theirs = fx
925 .advise_as(vec![Capability::Read], "bob", &["src/a.rs"], Some(&store))
926 .unwrap();
927 assert_eq!(theirs.paths[0].claims[0].holder, "alice");
928 }
929
930 #[test]
931 fn stale_context_is_flagged() {
932 let mut fx = Fixture::new("stale");
933 let newer = br#"{"schema_version":"1.0.0","name":"src","purpose":"Changed.","invariants":["new rule"]}"#;
934 let cs = fx.propose(&bob(), "bob-crumb", "src/.crumb", newer);
935 let adv = fx.advise(&["src/a.rs", "docs/x.md"], None);
936 assert_eq!(adv.compared_to, Some(TreeTarget::Changeset(cs)));
937 let Staleness::Stale { latest_digest } = adv.paths[0].staleness else {
938 panic!("expected stale, got {:?}", adv.paths[0].staleness);
939 };
940 assert_ne!(latest_digest, adv.paths[0].digest);
941 // Guidance still reports the base context, not the newer one.
942 assert_eq!(adv.paths[0].guidance[0].text, "src rule");
943 // A directory whose chain did not change stays current.
944 assert_eq!(adv.paths[1].staleness, Staleness::Current);
945 }
946
947 #[test]
948 fn refusals_over_cap_duplicate_invalid_and_without_read() {
949 let mut fx = Fixture::new("refuse");
950 let many: Vec<String> = (0..=MAX_ADVISORY_PATHS).map(|i| format!("f{i}")).collect();
951 let many: Vec<&str> = many.iter().map(String::as_str).collect();
952 let err = fx
953 .advise_as(vec![Capability::Read], "alice", &many, None)
954 .unwrap_err();
955 assert_eq!(err.code, RefusalCode::QuotaTooManyPaths);
956 let at_cap = fx
957 .advise_as(
958 vec![Capability::Read],
959 "alice",
960 &many[..MAX_ADVISORY_PATHS],
961 None,
962 )
963 .unwrap();
964 assert_eq!(at_cap.paths.len(), MAX_ADVISORY_PATHS);
965 let dup = fx
966 .advise_as(
967 vec![Capability::Read],
968 "alice",
969 &["src/a.rs", "src/a.rs"],
970 None,
971 )
972 .unwrap_err();
973 assert_eq!(dup.code, RefusalCode::PathDuplicate);
974 let bad = fx
975 .advise_as(vec![Capability::Read], "alice", &["../x"], None)
976 .unwrap_err();
977 assert_eq!(bad.code, RefusalCode::PathInvalid);
978 let denied = fx
979 .advise_as(vec![Capability::Propose], "alice", &["src/a.rs"], None)
980 .unwrap_err();
981 assert_eq!(denied.code, RefusalCode::AuthCapabilityDenied);
982 }
983
984 #[test]
985 fn advisory_writes_nothing_to_the_coordination_store() {
986 let mut fx = Fixture::new("nowrite");
987 let store = fx.coord(T0);
988 let adv = fx.advise(&["src/a.rs"], Some(&store));
989 assert_eq!(adv.coordination, CoordinationStatus::Read);
990 assert!(!fx.dir.join("coord").exists());
991 }
992
993 fn promote(fx: &mut Fixture, cs: ChangesetId) {
994 fx.svc
995 .store
996 .record_canonical_promotion(synapse_core::RadicleCanonicalHead {
997 repo_id: fx.repo.clone(),
998 default_branch: "main".to_string(),
999 canonical_git_oid: GitOid([2; 20]),
1000 promoted_changeset_id: Some(cs),
1001 rad_id_commit_oid: GitOid([3; 20]),
1002 threshold: 1,
1003 verified_delegates: vec![],
1004 verified_at_ms: 5,
1005 })
1006 .unwrap();
1007 }
1008
1009 #[test]
1010 fn pending_crumb_rewrite_after_a_promotion_is_flagged() {
1011 let mut fx = Fixture::new("pending-crumb");
1012 let cs1 = fx.propose(&bob(), "bob-b", "src/b.rs", b"fn b2() {}\n");
1013 promote(&mut fx, cs1);
1014 let newer = br#"{"schema_version":"1.0.0","name":"src","purpose":"Changed.","invariants":["new rule"]}"#;
1015 let cs2 = fx.propose(&bob(), "bob-crumb", "src/.crumb", newer);
1016 let adv = fx.advise(&["src/a.rs"], None);
1017 let p = &adv.paths[0];
1018 assert!(
1019 matches!(p.staleness, Staleness::Stale { .. }),
1020 "compared_to {:?}, staleness {:?}, overlaps {:?}",
1021 adv.compared_to,
1022 p.staleness,
1023 p.overlapping_proposals
1024 );
1025 assert_eq!(adv.compared_to, Some(TreeTarget::Changeset(cs2)));
1026 assert_eq!(
1027 adv.canonical,
1028 CanonicalStatus::Promoted(TreeTarget::Changeset(cs1))
1029 );
1030 // The promoted changeset kept the base `.crumb` chain.
1031 assert_eq!(p.canonical_staleness, Staleness::Current);
1032 // The pending rewrite is surfaced even though it does not touch the path.
1033 assert!(p.overlapping_proposals.is_empty());
1034 assert_eq!(p.pending_crumb_changes.len(), 1);
1035 assert_eq!(p.pending_crumb_changes[0].changeset_id, cs2);
1036 assert_eq!(p.pending_crumb_changes[0].mutated_path, "src/.crumb");
1037 let last = p.guidance.last().unwrap();
1038 assert_eq!(last.dir, "src");
1039 assert!(last.text.contains("src/.crumb"), "{last:?}");
1040 // A path outside `src` has no pending rewrite in its chain.
1041 let docs = fx.advise(&["docs/x.md"], None);
1042 assert!(docs.paths[0].pending_crumb_changes.is_empty());
1043 // An unrelated newer proposal does not hide the pending rewrite.
1044 let carol = SigningKey::from_bytes(&[40u8; 32]);
1045 let cs3 = fx.propose(&carol, "carol-docs", "docs/x.md", b"# y\n");
1046 let adv = fx.advise(&["src/a.rs"], None);
1047 assert_eq!(adv.compared_to, Some(TreeTarget::Changeset(cs3)));
1048 assert_eq!(adv.paths[0].staleness, Staleness::Current);
1049 assert_eq!(adv.paths[0].pending_crumb_changes[0].changeset_id, cs2);
1050 }
1051
1052 #[test]
1053 fn canonical_head_is_not_used_at_an_older_snapshot() {
1054 let mut fx = Fixture::new("canon-snap");
1055 let cs1 = fx.propose(&bob(), "bob-b", "src/b.rs", b"fn b2() {}\n");
1056 let before = fx.svc.store.committed_seq();
1057 promote(&mut fx, cs1);
1058 let now = fx.advise(&["src/b.rs"], None);
1059 assert_eq!(
1060 now.canonical,
1061 CanonicalStatus::Promoted(TreeTarget::Changeset(cs1))
1062 );
1063 assert!(now.paths[0].overlapping_proposals.is_empty());
1064 // At the earlier snapshot the head was not promoted yet; the store cannot say so,
1065 // so the head is not used and cs1 is still an open proposal there.
1066 let key = SigningKey::from_bytes(&[20u8; 32]);
1067 let grant = fx.grant(&key, vec![Capability::Read]);
1068 let t = 1000 + u64::from(fx.nonce);
1069 let req = AuthenticatedRequest::sign_new(
1070 &key,
1071 grant,
1072 fx.repo.clone(),
1073 Capability::Read,
1074 [fx.nonce; 32],
1075 t,
1076 0,
1077 ChangesetAdvisoryPayload {
1078 base: fx.base,
1079 latest: None,
1080 paths: vec!["src/b.rs".to_string()],
1081 agent: "alice".to_string(),
1082 snapshot_seq: Some(before),
1083 },
1084 )
1085 .unwrap();
1086 let old = fx.svc.changeset_advisory(&req, None, t).unwrap();
1087 assert_eq!(old.canonical, CanonicalStatus::NotAtSnapshot);
1088 assert_eq!(old.paths[0].canonical_staleness, Staleness::Unknown);
1089 assert_eq!(old.paths[0].overlapping_proposals[0].changeset_id, cs1);
1090 }
1091
1092 #[test]
1093 fn lock_without_holder_is_skipped() {
1094 let mut fx = Fixture::new("noholder");
1095 let store = fx.coord(T0);
1096 claim(&store, "bob", "src/a.rs", 600);
1097 let file = fx.dir.join("coord/dirs/src.json");
1098 let text = fs::read_to_string(&file).unwrap();
1099 let stripped = text.replacen("\"holder\": \"bob\",", "", 1);
1100 assert_ne!(stripped, text, "fixture: holder field not found in {text}");
1101 fs::write(&file, stripped).unwrap();
1102 let adv = fx.advise(&["src/a.rs"], Some(&store));
1103 assert_eq!(adv.coordination, CoordinationStatus::Read);
1104 assert!(adv.paths[0].claims.is_empty(), "{:?}", adv.paths[0].claims);
1105 }
1106
1107 /// Issue #94: repeated advisory calls on one snapshot materialize its tree once; a new
1108 /// snapshot costs one more build while the base stays cached.
1109 #[test]
1110 fn advisory_builds_each_snapshot_once() {
1111 let mut fx = Fixture::new("views-once");
1112 let b0 = fx.svc.snapshot_view_stats().builds;
1113 for _ in 0..5 {
1114 fx.advise(&["src/a.rs", "docs/x.md"], None);
1115 }
1116 assert_eq!(
1117 fx.svc.snapshot_view_stats().builds - b0,
1118 1,
1119 "base built once"
1120 );
1121 let cs = fx.propose(&bob(), "bob-a", "src/a.rs", b"fn a2() {}\n");
1122 for _ in 0..5 {
1123 let adv = fx.advise(&["src/a.rs"], None);
1124 assert_eq!(adv.compared_to, Some(TreeTarget::Changeset(cs)));
1125 }
1126 assert_eq!(
1127 fx.svc.snapshot_view_stats().builds - b0,
1128 2,
1129 "latest built once, base still cached"
1130 );
1131 }
1132
1133 /// Issue #94: the view cache keeps at most `SNAPSHOT_VIEW_CACHE_ENTRIES` snapshots and
1134 /// evicts the oldest first.
1135 #[test]
1136 fn snapshot_view_cache_is_bounded() {
1137 let mut fx = Fixture::new("views-bound");
1138 let n = SNAPSHOT_VIEW_CACHE_ENTRIES + 2;
1139 let ids: Vec<_> = (0..n)
1140 .map(|i| {
1141 let path = format!("gen/f{i}.rs");
1142 fx.propose(&bob(), &format!("bob-{i}"), &path, path.as_bytes())
1143 })
1144 .collect();
1145 let b0 = fx.svc.snapshot_view_stats().builds;
1146 for &cs in &ids {
1147 fx.base = TreeTarget::Changeset(cs);
1148 fx.advise(&["src/a.rs"], None);
1149 assert!(fx.svc.snapshot_view_stats().entries <= SNAPSHOT_VIEW_CACHE_ENTRIES);
1150 }
1151 // Each base is new; `latest` (the newest changeset) is built once and stays cached
1152 // until evicted, so at least one build per base.
1153 let built = fx.svc.snapshot_view_stats().builds - b0;
1154 assert!(built >= n as u64, "{built} builds for {n} snapshots");
1155 assert_eq!(
1156 fx.svc.snapshot_view_stats().entries,
1157 SNAPSHOT_VIEW_CACHE_ENTRIES
1158 );
1159 // The first base was evicted: asking again builds it again.
1160 let before = fx.svc.snapshot_view_stats().builds;
1161 fx.base = TreeTarget::Changeset(ids[0]);
1162 fx.advise(&["src/a.rs"], None);
1163 assert!(fx.svc.snapshot_view_stats().builds > before);
1164 }
1165
1166 /// Base tree of `files` long-path files under `dir`, registered as `oid` (no `.crumb`).
1167 fn long_path_base(fx: &mut Fixture, oid: GitOid, dir: &str, files: usize) -> TreeTarget {
1168 let seg = "s".repeat(200);
1169 let tree = (0..files)
1170 .map(|i| {
1171 (
1172 format!("{dir}/{seg}/{seg}/{seg}/f{i}.rs"),
1173 FileMode::Regular644,
1174 format!("{i}\n").into_bytes(),
1175 )
1176 })
1177 .collect();
1178 fx.svc.register_base_tree(oid, tree).unwrap();
1179 TreeTarget::BaseGitCommit(oid)
1180 }
1181
1182 fn small_tree_cache(fx: &mut Fixture) {
1183 fx.svc
1184 .set_tree_cache_config(crate::TreeCacheConfig {
1185 max_bytes: crate::tree::MIN_TREE_CACHE_BYTES,
1186 })
1187 .unwrap();
1188 }
1189
1190 /// Review of #98: a view larger than the byte budget (a share of the configured tree
1191 /// cache bound) is built for the call and not kept; the answer does not depend on it.
1192 #[test]
1193 fn snapshot_view_over_the_byte_budget_is_not_kept() {
1194 let mut roomy = Fixture::new("views-bytes-roomy");
1195 roomy.base = long_path_base(&mut roomy, GitOid([2; 20]), "big", 500);
1196 let expected = roomy.advise(&["big/x.rs"], None);
1197
1198 let mut fx = Fixture::new("views-bytes");
1199 small_tree_cache(&mut fx);
1200 fx.base = long_path_base(&mut fx, GitOid([2; 20]), "big", 500);
1201 let b0 = fx.svc.snapshot_view_stats().builds;
1202 for _ in 0..2 {
1203 assert_eq!(fx.advise(&["big/x.rs"], None), expected);
1204 let s = fx.svc.snapshot_view_stats();
1205 assert!(
1206 s.bytes <= s.budget,
1207 "view cache over its byte budget: {s:?}"
1208 );
1209 }
1210 let s = fx.svc.snapshot_view_stats();
1211 assert_eq!(s.entries, 0, "{s:?}");
1212 assert_eq!(s.builds - b0, 2, "too big to keep: built on every call");
1213 }
1214
1215 /// Review of #98: views that fit one at a time but not together evict the oldest, so the
1216 /// kept bytes never exceed the budget.
1217 #[test]
1218 fn snapshot_view_cache_evicts_by_bytes() {
1219 let mut fx = Fixture::new("views-bytes-evict");
1220 small_tree_cache(&mut fx);
1221 let a = long_path_base(&mut fx, GitOid([3; 20]), "a", 70);
1222 let b = long_path_base(&mut fx, GitOid([4; 20]), "b", 70);
1223 fx.base = a;
1224 fx.advise(&["a/x.rs"], None);
1225 let s = fx.svc.snapshot_view_stats();
1226 assert_eq!(s.entries, 1, "{s:?}");
1227 assert!(
1228 s.bytes <= s.budget && 2 * s.bytes > s.budget,
1229 "fixture size: {s:?}"
1230 );
1231 fx.base = b;
1232 fx.advise(&["b/x.rs"], None);
1233 let s = fx.svc.snapshot_view_stats();
1234 assert!(
1235 s.bytes <= s.budget,
1236 "view cache over its byte budget: {s:?}"
1237 );
1238 assert_eq!(s.entries, 1, "oldest view evicted: {s:?}");
1239 fx.base = a;
1240 let before = s.builds;
1241 fx.advise(&["a/x.rs"], None);
1242 assert_eq!(
1243 fx.svc.snapshot_view_stats().builds - before,
1244 1,
1245 "a was evicted"
1246 );
1247 }
1248
1249 /// Review of #98: views belong to the service that built them and are freed with it; a
1250 /// new service on the same thread starts empty.
1251 #[test]
1252 fn snapshot_views_are_released_with_the_service() {
1253 let mut fx = Fixture::new("views-release");
1254 fx.advise(&["src/a.rs"], None);
1255 let handles = fx.svc.snapshot_view_handles();
1256 assert!(!handles.is_empty());
1257 drop(fx);
1258 assert!(
1259 handles.iter().all(|h| h.upgrade().is_none()),
1260 "views outlive the service"
1261 );
1262 let fx2 = Fixture::new("views-release-next");
1263 assert_eq!(fx2.svc.snapshot_view_stats().entries, 0);
1264 }
1265}