Skip to main content

salsa/
interned.rs

1use std::any::TypeId;
2use std::borrow::Cow;
3use std::cell::UnsafeCell;
4use std::fmt;
5use std::hash::{BuildHasher, Hash};
6use std::marker::PhantomData;
7use std::num::NonZeroUsize;
8use std::path::{Path, PathBuf};
9use std::ptr::NonNull;
10
11use crossbeam_utils::CachePadded;
12use intrusive_collections::{LinkedList, LinkedListLink, UnsafeRef, intrusive_adapter};
13use rustc_hash::FxBuildHasher;
14use smallvec::SmallVec;
15
16use crate::durability::{AtomicDurability, Durability};
17use crate::function::VerifyResult;
18use crate::hash::{FxHashSet, FxIndexSet};
19use crate::id::{AsId, FromId};
20use crate::ingredient::Ingredient;
21use crate::plumbing::{self, Jar, ZalsaLocal};
22use crate::revision::AtomicRevision;
23use crate::sync::{Arc, Mutex, max_parallelism};
24use crate::table::Slot;
25use crate::table::memo::{MemoTable, MemoTableTypes, MemoTableWithTypesMut};
26use crate::zalsa::{IngredientIndex, JarKind, Zalsa};
27use crate::zalsa_local::QueryEdge;
28use crate::{DatabaseKeyIndex, Event, EventKind, Id, Revision};
29
30#[cfg(not(test))]
31const DEFAULT_REVISIONS: usize = 3;
32
33// More aggressive garbage collection by default when testing.
34#[cfg(test)]
35const DEFAULT_REVISIONS: usize = 1;
36
37/// Trait that defines the key properties of an interned struct.
38///
39/// Implemented by the `#[salsa::interned]` macro when applied to
40/// a struct.
41///
42/// # Safety
43///
44/// For every lifetime `'db`, `Fields<'db>` must be safe for Salsa to retain
45/// as `Fields<'static>` and later expose with the lifetime of a database
46/// borrow. Both types must have identical layouts and validity invariants.
47pub unsafe trait Configuration: Sized + 'static {
48    const LOCATION: crate::ingredient::Location;
49    const DEBUG_NAME: &'static str;
50
51    /// Whether this struct should be persisted with the database.
52    const PERSIST: bool;
53
54    // The minimum number of revisions that must pass before a stale value is garbage collected.
55    const REVISIONS: NonZeroUsize = NonZeroUsize::new(DEFAULT_REVISIONS).unwrap();
56
57    /// The fields of the struct being interned.
58    type Fields<'db>: InternedData;
59
60    /// The end user struct
61    type Struct<'db>: Copy + FromId + AsId;
62
63    /// Returns the size of any heap allocations in the output value, in bytes.
64    fn heap_size(_value: &Self::Fields<'_>) -> Option<usize> {
65        None
66    }
67
68    /// Serialize the fields using `serde`.
69    ///
70    /// Panics if the value is not persistable, i.e. `Configuration::PERSIST` is `false`.
71    fn serialize<S>(value: &Self::Fields<'_>, serializer: S) -> Result<S::Ok, S::Error>
72    where
73        S: plumbing::serde::Serializer;
74
75    /// Deserialize the fields using `serde`.
76    ///
77    /// Panics if the value is not persistable, i.e. `Configuration::PERSIST` is `false`.
78    fn deserialize<'de, D>(deserializer: D) -> Result<Self::Fields<'static>, D::Error>
79    where
80        D: plumbing::serde::Deserializer<'de>;
81}
82
83pub trait InternedData: Sized + Eq + Hash + Clone + Sync + Send {}
84impl<T: Eq + Hash + Clone + Sync + Send> InternedData for T {}
85
86pub struct JarImpl<C: Configuration> {
87    phantom: PhantomData<C>,
88}
89
90/// The interned ingredient hashes values of type `C::Fields` to produce an `Id`.
91///
92/// It used to store interned structs but also to store the ID fields of a tracked struct.
93/// Interned values are garbage collected and their memory reused based on an LRU heuristic.
94pub struct IngredientImpl<C: Configuration> {
95    /// Index of this ingredient in the database (used to construct database-IDs, etc).
96    ingredient_index: IngredientIndex,
97
98    /// A hasher for the sharded ID maps.
99    hasher: FxBuildHasher,
100
101    /// A shift used to determine the shard for a given hash.
102    shift: u32,
103
104    /// Sharded data that can only be accessed through a lock.
105    shards: Box<[CachePadded<Mutex<IngredientShard>>]>,
106
107    /// A queue of recent revisions in which values were interned.
108    revision_queue: RevisionQueue,
109
110    memo_table_types: Arc<MemoTableTypes>,
111
112    _marker: PhantomData<fn() -> C>,
113}
114
115struct IngredientShard {
116    /// Maps from data to the existing interned value for that data.
117    ///
118    /// The pointer is stable for the lifetime of the database. Storing it directly avoids a table
119    /// lookup when hashing or comparing an existing entry.
120    key_map: hashbrown::HashTable<ValueKey>,
121
122    /// An intrusive linked list for LRU.
123    lru: LinkedList<LruEntryAdapter>,
124}
125
126impl Default for IngredientShard {
127    fn default() -> Self {
128        Self {
129            lru: LinkedList::default(),
130            key_map: hashbrown::HashTable::new(),
131        }
132    }
133}
134
135// SAFETY: `IngredientShard` is only accessed through its mutex. Its LRU contains pointers to live,
136// stable values from this ingredient, and those pointers and their links are accessed only while
137// holding that mutex.
138unsafe impl Send for IngredientShard {}
139
140// SAFETY: `shard` is immutable. LRU links and IDs are protected by the shard lock.
141// Revision and durability are atomic and only published after the fields and memos are ready.
142// `fields` is mutated only while holding that lock after stale-slot reuse guarantees no references
143// remain, and is read only while holding the lock or after `assert_validated` prevents reuse.
144// `memos` supports concurrent shared access, and is mutated only with
145// exclusive access or after stale-slot reuse guarantees no shared references remain.
146unsafe impl<C: Configuration> Sync for Value<C> {}
147
148intrusive_adapter!(LruEntryAdapter = UnsafeRef<LruEntry>: LruEntry { link => LinkedListLink });
149
150/// Struct storing the interned fields.
151pub struct Value<C>
152where
153    C: Configuration,
154{
155    /// The index of the shard containing this value.
156    ///
157    /// This is immutable after construction and may be read to locate the protecting shard lock.
158    shard: u16,
159
160    /// Type-erased state used by the LRU scan.
161    lru: LruEntry,
162
163    /// The interned fields for this value.
164    ///
165    /// These are valid for read-only access as long as the lock is held
166    /// or the value has been validated in the current revision.
167    fields: UnsafeCell<C::Fields<'static>>,
168
169    /// Memos attached to this interned value.
170    ///
171    /// This is valid for read-only access as long as the lock is held
172    /// or the value has been validated in the current revision.
173    memos: UnsafeCell<MemoTable>,
174
175    /// The minimum durability of all inputs consumed by the creator query.
176    ///
177    /// Durability determines whether the value is added to the LRU list, but the LRU scan does
178    /// not read it. Keeping this byte outside `LruEntry` lets it occupy padding in the outer value;
179    /// adding it to the already aligned entry would increase the entry's size.
180    /// Writers hold the shard lock. Readers may observe non-reusable durability without the
181    /// lock, so it must only be published after initializing the fields and memos and removing
182    /// the value from the LRU. A non-reusable value never becomes reusable again.
183    durability: AtomicDurability,
184}
185
186/// Type-erased state stored in the intrusive LRU list.
187struct LruEntry {
188    /// Intrusive links, accessed only while holding the owning shard lock.
189    link: LinkedListLink,
190
191    /// The interned ID for this value.
192    ///
193    /// Storing this on the value itself is necessary to identify slots
194    /// from the LRU list, as well as keep track of the generation.
195    ///
196    /// Values that are reused increment the ID generation, as if they had
197    /// allocated a new slot. This eliminates the need for dependency edges
198    /// on queries that *read* from an interned value, as any memos dependent
199    /// on the previous value will not match the new ID.
200    ///
201    /// However, reusing a slot invalidates the previous ID, so queries that
202    /// *create* a reusable interned value record dependency edges to ensure the
203    /// value is re-interned with a new ID.
204    /// Only accessed while holding the shard lock or with exclusive database access.
205    id: UnsafeCell<Id>,
206
207    /// The revision the value was most recently interned in. Writers hold the shard lock
208    /// and release-publish this only after the fields and memos are ready to read.
209    last_interned_at: AtomicRevision,
210}
211
212impl LruEntry {
213    /// Returns a pointer to `value.lru` with provenance derived from `value`.
214    #[inline]
215    fn ptr_from_value<C: Configuration>(value: &Value<C>) -> *const Self {
216        let value = std::ptr::from_ref(value).cast::<u8>();
217
218        // SAFETY: `lru` is a field within `value`, so adding its offset is in bounds. Starting from
219        // `value`, rather than `value.lru`, gives the result provenance that permits
220        // `value_from_ptr` to subtract the offset again.
221        unsafe { value.add(std::mem::offset_of!(Value<C>, lru)).cast() }
222    }
223
224    /// Recovers a value from its LRU entry.
225    ///
226    /// # Safety
227    ///
228    /// `entry` must have been produced by `Self::ptr_from_value` for the same configuration, and
229    /// its value must remain live for the returned lifetime.
230    #[inline]
231    unsafe fn value_from_ptr<'a, C: Configuration>(entry: *const Self) -> &'a Value<C> {
232        // SAFETY: `ptr_from_value` derives `entry` from the enclosing `Value<C>` pointer, so
233        // subtracting the same field offset recovers that pointer. The other requirements are
234        // guaranteed by the caller.
235        unsafe {
236            &*entry
237                .cast::<u8>()
238                .sub(std::mem::offset_of!(Value<C>, lru))
239                .cast::<Value<C>>()
240        }
241    }
242}
243
244/// Returns `true` if a value slot with the given durability can be reused when interning.
245///
246/// This intentionally remains generic so the compiler specializes the immortal and reusable
247/// configurations instead of branching on `REVISIONS` at runtime.
248fn is_reusable<C: Configuration>(durability: Durability) -> bool {
249    // Garbage collection is disabled.
250    if C::REVISIONS == IMMORTAL {
251        return false;
252    }
253
254    // Collecting higher durability values requires invalidating the revision for their
255    // durability (see `Database::synthetic_write`, which requires a mutable reference to
256    // the database) to avoid short-circuiting calls to `maybe_changed_after`. This is
257    // necessary because `maybe_changed_after` for interned values is not "pure"; it updates
258    // the `last_interned_at` field before validating a given value to ensure that it is not
259    // reused after read in the current revision.
260    durability == Durability::LOW
261}
262
263/// Record a dependency on this value if its slot can be reused.
264fn report_tracked_read_if_reusable<C: Configuration>(
265    zalsa_local: &ZalsaLocal,
266    index: DatabaseKeyIndex,
267    current_revision: Revision,
268    durability: Durability,
269) {
270    if is_reusable::<C>(durability) {
271        zalsa_local.report_tracked_read_simple(index, durability, current_revision);
272    } else {
273        // The value cannot be reused, so the dependency edge is unnecessary. Its durability
274        // is derived from the active query, but its revision must still contribute to the
275        // query's stamp because the interned ID may have changed due to reuse.
276        zalsa_local.report_tracked_read_revision(current_revision);
277    }
278}
279
280struct ReusableSlot {
281    entry: *const LruEntry,
282    old_id: Id,
283    new_id: Id,
284}
285
286impl<C> Value<C>
287where
288    C: Configuration,
289{
290    /// Fields of this interned struct.
291    #[cfg(feature = "salsa_unstable")]
292    pub fn fields<'db>(&'db self) -> &'db C::Fields<'db> {
293        // SAFETY: The fact that this function is safe is technically unsound. However, interned
294        // values are only exposed if they have been validated in the current revision, which
295        // ensures that they are not reused while being accessed.
296        // SAFETY: Guaranteed by `Configuration`; the restored lifetime is
297        // bounded by the borrow of this interned value.
298        unsafe { std::mem::transmute::<&C::Fields<'static>, &C::Fields<'db>>(&*self.fields.get()) }
299    }
300
301    /// Returns memory usage information about the interned value.
302    ///
303    /// # Safety
304    ///
305    /// The `MemoTable` must belong to a `Value` of the correct type. The caller must
306    /// ensure exclusive access to the database's storage for the duration of this call.
307    #[cfg(all(not(feature = "shuttle"), feature = "salsa_unstable"))]
308    unsafe fn memory_usage(&self, memo_table_types: &MemoTableTypes) -> crate::database::SlotInfo {
309        let heap_size = C::heap_size(self.fields());
310        // SAFETY: The caller guarantees exclusive access to the database's storage,
311        // so the value's memos cannot be modified while we read them.
312        let memos = unsafe { &*self.memos.get() };
313        // SAFETY: The caller guarantees this is the correct types table.
314        let memos = unsafe { memo_table_types.attach_memos(memos) };
315
316        crate::database::SlotInfo {
317            debug_name: C::DEBUG_NAME,
318            size_of_metadata: std::mem::size_of::<Self>()
319                - std::mem::size_of::<C::Fields<'static>>(),
320            size_of_fields: std::mem::size_of::<C::Fields<'static>>(),
321            heap_size_of_fields: heap_size,
322            // SAFETY: The caller guarantees exclusive access to the database's storage.
323            memos: unsafe { memos.memory_usage() },
324        }
325    }
326}
327
328impl<C: Configuration> Default for JarImpl<C> {
329    fn default() -> Self {
330        Self {
331            phantom: PhantomData,
332        }
333    }
334}
335
336impl<C: Configuration> Jar for JarImpl<C> {
337    fn create_ingredients(
338        _zalsa: &mut Zalsa,
339        first_index: IngredientIndex,
340    ) -> Vec<Box<dyn Ingredient>> {
341        vec![Box::new(IngredientImpl::<C>::new(first_index)) as _]
342    }
343
344    fn id_struct_type_id() -> TypeId {
345        TypeId::of::<C::Struct<'static>>()
346    }
347}
348
349impl<C> IngredientImpl<C>
350where
351    C: Configuration,
352{
353    pub fn new(ingredient_index: IngredientIndex) -> Self {
354        let shards = new_shards();
355        let shift = usize::BITS - shards.len().trailing_zeros();
356
357        Self {
358            ingredient_index,
359            hasher: FxBuildHasher,
360            memo_table_types: Arc::new(MemoTableTypes::default()),
361            revision_queue: RevisionQueue::new(C::REVISIONS),
362            shift,
363            shards,
364            _marker: PhantomData,
365        }
366    }
367    /// Returns the shard for a given hash.
368    ///
369    /// Note that this value is guaranteed to be in-bounds for `self.shards`.
370    #[inline]
371    fn shard(&self, hash: u64) -> usize {
372        // https://github.com/xacrimon/dashmap/blob/366ce7e7872866a06de66eb95002fa6cf2c117a7/src/lib.rs#L421
373        ((hash as usize) << 7) >> self.shift
374    }
375
376    /// # Safety
377    ///
378    /// The `from_internal_data` function must be called to restore the correct lifetime
379    /// before access.
380    unsafe fn to_internal_data<'db>(&'db self, data: C::Fields<'db>) -> C::Fields<'static> {
381        // SAFETY: Guaranteed by `Configuration` and retained in this ingredient.
382        unsafe { std::mem::transmute::<C::Fields<'db>, C::Fields<'static>>(data) }
383    }
384
385    fn from_internal_data<'db>(data: &'db C::Fields<'static>) -> &'db C::Fields<'db> {
386        // SAFETY: Guaranteed by `Configuration`; the restored lifetime is
387        // bounded by the borrow of the retained data.
388        unsafe { std::mem::transmute::<&'db C::Fields<'static>, &'db C::Fields<'db>>(data) }
389    }
390
391    /// Intern data to a unique reference.
392    ///
393    /// If `key` is already interned, returns the existing [`Id`] for the interned data.
394    pub fn intern<'db, Key>(
395        &'db self,
396        zalsa: &'db Zalsa,
397        zalsa_local: &'db ZalsaLocal,
398        key: Key,
399    ) -> C::Struct<'db>
400    where
401        Key: Hash,
402        C::Fields<'db>: HashEqLike<Key>,
403        Key: Lookup<C::Fields<'db>>,
404    {
405        FromId::from_id(self.intern_id(zalsa, zalsa_local, key))
406    }
407
408    /// Intern data to a unique reference.
409    ///
410    /// If `key` is already interned, returns the existing [`Id`] for the interned data.
411    pub fn intern_id<'db, Key>(
412        &'db self,
413        zalsa: &'db Zalsa,
414        zalsa_local: &'db ZalsaLocal,
415        key: Key,
416    ) -> crate::Id
417    where
418        Key: Hash,
419        // We'd want the following predicate, but this currently implies `'static` due to a rustc
420        // bug
421        // for<'db> C::Data<'db>: HashEqLike<Key>,
422        // so instead we go with this and transmute the lifetime in the `eq` closure
423        C::Fields<'db>: HashEqLike<Key>,
424        Key: Lookup<C::Fields<'db>>,
425    {
426        // Record the current revision as active.
427        let current_revision = zalsa.current_revision();
428        if C::REVISIONS != IMMORTAL {
429            self.revision_queue.record(current_revision);
430        }
431
432        // Hash the value before acquiring the lock.
433        let hash = self.hasher.hash_one(&key);
434
435        let shard_index = self.shard(hash);
436        // SAFETY: `shard_index` is guaranteed to be in-bounds for `self.shards`.
437        let shard = unsafe { &mut *self.shards.get_unchecked(shard_index).lock() };
438
439        // SAFETY: We hold the lock for the shard containing the value.
440        let eq = |value: &ValueKey| unsafe { Self::value_eq(value.value::<C>(), &key) };
441
442        // Attempt a fast-path lookup of already interned data.
443        if let Some(value) = shard.key_map.find(hash, eq) {
444            // SAFETY: Values remain allocated for the lifetime of the database.
445            let value = unsafe { value.value::<C>() };
446
447            // SAFETY: We hold the lock for the shard containing the value.
448            let id = unsafe { *value.lru.id.get() };
449            let mut durability = value.durability.load();
450            let index = self.database_key_index(id);
451
452            // Validate the value in this revision to avoid reuse.
453            if value.lru.last_interned_at.load() < current_revision {
454                value.lru.last_interned_at.store(current_revision);
455
456                zalsa.event(&|| {
457                    Event::new(EventKind::DidValidateInternedValue {
458                        key: index,
459                        revision: current_revision,
460                    })
461                });
462
463                if is_reusable::<C>(durability) {
464                    // Move the value to the front of the LRU list.
465                    //
466                    // SAFETY: We hold the lock for the shard containing the value, and `value` is
467                    // a reusable value that was previously interned, so is in the list.
468                    unsafe { shard.lru.cursor_mut_from_ptr(&value.lru).remove() };
469
470                    // SAFETY: The value pointer is valid for the lifetime of the database
471                    // and never accessed mutably directly.
472                    unsafe {
473                        shard
474                            .lru
475                            .push_front(UnsafeRef::from_raw(LruEntry::ptr_from_value(value)))
476                    };
477                }
478            }
479
480            // Non-reusable slots need only contribute their revision to the active query.
481            if !is_reusable::<C>(durability) {
482                if let Some(query_durability) =
483                    zalsa_local.report_tracked_read_revision(current_revision)
484                    && query_durability > durability
485                {
486                    value.durability.store(query_durability);
487                }
488                return id;
489            }
490
491            if let Some((_, stamp)) = zalsa_local.active_query() {
492                // Record the maximum durability across all queries that intern this value.
493                durability = std::cmp::max(durability, stamp.durability);
494
495                // Remove the value from the LRU before publishing a non-reusable durability.
496                if !is_reusable::<C>(durability) {
497                    // SAFETY: We hold the lock for the shard containing the value, and `value`
498                    // was previously reusable, so is in the list.
499                    unsafe { shard.lru.cursor_mut_from_ptr(&value.lru).remove() };
500                }
501                value.durability.store(durability);
502            }
503
504            // Record a dependency on the value if its slot can be reused.
505            //
506            // See `intern_id_cold` for why we need to use `current_revision` here. Note that just
507            // because this value was previously interned does not mean it was previously interned
508            // by *our query*, so the same considerations apply.
509            report_tracked_read_if_reusable::<C>(zalsa_local, index, current_revision, durability);
510
511            return id;
512        }
513
514        // Fill up the table for the first few revisions without attempting garbage collection.
515        if !self.revision_queue.is_primed() {
516            return self.intern_id_cold(key, zalsa, zalsa_local, shard, shard_index, hash);
517        }
518
519        // Otherwise, try to reuse a stale slot.
520        // SAFETY: We hold the lock for this ingredient's shard, and `current_revision` is the
521        // database's current revision.
522        let Some((slot, value)) = (unsafe { self.find_reusable_slot(current_revision, shard) })
523        else {
524            // If we could not find a stale slot, we are forced to allocate a new one.
525            return self.intern_id_cold(key, zalsa, zalsa_local, shard, shard_index, hash);
526        };
527
528        // Record the durability of the current query on the interned value.
529        let (durability, last_interned_at) = zalsa_local
530            .active_query()
531            .map(|(_, stamp)| (stamp.durability, current_revision))
532            // If there is no active query this durability does not actually matter.
533            // `last_interned_at` needs to be `Revision::MAX`, see the `intern_access_in_different_revision` test.
534            .unwrap_or((Durability::MAX, Revision::max()));
535
536        // Assemble and hash the replacement before mutating the existing slot. Both operations
537        // can invoke user code and panic.
538        // SAFETY: We call `from_internal_data` to restore the correct lifetime before access.
539        let new_fields = unsafe { self.to_internal_data(key.into_owned()) };
540
541        // SAFETY: We hold the lock for the shard containing the value.
542        let old_hash = self.hasher.hash_one(unsafe { &*value.fields.get() });
543
544        let index = self.database_key_index(slot.new_id);
545
546        // Record a dependency on the new value if its slot can be reused.
547        //
548        // See `intern_id_cold` for why we need to use `current_revision` here.
549        report_tracked_read_if_reusable::<C>(zalsa_local, index, current_revision, durability);
550
551        // Reserve space while the old slot is still intact. Resizing can invoke user hashing, so
552        // doing it before mutating the slot leaves the old value reachable if that panics. Once
553        // capacity is available, replacing the pointer entry cannot invoke user code.
554        // SAFETY: We hold the lock for the shard containing every value passed to `hasher`.
555        let hasher = |value: &ValueKey| unsafe { self.value_hash(value.value::<C>()) };
556        shard.key_map.reserve(1, hasher);
557
558        // Clear the old memos before publishing either a current revision or a non-reusable
559        // durability. If a callback panics, the old fields, ID and key-map entry remain intact;
560        // `clear_memos` drops the remaining memos during unwinding.
561        // SAFETY: The slot is stale and reusable, and we hold its shard lock.
562        unsafe { self.clear_memos(zalsa, &mut *value.memos.get(), slot.old_id) };
563
564        // Remove the value from the LRU list.
565        // SAFETY: We hold the shard lock and `value` is currently in the LRU.
566        unsafe { shard.lru.cursor_mut_from_ptr(&value.lru).remove() };
567
568        // Remove the previous value from the key map.
569        //
570        // The pointer stays the same when a slot is reused, but the fields and thus the hash can
571        // change, so we need to re-insert it. The old and new hashes map to the same shard, because
572        // we selected the LRU list based on the new fields.
573        let value_key = ValueKey::new(value);
574        shard
575            .key_map
576            .find_entry(old_hash, |found_value| found_value.0 == value_key.0)
577            .unwrap_or_else(|_| panic!("interned value in LRU so must be in key_map"))
578            .remove();
579
580        // Replace the fields without dropping the previous value until the slot is consistent.
581        //
582        // SAFETY: `find_reusable_slot` guarantees that the value is reusable and stale, so no
583        // references to its fields remain. We still hold the shard lock.
584        let old_fields = unsafe { std::mem::replace(&mut *value.fields.get(), new_fields) };
585
586        // SAFETY: We hold the shard lock, which protects the ID.
587        unsafe { *value.lru.id.get() = slot.new_id };
588
589        shard.key_map.insert_unique(hash, value_key, hasher);
590
591        if is_reusable::<C>(durability) {
592            // Move the value to the front of the LRU list.
593            //
594            // SAFETY: The value pointer is valid for the lifetime of the database
595            // and is never accessed mutably directly.
596            unsafe {
597                shard
598                    .lru
599                    .push_front(UnsafeRef::from_raw(LruEntry::ptr_from_value(value)))
600            };
601        }
602
603        // Either atomic can allow a reader to access the slot without locking. Publish only
604        // after the new fields, empty memo table and LRU membership are consistent. Doing this
605        // before dropping the old fields also leaves a valid slot if their destructor panics.
606        value.durability.store(durability);
607        value.lru.last_interned_at.store(last_interned_at);
608
609        drop(old_fields);
610
611        zalsa.event(&|| {
612            Event::new(EventKind::DidReuseInternedValue {
613                key: index,
614                revision: current_revision,
615            })
616        });
617
618        slot.new_id
619    }
620
621    /// The cold path for interning a value, allocating a new slot.
622    ///
623    /// Returns `true` if the current thread interned the value.
624    #[allow(clippy::too_many_arguments)]
625    fn intern_id_cold<'db, Key>(
626        &'db self,
627        key: Key,
628        zalsa: &Zalsa,
629        zalsa_local: &ZalsaLocal,
630        shard: &mut IngredientShard,
631        shard_index: usize,
632        hash: u64,
633    ) -> crate::Id
634    where
635        Key: Hash,
636        C::Fields<'db>: HashEqLike<Key>,
637        Key: Lookup<C::Fields<'db>>,
638    {
639        let current_revision = zalsa.current_revision();
640
641        // Record the durability of the current query on the interned value.
642        let (durability, last_interned_at) = zalsa_local
643            .active_query()
644            .map(|(_, stamp)| (stamp.durability, current_revision))
645            // If there is no active query this durability does not actually matter.
646            // `last_interned_at` needs to be `Revision::MAX`, see the `intern_access_in_different_revision` test.
647            .unwrap_or((Durability::MAX, Revision::max()));
648
649        // Converting a borrowed key can call user code. Finish before the page selects
650        // a slot so that a reentrant allocation cannot select the same slot.
651        let fields = key.into_owned();
652
653        let (id, value) = zalsa_local.allocate(zalsa, self.ingredient_index, |id| Value::<C> {
654            shard: shard_index as u16,
655            lru: LruEntry {
656                link: LinkedListLink::new(),
657                id: UnsafeCell::new(id),
658                last_interned_at: AtomicRevision::new(last_interned_at),
659            },
660            // SAFETY: We call `from_internal_data` to restore the correct lifetime before access.
661            fields: UnsafeCell::new(unsafe { self.to_internal_data(fields) }),
662            // SAFETY: We only ever access the memos of a value that we allocated through
663            // our `MemoTableTypes`.
664            memos: UnsafeCell::new(unsafe { MemoTable::new(self.memo_table_types()) }),
665            durability: AtomicDurability::new(durability),
666        });
667
668        // Insert the newly allocated value.
669        // SAFETY: We hold this ingredient's shard lock, and `value` is the live, stable value that
670        // we just allocated in that shard.
671        unsafe { self.insert_value(shard, hash, value) };
672
673        let index = self.database_key_index(id);
674
675        // Record a dependency on the newly interned value if its slot can be reused.
676        //
677        // Note that the ID is unique to this use of the interned slot, so it seems logical to use
678        // `Revision::start()` here. However, it is possible that the ID we read is different from
679        // the previous execution of this query if the previous slot has been reused. In that case,
680        // the query has changed without a corresponding input changing. Using `current_revision`
681        // for dependencies on interned values encodes the fact that interned IDs are not stable
682        // across revisions.
683        report_tracked_read_if_reusable::<C>(zalsa_local, index, current_revision, durability);
684
685        zalsa.event(&|| {
686            Event::new(EventKind::DidInternValue {
687                key: index,
688                revision: current_revision,
689            })
690        });
691
692        id
693    }
694
695    /// Inserts a newly interned value into the LRU list and key map.
696    ///
697    /// # Safety
698    ///
699    /// `shard` must be a locked shard from this ingredient, and `value` must be the live, stable
700    /// `Value<C>` allocated in that shard.
701    unsafe fn insert_value(&self, shard: &mut IngredientShard, hash: u64, value: &Value<C>) {
702        /// Inserts a newly allocated value without depending on `C`.
703        ///
704        /// # Safety
705        ///
706        /// The caller must hold `shard`'s lock. `value_key` and `entry` must have been produced
707        /// from the same live value in this shard,
708        /// `reusable` must reflect whether that value is reusable, and `hasher` must hash values
709        /// while that lock is held.
710        unsafe fn inner(
711            shard: &mut IngredientShard,
712            hash: u64,
713            value_key: ValueKey,
714            entry: *const LruEntry,
715            reusable: bool,
716            hasher: &dyn Fn(&ValueKey) -> u64,
717        ) {
718            if reusable {
719                // SAFETY: The caller guarantees that `entry` points to a live `LruEntry` and was
720                // derived from its enclosing value.
721                unsafe { shard.lru.push_front(UnsafeRef::from_raw(entry)) };
722            }
723
724            insert_unique_erased(shard, hash, value_key, hasher);
725
726            debug_assert_eq!(hash, hasher(&value_key));
727        }
728
729        let durability = value.durability.load();
730        let reusable = is_reusable::<C>(durability);
731        let value_key = ValueKey::new(value);
732
733        // SAFETY: We hold the lock for the shard containing every value passed to `hasher`.
734        let hasher = |value: &ValueKey| unsafe { self.value_hash(value.value::<C>()) };
735
736        // SAFETY: We hold the lock for `shard`; `value_key` and `ptr_from_value` were derived from
737        // the same live value in that shard, and `reusable` was read from that value.
738        unsafe {
739            inner(
740                shard,
741                hash,
742                value_key,
743                LruEntry::ptr_from_value(value),
744                reusable,
745                &hasher,
746            )
747        };
748    }
749
750    /// Finds a reusable slot and reconstructs its typed value.
751    ///
752    /// # Safety
753    ///
754    /// `shard` must be a locked shard from this ingredient, and `current_revision` must be the
755    /// database's current revision. Every LRU entry pointer must have been derived from its live
756    /// enclosing `Value<C>` using `LruEntry::ptr_from_value`, so subtracting the field offset
757    /// recovers that value. Those values must remain stable for the ingredient's lifetime.
758    ///
759    /// The LRU contains only reusable values. Therefore, a slot returned as stale has no
760    /// outstanding references to its fields or memos and may be mutated while the lock is held.
761    unsafe fn find_reusable_slot(
762        &self,
763        current_revision: Revision,
764        shard: &mut IngredientShard,
765    ) -> Option<(ReusableSlot, &Value<C>)> {
766        /// Finds the least-recently-used stale slot whose generation can be incremented.
767        ///
768        /// # Safety
769        ///
770        /// The caller must hold `shard`'s lock, and every pointer in its LRU must refer to a live
771        /// `LruEntry` belonging to the shard.
772        unsafe fn inner(
773            revision_queue: &RevisionQueue,
774            current_revision: Revision,
775            shard: &mut IngredientShard,
776        ) -> Option<ReusableSlot> {
777            let mut cursor = shard.lru.back_mut();
778
779            while let Some(entry) = cursor.as_cursor().clone_pointer() {
780                let entry = UnsafeRef::into_raw(entry);
781
782                // SAFETY: The caller guarantees that `entry` points to a live value in this shard.
783                let entry_ref = unsafe { &*entry };
784                let last_interned_at = entry_ref.last_interned_at.load();
785
786                // The value must not have been read in the current revision to be collected
787                // soundly, but we also do not want to collect values that have been read recently.
788                //
789                // Note that the list is sorted by LRU, so if the tail of the list is not stale, we
790                // will not find any stale slots.
791                if !revision_queue.is_stale(last_interned_at) {
792                    return None;
793                }
794
795                // We should never reuse a value that was accessed in the current revision.
796                assert!(last_interned_at < current_revision);
797
798                // SAFETY: We hold the shard lock, which protects the ID.
799                let old_id = unsafe { *entry_ref.id.get() };
800
801                // Increment the generation of the ID, as if we allocated a new slot.
802                //
803                // If the ID is at its maximum generation, we are forced to leak the slot.
804                if let Some(new_id) = old_id.next_generation() {
805                    return Some(ReusableSlot {
806                        entry,
807                        old_id,
808                        new_id,
809                    });
810                }
811
812                // This slot can never be reused. Remove it and retry with the previous element.
813                cursor.remove().unwrap();
814                cursor = shard.lru.back_mut();
815            }
816
817            None
818        }
819
820        // SAFETY: Guaranteed by the caller.
821        let slot = unsafe { inner(&self.revision_queue, current_revision, shard) }?;
822
823        // SAFETY: The caller guarantees that this is a shard from `self`. Its LRU contains only
824        // entries produced by `LruEntry::ptr_from_value` for stable values allocated by this
825        // ingredient.
826        let value = unsafe { LruEntry::value_from_ptr::<C>(slot.entry) };
827
828        Some((slot, value))
829    }
830
831    /// Clears the given memo table.
832    ///
833    /// # Safety
834    ///
835    /// `memo_table` must belong to the value identified by `id` in this ingredient. The caller
836    /// must have exclusive access to the table.
837    pub(crate) unsafe fn clear_memos(&self, zalsa: &Zalsa, memo_table: &mut MemoTable, id: Id) {
838        /// Clears the given memo table without depending on `C`.
839        ///
840        /// # Safety
841        ///
842        /// `memo_table` must belong to the value identified by `id` in `ingredient_index` and must
843        /// have been created with `memo_table_types`. The caller must have exclusive access to the
844        /// table.
845        unsafe fn inner(
846            zalsa: &Zalsa,
847            ingredient_index: IngredientIndex,
848            memo_table_types: &MemoTableTypes,
849            memo_table: &mut MemoTable,
850            id: Id,
851        ) {
852            // SAFETY: The caller guarantees this is the correct types table.
853            let table = unsafe { memo_table_types.attach_memos_mut(memo_table) };
854
855            // `Database::salsa_event` is a user supplied callback which may panic
856            // in that case we need a drop guard to free the memo table
857            struct TableDropGuard<'a>(MemoTableWithTypesMut<'a>);
858
859            impl Drop for TableDropGuard<'_> {
860                fn drop(&mut self) {
861                    // SAFETY: We have `&mut MemoTable`, so no more references to these memos exist and we are good
862                    // to drop them.
863                    unsafe { self.0.drop() };
864                }
865            }
866
867            let mut table_guard = TableDropGuard(table);
868
869            // SAFETY: We have `&mut MemoTable`, so no more references to these memos exist and we are good
870            // to drop them.
871            unsafe {
872                table_guard.0.take_memos(|memo_ingredient_index, memo| {
873                    let ingredient_index =
874                        zalsa.ingredient_index_for_memo(ingredient_index, memo_ingredient_index);
875
876                    let executor = DatabaseKeyIndex::new(ingredient_index, id);
877
878                    zalsa.event(&|| Event::new(EventKind::DidDiscard { key: executor }));
879
880                    memo.remove_outputs(zalsa, executor);
881                })
882            };
883
884            std::mem::forget(table_guard);
885
886            // Reset the table after having dropped any memos.
887            memo_table.reset();
888        }
889
890        // SAFETY: The caller guarantees the table belongs to this ingredient's value, so these are
891        // the correct ingredient index and memo-table types.
892        unsafe {
893            inner(
894                zalsa,
895                self.ingredient_index,
896                &self.memo_table_types,
897                memo_table,
898                id,
899            )
900        }
901    }
902
903    // Hashes the value by its fields.
904    //
905    // # Safety
906    //
907    // The lock must be held for the shard containing the value.
908    unsafe fn value_hash(&self, value: &Value<C>) -> u64 {
909        // SAFETY: We hold the lock for the shard containing the value.
910        unsafe { self.hasher.hash_one(&*value.fields.get()) }
911    }
912
913    // Compares the value by its fields to the given key.
914    //
915    // # Safety
916    //
917    // The lock must be held for the shard containing the value.
918    unsafe fn value_eq<'db, Key>(value: &'db Value<C>, key: &Key) -> bool
919    where
920        C::Fields<'db>: HashEqLike<Key>,
921    {
922        // SAFETY: We hold the lock for the shard containing the value.
923        let fields = unsafe { &*value.fields.get() };
924
925        HashEqLike::eq(Self::from_internal_data(fields), key)
926    }
927
928    /// Returns the database key index for an interned value with the given id.
929    #[inline]
930    pub fn database_key_index(&self, id: Id) -> DatabaseKeyIndex {
931        DatabaseKeyIndex::new(self.ingredient_index, id)
932    }
933
934    /// Lookup the data for an interned value based on its ID.
935    #[inline]
936    pub fn data<'db>(&'db self, zalsa: &'db Zalsa, id: Id) -> &'db C::Fields<'db> {
937        let value = zalsa.table().get::<Value<C>>(id);
938        value.assert_validated(zalsa.current_revision());
939
940        debug_assert_eq!(
941            id,
942            // SAFETY: Validation prevents reuse, so the slot's ID cannot change while it is read.
943            unsafe { *value.lru.id.get() },
944            "Interned ID for `{}` refers to a reused slot",
945            C::DEBUG_NAME,
946        );
947
948        // SAFETY: Reusable interned values are only exposed if they have been validated
949        // in the current revision, as checked by the assertion above, which ensures that
950        // they are not reused while being accessed. Non-reusable values are never reused.
951        unsafe { Self::from_internal_data(&*value.fields.get()) }
952    }
953
954    /// Lookup the fields from an interned struct.
955    ///
956    /// Note that this is not "leaking" since no dependency edge is required.
957    #[inline]
958    pub fn fields<'db>(&'db self, zalsa: &'db Zalsa, s: C::Struct<'db>) -> &'db C::Fields<'db> {
959        self.data(zalsa, AsId::as_id(&s))
960    }
961
962    pub fn reset(&mut self, zalsa_mut: &mut Zalsa) {
963        _ = zalsa_mut;
964
965        for shard in self.shards.iter_mut() {
966            // We can clear the key maps now that we have cancelled all other handles.
967            shard.get_mut().key_map.clear();
968        }
969    }
970
971    /// Returns all data corresponding to the interned struct.
972    pub fn entries<'db>(&'db self, zalsa: &'db Zalsa) -> impl Iterator<Item = StructEntry<'db, C>> {
973        // SAFETY: `should_lock` is `true`
974        unsafe { self.entries_inner(true, zalsa) }
975    }
976
977    /// Returns all data corresponding to the interned struct.
978    ///
979    /// # Safety
980    ///
981    /// If `should_lock` is `false`, the caller must hold the locks for all shards
982    /// of the key map or ensure exclusive access to the database's storage while
983    /// consuming the iterator.
984    unsafe fn entries_inner<'db>(
985        &'db self,
986        should_lock: bool,
987        zalsa: &'db Zalsa,
988    ) -> impl Iterator<Item = StructEntry<'db, C>> {
989        // TODO: Grab all locks eagerly.
990        zalsa.table().slots_of::<Value<C>>().map(move |(_, value)| {
991            let id = if should_lock {
992                let _shard =
993                    // SAFETY: `value.shard` is guaranteed to be in-bounds for `self.shards`.
994                    unsafe { self.shards.get_unchecked(value.shard as usize) }.lock();
995
996                // Entries expose borrowed fields, so keep the slot alive for this revision.
997                // Preserve the maximum revision used by values interned outside queries.
998                // TODO: Ideally, enumeration would keep entries alive without marking them as
999                // interned in this revision, which can hide missing dependency validation.
1000                let last_interned_at = value.lru.last_interned_at.load();
1001                value
1002                    .lru
1003                    .last_interned_at
1004                    .store(last_interned_at.max(zalsa.current_revision()));
1005                // SAFETY: We hold the lock for the shard containing the value.
1006                unsafe { *value.lru.id.get() }
1007            } else {
1008                // SAFETY: The caller guarantees the shard is locked or the database's
1009                // storage is exclusively accessible, so the ID cannot be modified.
1010                unsafe { *value.lru.id.get() }
1011            };
1012
1013            StructEntry {
1014                value,
1015                key: self.database_key_index(id),
1016            }
1017        })
1018    }
1019}
1020
1021/// Creates the sharded storage outside of the generic [`IngredientImpl::new`] context.
1022///
1023/// Keeping this helper non-generic avoids monomorphizing the iterator machinery for every interned
1024/// struct configuration.
1025fn new_shards() -> Box<[CachePadded<Mutex<IngredientShard>>]> {
1026    let shard_count = (max_parallelism() * 4).next_power_of_two();
1027    (0..shard_count).map(|_| Default::default()).collect()
1028}
1029
1030/// A stable pointer to an interned value allocated in the database table.
1031#[repr(transparent)]
1032#[derive(Clone, Copy)]
1033struct ValueKey(NonNull<()>);
1034
1035impl ValueKey {
1036    fn new<C: Configuration>(value: &Value<C>) -> Self {
1037        Self(NonNull::from(value).cast())
1038    }
1039
1040    /// # Safety
1041    ///
1042    /// The database table containing this value must still be alive.
1043    unsafe fn value<'db, C: Configuration>(&self) -> &'db Value<C> {
1044        // SAFETY: Guaranteed by the caller. The erased pointer was created from a `Value<C>`.
1045        unsafe { &*self.0.as_ptr().cast::<Value<C>>() }
1046    }
1047}
1048
1049// SAFETY: Values remain allocated until after the ingredient and its key map are dropped.
1050// Access to their mutable state is synchronized by the corresponding shard lock.
1051unsafe impl Send for ValueKey {}
1052// SAFETY: See the `Send` implementation above.
1053unsafe impl Sync for ValueKey {}
1054
1055/// Inserts a value pointer while keeping the hasher and rehashing logic independent of `C`.
1056fn insert_unique_erased(
1057    shard: &mut IngredientShard,
1058    hash: u64,
1059    value: ValueKey,
1060    hasher: &dyn Fn(&ValueKey) -> u64,
1061) {
1062    shard.key_map.insert_unique(hash, value, hasher);
1063}
1064
1065/// An interned struct entry.
1066pub struct StructEntry<'db, C>
1067where
1068    C: Configuration,
1069{
1070    #[allow(dead_code)]
1071    value: &'db Value<C>,
1072    key: DatabaseKeyIndex,
1073}
1074
1075impl<'db, C> StructEntry<'db, C>
1076where
1077    C: Configuration,
1078{
1079    /// Returns the `DatabaseKeyIndex` for this entry.
1080    pub fn key(&self) -> DatabaseKeyIndex {
1081        self.key
1082    }
1083
1084    /// Returns the interned struct.
1085    pub fn as_struct(&self) -> C::Struct<'_> {
1086        FromId::from_id(self.key.key_index())
1087    }
1088
1089    #[cfg(feature = "salsa_unstable")]
1090    pub fn value(&self) -> &'db Value<C> {
1091        self.value
1092    }
1093}
1094
1095impl<C> Ingredient for IngredientImpl<C>
1096where
1097    C: Configuration,
1098{
1099    fn location(&self) -> &'static crate::ingredient::Location {
1100        &C::LOCATION
1101    }
1102
1103    fn ingredient_index(&self) -> IngredientIndex {
1104        self.ingredient_index
1105    }
1106
1107    unsafe fn maybe_changed_after(
1108        &self,
1109        zalsa: &crate::zalsa::Zalsa,
1110        _db: crate::database::RawDatabase<'_>,
1111        input: Id,
1112        _revision: Revision,
1113    ) -> VerifyResult {
1114        // Record the current revision as active.
1115        let current_revision = zalsa.current_revision();
1116        if C::REVISIONS != IMMORTAL {
1117            self.revision_queue.record(current_revision);
1118        }
1119
1120        let value = zalsa.table().get::<Value<C>>(input);
1121
1122        // SAFETY: `value.shard` is guaranteed to be in-bounds for `self.shards`.
1123        let _shard = unsafe { self.shards.get_unchecked(value.shard as usize) }.lock();
1124
1125        // SAFETY: We hold the lock for the shard containing the value.
1126        let id = unsafe { *value.lru.id.get() };
1127
1128        // The slot was reused.
1129        if id.generation() > input.generation() {
1130            return VerifyResult::changed();
1131        }
1132
1133        // Validate the value for the current revision to avoid reuse.
1134        value.lru.last_interned_at.store(current_revision);
1135
1136        zalsa.event(&|| {
1137            let index = self.database_key_index(input);
1138
1139            Event::new(EventKind::DidValidateInternedValue {
1140                key: index,
1141                revision: current_revision,
1142            })
1143        });
1144
1145        // Any change to an interned value results in a new ID generation.
1146        VerifyResult::unchanged()
1147    }
1148
1149    unsafe fn collect_minimum_serialized_edges(
1150        &self,
1151        _zalsa: &Zalsa,
1152        edge: QueryEdge,
1153        serialized_edges: &mut FxIndexSet<QueryEdge>,
1154        _visited_edges: &mut FxHashSet<QueryEdge>,
1155    ) {
1156        if C::PERSIST && C::REVISIONS != IMMORTAL {
1157            // If the interned struct is being persisted, it may be reachable through transitive queries.
1158            // Additionally, interned struct dependencies are impure in that garbage collection can
1159            // invalidate a dependency without a base input necessarily being updated. Thus, we must
1160            // preserve the transitive dependency on the interned struct, if garbage collection is
1161            // enabled.
1162            serialized_edges.insert(edge);
1163        }
1164
1165        // Otherwise, the dependency is covered by the base inputs.
1166    }
1167
1168    fn flatten_cycle_head_dependencies(
1169        &self,
1170        _zalsa: &Zalsa,
1171        id: Id,
1172        flattened_input_outputs: &mut FxIndexSet<QueryEdge>,
1173        _seen: &mut FxHashSet<DatabaseKeyIndex>,
1174    ) {
1175        flattened_input_outputs.insert(QueryEdge::input(self.database_key_index(id)));
1176    }
1177
1178    fn debug_name(&self) -> &'static str {
1179        C::DEBUG_NAME
1180    }
1181
1182    fn jar_kind(&self) -> JarKind {
1183        JarKind::Struct
1184    }
1185
1186    fn memo_table_types(&self) -> &Arc<MemoTableTypes> {
1187        &self.memo_table_types
1188    }
1189
1190    fn memo_table_types_mut(&mut self) -> &mut Arc<MemoTableTypes> {
1191        &mut self.memo_table_types
1192    }
1193
1194    /// Returns memory usage information about any interned values.
1195    #[cfg(all(not(feature = "shuttle"), feature = "salsa_unstable"))]
1196    unsafe fn memory_usage(
1197        &self,
1198        db: &dyn crate::Database,
1199    ) -> Option<Vec<crate::database::SlotInfo>> {
1200        // SAFETY: The caller guarantees exclusive access to the database's storage.
1201        let entries = unsafe { self.entries_inner(false, db.zalsa()) };
1202
1203        let memory_usage = entries
1204            // SAFETY: The memo table belongs to a value that we allocated, so it
1205            // has the correct type. The caller guarantees exclusive database access.
1206            .map(|entry| unsafe { entry.value.memory_usage(&self.memo_table_types) })
1207            .collect();
1208
1209        Some(memory_usage)
1210    }
1211
1212    fn is_persistable(&self) -> bool {
1213        C::PERSIST
1214    }
1215
1216    fn should_serialize(&self, zalsa: &Zalsa) -> bool {
1217        C::PERSIST && zalsa.table().slots_of::<Value<C>>().next().is_some()
1218    }
1219
1220    #[cfg(feature = "persistence")]
1221    unsafe fn serialize<'db>(
1222        &'db self,
1223        zalsa: &'db Zalsa,
1224        f: &mut dyn FnMut(&dyn erased_serde::Serialize),
1225    ) {
1226        f(&persistence::SerializeIngredient {
1227            zalsa,
1228            _ingredient: self,
1229        })
1230    }
1231
1232    #[cfg(feature = "persistence")]
1233    fn deserialize(
1234        &mut self,
1235        zalsa: &mut Zalsa,
1236        deserializer: &mut dyn erased_serde::Deserializer,
1237    ) -> Result<(), erased_serde::Error> {
1238        let deserialize = persistence::DeserializeIngredient {
1239            zalsa,
1240            ingredient: self,
1241        };
1242
1243        serde::de::DeserializeSeed::deserialize(deserialize, deserializer)
1244    }
1245}
1246
1247impl<C> std::fmt::Debug for IngredientImpl<C>
1248where
1249    C: Configuration,
1250{
1251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1252        f.debug_struct(std::any::type_name::<Self>())
1253            .field("index", &self.ingredient_index)
1254            .finish()
1255    }
1256}
1257
1258// SAFETY: `Value<C>` is our private type branded over the unique configuration `C`.
1259unsafe impl<C> Slot for Value<C>
1260where
1261    C: Configuration,
1262{
1263    #[inline(always)]
1264    unsafe fn memos(
1265        this: *const Self,
1266        current_revision: Revision,
1267    ) -> *const crate::table::memo::MemoTable {
1268        // SAFETY: The caller provides a valid slot pointer and its database's current revision.
1269        unsafe { (*this).assert_validated(current_revision) };
1270        // SAFETY: The assertion ensures the slot cannot be reused while its memos are borrowed.
1271        unsafe { Self::memos_unchecked(this) }
1272    }
1273
1274    #[inline(always)]
1275    unsafe fn memos_unchecked(this: *const Self) -> *const crate::table::memo::MemoTable {
1276        // SAFETY: The caller provides an initialized slot and prevents reuse.
1277        unsafe { (*this).memos.get() }
1278    }
1279
1280    #[inline(always)]
1281    fn memos_mut(&mut self) -> &mut crate::table::memo::MemoTable {
1282        self.memos.get_mut()
1283    }
1284}
1285
1286impl<C> Value<C>
1287where
1288    C: Configuration,
1289{
1290    /// Assert that this slot cannot be reused while its fields or memos are borrowed.
1291    #[inline]
1292    fn assert_validated(&self, current_revision: Revision) {
1293        // Either acquire load independently establishes that initialization and memo cleanup
1294        // finished: a current revision prevents reuse until the next revision, and a
1295        // non-reusable durability prevents reuse permanently. No atomic snapshot is needed.
1296        assert!(
1297            C::REVISIONS == IMMORTAL
1298                || self.lru.last_interned_at.load() >= current_revision
1299                || !is_reusable::<C>(self.durability.load()),
1300            "Data for reusable `{}` was not interned in the latest revision for its durability.",
1301            C::DEBUG_NAME,
1302        );
1303    }
1304}
1305
1306/// Keep track of revisions in which interned values were read, to determine staleness.
1307///
1308/// An interned value is considered stale if it has not been read in the past `REVS`
1309/// revisions. However, we only consider revisions in which interned values were actually
1310/// read, as revisions may be created in bursts.
1311struct RevisionQueue {
1312    lock: Mutex<()>,
1313    /// Recent revisions, stored inline for the default configuration.
1314    revisions: SmallVec<[AtomicRevision; DEFAULT_REVISIONS]>,
1315}
1316
1317// `#[salsa::interned(revisions = usize::MAX)]` disables garbage collection.
1318const IMMORTAL: NonZeroUsize = NonZeroUsize::MAX;
1319
1320impl RevisionQueue {
1321    fn new(capacity: NonZeroUsize) -> Self {
1322        let revisions = if capacity == IMMORTAL {
1323            SmallVec::new()
1324        } else {
1325            (0..capacity.get())
1326                .map(|_| AtomicRevision::start())
1327                .collect()
1328        };
1329
1330        Self {
1331            lock: Mutex::new(()),
1332            revisions,
1333        }
1334    }
1335
1336    /// Record the given revision as active.
1337    #[inline]
1338    fn record(&self, revision: Revision) {
1339        debug_assert!(
1340            !self.revisions.is_empty(),
1341            "cannot record revisions when interned garbage collection is disabled"
1342        );
1343
1344        // Fast-path: We already recorded this revision.
1345        if self.revisions[0].load() >= revision {
1346            return;
1347        }
1348
1349        self.record_cold(revision);
1350    }
1351
1352    #[cold]
1353    fn record_cold(&self, revision: Revision) {
1354        let _lock = self.lock.lock();
1355
1356        // Another thread may have recorded this revision while we waited for the lock.
1357        if self.revisions[0].load() >= revision {
1358            return;
1359        }
1360
1361        // Otherwise, update the queue, maintaining sorted order.
1362        //
1363        // Note that this should only happen once per revision.
1364        for i in (1..self.revisions.len()).rev() {
1365            self.revisions[i].store(self.revisions[i - 1].load());
1366        }
1367
1368        self.revisions[0].store(revision);
1369    }
1370
1371    /// Returns `true` if the given revision is old enough to be considered stale.
1372    #[inline]
1373    fn is_stale(&self, revision: Revision) -> bool {
1374        let Some(oldest) = self.revisions.last() else {
1375            return false;
1376        };
1377        let oldest = oldest.load();
1378
1379        // If we have not recorded `REVS` revisions yet, nothing can be stale.
1380        if oldest == Revision::start() {
1381            return false;
1382        }
1383
1384        revision < oldest
1385    }
1386
1387    /// Returns `true` if the configured number of revisions have been recorded as active,
1388    /// i.e. enough data has been recorded to start garbage collection.
1389    #[inline]
1390    fn is_primed(&self) -> bool {
1391        self.revisions
1392            .last()
1393            .is_some_and(|oldest| oldest.load() > Revision::start())
1394    }
1395}
1396
1397/// A trait for types that hash and compare like `O`.
1398pub trait HashEqLike<O> {
1399    fn eq(&self, data: &O) -> bool;
1400}
1401
1402/// The `Lookup` trait is a more flexible variant on [`std::borrow::Borrow`]
1403/// and [`std::borrow::ToOwned`].
1404///
1405/// It is implemented by "some type that can be used as the lookup key for `O`".
1406/// This means that `self` can be hashed and compared for equality with values
1407/// of type `O` without actually creating an owned value. It `self` needs to be interned,
1408/// it can be converted into an equivalent value of type `O`.
1409///
1410/// The canonical example is `&str: Lookup<String>`. However, this example
1411/// alone can be handled by [`std::borrow::Borrow`][]. In our case, we may have
1412/// multiple keys accumulated into a struct, like `ViewStruct: Lookup<(K1, ...)>`,
1413/// where `struct ViewStruct<L1: Lookup<K1>...>(K1...)`. The `Borrow` trait
1414/// requires that `&(K1...)` be convertible to `&ViewStruct` which just isn't
1415/// possible. `Lookup` instead offers direct `hash` and `eq` methods.
1416pub trait Lookup<O> {
1417    fn into_owned(self) -> O;
1418}
1419
1420impl<T> Lookup<T> for T {
1421    fn into_owned(self) -> T {
1422        self
1423    }
1424}
1425
1426impl<T> HashEqLike<T> for T
1427where
1428    T: Hash + Eq,
1429{
1430    fn eq(&self, data: &T) -> bool {
1431        self == data
1432    }
1433}
1434
1435impl<T> HashEqLike<T> for &T
1436where
1437    T: Hash + Eq,
1438{
1439    fn eq(&self, data: &T) -> bool {
1440        **self == *data
1441    }
1442}
1443
1444impl<T> HashEqLike<&T> for T
1445where
1446    T: Hash + Eq,
1447{
1448    fn eq(&self, data: &&T) -> bool {
1449        *self == **data
1450    }
1451}
1452
1453impl<T> Lookup<T> for &T
1454where
1455    T: Clone,
1456{
1457    fn into_owned(self) -> T {
1458        Clone::clone(self)
1459    }
1460}
1461
1462impl<'a, T> HashEqLike<&'a T> for Box<T>
1463where
1464    T: ?Sized + Hash + Eq,
1465    Box<T>: From<&'a T>,
1466{
1467    fn eq(&self, data: &&T) -> bool {
1468        **self == **data
1469    }
1470}
1471
1472impl<'a, T> Lookup<Box<T>> for &'a T
1473where
1474    T: ?Sized + Hash + Eq,
1475    Box<T>: From<&'a T>,
1476{
1477    fn into_owned(self) -> Box<T> {
1478        Box::from(self)
1479    }
1480}
1481
1482impl<'a, T> HashEqLike<&'a T> for Arc<T>
1483where
1484    T: ?Sized + Hash + Eq,
1485    Arc<T>: From<&'a T>,
1486{
1487    fn eq(&self, data: &&T) -> bool {
1488        **self == **data
1489    }
1490}
1491
1492impl<'a, T> Lookup<Arc<T>> for &'a T
1493where
1494    T: ?Sized + Hash + Eq,
1495    Arc<T>: From<&'a T>,
1496{
1497    fn into_owned(self) -> Arc<T> {
1498        Arc::from(self)
1499    }
1500}
1501
1502#[cfg(feature = "triomphe")]
1503impl<'a, T> HashEqLike<&'a T> for triomphe::Arc<T>
1504where
1505    T: ?Sized + Hash + Eq,
1506    triomphe::Arc<T>: From<&'a T>,
1507{
1508    fn eq(&self, data: &&T) -> bool {
1509        **self == **data
1510    }
1511}
1512
1513#[cfg(feature = "triomphe")]
1514impl<'a, T> Lookup<triomphe::Arc<T>> for &'a T
1515where
1516    T: ?Sized + Hash + Eq,
1517    triomphe::Arc<T>: From<&'a T>,
1518{
1519    fn into_owned(self) -> triomphe::Arc<T> {
1520        triomphe::Arc::from(self)
1521    }
1522}
1523
1524impl Lookup<String> for &str {
1525    fn into_owned(self) -> String {
1526        self.to_owned()
1527    }
1528}
1529
1530#[cfg(feature = "compact_str")]
1531impl Lookup<compact_str::CompactString> for &str {
1532    fn into_owned(self) -> compact_str::CompactString {
1533        compact_str::CompactString::new(self)
1534    }
1535}
1536
1537#[cfg(feature = "compact_str")]
1538impl HashEqLike<&str> for compact_str::CompactString {
1539    fn eq(&self, data: &&str) -> bool {
1540        self == *data
1541    }
1542}
1543
1544#[cfg(feature = "compact_str")]
1545impl HashEqLike<Cow<'_, str>> for compact_str::CompactString {
1546    fn eq(&self, data: &Cow<'_, str>) -> bool {
1547        self.as_str() == data.as_ref()
1548    }
1549}
1550
1551#[cfg(feature = "compact_str")]
1552impl Lookup<compact_str::CompactString> for Cow<'_, str> {
1553    fn into_owned(self) -> compact_str::CompactString {
1554        compact_str::CompactString::new(Cow::into_owned(self))
1555    }
1556}
1557
1558impl HashEqLike<&str> for String {
1559    fn eq(&self, data: &&str) -> bool {
1560        self == *data
1561    }
1562}
1563
1564impl<A, T: Hash + Eq + PartialEq<A>> HashEqLike<&[A]> for Vec<T> {
1565    fn eq(&self, data: &&[A]) -> bool {
1566        self.len() == data.len() && data.iter().enumerate().all(|(i, a)| &self[i] == a)
1567    }
1568}
1569
1570impl<A: Hash + Eq + PartialEq<T> + Clone + Lookup<T>, T> Lookup<Vec<T>> for &[A] {
1571    fn into_owned(self) -> Vec<T> {
1572        self.iter().map(|a| Lookup::into_owned(a.clone())).collect()
1573    }
1574}
1575
1576impl<const N: usize, A, T: Hash + Eq + PartialEq<A>> HashEqLike<[A; N]> for Vec<T> {
1577    fn eq(&self, data: &[A; N]) -> bool {
1578        self.len() == data.len() && data.iter().enumerate().all(|(i, a)| &self[i] == a)
1579    }
1580}
1581
1582impl<const N: usize, A: Hash + Eq + PartialEq<T> + Clone + Lookup<T>, T> Lookup<Vec<T>> for [A; N] {
1583    fn into_owned(self) -> Vec<T> {
1584        self.into_iter()
1585            .map(|a| Lookup::into_owned(a.clone()))
1586            .collect()
1587    }
1588}
1589
1590impl HashEqLike<&Path> for PathBuf {
1591    fn eq(&self, data: &&Path) -> bool {
1592        self == data
1593    }
1594}
1595
1596impl Lookup<PathBuf> for &Path {
1597    fn into_owned(self) -> PathBuf {
1598        self.to_owned()
1599    }
1600}
1601
1602impl<T: Hash + Eq + Clone> HashEqLike<Cow<'_, T>> for T {
1603    fn eq(&self, data: &Cow<'_, T>) -> bool {
1604        self == data.as_ref()
1605    }
1606}
1607
1608impl<T: Clone> Lookup<T> for Cow<'_, T> {
1609    fn into_owned(self) -> T {
1610        Cow::into_owned(self)
1611    }
1612}
1613
1614impl HashEqLike<Cow<'_, str>> for String {
1615    fn eq(&self, data: &Cow<'_, str>) -> bool {
1616        self.as_str() == data.as_ref()
1617    }
1618}
1619
1620impl Lookup<String> for Cow<'_, str> {
1621    fn into_owned(self) -> String {
1622        Cow::into_owned(self)
1623    }
1624}
1625
1626impl HashEqLike<Cow<'_, Path>> for PathBuf {
1627    fn eq(&self, data: &Cow<'_, Path>) -> bool {
1628        self.as_path() == data.as_ref()
1629    }
1630}
1631
1632impl Lookup<PathBuf> for Cow<'_, Path> {
1633    fn into_owned(self) -> PathBuf {
1634        Cow::into_owned(self)
1635    }
1636}
1637
1638impl<T: Hash + Eq + Clone> HashEqLike<Cow<'_, [T]>> for Box<[T]> {
1639    fn eq(&self, data: &Cow<'_, [T]>) -> bool {
1640        self.as_ref() == data.as_ref()
1641    }
1642}
1643
1644impl<T: Clone> Lookup<Box<[T]>> for Cow<'_, [T]> {
1645    fn into_owned(self) -> Box<[T]> {
1646        Cow::into_owned(self).into_boxed_slice()
1647    }
1648}
1649
1650impl<T: Hash + Eq + Clone> HashEqLike<Cow<'_, [T]>> for Vec<T> {
1651    fn eq(&self, data: &Cow<'_, [T]>) -> bool {
1652        self.as_slice() == data.as_ref()
1653    }
1654}
1655
1656impl<T: Clone> Lookup<Vec<T>> for Cow<'_, [T]> {
1657    fn into_owned(self) -> Vec<T> {
1658        Cow::into_owned(self)
1659    }
1660}
1661
1662#[cfg(feature = "persistence")]
1663mod persistence {
1664    use std::cell::UnsafeCell;
1665    use std::fmt;
1666    use std::hash::BuildHasher;
1667
1668    use intrusive_collections::LinkedListLink;
1669    use serde::ser::{SerializeMap, SerializeStruct};
1670    use serde::{Deserialize, de};
1671
1672    use super::{AtomicDurability, AtomicRevision, Configuration, IngredientImpl, LruEntry, Value};
1673    use crate::plumbing::Ingredient;
1674    use crate::table::memo::MemoTable;
1675    use crate::zalsa::Zalsa;
1676    use crate::{Durability, Id, Revision};
1677
1678    pub struct SerializeIngredient<'db, C>
1679    where
1680        C: Configuration,
1681    {
1682        pub zalsa: &'db Zalsa,
1683        pub _ingredient: &'db IngredientImpl<C>,
1684    }
1685
1686    impl<C> serde::Serialize for SerializeIngredient<'_, C>
1687    where
1688        C: Configuration,
1689    {
1690        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1691        where
1692            S: serde::Serializer,
1693        {
1694            let Self { zalsa, .. } = *self;
1695
1696            // Counting slots does not access shard metadata or interned fields. The exclusive
1697            // storage access acquired by `SerializeDatabase::new` keeps the count stable.
1698            let count = zalsa.table().slots_of::<Value<C>>().count();
1699            let mut map = serializer.serialize_map(Some(count))?;
1700
1701            for (_, value) in zalsa.table().slots_of::<Value<C>>() {
1702                // SAFETY: The safety invariant of `Ingredient::serialize` ensures we have exclusive access
1703                // to the database.
1704                let id = unsafe { *value.lru.id.get() };
1705
1706                map.serialize_entry(&id.as_bits(), value)?;
1707            }
1708
1709            map.end()
1710        }
1711    }
1712
1713    impl<C> serde::Serialize for Value<C>
1714    where
1715        C: Configuration,
1716    {
1717        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1718        where
1719            S: serde::Serializer,
1720        {
1721            let mut value = serializer.serialize_struct("Value,", 3)?;
1722
1723            let Value {
1724                fields,
1725                lru,
1726                durability,
1727                shard: _,
1728                memos: _,
1729            } = self;
1730            let LruEntry {
1731                link: _,
1732                id: _,
1733                last_interned_at,
1734            } = lru;
1735
1736            // SAFETY: The safety invariant of `Ingredient::serialize` ensures we have exclusive access
1737            // to the database.
1738            let fields = unsafe { &*fields.get() };
1739
1740            let durability = durability.load();
1741            let last_interned_at = last_interned_at.load();
1742
1743            value.serialize_field("durability", &durability)?;
1744            value.serialize_field("last_interned_at", &last_interned_at)?;
1745            value.serialize_field("fields", &SerializeFields::<C>(fields))?;
1746
1747            value.end()
1748        }
1749    }
1750
1751    struct SerializeFields<'db, C: Configuration>(&'db C::Fields<'static>);
1752
1753    impl<C> serde::Serialize for SerializeFields<'_, C>
1754    where
1755        C: Configuration,
1756    {
1757        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1758        where
1759            S: serde::Serializer,
1760        {
1761            C::serialize(IngredientImpl::<C>::from_internal_data(self.0), serializer)
1762        }
1763    }
1764
1765    pub struct DeserializeIngredient<'db, C>
1766    where
1767        C: Configuration,
1768    {
1769        pub zalsa: &'db mut Zalsa,
1770        pub ingredient: &'db mut IngredientImpl<C>,
1771    }
1772
1773    impl<'de, C> de::DeserializeSeed<'de> for DeserializeIngredient<'_, C>
1774    where
1775        C: Configuration,
1776    {
1777        type Value = ();
1778
1779        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1780        where
1781            D: serde::Deserializer<'de>,
1782        {
1783            deserializer.deserialize_map(self)
1784        }
1785    }
1786
1787    impl<'de, C> de::Visitor<'de> for DeserializeIngredient<'_, C>
1788    where
1789        C: Configuration,
1790    {
1791        type Value = ();
1792
1793        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1794            formatter.write_str("a map")
1795        }
1796
1797        fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
1798        where
1799            M: de::MapAccess<'de>,
1800        {
1801            let DeserializeIngredient { zalsa, ingredient } = self;
1802
1803            while let Some((id, value)) = access.next_entry::<u64, DeserializeValue<C>>()? {
1804                let id = Id::from_bits(id);
1805                let (page_idx, _) = crate::table::split_id(id);
1806
1807                // Determine the value shard.
1808                let hash = ingredient.hasher.hash_one(&value.fields.0);
1809                let shard_index = ingredient.shard(hash);
1810
1811                // SAFETY: `shard_index` is guaranteed to be in-bounds for `self.shards`.
1812                let shard = unsafe { &mut *ingredient.shards.get_unchecked(shard_index).lock() };
1813
1814                let value = Value::<C> {
1815                    shard: shard_index as u16,
1816                    lru: LruEntry {
1817                        link: LinkedListLink::new(),
1818                        id: UnsafeCell::new(id),
1819                        last_interned_at: AtomicRevision::new(value.last_interned_at),
1820                    },
1821                    fields: UnsafeCell::new(value.fields.0),
1822                    // SAFETY: We only ever access the memos of a value that we allocated through
1823                    // our `MemoTableTypes`.
1824                    memos: UnsafeCell::new(unsafe {
1825                        MemoTable::new(ingredient.memo_table_types())
1826                    }),
1827                    durability: AtomicDurability::new(value.durability),
1828                };
1829
1830                // Force initialize the relevant page.
1831                zalsa.table_mut().force_page::<Value<C>>(
1832                    page_idx,
1833                    ingredient.ingredient_index(),
1834                    ingredient.memo_table_types(),
1835                );
1836
1837                // Initialize the slot.
1838                //
1839                // SAFETY: We have a mutable reference to the database.
1840                let (allocated_id, value) = unsafe {
1841                    zalsa
1842                        .table()
1843                        .page(page_idx)
1844                        .allocate(page_idx, |_| value)
1845                        .unwrap_or_else(|_| panic!("serialized an invalid `Id`: {id:?}"))
1846                };
1847
1848                assert_eq!(
1849                    allocated_id.index(),
1850                    id.index(),
1851                    "values are serialized in allocation order"
1852                );
1853
1854                // Insert the newly allocated value into our ingredient.
1855                //
1856                // SAFETY: We hold this ingredient's shard lock, and `value` is the live, stable
1857                // value that we just allocated in that shard.
1858                unsafe { ingredient.insert_value(shard, hash, value) };
1859            }
1860
1861            Ok(())
1862        }
1863    }
1864
1865    #[derive(Deserialize)]
1866    #[serde(rename = "Value")]
1867    pub struct DeserializeValue<C: Configuration> {
1868        durability: Durability,
1869        last_interned_at: Revision,
1870        #[serde(bound = "C: Configuration")]
1871        fields: DeserializeFields<C>,
1872    }
1873
1874    struct DeserializeFields<C: Configuration>(C::Fields<'static>);
1875
1876    impl<'de, C> serde::Deserialize<'de> for DeserializeFields<C>
1877    where
1878        C: Configuration,
1879    {
1880        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1881        where
1882            D: serde::Deserializer<'de>,
1883        {
1884            C::deserialize(deserializer)
1885                .map(DeserializeFields)
1886                .map_err(de::Error::custom)
1887        }
1888    }
1889}
1890
1891#[cfg(all(not(feature = "shuttle"), target_pointer_width = "64"))]
1892mod _static_assertions {
1893    use std::mem;
1894
1895    use super::LruEntry;
1896    use super::{Configuration, Value};
1897    use crate::{Id, plumbing};
1898
1899    const _: [(); mem::size_of::<LruEntry>()] = [(); mem::size_of::<[usize; 4]>()];
1900
1901    const _: [(); mem::size_of::<Value<DummyConfiguration>>()] = [(); mem::size_of::<[usize; 7]>()];
1902
1903    struct DummyConfiguration;
1904
1905    // SAFETY: The fields are `[u8; 1]` for every database lifetime.
1906    unsafe impl Configuration for DummyConfiguration {
1907        const LOCATION: crate::ingredient::Location =
1908            crate::ingredient::Location { file: "", line: 0 };
1909        const DEBUG_NAME: &'static str = "";
1910        const PERSIST: bool = false;
1911
1912        type Fields<'db> = [u8; 1];
1913        type Struct<'db> = Id;
1914
1915        fn serialize<S>(_: &Self::Fields<'_>, _: S) -> Result<S::Ok, S::Error>
1916        where
1917            S: plumbing::serde::Serializer,
1918        {
1919            unimplemented!()
1920        }
1921
1922        fn deserialize<'de, D>(_: D) -> Result<Self::Fields<'static>, D::Error>
1923        where
1924            D: plumbing::serde::Deserializer<'de>,
1925        {
1926            unimplemented!()
1927        }
1928    }
1929}
1930
1931#[cfg(test)]
1932mod tests {
1933    use super::*;
1934
1935    struct TestConfiguration;
1936
1937    // SAFETY: The fields are `()` for every database lifetime.
1938    unsafe impl Configuration for TestConfiguration {
1939        const LOCATION: crate::ingredient::Location = crate::ingredient::Location {
1940            file: file!(),
1941            line: line!(),
1942        };
1943        const DEBUG_NAME: &'static str = "TestConfiguration";
1944        const PERSIST: bool = false;
1945        const REVISIONS: NonZeroUsize = NonZeroUsize::new(2).unwrap();
1946
1947        type Fields<'db> = ();
1948        type Struct<'db> = Id;
1949
1950        fn serialize<S>(_value: &Self::Fields<'_>, _serializer: S) -> Result<S::Ok, S::Error>
1951        where
1952            S: plumbing::serde::Serializer,
1953        {
1954            unimplemented!()
1955        }
1956
1957        fn deserialize<'de, D>(_deserializer: D) -> Result<Self::Fields<'static>, D::Error>
1958        where
1959            D: plumbing::serde::Deserializer<'de>,
1960        {
1961            unimplemented!()
1962        }
1963    }
1964
1965    #[test]
1966    fn revision_queue_records_each_revision_once() {
1967        let queue = RevisionQueue::new(TestConfiguration::REVISIONS);
1968        let revision = Revision::start().next();
1969
1970        // Simulate two threads that both passed the fast-path check before taking the lock.
1971        queue.record_cold(revision);
1972        queue.record_cold(revision);
1973
1974        assert_eq!(queue.revisions[0].load(), revision);
1975        assert_eq!(queue.revisions[1].load(), Revision::start());
1976    }
1977}