1use aspero_core::matching::same_work_id;
9use aspero_core::{Claim, IdKind, Update, UpdateKind, WorkId};
10use futures::StreamExt;
11
12use crate::{Candidate, Engine, Verdict, Verification};
13
14const ARXIV_DOI_PREFIX: &str = "10.48550";
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18#[non_exhaustive]
19pub enum Severity {
20 Info,
21 Warning,
22 Error,
23}
24
25impl Severity {
26 pub fn as_str(self) -> &'static str {
27 match self {
28 Severity::Info => "info",
29 Severity::Warning => "warning",
30 Severity::Error => "error",
31 }
32 }
33}
34
35#[derive(Debug, Clone, PartialEq)]
37#[non_exhaustive]
38pub enum Finding {
39 Verdict { verdict: Verdict, reason: String },
41 AddDoi { doi: WorkId },
43 ReplaceId {
45 claimed: WorkId,
46 with: Option<WorkId>,
47 },
48 YearDiffers { claimed: i16, actual: i16 },
51 Duplicate { of: usize },
53 Updated { update: Update },
55}
56
57impl Finding {
58 pub fn severity(&self) -> Severity {
59 match self {
60 Finding::Verdict { verdict, .. } => match verdict {
61 Verdict::Mismatch | Verdict::NotFound => Severity::Error,
62 _ => Severity::Warning,
63 },
64 Finding::ReplaceId { .. } => Severity::Error,
65 Finding::YearDiffers { claimed, actual } if (claimed - actual).abs() > 1 => {
68 Severity::Error
69 }
70 Finding::YearDiffers { .. } | Finding::AddDoi { .. } => Severity::Info,
71 Finding::Duplicate { .. } => Severity::Warning,
72 Finding::Updated { update } => match update.kind {
73 UpdateKind::Retraction | UpdateKind::Withdrawal => Severity::Error,
74 UpdateKind::ExpressionOfConcern | UpdateKind::NewVersion => Severity::Warning,
75 _ => Severity::Info,
76 },
77 }
78 }
79
80 pub fn kind(&self) -> &'static str {
82 match self {
83 Finding::Verdict { .. } => "verdict",
84 Finding::AddDoi { .. } => "add_doi",
85 Finding::ReplaceId { .. } => "replace_id",
86 Finding::YearDiffers { .. } => "year_differs",
87 Finding::Duplicate { .. } => "duplicate",
88 Finding::Updated { .. } => "updated",
89 }
90 }
91}
92
93#[derive(Debug, Clone)]
95pub struct Checked {
96 pub verification: Verification,
97 pub findings: Vec<Finding>,
98}
99
100impl Checked {
101 pub fn matched(&self) -> Option<&Candidate> {
102 let v = &self.verification;
103 v.best.map(|i| &v.report.candidates[i])
104 }
105
106 pub fn severity(&self) -> Option<Severity> {
108 self.findings.iter().map(Finding::severity).max()
109 }
110}
111
112impl Engine {
113 pub async fn check(
117 &self,
118 claims: &[Claim],
119 limit: u32,
120 mut progress: impl FnMut(usize),
121 ) -> Vec<Checked> {
122 self.prefetch(claims).await;
123 let mut checked = Vec::with_capacity(claims.len());
124 let mut verifications = std::pin::pin!(self.verify_many(claims, limit));
125 while let Some(verification) = verifications.next().await {
126 let i = checked.len();
127 let findings = findings(&claims[i], &verification);
128 checked.push(Checked {
129 verification,
130 findings,
131 });
132 progress(i);
133 }
134 let matches: Vec<Option<&Candidate>> = checked.iter().map(Checked::matched).collect();
135 let duplicates = duplicates(&matches);
136 for (c, dup) in checked.iter_mut().zip(duplicates) {
137 if let Some(of) = dup {
138 c.findings.push(Finding::Duplicate { of });
139 }
140 }
141 checked
142 }
143}
144
145pub fn findings(claim: &Claim, v: &Verification) -> Vec<Finding> {
148 let mut out = Vec::new();
149 if v.verdict != Verdict::Verified {
150 out.push(Finding::Verdict {
151 verdict: v.verdict,
152 reason: v.reason.clone(),
153 });
154 }
155 let Some(best) = v.best.map(|i| &v.report.candidates[i]) else {
156 return out;
157 };
158 let suggested = preferred_doi(&best.ids);
159 out.extend(
160 best.updates
161 .iter()
162 .map(|u| Finding::Updated { update: u.clone() }),
163 );
164
165 for claimed in &claim.ids {
170 let as_arxiv = arxiv_of(claimed);
171 let same = best.ids.iter().any(|id| {
172 same_work_id(id, claimed) || as_arxiv.as_ref().is_some_and(|a| same_work_id(id, a))
173 });
174 let contradicted = best.ids.iter().any(|id| id.kind() == claimed.kind());
175 if !same && (contradicted || v.verdict == Verdict::Mismatch) {
176 out.push(Finding::ReplaceId {
177 claimed: claimed.clone(),
178 with: suggested.cloned(),
179 });
180 }
181 }
182 let has_doi = claim.ids.iter().any(|id| id.kind() == IdKind::Doi);
184 if !has_doi
185 && matches!(v.verdict, Verdict::Verified | Verdict::Plausible)
186 && let Some(doi) = suggested
187 {
188 out.push(Finding::AddDoi { doi: doi.clone() });
189 }
190 let work = &best.record.work;
193 let years: Vec<i16> = work
194 .issued
195 .map(|d| d.year())
196 .into_iter()
197 .chain(work.other_years.iter().copied())
198 .collect();
199 if let Some(claimed) = claim.year
200 && let Some(&actual) = years.iter().min_by_key(|y| (*y - claimed).abs())
201 && actual != claimed
202 {
203 out.push(Finding::YearDiffers { claimed, actual });
204 }
205 out
206}
207
208fn arxiv_of(id: &WorkId) -> Option<WorkId> {
211 let WorkId::Doi(doi) = id else { return None };
212 (doi.prefix() == ARXIV_DOI_PREFIX)
213 .then(|| {
214 doi.suffix()
215 .strip_prefix("arxiv.")?
216 .parse()
217 .ok()
218 .map(WorkId::Arxiv)
219 })
220 .flatten()
221}
222
223fn preferred_doi(ids: &[WorkId]) -> Option<&WorkId> {
225 let dois = || ids.iter().filter(|id| id.kind() == IdKind::Doi);
226 dois()
227 .find(|id| {
228 !id.to_string()
229 .starts_with(&format!("doi:{ARXIV_DOI_PREFIX}/"))
230 })
231 .or_else(|| dois().next())
232}
233
234pub fn duplicates(matches: &[Option<&Candidate>]) -> Vec<Option<usize>> {
237 matches
238 .iter()
239 .enumerate()
240 .map(|(i, m)| {
241 let m = (*m)?;
242 matches[..i].iter().position(|other| {
243 other.is_some_and(|o| {
244 o.ids
245 .iter()
246 .any(|a| m.ids.iter().any(|b| same_work_id(a, b)))
247 })
248 })
249 })
250 .collect()
251}