-
Notifications
You must be signed in to change notification settings - Fork 245
feat: implement sync mode #2961
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
base: main
Are you sure you want to change the base?
Conversation
|
Claude finished @tac0turtle's task in 3m 9s —— View job Comprehensive Code ReviewI've completed a thorough review of the sync mode implementation. This is a significant architectural improvement that introduces dynamic synchronization modes for the DA worker. Here are my findings: Executive SummaryOverall Assessment: The implementation is architecturally sound with good separation of concerns. However, there are several critical bugs, security concerns, and design issues that must be addressed before merging. Critical Issues Found: 3 1. Code Quality & Architecture✅ Strengths
❌ Critical IssuesCRITICAL 1: Race condition in processSubscriptionResponse (syncer.go:566-579) for _, event := range events {
select {
case s.heightInCh <- event:
// ...
default:
s.cache.SetPendingEvent(event.Header.Height(), &event)
// ...
}
}Issue: Taking the address of the loop variable Impact: Loss of subscription events, incorrect block processing, potential chain halt. Fix: Add for _, event := range events {
event := event // Capture loop variable
select {
case s.heightInCh <- event:Note: Gemini correctly identified this in the review comments. While Go 1.22+ fixes this for CRITICAL 2: Watchdog timeout can trigger false mode switches (syncer.go:534-541) case <-time.After(watchdogTimeout):
s.logger.Debug().Dur("timeout", watchdogTimeout).Msg("subscription watchdog triggered, checking sync mode")
if s.determineSyncMode() == SyncModeCatchup {
return errors.New("fell behind, switching to catchup")
}Issue: If the DA layer simply has no new blocks for Impact: Unnecessary mode thrashing, increased DA layer load, performance degradation. Recommendation: Add a grace period or retry logic before switching modes. Consider tracking consecutive watchdog triggers: case <-time.After(watchdogTimeout):
localHead, err := s.daClient.LocalHead(s.ctx)
if err != nil {
// Network error - don't switch modes yet, retry
s.logger.Warn().Err(err).Msg("watchdog: failed to get local head, continuing in follow mode")
continue
}
if s.daRetrieverHeight.Load() + catchupThreshold < localHead {
return errors.New("fell behind, switching to catchup")
}CRITICAL 3: Missing validation of subscription response data (syncer.go:546-587) func (s *Syncer) processSubscriptionResponse(resp *blobrpc.SubscriptionResponse) error {
if resp == nil || len(resp.Blobs) == 0 {
return nil
}
// ... processes blobs directly without validation
events := s.daRetriever.ProcessBlobs(s.ctx, blobs, resp.Height)Issue: Subscription responses are processed without validating:
Impact: Potential DoS attack, out-of-order processing, resource exhaustion. Recommendation: Add validation: func (s *Syncer) processSubscriptionResponse(resp *blobrpc.SubscriptionResponse) error {
if resp == nil || len(resp.Blobs) == 0 {
return nil
}
// Validate height
currentHeight := s.daRetrieverHeight.Load()
if resp.Height < currentHeight {
s.logger.Warn().Uint64("resp_height", resp.Height).Uint64("current", currentHeight).
Msg("ignoring subscription response with old height")
return nil
}
// Validate blob count (reasonable upper limit)
const maxBlobsPerResponse = 1000
if len(resp.Blobs) > maxBlobsPerResponse {
return fmt.Errorf("subscription response contains too many blobs: %d > %d",
len(resp.Blobs), maxBlobsPerResponse)
}
// ... rest of processing
}2. Error Handling & Resilience❌ High Priority IssuesHIGH 1: Silent subscription channel closure (syncer.go:505-520) case resp, ok := <-headerCh:
if !ok {
return errors.New("header subscription closed")
}Issue: When a subscription channel closes, the function returns an error but doesn't log WHY it closed. Was it a network issue? Server shutdown? This makes debugging production issues difficult. Recommendation: Add structured logging with context: case resp, ok := <-headerCh:
if !ok {
s.logger.Error().
Str("channel", "header").
Uint64("last_height", s.daRetrieverHeight.Load()).
Msg("subscription channel unexpectedly closed")
return errors.New("header subscription closed")
}HIGH 2: No backoff between subscription retries (syncer.go:440-447) func (s *Syncer) runFollowMode() {
// ...
err := s.subscribeAndFollow()
if err != nil && !errors.Is(err, context.Canceled) {
s.metrics.SubscribeErrors.Add(1)
s.logger.Warn().Err(err).Msg("subscribe failed, will retry via mode check")
// No explicit catchup call needed
}
}Issue: If subscription fails immediately (e.g., DA node down), Impact: CPU spinning, log spam, network pressure on DA layer. Recommendation: Add backoff delay in func (s *Syncer) runFollowMode() {
s.logger.Debug().Msg("running follow mode")
s.metrics.SyncMode.Set(float64(SyncModeFollow))
err := s.subscribeAndFollow()
if err != nil && !errors.Is(err, context.Canceled) {
s.metrics.SubscribeErrors.Add(1)
s.logger.Warn().Err(err).Msg("subscribe failed, will retry via mode check")
// Backoff before retrying to avoid tight loop
backoff := s.config.DA.BlockTime.Duration
if backoff <= 0 {
backoff = 2 * time.Second
}
s.sleepOrDone(backoff)
}
}HIGH 3: Subscription context not properly cancelled on mode switch (syncer.go:457-459) subCtx, cancel := context.WithCancel(s.ctx)
defer cancel()Issue: When Recommendation: Explicitly document the cleanup contract in the // After return from subscribeAndFollow, drain any pending messages
// to ensure DA client goroutines can exit cleanly
go func() {
for range headerCh {
// Drain
}
}()
go func() {
for range dataCh {
// Drain
}
}()However, this may not be necessary if the DA client implementation properly handles context cancellation. Review the DA client implementation to ensure subscriptions are cleaned up when context is cancelled. HIGH 4: ProcessBlobs doesn't return errors (da_retriever.go:156) func (r *daRetriever) ProcessBlobs(ctx context.Context, blobs [][]byte, daHeight uint64) []common.DAHeightEventIssue: Recommendation: Add metrics for dropped blobs: // In metrics.go, add:
BlobProcessingFailures metrics.Counter
// In ProcessBlobs:
if header := r.tryDecodeHeader(bz, daHeight); header != nil {
// ...
} else if data := r.tryDecodeData(bz, daHeight); data != nil {
// ...
} else {
s.metrics.BlobProcessingFailures.Add(1)
s.logger.Debug().Int("blob_size", len(bz)).Msg("failed to decode blob as header or data")
}
|
|
The latest Buf updates on your PR. Results from workflow CI / buf-check (pull_request).
|
Summary of ChangesHello @tac0turtle, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the data availability (DA) worker's synchronization capabilities by introducing dynamic sync modes. It allows the system to efficiently transition between an aggressive polling strategy when catching up to the DA chain and a more resource-optimized, subscription-based approach once it reaches the chain head. This change aims to improve the overall performance and responsiveness of DA data processing. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a dual-mode synchronization mechanism, allowing the node to switch between an aggressive polling 'catchup' mode and a more efficient subscription-based 'follow' mode. This is a significant enhancement for nodes that are at the head of the chain. The changes are well-structured, introducing new DA client methods, metrics, and the core state machine logic in the daWorkerLoop. My review identified two critical bugs related to incorrect loop variable capturing that could lead to data corruption, and a couple of medium-severity design and style issues. Once these points are addressed, the implementation will be much more robust.
…in daRetriever; update tests and syncer for subscription handling
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2961 +/- ##
==========================================
- Coverage 57.88% 57.29% -0.60%
==========================================
Files 97 97
Lines 9306 9457 +151
==========================================
+ Hits 5387 5418 +31
- Misses 3315 3435 +120
Partials 604 604
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
95aeea4 to
ecfcf83
Compare
Overview
this pr add sync modes allowing us to move to subscriptions when at the head of the chain