feat: query multiple beacon nodes in parallel#751
feat: query multiple beacon nodes in parallel#751petarjuki7 wants to merge 14 commits intosigp:unstablefrom
Conversation
|
Claude finished @petarjuki7's task —— View job Code Review CompleteI've completed a comprehensive review of the parallel beacon node querying implementation. While the approach is sound, there are several critical issues that need to be addressed before this can be merged. Critical Issues
Design Concerns
Minor Issues
Testing Gaps
RecommendationsBefore merging:
The parallel querying approach is a solid improvement over sequential fallback, but the implementation needs refinement before it's production-ready. |
|
|
||
| use crate::{AnchorValidatorStore, ContributionWaiter, SlotMetadata}; | ||
|
|
||
| const SOFT_TIMEOUT: Duration = Duration::from_millis(500); |
There was a problem hiding this comment.
Magic Numbers: These timeout values should be documented or made configurable. Consider:
- Why is soft timeout exactly 500ms?
- How do these values relate to slot timing (typically 12s)?
- What happens if beacon nodes are consistently slower than 500ms but faster than 1s?
Add documentation explaining the rationale, or make these configurable based on network conditions.
| .data; | ||
|
|
||
| // Calculate base score from checkpoint epochs (higher epochs = more recent) | ||
| let base_score = (attestation_data.source.epoch.as_u64() |
There was a problem hiding this comment.
Scoring Algorithm Concerns:
-
Epoch Collision: Multiple attestation data with different roots but same source/target epochs get identical base scores. This could select suboptimal data.
-
Bonus Weighting: The proximity bonus (
1.0 / (1 + distance)) is tiny compared to base score. For example:- Base score: ~400,000 (epoch 200,000)
- Max bonus: 1.0
The bonus is essentially negligible and won't affect selection.
-
Missing Safety Checks: No validation that source < target, or that checkpoints are reasonable.
Consider:
- Normalizing scores or making bonus more significant
- Adding validation of attestation data consistency
- Implementing majority agreement checking (as mentioned in TODO)
| client: &BeaconNodeHttpClient, | ||
| block_root: Hash256, | ||
| ) -> Option<Slot> { | ||
| tokio::time::timeout(BLOCK_SLOT_LOOKUP_TIMEOUT, async { |
There was a problem hiding this comment.
Unbounded Timeout: If the block lookup hangs or is very slow, this adds 250ms to every attestation fetch. Consider:
- Using a shared timeout for all block lookups
- Caching block slot lookups
- Making block lookup optional with a fast-fail path
The 250ms timeout per client could accumulate to significant delays when querying many nodes.
3b8ef15 to
de9082f
Compare
|
Claude finished @petarjuki7's task in 4m 21s —— View job Code Review CompleteI've completed a comprehensive review of the parallel beacon node querying implementation. The PR adds good functionality, but there are several critical issues that must be addressed before merging. Critical Issues1. Compilation Error - Async Closure Captures
|
|
|
||
| const SOFT_TIMEOUT: Duration = Duration::from_millis(500); | ||
| const HARD_TIMEOUT: Duration = Duration::from_secs(1); | ||
| const BLOCK_SLOT_LOOKUP_TIMEOUT: Duration = Duration::from_millis(125); |
There was a problem hiding this comment.
Documentation Needed: These timeout constants need justification. Consider adding:
/// Soft timeout for beacon node responses. If we receive at least one valid
/// attestation data response by this timeout, we'll return early with the best
/// scored result. This is set to 500ms to balance responsiveness with giving
/// slower nodes a chance to respond.
const SOFT_TIMEOUT: Duration = Duration::from_millis(500);
/// Hard timeout for beacon node responses. After this timeout, we return
/// unconditionally with whatever responses we've received (or error if none).
/// Set to 1s to ensure we have time to fetch attestation data before the
/// attestation deadline (slot time is 12s).
const HARD_TIMEOUT: Duration = Duration::from_secs(1);
/// Timeout for looking up a block's slot number by root. This is an optional
/// enhancement to scoring, so we use a short timeout to avoid delaying the
/// overall attestation data fetch.
const BLOCK_SLOT_LOOKUP_TIMEOUT: Duration = Duration::from_millis(125);Questions to address:
- Why 500ms soft / 1s hard? How were these values determined?
- What happens if beacon nodes are consistently slower than 500ms but faster than 1s?
- How do these relate to attestation deadline constraints?
There was a problem hiding this comment.
Timeouts taken inspiration from the same parts of code in the Go implementation of SSV.
They use:
Soft timeout = 2 seconds
Hard timeout = 5 seconds
Block slot lookup timeout = 1.25 seconds
I found that a bit too long so adjusted to 1 second, 3 seconds and 0.5 seconds respectively
|
Some required checks have failed. Could you please take a look @petarjuki7? 🙏 |
dknopik
left a comment
There was a problem hiding this comment.
Thanks for the PR! I did a first pass, see below.
Additionally, I think we need to integrate this into sign_attestation to have it use the attestation from the metadata instead of the passed attestation if the weighting is enabled.
| Disabled by default.", | ||
| display_order = 0 | ||
| )] | ||
| pub with_weighted_attestation_data: bool, |
There was a problem hiding this comment.
Is parallel querying with weighted selection strictly better when we have multiple beacon nodes? If so, then it should just be the implementation, not a user choice. We already have 54 parameters.
There was a problem hiding this comment.
Fair point about the number of parameters... I wouldn't say it's strictly better. SSV describes it as:
Improves attestation accuracy by scoring responses from multiple Beacon nodes based on epoch and slot proximity. Adds slight latency to duties but includes safeguards (timeouts, retries).
So it's a tradeoff between accuracy and latency so it should probably stay as an option.
More about trade offs here
There was a problem hiding this comment.
Thanks, that makes sense. But then the question isn't whether a tradeoff exists; it's whether operators should be required to understand it and make a choice.
- The latency concern is already addressed by design; the timeouts enforce bounded latency regardless of beacon node response times.
- The tradeoff isn't operator-dependent: Unlike some configuration choices (e.g., "how much disk space to allocate"), there's no operator-specific context that changes the optimal decision here:
- 1 beacon node → WAD provides no benefit (nothing to compare)
- Multiple beacon nodes → WAD provides better accuracy with bounded latency
- Operators shouldn't need to read SSV WAD documentation: To make an informed choice about this flag, an operator would need to understand attestation scoring algorithms, epoch proximity, timeout implications, etc. That's an unreasonable cognitive load for what should be "run my validator correctly."
There was a problem hiding this comment.
What we could do is to collect data on mainnet that will help us to make an informed decision.
A practical measure first plan (no new operator config required) could look like this:
We ship it as “shadow mode” for one release:
• When --beacon-nodes has 2+ entries, run the parallel fetch/scoring in the background, but still use the current behavior for the actual duty result.
• Record metrics about what would have been selected and how long it took.
That gives us mainnet distributions with near-zero functional risk, and we can decide later whether it should become the default implementation. What do you think?
There was a problem hiding this comment.
I like the idea of collecting metrics first and maybe hiding the flag for the first release, but I would still leave the functionality as accessible if the users (staking pools) which requested it want to use it right away. And for the "general" public we track metrics and see if it should become the default implementation.
There was a problem hiding this comment.
Makes sense that some pools want to try this ASAP - but after thinking more about it, I’m worried we’re framing it as a trade-off when it’s really an unvalidated hypothesis. So the real claim here is: waiting/doing more work to pick "better" attestation data will improve outcomes (head correctness / inclusion) more than it harms them via added delay / load. That needs evidence. Adding a new public flag effectively ships a production-path behavior change and asks operators to run the experiment for us.
I’d strongly prefer we measure first: ship instrumentation + run the weighted selection in shadow mode when 2+ beacon nodes are configured (compute scores/timings and export metrics, but keep the current selection for duties). Then we can decide default/kill based on real mainnet distributions - without permanently growing the CLI surface.
If we must unblock specific pools immediately, I’d rather keep it clearly experimental/temporary (e.g. hidden-from-help / config-only) + mandatory metrics, with an explicit revisit and remove/make-default after N releases plan. Also, making it very clear that they are using it at their own risk.
|
|
||
| /// Calculate the score for attestation data based on checkpoint epochs and head slot proximity. | ||
| /// Extracted from fetch_and_score for testing. | ||
| fn calculate_attestation_score( |
There was a problem hiding this comment.
Could you please elaborate on the point of this function?
There was a problem hiding this comment.
It's a more stripped down version of fetch_and_score from the metadata_service.rs. It's to check the correctness and output of the scoring mechanism, but omits the parts about fetching attestations and block_slots, since they are provided in the test context.
There was a problem hiding this comment.
I get why you extracted this, but if the tests use calculate_attestation_score (or an identical copy of the formula) to compute the expected result, they’re tautological: the expected value is derived from the implementation, so a bug in the scoring logic won’t be caught. It's also code duplication. 
IMO, it's better to add tests with hard-coded fixtures and hand-computed expected outcomes (epoch dominates, proximity tie-break, missing head_slot behavior).
There was a problem hiding this comment.
Did some refactoring so I can have a proper extracted function in production code to test, let me know what do you think!
| } | ||
|
|
||
| /// Get the slot number for a given block root with timeout | ||
| async fn get_block_slot( |
There was a problem hiding this comment.
In Go SSV, they keep a blockRootToSlotCache populated from the CL event stream (so most lookups are zero-latency), and when scoring, they retry on cache miss every ~100ms up to a short timeout. The motivation seems to be a race they observed in practice: attestation_data can reference a block produced milliseconds ago, and the corresponding event/cache entry may arrive just after the first scoring attempt; plus the BeaconBlockHeader lookup can be slow/unreliable, so they wrap it in tight timeouts and retry to avoid hurting duty latency.
There was a problem hiding this comment.
I had that comment from Claude Code, had a small discussion somewhere up there in the comments.
Their cache is populated from HTTP responses as far as I can tell and managing cache state adds complexity. We'd have to add state management to our MetadataService struct as far as I can tell with something like a Arc<Mutex<Hashmap<...>>>. With our current setup (parallel queries, 1s soft / 3s hard timeout), we have plenty of opportunities to catch the block somewhere.
I think the simpler approach is fine for now, worst case we miss the proximity bonus on one node but get it from another. I think for now it could be fine without an explicit cache or retrys, but let me know what you think.
Issue Addressed
WAD - Weighted Attestation Data
Proposed Changes
The implementation uses
FuturesUnorderedto query all beacon nodes concurrently and selects the highest-scoring attestation data. Scoring works by summing source and target epochs (base score) plus a proximity bonus based on how close the head slot is to the attestation slot.Additional Info