Commit c0b4847a4e for golang

commit c0b4847a4e14b5d2172619758ec5c29d5d633659
Author: thepudds <thepudds1460@gmail.com>
Date:   Mon Nov 30 03:07:51 2026 +0000

    cmd/go/internal/cache: simplify trim base tracking and small cleanups

    This CL does some small follow up cleanups to cache trimming and
    the cache.log under GOEXPERIMENT=trimbuildcache.

    First, we simplify how the baseline is recorded, removing some
    logic that was effectively a holdover from an earlier version,
    while still having essentially the same effect in steady state.
    (The base is still recorded as all retained bytes for size-triggered
    trims or low disk space trims. The 24h trim does the same, except
    it never raises the base once there is a measurement, which was
    previously done less directly.)

    Second, the estimated size in size.txt is updated even when
    there is not yet an estimate, which helps when transitioning
    from an older go version (in particular, when the older go version
    might keep repeatedly winning on running the 24h trim).

    Together, this lets us remove the hasEstimated bool from the
    cache size state.

    While here, we do some minor polishing of the cache.log lines
    (e.g., adding the go version and an explicit tenured byte count)
    and also improve a couple of the tests (e.g., checking for negative
    values).

    Updates #29561
    Updates #81830

    Change-Id: Ic7ebe9ec9b0117d171b39345b9ae2d24c236521b
    Reviewed-on: https://go-review.googlesource.com/c/go/+/868084
    Reviewed-by: Michael Matloob <matloob@golang.org>
    Reviewed-by: Michael Matloob <matloob@google.com>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
    Reviewed-by: PJ Malloy <pjmalloy@google.com>

