Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/patches/d4b1e1c12cc18a6d # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/synapse#109 (code only) closed derived `d4b1e1c12cc18a6d` #109 Imported from GitHub aien-dev/synapse#109 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `2f06c455a5af8a5db7e0230c3692f08db21f61f2` · Head `507daaa0b00f1cee312f895db6a6d128f6d462de` ### Apply it ``` git checkout -b patch-d4b1e1c12cc18a6d 2f06c455a5af8a5db7e0230c3692f08db21f61f2 curl -fsSL https://interplane.io/drakestapleton/synapse/patches/d4b1e1c12cc18a6d.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/synapse 109 507daaa0b00f1cee312f895db6a6d128f6d462de ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"synapse","number":109,"url":"https://github.com/aien-dev/synapse/pull/109","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:10Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 6a12dd2..379b6bc 100644 --- a/.crumb +++ b/.crumb @@ -45,14 +45,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-17T12:02:42Z", + "compiled_at": "2026-10-18T13:11:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:fb301066e5ae4d15cead28f810814b4f4772e79638563bee1c13b56c86c3a501", + "digest": "sha256:0d25e8ab81f49af91a268c9eadecbb1ed1dbc66ea90dadeb28dc4c961cefab18", "evidence_files": 262, "evidence_root": "sha256:b25d2fcc4dd431ffce85a91a08342766e8f5d4b0309e16df46c008083835d98a", - "files": 456, - "generated_at_commit": "77227b6b132bbd9ca2d0fbd86bffd84b3c509dbc", - "source_tree": "sha256:0b135d43305597f16d1212342c522b05be78f06b5fa8befc2e645c28cb31e584" + "files": 458, + "generated_at_commit": "2c93a3665b563efccfc126cf34cc472e1f04a04c", + "source_tree": "sha256:78eccafd5d13849461a563d4ec808c7e956eae39be0f739c00d14e5b32299b50" }, "synapse": { "component_paths": { diff --git a/Cargo.lock b/Cargo.lock index 70b130d..fcd4307 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "base64ct" version = "1.8.3" @@ -223,6 +232,35 @@ dependencies = [ "getrandom", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "rustc_version" version = "0.4.1" @@ -372,6 +410,8 @@ version = "0.1.0" dependencies = [ "ed25519-dalek", "hex", + "regex", + "regex-syntax", "serde", "serde_json", "sha2", diff --git a/Cargo.toml b/Cargo.toml index 40750e4..4ad6984 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,10 @@ curve25519-dalek = { version = "4.1", default-features = false } ed25519-dalek = { version = "2.2", default-features = false, features = ["std", "fast"] } hex = "0.4" libc = "0.2" +# C3 trigram search: linear-time regular expressions over bytes (no backtracking) and the +# parsed syntax tree the trigram query is derived from; default features off (no perf deps). +regex = { version = "1.10", default-features = false, features = ["std", "unicode"] } +regex-syntax = { version = "0.8", default-features = false, features = ["std", "unicode"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha1 = "0.10" diff --git a/crates/synapse-api/Cargo.toml b/crates/synapse-api/Cargo.toml index 96467de..fdee5ba 100644 --- a/crates/synapse-api/Cargo.toml +++ b/crates/synapse-api/Cargo.toml @@ -10,6 +10,8 @@ description = "Bounded paginated read/proposal API, checkout-free virtual tree i [dependencies] ed25519-dalek.workspace = true hex.workspace = true +regex.workspace = true +regex-syntax.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true diff --git a/crates/synapse-api/src/lib.rs b/crates/synapse-api/src/lib.rs index f41f7de..1a752da 100644 --- a/crates/synapse-api/src/lib.rs +++ b/crates/synapse-api/src/lib.rs @@ -29,6 +29,7 @@ mod crumb; mod derivation; pub use derivation::ServiceDerivationTrees; mod evidence; +mod search; pub mod tree; pub use advisory::{ ChangesetAdvisory, ChangesetAdvisoryPayload, CoordinationStatus, GuidanceNote, @@ -39,6 +40,11 @@ pub use evidence::{ EvidenceBase, EvidenceBaseQueryPayload, ReceiptMismatch, ReceiptVerification, StaleContext, StaleReason, VerifyEvidenceReceiptPayload, }; +pub use search::{ + IndexReport, SearchIndex, SearchIndexConfig, SearchMatch, SearchQueryPayload, SearchResponse, + SearchStats, SearchTarget, DEFAULT_MAX_INDEXED_BLOB_BYTES, DEFAULT_SEARCH_INDEX_BYTES, + MAX_SEARCH_PATTERN_BYTES, MAX_SEARCH_RESULTS, MAX_SPANS_PER_FILE, +}; pub use tree::{ TreeCacheConfig, TreeDiffEntry, TreeEdit, TreeEntry, TreeEntryKind, TreeFile, TreeNode, TreeStore, TreeStoreStats, DEFAULT_TREE_CACHE_BYTES, MIN_TREE_CACHE_BYTES, @@ -378,6 +384,7 @@ pub struct SynapseService { trees: TreeStore, base_blobs: BTreeMap>, max_page_size: usize, + search_index: SearchIndex, } impl SynapseService { @@ -411,6 +418,7 @@ impl SynapseService { trees: TreeStore::new(TreeCacheConfig::default())?, base_blobs: BTreeMap::new(), max_page_size: DEFAULT_MAX_PAGE_SIZE, + search_index: SearchIndex::new(SearchIndexConfig::default()), }) } diff --git a/crates/synapse-api/src/search.rs b/crates/synapse-api/src/search.rs new file mode 100644 index 0000000..12db1b6 --- /dev/null +++ b/crates/synapse-api/src/search.rs @@ -0,0 +1,923 @@ +//! Trigram content search with the scope filter (ADR 0003 step C3, section 5.7, source [S25]). +//! +//! A query is a regular expression over raw file bytes (`regex::bytes`, linear time, no +//! backtracking). Its syntax tree is reduced to a boolean query over trigrams that every match +//! must contain (Russ Cox, "Regular Expression Matching with a Trigram Index"). Each indexed +//! blob keeps its sorted set of trigrams, so a file whose blob cannot contain a match is passed +//! over without reading a byte; every other file is read and matched in full, so the result is +//! exactly the result of a full scan. A blob the bounded index does not hold is always read. +//! +//! The scope filter runs before any content is touched: the walk enters only the subtrees the +//! caller's `Read` path scope covers, a revision target is resolved through the step B4 +//! visibility rule, and the query is evaluated per in-scope file against that file's own +//! trigram set (never by intersecting global posting lists), so no result, count, or amount of +//! work depends on a file outside the caller's scope. + +use crate::tree::{TreeEdit, TreeFile}; +use crate::{admission_authority, SynapseService, TreeTarget}; +use regex::bytes::{Regex, RegexBuilder}; +use regex_syntax::hir::{Class, Hir, HirKind}; +use std::collections::{BTreeMap, BTreeSet}; +use synapse_auth::{BoundaryKind, Capability, ChainedRequest}; +use synapse_core::{ + BlobDigest, ChangesetId, GitOid, MutationOp, RefusalCode, SynapseError, SynapseResult, + TreeDigest, +}; + +/// Most matching files one search returns. +pub const MAX_SEARCH_RESULTS: usize = 256; +/// Longest accepted pattern, in bytes. +pub const MAX_SEARCH_PATTERN_BYTES: usize = 4096; +/// Most match spans reported per file (`more_spans` says when there were more). +pub const MAX_SPANS_PER_FILE: usize = 16; +/// Compiled program bound for one pattern, in bytes (a larger one is refused, typed). +pub const MAX_REGEX_PROGRAM_BYTES: usize = 1 << 20; +/// Default memory bound of the trigram index. +pub const DEFAULT_SEARCH_INDEX_BYTES: usize = 64 << 20; +/// Default largest blob the index holds; a larger blob is always read and matched. +pub const DEFAULT_MAX_INDEXED_BLOB_BYTES: usize = 4 << 20; + +/// Files fetched from the tree per walk step: bounds the memory of one search. +const WALK_PAGE: usize = 1024; +/// Largest literal set kept while planning a query before it is folded into trigrams. +const MAX_EXACT_SET: usize = 64; +/// Largest character class expanded into literals while planning. +const MAX_CLASS_EXPANSION: usize = 32; +/// Most trigrams taken from one literal (a subset is still a necessary condition). +const MAX_TRIGRAMS_PER_LITERAL: usize = 64; +/// Most nodes in a planned query; a larger plan becomes "read every file" (still exact). +const MAX_QUERY_NODES: usize = 4096; +/// Bookkeeping charged per indexed blob on top of its trigrams. +const INDEX_ENTRY_OVERHEAD: usize = 96; + +/// What a search runs over. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SearchTarget { + /// A base Git tree or an envelope v1 changeset tree. + Tree(TreeTarget), + /// An envelope v2 revision (step B4): its base tree with its mutations applied. Another + /// owner's `Private` revision, or one with a mutation outside the caller's path scope, is + /// `ChangesetNotFound`, exactly like an unknown one (the `read_revision` rule). + Revision(ChangesetId), +} + +/// A search request, carried as the payload of a `ChainedRequest` granting `Read`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SearchQueryPayload { + pub target: SearchTarget, + /// Regular expression over raw bytes (`regex` crate syntax). + pub pattern: String, + /// Return only paths strictly after this one (the previous response's `next_after`). + pub after_path: Option, + /// 1..=`MAX_SEARCH_RESULTS` files. + pub limit: u32, +} + +const PAYLOAD_TAG: &[u8] = b"SYNAPSE_SEARCH_V1\0"; + +impl SearchQueryPayload { + /// Canonical bytes: tag, target kind and id, limit, optional after path, pattern. + pub fn encode(&self) -> Vec { + let mut out = PAYLOAD_TAG.to_vec(); + match self.target { + SearchTarget::Tree(TreeTarget::BaseGitCommit(oid)) => { + out.push(0); + out.extend_from_slice(&oid.0); + } + SearchTarget::Tree(TreeTarget::Changeset(id)) => { + out.push(1); + out.extend_from_slice(&id.0); + } + SearchTarget::Revision(id) => { + out.push(2); + out.extend_from_slice(&id.0); + } + } + out.extend_from_slice(&self.limit.to_le_bytes()); + match &self.after_path { + None => out.push(0), + Some(p) => { + out.push(1); + put_bytes(&mut out, p.as_bytes()); + } + } + put_bytes(&mut out, self.pattern.as_bytes()); + out + } + + /// Strict decode: any truncation, unknown kind, non-UTF-8 text, or trailing byte is + /// `EnvelopeMalformed`. + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader(bytes); + if r.take(PAYLOAD_TAG.len())? != PAYLOAD_TAG { + return Err(malformed("search payload tag")); + } + let target = match r.take(1)?[0] { + 0 => SearchTarget::Tree(TreeTarget::BaseGitCommit(GitOid(r.array()?))), + 1 => SearchTarget::Tree(TreeTarget::Changeset(ChangesetId(r.array()?))), + 2 => SearchTarget::Revision(ChangesetId(r.array()?)), + _ => return Err(malformed("search target kind")), + }; + let limit = u32::from_le_bytes(r.array()?); + let after_path = match r.take(1)?[0] { + 0 => None, + 1 => Some(r.text()?), + _ => return Err(malformed("search after_path flag")), + }; + let pattern = r.text()?; + if !r.0.is_empty() { + return Err(malformed("search payload has trailing bytes")); + } + Ok(Self { + target, + pattern, + after_path, + limit, + }) + } +} + +fn put_bytes(out: &mut Vec, b: &[u8]) { + out.extend_from_slice(&(b.len() as u32).to_le_bytes()); + out.extend_from_slice(b); +} + +struct Reader<'a>(&'a [u8]); + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> { + if self.0.len() < n { + return Err(malformed("search payload truncated")); + } + let (head, tail) = self.0.split_at(n); + self.0 = tail; + Ok(head) + } + + fn array(&mut self) -> SynapseResult<[u8; N]> { + let mut a = [0u8; N]; + a.copy_from_slice(self.take(N)?); + Ok(a) + } + + fn text(&mut self) -> SynapseResult { + let n = u32::from_le_bytes(self.array()?) as usize; + let b = self.take(n)?; + String::from_utf8(b.to_vec()).map_err(|_| malformed("search text is not UTF-8")) + } +} + +fn malformed(what: &str) -> SynapseError { + SynapseError::new(RefusalCode::EnvelopeMalformed, what.to_string()) +} + +/// One matching file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SearchMatch { + pub path: String, + pub blob_digest: BlobDigest, + /// Byte ranges `[start, end)` of the first `MAX_SPANS_PER_FILE` non-overlapping matches, + /// leftmost first. + pub spans: Vec<(u64, u64)>, + /// True when the file has more matches than `spans` lists. + pub more_spans: bool, +} + +/// One page of results, in path byte order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SearchResponse { + pub matches: Vec, + /// Set when more matching files follow: pass it as `after_path` for the next page. + pub next_after: Option, +} + +/// Memory bounds of the trigram index. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SearchIndexConfig { + pub max_bytes: usize, + pub max_blob_bytes: usize, +} + +impl Default for SearchIndexConfig { + fn default() -> Self { + Self { + max_bytes: DEFAULT_SEARCH_INDEX_BYTES, + max_blob_bytes: DEFAULT_MAX_INDEXED_BLOB_BYTES, + } + } +} + +/// Result of indexing one tree. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct IndexReport { + /// Distinct blobs newly indexed. + pub indexed: u64, + /// Blobs already in the index. + pub already: u64, + /// Blobs left out (too large, or the memory bound is reached); always read when searched. + pub skipped: u64, +} + +/// Server-side counters (never returned to a caller). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SearchStats { + /// In-scope files passed over by the trigram query without reading their bytes. + pub files_pruned: u64, + /// In-scope files read and matched. + pub files_read: u64, +} + +/// Bounded per-blob trigram index. Content addressed, so one entry serves every tree that +/// holds the blob. Trigrams are packed into the low 24 bits of a `u32`. +#[derive(Debug, Default)] +pub struct SearchIndex { + config: SearchIndexConfig, + blobs: BTreeMap>, + bytes: usize, + stats: SearchStats, +} + +impl SearchIndex { + pub fn new(config: SearchIndexConfig) -> Self { + Self { + config, + ..Default::default() + } + } + + pub fn config(&self) -> SearchIndexConfig { + self.config + } + + /// Bytes charged against `max_bytes`. + pub fn bytes(&self) -> usize { + self.bytes + } + + pub fn indexed_blobs(&self) -> usize { + self.blobs.len() + } + + pub fn contains(&self, digest: &BlobDigest) -> bool { + self.blobs.contains_key(digest) + } + + pub fn stats(&self) -> SearchStats { + self.stats + } + + /// Index `content` under `digest`. `Some(true)` when newly indexed, `Some(false)` when + /// already present, `None` when left out by a bound. + pub fn insert(&mut self, digest: BlobDigest, content: &[u8]) -> Option { + if self.blobs.contains_key(&digest) { + return Some(false); + } + if content.len() > self.config.max_blob_bytes { + return None; + } + let tris = trigrams_of(content); + let cost = tris.len() * 4 + INDEX_ENTRY_OVERHEAD; + if self.bytes.saturating_add(cost) > self.config.max_bytes { + return None; + } + self.bytes += cost; + self.blobs.insert(digest, tris.into_boxed_slice()); + Some(true) + } + + /// Whether the blob may hold a match of `query`: true for a blob the index does not hold. + fn may_match(&self, digest: &BlobDigest, query: &Query) -> bool { + match self.blobs.get(digest) { + Some(tris) => query.eval(tris), + None => true, + } + } +} + +fn pack(t: &[u8]) -> u32 { + (u32::from(t[0]) << 16) | (u32::from(t[1]) << 8) | u32::from(t[2]) +} + +/// Sorted distinct trigrams of `content`. +fn trigrams_of(content: &[u8]) -> Vec { + let mut v: Vec = content.windows(3).map(pack).collect(); + v.sort_unstable(); + v.dedup(); + v.shrink_to_fit(); + v +} + +/// A necessary condition on a file's trigram set for a match to exist. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Query { + /// No condition: every file is a candidate. + All, + /// No file can match. + Nothing, + Tri(u32), + And(Vec), + Or(Vec), +} + +impl Query { + fn and(a: Query, b: Query) -> Query { + match (a, b) { + (Query::All, x) | (x, Query::All) => x, + (Query::Nothing, _) | (_, Query::Nothing) => Query::Nothing, + (Query::And(mut x), Query::And(y)) => { + x.extend(y); + Query::And(x) + } + (Query::And(mut x), y) | (y, Query::And(mut x)) => { + x.push(y); + Query::And(x) + } + (x, y) => Query::And(vec![x, y]), + } + } + + fn or(a: Query, b: Query) -> Query { + match (a, b) { + (Query::Nothing, x) | (x, Query::Nothing) => x, + (Query::All, _) | (_, Query::All) => Query::All, + (Query::Or(mut x), Query::Or(y)) => { + x.extend(y); + Query::Or(x) + } + (Query::Or(mut x), y) | (y, Query::Or(mut x)) => { + x.push(y); + Query::Or(x) + } + (x, y) => Query::Or(vec![x, y]), + } + } + + fn nodes(&self) -> usize { + match self { + Query::And(v) | Query::Or(v) => 1 + v.iter().map(Query::nodes).sum::(), + _ => 1, + } + } + + fn eval(&self, tris: &[u32]) -> bool { + match self { + Query::All => true, + Query::Nothing => false, + Query::Tri(t) => tris.binary_search(t).is_ok(), + Query::And(v) => v.iter().all(|q| q.eval(tris)), + Query::Or(v) => v.iter().any(|q| q.eval(tris)), + } + } +} + +/// Planning facts of one syntax node: `exact` is the full set of byte strings the node can +/// match, when small enough to keep; `query` is a condition every match satisfies. Invariant: +/// when `exact` is set, `query` is `All`. +struct Info { + exact: Option>>, + query: Query, +} + +fn empty_string() -> Info { + Info { + exact: Some(BTreeSet::from([Vec::new()])), + query: Query::All, + } +} + +fn anything() -> Info { + Info { + exact: None, + query: Query::All, + } +} + +/// Condition that a match contains one of the strings of `set`. +fn trigrams_of_set(set: &BTreeSet>) -> Query { + let mut q = Query::Nothing; + for s in set { + if s.len() < 3 { + return Query::All; + } + let mut tris: Vec = s.windows(3).map(pack).collect(); + tris.sort_unstable(); + tris.dedup(); + tris.truncate(MAX_TRIGRAMS_PER_LITERAL); + let all = tris + .into_iter() + .fold(Query::All, |acc, t| Query::and(acc, Query::Tri(t))); + q = Query::or(q, all); + } + q +} + +fn info_query(i: Info) -> Query { + match i.exact { + Some(set) => Query::and(i.query, trigrams_of_set(&set)), + None => i.query, + } +} + +fn plan(hir: &Hir) -> Info { + match hir.kind() { + HirKind::Empty | HirKind::Look(_) => empty_string(), + HirKind::Literal(lit) => Info { + exact: Some(BTreeSet::from([lit.0.to_vec()])), + query: Query::All, + }, + HirKind::Class(class) => match expand_class(class) { + Some(set) => Info { + exact: Some(set), + query: Query::All, + }, + None => anything(), + }, + HirKind::Capture(c) => plan(&c.sub), + HirKind::Repetition(r) => { + if r.max == Some(0) { + empty_string() + } else if r.min == 0 { + anything() + } else if r.min == 1 && r.max == Some(1) { + plan(&r.sub) + } else { + Info { + exact: None, + query: info_query(plan(&r.sub)), + } + } + } + HirKind::Concat(subs) => { + let mut query = Query::All; + let mut run: Option>> = Some(BTreeSet::from([Vec::new()])); + let mut whole_exact = true; + for sub in subs { + let i = plan(sub); + match (run.take(), i.exact) { + (Some(a), Some(b)) => { + if a.len().saturating_mul(b.len()) <= MAX_EXACT_SET { + let mut prod = BTreeSet::new(); + for x in &a { + for y in &b { + let mut s = x.clone(); + s.extend_from_slice(y); + prod.insert(s); + } + } + run = Some(prod); + } else { + whole_exact = false; + query = Query::and(query, trigrams_of_set(&a)); + run = Some(b); + } + } + (Some(a), None) => { + whole_exact = false; + query = Query::and(query, trigrams_of_set(&a)); + query = Query::and(query, i.query); + } + (None, Some(b)) => run = Some(b), + (None, None) => query = Query::and(query, i.query), + } + } + if whole_exact { + Info { + exact: run, + query: Query::All, + } + } else { + if let Some(a) = run { + query = Query::and(query, trigrams_of_set(&a)); + } + Info { exact: None, query } + } + } + HirKind::Alternation(subs) => { + let infos: Vec = subs.iter().map(plan).collect(); + let union_len: usize = infos + .iter() + .map(|i| i.exact.as_ref().map_or(usize::MAX, BTreeSet::len)) + .fold(0usize, usize::saturating_add); + if union_len <= MAX_EXACT_SET { + let mut set = BTreeSet::new(); + for i in infos { + set.extend(i.exact.unwrap_or_default()); + } + Info { + exact: Some(set), + query: Query::All, + } + } else { + let query = infos + .into_iter() + .fold(Query::Nothing, |acc, i| Query::or(acc, info_query(i))); + Info { exact: None, query } + } + } + } +} + +/// The byte strings a small class matches (UTF-8 encodings for a Unicode class). +fn expand_class(class: &Class) -> Option>> { + let mut out = BTreeSet::new(); + match class { + Class::Unicode(c) => { + for r in c.ranges() { + for ch in r.start()..=r.end() { + if out.len() >= MAX_CLASS_EXPANSION { + return None; + } + let mut buf = [0u8; 4]; + out.insert(ch.encode_utf8(&mut buf).as_bytes().to_vec()); + } + } + } + Class::Bytes(c) => { + for r in c.ranges() { + for b in r.start()..=r.end() { + if out.len() >= MAX_CLASS_EXPANSION { + return None; + } + out.insert(vec![b]); + } + } + } + } + Some(out) +} + +/// A compiled pattern and its trigram query. +struct Compiled { + regex: Regex, + query: Query, +} + +/// Compile `pattern` the way `regex::bytes` does (Unicode on, UTF-8 matching off) and plan +/// its trigram query from the same syntax tree. +fn compile(pattern: &str) -> SynapseResult { + if pattern.len() > MAX_SEARCH_PATTERN_BYTES { + return Err(SynapseError::new( + RefusalCode::QuotaPayloadTooLarge, + format!("search pattern exceeds {MAX_SEARCH_PATTERN_BYTES} bytes"), + )); + } + let regex = RegexBuilder::new(pattern) + .size_limit(MAX_REGEX_PROGRAM_BYTES) + .dfa_size_limit(MAX_REGEX_PROGRAM_BYTES) + .build() + .map_err(|e| malformed(&format!("search pattern: {e}")))?; + let hir = regex_syntax::ParserBuilder::new() + .utf8(false) + .build() + .parse(pattern) + .map_err(|e| malformed(&format!("search pattern: {e}")))?; + let mut query = info_query(plan(&hir)); + if query.nodes() > MAX_QUERY_NODES { + query = Query::All; + } + Ok(Compiled { regex, query }) +} + +/// Match spans of `regex` in `content`. +fn spans_of(regex: &Regex, content: &[u8]) -> (Vec<(u64, u64)>, bool) { + let mut spans = Vec::new(); + for m in regex.find_iter(content) { + if spans.len() == MAX_SPANS_PER_FILE { + return (spans, true); + } + spans.push((m.start() as u64, m.end() as u64)); + } + (spans, false) +} + +impl SynapseService { + /// The trigram index (read-only view, for bounds and statistics). + pub fn search_index(&self) -> &SearchIndex { + &self.search_index + } + + /// Replace the trigram index with an empty one bounded by `config`. + pub fn set_search_index_config(&mut self, config: SearchIndexConfig) { + self.search_index = SearchIndex::new(config); + } + + /// Server-side step: add every blob of `target` to the trigram index, within its bounds. + /// Not on behalf of a key (no visibility filter), and never run by a search, so the + /// index's contents never depend on what any caller searched. + pub fn index_search_content(&mut self, target: SearchTarget) -> SynapseResult { + let mut report = IndexReport::default(); + let mut offset = 0u64; + loop { + let page = self.search_page(target, None, "", offset)?; + let n = page.len(); + for (_, file) in page { + if self.search_index.contains(&file.blob_digest) { + report.already += 1; + continue; + } + let bytes = self.read_blob_bytes(file.blob_digest, None)?; + match self.search_index.insert(file.blob_digest, &bytes) { + Some(true) => report.indexed += 1, + Some(false) => report.already += 1, + None => report.skipped += 1, + } + } + if n < WALK_PAGE { + return Ok(report); + } + offset += n as u64; + } + } + + /// Content search (ADR 0003 step C3) under an F1 delegation chain granting `Read`. + /// `req.payload` is a [`SearchQueryPayload`]. Only files the chain's leaf path scope + /// covers are walked, pruned, read, matched, or returned; a revision target the chain may + /// not see is `ChangesetNotFound`. Results are in path byte order, at most `limit` files. + pub fn search(&mut self, req: &ChainedRequest, now_ms: u64) -> SynapseResult { + let q = SearchQueryPayload::decode(&req.payload)?; + if q.limit == 0 || q.limit as usize > MAX_SEARCH_RESULTS { + return Err(SynapseError::new( + RefusalCode::PaginationLimitExceeded, + format!("search limit must be 1..={MAX_SEARCH_RESULTS}"), + )); + } + let compiled = compile(&q.pattern)?; + self.auth.authorize_chain( + BoundaryKind::Api, + "search", + &self.repo_id, + Capability::Read, + req, + self.store.committed_seq().next(), + now_ms, + )?; + let scope = req + .chain + .leaf() + .map(|leaf| leaf.caveats.paths.clone()) + .ok_or_else(|| { + SynapseError::new(RefusalCode::AuthChainBroken, "search: empty chain") + })?; + let revision_root = match q.target { + SearchTarget::Tree(_) => None, + SearchTarget::Revision(id) => { + let viewer = admission_authority(req)?.chain; + let rev = self + .store + .get_revision_visible_to(&self.repo_id, id, &viewer)?; + if !rev + .content + .mutations + .iter() + .all(|m| scope.covers_path(&m.path)) + { + return Err(SynapseError::new( + RefusalCode::ChangesetNotFound, + format!("revision {id} not found"), + )); + } + Some(self.revision_root(id)?) + } + }; + let limit = q.limit as usize; + let mut found: BTreeMap = BTreeMap::new(); + let mut consider = |svc: &mut Self, path: String, file: TreeFile| -> SynapseResult<()> { + if q.after_path.as_deref().is_some_and(|a| path.as_str() <= a) { + return Ok(()); + } + if found.len() > limit && found.last_key_value().is_some_and(|(k, _)| path > *k) { + return Ok(()); + } + if !svc + .search_index + .may_match(&file.blob_digest, &compiled.query) + { + svc.search_index.stats.files_pruned += 1; + return Ok(()); + } + svc.search_index.stats.files_read += 1; + let bytes = svc.read_blob_bytes(file.blob_digest, None)?; + let (spans, more_spans) = spans_of(&compiled.regex, &bytes); + if !spans.is_empty() { + found.insert( + path.clone(), + SearchMatch { + path, + blob_digest: file.blob_digest, + spans, + more_spans, + }, + ); + if found.len() > limit + 1 { + found.pop_last(); + } + } + Ok(()) + }; + for prefix in scope.prefixes() { + // A scope prefix covers the file at that exact path and everything under `prefix/`. + let walk_prefix = if prefix.is_empty() { + String::new() + } else { + if let Some(file) = self.search_lookup(q.target, revision_root, prefix)? { + consider(self, prefix.clone(), file)?; + } + format!("{prefix}/") + }; + let mut offset = 0u64; + loop { + let page = self.search_page(q.target, revision_root, &walk_prefix, offset)?; + let n = page.len(); + for (path, file) in page { + consider(self, path, file)?; + } + if n < WALK_PAGE { + break; + } + offset += n as u64; + } + } + let next_after = if found.len() > limit { + found.pop_last(); + found.last_key_value().map(|(k, _)| k.clone()) + } else { + None + }; + Ok(SearchResponse { + matches: found.into_values().collect(), + next_after, + }) + } + + /// The tree of a v2 revision: its base tree with its mutations applied (server side). + fn revision_root(&mut self, id: ChangesetId) -> SynapseResult { + let rev = self.store.get_revision(&self.repo_id, id)?; + let mut edit = TreeEdit::new(&mut self.trees, rev.content.base_tree)?; + for m in &rev.content.mutations { + match &m.op { + MutationOp::Upsert { + mode, + blob_digest, + size_bytes, + } => { + let raw = self.read_blob_bytes(*blob_digest, None)?; + let file = TreeFile { + mode: *mode, + blob_digest: *blob_digest, + size_bytes: *size_bytes, + git_blob_oid: GitOid::compute_blob(&raw), + }; + edit.upsert(&mut self.trees, &m.path, file)?; + } + MutationOp::Delete => edit.delete(&mut self.trees, &m.path)?, + } + } + edit.finish(&mut self.trees) + } + + /// One walk page of `target` under `prefix`. `revision_root` is the root already built + /// for a revision target (built here when absent); it is rebuilt once if the bounded tree + /// store evicted part of it. + fn search_page( + &mut self, + target: SearchTarget, + revision_root: Option, + prefix: &str, + offset: u64, + ) -> SynapseResult> { + match target { + SearchTarget::Tree(t) => self.with_tree(t, None, |trees, root| { + trees.page_files(root, prefix, offset, WALK_PAGE) + }), + SearchTarget::Revision(id) => { + let root = match revision_root { + Some(r) => r, + None => self.revision_root(id)?, + }; + match self.trees.page_files(root, prefix, offset, WALK_PAGE) { + Err(e) if e.code == RefusalCode::TreeNodeNotFound => { + let root = self.revision_root(id)?; + self.trees.page_files(root, prefix, offset, WALK_PAGE) + } + other => other, + } + } + } + } + + fn search_lookup( + &mut self, + target: SearchTarget, + revision_root: Option, + path: &str, + ) -> SynapseResult> { + match (target, revision_root) { + (SearchTarget::Tree(t), _) => { + self.with_tree(t, None, |trees, root| trees.lookup(root, path)) + } + (SearchTarget::Revision(id), root) => { + let root = match root { + Some(r) => r, + None => self.revision_root(id)?, + }; + match self.trees.lookup(root, path) { + Err(e) if e.code == RefusalCode::TreeNodeNotFound => { + let root = self.revision_root(id)?; + self.trees.lookup(root, path) + } + other => other, + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn candidates(pattern: &str, content: &[u8]) -> bool { + compile(pattern).unwrap().query.eval(&trigrams_of(content)) + } + + /// The planned query never prunes a file the pattern matches, and does prune files that + /// lack a required literal. + #[test] + fn planned_query_is_necessary_and_prunes() { + let cases: &[(&str, &[u8])] = &[ + ("hello", b"say hello world"), + ("(?i)hello", b"say HeLLo world"), + ("foo|barbaz", b"xx barbaz"), + ("ab+c", b"abbbbc"), + ("a.c", b"axc"), + ("serve\\(\\)", b"pub fn serve() {}"), + ("[0-9]{3}-wal", b"seg 042-wal"), + ("\u{e9}t\u{e9}", "caf\u{e9} \u{e9}t\u{e9}".as_bytes()), + ("(?-u)\\xFF\\xFEabc", b"\xff\xfeabc"), + ("^$", b""), + ("x*", b""), + ]; + for (p, c) in cases { + let re = compile(p).unwrap(); + assert!(re.regex.is_match(c), "{p} should match"); + assert!(re.query.eval(&trigrams_of(c)), "{p} pruned a match"); + } + assert!(!candidates("hello", b"help low")); + assert!(!candidates("foo|barbaz", b"bar baz fo")); + assert!(!candidates("[0-9]{3}-wal", b"no digits")); + assert!(candidates(".*", b"anything")); + } + + #[test] + fn index_bounds_are_enforced() { + let mut idx = SearchIndex::new(SearchIndexConfig { + max_bytes: 200, + max_blob_bytes: 64, + }); + let small = b"abcdef"; + let d = BlobDigest::compute(small); + assert_eq!(idx.insert(d, small), Some(true)); + assert_eq!(idx.insert(d, small), Some(false)); + let big = [b'a'; 65]; + assert_eq!(idx.insert(BlobDigest::compute(&big), &big), None); + let many: Vec = (0u8..=60).collect(); + assert_eq!(idx.insert(BlobDigest::compute(&many), &many), None); + assert!(idx.bytes() <= 200); + assert!(!idx.contains(&BlobDigest::compute(&big))); + } + + #[test] + fn payload_round_trips_and_malformed_payloads_are_refused() { + let p = SearchQueryPayload { + target: SearchTarget::Revision(ChangesetId([7; 32])), + pattern: "fn \\w+".into(), + after_path: Some("src/a.rs".into()), + limit: 10, + }; + let bytes = p.encode(); + assert_eq!(SearchQueryPayload::decode(&bytes).unwrap(), p); + for cut in 0..bytes.len() { + assert!(SearchQueryPayload::decode(&bytes[..cut]).is_err()); + } + let mut trailing = bytes.clone(); + trailing.push(0); + assert!(SearchQueryPayload::decode(&trailing).is_err()); + let mut bad_kind = bytes; + bad_kind[PAYLOAD_TAG.len()] = 9; + assert!(SearchQueryPayload::decode(&bad_kind).is_err()); + } + + #[test] + fn malformed_and_oversized_patterns_are_refused_typed() { + assert_eq!( + compile("(unclosed").err().unwrap().code, + RefusalCode::EnvelopeMalformed + ); + let long = "a".repeat(MAX_SEARCH_PATTERN_BYTES + 1); + assert_eq!( + compile(&long).err().unwrap().code, + RefusalCode::QuotaPayloadTooLarge + ); + assert!(compile("\\w{1000}\\w{1000}\\w{1000}").is_err()); + } +} diff --git a/crates/synapse-api/tests/c3_trigram_search.rs b/crates/synapse-api/tests/c3_trigram_search.rs new file mode 100644 index 0000000..55d0596 --- /dev/null +++ b/crates/synapse-api/tests/c3_trigram_search.rs @@ -0,0 +1,620 @@ +//! ADR 0003 step C3 through the API with real signed F1 capability chains: authority `A` +//! grants orchestrator `O` and outsider `X` (whole repository); `O` delegates worker `W` +//! (scoped to `src`), worker `V` (whole repository), and reader `D` (scoped to `docs`). +//! +//! Acceptance: every regular expression of a fixed query set returns exactly the matches of a +//! full scan of the same trees (before and after indexing); no result, count, or amount of +//! work reveals a file outside the caller's `Read` scope or another owner's `Private` revision. + +use ed25519_dalek::SigningKey; +use regex::bytes::Regex; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use synapse_api::{ + RevisionStateMovePayload, SearchMatch, SearchQueryPayload, SearchResponse, SearchTarget, + SynapseService, TreeTarget, MAX_SPANS_PER_FILE, +}; +use synapse_auth::{ + Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChainedRequest, ChangeScope, + LinkCaveats, OperationSet, PathScope, ReferenceKind, ReferenceScope, RequestScope, ROOT_PARENT, +}; +use synapse_core::{ + encode_did_key_ed25519, BlobDigest, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, + GitOid, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, + RevisionState, TreeDigest, WalSeq, +}; +use synapse_store::{FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits}; + +const NOW: u64 = 2_000; +const C: ChangeId = ChangeId([0xC3; 16]); +const BASE: GitOid = GitOid([0x0C; 20]); + +type Agent = (SigningKey, CapabilityChain); + +/// The fixed query set: literals, case folding, classes, alternation, repetition, anchors, +/// Unicode, raw non-UTF-8 bytes, and patterns no trigram can narrow. +const QUERIES: &[&str] = &[ + "secret", + "SECRET_KEY", + "(?i)secret_key", + "fn [a-z_]+\\(", + "serve|parse_frame", + "wal_[0-9]{2}", + "(?m)^pub ", + "caf\u{e9}", + "(?-u)\\xFF\\xFE", + "(?-u)\\xFFnul", + "TODO.*later", + "\\bmod\\b", + "[a-c]{3}x", + "zzz_never_present", + ".", + "x?", +]; + +fn link_nonces(dir: &Path) -> impl FnMut() -> [u8; 32] { + let seed = dir.to_string_lossy().into_owned(); + let mut issued = 0u32; + move || { + issued += 1; + let mut h = Sha256::new(); + h.update(seed.as_bytes()); + h.update(issued.to_le_bytes()); + h.finalize().into() + } +} + +fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() +} + +fn pk(k: &SigningKey) -> [u8; 32] { + k.verifying_key().to_bytes() +} + +fn caveats(paths: PathScope, share: u64) -> LinkCaveats { + LinkCaveats { + operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), + paths, + references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]), + changes: ChangeScope::any(), + quotas: ChainQuotas { + max_ops_per_window: (100_000 / share) as u32, + window_duration_ms: 60_000, + storage_bytes: (1 << 30) / share, + footprint_paths: (1 << 20) / share, + max_bytes_per_op: 1 << 20, + }, + issued_at_ms: 1_000, + expires_at_ms: 100_000, + } +} + +fn base_files() -> Vec<(String, FileMode, Vec)> { + let f = |p: &str, b: &[u8]| (p.to_string(), FileMode::Regular644, b.to_vec()); + let mut v = vec![ + f("README.md", b"Synapse: TODO explain later\nabcx\n"), + f( + "src/lib.rs", + b"pub mod wal;\npub fn serve() {}\n// TODO tidy later\n", + ), + f( + "src/wal.rs", + b"pub fn parse_frame(b: &[u8]) {}\nconst WAL: &str = \"wal_07\";\n", + ), + f( + "src/bin/\u{e9}t\u{e9}.rs", + "fn main() { println!(\"caf\u{e9}\"); }\n".as_bytes(), + ), + f( + "src/raw.bin", + b"\xff\xfe\x00\xffnul binary \xc3 not utf8 secret", + ), + f( + "src-other/leak.rs", + b"SECRET_KEY = \"src-other must not leak to src\"\n", + ), + f( + "docs/guide.md", + b"# Guide\nThe secret is in the wal_42 chapter. bbcx\n", + ), + f( + "docs/caf\u{e9}.md", + "caf\u{e9} au lait, fn brew(\n".as_bytes(), + ), + f( + "private/keys.env", + b"SECRET_KEY=hunter2\nsecret_key=lower\n", + ), + f( + "private/notes.txt", + b"pub fn serve_secretly() {}\nTODO do it later\n", + ), + ]; + // Enough files to need several walk pages and to give the index something to prune. + for i in 0..1500 { + v.push(f( + &format!("src/gen/m{i:04}.rs"), + format!("pub fn generated_{i}() -> u32 {{ {i} }}\n").as_bytes(), + )); + } + v.push(f( + "src/gen/m0777.rs", + b"pub fn generated_777() { /* secret */ }\n", + )); + v.sort_by(|a, b| a.0.cmp(&b.0)); + v.dedup_by(|a, b| a.0 == b.0); + v +} + +struct Fx { + svc: SynapseService, + base: TreeDigest, + o: Agent, + w: Agent, + v: Agent, + d: Agent, + x: Agent, + nonce: u32, +} + +impl Fx { + fn new(name: &str, files: Vec<(String, FileMode, Vec)>) -> Self { + let dir: PathBuf = std::env::temp_dir().join(format!( + "synapse-c3-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let mut svc = SynapseService::open( + &dir, + repo(), + FsyncPolicy::EveryCommit, + RecoveryPolicy::StrictFailClosed, + StoreLimits { + wal_prealloc_bytes: 64 * 1024, + ..Default::default() + }, + ) + .unwrap(); + let a = SigningKey::from_bytes(&[1; 32]); + let key = |n: u8| SigningKey::from_bytes(&[n; 32]); + let (o, w, v, d, x) = (key(2), key(3), key(4), key(5), key(9)); + svc.auth_mut() + .register_repo_authority(repo(), encode_did_key_ed25519(&pk(&a))); + let whole = PathScope::whole_repository; + let mut nonce = link_nonces(&dir); + let root = |nonce: [u8; 32], to: &SigningKey| { + CapabilityLink::issue(&a, ROOT_PARENT, nonce, repo(), pk(to), caveats(whole(), 1)) + }; + let root_o = root(nonce(), &o); + let root_x = root(nonce(), &x); + let child = |nonce: [u8; 32], to: &SigningKey, paths: PathScope| { + CapabilityLink::issue( + &o, + root_o.digest(), + nonce, + repo(), + pk(to), + caveats(paths, 4), + ) + }; + let link_w = child(nonce(), &w, PathScope::new(vec!["src".into()]).unwrap()); + let link_v = child(nonce(), &v, whole()); + let link_d = child(nonce(), &d, PathScope::new(vec!["docs".into()]).unwrap()); + let co = CapabilityChain::new(vec![root_o]); + let cx = CapabilityChain::new(vec![root_x]); + let (cw, cv, cd) = ( + co.extended(link_w), + co.extended(link_v), + co.extended(link_d), + ); + for c in [&co, &cx, &cw, &cv, &cd] { + svc.auth_mut().grant_link(c, WalSeq(0), NOW).unwrap(); + } + svc.register_base_tree(BASE, files).unwrap(); + let base = svc + .tree_digest(TreeTarget::BaseGitCommit(BASE), None) + .unwrap(); + Self { + svc, + base, + o: (o, co), + w: (w, cw), + v: (v, cv), + d: (d, cd), + x: (x, cx), + nonce: 0, + } + } + + fn request( + &mut self, + who: &Agent, + cap: Capability, + scope: RequestScope, + payload: Vec, + ) -> ChainedRequest { + self.nonce += 1; + let mut n = [0u8; 32]; + n[..4].copy_from_slice(&self.nonce.to_le_bytes()); + ChainedRequest::sign_new(&who.0, who.1.clone(), repo(), cap, scope, n, NOW, payload) + } + + fn search_page( + &mut self, + who: &Agent, + target: SearchTarget, + pattern: &str, + after: Option, + limit: u32, + ) -> Result { + let payload = SearchQueryPayload { + target, + pattern: pattern.into(), + after_path: after, + limit, + } + .encode(); + let req = self.request(who, Capability::Read, RequestScope::default(), payload); + self.svc.search(&req, NOW).map_err(|e| (e.code, e.message)) + } + + /// Every match, following `next_after` across pages of `limit`. + fn search_all( + &mut self, + who: &Agent, + target: SearchTarget, + pattern: &str, + limit: u32, + ) -> Result, (RefusalCode, String)> { + let mut out = Vec::new(); + let mut after = None; + loop { + let page = self.search_page(who, target, pattern, after, limit)?; + assert!(page.matches.len() <= limit as usize); + out.extend(page.matches); + match page.next_after { + Some(a) => after = Some(a), + None => return Ok(out), + } + } + } + + /// The reference: read every file of the tree and match it, keeping the files `scope` + /// covers. + fn full_scan( + &mut self, + target: TreeTarget, + scope: &PathScope, + pattern: &str, + ) -> Vec { + let re = Regex::new(pattern).unwrap(); + let files = self.svc.materialize_virtual_tree(target, None).unwrap(); + let mut out = Vec::new(); + for (path, entry) in files { + if !scope.covers_path(&path) { + continue; + } + let bytes = self.svc.read_blob_bytes(entry.blob_digest, None).unwrap(); + let all: Vec<(u64, u64)> = re + .find_iter(&bytes) + .map(|m| (m.start() as u64, m.end() as u64)) + .collect(); + if all.is_empty() { + continue; + } + out.push(SearchMatch { + path, + blob_digest: entry.blob_digest, + more_spans: all.len() > MAX_SPANS_PER_FILE, + spans: all.into_iter().take(MAX_SPANS_PER_FILE).collect(), + }); + } + out + } + + /// `who` submits a `Private` revision of change `C` writing `body` to `path`. + fn submit(&mut self, who: &Agent, path: &str, body: &[u8], idem: u8) -> ChangesetId { + let content = RevisionContent { + change_id: C, + base_tree: self.base, + parents: vec![], + mutations: vec![PathMutation { + path: path.into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(body), + size_bytes: body.len() as u64, + }, + }], + intent_summary: "c3 search fixture".into(), + }; + let env = + ChangesetEnvelopeV2::sign_new(&who.0, repo(), content, IdempotencyKey([idem; 32]), NOW); + let scope = RequestScope { + paths: vec![path.into()], + reference: None, + join_change: Some(C), + }; + let req = self.request(who, Capability::Propose, scope, env.encode()); + let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; + match self.svc.submit_revision(&req, &blobs, NOW).unwrap() { + RevisionOutcome::Admitted { changeset_id, .. } => changeset_id, + other => panic!("expected an admission, got {other:?}"), + } + } + + fn mv(&mut self, who: &Agent, id: ChangesetId, to: RevisionState) { + let payload = RevisionStateMovePayload::sign_new(&who.0, &repo(), &who.1, id, to, NOW) + .unwrap() + .encode(); + let req = self.request(who, Capability::Propose, RequestScope::default(), payload); + self.svc.advance_revision_state(&req, NOW).unwrap(); + } +} + +fn scope_of(prefixes: &[&str]) -> PathScope { + PathScope::new(prefixes.iter().map(|p| p.to_string()).collect()).unwrap() +} + +/// Acceptance 1: indexed search equals a full scan of the same tree, for every query of the +/// fixed set and every reader scope, before indexing (no pruning), after indexing (pruning), +/// and across pages. +#[test] +fn c3_search_equals_a_full_scan_for_the_fixed_query_set() { + let mut fx = Fx::new("parity", base_files()); + let target = TreeTarget::BaseGitCommit(BASE); + let readers = [ + (fx.v.clone(), scope_of(&[""])), + (fx.w.clone(), scope_of(&["src"])), + (fx.d.clone(), scope_of(&["docs"])), + ]; + for indexed in [false, true] { + if indexed { + let report = fx + .svc + .index_search_content(SearchTarget::Tree(target)) + .unwrap(); + assert!(report.indexed > 1000, "{report:?}"); + assert_eq!(report.skipped, 0); + } + for (who, scope) in &readers { + for q in QUERIES { + let want = fx.full_scan(target, scope, q); + let got = fx + .search_all(who, SearchTarget::Tree(target), q, 256) + .unwrap(); + assert_eq!(got, want, "query {q:?} indexed={indexed} scope={scope:?}"); + } + } + } + // Small pages give the same answer as one large one. + for q in ["secret", "fn [a-z_]+\\(", "."] { + let want = fx.full_scan(target, &scope_of(&[""]), q); + let v = fx.v.clone(); + assert_eq!( + fx.search_all(&v, SearchTarget::Tree(target), q, 3).unwrap(), + want + ); + } + // The index pruned files without reading them, and the results did not change. + let stats = fx.svc.search_index().stats(); + assert!(stats.files_pruned > 10_000, "{stats:?}"); + assert!(fx.svc.search_index().bytes() <= fx.svc.search_index().config().max_bytes); +} + +/// A tiny index bound leaves most blobs unindexed; those are read, so results stay exact. +#[test] +fn c3_bounded_index_keeps_results_exact() { + let mut fx = Fx::new("bounded", base_files()); + fx.svc + .set_search_index_config(synapse_api::SearchIndexConfig { + max_bytes: 4096, + max_blob_bytes: 64, + }); + let target = TreeTarget::BaseGitCommit(BASE); + let report = fx + .svc + .index_search_content(SearchTarget::Tree(target)) + .unwrap(); + assert!(report.skipped > 0 && report.indexed > 0, "{report:?}"); + assert!(fx.svc.search_index().bytes() <= 4096); + let v = fx.v.clone(); + for q in QUERIES { + let want = fx.full_scan(target, &scope_of(&[""]), q); + assert_eq!( + fx.search_all(&v, SearchTarget::Tree(target), q, 256) + .unwrap(), + want + ); + } +} + +/// Acceptance 2 (path scope): a `src` reader never sees `docs`, `private`, the root, or the +/// sibling prefix `src-other`, by result or by count; and the work done for a scoped search +/// (files pruned plus files read) does not change when out-of-scope files are added. +#[test] +fn c3_cross_scope_search_reveals_nothing_outside_the_read_scope() { + let mut fx = Fx::new("scope", base_files()); + let target = SearchTarget::Tree(TreeTarget::BaseGitCommit(BASE)); + fx.svc.index_search_content(target).unwrap(); + let (w, d) = (fx.w.clone(), fx.d.clone()); + // Matches exist only outside `src`: nothing comes back, no cursor, no count. + for q in [ + "SECRET_KEY", + "hunter2", + "Guide", + "explain", + "serve_secretly", + ] { + let page = fx.search_page(&w, target, q, None, 10).unwrap(); + assert!( + page.matches.is_empty() && page.next_after.is_none(), + "{q}: {page:?}" + ); + } + // A pattern matching everywhere returns only `src` files to W and only `docs` files to D. + for m in fx.search_all(&w, target, "secret|e", 256).unwrap() { + assert!(m.path.starts_with("src/"), "{}", m.path); + } + for m in fx.search_all(&d, target, "secret|e", 256).unwrap() { + assert!(m.path.starts_with("docs/"), "{}", m.path); + } + // A cursor before the scope does not pull in out-of-scope paths either. + let page = fx + .search_page(&w, target, "SECRET", Some(String::new()), 10) + .unwrap(); + assert!(page.matches.iter().all(|m| m.path.starts_with("src/"))); + + // Work is independent of out-of-scope content: same responses, same work, with 2000 + // extra matching files outside `docs`. + let mut more = base_files(); + for i in 0..2000 { + more.push(( + format!("private/extra/{i}.txt"), + FileMode::Regular644, + b"secret wal_99 caf\xc3\xa9".to_vec(), + )); + } + let mut big = Fx::new("scope-big", more); + big.svc.index_search_content(target).unwrap(); + let d_big = big.d.clone(); + for q in QUERIES { + let s0 = fx.svc.search_index().stats(); + let small = fx.search_all(&d, target, q, 256).unwrap(); + let s1 = fx.svc.search_index().stats(); + let b0 = big.svc.search_index().stats(); + let large = big.search_all(&d_big, target, q, 256).unwrap(); + let b1 = big.svc.search_index().stats(); + assert_eq!(small, large, "{q}"); + assert_eq!( + s1.files_read - s0.files_read, + b1.files_read - b0.files_read, + "{q}" + ); + assert_eq!( + s1.files_pruned - s0.files_pruned, + b1.files_pruned - b0.files_pruned, + "{q}" + ); + } +} + +/// Acceptance 2 (`Private`): W's `Private` revision is searchable by W and by O (whose grant +/// W's descends from) and by nobody else, each refused exactly like an unknown revision; the +/// base tree never shows its content. After `Draft` it is searchable within `Read` scope, and +/// still refused to D, whose scope does not cover its mutation. +#[test] +fn c3_private_revision_content_is_invisible_outside_its_owner_chain() { + let mut fx = Fx::new("private", base_files()); + let (o, w, v, d, x) = ( + fx.o.clone(), + fx.w.clone(), + fx.v.clone(), + fx.d.clone(), + fx.x.clone(), + ); + let rev = fx.submit(&w, "src/lib.rs", b"pub fn private_token_c3() {}\n", 1); + let target = SearchTarget::Revision(rev); + fx.svc.index_search_content(target).unwrap(); + for owner in [&w, &o] { + let hits = fx + .search_all(owner, target, "private_token_c3", 10) + .unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].path, "src/lib.rs"); + } + let unknown = SearchTarget::Revision(ChangesetId([0xEE; 32])); + let (code, msg) = fx.search_page(&o, unknown, "x", None, 1).unwrap_err(); + assert_eq!(code, RefusalCode::ChangesetNotFound); + for outsider in [&v, &d, &x] { + for q in ["private_token_c3", "zzz_never_present", "."] { + let (c, m) = fx.search_page(outsider, target, q, None, 10).unwrap_err(); + assert_eq!(c, code); + assert_eq!( + m, + msg.replace(&ChangesetId([0xEE; 32]).to_string(), &rev.to_string()) + ); + } + } + // The base tree never carries the revision's content, for anyone. + let base = SearchTarget::Tree(TreeTarget::BaseGitCommit(BASE)); + for who in [&o, &w, &v, &x] { + assert!(fx + .search_all(who, base, "private_token_c3", 10) + .unwrap() + .is_empty()); + } + fx.mv(&w, rev, RevisionState::Draft); + for reader in [&o, &w, &v, &x] { + assert_eq!( + fx.search_all(reader, target, "private_token_c3", 10) + .unwrap() + .len(), + 1 + ); + } + assert_eq!( + fx.search_page(&d, target, "private_token_c3", None, 10) + .unwrap_err() + .0, + RefusalCode::ChangesetNotFound + ); + // Parity with a full scan holds on the revision tree too. + let v_scope = scope_of(&[""]); + let rev_files = fx + .svc + .materialize_virtual_tree(TreeTarget::BaseGitCommit(BASE), None) + .unwrap(); + assert!(rev_files.contains_key("src/lib.rs")); + for q in QUERIES { + let mut want = fx.full_scan(TreeTarget::BaseGitCommit(BASE), &v_scope, q); + want.retain(|m| m.path != "src/lib.rs"); + let body: &[u8] = b"pub fn private_token_c3() {}\n"; + let re = Regex::new(q).unwrap(); + let spans: Vec<(u64, u64)> = re + .find_iter(body) + .map(|m| (m.start() as u64, m.end() as u64)) + .collect(); + if !spans.is_empty() { + want.push(SearchMatch { + path: "src/lib.rs".into(), + blob_digest: BlobDigest::compute(body), + more_spans: spans.len() > MAX_SPANS_PER_FILE, + spans: spans.into_iter().take(MAX_SPANS_PER_FILE).collect(), + }); + want.sort_by(|a, b| a.path.cmp(&b.path)); + } + assert_eq!(fx.search_all(&v, target, q, 256).unwrap(), want, "{q}"); + } +} + +/// Malformed requests are refused typed, never by a panic. +#[test] +fn c3_malformed_requests_are_refused_typed() { + let mut fx = Fx::new("malformed", base_files()); + let v = fx.v.clone(); + let target = SearchTarget::Tree(TreeTarget::BaseGitCommit(BASE)); + assert_eq!( + fx.search_page(&v, target, "(", None, 1).unwrap_err().0, + RefusalCode::EnvelopeMalformed + ); + assert_eq!( + fx.search_page(&v, target, "a", None, 0).unwrap_err().0, + RefusalCode::PaginationLimitExceeded + ); + assert_eq!( + fx.search_page(&v, target, "a", None, 257).unwrap_err().0, + RefusalCode::PaginationLimitExceeded + ); + for junk in [vec![], vec![0xff; 7], b"SYNAPSE_SEARCH_V1\0\x07".to_vec()] { + let req = fx.request(&v, Capability::Read, RequestScope::default(), junk); + assert_eq!( + fx.svc.search(&req, NOW).unwrap_err().code, + RefusalCode::EnvelopeMalformed + ); + } +} ```