Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keep data in fails cases in sync service #2361

Merged
merged 36 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
b191e08
Update p2p mock and add a test for the save of data
AurelienFT Oct 15, 2024
704a583
Fix a test
AurelienFT Oct 15, 2024
e94bee2
Add caching of headers or blocks already fetched. Removed when succes…
AurelienFT Oct 16, 2024
6a61661
Add changelog and fmt
AurelienFT Oct 16, 2024
34ec1c6
Fix clippy
AurelienFT Oct 16, 2024
c4bb96c
Add new cache structure. (Not fully working because of batch of heade…
AurelienFT Oct 17, 2024
23c7eaa
Add new chunk system to distinguish chunks of blocks and blocks heade…
AurelienFT Oct 18, 2024
41966a6
Improve changes made to back pressure test because going too fast
AurelienFT Oct 18, 2024
8e4fc44
Update get_chunks method to be more readable
AurelienFT Oct 18, 2024
27a5856
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Oct 18, 2024
879eb94
Update CHANGELOG.md
AurelienFT Oct 18, 2024
a29e763
Avoid unecessary changes in changelog
AurelienFT Oct 18, 2024
83401ce
Remove old comment
AurelienFT Oct 18, 2024
62cae71
fix compil benchmark
AurelienFT Oct 18, 2024
84bac0a
fix clippy
AurelienFT Oct 21, 2024
42719bf
Add a way to fetch transactions without specifying a peer in P2P
AurelienFT Oct 21, 2024
c80f3ac
Update CANGELOG.md
AurelienFT Oct 21, 2024
ab3221c
Merge branch 'add_p2p_fetch_txs_no_peer_specified' into sync_service/…
AurelienFT Oct 21, 2024
99135e3
Use get transactions without peer_id when use headers from cache
AurelienFT Oct 21, 2024
862ef36
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Oct 31, 2024
0ac1e34
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Oct 31, 2024
2407078
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Oct 31, 2024
bb3b8ca
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 14, 2024
6dae6c7
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 18, 2024
0862890
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 21, 2024
1ab0af5
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 27, 2024
a566ac5
Improve some caches mechanism in sync and more comments on tests
AurelienFT Nov 27, 2024
17a38e4
Simplify chunk lf cache creation algorithm
AurelienFT Nov 27, 2024
2f18123
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 27, 2024
d9ef69e
toml lint
AurelienFT Nov 27, 2024
546bcf5
Improve test and fix some safety clippy.
AurelienFT Nov 28, 2024
193e0ac
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 28, 2024
10c8a21
Fix tests checks and clippy
AurelienFT Nov 28, 2024
2af4312
Simplified the implementation
xgreenx Nov 28, 2024
8ffd925
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 29, 2024
e7e4195
Merge branch 'master' into sync_service/keep-data-on-stop
AurelienFT Nov 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

### Added
- [2361](https://github.com/FuelLabs/fuel-core/pull/2361): Add caches to the syync service to not reask for data it already fetched from the network.
AurelienFT marked this conversation as resolved.
Show resolved Hide resolved

## [Version 0.40.0]

### Added
Expand Down
182 changes: 131 additions & 51 deletions crates/services/sync/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use futures::{
Stream,
};
use std::{
collections::HashMap,
future::Future,
ops::{
Range,
Expand Down Expand Up @@ -98,6 +99,26 @@ pub struct Import<P, E, C> {
executor: Arc<E>,
/// Consensus port.
consensus: Arc<C>,
/// A cache of already validated header or blocks.
cache: SharedMutex<HashMap<Range<u32>, CachedData>>,
AurelienFT marked this conversation as resolved.
Show resolved Hide resolved
}

/// The data that is cached for a range of headers or blocks.
#[derive(Debug, Clone)]
enum CachedData {
// Only headers fetch + check has been done
Headers(Batch<SealedBlockHeader>),
// Both headers fetch + check and blocks fetch + check has been done
Blocks(Batch<SealedBlock>),
}

/// The data that is fetched either in the network or in the cache for a range of headers or blocks.
#[derive(Debug, Clone)]
enum BlockHeaderData {
/// The headers (or full blocks) have been fetched and checked.
Cached(CachedData),
/// The headers has just been fetched from the network.
Fetched(Batch<SealedBlockHeader>),
}

impl<P, E, C> Import<P, E, C> {
Expand All @@ -118,6 +139,7 @@ impl<P, E, C> Import<P, E, C> {
p2p,
executor,
consensus,
cache: SharedMutex::new(HashMap::new()),
netrome marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand All @@ -127,7 +149,7 @@ impl<P, E, C> Import<P, E, C> {
}
}

#[derive(Debug)]
#[derive(Debug, Clone)]
struct Batch<T> {
peer: Option<PeerId>,
range: Range<u32>,
Expand Down Expand Up @@ -199,6 +221,7 @@ where
params,
p2p,
consensus,
cache,
..
} = &self;

Expand All @@ -208,11 +231,17 @@ where
let params = *params;
let p2p = p2p.clone();
let consensus = consensus.clone();
let cache = cache.clone();
let block_stream_buffer_size = params.block_stream_buffer_size;
let mut shutdown_signal = shutdown.clone();
async move {
let block_stream =
get_block_stream(range.clone(), params, p2p, consensus);
let block_stream = get_block_stream(
range.clone(),
params,
p2p,
consensus,
cache.clone(),
);

let shutdown_future = {
let mut s = shutdown_signal.clone();
Expand All @@ -234,7 +263,9 @@ where
// return an empty response
_ = shutdown_signal.while_started() => None,
// Stream a batch of blocks
blocks = stream_block_batch => Some(blocks),
blocks = stream_block_batch => {
Some(blocks)
},
}
}).map(|task| {
task.trace_err("Failed to join the task").ok().flatten()
Expand Down Expand Up @@ -327,9 +358,13 @@ where
};
}

let batch = Batch::new(peer.clone(), range, done);
let batch = Batch::new(peer.clone(), range.clone(), done);

if !batch.is_err() {
{
let mut cache = self.cache.lock();
cache.remove(&range);
}
report_peer(p2p, peer, PeerReportReason::SuccessfulBlockImport);
}

Expand Down Expand Up @@ -364,28 +399,72 @@ fn get_block_stream<
params: Config,
p2p: Arc<P>,
consensus: Arc<C>,
cache: SharedMutex<HashMap<Range<u32>, CachedData>>,
) -> impl Stream<Item = impl Future<Output = SealedBlockBatch>> {
let header_stream = get_header_batch_stream(range.clone(), params, p2p.clone());
header_stream
let ranges = range_chunks(range, params.header_batch_size);
rafal-ch marked this conversation as resolved.
Show resolved Hide resolved
futures::stream::iter(ranges)
.map({
AurelienFT marked this conversation as resolved.
Show resolved Hide resolved
let p2p = p2p.clone();
let cache = cache.clone();
move |range| {
let p2p = p2p.clone();
let cache = cache.clone();
async move {
let cached_data = {
let cache = cache.lock();
cache.get(&range).cloned()
};

match cached_data {
Some(cached_data) => BlockHeaderData::Cached(cached_data),
None => BlockHeaderData::Fetched(
get_headers_batch(range.clone(), &p2p).await,
),
}
}
}
})
.map({
let p2p = p2p.clone();
let consensus = consensus.clone();
let cache = cache.clone();
move |header_batch| {
let p2p = p2p.clone();
let consensus = consensus.clone();
let cache = cache.clone();
async move {
let Batch {
peer,
range,
results,
} = header_batch.await;
let checked_headers = results
.into_iter()
.take_while(|header| {
check_sealed_header(header, peer.clone(), &p2p, &consensus)
})
.collect::<Vec<_>>();
Batch::new(peer, range, checked_headers)
match header_batch.await {
BlockHeaderData::Cached(cached_data) => {
BlockHeaderData::Cached(cached_data)
}
BlockHeaderData::Fetched(fetched_batch) => {
let Batch {
peer,
range,
results,
} = fetched_batch;
let checked_headers = results
.into_iter()
.take_while(|header| {
check_sealed_header(
header,
peer.clone(),
&p2p,
&consensus,
)
})
.collect::<Vec<_>>();
let batch = Batch::new(peer, range.clone(), checked_headers);
if !batch.is_err() {
let mut cache = cache.lock();
cache.insert(
range.clone(),
CachedData::Headers(batch.clone()),
);
}
BlockHeaderData::Fetched(batch)
}
}
}
}
})
Expand All @@ -395,24 +474,40 @@ fn get_block_stream<
move |headers| {
let p2p = p2p.clone();
let consensus = consensus.clone();
let cache = cache.clone();
async move {
let Batch {
peer,
range,
results,
} = headers.await;
if results.is_empty() {
SealedBlockBatch::new(peer, range, vec![])
} else {
await_da_height(
results
.last()
.expect("We checked headers are not empty above"),
&consensus,
)
.await;
let headers = SealedHeaderBatch::new(peer, range, results);
get_blocks(&p2p, headers).await
match headers.await {
BlockHeaderData::Cached(CachedData::Blocks(batch)) => batch,
BlockHeaderData::Cached(CachedData::Headers(batch))
| BlockHeaderData::Fetched(batch) => {
let Batch {
peer,
range,
results,
} = batch;
if results.is_empty() {
SealedBlockBatch::new(peer, range, vec![])
} else {
await_da_height(
results
.last()
.expect("We checked headers are not empty above"),
&consensus,
)
.await;
let headers =
SealedHeaderBatch::new(peer, range.clone(), results);
let batch = get_blocks(&p2p, headers).await;
if !batch.is_err() {
let mut cache = cache.lock();
cache.insert(
range.clone(),
CachedData::Blocks(batch.clone()),
);
}
batch
}
}
}
}
.instrument(tracing::debug_span!("consensus_and_transactions"))
Expand All @@ -421,21 +516,6 @@ fn get_block_stream<
})
}

fn get_header_batch_stream<P: PeerToPeerPort + Send + Sync + 'static>(
range: RangeInclusive<u32>,
params: Config,
p2p: Arc<P>,
) -> impl Stream<Item = impl Future<Output = SealedHeaderBatch>> {
let Config {
header_batch_size, ..
} = params;
let ranges = range_chunks(range, header_batch_size);
futures::stream::iter(ranges).map(move |range| {
let p2p = p2p.clone();
async move { get_headers_batch(range, &p2p).await }
})
}

fn range_chunks(
range: RangeInclusive<u32>,
chunk_size: usize,
Expand Down
3 changes: 2 additions & 1 deletion crates/services/sync/src/import/back_pressure_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ struct Input {
block_stream_buffer_size: 10,
header_batch_size: 5,
}
=> is less_or_equal_than Count{ headers: 10, consensus: 10, transactions: 10, executes: 1, blocks: 50 }
=> is less_or_equal_than Count{ headers: 10, consensus: 10, transactions: 10, executes: 1, blocks: 51 }
rafal-ch marked this conversation as resolved.
Show resolved Hide resolved
; "1000 headers with max 5 size and max 10 requests when slow headers"
)]
#[test_case(
Expand Down Expand Up @@ -113,6 +113,7 @@ async fn test_back_pressure(input: Input, state: State, params: Config) -> Count
p2p,
executor,
consensus,
cache: SharedMutex::new(HashMap::new()),
};

import.notify.notify_one();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,23 @@ impl PressurePeerToPeer {
pub fn new(counts: SharedCounts, delays: [Duration; 2]) -> Self {
let mut mock = MockPeerToPeerPort::default();
mock.expect_get_sealed_block_headers().returning(|range| {
let peer = random_peer();
let headers = range
.clone()
.map(BlockHeight::from)
.map(empty_header)
.collect();
let headers = peer.bind(Some(headers));
Ok(headers)
Box::pin(async move {
let peer = random_peer();
let headers = range
.clone()
.map(BlockHeight::from)
.map(empty_header)
.collect();
let headers = peer.bind(Some(headers));
Ok(headers)
})
});
mock.expect_get_transactions().returning(|block_ids| {
let data = block_ids.data;
let v = data.into_iter().map(|_| Transactions::default()).collect();
Ok(Some(v))
Box::pin(async move {
let data = block_ids.data;
let v = data.into_iter().map(|_| Transactions::default()).collect();
Ok(Some(v))
})
});
Self {
p2p: mock,
Expand Down
Loading
Loading