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, Clone, PartialEq, Eq)]
pub struct Touch {
pub ts: i64,
pub identity: Option<String>,
pub reference: String,
pub seq: usize,
}
#[derive(Debug, Default, Clone)]
pub struct MemTouches {
by_entity: HashMap<String, Vec<Touch>>,
renames: Vec<(usize, String, String)>,
}
impl MemTouches {
fn absorb(&mut self, entity_field: &str, touch: Touch) {
match super::history::parse_rename_pair(entity_field) {
Some((old, new)) => {
self.by_entity
.entry(old.clone())
.or_default()
.push(touch.clone());
let seq = touch.seq;
self.by_entity.entry(new.clone()).or_default().push(touch);
self.renames.push((seq, old, new));
}
None => self
.by_entity
.entry(entity_field.to_string())
.or_default()
.push(touch),
}
}
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);
}
}
}
for touches in self.by_entity.values_mut() {
touches.sort_by_key(|t| t.seq);
}
self.renames = renames;
}
pub fn story(&self, entity: &str) -> &[Touch] {
self.by_entity.get(entity).map(Vec::as_slice).unwrap_or(&[])
}
pub fn first_author(&self, entity: &str) -> Option<&str> {
self.story(entity)
.first()
.and_then(|t| t.identity.as_deref())
}
pub fn last_write(&self, entity: &str) -> Option<&str> {
self.story(entity).last().map(|t| t.reference.as_str())
}
fn written_at(&self, entity: &str) -> Option<i64> {
self.by_entity
.get(entity)
.and_then(|t| t.iter().map(|t| t.ts).min())
}
fn identities_since(&self, entity: &str, since: i64, into: &mut BTreeSet<String>) {
if let Some(touches) = self.by_entity.get(entity) {
for t in touches {
if t.ts >= since
&& let Some(id) = &t.identity
{
into.insert(id.clone());
}
}
}
}
fn any_identity(&self, entity: &str) -> bool {
self.by_entity
.get(entity)
.is_some_and(|t| t.iter().any(|t| t.identity.is_some()))
}
pub fn writes_seen_by(&self, entity: &str, check: &CheckRecord) -> Vec<&Touch> {
let story = self.story(entity);
if let Some(r) = check.checked_write.as_deref()
&& let Some(at) = story.iter().rposition(|t| t.reference == r)
{
return story[..=at].iter().collect();
}
story.iter().filter(|t| t.ts <= check.ts as i64).collect()
}
}
#[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,
)
{
let count = changes.notes.len();
for (i, n) in changes.notes.iter().enumerate() {
let touch = Touch {
ts: n.timestamp,
identity: n.identity.clone(),
reference: n.sha.clone(),
seq: count - i,
};
if let Some(entity) = n.entity_id.as_deref() {
out.absorb(entity, touch.clone());
}
for entity in &n.entity_ids {
out.absorb(entity, touch.clone());
}
for (entity, identity) in &n.co_writers {
out.absorb(
entity,
Touch {
identity: Some(identity.clone()),
..touch.clone()
},
);
}
for pair in &n.merge_renames {
out.absorb(pair, touch.clone());
}
for entity in &n.unattributed_writes {
out.absorb(
entity,
Touch {
identity: None,
..touch.clone()
},
);
}
}
out.follow_renames();
}
}
crate::workspace::MountStorage::Folder { .. }
| crate::workspace::MountStorage::InMemory => {
if let Ok(records) = m.backend.read_provenance(None) {
for (seq, r) in records.into_iter().enumerate() {
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);
let touch = Touch {
ts,
identity: r.identity.clone(),
reference: format!(
"{}#{seq}",
crate::filesystem::changelog::format_rfc3339_utc(r.timestamp)
),
seq,
};
match r.renamed_from.as_deref() {
Some(old) => out.absorb(&format!("{old} → {entity}"), touch),
None => out.absorb(entity, touch),
}
}
out.follow_renames();
}
}
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 seen = touches.writes_seen_by(&entity.id.0, check);
let reading = if seen.iter().any(|t| t.identity.as_deref() == Some(checker)) {
Independence::SelfChecked
} else if seen.is_empty() || seen.iter().any(|t| t.identity.is_none()) {
Independence::Unconfirmable
} else {
Independence::ConfirmedIndependent
};
(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();
let touch = |ts: i64, id: Option<&str>, seq: usize| super::Touch {
ts,
identity: id.map(str::to_string),
reference: format!("r{seq}"),
seq,
};
t.absorb("m--a", touch(10, Some("alice"), 1));
t.absorb("m--a → m--b", touch(20, Some("renamer"), 2));
t.absorb("m--b", touch(30, Some("bob"), 3));
t.absorb("m--b → m--c", touch(40, None, 4));
t.follow_renames();
assert_eq!(t.written_at("m--c"), Some(10));
assert_eq!(t.first_author("m--c"), 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)", touch(1, None, 5));
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"));
}
}