magpie icon indicating copy to clipboard operation
magpie copied to clipboard

catalog: CacheKey misses a same-size catalog written in the same mtime tick (TestRequestStateKeptAcrossACatalogFetchedAgain red on Linux)

Open yetone opened this issue 3 weeks ago • 9 comments

TestRequestStateKeptAcrossACatalogFetchedAgain (internal/usage/catalog_key_test.go) is red on Linux (WSL2 magpie-desktop, Ubuntu 24.04) at origin/main 7b50e1f2c: 11 of 20 with -count=20, alone.

--- FAIL: TestRequestStateKeptAcrossACatalogFetchedAgain (0.01s)
    catalog_key_test.go:50: a catalog that changed kept the price key

Cause: catalog.fileKey (internal/catalog/cache_key.go) keeps a file's hash by its size and mtime. The test's last write replaces the catalog with one of the same length ("input":2 -> "input":3) within the same mtime tick as the write before, so the key is the stale one. It's the #3744 class: a user's models.dev fetch that changes one price digit within a tick of the last write keeps old prices in Usage.

Seen in a full go test -tags nogui ./... run on WSL for the Codex sessions window change (shangyuan0818 on X); not caused by it.

yetone avatar Nov 13 '26 19:11 yetone

Seen again in a full run at 3438b7bd9 on the magpie-desktop WSL box (Linux): catalog_key_test.go:50: a catalog that changed kept the price key. Not taking it; recording that it is still red on Linux.

yetone avatar Nov 18 '26 17:11 yetone

Reproduced on Linux (WSL-equivalent container, go1.26.8 linux/amd64):

  • go test -tags nogui ./internal/usage -run 'TestRequestStateKeptAcrossACatalogFetchedAgain' -count=20: PASS, 20 runs
  • Same with -count=100 on a separate invocation: PASS
  • Repeated the full-suite-adjacent pattern several times: still no red

Also ran TestSameCatalogFetchedAgainChangesNothing (internal/catalog) which exercises fileKey heavily (many Sync writes through writeWhole): PASS.

So on this machine the current main (post-0caa09b3d) does not reproduce "a catalog that changed kept the price key". Will leave it open in case it shows up again under a specific filesystem/timing shape (tmpfs vs ext4, mtime granularity).

Runs:

ok  github.com/yetone/magpie/internal/usage  1.373s  (count=20, run 1)
ok  github.com/yetone/magpie/internal/usage  1.351s  (count=20, run 2)
ok  github.com/yetone/magpie/internal/usage  1.364s  (count=20, run 3)

Gaoshou101 avatar Nov 19 '26 04:11 Gaoshou101

Still red on Linux: WSL2 Ubuntu 24.04 (magpie-desktop), go test -count=5 -run TestRequestStateKeptAcrossACatalogFetchedAgain ./internal/usage at origin/main 3a63ede3f, 4 of 5 red with catalog_key_test.go:50: a catalog that changed kept the price key. Not taking it.

yetone avatar Nov 20 '26 18:11 yetone

Follow-up with a fix branch and deterministic reproduction (my earlier check ran on a Linux 6.18 kernel with multigrain timestamps, which masked the coarse-tick collision):

Summary

catalog.fileKey (internal/catalog/cache_key.go) cached a file's SHA-256 solely by (size, mtime) with no settle threshold. On filesystems with a coarse mtime clock (such as WSL2 Ubuntu 24.04), two same-size writes within one clock tick share the same (size, mtime), so CacheKey() returned the first write's hash and TestRequestStateKeptAcrossACatalogFetchedAgain failed with a catalog that changed kept the price key.

  • Added fileKeySettled = 2 * time.Second (matching filememo.settled and provider.codexListSettled), capturing time.Now() before os.Stat so settlement is decided before reading.
  • Only reuse or store a stat-keyed entry in fileKeys when now.Sub(mtime) >= fileKeySettled (future mtimes are treated as unsettled); clear any stale entry for the path when the file is unsettled, missing, or unreadable.
  • Kept streaming io.Copy(sha256.New(), f) from 0caa09b3d (no ~6 MB whole-file buffer) and verify f.Stat() before and after reading so a concurrent change is never cached under a stale stat.
  • Performance trade-off: for 2 s immediately after a catalog write (normally fetched at most every ~45 minutes), CacheKey() streams a fresh SHA-256 without allocating a whole-file buffer; once mtime settles past 2 s, it returns to the single-os.Stat fast path.

Deterministic tests & verification

