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.
This commit is contained in:
Lorenz Leutgeb
2026-11-06 17:44:00 +01:00
parent 795638dae0
commit 4724dd4987
10 changed files with 153 additions and 46 deletions
+4 -4
View File
@@ -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<storage::git::Repository>,
doc: Doc,
project: Option<Project>,
}
+3 -3
View File
@@ -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();
}
+2 -2
View File
@@ -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 {
+1 -2
View File
@@ -336,8 +336,7 @@ fn set_canonical_refs(
) -> Result<Option<UpdatedCanonicalRefs>, 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) {
+7 -12
View File
@@ -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<Signer>(
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()?)
+6 -3
View File
@@ -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]
+8 -6
View File
@@ -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<Oid, RepositoryError>;
/// Load the identity history.
fn identity(&self) -> Result<Identity, RepositoryError>
where
Self: cob::Store,
{
Identity::load(self)
/// Borrow the identity of this repository.
fn identity(&self) -> Result<Ref<'_, Identity>, 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<Ref<'_, Identity>, cob::store::Error>;
/// Compute the canonical `rad/id` of this repository.
///
/// Ignores any existing `rad/id` reference.
+104 -14
View File
@@ -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<Option<CachedIdentity>>,
/// The root of the last resolved `rad/id` commit.
cached_identity_root: Cell<Option<CachedIdentityRoot>>,
}
#[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<Oid>,
/// The actual evaluated identity being cached.
identity: Identity,
}
impl AsRef<Repository> 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<Oid, RepositoryError> {
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<DocAt, IdentityDocError> {
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<Oid, RepositoryError> {
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<CellRef<'_, Identity>, 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<Oid, RepositoryError> {
@@ -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<Oid, crate::git::raw::Error> {
+8
View File
@@ -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<R: storage::ReadRepository> ReadRepository for DraftStore<'_, R> {
self.repo.identity_root()
}
fn identity_from(
&self,
root: &ObjectId,
) -> Result<CellRef<'_, identity::Identity>, store::Error> {
self.repo.identity_from(root)
}
fn canonical_identity_head(&self) -> Result<Oid, RepositoryError> {
self.repo.canonical_identity_head()
}
+10
View File
@@ -311,6 +311,16 @@ impl ReadRepository for MockRepository {
Ok(self.doc.clone())
}
fn identity_from(
&self,
root: &crate::cob::ObjectId,
) -> Result<std::cell::Ref<'_, crate::identity::Identity>, crate::cob::store::Error> {
Err(crate::cob::store::Error::NotFound(
crate::identity::TYPENAME.clone(),
*root,
))
}
fn identity_doc_at(&self, _head: Oid) -> Result<crate::identity::DocAt, IdentityDocError> {
Ok(self.doc.clone())
}