Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
18 changes: 17 additions & 1 deletion block/internal/da/subscriber.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"errors"
"fmt"
"slices"
"sync"
"sync/atomic"
"time"
Expand Down Expand Up @@ -63,6 +64,11 @@ type Subscriber struct {
// namespaces to subscribe on. When multiple, they are merged.
namespaces [][]byte

// singleNamespace is false when header and data use separate namespaces:
// each event then carries one namespace's blobs, so heights are left to
// catch-up, which reads them all.
singleNamespace bool

// localDAHeight is only written by catchupLoop (via CAS) and read by
// followLoop to determine whether inline processing is possible.
localDAHeight atomic.Uint64
Expand Down Expand Up @@ -97,11 +103,15 @@ type Subscriber struct {

// NewSubscriber creates a new Subscriber.
func NewSubscriber(cfg SubscriberConfig) *Subscriber {
singleNamespace := !slices.ContainsFunc(cfg.Namespaces, func(ns []byte) bool {
return !bytes.Equal(ns, cfg.Namespaces[0])
})
s := &Subscriber{
client: cfg.Client,
logger: cfg.Logger,
handler: cfg.Handler,
namespaces: cfg.Namespaces,
singleNamespace: singleNamespace,
catchupSignal: make(chan struct{}, 1),
daBlockTime: cfg.DABlockTime,
fetchBlockTimestamp: cfg.FetchBlockTimestamp,
Expand Down Expand Up @@ -313,7 +323,7 @@ func (s *Subscriber) runSubscription(ctx context.Context) error {
s.updateHighest(ev.Height)

local := s.localDAHeight.Load()
isInline := ev.Height == local && s.localDAHeight.CompareAndSwap(local, local+1)
isInline := s.singleNamespace && ev.Height == local && s.localDAHeight.CompareAndSwap(local, local+1)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

err = s.handler.HandleEvent(subCtx, ev, isInline)
if isInline {
Expand All @@ -326,9 +336,15 @@ func (s *Subscriber) runSubscription(ctx context.Context) error {
}
} else {
s.localDAHeight.Store(local)
// Catch-up may have run while the height was claimed and
// stopped at it; nothing else wakes it on an idle chain.
s.signalCatchup()
s.logger.Debug().Err(err).Uint64("da_height", ev.Height).
Msg("inline processing skipped/failed, rolling back")
}
} else {
// The cursor may include an in-flight catch-up claim that later rolls back.
s.signalCatchup()
}

watchdog.Reset(watchdogTimeout)
Expand Down
193 changes: 193 additions & 0 deletions block/internal/da/subscriber_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,196 @@ func TestSubscriber_RunSubscription_InlineDoesNotPrematurelyReachHead(t *testing
assert.Equal(t, uint64(101), sub.LocalDAHeight())
assert.Equal(t, uint64(101), sub.HighestSeenDAHeight())
}

// Catch-up running while an inline height is claimed sees local past the head
// and stops. When inline processing then fails and rolls back, catch-up must be
// woken to retry the height: on an idle chain no new event would wake it.
func TestSubscriber_RunSubscription_RollbackWakesCatchup(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()

mockHandler := new(MockSubscriberHandler)
mockClient := testmocks.NewMockClient(t)

sub := NewSubscriber(SubscriberConfig{
Client: mockClient,
Logger: zerolog.Nop(),
Handler: mockHandler,
Namespaces: [][]byte{[]byte("ns")},
StartHeight: 100,
DABlockTime: time.Hour,
})
<-sub.catchupSignal // drain the startup signal

subCh := make(chan datypes.SubscriptionEvent, 1)
mockClient.EXPECT().
Subscribe(mock.Anything, []byte("ns"), false).
Return((<-chan datypes.SubscriptionEvent)(subCh), nil).
Once()

ev := datypes.SubscriptionEvent{Height: 100, Blobs: [][]byte{[]byte("h100")}}
mockHandler.On("HandleEvent", mock.Anything, ev, true).
Run(func(mock.Arguments) { sub.runCatchup(ctx) }).
Return(errors.New("skip inline")).Once()

subCh <- ev
close(subCh)
assert.Error(t, sub.runSubscription(ctx))
assert.Equal(t, uint64(100), sub.LocalDAHeight())

select {
case <-sub.catchupSignal:
default:
t.Fatal("rollback did not wake catch-up")
}
mockHandler.On("HandleCatchup", mock.Anything, uint64(100)).Return(nil).Once()
sub.runCatchup(ctx)
mockHandler.AssertExpectations(t)
assert.Equal(t, uint64(101), sub.LocalDAHeight())
}

// With distinct namespaces each event carries one namespace's blobs, so no
// event is processed inline: catch-up reads every namespace for the height.
func TestSubscriber_RunSubscription_SplitNamespacesNotInline(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()

mockHandler := new(MockSubscriberHandler)
mockClient := testmocks.NewMockClient(t)

sub := NewSubscriber(SubscriberConfig{
Client: mockClient,
Logger: zerolog.Nop(),
Handler: mockHandler,
Namespaces: [][]byte{[]byte("header"), []byte("data")},
StartHeight: 100,
DABlockTime: time.Hour,
})

headerCh := make(chan datypes.SubscriptionEvent, 1)
dataCh := make(chan datypes.SubscriptionEvent, 1)
mockClient.EXPECT().Subscribe(mock.Anything, []byte("header"), false).
Return((<-chan datypes.SubscriptionEvent)(headerCh), nil).Once()
mockClient.EXPECT().Subscribe(mock.Anything, []byte("data"), false).
Return((<-chan datypes.SubscriptionEvent)(dataCh), nil).Once()

headerEv := datypes.SubscriptionEvent{Height: 100, Blobs: [][]byte{[]byte("header")}}
dataEv := datypes.SubscriptionEvent{Height: 100, Blobs: [][]byte{[]byte("data")}}
mockHandler.On("HandleEvent", mock.Anything, headerEv, false).Return(nil).Once()
mockHandler.On("HandleEvent", mock.Anything, dataEv, false).Return(nil).Once()

headerCh <- headerEv
dataCh <- dataEv
close(headerCh)
close(dataCh)
assert.Error(t, sub.runSubscription(ctx))

mockHandler.AssertExpectations(t)
assert.Equal(t, uint64(100), sub.LocalDAHeight())
assert.Equal(t, uint64(100), sub.HighestSeenDAHeight())
}

// An event at the starting height must wake catch-up even when it does not
// increase highestSeenDAHeight and split namespaces prevent inline processing.
func TestSubscriber_RunSubscription_SplitNamespacesAtStartHeightWakeCatchup(t *testing.T) {
ctx := t.Context()
mockHandler := new(MockSubscriberHandler)
mockClient := testmocks.NewMockClient(t)
sub := NewSubscriber(SubscriberConfig{
Client: mockClient,
Logger: zerolog.Nop(),
Handler: mockHandler,
Namespaces: [][]byte{[]byte("header"), []byte("data")},
StartHeight: 100,
DABlockTime: time.Hour,
})

// Startup catch-up stops before the starting height is available.
<-sub.catchupSignal
mockHandler.On("HandleCatchup", mock.Anything, uint64(100)).
Return(datypes.ErrHeightFromFuture).Once()
sub.runCatchup(ctx)
assert.Equal(t, uint64(100), sub.LocalDAHeight())

headerCh := make(chan datypes.SubscriptionEvent, 1)
dataCh := make(chan datypes.SubscriptionEvent)
mockClient.EXPECT().Subscribe(mock.Anything, []byte("header"), false).
Return((<-chan datypes.SubscriptionEvent)(headerCh), nil).Once()
mockClient.EXPECT().Subscribe(mock.Anything, []byte("data"), false).
Return((<-chan datypes.SubscriptionEvent)(dataCh), nil).Once()

ev := datypes.SubscriptionEvent{Height: 100, Blobs: [][]byte{[]byte("header")}}
mockHandler.On("HandleEvent", mock.Anything, ev, false).Return(nil).Once()
headerCh <- ev
close(headerCh)
close(dataCh)
assert.Error(t, sub.runSubscription(ctx))

select {
case <-sub.catchupSignal:
default:
t.Fatal("equal-height event did not wake catch-up")
}
mockHandler.On("HandleCatchup", mock.Anything, uint64(100)).Return(nil).Once()
sub.runCatchup(ctx)
mockHandler.AssertExpectations(t)
assert.Equal(t, uint64(101), sub.LocalDAHeight())
}

func TestSubscriber_RunSubscription_EventDuringCatchupClaimWakesRetry(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
mockHandler := new(MockSubscriberHandler)
mockClient := testmocks.NewMockClient(t)
sub := NewSubscriber(SubscriberConfig{
Client: mockClient,
Logger: zerolog.Nop(),
Handler: mockHandler,
Namespaces: [][]byte{[]byte("header"), []byte("data")},
StartHeight: 100,
DABlockTime: time.Hour,
})

claimed := make(chan struct{})
release := make(chan struct{})
retried := make(chan struct{})
mockHandler.On("HandleCatchup", mock.Anything, uint64(100)).
Run(func(mock.Arguments) {
close(claimed)
select {
case <-release:
case <-ctx.Done():
}
}).Return(datypes.ErrHeightFromFuture).Once()
mockHandler.On("HandleCatchup", mock.Anything, uint64(100)).
Run(func(mock.Arguments) { close(retried) }).Return(nil).Once()

sub.wg.Add(1)
go sub.catchupLoop(ctx)
t.Cleanup(func() {
cancel()
sub.wg.Wait()
})
waitForLifecycleSignal(t, claimed, "catch-up to claim the starting height")
assert.Equal(t, uint64(101), sub.LocalDAHeight())

headerCh := make(chan datypes.SubscriptionEvent, 1)
dataCh := make(chan datypes.SubscriptionEvent)
mockClient.EXPECT().Subscribe(mock.Anything, []byte("header"), false).
Return((<-chan datypes.SubscriptionEvent)(headerCh), nil).Once()
mockClient.EXPECT().Subscribe(mock.Anything, []byte("data"), false).
Return((<-chan datypes.SubscriptionEvent)(dataCh), nil).Once()
ev := datypes.SubscriptionEvent{Height: 100, Blobs: [][]byte{[]byte("header")}}
mockHandler.On("HandleEvent", mock.Anything, ev, false).Return(nil).Once()
headerCh <- ev
close(headerCh)
close(dataCh)
assert.Error(t, sub.runSubscription(ctx))

close(release)
waitForLifecycleSignal(t, retried, "catch-up to retry after the in-flight claim rolls back")
cancel()
sub.wg.Wait()
mockHandler.AssertExpectations(t)
assert.Equal(t, uint64(101), sub.LocalDAHeight())
}
3 changes: 1 addition & 2 deletions block/internal/syncing/da_follower.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,7 @@ func (f *daFollower) HandleEvent(ctx context.Context, ev datypes.SubscriptionEve
completed = completed || event.DaHeight == ev.Height
}
// Events from earlier DA heights, e.g. held for a proposer rotation, say
// nothing about this height: with split namespaces its other half may still
// be on its way.
// nothing about this height, so leave it to catch-up.
if !completed {
return errors.New("skip inline: no complete events at this height") // subscriber rolls back
}
Expand Down
Loading