Skip to content

[Bug]: main and 4.2-dev duplicate same-key DiskCache file reads during cold-to-warm transitions #32491

Open

Description

@Ariznawlll

Description

4.2-dev 的 FileService 存在 cold-to-warm(冷转热)窗口中的同 key 文件读取放大:多个符合共享条件的请求在磁盘缓存尚未填入时跳过 fill 合并,随后等待同一个 PrefetchFile 完成,再各自读取相同的文件范围。

在已包含 #32361 的版本上,8 个同 key 并发请求稳定产生 8 次 DiskCache 文件读取;如果请求开始前磁盘缓存已经热,同样 8 个请求只产生 1 次读取。两种情况实际 LZ4 解压都只有 1 次。

这是残留的性能优化覆盖缺口,不是数据正确性错误,也不是声称 #32361 的已热缓存合并或解码共享完全失效。不声称此 PR 引入回归,不将 nightly 的全部 QPS 下降归因于本缺陷。

Environment

  • 已实测分支:4.2-dev。
  • 固定 MO commit:ba2a0caee86dd0f660776560a2a68943abb11df2(原失败 nightly 的 MO 版本)。
  • 已包含 fix(fileservice): coalesce same-key warm disk-cache column fills (#28918) to 4.2-dev #32361,merge commit:0351bc89d7478ccd908fbc7b084ff0dd71a0ee80。
  • 上述两个 commit 的 s3_fs.go、shared_decode.go、disk_cache.go、io_entry.go 无差异。
  • 本地 Go 1.26.5 darwin/arm64;使用现有 disk-backed ObjectStorage fixture,实际调用 S3FS、PrefetchFile、DiskCache 文件读取及 LZ4;未启动 MO SQL 服务或 TKE。
  • 8 readers,同一个 path/offset/size/codec;解压后 64 KiB,压缩后 280 bytes;MemCache 128 KiB,DiskCache 1 MiB。
  • 没有内存压力、admission rejection、共享配额耗尽或参数/超时修改。
  • 本报告仅对上述固定 4.2-dev commit 提供运行证明,未验证最新 main 或最新 4.2-dev HEAD。

Steps to reproduce

  1. 在上述 commit 的独立 checkout 中,将下方完整文件保存为 pkg/fileservice/cold_warm_32361_repro_test.go。它复用同包已有测试 fixture,不修改任何产品代码。
  2. 热缓存对照:先完成真实 PrefetchFile,再让 8 个同 key 请求加入 fill generation。
  3. 冷转热复现:阻塞真实 PrefetchFile 的 storage read;启动 8 个 Read;用每个请求的实际调用栈确认已经进入 DiskCache.waitUpdateCompleteFor,且磁盘文件尚不可用、fill registry 为空;再放行预取。
  4. 使用“最多读取一次”的验收断言运行:
env -u GOROOT MO_REPRO_REQUIRE_SINGLE_DISK_READ=1 go test -p 2 -vet=off ./pkg/fileservice \
  -run '^TestRepro32361ColdToWarm$' -count=3 -timeout=120s -v

当前版本退出码为 1:热缓存对照通过,冷转热子用例每次都报 expected: 1, actual: 8。

完整复现代码(只增加测试文件;保留真实读取及解压路径)
package fileservice

import (
	"bytes"
	"context"
	"io"
	"os"
	"runtime/debug"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/matrixorigin/matrixone/pkg/fileservice/fscache"
	"github.com/pierrec/lz4/v4"
	"github.com/stretchr/testify/require"
)

// Capture the actual first blocking site, rather than assuming that a Context
// Done call proves the reader has already passed warm-fill admission.
type repro32361WaitContext struct {
	context.Context
	once    sync.Once
	started chan struct{}
	stack   string
}

func (c *repro32361WaitContext) Done() <-chan struct{} {
	c.once.Do(func() {
		c.stack = string(debug.Stack())
		close(c.started)
	})
	return c.Context.Done()
}

// Investigation-only reproducer on ba2a0caee86d. No production hooks or changes.
// Disk.Hit counts successful DiskCache file reads (ReadFromOSFile/io.ReadFull),
// NOT physical device I/O: the OS page cache may satisfy these small reads.
// Default assertions characterize the residual duplication. Set
// MO_REPRO_REQUIRE_SINGLE_DISK_READ=1 to run the desired no-duplication oracle.
func TestRepro32361ColdToWarm(t *testing.T) {
	for _, cold := range []bool{false, true} {
		name := "warm_control"
		if cold {
			name = "cold_to_warm"
		}
		t.Run(name, func(t *testing.T) {
			const readers = 8
			ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
			defer cancel()
			fs, counters := newSharedDecodeDiskFillFS(t, CacheCallbacks{}, false)
			raw := bytes.Repeat([]byte("abcd"), 16<<10)
			compressed := make([]byte, lz4.CompressBlockBound(len(raw)))
			n, err := lz4.CompressBlock(raw, compressed, nil)
			require.NoError(t, err)
			require.Positive(t, n)
			compressed = compressed[:n]
			const path = "cold-warm-column"
			require.NoError(t, fs.Write(ctx, IOVector{FilePath: path, Policy: SkipAllCache,
				Entries: []IOEntry{{Size: int64(n), Data: compressed}}}))
			storage := &blockingReadObjectStorage{ObjectStorage: fs.storage,
				readStarted: make(chan struct{}), releaseRead: make(chan struct{})}
			fs.storage = storage
			releaseStorage := sync.OnceFunc(func() { close(storage.releaseRead) })
			decodeEntered, decodeContinue := make(chan struct{}), make(chan struct{})
			releaseDecode := sync.OnceFunc(func() { close(decodeContinue) })
			var entered sync.Once
			var converts atomic.Int32
			decode := func(ctx context.Context, _ io.Reader, data []byte, allocator CacheDataAllocator) (fscache.Data, error) {
				converts.Add(1)
				entered.Do(func() { close(decodeEntered) })
				select {
				case <-decodeContinue:
				case <-ctx.Done():
					return nil, ctx.Err()
				}
				out := allocator.AllocateCacheData(ctx, len(raw))
				size, err := lz4.UncompressBlock(data, out.Bytes())
				if err != nil || size != len(raw) {
					out.Release()
					return nil, io.ErrUnexpectedEOF
				}
				return out, nil
			}
			vectors := make([]IOVector, readers)
			var workers sync.WaitGroup
			t.Cleanup(func() {
				releaseStorage()
				releaseDecode()
				cancel()
				workers.Wait()
				for i := range vectors {
					vectors[i].ReleaseReadResultOnError()
				}
			})
			await := func(ch <-chan struct{}, description string) {
				t.Helper()
				select {
				case <-ch:
				case <-ctx.Done():
					t.Fatalf("timed out waiting for %s", description)
				}
			}
			prefetchDone := make(chan error, 1)
			workers.Add(1)
			go func() {
				defer workers.Done()
				prefetchDone <- fs.PrefetchFile(ctx, path)
			}()
			await(storage.readStarted, "real PrefetchFile storage read")
			if !cold {
				releaseStorage()
				require.NoError(t, <-prefetchDone)
				require.True(t, fs.diskCache.cache.Contains(fs.diskCache.pathForFile(path)))
			}
			beforeHits := counters.FileService.Cache.Disk.Hit.Load()
			beforeReads := counters.FileService.Cache.Disk.Read.Load()
			done := make(chan error, readers)
			waiting := make([]*repro32361WaitContext, readers)
			for i := range vectors {
				vectors[i] = IOVector{FilePath: path, Entries: []IOEntry{{
					Size: int64(n), CachedDataSize: int64(len(raw)), ToCacheData: decode,
					DecodeSharing: DecodeSharing{Codec: "repro-lz4-v1"},
				}}}
				waiting[i] = &repro32361WaitContext{Context: ctx, started: make(chan struct{})}
				workers.Add(1)
				go func(i int) {
					defer workers.Done()
					done <- fs.Read(waiting[i], &vectors[i])
				}(i)
			}
			if cold {
				// Prefetch owns the full-file update. Read reaches the existing
				// DiskCache wait only AFTER its one-time warm-fill admission.
				// No production code, quota or timer is modified to force this.
				for _, waiting := range waiting {
					await(waiting.started, "cold reader waiting for the disk-cache update")
					require.Contains(t, waiting.stack, "(*DiskCache).waitUpdateCompleteFor", "verify the exact controlled interleaving")
				}
				require.False(t, fs.diskCache.cache.Contains(fs.diskCache.pathForFile(path)))
				fs.decodedReads.mu.Lock()
				fills := len(fs.decodedReads.fills)
				fs.decodedReads.mu.Unlock()
				require.Zero(t, fills, "all requests skipped cold-path fill admission")
				releaseDecode()
				releaseStorage()
				require.NoError(t, <-prefetchDone)
			} else {
				await(decodeEntered, "warm disk-fill leader")
				waitForSharedDecodeFillParticipants(t, fs.decodedReads, readers)
				releaseDecode()
			}
			for range readers {
				require.NoError(t, <-done)
			}
			workers.Wait()
			hits := counters.FileService.Cache.Disk.Hit.Load() - beforeHits
			reads := counters.FileService.Cache.Disk.Read.Load() - beforeReads
			t.Logf("readers=%d compressed_bytes=%d decoded_bytes=%d disk_hits=%d disk_attempts=%d disk_file_bytes=%d storage_reads=%d actual_lz4_decodes=%d", readers, n, len(raw), hits, reads, hits*int64(n), storage.readCount.Load(), converts.Load())
			require.Equal(t, int64(1), storage.readCount.Load(), "only the single real prefetch may access storage")
			require.Equal(t, int32(1), converts.Load(), "conversion sharing still works")
			for i := range vectors {
				require.Equal(t, raw, vectors[i].Entries[0].CachedData.Bytes())
				vectors[i].ReleaseReadResultOnError()
			}
			requireDecodeDrained(t, fs.decodedReads)
			// A subsequent request is a genuine memory hit: zero extra disk I/O
			// or decode, without flushing, rejection or memory pressure.
			later := IOVector{FilePath: path, Entries: []IOEntry{{Size: int64(n), CachedDataSize: int64(len(raw)), ToCacheData: decode, DecodeSharing: DecodeSharing{Codec: "repro-lz4-v1"}}}}
			require.NoError(t, fs.Read(ctx, &later))
			require.Equal(t, raw, later.Entries[0].CachedData.Bytes())
			later.ReleaseReadResultOnError()
			require.Equal(t, beforeHits+hits, counters.FileService.Cache.Disk.Hit.Load())
			require.Equal(t, int32(1), converts.Load())
			requireDecodeDrained(t, fs.decodedReads)
			want := int64(1)
			if cold && os.Getenv("MO_REPRO_REQUIRE_SINGLE_DISK_READ") != "1" {
				want = readers // observed residual bug, not a successful fix
			}
			require.Equal(t, want, hits, "same-key disk-file reads")
		})
	}
}

Actual behavior

相同的 8-reader 请求 DiskCache 成功文件读取 逻辑文件读取字节 实际 LZ4 解压 ObjectStorage 读取
请求开始前已热 1 280 1 1(预取)
请求等待期间由冷转热 8 2240 1 1(预取)

DiskCache 的成功 hit 在 ReadFromOSFile 成功后计数,因此这里不是把缓存尝试次数误认为真实文件读取。8 次逻辑文件读取不代表 8 次物理设备读取,OS page cache 可能满足这些小读取。

Expected behavior

对同一不可变范围的符合条件并发请求,在等待缓存填入后仍应有机会复用一个有界的 fill/publication,避免仅因首次判断时缓存尚冷而让每个 waiter 独立读取相同内容。

修复不能无界缓存或全局串行化;应保留 cold/different-key 请求、取消、超时、失败回退、关闭及引用所有权语义。

Stability and controls

  • 普通模式:20/20 次冷转热均为 8 次读取,热对照均为 1 次。
  • -race 模式:20/20 次结果一致,无 race 报告。
  • 严格单读断言:冷转热 3/3 失败,热对照 3/3 通过。
  • 每次均检查全部返回字节、释放 IOVector,并检查 decoded registry 的 entries/fills/count/bytes/fillCount 清空。
  • 随后的同 key MemCache 命中不再增加文件读取或解压。
  • 原有 DiskFill、SkipsColdPaths、FailureIsolation、DiskCanceledDoesNotFallback、FallbackDoesNotRejoin 五组相邻测试在 -race -count=3 下通过。
  • 临时文件由测试 TempDir 清理、FileService 关闭;未触发整套回归或 TKE。
  • 默认观察模式断言的是“复现 8 次读取”,所以它的 PASS 不代表产品缺陷已修复;严格验收请设置上面的环境变量。

Evidence

最终测试代码 SHA256:29ce4ef37ccb9527da6f3dafdf69c2f9d06606b2bd8cf3b268d9cb0570eb9922。

最终运行的关键原始输出(没有将推测写成测量):

warm_control:
readers=8 compressed_bytes=280 decoded_bytes=65536 disk_hits=1 disk_attempts=1 disk_file_bytes=280 storage_reads=1 actual_lz4_decodes=1

cold_to_warm:
readers=8 compressed_bytes=280 decoded_bytes=65536 disk_hits=8 disk_attempts=8 disk_file_bytes=2240 storage_reads=1 actual_lz4_decodes=1

MO_REPRO_REQUIRE_SINGLE_DISK_READ=1:
expected: 1
actual  : 8
Test: TestRepro32361ColdToWarm/cold_to_warm
Messages: same-key disk-file reads
--- PASS: TestRepro32361ColdToWarm/warm_control
--- FAIL: TestRepro32361ColdToWarm/cold_to_warm

复核普通及 race 的机制重复性:

env -u GOROOT go test -p 2 -vet=off ./pkg/fileservice -run '^TestRepro32361ColdToWarm$' -count=20 -timeout=120s -v
env -u GOROOT go test -race -p 2 -vet=off ./pkg/fileservice -run '^TestRepro32361ColdToWarm$' -count=20 -timeout=180s -v

Code analysis

已通过受控并发及调用栈确认的路径:

  1. shared_decode.go:562:只有当时 DiskCache 已有内容,才取得 fill ticket。
  2. s3_fs.go:740:decodePrepared 限定准备只做一次;冷请求没有 ticket 后进入 DiskCache。
  3. disk_cache.go:346:等待 full-file 更新;预取完成后没有重新进行同 key fill 协调,各自执行 ReadFromOSFile。
  4. io_entry.go:64:io.ReadFull 先于 setCachedData/ToCacheData。后续解码共享成功,无法撤销此前已发生的重复读取。

限制:此小复现不测物理设备吞吐、CPU 限流、merge 时序或 nightly QPS,也没有证明原 nightly 中的每个重复读取都经过这一个等待窗口。

Regression coverage

应在 FileService Go UT 中覆盖“初次检查冷、等待过程中变热”的单次 fill;保留已热对照和后续内存命中,验证读取计数、实际解码计数、数据及引用释放;增加取消/关闭/预取失败和不同 key 的相邻控制。无需把内部调度窗口硬塞进 SQL BVT 或跑整套 nightly。

Related

Activity

  1. added this to the MO-202611 milestone on Nov 10, 2026
  2. added theissue type on Nov 10, 2026
  3. changed the title [-][Bug]: 4.2-dev cold-to-warm DiskCache transition duplicates same-key file reads after #32361[/-] [+][Bug]: main and 4.2-dev duplicate same-key DiskCache file reads during cold-to-warm transitions[/+] on Nov 10, 2026
  4. MatrixAdventurer commented on Nov 11, 2026

    @MatrixAdventurer
    Contributor

    分级建议(仅评论,不改标签/不指派):建议严重级 s2——冷→热读放大约 8 倍,纯性能问题,无正确性影响。模块:pkg/fileservice(DiskCache 冷热读取路径,waitUpdateCompleteFor 相关)。疑似重复:与 #32361 为同一修复方向的生产暴露面,正文已区分(非全量预取语义复测);未发现同款读放大问题。建议负责人:本次未能核实(CODEOWNERS 读取失败、该目录近期提交者未获取到),建议交由 pkg/fileservice 维护者确认分派。

    本操作由LW授权的MOI智能体提交

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions