Skip to content

feat(sequencer): catchup from base#3057

Draft
julienrbrt wants to merge 30 commits intomainfrom
julien/catchup-base
Draft

feat(sequencer): catchup from base#3057
julienrbrt wants to merge 30 commits intomainfrom
julien/catchup-base

Conversation

@julienrbrt
Copy link
Member

Closes: #3016

Opus did a pretty good job. I'll be improving it.

@github-actions
Copy link
Contributor

github-actions bot commented Feb 9, 2026

The latest Buf updates on your PR. Results from workflow CI / buf-check (pull_request).

BuildFormatLintBreakingUpdated (UTC)
✅ passed⏩ skipped✅ passed✅ passedFeb 19, 2026, 5:16 PM

@claude
Copy link
Contributor

claude bot commented Feb 9, 2026

Claude finished @julienrbrt's task in 6m 31s —— View job


Code Review: feat(sequencer): catchup from base

Tasks

  • Gather context and understand PR changes
  • Review core sequencer catch-up logic (pkg/sequencers/single/sequencer.go)
  • Review syncer DA height changes (block/internal/syncing/syncer.go)
  • Review DA client/tracing changes
  • Review executor changes
  • Review test coverage
  • Review E2E tests
  • Compile final review

Summary

This PR introduces a sequencer catch-up mechanism that replays missed DA epochs after extended downtime, producing forced-inclusion-only blocks to match what base sequencing nodes would have seen. The overall architecture is sound and well-commented. The state machine (catchUpUnchecked → catchUpInProgress → catchUpDone) is clear and the incremental DAHeight advance in the syncer is a particularly clever approach to keep forced inclusion verification aligned.

The main concerns are: a timestamp monotonicity edge case in the cross-epoch transition, silent failure of the catch-up detection query, and a security coverage gap in forced inclusion verification when using epoch sizes > 1. Gemini's time.Time data race report is a false positive given the single-goroutine access pattern in the execution loop.


Critical / High Priority

1. Cross-epoch timestamp monotonicity not guaranteed by the protocol

pkg/sequencers/single/sequencer.go:370–378

The jitter scheme daEndTime - (remainingForcedTxs * 1ms) correctly ensures monotonic timestamps within a single epoch. However, cross-epoch monotonicity requires:

epoch(N+1).Timestamp  >  epoch(N).Timestamp + (epoch(N+1).forcedTxCount - 1) * 1ms

This is not enforced. If two consecutive DA blocks are only a few milliseconds apart and epoch N+1 has many forced transactions, the first batch of epoch N+1 can receive a timestamp equal to or earlier than the last batch of epoch N. The test TestSequencer_CatchUp_MonotonicTimestamps uses a 10-second gap, which masks the edge case. A tighter clock (sub-second DA block times, or many forced txs) would violate strict monotonicity and cause the execution layer to reject blocks.

Consider tracking the last produced timestamp and clamping the computed value:

// Ensure strictly after the last block's timestamp.
if !lastBlockTime.IsZero() && !computed.After(lastBlockTime) {
    computed = lastBlockTime.Add(time.Millisecond)
}

A test with epoch2Timestamp = epochTimestamp + 1ms and three forced txs would reproduce the bug. Fix this →


2. Silent catch-up skip on GetLatestDAHeight failure

pkg/sequencers/single/sequencer.go:548–553

latestDAHeight, err := c.daClient.GetLatestDAHeight(ctx)
if err != nil {
    c.logger.Warn().Err(err).
        Msg("failed to get latest DA height for catch-up detection, skipping check")
    return
}

When this call fails (e.g., transient network issue at startup), the sequencer silently remains in catchUpDone state (set optimistically on line 537) and proceeds to produce mempool blocks — diverging from what base sequencing nodes would have produced during the downtime. This is the exact scenario the feature is designed to prevent.

This failure should be more conservative: either retry with backoff, or propagate the error so block production blocks until the check can be completed. At minimum, the log level should be Error rather than Warn, and GetNextBatch should return an error until the check succeeds. Fix this →


Medium Priority

3. Forced inclusion verification skipped for epoch_size > 1 during catch-up

block/internal/syncing/syncer.go:799–824

The incremental DAHeight advance sets newState.DAHeight = epochEnd + 1 (the start of the next epoch). For the subsequent catch-up block, VerifyForcedInclusionTxs is called with currentState.DAHeight = epochEnd + 1. Since epochEnd + 1 is not the end of the next epoch (for epoch_size > 1), the retriever returns an empty event — effectively skipping forced inclusion verification for all catch-up blocks with epoch_size > 1.