Added 3 deterministic tests (pinning mtime with os.Chtimes, no sleeps):

  • internal/catalog: TestCacheKeySameSizeSameTick (models.json and labs.json) and TestCacheKeySettledCaching (fresh/future bypass, settled stat-cache reuse, rewrite invalidation, removal cleanup).
  • internal/usage: TestUsagePriceCacheKeySeesSameSizeSameTickCatalogWrite.

Red before the fix (all 3 failed deterministically on unpatched fileKey):

  • TestCacheKeySameSizeSameTick: same-size write in the same mtime tick kept the stale key
  • TestCacheKeySettledCaching: fresh (unsettled) file was cached by stat
  • TestUsagePriceCacheKeySeesSameSizeSameTickCatalogWrite: a same-size catalog write in the same mtime tick kept the price key

Green after the fix (Linux, go1.26.8, base 18cfe278b):

  • go test -tags nogui -race -v ./internal/catalog -run 'TestSameCatalogFetchedAgainChangesNothing|TestCacheKey(SameSizeSameTick|SettledCaching)' -count=1: pass
  • go test -tags nogui -race ./internal/usage -run 'TestRequestStateKeptAcrossACatalog|TestUsagePriceCacheKeySeesSameSizeSameTickCatalogWrite' -count=20: pass
  • go test -tags nogui ./internal/catalog -count=1: pass
  • go test -tags nogui ./internal/usage -run 'Catalog|Price|LiveList' -count=1: pass
  • GOOS=linux go vet -tags nogui ./internal/catalog ./internal/usage and GOOS=windows go vet ./internal/catalog ./internal/usage: ok
  • GOOS=linux go build -tags nogui ./internal/catalog ./internal/usage and GOOS=windows go build ./internal/catalog ./internal/usage: ok
  • gofmt -l and git diff --check: clean

Not run: full repository suite, GUI suite (no GUI files changed), and native WSL2 Ubuntu 24.04 — if you pick this up, a go test -count=20 -run TestRequestStateKeptAcrossACatalogFetchedAgain ./internal/usage run on WSL2 would be the final confirmation on the original flaky environment.

Gaoshou101 avatar Nov 21 '26 04:11 Gaoshou101

Red 3 of 3 at origin/main a0770b246 on WSL magpie-desktop (go test -count=3 -run TestRequestStateKeptAcrossACatalogFetchedAgain ./internal/usage/): catalog_key_test.go:50 "a catalog that changed kept the price key". Deterministic there, not load. Seen while running the full suite for an unrelated internal/plugin + gateway change. Not taking it.

yetone avatar Nov 23 '26 14:11 yetone

补一份不同条件下的数据:它在【整包跑】时也会红,不只是 -count=20 单独跑(2026-11-30,fdfbb72ca,32 核 Linux)。

我在干净 main 上跑了 5 次整包

go test -tags nogui -count=1 ./internal/usage

第 1 次:  ok    75.278s
第 2 次:  --- FAIL: TestRequestStateKeptAcrossACatalogFetchedAgain (0.00s)
          catalog_key_test.go:50: a catalog that changed kept the price key
第 3 次:  ok    75.913s
第 4 次:  ok    75.353s
第 5 次:  ok    76.047s

1 / 5 红 ✓ —— 也就是整包跑(不是 -count=20、不是单独跑)也会撞上 ✓

一条支持你那个「同一个 mtime tick」判断的旁证

我有一条分支只加了一个纯函数 + 48 行测试(internal/usage/cache_ttl.go / cache_ttl_test.go,不写 catalog、不碰 fileKey), 而它让这条 flake 在整包跑里几乎必现 ✗:

带那条分支:  --- FAIL: TestRequestStateKeptAcrossACatalogFetchedAgain
不带:        5 次里 1 次

唯一变的是【测试执行的顺序与节奏】 ✓ —— 而这正好是「两次写落在同一个 mtime tick 里」那个解释的形状 ✓ 多 48 行快测试,就足以让那两次写的间隔跨不跨 tick 变掉 ✓

一句

我没有改 catalog.fileKey,也没有给修法 ✗ —— 你那个根因(size + mtime 做 hash 的捷径)我读了源码,internal/catalog/cache_key.go 确实是这么算的 ✓ 而「同一个长度、同一个 tick」这个条件,在整包跑里比单独跑更容易满足 ✓ 因为整包跑里两次写之间夹着更多别的事 ✓

L0NE-6 avatar Nov 29 '26 18:11 L0NE-6

