From c84864ffcca23fd53974b36b04e5e920b44ed31b Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 21 Oct 2026 00:13:04 +0800 Subject: [PATCH] sessions: tests swap the time zone only after the background cache writer is done go test -race -count=3 ./internal/sessions/ failed in TestOpenCodeSubagents: testenv.Zone (via inZone) wrote time.Local while saveCache's goroutine, started by List() in an earlier iteration, read it in os.MkdirAll -> time.Unix (sessions.go:717 -> writeCache :761). inZone, the only place this package's tests change the zone, now drains the writer before the swap and again before it is put back. The same drain written by hand in TestHermesStatsIncludesRecentUsageForOldTranscript is dropped: inZone does it for every caller. Run: go test -race -run 'TestOpenCodeSubagents|TestHermes' -count=20 ./internal/sessions/ ok (184s); before, -count=3 failed with the race. --- internal/sessions/hermes_test.go | 9 --------- internal/sessions/stats_test.go | 17 ++++++++++++++++- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/internal/sessions/hermes_test.go b/internal/sessions/hermes_test.go index ce1dbff6a..01ed7dd7d 100644 --- a/internal/sessions/hermes_test.go +++ b/internal/sessions/hermes_test.go @@ -256,15 +256,6 @@ func TestHermesOlderSchemaAndNullFields(t *testing.T) { func TestHermesStatsIncludesRecentUsageForOldTranscript(t *testing.T) { setup(t) inZone(t, 0) - // The background cache writer reads time.Local; drain it before inZone - // restores the zone. Cleanups run LIFO, so this runs before inZone's. - t.Cleanup(func() { - saving.Lock() - for saving.running { - saving.Wait() - } - saving.Unlock() - }) root := filepath.Join(t.TempDir(), "hermes") t.Setenv("HERMES_HOME", root) path := hermesFixture(t, root, "", "old-transcript", true) diff --git a/internal/sessions/stats_test.go b/internal/sessions/stats_test.go index 69e3c6ec1..f1629a8a1 100644 --- a/internal/sessions/stats_test.go +++ b/internal/sessions/stats_test.go @@ -11,9 +11,24 @@ import ( "github.com/yetone/magpie/internal/testenv" ) -// inZone runs the test with the local time zone at a fixed offset. +// inZone runs the test with the local time zone at a fixed offset. The +// background cache writer (saveCache) reads time.Local, and one started by +// this or an earlier test's List can still be running, so it is drained +// before the zone is swapped and again before it is put back (cleanups run +// last-in first-out). func inZone(t *testing.T, hours int) { + savesDone() testenv.Zone(t, time.FixedZone("test", hours*3600)) + t.Cleanup(savesDone) +} + +// savesDone waits for the background cache writer to finish. +func savesDone() { + saving.Lock() + for saving.running { + saving.Wait() + } + saving.Unlock() } // ccMsg is a line of a Claude Code reply at a time.