mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-09-18 12:30:46 +02:00
* fix(ec): generate .ecx before EC shards to prevent data inconsistency In VolumeEcShardsGenerate, the .ecx index was generated from .idx AFTER the EC shards were generated from .dat. If any write occurred between these two steps (e.g. WriteNeedleBlob during replica sync, which bypasses the read-only check), the .ecx would contain entries pointing to data that doesn't exist in the EC shards, causing "shard too short" and "size mismatch" errors on subsequent reads and scrubs. Fix by generating .ecx FIRST, then snapshotting datFileSize, then encoding EC shards. If a write sneaks in after .ecx generation, the EC shards contain more data than .ecx references — which is harmless (the extra data is simply not indexed). Also snapshot datFileSize before EC encoding to ensure the .vif reflects the same .dat state that .ecx was generated from. Add TestEcConsistency_WritesBetweenEncodeAndEcx that reproduces the race condition by appending data between EC encoding and .ecx generation. * fix: pass actual offset to ReadBytes, improve test quality - Pass offset.ToActualOffset() to ReadBytes instead of 0 to preserve correct error metrics and error messages within ReadBytes - Handle Stat() error in assembleFromIntervalsAllowError - Rename TestEcConsistency_DatFileGrowsDuringEncoding to TestEcConsistency_ExactLargeRowEncoding (test verifies fixed-size encoding, not concurrent growth) - Update test comment to clarify it reproduces the old buggy sequence - Fix verification loop to advance by readSize for full data coverage * fix(ec): add dat/idx consistency check in worker EC encoding The erasure_coding worker copies .dat and .idx as separate network transfers. If a write lands on the source between these copies, the .idx may have entries pointing past the end of .dat, leading to EC volumes with .ecx entries that reference non-existent shard data. Add verifyDatIdxConsistency() that walks the .idx and verifies no entry's offset+size exceeds the .dat file size. This fails the EC task early with a clear error instead of silently producing corrupt EC volumes. * test(ec): add integration test verifying .ecx/.ecd consistency TestEcIndexConsistencyAfterEncode uploads multiple needles of varying sizes (14B to 256KB), EC-encodes the volume, mounts data shards, then reads every needle back via the EC read path and verifies payload correctness. This catches any inconsistency between .ecx index entries and EC shard data. * fix(test): account for needle overhead in test volume fixture WriteTestVolumeFiles created a .dat of exactly datSize bytes but the .idx entry claimed a needle of that same size. GetActualSize adds header + checksum + timestamp overhead, so the consistency check correctly rejects this as the needle extends past the .dat file. Fix by sizing the .dat to GetActualSize(datSize) so the .idx entry is consistent with the .dat contents. * fix(test): remove flaky shard ID assertion in EC scrub test When shard 0 is truncated on disk after mount, the volume server may detect corruption via parity mismatches (shards 10-13) rather than a direct read failure on shard 0, depending on OS caching/mmap behavior. Replace the brittle shard-0-specific check with a volume ID validation. * fix(test): close upload response bodies and tighten file count assertion Wrap UploadBytes calls with ReadAllAndClose to prevent connection/fd leaks during test execution. Also tighten TotalFiles check from >= 1 to == 1 since ecSetup uploads exactly one file.
225 lines
8.5 KiB
Go
225 lines
8.5 KiB
Go
package erasure_coding
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"fmt"
|
|
"os"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
|
)
|
|
|
|
// TestEcConsistency_WritesBetweenEncodeAndEcx reproduces a race condition that
|
|
// existed in VolumeEcShardsGenerate before the fix in this PR.
|
|
//
|
|
// Previously, the order was:
|
|
// 1. WriteEcFilesWithContext(baseFileName, ecCtx) — EC shards from .dat
|
|
// 2. WriteSortedFileFromIdx(v.IndexFileName(), ".ecx") — .ecx from .idx
|
|
//
|
|
// If a write appended data to .dat/.idx between steps 1 and 2, the .ecx would
|
|
// have entries pointing to data that doesn't exist in the EC shards.
|
|
//
|
|
// The fix reverses the order (write .ecx first, then generate EC shards), so
|
|
// that .ecx is always a subset of what the EC shards contain.
|
|
//
|
|
// This test simulates the old buggy sequence to validate that the problem is real.
|
|
func TestEcConsistency_WritesBetweenEncodeAndEcx(t *testing.T) {
|
|
dir := t.TempDir()
|
|
baseFileName := dir + "/consistency"
|
|
|
|
ctx := NewDefaultECContext("", 0)
|
|
|
|
// Phase 1: Create initial .dat and .idx with known data
|
|
datSize := int64(largeBlockSize*DataShardsCount + smallBlockSize*DataShardsCount*3) // 1 large row + 3 small rows
|
|
originalData := make([]byte, datSize)
|
|
rand.Read(originalData)
|
|
|
|
err := os.WriteFile(baseFileName+".dat", originalData, 0644)
|
|
require.NoError(t, err)
|
|
|
|
// Create a minimal .idx with one entry pointing to the data
|
|
createTestIdx(t, baseFileName+".idx", []idxEntry{
|
|
{id: 1, offset: 0, size: types.Size(datSize)},
|
|
})
|
|
|
|
// Phase 2: EC encode — generates .ec00-.ec13 from current .dat
|
|
err = generateEcFiles(baseFileName, int(smallBlockSize), largeBlockSize, smallBlockSize, ctx)
|
|
require.NoError(t, err, "EC encoding")
|
|
|
|
// Phase 3: SIMULATE a write between EC encoding and .ecx generation
|
|
// (reproducing the old buggy order where .ecx was generated after EC shards)
|
|
extraData := make([]byte, 5000)
|
|
rand.Read(extraData)
|
|
|
|
f, err := os.OpenFile(baseFileName+".dat", os.O_WRONLY|os.O_APPEND, 0644)
|
|
require.NoError(t, err)
|
|
_, err = f.Write(extraData)
|
|
require.NoError(t, err)
|
|
f.Close()
|
|
|
|
// Update .idx with the new entry
|
|
createTestIdx(t, baseFileName+".idx", []idxEntry{
|
|
{id: 1, offset: 0, size: types.Size(datSize)},
|
|
{id: 2, offset: datSize, size: types.Size(len(extraData))},
|
|
})
|
|
|
|
// Phase 4: Generate .ecx from the UPDATED .idx (as the old buggy code did)
|
|
err = WriteSortedFileFromIdx(baseFileName, ".ecx")
|
|
require.NoError(t, err, "WriteSortedFileFromIdx")
|
|
|
|
// Phase 5: Now try to read needle 2 via EC shards — it should fail
|
|
// because the EC shards were generated from the OLD .dat (without the extra data)
|
|
ecFiles, err := openEcFiles(baseFileName, true, ctx)
|
|
require.NoError(t, err)
|
|
defer closeEcFiles(ecFiles)
|
|
|
|
ecStat, err := ecFiles[0].Stat()
|
|
require.NoError(t, err)
|
|
shardSize := ecStat.Size()
|
|
|
|
// Read needle 2 (the one added after EC encoding) using LocateData.
|
|
// Use shardSize-1 to simulate the ecdFileSize fallback path used by
|
|
// LocateEcShardNeedleInterval when datFileSize is unavailable.
|
|
actualSize := needle.GetActualSize(types.Size(len(extraData)), needle.Version3)
|
|
intervals := LocateData(largeBlockSize, smallBlockSize, shardSize-1, datSize, types.Size(actualSize))
|
|
|
|
t.Logf("Trying to read needle 2 at offset %d size %d from EC shards (shardSize=%d)", datSize, actualSize, shardSize)
|
|
t.Logf("Intervals: %+v", intervals)
|
|
|
|
// Try to read — this will either fail with an error (offset out of bounds)
|
|
// or return garbage data (the padded zeros from EC encoding)
|
|
ecData, readErr := assembleFromIntervalsAllowError(ecFiles, intervals, largeBlockSize, smallBlockSize)
|
|
|
|
if readErr != nil {
|
|
t.Logf("CONFIRMED: Read error for needle written after EC encoding: %v", readErr)
|
|
} else {
|
|
// If we got data, it should be zeros (padding) or garbage, not the actual extraData
|
|
isAllZeros := true
|
|
for _, b := range ecData {
|
|
if b != 0 {
|
|
isAllZeros = false
|
|
break
|
|
}
|
|
}
|
|
if isAllZeros {
|
|
t.Logf("CONFIRMED: Read returned zero-padded data (EC shards don't have the needle)")
|
|
} else if !bytes.Equal(ecData[:len(extraData)], extraData) {
|
|
t.Logf("CONFIRMED: Read returned wrong data (EC shards don't have the needle)")
|
|
} else {
|
|
t.Error("UNEXPECTED: Read returned correct data — needle should NOT be in EC shards")
|
|
}
|
|
}
|
|
|
|
// Phase 6: Verify a small read from the original data still works.
|
|
// Use the correct shardDatSize (from the original datSize, not the modified one)
|
|
// to avoid the fallback heuristic issues.
|
|
shardDatSize := datSize / int64(DataShardsCount)
|
|
readSize := types.Size(smallBlockSize)
|
|
intervals1 := LocateData(largeBlockSize, smallBlockSize, shardDatSize, 0, readSize)
|
|
ecData1, err := assembleFromIntervalsAllowError(ecFiles, intervals1, largeBlockSize, smallBlockSize)
|
|
require.NoError(t, err, "reading original data from EC shards")
|
|
|
|
assert.True(t, bytes.Equal(originalData[:readSize], ecData1),
|
|
"Original data at offset 0 should match EC shard data")
|
|
t.Logf("Original data reads correctly from EC shards")
|
|
}
|
|
|
|
// TestEcConsistency_ExactLargeRowEncoding verifies that generateEcFiles correctly
|
|
// encodes a .dat file whose size is exactly one large row (DataShardsCount *
|
|
// largeBlockSize), producing shards of exactly largeBlockSize each, and that
|
|
// every chunk of the encoded data can be read back correctly via LocateData.
|
|
func TestEcConsistency_ExactLargeRowEncoding(t *testing.T) {
|
|
dir := t.TempDir()
|
|
baseFileName := dir + "/exact"
|
|
ctx := NewDefaultECContext("", 0)
|
|
|
|
datSize := int64(largeBlockSize * DataShardsCount) // exactly 1 large row
|
|
data := make([]byte, datSize)
|
|
rand.Read(data)
|
|
err := os.WriteFile(baseFileName+".dat", data, 0644)
|
|
require.NoError(t, err)
|
|
|
|
// EC encode
|
|
err = generateEcFiles(baseFileName, int(smallBlockSize), largeBlockSize, smallBlockSize, ctx)
|
|
require.NoError(t, err)
|
|
|
|
// Check shard sizes — each shard should be exactly largeBlockSize
|
|
ecFiles, err := openEcFiles(baseFileName, true, ctx)
|
|
require.NoError(t, err)
|
|
defer closeEcFiles(ecFiles)
|
|
|
|
for i := 0; i < ctx.DataShards; i++ {
|
|
stat, err := ecFiles[i].Stat()
|
|
require.NoError(t, err, "stat shard %d", i)
|
|
assert.Equal(t, int64(largeBlockSize), stat.Size(),
|
|
"data shard %d should be exactly largeBlockSize", i)
|
|
}
|
|
|
|
// Verify data reads correctly at every smallBlockSize offset via LocateData
|
|
shardDatSize := datSize / int64(ctx.DataShards)
|
|
readSize := types.Size(smallBlockSize)
|
|
for offset := int64(0); offset+int64(readSize) <= datSize; offset += int64(readSize) {
|
|
intervals := LocateData(largeBlockSize, smallBlockSize, shardDatSize, offset, readSize)
|
|
ecData, err := assembleFromIntervalsAllowError(ecFiles, intervals, largeBlockSize, smallBlockSize)
|
|
require.NoError(t, err, "reading at offset %d", offset)
|
|
expected := data[offset : offset+int64(readSize)]
|
|
assert.True(t, bytes.Equal(expected, ecData),
|
|
"data mismatch at offset %d", offset)
|
|
}
|
|
}
|
|
|
|
type idxEntry struct {
|
|
id types.NeedleId
|
|
offset int64
|
|
size types.Size
|
|
}
|
|
|
|
func createTestIdx(t *testing.T, filename string, entries []idxEntry) {
|
|
t.Helper()
|
|
f, err := os.Create(filename)
|
|
require.NoError(t, err)
|
|
defer f.Close()
|
|
|
|
buf := make([]byte, types.NeedleMapEntrySize)
|
|
for _, e := range entries {
|
|
types.NeedleIdToBytes(buf[:types.NeedleIdSize], e.id)
|
|
types.OffsetToBytes(buf[types.NeedleIdSize:types.NeedleIdSize+types.OffsetSize], types.ToOffset(e.offset))
|
|
types.SizeToBytes(buf[types.NeedleIdSize+types.OffsetSize:], e.size)
|
|
_, err := f.Write(buf)
|
|
require.NoError(t, err)
|
|
}
|
|
}
|
|
|
|
func assembleFromIntervalsAllowError(ecFiles []*os.File, intervals []Interval, large, small int64) ([]byte, error) {
|
|
var data []byte
|
|
for _, interval := range intervals {
|
|
shardId, shardOffset := interval.ToShardIdAndOffset(large, small)
|
|
if int(shardId) >= len(ecFiles) {
|
|
return nil, fmt.Errorf("shard %d out of range (have %d files)", shardId, len(ecFiles))
|
|
}
|
|
stat, err := ecFiles[shardId].Stat()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("stat shard %d: %v", shardId, err)
|
|
}
|
|
if shardOffset+int64(interval.Size) > stat.Size() {
|
|
return nil, fmt.Errorf("read past end of shard %d: offset %d + size %d > fileSize %d",
|
|
shardId, shardOffset, interval.Size, stat.Size())
|
|
}
|
|
chunk := make([]byte, interval.Size)
|
|
n, err := ecFiles[shardId].ReadAt(chunk, shardOffset)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read shard %d offset %d: %v", shardId, shardOffset, err)
|
|
}
|
|
if n != int(interval.Size) {
|
|
return nil, fmt.Errorf("short read shard %d: got %d want %d", shardId, n, interval.Size)
|
|
}
|
|
data = append(data, chunk...)
|
|
}
|
|
return data, nil
|
|
}
|