1use crate::JsString;
5use std::collections::{HashMap, HashSet};
6use crate::content_types::ContentMatch;
7use crate::identity_map::{identity_map_from_content_matches, identity_map_from_successors};
8use crate::model::{DiffState, KeyDiff};
9use crate::split_types::{SplitMergeClaim, SplitMergeKind, SplitConfidence};
10use crate::successor::SuccessorClaim;
11use crate::utf16::cmp_code_units;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum LineageRelation { Identity, Split, Merge, Replaced }
15#[derive(Debug, Clone, PartialEq)]
16pub struct LineageEntry {
17 pub base: Vec<JsString>, pub head: Vec<JsString>, pub relation: LineageRelation,
18 pub reason: JsString, pub shares: Option<Vec<f64>>,
19}
20#[derive(Debug, Clone, Default, PartialEq)]
21pub struct Lineage { pub entries: Vec<LineageEntry>, pub deleted: Vec<JsString> }
22#[derive(Default)]
23pub struct AliasProvenance {
24 pub reasons: HashMap<JsString, JsString>,
25 pub relations: HashMap<JsString, LineageRelation>,
26}
27pub fn lineage_of_diff<R>(diff: &KeyDiff<'_, R>, matches: &[ContentMatch<'_, R>], splits: &[SplitMergeClaim<'_, R>],
28 accepted: &[SuccessorClaim<'_, R>], provenance: &AliasProvenance) -> Lineage {
29 let mut entries = vec![];
30 for (here, base) in diff.applied_key_aliases.iter().flatten() {
31 let reason = provenance.reasons.get(here).cloned().unwrap_or_else(|| "alias:replayed".into());
32 let relation = provenance.relations.get(here).copied().unwrap_or_else(||
33 if reason.starts_with("successor:") { LineageRelation::Replaced } else { LineageRelation::Identity });
34 entries.push(LineageEntry { base: vec![base.clone()], head: vec![here.clone()], relation, reason, shares: None });
35 }
36 for e in identity_map_from_content_matches(matches) {
37 entries.push(LineageEntry { base: vec![e.base], head: vec![e.here], relation: LineageRelation::Identity, reason: e.reason, shares: None });
38 }
39 for claim in splits {
40 let pieces: Vec<_> = claim.pieces.iter().map(|p| p.key.clone()).collect();
41 let shares = if claim.confidence != SplitConfidence::Extent {
42 claim.pieces_volume.filter(|v| *v > 0.0).and_then(|total| claim.pieces.iter()
43 .map(|p| p.volume.filter(|v| v.is_finite() && *v > 0.0).map(|v| v / total)).collect())
44 } else { None };
45 let confidence = match claim.confidence { SplitConfidence::Verified => "verified", SplitConfidence::Extent => "extent", SplitConfidence::Displaced => "displaced" };
46 let (base, head, relation, kind) = match claim.kind {
47 SplitMergeKind::Split => (vec![claim.whole.key.clone()], pieces, LineageRelation::Split, "split"),
48 SplitMergeKind::Merge => (pieces, vec![claim.whole.key.clone()], LineageRelation::Merge, "merge"),
49 };
50 entries.push(LineageEntry { base, head, relation, reason: format!("{kind}:{confidence}").into(), shares });
51 }
52 for e in identity_map_from_successors(accepted) {
53 entries.push(LineageEntry { base: vec![e.base], head: vec![e.here], relation: LineageRelation::Replaced, reason: e.reason, shares: None });
54 }
55 entries.sort_by(|a, b| a.base.first().map(|s| s.units()).unwrap_or(&[]).cmp(b.base.first().map(|s| s.units()).unwrap_or(&[]))
56 .then_with(|| a.head.first().map(|s| s.units()).unwrap_or(&[]).cmp(b.head.first().map(|s| s.units()).unwrap_or(&[]))));
57 let accounted: HashSet<_> = entries.iter().flat_map(|e| e.base.iter()).collect();
58 let mut deleted: Vec<_> = diff.entries.iter().filter(|e| e.state == DiffState::Deleted && !accounted.contains(&e.key)).map(|e| e.key.clone()).collect();
59 deleted.sort_by(cmp_code_units);
60 Lineage { entries, deleted }
61}
62pub fn lineage_conflicts(entries: &[LineageEntry]) -> Vec<JsString> {
63 let mut problems = vec![];
64 for side in ["base", "head"] {
65 let mut seen = HashSet::new();
66 let mut repeated = HashSet::new();
67 for entry in entries {
68 for key in if side == "base" { &entry.base } else { &entry.head } {
69 if !seen.insert(key) { repeated.insert(key); }
70 }
71 }
72 let mut repeated: Vec<_> = repeated.into_iter().collect();
73 repeated.sort_by(cmp_code_units);
74 for key in repeated { problems.push(JsString::surround(&format!("{side} key \""), key, "\" appears in more than one lineage entry")); }
75 }
76 problems
77}
78pub fn key_aliases_from_lineage(entries: &[LineageEntry]) -> Vec<(JsString, JsString)> {
80 let mut claims: Vec<(JsString, JsString)> = vec![];
81 let mut by_head: HashMap<&JsString, usize> = HashMap::new();
82 let mut conflicted = HashSet::new();
83 for entry in entries {
84 if !matches!(entry.relation, LineageRelation::Identity | LineageRelation::Replaced) || entry.base.len() != 1 || entry.head.len() != 1 { continue; }
85 let here = &entry.head[0]; let base = &entry.base[0];
86 if let Some(&index) = by_head.get(here) {
87 if &claims[index].1 != base { conflicted.insert(here.clone()); }
88 } else {
89 by_head.insert(here, claims.len());
90 claims.push((here.clone(), base.clone()));
91 }
92 }
93 claims.into_iter().filter(|(here, base)| here != base && !conflicted.contains(here)).collect()
94}
95#[derive(Debug, Clone, Copy)]
96pub enum RekeyPolicy { CopyToAll, LargestShare, OrphanOnSplit }
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum RekeyRelation { Changed(LineageRelation), Unchanged }
99#[derive(Debug, PartialEq)]
100pub struct RekeyResult { pub key: JsString, pub successors: Vec<JsString>, pub relation: Option<RekeyRelation>, pub orphan: bool }
101pub fn rekey_by_lineage(keys: &[JsString], lineage: &Lineage, policy: RekeyPolicy) -> Vec<RekeyResult> {
104 let deleted: HashSet<_> = lineage.deleted.iter().collect();
105 let mut by_base = HashMap::new();
106 for entry in &lineage.entries { for key in &entry.base { by_base.entry(key).or_insert(entry); } }
107 keys.iter().map(|key| {
108 let Some(entry) = by_base.get(key) else {
109 let orphan = deleted.contains(key);
110 return RekeyResult { key: key.clone(), successors: if orphan { vec![] } else { vec![key.clone()] },
111 relation: if orphan { None } else { Some(RekeyRelation::Unchanged) }, orphan };
112 };
113 let successors = if entry.relation != LineageRelation::Split || matches!(policy, RekeyPolicy::CopyToAll) { entry.head.clone() }
114 else if matches!(policy, RekeyPolicy::LargestShare) {
115 match &entry.shares {
116 Some(shares) if shares.len() == entry.head.len() && !shares.is_empty()
117 && shares.iter().all(|s| s.is_finite() && *s >= 0.0) => {
118 let mut best = 0;
119 for i in 1..shares.len() { if shares[i] > shares[best] { best = i; } }
120 if shares.iter().filter(|&&s| s == shares[best]).count() > 1 { vec![] } else { vec![entry.head[best].clone()] }
121 }, _ => vec![],
122 }
123 } else { vec![] };
124 RekeyResult { key: key.clone(), orphan: entry.relation == LineageRelation::Split && successors.is_empty(),
125 successors, relation: Some(RekeyRelation::Changed(entry.relation)) }
126 }).collect()
127}