With epoch_size = 1 (all tests), every height is both an epoch start and end, so verification works. This gap would be present in production deployments with larger epoch sizes. At minimum this should be documented; ideally there should be a test with epoch_size > 1 to confirm the expected behavior. Fix this →

4. Excessive empty blocks during catch-up with large epoch sizes

pkg/sequencers/single/sequencer.go:220–226

When DAEpochForcedInclusion > 1, the retriever returns an empty ForcedInclusionEvent for every non-epoch-end height. The sequencer then produces an empty block for each, advancing the checkpoint by 1 per call. For 50 missed epochs of size 100, this produces ~4950 empty blocks before the catch-up completes. The executor already short-circuits on ErrNoTransactionsInBatch, but a block is still attempted. Consider batching the checkpoint advancement for empty heights rather than producing one block per empty height.

5. currentDAEndTime field is unprotected but accessed across function boundaries

pkg/sequencers/single/sequencer.go:71, 370, 482

The catchUpState field correctly uses atomic.Int32, but currentDAEndTime time.Time is a plain struct field. In the current implementation this is safe because GetNextBatch is the sole caller and it calls fetchNextDAEpoch (which writes) before reading the field. However, if GetNextBatch is ever called from multiple goroutines, or if external access is added later, this will be a data race. A comment noting the single-goroutine access invariant would prevent a future bug.

6. GetLatestDAHeight not in block/internal/da interface, added only to sequencer's block.FullDAClient

block/internal/da/interface.go was also updated to include GetLatestDAHeight. Verify that the GetLatestDAHeight in the sequencer's block.FullDAClient interface (block/ package) and the one in block/internal/da/Client interface are consistent and both wrapped by the tracing client. Looking at block/internal/da/tracing.go:126–138, GetLatestDAHeight is traced correctly — this looks good.


Low Priority / Suggestions

7. Test logger inconsistency

pkg/sequencers/single/sequencer_test.go (lines ~1243, 1309, 1457, 1676 as flagged by Gemini)

Some catch-up tests use zerolog.New(zerolog.NewConsoleWriter()) which produces noisy output on every test run. The majority of new tests already use zerolog.New(zerolog.NewTestWriter(t)). Align all catch-up tests to use zerolog.New(zerolog.NewTestWriter(t)) or zerolog.Nop().

8. Missing test for tight cross-epoch timestamp

The test TestSequencer_CatchUp_MonotonicTimestamps uses a 10-second gap between epoch timestamps, which is large enough to guarantee monotonicity regardless of forcedTxCount. Add a test where the epoch timestamps are separated by only 1ms to exercise the cross-epoch monotonicity boundary.

9. DummyDA GetForcedInclusionNamespace returns nil

test/testda/dummy.go:182

GetForcedInclusionNamespace() returns nil and HasForcedInclusionNamespace() returns false for the DummyDA. This means the catch-up mechanism is never exercised through DummyDA-based integration tests. Tests that test forced inclusion via DummyDA must configure the namespace separately, which limits integration-level test coverage for this feature. Consider adding an option (WithForcedInclusionNamespace(ns []byte)) to DummyDA.

10. DA height missedEpochs edge case

pkg/sequencers/single/sequencer.go:567

missedEpochs := latestEpoch - currentEpoch

latestEpoch and currentEpoch are uint64. The guard latestDAHeight <= currentDAHeight (line 555) prevents underflow in terms of heights, but if CalculateEpochNumber somehow returns a larger value for the smaller height (e.g., edge cases around daStartHeight), this would underflow silently. A comment or assertion would help future maintainers.