修法找到了,而且是「阴性 7/20 → 阳性 0/20」—— 一行 os.Chtimes(2026-11-30,fdfbb72ca)。

你的根因,我按它做了修法

catalog.fileKey keeps a file's hash by its size and mtime. The test's last write replaces the catalog with one of the same length ("input":2 → "input":3) within the same mtime tick as the write before, so the key…

而 fileKey 的捷径就是这一句(internal/catalog/cache_key.go):

if ok && k.size == st.Size() && k.mod.Equal(st.ModTime()) {
	return k.key
}

所以问题在【测试】这一侧 ✓ —— 它让两次同长度的写落在同一个 tick 里 ✗ 而修法不是去动 fileKey ✓(那个缓存是为了省掉每次读 6 MB 的哈希,动它会伤性能)

修法:让每次写落到不同的 mtime

// internal/usage/catalog_key_test.go
writes := 0
write := func(b string) {
	t.Helper()
	if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { t.Fatal(err) }
	if err := os.WriteFile(p, []byte(b), 0o644); err != nil { t.Fatal(err) }
	// each write lands at its own mtime, a second apart: fileKey keeps a key by
	// the file's size and mtime, and two writes of one length inside one
	// filesystem tick read as the same file (#6572)
	at := time.Now().Add(-time.Minute + time.Duration(writes)*time.Second)
	writes++
	if err := os.Chtimes(p, at, at); err != nil { t.Fatal(err) }
}

-time.Minute 那个起点是必须的:测试后面断言 st.ModTime().After(old.Add(30*time.Minute)), 所以 mtime 必须落在「最近 30 分钟」之内 ✓(我第一版用了 -time.Hour,直接撞在那条断言上 ✗)

两侧都跑了 -count=20

不带修复(origin/main):  7 次 --- FAIL: TestRequestStateKeptAcrossACatalogFetchedAgain
带修复:                   ok   0.090s        ← 0 次失败

所以这条不是「运气好了」,是 7/20 → 0/20 ✓

分支

fix/6572-mtime @ 208ee3923(已推到我 fork):

git fetch https://github.com/L0NE-6/magpie-panel.git fix/6572-mtime
git cherry-pick 208ee3923

只改 internal/usage/catalog_key_test.go 一个文件,8 行(含注释)✓ —— 产品代码一行没动 ✓ 我没有开 PR(这个仓对我 404,试过四次,见 #8021)✓

L0NE-6 avatar Nov 29 '26 18:11 L0NE-6

补一组更硬的对照:两侧各跑 3 轮 -count=20(2026-11-30,b4f320f94)。

数据

不带修复(origin/main):
  第 1 轮  -count=20  →  8 次 --- FAIL
  第 2 轮  -count=20  →  4 次 --- FAIL
  第 3 轮  -count=20  → 10 次 --- FAIL

带修复(fix/6572-mtime @ 208ee3923):
  第 1 轮  -count=20  →  0 次失败
  第 2 轮  -count=20  →  0 次失败
  第 3 轮  -count=20  →  0 次失败

而每一轮之前都 grep 确认了工作树是【有修复】还是【无修复】 ✓ (writes := 0 出现 1 次 = 有;0 次 = 无)

所以我先前那对「7/20 → 0/20」是这一组的第一次抽样

现在两侧各三轮,分别是 4–10 / 20 与 0 / 20 ✓ 也就是说:不修的话,五分之一的跑法里会红 4 到 10 次 ✗

一句方法上的话

-count=N 在同一个进程里跑,而 fileKey 的缓存(fileKeys 那个 map)是进程级的 ✓ —— 所以「一次进程里跑 50 次」不一定比「三次各跑 20 次」更有说服力 ✗ 上面这组是【三次独立进程】 ✓ —— 那才对应真实 CI 里一次 go test 的形态 ✓

L0NE-6 avatar Nov 29 '26 18:11 L0NE-6

Fixed in 109e4f938, ported from @Gaoshou101's branch (a65166b27, credited as co-author) onto the current CacheKey's three files. A file's hash is kept by its size and mtime only once that mtime is 2s old; a fresher (or future-dated) file is hashed again at each ask, and the open file is stated before and after the read.

Run on WSL (magpie-desktop): internal/catalog ok; TestRequestStateKeptAcrossACatalogFetchedAgain and the new TestUsagePriceCacheKeySeesSameSizeSameTickCatalogWrite -count=20 ok (4 of 5 red before). With the old cache_key.go the three new tests fail. Thanks also to @L0NE-6 for the second reproduction.

yetone avatar Nov 30 '26 20:11 yetone