You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2025/10/09 13:11:09 UTC
(skywalking-banyandb) branch main updated: Fix long latency of trace merge (#801)
This is an automated email from the ASF dual-hosted git repository.
wusheng pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git
The following commit(s) were added to refs/heads/main by this push:
new 7671bcc2 Fix long latency of trace merge (#801)
7671bcc2 is described below
commit 7671bcc2eee6a7255074689265334cd083a691c8
Author: Gao Hongtao <ha...@gmail.com>
AuthorDate: Thu Oct 9 21:11:04 2025 +0800
Fix long latency of trace merge (#801)
---
.github/workflows/ci.yml | 2 +-
banyand/internal/sidx/gc.go | 57 -----
banyand/internal/sidx/gc_test.go | 71 ------
banyand/internal/sidx/interfaces.go | 27 ++-
banyand/internal/sidx/introducer.go | 192 ++++------------
banyand/internal/sidx/introducer_test.go | 244 +--------------------
banyand/internal/sidx/merge.go | 75 +------
banyand/internal/sidx/multi_sidx_query_test.go | 40 ++--
banyand/internal/sidx/options.go | 5 +
banyand/internal/sidx/part_wrapper.go | 82 +------
banyand/internal/sidx/part_wrapper_test.go | 101 ++++-----
banyand/internal/sidx/sidx.go | 239 ++++----------------
banyand/internal/sidx/sidx_test.go | 60 ++---
banyand/internal/sidx/snapshot.go | 83 +------
banyand/internal/sidx/snapshot_test.go | 69 +++---
banyand/internal/sidx/sync.go | 67 +++---
banyand/measure/write_data.go | 10 +
banyand/queue/queue.go | 1 +
banyand/queue/sub/chunked_sync.go | 16 +-
banyand/queue/sub/chunked_sync_test.go | 214 ++++++++++++++++++
banyand/queue/test/chunked_sync_common.go | 148 +++++++++++++
banyand/queue/test/chunked_sync_parttype_test.go | 268 +++++++++++++++++++++++
banyand/stream/write_data.go | 15 ++
banyand/trace/flusher.go | 62 ++----
banyand/trace/introducer.go | 79 +++++--
banyand/trace/merger.go | 47 ++--
banyand/trace/metrics.go | 2 +-
banyand/trace/query_test.go | 4 +-
banyand/trace/snapshot.go | 4 +-
banyand/trace/snapshot_test.go | 22 +-
banyand/trace/svc_liaison.go | 3 +-
banyand/trace/syncer.go | 236 +++++---------------
banyand/trace/tstable.go | 43 +++-
banyand/trace/tstable_test.go | 4 +-
banyand/trace/wqueue.go | 2 +-
banyand/trace/wqueue_test.go | 2 +-
banyand/trace/write_data.go | 87 ++++----
banyand/trace/write_liaison.go | 14 +-
banyand/trace/write_standalone.go | 13 +-
39 files changed, 1230 insertions(+), 1480 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ed539abd..bdda9c55 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -139,7 +139,7 @@ jobs:
uses: ./.github/workflows/test.yml
with:
options: --vv --fail-fast --label-filter \\!slow
- timeout-minutes: 30
+ timeout-minutes: 60
result:
name: Continuous Integration
diff --git a/banyand/internal/sidx/gc.go b/banyand/internal/sidx/gc.go
deleted file mode 100644
index 5b303029..00000000
--- a/banyand/internal/sidx/gc.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// Licensed to Apache Software Foundation (ASF) under one or more contributor
-// license agreements. See the NOTICE file distributed with
-// this work for additional information regarding copyright
-// ownership. Apache Software Foundation (ASF) licenses this file to you under
-// the Apache License, Version 2.0 (the "License"); you may
-// not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-package sidx
-
-import (
- "path/filepath"
-)
-
-type garbageCleaner struct {
- parent *sidx
- deletableEpochs []uint64
- liveEpoch uint64
-}
-
-func (g *garbageCleaner) init(parent *sidx) {
- g.parent = parent
-}
-
-func (g *garbageCleaner) registerSnapshot(snapshot *snapshot) {
- if g.liveEpoch > 0 {
- g.deletableEpochs = append(g.deletableEpochs, g.liveEpoch)
- }
- g.liveEpoch = snapshot.epoch
-}
-
-func (g *garbageCleaner) removePart(partID uint64) {
- g.parent.fileSystem.MustRMAll(partPath(g.parent.root, partID))
-}
-
-func (g *garbageCleaner) clean() {
- var remainingEpochs []uint64
- for _, deletableEpoch := range g.deletableEpochs {
- path := filepath.Join(g.parent.root, snapshotName(deletableEpoch))
- err := g.parent.fileSystem.DeleteFile(path)
- if err == nil {
- continue
- }
- g.parent.l.Warn().Err(err).Msgf("cannot delete snapshot file: %s", path)
- remainingEpochs = append(remainingEpochs, deletableEpoch)
- }
- g.deletableEpochs = remainingEpochs
-}
diff --git a/banyand/internal/sidx/gc_test.go b/banyand/internal/sidx/gc_test.go
deleted file mode 100644
index 4dea7d99..00000000
--- a/banyand/internal/sidx/gc_test.go
+++ /dev/null
@@ -1,71 +0,0 @@
-// Licensed to Apache Software Foundation (ASF) under one or more contributor
-// license agreements. See the NOTICE file distributed with
-// this work for additional information regarding copyright
-// ownership. Apache Software Foundation (ASF) licenses this file to you under
-// the Apache License, Version 2.0 (the "License"); you may
-// not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-package sidx
-
-import (
- "fmt"
- "reflect"
- "testing"
-
- "github.com/apache/skywalking-banyandb/pkg/fs"
-)
-
-func TestDeletableEpochs(t *testing.T) {
- tests := []struct {
- name string
- knownEpochs []uint64
- deletableEpochs []uint64
- n int
- }{
- {
- name: "empty",
- n: 1,
- knownEpochs: nil,
- deletableEpochs: nil,
- },
- {
- name: "one",
- n: 1,
- knownEpochs: []uint64{1},
- deletableEpochs: nil,
- },
- {
- name: "many",
- n: 1,
- knownEpochs: []uint64{1, 2, 3, 4},
- deletableEpochs: []uint64{1, 2, 3},
- },
- }
-
- for _, test := range tests {
- test := test
- t.Run(fmt.Sprintf("%s-%d", test.name, test.n), func(t *testing.T) {
- var gc garbageCleaner
- gc.init(&sidx{
- fileSystem: fs.NewLocalFileSystem(),
- })
-
- for _, epoch := range test.knownEpochs {
- gc.registerSnapshot(&snapshot{epoch: epoch})
- }
- if !reflect.DeepEqual(gc.deletableEpochs, test.deletableEpochs) {
- t.Errorf("expected deletable: %#v, got %#v", test.deletableEpochs, gc.deletableEpochs)
- }
- })
- }
-}
diff --git a/banyand/internal/sidx/interfaces.go b/banyand/internal/sidx/interfaces.go
index f514886f..9d46c54c 100644
--- a/banyand/internal/sidx/interfaces.go
+++ b/banyand/internal/sidx/interfaces.go
@@ -36,11 +36,14 @@ import (
// opaque ordering values by sidx - the system only performs numerical comparisons
// without interpreting the semantic meaning of keys.
type SIDX interface {
- // MustAddMemPart adds a memPart to the SIDX instance.
- MustAddMemPart(ctx context.Context, mp *memPart)
- // Write performs batch write operations. All writes must be submitted as batches.
- // Elements within each batch should be pre-sorted by the caller for optimal performance.
- Write(ctx context.Context, reqs []WriteRequest, segmentID int64) error
+ // IntroduceMemPart introduces a memPart to the SIDX instance.
+ IntroduceMemPart(partID uint64, mp *MemPart)
+ // IntroduceFlushed introduces a flushed map to the SIDX instance.
+ IntroduceFlushed(nextIntroduction *FlusherIntroduction)
+ // IntroduceMerged introduces a merged map and a new part to the SIDX instance.
+ IntroduceMerged(nextIntroduction *MergerIntroduction) func()
+ // ConvertToMemPart converts a write request to a memPart.
+ ConvertToMemPart(reqs []WriteRequest, segmentID int64) (*MemPart, error)
// Query executes a query with key range and tag filtering.
// Returns a QueryResponse directly with all results loaded.
// Both setup/validation errors and execution errors are returned via the error return value.
@@ -50,17 +53,13 @@ type SIDX interface {
// Close gracefully shuts down the SIDX instance, ensuring all data is persisted.
Close() error
// Flush flushes the SIDX instance to disk.
- Flush() error
+ Flush(partIDsToFlush map[uint64]struct{}) (*FlusherIntroduction, error)
// Merge merges the specified parts into a new part.
- Merge(closeCh <-chan struct{}) (uint64, error)
- // MergeMemPart merges the mem parts into a new part.
- MergeMemParts(closeCh <-chan struct{}) (uint64, error)
- // PartsToSync returns the parts to sync.
- PartsToSync() []*part
+ Merge(closeCh <-chan struct{}, partIDstoMerge map[uint64]struct{}, newPartID uint64) (*MergerIntroduction, error)
// StreamingParts returns the streaming parts.
- StreamingParts(partsToSync []*part, group string, shardID uint32, name string) ([]queue.StreamingPartData, []func())
- // SyncCh returns the sync channel for external synchronization.
- SyncCh() chan<- *SyncIntroduction
+ StreamingParts(partIDsToSync map[uint64]struct{}, group string, shardID uint32, name string) ([]queue.StreamingPartData, []func())
+ // IntroduceSynced introduces a synced map to the SIDX instance.
+ IntroduceSynced(partIDsToSync map[uint64]struct{}) func()
}
// WriteRequest contains data for a single write operation within a batch.
diff --git a/banyand/internal/sidx/introducer.go b/banyand/internal/sidx/introducer.go
index c87bd163..535d361a 100644
--- a/banyand/internal/sidx/introducer.go
+++ b/banyand/internal/sidx/introducer.go
@@ -19,53 +19,30 @@ package sidx
import (
"github.com/apache/skywalking-banyandb/pkg/pool"
- "github.com/apache/skywalking-banyandb/pkg/watcher"
)
-type introduction struct {
- memPart *memPart
- applied chan struct{}
-}
-
-func (i *introduction) reset() {
- i.memPart = nil
- i.applied = nil
-}
-
-var introductionPool = pool.Register[*introduction]("sidx-introduction")
-
-func generateIntroduction() *introduction {
- v := introductionPool.Get()
- if v == nil {
- return &introduction{}
- }
- intro := v
- intro.reset()
- return intro
-}
-
-func releaseIntroduction(i *introduction) {
- introductionPool.Put(i)
+// FlusherIntroduction represents the introduction of a flusher operation.
+type FlusherIntroduction struct {
+ flushed map[uint64]*partWrapper
}
-type flusherIntroduction struct {
- flushed map[uint64]*partWrapper
- applied chan struct{}
+// Release releases the FlusherIntroduction back to the pool.
+func (i *FlusherIntroduction) Release() {
+ releaseFlusherIntroduction(i)
}
-func (i *flusherIntroduction) reset() {
+func (i *FlusherIntroduction) reset() {
for k := range i.flushed {
delete(i.flushed, k)
}
- i.applied = nil
}
-var flusherIntroductionPool = pool.Register[*flusherIntroduction]("sidx-flusher-introduction")
+var flusherIntroductionPool = pool.Register[*FlusherIntroduction]("sidx-flusher-introduction")
-func generateFlusherIntroduction() *flusherIntroduction {
+func generateFlusherIntroduction() *FlusherIntroduction {
v := flusherIntroductionPool.Get()
if v == nil {
- return &flusherIntroduction{
+ return &FlusherIntroduction{
flushed: make(map[uint64]*partWrapper),
}
}
@@ -74,30 +51,34 @@ func generateFlusherIntroduction() *flusherIntroduction {
return fi
}
-func releaseFlusherIntroduction(i *flusherIntroduction) {
+func releaseFlusherIntroduction(i *FlusherIntroduction) {
flusherIntroductionPool.Put(i)
}
-type mergerIntroduction struct {
+// MergerIntroduction represents the introduction of a merger operation.
+type MergerIntroduction struct {
merged map[uint64]struct{}
newPart *partWrapper
- applied chan struct{}
}
-func (i *mergerIntroduction) reset() {
+// Release releases the MergerIntroduction back to the pool.
+func (i *MergerIntroduction) Release() {
+ releaseMergerIntroduction(i)
+}
+
+func (i *MergerIntroduction) reset() {
for k := range i.merged {
delete(i.merged, k)
}
i.newPart = nil
- i.applied = nil
}
-var mergerIntroductionPool = pool.Register[*mergerIntroduction]("sidx-merger-introduction")
+var mergerIntroductionPool = pool.Register[*MergerIntroduction]("sidx-merger-introduction")
-func generateMergerIntroduction() *mergerIntroduction {
+func generateMergerIntroduction() *MergerIntroduction {
v := mergerIntroductionPool.Get()
if v == nil {
- return &mergerIntroduction{
+ return &MergerIntroduction{
merged: make(map[uint64]struct{}),
}
}
@@ -106,84 +87,12 @@ func generateMergerIntroduction() *mergerIntroduction {
return mi
}
-func releaseMergerIntroduction(i *mergerIntroduction) {
+func releaseMergerIntroduction(i *MergerIntroduction) {
mergerIntroductionPool.Put(i)
}
-// SyncIntroduction is used to introduce synced parts to the sidx.
-type SyncIntroduction struct {
- Synced map[uint64]struct{}
- Applied chan struct{}
-}
-
-func (si *SyncIntroduction) reset() {
- for k := range si.Synced {
- delete(si.Synced, k)
- }
- si.Applied = nil
-}
-
-var syncIntroductionPool = pool.Register[*SyncIntroduction]("sidx-sync-introduction")
-
-// GenerateSyncIntroduction generates a new SyncIntroduction.
-func GenerateSyncIntroduction() *SyncIntroduction {
- v := syncIntroductionPool.Get()
- if v == nil {
- return &SyncIntroduction{
- Synced: make(map[uint64]struct{}),
- }
- }
- si := v
- si.reset()
- return si
-}
-
-// ReleaseSyncIntroduction releases a SyncIntroduction.
-func ReleaseSyncIntroduction(i *SyncIntroduction) {
- syncIntroductionPool.Put(i)
-}
-
-func (s *sidx) introducerLoop(flushCh chan *flusherIntroduction, mergeCh chan *mergerIntroduction,
- syncCh chan *SyncIntroduction, watcherCh watcher.Channel, epoch uint64,
-) {
- var introducerWatchers watcher.Epochs
- defer s.loopCloser.Done()
- for {
- select {
- case <-s.loopCloser.CloseNotify():
- return
- case next := <-s.introductions:
- s.incTotalIntroduceLoopStarted("mem")
- s.introduceMemPart(next, epoch)
- s.incTotalIntroduceLoopFinished("mem")
- epoch++
- case next := <-flushCh:
- s.incTotalIntroduceLoopStarted("flush")
- s.introduceFlushed(next, epoch)
- s.incTotalIntroduceLoopFinished("flush")
- s.gc.clean()
- epoch++
- case next := <-mergeCh:
- s.incTotalIntroduceLoopStarted("merge")
- s.introduceMerged(next, epoch)
- s.incTotalIntroduceLoopFinished("merge")
- s.gc.clean()
- epoch++
- case next := <-syncCh:
- s.incTotalIntroduceLoopStarted("sync")
- s.introduceSync(next, epoch)
- s.incTotalIntroduceLoopFinished("sync")
- s.gc.clean()
- epoch++
- case epochWatcher := <-watcherCh:
- introducerWatchers.Add(epochWatcher)
- }
- curEpoch := s.currentEpoch()
- introducerWatchers.Notify(curEpoch)
- }
-}
-
-func (s *sidx) introduceMemPart(nextIntroduction *introduction, epoch uint64) {
+func (s *sidx) IntroduceMemPart(partID uint64, memPart *memPart) {
+ memPart.partMetadata.ID = partID
cur := s.currentSnapshot()
if cur != nil {
defer cur.decRef()
@@ -191,66 +100,50 @@ func (s *sidx) introduceMemPart(nextIntroduction *introduction, epoch uint64) {
cur = &snapshot{}
}
- next := nextIntroduction.memPart
- nextSnp := cur.copyAllTo(epoch)
+ nextSnp := cur.copyAllTo()
// Convert memPart to part and wrap it
- part := openMemPart(next)
- pw := newPartWrapper(next, part)
+ part := openMemPart(memPart)
+ pw := newPartWrapper(memPart, part)
nextSnp.parts = append(nextSnp.parts, pw)
s.replaceSnapshot(nextSnp)
- if nextIntroduction.applied != nil {
- close(nextIntroduction.applied)
- }
}
-func (s *sidx) introduceFlushed(nextIntroduction *flusherIntroduction, epoch uint64) {
+func (s *sidx) IntroduceFlushed(nextIntroduction *FlusherIntroduction) {
cur := s.currentSnapshot()
if cur == nil {
s.l.Panic().Msg("current snapshot is nil")
}
defer cur.decRef()
- nextSnp := cur.merge(epoch, nextIntroduction.flushed)
+ nextSnp := cur.merge(nextIntroduction.flushed)
s.replaceSnapshot(nextSnp)
- s.persistSnapshot(nextSnp)
- if nextIntroduction.applied != nil {
- close(nextIntroduction.applied)
- }
}
-func (s *sidx) introduceMerged(nextIntroduction *mergerIntroduction, epoch uint64) {
+func (s *sidx) IntroduceMerged(nextIntroduction *MergerIntroduction) func() {
cur := s.currentSnapshot()
if cur == nil {
s.l.Panic().Msg("current snapshot is nil")
- return
+ return nil
}
- defer cur.decRef()
- nextSnp := cur.remove(epoch, nextIntroduction.merged)
+ nextSnp := cur.remove(nextIntroduction.merged)
// Wrap the new part
nextSnp.parts = append(nextSnp.parts, nextIntroduction.newPart)
s.replaceSnapshot(nextSnp)
- s.persistSnapshot(nextSnp)
- if nextIntroduction.applied != nil {
- close(nextIntroduction.applied)
- }
+ return cur.decRef
}
-func (s *sidx) introduceSync(nextIntroduction *SyncIntroduction, epoch uint64) {
+func (s *sidx) IntroduceSynced(partIDsToSync map[uint64]struct{}) func() {
cur := s.currentSnapshot()
if cur == nil {
s.l.Panic().Msg("current snapshot is nil")
- return
+ return nil
}
- defer cur.decRef()
- nextSnp := cur.remove(epoch, nextIntroduction.Synced)
+ nextSnp := cur.remove(partIDsToSync)
s.replaceSnapshot(nextSnp)
- s.persistSnapshot(nextSnp)
- if nextIntroduction.Applied != nil {
- close(nextIntroduction.Applied)
- }
+ return cur.decRef
}
func (s *sidx) replaceSnapshot(next *snapshot) {
@@ -261,12 +154,3 @@ func (s *sidx) replaceSnapshot(next *snapshot) {
}
s.snapshot = next
}
-
-func (s *sidx) currentEpoch() uint64 {
- snap := s.currentSnapshot()
- if snap == nil {
- return 0
- }
- defer snap.decRef()
- return snap.epoch
-}
diff --git a/banyand/internal/sidx/introducer_test.go b/banyand/internal/sidx/introducer_test.go
index a8651496..45ee55cc 100644
--- a/banyand/internal/sidx/introducer_test.go
+++ b/banyand/internal/sidx/introducer_test.go
@@ -18,39 +18,13 @@
package sidx
import (
- "sync"
"testing"
- "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIntroductionPooling(t *testing.T) {
- t.Run("introduction pooling reduces allocations", func(t *testing.T) {
- // Test that the pool works by verifying reuse
- intro1 := generateIntroduction()
- releaseIntroduction(intro1)
-
- intro2 := generateIntroduction()
- // With pooling, we might get the same instance back
- require.NotNil(t, intro2, "pool should provide introduction instance")
- releaseIntroduction(intro2)
-
- // Test multiple allocations work correctly
- var intros []*introduction
- for i := 0; i < 10; i++ {
- intro := generateIntroduction()
- intro.memPart = &memPart{}
- intro.applied = make(chan struct{})
- intros = append(intros, intro)
- }
-
- for _, intro := range intros {
- releaseIntroduction(intro)
- }
- })
-
t.Run("flusher introduction pooling reduces allocations", func(t *testing.T) {
intro1 := generateFlusherIntroduction()
releaseFlusherIntroduction(intro1)
@@ -61,11 +35,10 @@ func TestIntroductionPooling(t *testing.T) {
releaseFlusherIntroduction(intro2)
// Test multiple allocations
- var intros []*flusherIntroduction
+ var intros []*FlusherIntroduction
for i := 0; i < 10; i++ {
intro := generateFlusherIntroduction()
intro.flushed[uint64(i)] = &partWrapper{}
- intro.applied = make(chan struct{})
intros = append(intros, intro)
}
@@ -84,12 +57,11 @@ func TestIntroductionPooling(t *testing.T) {
releaseMergerIntroduction(intro2)
// Test multiple allocations
- var intros []*mergerIntroduction
+ var intros []*MergerIntroduction
for i := 0; i < 10; i++ {
intro := generateMergerIntroduction()
intro.merged[uint64(i)] = struct{}{}
intro.newPart = &partWrapper{}
- intro.applied = make(chan struct{})
intros = append(intros, intro)
}
@@ -100,37 +72,18 @@ func TestIntroductionPooling(t *testing.T) {
}
func TestIntroductionReset(t *testing.T) {
- t.Run("introduction reset for reuse", func(t *testing.T) {
- intro := generateIntroduction()
-
- // Set up introduction with data
- intro.memPart = &memPart{}
- intro.applied = make(chan struct{})
-
- // Reset the introduction
- intro.reset()
-
- // Verify all fields are cleared
- assert.Nil(t, intro.memPart, "memPart should be nil")
- assert.Nil(t, intro.applied, "applied channel should be nil")
-
- releaseIntroduction(intro)
- })
-
t.Run("flusher introduction reset for reuse", func(t *testing.T) {
intro := generateFlusherIntroduction()
// Set up flusher introduction with data
intro.flushed[1] = &partWrapper{}
intro.flushed[2] = &partWrapper{}
- intro.applied = make(chan struct{})
// Reset the flusher introduction
intro.reset()
// Verify all fields are cleared
assert.Len(t, intro.flushed, 0, "flushed map should be empty")
- assert.Nil(t, intro.applied, "applied channel should be nil")
releaseFlusherIntroduction(intro)
})
@@ -142,7 +95,6 @@ func TestIntroductionReset(t *testing.T) {
intro.merged[1] = struct{}{}
intro.merged[2] = struct{}{}
intro.newPart = &partWrapper{}
- intro.applied = make(chan struct{})
// Reset the merger introduction
intro.reset()
@@ -150,198 +102,11 @@ func TestIntroductionReset(t *testing.T) {
// Verify all fields are cleared
assert.Len(t, intro.merged, 0, "merged map should be empty")
assert.Nil(t, intro.newPart, "newPart should be nil")
- assert.Nil(t, intro.applied, "applied channel should be nil")
-
- releaseMergerIntroduction(intro)
- })
-}
-
-func TestChannelSynchronization(t *testing.T) {
- t.Run("applied notifications work reliably", func(t *testing.T) {
- intro := generateIntroduction()
- intro.applied = make(chan struct{})
-
- // Start a goroutine that waits for the notification
- done := make(chan bool)
- go func() {
- select {
- case <-intro.applied:
- done <- true
- case <-time.After(100 * time.Millisecond):
- done <- false
- }
- }()
-
- // Close the applied channel to simulate completion
- close(intro.applied)
-
- // Check that the notification was received
- result := <-done
- assert.True(t, result, "applied notification should be received")
-
- releaseIntroduction(intro)
- })
-
- t.Run("multiple waiters on applied channel", func(t *testing.T) {
- intro := generateFlusherIntroduction()
- intro.applied = make(chan struct{})
-
- const numWaiters = 5
- var wg sync.WaitGroup
- results := make(chan bool, numWaiters)
-
- // Start multiple waiters
- for i := 0; i < numWaiters; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- select {
- case <-intro.applied:
- results <- true
- case <-time.After(100 * time.Millisecond):
- results <- false
- }
- }()
- }
-
- // Close the applied channel
- close(intro.applied)
- wg.Wait()
- close(results)
-
- // All waiters should receive the notification
- successCount := 0
- for result := range results {
- if result {
- successCount++
- }
- }
- assert.Equal(t, numWaiters, successCount, "all waiters should receive notification")
-
- releaseFlusherIntroduction(intro)
- })
-
- t.Run("channel synchronization correctness", func(t *testing.T) {
- intro := generateMergerIntroduction()
- intro.applied = make(chan struct{})
-
- // Test that reading from a closed channel doesn't block
- close(intro.applied)
-
- // Multiple reads should work
- for i := 0; i < 3; i++ {
- select {
- case <-intro.applied:
- // Should not block
- default:
- t.Errorf("reading from closed channel should not block")
- }
- }
-
- releaseMergerIntroduction(intro)
- })
-}
-
-func TestIntroductionGeneration(t *testing.T) {
- t.Run("introduction generation creates valid instances", func(t *testing.T) {
- intro := generateIntroduction()
- require.NotNil(t, intro, "generated introduction should not be nil")
- assert.Nil(t, intro.memPart, "initial memPart should be nil")
- assert.Nil(t, intro.applied, "initial applied channel should be nil")
- releaseIntroduction(intro)
- })
- t.Run("flusher introduction generation creates valid instances", func(t *testing.T) {
- intro := generateFlusherIntroduction()
- require.NotNil(t, intro, "generated flusher introduction should not be nil")
- require.NotNil(t, intro.flushed, "flushed map should be initialized")
- assert.Len(t, intro.flushed, 0, "flushed map should be empty")
- assert.Nil(t, intro.applied, "initial applied channel should be nil")
- releaseFlusherIntroduction(intro)
- })
-
- t.Run("merger introduction generation creates valid instances", func(t *testing.T) {
- intro := generateMergerIntroduction()
- require.NotNil(t, intro, "generated merger introduction should not be nil")
- require.NotNil(t, intro.merged, "merged map should be initialized")
- assert.Len(t, intro.merged, 0, "merged map should be empty")
- assert.Nil(t, intro.newPart, "initial newPart should be nil")
- assert.Nil(t, intro.applied, "initial applied channel should be nil")
releaseMergerIntroduction(intro)
})
}
-func TestConcurrentPoolAccess(t *testing.T) {
- t.Run("concurrent pool access is safe", func(_ *testing.T) {
- const numGoroutines = 10
- const operationsPerGoroutine = 100
-
- var wg sync.WaitGroup
-
- // Test concurrent access to introduction pool
- for i := 0; i < numGoroutines; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for j := 0; j < operationsPerGoroutine; j++ {
- intro := generateIntroduction()
- intro.memPart = &memPart{}
- intro.applied = make(chan struct{})
- releaseIntroduction(intro)
- }
- }()
- }
-
- wg.Wait()
- // Test should complete without data races
- })
-
- t.Run("concurrent flusher introduction pool access", func(_ *testing.T) {
- const numGoroutines = 10
- const operationsPerGoroutine = 100
-
- var wg sync.WaitGroup
-
- for i := 0; i < numGoroutines; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for j := 0; j < operationsPerGoroutine; j++ {
- intro := generateFlusherIntroduction()
- intro.flushed[uint64(j)] = &partWrapper{}
- intro.applied = make(chan struct{})
- releaseFlusherIntroduction(intro)
- }
- }()
- }
-
- wg.Wait()
- })
-
- t.Run("concurrent merger introduction pool access", func(_ *testing.T) {
- const numGoroutines = 10
- const operationsPerGoroutine = 100
-
- var wg sync.WaitGroup
-
- for i := 0; i < numGoroutines; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for j := 0; j < operationsPerGoroutine; j++ {
- intro := generateMergerIntroduction()
- intro.merged[uint64(j)] = struct{}{}
- intro.newPart = &partWrapper{}
- intro.applied = make(chan struct{})
- releaseMergerIntroduction(intro)
- }
- }()
- }
-
- wg.Wait()
- })
-}
-
func TestIntroductionMapOperations(t *testing.T) {
t.Run("flusher introduction map operations", func(t *testing.T) {
intro := generateFlusherIntroduction()
@@ -393,11 +158,6 @@ func TestIntroductionMapOperations(t *testing.T) {
}
func TestNilSafetyForIntroductions(t *testing.T) {
- t.Run("release nil introduction", func(_ *testing.T) {
- // Should not panic
- releaseIntroduction(nil)
- })
-
t.Run("release nil flusher introduction", func(_ *testing.T) {
// Should not panic
releaseFlusherIntroduction(nil)
diff --git a/banyand/internal/sidx/merge.go b/banyand/internal/sidx/merge.go
index e384bd95..b9175c88 100644
--- a/banyand/internal/sidx/merge.go
+++ b/banyand/internal/sidx/merge.go
@@ -19,10 +19,10 @@ package sidx
import (
"fmt"
- "sync/atomic"
"github.com/apache/skywalking-banyandb/pkg/encoding"
"github.com/apache/skywalking-banyandb/pkg/fs"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
)
var (
@@ -31,101 +31,42 @@ var (
)
// Merge implements Merger interface.
-func (s *sidx) Merge(closeCh <-chan struct{}) (uint64, error) {
+func (s *sidx) Merge(closeCh <-chan struct{}, partIDtoMerge map[uint64]struct{}, newPartID uint64) (*MergerIntroduction, error) {
// Get current snapshot
snap := s.currentSnapshot()
if snap == nil {
- return 0, nil
+ return nil, nil
}
defer snap.decRef()
- // Create merge introduction
- mergeIntro := generateMergerIntroduction()
- defer releaseMergerIntroduction(mergeIntro)
- mergeIntro.applied = make(chan struct{})
-
// Select parts to merge (all active non-memory parts)
var partsToMerge []*partWrapper
for _, pw := range snap.parts {
- if pw.isActive() && !pw.isMemPart() {
+ if _, ok := partIDtoMerge[pw.ID()]; ok {
partsToMerge = append(partsToMerge, pw)
}
}
- if len(partsToMerge) < 2 {
- return 0, nil
+ if len(partsToMerge) != len(partIDtoMerge) {
+ logger.Panicf("not enough parts to merge: %d", len(partsToMerge))
}
- // Mark parts for merging
- for _, pw := range partsToMerge {
- mergeIntro.merged[pw.ID()] = struct{}{}
- }
-
- // Generate new part ID using atomic increment
- newPartID := atomic.AddUint64(&s.curPartID, 1)
-
// Create new merged part
newPart, err := s.mergeParts(s.fileSystem, closeCh, partsToMerge, newPartID, s.root)
if err != nil {
- return 0, err
- }
- mergeIntro.newPart = newPart
-
- // Send to introducer loop
- s.mergeCh <- mergeIntro
-
- // Wait for merge to complete
- <-mergeIntro.applied
-
- return uint64(len(partsToMerge)), nil
-}
-
-func (s *sidx) MergeMemParts(closeCh <-chan struct{}) (uint64, error) {
- snap := s.currentSnapshot()
- if snap == nil {
- return 0, nil
+ return nil, err
}
- defer snap.decRef()
// Create merge introduction
mergeIntro := generateMergerIntroduction()
- defer releaseMergerIntroduction(mergeIntro)
- mergeIntro.applied = make(chan struct{})
-
- // Select parts to merge (all active memory parts)
- var partsToMerge []*partWrapper
- for _, pw := range snap.parts {
- if pw.isActive() && pw.isMemPart() {
- partsToMerge = append(partsToMerge, pw)
- }
- }
-
- if len(partsToMerge) < 2 {
- return 0, nil
- }
// Mark parts for merging
for _, pw := range partsToMerge {
mergeIntro.merged[pw.ID()] = struct{}{}
}
- // Generate new part ID using atomic increment
- newPartID := atomic.AddUint64(&s.curPartID, 1)
-
- // Create new merged part
- newPart, err := s.mergeParts(s.fileSystem, closeCh, partsToMerge, newPartID, s.root)
- if err != nil {
- return 0, err
- }
mergeIntro.newPart = newPart
-
- // Send to introducer loop
- s.mergeCh <- mergeIntro
-
- // Wait for merge to complete
- <-mergeIntro.applied
-
- return uint64(len(partsToMerge)), nil
+ return mergeIntro, nil
}
func (s *sidx) mergeParts(fileSystem fs.FileSystem, closeCh <-chan struct{}, parts []*partWrapper, partID uint64, root string) (*partWrapper, error) {
diff --git a/banyand/internal/sidx/multi_sidx_query_test.go b/banyand/internal/sidx/multi_sidx_query_test.go
index 853e2c16..059ad38b 100644
--- a/banyand/internal/sidx/multi_sidx_query_test.go
+++ b/banyand/internal/sidx/multi_sidx_query_test.go
@@ -37,10 +37,26 @@ type mockSIDX struct {
name string
}
-func (m *mockSIDX) MustAddMemPart(_ context.Context, _ *memPart) {}
+func (m *mockSIDX) ConvertToMemPart(_ []WriteRequest, _ int64) (*MemPart, error) {
+ return nil, nil // Not implemented for tests
+}
+
+func (m *mockSIDX) IntroduceMemPart(_ uint64, _ *MemPart) {
+ // Not implemented for tests
+}
+
+func (m *mockSIDX) IntroduceFlushed(_ *FlusherIntroduction) {
+ // Not implemented for tests
+}
+
+func (m *mockSIDX) IntroduceMerged(_ *MergerIntroduction) func() {
+ // Not implemented for tests
+ return nil
+}
-func (m *mockSIDX) Write(_ context.Context, _ []WriteRequest, _ int64) error {
- return nil // Not implemented for tests
+func (m *mockSIDX) IntroduceSynced(_ map[uint64]struct{}) func() {
+ // Not implemented for tests
+ return nil
}
func (m *mockSIDX) Query(_ context.Context, _ QueryRequest) (*QueryResponse, error) {
@@ -58,30 +74,22 @@ func (m *mockSIDX) Close() error {
return nil
}
-func (m *mockSIDX) Flush() error {
- return nil
-}
-
-func (m *mockSIDX) Merge(_ <-chan struct{}) (uint64, error) {
- return 0, nil
+func (m *mockSIDX) Flush(_ map[uint64]struct{}) (*FlusherIntroduction, error) {
+ return nil, nil
}
-func (m *mockSIDX) MergeMemParts(_ <-chan struct{}) (uint64, error) {
- return 0, nil
+func (m *mockSIDX) Merge(_ <-chan struct{}, _ map[uint64]struct{}, _ uint64) (*MergerIntroduction, error) {
+ return nil, nil
}
func (m *mockSIDX) PartsToSync() []*part {
return nil
}
-func (m *mockSIDX) StreamingParts(_ []*part, _ string, _ uint32, _ string) ([]queue.StreamingPartData, []func()) {
+func (m *mockSIDX) StreamingParts(_ map[uint64]struct{}, _ string, _ uint32, _ string) ([]queue.StreamingPartData, []func()) {
return nil, nil
}
-func (m *mockSIDX) SyncCh() chan<- *SyncIntroduction {
- return make(chan *SyncIntroduction)
-}
-
// Helper function to create mock QueryResponse with test data.
func createMockQueryResponse(keyStart int64, count int, seriesIDBase common.SeriesID) *QueryResponse {
keys := make([]int64, count)
diff --git a/banyand/internal/sidx/options.go b/banyand/internal/sidx/options.go
index 58bbcc43..ac95057b 100644
--- a/banyand/internal/sidx/options.go
+++ b/banyand/internal/sidx/options.go
@@ -37,6 +37,11 @@ type Options struct {
// This includes part directories, metadata files, and temporary files.
// MANDATORY: Must be provided, non-empty, and an absolute path.
Path string
+
+ // AvailablePartIDs is the list of available part IDs.
+ // It is used to load the snapshot and validate the part IDs.
+ // MANDATORY: Must be provided and cannot be nil.
+ AvailablePartIDs []uint64
}
// MergePolicy defines the strategy for merging parts in SIDX.
diff --git a/banyand/internal/sidx/part_wrapper.go b/banyand/internal/sidx/part_wrapper.go
index 42244f80..7d7ecf84 100644
--- a/banyand/internal/sidx/part_wrapper.go
+++ b/banyand/internal/sidx/part_wrapper.go
@@ -24,32 +24,6 @@ import (
"github.com/apache/skywalking-banyandb/pkg/logger"
)
-// partWrapperState represents the state of a partWrapper in its lifecycle.
-type partWrapperState int32
-
-const (
- // partStateActive indicates the part is active and available for use.
- partStateActive partWrapperState = iota
- // partStateRemoving indicates the part is being removed but may still have references.
- partStateRemoving
- // partStateRemoved indicates the part has been fully removed and cleaned up.
- partStateRemoved
-)
-
-// String returns a string representation of the part state.
-func (s partWrapperState) String() string {
- switch s {
- case partStateActive:
- return "active"
- case partStateRemoving:
- return "removing"
- case partStateRemoved:
- return "removed"
- default:
- return fmt.Sprintf("unknown(%d)", int32(s))
- }
-}
-
// partWrapper provides thread-safe reference counting for parts.
// It enables safe concurrent access to parts while managing their lifecycle.
// When the reference count reaches zero, the underlying part is cleaned up.
@@ -57,7 +31,6 @@ type partWrapper struct {
p *part
mp *memPart
ref int32
- state int32
removable atomic.Bool
}
@@ -65,10 +38,9 @@ type partWrapper struct {
// The part starts in the active state.
func newPartWrapper(mp *memPart, p *part) *partWrapper {
pw := &partWrapper{
- mp: mp,
- p: p,
- ref: 1,
- state: int32(partStateActive),
+ mp: mp,
+ p: p,
+ ref: 1,
}
return pw
@@ -78,11 +50,6 @@ func newPartWrapper(mp *memPart, p *part) *partWrapper {
// Returns true if the reference was successfully acquired (part is still active),
// false if the part is being removed or has been removed.
func (pw *partWrapper) acquire() bool {
- // Check state first to avoid unnecessary atomic operations
- if atomic.LoadInt32(&pw.state) != int32(partStateActive) {
- return false
- }
-
// Try to increment reference count
for {
oldRef := atomic.LoadInt32(&pw.ref)
@@ -91,11 +58,6 @@ func (pw *partWrapper) acquire() bool {
return false
}
- // Double-check state hasn't changed
- if atomic.LoadInt32(&pw.state) != int32(partStateActive) {
- return false
- }
-
// Try to atomically increment
if atomic.CompareAndSwapInt32(&pw.ref, oldRef, oldRef+1) {
return true
@@ -129,9 +91,6 @@ func (pw *partWrapper) release() {
// cleanup performs the actual cleanup when reference count reaches zero.
// This includes closing the part and potentially removing files from disk.
func (pw *partWrapper) cleanup() {
- // Mark as removed
- atomic.StoreInt32(&pw.state, int32(partStateRemoved))
-
// Release memory part if it exists
if pw.mp != nil {
ReleaseMemPart(pw.mp)
@@ -161,8 +120,6 @@ func (pw *partWrapper) cleanup() {
// Once marked for removal, no new references can be acquired.
// The part will be physically removed when the reference count reaches zero.
func (pw *partWrapper) markForRemoval() {
- // Transition to removing state
- atomic.StoreInt32(&pw.state, int32(partStateRemoving))
// Mark as removable for cleanup
pw.removable.Store(true)
}
@@ -178,26 +135,6 @@ func (pw *partWrapper) refCount() int32 {
return atomic.LoadInt32(&pw.ref)
}
-// getState returns the current state of the part.
-func (pw *partWrapper) getState() partWrapperState {
- return partWrapperState(atomic.LoadInt32(&pw.state))
-}
-
-// isActive returns true if the part is in the active state.
-func (pw *partWrapper) isActive() bool {
- return atomic.LoadInt32(&pw.state) == int32(partStateActive)
-}
-
-// isRemoving returns true if the part is in the removing state.
-func (pw *partWrapper) isRemoving() bool {
- return atomic.LoadInt32(&pw.state) == int32(partStateRemoving)
-}
-
-// isRemoved returns true if the part is in the removed state.
-func (pw *partWrapper) isRemoved() bool {
- return atomic.LoadInt32(&pw.state) == int32(partStateRemoved)
-}
-
// isMemPart returns true if this wrapper contains a memory part.
func (pw *partWrapper) isMemPart() bool {
// A memory part typically has no file system path or is stored in memory
@@ -206,11 +143,10 @@ func (pw *partWrapper) isMemPart() bool {
// String returns a string representation of the partWrapper.
func (pw *partWrapper) String() string {
- state := pw.getState()
refCount := pw.refCount()
if pw.p == nil && pw.mp == nil {
- return fmt.Sprintf("partWrapper{id=nil, state=%s, ref=%d}", state, refCount)
+ return fmt.Sprintf("partWrapper{id=nil, ref=%d}", refCount)
}
if pw.mp != nil {
@@ -218,12 +154,12 @@ func (pw *partWrapper) String() string {
if pw.mp.partMetadata != nil {
id = pw.mp.partMetadata.ID
}
- return fmt.Sprintf("partWrapper{id=%d, state=%s, ref=%d, memPart=true}",
- id, state, refCount)
+ return fmt.Sprintf("partWrapper{id=%d, ref=%d, memPart=true}",
+ id, refCount)
}
if pw.p == nil {
- return fmt.Sprintf("partWrapper{id=nil, state=%s, ref=%d, part=nil}", state, refCount)
+ return fmt.Sprintf("partWrapper{id=nil, ref=%d, part=nil}", refCount)
}
// Handle case where p.partMetadata might be nil after cleanup
@@ -238,8 +174,8 @@ func (pw *partWrapper) String() string {
path = "unknown"
}
- return fmt.Sprintf("partWrapper{id=%d, state=%s, ref=%d, path=%s}",
- id, state, refCount, path)
+ return fmt.Sprintf("partWrapper{id=%d, ref=%d, path=%s}",
+ id, refCount, path)
}
// overlapsKeyRange checks if the part overlaps with the given key range.
diff --git a/banyand/internal/sidx/part_wrapper_test.go b/banyand/internal/sidx/part_wrapper_test.go
index 9a1a0971..c2267808 100644
--- a/banyand/internal/sidx/part_wrapper_test.go
+++ b/banyand/internal/sidx/part_wrapper_test.go
@@ -38,7 +38,6 @@ func TestPartWrapper_BasicLifecycle(t *testing.T) {
pw := newPartWrapper(nil, p)
require.NotNil(t, pw)
assert.Equal(t, int32(1), pw.refCount())
- assert.True(t, pw.isActive())
assert.Equal(t, uint64(1), pw.ID())
// Test acquire
@@ -61,10 +60,9 @@ func TestPartWrapper_BasicLifecycle(t *testing.T) {
// Final release should trigger cleanup
pw.release()
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
}
-func TestPartWrapper_StateTransitions(t *testing.T) {
+func TestPartWrapper_MarkForRemovalBehavior(t *testing.T) {
p := &part{
path: "/test/part/002",
partMetadata: &partMetadata{ID: 2},
@@ -72,29 +70,24 @@ func TestPartWrapper_StateTransitions(t *testing.T) {
pw := newPartWrapper(nil, p)
- // Initial state should be active
- assert.True(t, pw.isActive())
- assert.False(t, pw.isRemoving())
- assert.False(t, pw.isRemoved())
- assert.Equal(t, partStateActive, pw.getState())
+ // Initial reference count should be 1
+ assert.Equal(t, int32(1), pw.refCount())
- // Mark for removal
+ // Mark for removal - should set removable flag
pw.markForRemoval()
- assert.False(t, pw.isActive())
- assert.True(t, pw.isRemoving())
- assert.False(t, pw.isRemoved())
- assert.Equal(t, partStateRemoving, pw.getState())
+ assert.True(t, pw.removable.Load())
- // Should not be able to acquire new references
- assert.False(t, pw.acquire())
+ // Should still be able to acquire references until ref count reaches 0
+ assert.True(t, pw.acquire())
+ assert.Equal(t, int32(2), pw.refCount())
+
+ // Release back to 1
+ pw.release()
assert.Equal(t, int32(1), pw.refCount())
- // Release should transition to removed
+ // Final release should trigger cleanup
pw.release()
- assert.False(t, pw.isActive())
- assert.False(t, pw.isRemoving())
- assert.True(t, pw.isRemoved())
- assert.Equal(t, partStateRemoved, pw.getState())
+ assert.Equal(t, int32(0), pw.refCount())
}
func TestPartWrapper_ConcurrentReferenceCounting(t *testing.T) {
@@ -193,12 +186,10 @@ func TestPartWrapper_ConcurrentAcquireWithMarkForRemoval(t *testing.T) {
// Reference count should be 1 (initial reference)
assert.Equal(t, int32(1), pw.refCount())
- assert.True(t, pw.isRemoving())
// Final cleanup
pw.release()
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
}
func TestPartWrapper_NilPart(t *testing.T) {
@@ -207,7 +198,6 @@ func TestPartWrapper_NilPart(t *testing.T) {
assert.Equal(t, int32(1), pw.refCount())
assert.Nil(t, pw.p)
- assert.True(t, pw.isActive())
// Test acquire/release with nil part
assert.True(t, pw.acquire())
@@ -218,7 +208,6 @@ func TestPartWrapper_NilPart(t *testing.T) {
pw.release()
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
}
func TestPartWrapper_MultipleReleases(t *testing.T) {
@@ -235,16 +224,13 @@ func TestPartWrapper_MultipleReleases(t *testing.T) {
pw.release() // ref count = 2
assert.Equal(t, int32(2), pw.refCount())
- assert.True(t, pw.isActive())
pw.release() // ref count = 1
assert.Equal(t, int32(1), pw.refCount())
- assert.True(t, pw.isActive())
// Final release should trigger cleanup and set ref to 0
pw.release()
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
// Additional releases should not cause issues (though they log warnings)
pw.release()
@@ -257,7 +243,6 @@ func TestPartWrapper_StringRepresentation(t *testing.T) {
pw1 := newPartWrapper(nil, nil)
str1 := pw1.String()
assert.Contains(t, str1, "id=nil")
- assert.Contains(t, str1, "state=active")
assert.Contains(t, str1, "ref=1")
// Test with real part
@@ -268,25 +253,29 @@ func TestPartWrapper_StringRepresentation(t *testing.T) {
pw2 := newPartWrapper(nil, p)
str2 := pw2.String()
assert.Contains(t, str2, "id=6")
- assert.Contains(t, str2, "state=active")
assert.Contains(t, str2, "ref=1")
assert.Contains(t, str2, "path=/test/part/006")
- // Test state changes in string
- pw2.markForRemoval()
+ // Test reference count changes in string
+ pw2.acquire()
str3 := pw2.String()
- assert.Contains(t, str3, "state=removing")
+ assert.Contains(t, str3, "ref=2")
pw2.release()
str4 := pw2.String()
- assert.Contains(t, str4, "state=removed")
+ assert.Contains(t, str4, "ref=1")
}
-func TestPartWrapper_StateStringRepresentation(t *testing.T) {
- assert.Equal(t, "active", partStateActive.String())
- assert.Equal(t, "removing", partStateRemoving.String())
- assert.Equal(t, "removed", partStateRemoved.String())
- assert.Contains(t, partWrapperState(999).String(), "unknown")
+func TestPartWrapper_StringRepresentationWithMemPart(t *testing.T) {
+ // Test with memory part
+ mp := &memPart{
+ partMetadata: &partMetadata{ID: 42},
+ }
+ pw := newPartWrapper(mp, nil)
+ str := pw.String()
+ assert.Contains(t, str, "id=42")
+ assert.Contains(t, str, "ref=1")
+ assert.Contains(t, str, "memPart=true")
}
func TestPartWrapper_CleanupWithRemovableFlag(t *testing.T) {
@@ -303,11 +292,10 @@ func TestPartWrapper_CleanupWithRemovableFlag(t *testing.T) {
// Mark for removal sets the flag
pw.markForRemoval()
assert.True(t, pw.removable.Load())
- assert.True(t, pw.isRemoving())
// Release should trigger cleanup
pw.release()
- assert.True(t, pw.isRemoved())
+ assert.Equal(t, int32(0), pw.refCount())
}
// Benchmark tests.
@@ -329,7 +317,7 @@ func BenchmarkPartWrapper_AcquireRelease(b *testing.B) {
})
}
-func BenchmarkPartWrapper_StateCheck(b *testing.B) {
+func BenchmarkPartWrapper_RefCountCheck(b *testing.B) {
p := &part{
path: "/bench/part",
partMetadata: &partMetadata{ID: 1},
@@ -339,7 +327,7 @@ func BenchmarkPartWrapper_StateCheck(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
- _ = pw.isActive()
+ _ = pw.refCount()
}
}
@@ -359,12 +347,10 @@ func TestPartWrapper_CleanupPreventNegativeRefCount(t *testing.T) {
// Release back to 1
pw.release()
assert.Equal(t, int32(1), pw.refCount())
- assert.True(t, pw.isActive())
// Final release should trigger cleanup and set ref to 0
pw.release()
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
// Additional releases should not make ref count go further negative than logged
// The implementation allows negative counts but logs warnings
@@ -417,7 +403,6 @@ func TestPartWrapper_CleanupWithConcurrentAccess(t *testing.T) {
// Final cleanup
pw.release()
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
}
func TestPartWrapper_CleanupStateTransition(t *testing.T) {
@@ -428,23 +413,16 @@ func TestPartWrapper_CleanupStateTransition(t *testing.T) {
pw := newPartWrapper(nil, p)
- // Verify initial state
- assert.True(t, pw.isActive())
- assert.False(t, pw.isRemoving())
- assert.False(t, pw.isRemoved())
+ // Verify initial reference count
+ assert.Equal(t, int32(1), pw.refCount())
- // Mark for removal should change state but not trigger cleanup yet
+ // Mark for removal should set removable flag but not trigger cleanup yet
pw.markForRemoval()
- assert.False(t, pw.isActive())
- assert.True(t, pw.isRemoving())
- assert.False(t, pw.isRemoved())
+ assert.True(t, pw.removable.Load())
assert.Equal(t, int32(1), pw.refCount()) // Should still be 1
- // Release should trigger cleanup and change state to removed
+ // Release should trigger cleanup and set ref count to 0
pw.release()
- assert.False(t, pw.isActive())
- assert.False(t, pw.isRemoving())
- assert.True(t, pw.isRemoved())
assert.Equal(t, int32(0), pw.refCount())
}
@@ -453,15 +431,13 @@ func TestPartWrapper_CleanupWithNilPart(t *testing.T) {
// Verify cleanup works correctly with nil part
assert.Equal(t, int32(1), pw.refCount())
- assert.True(t, pw.isActive())
// Mark for removal
pw.markForRemoval()
- assert.True(t, pw.isRemoving())
+ assert.True(t, pw.removable.Load())
// Release should complete cleanup without issues
pw.release()
- assert.True(t, pw.isRemoved())
assert.Equal(t, int32(0), pw.refCount())
// Additional releases should be handled gracefully
@@ -498,7 +474,6 @@ func TestPartWrapper_CleanupRaceCondition(t *testing.T) {
// All references should be released, cleanup should have occurred exactly once
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
// Verify that no further operations are possible
assert.False(t, pw.acquire())
@@ -515,15 +490,13 @@ func TestPartWrapper_CleanupIdempotency(t *testing.T) {
// Release to trigger cleanup
pw.release()
assert.Equal(t, int32(0), pw.refCount())
- assert.True(t, pw.isRemoved())
// Call cleanup directly multiple times - should be safe
pw.cleanup()
pw.cleanup()
pw.cleanup()
- // State should remain consistent
- assert.True(t, pw.isRemoved())
+ // Reference count should remain consistent
assert.Equal(t, int32(0), pw.refCount())
}
diff --git a/banyand/internal/sidx/sidx.go b/banyand/internal/sidx/sidx.go
index 2436b379..aa7258dc 100644
--- a/banyand/internal/sidx/sidx.go
+++ b/banyand/internal/sidx/sidx.go
@@ -20,7 +20,6 @@ package sidx
import (
"container/heap"
"context"
- "encoding/json"
"math"
"os"
"path/filepath"
@@ -32,37 +31,25 @@ import (
"github.com/apache/skywalking-banyandb/api/common"
modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
- "github.com/apache/skywalking-banyandb/banyand/internal/storage"
"github.com/apache/skywalking-banyandb/banyand/protector"
"github.com/apache/skywalking-banyandb/pkg/cgroups"
"github.com/apache/skywalking-banyandb/pkg/fs"
"github.com/apache/skywalking-banyandb/pkg/logger"
"github.com/apache/skywalking-banyandb/pkg/pool"
- "github.com/apache/skywalking-banyandb/pkg/run"
- "github.com/apache/skywalking-banyandb/pkg/watcher"
)
const maxBlockLength = 8 * 1024
// sidx implements the SIDX interface with introduction channels for async operations.
type sidx struct {
- fileSystem fs.FileSystem
- snapshot *snapshot
- introductions chan *introduction
- flushCh chan *flusherIntroduction
- mergeCh chan *mergerIntroduction
- syncCh chan *SyncIntroduction
- loopCloser *run.Closer
- l *logger.Logger
- pm protector.Memory
- root string
- gc garbageCleaner
- totalIntroduceLoopStarted atomic.Int64
- totalIntroduceLoopFinished atomic.Int64
- totalQueries atomic.Int64
- totalWrites atomic.Int64
- curPartID uint64
- mu sync.RWMutex
+ fileSystem fs.FileSystem
+ snapshot *snapshot
+ l *logger.Logger
+ pm protector.Memory
+ root string
+ totalQueries atomic.Int64
+ totalWrites atomic.Int64
+ mu sync.RWMutex
}
// NewSIDX creates a new SIDX instance with introduction channels.
@@ -76,65 +63,23 @@ func NewSIDX(fileSystem fs.FileSystem, opts *Options) (SIDX, error) {
}
s := &sidx{
- fileSystem: fileSystem,
- introductions: make(chan *introduction),
- flushCh: make(chan *flusherIntroduction),
- mergeCh: make(chan *mergerIntroduction),
- syncCh: make(chan *SyncIntroduction),
- loopCloser: run.NewCloser(1 + 1),
- l: logger.GetLogger().Named("sidx"),
- pm: opts.Memory,
- root: opts.Path,
+ fileSystem: fileSystem,
+ l: logger.GetLogger().Named("sidx"),
+ pm: opts.Memory,
+ root: opts.Path,
}
- // Initialize garbage collector
- s.gc.init(s)
-
// Initialize sidx
- epoch := s.init()
-
- // Start introducer loop with loaded epoch
- watcherCh := make(watcher.Channel, 10)
- go s.introducerLoop(s.flushCh, s.mergeCh, s.syncCh, watcherCh, epoch)
-
+ s.init(opts.AvailablePartIDs)
return s, nil
}
-// SyncCh returns the sync channel for external synchronization.
-func (s *sidx) SyncCh() chan<- *SyncIntroduction {
- return s.syncCh
-}
-
-func (s *sidx) MustAddMemPart(ctx context.Context, mp *memPart) {
- // Generate part ID using atomic increment
- partID := atomic.AddUint64(&s.curPartID, 1)
-
- // Create introduction
- intro := generateIntroduction()
- intro.memPart = mp
- intro.memPart.partMetadata.ID = partID
- intro.applied = make(chan struct{})
-
- // Send to introducer loop
- select {
- case s.introductions <- intro:
- // Wait for introduction to be applied
- <-intro.applied
- releaseIntroduction(intro)
- return
- case <-ctx.Done():
- releaseIntroduction(intro)
- ReleaseMemPart(mp)
- return
- }
-}
-
-// Write implements SIDX interface.
-func (s *sidx) Write(ctx context.Context, reqs []WriteRequest, segmentID int64) error {
+// ConvertToMemPart converts a write request to a memPart.
+func (s *sidx) ConvertToMemPart(reqs []WriteRequest, segmentID int64) (*MemPart, error) {
// Validate requests
for _, req := range reqs {
if err := req.Validate(); err != nil {
- return err
+ return nil, err
}
}
@@ -152,29 +97,8 @@ func (s *sidx) Write(ctx context.Context, reqs []WriteRequest, segmentID int64)
// Create memory part from elements
mp := GenerateMemPart()
mp.mustInitFromElements(es)
-
- // Generate part ID using atomic increment
- partID := atomic.AddUint64(&s.curPartID, 1)
-
- // Create introduction
- intro := generateIntroduction()
- intro.memPart = mp
- intro.memPart.partMetadata.ID = partID
- intro.memPart.partMetadata.SegmentID = segmentID
- intro.applied = make(chan struct{})
-
- // Send to introducer loop
- select {
- case s.introductions <- intro:
- // Wait for introduction to be applied
- <-intro.applied
- releaseIntroduction(intro)
- return nil
- case <-ctx.Done():
- releaseIntroduction(intro)
- ReleaseMemPart(mp)
- return ctx.Err()
- }
+ mp.partMetadata.SegmentID = segmentID
+ return mp, nil
}
// Query implements SIDX interface.
@@ -288,7 +212,7 @@ func selectPartsForQuery(snap *snapshot, minKey, maxKey int64) []*part {
var selectedParts []*part
for _, pw := range snap.parts {
- if pw.isActive() && pw.overlapsKeyRange(minKey, maxKey) {
+ if pw.overlapsKeyRange(minKey, maxKey) {
selectedParts = append(selectedParts, pw.p)
}
}
@@ -433,24 +357,25 @@ func (s *sidx) Stats(_ context.Context) (*Stats, error) {
}
// Flush implements Flusher interface.
-func (s *sidx) Flush() error {
+func (s *sidx) Flush(partIDsToFlush map[uint64]struct{}) (*FlusherIntroduction, error) {
// Get current memory parts that need flushing
snap := s.currentSnapshot()
if snap == nil {
- return nil
+ return nil, nil
}
defer snap.decRef()
// Create flush introduction
flushIntro := generateFlusherIntroduction()
- defer releaseFlusherIntroduction(flushIntro)
- flushIntro.applied = make(chan struct{})
// Select memory parts to flush
for _, pw := range snap.parts {
- if !pw.isMemPart() || !pw.isActive() {
+ if _, ok := partIDsToFlush[pw.ID()]; !ok {
continue
}
+ if !pw.isMemPart() {
+ logger.Panicf("sidx part %d is not a memory part", pw.ID())
+ }
partPath := partPath(s.root, pw.ID())
pw.mp.mustFlush(s.fileSystem, partPath)
if l := s.l.Debug(); l.Enabled() {
@@ -463,26 +388,15 @@ func (s *sidx) Flush() error {
flushIntro.flushed[newPW.ID()] = newPW
}
- if len(flushIntro.flushed) == 0 {
- return nil
+ if len(flushIntro.flushed) != len(partIDsToFlush) {
+ logger.Panicf("expected %d parts to flush, but got %d", len(partIDsToFlush), len(flushIntro.flushed))
+ return nil, nil
}
-
- // Send to introducer loop
- s.flushCh <- flushIntro
-
- // Wait for flush to complete
- <-flushIntro.applied
-
- return nil
+ return flushIntro, nil
}
// Close implements SIDX interface.
func (s *sidx) Close() error {
- if s.loopCloser != nil {
- s.loopCloser.Done()
- s.loopCloser.CloseThenWait()
- }
-
// Close current snapshot
s.mu.Lock()
if s.snapshot != nil {
@@ -510,44 +424,6 @@ func (s *sidx) currentSnapshot() *snapshot {
return nil
}
-// persistSnapshot persists the snapshot to disk.
-func (s *sidx) persistSnapshot(snapshot *snapshot) {
- var partNames []string
- for i := range snapshot.parts {
- partNames = append(partNames, partName(snapshot.parts[i].ID()))
- }
- s.mustWriteSnapshot(snapshot.epoch, partNames)
- s.gc.registerSnapshot(snapshot)
-}
-
-func (s *sidx) mustWriteSnapshot(snapshot uint64, partNames []string) {
- data, err := json.Marshal(partNames)
- if err != nil {
- logger.Panicf("cannot marshal partNames to JSON: %s", err)
- }
- snapshotPath := filepath.Join(s.root, snapshotName(snapshot))
- lf, err := s.fileSystem.CreateLockFile(snapshotPath, storage.FilePerm)
- if err != nil {
- logger.Panicf("cannot create lock file %s: %s", snapshotPath, err)
- }
- n, err := lf.Write(data)
- if err != nil {
- logger.Panicf("cannot write snapshot %s: %s", snapshotPath, err)
- }
- if n != len(data) {
- logger.Panicf("unexpected number of bytes written to %s; got %d; want %d", snapshotPath, n, len(data))
- }
-}
-
-// Helper methods for metrics.
-func (s *sidx) incTotalIntroduceLoopStarted(_ string) {
- s.totalIntroduceLoopStarted.Add(1)
-}
-
-func (s *sidx) incTotalIntroduceLoopFinished(_ string) {
- s.totalIntroduceLoopFinished.Add(1)
-}
-
// blockCursor represents a cursor for iterating through a loaded block, similar to query_by_ts.go.
type blockCursor struct {
p *part
@@ -782,20 +658,19 @@ func releaseBlockCursor(bc *blockCursor) {
blockCursorPool.Put(bc)
}
-func (s *sidx) init() uint64 {
+func (s *sidx) init(availablePartIDs []uint64) {
if _, err := os.Stat(s.root); os.IsNotExist(err) {
s.l.Debug().Str("path", s.root).Msg("sidx directory does not exist")
- return 0
+ return
}
entries := s.fileSystem.ReadDir(s.root)
if len(entries) == 0 {
s.l.Debug().Str("path", s.root).Msg("no existing sidx data found")
- return 0
+ return
}
var loadedParts []uint64
- var loadedSnapshots []uint64
var needToDelete []string
for i := range entries {
@@ -809,17 +684,6 @@ func (s *sidx) init() uint64 {
loadedParts = append(loadedParts, p)
continue
}
-
- if filepath.Ext(entries[i].Name()) != snapshotSuffix {
- continue
- }
- snapshot, err := parseSnapshot(entries[i].Name())
- if err != nil {
- s.l.Info().Err(err).Str("name", entries[i].Name()).Msg("cannot parse snapshot file name, skipping")
- needToDelete = append(needToDelete, entries[i].Name())
- continue
- }
- loadedSnapshots = append(loadedSnapshots, snapshot)
}
for i := range needToDelete {
@@ -827,62 +691,45 @@ func (s *sidx) init() uint64 {
s.fileSystem.MustRMAll(filepath.Join(s.root, needToDelete[i]))
}
- if len(loadedParts) == 0 || len(loadedSnapshots) == 0 {
- s.l.Debug().Msg("no valid parts or snapshots found")
- return 0
+ if len(loadedParts) == 0 {
+ s.l.Debug().Msg("no valid parts found")
+ return
}
- sort.Slice(loadedSnapshots, func(i, j int) bool {
- return loadedSnapshots[i] > loadedSnapshots[j]
- })
-
- latestEpoch := loadedSnapshots[0]
- s.loadSnapshot(latestEpoch, loadedParts)
+ s.loadSnapshot(loadedParts, availablePartIDs)
- s.l.Info().Uint64("epoch", latestEpoch).Int("parts", len(loadedParts)).Msg("loaded existing sidx data")
- return latestEpoch
+ s.l.Info().Int("parts", len(loadedParts)).Msg("loaded existing sidx data")
}
-func (s *sidx) loadSnapshot(epoch uint64, loadedParts []uint64) {
- partIDs := mustReadSnapshot(s.fileSystem, s.root, epoch)
- snp := newSnapshot(nil, epoch)
- needToPersist := false
+func (s *sidx) loadSnapshot(loadedParts, availablePartIDs []uint64) {
+ snp := newSnapshot(nil)
for _, id := range loadedParts {
var find bool
- for j := range partIDs {
- if id == partIDs[j] {
+ for j := range availablePartIDs {
+ if id == availablePartIDs[j] {
find = true
break
}
}
if !find {
- s.gc.removePart(id)
+ s.fileSystem.MustRMAll(partPath(s.root, id))
continue
}
err := validatePartMetadata(s.fileSystem, partPath(s.root, id))
if err != nil {
s.l.Info().Err(err).Uint64("id", id).Msg("cannot validate part metadata. skip and delete it")
- s.gc.removePart(id)
- needToPersist = true
+ s.fileSystem.MustRMAll(partPath(s.root, id))
continue
}
partPath := partPath(s.root, id)
part := mustOpenPart(id, partPath, s.fileSystem)
pw := newPartWrapper(nil, part)
snp.addPart(pw)
- if s.curPartID < id {
- s.curPartID = id
- }
}
- s.gc.registerSnapshot(snp)
- s.gc.clean()
if snp.getPartCount() < 1 {
snp.release()
return
}
snp.acquire()
s.snapshot = snp
- if needToPersist {
- s.persistSnapshot(snp)
- }
}
diff --git a/banyand/internal/sidx/sidx_test.go b/banyand/internal/sidx/sidx_test.go
index 1025cad1..0c457cc5 100644
--- a/banyand/internal/sidx/sidx_test.go
+++ b/banyand/internal/sidx/sidx_test.go
@@ -61,6 +61,16 @@ func createTestSIDX(t *testing.T) SIDX {
return sidx
}
+func writeTestData(t *testing.T, sidx SIDX, reqs []WriteRequest, segmentID int64, partID uint64) {
+ // Convert write requests to MemPart
+ memPart, err := sidx.ConvertToMemPart(reqs, segmentID)
+ require.NoError(t, err)
+ require.NotNil(t, memPart)
+
+ // Introduce the MemPart to SIDX
+ sidx.IntroduceMemPart(partID, memPart)
+}
+
func createTestTag(name, value string) Tag {
return Tag{
Name: name,
@@ -99,8 +109,7 @@ func TestSIDX_Write_SingleRequest(t *testing.T) {
createTestWriteRequest(1, 100, "data1", createTestTag("tag1", "value1")),
}
- err := sidx.Write(ctx, reqs, 1)
- assert.NoError(t, err)
+ writeTestData(t, sidx, reqs, 1, 1) // Test with segmentID=1, partID=1
// Verify stats
stats, err := sidx.Stats(ctx)
@@ -123,8 +132,7 @@ func TestSIDX_Write_BatchRequest(t *testing.T) {
createTestWriteRequest(2, 200, "data3", createTestTag("tag2", "value3")),
}
- err := sidx.Write(ctx, reqs, 1)
- assert.NoError(t, err)
+ writeTestData(t, sidx, reqs, 2, 2) // Test with segmentID=2, partID=2
// Verify stats
stats, err := sidx.Stats(ctx)
@@ -138,8 +146,6 @@ func TestSIDX_Write_Validation(t *testing.T) {
assert.NoError(t, sidx.Close())
}()
- ctx := context.Background()
-
tests := []struct {
name string
req WriteRequest
@@ -169,7 +175,7 @@ func TestSIDX_Write_Validation(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- err := sidx.Write(ctx, []WriteRequest{tt.req}, 1)
+ _, err := sidx.ConvertToMemPart([]WriteRequest{tt.req}, 12) // Test with segmentID=12
if tt.expectErr {
assert.Error(t, err)
} else {
@@ -185,8 +191,6 @@ func TestSIDX_Write_WithTags(t *testing.T) {
assert.NoError(t, sidx.Close())
}()
- ctx := context.Background()
-
// Write with multiple tags
tags := []Tag{
createTestTag("service", "user-service"),
@@ -198,8 +202,7 @@ func TestSIDX_Write_WithTags(t *testing.T) {
createTestWriteRequest(1, 100, "trace-data", tags...),
}
- err := sidx.Write(ctx, reqs, 1)
- assert.NoError(t, err)
+ writeTestData(t, sidx, reqs, 3, 3) // Test with segmentID=3, partID=3
}
// Query Operation Tests.
@@ -217,8 +220,7 @@ func TestSIDX_Query_BasicQuery(t *testing.T) {
createTestWriteRequest(1, 100, "data1"),
createTestWriteRequest(1, 101, "data2"),
}
- err := sidx.Write(ctx, reqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, reqs, 4, 4) // Test with segmentID=4, partID=4
// Wait for introducer loop to process
waitForIntroducerLoop()
@@ -267,8 +269,7 @@ func TestSIDX_Query_KeyRangeFilter(t *testing.T) {
createTestWriteRequest(1, 150, "data150"),
createTestWriteRequest(1, 200, "data200"),
}
- err := sidx.Write(ctx, reqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, reqs, 5, 5) // Test with segmentID=5, partID=5
// Wait for introducer loop to process
waitForIntroducerLoop()
@@ -321,8 +322,7 @@ func TestSIDX_Query_Ordering(t *testing.T) {
createTestWriteRequest(3, 75, "series3-data75"),
createTestWriteRequest(3, 175, "series3-data175"),
}
- err := sidx.Write(ctx, reqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, reqs, 6, 6) // Test with segmentID=6, partID=6
// Wait for introducer loop to process
waitForIntroducerLoop()
@@ -423,8 +423,7 @@ func TestSIDX_Query_WithArrValues(t *testing.T) {
createTestWriteRequest(1, 150, "data150"),
createTestWriteRequest(1, 200, "data200"),
}
- err := sidx.Write(ctx, reqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, reqs, 7, 7) // Test with segmentID=7, partID=7
// Wait for introducer loop to process
waitForIntroducerLoop()
@@ -527,8 +526,7 @@ func TestSIDX_WriteQueryIntegration(t *testing.T) {
createTestWriteRequest(2, 180, "series2-data2", createTestTag("env", "dev")),
}
- err := sidx.Write(ctx, reqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, reqs, 8, 8) // Test with segmentID=8, partID=8
// Test 1: Query single series
queryReq := createTestQueryRequest(1)
@@ -588,8 +586,7 @@ func TestSIDX_DataConsistency(t *testing.T) {
reqs = append(reqs, createTestWriteRequest(1, key, data))
}
- err := sidx.Write(ctx, reqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, reqs, 9, 9) // Test with segmentID=9, partID=9
// Query back and verify data integrity
queryReq := createTestQueryRequest(1)
@@ -635,8 +632,7 @@ func TestSIDX_LargeDataset(t *testing.T) {
))
}
- err := sidx.Write(ctx, reqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, reqs, 10, 10) // Test with segmentID=10, partID=10
// Query back and verify we can handle large result sets
queryReq := QueryRequest{
@@ -682,9 +678,13 @@ func TestSIDX_ConcurrentWrites(t *testing.T) {
reqs = append(reqs, createTestWriteRequest(seriesID, key, data))
}
- if err := sidx.Write(ctx, reqs, 1); err != nil {
+ // Convert to MemPart and introduce
+ memPart, err := sidx.ConvertToMemPart(reqs, int64(goroutineID+12)) // Test with varied segmentID
+ if err != nil {
errors <- err
+ return
}
+ sidx.IntroduceMemPart(uint64(goroutineID+12), memPart) // Test with varied partID
}(g)
}
@@ -714,8 +714,7 @@ func TestSIDX_ConcurrentReadsWrites(t *testing.T) {
initialReqs := []WriteRequest{
createTestWriteRequest(1, 100, "initial-data"),
}
- err := sidx.Write(ctx, initialReqs, 1)
- require.NoError(t, err)
+ writeTestData(t, sidx, initialReqs, 11, 11) // Test with segmentID=11, partID=11
var wg sync.WaitGroup
numReaders := 5
@@ -756,7 +755,10 @@ func TestSIDX_ConcurrentReadsWrites(t *testing.T) {
int64(writeCount),
fmt.Sprintf("writer-%d-data-%d", writerID, writeCount),
)
- sidx.Write(ctx, []WriteRequest{req}, 1) // Ignore errors during concurrent stress
+ // Convert to MemPart and introduce (ignore errors during concurrent stress)
+ if memPart, err := sidx.ConvertToMemPart([]WriteRequest{req}, int64(writerID+13)); err == nil { // Test with varied segmentID
+ sidx.IntroduceMemPart(uint64(writerID+13), memPart) // Test with varied partID
+ }
writeCount++
}
}(i)
diff --git a/banyand/internal/sidx/snapshot.go b/banyand/internal/sidx/snapshot.go
index e99182d6..c59c3c39 100644
--- a/banyand/internal/sidx/snapshot.go
+++ b/banyand/internal/sidx/snapshot.go
@@ -18,20 +18,13 @@
package sidx
import (
- "encoding/json"
"fmt"
- "path/filepath"
"strconv"
"sync/atomic"
- "github.com/apache/skywalking-banyandb/pkg/fs"
"github.com/apache/skywalking-banyandb/pkg/logger"
)
-const (
- snapshotSuffix = ".snp"
-)
-
// snapshot represents an immutable collection of parts at a specific epoch.
// It provides safe concurrent access to parts through reference counting and
// enables queries to work with a consistent view of data.
@@ -39,19 +32,15 @@ type snapshot struct {
// parts contains all active parts sorted by epoch (oldest first)
parts []*partWrapper
- // epoch uniquely identifies this snapshot generation
- epoch uint64
-
// ref is the atomic reference counter for safe concurrent access
ref int32
}
// newSnapshot creates a new snapshot with the given parts and epoch.
// The snapshot starts with a reference count of 1.
-func newSnapshot(parts []*partWrapper, epoch uint64) *snapshot {
+func newSnapshot(parts []*partWrapper) *snapshot {
s := &snapshot{}
s.parts = append(s.parts[:0], parts...)
- s.epoch = epoch
s.ref = 1
// Acquire references to all parts to ensure they remain valid
@@ -60,7 +49,6 @@ func newSnapshot(parts []*partWrapper, epoch uint64) *snapshot {
// Part is being removed, skip it
logger.GetLogger().Warn().
Uint64("part_id", pw.ID()).
- Uint64("epoch", epoch).
Msg("part unavailable during snapshot creation")
}
}
@@ -90,7 +78,6 @@ func (s *snapshot) release() {
if newRef < 0 {
logger.GetLogger().Warn().
Int32("ref", newRef).
- Uint64("epoch", s.epoch).
Msg("snapshot reference count went negative")
return
}
@@ -104,10 +91,6 @@ func (s *snapshot) getParts(minKey, maxKey int64) []*partWrapper {
var result []*partWrapper
for _, pw := range s.parts {
- if !pw.isActive() {
- continue
- }
-
part := pw.p
if part == nil || part.partMetadata == nil {
continue
@@ -133,7 +116,7 @@ func (s *snapshot) getPartsAll() []*partWrapper {
var result []*partWrapper
for _, pw := range s.parts {
- if pw.isActive() {
+ if !pw.removable.Load() {
result = append(result, pw)
}
}
@@ -143,18 +126,7 @@ func (s *snapshot) getPartsAll() []*partWrapper {
// getPartCount returns the number of parts in the snapshot.
func (s *snapshot) getPartCount() int {
- count := 0
- for _, pw := range s.parts {
- if pw.isActive() {
- count++
- }
- }
- return count
-}
-
-// getEpoch returns the snapshot's epoch.
-func (s *snapshot) getEpoch() uint64 {
- return s.epoch
+ return len(s.getPartsAll())
}
// refCount returns the current reference count (for testing/debugging).
@@ -215,61 +187,24 @@ func (s *snapshot) reset() {
}
s.parts = s.parts[:0]
- s.epoch = 0
s.ref = 0
}
// String returns a string representation of the snapshot.
func (s *snapshot) String() string {
activeCount := s.getPartCount()
- return fmt.Sprintf("snapshot{epoch=%d, parts=%d/%d, ref=%d}",
- s.epoch, activeCount, len(s.parts), s.refCount())
-}
-
-func snapshotName(snapshot uint64) string {
- return fmt.Sprintf("%016x%s", snapshot, snapshotSuffix)
-}
-
-func parseSnapshot(name string) (uint64, error) {
- if filepath.Ext(name) != snapshotSuffix {
- return 0, fmt.Errorf("invalid snapshot file ext")
- }
- if len(name) < 16 {
- return 0, fmt.Errorf("invalid snapshot file name")
- }
- return parseEpoch(name[:16])
+ return fmt.Sprintf("snapshot{parts=%d/%d, ref=%d}",
+ activeCount, len(s.parts), s.refCount())
}
func parseEpoch(epochStr string) (uint64, error) {
return strconv.ParseUint(epochStr, 16, 64)
}
-func mustReadSnapshot(fileSystem fs.FileSystem, root string, snapshot uint64) []uint64 {
- snapshotPath := filepath.Join(root, snapshotName(snapshot))
- data, err := fileSystem.Read(snapshotPath)
- if err != nil {
- logger.GetLogger().Panic().Err(err).Str("path", snapshotPath).Msg("cannot read snapshot")
- }
- var partNames []string
- if err := json.Unmarshal(data, &partNames); err != nil {
- logger.GetLogger().Panic().Err(err).Str("path", snapshotPath).Msg("cannot parse snapshot")
- }
- var result []uint64
- for i := range partNames {
- e, err := parseEpoch(partNames[i])
- if err != nil {
- logger.GetLogger().Panic().Err(err).Str("name", partNames[i]).Msg("cannot parse part name")
- }
- result = append(result, e)
- }
- return result
-}
-
// copyAllTo creates a new snapshot with all parts from current snapshot.
-func (s *snapshot) copyAllTo(epoch uint64) *snapshot {
+func (s *snapshot) copyAllTo() *snapshot {
var result snapshot
result.parts = make([]*partWrapper, len(s.parts))
- result.epoch = epoch
result.ref = 1
// Copy all parts and acquire references
@@ -284,9 +219,8 @@ func (s *snapshot) copyAllTo(epoch uint64) *snapshot {
}
// merge creates a new snapshot by merging flushed parts into the current snapshot.
-func (s *snapshot) merge(nextEpoch uint64, nextParts map[uint64]*partWrapper) *snapshot {
+func (s *snapshot) merge(nextParts map[uint64]*partWrapper) *snapshot {
var result snapshot
- result.epoch = nextEpoch
result.ref = 1
for i := 0; i < len(s.parts); i++ {
if n, ok := nextParts[s.parts[i].ID()]; ok {
@@ -301,9 +235,8 @@ func (s *snapshot) merge(nextEpoch uint64, nextParts map[uint64]*partWrapper) *s
}
// remove creates a new snapshot by removing specified parts.
-func (s *snapshot) remove(epoch uint64, toRemove map[uint64]struct{}) *snapshot {
+func (s *snapshot) remove(toRemove map[uint64]struct{}) *snapshot {
var result snapshot
- result.epoch = epoch
result.ref = 1
// Copy parts except those being removed
diff --git a/banyand/internal/sidx/snapshot_test.go b/banyand/internal/sidx/snapshot_test.go
index fd4d5abe..0852cc19 100644
--- a/banyand/internal/sidx/snapshot_test.go
+++ b/banyand/internal/sidx/snapshot_test.go
@@ -29,6 +29,19 @@ import (
"github.com/apache/skywalking-banyandb/pkg/fs"
)
+// writeTestData is a helper function for writing test data using the new pattern.
+func writeTestDataToSIDX(t *testing.T, sidx SIDX, reqs []WriteRequest, segmentID int64, partID uint64) {
+ // Convert write requests to MemPart
+ memPart, err := sidx.ConvertToMemPart(reqs, segmentID)
+ if err != nil {
+ t.Errorf("ConvertToMemPart failed: %v", err)
+ return
+ }
+
+ // Introduce the MemPart to SIDX
+ sidx.IntroduceMemPart(partID, memPart)
+}
+
func TestSnapshot_Creation(t *testing.T) {
// Create test parts with different key ranges
parts := createTestParts(t, []keyRange{
@@ -39,14 +52,10 @@ func TestSnapshot_Creation(t *testing.T) {
defer cleanupTestParts(parts)
// Create snapshot
- epoch := uint64(1001)
- snapshot := newSnapshot(parts, epoch)
+ snapshot := newSnapshot(parts)
defer snapshot.release()
// Verify snapshot properties
- if snapshot.getEpoch() != epoch {
- t.Errorf("expected epoch %d, got %d", epoch, snapshot.getEpoch())
- }
if snapshot.refCount() != 1 {
t.Errorf("expected ref count 1, got %d", snapshot.refCount())
@@ -61,7 +70,7 @@ func TestSnapshot_ReferenceCountingBasic(t *testing.T) {
parts := createTestParts(t, []keyRange{{minKey: 100, maxKey: 199, id: 1}})
defer cleanupTestParts(parts)
- snapshot := newSnapshot(parts, 1001)
+ snapshot := newSnapshot(parts)
// Test acquire
if !snapshot.acquire() {
@@ -85,7 +94,7 @@ func TestSnapshot_ReferenceCountingConcurrent(t *testing.T) {
parts := createTestParts(t, []keyRange{{minKey: 100, maxKey: 199, id: 1}})
defer cleanupTestParts(parts)
- snapshot := newSnapshot(parts, 1001)
+ snapshot := newSnapshot(parts)
defer snapshot.release()
// Simulate concurrent access
@@ -134,7 +143,7 @@ func TestSnapshot_GetPartsByKeyRange(t *testing.T) {
})
defer cleanupTestParts(parts)
- snapshot := newSnapshot(parts, 1001)
+ snapshot := newSnapshot(parts)
defer snapshot.release()
tests := []struct {
@@ -214,7 +223,7 @@ func TestSnapshot_GetPartsAll(t *testing.T) {
})
defer cleanupTestParts(parts)
- snapshot := newSnapshot(parts, 1001)
+ snapshot := newSnapshot(parts)
defer snapshot.release()
allParts := snapshot.getPartsAll()
@@ -229,7 +238,7 @@ func TestSnapshot_GetPartsAll(t *testing.T) {
allParts = snapshot.getPartsAll()
activeCount := 0
for _, pw := range allParts {
- if pw.isActive() {
+ if pw.refCount() > 0 {
activeCount++
}
}
@@ -245,7 +254,7 @@ func TestSnapshot_Validation(t *testing.T) {
})
defer cleanupTestParts(parts)
- snapshot := newSnapshot(parts, 1001)
+ snapshot := newSnapshot(parts)
// Valid snapshot should pass validation
if err := snapshot.validate(); err != nil {
@@ -266,7 +275,7 @@ func TestSnapshot_String(t *testing.T) {
})
defer cleanupTestParts(parts)
- snapshot := newSnapshot(parts, 1001)
+ snapshot := newSnapshot(parts)
defer snapshot.release()
str := snapshot.String()
@@ -274,10 +283,7 @@ func TestSnapshot_String(t *testing.T) {
t.Error("String() should return non-empty string")
}
- // String should contain epoch and part count
- if !contains(str, "epoch=1001") {
- t.Error("String() should contain epoch")
- }
+ // String should contain part count
if !contains(str, "parts=2") {
t.Error("String() should contain part count")
}
@@ -291,7 +297,7 @@ func TestSnapshot_PartManagement(t *testing.T) {
})
defer cleanupTestParts(parts)
- snapshot := newSnapshot(parts, 1001)
+ snapshot := newSnapshot(parts)
defer snapshot.release()
initialCount := snapshot.getPartCount()
@@ -321,17 +327,14 @@ func TestSnapshot_PoolReuse(t *testing.T) {
defer cleanupTestParts(parts)
// Create and release a snapshot
- snapshot1 := newSnapshot(parts, 1001)
+ snapshot1 := newSnapshot(parts)
snapshot1.release()
// Create another snapshot - should potentially reuse the same object
- snapshot2 := newSnapshot(parts, 1002)
+ snapshot2 := newSnapshot(parts)
defer snapshot2.release()
// Should be clean state
- if snapshot2.getEpoch() != 1002 {
- t.Errorf("expected epoch 1002, got %d", snapshot2.getEpoch())
- }
if snapshot2.refCount() != 1 {
t.Errorf("expected ref count 1, got %d", snapshot2.refCount())
}
@@ -370,7 +373,7 @@ func createTestParts(_ *testing.T, ranges []keyRange) []*partWrapper {
func cleanupTestParts(parts []*partWrapper) {
for _, pw := range parts {
- if pw != nil && !pw.isRemoved() {
+ if pw != nil && pw.refCount() > 0 {
pw.release()
}
}
@@ -413,9 +416,7 @@ func TestSnapshotReplacement_Basic(t *testing.T) {
Tags: []Tag{{Name: "test", Value: []byte("snapshot-replacement")}},
}
- if err := sidx.Write(ctx, []WriteRequest{req}, 1); err != nil {
- t.Errorf("write %d failed: %v", i, err)
- }
+ writeTestDataToSIDX(t, sidx, []WriteRequest{req}, int64(i+1), uint64(i+1))
// Verify system remains consistent after each write
stats, err := sidx.Stats(ctx)
@@ -504,9 +505,7 @@ func TestSnapshotReplacement_ConcurrentReadsConsistentData(t *testing.T) {
},
}
- if err := sidx.Write(ctx, reqs, 1); err != nil {
- t.Errorf("write %d failed: %v", i, err)
- }
+ writeTestDataToSIDX(t, sidx, reqs, int64(i+1), uint64(i+1))
time.Sleep(10 * time.Millisecond) // Space out writes
}
@@ -584,7 +583,7 @@ func TestSnapshotReplacement_NoDataRacesDuringReplacement(t *testing.T) {
// Write operation - triggers memory part introduction (snapshot replacement)
reqs := []WriteRequest{
{
- SeriesID: common.SeriesID(id*1000 + j),
+ SeriesID: common.SeriesID(id*1000 + j + 1), // Ensure non-zero SeriesID
Key: int64(id*1000 + j),
Data: []byte(fmt.Sprintf("race-test-%d-%d", id, j)),
Tags: []Tag{
@@ -593,7 +592,7 @@ func TestSnapshotReplacement_NoDataRacesDuringReplacement(t *testing.T) {
},
},
}
- sidx.Write(ctx, reqs, 1)
+ writeTestDataToSIDX(t, sidx, reqs, int64(id+1), uint64(j+1))
case 1:
// Stats operation - accesses current snapshot
sidx.Stats(ctx)
@@ -653,9 +652,7 @@ func TestSnapshotReplacement_MemoryLeaksPrevention(t *testing.T) {
},
}
- if writeErr := sidx.Write(ctx, reqs, 1); writeErr != nil {
- t.Errorf("batch %d write %d failed: %v", i, j, writeErr)
- }
+ writeTestDataToSIDX(t, sidx, reqs, int64(i+1), uint64(j+1))
}
// Verify the system state remains consistent
@@ -714,9 +711,7 @@ func TestSnapshotReplacement_MemoryLeaksPrevention(t *testing.T) {
},
}
- if writeErr := sidx.Write(ctx, reqs, 1); writeErr != nil {
- t.Errorf("concurrent writer %d write %d failed: %v", writerID, j, writeErr)
- }
+ writeTestDataToSIDX(t, sidx, reqs, int64(writerID+1), uint64(j+1))
time.Sleep(3 * time.Millisecond)
}
diff --git a/banyand/internal/sidx/sync.go b/banyand/internal/sidx/sync.go
index 0a671ebb..465df54e 100644
--- a/banyand/internal/sidx/sync.go
+++ b/banyand/internal/sidx/sync.go
@@ -25,6 +25,7 @@ import (
"github.com/apache/skywalking-banyandb/banyand/queue"
"github.com/apache/skywalking-banyandb/pkg/bytes"
"github.com/apache/skywalking-banyandb/pkg/compress/zstd"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
)
// NewPartsToSync creates a new map of parts to sync.
@@ -35,23 +36,17 @@ func NewPartsToSync() map[string][]*Part {
// PartsToSync returns the parts to sync.
func (s *sidx) PartsToSync() []*part {
- if s.loopCloser != nil && s.loopCloser.Closed() {
- return nil
- }
-
- s.mu.RLock()
- snapshot := s.snapshot
+ snapshot := s.currentSnapshot()
if snapshot == nil {
- s.mu.RUnlock()
return nil
}
+ defer snapshot.decRef()
partsToSync := make([]*part, 0, len(snapshot.parts))
for _, pw := range snapshot.parts {
if pw.mp == nil && pw.p.partMetadata.TotalCount > 0 {
partsToSync = append(partsToSync, pw.p)
}
}
- s.mu.RUnlock()
if len(partsToSync) > 1 {
sort.Slice(partsToSync, func(i, j int) bool {
@@ -62,28 +57,44 @@ func (s *sidx) PartsToSync() []*part {
}
// StreamingParts returns the streaming parts.
-func (s *sidx) StreamingParts(partsToSync []*part, group string, shardID uint32, name string) ([]queue.StreamingPartData, []func()) {
+func (s *sidx) StreamingParts(partIDsToSync map[uint64]struct{}, group string, shardID uint32, name string) ([]queue.StreamingPartData, []func()) {
+ snapshot := s.currentSnapshot()
+ if snapshot == nil {
+ return nil, nil
+ }
+ defer snapshot.decRef()
var streamingParts []queue.StreamingPartData
var releaseFuncs []func()
- for _, part := range partsToSync {
- // Create streaming reader for the part
- files, release := createPartFileReaders(part)
- releaseFuncs = append(releaseFuncs, release)
- // Create streaming part sync data
- streamingParts = append(streamingParts, queue.StreamingPartData{
- ID: part.partMetadata.ID,
- Group: group,
- ShardID: shardID,
- Topic: data.TopicTracePartSync.String(),
- Files: files,
- CompressedSizeBytes: part.partMetadata.CompressedSizeBytes,
- UncompressedSizeBytes: part.partMetadata.UncompressedSizeBytes,
- TotalCount: part.partMetadata.TotalCount,
- BlocksCount: part.partMetadata.BlocksCount,
- MinTimestamp: part.partMetadata.SegmentID,
- MinKey: part.partMetadata.MinKey,
- MaxKey: part.partMetadata.MaxKey,
- PartType: name,
+ for _, pw := range snapshot.parts {
+ if _, ok := partIDsToSync[pw.p.partMetadata.ID]; ok {
+ if pw.mp != nil {
+ logger.Panicf("sidx streaming parts: %s, part %d should not a mem part", name, pw.p.partMetadata.ID)
+ return nil, nil
+ }
+ part := pw.p
+ files, release := createPartFileReaders(part)
+ releaseFuncs = append(releaseFuncs, release)
+ streamingParts = append(streamingParts, queue.StreamingPartData{
+ ID: part.partMetadata.ID,
+ Group: group,
+ ShardID: shardID,
+ Topic: data.TopicTracePartSync.String(),
+ Files: files,
+ CompressedSizeBytes: part.partMetadata.CompressedSizeBytes,
+ UncompressedSizeBytes: part.partMetadata.UncompressedSizeBytes,
+ TotalCount: part.partMetadata.TotalCount,
+ BlocksCount: part.partMetadata.BlocksCount,
+ MinTimestamp: part.partMetadata.SegmentID,
+ MinKey: part.partMetadata.MinKey,
+ MaxKey: part.partMetadata.MaxKey,
+ PartType: name,
+ })
+ }
+ }
+
+ if len(streamingParts) > 1 {
+ sort.Slice(streamingParts, func(i, j int) bool {
+ return streamingParts[i].ID < streamingParts[j].ID
})
}
return streamingParts, releaseFuncs
diff --git a/banyand/measure/write_data.go b/banyand/measure/write_data.go
index 93b7bc43..b83ff65f 100644
--- a/banyand/measure/write_data.go
+++ b/banyand/measure/write_data.go
@@ -37,6 +37,11 @@ type syncPartContext struct {
memPart *memPart
}
+func (s *syncPartContext) NewPartType(_ *queue.ChunkedSyncPartContext) error {
+ logger.Panicf("new part type is not supported for measure")
+ return nil
+}
+
func (s *syncPartContext) FinishSync() error {
s.tsTable.mustAddMemPart(s.memPart)
return s.Close()
@@ -181,6 +186,11 @@ type syncSeriesContext struct {
fileName string
}
+func (s *syncSeriesContext) NewPartType(_ *queue.ChunkedSyncPartContext) error {
+ logger.Panicf("new part type is not supported for measure")
+ return nil
+}
+
func (s *syncSeriesContext) FinishSync() error {
if s.streamer != nil {
if err := s.streamer.CompleteSegment(); err != nil {
diff --git a/banyand/queue/queue.go b/banyand/queue/queue.go
index 41eb64a5..14cab1ee 100644
--- a/banyand/queue/queue.go
+++ b/banyand/queue/queue.go
@@ -132,6 +132,7 @@ func (c *ChunkedSyncPartContext) Close() error {
// PartHandler handles individual parts during sync operations.
type PartHandler interface {
+ NewPartType(ctx *ChunkedSyncPartContext) error
FinishSync() error
Close() error
}
diff --git a/banyand/queue/sub/chunked_sync.go b/banyand/queue/sub/chunked_sync.go
index 10eef34e..b07b83c0 100644
--- a/banyand/queue/sub/chunked_sync.go
+++ b/banyand/queue/sub/chunked_sync.go
@@ -325,8 +325,7 @@ func (s *server) processExpectedChunk(stream clusterv1.ChunkedSyncService_SyncPa
for partIndex, partInfo := range req.PartsInfo {
createNewContext := session.partCtx == nil ||
- session.partCtx.ID != partInfo.Id ||
- session.partCtx.PartType != partInfo.PartType
+ session.partCtx.ID != partInfo.Id
if createNewContext && session.partCtx != nil && session.partCtx.Handler != nil {
if err := session.partCtx.Handler.FinishSync(); err != nil {
@@ -354,6 +353,19 @@ func (s *server) processExpectedChunk(stream clusterv1.ChunkedSyncService_SyncPa
return fmt.Errorf("failed to create part handler: %w", err)
}
session.partCtx.Handler = partHandler
+ } else if session.partCtx.PartType != partInfo.PartType {
+ session.partCtx.CompressedSizeBytes = partInfo.CompressedSizeBytes
+ session.partCtx.UncompressedSizeBytes = partInfo.UncompressedSizeBytes
+ session.partCtx.TotalCount = partInfo.TotalCount
+ session.partCtx.BlocksCount = partInfo.BlocksCount
+ session.partCtx.MinTimestamp = partInfo.MinTimestamp
+ session.partCtx.MaxTimestamp = partInfo.MaxTimestamp
+ session.partCtx.MinKey = partInfo.MinKey
+ session.partCtx.MaxKey = partInfo.MaxKey
+ session.partCtx.PartType = partInfo.PartType
+ if err := session.partCtx.Handler.NewPartType(session.partCtx); err != nil {
+ return fmt.Errorf("failed to new part type: %w", err)
+ }
}
if err := s.processPart(session, req, partInfo, partIndex, handler); err != nil {
diff --git a/banyand/queue/sub/chunked_sync_test.go b/banyand/queue/sub/chunked_sync_test.go
index 8fd418e0..0a5922e5 100644
--- a/banyand/queue/sub/chunked_sync_test.go
+++ b/banyand/queue/sub/chunked_sync_test.go
@@ -203,6 +203,10 @@ func (m *MockChunkedSyncHandler) HandleFileChunk(_ *queue.ChunkedSyncPartContext
// MockChunkedSyncPartHandler implements queue.PartHandler for testing.
type MockChunkedSyncPartHandler struct{}
+func (m *MockChunkedSyncPartHandler) NewPartType(_ *queue.ChunkedSyncPartContext) error {
+ return nil
+}
+
func (m *MockChunkedSyncPartHandler) FinishSync() error {
return nil
}
@@ -568,3 +572,213 @@ func TestChunkedSyncOutOfOrderBasic(t *testing.T) {
assert.Contains(t, resp.Error, "got 2")
})
}
+
+func TestChunkedSyncNewPartTypeBehavior(t *testing.T) {
+ // Initialize logger for tests
+ err := logger.Init(logger.Logging{
+ Env: "dev",
+ Level: "info",
+ })
+ require.NoError(t, err)
+
+ tests := []struct {
+ name string
+ firstPartType string
+ secondPartType string
+ description string
+ firstPartID uint64
+ secondPartID uint64
+ expectNewPartTypeCalled bool
+ }{
+ {
+ name: "same_id_different_parttype",
+ firstPartID: 123,
+ firstPartType: "primary",
+ secondPartID: 123, // Same ID
+ secondPartType: "secondary", // Different PartType
+ expectNewPartTypeCalled: true,
+ description: "NewPartType should be called when ID is same but PartType changes",
+ },
+ {
+ name: "same_id_same_parttype",
+ firstPartID: 456,
+ firstPartType: "primary",
+ secondPartID: 456, // Same ID
+ secondPartType: "primary", // Same PartType
+ expectNewPartTypeCalled: false,
+ description: "NewPartType should NOT be called when both ID and PartType are same",
+ },
+ {
+ name: "different_id_same_parttype",
+ firstPartID: 789,
+ firstPartType: "primary",
+ secondPartID: 790, // Different ID
+ secondPartType: "primary", // Same PartType
+ expectNewPartTypeCalled: false,
+ description: "NewPartType should NOT be called when ID changes (CreatePartHandler is called instead)",
+ },
+ {
+ name: "different_id_different_parttype",
+ firstPartID: 111,
+ firstPartType: "primary",
+ secondPartID: 222, // Different ID
+ secondPartType: "secondary", // Different PartType
+ expectNewPartTypeCalled: false,
+ description: "NewPartType should NOT be called when ID changes (CreatePartHandler is called instead)",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Create server
+ s := &server{
+ log: logger.GetLogger("test-server-" + tt.name),
+ chunkedSyncHandlers: make(map[bus.Topic]queue.ChunkedSyncHandler),
+ enableChunkReordering: false,
+ }
+
+ // Create mock handler that tracks NewPartType calls
+ mockHandler := &MockChunkedSyncHandlerWithTracking{}
+ s.chunkedSyncHandlers[data.TopicStreamPartSync] = mockHandler
+
+ // Create mock stream
+ mockStream := &MockSyncPartStream{}
+
+ // Create a session
+ session := &syncSession{
+ sessionID: "test-session-" + tt.name,
+ startTime: time.Now(),
+ chunksReceived: 0,
+ partsProgress: make(map[int]*partProgress),
+ metadata: &clusterv1.SyncMetadata{
+ Group: "test-group",
+ ShardId: 1,
+ Topic: data.TopicStreamPartSync.String(),
+ },
+ }
+
+ // Send first chunk
+ req1 := &clusterv1.SyncPartRequest{
+ SessionId: "test-session-" + tt.name,
+ ChunkIndex: 0,
+ ChunkData: []byte("first-chunk-data"),
+ ChunkChecksum: fmt.Sprintf("%x", crc32.ChecksumIEEE([]byte("first-chunk-data"))),
+ PartsInfo: []*clusterv1.PartInfo{
+ {
+ Id: tt.firstPartID,
+ PartType: tt.firstPartType,
+ CompressedSizeBytes: 100,
+ UncompressedSizeBytes: 200,
+ TotalCount: 10,
+ BlocksCount: 5,
+ MinTimestamp: time.Now().UnixMilli(),
+ MaxTimestamp: time.Now().UnixMilli(),
+ Files: []*clusterv1.FileInfo{
+ {
+ Name: "test-file.dat",
+ Offset: 0,
+ Size: 17,
+ },
+ },
+ },
+ },
+ }
+
+ err := s.processChunk(mockStream, session, req1)
+ require.NoError(t, err, "First chunk should be processed successfully")
+
+ // Reset the NewPartType call tracking
+ mockHandler.resetNewPartTypeCalls()
+
+ // Send second chunk
+ req2 := &clusterv1.SyncPartRequest{
+ SessionId: "test-session-" + tt.name,
+ ChunkIndex: 1,
+ ChunkData: []byte("second-chunk-data"),
+ ChunkChecksum: fmt.Sprintf("%x", crc32.ChecksumIEEE([]byte("second-chunk-data"))),
+ PartsInfo: []*clusterv1.PartInfo{
+ {
+ Id: tt.secondPartID,
+ PartType: tt.secondPartType,
+ CompressedSizeBytes: 150,
+ UncompressedSizeBytes: 250,
+ TotalCount: 15,
+ BlocksCount: 7,
+ MinTimestamp: time.Now().UnixMilli(),
+ MaxTimestamp: time.Now().UnixMilli(),
+ Files: []*clusterv1.FileInfo{
+ {
+ Name: "test-file.dat",
+ Offset: 0,
+ Size: 18,
+ },
+ },
+ },
+ },
+ }
+
+ err = s.processChunk(mockStream, session, req2)
+ require.NoError(t, err, "Second chunk should be processed successfully")
+
+ // Verify NewPartType call behavior
+ if tt.expectNewPartTypeCalled {
+ assert.True(t, mockHandler.newPartTypeCalled, "NewPartType should have been called: %s", tt.description)
+ assert.Len(t, mockHandler.newPartTypeContexts, 1, "NewPartType should have been called exactly once")
+ if len(mockHandler.newPartTypeContexts) > 0 {
+ ctx := mockHandler.newPartTypeContexts[0]
+ assert.Equal(t, tt.secondPartID, ctx.ID, "NewPartType should be called with correct part ID")
+ assert.Equal(t, tt.secondPartType, ctx.PartType, "NewPartType should be called with correct part type")
+ }
+ } else {
+ assert.False(t, mockHandler.newPartTypeCalled, "NewPartType should NOT have been called: %s", tt.description)
+ assert.Len(t, mockHandler.newPartTypeContexts, 0, "NewPartType should not have been called")
+ }
+
+ // Verify that both chunks were processed successfully
+ assert.Len(t, mockStream.sentResponses, 2, "Should have received responses for both chunks")
+ for i, resp := range mockStream.sentResponses {
+ assert.Equal(t, clusterv1.SyncStatus_SYNC_STATUS_CHUNK_RECEIVED, resp.Status,
+ "Chunk %d should be received successfully", i)
+ assert.Empty(t, resp.Error, "Chunk %d should not have errors", i)
+ }
+ })
+ }
+}
+
+// MockChunkedSyncHandlerWithTracking implements queue.ChunkedSyncHandler with tracking capabilities.
+type MockChunkedSyncHandlerWithTracking struct {
+ newPartTypeContexts []*queue.ChunkedSyncPartContext
+ newPartTypeCalled bool
+}
+
+func (m *MockChunkedSyncHandlerWithTracking) CreatePartHandler(_ *queue.ChunkedSyncPartContext) (queue.PartHandler, error) {
+ return &MockChunkedSyncPartHandlerWithTracking{parent: m}, nil
+}
+
+func (m *MockChunkedSyncHandlerWithTracking) HandleFileChunk(_ *queue.ChunkedSyncPartContext, _ []byte) error {
+ return nil
+}
+
+func (m *MockChunkedSyncHandlerWithTracking) resetNewPartTypeCalls() {
+ m.newPartTypeCalled = false
+ m.newPartTypeContexts = nil
+}
+
+// MockChunkedSyncPartHandlerWithTracking implements queue.PartHandler with tracking capabilities.
+type MockChunkedSyncPartHandlerWithTracking struct {
+ parent *MockChunkedSyncHandlerWithTracking
+}
+
+func (m *MockChunkedSyncPartHandlerWithTracking) NewPartType(ctx *queue.ChunkedSyncPartContext) error {
+ m.parent.newPartTypeCalled = true
+ m.parent.newPartTypeContexts = append(m.parent.newPartTypeContexts, ctx)
+ return nil
+}
+
+func (m *MockChunkedSyncPartHandlerWithTracking) FinishSync() error {
+ return nil
+}
+
+func (m *MockChunkedSyncPartHandlerWithTracking) Close() error {
+ return nil
+}
diff --git a/banyand/queue/test/chunked_sync_common.go b/banyand/queue/test/chunked_sync_common.go
index f39f528f..566f36e9 100644
--- a/banyand/queue/test/chunked_sync_common.go
+++ b/banyand/queue/test/chunked_sync_common.go
@@ -232,11 +232,20 @@ func createTestDataPartWithMetadata(files map[string][]byte, group string, shard
type MockPartHandler struct {
receivedFiles map[string][]byte
syncHandler *MockChunkedSyncHandler
+ trackingHandler *MockChunkedSyncHandlerWithTracking
receivedChunks [][]byte
finishSyncCalled bool
closeCalled bool
}
+// NewPartType marks the part as new and tracks the call.
+func (m *MockPartHandler) NewPartType(ctx *queue.ChunkedSyncPartContext) error {
+ if m.trackingHandler != nil {
+ m.trackingHandler.TrackNewPartType(ctx)
+ }
+ return nil
+}
+
// FinishSync marks the sync as finished and closes the handler.
func (m *MockPartHandler) FinishSync() error {
m.finishSyncCalled = true
@@ -310,6 +319,7 @@ func (m *MockChunkedSyncHandler) CreatePartHandler(ctx *queue.ChunkedSyncPartCon
ID: ctx.ID,
Group: ctx.Group,
ShardID: ctx.ShardID,
+ PartType: ctx.PartType,
CompressedSizeBytes: ctx.CompressedSizeBytes,
UncompressedSizeBytes: ctx.UncompressedSizeBytes,
TotalCount: ctx.TotalCount,
@@ -389,3 +399,141 @@ func (m *MockChunkedSyncHandler) GetReceivedContexts() []*queue.ChunkedSyncPartC
}
return result
}
+
+// MockChunkedSyncHandlerWithTracking extends MockChunkedSyncHandler with NewPartType call tracking.
+type MockChunkedSyncHandlerWithTracking struct {
+ *MockChunkedSyncHandler
+ newPartTypeContexts []*queue.ChunkedSyncPartContext
+ trackingMu sync.Mutex
+ newPartTypeCalled bool
+}
+
+// NewMockChunkedSyncHandlerWithTracking creates a new mock handler with tracking capabilities.
+func NewMockChunkedSyncHandlerWithTracking() *MockChunkedSyncHandlerWithTracking {
+ return &MockChunkedSyncHandlerWithTracking{
+ MockChunkedSyncHandler: NewMockChunkedSyncHandler(),
+ newPartTypeContexts: make([]*queue.ChunkedSyncPartContext, 0),
+ }
+}
+
+// TrackNewPartType tracks a NewPartType call.
+func (m *MockChunkedSyncHandlerWithTracking) TrackNewPartType(ctx *queue.ChunkedSyncPartContext) {
+ m.trackingMu.Lock()
+ defer m.trackingMu.Unlock()
+ m.newPartTypeCalled = true
+ contextCopy := &queue.ChunkedSyncPartContext{
+ ID: ctx.ID,
+ Group: ctx.Group,
+ ShardID: ctx.ShardID,
+ PartType: ctx.PartType,
+ CompressedSizeBytes: ctx.CompressedSizeBytes,
+ UncompressedSizeBytes: ctx.UncompressedSizeBytes,
+ TotalCount: ctx.TotalCount,
+ BlocksCount: ctx.BlocksCount,
+ MinTimestamp: ctx.MinTimestamp,
+ MaxTimestamp: ctx.MaxTimestamp,
+ MinKey: ctx.MinKey,
+ MaxKey: ctx.MaxKey,
+ }
+ m.newPartTypeContexts = append(m.newPartTypeContexts, contextCopy)
+}
+
+// NewPartTypeCalled returns whether NewPartType has been called.
+func (m *MockChunkedSyncHandlerWithTracking) NewPartTypeCalled() bool {
+ m.trackingMu.Lock()
+ defer m.trackingMu.Unlock()
+ return m.newPartTypeCalled
+}
+
+// GetNewPartTypeContexts returns all contexts passed to NewPartType.
+func (m *MockChunkedSyncHandlerWithTracking) GetNewPartTypeContexts() []*queue.ChunkedSyncPartContext {
+ m.trackingMu.Lock()
+ defer m.trackingMu.Unlock()
+ result := make([]*queue.ChunkedSyncPartContext, len(m.newPartTypeContexts))
+ copy(result, m.newPartTypeContexts)
+ return result
+}
+
+// ResetNewPartTypeCalls resets the tracking state.
+func (m *MockChunkedSyncHandlerWithTracking) ResetNewPartTypeCalls() {
+ m.trackingMu.Lock()
+ defer m.trackingMu.Unlock()
+ m.newPartTypeCalled = false
+ m.newPartTypeContexts = nil
+}
+
+// CreatePartHandler creates a new part handler with tracking capabilities.
+func (m *MockChunkedSyncHandlerWithTracking) CreatePartHandler(ctx *queue.ChunkedSyncPartContext) (queue.PartHandler, error) {
+ partHandler, err := m.MockChunkedSyncHandler.CreatePartHandler(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // Cast to our enhanced handler and set tracking reference
+ if mockHandler, ok := partHandler.(*MockPartHandler); ok {
+ mockHandler.trackingHandler = m
+ }
+
+ return partHandler, nil
+}
+
+// createTestDataPartWithPartType creates test data part with specified PartType.
+func createTestDataPartWithPartType(
+ files map[string][]byte,
+ group string,
+ shardID uint32,
+ partID uint64,
+ partType string,
+) queue.StreamingPartData {
+ var fileInfos []queue.FileInfo
+
+ for fileName, content := range files {
+ var buf bytes.Buffer
+ if _, err := buf.Write(content); err != nil {
+ panic(fmt.Sprintf("failed to write content to buffer: %v", err))
+ }
+ fileInfos = append(fileInfos, queue.FileInfo{
+ Name: fileName,
+ Reader: buf.SequentialRead(),
+ })
+ }
+
+ return queue.StreamingPartData{
+ ID: partID,
+ Files: fileInfos,
+ Group: group,
+ ShardID: shardID,
+ PartType: partType,
+ Topic: data.TopicStreamPartSync.String(),
+ CompressedSizeBytes: 1024,
+ UncompressedSizeBytes: 2048,
+ TotalCount: 100,
+ BlocksCount: 5,
+ MinTimestamp: time.Now().UnixMilli(),
+ MaxTimestamp: time.Now().UnixMilli(),
+ }
+}
+
+// TrackingSetup extends Setup with tracking capabilities.
+type TrackingSetup struct {
+ *Setup
+ TrackingHandler *MockChunkedSyncHandlerWithTracking
+}
+
+// setupChunkedSyncTestWithTracking creates a test environment with tracking capabilities.
+func setupChunkedSyncTestWithTracking(t *testing.T, testName string) *TrackingSetup {
+ setup := setupChunkedSyncTest(t, testName)
+
+ trackingHandler := NewMockChunkedSyncHandlerWithTracking()
+
+ // Replace the handler in the server
+ setup.Server.RegisterChunkedSyncHandler(data.TopicStreamPartSync, trackingHandler)
+
+ // Update the MockHandler reference in the setup to point to our tracking handler
+ setup.MockHandler = trackingHandler.MockChunkedSyncHandler
+
+ return &TrackingSetup{
+ Setup: setup,
+ TrackingHandler: trackingHandler,
+ }
+}
diff --git a/banyand/queue/test/chunked_sync_parttype_test.go b/banyand/queue/test/chunked_sync_parttype_test.go
new file mode 100644
index 00000000..81cfd8ef
--- /dev/null
+++ b/banyand/queue/test/chunked_sync_parttype_test.go
@@ -0,0 +1,268 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package test
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/apache/skywalking-banyandb/banyand/queue"
+)
+
+// TestChunkedSyncPartTypeBehavior tests the NewPartType handler invocation behavior
+// when partCtx is created with different ID and PartType combinations.
+func TestChunkedSyncPartTypeBehavior(t *testing.T) {
+ tests := []struct {
+ name string
+ firstPartType string
+ secondPartType string
+ description string
+ firstPartID uint64
+ secondPartID uint64
+ expectNewPartTypeCalled bool
+ }{
+ {
+ name: "same_id_different_parttype",
+ firstPartID: 123,
+ firstPartType: "primary",
+ secondPartID: 123, // Same ID
+ secondPartType: "secondary", // Different PartType
+ expectNewPartTypeCalled: true,
+ description: "NewPartType should be called when ID is same but PartType changes",
+ },
+ {
+ name: "same_id_same_parttype",
+ firstPartID: 456,
+ firstPartType: "primary",
+ secondPartID: 456, // Same ID
+ secondPartType: "primary", // Same PartType
+ expectNewPartTypeCalled: false,
+ description: "NewPartType should NOT be called when both ID and PartType are same",
+ },
+ {
+ name: "different_id_same_parttype",
+ firstPartID: 789,
+ firstPartType: "primary",
+ secondPartID: 790, // Different ID
+ secondPartType: "primary", // Same PartType
+ expectNewPartTypeCalled: false,
+ description: "NewPartType should NOT be called when ID changes (CreatePartHandler is called instead)",
+ },
+ {
+ name: "different_id_different_parttype",
+ firstPartID: 111,
+ firstPartType: "primary",
+ secondPartID: 222, // Different ID
+ secondPartType: "secondary", // Different PartType
+ expectNewPartTypeCalled: false,
+ description: "NewPartType should NOT be called when ID changes (CreatePartHandler is called instead)",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ setup := setupChunkedSyncTestWithTracking(t, "parttype-test-"+tt.name)
+ defer cleanupTestSetup(setup.Setup)
+
+ // Create first part
+ firstPartFiles := map[string][]byte{
+ "first-file.txt": []byte("First part data"),
+ }
+ firstPart := createTestDataPartWithPartType(
+ firstPartFiles,
+ "test-group",
+ 1, // shardID
+ tt.firstPartID,
+ tt.firstPartType,
+ )
+
+ // Create second part
+ secondPartFiles := map[string][]byte{
+ "second-file.txt": []byte("Second part data"),
+ }
+ secondPart := createTestDataPartWithPartType(
+ secondPartFiles,
+ "test-group",
+ 1, // shardID
+ tt.secondPartID,
+ tt.secondPartType,
+ )
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ // Send both parts in a single session to test NewPartType behavior
+ bothParts := []queue.StreamingPartData{firstPart, secondPart}
+ result, err := setup.ChunkedClient.SyncStreamingParts(ctx, bothParts)
+ require.NoError(t, err, "Both parts should sync successfully")
+ require.True(t, result.Success, "Both parts sync should be successful")
+
+ time.Sleep(500 * time.Millisecond)
+
+ // Verify NewPartType call behavior
+ if tt.expectNewPartTypeCalled {
+ assert.True(t, setup.TrackingHandler.NewPartTypeCalled(),
+ "NewPartType should have been called: %s", tt.description)
+ newPartTypeContexts := setup.TrackingHandler.GetNewPartTypeContexts()
+ assert.Len(t, newPartTypeContexts, 1, "NewPartType should have been called exactly once")
+ if len(newPartTypeContexts) > 0 {
+ ctx := newPartTypeContexts[0]
+ assert.Equal(t, tt.secondPartID, ctx.ID, "NewPartType should be called with correct part ID")
+ assert.Equal(t, tt.secondPartType, ctx.PartType, "NewPartType should be called with correct part type")
+ }
+ } else {
+ assert.False(t, setup.TrackingHandler.NewPartTypeCalled(),
+ "NewPartType should NOT have been called: %s", tt.description)
+ newPartTypeContexts := setup.TrackingHandler.GetNewPartTypeContexts()
+ assert.Len(t, newPartTypeContexts, 0, "NewPartType should not have been called")
+ }
+
+ // Verify that both parts were processed successfully
+ receivedFiles := setup.MockHandler.GetReceivedFiles()
+ expectedFileCount := len(firstPartFiles) + len(secondPartFiles)
+ assert.Len(t, receivedFiles, expectedFileCount, "Should have received all files from both parts")
+
+ // Verify file contents
+ for fileName, expectedContent := range firstPartFiles {
+ receivedContent, exists := receivedFiles[fileName]
+ require.True(t, exists, "File %s should be received", fileName)
+ assert.Equal(t, expectedContent, receivedContent, "Content for file %s should match", fileName)
+ }
+ for fileName, expectedContent := range secondPartFiles {
+ receivedContent, exists := receivedFiles[fileName]
+ require.True(t, exists, "File %s should be received", fileName)
+ assert.Equal(t, expectedContent, receivedContent, "Content for file %s should match", fileName)
+ }
+
+ completedParts := setup.MockHandler.GetCompletedParts()
+ // When parts have the same ID, they share the same part context, so only one FinishSync is called
+ expectedCompletedParts := 1
+ if tt.firstPartID != tt.secondPartID {
+ expectedCompletedParts = 2 // Different IDs create separate part contexts
+ }
+ assert.Len(t, completedParts, expectedCompletedParts, "Should have completed %d parts", expectedCompletedParts)
+ for i, part := range completedParts {
+ assert.True(t, part.finishSyncCalled, "FinishSync should have been called for part %d", i+1)
+ assert.True(t, part.closeCalled, "Close should have been called for part %d", i+1)
+ }
+
+ t.Logf("PartType behavior test '%s' completed successfully:", tt.name)
+ t.Logf(" - Session ID: %s", result.SessionID)
+ t.Logf(" - First part: ID=%d, PartType=%s", tt.firstPartID, tt.firstPartType)
+ t.Logf(" - Second part: ID=%d, PartType=%s", tt.secondPartID, tt.secondPartType)
+ t.Logf(" - NewPartType called: %v", setup.TrackingHandler.NewPartTypeCalled())
+ t.Logf(" - Files received: %d", len(receivedFiles))
+ t.Logf(" - Parts completed: %d", len(completedParts))
+ t.Logf(" - Total bytes sent: %d", result.TotalBytes)
+ })
+ }
+}
+
+// TestChunkedSyncMultiplePartTypesInSequence tests multiple part types with same ID in sequence.
+func TestChunkedSyncMultiplePartTypesInSequence(t *testing.T) {
+ setup := setupChunkedSyncTestWithTracking(t, "multiple-parttypes-sequence")
+ defer cleanupTestSetup(setup.Setup)
+
+ partID := uint64(999)
+ partTypes := []string{"primary", "secondary", "tertiary", "primary"} // Last one is same as first
+ expectedNewPartTypeCalls := 3 // Should be called for secondary, tertiary, and primary (when it changes back)
+
+ var allFiles []queue.StreamingPartData
+ for i, partType := range partTypes {
+ partFiles := map[string][]byte{
+ fmt.Sprintf("part-%d-%s.txt", i+1, partType): []byte(fmt.Sprintf("Data for part %d with type %s", i+1, partType)),
+ }
+ part := createTestDataPartWithPartType(
+ partFiles,
+ "test-group-multi",
+ 1, // shardID
+ partID,
+ partType,
+ )
+ allFiles = append(allFiles, part)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ // Send all parts in a single session to test NewPartType behavior
+ result, err := setup.ChunkedClient.SyncStreamingParts(ctx, allFiles)
+ require.NoError(t, err, "All parts should sync successfully")
+ require.True(t, result.Success, "All parts sync should be successful")
+
+ time.Sleep(500 * time.Millisecond)
+
+ // Verify NewPartType was called for each part type change
+ actualNewPartTypeCalls := 0
+ for i := 1; i < len(partTypes); i++ {
+ if partTypes[i] != partTypes[i-1] {
+ actualNewPartTypeCalls++
+ }
+ }
+
+ newPartTypeContexts := setup.TrackingHandler.GetNewPartTypeContexts()
+ assert.Len(t, newPartTypeContexts, actualNewPartTypeCalls,
+ "NewPartType should have been called %d times for part type changes", actualNewPartTypeCalls)
+
+ // Verify each NewPartType call has the correct context
+ newPartTypeIndex := 0
+ for i := 1; i < len(partTypes); i++ {
+ if partTypes[i] != partTypes[i-1] {
+ require.Less(t, newPartTypeIndex, len(newPartTypeContexts),
+ "Should have NewPartType context for part %d", i+1)
+ ctx := newPartTypeContexts[newPartTypeIndex]
+ assert.Equal(t, partID, ctx.ID, "NewPartType should be called with correct part ID for part %d", i+1)
+ assert.Equal(t, partTypes[i], ctx.PartType, "NewPartType should be called with correct part type for part %d", i+1)
+ newPartTypeIndex++
+ }
+ }
+
+ // Verify all files were received
+ receivedFiles := setup.MockHandler.GetReceivedFiles()
+ expectedFileCount := len(allFiles)
+ assert.Len(t, receivedFiles, expectedFileCount, "Should have received all files from all parts")
+
+ // Verify file contents
+ for _, part := range allFiles {
+ for _, fileInfo := range part.Files {
+ receivedContent, exists := receivedFiles[fileInfo.Name]
+ require.True(t, exists, "File %s should be received", fileInfo.Name)
+ assert.NotEmpty(t, receivedContent, "Content for file %s should not be empty", fileInfo.Name)
+ }
+ }
+
+ completedParts := setup.MockHandler.GetCompletedParts()
+ // All parts have the same ID, so they share the same part context - only one FinishSync is called
+ assert.Len(t, completedParts, 1, "Should have completed one part (all parts share same context due to same ID)")
+ for i, part := range completedParts {
+ assert.True(t, part.finishSyncCalled, "FinishSync should have been called for part %d", i+1)
+ assert.True(t, part.closeCalled, "Close should have been called for part %d", i+1)
+ }
+
+ t.Logf("Multiple part types sequence test completed successfully:")
+ t.Logf(" - Parts sent: %d", len(allFiles))
+ t.Logf(" - Part types: %v", partTypes)
+ t.Logf(" - Expected NewPartType calls: %d", expectedNewPartTypeCalls)
+ t.Logf(" - Files received: %d", len(receivedFiles))
+ t.Logf(" - Parts completed: %d", len(completedParts))
+}
diff --git a/banyand/stream/write_data.go b/banyand/stream/write_data.go
index c0c9b756..e9bd52cc 100644
--- a/banyand/stream/write_data.go
+++ b/banyand/stream/write_data.go
@@ -36,6 +36,11 @@ type syncPartContext struct {
memPart *memPart
}
+func (s *syncPartContext) NewPartType(_ *queue.ChunkedSyncPartContext) error {
+ logger.Panicf("new part type is not supported for stream")
+ return nil
+}
+
func (s *syncPartContext) FinishSync() error {
s.tsTable.mustAddMemPart(s.memPart)
return s.Close()
@@ -146,6 +151,11 @@ type syncSeriesContext struct {
fileName string
}
+func (s *syncSeriesContext) NewPartType(_ *queue.ChunkedSyncPartContext) error {
+ logger.Panicf("new part type is not supported for stream")
+ return nil
+}
+
func (s *syncSeriesContext) FinishSync() error {
if s.streamer != nil {
if err := s.streamer.CompleteSegment(); err != nil {
@@ -245,6 +255,11 @@ type syncElementIndexContext struct {
fileName string
}
+func (s *syncElementIndexContext) NewPartType(_ *queue.ChunkedSyncPartContext) error {
+ logger.Panicf("new part type is not supported for stream")
+ return nil
+}
+
func (s *syncElementIndexContext) FinishSync() error {
if s.streamer != nil {
if err := s.streamer.CompleteSegment(); err != nil {
diff --git a/banyand/trace/flusher.go b/banyand/trace/flusher.go
index ce8338af..194f8a0d 100644
--- a/banyand/trace/flusher.go
+++ b/banyand/trace/flusher.go
@@ -76,49 +76,6 @@ func (tst *tsTable) flusherLoop(flushCh chan *flusherIntroduction, mergeCh chan
}
}
-func (tst *tsTable) flusherLoopNoMerger(flushCh chan *flusherIntroduction, introducerWatcher, flusherWatcher watcher.Channel, epoch uint64) {
- defer tst.loopCloser.Done()
- epochWatcher := introducerWatcher.Add(epoch, tst.loopCloser.CloseNotify())
- if epochWatcher == nil {
- return
- }
- var flusherWatchers watcher.Epochs
-
- for {
- select {
- case <-tst.loopCloser.CloseNotify():
- return
- case e := <-flusherWatcher:
- flusherWatchers.Add(e)
- case <-epochWatcher.Watch():
- if func() bool {
- tst.incTotalFlushLoopStarted(1)
- start := time.Now()
- defer func() {
- tst.incTotalFlushLoopFinished(1)
- tst.incTotalFlushLatency(time.Since(start).Seconds())
- }()
- curSnapshot := tst.currentSnapshot()
- if curSnapshot != nil {
- defer curSnapshot.decRef()
- tst.flush(curSnapshot, flushCh)
- epoch = curSnapshot.epoch
- flusherWatchers.Notify(epoch)
- flusherWatchers = nil
- if tst.currentEpoch() != epoch {
- tst.incTotalFlushLoopProgress(1)
- return false
- }
- }
- epochWatcher = introducerWatcher.Add(epoch, tst.loopCloser.CloseNotify())
- return epochWatcher == nil
- }() {
- return
- }
- }
- }
-}
-
func (tst *tsTable) pauseFlusherToPileupMemPartsWithMerge(
curSnapshot *snapshot, flusherWatcher watcher.Channel, flusherWatchers watcher.Epochs,
epoch uint64, mergeCh chan *mergerIntroduction,
@@ -175,7 +132,7 @@ func (tst *tsTable) mergeMemParts(snp *snapshot, mergeCh chan *mergerIntroductio
var merged bool
var currentSegmentID int64
var memParts []*partWrapper
- mergedIDs := make(map[partHandle]struct{})
+ mergedIDs := make(map[uint64]struct{})
// Helper function to merge current segment's parts
mergeCurrentSegment := func() (bool, error) {
@@ -184,7 +141,7 @@ func (tst *tsTable) mergeMemParts(snp *snapshot, mergeCh chan *mergerIntroductio
}
// Create a copy of mergedIDs for this merge operation
- currentMergedIDs := make(map[partHandle]struct{}, len(mergedIDs))
+ currentMergedIDs := make(map[uint64]struct{}, len(mergedIDs))
for id := range mergedIDs {
currentMergedIDs[id] = struct{}{}
}
@@ -231,7 +188,7 @@ func (tst *tsTable) mergeMemParts(snp *snapshot, mergeCh chan *mergerIntroductio
// Add part to current segment
currentSegmentID = segID
memParts = append(memParts, snp.parts[i])
- mergedIDs[partHandle{partID: snp.parts[i].ID(), partType: PartTypeCore}] = struct{}{}
+ mergedIDs[snp.parts[i].ID()] = struct{}{}
}
// Merge the last segment if it has parts
@@ -253,6 +210,7 @@ func (tst *tsTable) flush(snapshot *snapshot, flushCh chan *flusherIntroduction)
defer releaseFlusherIntroduction(ind)
start := time.Now()
partsCount := 0
+ partIDMap := make(map[uint64]struct{})
for _, pw := range snapshot.parts {
if pw.mp == nil || pw.mp.partMetadata.TotalCount < 1 {
continue
@@ -263,6 +221,7 @@ func (tst *tsTable) flush(snapshot *snapshot, flushCh chan *flusherIntroduction)
newPW := newPartWrapper(nil, mustOpenFilePart(pw.ID(), tst.root, tst.fileSystem))
newPW.p.partMetadata.ID = pw.ID()
ind.flushed[newPW.ID()] = newPW
+ partIDMap[newPW.ID()] = struct{}{}
}
if len(ind.flushed) < 1 {
return
@@ -274,10 +233,19 @@ func (tst *tsTable) flush(snapshot *snapshot, flushCh chan *flusherIntroduction)
Str("sidx_name", name).
Msg("flushing sidx")
}
- if err := sidxInstance.Flush(); err != nil {
+ sidxFlusherIntroduced, err := sidxInstance.Flush(partIDMap)
+ if err != nil {
tst.l.Warn().Err(err).Str("sidx", name).Msg("sidx flush failed")
return
}
+ ind.sidxFlusherIntroduced[name] = sidxFlusherIntroduced
+ }
+ if len(ind.sidxFlusherIntroduced) > 0 {
+ defer func() {
+ for _, sidxFlusherIntroduced := range ind.sidxFlusherIntroduced {
+ sidxFlusherIntroduced.Release()
+ }
+ }()
}
end := time.Now()
tst.incTotalFlushed(1)
diff --git a/banyand/trace/introducer.go b/banyand/trace/introducer.go
index 2e4cc2de..c7c61949 100644
--- a/banyand/trace/introducer.go
+++ b/banyand/trace/introducer.go
@@ -18,18 +18,21 @@
package trace
import (
+ "github.com/apache/skywalking-banyandb/banyand/internal/sidx"
"github.com/apache/skywalking-banyandb/pkg/pool"
"github.com/apache/skywalking-banyandb/pkg/watcher"
)
type introduction struct {
- memPart *partWrapper
- applied chan struct{}
+ memPart *partWrapper
+ applied chan struct{}
+ sidxReqsMap map[string]*sidx.MemPart
}
func (i *introduction) reset() {
i.memPart = nil
i.applied = nil
+ i.sidxReqsMap = nil
}
var introductionPool = pool.Register[*introduction]("trace-introduction")
@@ -37,7 +40,9 @@ var introductionPool = pool.Register[*introduction]("trace-introduction")
func generateIntroduction() *introduction {
v := introductionPool.Get()
if v == nil {
- return &introduction{}
+ return &introduction{
+ sidxReqsMap: make(map[string]*sidx.MemPart),
+ }
}
intro := v
intro.reset()
@@ -49,14 +54,18 @@ func releaseIntroduction(i *introduction) {
}
type flusherIntroduction struct {
- flushed map[uint64]*partWrapper
- applied chan struct{}
+ flushed map[uint64]*partWrapper
+ sidxFlusherIntroduced map[string]*sidx.FlusherIntroduction
+ applied chan struct{}
}
func (i *flusherIntroduction) reset() {
for k := range i.flushed {
delete(i.flushed, k)
}
+ for k := range i.sidxFlusherIntroduced {
+ delete(i.sidxFlusherIntroduced, k)
+ }
i.applied = nil
}
@@ -66,7 +75,8 @@ func generateFlusherIntroduction() *flusherIntroduction {
v := flusherIntroductionPool.Get()
if v == nil {
return &flusherIntroduction{
- flushed: make(map[uint64]*partWrapper),
+ flushed: make(map[uint64]*partWrapper),
+ sidxFlusherIntroduced: make(map[string]*sidx.FlusherIntroduction),
}
}
fi := v
@@ -79,16 +89,16 @@ func releaseFlusherIntroduction(i *flusherIntroduction) {
}
type mergerIntroduction struct {
- merged map[partHandle]struct{}
- newPart *partWrapper
- applied chan struct{}
- creator snapshotCreator
+ merged map[uint64]struct{}
+ newPart *partWrapper
+ sidxMergerIntroduced map[string]*sidx.MergerIntroduction
+ applied chan struct{}
+ creator snapshotCreator
}
func (i *mergerIntroduction) reset() {
- for k := range i.merged {
- delete(i.merged, partHandle{partID: k.partID, partType: PartTypeCore})
- }
+ i.merged = nil
+ i.sidxMergerIntroduced = nil
i.newPart = nil
i.applied = nil
i.creator = 0
@@ -110,13 +120,8 @@ func releaseMergerIntroduction(i *mergerIntroduction) {
mergerIntroductionPool.Put(i)
}
-type partHandle struct {
- partType string
- partID uint64
-}
-
type syncIntroduction struct {
- synced map[partHandle]struct{}
+ synced map[uint64]struct{}
applied chan struct{}
}
@@ -133,7 +138,7 @@ func generateSyncIntroduction() *syncIntroduction {
v := syncIntroductionPool.Get()
if v == nil {
return &syncIntroduction{
- synced: make(map[partHandle]struct{}),
+ synced: make(map[uint64]struct{}),
}
}
si := v
@@ -177,7 +182,9 @@ func (tst *tsTable) introducerLoop(flushCh chan *flusherIntroduction, mergeCh ch
}
}
-func (tst *tsTable) introducerLoopWithSync(flushCh chan *flusherIntroduction, syncCh chan *syncIntroduction, watcherCh watcher.Channel, epoch uint64) {
+func (tst *tsTable) introducerLoopWithSync(flushCh chan *flusherIntroduction, mergeCh chan *mergerIntroduction,
+ syncCh chan *syncIntroduction, watcherCh watcher.Channel, epoch uint64,
+) {
var introducerWatchers watcher.Epochs
defer tst.loopCloser.Done()
for {
@@ -195,6 +202,12 @@ func (tst *tsTable) introducerLoopWithSync(flushCh chan *flusherIntroduction, sy
tst.incTotalIntroduceLoopFinished("flush")
tst.gc.clean()
epoch++
+ case next := <-mergeCh:
+ tst.incTotalIntroduceLoopStarted("merge")
+ tst.introduceMerged(next, epoch)
+ tst.incTotalIntroduceLoopFinished("merge")
+ tst.gc.clean()
+ epoch++
case next := <-syncCh:
tst.incTotalIntroduceLoopStarted("sync")
tst.introduceSync(next, epoch)
@@ -210,6 +223,10 @@ func (tst *tsTable) introducerLoopWithSync(flushCh chan *flusherIntroduction, sy
}
func (tst *tsTable) introduceMemPart(nextIntroduction *introduction, epoch uint64) {
+ next := nextIntroduction.memPart
+ for name, memPart := range nextIntroduction.sidxReqsMap {
+ tst.mustGetOrCreateSidx(name).IntroduceMemPart(next.p.partMetadata.ID, memPart)
+ }
cur := tst.currentSnapshot()
if cur != nil {
defer cur.decRef()
@@ -217,7 +234,6 @@ func (tst *tsTable) introduceMemPart(nextIntroduction *introduction, epoch uint6
cur = new(snapshot)
}
- next := nextIntroduction.memPart
nextSnp := cur.copyAllTo(epoch)
nextSnp.parts = append(nextSnp.parts, next)
nextSnp.creator = snapshotCreatorMemPart
@@ -228,6 +244,9 @@ func (tst *tsTable) introduceMemPart(nextIntroduction *introduction, epoch uint6
}
func (tst *tsTable) introduceFlushed(nextIntroduction *flusherIntroduction, epoch uint64) {
+ for name, sidxFlusherIntroduced := range nextIntroduction.sidxFlusherIntroduced {
+ tst.mustGetSidx(name).IntroduceFlushed(sidxFlusherIntroduced)
+ }
cur := tst.currentSnapshot()
if cur == nil {
tst.l.Panic().Msg("current snapshot is nil")
@@ -243,6 +262,12 @@ func (tst *tsTable) introduceFlushed(nextIntroduction *flusherIntroduction, epoc
}
func (tst *tsTable) introduceMerged(nextIntroduction *mergerIntroduction, epoch uint64) {
+ for name, sidxMergerIntroduced := range nextIntroduction.sidxMergerIntroduced {
+ deferFuncs := tst.mustGetSidx(name).IntroduceMerged(sidxMergerIntroduced)
+ if deferFuncs != nil {
+ defer deferFuncs()
+ }
+ }
cur := tst.currentSnapshot()
if cur == nil {
tst.l.Panic().Msg("current snapshot is nil")
@@ -260,13 +285,21 @@ func (tst *tsTable) introduceMerged(nextIntroduction *mergerIntroduction, epoch
}
func (tst *tsTable) introduceSync(nextIntroduction *syncIntroduction, epoch uint64) {
+ synced := nextIntroduction.synced
+ allSidx := tst.getAllSidx()
+ for _, sidx := range allSidx {
+ deferFuncs := sidx.IntroduceSynced(synced)
+ if deferFuncs != nil {
+ defer deferFuncs()
+ }
+ }
cur := tst.currentSnapshot()
if cur == nil {
tst.l.Panic().Msg("current snapshot is nil")
return
}
defer cur.decRef()
- nextSnp := cur.remove(epoch, nextIntroduction.synced)
+ nextSnp := cur.remove(epoch, synced)
nextSnp.creator = snapshotCreatorSyncer
tst.replaceSnapshot(&nextSnp)
tst.persistSnapshot(&nextSnp)
diff --git a/banyand/trace/merger.go b/banyand/trace/merger.go
index fe2fb194..3892f045 100644
--- a/banyand/trace/merger.go
+++ b/banyand/trace/merger.go
@@ -25,6 +25,7 @@ import (
"github.com/dustin/go-humanize"
+ "github.com/apache/skywalking-banyandb/banyand/internal/sidx"
"github.com/apache/skywalking-banyandb/pkg/cgroups"
"github.com/apache/skywalking-banyandb/pkg/encoding"
"github.com/apache/skywalking-banyandb/pkg/fs"
@@ -94,7 +95,7 @@ func (tst *tsTable) mergeLoop(merges chan *mergerIntroduction, flusherNotifier w
func (tst *tsTable) mergeSnapshot(curSnapshot *snapshot, merges chan *mergerIntroduction, dst []*partWrapper) ([]*partWrapper, error) {
freeDiskSize := tst.freeDiskSpace(tst.root)
- var toBeMerged map[partHandle]struct{}
+ var toBeMerged map[uint64]struct{}
dst, toBeMerged = tst.getPartsToMerge(curSnapshot, freeDiskSize, dst)
if len(dst) < 2 {
return nil, nil
@@ -106,7 +107,7 @@ func (tst *tsTable) mergeSnapshot(curSnapshot *snapshot, merges chan *mergerIntr
return dst, nil
}
-func (tst *tsTable) mergePartsThenSendIntroduction(creator snapshotCreator, parts []*partWrapper, merged map[partHandle]struct{}, merges chan *mergerIntroduction,
+func (tst *tsTable) mergePartsThenSendIntroduction(creator snapshotCreator, parts []*partWrapper, merged map[uint64]struct{}, merges chan *mergerIntroduction,
closeCh <-chan struct{}, typ string,
) (*partWrapper, error) {
reservedSpace := tst.reserveSpace(parts)
@@ -156,37 +157,41 @@ func (tst *tsTable) mergePartsThenSendIntroduction(creator snapshotCreator, part
Msg("background merger merges unbalanced parts")
}
}
+ partIDMap := make(map[uint64]struct{})
+ for _, pw := range parts {
+ partIDMap[pw.ID()] = struct{}{}
+ }
+ mergerIntroductionMap := make(map[string]*sidx.MergerIntroduction)
for sidxName, sidxInstance := range tst.getAllSidx() {
start = time.Now()
- var mergedPartsCount uint64
- var err error
- if typ == mergeTypeMem {
- mergedPartsCount, err = sidxInstance.MergeMemParts(closeCh)
- if err != nil {
- tst.l.Warn().Err(err).Msg("sidx merge mem parts failed")
- return nil, err
- }
- } else {
- mergedPartsCount, err = sidxInstance.Merge(closeCh)
- if err != nil {
- tst.l.Warn().Err(err).Msg("sidx merge file parts failed")
- return nil, err
- }
+ mergerIntroduction, err := sidxInstance.Merge(closeCh, partIDMap, newPartID)
+ if err != nil {
+ tst.l.Warn().Err(err).Msg("sidx merge mem parts failed")
+ return nil, err
}
+ mergerIntroductionMap[sidxName] = mergerIntroduction
elapsed = time.Since(start)
tst.incTotalMergeLatency(elapsed.Seconds(), fmt.Sprintf("%s_%s", typ, sidxName))
tst.incTotalMerged(1, fmt.Sprintf("%s_%s", typ, sidxName))
- tst.incTotalMergedParts(int(mergedPartsCount), fmt.Sprintf("%s_%s", typ, sidxName))
+ tst.incTotalMergedParts(len(parts), fmt.Sprintf("%s_%s", typ, sidxName))
if elapsed > 30*time.Second {
- tst.l.Warn().Uint64("mergedPartsCount", mergedPartsCount).Str("sidxName", sidxName).Dur("elapsed", elapsed).Msg("sidx merge parts took too long")
+ tst.l.Warn().Int("mergedPartsCount", len(parts)).Str("sidxName", sidxName).Dur("elapsed", elapsed).Msg("sidx merge parts took too long")
}
}
+ if len(mergerIntroductionMap) > 0 {
+ defer func() {
+ for _, mergerIntroduction := range mergerIntroductionMap {
+ mergerIntroduction.Release()
+ }
+ }()
+ }
mi := generateMergerIntroduction()
defer releaseMergerIntroduction(mi)
mi.creator = creator
mi.newPart = newPart
mi.merged = merged
+ mi.sidxMergerIntroduced = mergerIntroductionMap
mi.applied = make(chan struct{})
select {
case merges <- mi:
@@ -230,7 +235,7 @@ func releaseDiskSpace(n uint64) {
var reservedDiskSpace uint64
-func (tst *tsTable) getPartsToMerge(snapshot *snapshot, freeDiskSize uint64, dst []*partWrapper) ([]*partWrapper, map[partHandle]struct{}) {
+func (tst *tsTable) getPartsToMerge(snapshot *snapshot, freeDiskSize uint64, dst []*partWrapper) ([]*partWrapper, map[uint64]struct{}) {
var parts []*partWrapper
for _, pw := range snapshot.parts {
@@ -245,9 +250,9 @@ func (tst *tsTable) getPartsToMerge(snapshot *snapshot, freeDiskSize uint64, dst
return nil, nil
}
- toBeMerged := make(map[partHandle]struct{})
+ toBeMerged := make(map[uint64]struct{})
for _, pw := range dst {
- toBeMerged[partHandle{partID: pw.ID(), partType: PartTypeCore}] = struct{}{}
+ toBeMerged[pw.ID()] = struct{}{}
}
return dst, toBeMerged
}
diff --git a/banyand/trace/metrics.go b/banyand/trace/metrics.go
index e71514f0..1c66fce6 100644
--- a/banyand/trace/metrics.go
+++ b/banyand/trace/metrics.go
@@ -26,7 +26,7 @@ import (
)
var (
- streamScope = observability.RootScope.SubScope("stream")
+ streamScope = observability.RootScope.SubScope("trace")
tbScope = streamScope.SubScope("tst")
)
diff --git a/banyand/trace/query_test.go b/banyand/trace/query_test.go
index bc9781b2..0d34ff2f 100644
--- a/banyand/trace/query_test.go
+++ b/banyand/trace/query_test.go
@@ -150,7 +150,7 @@ func TestQueryResult(t *testing.T) {
introducerWatcher := make(watcher.Channel, 1)
go tst.introducerLoop(flushCh, mergeCh, introducerWatcher, 1)
for _, traces := range tt.tracesList {
- tst.mustAddTraces(traces)
+ tst.mustAddTraces(traces, nil)
time.Sleep(100 * time.Millisecond)
}
verify(t, tst)
@@ -165,7 +165,7 @@ func TestQueryResult(t *testing.T) {
logger.GetLogger("test"), timestamp.TimeRange{}, option{flushTimeout: 0, mergePolicy: newDefaultMergePolicyForTesting(), protector: protector.Nop{}}, nil)
require.NoError(t, err)
for _, traces := range tt.tracesList {
- tst.mustAddTraces(traces)
+ tst.mustAddTraces(traces, nil)
time.Sleep(100 * time.Millisecond)
}
// wait until the introducer is done
diff --git a/banyand/trace/snapshot.go b/banyand/trace/snapshot.go
index 2019335a..ca741782 100644
--- a/banyand/trace/snapshot.go
+++ b/banyand/trace/snapshot.go
@@ -114,13 +114,13 @@ func (s *snapshot) merge(nextEpoch uint64, nextParts map[uint64]*partWrapper) sn
return result
}
-func (s *snapshot) remove(nextEpoch uint64, merged map[partHandle]struct{}) snapshot {
+func (s *snapshot) remove(nextEpoch uint64, merged map[uint64]struct{}) snapshot {
var result snapshot
result.epoch = nextEpoch
result.ref = 1
var removedCount int
for i := 0; i < len(s.parts); i++ {
- if _, ok := merged[partHandle{partID: s.parts[i].ID(), partType: PartTypeCore}]; !ok {
+ if _, ok := merged[s.parts[i].ID()]; !ok {
s.parts[i].incRef()
result.parts = append(result.parts, s.parts[i])
continue
diff --git a/banyand/trace/snapshot_test.go b/banyand/trace/snapshot_test.go
index 9c8144ae..d033fdd6 100644
--- a/banyand/trace/snapshot_test.go
+++ b/banyand/trace/snapshot_test.go
@@ -302,7 +302,7 @@ func TestSnapshotMerge(t *testing.T) {
func TestSnapshotRemove(t *testing.T) {
tests := []struct {
snapshot *snapshot
- mergedParts map[partHandle]struct{}
+ mergedParts map[uint64]struct{}
name string
expected snapshot
nextEpoch uint64
@@ -314,7 +314,7 @@ func TestSnapshotRemove(t *testing.T) {
parts: []*partWrapper{},
},
nextEpoch: 1,
- mergedParts: map[partHandle]struct{}{},
+ mergedParts: map[uint64]struct{}{},
expected: snapshot{
epoch: 1,
ref: 1,
@@ -330,7 +330,7 @@ func TestSnapshotRemove(t *testing.T) {
},
},
nextEpoch: 1,
- mergedParts: map[partHandle]struct{}{},
+ mergedParts: map[uint64]struct{}{},
expected: snapshot{
epoch: 1,
ref: 1,
@@ -349,8 +349,8 @@ func TestSnapshotRemove(t *testing.T) {
},
},
nextEpoch: 1,
- mergedParts: map[partHandle]struct{}{
- {partID: 1, partType: PartTypeCore}: {},
+ mergedParts: map[uint64]struct{}{
+ 1: {},
},
expected: snapshot{
epoch: 1,
@@ -366,7 +366,7 @@ func TestSnapshotRemove(t *testing.T) {
parts: []*partWrapper{},
},
nextEpoch: 1,
- mergedParts: map[partHandle]struct{}{},
+ mergedParts: map[uint64]struct{}{},
expected: snapshot{
epoch: 1,
ref: 1,
@@ -383,7 +383,7 @@ func TestSnapshotRemove(t *testing.T) {
},
},
nextEpoch: 1,
- mergedParts: map[partHandle]struct{}{},
+ mergedParts: map[uint64]struct{}{},
expected: snapshot{
epoch: 1,
ref: 1,
@@ -407,8 +407,8 @@ func TestSnapshotRemove(t *testing.T) {
},
},
nextEpoch: 1,
- mergedParts: map[partHandle]struct{}{
- {partID: 1, partType: PartTypeCore}: {},
+ mergedParts: map[uint64]struct{}{
+ 1: {},
},
expected: snapshot{
epoch: 1,
@@ -459,8 +459,8 @@ func TestSnapshotFunctionality(t *testing.T) {
}
defer tst.Close()
- tst.mustAddTraces(tsTS1)
- tst.mustAddTraces(tsTS2)
+ tst.mustAddTraces(tsTS1, nil)
+ tst.mustAddTraces(tsTS2, nil)
time.Sleep(100 * time.Millisecond) // allow time for flushing
require.Eventually(t, func() bool {
diff --git a/banyand/trace/svc_liaison.go b/banyand/trace/svc_liaison.go
index c52bc566..b503db77 100644
--- a/banyand/trace/svc_liaison.go
+++ b/banyand/trace/svc_liaison.go
@@ -22,6 +22,7 @@ import (
"errors"
"path"
"path/filepath"
+ "time"
"github.com/apache/skywalking-banyandb/api/common"
"github.com/apache/skywalking-banyandb/api/data"
@@ -85,7 +86,7 @@ func (l *liaison) FlagSet() *run.FlagSet {
fs := run.NewFlagSet("trace")
fs.StringVar(&l.root, "trace-root-path", "/tmp", "the root path for trace data")
fs.StringVar(&l.dataPath, "trace-data-path", "", "the path for trace data (optional)")
- fs.DurationVar(&l.option.flushTimeout, "trace-flush-timeout", defaultFlushTimeout, "the timeout for trace data flush")
+ fs.DurationVar(&l.option.flushTimeout, "trace-flush-timeout", 3*time.Second, "the timeout for trace data flush")
fs.IntVar(&l.maxDiskUsagePercent, "trace-max-disk-usage-percent", 95, "the maximum disk usage percentage")
fs.DurationVar(&l.option.syncInterval, "trace-sync-interval", defaultSyncInterval, "the periodic sync interval for trace data")
return fs
diff --git a/banyand/trace/syncer.go b/banyand/trace/syncer.go
index b0155363..79c95e33 100644
--- a/banyand/trace/syncer.go
+++ b/banyand/trace/syncer.go
@@ -25,10 +25,10 @@ import (
"time"
"github.com/apache/skywalking-banyandb/api/data"
- "github.com/apache/skywalking-banyandb/banyand/internal/sidx"
"github.com/apache/skywalking-banyandb/banyand/queue"
"github.com/apache/skywalking-banyandb/pkg/bytes"
"github.com/apache/skywalking-banyandb/pkg/compress/zstd"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
"github.com/apache/skywalking-banyandb/pkg/watcher"
)
@@ -185,107 +185,44 @@ func (tst *tsTable) syncSnapshot(curSnapshot *snapshot, syncCh chan *syncIntrodu
}
// Collect parts to sync
- partsToSync, sidxPartsToSync, err := tst.collectPartsToSync(curSnapshot)
- if err != nil {
- return err
- }
- if l := tst.l.Debug(); l.Enabled() {
- for name, sidxParts := range sidxPartsToSync {
- tst.l.Debug().
- Str("sidx_name", name).
- Int("sidx_parts_count", len(sidxParts)).
- Msg("sidxPartsToSync in syncSnapshot")
- }
- }
+ partsToSync, partIDsToSync := tst.collectPartsToSync(curSnapshot)
// Validate sync preconditions
- if !tst.needToSync(partsToSync, sidxPartsToSync) {
+ if !tst.needToSync(partsToSync) {
return nil
}
// Execute sync operation
- if err := tst.executeSyncOperation(partsToSync, sidxPartsToSync); err != nil {
+ if err := tst.executeSyncOperation(partsToSync, partIDsToSync); err != nil {
return err
}
// Handle sync introductions
- return tst.handleSyncIntroductions(partsToSync, sidxPartsToSync, syncCh)
+ return tst.handleSyncIntroductions(partsToSync, syncCh)
}
// collectPartsToSync collects both core and sidx parts that need to be synchronized.
-func (tst *tsTable) collectPartsToSync(curSnapshot *snapshot) ([]*part, map[string][]*sidx.Part, error) {
+func (tst *tsTable) collectPartsToSync(curSnapshot *snapshot) ([]*part, map[uint64]struct{}) {
// Get all parts from the current snapshot
var partsToSync []*part
+ sidxPartsToSync := make(map[uint64]struct{})
for _, pw := range curSnapshot.parts {
if pw.mp == nil && pw.p.partMetadata.TotalCount > 0 {
partsToSync = append(partsToSync, pw.p)
+ sidxPartsToSync[pw.p.partMetadata.ID] = struct{}{}
}
}
-
- sidxPartsToSync := sidx.NewPartsToSync()
- for name, sidx := range tst.getAllSidx() {
- if tst.loopCloser != nil && tst.loopCloser.Closed() {
- return nil, nil, errClosed
- }
- sidxPartsToSync[name] = sidx.PartsToSync()
- if l := tst.l.Debug(); l.Enabled() {
- tst.l.Debug().
- Str("sidx_name", name).
- Int("sidx_parts_count", len(sidxPartsToSync[name])).
- Msg("get sidx parts to sync")
- }
- }
-
- if l := tst.l.Debug(); l.Enabled() {
- tst.l.Debug().
- Int("core_parts_count", len(partsToSync)).
- Uint64("snapshot_epoch", curSnapshot.epoch).
- Msg("collected core parts for sync")
- if len(partsToSync) > 0 {
- var corePartIDs []uint64
- for _, part := range partsToSync {
- corePartIDs = append(corePartIDs, part.partMetadata.ID)
- }
- tst.l.Debug().
- Interface("core_part_ids", corePartIDs).
- Msg("core parts to sync details")
- }
- for sidxName, sidxParts := range sidxPartsToSync {
- var sidxPartIDs []uint64
- for _, part := range sidxParts {
- sidxPartIDs = append(sidxPartIDs, part.ID())
- }
- tst.l.Debug().
- Str("sidx_name", sidxName).
- Int("sidx_parts_count", len(sidxParts)).
- Interface("sidx_part_ids", sidxPartIDs).
- Msg("collected sidx parts for sync")
- }
- }
-
- return partsToSync, sidxPartsToSync, nil
+ return partsToSync, sidxPartsToSync
}
// needToSync validates that there are parts to sync and nodes available.
-func (tst *tsTable) needToSync(partsToSync []*part, sidxPartsToSync map[string][]*sidx.Part) bool {
- hasCoreParts := len(partsToSync) > 0
- hasSidxParts := false
- for _, parts := range sidxPartsToSync {
- if len(parts) > 0 {
- hasSidxParts = true
- break
- }
- }
- if !hasCoreParts && !hasSidxParts {
- return false
- }
-
+func (tst *tsTable) needToSync(partsToSync []*part) bool {
nodes := tst.getNodes()
- return len(nodes) > 0
+ return len(partsToSync) > 0 && len(nodes) > 0
}
// executeSyncOperation performs the actual synchronization of parts to nodes.
-func (tst *tsTable) executeSyncOperation(partsToSync []*part, sidxPartsToSync map[string][]*sidx.Part) error {
+func (tst *tsTable) executeSyncOperation(partsToSync []*part, partIDsToSync map[uint64]struct{}) error {
sort.Slice(partsToSync, func(i, j int) bool {
return partsToSync[i].partMetadata.ID < partsToSync[j].partMetadata.ID
})
@@ -299,106 +236,10 @@ func (tst *tsTable) executeSyncOperation(partsToSync []*part, sidxPartsToSync ma
}()
nodes := tst.getNodes()
- return tst.syncStreamingPartsToNodes(ctx, nodes, partsToSync, sidxPartsToSync, &releaseFuncs)
-}
-
-// handleSyncIntroductions creates and processes sync introductions for both core and sidx parts.
-func (tst *tsTable) handleSyncIntroductions(partsToSync []*part, sidxPartsToSync map[string][]*sidx.Part, syncCh chan *syncIntroduction) error {
- // Create core sync introduction
- si := generateSyncIntroduction()
- defer releaseSyncIntroduction(si)
- si.applied = make(chan struct{})
- for _, part := range partsToSync {
- ph := partHandle{
- partID: part.partMetadata.ID,
- partType: PartTypeCore,
- }
- si.synced[ph] = struct{}{}
- }
-
- // Create sidx sync introductions
- sidxSyncIntroductions := tst.createSidxSyncIntroductions(sidxPartsToSync)
- defer tst.releaseSidxSyncIntroductions(sidxSyncIntroductions)
-
- // Send sync introductions
- if err := tst.sendSyncIntroductions(si, sidxSyncIntroductions, syncCh); err != nil {
- return err
- }
-
- // Wait for sync introductions to be applied
- return tst.waitForSyncIntroductions(si, sidxSyncIntroductions)
-}
-
-// createSidxSyncIntroductions creates sync introductions for sidx parts.
-func (tst *tsTable) createSidxSyncIntroductions(sidxPartsToSync map[string][]*sidx.Part) map[string]*sidx.SyncIntroduction {
- sidxSyncIntroductions := make(map[string]*sidx.SyncIntroduction)
- for name, sidxParts := range sidxPartsToSync {
- if len(sidxParts) > 0 {
- ssi := sidx.GenerateSyncIntroduction()
- ssi.Applied = make(chan struct{})
- for _, part := range sidxParts {
- ssi.Synced[part.ID()] = struct{}{}
- }
- sidxSyncIntroductions[name] = ssi
- }
- }
- return sidxSyncIntroductions
-}
-
-// releaseSidxSyncIntroductions releases sidx sync introductions.
-func (tst *tsTable) releaseSidxSyncIntroductions(sidxSyncIntroductions map[string]*sidx.SyncIntroduction) {
- for _, ssi := range sidxSyncIntroductions {
- sidx.ReleaseSyncIntroduction(ssi)
- }
-}
-
-// sendSyncIntroductions sends sync introductions to their respective channels.
-func (tst *tsTable) sendSyncIntroductions(si *syncIntroduction, sidxSyncIntroductions map[string]*sidx.SyncIntroduction, syncCh chan *syncIntroduction) error {
- select {
- case syncCh <- si:
- case <-tst.loopCloser.CloseNotify():
- return errClosed
- }
-
- for name, ssi := range sidxSyncIntroductions {
- sidx, ok := tst.getSidx(name)
- if !ok {
- return fmt.Errorf("sidx %s not found", name)
- }
- select {
- case sidx.SyncCh() <- ssi:
- case <-tst.loopCloser.CloseNotify():
- return errClosed
- }
- }
- return nil
-}
-
-// waitForSyncIntroductions waits for all sync introductions to be applied.
-func (tst *tsTable) waitForSyncIntroductions(si *syncIntroduction, sidxSyncIntroductions map[string]*sidx.SyncIntroduction) error {
- select {
- case <-si.applied:
- case <-tst.loopCloser.CloseNotify():
- return errClosed
- }
-
- for _, ssi := range sidxSyncIntroductions {
- select {
- case <-ssi.Applied:
- case <-tst.loopCloser.CloseNotify():
- return errClosed
- }
- }
- return nil
-}
-
-// syncStreamingPartsToNodes synchronizes streamingparts to multiple nodes.
-func (tst *tsTable) syncStreamingPartsToNodes(ctx context.Context, nodes []string,
- partsToSync []*part, sidxPartsToSync map[string][]*sidx.Part, releaseFuncs *[]func(),
-) error {
if tst.loopCloser != nil && tst.loopCloser.Closed() {
return errClosed
}
+ sidxMap := tst.getAllSidx()
for _, node := range nodes {
if tst.loopCloser != nil && tst.loopCloser.Closed() {
return errClosed
@@ -406,22 +247,23 @@ func (tst *tsTable) syncStreamingPartsToNodes(ctx context.Context, nodes []strin
// Prepare all streaming parts data
streamingParts := make([]queue.StreamingPartData, 0)
// Add sidx streaming parts
- for name, sidxParts := range sidxPartsToSync {
- if len(sidxParts) == 0 {
- continue
+ for name, sidx := range sidxMap {
+ sidxStreamingParts, sidxReleaseFuncs := sidx.StreamingParts(partIDsToSync, tst.group, uint32(tst.shardID), name)
+ if len(sidxStreamingParts) != len(partIDsToSync) {
+ logger.Panicf("sidx streaming parts count mismatch: %d != %d", len(sidxStreamingParts), len(partIDsToSync))
+ return nil
}
- sidx, ok := tst.getSidx(name)
- if !ok {
- return fmt.Errorf("sidx %s not found", name)
- }
- sidxStreamingParts, sidxReleaseFuncs := sidx.StreamingParts(sidxParts, tst.group, uint32(tst.shardID), name)
streamingParts = append(streamingParts, sidxStreamingParts...)
- *releaseFuncs = append(*releaseFuncs, sidxReleaseFuncs...)
+ releaseFuncs = append(releaseFuncs, sidxReleaseFuncs...)
+ }
+ if len(streamingParts) != len(partIDsToSync)*len(sidxMap) {
+ logger.Panicf("streaming parts count mismatch: %d != %d", len(streamingParts), len(partIDsToSync)*len(sidxMap))
+ return nil
}
// Create streaming parts from core trace parts.
for _, part := range partsToSync {
files, release := createPartFileReaders(part)
- *releaseFuncs = append(*releaseFuncs, release)
+ releaseFuncs = append(releaseFuncs, release)
streamingParts = append(streamingParts, queue.StreamingPartData{
ID: part.partMetadata.ID,
Group: tst.group,
@@ -437,6 +279,12 @@ func (tst *tsTable) syncStreamingPartsToNodes(ctx context.Context, nodes []strin
PartType: PartTypeCore,
})
}
+ sort.Slice(streamingParts, func(i, j int) bool {
+ if streamingParts[i].ID == streamingParts[j].ID {
+ return streamingParts[i].PartType < streamingParts[j].PartType
+ }
+ return streamingParts[i].ID < streamingParts[j].ID
+ })
if err := tst.syncStreamingPartsToNode(ctx, node, streamingParts); err != nil {
return err
}
@@ -444,6 +292,30 @@ func (tst *tsTable) syncStreamingPartsToNodes(ctx context.Context, nodes []strin
return nil
}
+// handleSyncIntroductions creates and processes sync introductions for both core and sidx parts.
+func (tst *tsTable) handleSyncIntroductions(partsToSync []*part, syncCh chan *syncIntroduction) error {
+ // Create core sync introduction
+ si := generateSyncIntroduction()
+ defer releaseSyncIntroduction(si)
+ si.applied = make(chan struct{})
+ for _, part := range partsToSync {
+ si.synced[part.partMetadata.ID] = struct{}{}
+ }
+
+ select {
+ case syncCh <- si:
+ case <-tst.loopCloser.CloseNotify():
+ return errClosed
+ }
+
+ select {
+ case <-si.applied:
+ case <-tst.loopCloser.CloseNotify():
+ return errClosed
+ }
+ return nil
+}
+
// syncStreamingPartsToNode synchronizes streaming parts to a node.
func (tst *tsTable) syncStreamingPartsToNode(ctx context.Context, node string, streamingParts []queue.StreamingPartData) error {
// Get chunked sync client for this node
diff --git a/banyand/trace/tstable.go b/banyand/trace/tstable.go
index 86453916..0bd13dd1 100644
--- a/banyand/trace/tstable.go
+++ b/banyand/trace/tstable.go
@@ -106,6 +106,7 @@ func (tst *tsTable) loadSnapshot(epoch uint64, loadedParts []uint64) {
}
snp.incRef()
tst.snapshot = &snp
+ tst.loadSidxMap(parts)
if needToPersist {
tst.persistSnapshot(&snp)
}
@@ -123,15 +124,16 @@ func (tst *tsTable) startLoop(cur uint64) {
go tst.mergeLoop(mergeCh, flusherWatcher)
}
-func (tst *tsTable) startLoopNoMerge(cur uint64) {
+func (tst *tsTable) startLoopWithConditionalMerge(cur uint64) {
tst.loopCloser = run.NewCloser(1 + 3)
tst.introductions = make(chan *introduction)
flushCh := make(chan *flusherIntroduction)
syncCh := make(chan *syncIntroduction)
+ mergeCh := make(chan *mergerIntroduction)
introducerWatcher := make(watcher.Channel, 1)
flusherWatcher := make(watcher.Channel, 1)
- go tst.introducerLoopWithSync(flushCh, syncCh, introducerWatcher, cur+1)
- go tst.flusherLoopNoMerger(flushCh, introducerWatcher, flusherWatcher, cur)
+ go tst.introducerLoopWithSync(flushCh, mergeCh, syncCh, introducerWatcher, cur+1)
+ go tst.flusherLoop(flushCh, mergeCh, introducerWatcher, flusherWatcher, cur)
go tst.syncLoop(syncCh, flusherWatcher)
}
@@ -203,7 +205,6 @@ func initTSTable(fileSystem fs.FileSystem, rootPath string, p common.Position,
if m != nil {
tst.metrics = m.(*metrics)
}
- tst.loadSidxMap()
tst.gc.init(&tst)
ee := fileSystem.ReadDir(rootPath)
if len(ee) == 0 {
@@ -276,6 +277,22 @@ func (tst *tsTable) getSidx(name string) (sidx.SIDX, bool) {
return sidxInstance, ok
}
+func (tst *tsTable) mustGetSidx(name string) sidx.SIDX {
+ sidxInstance, ok := tst.getSidx(name)
+ if !ok {
+ tst.l.Panic().Str("name", name).Msg("sidx not found")
+ }
+ return sidxInstance
+}
+
+func (tst *tsTable) mustGetOrCreateSidx(name string) sidx.SIDX {
+ sidxInstance, err := tst.getOrCreateSidx(name)
+ if err != nil {
+ tst.l.Panic().Str("name", name).Msg("cannot get or create sidx")
+ }
+ return sidxInstance
+}
+
func (tst *tsTable) getOrCreateSidx(name string) (sidx.SIDX, error) {
if sidxInstance, ok := tst.getSidx(name); ok {
return sidxInstance, nil
@@ -300,6 +317,9 @@ func (tst *tsTable) getOrCreateSidx(name string) (sidx.SIDX, error) {
if err != nil {
return nil, fmt.Errorf("cannot create sidx for %s: %w", name, err)
}
+ if tst.sidxMap == nil {
+ tst.sidxMap = make(map[string]sidx.SIDX)
+ }
tst.sidxMap[name] = newSidx
return newSidx, nil
@@ -317,7 +337,7 @@ func (tst *tsTable) getAllSidx() map[string]sidx.SIDX {
return result
}
-func (tst *tsTable) loadSidxMap() {
+func (tst *tsTable) loadSidxMap(availablePartIDs []uint64) {
tst.sidxMap = make(map[string]sidx.SIDX)
sidxRootPath := filepath.Join(tst.root, sidxDirName)
if _, err := os.Stat(sidxRootPath); os.IsNotExist(err) {
@@ -341,6 +361,7 @@ func (tst *tsTable) loadSidxMap() {
tst.l.Error().Err(err).Str("name", sidxName).Msg("failed to create sidx options, skipping")
continue
}
+ sidxOpts.AvailablePartIDs = availablePartIDs
newSidx, err := sidx.NewSIDX(tst.fileSystem, sidxOpts)
if err != nil {
tst.l.Error().Err(err).Str("name", sidxName).Msg("failed to create sidx instance, skipping")
@@ -378,7 +399,7 @@ func (tst *tsTable) Close() error {
return tst.closeSidxMap()
}
-func (tst *tsTable) mustAddMemPart(mp *memPart) {
+func (tst *tsTable) mustAddMemPart(mp *memPart, sidxReqsMap map[string]*sidx.MemPart) {
p := openMemPart(mp)
ind := generateIntroduction()
@@ -386,6 +407,7 @@ func (tst *tsTable) mustAddMemPart(mp *memPart) {
ind.applied = make(chan struct{})
ind.memPart = newPartWrapper(mp, p)
ind.memPart.p.partMetadata.ID = atomic.AddUint64(&tst.curPartID, 1)
+ ind.sidxReqsMap = sidxReqsMap
startTime := time.Now()
totalCount := mp.partMetadata.TotalCount
select {
@@ -402,11 +424,11 @@ func (tst *tsTable) mustAddMemPart(mp *memPart) {
tst.incTotalBatchIntroLatency(time.Since(startTime).Seconds())
}
-func (tst *tsTable) mustAddTraces(ts *traces) {
- tst.mustAddTracesWithSegmentID(ts, 0)
+func (tst *tsTable) mustAddTraces(ts *traces, sidxReqsMap map[string]*sidx.MemPart) {
+ tst.mustAddTracesWithSegmentID(ts, 0, sidxReqsMap)
}
-func (tst *tsTable) mustAddTracesWithSegmentID(ts *traces, segmentID int64) {
+func (tst *tsTable) mustAddTracesWithSegmentID(ts *traces, segmentID int64, sidxReqsMap map[string]*sidx.MemPart) {
if len(ts.traceIDs) == 0 {
return
}
@@ -414,7 +436,8 @@ func (tst *tsTable) mustAddTracesWithSegmentID(ts *traces, segmentID int64) {
mp := generateMemPart()
mp.mustInitFromTraces(ts)
mp.segmentID = segmentID
- tst.mustAddMemPart(mp)
+
+ tst.mustAddMemPart(mp, sidxReqsMap)
}
type tstIter struct {
diff --git a/banyand/trace/tstable_test.go b/banyand/trace/tstable_test.go
index 244afa11..6b7ef6bb 100644
--- a/banyand/trace/tstable_test.go
+++ b/banyand/trace/tstable_test.go
@@ -92,7 +92,7 @@ func Test_tsTable_mustAddTraces(t *testing.T) {
go tst.introducerLoop(flushCh, mergeCh, introducerWatcher, 1)
defer tst.Close()
for _, ts := range tt.tsList {
- tst.mustAddTraces(ts)
+ tst.mustAddTraces(ts, nil)
time.Sleep(100 * time.Millisecond)
}
s := tst.currentSnapshot()
@@ -208,7 +208,7 @@ func Test_tstIter(t *testing.T) {
introducerWatcher := make(watcher.Channel, 1)
go tst.introducerLoop(flushCh, mergeCh, introducerWatcher, 1)
for _, ts := range tt.tsList {
- tst.mustAddTraces(ts)
+ tst.mustAddTraces(ts, nil)
time.Sleep(100 * time.Millisecond)
}
verify(t, tt, tst)
diff --git a/banyand/trace/wqueue.go b/banyand/trace/wqueue.go
index 96976e22..ef5584dd 100644
--- a/banyand/trace/wqueue.go
+++ b/banyand/trace/wqueue.go
@@ -39,6 +39,6 @@ func newWriteQueue(fileSystem fs.FileSystem, rootPath string, p common.Position,
t.getNodes = getNodes
t.group = group
t.shardID = shardID
- t.startLoopNoMerge(epoch)
+ t.startLoopWithConditionalMerge(epoch)
return t, nil
}
diff --git a/banyand/trace/wqueue_test.go b/banyand/trace/wqueue_test.go
index 9a6862fb..02c20d2a 100644
--- a/banyand/trace/wqueue_test.go
+++ b/banyand/trace/wqueue_test.go
@@ -81,7 +81,7 @@ func Test_newWriteQueue(t *testing.T) {
// Wait for the creator to be set to snapshotCreatorSyncer
assert.Eventually(t, func() bool {
- tst.mustAddTraces(ts)
+ tst.mustAddTraces(ts, nil)
time.Sleep(100 * time.Millisecond)
s := tst.currentSnapshot()
if s == nil {
diff --git a/banyand/trace/write_data.go b/banyand/trace/write_data.go
index f1d8da52..2e691cef 100644
--- a/banyand/trace/write_data.go
+++ b/banyand/trace/write_data.go
@@ -18,7 +18,6 @@
package trace
import (
- "context"
"fmt"
"strings"
"time"
@@ -35,11 +34,41 @@ type syncPartContext struct {
l *logger.Logger
writers *writers
memPart *memPart
- sidxPartContext *sidx.SyncPartContext
+ sidxPartContexts map[string]*sidx.SyncPartContext
traceIDFilterBuffer []byte
tagTypeBuffer []byte
}
+func (s *syncPartContext) NewPartType(ctx *queue.ChunkedSyncPartContext) error {
+ if ctx.PartType != PartTypeCore {
+ sidxPartContext := sidx.NewSyncPartContext()
+ memPart := sidx.GenerateMemPart()
+ memPart.SetPartMetadata(ctx.CompressedSizeBytes, ctx.UncompressedSizeBytes, ctx.TotalCount, ctx.BlocksCount, ctx.MinKey, ctx.MaxKey, ctx.ID)
+ writers := sidx.GenerateWriters()
+ writers.MustInitForMemPart(memPart)
+ sidxPartContext.Set(ctx.PartType, memPart, writers)
+ if s.sidxPartContexts == nil {
+ s.sidxPartContexts = make(map[string]*sidx.SyncPartContext)
+ }
+ s.sidxPartContexts[ctx.PartType] = sidxPartContext
+ return nil
+ }
+
+ memPart := generateMemPart()
+ memPart.partMetadata.CompressedSizeBytes = ctx.CompressedSizeBytes
+ memPart.partMetadata.UncompressedSpanSizeBytes = ctx.UncompressedSizeBytes
+ memPart.partMetadata.TotalCount = ctx.TotalCount
+ memPart.partMetadata.BlocksCount = ctx.BlocksCount
+ memPart.partMetadata.MinTimestamp = ctx.MinTimestamp
+ memPart.partMetadata.MaxTimestamp = ctx.MaxTimestamp
+ memPart.partMetadata.ID = ctx.ID
+ writers := generateWriters()
+ writers.mustInitForMemPart(memPart)
+ s.writers = writers
+ s.memPart = memPart
+ return nil
+}
+
func (s *syncPartContext) FinishSync() error {
if len(s.traceIDFilterBuffer) > 0 && s.memPart != nil {
bf := filter.NewBloomFilter(0)
@@ -56,15 +85,11 @@ func (s *syncPartContext) FinishSync() error {
}
if s.memPart != nil {
- s.tsTable.mustAddMemPart(s.memPart)
- }
- if s.sidxPartContext != nil {
- memPart := s.sidxPartContext.GetMemPart()
- sidxInstance, err := s.tsTable.getOrCreateSidx(s.sidxPartContext.Name())
- if err != nil {
- return err
+ sidxPartContexts := make(map[string]*sidx.MemPart, len(s.sidxPartContexts))
+ for _, sidxPartContext := range s.sidxPartContexts {
+ sidxPartContexts[sidxPartContext.Name()] = sidxPartContext.GetMemPart()
}
- sidxInstance.MustAddMemPart(context.TODO(), memPart)
+ s.tsTable.mustAddMemPart(s.memPart, sidxPartContexts)
}
return s.Close()
}
@@ -78,9 +103,11 @@ func (s *syncPartContext) Close() error {
if s.memPart != nil {
s.memPart = nil
}
- if s.sidxPartContext != nil {
- s.sidxPartContext.Close()
- s.sidxPartContext = nil
+ if s.sidxPartContexts != nil {
+ for _, sidxPartContext := range s.sidxPartContexts {
+ sidxPartContext.Close()
+ }
+ s.sidxPartContexts = nil
}
s.tsTable = nil
s.traceIDFilterBuffer = nil
@@ -125,37 +152,11 @@ func (s *syncCallback) CreatePartHandler(ctx *queue.ChunkedSyncPartContext) (que
}
tsdb.Tick(ctx.MaxTimestamp)
-
- if ctx.PartType != PartTypeCore {
- sidxPartContext := sidx.NewSyncPartContext()
- memPart := sidx.GenerateMemPart()
- memPart.SetPartMetadata(ctx.CompressedSizeBytes, ctx.UncompressedSizeBytes, ctx.TotalCount, ctx.BlocksCount, ctx.MinKey, ctx.MaxKey, ctx.ID)
- writers := sidx.GenerateWriters()
- writers.MustInitForMemPart(memPart)
- sidxPartContext.Set(ctx.PartType, memPart, writers)
- return &syncPartContext{
- tsTable: tsTable,
- l: s.l,
- sidxPartContext: sidxPartContext,
- }, nil
- }
-
- memPart := generateMemPart()
- memPart.partMetadata.CompressedSizeBytes = ctx.CompressedSizeBytes
- memPart.partMetadata.UncompressedSpanSizeBytes = ctx.UncompressedSizeBytes
- memPart.partMetadata.TotalCount = ctx.TotalCount
- memPart.partMetadata.BlocksCount = ctx.BlocksCount
- memPart.partMetadata.MinTimestamp = ctx.MinTimestamp
- memPart.partMetadata.MaxTimestamp = ctx.MaxTimestamp
- memPart.partMetadata.ID = ctx.ID
- writers := generateWriters()
- writers.mustInitForMemPart(memPart)
- return &syncPartContext{
+ partCtx := &syncPartContext{
tsTable: tsTable,
l: s.l,
- writers: writers,
- memPart: memPart,
- }, nil
+ }
+ return partCtx, partCtx.NewPartType(ctx)
}
// HandleFileChunk implements queue.ChunkedSyncHandler for streaming file chunks.
@@ -173,7 +174,7 @@ func (s *syncCallback) handleSidxFileChunk(ctx *queue.ChunkedSyncPartContext, ch
sidxName := ctx.PartType
fileName := ctx.FileName
partCtx := ctx.Handler.(*syncPartContext)
- writers := partCtx.sidxPartContext.GetWriters()
+ writers := partCtx.sidxPartContexts[sidxName].GetWriters()
switch {
case fileName == sidx.SidxPrimaryName:
writers.SidxPrimaryWriter().MustWrite(chunk)
diff --git a/banyand/trace/write_liaison.go b/banyand/trace/write_liaison.go
index d4741f50..6bf27f41 100644
--- a/banyand/trace/write_liaison.go
+++ b/banyand/trace/write_liaison.go
@@ -191,9 +191,7 @@ func (w *writeQueueCallback) Rev(ctx context.Context, message bus.Message) (resp
g := groups[i]
for j := range g.tables {
es := g.tables[j]
- es.tsTable.mustAddTracesWithSegmentID(es.traces, es.timeRange.Start.UnixNano())
- releaseTraces(es.traces)
-
+ var sidxMemPartMap map[string]*sidx.MemPart
for sidxName, sidxReqs := range es.sidxReqsMap {
if len(sidxReqs) > 0 {
sidxInstance, err := es.tsTable.getOrCreateSidx(sidxName)
@@ -201,11 +199,19 @@ func (w *writeQueueCallback) Rev(ctx context.Context, message bus.Message) (resp
w.l.Error().Err(err).Str("sidx", sidxName).Msg("cannot get or create sidx instance")
continue
}
- if err := sidxInstance.Write(ctx, sidxReqs, es.timeRange.Start.UnixNano()); err != nil {
+ var siMemPart *sidx.MemPart
+ if siMemPart, err = sidxInstance.ConvertToMemPart(sidxReqs, es.timeRange.Start.UnixNano()); err != nil {
w.l.Error().Err(err).Str("sidx", sidxName).Msg("cannot write to secondary index")
+ continue
}
+ if sidxMemPartMap == nil {
+ sidxMemPartMap = make(map[string]*sidx.MemPart)
+ }
+ sidxMemPartMap[sidxName] = siMemPart
}
}
+ es.tsTable.mustAddTracesWithSegmentID(es.traces, es.timeRange.Start.UnixNano(), sidxMemPartMap)
+ releaseTraces(es.traces)
nodes := g.queue.GetNodes(es.shardID)
if len(nodes) == 0 {
diff --git a/banyand/trace/write_standalone.go b/banyand/trace/write_standalone.go
index eece4100..89db05fa 100644
--- a/banyand/trace/write_standalone.go
+++ b/banyand/trace/write_standalone.go
@@ -331,7 +331,7 @@ func processTraces(schemaRepo *schemaRepo, tracesInTable *tracesInTable, writeEv
return nil
}
-func (w *writeCallback) Rev(ctx context.Context, message bus.Message) (resp bus.Message) {
+func (w *writeCallback) Rev(_ context.Context, message bus.Message) (resp bus.Message) {
events, ok := message.Data().([]any)
if !ok {
w.l.Warn().Msg("invalid event data type")
@@ -368,6 +368,7 @@ func (w *writeCallback) Rev(ctx context.Context, message bus.Message) (resp bus.
g := groups[i]
for j := range g.tables {
es := g.tables[j]
+ var sidxMemPartMap map[string]*sidx.MemPart
for sidxName, sidxReqs := range es.sidxReqsMap {
if len(sidxReqs) > 0 {
sidxInstance, err := es.tsTable.getOrCreateSidx(sidxName)
@@ -375,9 +376,15 @@ func (w *writeCallback) Rev(ctx context.Context, message bus.Message) (resp bus.
w.l.Error().Err(err).Str("sidx", sidxName).Msg("cannot get or create sidx instance")
continue
}
- if err := sidxInstance.Write(ctx, sidxReqs, es.timeRange.Start.UnixNano()); err != nil {
+ var siMemPart *sidx.MemPart
+ if siMemPart, err = sidxInstance.ConvertToMemPart(sidxReqs, es.timeRange.Start.UnixNano()); err != nil {
w.l.Error().Err(err).Str("sidx", sidxName).Msg("cannot write to secondary index")
+ continue
+ }
+ if sidxMemPartMap == nil {
+ sidxMemPartMap = make(map[string]*sidx.MemPart)
}
+ sidxMemPartMap[sidxName] = siMemPart
}
}
if len(es.seriesDocs.docs) > 0 {
@@ -385,7 +392,7 @@ func (w *writeCallback) Rev(ctx context.Context, message bus.Message) (resp bus.
w.l.Error().Err(err).Msg("cannot write series index")
}
}
- es.tsTable.mustAddTraces(es.traces)
+ es.tsTable.mustAddTraces(es.traces, sidxMemPartMap)
releaseTraces(es.traces)
}
if len(g.segments) > 0 {