Positive Observations

  • The three-state catch-up lifecycle (catchUpUnchecked → catchUpInProgress → catchUpDone) with atomic state is clean and well-documented.
  • The incremental DAHeight advance per epoch in syncer.go is an elegant solution to the forced-inclusion epoch alignment problem.
  • GetLatestDAHeight was cleanly added to the block/internal/da interface, concrete client, tracing decorator, and mock simultaneously — no partial implementation.
  • Test coverage is comprehensive: 9 catch-up scenarios including multi-epoch, DA head exit, ErrHeightFromFuture, mempool suppression, and timestamp monotonicity.
  • The ErrForceInclusionNotConfigured path correctly sets catchUpDone immediately, ensuring no overhead when the feature is disabled.
  • updateCatchUpState runs exactly once per lifecycle via the catchUpUnchecked guard — appropriate design for a one-shot initialization check.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @julienrbrt, 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 implements a critical "catch-up" feature for the sequencer, designed to enhance its resilience and consistency following periods of inactivity or downtime. By intelligently replaying missed Data Availability (DA) epochs, the sequencer can resynchronize its state, ensuring that all forced inclusion transactions are processed in the correct order and with accurate timestamps, thereby maintaining a consistent view of the blockchain's history, even when operating in a decentralized environment. This mechanism allows the sequencer to seamlessly transition back to normal operation without compromising data integrity.

Highlights

  • Sequencer Catch-up Mechanism: Introduced a new mechanism allowing the sequencer to "catch up" on missed Data Availability (DA) epochs after extended downtime.
  • Forced Inclusion Priority: During catch-up, the sequencer temporarily processes only forced inclusion transactions, ensuring consistency with base sequencing nodes and temporarily skipping mempool transactions.
  • DA Height Synchronization: Modified syncer.go to incrementally advance the DAHeight by one epoch during catch-up, preventing issues with forced inclusion transaction verification.
  • Timestamp Alignment: Block timestamps generated during catch-up are now aligned with the DA epoch's end timestamp for historical accuracy.
  • Comprehensive Testing: Added extensive unit tests covering various catch-up scenarios, including detection, mempool skipping, timestamp usage, exit conditions, and multi-epoch replay.

🧠 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.

