package engine import ( "context" "errors" "fmt" "path" "strings" "testing" "time" "github.com/seaweedfs/seaweedfs/weed/mq/schema" "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/mq/topictable" "github.com/seaweedfs/seaweedfs/weed/mq/topictable/topictabletest" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb" "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" "github.com/seaweedfs/seaweedfs/weed/util/log_buffer" "google.golang.org/protobuf/proto" ) var tableRecordType = schema.RecordTypeBegin().WithField("id", schema.TypeInt64).WithField("body", schema.TypeString).RecordTypeEnd() type tableTestBroker struct{ BrokerClientInterface } func (tableTestBroker) GetTopicSchema(context.Context, string, string) (*schema_pb.RecordType, []string, string, error) { return tableRecordType, nil, "", nil } func (tableTestBroker) GetUnflushedMessages(context.Context, string, string, topic.Partition, int64) ([]*filer_pb.LogEntry, error) { return nil, nil } // tableMessage is offset's message; 5 is a close marker, with neither key nor value. func tableMessage(t *testing.T, offset int64) *filer_pb.LogEntry { t.Helper() data, err := proto.Marshal(&schema_pb.RecordValue{Fields: map[string]*schema_pb.Value{ "id": {Kind: &schema_pb.Value_Int64Value{Int64Value: offset}}, "body": {Kind: &schema_pb.Value_StringValue{StringValue: fmt.Sprintf("message %d", offset)}}, }}) if err != nil { t.Fatal(err) } day := time.Date(2026, 11, 30, 23, 59, 0, 0, time.UTC) if offset >= 6 { day = day.Add(2 * time.Minute) } entry := &filer_pb.LogEntry{Offset: offset, TsNs: day.Add(time.Duration(offset) * time.Second).UnixNano(), Key: fmt.Appendf(nil, "k%d", offset), Data: data} if offset == 5 { entry.Key, entry.Data = nil, nil } return entry } func tableMessages(t *testing.T, from, to int64) (entries []*filer_pb.LogEntry) { for offset := from; offset <= to; offset++ { entries = append(entries, tableMessage(t, offset)) } return entries } var ( tableGeneration = time.Date(2026, 11, 30, 0, 0, 0, 0, time.UTC).UnixNano() tablePartitionA = topic.Partition{RangeStart: 0, RangeStop: 2048, RingSize: topic.PartitionCount, UnixTimeNs: tableGeneration} tablePartitionB = topic.Partition{RangeStart: 2048, RangeStop: 4096, RingSize: topic.PartitionCount, UnixTimeNs: tableGeneration} ) func putPartitionDirs(f *topictabletest.Filer, tp topic.Topic) { for _, p := range []topic.Partition{tablePartitionA, tablePartitionB} { dir := topic.PartitionDir(tp, p) f.Put(path.Dir(dir), path.Base(dir), nil) f.Put(path.Dir(path.Dir(dir)), path.Base(path.Dir(dir)), nil) } } func scanAll(t *testing.T, f *topictabletest.Filer, tp topic.Topic) []HybridScanResult { t.Helper() hms, err := NewHybridMessageScanner(f.FilerClient(), tableTestBroker{}, tp.Namespace, tp.Name, nil) if err != nil { t.Fatal(err) } results, _, err := hms.ScanWithStats(context.Background(), HybridScanOptions{Limit: -1, Predicate: func(*schema_pb.RecordValue) bool { return true }}) if err != nil { t.Fatal(err) } return results } // A table-backed topic scans the same rows as the same messages held in log // files: the table below each partition's mark, the logs from it, and the // logs a crash left below the mark not at all. func TestScanOfATopicTableMatchesItsLogs(t *testing.T) { f := topictabletest.StartFiler(t) baseline := topic.NewTopic("test", "logs") f.PutTopicConf(t, baseline, &mq_pb.ConfigureTopicResponse{MessageRecordType: tableRecordType}) putPartitionDirs(f, baseline) f.PutLogFile(t, baseline, tablePartitionA, tableMessages(t, 0, 5)...) f.PutLogFile(t, baseline, tablePartitionA, tableMessages(t, 6, 14)...) f.PutLogFile(t, baseline, tablePartitionB, tableMessages(t, 0, 6)...) tiered := topic.NewTopic("test", "tiered") tb := topictabletest.NewTable(t, f, tiered, tableRecordType) f.PutTopicConf(t, tiered, &mq_pb.ConfigureTopicResponse{MessageRecordType: tableRecordType, Table: tb.Ref}) putPartitionDirs(f, tiered) a, b := topictable.PartitionName(tiered, tablePartitionA), topictable.PartitionName(tiered, tablePartitionB) tb.Append(t, map[string]int64{a: 10, b: 4}, topictabletest.File{Partition: a, Entries: tableMessages(t, 0, 4)}, topictabletest.File{Partition: a, Entries: tableMessages(t, 6, 9)}, topictabletest.File{Partition: b, Entries: tableMessages(t, 0, 3)}) f.PutLogFile(t, tiered, tablePartitionA, tableMessages(t, 8, 11)...) f.PutLogFile(t, tiered, tablePartitionA, tableMessages(t, 12, 14)...) f.PutLogFile(t, tiered, tablePartitionB, tableMessages(t, 2, 6)...) want, got := scanAll(t, f, baseline), scanAll(t, f, tiered) if len(want) != 20 { t.Fatalf("baseline scanned %d rows, want 20", len(want)) } if len(got) != len(want) { t.Fatalf("scanned %d rows, the logs hold %d", len(got), len(want)) } seen := map[string]int{} for _, r := range want { seen[fmt.Sprintf("%d/%s/%v", r.Timestamp, r.Key, r.Values["body"])]++ } for _, r := range got { seen[fmt.Sprintf("%d/%s/%v", r.Timestamp, r.Key, r.Values["body"])]-- } for row, n := range seen { if n != 0 { t.Errorf("row %s: %d more in the logs' scan than the table's", row, n) } } sources := map[string]int{} for _, r := range got { sources[r.Source]++ } for _, r := range want { sources["baseline "+r.Source]++ } // table rows: A's 0..9 but the control entry 5, and B's 0..3 if sources["parquet_archive"] != 13 || sources["live_log"] != 7 || sources["baseline live_log"] != 20 { t.Errorf("sources %v, want the table's rows as parquet_archive", sources) } hms, err := NewHybridMessageScanner(f.FilerClient(), tableTestBroker{}, tiered.Namespace, tiered.Name, nil) if err != nil { t.Fatal(err) } if _, fast := (&SQLEngine{}).tryFastParquetAggregationWithPlan(context.Background(), hms, []AggregationSpec{{Function: FuncCOUNT, Column: "*"}}, nil, 0, 0, nil); fast { t.Error("counted a table-backed topic from parquet statistics, which hold none of its table's rows") } } // A query cancelled while its table lookup stalls returns at once. func TestCancelledScanOfAStalledTableReturns(t *testing.T) { f := topictabletest.StartFiler(t) tiered := topic.NewTopic("test", "tiered") tb := topictabletest.NewTable(t, f, tiered, tableRecordType) f.PutTopicConf(t, tiered, &mq_pb.ConfigureTopicResponse{MessageRecordType: tableRecordType, Table: tb.Ref}) putPartitionDirs(f, tiered) f.PutLogFile(t, tiered, tablePartitionA, tableMessages(t, 0, 3)...) release := make(chan struct{}) t.Cleanup(func() { close(release) }) f.OnLookup = func(dir, _ string) { if strings.HasPrefix(dir, "/buckets") { <-release } } hms, err := NewHybridMessageScanner(f.FilerClient(), tableTestBroker{}, tiered.Namespace, tiered.Name, nil) if err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) defer cancel() done := make(chan error, 1) go func() { _, _, err := hms.ScanWithStats(ctx, HybridScanOptions{Limit: -1, Predicate: func(*schema_pb.RecordValue) bool { return true }}) done <- err }() select { case err := <-done: if err == nil { t.Fatal("a scan of a table that never answered succeeded") } case <-time.After(5 * time.Second): t.Fatal("a cancelled scan stayed blocked on its table lookup") } } // manyRowsTopic is a topic whose logs hold more rows than a flushed data // source buffers, so its producer blocks sending. func manyRowsTopic(t *testing.T) (*topictabletest.Filer, *HybridMessageScanner) { t.Helper() f := topictabletest.StartFiler(t) logs := topic.NewTopic("test", "many") f.PutTopicConf(t, logs, &mq_pb.ConfigureTopicResponse{MessageRecordType: tableRecordType}) // one partition, so a scan's answer is that partition's merge alone dir := topic.PartitionDir(logs, tablePartitionA) f.Put(path.Dir(dir), path.Base(dir), nil) f.Put(path.Dir(path.Dir(dir)), path.Base(path.Dir(dir)), nil) f.PutLogFile(t, logs, tablePartitionA, tableMessages(t, 6, 400)...) hms, err := NewHybridMessageScanner(f.FilerClient(), tableTestBroker{}, logs.Namespace, logs.Name, nil) if err != nil { t.Fatal(err) } return f, hms } // Closing a source whose producer is blocked sending stops the producer; // nothing sends on a channel closed under it. func TestClosingAFlushedSourceStopsItsBlockedProducer(t *testing.T) { _, hms := manyRowsTopic(t) source := NewStreamingFlushedDataSource(context.Background(), hms, tablePartitionA, HybridScanOptions{Predicate: func(*schema_pb.RecordValue) bool { return true }}) if result, err := source.Next(); err != nil || result == nil { t.Fatalf("first row %v %v", result, err) } // let the producer fill the buffer and block on the next send deadline := time.Now().Add(5 * time.Second) for len(source.resultChan) < cap(source.resultChan) && time.Now().Before(deadline) { time.Sleep(time.Millisecond) } source.Close() for !source.finished.Load() { if time.Now().After(deadline) { t.Fatal("the producer kept running after its source was closed") } time.Sleep(time.Millisecond) } } // A query cancelled after its first row fails with the context's error, // not with the rows read so far, which a COUNT or SUM would take as its answer. func TestScanCancelledMidwayFails(t *testing.T) { _, hms := manyRowsTopic(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() // cancelled past what the source buffers, so the merge has taken rows rows := 0 results, _, err := hms.ScanWithStats(ctx, HybridScanOptions{Limit: -1, Predicate: func(*schema_pb.RecordValue) bool { if rows++; rows == 150 { cancel() } return true }}) if !errors.Is(err, context.Canceled) { t.Fatalf("a cancelled scan returned %d rows and %v, want the context's error", len(results), err) } } // slowAfterFirst takes its first row while the producer behind it still // holds its error back, lets the producer go on, and returns the row only once // the producer has failed and finished, as a merge slower than its producer // sees it. type slowAfterFirst struct { *StreamingFlushedDataSource received chan struct{} rows int } func (s *slowAfterFirst) Next() (*HybridScanResult, error) { result, err := s.StreamingFlushedDataSource.Next() if s.rows++; s.rows == 1 { close(s.received) for !s.finished.Load() { time.Sleep(time.Millisecond) } } return result, err } // A producer that fails after its last row and finishes before the merge // asks for more fails the merge: an error waiting is more to read. func TestMergeReturnsAnErrorPendingAfterTheLastRow(t *testing.T) { _, hms := manyRowsTopic(t) source := NewStreamingFlushedDataSource(context.Background(), hms, tablePartitionA, HybridScanOptions{Predicate: func(*schema_pb.RecordValue) bool { return true }}) slow := &slowAfterFirst{StreamingFlushedDataSource: source, received: make(chan struct{})} failed := errors.New("volume unreachable") source.mergedReadFn = func(start log_buffer.MessagePosition, stopTsNs int64, each log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) { if _, err := each(tableMessage(t, 6)); err != nil { return start, false, err } // the first Next has the row before the error exists <-slow.received return start, false, failed } results, err := hms.streamingMerge([]StreamingDataSource{slow}, 0) if !errors.Is(err, failed) { t.Fatalf("the merge returned %d rows and %v, want the producer's error", len(results), err) } }