Skip to main content

aspero_engine/
resolve.rs

1//! `resolve` and `verify`: from a citation claim to scored candidate works.
2//!
3//! Candidates are gathered in cost order, cheapest first:
4//!
5//! 1. **Lookup** of identifiers the claim asserts (free at OpenAlex and
6//!    Crossref).
7//! 2. **Citation matchers** (Crossref) with the whole reference. Good at
8//!    picking the title out of a messy string, even when the work they
9//!    return is a lookalike.
10//! 3. **Title searches** on keyword providers (OpenAlex, $0.001 each): the
11//!    claim's title, or the title the reference cites as located via the
12//!    matchers' hits ([`matching::shared_title`]). Bare titles rank far
13//!    better there than whole references (DESIGN §9), and locating the
14//!    title in the reference keeps derivative hits ("Faculty Opinions
15//!    recommendation of …") from steering the search.
16//!
17//! Candidates sharing an identifier are merged; each is scored against the
18//! claim with [`assess`]. `verify` stops as soon as a candidate verifies, so
19//! paid searches only run when the free sources weren't conclusive.
20
21use aspero_core::matching::{self, id_agreement, same_work_id};
22use aspero_core::{
23    Agreement, Assessment, Claim, FieldSet, Filter, IdKind, ProviderId, SearchQuery, SourceRecord,
24    Update, Usage, WorkId, YearRange,
25};
26
27use futures::future::{Either, join_all, select};
28use futures::stream::{self, FuturesUnordered, Stream, StreamExt};
29
30use crate::verdict::{Verification, judge};
31use crate::{Engine, EngineError, LookupResult, SearchReport, add_usage};
32
33/// Title searches per claim: the claim's own title or the matchers' top
34/// distinct titles.
35const MAX_TITLE_SEARCHES: usize = 2;
36
37/// Confidence at which `verify` stops gathering candidates early.
38const DECISIVE: f64 = 0.95;
39
40/// Claims verified at once in batches. Providers pace themselves, so this
41/// overlaps different providers' waits rather than adding load to any one;
42/// and it keeps a batch from queueing so many requests that a caller
43/// sharing the engine (someone waiting) is stuck behind them.
44const CLAIM_CONCURRENCY: usize = 4;
45/// Results per search by volume and first page: those of every journal
46/// that year, from which the journal picks.
47const PLACE_LIMIT: u32 = 25;
48
49/// How a candidate was found.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum Via {
53    Lookup,
54    CitationMatch,
55    TitleSearch,
56    KeywordSearch,
57    /// A search by volume and first page.
58    PlaceSearch,
59}
60
61impl Via {
62    pub fn as_str(self) -> &'static str {
63        match self {
64            Via::Lookup => "lookup",
65            Via::CitationMatch => "citation_match",
66            Via::TitleSearch => "title_search",
67            Via::KeywordSearch => "keyword_search",
68            Via::PlaceSearch => "place_search",
69        }
70    }
71}
72
73/// One provider surfacing a candidate.
74#[derive(Debug, Clone)]
75pub struct Sighting {
76    pub provider: ProviderId,
77    pub via: Via,
78    /// 1-based rank in that provider's results.
79    pub rank: usize,
80    pub score: Option<f64>,
81}
82
83#[derive(Debug, Clone)]
84pub struct Candidate {
85    /// The best-matching record among those merged into this candidate.
86    pub record: SourceRecord,
87    /// Every identifier any merged record asserted.
88    pub ids: Vec<WorkId>,
89    pub sightings: Vec<Sighting>,
90    pub assessment: Assessment,
91    /// Editorial notices from every merged record, most detailed kept.
92    pub updates: Vec<Update>,
93}
94
95impl Candidate {
96    /// The first retraction or withdrawal notice, if any.
97    pub fn retraction(&self) -> Option<&Update> {
98        self.updates.iter().find(|u| u.kind.is_retraction())
99    }
100}
101
102/// Adds notices not already known. A detailed notice (with the notice's
103/// identifier) replaces a bare one of the same kind, such as OpenAlex's
104/// `is_retracted` flag.
105pub(crate) fn merge_updates(known: &mut Vec<Update>, new: &[Update]) {
106    for update in new {
107        let same_kind = |k: &Update| k.kind == update.kind;
108        if known
109            .iter()
110            .any(|k| same_kind(k) && k.notice == update.notice)
111        {
112            continue; // already known
113        }
114        if update.notice.is_none() {
115            if !known.iter().any(same_kind) {
116                known.push(update.clone());
117            }
118            continue; // a bare flag adds nothing to a known notice
119        }
120        match known
121            .iter_mut()
122            .find(|k| same_kind(k) && k.notice.is_none())
123        {
124            Some(bare) => *bare = update.clone(),
125            None => known.push(update.clone()),
126        }
127    }
128}
129
130#[derive(Debug, Clone, Default)]
131pub struct ResolveReport {
132    /// Most confident first.
133    pub candidates: Vec<Candidate>,
134    /// Lookups of the claim's identifiers, if it had any.
135    pub lookups: Vec<LookupResult>,
136    /// Providers that failed; their absence from candidates is not evidence.
137    pub errors: Vec<EngineError>,
138    pub usage: Vec<(ProviderId, Usage)>,
139}
140
141impl ResolveReport {
142    /// Every failure: providers' searches, and lookups of the claimed
143    /// identifiers that failed rather than finding nothing.
144    pub fn failures(&self) -> Vec<EngineError> {
145        let lookups = self
146            .lookups
147            .iter()
148            .filter(|l| l.record.is_none())
149            .flat_map(|l| &l.attempts)
150            .filter_map(|a| match &a.outcome {
151                crate::Outcome::Failed(error) => Some(EngineError::Provider {
152                    provider: a.provider.clone(),
153                    error: error.clone(),
154                }),
155                _ => None,
156            });
157        self.errors.iter().cloned().chain(lookups).collect()
158    }
159}
160
161impl Engine {
162    /// Gathers and scores every candidate for `claim`. `limit` caps results
163    /// per provider search.
164    pub async fn resolve(&self, claim: &Claim, limit: u32) -> ResolveReport {
165        self.gather(claim, limit, false).await
166    }
167
168    /// Decides whether `claim` refers to a real work, stopping early once it
169    /// does.
170    pub async fn verify(&self, claim: &Claim, limit: u32) -> Verification {
171        // Alternative readings of claimed identifiers are looked up with
172        // them, alongside the citation matchers; which was meant is settled
173        // after, so a broken DOI costs no extra round of lookups.
174        let mut wide = claim.clone();
175        for a in &claim.alternatives {
176            if claim.ids.contains(&a.claimed) && !wide.ids.contains(&a.alternative) {
177                wide.ids.push(a.alternative.clone());
178            }
179        }
180        let mut report = self.gather(&wide, limit, true).await;
181        let claim = settle_alternatives(claim, &mut report);
182        self.detail_notices(&mut report).await;
183        judge(&claim, report)
184    }
185
186    /// Verifies many claims, several at a time (each provider's pacing
187    /// still applies), yielding each with its claim's index as soon as it
188    /// completes: a slow claim doesn't hold up the rest.
189    pub fn verify_many<'a>(
190        &'a self,
191        claims: &'a [Claim],
192        limit: u32,
193    ) -> impl Stream<Item = (usize, Verification)> + 'a {
194        stream::iter(claims.iter().enumerate())
195            .map(move |(i, claim)| async move { (i, self.verify(claim, limit).await) })
196            .buffer_unordered(CLAIM_CONCURRENCY)
197    }
198
199    /// For candidates known to be retracted only by a bare flag (OpenAlex's
200    /// `is_retracted`), asks the other providers by identifier for the
201    /// notice itself: date, notice DOI, source. Free, cached, and only for
202    /// flagged works.
203    async fn detail_notices(&self, report: &mut ResolveReport) {
204        let bare = |c: &Candidate| {
205            c.updates
206                .iter()
207                .any(|u| u.kind.is_retraction() && u.notice.is_none())
208        };
209        for entry in &self.entries {
210            let provider = entry.provider.id();
211            let kinds = &entry.provider.capabilities().lookup_kinds;
212            let wanted: Vec<(usize, WorkId)> = report
213                .candidates
214                .iter()
215                .enumerate()
216                .filter(|(_, c)| bare(c) && !c.sightings.iter().any(|s| s.provider == provider))
217                .filter_map(|(i, c)| {
218                    Some((
219                        i,
220                        c.ids.iter().find(|id| kinds.contains(&id.kind()))?.clone(),
221                    ))
222                })
223                .collect();
224            if wanted.is_empty() {
225                continue;
226            }
227            let ids: Vec<WorkId> = wanted.iter().map(|(_, id)| id.clone()).collect();
228            let answers = self
229                .lookup_at(entry, &ids, FieldSet::ALL, &mut report.usage)
230                .await;
231            for ((i, _), (_, record)) in wanted.into_iter().zip(answers) {
232                if let Some(record) = record {
233                    merge_updates(&mut report.candidates[i].updates, &record.work.updates);
234                }
235            }
236        }
237    }
238
239    /// Looks up every identifier the claims assert, in one batched call per
240    /// provider. With a cache attached, this warms it so verifying the
241    /// claims one by one (and streaming results) doesn't look them up one
242    /// by one.
243    pub async fn prefetch(&self, claims: &[Claim]) -> crate::LookupReport {
244        let mut ids: Vec<WorkId> = Vec::new();
245        for id in claims.iter().flat_map(|c| &c.ids) {
246            if !ids.contains(id) {
247                ids.push(id.clone());
248            }
249        }
250        self.lookup(&ids, FieldSet::DEFAULT).await
251    }
252
253    async fn gather(&self, claim: &Claim, limit: u32, stop_when_verified: bool) -> ResolveReport {
254        let mut acc = Accumulator {
255            claim,
256            report: ResolveReport::default(),
257        };
258        let done = |acc: &Accumulator| stop_when_verified && acc.verified();
259        let query = |text: &str, citation: bool| {
260            let mut q = if citation {
261                SearchQuery::citation(text)
262            } else {
263                SearchQuery::new(text)
264            };
265            q.page.limit = limit;
266            q
267        };
268
269        // Stage 1, concurrently (both free): lookups of the claimed
270        // identifiers, and citation matchers on the whole reference.
271        let reference = claim.reference();
272        let matchers: Vec<ProviderId> = match &reference {
273            Some(_) => self.searchers(true),
274            None => Vec::new(),
275        };
276        let lookup = async {
277            match claim.ids.is_empty() {
278                true => None,
279                false => Some(self.lookup(&claim.ids, FieldSet::DEFAULT).await),
280            }
281        };
282        let matched = join_all(matchers.iter().map(|p| {
283            let q = query(reference.as_deref().unwrap_or_default(), true);
284            async move { self.search(Some(p.as_str()), &q).await }
285        }));
286        let (lookup, matched) = (std::pin::pin!(lookup), std::pin::pin!(matched));
287        let (lookup, matched) = match select(lookup, matched).await {
288            Either::Left((lookup, matched)) => (lookup, Either::Left(matched)),
289            Either::Right((matched, lookup)) => (lookup.await, Either::Right(matched)),
290        };
291
292        if let Some(lookup) = lookup {
293            for record in lookup.results.iter().filter_map(|r| r.record.as_ref()) {
294                let sighting = Sighting {
295                    provider: record.source.clone(),
296                    via: Via::Lookup,
297                    rank: 1,
298                    score: None,
299                };
300                acc.add(record.clone(), sighting);
301            }
302            acc.usage(lookup.usage);
303            acc.report.lookups = lookup.results;
304        }
305        // When the identifiers' lookup alone verifies the claim, the
306        // matchers can't change the verdict: stop waiting for them (Crossref's
307        // takes seconds).
308        let matched = match matched {
309            Either::Right(matched) => matched,
310            Either::Left(_) if done(&acc) => Vec::new(),
311            Either::Left(pending) => pending.await,
312        };
313        let mut titles: Vec<String> = claim.title.iter().cloned().collect();
314        for (provider, result) in matchers.iter().zip(matched) {
315            let hits = acc.add_search(provider, Via::CitationMatch, result);
316            if let (None, Some(reference)) = (&claim.title, &reference) {
317                // Query the title the reference cites, as found via each
318                // hit: a commentary titled "Recommendation of X" yields X.
319                titles.extend(
320                    hits.iter()
321                        .filter_map(|t| matching::shared_title(t, reference)),
322                );
323            }
324        }
325        // An identifier-only claim has nothing else to compare.
326        if done(&acc) || !claim.is_descriptive() {
327            return acc.finish();
328        }
329
330        // Stage 2, concurrently: title searches (or, with no title to go on,
331        // cleaned-up keywords) on every keyword provider. Results are added
332        // in provider-then-title order, so merging stays deterministic.
333        titles = distinct(titles);
334        titles.truncate(MAX_TITLE_SEARCHES);
335        let mut jobs: Vec<(ProviderId, SearchQuery, Via)> = Vec::new();
336        for provider in self.searchers(false) {
337            if titles.is_empty()
338                && let Some(text) = &claim.text
339            {
340                let q = query(&matching::search_terms(text), false);
341                jobs.push((provider.clone(), q, Via::KeywordSearch));
342            }
343            for title in &titles {
344                jobs.push((provider.clone(), query(title, false), Via::TitleSearch));
345            }
346        }
347        // A reference without a title ("Injury 47 (2016) 797–804") is
348        // found by where it appeared, in the years it cites (and either
349        // side: online first, then in print).
350        if let Some(place) = claim.place() {
351            let years = claim.cited_years();
352            for provider in self.placers() {
353                let mut q = query("", false);
354                q.page.limit = PLACE_LIMIT;
355                q.place = Some(place.clone());
356                q.years = years
357                    .iter()
358                    .min()
359                    .zip(years.iter().max())
360                    .map(|(&a, &b)| YearRange {
361                        from: Some(a - 1),
362                        to: Some(b + 1),
363                    });
364                jobs.push((provider, q, Via::PlaceSearch));
365            }
366        }
367        // Each answer is added as it arrives, so a verified claim stops
368        // waiting for slower providers. The report is rebuilt in job order
369        // each time, so what's kept doesn't depend on who answered first.
370        let mut pending: FuturesUnordered<_> = jobs
371            .iter()
372            .enumerate()
373            .map(|(i, (p, q, _))| async move { (i, self.search(Some(p.as_str()), q).await) })
374            .collect();
375        let before = acc.report.clone();
376        let mut answers: Vec<Option<Result<SearchReport, EngineError>>> = vec![None; jobs.len()];
377        while let Some((i, result)) = pending.next().await {
378            answers[i] = Some(result);
379            acc.report = before.clone();
380            for ((provider, _, via), answer) in jobs.iter().zip(&answers) {
381                if let Some(result) = answer {
382                    acc.add_search(provider, *via, result.clone());
383                }
384            }
385            if done(&acc) {
386                break;
387            }
388        }
389        acc.finish()
390    }
391
392    /// Keyword engines that can search by volume and first page.
393    fn placers(&self) -> Vec<ProviderId> {
394        self.providers()
395            .filter(|p| {
396                let caps = p.capabilities();
397                caps.search && !caps.citation_search && caps.search_filters.contains(&Filter::Place)
398            })
399            .map(|p| p.id())
400            .collect()
401    }
402
403    /// Providers that search, either citation matchers or keyword engines.
404    fn searchers(&self, matchers: bool) -> Vec<ProviderId> {
405        self.providers()
406            .filter(|p| p.capabilities().search && p.capabilities().citation_search == matchers)
407            .map(|p| p.id())
408            .collect()
409    }
410}
411
412pub(crate) trait ClaimExt {
413    fn is_descriptive(&self) -> bool;
414}
415
416impl ClaimExt for Claim {
417    /// Whether the claim says anything besides identifiers.
418    fn is_descriptive(&self) -> bool {
419        self.text.is_some() || self.title.is_some() || !self.authors.is_empty()
420    }
421}
422
423struct Accumulator<'a> {
424    claim: &'a Claim,
425    report: ResolveReport,
426}
427
428impl Accumulator<'_> {
429    /// Adds a record, merging it into an existing candidate that shares an
430    /// identifier.
431    fn add(&mut self, mut record: SourceRecord, sighting: Sighting) {
432        let assessment = matching::assess(self.claim, &record);
433        let candidates = &mut self.report.candidates;
434        let existing = candidates.iter_mut().find(|c| {
435            c.ids
436                .iter()
437                .any(|a| record.ids.iter().any(|b| same_work_id(a, b)))
438        });
439        let candidate = match existing {
440            Some(c) => {
441                for id in &record.ids {
442                    if !c.ids.iter().any(|known| same_work_id(known, id)) {
443                        c.ids.push(id.clone());
444                    }
445                }
446                c.sightings.push(sighting);
447                merge_updates(&mut c.updates, &record.work.updates);
448                // Pool the years every source reports (online-first vs
449                // print, editions), then keep the better-matching record.
450                let pooled: Vec<i16> = years(&c.record).chain(years(&record)).collect();
451                add_years(&mut c.record, &pooled);
452                add_years(&mut record, &pooled);
453                // And keep a free copy's location, whichever record wins.
454                let oa = |r: &SourceRecord| r.work.open_access.clone();
455                let known = oa(&c.record).or_else(|| oa(&record));
456                c.record.work.open_access.clone_from(&known);
457                record.work.open_access = record.work.open_access.take().or(known);
458                c.assessment = matching::assess(self.claim, &c.record);
459                let assessment = matching::assess(self.claim, &record);
460                if assessment.confidence > c.assessment.confidence {
461                    c.record = record;
462                    c.assessment = assessment;
463                }
464                c
465            }
466            None => {
467                let mut updates = Vec::new();
468                merge_updates(&mut updates, &record.work.updates);
469                candidates.push(Candidate {
470                    ids: record.ids.clone(),
471                    updates,
472                    record,
473                    sightings: vec![sighting],
474                    assessment,
475                });
476                candidates.last_mut().expect("just pushed")
477            }
478        };
479        // Judge claimed identifiers against everything known about the work.
480        candidate.assessment.ids = id_agreement(&self.claim.ids, &candidate.ids);
481    }
482
483    /// Adds one search's hits; returns the hits' titles.
484    fn add_search(
485        &mut self,
486        provider: &ProviderId,
487        via: Via,
488        result: Result<SearchReport, EngineError>,
489    ) -> Vec<String> {
490        match result {
491            Ok(report) => {
492                if let Some(u) = report.usage {
493                    add_usage(&mut self.report.usage, provider, u);
494                }
495                let mut titles = Vec::new();
496                for (i, hit) in report.page.hits.into_iter().enumerate() {
497                    // An untitled hit (a book chapter registered under the
498                    // book) points to the cited title via its container.
499                    let w = &hit.record.work;
500                    titles.extend(w.title.clone().or_else(|| w.container_title.clone()));
501                    let sighting = Sighting {
502                        provider: provider.clone(),
503                        via,
504                        rank: i + 1,
505                        score: hit.score,
506                    };
507                    self.add(hit.record, sighting);
508                }
509                titles
510            }
511            Err(e) => {
512                self.report.errors.push(e);
513                Vec::new()
514            }
515        }
516    }
517
518    fn usage(&mut self, usage: Vec<(ProviderId, Usage)>) {
519        for (provider, u) in usage {
520            add_usage(&mut self.report.usage, &provider, u);
521        }
522    }
523
524    /// A candidate so clearly right that searching further can't improve
525    /// on it: decisive, and either the identifiers the claim asserted or two
526    /// providers vouch for it. A digest or reprint of a paper can match the
527    /// claim exactly while only a later search finds the original. Two
528    /// providers also settle a claim whose identifier names another work,
529    /// but not one whose identifiers the candidate can't yet be compared
530    /// with: a later provider may add the claimed PMID.
531    fn verified(&self) -> bool {
532        self.report.candidates.iter().any(|c| {
533            let vouched = || {
534                c.sightings
535                    .iter()
536                    .any(|s| s.provider != c.sightings[0].provider)
537            };
538            let corroborated = match c.assessment.ids {
539                Agreement::Match => true,
540                Agreement::Mismatch => vouched(),
541                _ => self.claim.ids.is_empty() && vouched(),
542            };
543            c.assessment.confidence >= DECISIVE && corroborated
544        })
545    }
546
547    fn finish(mut self) -> ResolveReport {
548        rank(&mut self.report.candidates);
549        self.report
550    }
551}
552
553/// The claim with each claimed identifier that doesn't exist replaced by
554/// an alternative reading that does, and the report made about that
555/// claim: lookups of readings not taken dropped, candidates rescored.
556fn settle_alternatives(claim: &Claim, report: &mut ResolveReport) -> Claim {
557    let mut claim = claim.clone();
558    let lookup = |id: &WorkId| report.lookups.iter().find(|l| l.id == *id);
559    let missing = |id: &WorkId| lookup(id).is_some_and(LookupResult::is_not_found);
560    let mut settled: Vec<(WorkId, WorkId)> = Vec::new();
561    for a in &claim.alternatives {
562        if missing(&a.claimed) && lookup(&a.alternative).is_some_and(|l| l.record.is_some()) {
563            settled.push((a.claimed.clone(), a.alternative.clone()));
564        }
565    }
566    // A DOI that doesn't exist, and a work found by the citation's text
567    // whose DOI starts with it: the same DOI, cut short at a line break
568    // (#39).
569    for id in claim
570        .ids
571        .iter()
572        .filter(|id| id.kind() == IdKind::Doi && missing(id))
573    {
574        let cited = id.to_string();
575        let longer = report
576            .candidates
577            .iter()
578            .flat_map(|c| &c.ids)
579            .find(|c| c.kind() == IdKind::Doi && c.to_string().starts_with(&cited) && *c != id);
580        if let Some(longer) = longer
581            && !settled.iter().any(|(from, _)| from == id)
582        {
583            settled.push((id.clone(), longer.clone()));
584        }
585    }
586    if claim.alternatives.is_empty() && settled.is_empty() {
587        return claim;
588    }
589    for (from, to) in settled {
590        for id in claim.ids.iter_mut().filter(|id| **id == from) {
591            *id = to.clone();
592        }
593    }
594    report.lookups.retain(|l| claim.ids.contains(&l.id));
595    for c in &mut report.candidates {
596        c.assessment = matching::assess(&claim, &c.record);
597        c.assessment.ids = id_agreement(&claim.ids, &c.ids);
598    }
599    rank(&mut report.candidates);
600    claim
601}
602
603/// Most confident first; on a tie the earliest-published (an original
604/// precedes its reprints, abstracts and corrections), then the one more
605/// providers agree on.
606fn rank(candidates: &mut [Candidate]) {
607    let issued = |c: &Candidate| {
608        c.record.work.issued.map_or(i64::MAX, |d| {
609            i64::from(d.year()) * 10_000
610                + i64::from(d.month().unwrap_or(12)) * 100
611                + i64::from(d.day().unwrap_or(31))
612        })
613    };
614    candidates.sort_by(|a, b| {
615        b.assessment
616            .confidence
617            .total_cmp(&a.assessment.confidence)
618            .then(issued(a).cmp(&issued(b)))
619            .then(b.sightings.len().cmp(&a.sightings.len()))
620    });
621}
622
623/// Every year a record reports: issued, then other editions or versions.
624fn years(record: &SourceRecord) -> impl Iterator<Item = i16> + '_ {
625    let w = &record.work;
626    w.issued
627        .map(|d| d.year())
628        .into_iter()
629        .chain(w.other_years.iter().copied())
630}
631
632/// Adds `pooled` years the record doesn't already report to its
633/// `other_years`.
634fn add_years(record: &mut SourceRecord, pooled: &[i16]) {
635    let issued = record.work.issued.map(|d| d.year());
636    for &y in pooled {
637        if Some(y) != issued && !record.work.other_years.contains(&y) {
638            record.work.other_years.push(y);
639        }
640    }
641    record.work.other_years.sort_unstable();
642}
643
644/// Titles with duplicates (by normalised form) removed, order kept.
645fn distinct(titles: Vec<String>) -> Vec<String> {
646    let mut seen = Vec::new();
647    titles
648        .into_iter()
649        .filter(|t| {
650            let norm = matching::normalise(t);
651            let new = !norm.is_empty() && !seen.contains(&norm);
652            seen.push(norm);
653            new
654        })
655        .collect()
656}
657
658#[cfg(test)]
659mod tests {
660    use aspero_core::UpdateKind;
661
662    use super::*;
663
664    fn update(kind: UpdateKind, notice: Option<&str>) -> Update {
665        let mut u = Update::new(kind);
666        u.notice = notice.map(|n| n.parse().unwrap());
667        u
668    }
669
670    #[test]
671    fn detailed_notices_replace_bare_flags_without_duplicates() {
672        let mut known = vec![update(UpdateKind::Retraction, None)];
673        let crossref = [
674            update(UpdateKind::Correction, Some("10.1000/c1")),
675            update(UpdateKind::Retraction, Some("10.1000/r")),
676            update(UpdateKind::Correction, Some("10.1000/c2")),
677        ];
678        merge_updates(&mut known, &crossref);
679        merge_updates(&mut known, &crossref); // again: nothing new
680        merge_updates(&mut known, &[update(UpdateKind::Retraction, None)]);
681        let summary: Vec<(String, Option<String>)> = known
682            .iter()
683            .map(|u| {
684                (
685                    u.kind.as_str().to_owned(),
686                    u.notice.as_ref().map(ToString::to_string),
687                )
688            })
689            .collect();
690        assert_eq!(
691            summary,
692            [
693                ("retraction".into(), Some("doi:10.1000/r".into())),
694                ("correction".into(), Some("doi:10.1000/c1".into())),
695                ("correction".into(), Some("doi:10.1000/c2".into())),
696            ]
697        );
698    }
699}