Changelog
  • block/internal/syncing/syncer.go
    • Updated the logic for DAHeight updates to handle large discrepancies between event.DaHeight and newState.DAHeight. When a significant gap (more than one epoch) is detected, newState.DAHeight is now advanced by exactly one epoch per block, rather than jumping directly to event.DaHeight. This ensures correct verification of forced inclusion transactions during sequencer catch-up.
    • Added detailed comments explaining the new DAHeight update strategy and its importance for catch-up blocks and forced inclusion verification.
  • pkg/sequencers/single/sequencer.go
    • Added catchingUp (boolean) and currentDAEndTime (time.Time) to the Sequencer struct to manage the catch-up state and store the DA epoch's end timestamp.
    • Modified GetNextBatch to conditionally skip fetching transactions from the mempool when the sequencer is in catchingUp mode. This ensures that only forced inclusion transactions are included in batches during catch-up.
    • Updated GetNextBatch to use sequencer.currentDAEndTime as the block timestamp when catchingUp is true, aligning block timestamps with the historical DA epoch.
    • Introduced a public IsCatchingUp() method to query the sequencer's current catch-up status.
    • Modified fetchNextDAEpoch to store the forcedTxsEvent.Timestamp in currentDAEndTime and to call a new updateCatchUpState method to manage the catchingUp flag. It also now exits catch-up mode if StatusHeightFromFuture is returned by the DA client.
    • Implemented a new private method updateCatchUpState that determines whether the sequencer should be in catch-up mode based on the timestamp of the fetched DA epoch. It enters catch-up if the epoch timestamp is significantly in the past (more than one epoch's wall-clock duration) and exits if it's recent.
  • pkg/sequencers/single/sequencer_test.go
    • Added a comprehensive suite of tests (TestSequencer_CatchUp_...) to validate the new catch-up functionality. These tests cover:
    • Detection of old epochs and entering catch-up mode.
    • Skipping mempool transactions during catch-up.
    • Using DA epoch timestamps for blocks during catch-up.
    • Exiting catch-up mode when the DA head is reached (either a recent epoch or HeightFromFuture).
    • Scenarios where catch-up is not triggered (recent epoch, no forced inclusion configured).
    • Multi-epoch replay scenarios.
    • Correct advancement of the internal checkpoint (DAHeight) during catch-up.
Activity
  • The pull request addresses and closes issue https://github.com/evstack/ev-node/issues/3016.
  • The author indicates that this work builds upon a previous attempt by "Opus", aiming for improvement.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@codecov
Copy link

codecov bot commented Feb 9, 2026

Codecov Report

❌ Patch coverage is 62.77372% with 51 lines in your changes missing coverage. Please review.
✅ Project coverage is 61.12%. Comparing base (05ce69e) to head (0ee3484).

Files with missing lines Patch % Lines
block/internal/syncing/syncer.go 34.37% 19 Missing and 2 partials ⚠️
block/internal/da/tracing.go 0.00% 10 Missing ⚠️
block/internal/da/client.go 0.00% 9 Missing ⚠️
pkg/sequencers/single/sequencer.go 91.89% 4 Missing and 2 partials ⚠️
block/internal/executing/executor.go 28.57% 3 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3057      +/-   ##
==========================================
+ Coverage   61.03%   61.12%   +0.08%     
==========================================
  Files         113      113              
  Lines       11544    11659     +115     
==========================================
+ Hits         7046     7126      +80     
- Misses       3699     3733      +34     
- Partials      799      800       +1     
Flag Coverage Δ
combined 61.12% <62.77%> (+0.08%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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 robust catch-up mechanism for the sequencer, designed to handle restarts after extended downtime. While the overall approach for consuming and verifying catch-up blocks in the syncer, including the incremental advancement of DAHeight, is well-implemented and tested, the implementation of catch-up mode in the single sequencer has significant flaws. Specifically, it produces non-monotonic block timestamps when multiple blocks are generated for a single DA epoch or when empty epochs are encountered, which will likely cause the execution layer to reject blocks and halt the chain. Additionally, there is a data race on the new catch-up state fields due to a lack of synchronization primitives. Minor suggestions for code clarity and testing experience were also noted.

Comment on lines 362 to 365
timestamp := time.Now()
if c.catchingUp && !c.currentDAEndTime.IsZero() {
timestamp = c.currentDAEndTime
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

During catch-up mode, the sequencer uses the timestamp from the last fetched DA epoch as the block timestamp. However, multiple blocks can be produced for a single DA epoch (e.g., if the epoch contains many transactions that don't fit in one block). In this case, all blocks produced for that epoch will have the exact same timestamp (c.currentDAEndTime). Furthermore, if an empty DA epoch is encountered, c.currentDAEndTime is not updated, causing the next block to reuse the timestamp from the previous non-empty epoch.

Most blockchain execution layers (like EVM) require that each new block has a timestamp strictly greater than its parent. If the sequencer produces multiple blocks with the same timestamp, the execution layer will reject them, halting the block production process and causing a Denial of Service.

Comment on lines 60 to 63
catchingUp bool
// currentDAEndTime is the DA epoch end timestamp from the last fetched epoch.
// Used as the block timestamp during catch-up to match based sequencing behavior.
currentDAEndTime time.Time
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The fields catchingUp and currentDAEndTime are accessed concurrently without proper synchronization. GetNextBatch and fetchNextDAEpoch (which update these fields) can be called by the block production loop, while IsCatchingUp() can be called concurrently by other components (e.g., RPC, monitoring, or metrics).

In Go, concurrent read/write access to non-atomic fields is a data race, which leads to undefined behavior. Specifically, a race on time.Time (which is a struct) can result in a corrupted timestamp being read, potentially leading to invalid blocks and a Denial of Service.

Comment on lines 533 to 535
if catchUpThreshold < 30*time.Second {
catchUpThreshold = 30 * time.Second
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The value 30*time.Second is used as a minimum threshold for the catch-up logic. To improve readability and maintainability, consider defining this as a named constant at the package level, for example: const minCatchUpThreshold = 30 * time.Second, and using that constant here. This makes the intent of the value clearer and centralizes its definition.

// This test uses maxBytes to limit how many txs are fetched, triggering the unprocessed txs scenario.
func TestSequencer_CatchUp_DetectsOldEpoch(t *testing.T) {
ctx := context.Background()
logger := zerolog.New(zerolog.NewConsoleWriter())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using zerolog.New(zerolog.NewConsoleWriter()) in tests can lead to verbose output in the console during test runs. It's generally better to use a logger that integrates with the testing framework, such as zerolog.New(zerolog.NewTestWriter(t)), which only shows logs for failed tests, or zerolog.Nop() if logs are not needed. This practice is followed in other new tests in this file (e.g., TestSequencer_CatchUp_UsesDATimestamp). Applying this consistently would improve the developer experience. This comment also applies to lines 1309, 1457, and 1676.

Suggested change
logger := zerolog.New(zerolog.NewConsoleWriter())
logger := zerolog.New(zerolog.NewTestWriter(t))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Sequencer catchup on restart from base

1 participant

Comments