Skip to main content

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] 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 / u64::from(Self::element_size())) as u32;
102            let to_offset = (file_size / u64::from(Self::element_size())) 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) => {
107                        if let Some(piece_index) = maybe_piece_index {
108                            map.insert(RecordKey::from(piece_index.to_multihash()), offset);
109                        } else {
110                            next_offset.replace(offset);
111                            break;
112                        }
113                    }
114                    Err(DiskPlotCacheError::ChecksumMismatch) => {
115                        next_offset.replace(offset);
116                        break;
117                    }
118                    Err(error) => {
119                        warn!(%error, %offset, "Failed to read plot cache element");
120                        break;
121                    }
122                }
123            }
124
125            CachedPieces { map, next_offset }
126        };
127
128        info!("Finished checking plot cache contents");
129
130        Self {
131            file: Arc::downgrade(file),
132            sectors_metadata: Arc::downgrade(sectors_metadata),
133            cached_pieces: Arc::new(RwLock::new(cached_pieces)),
134            target_sector_count,
135            sector_size,
136        }
137    }
138
139    /// Size of a single plot cache element
140    pub(crate) const fn element_size() -> u32 {
141        (PieceIndex::SIZE + Piece::SIZE + Blake3Hash::SIZE) as u32
142    }
143
144    /// Check if piece is potentially stored in this cache (not guaranteed to be because it might be
145    /// overridden with sector any time)
146    pub(crate) fn is_piece_maybe_stored(&self, key: &RecordKey) -> MaybePieceStoredResult {
147        let offset = {
148            let cached_pieces = self.cached_pieces.read();
149
150            let Some(offset) = cached_pieces.map.get(key).copied() else {
151                return if cached_pieces.next_offset.is_some() {
152                    MaybePieceStoredResult::Vacant
153                } else {
154                    MaybePieceStoredResult::No
155                };
156            };
157
158            offset
159        };
160
161        let Some(sectors_metadata) = self.sectors_metadata.upgrade() else {
162            return MaybePieceStoredResult::No;
163        };
164
165        let element_offset = u64::from(offset) * u64::from(Self::element_size());
166        // Blocking read is fine because writes in farmer are very rare and very brief
167        let plotted_bytes = self.sector_size * sectors_metadata.read_blocking().len() as u64;
168
169        // Make sure offset is after anything that is already plotted
170        if element_offset < plotted_bytes {
171            // Remove entry since it was overwritten with a sector already
172            self.cached_pieces.write().map.remove(key);
173            MaybePieceStoredResult::No
174        } else {
175            MaybePieceStoredResult::Yes
176        }
177    }
178
179    /// Store piece in cache if there is free space, and return `Ok(true)`.
180    /// Returns `Ok(false)` if there is no free space, or the farm or process is shutting down.
181    pub(crate) async fn try_store_piece(
182        &self,
183        piece_index: PieceIndex,
184        piece: &Piece,
185    ) -> Result<bool, DiskPlotCacheError> {
186        let offset = {
187            // First, do a quick concurrent check for free space with a read lock, dropping it
188            // immediately.
189            if self.cached_pieces.read().next_offset.is_none() {
190                return Ok(false);
191            }
192
193            // Then, if there was free space, acquire a write lock, and check for intervening
194            // writes.
195            let mut cached_pieces = self.cached_pieces.write();
196            let Some(next_offset) = cached_pieces.next_offset else {
197                return Ok(false);
198            };
199
200            let offset = next_offset;
201            cached_pieces.next_offset = offset.checked_sub(1);
202            offset
203        };
204
205        let Some(sectors_metadata) = self.sectors_metadata.upgrade() else {
206            // Metadata has been dropped, farm or process is shutting down
207            return Ok(false);
208        };
209
210        let element_offset = u64::from(offset) * u64::from(Self::element_size());
211        let sectors_metadata = sectors_metadata.read().await;
212        let plotted_sectors_count = sectors_metadata.len() as u16;
213        let plotted_bytes = self.sector_size * u64::from(plotted_sectors_count);
214
215        // Make sure offset is after anything that is already plotted
216        if element_offset < plotted_bytes {
217            // Just to be safe, avoid any overlap of read and write locks
218            drop(sectors_metadata);
219            let mut cached_pieces = self.cached_pieces.write();
220            // No space to store more pieces anymore
221            cached_pieces.next_offset.take();
222            if plotted_sectors_count == self.target_sector_count {
223                // Free allocated memory once fully plotted
224                mem::take(&mut cached_pieces.map);
225            }
226            return Ok(false);
227        }
228
229        let Some(file) = self.file.upgrade() else {
230            // File has been dropped, farm or process is shutting down
231            return Ok(false);
232        };
233
234        trace!(
235            %offset,
236            ?piece_index,
237            %plotted_sectors_count,
238            "Found available piece cache free space offset, writing piece",
239        );
240
241        let write_fut = task::spawn_blocking({
242            let piece_index_bytes = piece_index.to_bytes();
243            // File writes are read/write/modify internally, so combine all data here for more
244            // efficient write
245            let mut bytes = Vec::with_capacity(PieceIndex::SIZE + Piece::SIZE + Blake3Hash::SIZE);
246            bytes.extend_from_slice(&piece_index_bytes);
247            bytes.extend_from_slice(piece.as_ref());
248            bytes.extend_from_slice(
249                {
250                    let mut hasher = blake3::Hasher::new();
251                    hasher.update(&piece_index_bytes);
252                    hasher.update(piece.as_ref());
253                    hasher.finalize()
254                }
255                .as_bytes(),
256            );
257
258            move || file.write_all_at(&bytes, element_offset)
259        });
260
261        AsyncJoinOnDrop::new(write_fut, false).await??;
262
263        // Just to be safe, avoid any overlap of read and write locks
264        drop(sectors_metadata);
265        // Store newly written piece in the map
266        self.cached_pieces
267            .write()
268            .map
269            .insert(RecordKey::from(piece_index.to_multihash()), offset);
270
271        Ok(true)
272    }
273
274    /// Read piece from cache.
275    ///
276    /// Returns `None` if not cached.
277    pub(crate) async fn read_piece(&self, key: &RecordKey) -> Option<Piece> {
278        let offset = self.cached_pieces.read().map.get(key).copied()?;
279
280        let file = self.file.upgrade()?;
281
282        let read_fn = move || {
283            let mut element = BytesMut::zeroed(Self::element_size() as usize);
284            if let Ok(Some(_piece_index)) = Self::read_piece_internal(&file, offset, &mut element) {
285                let element = element.freeze();
286                let piece =
287                    Piece::try_from(element.slice_ref(&element[PieceIndex::SIZE..][..Piece::SIZE]))
288                        .expect("Correct length; qed");
289                Some(piece)
290            } else {
291                None
292            }
293        };
294        // TODO: On Windows spawning blocking task that allows concurrent reads causes huge memory
295        //  usage. No idea why it happens, but not spawning anything at all helps for some reason.
296        //  Someone at some point should figure it out and fix, but it will probably be not me
297        //  (Nazar).
298        //  See https://github.com/autonomys/subspace/issues/2813 and linked forum post for details.
299        //  This TODO exists in multiple files
300        let maybe_piece = if cfg!(windows) {
301            task::block_in_place(read_fn)
302        } else {
303            let read_fut = task::spawn_blocking(read_fn);
304
305            AsyncJoinOnDrop::new(read_fut, false)
306                .await
307                .unwrap_or_default()
308        };
309
310        if maybe_piece.is_none()
311            && let Some(sectors_metadata) = self.sectors_metadata.upgrade()
312        {
313            let plotted_sectors_count = sectors_metadata.read().await.len() as u16;
314
315            let mut cached_pieces = self.cached_pieces.write();
316            if plotted_sectors_count == self.target_sector_count {
317                // Free allocated memory once fully plotted
318                mem::take(&mut cached_pieces.map);
319            } else {
320                // Remove entry just in case it was overridden with a sector already
321                cached_pieces.map.remove(key);
322            }
323        }
324
325        maybe_piece
326    }
327
328    fn read_piece_internal(
329        file: &DirectIoFileWrapper,
330        offset: u32,
331        element: &mut [u8],
332    ) -> Result<Option<PieceIndex>, DiskPlotCacheError> {
333        file.read_exact_at(element, u64::from(offset) * u64::from(Self::element_size()))?;
334
335        let (piece_index_bytes, remaining_bytes) = element.split_at(PieceIndex::SIZE);
336        let (piece_bytes, expected_checksum) = remaining_bytes.split_at(Piece::SIZE);
337
338        // Verify checksum
339        let actual_checksum = {
340            let mut hasher = blake3::Hasher::new();
341            hasher.update(piece_index_bytes);
342            hasher.update(piece_bytes);
343            *hasher.finalize().as_bytes()
344        };
345        if actual_checksum != expected_checksum {
346            if element.iter().all(|&byte| byte == 0) {
347                return Ok(None);
348            }
349
350            debug!(
351                actual_checksum = %hex::encode(actual_checksum),
352                expected_checksum = %hex::encode(expected_checksum),
353                "Hash doesn't match, corrupted or overridden piece in cache"
354            );
355
356            return Err(DiskPlotCacheError::ChecksumMismatch);
357        }
358
359        let piece_index = PieceIndex::from_bytes(
360            piece_index_bytes
361                .try_into()
362                .expect("Statically known to have correct size; qed"),
363        );
364        Ok(Some(piece_index))
365    }
366}