From 89cb24a80ae20e269d8c4aac7f415477c1cc6f2f Mon Sep 17 00:00:00 2001 From: Beardthelion Date: Tue, 1 Dec 2026 04:53:03 +0000 Subject: [PATCH 1/2] perf(node): bucket ref-update visibility by repo name --- crates/twigpine-node/src/api/events.rs | 11 +- crates/twigpine-node/src/api/tasks.rs | 7 +- crates/twigpine-node/src/visibility.rs | 396 +++++++++++++++++++++---- 3 files changed, 344 insertions(+), 70 deletions(-) diff --git a/crates/twigpine-node/src/api/events.rs b/crates/twigpine-node/src/api/events.rs index 4e619d6a7..506bcf74f 100644 --- a/crates/twigpine-node/src/api/events.rs +++ b/crates/twigpine-node/src/api/events.rs @@ -79,6 +79,7 @@ async fn collect_visible_ref_updates_inner( let quarantined = db.list_quarantined_repos().await?; let ids: Vec = deduped.iter().map(|r| r.id.clone()).collect(); let rules = db.list_visibility_rules_for_repos(&ids).await?; + let repos = crate::visibility::RefUpdateRepoIndex::new(&deduped, &quarantined); // Never scan fewer rows than the caller asked for (no regression vs the old // single LIMIT), but cap the walk so a feed of newest-private rows can't @@ -110,15 +111,7 @@ async fn collect_visible_ref_updates_inner( after = Some((last.received_at.clone(), last.id.clone())); } for u in rows { - // Quarantine denies unconditionally, before the visibility gate, so - // even a caller matching the mirror's owner_did cannot read the row. - if quarantined - .iter() - .any(|q| crate::visibility::ref_update_row_names_repo(q, &u.repo)) - { - continue; - } - if crate::visibility::ref_update_row_visible(&deduped, &rules, caller, &u.repo) { + if repos.row_visible(&rules, caller, &u.repo) { visible.push(u); if visible.len() == want { return Ok(visible); diff --git a/crates/twigpine-node/src/api/tasks.rs b/crates/twigpine-node/src/api/tasks.rs index 775bb795f..13519b0d3 100644 --- a/crates/twigpine-node/src/api/tasks.rs +++ b/crates/twigpine-node/src/api/tasks.rs @@ -179,10 +179,9 @@ const MAX_TASK_SCAN_CANDIDATES: i64 = 1_000; /// to — they hold its `payload` (and held `ucan_token`, though reads never /// echo it back) from creating or being assigned it. Otherwise, a task naming /// a locally-hosted repo follows that repo's normal read gate, the same way -/// `ref_update_row_visible` (`visibility.rs`) drops a ref-update row for a -/// repo the caller can't read. A task with no `repo_id`, or naming a repo this -/// node does not host, is visible only to its delegator/assignee — fail -/// closed, since an open-to-everyone default is exactly the gap #268 found +/// the ref-update feed drops a row for a repo the caller can't read. A task with +/// no `repo_id`, or naming a repo this node does not host, is visible only to +/// its delegator/assignee, since an open default is the gap #268 found /// (`GET /api/v1/tasks` and `/tasks/{id}` had no gate at all). pub(crate) fn task_visible( task: &AgentTask, diff --git a/crates/twigpine-node/src/visibility.rs b/crates/twigpine-node/src/visibility.rs index a8d7ddba0..5da973915 100644 --- a/crates/twigpine-node/src/visibility.rs +++ b/crates/twigpine-node/src/visibility.rs @@ -129,69 +129,76 @@ pub fn listable_at_root( visibility_check(rules, is_public, owner_did, caller, "/") == Decision::Allow } -/// Whether a single `received_ref_updates` row (identified by its peer-supplied -/// `row_repo` slug) should be shown to `caller` (None = anonymous) on the -/// cross-repo ref-updates feeds (#112 GraphQL, #114 REST). -/// -/// Pure and I/O-free: both call sites load the deduped local repo set and its -/// visibility rules once per request and pass them in, so the gate logic lives -/// here and visibility.rs keeps its "no I/O" property. -/// -/// The slug is written verbatim from the inbound gossip/notify message, so it is -/// untrusted input, not a canonical key. The decision is fail-closed by -/// construction: the only KEEP paths are (a) a slug with no `/` (cannot name a -/// local `owner/name` pair, so remote by definition), (b) all matched local -/// records are readable, and (c) no local record matches (remote/gossip-only). -/// Any local match the caller cannot read at root DROPs the row. There is no -/// catch-all keep on unexpected state. -/// -/// Slug/record owner keys are matched prefix-tolerantly (one is a prefix of the -/// other), covering the exact short-key, the full `did:key:` form, and the -/// URL-truncated 8-char form. Prefix over-match can only over-drop a genuinely -/// remote row (fail-safe), never over-serve a private local one. -/// -/// The live call sites are the #112 (GraphQL) and #114 (REST) feed handlers, -/// added in the following units; exercised by the unit tests below meanwhile. -pub fn ref_update_row_visible( - deduped: &[RepoRecord], - rules_by_repo: &HashMap>, - caller: Option<&str>, - row_repo: &str, -) -> bool { - // A slug with no '/' cannot name a local owner/name pair — remote by - // definition (same branch as "matches nothing local") → KEEP. - if row_repo.rsplit_once('/').is_none() { - return true; - } +/// Request-local index for the REST and GraphQL ref-update feed gate. +pub(crate) struct RefUpdateRepoIndex<'a> { + by_name: HashMap<&'a str, Vec>>, +} - // Match each local record with the shared slug predicate (one matcher, so - // this gate and the collector's quarantine drop cannot disagree about which - // rows a repo owns), then fail closed on any matched record the caller - // cannot read at root. - for record in deduped { - if !ref_update_row_names_repo(record, row_repo) { - continue; +enum RefUpdateCandidate<'a> { + Quarantined(&'a RepoRecord), + Active(&'a RepoRecord), +} + +impl<'a> RefUpdateRepoIndex<'a> { + pub(crate) fn new(deduped: &'a [RepoRecord], quarantined: &'a [RepoRecord]) -> Self { + let mut by_name = HashMap::<_, Vec<_>>::new(); + for record in quarantined { + by_name + .entry(record.name.as_str()) + .or_default() + .push(RefUpdateCandidate::Quarantined(record)); } - let rules = rules_by_repo - .get(&record.id) - .map(Vec::as_slice) - .unwrap_or(&[]); - if !listable_at_root(rules, record.is_public, &record.owner_did, caller) { - return false; + for record in deduped { + by_name + .entry(record.name.as_str()) + .or_default() + .push(RefUpdateCandidate::Active(record)); } + Self { by_name } } - // Reached only if every matched local record is readable, or nothing local - // matched (remote/gossip-only). Both are the KEEP paths; there is no - // default-keep on unexpected state — an unreadable match already returned. - true + /// The peer-supplied slug is not a canonical key. Keep rows that match no + /// local repo, and drop on any match that is quarantined or unreadable at + /// root. Quarantine is checked first and applies even to the repo's owner. + pub(crate) fn row_visible( + &self, + rules_by_repo: &HashMap>, + caller: Option<&str>, + row_repo: &str, + ) -> bool { + let Some((_, name)) = row_repo.rsplit_once('/') else { + return true; + }; + let Some(candidates) = self.by_name.get(name) else { + return true; + }; + for candidate in candidates { + let (record, quarantined) = match candidate { + RefUpdateCandidate::Quarantined(record) => (record, true), + RefUpdateCandidate::Active(record) => (record, false), + }; + if !ref_update_row_names_repo(record, row_repo) { + continue; + } + if quarantined { + return false; + } + let rules = rules_by_repo + .get(&record.id) + .map(Vec::as_slice) + .unwrap_or(&[]); + if !listable_at_root(rules, record.is_public, &record.owner_did, caller) { + return false; + } + } + true + } } /// Whether `row_repo`'s peer-supplied slug names the local `record`. The single -/// match predicate shared by the feed gate ([`ref_update_row_visible`]) and the -/// quarantine hard-drop in the ref-update collector, so the two cannot diverge -/// about which rows a repo owns — a second, drifting matcher is exactly the #134 -/// slug-collision class. +/// match predicate shared by the visibility check and quarantine veto in +/// [`RefUpdateRepoIndex::row_visible`], so they cannot diverge about which rows a +/// repo owns. /// /// A record matches when the slug's `name` half is equal and one owner key is a /// prefix of the other (prefix-tolerant: exact short key, full `did:key:` form, @@ -212,7 +219,7 @@ pub fn ref_update_row_visible( /// when a remote owner shares both a trailing segment and a repo name with a local /// private repo (negligible for full did:key ids; only did:web / truncated forms /// collide): it can hide a genuinely remote row, never serve a private one. -pub fn ref_update_row_names_repo(record: &RepoRecord, row_repo: &str) -> bool { +fn ref_update_row_names_repo(record: &RepoRecord, row_repo: &str) -> bool { let Some((owner_part, name)) = row_repo.rsplit_once('/') else { return false; }; @@ -583,7 +590,7 @@ mod tests { )); } - // ── ref_update_row_visible (feed gate) ────────────────────────────────── + // ── Ref-update feed gate ────────────────────────────────────────────── fn rec(id: &str, owner_did: &str, name: &str, is_public: bool) -> RepoRecord { RepoRecord { @@ -608,6 +615,15 @@ mod tests { .collect() } + fn ref_update_row_visible( + deduped: &[RepoRecord], + rules: &HashMap>, + caller: Option<&str>, + slug: &str, + ) -> bool { + RefUpdateRepoIndex::new(deduped, &[]).row_visible(rules, caller, slug) + } + #[test] fn feed_public_local_repo_kept_for_anon() { let deduped = [rec("r1", "did:key:z6MkOwner", "widget", true)]; @@ -837,6 +853,272 @@ mod tests { assert!(!ref_update_row_names_repo(&bare, "noslash")); } + #[test] + fn feed_checks_every_same_name_candidate() { + let deduped = [ + rec("public", "did:key:team-public", "widget", true), + rec("private", "did:web:host:team-private", "widget", false), + rec("case", "did:key:team", "Widget", false), + ]; + let quarantined = [ + rec("unrelated", "did:key:other", "widget", true), + rec("quarantined", "did:key:team-quarantined", "widget", true), + ]; + let rules = HashMap::new(); + let active = RefUpdateRepoIndex::new(&deduped, &[]); + assert!(!active.row_visible(&rules, None, "team/widget")); + let caller = Some("did:web:host:team-private"); + assert!(active.row_visible(&rules, caller, "team/widget")); + let all = RefUpdateRepoIndex::new(&deduped, &quarantined); + assert!(!all.row_visible(&rules, caller, "team/widget")); + assert!(!all.row_visible( + &rules, + Some("did:key:team-quarantined"), + "team-quarantined/widget" + )); + assert!(all.row_visible(&rules, None, "team-public/widget")); + assert!(all.row_visible(&rules, None, "team-public/WIDGET")); + } + + // The unindexed collector's quarantine scan and root gate from main. + fn full_scan_row_visible( + deduped: &[RepoRecord], + quarantined: &[RepoRecord], + rules_by_repo: &HashMap>, + caller: Option<&str>, + row_repo: &str, + ) -> bool { + if quarantined + .iter() + .any(|q| ref_update_row_names_repo(q, row_repo)) + { + return false; + } + if row_repo.rsplit_once('/').is_none() { + return true; + } + for record in deduped { + if !ref_update_row_names_repo(record, row_repo) { + continue; + } + let rules = rules_by_repo + .get(&record.id) + .map(Vec::as_slice) + .unwrap_or(&[]); + if !listable_at_root(rules, record.is_public, &record.owner_did, caller) { + return false; + } + } + true + } + + fn filter_ref_update_window( + rows: &[(usize, String)], + mut visible: impl FnMut(&str) -> bool, + ) -> Vec<&(usize, String)> { + rows.iter().filter(|(_, slug)| visible(slug)).collect() + } + + #[test] + fn feed_index_matches_full_scan_rows_and_order() { + use rand::{rngs::StdRng, seq::SliceRandom, Rng, SeedableRng}; + + let mut rng = StdRng::seed_from_u64(0x2137); + let mut deduped = Vec::new(); + let mut quarantined = Vec::new(); + let mut rules = HashMap::new(); + for name in 0..4096 { + for owner in ["team-alice", "team-bob", "unrelated"] { + let id = format!("{name}-{owner}"); + let record = rec( + &id, + &format!("did:web:host:{owner}"), + &format!("repo-{name}"), + rng.gen_bool(0.4), + ); + if rng.gen_bool(0.1) { + quarantined.push(record); + } else { + if rng.gen_bool(0.25) { + let mode = if rng.gen_bool(0.5) { + VisibilityMode::A + } else { + VisibilityMode::B + }; + rules.insert(id, vec![rule("/", mode, &["did:key:friend"])]); + } + deduped.push(record); + } + } + } + deduped.shuffle(&mut rng); + quarantined.shuffle(&mut rng); + let rows: Vec<_> = (0..2048) + .rev() + .map(|id| { + let name = rng.gen_range(0..4608); + let owner = [ + "team", + "team-alice", + "team-bob-long", + "did:key:team-b", + "", + "remote", + ] + .choose(&mut rng) + .unwrap(); + let slug = if rng.gen_bool(0.02) { + format!("repo-{name}") + } else { + format!("{owner}/repo-{name}") + }; + (id, slug) + }) + .collect(); + let repos = RefUpdateRepoIndex::new(&deduped, &quarantined); + for caller in [ + None, + Some("did:web:host:team-alice"), + Some("did:key:friend"), + ] { + let before = filter_ref_update_window(&rows, |slug| { + full_scan_row_visible(&deduped, &quarantined, &rules, caller, slug) + }); + let after = + filter_ref_update_window(&rows, |slug| repos.row_visible(&rules, caller, slug)); + assert!(!before.is_empty() && before.len() < rows.len()); + assert_eq!(after, before, "caller: {caller:?}"); + } + } + + #[cfg(target_os = "linux")] + #[test] + #[ignore = "release-mode timing harness"] + fn bench_ref_update_visibility() { + use std::hint::black_box; + use std::time::{Duration, Instant}; + + fn thread_cpu() -> Duration { + let mut time = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: time is a valid, writable timespec. + assert_eq!( + unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) }, + 0 + ); + Duration::new(time.tv_sec as u64, time.tv_nsec as u32) + } + + fn sample(mut f: impl FnMut() -> usize) -> (Duration, Duration) { + let cpu = thread_cpu(); + let wall = Instant::now(); + assert_eq!(black_box(f()), 128); + let elapsed = wall.elapsed(); + (thread_cpu() - cpu, elapsed) + } + + fn report(label: &str, calls: usize, mut samples: Vec<(Duration, Duration)>) { + let cpu = samples + .iter() + .map(|(cpu, _)| cpu.as_secs_f64()) + .sum::(); + samples.sort_unstable_by_key(|(_, wall)| *wall); + let p95 = samples[samples.len() * 95 / 100 - 1].1; + println!( + "{label}: {calls} matcher calls/window, {:.3} ms mean thread CPU/window, {:.3} ms p95 wall/window", + 1000.0 * cpu / samples.len() as f64, + 1000.0 * p95.as_secs_f64(), + ); + } + + const ACTIVE: usize = 30_000; + const QUARANTINED: usize = 2_000; + let deduped: Vec<_> = (0..ACTIVE) + .map(|i| { + let id = format!("a{i}"); + match i % 16 { + 0 => rec( + &id, + "did:key:team-other", + &format!("private-{}", i / 16), + true, + ), + 1 => rec( + &id, + "did:key:team-private", + &format!("private-{}", i / 16), + false, + ), + _ => rec(&id, OWNER, &format!("active-{i}"), true), + } + }) + .collect(); + let quarantined: Vec<_> = (0..QUARANTINED) + .map(|i| { + let id = format!("q{i}"); + match i % 15 { + 0 => rec(&id, "did:key:other", &format!("mirror-{}", i / 15), true), + 1 => rec( + &id, + "did:web:host:team-mirror", + &format!("mirror-{}", i / 15), + true, + ), + _ => rec(&id, OWNER, &format!("quarantined-{i}"), true), + } + }) + .collect(); + let rows: Vec<_> = (0..2048) + .rev() + .map(|id| { + let slug = match id % 16 { + 0 => format!("remote/off-node-{id}"), + 1 => format!("team/mirror-{}", id / 16), + offset => format!("team/private-{}", (id / 16) * 14 + offset - 2), + }; + (id, slug) + }) + .collect(); + let rules = HashMap::new(); + let before = || { + filter_ref_update_window(black_box(&rows), |slug| { + full_scan_row_visible(&deduped, &quarantined, &rules, None, slug) + }) + }; + let after = || { + let repos = RefUpdateRepoIndex::new(black_box(&deduped), black_box(&quarantined)); + filter_ref_update_window(black_box(&rows), |slug| { + repos.row_visible(&rules, None, slug) + }) + }; + assert_eq!(before(), after()); + let mut old_samples = Vec::new(); + let mut new_samples = Vec::new(); + for i in 0..40 { + let mut old = || old_samples.push(sample(|| black_box(before()).len())); + let mut new = || new_samples.push(sample(|| black_box(after()).len())); + if i % 2 == 0 { + old(); + new(); + } else { + new(); + old(); + } + } + // Count calls from the fixture positions, without instrumenting the timed gates. + let remote_calls = 128 * (ACTIVE + QUARANTINED); + let mirror_calls: usize = (0..128).map(|i| i * 15 + 2).sum(); + let private_calls: usize = (0..1792).map(|i| QUARANTINED + i * 16 + 2).sum(); + report( + "before", + remote_calls + mirror_calls + private_calls, + old_samples, + ); + report("after", (128 + 1792) * 2, new_samples); + } + // #101: a deny rule must withhold a path that denotes the same characters in // a different Unicode normalization form. Without NFC normalization at the // matcher seam, an NFC-authored rule byte-compares unequal to an NFD-stored From 5ba570ced28f33f1afc693ce759ec106ed8111d9 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:34:13 -0600 Subject: [PATCH 2/2] docs(node): update stale quarantine comment in ref-update collector --- crates/twigpine-node/src/api/events.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-node/src/api/events.rs b/crates/twigpine-node/src/api/events.rs index 506bcf74f..697f0bca8 100644 --- a/crates/twigpine-node/src/api/events.rs +++ b/crates/twigpine-node/src/api/events.rs @@ -73,9 +73,10 @@ async fn collect_visible_ref_updates_inner( // at admission, checked separately from the mirror's (untrustworthy) // visibility fields. A folded is_public=false cannot enforce that here — // visibility_check short-circuits to Allow for the owner before is_public is - // read, so an owner-matched row would leak. Instead, drop any row that names a - // quarantined repo in the loop below, before the visibility gate runs, so the - // drop bypasses that owner short-circuit entirely. + // read, so an owner-matched row would leak. Instead, the loop below calls + // RefUpdateRepoIndex::row_visible, which vetoes any row that names a + // quarantined repo before it checks visibility, so the drop bypasses that + // owner short-circuit entirely. let quarantined = db.list_quarantined_repos().await?; let ids: Vec = deduped.iter().map(|r| r.id.clone()).collect(); let rules = db.list_visibility_rules_for_repos(&ids).await?;