Skip to main content

ab_farmer/single_disk_farm/
plotting.rs

1#[cfg(test)]
2mod tests;
3
4use crate::farm::{SectorExpirationDetails, SectorPlottingDetails, SectorUpdate};
5use crate::node_client::NodeClient;
6use crate::plotter::{Plotter, SectorPlottingProgress};
7use crate::single_disk_farm::metrics::{SectorState, SingleDiskFarmMetrics};
8use crate::single_disk_farm::{
9    BackgroundTaskError, Handlers, PlotMetadataHeader, RESERVED_PLOT_METADATA,
10};
11use ab_core_primitives::ed25519::Ed25519PublicKey;
12use ab_core_primitives::hashes::Blake3Hash;
13use ab_core_primitives::pieces::PieceOffset;
14use ab_core_primitives::sectors::{SectorId, SectorIndex};
15use ab_core_primitives::segments::{HistorySize, SegmentIndex};
16use ab_direct_io_file::{DirectIoFile, IoBufError, OwnedPages};
17use ab_farmer_components::plotting::PlottedSector;
18use ab_farmer_components::sector::SectorMetadataChecksummed;
19use ab_farmer_components::shard_commitment::ShardCommitmentsRootsCache;
20use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock, Semaphore, SemaphoreGuard};
21use futures::channel::{mpsc, oneshot};
22use futures::stream::FuturesOrdered;
23use futures::{FutureExt, SinkExt, StreamExt, select};
24use parking_lot::RwLock;
25use rand::prelude::*;
26use std::collections::HashSet;
27use std::future::Future;
28use std::io;
29use std::num::NonZeroUsize;
30use std::ops::Range;
31use std::pin::pin;
32use std::sync::Arc as StdArc;
33use std::time::{Duration, Instant};
34use thiserror::Error;
35use tokio::sync::watch;
36use tokio::task;
37use tracing::{Instrument, debug, info, info_span, trace, warn};
38use triomphe::Arc;
39
40const FARMER_APP_INFO_RETRY_INTERVAL: Duration = Duration::from_millis(500);
41const PLOTTING_RETRY_DELAY: Duration = Duration::from_secs(1);
42
43pub(super) struct SectorToPlot {
44    sector_index: SectorIndex,
45    /// Progress so far in % (not including this sector)
46    progress: f32,
47    /// Whether this is the last sector queued so far
48    last_queued: bool,
49    acknowledgement_sender: oneshot::Sender<()>,
50}
51
52/// Errors that happen during plotting
53#[derive(Debug, Error)]
54pub enum PlottingError {
55    /// Failed to retrieve farmer info
56    #[error("Failed to retrieve farmer info: {error}")]
57    FailedToGetFarmerInfo {
58        /// Lower-level error
59        error: anyhow::Error,
60    },
61    /// Failed to get super segment root
62    #[error("Failed to get super segment root: {error}")]
63    FailedToGetSuperSegmentRoot {
64        /// Lower-level error
65        error: anyhow::Error,
66    },
67    /// Missing archived segment header
68    #[error("Missing archived segment header: {segment_index}")]
69    MissingArchivedSegmentHeader {
70        /// Segment index that was missing
71        segment_index: SegmentIndex,
72    },
73    /// Failed to subscribe to archived segments
74    #[error("Failed to subscribe to archived segments: {error}")]
75    FailedToSubscribeArchivedSegments {
76        /// Lower-level error
77        error: anyhow::Error,
78    },
79    /// Low-level plotting error
80    #[error("Low-level plotting error: {0}")]
81    LowLevel(String),
82    /// I/O error occurred
83    #[error("Plotting I/O error: {0}")]
84    Io(#[from] io::Error),
85    /// Background downloading panicked
86    #[error("Background downloading panicked")]
87    BackgroundDownloadingPanicked,
88}
89
90impl<B> From<IoBufError<B>> for PlottingError {
91    #[inline]
92    fn from(error: IoBufError<B>) -> Self {
93        Self::Io(error.into())
94    }
95}
96
97pub(super) struct SectorPlottingOptions<'a, NC> {
98    pub(super) public_key: Ed25519PublicKey,
99    pub(super) shard_commitments_roots_cache: ShardCommitmentsRootsCache,
100    pub(super) node_client: &'a NC,
101    pub(super) pieces_in_sector: u16,
102    pub(super) sector_size: usize,
103    pub(super) plot_file: StdArc<DirectIoFile>,
104    pub(super) metadata_file: Arc<DirectIoFile>,
105    pub(super) handlers: &'a Handlers,
106    pub(super) global_mutex: &'a AsyncMutex<()>,
107    pub(super) plotter: StdArc<dyn Plotter>,
108    pub(super) metrics: Option<Arc<SingleDiskFarmMetrics>>,
109}
110
111pub(super) struct PlottingOptions<'a, NC> {
112    pub(super) metadata_header: PlotMetadataHeader,
113    pub(super) sectors_metadata: &'a AsyncRwLock<Vec<SectorMetadataChecksummed>>,
114    pub(super) sectors_being_modified: &'a AsyncRwLock<HashSet<SectorIndex>>,
115    pub(super) sectors_to_plot_receiver: mpsc::Receiver<SectorToPlot>,
116    pub(super) sector_plotting_options: SectorPlottingOptions<'a, NC>,
117    pub(super) max_plotting_sectors_per_farm: NonZeroUsize,
118}
119
120/// Starts plotting process.
121///
122/// NOTE: Returned future is async, but does blocking operations and should be running in dedicated
123/// thread.
124pub(super) async fn plotting<NC>(
125    plotting_options: PlottingOptions<'_, NC>,
126) -> Result<(), PlottingError>
127where
128    NC: NodeClient,
129{
130    let PlottingOptions {
131        mut metadata_header,
132        sectors_metadata,
133        sectors_being_modified,
134        mut sectors_to_plot_receiver,
135        sector_plotting_options,
136        max_plotting_sectors_per_farm,
137    } = plotting_options;
138
139    let sector_plotting_options = &sector_plotting_options;
140    let plotting_semaphore = Semaphore::new(max_plotting_sectors_per_farm.get());
141    let max_used_history_size = RwLock::new(
142        sectors_metadata
143            .read()
144            .await
145            .iter()
146            .map(|sector_metadata| sector_metadata.history_size)
147            .max(),
148    );
149    let mut sectors_being_plotted = FuturesOrdered::new();
150    // Channel size is intentionally unbounded for easier analysis, but it is bounded by plotting
151    // semaphore in practice due to permit stored in `SectorPlottingResult`
152    let (sector_plotting_result_sender, mut sector_plotting_result_receiver) = mpsc::unbounded();
153    let process_plotting_result_fut = async move {
154        while let Some(sector_plotting_result) = sector_plotting_result_receiver.next().await {
155            process_plotting_result(
156                sector_plotting_result,
157                sectors_metadata,
158                sectors_being_modified,
159                &mut metadata_header,
160                Arc::clone(&sector_plotting_options.metadata_file),
161            )
162            .await?;
163        }
164
165        unreachable!(
166            "Stream will not end before the rest of the plotting process is shutting down"
167        );
168    };
169    let process_plotting_result_fut = process_plotting_result_fut.fuse();
170    let mut process_plotting_result_fut = pin!(process_plotting_result_fut);
171
172    // Wait for new sectors to plot from `sectors_to_plot_receiver` and wait for sectors that
173    // already started plotting to finish plotting and then update metadata header
174    loop {
175        select! {
176            maybe_sector_to_plot = sectors_to_plot_receiver.next() => {
177                let Some(sector_to_plot) = maybe_sector_to_plot else {
178                    break;
179                };
180
181                let sector_index = sector_to_plot.sector_index;
182                let sector_plotting_init_fut = plot_single_sector(
183                    sector_to_plot,
184                    sector_plotting_options,
185                    sectors_metadata,
186                    sectors_being_modified,
187                    &plotting_semaphore,
188                    &max_used_history_size,
189                )
190                    .instrument(info_span!("", %sector_index))
191                    .fuse();
192                let mut sector_plotting_init_fut = pin!(sector_plotting_init_fut);
193
194                // Wait for plotting of new sector to start (backpressure), while also waiting
195                // for sectors that already started plotting to finish plotting and then update
196                // metadata header
197                loop {
198                    select! {
199                        sector_plotting_init_result = sector_plotting_init_fut => {
200                            let sector_plotting_fut = match sector_plotting_init_result {
201                                PlotSingleSectorResult::Scheduled(future) => future,
202                                PlotSingleSectorResult::Skipped => {
203                                    break;
204                                }
205                                PlotSingleSectorResult::FatalError(error) => {
206                                    return Err(error);
207                                }
208                            };
209                            sectors_being_plotted.push_back(
210                                sector_plotting_fut.instrument(info_span!("", %sector_index))
211                            );
212                            break;
213                        }
214                        maybe_sector_plotting_result = sectors_being_plotted.select_next_some() => {
215                            sector_plotting_result_sender
216                                .unbounded_send(maybe_sector_plotting_result?)
217                                .expect("Sending means receiver is not dropped yet; qed");
218                        }
219                        result = process_plotting_result_fut => {
220                            return result;
221                        }
222                    }
223                }
224            }
225            maybe_sector_plotting_result = sectors_being_plotted.select_next_some() => {
226                sector_plotting_result_sender
227                    .unbounded_send(maybe_sector_plotting_result?)
228                    .expect("Sending means receiver is not dropped yet; qed");
229            }
230            result = process_plotting_result_fut => {
231                return result;
232            }
233        }
234    }
235
236    Ok(())
237}
238
239async fn process_plotting_result(
240    sector_plotting_result: SectorPlottingResult<'_>,
241    sectors_metadata: &AsyncRwLock<Vec<SectorMetadataChecksummed>>,
242    sectors_being_modified: &AsyncRwLock<HashSet<SectorIndex>>,
243    metadata_header: &mut PlotMetadataHeader,
244    metadata_file: Arc<DirectIoFile>,
245) -> Result<(), PlottingError> {
246    let SectorPlottingResult {
247        sector_metadata,
248        replotting,
249        last_queued,
250        plotting_permit,
251    } = sector_plotting_result;
252
253    let sector_index = sector_metadata.sector_index;
254
255    {
256        let mut sectors_metadata = sectors_metadata.write().await;
257        // If exists then we're replotting, otherwise we create sector for the first time
258        if let Some(existing_sector_metadata) = sectors_metadata.get_mut(usize::from(sector_index))
259        {
260            *existing_sector_metadata = sector_metadata;
261        } else {
262            sectors_metadata.push(sector_metadata);
263        }
264    }
265
266    // Inform others that this sector is no longer being modified
267    sectors_being_modified.write().await.remove(&sector_index);
268
269    if u16::from(sector_index) + 1 > metadata_header.plotted_sector_count {
270        metadata_header.plotted_sector_count = u16::from(sector_index) + 1;
271
272        let encoded_metadata_header = metadata_header.encode_page();
273        let write_fut =
274            task::spawn_blocking(move || metadata_file.write_at(encoded_metadata_header, 0));
275        write_fut.await.map_err(|error| {
276            PlottingError::LowLevel(format!("Failed to spawn blocking tokio task: {error}"))
277        })??;
278    }
279
280    if last_queued {
281        if replotting {
282            info!("Replotting complete");
283        } else {
284            info!("Initial plotting complete");
285        }
286    }
287
288    drop(plotting_permit);
289
290    Ok(())
291}
292
293enum PlotSingleSectorResult<F> {
294    Scheduled(F),
295    Skipped,
296    FatalError(PlottingError),
297}
298
299struct SectorPlottingResult<'a> {
300    sector_metadata: SectorMetadataChecksummed,
301    replotting: bool,
302    last_queued: bool,
303    plotting_permit: SemaphoreGuard<'a>,
304}
305
306/// Select the history size to plot a sector at.
307///
308/// The max history size used so far is maintained unless it is too old. This reduces the diversity
309/// of shard assignment, making it easier for farmers to run nodes. The current history size is
310/// used instead when nothing was plotted yet, when the sector being replotted was plotted at the
311/// max used history size, and when the max used history size is too old: a sector plotted at it
312/// may already be expired or about to expire by the same margin replotting uses, so it would have
313/// to be replotted right away.
314fn select_history_size(
315    max_used_history_size: Option<HistorySize>,
316    old_sector_history_size: Option<HistorySize>,
317    current_history_size: HistorySize,
318    min_sector_lifetime: HistorySize,
319) -> HistorySize {
320    if let Some(max_used_history_size) = max_used_history_size
321        && old_sector_history_size != Some(max_used_history_size)
322        && let Some(expiration_check_history_size) =
323            max_used_history_size.sector_expiration_check(min_sector_lifetime)
324        && expiration_check_history_size.segment_index()
325            > current_history_size.segment_index() + SegmentIndex::ONE
326    {
327        max_used_history_size
328    } else {
329        current_history_size
330    }
331}
332
333async fn plot_single_sector<'a, NC>(
334    sector_to_plot: SectorToPlot,
335    sector_plotting_options: &'a SectorPlottingOptions<'a, NC>,
336    sectors_metadata: &'a AsyncRwLock<Vec<SectorMetadataChecksummed>>,
337    sectors_being_modified: &'a AsyncRwLock<HashSet<SectorIndex>>,
338    plotting_semaphore: &'a Semaphore,
339    max_used_history_size: &RwLock<Option<HistorySize>>,
340) -> PlotSingleSectorResult<
341    impl Future<Output = Result<SectorPlottingResult<'a>, PlottingError>> + 'a,
342>
343where
344    NC: NodeClient,
345{
346    let SectorPlottingOptions {
347        public_key,
348        shard_commitments_roots_cache,
349        node_client,
350        pieces_in_sector,
351        sector_size,
352        plot_file,
353        metadata_file,
354        handlers,
355        global_mutex,
356        plotter,
357        metrics,
358    } = sector_plotting_options;
359
360    let SectorToPlot {
361        sector_index,
362        progress,
363        last_queued,
364        acknowledgement_sender: _acknowledgement_sender,
365    } = sector_to_plot;
366    trace!("Preparing to plot sector");
367
368    // Inform others that this sector is being modified
369    {
370        let mut sectors_being_modified = sectors_being_modified.write().await;
371        if !sectors_being_modified.insert(sector_index) {
372            debug!("Skipped sector plotting, it is already in progress");
373            return PlotSingleSectorResult::Skipped;
374        }
375    }
376
377    let plotting_permit = plotting_semaphore.acquire().await;
378
379    let maybe_old_sector_metadata = sectors_metadata
380        .read()
381        .await
382        .get(usize::from(sector_index))
383        .cloned();
384    let replotting = maybe_old_sector_metadata.is_some();
385
386    if let Some(metrics) = metrics {
387        metrics.sector_plotting.inc();
388    }
389    let sector_state = SectorUpdate::Plotting(SectorPlottingDetails::Starting {
390        progress,
391        replotting,
392        last_queued,
393    });
394    handlers
395        .sector_update
396        .call_simple(&(sector_index, sector_state));
397
398    let start = Instant::now();
399
400    // This `loop` is a workaround for an edge-case in local setup if expiration is configured to 1.
401    // In that scenario we get a replotting notification essentially straight from a block import
402    // pipeline of the node, before the block is imported. This can result in a later request for
403    // farmer app info to return old data, meaning we're replotting exactly the same sector that
404    // just expired.
405    let mut protocol_info = loop {
406        let protocol_info = match node_client.farmer_app_info().await {
407            Ok(farmer_app_info) => farmer_app_info.protocol_info,
408            Err(error) => {
409                return PlotSingleSectorResult::FatalError(PlottingError::FailedToGetFarmerInfo {
410                    error,
411                });
412            }
413        };
414
415        if let Some(old_sector_metadata) = &maybe_old_sector_metadata
416            && protocol_info.history_size <= old_sector_metadata.history_size
417        {
418            if protocol_info.min_sector_lifetime == HistorySize::ONE {
419                debug!(
420                    current_history_size = %protocol_info.history_size,
421                    old_sector_history_size = %old_sector_metadata.history_size,
422                    "Latest protocol history size is not yet newer than old sector history \
423                    size, wait for a bit and try again"
424                );
425                tokio::time::sleep(FARMER_APP_INFO_RETRY_INTERVAL).await;
426                continue;
427            }
428
429            debug!(
430                current_history_size = %protocol_info.history_size,
431                old_sector_history_size = %old_sector_metadata.history_size,
432                "Skipped sector plotting, likely redundant due to redundant archived \
433                segment notification"
434            );
435            return PlotSingleSectorResult::Skipped;
436        }
437
438        break protocol_info;
439    };
440
441    {
442        let mut max_used_history_size = max_used_history_size.write();
443        protocol_info.history_size = select_history_size(
444            *max_used_history_size,
445            maybe_old_sector_metadata
446                .as_ref()
447                .map(|sector_metadata| sector_metadata.history_size),
448            protocol_info.history_size,
449            protocol_info.min_sector_lifetime,
450        );
451        max_used_history_size.replace(protocol_info.history_size);
452    }
453
454    let (progress_sender, mut progress_receiver) = mpsc::channel(10);
455    let shard_commitments_root = shard_commitments_roots_cache.get(protocol_info.history_size);
456
457    // Initiate plotting
458    plotter
459        .plot_sector(
460            *public_key,
461            shard_commitments_root,
462            sector_index,
463            protocol_info,
464            *pieces_in_sector,
465            replotting,
466            progress_sender,
467        )
468        .await;
469
470    if replotting {
471        info!("Replotting sector ({progress:.2}% complete)");
472    } else {
473        info!("Plotting sector ({progress:.2}% complete)");
474    }
475
476    PlotSingleSectorResult::Scheduled(async move {
477        let plotted_sector = loop {
478            match plot_single_sector_internal(
479                sector_index,
480                *sector_size,
481                plot_file,
482                metadata_file,
483                handlers,
484                global_mutex,
485                progress_receiver,
486                metrics.as_ref(),
487            )
488            .await?
489            {
490                Ok(plotted_sector) => {
491                    break plotted_sector;
492                }
493                Err(error) => {
494                    warn!(
495                        %error,
496                        "Failed to plot sector, retrying in {PLOTTING_RETRY_DELAY:?}"
497                    );
498
499                    tokio::time::sleep(PLOTTING_RETRY_DELAY).await;
500                }
501            }
502
503            let (retry_progress_sender, retry_progress_receiver) = mpsc::channel(10);
504            progress_receiver = retry_progress_receiver;
505
506            // Initiate plotting
507            plotter
508                .plot_sector(
509                    *public_key,
510                    shard_commitments_root,
511                    sector_index,
512                    protocol_info,
513                    *pieces_in_sector,
514                    replotting,
515                    retry_progress_sender,
516                )
517                .await;
518
519            if replotting {
520                info!("Replotting sector retry");
521            } else {
522                info!("Plotting sector retry");
523            }
524        };
525
526        let maybe_old_plotted_sector = maybe_old_sector_metadata.map(|old_sector_metadata| {
527            let old_history_size = old_sector_metadata.history_size;
528
529            PlottedSector {
530                sector_id: plotted_sector.sector_id,
531                sector_index: plotted_sector.sector_index,
532                sector_metadata: old_sector_metadata,
533                piece_indexes: {
534                    let mut piece_indexes = Vec::with_capacity(usize::from(*pieces_in_sector));
535                    (PieceOffset::ZERO..)
536                        .take(usize::from(*pieces_in_sector))
537                        .map(|piece_offset| {
538                            plotted_sector.sector_id.derive_piece_index(
539                                piece_offset,
540                                old_history_size,
541                                protocol_info.max_pieces_in_sector,
542                                protocol_info.recent_segments,
543                                protocol_info.recent_history_fraction,
544                            )
545                        })
546                        .collect_into(&mut piece_indexes);
547                    piece_indexes
548                },
549            }
550        });
551
552        if replotting {
553            debug!("Sector replotted successfully");
554        } else {
555            debug!("Sector plotted successfully");
556        }
557
558        let sector_metadata = plotted_sector.sector_metadata.clone();
559
560        let time = start.elapsed();
561        if let Some(metrics) = metrics {
562            metrics.sector_plotting_time.observe(time.as_secs_f64());
563            metrics.sector_plotted.inc();
564            metrics.update_sector_state(SectorState::Plotted);
565        }
566        let sector_state = SectorUpdate::Plotting(SectorPlottingDetails::Finished {
567            plotted_sector,
568            old_plotted_sector: maybe_old_plotted_sector,
569            time,
570        });
571        handlers
572            .sector_update
573            .call_simple(&(sector_index, sector_state));
574
575        Ok(SectorPlottingResult {
576            sector_metadata,
577            replotting,
578            last_queued,
579            plotting_permit,
580        })
581    })
582}
583
584/// Outer error is used to indicate irrecoverable plotting errors, while inner result is for
585/// recoverable errors
586#[expect(clippy::too_many_arguments, reason = "Internal API")]
587async fn plot_single_sector_internal(
588    sector_index: SectorIndex,
589    sector_size: usize,
590    plot_file: &StdArc<DirectIoFile>,
591    metadata_file: &Arc<DirectIoFile>,
592    handlers: &Handlers,
593    global_mutex: &AsyncMutex<()>,
594    mut progress_receiver: mpsc::Receiver<SectorPlottingProgress>,
595    metrics: Option<&Arc<SingleDiskFarmMetrics>>,
596) -> Result<Result<PlottedSector, PlottingError>, PlottingError> {
597    // Process plotting progress notifications
598    let progress_processor_fut = async {
599        while let Some(progress) = progress_receiver.next().await {
600            match progress {
601                SectorPlottingProgress::Downloading => {
602                    if let Some(metrics) = metrics {
603                        metrics.sector_downloading.inc();
604                    }
605                    handlers.sector_update.call_simple(&(
606                        sector_index,
607                        SectorUpdate::Plotting(SectorPlottingDetails::Downloading),
608                    ));
609                }
610                SectorPlottingProgress::Downloaded(time) => {
611                    if let Some(metrics) = metrics {
612                        metrics.sector_downloading_time.observe(time.as_secs_f64());
613                        metrics.sector_downloaded.inc();
614                    }
615                    handlers.sector_update.call_simple(&(
616                        sector_index,
617                        SectorUpdate::Plotting(SectorPlottingDetails::Downloaded(time)),
618                    ));
619                }
620                SectorPlottingProgress::Encoding => {
621                    if let Some(metrics) = metrics {
622                        metrics.sector_encoding.inc();
623                    }
624                    handlers.sector_update.call_simple(&(
625                        sector_index,
626                        SectorUpdate::Plotting(SectorPlottingDetails::Encoding),
627                    ));
628                }
629                SectorPlottingProgress::Encoded(time) => {
630                    if let Some(metrics) = metrics {
631                        metrics.sector_encoding_time.observe(time.as_secs_f64());
632                        metrics.sector_encoded.inc();
633                    }
634                    handlers.sector_update.call_simple(&(
635                        sector_index,
636                        SectorUpdate::Plotting(SectorPlottingDetails::Encoded(time)),
637                    ));
638                }
639                SectorPlottingProgress::Finished {
640                    plotted_sector,
641                    time: _,
642                    sector,
643                } => {
644                    return Ok((plotted_sector, sector));
645                }
646                SectorPlottingProgress::Error { error } => {
647                    if let Some(metrics) = metrics {
648                        metrics.sector_plotting_error.inc();
649                    }
650                    handlers.sector_update.call_simple(&(
651                        sector_index,
652                        SectorUpdate::Plotting(SectorPlottingDetails::Error(error.clone())),
653                    ));
654                    return Err(error);
655                }
656            }
657        }
658
659        Err("Plotting progress stream ended before plotting finished".to_string())
660    };
661
662    let (plotted_sector, mut sector) = match progress_processor_fut.await {
663        Ok(result) => result,
664        Err(error) => {
665            return Ok(Err(PlottingError::LowLevel(error)));
666        }
667    };
668
669    {
670        // Take mutex briefly to make sure writing is allowed right now
671        global_mutex.lock().await;
672
673        if let Some(metrics) = metrics {
674            metrics.sector_writing.inc();
675        }
676        handlers.sector_update.call_simple(&(
677            sector_index,
678            SectorUpdate::Plotting(SectorPlottingDetails::Writing),
679        ));
680
681        let start = Instant::now();
682
683        {
684            let sector_write_base_offset = u64::from(sector_index) * sector_size as u64;
685            let mut total_received = 0;
686            let mut sector_write_offset = sector_write_base_offset;
687            while let Some(maybe_sector_chunk) = sector.next().await {
688                let sector_chunk = match maybe_sector_chunk {
689                    Ok(sector_chunk) => sector_chunk,
690                    Err(error) => {
691                        return Ok(Err(PlottingError::LowLevel(format!(
692                            "Sector chunk receive error: {error}"
693                        ))));
694                    }
695                };
696
697                total_received += sector_chunk.len() as usize;
698
699                if total_received > sector_size {
700                    return Ok(Err(PlottingError::LowLevel(format!(
701                        "Received too many bytes {total_received} instead of expected \
702                        {sector_size} bytes"
703                    ))));
704                }
705
706                let sector_chunk_size = u64::from(sector_chunk.len());
707
708                trace!(sector_chunk_size, "Writing sector chunk to disk");
709                let write_fut = task::spawn_blocking({
710                    let plot_file = StdArc::clone(plot_file);
711
712                    move || plot_file.write_at(sector_chunk, sector_write_offset)
713                });
714                write_fut.await.map_err(|error| {
715                    PlottingError::LowLevel(format!("Failed to spawn blocking tokio task: {error}"))
716                })??;
717
718                sector_write_offset += sector_chunk_size;
719            }
720            drop(sector);
721
722            if total_received != sector_size {
723                return Ok(Err(PlottingError::LowLevel(format!(
724                    "Received only {total_received} sector bytes out of {sector_size} \
725                    expected bytes"
726                ))));
727            }
728        }
729        // Sector metadata is written after the sector on purpose. A sector is only (re)plotted when
730        // it is plotted for the first time, has expired or is corrupted, and in all those cases the
731        // old metadata is already invalid, so invalidating it before writing the sector would only
732        // increase write amplification.
733        {
734            let encoded_sector_metadata = plotted_sector.sector_metadata.encode_for_disk();
735            let sector_metadata_offset = RESERVED_PLOT_METADATA
736                + u64::from(sector_index)
737                    * u64::from(SectorMetadataChecksummed::DISK_PAGES)
738                    * u64::from(OwnedPages::ALIGN);
739            let write_fut = task::spawn_blocking({
740                let metadata_file = Arc::clone(metadata_file);
741
742                move || metadata_file.write_at(encoded_sector_metadata, sector_metadata_offset)
743            });
744            write_fut.await.map_err(|error| {
745                PlottingError::LowLevel(format!("Failed to spawn blocking tokio task: {error}"))
746            })??;
747        }
748
749        let time = start.elapsed();
750        if let Some(metrics) = metrics {
751            metrics.sector_writing_time.observe(time.as_secs_f64());
752            metrics.sector_written.inc();
753        }
754        handlers.sector_update.call_simple(&(
755            sector_index,
756            SectorUpdate::Plotting(SectorPlottingDetails::Written(time)),
757        ));
758    }
759
760    Ok(Ok(plotted_sector))
761}
762
763pub(super) struct PlottingSchedulerOptions<NC> {
764    pub(super) public_key_hash: Blake3Hash,
765    pub(super) shard_commitments_roots_cache: ShardCommitmentsRootsCache,
766    pub(super) sectors_indices_left_to_plot: Range<SectorIndex>,
767    pub(super) target_sector_count: u16,
768    pub(super) last_archived_segment_index: SegmentIndex,
769    pub(super) min_sector_lifetime: HistorySize,
770    pub(super) node_client: NC,
771    pub(super) handlers: Arc<Handlers>,
772    pub(super) sectors_metadata: StdArc<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
773    pub(super) sectors_to_plot_sender: mpsc::Sender<SectorToPlot>,
774    // Max delay between segment header being acknowledged by farmer and potentially
775    // triggering replotting
776    pub(super) new_segment_processing_delay: Duration,
777    pub(super) metrics: Option<Arc<SingleDiskFarmMetrics>>,
778}
779
780pub(super) async fn plotting_scheduler<NC>(
781    plotting_scheduler_options: PlottingSchedulerOptions<NC>,
782) -> Result<(), BackgroundTaskError>
783where
784    NC: NodeClient,
785{
786    let PlottingSchedulerOptions {
787        public_key_hash,
788        shard_commitments_roots_cache,
789        sectors_indices_left_to_plot,
790        target_sector_count,
791        last_archived_segment_index,
792        min_sector_lifetime,
793        node_client,
794        handlers,
795        sectors_metadata,
796        sectors_to_plot_sender,
797        new_segment_processing_delay,
798        metrics,
799    } = plotting_scheduler_options;
800
801    // Create a proxy channel with atomically updatable last archived segment that allows to not
802    // buffer messages from RPC subscription but also access the most recent value at any time
803    let (new_segment_index_sender, new_segment_index_receiver) =
804        watch::channel(last_archived_segment_index);
805
806    let read_new_super_segments_notifications_fut = read_new_segment_index_notifications(
807        &node_client,
808        new_segment_index_sender,
809        new_segment_processing_delay,
810    );
811
812    let send_plotting_notifications_fut = send_plotting_notifications(
813        public_key_hash,
814        &shard_commitments_roots_cache,
815        sectors_indices_left_to_plot,
816        target_sector_count,
817        min_sector_lifetime,
818        &node_client,
819        &handlers,
820        sectors_metadata,
821        new_segment_index_receiver,
822        sectors_to_plot_sender,
823        metrics.as_ref(),
824    );
825
826    select! {
827        result = read_new_super_segments_notifications_fut.fuse() => {
828            result
829        }
830        result = send_plotting_notifications_fut.fuse() => {
831            result
832        }
833    }
834}
835
836async fn read_new_segment_index_notifications<NC>(
837    node_client: &NC,
838    new_super_segments_sender: watch::Sender<SegmentIndex>,
839    new_segment_processing_delay: Duration,
840) -> Result<(), BackgroundTaskError>
841where
842    NC: NodeClient,
843{
844    info!("Subscribing to new super segments");
845
846    let mut super_segment_headers_notifications = node_client
847        .subscribe_new_super_segment_headers()
848        .await
849        .map_err(|error| PlottingError::FailedToSubscribeArchivedSegments { error })?;
850
851    while let Some(super_segment_header) = super_segment_headers_notifications.next().await {
852        debug!(?super_segment_header, "New super segment");
853
854        // There is no urgent need to rush replotting sectors immediately, and this delay allows for
855        // newly archived pieces to be both cached locally and on other farmers on the network
856        let delay = Duration::from_secs(rand::rng().random_range(
857            new_segment_processing_delay.as_secs() / 10..=new_segment_processing_delay.as_secs(),
858        ));
859        tokio::time::sleep(delay).await;
860
861        if new_super_segments_sender
862            .send(super_segment_header.max_segment_index.as_inner())
863            .is_err()
864        {
865            break;
866        }
867    }
868
869    Ok(())
870}
871
872struct SectorToReplot {
873    sector_index: SectorIndex,
874    expires_at: SegmentIndex,
875}
876
877#[expect(clippy::too_many_arguments, reason = "Internal API")]
878async fn send_plotting_notifications<NC>(
879    public_key_hash: Blake3Hash,
880    shard_commitments_roots_cache: &ShardCommitmentsRootsCache,
881    sectors_indices_left_to_plot: Range<SectorIndex>,
882    target_sector_count: u16,
883    min_sector_lifetime: HistorySize,
884    node_client: &NC,
885    handlers: &Handlers,
886    sectors_metadata: StdArc<AsyncRwLock<Vec<SectorMetadataChecksummed>>>,
887    mut new_segment_index_receiver: watch::Receiver<SegmentIndex>,
888    mut sectors_to_plot_sender: mpsc::Sender<SectorToPlot>,
889    metrics: Option<&Arc<SingleDiskFarmMetrics>>,
890) -> Result<(), BackgroundTaskError>
891where
892    NC: NodeClient,
893{
894    // Finish initial plotting if some sectors were not plotted fully yet
895    for sector_index in sectors_indices_left_to_plot {
896        let (acknowledgement_sender, acknowledgement_receiver) = oneshot::channel();
897        if let Err(error) = sectors_to_plot_sender
898            .send(SectorToPlot {
899                sector_index,
900                progress: f32::from(u16::from(sector_index)) / f32::from(target_sector_count)
901                    * 100.0,
902                last_queued: u16::from(sector_index) + 1 == target_sector_count,
903                acknowledgement_sender,
904            })
905            .await
906        {
907            warn!(%error, "Failed to send sector index for initial plotting");
908            return Ok(());
909        }
910
911        // We do not care if message was sent back or sender was just dropped
912        let _: Result<(), _> = acknowledgement_receiver.await;
913    }
914
915    let mut sectors_expire_at = vec![None::<SegmentIndex>; usize::from(target_sector_count)];
916    // 10% capacity is generous and should prevent reallocation in most cases
917    let mut sectors_to_replot = Vec::with_capacity(usize::from(target_sector_count) / 10);
918
919    loop {
920        let segment_index = *new_segment_index_receiver.borrow_and_update();
921        trace!(%segment_index, "New archived segment received");
922
923        let sectors_metadata = sectors_metadata.read().await;
924        let sectors_to_check = sectors_metadata
925            .iter()
926            .map(|sector_metadata| (sector_metadata.sector_index, sector_metadata.history_size));
927        for (sector_index, history_size) in sectors_to_check {
928            if let Some(Some(expires_at)) =
929                sectors_expire_at.get(usize::from(sector_index)).copied()
930            {
931                trace!(
932                    %sector_index,
933                    %history_size,
934                    %expires_at,
935                    "Checking sector for expiration"
936                );
937                // +1 means we will start replotting a bit before it actually expires to avoid
938                // storing expired sectors
939                if expires_at <= (segment_index + SegmentIndex::ONE) {
940                    debug!(
941                        %sector_index,
942                        %history_size,
943                        %expires_at,
944                        "Sector expires soon #1, scheduling replotting"
945                    );
946
947                    let expiration_details = if expires_at <= segment_index {
948                        if let Some(metrics) = metrics {
949                            metrics.update_sector_state(SectorState::Expired);
950                        }
951                        SectorExpirationDetails::Expired
952                    } else {
953                        if let Some(metrics) = metrics {
954                            metrics.update_sector_state(SectorState::AboutToExpire);
955                        }
956                        SectorExpirationDetails::AboutToExpire
957                    };
958                    handlers
959                        .sector_update
960                        .call_simple(&(sector_index, SectorUpdate::Expiration(expiration_details)));
961
962                    // Time to replot
963                    sectors_to_replot.push(SectorToReplot {
964                        sector_index,
965                        expires_at,
966                    });
967                }
968                continue;
969            }
970
971            let shard_commitments_root = shard_commitments_roots_cache.get(history_size);
972            if let Some(expiration_check_segment_index) = history_size
973                .sector_expiration_check(min_sector_lifetime)
974                .map(|expiration_check_history_size| expiration_check_history_size.segment_index())
975            {
976                trace!(
977                    %sector_index,
978                    %history_size,
979                    %expiration_check_segment_index,
980                    "Determined sector expiration check segment index"
981                );
982                let maybe_sector_expiration_check_super_segment_root = node_client
983                    .super_segment_header_for_segment_index(expiration_check_segment_index)
984                    .await
985                    .map_err(|error| PlottingError::FailedToGetSuperSegmentRoot { error })?
986                    .map(|super_segment_header| super_segment_header.root);
987
988                if let Some(sector_expiration_check_super_segment_root) =
989                    maybe_sector_expiration_check_super_segment_root
990                {
991                    let sector_id = SectorId::new(
992                        &public_key_hash,
993                        &shard_commitments_root,
994                        sector_index,
995                        history_size,
996                    );
997                    let expiration_history_size = sector_id
998                        .derive_expiration_history_size(
999                            history_size,
1000                            &sector_expiration_check_super_segment_root,
1001                            min_sector_lifetime,
1002                        )
1003                        .expect(
1004                            "Farmers internally stores correct history size in sector \
1005                            metadata; qed",
1006                        );
1007
1008                    let expires_at = expiration_history_size.segment_index();
1009
1010                    trace!(
1011                        %sector_index,
1012                        %history_size,
1013                        sector_expire_at = %expires_at,
1014                        "Determined sector expiration segment index"
1015                    );
1016                    // +1 means we will start replotting a bit before it actually expires to avoid
1017                    // storing expired sectors
1018                    if expires_at <= (segment_index + SegmentIndex::ONE) {
1019                        debug!(
1020                            %sector_index,
1021                            %history_size,
1022                            %expires_at,
1023                            "Sector expires soon #2, scheduling replotting"
1024                        );
1025
1026                        let expiration_details = if expires_at <= segment_index {
1027                            if let Some(metrics) = metrics {
1028                                metrics.update_sector_state(SectorState::Expired);
1029                            }
1030                            SectorExpirationDetails::Expired
1031                        } else {
1032                            if let Some(metrics) = metrics {
1033                                metrics.update_sector_state(SectorState::AboutToExpire);
1034                            }
1035                            SectorExpirationDetails::AboutToExpire
1036                        };
1037                        handlers.sector_update.call_simple(&(
1038                            sector_index,
1039                            SectorUpdate::Expiration(expiration_details),
1040                        ));
1041
1042                        // Time to replot
1043                        sectors_to_replot.push(SectorToReplot {
1044                            sector_index,
1045                            expires_at,
1046                        });
1047                    } else {
1048                        trace!(
1049                            %sector_index,
1050                            %history_size,
1051                            sector_expire_at = %expires_at,
1052                            "Sector expires later, remembering sector expiration"
1053                        );
1054
1055                        handlers.sector_update.call_simple(&(
1056                            sector_index,
1057                            SectorUpdate::Expiration(SectorExpirationDetails::Determined {
1058                                expires_at,
1059                            }),
1060                        ));
1061
1062                        // Store expiration so we don't have to recalculate it later
1063                        if let Some(expires_at_entry) =
1064                            sectors_expire_at.get_mut(usize::from(sector_index))
1065                        {
1066                            expires_at_entry.replace(expires_at);
1067                        }
1068                    }
1069                }
1070            }
1071        }
1072        drop(sectors_metadata);
1073
1074        let sectors_queued = sectors_to_replot.len();
1075        sectors_to_replot.sort_by_key(|sector_to_replot| sector_to_replot.expires_at);
1076        for (
1077            index,
1078            SectorToReplot {
1079                sector_index,
1080                expires_at: _,
1081            },
1082        ) in sectors_to_replot.drain(..).enumerate()
1083        {
1084            let (acknowledgement_sender, acknowledgement_receiver) = oneshot::channel();
1085            if let Err(error) = sectors_to_plot_sender
1086                .send(SectorToPlot {
1087                    sector_index,
1088                    progress: index as f32 / sectors_queued as f32 * 100.0,
1089                    last_queued: index + 1 == sectors_queued,
1090                    acknowledgement_sender,
1091                })
1092                .await
1093            {
1094                warn!(%error, "Failed to send sector index for replotting");
1095                return Ok(());
1096            }
1097
1098            // We do not care if message was sent back or sender was just dropped
1099            let _: Result<(), _> = acknowledgement_receiver.await;
1100
1101            if let Some(expires_at_entry) = sectors_expire_at.get_mut(usize::from(sector_index)) {
1102                expires_at_entry.take();
1103            }
1104        }
1105
1106        if new_segment_index_receiver.changed().await.is_err() {
1107            break;
1108        }
1109    }
1110
1111    Ok(())
1112}