ab_farmer/single_disk_farm/
plot_cache.rs

1//! Plot cache for single disk farm
2
3// TODO: Not supported under Miri: https://github.com/rust-lang/miri/issues/4464
4#[cfg(not(miri))]
5#[cfg(test)]
6mod tests;
7
8use crate::farm::{FarmError, MaybePieceStoredResult, PlotCache};
9use crate::single_disk_farm::direct_io_file_wrapper::DirectIoFileWrapper;
10use crate::utils::AsyncJoinOnDrop;
11use ab_core_primitives::hashes::Blake3Hash;
12use ab_core_primitives::pieces::{Piece, PieceIndex};
13use ab_farmer_components::file_ext::FileExt;
14use ab_farmer_components::sector::SectorMetadataChecksummed;
15use ab_networking::libp2p::kad::RecordKey;
16use ab_networking::utils::multihash::ToMultihash;
17use async_lock::RwLock as AsyncRwLock;
18use async_trait::async_trait;
19use bytes::BytesMut;
20use parking_lot::RwLock;
21use std::collections::HashMap;
22use std::sync::{Arc, Weak};
23use std::{io, mem};
24use thiserror::Error;
25use tokio::task;
26use tracing::{debug, info, trace, warn};
27
28/// Disk plot cache open error
29#[derive(Debug, Error)]
30pub enum DiskPlotCacheError {
31    /// I/O error occurred
32    #[error("Plot cache I/O error: {0}")]
33    Io(#[from] io::Error),
34    /// Failed to spawn task for blocking thread
35    #[error("Failed to spawn task for blocking thread: {0}")]
36    TokioJoinError(#[from] tokio::task::JoinError),
37    /// Checksum mismatch
38    #[error("Checksum mismatch")]
39    ChecksumMismatch,
40}
41
42#[derive(Debug)]
43struct CachedPieces {
44    /// Map of piece index into offset
45    map: HashMap<RecordKey, u32>,
46    next_offset: Option<u32>,
47}
48
49/// Additional piece cache that exploit part of the plot that does not contain sectors yet
50#[derive(Debug, Clone)]
51pub struct DiskPlotCache {
52    file: Weak<DirectIoFileWrapper>,
53    sectors_metadata: Weak<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
54    cached_pieces: Arc<RwLock<CachedPieces>>,
55    target_sector_count: u16,
56    sector_size: u64,
57}
58
59#[async_trait]
60impl PlotCache for DiskPlotCache {
61    async fn is_piece_maybe_stored(
62        &self,
63        key: &RecordKey,
64    ) -> Result<MaybePieceStoredResult, FarmError> {
65        Ok(self.is_piece_maybe_stored(key))
66    }
67
68    /// Store piece in cache if there is free space, and return `Ok(true)`.
69    /// Returns `Ok(false)` if there is no free space, or the farm or process is shutting down.
70    async fn try_store_piece(
71        &self,
72        piece_index: PieceIndex,
73        piece: &Piece,
74    ) -> Result<bool, FarmError> {
75        Ok(self.try_store_piece(piece_index, piece).await?)
76    }
77
78    async fn read_piece(&self, key: &RecordKey) -> Result<Option<Piece>, FarmError> {
79        Ok(self.read_piece(key).await)
80    }
81}
82
83impl DiskPlotCache {
84    pub(crate) fn new(
85        file: &Arc<DirectIoFileWrapper>,
86        sectors_metadata: &Arc<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
87        target_sector_count: u16,
88        sector_size: u64,
89    ) -> Self {
90        info!("Checking plot cache contents, this can take a while");
91        let cached_pieces = {
92            let sectors_metadata = sectors_metadata.read_blocking();
93            let mut element = vec![0; Self::element_size() as usize];
94            let mut map = HashMap::new();
95            let mut next_offset = None;
96
97            let file_size = sector_size * u64::from(target_sector_count);
98            let plotted_size = sector_size * sectors_metadata.len() as u64;
99
100            // Step over all free potential offsets for pieces that could have been cached
101            let from_offset = (plotted_size / Self::element_size() as u64) as u32;
102            let to_offset = (file_size / Self::element_size() as u64) as u32;
103            // TODO: Parallelize or read in larger batches
104            for offset in (from_offset..to_offset).rev() {
105                match Self::read_piece_internal(file, offset, &mut element) {
106                    Ok(maybe_piece_index) => match maybe_piece_index {
107                        Some(piece_index) => {
108                            map.insert(RecordKey::from(piece_index.to_multihash()), offset);
109                        }
110                        None => {
111                            next_offset.replace(offset);
112                            break;
113                        }
114                    },
115                    Err(DiskPlotCacheError::ChecksumMismatch) => {
116                        next_offset.replace(offset);
117                        break;
118                    }
119                    Err(error) => {
120                        warn!(%error, %offset, "Failed to read plot cache element");
121                        break;
122                    }
123                }
124            }
125
126            CachedPieces { map, next_offset }
127        };
128
129        info!("Finished checking plot cache contents");
130
131        Self {
132            file: Arc::downgrade(file),
133            sectors_metadata: Arc::downgrade(sectors_metadata),
134            cached_pieces: Arc::new(RwLock::new(cached_pieces)),
135            target_sector_count,
136            sector_size,
137        }
138    }
139
140    /// Size of a single plot cache element
141    pub(crate) const fn element_size() -> u32 {
142        (PieceIndex::SIZE + Piece::SIZE + Blake3Hash::SIZE) as u32
143    }
144
145    /// Check if piece is potentially stored in this cache (not guaranteed to be because it might be
146    /// overridden with sector any time)
147    pub(crate) fn is_piece_maybe_stored(&self, key: &RecordKey) -> MaybePieceStoredResult {
148        let offset = {
149            let cached_pieces = self.cached_pieces.read();
150
151            let Some(offset) = cached_pieces.map.get(key).copied() else {
152                return if cached_pieces.next_offset.is_some() {
153                    MaybePieceStoredResult::Vacant
154                } else {
155                    MaybePieceStoredResult::No
156                };
157            };
158
159            offset
160        };
161
162        let Some(sectors_metadata) = self.sectors_metadata.upgrade() else {
163            return MaybePieceStoredResult::No;
164        };
165
166        let element_offset = u64::from(offset) * u64::from(Self::element_size());
167        // Blocking read is fine because writes in farmer are very rare and very brief
168        let plotted_bytes = self.sector_size * sectors_metadata.read_blocking().len() as u64;
169
170        // Make sure offset is after anything that is already plotted
171        if element_offset < plotted_bytes {
172            // Remove entry since it was overwritten with a sector already
173            self.cached_pieces.write().map.remove(key);
174            MaybePieceStoredResult::No
175        } else {
176            MaybePieceStoredResult::Yes
177        }
178    }
179
180    /// Store piece in cache if there is free space, and return `Ok(true)`.
181    /// Returns `Ok(false)` if there is no free space, or the farm or process is shutting down.
182    pub(crate) async fn try_store_piece(
183        &self,
184        piece_index: PieceIndex,
185        piece: &Piece,
186    ) -> Result<bool, DiskPlotCacheError> {
187        let offset = {
188            // First, do a quick concurrent check for free space with a read lock, dropping it
189            // immediately.
190            if self.cached_pieces.read().next_offset.is_none() {
191                return Ok(false);
192            };
193
194            // Then, if there was free space, acquire a write lock, and check for intervening
195            // writes.
196            let mut cached_pieces = self.cached_pieces.write();
197            let Some(next_offset) = cached_pieces.next_offset else {
198                return Ok(false);
199            };
200
201            let offset = next_offset;
202            cached_pieces.next_offset = offset.checked_sub(1);
203            offset
204        };
205
206        let Some(sectors_metadata) = self.sectors_metadata.upgrade() else {
207            // Metadata has been dropped, farm or process is shutting down
208            return Ok(false);
209        };
210
211        let element_offset = u64::from(offset) * u64::from(Self::element_size());
212        let sectors_metadata = sectors_metadata.read().await;
213        let plotted_sectors_count = sectors_metadata.len() as u16;
214        let plotted_bytes = self.sector_size * u64::from(plotted_sectors_count);
215
216        // Make sure offset is after anything that is already plotted
217        if element_offset < plotted_bytes {
218            // Just to be safe, avoid any overlap of read and write locks
219            drop(sectors_metadata);
220            let mut cached_pieces = self.cached_pieces.write();
221            // No space to store more pieces anymore
222            cached_pieces.next_offset.take();
223            if plotted_sectors_count == self.target_sector_count {
224                // Free allocated memory once fully plotted
225                mem::take(&mut cached_pieces.map);
226            }
227            return Ok(false);
228        }
229
230        let Some(file) = self.file.upgrade() else {
231            // File has been dropped, farm or process is shutting down
232            return Ok(false);
233        };
234
235        trace!(
236            %offset,
237            ?piece_index,
238            %plotted_sectors_count,
239            "Found available piece cache free space offset, writing piece",
240        );
241
242        let write_fut = tokio::task::spawn_blocking({
243            let piece_index_bytes = piece_index.to_bytes();
244            // File writes are read/write/modify internally, so combine all data here for more
245            // efficient write
246            let mut bytes = Vec::with_capacity(PieceIndex::SIZE + piece.len() + Blake3Hash::SIZE);
247            bytes.extend_from_slice(&piece_index_bytes);
248            bytes.extend_from_slice(piece.as_ref());
249            bytes.extend_from_slice(
250                {
251                    let mut hasher = blake3::Hasher::new();
252                    hasher.update(&piece_index_bytes);
253                    hasher.update(piece.as_ref());
254                    hasher.finalize()
255                }
256                .as_bytes(),
257            );
258
259            move || file.write_all_at(&bytes, element_offset)
260        });
261
262        AsyncJoinOnDrop::new(write_fut, false).await??;
263
264        // Just to be safe, avoid any overlap of read and write locks
265        drop(sectors_metadata);
266        // Store newly written piece in the map
267        self.cached_pieces
268            .write()
269            .map
270            .insert(RecordKey::from(piece_index.to_multihash()), offset);
271
272        Ok(true)
273    }
274
275    /// Read piece from cache.
276    ///
277    /// Returns `None` if not cached.
278    pub(crate) async fn read_piece(&self, key: &RecordKey) -> Option<Piece> {
279        let offset = self.cached_pieces.read().map.get(key).copied()?;
280
281        let file = self.file.upgrade()?;
282
283        let read_fn = move || {
284            let mut element = BytesMut::zeroed(Self::element_size() as usize);
285            if let Ok(Some(_piece_index)) = Self::read_piece_internal(&file, offset, &mut element) {
286                let element = element.freeze();
287                let piece =
288                    Piece::try_from(element.slice_ref(&element[PieceIndex::SIZE..][..Piece::SIZE]))
289                        .expect("Correct length; qed");
290                Some(piece)
291            } else {
292                None
293            }
294        };
295        // TODO: On Windows spawning blocking task that allows concurrent reads causes huge memory
296        //  usage. No idea why it happens, but not spawning anything at all helps for some reason.
297        //  Someone at some point should figure it out and fix, but it will probably be not me
298        //  (Nazar).
299        //  See https://github.com/autonomys/subspace/issues/2813 and linked forum post for details.
300        //  This TODO exists in multiple files
301        let maybe_piece = if cfg!(windows) {
302            task::block_in_place(read_fn)
303        } else {
304            let read_fut = task::spawn_blocking(read_fn);
305
306            AsyncJoinOnDrop::new(read_fut, false)
307                .await
308                .unwrap_or_default()
309        };
310
311        if maybe_piece.is_none()
312            && let Some(sectors_metadata) = self.sectors_metadata.upgrade()
313        {
314            let plotted_sectors_count = sectors_metadata.read().await.len() as u16;
315
316            let mut cached_pieces = self.cached_pieces.write();
317            if plotted_sectors_count == self.target_sector_count {
318                // Free allocated memory once fully plotted
319                mem::take(&mut cached_pieces.map);
320            } else {
321                // Remove entry just in case it was overridden with a sector already
322                cached_pieces.map.remove(key);
323            }
324        }
325
326        maybe_piece
327    }
328
329    fn read_piece_internal(
330        file: &DirectIoFileWrapper,
331        offset: u32,
332        element: &mut [u8],
333    ) -> Result<Option<PieceIndex>, DiskPlotCacheError> {
334        file.read_exact_at(element, u64::from(offset) * u64::from(Self::element_size()))?;
335
336        let (piece_index_bytes, remaining_bytes) = element.split_at(PieceIndex::SIZE);
337        let (piece_bytes, expected_checksum) = remaining_bytes.split_at(Piece::SIZE);
338
339        // Verify checksum
340        let actual_checksum = {
341            let mut hasher = blake3::Hasher::new();
342            hasher.update(piece_index_bytes);
343            hasher.update(piece_bytes);
344            *hasher.finalize().as_bytes()
345        };
346        if actual_checksum != expected_checksum {
347            if element.iter().all(|&byte| byte == 0) {
348                return Ok(None);
349            }
350
351            debug!(
352                actual_checksum = %hex::encode(actual_checksum),
353                expected_checksum = %hex::encode(expected_checksum),
354                "Hash doesn't match, corrupted or overridden piece in cache"
355            );
356
357            return Err(DiskPlotCacheError::ChecksumMismatch);
358        }
359
360        let piece_index = PieceIndex::from_bytes(
361            piece_index_bytes
362                .try_into()
363                .expect("Statically known to have correct size; qed"),
364        );
365        Ok(Some(piece_index))
366    }
367}