From 4724dd49875075c4ba75ef8d40b153578d9d0fdd Mon Sep 17 00:00:00 2001 From: Lorenz Leutgeb Date: Mon, 2 Nov 2026 21:08:51 +0100 Subject: [PATCH] radicle/storage: Cache evaluated identity COB Cache the evaluated identity per repository handle, keyed by its root and the set of COB tips. Read the refs on each lookup to detect writes through other handles. --- crates/radicle-cli/src/commands/clone.rs | 8 +- crates/radicle-cli/src/commands/inbox.rs | 6 +- crates/radicle-cli/src/commands/inspect.rs | 4 +- crates/radicle-node/src/worker/fetch.rs | 3 +- crates/radicle-remote-helper/src/push.rs | 19 ++-- crates/radicle/src/cob/identity.rs | 9 +- crates/radicle/src/storage.rs | 14 +-- crates/radicle/src/storage/git.rs | 118 ++++++++++++++++++--- crates/radicle/src/storage/git/cob.rs | 8 ++ crates/radicle/src/test/storage.rs | 10 ++ 10 files changed, 153 insertions(+), 46 deletions(-) diff --git a/crates/radicle-cli/src/commands/clone.rs b/crates/radicle-cli/src/commands/clone.rs index 8629e88ba..fae6cdb7e 100644 --- a/crates/radicle-cli/src/commands/clone.rs +++ b/crates/radicle-cli/src/commands/clone.rs @@ -94,8 +94,8 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { info.push([term::format::italic(project.description()).into()]); } - let issues = term::cob::issues(&profile, &repo)?.counts()?; - let patches = term::cob::patches(&profile, &repo)?.counts()?; + let issues = term::cob::issues(&profile, repo.as_ref())?.counts()?; + let patches = term::cob::patches(&profile, repo.as_ref())?.counts()?; info.push([term::Line::spaced([ term::format::tertiary(issues.open).into(), @@ -210,7 +210,7 @@ impl Checkout { spinner.finish(); Ok(CloneResult::Success(Success { working_copy, - repository: self.repository, + repository: Box::new(self.repository), doc: self.doc, project: self.project, })) @@ -302,7 +302,7 @@ enum CloneResult { struct Success { working_copy: raw::Repository, - repository: storage::git::Repository, + repository: Box, doc: Doc, project: Option, } diff --git a/crates/radicle-cli/src/commands/inbox.rs b/crates/radicle-cli/src/commands/inbox.rs index 66ed1e029..0070b9fd1 100644 --- a/crates/radicle-cli/src/commands/inbox.rs +++ b/crates/radicle-cli/src/commands/inbox.rs @@ -9,7 +9,7 @@ use localtime::LocalTime; use radicle::cob::TypedId; use radicle::git::BranchName; use radicle::git::fmt::{Component, Qualified}; -use radicle::identity::{Identity, doc::GetPayload as _}; +use radicle::identity::doc::GetPayload as _; use radicle::issue::cache::Issues as _; use radicle::node::notifications; use radicle::node::notifications::*; @@ -339,7 +339,7 @@ impl NotificationRow { term::format::patch::state(patch.state()), ) } else if typed_id.is_identity() { - let Ok(identity) = Identity::get(id, repo) else { + let Ok(identity) = repo.identity_from(id) else { log::error!( target: "cli", "Error retrieving identity {id} for notification {}", n.id @@ -438,7 +438,7 @@ fn show( term::patch::show(&patch, &typed_id.id, false, &repo, None, profile)?; } NotificationKind::Cob { typed_id } if typed_id.is_identity() => { - let identity = Identity::get(&typed_id.id, &repo)?; + let identity = repo.identity_from(&typed_id.id)?; term::json::to_pretty(&identity.doc, Path::new("radicle.json"))?.print(); } diff --git a/crates/radicle-cli/src/commands/inspect.rs b/crates/radicle-cli/src/commands/inspect.rs index 977730078..c4e620788 100644 --- a/crates/radicle-cli/src/commands/inspect.rs +++ b/crates/radicle-cli/src/commands/inspect.rs @@ -7,8 +7,8 @@ use std::str::FromStr; use anyhow::Context as _; use chrono::prelude::*; +use radicle::identity::DocAt; use radicle::identity::RepoId; -use radicle::identity::{DocAt, Identity}; use radicle::node::AliasStore as _; use radicle::node::policy::SeedingPolicy; use radicle::storage::git::{Repository, Storage}; @@ -148,8 +148,8 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { } Target::History => { let (repo, _) = repo(rid, storage)?; - let identity = Identity::load(&repo)?; let head = repo.identity_head()?; + let identity = repo.identity()?; let history = repo.revwalk(head)?; for oid in history { diff --git a/crates/radicle-node/src/worker/fetch.rs b/crates/radicle-node/src/worker/fetch.rs index 29a02a87d..eb167cbaf 100644 --- a/crates/radicle-node/src/worker/fetch.rs +++ b/crates/radicle-node/src/worker/fetch.rs @@ -336,8 +336,7 @@ fn set_canonical_refs( ) -> Result, error::Canonical> { const LOG_MESSAGE: &str = "set-canonical-reference from fetch (radicle)"; - let identity = repo.identity()?; - let crefs = identity.doc().canonical_refs()?; + let crefs = repo.identity()?.doc().canonical_refs()?; for (name, target) in crefs.symbolic().iter() { if let Err(e) = repo.set_symbolic_ref(name, target, LOG_MESSAGE) { diff --git a/crates/radicle-remote-helper/src/push.rs b/crates/radicle-remote-helper/src/push.rs index 7d5129607..6b1ad1f97 100644 --- a/crates/radicle-remote-helper/src/push.rs +++ b/crates/radicle-remote-helper/src/push.rs @@ -378,8 +378,7 @@ pub(super) fn run( git, ), PushAction::PushRef { dst } => { - let identity = stored.identity()?; - let crefs = identity.doc().canonical_refs()?; + let crefs = stored.identity()?.doc().canonical_refs()?; let rules = crefs.rules(); let me = Did::from(nid); @@ -836,8 +835,8 @@ where }; if let Some(old) = old { - let identity = stored.identity()?; - let crefs = identity.doc().canonical_refs()?; + let doc = stored.identity()?.doc().clone(); + let crefs = doc.canonical_refs()?; let rules = crefs.rules(); let me = Did::from(nid); @@ -846,8 +845,8 @@ where if let Some((_, rule)) = rules.matches(dst).next() && rule.allowed().contains(&me) { - patch_revert_all(old, head, dst, &stored.backend, &mut patches, &identity)?; - patch_merge_all(old, head, dst, working, &mut patches, signer, &identity)?; + patch_revert_all(old, head, dst, &stored.backend, &mut patches, &doc)?; + patch_merge_all(old, head, dst, working, &mut patches, signer, &doc)?; } } // Annotated tags point to a tag object, but the explorer can only show @@ -875,7 +874,7 @@ fn patch_revert_all( WriteAs<'_, impl crypto::Signer>, cob::cache::StoreWriter, >, - identity: &radicle::identity::Identity, + identity_doc: &identity::Doc, ) -> Result<(), Error> { // Find all commits reachable from the old OID but not from the new OID. let mut revwalk = stored.revwalk()?; @@ -890,8 +889,6 @@ fn patch_revert_all( return Ok(()); } - let identity_doc = identity.doc(); - // Get the list of merged patches. let merged = patches .merged()? @@ -959,7 +956,7 @@ fn patch_merge_all( cob::cache::StoreWriter, >, signer: &Signer, - identity: &radicle::identity::Identity, + identity_doc: &identity::Doc, ) -> Result<(), Error> where Signer: crypto::Signer, @@ -975,8 +972,6 @@ where return Ok(()); } - let identity_doc = identity.doc(); - let open = patches .opened()? .chain(patches.drafted()?) diff --git a/crates/radicle/src/cob/identity.rs b/crates/radicle/src/cob/identity.rs index 15d9ab9c6..ad95c401d 100644 --- a/crates/radicle/src/cob/identity.rs +++ b/crates/radicle/src/cob/identity.rs @@ -1524,9 +1524,12 @@ mod test { assert_eq!(repo.canonical_identity_doc().unwrap().commit, r2); repo.set_identity_head_to(identity.current).unwrap(); - assert_eq!(repo.identity_doc_at(r0).unwrap().commit, r0); - assert_eq!(repo.identity_doc_at(r1).unwrap().commit, r1); - assert_eq!(repo.identity_doc_at(r2).unwrap().commit, r2); + for revision in [r0, r1, r2] { + assert_eq!( + repo.identity_doc_at(revision).unwrap(), + Doc::load_at(revision, &*repo).unwrap() + ); + } } #[test] diff --git a/crates/radicle/src/storage.rs b/crates/radicle/src/storage.rs index 2812ccaf9..55d310d5b 100644 --- a/crates/radicle/src/storage.rs +++ b/crates/radicle/src/storage.rs @@ -1,6 +1,7 @@ pub mod git; pub mod refs; +use std::cell::Ref; use std::collections::{HashSet, hash_map}; use std::ops::Deref; use std::path::{Path, PathBuf}; @@ -565,14 +566,15 @@ pub trait ReadRepository: Sized + ValidateRepository { /// Get the root commit of the canonical identity branch. fn identity_root(&self) -> Result; - /// Load the identity history. - fn identity(&self) -> Result - where - Self: cob::Store, - { - Identity::load(self) + /// Borrow the identity of this repository. + fn identity(&self) -> Result, RepositoryError> { + let root = self.identity_root()?; + Ok(self.identity_from(&root.into())?) } + /// Borrow the identity history for a specific COB root. + fn identity_from(&self, root: &cob::ObjectId) -> Result, cob::store::Error>; + /// Compute the canonical `rad/id` of this repository. /// /// Ignores any existing `rad/id` reference. diff --git a/crates/radicle/src/storage/git.rs b/crates/radicle/src/storage/git.rs index 405f5f56d..c281936a9 100644 --- a/crates/radicle/src/storage/git.rs +++ b/crates/radicle/src/storage/git.rs @@ -5,12 +5,16 @@ pub mod transport; pub mod temp; pub use temp::TempRepository; +use std::cell::{Cell, Ref as CellRef, RefCell}; use std::collections::{BTreeMap, BTreeSet}; use std::ops::{Deref, DerefMut}; use std::path::{Path, PathBuf}; use std::sync::LazyLock; use std::{fs, io}; +use crate::cob::identity::TYPENAME as IDENTITY_TYPENAME; +use crate::cob::object::{self, collaboration::get_from_objects}; +use crate::cob::{ObjectId, error, store}; use crate::git::canonical::Quorum; use crate::git::raw::ErrorExt as _; use crate::identity::doc::{DocError, GetPayload as _}; @@ -299,6 +303,26 @@ pub struct Repository { pub id: RepoId, /// The backing Git repository. pub backend: git::raw::Repository, + /// A cache of the evaluated identity. + cached_identity: RefCell>, + /// The root of the last resolved `rad/id` commit. + cached_identity_root: Cell>, +} + +#[derive(Clone, Copy)] +struct CachedIdentityRoot { + /// The commit referenced by `rad/id` when the root was resolved. + head: Oid, + /// The root commit of that identity history. + root: Oid, +} + +struct CachedIdentity { + root: ObjectId, + /// Tips of the various COB references that were considered. + tips: BTreeSet, + /// The actual evaluated identity being cached. + identity: Identity, } impl AsRef for Repository { @@ -423,7 +447,12 @@ impl Repository { &[] as &[&std::ffi::OsStr], )?; - Ok(Self { id, backend }) + Ok(Self { + id, + backend, + cached_identity: RefCell::default(), + cached_identity_root: Cell::default(), + }) } /// Create a new repository. @@ -456,7 +485,21 @@ impl Repository { config.set_str("user.name", &info.name())?; config.set_str("user.email", &info.email())?; - Ok(Self { id, backend }) + Ok(Self { + id, + backend, + cached_identity: RefCell::default(), + cached_identity_root: Cell::default(), + }) + } + + fn identity_root_at(&self, head: Oid) -> Result { + let root = self + .revwalk(head)? + .last() + .ok_or(RepositoryError::Doc(DocError::Missing))??; + + Ok(root.into()) } /// Remove an existing repository @@ -833,11 +876,17 @@ impl ReadRepository for Repository { } fn identity_doc_at(&self, head: Oid) -> Result { - let identity = Identity::load(self)?; - if !identity.revision(&head).is_some_and(|r| r.is_accepted()) { - return Err(IdentityDocError::UnacceptedRevision(head)); - } - Ok(Doc::load_at(head, self)?) + let identity = self.identity()?; + let revision = identity + .revision(&head) + .filter(|r| r.is_accepted()) + .ok_or(IdentityDocError::UnacceptedRevision(head))?; + + Ok(DocAt { + commit: revision.id, + blob: revision.blob, + doc: revision.doc.clone(), + }) } fn head(&self) -> Result<(Qualified<'_>, Oid), RepositoryError> { @@ -884,13 +933,54 @@ impl ReadRepository for Repository { } fn identity_root(&self) -> Result { - let oid = self.backend.refname_to_id(CANONICAL_IDENTITY.as_str())?; - let root = self - .revwalk(oid.into())? - .last() - .ok_or(RepositoryError::Doc(DocError::Missing))??; + let head = self + .backend + .refname_to_id(CANONICAL_IDENTITY.as_str())? + .into(); + if let Some(cached) = self.cached_identity_root.get() + && cached.head == head + { + return Ok(cached.root); + } + let root = self.identity_root_at(head)?; + self.cached_identity_root + .set(Some(CachedIdentityRoot { head, root })); - Ok(root.into()) + Ok(root) + } + + fn identity_from(&self, root: &ObjectId) -> Result, store::Error> { + // Another handle or process may have changed the refs. Evaluate exactly + // this snapshot of the refs, so the cache key matches the evaluation. + let refs = object::Storage::objects(self, &IDENTITY_TYPENAME, root) + .map_err(|err| error::Retrieve::Refs { err: Box::new(err) })?; + let tips = refs.iter().map(|r| r.target.id).collect(); + let mut cached = self.cached_identity.borrow(); + + if !cached + .as_ref() + .is_some_and(|cached| cached.root == *root && cached.tips == tips) + { + drop(cached); + + let identity = get_from_objects(self, &IDENTITY_TYPENAME, root, &refs)? + .ok_or_else(|| store::Error::NotFound(IDENTITY_TYPENAME.clone(), *root))? + .object; + + *self.cached_identity.borrow_mut() = Some(CachedIdentity { + root: *root, + tips, + identity, + }); + cached = self.cached_identity.borrow(); + } + + Ok(CellRef::map(cached, |cached| { + &cached + .as_ref() + .expect("identity cache is populated") + .identity + })) } fn canonical_identity_head(&self) -> Result { @@ -944,7 +1034,7 @@ impl ReadRepository for Repository { return Err(RepositoryError::Doc(DocError::Missing)); } - Ok(Identity::get(&root.into(), self)?.head()) + Ok(self.identity_from(&root.into())?.head()) } fn merge_base(&self, left: &Oid, right: &Oid) -> Result { diff --git a/crates/radicle/src/storage/git/cob.rs b/crates/radicle/src/storage/git/cob.rs index b5a4f8f45..aad3c7cc3 100644 --- a/crates/radicle/src/storage/git/cob.rs +++ b/crates/radicle/src/storage/git/cob.rs @@ -1,4 +1,5 @@ //! COB storage Git backend. +use std::cell::Ref as CellRef; use std::collections::BTreeMap; use std::path::Path; @@ -384,6 +385,13 @@ impl ReadRepository for DraftStore<'_, R> { self.repo.identity_root() } + fn identity_from( + &self, + root: &ObjectId, + ) -> Result, store::Error> { + self.repo.identity_from(root) + } + fn canonical_identity_head(&self) -> Result { self.repo.canonical_identity_head() } diff --git a/crates/radicle/src/test/storage.rs b/crates/radicle/src/test/storage.rs index 01ebc5232..ba2357afa 100644 --- a/crates/radicle/src/test/storage.rs +++ b/crates/radicle/src/test/storage.rs @@ -311,6 +311,16 @@ impl ReadRepository for MockRepository { Ok(self.doc.clone()) } + fn identity_from( + &self, + root: &crate::cob::ObjectId, + ) -> Result, crate::cob::store::Error> { + Err(crate::cob::store::Error::NotFound( + crate::identity::TYPENAME.clone(), + *root, + )) + } + fn identity_doc_at(&self, _head: Oid) -> Result { Ok(self.doc.clone()) }