diff --git a/src/cmd/go/internal/cache/cache.go b/src/cmd/go/internal/cache/cache.go
index 58ead742a2..215de29461 100644
--- a/src/cmd/go/internal/cache/cache.go
+++ b/src/cmd/go/internal/cache/cache.go
@@ -432,11 +432,13 @@ const (
 // to size.txt and keeps the remainder. The expected increment is B, while a command adding
 // no bytes never touches size.txt and one adding 1 MiB updates it only once in 64 runs.
 //
-// Each trim scan replaces the estimate with the measured size of the entries it kept,
-// plus any bytes other go commands added during the scan, and records as the baseline
-// ("base") the kept bytes a size triggered trim could not delete at that moment
-// (tenured30m files, young generation files under 90 minutes old, and undeletable files).
-// A new or cleaned cache has base 0, so its first size triggered trim runs when the
+// Each trim scan replaces the recorded estimate with the measured size of the entries it kept,
+// and updates the baseline ("base") to kept bytes. The exception is a daily trim never raises
+// a non-zero base because it does not delete young generation files early, and raising
+// the base after a daily trim would essentially lock in daily cache growth that was
+// not already trimmed.
+//
+// When base is 0 (due to a new or cleaned cache), a size triggered trim runs when the
 // estimate reaches defaultMinTarget (5 GiB).
 //
 // Completed trim scans and 'go clean -cache' also append a line to cache.log (see log.go).
@@ -564,9 +566,8 @@ func writeTrimTimestamp(trimFile *lockedfile.File, t int64) ([]byte, error) {

 // cacheSizeState holds the parsed contents of size.txt ("key value\n" lines).
 type cacheSizeState struct {
-	estimated    int64 // estimated logical size of cache entries, in bytes
-	base         int64 // baseline size from the last trim scan (0 if none)
-	hasEstimated bool  // size.txt held a valid estimate
+	estimated int64 // estimated logical size of cache entries, in bytes
+	base      int64 // baseline for targetSize, see above (0 if none)
 }

 // readSize reads dir/size.txt. Callers that modify size.txt must hold the trim.txt lock.
@@ -584,7 +585,7 @@ func readSize(dir string) (st cacheSizeState, exists, ok bool) {
 		return cacheSizeState{}, true, false
 	}
 	rest := string(data)
-	var hasBase bool
+	var hasEstimated, hasBase bool
 	for {
 		line, after, found := strings.Cut(rest, "\n")
 		if !found {
@@ -603,8 +604,8 @@ func readSize(dir string) (st cacheSizeState, exists, ok bool) {
 				continue
 			}
 			n = min(n, maxSizeBound)
-			if key == "estimated" && !st.hasEstimated {
-				st.estimated, st.hasEstimated = n, true
+			if key == "estimated" && !hasEstimated {
+				st.estimated, hasEstimated = n, true
 			} else if key == "base" && !hasBase {
 				st.base, hasBase = n, true
 			}
@@ -630,12 +631,12 @@ func writeSizeLocked(dir string, st cacheSizeState) {
 	_ = f.Close()
 }

-// addSizeLocked adds delta to an existing estimate in size.txt while holding the
+// addSizeLocked adds delta to the estimate in size.txt while holding the
 // trim.txt lock, returning the updated state. If size.txt has no valid estimate,
-// it does nothing (the next trim scan records one). If unreadable, it returns ok=false.
+// it starts from 0. If unreadable, it returns ok=false.
 func (c *DiskCache) addSizeLocked(delta int64) (st cacheSizeState, ok bool) {
 	st, _, ok = readSize(c.dir)
-	if ok && st.hasEstimated && delta > 0 {
+	if ok && delta > 0 {
 		st.estimated = min(st.estimated+delta, maxSizeBound)
 		writeSizeLocked(c.dir, st)
 	}
@@ -836,7 +837,7 @@ func (c *DiskCache) trim(youngGenAsOf time.Time) error {
 		case added > 0:
 			// This command grew the cache: update size.txt and check the size trigger.
 			st, ok = c.addSizeLocked(added)
-			sizeTrim = ok && st.hasEstimated && st.estimated >= c.targetSize(st.base) &&
+			sizeTrim = ok && st.estimated >= c.targetSize(st.base) &&
 				trimDue(data, now, minTrimSpacing)
 			if !sizeTrim && !lowDisk && !trimDue(data, now, trimInterval) {
 				return
@@ -865,17 +866,26 @@ func (c *DiskCache) trim(youngGenAsOf time.Time) error {
 	// We subtract an additional mtimeInterval
 	// to account for the imprecision of our "last used" mtimes.
 	cutoff := now.Add(-trimLimit - mtimeInterval)
-	classify := func(mt time.Time) (remove, inBase bool) {
+	remove := func(mt time.Time) bool {
+		// Measure delete age from the file's mtime (last recorded use time) to when
+		// the cache was opened. This prevents a very long go command from deleting
+		// files it wrote or used itself during the run, including across forward wall clock jumps.
+		pastDeleteAge := youngGenAsOf.Sub(mt) >= youngGenDeleteAge
 		switch {
 		case mt.Before(cutoff):
-			return true, false // unused for 5 days, either generation
-		case !isYoungGen(mt):
-			// Tenured30m generation: only a low disk trim deletes it early.
-			return lowDisk && youngGenAsOf.Sub(mt) >= youngGenDeleteAge, true
+			// Unused for 5 days, always delete.
+			return true
+		case lowDisk:
+			// Low disk trim removes any generation that has reached delete age.
+			return pastDeleteAge
+		case sizeTrim:
+			// Size-triggered trim removes only young generation files that have reached delete age.
+			return isYoungGen(mt) && pastDeleteAge
+		default:
+			// Otherwise, do not delete (including daily trim does not delete
+			// based on generations).
+			return false
 		}
-		// Young generation: only a size or low disk triggered trim deletes it early,
-		// and it counts in the baseline while too young to delete as of now.
-		return (sizeTrim || lowDisk) && youngGenAsOf.Sub(mt) >= youngGenDeleteAge, now.Sub(mt) < youngGenDeleteAge
 	}
 	limit := 8 // lower cap outside Linux for small fd limits
 	if runtime.GOOS == "linux" {
@@ -889,7 +899,7 @@ func (c *DiskCache) trim(youngGenAsOf time.Time) error {
 				return
 			}
 			subdir := filepath.Join(c.dir, fmt.Sprintf("%02x", i))
-			c.trimSubdir(subdir, classify, &perDir[i])
+			c.trimSubdir(subdir, remove, &perDir[i])
 		})
 	}
 	<-q.Idle()
@@ -911,14 +921,15 @@ func (c *DiskCache) trim(youngGenAsOf time.Time) error {
 		if data, _ := io.ReadAll(trimFile); len(stamp) == 0 || !bytes.Equal(data, stamp) {
 			return
 		}
-		base := min(stats.baseBytes, maxSizeBound)
+		base := min(stats.keptBytes, maxSizeBound)
+		if !sizeTrim && !lowDisk && before.base > 0 {
+			// Daily trim does not delete young files early, so do not raise base.
+			base = min(base, before.base)
+		}
 		// Keep any bytes that other go commands added during the scan.
 		if sizeOK {
 			if st, _, ok := readSize(c.dir); ok {
-				var concAdded int64
-				if before.hasEstimated && st.hasEstimated {
-					concAdded = max(0, st.estimated-before.estimated)
-				}
+				concAdded := max(0, st.estimated-before.estimated)
 				st.estimated = min(stats.keptBytes+concAdded, maxSizeBound)
 				st.base = base
 				writeSizeLocked(c.dir, st)
@@ -934,16 +945,17 @@ func (c *DiskCache) trim(youngGenAsOf time.Time) error {
 		}
 		actual := stats.keptBytes + stats.removedBytes
 		var estNote, freeNote string
-		if before.hasEstimated {
+		if sizeOK {
 			estNote = formatEstimateDelta(before.estimated, actual)
 		}
 		if lowDisk {
-			freeNote = fmt.Sprintf(" free=%s (consider providing more space)", formatBytes(free))
+			// free was measured before the scan.
+			freeNote = fmt.Sprintf(" (%s free, consider providing more space)", formatBytes(free))
 		}
-		appendLogLocked(c.dir, end, "trim: %s trigger: %s -> %s in %s, removed %d of %d files, base=%s next=%s%s%s",
+		appendLogLocked(c.dir, end, "trim: %s trigger: %s -> %s in %s, removed %d of %d files, next=%s, base=%s, tenured=%s%s%s",
 			trigger, formatBytes(actual), formatBytes(stats.keptBytes),
 			elapsed.Round(time.Millisecond), stats.removedFiles, stats.keptFiles+stats.removedFiles,
-			formatBytes(base), formatBytes(c.targetSize(base)), estNote, freeNote)
+			formatBytes(c.targetSize(base)), formatBytes(base), formatBytes(stats.tenuredBytes), estNote, freeNote)
 	})
 }

@@ -991,10 +1003,10 @@ func (c *DiskCache) trimLegacy() error {
 	// We subtract an additional mtimeInterval
 	// to account for the imprecision of our "last used" mtimes.
 	cutoff := now.Add(-trimLimit - mtimeInterval)
-	classify := func(mt time.Time) (remove, inBase bool) { return mt.Before(cutoff), false }
+	remove := func(mt time.Time) bool { return mt.Before(cutoff) }
 	for i := 0; i < 256; i++ {
 		subdir := filepath.Join(c.dir, fmt.Sprintf("%02x", i))
-		c.trimSubdir(subdir, classify, nil)
+		c.trimSubdir(subdir, remove, nil)
 	}

 	return nil
@@ -1004,7 +1016,7 @@ func (c *DiskCache) trimLegacy() error {
 type trimStats struct {
 	keptFiles, keptBytes       int64
 	removedFiles, removedBytes int64
-	baseBytes                  int64 // kept bytes counted toward the baseline
+	tenuredBytes               int64 // kept tenured generation bytes (for cache.log)
 }

 func (s *trimStats) add(o trimStats) {
@@ -1012,11 +1024,11 @@ func (s *trimStats) add(o trimStats) {
 	s.keptBytes += o.keptBytes
 	s.removedFiles += o.removedFiles
 	s.removedBytes += o.removedBytes
-	s.baseBytes += o.baseBytes
+	s.tenuredBytes += o.tenuredBytes
 }

 // trimSubdir trims a single cache subdirectory, accumulating counts into stats if non-nil.
-func (c *DiskCache) trimSubdir(subdir string, classify func(mt time.Time) (remove, inBase bool), stats *trimStats) {
+func (c *DiskCache) trimSubdir(subdir string, remove func(mt time.Time) bool, stats *trimStats) {
 	// Read all directory entries from subdir before removing
 	// any files, in case removing files invalidates the file offset
 	// in the directory scan. Also, ignore error from f.Readdirnames,
@@ -1046,8 +1058,7 @@ func (c *DiskCache) trimSubdir(subdir string, classify func(mt time.Time) (remov
 				size = dirFilesSize(entry)
 			}
 		}
-		remove, inBase := classify(info.ModTime())
-		if remove {
+		if remove(info.ModTime()) {
 			if info.IsDir() { // executable cache entry
 				err = os.RemoveAll(entry)
 			} else {
@@ -1060,13 +1071,12 @@ func (c *DiskCache) trimSubdir(subdir string, classify func(mt time.Time) (remov
 				}
 				continue
 			}
-			inBase = true // could not be deleted
 		}
 		if stats != nil {
 			stats.keptFiles++
 			stats.keptBytes += size
-			if inBase {
-				stats.baseBytes += size
+			if !isYoungGen(info.ModTime()) {
+				stats.tenuredBytes += size
 			}
 		}
 	}
diff --git a/src/cmd/go/internal/cache/cache_test.go b/src/cmd/go/internal/cache/cache_test.go
index d4d53f06ee..1af9069950 100644
--- a/src/cmd/go/internal/cache/cache_test.go
+++ b/src/cmd/go/internal/cache/cache_test.go
@@ -349,6 +349,9 @@ func payload(n, size int) []byte {
 // A total of 0 stores an empty output.
 func (c *testCache) put(n, total int) {
 	c.t.Helper()
+	if total != 0 && total < entrySize {
+		c.t.Fatalf("put(%d, %d): total must be 0 or >= entrySize (%d)", n, total, entrySize)
+	}
 	out, _, err := c.Put(dummyID(n), bytes.NewReader(payload(n, max(0, total-entrySize))))
 	c.must(err)
 	c.outs[n] = out
@@ -356,6 +359,9 @@ func (c *testCache) put(n, total int) {

 func (c *testCache) putExe(n, total int) {
 	c.t.Helper()
+	if total != 0 && total < entrySize {
+		c.t.Fatalf("putExe(%d, %d): total must be 0 or >= entrySize (%d)", n, total, entrySize)
+	}
 	out, _, err := c.PutExecutable(dummyID(n), "prog", bytes.NewReader(payload(n, max(0, total-entrySize))))
 	c.must(err)
 	c.outs[n] = out
@@ -548,10 +554,11 @@ func TestCacheSizeFile(t *testing.T) {
 	c := newTestCache(t, dir, 1000, 0)
 	path := filepath.Join(dir, "size.txt")
 	for _, tc := range []struct {
-		in, want string // want "" means unchanged
+		in, want string
 	}{
 		{in: "estimated 5000\ntorn", want: "base 0\nestimated 6000\n"},
-		{in: "estimated -42\nestimated abc\nestimated 99999999999999999999\nestimated 5000 extra\nestimated 999"},
+		{in: "estimated -42\nestimated abc\nestimated 99999999999999999999\nestimated 5000 extra\nestimated 999", want: "base 0\nestimated 1000\n"},
+		{in: "base 7\nestimated bad\n", want: "base 7\nestimated 1000\n"},
 		{in: "estimated abc\nestimated   7000  \nestimated 9000\nfuture 1\n", want: "base 0\nestimated 8000\n"},
 		{in: "estimated 9223372036854775807\n", want: fmt.Sprintf("base 0\nestimated %d\n", maxSizeBound)},
 		{in: "estimated 1\nbase -5\nbase 7\nbase 9\n", want: "base 7\nestimated 1001\n"},
@@ -559,18 +566,14 @@ func TestCacheSizeFile(t *testing.T) {
 		writeFile(t, dir, "size.txt", tc.in)
 		c.sampleAcc.Store(1000)
 		c.flush()
-		want := tc.want
-		if want == "" {
-			want = tc.in
-		}
-		wantFile(t, dir, "size.txt", want)
+		wantFile(t, dir, "size.txt", tc.want)
 	}

 	// writeSizeLocked always writes "base" then "estimated", so an untruncated
 	// shorter rewrite never resurrects old values.
-	writeSizeLocked(dir, cacheSizeState{base: 5e9, estimated: 6e9, hasEstimated: true})
+	writeSizeLocked(dir, cacheSizeState{base: 5e9, estimated: 6e9})
 	tmp := t.TempDir()
-	writeSizeLocked(tmp, cacheSizeState{estimated: 0, hasEstimated: true})
+	writeSizeLocked(tmp, cacheSizeState{base: 1, estimated: 2})
 	raw, err := os.ReadFile(filepath.Join(tmp, "size.txt"))
 	c.must(err)
 	f, err := os.OpenFile(path, os.O_WRONLY, 0o666)
@@ -578,8 +581,8 @@ func TestCacheSizeFile(t *testing.T) {
 	_, err = f.Write(raw)
 	c.must(err)
 	c.must(f.Close())
-	if st, _, ok := readSize(dir); !ok || !st.hasEstimated || st.estimated != 0 || st.base != 0 {
-		t.Errorf("torn clear: %+v, want estimated=0 base=0", st)
+	if st, _, ok := readSize(dir); !ok || st.estimated != 2 || st.base != 1 {
+		t.Errorf("torn rewrite: %+v, want estimated=2 base=1", st)
 	}
 }

@@ -616,7 +619,6 @@ func TestCacheTrimDuringScan(t *testing.T) {
 	c := newTestCache(t, dir, 1<<40, 0)
 	other := newTestCache(t, dir, 1000, 1000)
 	c.put(1, 500)
-	writeFile(t, dir, "size.txt", "estimated 0\n")
 	c.trimMidScan(func() {
 		other.flush()
 		c.clock = c.clock.Add(2 * time.Second)
@@ -626,6 +628,15 @@ func TestCacheTrimDuringScan(t *testing.T) {
 	if log, err := os.ReadFile(filepath.Join(dir, "cache.log")); err != nil || !strings.Contains(string(log), " in 2s, ") {
 		t.Errorf("cache.log = %q, %v; want elapsed 2s", log, err)
 	}
+	// Repeat with an existing estimate in size.txt.
+	c.clock = c.clock.Add(24 * time.Hour)
+	other.sampleAcc.Store(2000)
+	c.trimMidScan(func() { other.flush() })
+	wantFile(t, dir, "size.txt", "base 500\nestimated 2500\n")
+	// A size.txt removed during a scan is rewritten from the scan alone.
+	c.clock = c.clock.Add(24 * time.Hour)
+	c.trimMidScan(func() { c.must(os.Remove(filepath.Join(dir, "size.txt"))) })
+	wantFile(t, dir, "size.txt", "base 500\nestimated 500\n")

 	// (b) CleanCache during a scan discards stale scan results.
 	dir2 := t.TempDir()
@@ -691,17 +702,26 @@ func TestDefaultCacheAtExit(t *testing.T) {

 const logTimeFormat = "2006/01/02 15:04:05"

+var logVersion, _, _ = strings.Cut(runtime.Version(), " ")
+
+func logLine(t time.Time, msg string) string {
+	return t.Format(logTimeFormat) + " " + logVersion + ": " + msg + "\n"
+}
+
 func TestCacheLog(t *testing.T) {
 	skipIfLockUnsupported(t)
 	t.Parallel()

 	dir := t.TempDir()
 	c := newTestCache(t, dir, 1<<40, 0)
-	c.put(1, 1<<20) // 1 MiB expired so before (0.001 GiB) != after (0.000 GiB)
+	c.put(1, 2<<20) // expired young entry (removed)
+	c.clock = c.start.Add(6*24*time.Hour - 35*time.Minute)
+	c.put(2, 1<<20) // promoted to tenured30m below
 	c.clock = c.start.Add(6 * 24 * time.Hour)
-	c.put(2, 500)
+	c.use(2)
+	c.put(3, 2<<20) // kept young entry (excluded from tenured)
 	c.must(c.Trim())
-	want := c.clock.Format(logTimeFormat) + " trim: 24h trigger: 0.001 GiB -> 0.000 GiB in 0s, removed 2 of 4 files, base=0.000 GiB next=5.000 GiB\n"
+	want := logLine(c.clock, "trim: 24h trigger: 0.005 GiB -> 0.003 GiB in 0s, removed 2 of 6 files, next=5.000 GiB, base=0.003 GiB, tenured=0.001 GiB")
 	wantFile(t, dir, "cache.log", want)

 	// Routine sampled flushes and non-due trims are not logged.
@@ -714,11 +734,11 @@ func TestCacheLog(t *testing.T) {
 	writeFile(t, dir, "cache.1.log", "one\n")
 	CleanCache(dir)
 	wantFile(t, dir, "cache.1.log", "one\n")
-	if log, err := os.ReadFile(filepath.Join(dir, "cache.log")); err != nil || !strings.HasSuffix(string(log), " clean -cache\n") {
+	if log, err := os.ReadFile(filepath.Join(dir, "cache.log")); err != nil || !strings.HasSuffix(string(log), " "+logVersion+": clean -cache\n") {
 		t.Errorf("cache.log = %q, %v; want clean -cache", log, err)
 	}

-	// A trim scan whose prior estimate drifted by >10% and >1 GiB logs the delta.
+	// A trim scan whose prior estimate drifted by >10% and >1 GiB logs a drift note.
 	const GiB int64 = 1 << 30
 	driftDir := t.TempDir()
 	dc := newTestCache(t, driftDir, 1<<40, 0)
@@ -726,22 +746,22 @@ func TestCacheLog(t *testing.T) {
 	writeFile(t, driftDir, "size.txt", fmt.Sprintf("estimated %d\n", 2*GiB))
 	dc.must(dc.Trim())
 	if log, err := os.ReadFile(filepath.Join(driftDir, "cache.log")); err != nil ||
-		!strings.Contains(string(log), " (prior estimate=2.000 GiB actual=0.000 GiB delta=") {
-		t.Errorf("drifted trim cache.log = %q, %v; want prior estimate delta", log, err)
+		!strings.HasSuffix(string(log), " (prior estimate=2.000 GiB, actual=0.000 GiB, older go is untracked)\n") {
+		t.Errorf("drifted trim cache.log = %q, %v; want drift note", log, err)
 	}

 	// Lines up to 2048 bytes are written intact, while longer lines are truncated.
 	truncDir := t.TempDir()
-	exactMsg := strings.Repeat("x", 2048-len(logTimeFormat)-2)
+	exactMsg := strings.Repeat("x", 2048-len(logLine(c.clock, "")))
 	appendLogLocked(truncDir, c.clock, "%s", exactMsg)
-	wantExact := c.clock.Format(logTimeFormat) + " " + exactMsg + "\n"
+	wantExact := logLine(c.clock, exactMsg)
 	if len(wantExact) != 2048 {
 		t.Fatalf("len(wantExact) = %d, want 2048", len(wantExact))
 	}
 	wantFile(t, truncDir, "cache.log", wantExact)

 	appendLogLocked(truncDir, c.clock, "%s", exactMsg+"y")
-	wantTrunc := (c.clock.Format(logTimeFormat) + " " + exactMsg + "y\n")[:2048] + " [truncated]\n"
+	wantTrunc := logLine(c.clock, exactMsg+"y")[:2048] + " [truncated]\n"
 	wantFile(t, truncDir, "cache.log", wantExact+wantTrunc)

 	for _, tc := range []struct {
@@ -749,10 +769,10 @@ func TestCacheLog(t *testing.T) {
 		want        string
 	}{
 		{22 * GiB, 20 * GiB, ""},
-		{22*GiB + 1, 20 * GiB, " (prior estimate=22.000 GiB actual=20.000 GiB delta=+10.0%)"},
+		{22*GiB + 1, 20 * GiB, " (prior estimate=22.000 GiB, actual=20.000 GiB, older go is untracked)"},
 		{1 * GiB, 0, ""},
-		{1*GiB + 1, 0, " (prior estimate=1.000 GiB actual=0.000 GiB)"},
-		{8 * GiB, 10 * GiB, " (prior estimate=8.000 GiB actual=10.000 GiB delta=-20.0%)"},
+		{1*GiB + 1, 0, " (prior estimate=1.000 GiB, actual=0.000 GiB, older go is untracked)"},
+		{8 * GiB, 10 * GiB, " (prior estimate=8.000 GiB, actual=10.000 GiB, older go is untracked)"},
 	} {
 		if got := formatEstimateDelta(tc.est, tc.actual); got != tc.want {
 			t.Errorf("formatEstimateDelta(%d, %d) = %q, want %q", tc.est, tc.actual, got, tc.want)
@@ -765,7 +785,7 @@ func TestCacheLogRotation(t *testing.T) {

 	const roll = 128 << 10
 	now := time.Date(2026, 1, 2, 15, 4, 5, 0, time.Local)
-	line := func(msg string) string { return now.Format(logTimeFormat) + " " + msg + "\n" }
+	line := func(msg string) string { return logLine(now, msg) }

 	dir := t.TempDir()
 	pre := strings.Repeat("a", roll-1)
@@ -968,9 +988,9 @@ func TestCacheTrimYoungGen(t *testing.T) {
 	now := c2.clock
 	exp := now.Add(-5*24*time.Hour - time.Hour - time.Minute)
 	mtimes := []time.Time{
-		now.Add(-24 * time.Hour), // young, 1d old: kept, excluded from base
+		now.Add(-24 * time.Hour), // young, 1d old: kept
 		exp,                      // young, >5d+1h: expired
-		now.Add(-4*24*time.Hour + 16*time.Second), // plain mtime (tenured), 4d old: kept in base
+		now.Add(-4*24*time.Hour + 16*time.Second), // plain mtime (tenured), 4d old: kept
 		exp.Add(-30 * time.Second),                // tenured, >5d+1h: expired
 	}
 	for i, mt := range mtimes {
@@ -983,7 +1003,13 @@ func TestCacheTrimYoungGen(t *testing.T) {
 	c2.sampleAcc.Store(0)
 	c2.must(c2.Trim())
 	c2.wantEntries(1, 3)
-	wantFile(t, dir2, "size.txt", "base 500\nestimated 900\n")
+	wantFile(t, dir2, "size.txt", "base 100\nestimated 900\n") // daily trim does not raise base
+
+	// With base 0, a daily trim records kept bytes.
+	writeFile(t, dir2, "trim.txt", fmt.Sprint(now.Add(-24*time.Hour).Unix()))
+	writeFile(t, dir2, "size.txt", "base 0\nestimated 900\n")
+	c2.must(c2.Trim())
+	wantFile(t, dir2, "size.txt", "base 900\nestimated 900\n")
 }

 func TestCacheTrimSize(t *testing.T) {
@@ -1039,18 +1065,25 @@ func TestCacheTrimSize(t *testing.T) {
 	c.wantEntries(1, 4, 5, 6, 7)
 	wantFile(t, dir, "size.txt", "base 3300\nestimated 3300\n")

-	// Next day (28h): daily trim lowers base to tenured deps (300) without removing 4 to 7.
-	// An hour later, a small sampled put crosses targetSize(300) = 1000 and reclaims 4 to 7.
+	// Next day (28h): daily trim leaves base at 3300, so a small put at 29h
+	// stays under targetSize(3300) = 4950 and keeps 4 to 7.
 	c.clock = c.start.Add(28 * time.Hour)
 	c.must(c.Trim())
 	c.wantEntries(1, 4, 5, 6, 7)
-	wantFile(t, dir, "size.txt", "base 300\nestimated 3300\n")
+	wantFile(t, dir, "size.txt", "base 3300\nestimated 3300\n")

 	c.clock = c.start.Add(29 * time.Hour)
 	c.put(8, 200)
 	c.must(c.Trim())
-	c.wantEntries(1, 8)
-	wantFile(t, dir, "size.txt", "base 500\nestimated 500\n")
+	c.wantEntries(1, 4, 5, 6, 7, 8)
+	wantFile(t, dir, "size.txt", "base 3300\nestimated 3500\n")
+
+	// 31h: growth past targetSize(3300) reclaims young entries 4 to 8.
+	c.clock = c.start.Add(31 * time.Hour)
+	c.put(9, 1500)
+	c.must(c.Trim())
+	c.wantEntries(1, 9)
+	wantFile(t, dir, "size.txt", "base 1800\nestimated 1800\n")

 	// Base follows the cache back down: after a 5d+1h expiry, the daily trim records
 	// the smaller baseline, so the next target is sizeMinTarget again.
@@ -1065,6 +1098,22 @@ func TestCacheTrimSize(t *testing.T) {
 	c2.must(c2.Trim())
 	c2.wantEntries(2)
 	wantFile(t, dir2, "size.txt", "base 200\nestimated 200\n")
+
+	// A cache trimmed by an older Go has a fresh trim.txt but no size.txt. Sampled
+	// bytes seed size.txt and trigger a size trim without waiting for a daily trim.
+	dir3 := t.TempDir()
+	c3 := newTestCache(t, dir3, 100, 0)
+	c3.sizeMinTarget = 1000
+	c3.put(1, 300)
+	writeFile(t, dir3, "trim.txt", fmt.Sprint(c3.clock.Unix()))
+	c3.clock = c3.start.Add(2 * time.Hour)
+	c3.put(2, 700)
+	c3.must(c3.Trim())
+	c3.wantEntries(2)
+	wantFile(t, dir3, "size.txt", "base 700\nestimated 700\n")
+	if log, err := os.ReadFile(filepath.Join(dir3, "cache.log")); err != nil || !strings.Contains(string(log), " trim: size trigger: ") {
+		t.Errorf("cache.log = %q, %v; want size trigger", log, err)
+	}
 }

 func TestCacheCloseKeepsOwnOutput(t *testing.T) {
@@ -1088,7 +1137,7 @@ func TestCacheCloseKeepsOwnOutput(t *testing.T) {
 	c.sampleAcc.Store(100)
 	c.must(c.Close())
 	c.wantEntries(2)
-	wantFile(t, dir, "size.txt", "base 0\nestimated 800\n")
+	wantFile(t, dir, "size.txt", "base 800\nestimated 800\n")
 }

 func TestCacheLowDiskFree(t *testing.T) {
@@ -1141,12 +1190,12 @@ func TestCacheTrimLowDisk(t *testing.T) {
 		now.Add(-89*time.Minute - 30*time.Second), // tenured, 89m30s: kept in base
 		now.Add(-3*time.Hour + 16*time.Second),    // plain mtime (tenured), ~3h: removed
 	} {
-		c.put(i+1, 100*(i+1))
+		c.put(i+1, 200*(i+1))
 		c.must(os.Chtimes(c.fileName(dummyID(i+1), "a"), mt, mt))
 		c.must(os.Chtimes(c.fileName(c.outs[i+1], "d"), mt, mt))
 	}
 	c.sampleAcc.Store(0)
-	writeFile(t, dir, "size.txt", "base 0\nestimated 1500\n")
+	writeFile(t, dir, "size.txt", "base 100\nestimated 3000\n")

 	// A low disk trim waits for minTrimSpacing (with or without sampled bytes),
 	// and a disk with space left does not trim.
@@ -1165,20 +1214,20 @@ func TestCacheTrimLowDisk(t *testing.T) {
 	low = true
 	c.must(c.Trim())
 	c.wantEntries(2, 4)
-	wantFile(t, dir, "size.txt", "base 600\nestimated 600\n")
-	wantFile(t, dir, "cache.log", now.Format(logTimeFormat)+
-		" trim: low disk trigger: 0.000 GiB -> 0.000 GiB in 0s, removed 6 of 10 files,"+
-		" base=0.000 GiB next=5.000 GiB free=0.001 GiB (consider providing more space)\n")
+	wantFile(t, dir, "size.txt", "base 1200\nestimated 1200\n")
+	wantFile(t, dir, "cache.log", logLine(now,
+		"trim: low disk trigger: 0.000 GiB -> 0.000 GiB in 0s, removed 6 of 10 files,"+
+			" next=5.000 GiB, base=0.000 GiB, tenured=0.000 GiB (0.001 GiB free, consider providing more space)"))

 	// Later, Close measures age from openTime, so it keeps tenured entry 6
 	// (over 90m old now but not at openTime) and the new entry 7 it just wrote.
 	c.clock = now.Add(minTrimSpacing)
 	c.openTime = c.clock.Add(-30 * time.Minute)
-	c.put(6, 100)
+	c.put(6, 200)
 	mt := c.clock.Add(-100*time.Minute - 30*time.Second)
 	c.must(os.Chtimes(c.fileName(dummyID(6), "a"), mt, mt))
 	c.must(os.Chtimes(c.fileName(c.outs[6], "d"), mt, mt))
-	c.put(7, 100)
+	c.put(7, 200)
 	c.must(c.Close())
 	c.wantEntries(6, 7)
 }
diff --git a/src/cmd/go/internal/cache/log.go b/src/cmd/go/internal/cache/log.go
index 2e0c93057c..17093e61a8 100644
--- a/src/cmd/go/internal/cache/log.go
+++ b/src/cmd/go/internal/cache/log.go
@@ -10,14 +10,18 @@ import (
 	"io/fs"
 	"os"
 	"path/filepath"
+	"runtime"
+	"strings"
 	"time"
 )

 // With GOEXPERIMENT=trimbuildcache, GOCACHE/cache.log records each trim attempt. Sample lines:
 //
-//	<time> trim: size trigger: 9.000 GiB -> 6.000 GiB in 2.123s, removed 9 of 48 files, base=6.000 GiB next=9.000 GiB
-//	<time> trim: 24h trigger: 1.200 GiB -> 0.800 GiB in 1.52s, removed 12 of 56 files, base=0.800 GiB next=5.000 GiB
-//	<time> trim: low disk trigger: 4.100 GiB -> 1.300 GiB in 810ms, removed 30 of 90 files, base=1.000 GiB next=5.000 GiB free=0.400 GiB (consider providing more space)
+//	<time> go1.28.0: trim: size trigger: 9.000 GiB -> 6.000 GiB in 2.123s, removed 9 of 48 files, next=9.000 GiB, base=6.000 GiB, tenured=4.500 GiB
+//	<time> go1.28.0: trim: 24h trigger: 7.200 GiB -> 6.800 GiB in 1.52s, removed 12 of 56 files, next=9.000 GiB, base=6.000 GiB, tenured=5.900 GiB
+//	<time> go1.28.0: trim: low disk trigger: 4.100 GiB -> 1.300 GiB in 810ms, removed 30 of 90 files, next=5.000 GiB, base=1.300 GiB, tenured=0.800 GiB (0.400 GiB free, consider providing more space)
+//
+// next is the size trim target, base is the size.txt baseline, and tenured is kept tenured30m bytes.
 //
 // Once cache.log reaches logRollSize, it rotates through cache.1.log and cache.2.log as needed,
 // with an old cache.2.log being discarded. 'go clean -cache' does not delete the logs.
@@ -31,7 +35,8 @@ const logRollSize int64 = 128 << 10 // 128 KiB per log file (3 files max)
 // failure to roll might cause the active log to grow up to ~2x expected max size.
 func appendLogLocked(dir string, now time.Time, format string, args ...any) {
 	msg := fmt.Sprintf(format, args...)
-	line := fmt.Sprintf("%s %s\n", now.Format("2006/01/02 15:04:05"), msg)
+	goVersion, _, _ := strings.Cut(runtime.Version(), " ") // 1st field, like go1.28-devel_a1ea021
+	line := fmt.Sprintf("%s %s: %s\n", now.Format("2006/01/02 15:04:05"), goVersion, msg)
 	if len(line) > 2048 {
 		line = line[:2048] + " [truncated]\n"
 	}
@@ -87,15 +92,12 @@ func formatBytes(b int64) string {
 }

 // formatEstimateDelta returns a parenthetical note if est differs from actual
-// by more than 10% and 1 GiB, or "" otherwise.
+// by a material amount, or "" otherwise. Drift can happen when an older Go
+// updates the cache without updating size.txt.
 func formatEstimateDelta(est, actual int64) string {
 	delta := est - actual
 	if absDelta := max(delta, -delta); absDelta <= actual/10 || absDelta <= 1<<30 {
 		return ""
 	}
-	var pct string
-	if actual > 0 {
-		pct = fmt.Sprintf(" delta=%+.1f%%", 100*float64(delta)/float64(actual))
-	}
-	return fmt.Sprintf(" (prior estimate=%s actual=%s%s)", formatBytes(est), formatBytes(actual), pct)
+	return fmt.Sprintf(" (prior estimate=%s, actual=%s, older go is untracked)", formatBytes(est), formatBytes(actual))
 }
diff --git a/src/cmd/go/testdata/script/cache_trim.txt b/src/cmd/go/testdata/script/cache_trim.txt
index f09d3ad259..809e18d550 100644
--- a/src/cmd/go/testdata/script/cache_trim.txt
+++ b/src/cmd/go/testdata/script/cache_trim.txt
@@ -11,7 +11,7 @@ env GOCACHE=$WORK/cache
 go build -o $WORK/p.a p.go
 exists $GOCACHE/trim.txt
 grep -count=1 '^estimated [1-9][0-9]*$' $GOCACHE/size.txt
-grep -count=1 ' trim: (24h|low disk) trigger: .* removed [0-9]+ of [0-9]+ files' $GOCACHE/cache.log
+grep -count=1 '^[0-9/]+ [0-9:]+ go[^ ]+: trim: (24h|low disk) trigger: .* removed [0-9]+ of [0-9]+ files' $GOCACHE/cache.log
 cp $GOCACHE/size.txt $WORK/size.txt
 cp $GOCACHE/cache.log $WORK/log.txt
 go build -o $WORK/p.a p.go
@@ -31,7 +31,7 @@ go clean -cache
 grep -count=1 '^estimated 0$' $GOCACHE/size.txt
 ! grep . $GOCACHE/trim.txt
 grep -count=2 '^.' $GOCACHE/cache.log
-grep -count=1 ' clean -cache$' $GOCACHE/cache.log
+grep -count=1 ' go[^ ]+: clean -cache$' $GOCACHE/cache.log
 cmp $GOCACHE/cache.1.log $WORK/log.txt
 cmp $GOCACHE/cache.2.log $WORK/log.txt
 env GOCACHE=$WORK/nonexistent