mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
* log_buffer: find a fetched offset in a disk chunk by its offset A stateless read caches disk reads in chunks aligned to 1000 offsets and picked the requested message by its distance from the aligned start. A chunk read from disk begins at the first offset stored at or above that start, so once the partition's oldest files are gone the chunk begins later and the read returned messages from further on, under the requested offsets. The message is now found by its offset, and the next offset follows the last message returned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: start a loaded partition's log at its earliest stored offset A loaded partition reported its earliest offset as 0 and its log start as the start of its memory, so neither said where the stored data begins. The log buffer now keeps the earliest offset still stored: a leader seeds it from the offset ranges on its files when it loads, it only moves up, and the partition's offset info and log start report it. A stateless read below it fails with ErrOffsetOutOfRange instead of being answered from a later file under the requested offsets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: purge a partition's files past its topic's retention A topic's retention was stored but never applied, so a topic that is not re-partitioned kept every flushed file. Every five minutes the broker now purges each partition it leads whose topic has retention enabled. It deletes the oldest run of files whose newest message is older than the retention, stopping at the first file still retained so the stored offsets stay contiguous, and always keeps the file with the highest offset, which a later load continues offsets from. A log file is judged by when it was flushed and a parquet file by its newest row; a parquet file is deleted together with its source log files. The partition's log start is raised before the deletes, and each delete is a transaction conditioned on the partition's fence token, so a leader that lost its fence deletes nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: map an unknown broker error to UNKNOWN_SERVER_ERROR (-1) The gateway's error table gave UNKNOWN_SERVER_ERROR the code 1, which Kafka uses for OFFSET_OUT_OF_RANGE, and the broker's table carried the same value for its unknown and publisher-not-found errors. Today the mapped code only reaches error text, but a fetch path that answers OFFSET_OUT_OF_RANGE by its Kafka code would make every unknown broker failure reset a consumer. The code is now -1. The gateway only tests these codes against 0 and against specific codes, and the cached assignment is still dropped on the broker's own code 1, so nothing treated 1 as success or depended on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: answer a fetch below retention with OFFSET_OUT_OF_RANGE A read below the earliest retained offset failed like any other read, so FetchMessage reported a storage error and the gateway answered KAFKA_STORAGE_ERROR, which a consumer retries at the same offset forever once retention has purged it. FetchMessage now answers ErrOffsetOutOfRange with its own broker code, the earliest retained offset as LogStartOffset, and the requested offset as NextOffset. The gateway carries it as ErrOffsetOutOfRange and answers the partition with OFFSET_OUT_OF_RANGE, so the consumer applies auto.offset.reset; a reset to earliest asks ListOffsets, which reports the retained start through the leader's range info. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: keep a disk chunk's entries in offset order A disk read filled its 1000-offset chunk with the first 1000 entries in the order the files listed, and the lookup searches the chunk by offset. Files whose names sort out of offset order deliver entries out of order, so the chunk held the wrong offsets and was cached that way. It now keeps only the chunk's offsets, wherever they come, and sorts them before caching. * mq broker: purge a partition's files in offset order The purge walked a partition's files in name order and stopped at the first one still retained. Names sort by the start of a window, which can be earlier than older files' after a reload, so a file holding higher offsets could be purged ahead of a retained one below it, leaving a hole. The walk now goes by each file's first offset, taking a parquet file that records none from its first source, and by name among equals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: round a log file's flush time up to bound its messages A log file without a recorded newest timestamp is judged by its Mtime, which the filer keeps in whole seconds, so a file flushed later in the cutoff's second looked older than messages it may hold. The purge now takes the end of that second as the bound. A recorded newest timestamp is still used as is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: keep one entry per offset in a disk chunk A disk read goes through a partition's log files and then its parquet files, and a parquet file holds the same offsets as the log files it was compacted from, so a chunk could take an offset twice and a fetch returned the duplicate as the next message. The chunk now keeps the first entry for each offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: reread a cached disk chunk that lacks the fetched offset A disk chunk can be cached while its later offsets are still in memory. Once those are flushed and memory moves on, a fetch past the cached part hit the cache, found nothing, and returned no messages until the chunk was evicted. A cached chunk that does not hold the fetched offset is now dropped and read from disk again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: record a parquet file's offset range from its sources The compactor took a parquet file's offset range from its entries' offsets above 0 and recorded it only when the lowest was above 0, so a file compacted from a partition's first window recorded no range, and one whose entries started at 0 would have claimed to start at 1. The range now comes from the source log files' recorded ranges, including one that starts at offset 0, and is left out unless every source records one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: keep the earliest offset at or below files that record no range The earliest stored offset was the lowest offset any file records, so a file that records none, such as a parquet file compacted from a partition's first window or a log file flushed without a range, was left out. A reload or a purge could then start the log above offsets a read can still return, and ListOffsets for the earliest offset left them out. OffsetRange now takes the whole entry and keeps the earliest offset at 0 while a log or parquet file records no range, except a parquet file whose listed sources are all present, as their ranges cover it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a partition whose files cannot all be placed by offset The purge ordered a data file that records no offsets, and whose sources give none, as if it held the lowest, so an expired one could be deleted while a retained file below its offsets stayed, leaving a hole. A partition holding such a file is now left alone; only files written before offsets were recorded lack them. * mq broker: purge a parquet file only when each of its sources has expired The purge deleted every source of an expired parquet file along with it, judging the whole group by the parquet file's newest timestamp. Message timestamps are not ordered across reloads, so a parquet file can hold an expired source next to one still retained, and the retained one went early. A parquet group is now purged only when the parquet file and each source in it are past the cutoff on their own; otherwise the walk stops there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: record a parquet file's lowest and highest timestamps The compactor recorded a parquet file's timestamp range from its first and last rows. Message timestamps are not ordered across reloads, so the last row need not be the newest, and the recorded ts_max could sit below messages the file holds, making it look older to the retention purge and to readers that skip files by time. It now records the lowest and highest timestamps over all rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: keep each compacted row's offset in the _offset column The compaction schema had no _offset column, so a schematized row's offset was dropped and a schemaless row never carried one, while the parquet reader expects the column and a fetch places rows by offset. The compactor now adds the column when the schema lacks it and fills it for every row, schemaless ones included, when the source files record their offsets; otherwise it is left null. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: read a parquet file by its own columns and mark unknown offsets The parquet reader always expected an _offset column and read rows by column position, so a file compacted before the column existed was read out of alignment and panicked with an index out of range. A row with no real offset also read back as offset 0, so a disk chunk, which keeps one entry per offset, collapsed such rows into one. The reader now uses the _offset column only when the file has it, trusts it only when the file records its offset range, and reports any other row with offset -1, which keeps it out of reads by offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a purge group that reaches past the first retained offset A parquet file is purged with its sources as one group, and the sources need not be contiguous: an expired parquet file could list expired files on both sides of a retained one, so purging the group left a hole above the retained file. A group now goes only when every offset it and its sources cover lies below the first offset left behind; the walk keeps the first group that does not, and the ones after it. A log file whose offsets a retained parquet file also starts at now stays until that parquet file goes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: give compaction test fixtures file ids no other fixture uses The parquet reader caches chunks in a package-wide cache keyed by file id, and each compaction fixture numbered its file ids from 1, so one fixture could read another's cached bytes; with -count=3 a test read a parquet file from an earlier run and failed. File ids are now numbered across all fixtures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: compact legacy log files apart from ones that record offsets A compaction group could hold a legacy log file without an offset range next to files that record one, and a parquet file keeps its rows' offsets only when every source records them, so the ranged rows lost their offsets and could no longer be fetched by offset. Groups now split where a file's having an offset range differs from the group's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: treat a parquet file's end as unknown when a source is gone A parquet file that records no offset range took its last offset from the sources still present, so one whose later source was already gone looked as if it ended below a retained file and was purged, though it may hold that source's offsets above the retained one. A gone or unranged source now leaves the end unknown, and the group stays. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
529 lines
15 KiB
Go
529 lines
15 KiB
Go
package log_buffer
|
|
|
|
import (
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
)
|
|
|
|
func TestReadMessagesAtOffset_EmptyBuffer(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
lb.bufferStartOffset = 0
|
|
lb.offset = 0 // Empty buffer
|
|
|
|
messages, nextOffset, hwm, endOfPartition, err := lb.ReadMessagesAtOffset(100, 10, 1024)
|
|
|
|
// Reading from future offset (100) when buffer is at 0
|
|
// Should return empty, no error
|
|
if err != nil {
|
|
t.Errorf("Expected no error for future offset, got %v", err)
|
|
}
|
|
if len(messages) != 0 {
|
|
t.Errorf("Expected 0 messages, got %d", len(messages))
|
|
}
|
|
if nextOffset != 100 {
|
|
t.Errorf("Expected nextOffset=100, got %d", nextOffset)
|
|
}
|
|
if !endOfPartition {
|
|
t.Error("Expected endOfPartition=true for future offset")
|
|
}
|
|
if hwm != 0 {
|
|
t.Errorf("Expected highWaterMark=0, got %d", hwm)
|
|
}
|
|
}
|
|
|
|
func TestReadMessagesAtOffset_SingleMessage(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Add a message
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key1"),
|
|
Data: []byte("value1"),
|
|
Offset: 0,
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
|
|
// Read from offset 0
|
|
messages, nextOffset, _, endOfPartition, err := lb.ReadMessagesAtOffset(0, 10, 1024)
|
|
|
|
if err != nil {
|
|
t.Errorf("Expected no error, got %v", err)
|
|
}
|
|
if len(messages) != 1 {
|
|
t.Errorf("Expected 1 message, got %d", len(messages))
|
|
}
|
|
if nextOffset != 1 {
|
|
t.Errorf("Expected nextOffset=1, got %d", nextOffset)
|
|
}
|
|
if !endOfPartition {
|
|
t.Error("Expected endOfPartition=true after reading all messages")
|
|
}
|
|
if messages[0].Offset != 0 {
|
|
t.Errorf("Expected message offset=0, got %d", messages[0].Offset)
|
|
}
|
|
if string(messages[0].Key) != "key1" {
|
|
t.Errorf("Expected key='key1', got '%s'", string(messages[0].Key))
|
|
}
|
|
}
|
|
|
|
func TestReadMessagesAtOffset_MultipleMessages(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Add 5 messages
|
|
for i := 0; i < 5; i++ {
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: []byte("value"),
|
|
Offset: int64(i),
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
}
|
|
|
|
// Read from offset 0, max 3 messages
|
|
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(0, 3, 10240)
|
|
|
|
if err != nil {
|
|
t.Errorf("Expected no error, got %v", err)
|
|
}
|
|
if len(messages) != 3 {
|
|
t.Errorf("Expected 3 messages, got %d", len(messages))
|
|
}
|
|
if nextOffset != 3 {
|
|
t.Errorf("Expected nextOffset=3, got %d", nextOffset)
|
|
}
|
|
|
|
// Verify offsets are sequential
|
|
for i, msg := range messages {
|
|
if msg.Offset != int64(i) {
|
|
t.Errorf("Message %d: expected offset=%d, got %d", i, i, msg.Offset)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReadMessagesAtOffset_StartFromMiddle(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Add 10 messages (0-9)
|
|
for i := 0; i < 10; i++ {
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: []byte("value"),
|
|
Offset: int64(i),
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
}
|
|
|
|
// Read from offset 5
|
|
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(5, 3, 10240)
|
|
|
|
if err != nil {
|
|
t.Errorf("Expected no error, got %v", err)
|
|
}
|
|
if len(messages) != 3 {
|
|
t.Errorf("Expected 3 messages, got %d", len(messages))
|
|
}
|
|
if nextOffset != 8 {
|
|
t.Errorf("Expected nextOffset=8, got %d", nextOffset)
|
|
}
|
|
|
|
// Verify we got messages 5, 6, 7
|
|
expectedOffsets := []int64{5, 6, 7}
|
|
for i, msg := range messages {
|
|
if msg.Offset != expectedOffsets[i] {
|
|
t.Errorf("Message %d: expected offset=%d, got %d", i, expectedOffsets[i], msg.Offset)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReadMessagesAtOffset_MaxBytesLimit(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Add messages with 100 bytes each
|
|
for i := 0; i < 10; i++ {
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: make([]byte, 100), // 100 bytes
|
|
Offset: int64(i),
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
}
|
|
|
|
// Request with max 250 bytes (should get ~2 messages)
|
|
messages, _, _, _, err := lb.ReadMessagesAtOffset(0, 100, 250)
|
|
|
|
if err != nil {
|
|
t.Errorf("Expected no error, got %v", err)
|
|
}
|
|
|
|
// Should get at least 1 message, but likely 2
|
|
if len(messages) == 0 {
|
|
t.Error("Expected at least 1 message")
|
|
}
|
|
if len(messages) > 3 {
|
|
t.Errorf("Expected max 3 messages with 250 byte limit, got %d", len(messages))
|
|
}
|
|
}
|
|
|
|
func TestReadMessagesAtOffset_ConcurrentReads(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Add 100 messages
|
|
for i := 0; i < 100; i++ {
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: []byte("value"),
|
|
Offset: int64(i),
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
}
|
|
|
|
// Start 10 concurrent readers at different offsets
|
|
done := make(chan bool, 10)
|
|
|
|
for reader := 0; reader < 10; reader++ {
|
|
startOffset := int64(reader * 10)
|
|
go func(offset int64) {
|
|
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(offset, 5, 10240)
|
|
|
|
if err != nil {
|
|
t.Errorf("Reader at offset %d: unexpected error: %v", offset, err)
|
|
}
|
|
if len(messages) != 5 {
|
|
t.Errorf("Reader at offset %d: expected 5 messages, got %d", offset, len(messages))
|
|
}
|
|
if nextOffset != offset+5 {
|
|
t.Errorf("Reader at offset %d: expected nextOffset=%d, got %d", offset, offset+5, nextOffset)
|
|
}
|
|
|
|
// Verify sequential offsets
|
|
for i, msg := range messages {
|
|
expectedOffset := offset + int64(i)
|
|
if msg.Offset != expectedOffset {
|
|
t.Errorf("Reader at offset %d: message %d has offset %d, expected %d",
|
|
offset, i, msg.Offset, expectedOffset)
|
|
}
|
|
}
|
|
|
|
done <- true
|
|
}(startOffset)
|
|
}
|
|
|
|
// Wait for all readers
|
|
for i := 0; i < 10; i++ {
|
|
<-done
|
|
}
|
|
}
|
|
|
|
func TestReadMessagesAtOffset_FutureOffset(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Add 5 messages (0-4)
|
|
for i := 0; i < 5; i++ {
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: []byte("value"),
|
|
Offset: int64(i),
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
}
|
|
|
|
// Try to read from offset 10 (future)
|
|
messages, nextOffset, _, endOfPartition, err := lb.ReadMessagesAtOffset(10, 10, 10240)
|
|
|
|
if err != nil {
|
|
t.Errorf("Expected no error for future offset, got %v", err)
|
|
}
|
|
if len(messages) != 0 {
|
|
t.Errorf("Expected 0 messages for future offset, got %d", len(messages))
|
|
}
|
|
if nextOffset != 10 {
|
|
t.Errorf("Expected nextOffset=10, got %d", nextOffset)
|
|
}
|
|
if !endOfPartition {
|
|
t.Error("Expected endOfPartition=true for future offset")
|
|
}
|
|
}
|
|
|
|
func TestWaitForDataWithTimeout_DataAvailable(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Add message at offset 0
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: []byte("value"),
|
|
Offset: 0,
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
|
|
// Wait for data at offset 0 (should return immediately)
|
|
dataAvailable := lb.WaitForDataWithTimeout(0, 100)
|
|
|
|
if !dataAvailable {
|
|
t.Error("Expected data to be available at offset 0")
|
|
}
|
|
}
|
|
|
|
func TestWaitForDataWithTimeout_NoData(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
lb.bufferStartOffset = 0
|
|
lb.offset = 0
|
|
|
|
// Don't add any messages, wait for offset 10
|
|
|
|
// Wait for data at offset 10 with short timeout
|
|
start := time.Now()
|
|
dataAvailable := lb.WaitForDataWithTimeout(10, 50)
|
|
elapsed := time.Since(start)
|
|
|
|
if dataAvailable {
|
|
t.Error("Expected no data to be available")
|
|
}
|
|
// Note: Actual wait time may be shorter if subscriber mechanism
|
|
// returns immediately. Just verify no data was returned.
|
|
t.Logf("Waited %v for timeout", elapsed)
|
|
}
|
|
|
|
func TestWaitForDataWithTimeout_DataArrives(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Start waiting in background
|
|
done := make(chan bool)
|
|
var dataAvailable bool
|
|
|
|
go func() {
|
|
dataAvailable = lb.WaitForDataWithTimeout(0, 500)
|
|
done <- true
|
|
}()
|
|
|
|
// Add data after 50ms
|
|
time.Sleep(50 * time.Millisecond)
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: []byte("value"),
|
|
Offset: 0,
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
|
|
// Wait for result
|
|
<-done
|
|
|
|
if !dataAvailable {
|
|
t.Error("Expected data to become available after being added")
|
|
}
|
|
}
|
|
|
|
func TestGetHighWaterMark(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
|
|
// Initially should be 0
|
|
hwm := lb.GetHighWaterMark()
|
|
if hwm != 0 {
|
|
t.Errorf("Expected initial HWM=0, got %d", hwm)
|
|
}
|
|
|
|
// Add messages (offsets 0-4)
|
|
for i := 0; i < 5; i++ {
|
|
entry := &filer_pb.LogEntry{
|
|
TsNs: time.Now().UnixNano(),
|
|
Key: []byte("key"),
|
|
Data: []byte("value"),
|
|
Offset: int64(i),
|
|
}
|
|
if err := lb.AddLogEntryToBuffer(entry); err != nil {
|
|
t.Fatalf("Failed to add log entry to buffer: %v", err)
|
|
}
|
|
}
|
|
|
|
// HWM should be 5 (next offset to write, not last written offset)
|
|
// This matches Kafka semantics where HWM = last offset + 1
|
|
hwm = lb.GetHighWaterMark()
|
|
if hwm != 5 {
|
|
t.Errorf("Expected HWM=5 after adding 5 messages (0-4), got %d", hwm)
|
|
}
|
|
}
|
|
|
|
func TestGetLogStartOffset(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
lb.bufferStartOffset = 10
|
|
lb.offset = 20
|
|
|
|
// offsets below the in-memory window are still on disk
|
|
if lso := lb.GetLogStartOffset(); lso != 0 {
|
|
t.Errorf("Expected LSO=0, got %d", lso)
|
|
}
|
|
|
|
lb.SetLogStartOffset(7)
|
|
lb.SetLogStartOffset(3)
|
|
if lso := lb.GetLogStartOffset(); lso != 7 {
|
|
t.Errorf("Expected LSO=7 after it was raised to 7, got %d", lso)
|
|
}
|
|
if _, _, _, _, err := lb.ReadMessagesAtOffset(6, 10, 1024); !errors.Is(err, ErrOffsetOutOfRange) {
|
|
t.Errorf("read below the log start: %v, want ErrOffsetOutOfRange", err)
|
|
}
|
|
}
|
|
|
|
// Once older files are purged, a disk chunk starts above its aligned start, so
|
|
// a read must find its offset by value rather than by position in the chunk.
|
|
func TestReadMessagesAtOffset_DiskChunkStartingAboveItsAlignedStart(t *testing.T) {
|
|
const earliest, end = 1500, 3000
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
lb.bufferStartOffset = end
|
|
lb.offset = end
|
|
lb.ReadFromDiskFn = func(start MessagePosition, stopTsNs int64, eachLogEntryFn EachLogEntryFuncType) (MessagePosition, bool, error) {
|
|
for offset := max(start.Offset, earliest); offset < end; offset++ {
|
|
if done, err := eachLogEntryFn(&filer_pb.LogEntry{Offset: offset, Data: []byte("v")}); done || err != nil {
|
|
return start, false, err
|
|
}
|
|
}
|
|
return start, false, nil
|
|
}
|
|
|
|
for _, startOffset := range []int64{1600, 1501, 2400} {
|
|
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(startOffset, 5, 1<<20)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(messages) != 5 || messages[0].Offset != startOffset || messages[4].Offset != startOffset+4 || nextOffset != startOffset+5 {
|
|
t.Fatalf("read at %d: %d messages from %v, next %d", startOffset, len(messages), messages, nextOffset)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Files whose names sort out of offset order hand a disk read its entries out of
|
|
// order; each read must still return the messages at the offsets it asked for.
|
|
func TestReadMessagesAtOffset_DiskEntriesOutOfOrder(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
lb.bufferStartOffset = 300
|
|
lb.offset = 300
|
|
order := append([]int64{256, 257}, make([]int64, 0, 256)...)
|
|
for offset := int64(0); offset < 256; offset++ {
|
|
order = append(order, offset)
|
|
}
|
|
for offset := int64(258); offset < 300; offset++ {
|
|
order = append(order, offset)
|
|
}
|
|
lb.ReadFromDiskFn = func(start MessagePosition, stopTsNs int64, eachLogEntryFn EachLogEntryFuncType) (MessagePosition, bool, error) {
|
|
for _, offset := range order {
|
|
if offset < start.Offset {
|
|
continue
|
|
}
|
|
if done, err := eachLogEntryFn(&filer_pb.LogEntry{Offset: offset, Data: []byte("v")}); done || err != nil {
|
|
return start, false, err
|
|
}
|
|
}
|
|
return start, false, nil
|
|
}
|
|
|
|
for _, startOffset := range []int64{0, 255, 256, 3} {
|
|
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(startOffset, 3, 1<<20)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(messages) != 3 || messages[0].Offset != startOffset || messages[2].Offset != startOffset+2 || nextOffset != startOffset+3 {
|
|
t.Fatalf("read at %d: %v, next %d", startOffset, messages, nextOffset)
|
|
}
|
|
}
|
|
}
|
|
|
|
// diskReadFrom serves offset-based disk reads from runs of offsets delivered in turn,
|
|
// as a reader that goes through the log files and then the parquet files does.
|
|
func diskReadFrom(runs ...[2]int64) LogReadFromDiskFuncType {
|
|
return func(start MessagePosition, stopTsNs int64, eachLogEntryFn EachLogEntryFuncType) (MessagePosition, bool, error) {
|
|
for _, run := range runs {
|
|
for offset := max(run[0], start.Offset); offset <= run[1]; offset++ {
|
|
if done, err := eachLogEntryFn(&filer_pb.LogEntry{Offset: offset, Data: []byte("v")}); done || err != nil {
|
|
return start, false, err
|
|
}
|
|
}
|
|
}
|
|
return start, false, nil
|
|
}
|
|
}
|
|
|
|
// A chunk cached while its later offsets were still in memory must not hide
|
|
// them once they are flushed and the memory has moved on.
|
|
func TestReadMessagesAtOffset_CachedChunkPrefix(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
lb.bufferStartOffset = 300
|
|
lb.offset = 300
|
|
lb.ReadFromDiskFn = diskReadFrom([2]int64{0, 99})
|
|
if messages, _, _, _, err := lb.ReadMessagesAtOffset(50, 5, 1<<20); err != nil || len(messages) != 5 {
|
|
t.Fatalf("read at 50: %d messages, %v", len(messages), err)
|
|
}
|
|
|
|
lb.ReadFromDiskFn = diskReadFrom([2]int64{0, 299})
|
|
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(150, 5, 1<<20)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(messages) != 5 || messages[0].Offset != 150 || nextOffset != 155 {
|
|
t.Fatalf("read at 150 past the cached prefix: %v, next %d", messages, nextOffset)
|
|
}
|
|
}
|
|
|
|
// Log files and a parquet file compacted from them both hold offsets 1000-1499;
|
|
// each offset is returned once.
|
|
func TestReadMessagesAtOffset_DiskOffsetsInLogsAndParquet(t *testing.T) {
|
|
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
|
lb.hasOffsets = true
|
|
lb.bufferStartOffset = 1500
|
|
lb.offset = 1500
|
|
lb.ReadFromDiskFn = diskReadFrom([2]int64{1000, 1499}, [2]int64{0, 1499})
|
|
|
|
for _, startOffset := range []int64{1100, 0} {
|
|
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(startOffset, 5, 1<<20)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for i, m := range messages {
|
|
if m.Offset != startOffset+int64(i) {
|
|
t.Fatalf("read at %d: message %d has offset %d", startOffset, i, m.Offset)
|
|
}
|
|
}
|
|
if len(messages) != 5 || nextOffset != startOffset+5 {
|
|
t.Fatalf("read at %d: %d messages, next %d", startOffset, len(messages), nextOffset)
|
|
}
|
|
}
|
|
}
|