Skip to main content

allsource_core/
store_feed.rs

1use super::EventStore;
2use crate::{
3    application::dto::EventDto,
4    domain::entities::Event,
5    error::{AllSourceError, Result},
6    infrastructure::{
7        hash_state::{
8            FastMap, FastSet, fast_map, fast_map_with_capacity, fast_set, fast_set_with_capacity,
9        },
10        memory::ledger::{Owner, Tally},
11        observability::heap::hash_entry_bytes,
12        persistence::{
13            archive_budget::ArchiveReadBudget,
14            feed_log::{Appended, FeedLog, FeedLogRecord, FeedLogScope},
15        },
16    },
17};
18use serde::{Deserialize, Serialize};
19use std::{
20    collections::BTreeMap,
21    mem::size_of,
22    path::{Path, PathBuf},
23    sync::{Arc, OnceLock},
24};
25use uuid::Uuid;
26
27pub const MODEL_EVENT: &str = "allsource.read_model.committed";
28pub const FEED_BYTES: usize = 512 * 1024;
29const SCAN_WINDOW: usize = 10_000;
30pub const DURABLE_LOG_ENV: &str = "ALLSOURCE_FEED_DURABLE_LOG";
31/// Under the WAL directory.
32pub const FEED_LOG_DIR: &str = "feed-log";
33
34/// `ALLSOURCE_FEED_DURABLE_LOG` (default off, syntax in
35/// [`FeedLogScope::parse`]) keeps the named tenants' feed epoch and positions
36/// in a log, so a restart does not renumber them.
37pub(super) fn open_feed_log(wal_dir: Option<&Path>, read_only: bool) -> Option<Arc<FeedLog>> {
38    let scope = FeedLogScope::parse(std::env::var(DURABLE_LOG_ENV).ok().as_deref())?;
39    let Some(wal_dir) = wal_dir.filter(|_| !read_only) else {
40        tracing::warn!(
41            "{DURABLE_LOG_ENV} needs a writable store with a WAL; feed positions stay per process"
42        );
43        return None;
44    };
45    let dir = wal_dir.join(FEED_LOG_DIR);
46    match FeedLog::open(dir.clone(), scope) {
47        Ok(log) => Some(Arc::new(log)),
48        Err(error) => {
49            tracing::error!(
50                "Durable feed log unavailable at {}: {error}; feed positions stay per process",
51                dir.display()
52            );
53            None
54        }
55    }
56}
57
58/// `ALLSOURCE_FEED_NARROW_INDEX=0` restores the feed that hydrates the whole
59/// tenant on every call.
60fn narrow_feed_enabled() -> bool {
61    static ENABLED: OnceLock<bool> = OnceLock::new();
62    *ENABLED.get_or_init(|| {
63        std::env::var("ALLSOURCE_FEED_NARROW_INDEX").map_or(true, |value| value.trim() != "0")
64    })
65}
66
67#[derive(Clone)]
68pub(super) enum Locator {
69    Memory,
70    Archive { file: Arc<PathBuf>, row: u64 },
71}
72
73struct FeedEntry {
74    id: Uuid,
75    event_type: Arc<str>,
76    entity_id: Arc<str>,
77    at: Locator,
78}
79
80pub(super) struct FeedIndex {
81    epoch: u64,
82    events: Vec<FeedEntry>,
83    ids: FastSet<Uuid>,
84    /// Built from the tenant's whole archive plus memory, so it numbers every
85    /// event without the tenant being resident.
86    narrow: bool,
87    /// Mirrors the tenant's [`FeedLog`] record for record: same epoch, same
88    /// positions.
89    durable: bool,
90    /// Released when the tenant's feed is dropped.
91    charged: Tally,
92}
93
94impl Default for FeedIndex {
95    fn default() -> Self {
96        Self {
97            epoch: Uuid::new_v4().as_u64_pair().0 & ((1_u64 << 52) - 1),
98            events: Vec::new(),
99            ids: fast_set(),
100            narrow: false,
101            durable: false,
102            charged: Tally::new(Owner::FeedIndex),
103        }
104    }
105}
106
107/// Bytes a feed entry holds beyond its slot in `events`: the two `Arc<str>`
108/// allocations and its id in the set.
109fn feed_entry_owned_bytes(entry: &FeedEntry) -> u64 {
110    const ARC_HEADER: usize = 2 * size_of::<usize>();
111    (2 * ARC_HEADER
112        + entry.event_type.len()
113        + entry.entity_id.len()
114        + hash_entry_bytes::<Uuid, ()>()) as u64
115}
116
117fn push_entry(feed: &mut FeedIndex, entry: FeedEntry) {
118    let before = feed.events.capacity();
119    let owned = feed_entry_owned_bytes(&entry);
120    feed.events.push(entry);
121    feed.charged
122        .grow(before, feed.events.capacity(), size_of::<FeedEntry>());
123    feed.charged.add(owned);
124}
125
126#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
127pub struct FeedCursor {
128    pub epoch: u64,
129    pub position: usize,
130}
131
132#[derive(Debug, Serialize)]
133pub struct FeedPage {
134    pub tenant_id: String,
135    pub cursor: FeedCursor,
136    pub head: FeedCursor,
137    pub events: Vec<EventDto>,
138    pub positions: Vec<usize>,
139    pub caught_up: bool,
140}
141
142pub(super) struct Candidate {
143    pub(super) position: usize,
144    pub(super) id: Uuid,
145    pub(super) at: Locator,
146}
147
148struct Scan {
149    epoch: u64,
150    head: usize,
151    start: FeedCursor,
152    candidates: Vec<Candidate>,
153    stop: usize,
154}
155
156/// Positions past `visible` are not served yet.
157fn scan_feed(
158    feed: &FeedIndex,
159    visible: usize,
160    cursor: Option<FeedCursor>,
161    limit: usize,
162    prefixes: &[String],
163    entity: Option<&str>,
164) -> Result<Scan> {
165    let epoch = feed.epoch;
166    let head = feed.events.len().min(visible);
167    let start = cursor.unwrap_or(FeedCursor { epoch, position: 0 });
168    if start.epoch != epoch || start.position > head {
169        return Err(AllSourceError::VersionConflict {
170            expected: start.epoch,
171            current: epoch,
172        });
173    }
174    let mut candidates = Vec::new();
175    let mut position = start.position;
176    if limit > 0 {
177        let scan_end = head.min(start.position.saturating_add(SCAN_WINDOW));
178        while position < scan_end {
179            let entry = &feed.events[position];
180            position += 1;
181            if entity.is_none_or(|entity| &*entry.entity_id == entity)
182                && (prefixes.is_empty()
183                    || prefixes
184                        .iter()
185                        .any(|prefix| entry.event_type.starts_with(prefix.as_str())))
186            {
187                candidates.push(Candidate {
188                    position: position - 1,
189                    id: entry.id,
190                    at: entry.at.clone(),
191                });
192                if candidates.len() == limit {
193                    break;
194                }
195            }
196        }
197    }
198    Ok(Scan {
199        epoch,
200        head,
201        start,
202        candidates,
203        stop: position,
204    })
205}
206
207impl EventStore {
208    fn durable_feed_log(&self, tenant: &str) -> Option<&FeedLog> {
209        self.feed_log.as_deref().filter(|log| log.includes(tenant))
210    }
211
212    pub(super) fn observe_feed_head(&self, event: &Event, _position: usize) {
213        if event.event_type_str() == MODEL_EVENT {
214            return;
215        }
216        if let Some(log) = self.durable_feed_log(event.tenant_id_str()) {
217            self.observe_durable_feed(log, event);
218            return;
219        }
220        let tenant = event.tenant_id_str();
221        self.feed_indexes_charge.ensure(
222            &self.feed_indexes,
223            tenant,
224            || tenant.to_owned(),
225            FeedIndex::default,
226            tenant.len() as u64,
227        );
228        let mut feed = self.feed_indexes.entry(tenant.to_owned()).or_default();
229        if feed.ids.insert(event.id) {
230            push_entry(
231                &mut feed,
232                FeedEntry {
233                    id: event.id,
234                    event_type: Arc::from(event.event_type_str()),
235                    entity_id: Arc::from(event.entity_id_str()),
236                    at: Locator::Memory,
237                },
238            );
239        }
240    }
241
242    /// Drop a tenant's feed and release its key. The feed's own bytes go with
243    /// its [`Tally`].
244    pub(super) fn remove_feed_index(&self, tenant: &str) {
245        if self.feed_indexes.remove(tenant).is_some() {
246            self.feed_indexes_charge.release_owned(tenant.len() as u64);
247        }
248    }
249
250    fn feed_entry_for(&self, tenant: &str) -> dashmap::mapref::one::RefMut<'_, String, FeedIndex> {
251        self.feed_indexes_charge.ensure(
252            &self.feed_indexes,
253            tenant,
254            || tenant.to_owned(),
255            FeedIndex::default,
256            tenant.len() as u64,
257        );
258        self.feed_indexes.entry(tenant.to_owned()).or_default()
259    }
260
261    fn insert_feed_index(&self, tenant: &str, feed: FeedIndex) {
262        self.feed_indexes_charge.ensure(
263            &self.feed_indexes,
264            tenant,
265            || tenant.to_owned(),
266            FeedIndex::default,
267            tenant.len() as u64,
268        );
269        self.feed_indexes.insert(tenant.to_owned(), feed);
270    }
271
272    pub(super) fn rebuild_tenant_feed(&self, tenant: &str, events: &[Event]) {
273        self.remove_feed_index(tenant);
274        for event in events
275            .iter()
276            .filter(|event| event.tenant_id_str() == tenant)
277        {
278            self.observe_feed_head(event, 0);
279        }
280    }
281
282    /// Called under the events write lock, as is every durable index build,
283    /// so the index and the log take records in the same order.
284    fn observe_durable_feed(&self, log: &FeedLog, event: &Event) {
285        let tenant = event.tenant_id_str();
286        let record = FeedLogRecord::new(event.id, event.event_type_str(), event.entity_id_str());
287        match log.append(tenant, record.clone()) {
288            Ok(Appended::New) => {
289                if let Some(mut feed) = self.feed_indexes.get_mut(tenant)
290                    && feed.durable
291                {
292                    feed.ids.insert(record.id);
293                    push_entry(
294                        &mut feed,
295                        FeedEntry {
296                            id: record.id,
297                            event_type: record.event_type,
298                            entity_id: record.entity_id,
299                            at: Locator::Memory,
300                        },
301                    );
302                }
303            }
304            Ok(Appended::Duplicate | Appended::NotOpen) => {}
305            Err(error) => {
306                tracing::error!("Feed log append failed for event {}: {error}", event.id);
307                // The next read rebuilds the index and re-appends what the log lacks.
308                self.remove_feed_index(tenant);
309            }
310        }
311    }
312
313    /// Make every pending feed-log record durable. Runs before a checkpoint
314    /// retires WAL segments and before boot recovery truncates the WAL, so
315    /// the order the log gave recovered events is not lost with them.
316    pub(super) fn sync_feed_log(&self) -> Result<()> {
317        match &self.feed_log {
318            Some(log) => self.publish_feed_log(log, None),
319            None => Ok(()),
320        }
321    }
322
323    /// The WAL is fsynced first so that no visible position outlives the
324    /// event it names.
325    fn publish_feed_log(&self, log: &FeedLog, tenant: Option<&str>) -> Result<()> {
326        let pending = match tenant {
327            Some(tenant) => log.has_pending(tenant),
328            None => log.has_any_pending(),
329        };
330        if !pending {
331            return Ok(());
332        }
333        if let Some(wal) = &self.wal {
334            wal.sync()?;
335        }
336        match tenant {
337            Some(tenant) => log.sync_tenant(tenant),
338            None => log.sync_all(),
339        }
340    }
341
342    fn ensure_durable_feed(&self, tenant: &str, log: &FeedLog) -> Result<()> {
343        if !self
344            .feed_indexes
345            .get(tenant)
346            .is_some_and(|feed| feed.durable)
347        {
348            self.build_durable_feed(tenant, log)?;
349        }
350        self.publish_feed_log(log, Some(tenant))
351    }
352
353    /// Index the tenant's log. A tenant without one is backfilled from the
354    /// archive in path order plus memory, as the narrow index numbers it; a
355    /// tenant with one gets any event the log lacks appended at the end, so
356    /// no served position moves.
357    fn build_durable_feed(&self, tenant: &str, log: &FeedLog) -> Result<()> {
358        let _resident = self.cache_residency_gate.read();
359        let keys = match &self.storage {
360            Some(storage) => {
361                let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
362                storage.read().scan_feed_keys(tenant, &mut budget)?
363            }
364            None => Vec::new(),
365        };
366        let events = self.events.write();
367        if self
368            .feed_indexes
369            .get(tenant)
370            .is_some_and(|feed| feed.durable)
371        {
372            return Ok(());
373        }
374        let mut names: FastMap<String, Arc<str>> = fast_map();
375        let mut intern = |value: String| -> Arc<str> {
376            names
377                .entry(value)
378                .or_insert_with_key(|value| Arc::from(value.as_str()))
379                .clone()
380        };
381        let mut located: FastMap<Uuid, Locator> = fast_map_with_capacity(keys.len());
382        let mut seen = fast_set_with_capacity(keys.len());
383        let mut history = Vec::new();
384        for key in keys {
385            if key.event_type == MODEL_EVENT {
386                continue;
387            }
388            located.entry(key.id).or_insert(Locator::Archive {
389                file: key.file,
390                row: key.row,
391            });
392            if seen.insert(key.id) {
393                history.push(FeedLogRecord {
394                    id: key.id,
395                    event_type: intern(key.event_type),
396                    entity_id: intern(key.entity_id),
397                });
398            }
399        }
400        for event in events.iter().filter(|event| {
401            event.tenant_id_str() == tenant && event.event_type_str() != MODEL_EVENT
402        }) {
403            if seen.insert(event.id) {
404                history.push(FeedLogRecord {
405                    id: event.id,
406                    event_type: intern(event.event_type_str().to_owned()),
407                    entity_id: intern(event.entity_id_str().to_owned()),
408                });
409            }
410        }
411        if log.is_open(tenant) {
412            let mut appended = 0_usize;
413            for record in history {
414                if log.append(tenant, record)? == Appended::New {
415                    appended += 1;
416                }
417            }
418            if appended > 0 {
419                tracing::warn!("Feed log lacked {appended} archived or resident events; appended");
420            }
421        } else {
422            if let Some(wal) = &self.wal {
423                wal.sync()?;
424            }
425            log.create(tenant, &history)?;
426        }
427        let (epoch, records) = log
428            .records(tenant)
429            .ok_or_else(|| AllSourceError::StorageError("feed log is not open; retry".into()))?;
430        let mut feed = FeedIndex {
431            epoch,
432            events: Vec::with_capacity(records.len()),
433            ids: fast_set_with_capacity(records.len()),
434            narrow: true,
435            durable: true,
436            charged: Tally::new(Owner::FeedIndex),
437        };
438        for record in records {
439            feed.ids.insert(record.id);
440            push_entry(
441                &mut feed,
442                FeedEntry {
443                    at: located.get(&record.id).cloned().unwrap_or(Locator::Memory),
444                    id: record.id,
445                    event_type: record.event_type,
446                    entity_id: record.entity_id,
447                },
448            );
449        }
450        self.insert_feed_index(tenant, feed);
451        drop(events);
452        Ok(())
453    }
454
455    /// Number the tenant's whole history from the archive's id, type and
456    /// entity columns plus the events still only in memory. The epoch is new:
457    /// positions from any earlier index of this tenant do not carry over.
458    fn ensure_narrow_feed(&self, tenant: &str) -> Result<()> {
459        if self
460            .feed_indexes
461            .get(tenant)
462            .is_some_and(|feed| feed.narrow)
463        {
464            return Ok(());
465        }
466        let _resident = self.cache_residency_gate.read();
467        let keys = match &self.storage {
468            Some(storage) => {
469                let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
470                storage.read().scan_feed_keys(tenant, &mut budget)?
471            }
472            None => Vec::new(),
473        };
474        // Ingest observes the feed under the events write lock, so holding it
475        // makes the swap atomic with every concurrent append.
476        let events = self.events.write();
477        if self
478            .feed_indexes
479            .get(tenant)
480            .is_some_and(|feed| feed.narrow)
481        {
482            return Ok(());
483        }
484        let mut names: FastMap<String, Arc<str>> = fast_map();
485        let mut intern = |value: String| -> Arc<str> {
486            names
487                .entry(value)
488                .or_insert_with_key(|value| Arc::from(value.as_str()))
489                .clone()
490        };
491        let mut feed = FeedIndex {
492            narrow: true,
493            ..FeedIndex::default()
494        };
495        for key in keys {
496            if key.event_type == MODEL_EVENT || !feed.ids.insert(key.id) {
497                continue;
498            }
499            push_entry(
500                &mut feed,
501                FeedEntry {
502                    id: key.id,
503                    event_type: intern(key.event_type),
504                    entity_id: intern(key.entity_id),
505                    at: Locator::Archive {
506                        file: key.file,
507                        row: key.row,
508                    },
509                },
510            );
511        }
512        for event in events.iter().filter(|event| {
513            event.tenant_id_str() == tenant && event.event_type_str() != MODEL_EVENT
514        }) {
515            if feed.ids.insert(event.id) {
516                push_entry(
517                    &mut feed,
518                    FeedEntry {
519                        id: event.id,
520                        event_type: intern(event.event_type_str().to_owned()),
521                        entity_id: intern(event.entity_id_str().to_owned()),
522                        at: Locator::Memory,
523                    },
524                );
525            }
526        }
527        self.insert_feed_index(tenant, feed);
528        drop(events);
529        Ok(())
530    }
531
532    /// Epoch changes force a rebuild instead of silently skipping reordered history.
533    pub fn tenant_feed(
534        &self,
535        tenant: &str,
536        cursor: Option<FeedCursor>,
537        limit: usize,
538    ) -> Result<FeedPage> {
539        self.tenant_feed_filtered(tenant, cursor, limit, &[])
540    }
541
542    pub fn tenant_feed_filtered(
543        &self,
544        tenant: &str,
545        cursor: Option<FeedCursor>,
546        limit: usize,
547        prefixes: &[String],
548    ) -> Result<FeedPage> {
549        self.tenant_feed_scoped(tenant, cursor, limit, prefixes, None)
550    }
551
552    pub fn tenant_feed_scoped(
553        &self,
554        tenant: &str,
555        cursor: Option<FeedCursor>,
556        limit: usize,
557        prefixes: &[String],
558        entity: Option<&str>,
559    ) -> Result<FeedPage> {
560        if limit > 500 {
561            return Err(AllSourceError::InvalidInput(
562                "feed limit must be 0..500".into(),
563            ));
564        }
565        let durable = self.durable_feed_log(tenant);
566        if let Some(log) = durable {
567            self.ensure_durable_feed(tenant, log)?;
568        } else if narrow_feed_enabled() {
569            self.ensure_narrow_feed(tenant)?;
570        } else {
571            self.ensure_tenant_loaded_with_integrity(tenant, true)?;
572            if self.storage.is_some() && !self.tenant_loader.is_complete(tenant) {
573                return Err(AllSourceError::StorageError(
574                    "feed archive certification was evicted; retry".into(),
575                ));
576            }
577        }
578        let _resident = self.cache_residency_gate.read();
579        let Scan {
580            epoch,
581            head: head_position,
582            start,
583            candidates,
584            stop: scan_stop,
585        } = match durable {
586            Some(log) => {
587                let visible = log.durable_len(tenant);
588                match self.feed_indexes.get(tenant) {
589                    Some(feed) if feed.durable => {
590                        scan_feed(&feed, visible, cursor, limit, prefixes, entity)
591                    }
592                    // A default index here would serve a random epoch.
593                    _ => Err(AllSourceError::StorageError(
594                        "feed index was evicted; retry".into(),
595                    )),
596                }
597            }
598            None => scan_feed(
599                &self.feed_entry_for(tenant),
600                usize::MAX,
601                cursor,
602                limit,
603                prefixes,
604                entity,
605            ),
606        }?;
607        let head = FeedCursor {
608            epoch,
609            position: head_position,
610        };
611        if limit == 0 {
612            return Ok(FeedPage {
613                tenant_id: tenant.to_owned(),
614                cursor: head,
615                head,
616                events: vec![],
617                positions: vec![],
618                caught_up: true,
619            });
620        }
621        let events = self.feed_payloads(tenant, &candidates)?;
622        let mut output = Vec::new();
623        let mut positions = Vec::new();
624        let mut bytes = 1024;
625        let mut cursor_position = scan_stop.max(start.position);
626        for (candidate, event) in candidates.iter().zip(events) {
627            let dto = EventDto::from(&event);
628            let size = serde_json::to_vec(&dto)?.len() + 24;
629            if bytes + size > FEED_BYTES {
630                if output.is_empty() {
631                    return Err(AllSourceError::InvalidInput(
632                        "single feed event exceeds bounded feed response".into(),
633                    ));
634                }
635                cursor_position = candidate.position;
636                break;
637            }
638            bytes += size;
639            output.push(dto);
640            positions.push(candidate.position + 1);
641        }
642        Ok(FeedPage {
643            tenant_id: tenant.to_owned(),
644            cursor: FeedCursor {
645                epoch,
646                position: cursor_position,
647            },
648            head,
649            events: output,
650            positions,
651            caught_up: cursor_position >= head_position,
652        })
653    }
654
655    /// Payloads for `candidates`, in order. If an archive file moved under the
656    /// index (compaction or repack), locators are remapped from a fresh narrow
657    /// scan once; positions do not change.
658    fn feed_payloads(&self, tenant: &str, candidates: &[Candidate]) -> Result<Vec<Event>> {
659        if let Some(events) = self.read_feed_payloads(tenant, candidates)? {
660            return Ok(events);
661        }
662        let remapped = self.remap_feed_locators(tenant, candidates)?;
663        self.read_feed_payloads(tenant, &remapped)?.ok_or_else(|| {
664            self.remove_feed_index(tenant);
665            AllSourceError::StorageError("feed archive changed; retry".into())
666        })
667    }
668
669    /// `None` when a locator no longer resolves.
670    pub(super) fn read_feed_payloads(
671        &self,
672        tenant: &str,
673        candidates: &[Candidate],
674    ) -> Result<Option<Vec<Event>>> {
675        let mut found: FastMap<Uuid, Event> = fast_map_with_capacity(candidates.len());
676        // Path order fixes which error is reported when several files fail.
677        let mut by_file: BTreeMap<Arc<PathBuf>, Vec<u64>> = BTreeMap::new();
678        {
679            let events = self.events.read();
680            for candidate in candidates {
681                match &candidate.at {
682                    Locator::Memory => {
683                        let event = self
684                            .index
685                            .get_by_id(&candidate.id)
686                            .and_then(|offset| events.get(offset))
687                            .filter(|event| event.id == candidate.id);
688                        match event {
689                            Some(event) => {
690                                found.insert(candidate.id, event.clone());
691                            }
692                            None => return Ok(None),
693                        }
694                    }
695                    Locator::Archive { file, row } => {
696                        by_file.entry(Arc::clone(file)).or_default().push(*row);
697                    }
698                }
699            }
700        }
701        if !by_file.is_empty() {
702            let Some(storage) = &self.storage else {
703                return Ok(None);
704            };
705            let storage = storage.read();
706            let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
707            for (file, mut rows) in by_file {
708                rows.sort_unstable();
709                rows.dedup();
710                match storage.read_feed_rows(&file, &rows, tenant, &mut budget) {
711                    Ok(events) => {
712                        for event in events {
713                            found.insert(event.id, event);
714                        }
715                    }
716                    Err(_) if !file.exists() => return Ok(None),
717                    Err(error) => return Err(error),
718                }
719            }
720        }
721        let mut ordered = Vec::with_capacity(candidates.len());
722        for candidate in candidates {
723            match found.remove(&candidate.id) {
724                Some(event) => ordered.push(event),
725                None => return Ok(None),
726            }
727        }
728        Ok(Some(ordered))
729    }
730
731    fn remap_feed_locators(
732        &self,
733        tenant: &str,
734        candidates: &[Candidate],
735    ) -> Result<Vec<Candidate>> {
736        let keys = match &self.storage {
737            Some(storage) => {
738                let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
739                storage.read().scan_feed_keys(tenant, &mut budget)?
740            }
741            None => Vec::new(),
742        };
743        let mut located: FastMap<Uuid, Locator> = fast_map_with_capacity(keys.len());
744        for key in keys {
745            located.entry(key.id).or_insert(Locator::Archive {
746                file: key.file,
747                row: key.row,
748            });
749        }
750        if let Some(mut feed) = self.feed_indexes.get_mut(tenant) {
751            for entry in &mut feed.events {
752                if let Some(at) = located.get(&entry.id) {
753                    entry.at = at.clone();
754                }
755            }
756        }
757        Ok(candidates
758            .iter()
759            .map(|candidate| Candidate {
760                position: candidate.position,
761                id: candidate.id,
762                at: located
763                    .get(&candidate.id)
764                    .cloned()
765                    .unwrap_or(Locator::Memory),
766            })
767            .collect())
768    }
769}