use std::collections::{BTreeSet, HashMap};
use serde::Serialize;
use super::Engine;
use crate::check::{CheckRecord, CheckState};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Independence {
ConfirmedIndependent,
SelfChecked,
Unconfirmable,
}
impl Independence {
pub const ALL: [Self; 3] = [
Self::ConfirmedIndependent,
Self::SelfChecked,
Self::Unconfirmable,
];
pub fn as_str(self) -> &'static str {
match self {
Self::ConfirmedIndependent => "confirmed_independent",
Self::SelfChecked => "self_checked",
Self::Unconfirmable => "unconfirmable",
}
}
pub fn from_wire(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|r| r.as_str() == s)
}
pub fn vocabulary_hint() -> String {
Self::ALL
.iter()
.map(|r| r.as_str())
.collect::<Vec<_>>()
.join(", ")
}
}
pub const LABEL_ROLE_AUTHOR: &str = "role_author";
pub const LABEL_ROLE_UNSPECIFIED: &str = "role_unspecified";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckStanding {
pub state: CheckState,
pub independence: Option<Independence>,
pub role: crate::vcs::Role,
}
impl CheckStanding {
pub fn assumed_independent(state: CheckState) -> Self {
Self {
state,
independence: (state == CheckState::CheckedOk)
.then_some(Independence::ConfirmedIndependent),
role: crate::vcs::Role::Checker,
}
}
pub fn role_confirms(&self) -> bool {
matches!(
self.role,
crate::vcs::Role::Checker | crate::vcs::Role::Verifier
)
}
pub fn confirms(&self) -> bool {
self.state == CheckState::CheckedOk
&& self.independence == Some(Independence::ConfirmedIndependent)
&& self.role_confirms()
}
pub fn label(&self) -> &'static str {
match (self.state, self.independence) {
(CheckState::CheckedOk, Some(Independence::ConfirmedIndependent)) => match self.role {
crate::vcs::Role::Checker | crate::vcs::Role::Verifier => {
Independence::ConfirmedIndependent.as_str()
}
crate::vcs::Role::Author => LABEL_ROLE_AUTHOR,
crate::vcs::Role::Unspecified => LABEL_ROLE_UNSPECIFIED,
},
(CheckState::CheckedOk, Some(i)) => i.as_str(),
(CheckState::CheckedOk, None) => Independence::Unconfirmable.as_str(),
(s, _) => s.as_str(),
}
}
}
#[derive(Debug, Default, Clone)]
pub struct MemTouches {
by_entity: HashMap<String, Vec<(i64, Option<String>)>>,
renames: Vec<(i64, String, String)>,
}
impl MemTouches {
fn absorb(&mut self, entity_field: &str, ts: i64, identity: Option<String>) {
match super::history::parse_rename_pair(entity_field) {
Some((old, new)) => {
self.by_entity
.entry(old.clone())
.or_default()
.push((ts, identity.clone()));
self.by_entity
.entry(new.clone())
.or_default()
.push((ts, identity));
self.renames.push((ts, old, new));
}
None => self
.by_entity
.entry(entity_field.to_string())
.or_default()
.push((ts, identity)),
}
}
fn follow_renames(&mut self) {
let mut renames = std::mem::take(&mut self.renames);
renames.sort_by_key(|r| r.0);
for (_, old, new) in &renames {
let inherited = self.by_entity.get(old).cloned().unwrap_or_default();
let target = self.by_entity.entry(new.clone()).or_default();
for touch in inherited {
if !target.contains(&touch) {
target.push(touch);
}
}
}
self.renames = renames;
}
fn written_at(&self, entity: &str) -> Option<i64> {
self.by_entity
.get(entity)
.and_then(|t| t.iter().map(|(ts, _)| *ts).min())
}
fn identities_since(&self, entity: &str, since: i64, into: &mut BTreeSet<String>) {
if let Some(touches) = self.by_entity.get(entity) {
for (ts, id) in touches {
if *ts >= since
&& let Some(id) = id
{
into.insert(id.clone());
}
}
}
}
fn any_identity(&self, entity: &str) -> bool {
self.by_entity
.get(entity)
.is_some_and(|t| t.iter().any(|(_, id)| id.is_some()))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Executors {
pub identities: Vec<String>,
pub plans: Vec<String>,
}
impl Engine {
pub fn mem_touches(&self, mem: &str) -> MemTouches {
let mut out = MemTouches::default();
let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
return out;
};
match &m.mount.storage {
crate::workspace::MountStorage::GitBranch { gitdir, branch } => {
if let Some(hook) = self.git_branch_ops.as_ref()
&& let Ok(changes) = (hook.changes_since)(
gitdir,
branch,
mem,
crate::ops::EMPTY_TREE_SHA,
crate::ops::RENAME_SIMILARITY_DEFAULT,
)
{
for n in &changes.notes {
if let Some(entity) = n.entity_id.as_deref() {
out.absorb(entity, n.timestamp, n.identity.clone());
}
for entity in &n.entity_ids {
out.absorb(entity, n.timestamp, n.identity.clone());
}
}
out.follow_renames();
}
}
crate::workspace::MountStorage::Folder { .. }
| crate::workspace::MountStorage::InMemory => {
if let Ok(records) = m.backend.read_provenance(None) {
for r in records {
let Some(entity) = r.entity.as_deref() else {
continue;
};
let ts = r
.timestamp
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
out.by_entity
.entry(entity.to_string())
.or_default()
.push((ts, r.identity.clone()));
}
}
}
crate::workspace::MountStorage::Archive { .. } => {}
}
out
}
pub fn executors_of(
&self,
entity: &crate::entity::Entity,
touches: &MemTouches,
) -> Option<Executors> {
let plans: Vec<crate::entity::EntityId> = entity
.relationships
.iter()
.filter(|r| r.rel_type == "VERIFIES")
.map(|r| r.target.clone())
.collect();
if plans.is_empty() {
return None;
}
let since = touches.written_at(&entity.id.0).unwrap_or(0);
let mut set: BTreeSet<String> = BTreeSet::new();
let mut members: BTreeSet<String> = BTreeSet::new();
for plan in &plans {
members.insert(plan.0.clone());
for other in self.store.all_entities().filter(|o| o.mem == entity.mem) {
if other.relationships.iter().any(|r| {
&r.target == plan && (r.rel_type == "VERIFIES" || r.rel_type == "PART_OF")
}) {
members.insert(other.id.0.clone());
}
}
}
for member in &members {
touches.identities_since(member, since, &mut set);
}
Some(Executors {
identities: set.into_iter().collect(),
plans: plans.into_iter().map(|p| p.0).collect(),
})
}
pub fn independence_of(
&self,
entity: &crate::entity::Entity,
check: &CheckRecord,
touches: &MemTouches,
) -> (Independence, Option<Executors>) {
if self.is_archive_mount(&entity.mem) {
return (
self.sealed_independence_of(&entity.mem, check)
.unwrap_or(Independence::Unconfirmable),
None,
);
}
let Some(checker) = check.identity.as_deref() else {
return (Independence::Unconfirmable, None);
};
match self.executors_of(entity, touches) {
Some(executors) => {
let reading = if executors.identities.iter().any(|i| i == checker) {
Independence::SelfChecked
} else if executors.identities.is_empty()
&& !executors.plans.iter().any(|p| touches.any_identity(p))
&& !touches.any_identity(&entity.id.0)
{
Independence::Unconfirmable
} else {
Independence::ConfirmedIndependent
};
(reading, Some(executors))
}
None => {
let author = touches
.by_entity
.get(&entity.id.0)
.and_then(|t| t.iter().rev().min_by_key(|(ts, _)| *ts))
.and_then(|(_, id)| id.clone());
let reading = match author {
Some(a) if a == checker => Independence::SelfChecked,
Some(_) => Independence::ConfirmedIndependent,
None => Independence::Unconfirmable,
};
(reading, None)
}
}
}
pub fn sealed_independence_of(&self, mem: &str, check: &CheckRecord) -> Option<Independence> {
let sealed = self.archive_checks_for(mem)?;
let id = crate::EntityId(check.entity.clone());
let kind = crate::check::sealed_kind_of(check);
sealed
.latest(id.path(), &kind)
.filter(|sc| sc.ts == check.ts && sc.entity_hash == check.entity_hash)
.and_then(crate::check::SealedCheck::sealed_independence)
}
pub fn sealed_independence_reader(
&self,
mem: &str,
) -> impl Fn(&CheckRecord) -> Option<Independence> + '_ {
let touches = self.mem_touches(mem);
move |rec: &CheckRecord| {
let entity = self.store.get(&crate::EntityId(rec.entity.clone()))?;
Some(self.independence_of(entity, rec, &touches).0)
}
}
pub fn sealed_row_reader(
&self,
mem: &str,
) -> impl Fn(&CheckRecord) -> crate::ops::export::SealedRowFacts + '_ {
let independence = self.sealed_independence_reader(mem);
let mem = mem.to_string();
move |rec: &CheckRecord| crate::ops::export::SealedRowFacts {
independence: independence(rec),
origin: self
.declares_owner_identities()
.then(|| self.check_row_origin_class(&mem, rec.identity.as_deref())),
}
}
pub(crate) fn check_standing_provider(
&self,
) -> impl Fn(&crate::entity::Entity, &str) -> CheckStanding + '_ {
let touches: std::cell::RefCell<HashMap<String, MemTouches>> =
std::cell::RefCell::new(HashMap::new());
move |entity: &crate::entity::Entity, kind: &str| {
let latest = self.latest_check_record(&entity.mem, &entity.id.0, kind);
let current_pin = self
.find_mount(&entity.mem)
.ok()
.and_then(|m| m.mount.schema.as_ref().map(|s| s.as_display()));
let state = crate::check::derive_state_pinned(
latest.as_ref(),
&entity.content_hash,
current_pin.as_deref(),
);
if state != CheckState::CheckedOk {
return CheckStanding {
state,
independence: None,
role: crate::vcs::Role::Unspecified,
};
}
let check = latest.expect("checked_ok implies a record");
let mut cache = touches.borrow_mut();
let mem_touches = cache
.entry(entity.mem.clone())
.or_insert_with(|| self.mem_touches(&entity.mem));
let (independence, _) = self.independence_of(entity, &check, mem_touches);
CheckStanding {
state,
independence: Some(independence),
role: crate::vcs::Role::from_wire(&check.role).unwrap_or_default(),
}
}
}
}
#[cfg(test)]
mod tests {
use super::MemTouches;
#[test]
fn rename_notes_join_the_story_under_the_new_id() {
let mut t = MemTouches::default();
t.absorb("m--a", 10, Some("alice".into()));
t.absorb("m--a → m--b", 20, Some("renamer".into()));
t.absorb("m--b", 30, Some("bob".into()));
t.absorb("m--b → m--c", 40, None);
t.follow_renames();
assert_eq!(t.written_at("m--c"), Some(10));
let author = t
.by_entity
.get("m--c")
.and_then(|v| v.iter().min_by_key(|(ts, _)| *ts))
.and_then(|(_, id)| id.clone());
assert_eq!(author.as_deref(), Some("alice"));
let mut ids = std::collections::BTreeSet::new();
t.identities_since("m--c", 0, &mut ids);
assert_eq!(
ids.into_iter().collect::<Vec<_>>(),
vec!["alice", "bob", "renamer"]
);
let mut u = MemTouches::default();
u.absorb("m--x → m--y (cross-mem rewrite in peer)", 1, None);
u.follow_renames();
assert!(
u.by_entity
.contains_key("m--x → m--y (cross-mem rewrite in peer)")
);
assert!(!u.by_entity.contains_key("m--y"));
}
}