Skip to main content

sui_core/execution_cache/
writeback_cache.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MemoryCache is a cache for the transaction execution which delays writes to the database until
5//! transaction results are certified (i.e. they appear in a certified checkpoint, or an effects cert
6//! is observed by a fullnode). The cache also stores committed data in memory in order to serve
7//! future reads without hitting the database.
8//!
9//! For storing uncommitted transaction outputs, we cannot evict the data at all until it is written
10//! to disk. Committed data not only can be evicted, but it is also unbounded (imagine a stream of
11//! transactions that keep splitting a coin into smaller coins).
12//!
13//! We also want to be able to support negative cache hits (i.e. the case where we can determine an
14//! object does not exist without hitting the database).
15//!
16//! To achieve both of these goals, we split the cache data into two pieces, a dirty set and a cached
17//! set. The dirty set has no automatic evictions, data is only removed after being committed. The
18//! cached set is in a bounded-sized cache with automatic evictions. In order to support negative
19//! cache hits, we treat the two halves of the cache as FIFO queue. Newly written (dirty) versions are
20//! inserted to one end of the dirty queue. As versions are committed to disk, they are
21//! removed from the other end of the dirty queue and inserted into the cache queue. The cache queue
22//! is truncated if it exceeds its maximum size, by removing all but the N newest versions.
23//!
24//! This gives us the property that the sequence of versions in the dirty and cached queues are the
25//! most recent versions of the object, i.e. there can be no "gaps". This allows for the following:
26//!
27//!   - Negative cache hits: If the queried version is not in memory, but is higher than the smallest
28//!     version in the cached queue, it does not exist in the db either.
29//!   - Bounded reads: When reading the most recent version that is <= some version bound, we can
30//!     correctly satisfy this query from the cache, or determine that we must go to the db.
31//!
32//! Note that at any time, either or both the dirty or the cached queue may be non-existent. There may be no
33//! dirty versions of the objects, in which case there will be no dirty queue. And, the cached queue
34//! may be evicted from the cache, in which case there will be no cached queue. Because only the cached
35//! queue can be evicted (the dirty queue can only become empty by moving versions from it to the cached
36//! queue), the "highest versions" property still holds in all cases.
37//!
38//! The above design is used for both objects and markers.
39
40use crate::accumulators::funds_read::AccountFundsRead;
41use crate::authority::AuthorityStore;
42use crate::authority::authority_per_epoch_store::AuthorityPerEpochStore;
43use crate::authority::authority_store::ExecutionLockWriteGuard;
44#[cfg(test)]
45use crate::authority::authority_store::{LockDetailsDeprecated, ObjectLockStatus, SuiLockResult};
46use crate::authority::authority_store_tables::LiveObject;
47use crate::authority::backpressure::BackpressureManager;
48use crate::authority::epoch_start_configuration::{EpochFlag, EpochStartConfiguration};
49use crate::fallback_fetch::do_fallback_lookup;
50use crate::global_state_hasher::GlobalStateHashStore;
51use crate::transaction_outputs::TransactionOutputs;
52
53use dashmap::DashMap;
54use dashmap::mapref::entry::Entry as DashMapEntry;
55use futures::{FutureExt, future::BoxFuture};
56use moka::sync::SegmentedCache as MokaCache;
57use mysten_common::ZipDebugEqIteratorExt;
58use mysten_common::debug_fatal;
59use mysten_common::random_util::randomize_cache_capacity_in_tests;
60use mysten_common::sync::notify_read::NotifyRead;
61use parking_lot::Mutex;
62use rayon::prelude::*;
63use std::collections::{BTreeMap, HashSet};
64use std::hash::Hash;
65use std::sync::Arc;
66use std::sync::atomic::AtomicU64;
67use std::time::Instant;
68use sui_config::ExecutionCacheConfig;
69use sui_macros::fail_point;
70use sui_protocol_config::ProtocolVersion;
71use sui_types::SUI_ACCUMULATOR_ROOT_OBJECT_ID;
72use sui_types::accumulator_event::AccumulatorEvent;
73use sui_types::accumulator_root::{AccumulatorObjId, AccumulatorValue};
74use sui_types::base_types::{
75    ConsensusObjectVersion, EpochId, FullObjectID, ObjectID, ObjectRef, SequenceNumber,
76    VerifiedExecutionData,
77};
78use sui_types::bridge::{Bridge, get_bridge};
79use sui_types::digests::{ObjectDigest, TransactionDigest, TransactionEffectsDigest};
80use sui_types::effects::{TransactionEffects, TransactionEvents};
81#[cfg(test)]
82use sui_types::error::SuiError;
83use sui_types::error::{SuiErrorKind, SuiResult, UserInputError};
84use sui_types::executable_transaction::VerifiedExecutableTransaction;
85use sui_types::global_state_hash::GlobalStateHash;
86use sui_types::message_envelope::Message;
87use sui_types::messages_checkpoint::CheckpointSequenceNumber;
88use sui_types::object::Object;
89use sui_types::storage::{
90    FullObjectKey, InputKey, MarkerValue, ObjectKey, ObjectOrTombstone, ObjectStore, PackageObject,
91};
92use sui_types::sui_system_state::{SuiSystemState, get_sui_system_state};
93use sui_types::transaction::{TransactionDataAPI, VerifiedTransaction};
94use tap::TapOptional;
95use tracing::{debug, info, instrument, trace, warn};
96
97use super::ExecutionCacheAPI;
98use super::FoundObjectOrTombstone;
99use super::cache_types::Ticket;
100use super::{
101    Batch, CheckpointCache, ExecutionCacheCommit, ExecutionCacheMetrics, ExecutionCacheReconfigAPI,
102    ExecutionCacheWrite, ObjectCacheRead, StateSyncAPI, TestingAPI, TransactionCacheRead,
103    cache_types::{CacheResult, CachedVersionMap, IsNewer, MonotonicCache},
104    implement_passthrough_traits,
105    object_locks::ObjectLocks,
106};
107
108#[cfg(test)]
109#[path = "unit_tests/writeback_cache_tests.rs"]
110pub mod writeback_cache_tests;
111
112#[cfg(test)]
113#[path = "unit_tests/notify_read_input_objects_tests.rs"]
114mod notify_read_input_objects_tests;
115
116#[derive(Clone, PartialEq, Eq)]
117enum ObjectEntry {
118    Object(Object),
119    Deleted,
120    Wrapped,
121}
122
123impl ObjectEntry {
124    #[cfg(test)]
125    fn unwrap_object(&self) -> &Object {
126        match self {
127            ObjectEntry::Object(o) => o,
128            _ => panic!("unwrap_object called on non-Object"),
129        }
130    }
131
132    fn is_tombstone(&self) -> bool {
133        match self {
134            ObjectEntry::Deleted | ObjectEntry::Wrapped => true,
135            ObjectEntry::Object(_) => false,
136        }
137    }
138
139    /// This entry as the entry of `object_id` at `version`: the object, or the tombstone of the
140    /// deletion or wrap at `version`.
141    fn into_object_or_tombstone(
142        self,
143        object_id: ObjectID,
144        version: SequenceNumber,
145    ) -> ObjectOrTombstone {
146        match self {
147            ObjectEntry::Object(object) => ObjectOrTombstone::Object(object),
148            ObjectEntry::Deleted => ObjectOrTombstone::Tombstone((
149                object_id,
150                version,
151                ObjectDigest::OBJECT_DIGEST_DELETED,
152            )),
153            ObjectEntry::Wrapped => ObjectOrTombstone::Tombstone((
154                object_id,
155                version,
156                ObjectDigest::OBJECT_DIGEST_WRAPPED,
157            )),
158        }
159    }
160}
161
162impl std::fmt::Debug for ObjectEntry {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        match self {
165            ObjectEntry::Object(o) => {
166                write!(f, "ObjectEntry::Object({:?})", o.compute_object_reference())
167            }
168            ObjectEntry::Deleted => write!(f, "ObjectEntry::Deleted"),
169            ObjectEntry::Wrapped => write!(f, "ObjectEntry::Wrapped"),
170        }
171    }
172}
173
174impl From<Object> for ObjectEntry {
175    fn from(object: Object) -> Self {
176        ObjectEntry::Object(object)
177    }
178}
179
180impl From<ObjectOrTombstone> for ObjectEntry {
181    fn from(object: ObjectOrTombstone) -> Self {
182        match object {
183            ObjectOrTombstone::Object(o) => o.into(),
184            ObjectOrTombstone::Tombstone(obj_ref) => {
185                if obj_ref.2.is_deleted() {
186                    ObjectEntry::Deleted
187                } else if obj_ref.2.is_wrapped() {
188                    ObjectEntry::Wrapped
189                } else {
190                    panic!("tombstone digest must either be deleted or wrapped");
191                }
192            }
193        }
194    }
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198enum LatestObjectCacheEntry {
199    Object(SequenceNumber, ObjectEntry),
200    NonExistent,
201}
202
203impl LatestObjectCacheEntry {
204    #[cfg(test)]
205    fn version(&self) -> Option<SequenceNumber> {
206        match self {
207            LatestObjectCacheEntry::Object(version, _) => Some(*version),
208            LatestObjectCacheEntry::NonExistent => None,
209        }
210    }
211
212    fn is_alive(&self) -> bool {
213        match self {
214            LatestObjectCacheEntry::Object(_, entry) => !entry.is_tombstone(),
215            LatestObjectCacheEntry::NonExistent => false,
216        }
217    }
218}
219
220impl IsNewer for LatestObjectCacheEntry {
221    fn is_newer_than(&self, other: &LatestObjectCacheEntry) -> bool {
222        match (self, other) {
223            (LatestObjectCacheEntry::Object(v1, _), LatestObjectCacheEntry::Object(v2, _)) => {
224                v1 > v2
225            }
226            (LatestObjectCacheEntry::Object(_, _), LatestObjectCacheEntry::NonExistent) => true,
227            _ => false,
228        }
229    }
230}
231
232type MarkerKey = (EpochId, FullObjectID);
233
234/// UncommittedData stores execution outputs that are not yet written to the db. Entries in this
235/// struct can only be purged after they are committed.
236struct UncommittedData {
237    /// The object dirty set. All writes go into this table first. After we flush the data to the
238    /// db, the data is removed from this table and inserted into the object_cache.
239    ///
240    /// This table may contain both live and dead objects, since we flush both live and dead
241    /// objects to the db in order to support past object queries on fullnodes.
242    ///
243    /// Further, we only remove objects in FIFO order, which ensures that the cached
244    /// sequence of objects has no gaps. In other words, if we have versions 4, 8, 13 of
245    /// an object, we can deduce that version 9 does not exist. This also makes child object
246    /// reads efficient. `object_cache` cannot contain a more recent version of an object than
247    /// `objects`, and neither can have any gaps. Therefore if there is any object <= the version
248    /// bound for a child read in objects, it is the correct object to return.
249    objects: DashMap<ObjectID, CachedVersionMap<ObjectEntry>>,
250
251    // Markers for received objects and deleted shared objects. This contains all of the dirty
252    // marker state, which is committed to the db at the same time as other transaction data.
253    // After markers are committed to the db we remove them from this table and insert them into
254    // marker_cache.
255    markers: DashMap<MarkerKey, CachedVersionMap<MarkerValue>>,
256
257    transaction_effects: DashMap<TransactionEffectsDigest, TransactionEffects>,
258
259    transaction_events: DashMap<TransactionDigest, TransactionEvents>,
260
261    unchanged_loaded_runtime_objects: DashMap<TransactionDigest, Vec<ObjectKey>>,
262
263    executed_effects_digests: DashMap<TransactionDigest, TransactionEffectsDigest>,
264
265    // Transaction outputs that have not yet been written to the DB. Items are removed from this
266    // table as they are flushed to the db.
267    pending_transaction_writes: DashMap<TransactionDigest, Arc<TransactionOutputs>>,
268
269    total_transaction_inserts: AtomicU64,
270    total_transaction_commits: AtomicU64,
271}
272
273impl UncommittedData {
274    fn new() -> Self {
275        Self {
276            objects: DashMap::with_shard_amount(2048),
277            markers: DashMap::with_shard_amount(2048),
278            transaction_effects: DashMap::with_shard_amount(2048),
279            executed_effects_digests: DashMap::with_shard_amount(2048),
280            pending_transaction_writes: DashMap::with_shard_amount(2048),
281            transaction_events: DashMap::with_shard_amount(2048),
282            unchanged_loaded_runtime_objects: DashMap::with_shard_amount(2048),
283            total_transaction_inserts: AtomicU64::new(0),
284            total_transaction_commits: AtomicU64::new(0),
285        }
286    }
287
288    fn clear(&self) {
289        self.objects.clear();
290        self.markers.clear();
291        self.transaction_effects.clear();
292        self.executed_effects_digests.clear();
293        self.pending_transaction_writes.clear();
294        self.transaction_events.clear();
295        self.unchanged_loaded_runtime_objects.clear();
296        self.total_transaction_inserts
297            .store(0, std::sync::atomic::Ordering::Relaxed);
298        self.total_transaction_commits
299            .store(0, std::sync::atomic::Ordering::Relaxed);
300    }
301
302    fn is_empty(&self) -> bool {
303        let empty = self.pending_transaction_writes.is_empty();
304        if empty && cfg!(debug_assertions) {
305            assert!(
306                self.objects.is_empty()
307                    && self.markers.is_empty()
308                    && self.transaction_effects.is_empty()
309                    && self.executed_effects_digests.is_empty()
310                    && self.transaction_events.is_empty()
311                    && self.unchanged_loaded_runtime_objects.is_empty()
312                    && self
313                        .total_transaction_inserts
314                        .load(std::sync::atomic::Ordering::Relaxed)
315                        == self
316                            .total_transaction_commits
317                            .load(std::sync::atomic::Ordering::Relaxed),
318            );
319        }
320        empty
321    }
322}
323
324// Point items (anything without a version number) can be negatively cached as None
325type PointCacheItem<T> = Option<T>;
326
327// PointCacheItem can only be used for insert-only collections, so a Some entry
328// is always newer than a None entry.
329impl<T: Eq + std::fmt::Debug> IsNewer for PointCacheItem<T> {
330    fn is_newer_than(&self, other: &PointCacheItem<T>) -> bool {
331        match (self, other) {
332            (Some(_), None) => true,
333
334            (Some(a), Some(b)) => {
335                // conflicting inserts should never happen
336                debug_assert_eq!(a, b);
337                false
338            }
339
340            _ => false,
341        }
342    }
343}
344
345/// CachedData stores data that has been committed to the db, but is likely to be read soon.
346struct CachedCommittedData {
347    // See module level comment for an explanation of caching strategy.
348    object_cache: MokaCache<ObjectID, Arc<Mutex<CachedVersionMap<ObjectEntry>>>>,
349
350    // See module level comment for an explanation of caching strategy.
351    marker_cache: MokaCache<MarkerKey, Arc<Mutex<CachedVersionMap<MarkerValue>>>>,
352
353    transactions: MonotonicCache<TransactionDigest, PointCacheItem<Arc<VerifiedTransaction>>>,
354
355    transaction_effects:
356        MonotonicCache<TransactionEffectsDigest, PointCacheItem<Arc<TransactionEffects>>>,
357
358    transaction_events: MonotonicCache<TransactionDigest, PointCacheItem<Arc<TransactionEvents>>>,
359
360    executed_effects_digests:
361        MonotonicCache<TransactionDigest, PointCacheItem<TransactionEffectsDigest>>,
362
363    transaction_executed_in_last_epoch:
364        MonotonicCache<(EpochId, TransactionDigest), PointCacheItem<()>>,
365
366    // Objects that were read at transaction signing time - allows us to access them again at
367    // execution time with a single lock / hash lookup
368    _transaction_objects: MokaCache<TransactionDigest, Vec<Object>>,
369}
370
371impl CachedCommittedData {
372    fn new(config: &ExecutionCacheConfig) -> Self {
373        let object_cache = MokaCache::builder(8)
374            .max_capacity(randomize_cache_capacity_in_tests(
375                config.object_cache_size(),
376            ))
377            .build();
378        let marker_cache = MokaCache::builder(8)
379            .max_capacity(randomize_cache_capacity_in_tests(
380                config.marker_cache_size(),
381            ))
382            .build();
383
384        let transactions = MonotonicCache::new(randomize_cache_capacity_in_tests(
385            config.transaction_cache_size(),
386        ));
387        let transaction_effects = MonotonicCache::new(randomize_cache_capacity_in_tests(
388            config.effect_cache_size(),
389        ));
390        let transaction_events = MonotonicCache::new(randomize_cache_capacity_in_tests(
391            config.events_cache_size(),
392        ));
393        let executed_effects_digests = MonotonicCache::new(randomize_cache_capacity_in_tests(
394            config.executed_effect_cache_size(),
395        ));
396
397        let transaction_objects = MokaCache::builder(8)
398            .max_capacity(randomize_cache_capacity_in_tests(
399                config.transaction_objects_cache_size(),
400            ))
401            .build();
402
403        let transaction_executed_in_last_epoch = MonotonicCache::new(
404            randomize_cache_capacity_in_tests(config.executed_effect_cache_size()),
405        );
406
407        Self {
408            object_cache,
409            marker_cache,
410            transactions,
411            transaction_effects,
412            transaction_events,
413            executed_effects_digests,
414            transaction_executed_in_last_epoch,
415            _transaction_objects: transaction_objects,
416        }
417    }
418
419    fn clear_and_assert_empty(&self) {
420        self.object_cache.invalidate_all();
421        self.marker_cache.invalidate_all();
422        self.transactions.invalidate_all();
423        self.transaction_effects.invalidate_all();
424        self.transaction_events.invalidate_all();
425        self.executed_effects_digests.invalidate_all();
426        self.transaction_executed_in_last_epoch.invalidate_all();
427        self._transaction_objects.invalidate_all();
428
429        assert_empty(&self.object_cache);
430        assert_empty(&self.marker_cache);
431        assert!(self.transactions.is_empty());
432        assert!(self.transaction_effects.is_empty());
433        assert!(self.transaction_events.is_empty());
434        assert!(self.executed_effects_digests.is_empty());
435        assert!(self.transaction_executed_in_last_epoch.is_empty());
436        assert_empty(&self._transaction_objects);
437    }
438}
439
440fn assert_empty<K, V>(cache: &MokaCache<K, V>)
441where
442    K: std::hash::Hash + std::cmp::Eq + std::cmp::PartialEq + Send + Sync + 'static,
443    V: std::clone::Clone + std::marker::Send + std::marker::Sync + 'static,
444{
445    if cache.iter().next().is_some() {
446        panic!("cache should be empty");
447    }
448}
449
450pub struct WritebackCache {
451    dirty: UncommittedData,
452    cached: CachedCommittedData,
453
454    // We separately cache the latest version of each object. Although this seems
455    // redundant, it is the only way to support populating the cache after a read.
456    // We cannot simply insert objects that we read off the disk into `object_cache`,
457    // since that may violate the no-missing-versions property.
458    // `object_by_id_cache` is also written to on writes so that it is always coherent.
459    // Hence it contains both committed and dirty object data.
460    object_by_id_cache: MonotonicCache<ObjectID, LatestObjectCacheEntry>,
461
462    // The packages cache is treated separately from objects, because they are immutable and can be
463    // used by any number of transactions. Additionally, many operations require loading large
464    // numbers of packages (due to dependencies), so we want to try to keep all packages in memory.
465    //
466    // Also, this cache can contain packages that are dirty or committed, so it does not live in
467    // UncachedData or CachedCommittedData. The cache is populated in two ways:
468    // - when packages are written (in which case they will also be present in the dirty set)
469    // - after a cache miss. Because package IDs are unique (only one version exists for each ID)
470    //   we do not need to worry about the contiguous version property.
471    // - note that we removed any unfinalized packages from the cache during revert_state_update().
472    packages: MokaCache<ObjectID, PackageObject>,
473
474    object_locks: ObjectLocks,
475
476    executed_effects_digests_notify_read: NotifyRead<TransactionDigest, TransactionEffectsDigest>,
477    object_notify_read: NotifyRead<InputKey, ()>,
478
479    store: Arc<AuthorityStore>,
480    backpressure_threshold: u64,
481    backpressure_manager: Arc<BackpressureManager>,
482    metrics: Arc<ExecutionCacheMetrics>,
483}
484
485macro_rules! check_cache_entry_by_version {
486    ($self: ident, $table: expr, $level: expr, $cache: expr, $version: expr) => {
487        $self.metrics.record_cache_request($table, $level);
488        if let Some(cache) = $cache {
489            if let Some(entry) = cache.get(&$version) {
490                $self.metrics.record_cache_hit($table, $level);
491                return CacheResult::Hit(entry.clone());
492            }
493
494            if let Some(least_version) = cache.get_least() {
495                if least_version.0 < $version {
496                    // If the version is greater than the least version in the cache, then we know
497                    // that the object does not exist anywhere
498                    $self.metrics.record_cache_negative_hit($table, $level);
499                    return CacheResult::NegativeHit;
500                }
501            }
502        }
503        $self.metrics.record_cache_miss($table, $level);
504    };
505}
506
507macro_rules! check_cache_entry_by_latest {
508    ($self: ident, $table: expr, $level: expr, $cache: expr) => {
509        $self.metrics.record_cache_request($table, $level);
510        if let Some(cache) = $cache {
511            if let Some((version, entry)) = cache.get_highest() {
512                $self.metrics.record_cache_hit($table, $level);
513                return CacheResult::Hit((*version, entry.clone()));
514            } else {
515                panic!("empty CachedVersionMap should have been removed");
516            }
517        }
518        $self.metrics.record_cache_miss($table, $level);
519    };
520}
521
522impl WritebackCache {
523    /// Load an implicitly read system object at the requested version.
524    /// In normal execution, this function can block wait until the object is available at the requested version,
525    /// and it is guaranteed to return an object with the requested version.
526    /// In dry-runs, this function will never block wait, but may return None if the requested version was pruned by this point.
527    pub(crate) fn load_implicitly_read_system_object(
528        &self,
529        object_id: &ObjectID,
530        version: ConsensusObjectVersion,
531    ) -> Option<Object> {
532        assert!(
533            sui_types::IMPLICITLY_READ_SYSTEM_OBJECTS.contains(object_id),
534            "{object_id} is not an implicitly read system object"
535        );
536        let ConsensusObjectVersion {
537            initial_shared_version,
538            version,
539        } = version;
540        if let Some(object) = ObjectCacheRead::get_object_by_key(self, object_id, version) {
541            return Some(object);
542        }
543        self.metrics
544            .implicit_system_object_read_waits
545            .with_label_values(&[object_id.to_string().as_str()])
546            .inc();
547        let wait_start = Instant::now();
548        let key = InputKey::VersionedObject {
549            id: FullObjectID::Consensus((*object_id, initial_shared_version)),
550            version,
551        };
552        // Block wait until the object is available at the requested version.
553        // Note that before blocking, we check if the latest version already passed the requested version,
554        // if so it must imply that we have already produced the requested version.
555        // We are doing this check instead of exact version comparison to handle the rare case during
556        // dry-runs where the requested version was pruned by this point.
557        // Also note that in the case of dry-run, this will never block wait.
558        self.object_notify_read.read_one_blocking(
559            "load_implicitly_read_system_object",
560            &key,
561            |_key| {
562                ObjectCacheRead::get_object(self, object_id)
563                    .is_some_and(|latest| latest.version() >= version)
564                    .then_some(())
565            },
566        );
567        self.metrics
568            .implicit_system_object_read_wait_latency
569            .with_label_values(&[object_id.to_string().as_str()])
570            .observe(wait_start.elapsed().as_secs_f64());
571        ObjectCacheRead::get_object_by_key(self, object_id, version)
572    }
573
574    pub fn new(
575        config: &ExecutionCacheConfig,
576        store: Arc<AuthorityStore>,
577        metrics: Arc<ExecutionCacheMetrics>,
578        backpressure_manager: Arc<BackpressureManager>,
579    ) -> Self {
580        let packages = MokaCache::builder(8)
581            .max_capacity(randomize_cache_capacity_in_tests(
582                config.package_cache_size(),
583            ))
584            .build();
585        Self {
586            dirty: UncommittedData::new(),
587            cached: CachedCommittedData::new(config),
588            object_by_id_cache: MonotonicCache::new(randomize_cache_capacity_in_tests(
589                config.object_by_id_cache_size(),
590            )),
591            packages,
592            object_locks: ObjectLocks::new(),
593            executed_effects_digests_notify_read: NotifyRead::new(),
594            object_notify_read: NotifyRead::new(),
595            store,
596            backpressure_manager,
597            backpressure_threshold: config.backpressure_threshold(),
598            metrics,
599        }
600    }
601
602    pub fn new_for_tests(store: Arc<AuthorityStore>) -> Self {
603        Self::new(
604            &Default::default(),
605            store,
606            ExecutionCacheMetrics::new(&prometheus::Registry::new()).into(),
607            BackpressureManager::new_for_tests(),
608        )
609    }
610
611    #[cfg(test)]
612    pub fn reset_for_test(&mut self) {
613        let mut new = Self::new(
614            &Default::default(),
615            self.store.clone(),
616            self.metrics.clone(),
617            self.backpressure_manager.clone(),
618        );
619        std::mem::swap(self, &mut new);
620    }
621
622    pub fn evict_executed_effects_from_cache_for_testing(&self, tx_digest: &TransactionDigest) {
623        self.cached.executed_effects_digests.invalidate(tx_digest);
624        self.cached.transaction_events.invalidate(tx_digest);
625        self.cached.transactions.invalidate(tx_digest);
626    }
627
628    fn write_object_entry(
629        &self,
630        object_id: &ObjectID,
631        version: SequenceNumber,
632        object: ObjectEntry,
633    ) {
634        trace!(?object_id, ?version, ?object, "inserting object entry");
635        self.metrics.record_cache_write("object");
636
637        // We must hold the lock for the object entry while inserting to the
638        // object_by_id_cache. Otherwise, a surprising bug can occur:
639        //
640        // 1. A thread executing TX1 can write object (O,1) to the dirty set and then pause.
641        // 2. TX2, which reads (O,1) can begin executing, because ExecutionScheduler immediately
642        //    schedules transactions if their inputs are available. It does not matter that TX1
643        //    hasn't finished executing yet.
644        // 3. TX2 can write (O,2) to both the dirty set and the object_by_id_cache.
645        // 4. The thread executing TX1 can resume and write (O,1) to the object_by_id_cache.
646        //
647        // Now, any subsequent attempt to get the latest version of O will return (O,1) instead of
648        // (O,2).
649        //
650        // This seems very unlikely, but it may be possible under the following circumstances:
651        // - While a thread is unlikely to pause for so long, moka cache uses optimistic
652        //   lock-free algorithms that have retry loops. Possibly, under high contention, this
653        //   code might spin for a surprisingly long time.
654        // - Additionally, many concurrent re-executions of the same tx could happen due to
655        //   the tx finalizer, plus checkpoint executor, consensus, and RPCs from fullnodes.
656        let mut entry = self.dirty.objects.entry(*object_id).or_default();
657
658        self.object_by_id_cache
659            .insert(
660                object_id,
661                LatestObjectCacheEntry::Object(version, object.clone()),
662                Ticket::Write,
663            )
664            // While Ticket::Write cannot expire, this insert may still fail.
665            // See the comment in `MonotonicCache::insert`.
666            .ok();
667
668        entry.insert(version, object.clone());
669
670        if let ObjectEntry::Object(object) = &object {
671            if object.is_package() {
672                self.object_notify_read
673                    .notify(&InputKey::Package { id: *object_id }, &());
674            } else if !object.is_child_object() {
675                self.object_notify_read.notify(
676                    &InputKey::VersionedObject {
677                        id: object.full_id(),
678                        version: object.version(),
679                    },
680                    &(),
681                );
682            }
683        }
684    }
685
686    fn write_marker_value(
687        &self,
688        epoch_id: EpochId,
689        object_key: FullObjectKey,
690        marker_value: MarkerValue,
691    ) {
692        tracing::trace!("inserting marker value {object_key:?}: {marker_value:?}",);
693        self.metrics.record_cache_write("marker");
694        self.dirty
695            .markers
696            .entry((epoch_id, object_key.id()))
697            .or_default()
698            .value_mut()
699            .insert(object_key.version(), marker_value);
700        // It is possible for a transaction to use a consensus stream ended
701        // object in the input, hence we must notify that it is now available
702        // at the assigned version, so that any transaction waiting for this
703        // object version can start execution.
704        if matches!(marker_value, MarkerValue::ConsensusStreamEnded(_)) {
705            self.object_notify_read.notify(
706                &InputKey::VersionedObject {
707                    id: object_key.id(),
708                    version: object_key.version(),
709                },
710                &(),
711            );
712        }
713    }
714
715    // lock both the dirty and committed sides of the cache, and then pass the entries to
716    // the callback. Written with the `with` pattern because any other way of doing this
717    // creates lifetime hell.
718    fn with_locked_cache_entries<K, V, R>(
719        dirty_map: &DashMap<K, CachedVersionMap<V>>,
720        cached_map: &MokaCache<K, Arc<Mutex<CachedVersionMap<V>>>>,
721        key: &K,
722        cb: impl FnOnce(Option<&CachedVersionMap<V>>, Option<&CachedVersionMap<V>>) -> R,
723    ) -> R
724    where
725        K: Copy + Eq + Hash + Send + Sync + 'static,
726        V: Send + Sync + 'static,
727    {
728        let dirty_entry = dirty_map.entry(*key);
729        let dirty_entry = match &dirty_entry {
730            DashMapEntry::Occupied(occupied) => Some(occupied.get()),
731            DashMapEntry::Vacant(_) => None,
732        };
733
734        let cached_entry = cached_map.get(key);
735        let cached_lock = cached_entry.as_ref().map(|entry| entry.lock());
736        let cached_entry = cached_lock.as_deref();
737
738        cb(dirty_entry, cached_entry)
739    }
740
741    // Attempt to get an object from the cache. The DB is not consulted.
742    // Can return Hit, Miss, or NegativeHit (if the object is known to not exist).
743    fn get_object_entry_by_key_cache_only(
744        &self,
745        object_id: &ObjectID,
746        version: SequenceNumber,
747    ) -> CacheResult<ObjectEntry> {
748        Self::with_locked_cache_entries(
749            &self.dirty.objects,
750            &self.cached.object_cache,
751            object_id,
752            |dirty_entry, cached_entry| {
753                check_cache_entry_by_version!(
754                    self,
755                    "object_by_version",
756                    "uncommitted",
757                    dirty_entry,
758                    version
759                );
760                check_cache_entry_by_version!(
761                    self,
762                    "object_by_version",
763                    "committed",
764                    cached_entry,
765                    version
766                );
767                CacheResult::Miss
768            },
769        )
770    }
771
772    fn get_object_by_key_cache_only(
773        &self,
774        object_id: &ObjectID,
775        version: SequenceNumber,
776    ) -> CacheResult<Object> {
777        match self.get_object_entry_by_key_cache_only(object_id, version) {
778            CacheResult::Hit(entry) => match entry {
779                ObjectEntry::Object(object) => CacheResult::Hit(object),
780                ObjectEntry::Deleted | ObjectEntry::Wrapped => CacheResult::NegativeHit,
781            },
782            CacheResult::Miss => CacheResult::Miss,
783            CacheResult::NegativeHit => CacheResult::NegativeHit,
784        }
785    }
786
787    fn get_object_entry_by_id_cache_only(
788        &self,
789        request_type: &'static str,
790        object_id: &ObjectID,
791    ) -> CacheResult<(SequenceNumber, ObjectEntry)> {
792        self.metrics
793            .record_cache_request(request_type, "object_by_id");
794        let entry = self.object_by_id_cache.get(object_id);
795
796        if cfg!(debug_assertions)
797            && let Some(entry) = &entry
798        {
799            // check that cache is coherent
800            let highest: Option<ObjectEntry> = self
801                .dirty
802                .objects
803                .get(object_id)
804                .and_then(|entry| entry.get_highest().map(|(_, o)| o.clone()))
805                .or_else(|| {
806                    let obj: Option<ObjectEntry> = self
807                        .store
808                        .get_latest_object_or_tombstone(*object_id)
809                        .unwrap()
810                        .map(|(_, o)| o.into());
811                    obj
812                });
813
814            let cache_entry = match &*entry.lock() {
815                LatestObjectCacheEntry::Object(_, entry) => Some(entry.clone()),
816                LatestObjectCacheEntry::NonExistent => None,
817            };
818
819            // If the cache entry is a tombstone, the db entry may be missing if it was pruned.
820            let tombstone_possibly_pruned = highest.is_none()
821                && cache_entry
822                    .as_ref()
823                    .map(|e| e.is_tombstone())
824                    .unwrap_or(false);
825
826            if highest != cache_entry && !tombstone_possibly_pruned {
827                tracing::error!(
828                    ?highest,
829                    ?cache_entry,
830                    ?tombstone_possibly_pruned,
831                    "object_by_id cache is incoherent for {:?}",
832                    object_id
833                );
834                panic!("object_by_id cache is incoherent for {:?}", object_id);
835            }
836        }
837
838        if let Some(entry) = entry {
839            let entry = entry.lock();
840            match &*entry {
841                LatestObjectCacheEntry::Object(latest_version, latest_object) => {
842                    self.metrics.record_cache_hit(request_type, "object_by_id");
843                    return CacheResult::Hit((*latest_version, latest_object.clone()));
844                }
845                LatestObjectCacheEntry::NonExistent => {
846                    self.metrics
847                        .record_cache_negative_hit(request_type, "object_by_id");
848                    return CacheResult::NegativeHit;
849                }
850            }
851        } else {
852            self.metrics.record_cache_miss(request_type, "object_by_id");
853        }
854
855        Self::with_locked_cache_entries(
856            &self.dirty.objects,
857            &self.cached.object_cache,
858            object_id,
859            |dirty_entry, cached_entry| {
860                check_cache_entry_by_latest!(self, request_type, "uncommitted", dirty_entry);
861                check_cache_entry_by_latest!(self, request_type, "committed", cached_entry);
862                CacheResult::Miss
863            },
864        )
865    }
866
867    fn get_marker_value_cache_only(
868        &self,
869        object_key: FullObjectKey,
870        epoch_id: EpochId,
871    ) -> CacheResult<MarkerValue> {
872        Self::with_locked_cache_entries(
873            &self.dirty.markers,
874            &self.cached.marker_cache,
875            &(epoch_id, object_key.id()),
876            |dirty_entry, cached_entry| {
877                check_cache_entry_by_version!(
878                    self,
879                    "marker_by_version",
880                    "uncommitted",
881                    dirty_entry,
882                    object_key.version()
883                );
884                check_cache_entry_by_version!(
885                    self,
886                    "marker_by_version",
887                    "committed",
888                    cached_entry,
889                    object_key.version()
890                );
891                CacheResult::Miss
892            },
893        )
894    }
895
896    fn get_latest_marker_value_cache_only(
897        &self,
898        object_id: FullObjectID,
899        epoch_id: EpochId,
900    ) -> CacheResult<(SequenceNumber, MarkerValue)> {
901        Self::with_locked_cache_entries(
902            &self.dirty.markers,
903            &self.cached.marker_cache,
904            &(epoch_id, object_id),
905            |dirty_entry, cached_entry| {
906                check_cache_entry_by_latest!(self, "marker_latest", "uncommitted", dirty_entry);
907                check_cache_entry_by_latest!(self, "marker_latest", "committed", cached_entry);
908                CacheResult::Miss
909            },
910        )
911    }
912
913    fn get_object_impl(&self, request_type: &'static str, id: &ObjectID) -> Option<Object> {
914        let ticket = self.object_by_id_cache.get_ticket_for_read(id);
915        match self.get_object_entry_by_id_cache_only(request_type, id) {
916            CacheResult::Hit((_, entry)) => match entry {
917                ObjectEntry::Object(object) => Some(object),
918                ObjectEntry::Deleted | ObjectEntry::Wrapped => None,
919            },
920            CacheResult::NegativeHit => None,
921            CacheResult::Miss => {
922                let obj = self
923                    .store
924                    .get_latest_object_or_tombstone(*id)
925                    .expect("db error");
926                match obj {
927                    Some((key, obj)) => {
928                        self.cache_latest_object_by_id(
929                            id,
930                            LatestObjectCacheEntry::Object(key.1, obj.clone().into()),
931                            ticket,
932                        );
933                        match obj {
934                            ObjectOrTombstone::Object(object) => Some(object),
935                            ObjectOrTombstone::Tombstone(_) => None,
936                        }
937                    }
938                    None => {
939                        self.cache_object_not_found(id, ticket);
940                        None
941                    }
942                }
943            }
944        }
945    }
946
947    fn record_db_get(&self, request_type: &'static str) -> &AuthorityStore {
948        self.metrics.record_cache_request(request_type, "db");
949        &self.store
950    }
951
952    fn record_db_multi_get(&self, request_type: &'static str, count: usize) -> &AuthorityStore {
953        self.metrics
954            .record_cache_multi_request(request_type, "db", count);
955        &self.store
956    }
957
958    #[instrument(level = "debug", skip_all)]
959    fn write_transaction_outputs(&self, epoch_id: EpochId, tx_outputs: Arc<TransactionOutputs>) {
960        let tx_digest = *tx_outputs.transaction.digest();
961        trace!(?tx_digest, "writing transaction outputs to cache");
962
963        assert!(
964            !self.transaction_executed_in_last_epoch(&tx_digest, epoch_id),
965            "Transaction {:?} was already executed in epoch {}",
966            tx_digest,
967            epoch_id.saturating_sub(1)
968        );
969
970        let TransactionOutputs {
971            transaction,
972            effects,
973            markers,
974            written,
975            deleted,
976            wrapped,
977            events,
978            unchanged_loaded_runtime_objects,
979            ..
980        } = &*tx_outputs;
981
982        // Deletions and wraps must be written first. The reason is that one of the deletes
983        // may be a child object, and if we write the parent object first, a reader may or may
984        // not see the previous version of the child object, instead of the deleted/wrapped
985        // tombstone, which would cause an execution fork
986        for ObjectKey(id, version) in deleted.iter() {
987            self.write_object_entry(id, *version, ObjectEntry::Deleted);
988        }
989
990        for ObjectKey(id, version) in wrapped.iter() {
991            self.write_object_entry(id, *version, ObjectEntry::Wrapped);
992        }
993
994        // Update all markers
995        for (object_key, marker_value) in markers.iter() {
996            self.write_marker_value(epoch_id, *object_key, *marker_value);
997        }
998
999        // Write children before parents to ensure that readers do not observe a parent object
1000        // before its most recent children are visible. Also write packages first.
1001        for (object_id, object) in written.iter() {
1002            if object.is_child_object() || object.is_package() {
1003                self.write_object_entry(object_id, object.version(), object.clone().into());
1004            }
1005
1006            if object.is_package() {
1007                debug!("caching package: {:?}", object.compute_object_reference());
1008                self.packages
1009                    .insert(*object_id, PackageObject::new(object.clone()));
1010            }
1011        }
1012        for (object_id, object) in written.iter() {
1013            if !object.is_child_object() && !object.is_package() {
1014                self.write_object_entry(object_id, object.version(), object.clone().into());
1015            }
1016        }
1017
1018        let tx_digest = *transaction.digest();
1019        debug!(
1020            ?tx_digest,
1021            "Writing transaction output objects to cache: {:?}",
1022            written
1023                .values()
1024                .map(|o| (o.id(), o.version()))
1025                .collect::<Vec<_>>(),
1026        );
1027        let effects_digest = effects.digest();
1028
1029        self.metrics.record_cache_write("transaction_block");
1030        self.dirty
1031            .pending_transaction_writes
1032            .insert(tx_digest, tx_outputs.clone());
1033
1034        // insert transaction effects before executed_effects_digests so that there
1035        // are never dangling entries in executed_effects_digests
1036        self.metrics.record_cache_write("transaction_effects");
1037        self.dirty
1038            .transaction_effects
1039            .insert(effects_digest, effects.clone());
1040
1041        // note: if events.data.is_empty(), then there are no events for this transaction. We
1042        // store it anyway to avoid special cases in commint_transaction_outputs, and translate
1043        // an empty events structure to None when reading.
1044        self.metrics.record_cache_write("transaction_events");
1045        self.dirty
1046            .transaction_events
1047            .insert(tx_digest, events.clone());
1048
1049        self.metrics
1050            .record_cache_write("unchanged_loaded_runtime_objects");
1051        self.dirty
1052            .unchanged_loaded_runtime_objects
1053            .insert(tx_digest, unchanged_loaded_runtime_objects.clone());
1054
1055        self.metrics.record_cache_write("executed_effects_digests");
1056        self.dirty
1057            .executed_effects_digests
1058            .insert(tx_digest, effects_digest);
1059
1060        self.executed_effects_digests_notify_read
1061            .notify(&tx_digest, &effects_digest);
1062
1063        self.metrics
1064            .pending_notify_read
1065            .set(self.executed_effects_digests_notify_read.num_pending() as i64);
1066
1067        let prev = self
1068            .dirty
1069            .total_transaction_inserts
1070            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1071
1072        let pending_count = (prev + 1).saturating_sub(
1073            self.dirty
1074                .total_transaction_commits
1075                .load(std::sync::atomic::Ordering::Relaxed),
1076        );
1077
1078        self.set_backpressure(pending_count);
1079    }
1080
1081    fn build_db_batch(&self, epoch: EpochId, digests: &[TransactionDigest]) -> Batch {
1082        let _metrics_guard = mysten_metrics::monitored_scope("WritebackCache::build_db_batch");
1083        let mut all_outputs = Vec::with_capacity(digests.len());
1084        for tx in digests {
1085            let Some(outputs) = self
1086                .dirty
1087                .pending_transaction_writes
1088                .get(tx)
1089                .map(|o| o.clone())
1090            else {
1091                // This can happen in the following rare case:
1092                // All transactions in the checkpoint are committed to the db (by commit_transaction_outputs,
1093                // called in CheckpointExecutor::process_executed_transactions), but the process crashes before
1094                // the checkpoint water mark is bumped. We will then re-commit the checkpoint at startup,
1095                // despite that all transactions are already executed.
1096                warn!("Attempt to commit unknown transaction {:?}", tx);
1097                continue;
1098            };
1099            all_outputs.push(outputs);
1100        }
1101
1102        let batch = self
1103            .store
1104            .build_db_batch(epoch, &all_outputs)
1105            .expect("db error");
1106        (all_outputs, batch)
1107    }
1108
1109    // Commits dirty data for the given TransactionDigest to the db.
1110    #[instrument(level = "debug", skip_all)]
1111    fn commit_transaction_outputs(
1112        &self,
1113        epoch: EpochId,
1114        (all_outputs, db_batch): Batch,
1115        digests: &[TransactionDigest],
1116    ) {
1117        let _metrics_guard =
1118            mysten_metrics::monitored_scope("WritebackCache::commit_transaction_outputs");
1119        fail_point!("writeback-cache-commit");
1120        trace!(?digests);
1121
1122        // Flush writes to disk before removing anything from dirty set. otherwise,
1123        // a cache eviction could cause a value to disappear briefly, even if we insert to the
1124        // cache before removing from the dirty set.
1125        db_batch.write().expect("db error");
1126
1127        let _metrics_guard =
1128            mysten_metrics::monitored_scope("WritebackCache::commit_transaction_outputs::flush");
1129        // Parallel phase: tx-level metadata is keyed by unique tx_digest/effects_digest,
1130        // so there are no cross-transaction ordering constraints.
1131        all_outputs.par_iter().with_min_len(16).for_each(|outputs| {
1132            let tx_digest = outputs.transaction.digest();
1133            assert!(
1134                self.dirty
1135                    .pending_transaction_writes
1136                    .remove(tx_digest)
1137                    .is_some()
1138            );
1139            self.flush_tx_metadata_from_dirty_to_cached(*tx_digest, outputs);
1140        });
1141
1142        // Sequential phase: object/marker versions must be popped in causal order
1143        // (oldest first) per object_id. Multiple transactions in the batch can touch
1144        // the same shared object at consecutive versions, so this loop must preserve
1145        // the order of all_outputs.
1146        for outputs in all_outputs.iter() {
1147            self.flush_objects_from_dirty_to_cached(epoch, outputs);
1148        }
1149
1150        let num_outputs = all_outputs.len() as u64;
1151        let num_commits = self
1152            .dirty
1153            .total_transaction_commits
1154            .fetch_add(num_outputs, std::sync::atomic::Ordering::Relaxed)
1155            + num_outputs;
1156
1157        let pending_count = self
1158            .dirty
1159            .total_transaction_inserts
1160            .load(std::sync::atomic::Ordering::Relaxed)
1161            .saturating_sub(num_commits);
1162
1163        self.set_backpressure(pending_count);
1164    }
1165
1166    fn approximate_pending_transaction_count(&self) -> u64 {
1167        let num_commits = self
1168            .dirty
1169            .total_transaction_commits
1170            .load(std::sync::atomic::Ordering::Relaxed);
1171
1172        self.dirty
1173            .total_transaction_inserts
1174            .load(std::sync::atomic::Ordering::Relaxed)
1175            .saturating_sub(num_commits)
1176    }
1177
1178    fn set_backpressure(&self, pending_count: u64) {
1179        let backpressure = pending_count > self.backpressure_threshold;
1180        let backpressure_changed = self.backpressure_manager.set_backpressure(backpressure);
1181        if backpressure_changed {
1182            self.metrics.backpressure_toggles.inc();
1183        }
1184        self.metrics
1185            .backpressure_status
1186            .set(if backpressure { 1 } else { 0 });
1187    }
1188
1189    // Flushes tx-level metadata for a single transaction from dirty to cache.
1190    // All keys are unique per transaction (tx_digest, effects_digest), so this
1191    // is safe to call in parallel across transactions.
1192    fn flush_tx_metadata_from_dirty_to_cached(
1193        &self,
1194        tx_digest: TransactionDigest,
1195        outputs: &TransactionOutputs,
1196    ) {
1197        // TODO: outputs should have a strong count of 1 so we should be able to move out of it
1198        let TransactionOutputs {
1199            transaction,
1200            effects,
1201            events,
1202            ..
1203        } = outputs;
1204
1205        let effects_digest = effects.digest();
1206
1207        // Update cache before removing from self.dirty to avoid
1208        // unnecessary cache misses
1209        self.cached
1210            .transactions
1211            .insert(
1212                &tx_digest,
1213                PointCacheItem::Some(transaction.clone()),
1214                Ticket::Write,
1215            )
1216            .ok();
1217        self.cached
1218            .transaction_effects
1219            .insert(
1220                &effects_digest,
1221                PointCacheItem::Some(effects.clone().into()),
1222                Ticket::Write,
1223            )
1224            .ok();
1225        self.cached
1226            .executed_effects_digests
1227            .insert(
1228                &tx_digest,
1229                PointCacheItem::Some(effects_digest),
1230                Ticket::Write,
1231            )
1232            .ok();
1233        self.cached
1234            .transaction_events
1235            .insert(
1236                &tx_digest,
1237                PointCacheItem::Some(events.clone().into()),
1238                Ticket::Write,
1239            )
1240            .ok();
1241
1242        self.dirty
1243            .transaction_effects
1244            .remove(&effects_digest)
1245            .expect("effects must exist");
1246
1247        self.dirty
1248            .transaction_events
1249            .remove(&tx_digest)
1250            .expect("events must exist");
1251
1252        self.dirty
1253            .unchanged_loaded_runtime_objects
1254            .remove(&tx_digest)
1255            .expect("unchanged_loaded_runtime_objects must exist");
1256
1257        self.dirty
1258            .executed_effects_digests
1259            .remove(&tx_digest)
1260            .expect("executed effects must exist");
1261    }
1262
1263    // Flushes object and marker versions for a single transaction from dirty to cache.
1264    // Multiple transactions in the same batch can modify the same shared object at
1265    // consecutive versions, so callers must invoke this in causal (checkpoint) order.
1266    fn flush_objects_from_dirty_to_cached(&self, epoch: EpochId, outputs: &TransactionOutputs) {
1267        let TransactionOutputs {
1268            markers,
1269            written,
1270            deleted,
1271            wrapped,
1272            ..
1273        } = outputs;
1274
1275        for (object_key, marker_value) in markers.iter() {
1276            Self::move_version_from_dirty_to_cache(
1277                &self.dirty.markers,
1278                &self.cached.marker_cache,
1279                (epoch, object_key.id()),
1280                object_key.version(),
1281                marker_value,
1282            );
1283        }
1284
1285        for (object_id, object) in written.iter() {
1286            Self::move_version_from_dirty_to_cache(
1287                &self.dirty.objects,
1288                &self.cached.object_cache,
1289                *object_id,
1290                object.version(),
1291                &ObjectEntry::Object(object.clone()),
1292            );
1293        }
1294
1295        for ObjectKey(object_id, version) in deleted.iter() {
1296            Self::move_version_from_dirty_to_cache(
1297                &self.dirty.objects,
1298                &self.cached.object_cache,
1299                *object_id,
1300                *version,
1301                &ObjectEntry::Deleted,
1302            );
1303        }
1304
1305        for ObjectKey(object_id, version) in wrapped.iter() {
1306            Self::move_version_from_dirty_to_cache(
1307                &self.dirty.objects,
1308                &self.cached.object_cache,
1309                *object_id,
1310                *version,
1311                &ObjectEntry::Wrapped,
1312            );
1313        }
1314    }
1315
1316    // Move the oldest/least entry from the dirty queue to the cache queue.
1317    // This is called after the entry is committed to the db.
1318    fn move_version_from_dirty_to_cache<K, V>(
1319        dirty: &DashMap<K, CachedVersionMap<V>>,
1320        cache: &MokaCache<K, Arc<Mutex<CachedVersionMap<V>>>>,
1321        key: K,
1322        version: SequenceNumber,
1323        value: &V,
1324    ) where
1325        K: Eq + std::hash::Hash + Clone + Send + Sync + Copy + 'static,
1326        V: Send + Sync + Clone + Eq + std::fmt::Debug + 'static,
1327    {
1328        static MAX_VERSIONS: usize = 3;
1329
1330        // IMPORTANT: lock both the dirty set entry and the cache entry before modifying either.
1331        // this ensures that readers cannot see a value temporarily disappear.
1332        let dirty_entry = dirty.entry(key);
1333        let cache_entry = cache.entry(key).or_default();
1334        let mut cache_map = cache_entry.value().lock();
1335
1336        // insert into cache and drop old versions.
1337        cache_map.insert(version, value.clone());
1338        // TODO: make this automatic by giving CachedVersionMap an optional max capacity
1339        cache_map.truncate_to(MAX_VERSIONS);
1340
1341        let DashMapEntry::Occupied(mut occupied_dirty_entry) = dirty_entry else {
1342            panic!("dirty map must exist");
1343        };
1344
1345        let removed = occupied_dirty_entry.get_mut().pop_oldest(&version);
1346
1347        assert_eq!(removed.as_ref(), Some(value), "dirty version must exist");
1348
1349        // if there are no versions remaining, remove the map entry
1350        if occupied_dirty_entry.get().is_empty() {
1351            occupied_dirty_entry.remove();
1352        }
1353    }
1354
1355    // Updates the latest object id cache with an entry that was read from the db.
1356    fn cache_latest_object_by_id(
1357        &self,
1358        object_id: &ObjectID,
1359        object: LatestObjectCacheEntry,
1360        ticket: Ticket,
1361    ) {
1362        trace!("caching object by id: {:?} {:?}", object_id, object);
1363        if self
1364            .object_by_id_cache
1365            .insert(object_id, object, ticket)
1366            .is_ok()
1367        {
1368            self.metrics.record_cache_write("object_by_id");
1369        } else {
1370            trace!("discarded cache write due to expired ticket");
1371            self.metrics.record_ticket_expiry();
1372        }
1373    }
1374
1375    fn cache_object_not_found(&self, object_id: &ObjectID, ticket: Ticket) {
1376        self.cache_latest_object_by_id(object_id, LatestObjectCacheEntry::NonExistent, ticket);
1377    }
1378
1379    fn clear_state_end_of_epoch_impl(&self, execution_guard: &ExecutionLockWriteGuard<'_>) {
1380        info!("clearing state at end of epoch");
1381
1382        // Note: there cannot be any concurrent writes to self.dirty while we are in this function,
1383        // as all transaction execution is paused.
1384        for r in self.dirty.pending_transaction_writes.iter() {
1385            let outputs = r.value();
1386            if !outputs
1387                .transaction
1388                .transaction_data()
1389                .shared_input_objects()
1390                .is_empty()
1391            {
1392                debug_fatal!("transaction must be single writer");
1393            }
1394            info!(
1395                "clearing state for transaction {:?}",
1396                outputs.transaction.digest()
1397            );
1398            for (object_id, object) in outputs.written.iter() {
1399                if object.is_package() {
1400                    info!("removing non-finalized package from cache: {:?}", object_id);
1401                    self.packages.invalidate(object_id);
1402                }
1403                self.object_by_id_cache.invalidate(object_id);
1404                self.cached.object_cache.invalidate(object_id);
1405            }
1406
1407            for ObjectKey(object_id, _) in outputs.deleted.iter().chain(outputs.wrapped.iter()) {
1408                self.object_by_id_cache.invalidate(object_id);
1409                self.cached.object_cache.invalidate(object_id);
1410            }
1411        }
1412
1413        self.dirty.clear();
1414        self.set_backpressure(0);
1415
1416        info!("clearing old transaction locks");
1417        self.object_locks.clear();
1418        info!("clearing object per epoch marker table");
1419        self.store
1420            .clear_object_per_epoch_marker_table(execution_guard)
1421            .expect("db error");
1422    }
1423
1424    fn bulk_insert_genesis_objects_impl(&self, objects: &[Object]) {
1425        self.store
1426            .bulk_insert_genesis_objects(objects)
1427            .expect("db error");
1428        for obj in objects {
1429            self.cached.object_cache.invalidate(&obj.id());
1430            self.object_by_id_cache.invalidate(&obj.id());
1431        }
1432    }
1433
1434    fn insert_genesis_object_impl(&self, object: Object) {
1435        self.object_by_id_cache.invalidate(&object.id());
1436        self.cached.object_cache.invalidate(&object.id());
1437        self.store.insert_genesis_object(object).expect("db error");
1438    }
1439
1440    pub fn clear_caches_and_assert_empty(&self) {
1441        info!("clearing caches");
1442        self.cached.clear_and_assert_empty();
1443        self.object_by_id_cache.invalidate_all();
1444        assert!(&self.object_by_id_cache.is_empty());
1445        self.packages.invalidate_all();
1446        assert_empty(&self.packages);
1447    }
1448}
1449
1450fn account_amount_from_object(account_obj: &Object) -> u128 {
1451    let (_, AccumulatorValue::U128(value)) =
1452        account_obj.data.try_as_move().unwrap().try_into().unwrap();
1453    value.value
1454}
1455
1456impl AccountFundsRead for WritebackCache {
1457    fn get_latest_account_amount(&self, account_id: &AccumulatorObjId) -> u128 {
1458        ObjectCacheRead::get_object(self, account_id.inner())
1459            .map(|account_obj| account_amount_from_object(&account_obj))
1460            .unwrap_or(0)
1461    }
1462
1463    fn get_consistent_latest_account_amount_and_version(
1464        &self,
1465        account_id: &AccumulatorObjId,
1466    ) -> (u128, SequenceNumber) {
1467        // Settlement is not atomic. A settlement transaction writes the accumulator
1468        // objects at version V+1 first, and then a later barrier transaction bumps the
1469        // root from V to V+1. A reader that observes the state in between sees
1470        // post-settlement account objects alongside the pre-settlement root version,
1471        // and reading the "latest" account can therefore disagree with the root we
1472        // just captured.
1473        //
1474        // We handle this with two pieces:
1475        //
1476        // 1. MVCC read capped at the captured root version (see the call site below).
1477        //    By construction of the settlement/barrier ordering, every account object's
1478        //    version is <= the root version after the corresponding barrier runs, so
1479        //    capping at the captured root strips away any newer-settlement writes that
1480        //    have raced ahead of the barrier. The returned amount is the balance at or
1481        //    before the captured root version, even if the account object has a newer
1482        //    latest version by the time this method returns.
1483        //
1484        // 2. Root-version stability check (pre == post). `get_account_amount_at_version`
1485        //    is only safe to call when the target version has not been pruned. Pruning
1486        //    is tied to root advancement, so by reading the root before and after the
1487        //    MVCC read and retrying on mismatch, we ensure that no root advance (and
1488        //    therefore no pruning of the version we read at) could have happened while
1489        //    we were reading — the data we read is still live in the system (memory or
1490        //    db) throughout the call.
1491        let mut pre_root_version =
1492            ObjectCacheRead::get_object(self, &SUI_ACCUMULATOR_ROOT_OBJECT_ID)
1493                .unwrap()
1494                .version();
1495        let starting_root_version = pre_root_version;
1496        let mut loop_iter = 0;
1497        loop {
1498            loop_iter += 1;
1499            // Safe because of (1) and (2) above: the stability check below bounds the
1500            // lifetime of `pre_root_version` to a window in which no pruning happens.
1501            let value = self.get_account_amount_at_version(account_id, pre_root_version);
1502            let post_root_version =
1503                ObjectCacheRead::get_object(self, &SUI_ACCUMULATOR_ROOT_OBJECT_ID)
1504                    .unwrap()
1505                    .version();
1506            if pre_root_version == post_root_version {
1507                if loop_iter > 10 {
1508                    debug!(
1509                        iterations = loop_iter,
1510                        starting_root_version = %starting_root_version,
1511                        ending_root_version = %post_root_version,
1512                        "Root version stabilized after multiple iterations during MVCC read"
1513                    );
1514                }
1515                return (value, pre_root_version);
1516            }
1517            debug!(
1518                "Root version changed from {} to {} during MVCC read, retrying",
1519                pre_root_version, post_root_version
1520            );
1521            pre_root_version = post_root_version;
1522        }
1523    }
1524
1525    fn get_account_amount_at_version(
1526        &self,
1527        account_id: &AccumulatorObjId,
1528        version: SequenceNumber,
1529    ) -> u128 {
1530        let account_obj = self.find_object_lt_or_eq_version(*account_id.inner(), version);
1531        account_obj
1532            .map(|account_obj| account_amount_from_object(&account_obj))
1533            .unwrap_or(0)
1534    }
1535}
1536
1537impl ExecutionCacheAPI for WritebackCache {}
1538
1539impl ExecutionCacheCommit for WritebackCache {
1540    fn build_db_batch(&self, epoch: EpochId, digests: &[TransactionDigest]) -> Batch {
1541        self.build_db_batch(epoch, digests)
1542    }
1543
1544    fn set_highest_committed_checkpoint_in_batch(
1545        &self,
1546        batch: &mut Batch,
1547        checkpoint: CheckpointSequenceNumber,
1548    ) {
1549        self.store
1550            .perpetual_tables
1551            .set_highest_committed_checkpoint(&mut batch.1, checkpoint)
1552            .expect("db error");
1553    }
1554
1555    fn commit_transaction_outputs(
1556        &self,
1557        epoch: EpochId,
1558        batch: Batch,
1559        digests: &[TransactionDigest],
1560    ) {
1561        WritebackCache::commit_transaction_outputs(self, epoch, batch, digests)
1562    }
1563
1564    fn persist_transaction(&self, tx: &VerifiedExecutableTransaction) {
1565        self.store.persist_transaction(tx).expect("db error");
1566    }
1567
1568    fn approximate_pending_transaction_count(&self) -> u64 {
1569        WritebackCache::approximate_pending_transaction_count(self)
1570    }
1571}
1572
1573impl ObjectCacheRead for WritebackCache {
1574    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
1575        self.metrics
1576            .record_cache_request("package", "package_cache");
1577        if let Some(p) = self.packages.get(package_id) {
1578            if cfg!(debug_assertions) {
1579                let canonical_package = self
1580                    .dirty
1581                    .objects
1582                    .get(package_id)
1583                    .and_then(|v| match v.get_highest().map(|v| v.1.clone()) {
1584                        Some(ObjectEntry::Object(object)) => Some(object),
1585                        _ => None,
1586                    })
1587                    .or_else(|| self.store.get_object(package_id));
1588
1589                if let Some(canonical_package) = canonical_package {
1590                    assert_eq!(
1591                        canonical_package.digest(),
1592                        p.object().digest(),
1593                        "Package object cache is inconsistent for package {:?}",
1594                        package_id
1595                    );
1596                }
1597            }
1598            self.metrics.record_cache_hit("package", "package_cache");
1599            return Ok(Some(p));
1600        } else {
1601            self.metrics.record_cache_miss("package", "package_cache");
1602        }
1603
1604        // We try the dirty objects cache as well before going to the database. This is necessary
1605        // because the package could be evicted from the package cache before it is committed
1606        // to the database.
1607        if let Some(p) = self.get_object_impl("package", package_id) {
1608            if p.is_package() {
1609                let p = PackageObject::new(p);
1610                tracing::trace!(
1611                    "caching package: {:?}",
1612                    p.object().compute_object_reference()
1613                );
1614                self.metrics.record_cache_write("package");
1615                self.packages.insert(*package_id, p.clone());
1616                Ok(Some(p))
1617            } else {
1618                Err(SuiErrorKind::UserInputError {
1619                    error: UserInputError::MoveObjectAsPackage {
1620                        object_id: *package_id,
1621                    },
1622                }
1623                .into())
1624            }
1625        } else {
1626            Ok(None)
1627        }
1628    }
1629
1630    fn force_reload_system_packages(&self, _system_package_ids: &[ObjectID]) {
1631        // This is a no-op because all writes go through the cache, therefore it can never
1632        // be incoherent
1633    }
1634
1635    // get_object and variants.
1636
1637    fn get_object(&self, id: &ObjectID) -> Option<Object> {
1638        self.get_object_impl("object_latest", id)
1639    }
1640
1641    fn get_object_by_key(&self, object_id: &ObjectID, version: SequenceNumber) -> Option<Object> {
1642        match self.get_object_by_key_cache_only(object_id, version) {
1643            CacheResult::Hit(object) => Some(object),
1644            CacheResult::NegativeHit => None,
1645            CacheResult::Miss => self
1646                .record_db_get("object_by_version")
1647                .get_object_by_key(object_id, version),
1648        }
1649    }
1650
1651    fn multi_get_objects_by_key(&self, object_keys: &[ObjectKey]) -> Vec<Option<Object>> {
1652        do_fallback_lookup(
1653            object_keys,
1654            |key| match self.get_object_by_key_cache_only(&key.0, key.1) {
1655                CacheResult::Hit(maybe_object) => CacheResult::Hit(Some(maybe_object)),
1656                CacheResult::NegativeHit => CacheResult::NegativeHit,
1657                CacheResult::Miss => CacheResult::Miss,
1658            },
1659            |remaining| {
1660                self.record_db_multi_get("object_by_version", remaining.len())
1661                    .multi_get_objects_by_key(remaining)
1662                    .expect("db error")
1663            },
1664        )
1665    }
1666
1667    fn object_exists_by_key(&self, object_id: &ObjectID, version: SequenceNumber) -> bool {
1668        match self.get_object_by_key_cache_only(object_id, version) {
1669            CacheResult::Hit(_) => true,
1670            CacheResult::NegativeHit => false,
1671            CacheResult::Miss => self
1672                .record_db_get("object_by_version")
1673                .object_exists_by_key(object_id, version)
1674                .expect("db error"),
1675        }
1676    }
1677
1678    fn multi_object_exists_by_key(&self, object_keys: &[ObjectKey]) -> Vec<bool> {
1679        do_fallback_lookup(
1680            object_keys,
1681            |key| match self.get_object_by_key_cache_only(&key.0, key.1) {
1682                CacheResult::Hit(_) => CacheResult::Hit(true),
1683                CacheResult::NegativeHit => CacheResult::Hit(false),
1684                CacheResult::Miss => CacheResult::Miss,
1685            },
1686            |remaining| {
1687                self.record_db_multi_get("object_by_version", remaining.len())
1688                    .multi_object_exists_by_key(remaining)
1689                    .expect("db error")
1690            },
1691        )
1692    }
1693
1694    fn get_latest_object_ref_or_tombstone(&self, object_id: ObjectID) -> Option<ObjectRef> {
1695        match self.get_object_entry_by_id_cache_only("latest_objref_or_tombstone", &object_id) {
1696            CacheResult::Hit((version, entry)) => Some(match entry {
1697                ObjectEntry::Object(object) => object.compute_object_reference(),
1698                ObjectEntry::Deleted => (object_id, version, ObjectDigest::OBJECT_DIGEST_DELETED),
1699                ObjectEntry::Wrapped => (object_id, version, ObjectDigest::OBJECT_DIGEST_WRAPPED),
1700            }),
1701            CacheResult::NegativeHit => None,
1702            CacheResult::Miss => self
1703                .record_db_get("latest_objref_or_tombstone")
1704                .get_latest_object_ref_or_tombstone(object_id)
1705                .expect("db error"),
1706        }
1707    }
1708
1709    fn get_latest_object_or_tombstone(
1710        &self,
1711        object_id: ObjectID,
1712    ) -> Option<(ObjectKey, ObjectOrTombstone)> {
1713        match self.get_object_entry_by_id_cache_only("latest_object_or_tombstone", &object_id) {
1714            CacheResult::Hit((version, entry)) => {
1715                let key = ObjectKey(object_id, version);
1716                Some(match entry {
1717                    ObjectEntry::Object(object) => (key, object.into()),
1718                    ObjectEntry::Deleted => (
1719                        key,
1720                        ObjectOrTombstone::Tombstone((
1721                            object_id,
1722                            version,
1723                            ObjectDigest::OBJECT_DIGEST_DELETED,
1724                        )),
1725                    ),
1726                    ObjectEntry::Wrapped => (
1727                        key,
1728                        ObjectOrTombstone::Tombstone((
1729                            object_id,
1730                            version,
1731                            ObjectDigest::OBJECT_DIGEST_WRAPPED,
1732                        )),
1733                    ),
1734                })
1735            }
1736            CacheResult::NegativeHit => None,
1737            CacheResult::Miss => self
1738                .record_db_get("latest_object_or_tombstone")
1739                .get_latest_object_or_tombstone(object_id)
1740                .expect("db error"),
1741        }
1742    }
1743
1744    fn multi_input_objects_available_cache_only(&self, keys: &[InputKey]) -> Vec<bool> {
1745        keys.iter()
1746            .map(|key| {
1747                if key.is_cancelled() {
1748                    true
1749                } else {
1750                    match key {
1751                        // See multi_input_objects_available: a consensus input is not satisfied
1752                        // by an object at the same version on a different stream.
1753                        InputKey::VersionedObject { id, version } => {
1754                            match self.get_object_by_key_cache_only(&id.id(), *version) {
1755                                CacheResult::Hit(object) => {
1756                                    !matches!(id, FullObjectID::Consensus(_))
1757                                        || object.full_id() == *id
1758                                }
1759                                _ => false,
1760                            }
1761                        }
1762                        InputKey::Package { id } => self.packages.contains_key(id),
1763                    }
1764                }
1765            })
1766            .collect()
1767    }
1768
1769    #[instrument(level = "trace", skip_all, fields(object_id, version_bound))]
1770    fn find_object_lt_or_eq_version(
1771        &self,
1772        object_id: ObjectID,
1773        version_bound: SequenceNumber,
1774    ) -> Option<Object> {
1775        macro_rules! check_cache_entry {
1776            ($level: expr, $objects: expr) => {
1777                self.metrics
1778                    .record_cache_request("object_lt_or_eq_version", $level);
1779                if let Some(objects) = $objects {
1780                    if let Some((_, object)) = objects
1781                        .all_versions_lt_or_eq_descending(&version_bound)
1782                        .next()
1783                    {
1784                        if let ObjectEntry::Object(object) = object {
1785                            self.metrics
1786                                .record_cache_hit("object_lt_or_eq_version", $level);
1787                            return Some(object.clone());
1788                        } else {
1789                            // if we find a tombstone, the object does not exist
1790                            self.metrics
1791                                .record_cache_negative_hit("object_lt_or_eq_version", $level);
1792                            return None;
1793                        }
1794                    } else {
1795                        self.metrics
1796                            .record_cache_miss("object_lt_or_eq_version", $level);
1797                    }
1798                }
1799            };
1800        }
1801
1802        // if we have the latest version cached, and it is within the bound, we are done
1803        self.metrics
1804            .record_cache_request("object_lt_or_eq_version", "object_by_id");
1805        let latest_cache_entry = self.object_by_id_cache.get(&object_id);
1806        if let Some(latest) = &latest_cache_entry {
1807            let latest = latest.lock();
1808            match &*latest {
1809                LatestObjectCacheEntry::Object(latest_version, object) => {
1810                    if *latest_version <= version_bound {
1811                        if let ObjectEntry::Object(object) = object {
1812                            self.metrics
1813                                .record_cache_hit("object_lt_or_eq_version", "object_by_id");
1814                            return Some(object.clone());
1815                        } else {
1816                            // object is a tombstone, but is still within the version bound
1817                            self.metrics.record_cache_negative_hit(
1818                                "object_lt_or_eq_version",
1819                                "object_by_id",
1820                            );
1821                            return None;
1822                        }
1823                    }
1824                    // latest object is not within the version bound. fall through.
1825                }
1826                // No object by this ID exists at all
1827                LatestObjectCacheEntry::NonExistent => {
1828                    self.metrics
1829                        .record_cache_negative_hit("object_lt_or_eq_version", "object_by_id");
1830                    return None;
1831                }
1832            }
1833        }
1834        self.metrics
1835            .record_cache_miss("object_lt_or_eq_version", "object_by_id");
1836
1837        Self::with_locked_cache_entries(
1838            &self.dirty.objects,
1839            &self.cached.object_cache,
1840            &object_id,
1841            |dirty_entry, cached_entry| {
1842                check_cache_entry!("committed", dirty_entry);
1843                check_cache_entry!("uncommitted", cached_entry);
1844
1845                // Much of the time, the query will be for the very latest object version, so
1846                // try that first. But we have to be careful:
1847                // 1. We must load the tombstone if it is present, because its version may exceed
1848                //    the version_bound, in which case we must do a scan.
1849                // 2. You might think we could just call `self.store.get_latest_object_or_tombstone` here.
1850                //    But we cannot, because there may be a more recent version in the dirty set, which
1851                //    we skipped over in check_cache_entry! because of the version bound. However, if we
1852                //    skipped it above, we will skip it here as well, again due to the version bound.
1853                // 3. Despite that, we really want to warm the cache here. Why? Because if the object is
1854                //    cold (not being written to), then we will very soon be able to start serving reads
1855                //    of it from the object_by_id cache, IF we can warm the cache. If we don't warm the
1856                //    the cache here, and no writes to the object occur, then we will always have to go
1857                //    to the db for the object.
1858                //
1859                // Lastly, it is important to understand the rationale for all this: If the object is
1860                // write-hot, we will serve almost all reads to it from the dirty set (or possibly the
1861                // cached set if it is only written to once every few checkpoints). If the object is
1862                // write-cold (or non-existent) and read-hot, then we will serve almost all reads to it
1863                // from the object_by_id cache check above.  Most of the apparently wasteful code here
1864                // exists only to ensure correctness in all the edge cases.
1865                let latest: Option<(SequenceNumber, ObjectEntry)> =
1866                    if let Some(dirty_set) = dirty_entry {
1867                        dirty_set
1868                            .get_highest()
1869                            .cloned()
1870                            .tap_none(|| panic!("dirty set cannot be empty"))
1871                    } else {
1872                        // TODO: we should try not to read from the db while holding the locks.
1873                        self.record_db_get("object_lt_or_eq_version_latest")
1874                            .get_latest_object_or_tombstone(object_id)
1875                            .expect("db error")
1876                            .map(|(ObjectKey(_, version), obj_or_tombstone)| {
1877                                (version, ObjectEntry::from(obj_or_tombstone))
1878                            })
1879                    };
1880
1881                if let Some((obj_version, obj_entry)) = latest {
1882                    // we can always cache the latest object (or tombstone), even if it is not within the
1883                    // version_bound. This is done in order to warm the cache in the case where a sequence
1884                    // of transactions all read the same child object without writing to it.
1885
1886                    // Note: no need to call with_object_by_id_cache_update here, because we are holding
1887                    // the lock on the dirty cache entry, and `latest` cannot become out-of-date
1888                    // while we hold that lock.
1889                    self.cache_latest_object_by_id(
1890                        &object_id,
1891                        LatestObjectCacheEntry::Object(obj_version, obj_entry.clone()),
1892                        // We can get a ticket at the last second, because we are holding the lock
1893                        // on dirty, so there cannot be any concurrent writes.
1894                        self.object_by_id_cache.get_ticket_for_read(&object_id),
1895                    );
1896
1897                    if obj_version <= version_bound {
1898                        match obj_entry {
1899                            ObjectEntry::Object(object) => Some(object),
1900                            ObjectEntry::Deleted | ObjectEntry::Wrapped => None,
1901                        }
1902                    } else {
1903                        // The latest object exceeded the bound, so now we have to do a scan
1904                        // But we already know there is no dirty entry within the bound,
1905                        // so we go to the db.
1906                        self.record_db_get("object_lt_or_eq_version_scan")
1907                            .find_object_lt_or_eq_version(object_id, version_bound)
1908                            .expect("db error")
1909                    }
1910
1911                // no object found in dirty set or db, object does not exist
1912                // When this is called from a read api (i.e. not the execution path) it is
1913                // possible that the object has been deleted and pruned. In this case,
1914                // there would be no entry at all on disk, but we may have a tombstone in the
1915                // cache
1916                } else if let Some(latest_cache_entry) = latest_cache_entry {
1917                    // If there is a latest cache entry, it had better not be a live object!
1918                    assert!(!latest_cache_entry.lock().is_alive());
1919                    None
1920                } else {
1921                    // If there is no latest cache entry, we can insert one.
1922                    let highest = cached_entry.and_then(|c| c.get_highest());
1923                    assert!(highest.is_none() || highest.unwrap().1.is_tombstone());
1924                    self.cache_object_not_found(
1925                        &object_id,
1926                        // okay to get ticket at last second - see above
1927                        self.object_by_id_cache.get_ticket_for_read(&object_id),
1928                    );
1929                    None
1930                }
1931            },
1932        )
1933    }
1934
1935    fn find_object_or_tombstone_lt_or_eq_version_unlocked(
1936        &self,
1937        object_id: ObjectID,
1938        version_bound: SequenceNumber,
1939    ) -> Option<FoundObjectOrTombstone> {
1940        // Copied out under the shard's read lock, which is released at the end of the statement,
1941        // before the store read.
1942        let uncommitted = self.dirty.objects.get(&object_id).and_then(|versions| {
1943            versions
1944                .all_versions_lt_or_eq_descending(&version_bound)
1945                .next()
1946                .map(|(version, entry)| (*version, entry.clone()))
1947        });
1948        // `commit_transaction_outputs` writes a version to the store before
1949        // `flush_objects_from_dirty_to_cached` removes it from the dirty set, so a version that
1950        // left the dirty set after the read above is in the store now.
1951        let committed = self
1952            .record_db_get("object_or_tombstone_lt_or_eq_version_unlocked")
1953            .perpetual_tables
1954            .find_object_or_tombstone_lt_or_eq_version(object_id, version_bound)
1955            .expect("db error");
1956        let committed_version = committed.as_ref().map(|committed| match committed {
1957            ObjectOrTombstone::Object(object) => object.version(),
1958            ObjectOrTombstone::Tombstone((_, version, _)) => *version,
1959        });
1960        match uncommitted {
1961            Some((version, entry))
1962                if committed_version.is_none_or(|committed| committed < version) =>
1963            {
1964                Some(FoundObjectOrTombstone {
1965                    entry: entry.into_object_or_tombstone(object_id, version),
1966                    committed: false,
1967                })
1968            }
1969            _ => committed.map(|entry| FoundObjectOrTombstone {
1970                entry,
1971                committed: true,
1972            }),
1973        }
1974    }
1975
1976    fn get_sui_system_state_object_unsafe(&self) -> SuiResult<SuiSystemState> {
1977        get_sui_system_state(self)
1978    }
1979
1980    fn get_bridge_object_unsafe(&self) -> SuiResult<Bridge> {
1981        get_bridge(self)
1982    }
1983
1984    fn get_marker_value(
1985        &self,
1986        object_key: FullObjectKey,
1987        epoch_id: EpochId,
1988    ) -> Option<MarkerValue> {
1989        match self.get_marker_value_cache_only(object_key, epoch_id) {
1990            CacheResult::Hit(marker) => Some(marker),
1991            CacheResult::NegativeHit => None,
1992            CacheResult::Miss => self
1993                .record_db_get("marker_by_version")
1994                .get_marker_value(object_key, epoch_id)
1995                .expect("db error"),
1996        }
1997    }
1998
1999    fn get_latest_marker(
2000        &self,
2001        object_id: FullObjectID,
2002        epoch_id: EpochId,
2003    ) -> Option<(SequenceNumber, MarkerValue)> {
2004        match self.get_latest_marker_value_cache_only(object_id, epoch_id) {
2005            CacheResult::Hit((v, marker)) => Some((v, marker)),
2006            CacheResult::NegativeHit => {
2007                panic!("cannot have negative hit when getting latest marker")
2008            }
2009            CacheResult::Miss => self
2010                .record_db_get("marker_latest")
2011                .get_latest_marker(object_id, epoch_id)
2012                .expect("db error"),
2013        }
2014    }
2015
2016    #[cfg(test)]
2017    fn get_lock(&self, obj_ref: ObjectRef, epoch_store: &AuthorityPerEpochStore) -> SuiLockResult {
2018        let cur_epoch = epoch_store.epoch();
2019        let Some(obj) = self.get_object_impl("lock", &obj_ref.0) else {
2020            return Err(SuiError::from(UserInputError::ObjectNotFound {
2021                object_id: obj_ref.0,
2022                // even though we know the requested version, we leave it as None to indicate
2023                // that the object does not exist at any version
2024                version: None,
2025            }));
2026        };
2027        let actual_objref = obj.compute_object_reference();
2028        if obj_ref != actual_objref {
2029            Ok(ObjectLockStatus::LockedAtDifferentVersion {
2030                locked_ref: actual_objref,
2031            })
2032        } else {
2033            // requested object ref is live, check if there is a lock
2034            Ok(
2035                match self
2036                    .object_locks
2037                    .get_transaction_lock(&obj_ref, epoch_store)?
2038                {
2039                    Some(tx_digest) => ObjectLockStatus::LockedToTx {
2040                        locked_by_tx: LockDetailsDeprecated {
2041                            epoch: cur_epoch,
2042                            tx_digest,
2043                        },
2044                    },
2045                    None => ObjectLockStatus::Initialized,
2046                },
2047            )
2048        }
2049    }
2050
2051    fn _get_live_objref(&self, object_id: ObjectID) -> SuiResult<ObjectRef> {
2052        let obj = self.get_object_impl("live_objref", &object_id).ok_or(
2053            UserInputError::ObjectNotFound {
2054                object_id,
2055                version: None,
2056            },
2057        )?;
2058        Ok(obj.compute_object_reference())
2059    }
2060
2061    fn object_versions_iter(
2062        &self,
2063        object_id: ObjectID,
2064        versions: std::ops::RangeInclusive<SequenceNumber>,
2065        descending: bool,
2066    ) -> SuiResult<Box<dyn Iterator<Item = SuiResult<ObjectOrTombstone>> + '_>> {
2067        let versions = self
2068            .store
2069            .perpetual_tables
2070            .object_versions_iter(object_id, versions, descending)?;
2071        Ok(Box::new(versions))
2072    }
2073
2074    fn get_highest_pruned_checkpoint(&self) -> Option<CheckpointSequenceNumber> {
2075        self.store
2076            .perpetual_tables
2077            .get_highest_pruned_checkpoint()
2078            .expect("db error")
2079    }
2080
2081    fn notify_read_input_objects<'a>(
2082        &'a self,
2083        input_and_receiving_keys: &'a [InputKey],
2084        receiving_keys: &'a HashSet<InputKey>,
2085        epoch: EpochId,
2086    ) -> BoxFuture<'a, ()> {
2087        self.object_notify_read
2088            .read(
2089                "notify_read_input_objects",
2090                input_and_receiving_keys,
2091                move |keys| {
2092                    self.multi_input_objects_available(keys, receiving_keys, epoch)
2093                        .into_iter()
2094                        .map(|available| if available { Some(()) } else { None })
2095                        .collect::<Vec<_>>()
2096                },
2097            )
2098            .map(|_| ())
2099            .boxed()
2100    }
2101}
2102
2103impl TransactionCacheRead for WritebackCache {
2104    fn multi_get_transaction_blocks(
2105        &self,
2106        digests: &[TransactionDigest],
2107    ) -> Vec<Option<Arc<VerifiedTransaction>>> {
2108        let digests_and_tickets: Vec<_> = digests
2109            .iter()
2110            .map(|d| (*d, self.cached.transactions.get_ticket_for_read(d)))
2111            .collect();
2112        do_fallback_lookup(
2113            &digests_and_tickets,
2114            |(digest, _)| {
2115                self.metrics
2116                    .record_cache_request("transaction_block", "uncommitted");
2117                if let Some(tx) = self.dirty.pending_transaction_writes.get(digest) {
2118                    self.metrics
2119                        .record_cache_hit("transaction_block", "uncommitted");
2120                    return CacheResult::Hit(Some(tx.transaction.clone()));
2121                }
2122                self.metrics
2123                    .record_cache_miss("transaction_block", "uncommitted");
2124
2125                self.metrics
2126                    .record_cache_request("transaction_block", "committed");
2127
2128                match self
2129                    .cached
2130                    .transactions
2131                    .get(digest)
2132                    .map(|l| l.lock().clone())
2133                {
2134                    Some(PointCacheItem::Some(tx)) => {
2135                        self.metrics
2136                            .record_cache_hit("transaction_block", "committed");
2137                        CacheResult::Hit(Some(tx))
2138                    }
2139                    Some(PointCacheItem::None) => CacheResult::NegativeHit,
2140                    None => {
2141                        self.metrics
2142                            .record_cache_miss("transaction_block", "committed");
2143
2144                        CacheResult::Miss
2145                    }
2146                }
2147            },
2148            |remaining| {
2149                let remaining_digests: Vec<_> = remaining.iter().map(|(d, _)| *d).collect();
2150                let results: Vec<_> = self
2151                    .record_db_multi_get("transaction_block", remaining.len())
2152                    .multi_get_transaction_blocks(&remaining_digests)
2153                    .expect("db error")
2154                    .into_iter()
2155                    .map(|o| o.map(Arc::new))
2156                    .collect();
2157                for ((digest, ticket), result) in remaining.iter().zip_debug_eq(results.iter()) {
2158                    if result.is_none() {
2159                        self.cached.transactions.insert(digest, None, *ticket).ok();
2160                    }
2161                }
2162                results
2163            },
2164        )
2165    }
2166
2167    fn multi_get_executed_effects_digests(
2168        &self,
2169        digests: &[TransactionDigest],
2170    ) -> Vec<Option<TransactionEffectsDigest>> {
2171        let digests_and_tickets: Vec<_> = digests
2172            .iter()
2173            .map(|d| {
2174                (
2175                    *d,
2176                    self.cached.executed_effects_digests.get_ticket_for_read(d),
2177                )
2178            })
2179            .collect();
2180        do_fallback_lookup(
2181            &digests_and_tickets,
2182            |(digest, _)| {
2183                self.metrics
2184                    .record_cache_request("executed_effects_digests", "uncommitted");
2185                if let Some(digest) = self.dirty.executed_effects_digests.get(digest) {
2186                    self.metrics
2187                        .record_cache_hit("executed_effects_digests", "uncommitted");
2188                    return CacheResult::Hit(Some(*digest));
2189                }
2190                self.metrics
2191                    .record_cache_miss("executed_effects_digests", "uncommitted");
2192
2193                self.metrics
2194                    .record_cache_request("executed_effects_digests", "committed");
2195                match self
2196                    .cached
2197                    .executed_effects_digests
2198                    .get(digest)
2199                    .map(|l| *l.lock())
2200                {
2201                    Some(PointCacheItem::Some(digest)) => {
2202                        self.metrics
2203                            .record_cache_hit("executed_effects_digests", "committed");
2204                        CacheResult::Hit(Some(digest))
2205                    }
2206                    Some(PointCacheItem::None) => CacheResult::NegativeHit,
2207                    None => {
2208                        self.metrics
2209                            .record_cache_miss("executed_effects_digests", "committed");
2210                        CacheResult::Miss
2211                    }
2212                }
2213            },
2214            |remaining| {
2215                let remaining_digests: Vec<_> = remaining.iter().map(|(d, _)| *d).collect();
2216                let results = self
2217                    .record_db_multi_get("executed_effects_digests", remaining.len())
2218                    .multi_get_executed_effects_digests(&remaining_digests)
2219                    .expect("db error");
2220                for ((digest, ticket), result) in remaining.iter().zip_debug_eq(results.iter()) {
2221                    if result.is_none() {
2222                        self.cached
2223                            .executed_effects_digests
2224                            .insert(digest, None, *ticket)
2225                            .ok();
2226                    }
2227                }
2228                results
2229            },
2230        )
2231    }
2232
2233    fn multi_get_effects(
2234        &self,
2235        digests: &[TransactionEffectsDigest],
2236    ) -> Vec<Option<TransactionEffects>> {
2237        let digests_and_tickets: Vec<_> = digests
2238            .iter()
2239            .map(|d| (*d, self.cached.transaction_effects.get_ticket_for_read(d)))
2240            .collect();
2241        do_fallback_lookup(
2242            &digests_and_tickets,
2243            |(digest, _)| {
2244                self.metrics
2245                    .record_cache_request("transaction_effects", "uncommitted");
2246                if let Some(effects) = self.dirty.transaction_effects.get(digest) {
2247                    self.metrics
2248                        .record_cache_hit("transaction_effects", "uncommitted");
2249                    return CacheResult::Hit(Some(effects.clone()));
2250                }
2251                self.metrics
2252                    .record_cache_miss("transaction_effects", "uncommitted");
2253
2254                self.metrics
2255                    .record_cache_request("transaction_effects", "committed");
2256                match self
2257                    .cached
2258                    .transaction_effects
2259                    .get(digest)
2260                    .map(|l| l.lock().clone())
2261                {
2262                    Some(PointCacheItem::Some(effects)) => {
2263                        self.metrics
2264                            .record_cache_hit("transaction_effects", "committed");
2265                        CacheResult::Hit(Some((*effects).clone()))
2266                    }
2267                    Some(PointCacheItem::None) => CacheResult::NegativeHit,
2268                    None => {
2269                        self.metrics
2270                            .record_cache_miss("transaction_effects", "committed");
2271                        CacheResult::Miss
2272                    }
2273                }
2274            },
2275            |remaining| {
2276                let remaining_digests: Vec<_> = remaining.iter().map(|(d, _)| *d).collect();
2277                let results = self
2278                    .record_db_multi_get("transaction_effects", remaining.len())
2279                    .multi_get_effects(remaining_digests.iter())
2280                    .expect("db error");
2281                for ((digest, ticket), result) in remaining.iter().zip_debug_eq(results.iter()) {
2282                    if result.is_none() {
2283                        self.cached
2284                            .transaction_effects
2285                            .insert(digest, None, *ticket)
2286                            .ok();
2287                    }
2288                }
2289                results
2290            },
2291        )
2292    }
2293
2294    fn transaction_executed_in_last_epoch(
2295        &self,
2296        digest: &TransactionDigest,
2297        current_epoch: EpochId,
2298    ) -> bool {
2299        if current_epoch == 0 {
2300            return false;
2301        }
2302        let last_epoch = current_epoch - 1;
2303        let cache_key = (last_epoch, *digest);
2304
2305        let ticket = self
2306            .cached
2307            .transaction_executed_in_last_epoch
2308            .get_ticket_for_read(&cache_key);
2309
2310        if let Some(cached) = self
2311            .cached
2312            .transaction_executed_in_last_epoch
2313            .get(&cache_key)
2314        {
2315            return cached.lock().is_some();
2316        }
2317
2318        let was_executed = self
2319            .store
2320            .perpetual_tables
2321            .was_transaction_executed_in_last_epoch(digest, current_epoch);
2322
2323        let value = if was_executed { Some(()) } else { None };
2324        self.cached
2325            .transaction_executed_in_last_epoch
2326            .insert(&cache_key, value, ticket)
2327            .ok();
2328
2329        was_executed
2330    }
2331
2332    fn notify_read_executed_effects_digests<'a>(
2333        &'a self,
2334        task_name: &'static str,
2335        digests: &'a [TransactionDigest],
2336    ) -> BoxFuture<'a, Vec<TransactionEffectsDigest>> {
2337        self.executed_effects_digests_notify_read
2338            .read(task_name, digests, |digests| {
2339                self.multi_get_executed_effects_digests(digests)
2340            })
2341            .boxed()
2342    }
2343
2344    fn multi_get_events(
2345        &self,
2346        event_digests: &[TransactionDigest],
2347    ) -> Vec<Option<TransactionEvents>> {
2348        fn map_events(events: TransactionEvents) -> Option<TransactionEvents> {
2349            if events.data.is_empty() {
2350                None
2351            } else {
2352                Some(events)
2353            }
2354        }
2355
2356        let digests_and_tickets: Vec<_> = event_digests
2357            .iter()
2358            .map(|d| (*d, self.cached.transaction_events.get_ticket_for_read(d)))
2359            .collect();
2360        do_fallback_lookup(
2361            &digests_and_tickets,
2362            |(digest, _)| {
2363                self.metrics
2364                    .record_cache_request("transaction_events", "uncommitted");
2365                if let Some(events) = self.dirty.transaction_events.get(digest).map(|e| e.clone()) {
2366                    self.metrics
2367                        .record_cache_hit("transaction_events", "uncommitted");
2368
2369                    return CacheResult::Hit(map_events(events));
2370                }
2371                self.metrics
2372                    .record_cache_miss("transaction_events", "uncommitted");
2373
2374                self.metrics
2375                    .record_cache_request("transaction_events", "committed");
2376                match self
2377                    .cached
2378                    .transaction_events
2379                    .get(digest)
2380                    .map(|l| l.lock().clone())
2381                {
2382                    Some(PointCacheItem::Some(events)) => {
2383                        self.metrics
2384                            .record_cache_hit("transaction_events", "committed");
2385                        CacheResult::Hit(map_events((*events).clone()))
2386                    }
2387                    Some(PointCacheItem::None) => CacheResult::NegativeHit,
2388                    None => {
2389                        self.metrics
2390                            .record_cache_miss("transaction_events", "committed");
2391
2392                        CacheResult::Miss
2393                    }
2394                }
2395            },
2396            |remaining| {
2397                let remaining_digests: Vec<_> = remaining.iter().map(|(d, _)| *d).collect();
2398                let results = self
2399                    .store
2400                    .multi_get_events(&remaining_digests)
2401                    .expect("db error");
2402                for ((digest, ticket), result) in remaining.iter().zip_debug_eq(results.iter()) {
2403                    if result.is_none() {
2404                        self.cached
2405                            .transaction_events
2406                            .insert(digest, None, *ticket)
2407                            .ok();
2408                    }
2409                }
2410                results
2411            },
2412        )
2413    }
2414
2415    fn get_unchanged_loaded_runtime_objects(
2416        &self,
2417        digest: &TransactionDigest,
2418    ) -> Option<Vec<ObjectKey>> {
2419        self.dirty
2420            .unchanged_loaded_runtime_objects
2421            .get(digest)
2422            .map(|b| b.clone())
2423            .or_else(|| {
2424                self.store
2425                    .get_unchanged_loaded_runtime_objects(digest)
2426                    .expect("db error")
2427            })
2428    }
2429
2430    fn multi_get_unchanged_loaded_runtime_objects(
2431        &self,
2432        digests: &[TransactionDigest],
2433    ) -> Vec<Option<Vec<ObjectKey>>> {
2434        do_fallback_lookup(
2435            digests,
2436            |digest| match self.dirty.unchanged_loaded_runtime_objects.get(digest) {
2437                Some(objects) => CacheResult::Hit(Some(objects.clone())),
2438                None => CacheResult::Miss,
2439            },
2440            |digests| {
2441                self.store
2442                    .multi_get_unchanged_loaded_runtime_objects(digests)
2443                    .expect("db error")
2444            },
2445        )
2446    }
2447
2448    fn get_highest_pruned_effects_checkpoint(&self) -> Option<CheckpointSequenceNumber> {
2449        self.store
2450            .perpetual_tables
2451            .get_highest_pruned_effects_checkpoint()
2452            .expect("db error")
2453    }
2454
2455    fn take_accumulator_events(&self, digest: &TransactionDigest) -> Option<Vec<AccumulatorEvent>> {
2456        self.dirty
2457            .pending_transaction_writes
2458            .get(digest)
2459            .map(|transaction_output| transaction_output.take_accumulator_events())
2460    }
2461}
2462
2463impl ExecutionCacheWrite for WritebackCache {
2464    fn validate_owned_object_versions(&self, owned_input_objects: &[ObjectRef]) -> SuiResult {
2465        ObjectLocks::validate_owned_object_versions(self, owned_input_objects)
2466    }
2467
2468    fn write_transaction_outputs(&self, epoch_id: EpochId, tx_outputs: Arc<TransactionOutputs>) {
2469        WritebackCache::write_transaction_outputs(self, epoch_id, tx_outputs);
2470    }
2471
2472    #[cfg(test)]
2473    fn write_object_entry_for_test(&self, object: Object) {
2474        self.write_object_entry(&object.id(), object.version(), object.into());
2475    }
2476}
2477
2478implement_passthrough_traits!(WritebackCache);
2479
2480impl GlobalStateHashStore for WritebackCache {
2481    fn get_object_ref_prior_to_key_deprecated(
2482        &self,
2483        object_id: &ObjectID,
2484        version: SequenceNumber,
2485    ) -> SuiResult<Option<ObjectRef>> {
2486        // There is probably a more efficient way to implement this, but since this is only used by
2487        // old protocol versions, it is better to do the simple thing that is obviously correct.
2488        // In this case we previous version from all sources and choose the highest
2489        let mut candidates = Vec::new();
2490
2491        let check_versions =
2492            |versions: &CachedVersionMap<ObjectEntry>| match versions.get_prior_to(&version) {
2493                Some((version, object_entry)) => match object_entry {
2494                    ObjectEntry::Object(object) => {
2495                        assert_eq!(object.version(), version);
2496                        Some(object.compute_object_reference())
2497                    }
2498                    ObjectEntry::Deleted => {
2499                        Some((*object_id, version, ObjectDigest::OBJECT_DIGEST_DELETED))
2500                    }
2501                    ObjectEntry::Wrapped => {
2502                        Some((*object_id, version, ObjectDigest::OBJECT_DIGEST_WRAPPED))
2503                    }
2504                },
2505                None => None,
2506            };
2507
2508        // first check dirty data
2509        if let Some(objects) = self.dirty.objects.get(object_id)
2510            && let Some(prior) = check_versions(&objects)
2511        {
2512            candidates.push(prior);
2513        }
2514
2515        if let Some(objects) = self.cached.object_cache.get(object_id)
2516            && let Some(prior) = check_versions(&objects.lock())
2517        {
2518            candidates.push(prior);
2519        }
2520
2521        if let Some(prior) = self
2522            .store
2523            .get_object_ref_prior_to_key_deprecated(object_id, version)?
2524        {
2525            candidates.push(prior);
2526        }
2527
2528        // sort candidates by version, and return the highest
2529        candidates.sort_by_key(|(_, version, _)| *version);
2530        Ok(candidates.pop())
2531    }
2532
2533    fn get_root_state_hash_for_epoch(
2534        &self,
2535        epoch: EpochId,
2536    ) -> SuiResult<Option<(CheckpointSequenceNumber, GlobalStateHash)>> {
2537        self.store.get_root_state_hash_for_epoch(epoch)
2538    }
2539
2540    fn insert_state_hash_for_epoch(
2541        &self,
2542        epoch: EpochId,
2543        checkpoint_seq_num: &CheckpointSequenceNumber,
2544        acc: &GlobalStateHash,
2545    ) -> SuiResult {
2546        self.store
2547            .insert_state_hash_for_epoch(epoch, checkpoint_seq_num, acc)
2548    }
2549
2550    fn iter_live_object_set(
2551        &self,
2552        include_wrapped_tombstone: bool,
2553    ) -> Box<dyn Iterator<Item = LiveObject> + '_> {
2554        // The only time it is safe to iterate the live object set is at an epoch boundary,
2555        // at which point the db is consistent and the dirty cache is empty. So this does
2556        // read the cache
2557        assert!(
2558            self.dirty.is_empty(),
2559            "cannot iterate live object set with dirty data"
2560        );
2561        self.store.iter_live_object_set(include_wrapped_tombstone)
2562    }
2563
2564    // A version of iter_live_object_set that reads the cache. Only use for testing. If used
2565    // on a live validator, can cause the server to block for as long as it takes to iterate
2566    // the entire live object set.
2567    fn iter_cached_live_object_set_for_testing(
2568        &self,
2569        include_wrapped_tombstone: bool,
2570    ) -> Box<dyn Iterator<Item = LiveObject> + '_> {
2571        // hold iter until we are finished to prevent any concurrent inserts/deletes
2572        let iter = self.dirty.objects.iter();
2573        let mut dirty_objects = BTreeMap::new();
2574
2575        // add everything from the store
2576        for obj in self.store.iter_live_object_set(include_wrapped_tombstone) {
2577            dirty_objects.insert(obj.object_id(), obj);
2578        }
2579
2580        // add everything from the cache, but also remove deletions
2581        for entry in iter {
2582            let id = *entry.key();
2583            let value = entry.value();
2584            match value.get_highest().unwrap() {
2585                (_, ObjectEntry::Object(object)) => {
2586                    dirty_objects.insert(id, LiveObject::Normal(object.clone()));
2587                }
2588                (version, ObjectEntry::Wrapped) => {
2589                    if include_wrapped_tombstone {
2590                        dirty_objects.insert(id, LiveObject::Wrapped(ObjectKey(id, *version)));
2591                    } else {
2592                        dirty_objects.remove(&id);
2593                    }
2594                }
2595                (_, ObjectEntry::Deleted) => {
2596                    dirty_objects.remove(&id);
2597                }
2598            }
2599        }
2600
2601        Box::new(dirty_objects.into_values())
2602    }
2603}
2604
2605// TODO: For correctness, we must at least invalidate the cache when items are written through this
2606// trait (since they could be negatively cached as absent). But it may or may not be optimal to
2607// actually insert them into the cache. For instance if state sync is running ahead of execution,
2608// they might evict other items that are about to be read. This could be an area for tuning in the
2609// future.
2610impl StateSyncAPI for WritebackCache {
2611    fn insert_transaction_and_effects(
2612        &self,
2613        transaction: &VerifiedTransaction,
2614        transaction_effects: &TransactionEffects,
2615    ) {
2616        self.store
2617            .insert_transaction_and_effects(transaction, transaction_effects)
2618            .expect("db error");
2619        self.cached
2620            .transactions
2621            .insert(
2622                transaction.digest(),
2623                PointCacheItem::Some(Arc::new(transaction.clone())),
2624                Ticket::Write,
2625            )
2626            .ok();
2627        self.cached
2628            .transaction_effects
2629            .insert(
2630                &transaction_effects.digest(),
2631                PointCacheItem::Some(Arc::new(transaction_effects.clone())),
2632                Ticket::Write,
2633            )
2634            .ok();
2635    }
2636
2637    fn multi_insert_transaction_and_effects(
2638        &self,
2639        transactions_and_effects: &[VerifiedExecutionData],
2640    ) {
2641        self.store
2642            .multi_insert_transaction_and_effects(transactions_and_effects.iter())
2643            .expect("db error");
2644        for VerifiedExecutionData {
2645            transaction,
2646            effects,
2647        } in transactions_and_effects
2648        {
2649            self.cached
2650                .transactions
2651                .insert(
2652                    transaction.digest(),
2653                    PointCacheItem::Some(Arc::new(transaction.clone())),
2654                    Ticket::Write,
2655                )
2656                .ok();
2657            self.cached
2658                .transaction_effects
2659                .insert(
2660                    &effects.digest(),
2661                    PointCacheItem::Some(Arc::new(effects.clone())),
2662                    Ticket::Write,
2663                )
2664                .ok();
2665        }
2666    }
2667}