From 8b07592ce270ced3a5d406a5caee3c9e47cabb0b Mon Sep 17 00:00:00 2001 From: YaroShkvorets Date: Thu, 19 Nov 2026 12:21:00 -0500 Subject: [PATCH 1/2] hub: fix race that drops sources subscribing at the same time ForkableHub.subscribe appended to the list of subscribers from the CallWithBlocks* callbacks, which only hold the forkable's read lock. Sources created at the same time could overwrite each other's entry. A lost one was sent the blocks the hub already had and then never a live block, with no error, so its stream stayed open and silent. The list now has its own mutex. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01CKy2EkG5bfA6HNM1MZSHWz --- CHANGELOG.md | 1 + hub/hub.go | 34 ++++++++++++---- hub/subscribe_race_test.go | 81 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 7 deletions(-) create mode 100644 hub/subscribe_race_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ad235f..592ae9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- `hub`: sources created from a `ForkableHub` at the same time could overwrite each other in its list of subscribers. A lost one was sent the blocks the hub already had and then never a live block, without an error, so its stream stayed open and silent until the client or the process was restarted. It could happen on a relayer when several clients reconnected to it at once, and on any hub serving streams. - `(*transform.BlockIndexer).Add` no longer swallows a failed index write with a warning and moves on to the next range, which left permanent holes in the index; the error now propagates to the caller and `currentIndex` is left unchanged so a retry does not lose data. `writeIndex` also waits with a backoff between retry attempts instead of retrying back-to-back, and no longer leaks a context per attempt until the whole call returns. - A live stream starting at a block number with no block (a missed or skipped slot) now starts at the next block instead of waiting for the merged bundle containing it. - `hub.ForkableHub` no longer breaks when its one-block bootstrap races with the merger deleting the files of a bundle it just merged. Concretely: bootstrap retries a few times when the listing comes back with a gap or a listed file is gone by the time it is opened (both expected during that race), a failed bootstrap no longer leaves the forkable holding a bogus LIB it then can't reconcile with live blocks (the hub now only swaps in the forkable it built once bootstrap actually succeeds, falling back to a fresh one otherwise), and `cannot link block after reconnection` is only fatal once the hub has actually been ready — before that, an unlinkable block is handled like any other, already subject to `WithMaxConsecutiveUnlinkableBlocks`. Previously a consumer starting or restarting during that race could see the hub die or never become ready. diff --git a/hub/hub.go b/hub/hub.go index 5273279..aeac82e 100644 --- a/hub/hub.go +++ b/hub/hub.go @@ -21,6 +21,7 @@ import ( "io" "strconv" "strings" + "sync" "time" "github.com/streamingfast/dstore" @@ -46,6 +47,10 @@ type ForkableHub struct { keepFinalBlocks int + // subscribersLock guards subscribers. The forkable lock is not enough: sources are + // created from the CallWithBlocks* callbacks, which only hold its read lock, so + // several of them can subscribe at the same time. + subscribersLock sync.Mutex subscribers []*Subscription sourceChannelSize int @@ -129,7 +134,7 @@ func newForkableHub(liveSourceFactory bstream.SourceFactory, keepFinalBlocks int ) hub.OnTerminating(func(err error) { - for _, sub := range hub.subscribers { + for _, sub := range hub.currentSubscribers() { sub.Shutdown(err) } }) @@ -230,19 +235,35 @@ func (h *ForkableHub) IsReady() bool { } } -// subscribe must be called while hub is locked +// subscribe must be called while the forkable is locked (a read lock is enough), so that +// no live block is broadcast between reading initialBlocks and registering the subscription. func (h *ForkableHub) subscribe(handler bstream.Handler, initialBlocks []*bstream.PreprocessedBlock, withPartials bool) *Subscription { chanSize := h.sourceChannelSize + len(initialBlocks) sub := NewSubscription(handler, chanSize, withPartials) for _, ppblk := range initialBlocks { _ = sub.push(ppblk) } - h.subscribers = append(h.subscribers, sub) + + h.subscribersLock.Lock() + // The full slice expression forces a copy, so a slice held by currentSubscribers() + // is never written to. + h.subscribers = append(h.subscribers[:len(h.subscribers):len(h.subscribers)], sub) + h.subscribersLock.Unlock() return sub } -// unsubscribe must be called while hub is locked +// currentSubscribers returns the subscribers at the time of the call. The returned slice +// is never modified afterwards, so it can be ranged over without holding the lock. +func (h *ForkableHub) currentSubscribers() []*Subscription { + h.subscribersLock.Lock() + defer h.subscribersLock.Unlock() + return h.subscribers +} + func (h *ForkableHub) unsubscribe(removeSub *Subscription) { + h.subscribersLock.Lock() + defer h.subscribersLock.Unlock() + var newSubscriber []*Subscription for _, sub := range h.subscribers { if sub != removeSub { @@ -832,9 +853,8 @@ func (h *ForkableHub) broadcastBlock(blk *pbbstream.Block, obj any) error { preprocBlock := &bstream.PreprocessedBlock{Block: blk, Obj: obj} - subscribers := h.subscribers // we may remove some from the original slice during the loop - - for _, sub := range subscribers { + // unsubscribe replaces the slice, it does not modify the one being ranged over + for _, sub := range h.currentSubscribers() { err := sub.push(preprocBlock) if err != nil { h.unsubscribe(sub) diff --git a/hub/subscribe_race_test.go b/hub/subscribe_race_test.go new file mode 100644 index 0000000..1936deb --- /dev/null +++ b/hub/subscribe_race_test.go @@ -0,0 +1,81 @@ +package hub + +import ( + "sync" + "testing" + "time" + + "github.com/streamingfast/bstream" + pbbstream "github.com/streamingfast/bstream/pb/sf/bstream/v1" + "github.com/streamingfast/dstore" + "github.com/stretchr/testify/require" +) + +// Sources created from the hub at the same instant must all get live blocks. This is +// what happens on a relayer when the other relayer goes down: every client of the dead +// one sends its block request to the survivor within a few milliseconds. +func TestForkableHub_ConcurrentSubscribe(t *testing.T) { + const clients = 8 + const rounds = 200 + + for round := range rounds { + lsf := bstream.NewTestSourceFactory() + store := dstore.NewMockStore(nil) + fh := NewForkableHub(lsf.NewSource, 0, store) + AddToMockStore(t, store, + bstream.TestBlockWithLIBNum("00000003", "00000002", 2), + bstream.TestBlockWithLIBNum("00000004", "00000003", 2), + bstream.TestBlockWithLIBNum("00000005", "00000004", 2), + bstream.TestBlockWithLIBNum("00000008", "00000005", 3), + ) + go fh.Run() + select { + case <-fh.Ready: + case <-time.After(time.Second): + t.Fatal("hub not ready") + } + liveSource := <-lsf.Created + + gotLiveBlock := make([]chan struct{}, clients) + sources := make([]bstream.Source, clients) + + var wg sync.WaitGroup + start := make(chan struct{}) + for i := range clients { + gotLiveBlock[i] = make(chan struct{}, 1) + handler := bstream.HandlerFunc(func(blk *pbbstream.Block, _ any) error { + if blk.Id == "00000009" { + gotLiveBlock[i] <- struct{}{} + } + return nil + }) + + wg.Add(1) + go func() { + defer wg.Done() + <-start + // as BlockstreamServer.Blocks does for each block request + sources[i] = fh.SourceFromBlockNumWithForks(3, handler, true) + }() + } + close(start) + wg.Wait() + + for i, source := range sources { + require.NotNil(t, source, "round %d: client %d", round, i) + go source.Run() + } + + require.NoError(t, liveSource.Push(bstream.TestBlockWithLIBNum("00000009", "00000008", 3), nil)) + + for i := range clients { + select { + case <-gotLiveBlock[i]: + case <-time.After(time.Second): + t.Fatalf("round %d: client %d never got the live block, the hub has %d subscribers for %d clients", + round, i, len(fh.currentSubscribers()), clients) + } + } + fh.Shutdown(nil) + } +} From 6ccbc6d8c898f8d114a739b9fff4595c7ad53d24 Mon Sep 17 00:00:00 2001 From: YaroShkvorets Date: Thu, 19 Nov 2026 12:31:57 -0500 Subject: [PATCH 2/2] hub: shorten comments Also drop the copy on append: appending past a snapshot's length does not change what the snapshot holds. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01CKy2EkG5bfA6HNM1MZSHWz --- CHANGELOG.md | 2 +- hub/hub.go | 16 ++++------------ hub/subscribe_race_test.go | 4 +--- 3 files changed, 6 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 592ae9a..e2710e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- `hub`: sources created from a `ForkableHub` at the same time could overwrite each other in its list of subscribers. A lost one was sent the blocks the hub already had and then never a live block, without an error, so its stream stayed open and silent until the client or the process was restarted. It could happen on a relayer when several clients reconnected to it at once, and on any hub serving streams. +- `hub`: sources created from a `ForkableHub` at the same time could lose their subscription: they got the hub's current blocks, then never a live block and no error. - `(*transform.BlockIndexer).Add` no longer swallows a failed index write with a warning and moves on to the next range, which left permanent holes in the index; the error now propagates to the caller and `currentIndex` is left unchanged so a retry does not lose data. `writeIndex` also waits with a backoff between retry attempts instead of retrying back-to-back, and no longer leaks a context per attempt until the whole call returns. - A live stream starting at a block number with no block (a missed or skipped slot) now starts at the next block instead of waiting for the merged bundle containing it. - `hub.ForkableHub` no longer breaks when its one-block bootstrap races with the merger deleting the files of a bundle it just merged. Concretely: bootstrap retries a few times when the listing comes back with a gap or a listed file is gone by the time it is opened (both expected during that race), a failed bootstrap no longer leaves the forkable holding a bogus LIB it then can't reconcile with live blocks (the hub now only swaps in the forkable it built once bootstrap actually succeeds, falling back to a fresh one otherwise), and `cannot link block after reconnection` is only fatal once the hub has actually been ready — before that, an unlinkable block is handled like any other, already subject to `WithMaxConsecutiveUnlinkableBlocks`. Previously a consumer starting or restarting during that race could see the hub die or never become ready. diff --git a/hub/hub.go b/hub/hub.go index aeac82e..dc9c5e3 100644 --- a/hub/hub.go +++ b/hub/hub.go @@ -47,10 +47,7 @@ type ForkableHub struct { keepFinalBlocks int - // subscribersLock guards subscribers. The forkable lock is not enough: sources are - // created from the CallWithBlocks* callbacks, which only hold its read lock, so - // several of them can subscribe at the same time. - subscribersLock sync.Mutex + subscribersLock sync.Mutex // subscribe only runs under the forkable's read lock subscribers []*Subscription sourceChannelSize int @@ -235,8 +232,7 @@ func (h *ForkableHub) IsReady() bool { } } -// subscribe must be called while the forkable is locked (a read lock is enough), so that -// no live block is broadcast between reading initialBlocks and registering the subscription. +// subscribe must be called while the forkable is locked (a read lock is enough) func (h *ForkableHub) subscribe(handler bstream.Handler, initialBlocks []*bstream.PreprocessedBlock, withPartials bool) *Subscription { chanSize := h.sourceChannelSize + len(initialBlocks) sub := NewSubscription(handler, chanSize, withPartials) @@ -245,15 +241,12 @@ func (h *ForkableHub) subscribe(handler bstream.Handler, initialBlocks []*bstrea } h.subscribersLock.Lock() - // The full slice expression forces a copy, so a slice held by currentSubscribers() - // is never written to. - h.subscribers = append(h.subscribers[:len(h.subscribers):len(h.subscribers)], sub) + h.subscribers = append(h.subscribers, sub) h.subscribersLock.Unlock() return sub } -// currentSubscribers returns the subscribers at the time of the call. The returned slice -// is never modified afterwards, so it can be ranged over without holding the lock. +// currentSubscribers returns a snapshot, safe to range over without the lock func (h *ForkableHub) currentSubscribers() []*Subscription { h.subscribersLock.Lock() defer h.subscribersLock.Unlock() @@ -853,7 +846,6 @@ func (h *ForkableHub) broadcastBlock(blk *pbbstream.Block, obj any) error { preprocBlock := &bstream.PreprocessedBlock{Block: blk, Obj: obj} - // unsubscribe replaces the slice, it does not modify the one being ranged over for _, sub := range h.currentSubscribers() { err := sub.push(preprocBlock) if err != nil { diff --git a/hub/subscribe_race_test.go b/hub/subscribe_race_test.go index 1936deb..f73241d 100644 --- a/hub/subscribe_race_test.go +++ b/hub/subscribe_race_test.go @@ -11,9 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -// Sources created from the hub at the same instant must all get live blocks. This is -// what happens on a relayer when the other relayer goes down: every client of the dead -// one sends its block request to the survivor within a few milliseconds. +// Sources created at the same time must all get live blocks. func TestForkableHub_ConcurrentSubscribe(t *testing.T) { const clients = 8 const rounds = 200