Skip to main content

risingwave_storage/hummock/pin_cache/
mod.rs

1// Copyright 2026 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Dormant local whole-SST read index. The remote object store remains authoritative.
16//!
17//! Registration makes an object eligible for a local route but does not write or publish it.
18//! Files use the fixed `<object_id>.sst` path. There is no download API in this layer:
19//! safe path reuse requires the storage admission and GC unlink protections added later.
20//! Unregistering prevents new lookups; existing handles retain their selected file.
21//! Reads never enqueue refill work. The backend does not track version or refill identities.
22
23use std::collections::HashMap;
24use std::sync::Arc;
25
26use bytes::Bytes;
27use parking_lot::RwLock;
28use risingwave_hummock_sdk::HummockSstableObjectId;
29use risingwave_object_store::object::{ObjectRangeBounds, ObjectResult, ObjectStoreRef};
30
31mod membership;
32#[cfg(test)]
33pub(super) mod test_utils;
34#[cfg(test)]
35mod tests;
36
37use crate::monitor::GLOBAL_PIN_CACHE_METRICS;
38
39fn metric_bytes(bytes: u64) -> i64 {
40    bytes.min(i64::MAX as u64) as i64
41}
42
43/// One local file, shared by the index and readers after publication.
44struct PinCacheFile {
45    path: String,
46    size: u64,
47}
48
49/// One registered SST object; registration alone does not make it readable or start refill.
50struct PinCacheObject {
51    published: Option<Arc<PinCacheFile>>,
52}
53
54impl PinCacheObject {
55    /// Withdraws the read route and returns the detached file.
56    /// Object registration remains valid.
57    /// The caller must release the returned reference outside the shard lock.
58    fn unpublish(&mut self) -> Option<Arc<PinCacheFile>> {
59        let file = self.published.take()?;
60        GLOBAL_PIN_CACHE_METRICS.published_objects.dec();
61        GLOBAL_PIN_CACHE_METRICS
62            .published_bytes
63            .sub(metric_bytes(file.size));
64        Some(file)
65    }
66
67    #[cfg(test)]
68    fn publish(&mut self, file: Arc<PinCacheFile>) {
69        assert!(self.published.is_none());
70        GLOBAL_PIN_CACHE_METRICS.published_objects.inc();
71        GLOBAL_PIN_CACHE_METRICS
72            .published_bytes
73            .add(metric_bytes(file.size));
74        self.published = Some(file);
75    }
76}
77
78/// One shard's registered object index.
79#[derive(Default)]
80struct PinCacheShard {
81    objects: HashMap<HummockSstableObjectId, PinCacheObject>,
82}
83
84impl PinCacheShard {
85    fn register_object(&mut self, id: HummockSstableObjectId) {
86        self.objects
87            .entry(id)
88            .or_insert(PinCacheObject { published: None });
89    }
90}
91
92/// A local whole-SST cache. The remote object store remains authoritative.
93/// Each object's state is protected by its shard lock. Reads and membership updates
94/// may run concurrently; batch membership updates are not atomic across objects.
95pub(crate) struct PinCache {
96    store: ObjectStoreRef,
97    // Hold only one shard lock at a time. Never perform I/O or call back into the controller
98    // or refill executor while locked. Construction finishes before this cache is shared.
99    shards: Box<[RwLock<PinCacheShard>]>,
100}
101
102/// A reference to one published file, retained even after its object leaves the index.
103/// Reads never look up the object a second time.
104/// Callers must support fallback if the selected local file becomes unavailable.
105#[derive(Clone)]
106pub(crate) struct PinCacheReadHandle {
107    pin_cache: Arc<PinCache>,
108    object_id: HummockSstableObjectId,
109    file: Arc<PinCacheFile>,
110}
111
112impl PinCacheReadHandle {
113    /// Withdraws this specific publication, preserving registration.
114    /// Use after its file fails to read or decode, or is no longer eligible for local reads.
115    /// A shared cache fetch can fail on another request's route; such an error alone must not
116    /// invalidate this handle's publication.
117    pub(crate) fn invalidate(&self) {
118        let mut state = self.pin_cache.shard(self.object_id).write();
119        // A late failure must not invalidate a newer publication of the same object.
120        if let Some(object) = state.objects.get_mut(&self.object_id)
121            && object
122                .published
123                .as_ref()
124                .is_some_and(|file| Arc::ptr_eq(file, &self.file))
125        {
126            let file = object.unpublish().unwrap();
127            drop(state);
128            drop(file);
129        }
130    }
131
132    /// Reads the selected publication through the local object store. On failure, invalidates only
133    /// this publication and returns the error so the caller can fall back to its normal read path.
134    pub(crate) async fn read(&self, range: impl ObjectRangeBounds) -> ObjectResult<Bytes> {
135        self.pin_cache
136            .store
137            .read(&self.file.path, range)
138            .await
139            .inspect_err(|_| self.invalidate())
140    }
141}
142
143impl PinCache {
144    /// Registers initial objects without reading or writing local files.
145    /// Recovery is added separately before this backend is connected to production reads.
146    pub(crate) fn new(
147        store: ObjectStoreRef,
148        shard_num: usize,
149        objects: impl IntoIterator<Item = HummockSstableObjectId>,
150    ) -> Arc<Self> {
151        assert!(
152            shard_num > 0,
153            "pin cache shard count must be greater than zero"
154        );
155        let mut pin_cache = Self {
156            store,
157            shards: (0..shard_num)
158                .map(|_| RwLock::new(PinCacheShard::default()))
159                .collect(),
160        };
161        for id in objects {
162            pin_cache.shards[Self::shard_index(id, shard_num)]
163                .get_mut()
164                .register_object(id);
165        }
166        GLOBAL_PIN_CACHE_METRICS.published_objects.set(0);
167        GLOBAL_PIN_CACHE_METRICS.published_bytes.set(0);
168        Arc::new(pin_cache)
169    }
170
171    pub(crate) fn get(
172        self: &Arc<Self>,
173        object_id: HummockSstableObjectId,
174    ) -> Option<PinCacheReadHandle> {
175        let state = self.shard(object_id).read();
176        let file = Arc::clone(state.objects.get(&object_id)?.published.as_ref()?);
177        Some(PinCacheReadHandle {
178            pin_cache: Arc::clone(self),
179            object_id,
180            file,
181        })
182    }
183
184    fn shard_index(object_id: HummockSstableObjectId, shard_num: usize) -> usize {
185        xxhash_rust::xxh64::xxh64(&object_id.as_raw_id().to_le_bytes(), 0) as usize % shard_num
186    }
187
188    fn shard(&self, object_id: HummockSstableObjectId) -> &RwLock<PinCacheShard> {
189        &self.shards[Self::shard_index(object_id, self.shards.len())]
190    }
191}