assetcache: own committed headers; fail Commit on close and meta-sync errors
Commit clones the caller's header before encoding and indexing it. A body temporary that fails to close aborts the commit before anything is renamed. A failed directory sync after the meta rename is returned: the new entry stays published, and the old version's bodies are kept on disk and counted for the next Open instead of being deleted, since a crash could still bring back the old meta. The concurrency test now checks every Open and read error and the bytes read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+207
−16
internal/assetcache/entry_test.go+138 −4internal/assetcache/fill.go+63 −8internal/assetcache/store.go+6 −4
CI failed — run details
diff --git a/internal/assetcache/entry_test.go b/internal/assetcache/entry_test.go| index 84ae6b723..75c222b15 100644 |
| --- a/internal/assetcache/entry_test.go |
| +++ b/internal/assetcache/entry_test.go |
| @@ -594,10 +594,40 @@ func TestCommitGetAndReadConcurrently(t *testing.T) { |
| t.Errorf("Commit: %v", err) |
| } |
| case 1: |
| - if e, ok := s.Get(k); ok { |
| - if r, err := e.Open(false); err == nil { |
| - io.Copy(io.Discard, r) |
| - r.Close() |
| + e, ok := s.Get(k) |
| + if !ok { |
| + continue |
| + } |
| + for _, gz := range []bool{false, true} { |
| + if gz && e.Meta.GzipSize == 0 { |
| + continue |
| + } |
| + r, err := e.Open(gz) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue // retired between Get and Open |
| + } |
| + if err != nil { |
| + t.Errorf("Open(gzip=%v): %v", gz, err) |
| + continue |
| + } |
| + got, err := io.ReadAll(r) |
| + r.Close() |
| + if err != nil { |
| + t.Errorf("read (gzip=%v): %v", gz, err) |
| + continue |
| + } |
| + if gz { |
| + zr, err := gzip.NewReader(bytes.NewReader(got)) |
| + if err == nil { |
| + got, err = io.ReadAll(zr) |
| + } |
| + if err != nil { |
| + t.Errorf("gunzip: %v", err) |
| + continue |
| + } |
| + } |
| + if int64(len(got)) != e.Meta.Size || !bytes.HasPrefix(got, cssText[:200]) { |
| + t.Errorf("read %d bytes (gzip=%v), want the %d-byte body of a commit", len(got), gz, e.Meta.Size) |
| } |
| } |
| case 2: |
| @@ -631,3 +661,107 @@ func TestCommitGetAndReadConcurrently(t *testing.T) { |
| t.Fatalf("Stats after reopen = %+v, before %+v", st2, st) |
| } |
| } |
| + |
| +// TestCommittedHeaderIsTheStoresOwn is not acceptance: it uses a fake FS. |
| +// Changing the caller's header after Commit changes neither later hits nor |
| +// what a restart reads. |
| +func TestCommittedHeaderIsTheStoresOwn(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + h := cssHeader("1") |
| + commit(t, s, k, cssText, h, false) |
| + h.Set("X-Version", "changed") |
| + h["Content-Type"][0] = "text/evil" |
| + h.Add("X-New", "x") |
| + |
| + check := func(name string, e *Entry) { |
| + t.Helper() |
| + got := e.Meta.Header |
| + if got.Get("X-Version") != "1" || got.Get("Content-Type") != "text/css" || got.Get("X-New") != "" { |
| + t.Fatalf("%s: Header = %v, want the header as committed", name, got) |
| + } |
| + } |
| + check("hit", mustGet(t, s, k)) |
| + check("after reopen", mustGet(t, reopen(t, dir), k)) |
| +} |
| + |
| +// TestBodyCloseFailureAborts is not acceptance: it uses a fake FS. A body |
| +// that fails to close before publication aborts the commit, and the old entry |
| +// stays as it was. |
| +func TestBodyCloseFailureAborts(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, []byte("old bytes"), cssHeader("old"), false) |
| + oldFiles := listDir(t, dir) |
| + before := s.Stats() |
| + |
| + f := fill(t, s, k, cssText) |
| + f.failAt = faultBodyClose |
| + if err := f.Commit(Meta{Header: cssHeader("new"), Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, true); !errors.Is(err, errInjected) { |
| + t.Fatalf("Commit = %v, want the injected close failure", err) |
| + } |
| + f.Abort() |
| + sameNames(t, listDir(t, dir), oldFiles) |
| + if st := s.Stats(); st != before { |
| + t.Fatalf("Stats = %+v, want %+v", st, before) |
| + } |
| + if box, apps := slots(s); box != 0 || apps != 0 { |
| + t.Fatalf("slots: box %d, apps %d", box, apps) |
| + } |
| + e := mustGet(t, s, k) |
| + if e.Meta.Header.Get("X-Version") != "old" || string(readAll(t, e, false)) != "old bytes" { |
| + t.Fatalf("entry after a failed commit = %+v", e.Meta) |
| + } |
| +} |
| + |
| +// TestUnsyncedMetaRenameKeepsTheOldBodies is not acceptance: it uses a fake |
| +// FS. When the directory sync after the meta rename fails, Commit reports it, |
| +// the new entry (whose files are on disk) stays indexed, and the old bodies |
| +// are kept, still counted, for the next Open: a crash could yet bring back |
| +// the old meta, which must find its bodies. |
| +func TestUnsyncedMetaRenameKeepsTheOldBodies(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + old := cssText[:1000] |
| + commit(t, s, k, old, cssHeader("old"), true) |
| + oldMeta := mustGet(t, s, k).Meta |
| + oldBytes := oldMeta.Size + oldMeta.GzipSize |
| + |
| + f := fill(t, s, k, []byte("new body")) |
| + f.failAt = faultMetaDirSync |
| + if err := f.Commit(Meta{Header: cssHeader("new"), Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, false); !errors.Is(err, errInjected) { |
| + t.Fatalf("Commit = %v, want the injected sync failure", err) |
| + } |
| + f.Abort() // a no-op: the entry is published |
| + |
| + e := mustGet(t, s, k) |
| + if e.Meta.Header.Get("X-Version") != "new" || string(readAll(t, e, false)) != "new body" { |
| + t.Fatalf("entry = %+v, want the new one", e.Meta) |
| + } |
| + sameNames(t, listDir(t, dir), []string{ |
| + k.ID() + ".meta", bodyName(k.ID(), e.Meta.Version), |
| + bodyName(k.ID(), oldMeta.Version), gzipName(k.ID(), oldMeta.Version), |
| + }) |
| + metaSize := fileSize(t, filepath.Join(dir, k.ID()+".meta")) |
| + want := Stats{Entries: 1, Bytes: int64(len("new body")) + metaSize + oldBytes, Retired: oldBytes, Apps: 1} |
| + if st := s.Stats(); st != want { |
| + t.Fatalf("Stats = %+v, want %+v", st, want) |
| + } |
| + if box, apps := slots(s); box != 0 || apps != 0 { |
| + t.Fatalf("slots: box %d, apps %d", box, apps) |
| + } |
| + // Later commits and drops do not delete the kept bodies either. |
| + commit(t, s, testKey("blog", "/b.css"), []byte("b"), cssHeader("b"), false) |
| + if _, err := os.Stat(filepath.Join(dir, bodyName(k.ID(), oldMeta.Version))); err != nil { |
| + t.Fatalf("old body after a later commit: %v", err) |
| + } |
| + |
| + s2 := reopen(t, dir) |
| + e2 := mustGet(t, s2, k) |
| + if e2.Meta.Version != e.Meta.Version { |
| + t.Fatalf("after reopen: version %q, want %q", e2.Meta.Version, e.Meta.Version) |
| + } |
| + if _, err := os.Stat(filepath.Join(dir, bodyName(k.ID(), oldMeta.Version))); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("old body after reopen: %v, want removed", err) |
| + } |
| +} |
diff --git a/internal/assetcache/fill.go b/internal/assetcache/fill.go| index b2b33e474..7c8bf4d7f 100644 |
| --- a/internal/assetcache/fill.go |
| +++ b/internal/assetcache/fill.go |
| @@ -77,6 +77,7 @@ type Fill struct { |
| left []leftover // temporaries an Abort could not remove yet |
| crashAt string // tests only: the Commit stage at which to stop as a crash would |
| + failAt string // tests only: the Commit stage whose I/O fails with errInjected |
| } |
| // leftover is a temporary still on disk and the bytes it holds. |
| @@ -273,6 +274,27 @@ func (f *Fill) closeFiles() { |
| } |
| } |
| +// closeBodies closes the body temporaries before they are published and |
| +// reports the first failure, so a body the kernel could not finish writing |
| +// is never renamed into place. The caller holds f.mu. |
| +func (f *Fill) closeBodies() error { |
| + var err error |
| + if f.tmp != nil { |
| + err = f.tmp.Close() |
| + f.tmp = nil |
| + } |
| + if f.gz != nil { |
| + if cerr := f.gz.Close(); err == nil { |
| + err = cerr |
| + } |
| + f.gz = nil |
| + } |
| + if err != nil { |
| + err = fmt.Errorf("assetcache: %w", err) |
| + } |
| + return f.fault(faultBodyClose, err) |
| +} |
| + |
| // releaseSlot returns a fill slot. |
| func (s *Store) releaseSlot(scope string) { |
| s.mu.Lock() |
| @@ -306,6 +328,23 @@ const crashBeforeMetaRename = "before meta rename" |
| // leaves the files as a crash would and cleans up nothing. |
| var errSimulatedCrash = errors.New("assetcache: simulated crash") |
| +// Commit stages at which a test can inject an I/O failure through f.failAt. |
| +const ( |
| + faultBodyClose = "body close" |
| + faultMetaDirSync = "meta dir sync" |
| +) |
| + |
| +// errInjected is the failure a test injects through f.failAt. |
| +var errInjected = errors.New("assetcache: injected failure") |
| + |
| +// fault is err, or errInjected when a test has asked stage to fail. |
| +func (f *Fill) fault(stage string, err error) error { |
| + if err == nil && f.failAt == stage { |
| + return errInjected |
| + } |
| + return err |
| +} |
| + |
| // errGzipTooLarge stops the gzip copy once it would pass its limit. |
| var errGzipTooLarge = errors.New("assetcache: gzip copy larger than its limit") |
| @@ -324,8 +363,10 @@ var errGzipTooLarge = errors.New("assetcache: gzip copy larger than its limit") |
| // files are unlinked at once but stay counted while a Reader holds them. The |
| // meta's bytes are then counted with the entry and the reservation released. |
| // |
| -// Any error before the meta rename behaves as Abort. Commit after Commit or |
| -// Abort returns os.ErrClosed and changes nothing. |
| +// Any error before the meta rename behaves as Abort. If the directory sync |
| +// after the meta rename fails, Commit returns that error but the new entry |
| +// stays published (see commit). Commit after Commit or Abort returns |
| +// os.ErrClosed and changes nothing. |
| func (f *Fill) Commit(m Meta, gzipCopy bool) error { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| @@ -347,8 +388,8 @@ func (f *Fill) Commit(m Meta, gzipCopy bool) error { |
| } |
| // commit does Commit's work. Until the meta rename every error returns with |
| -// the fill's files where finish can find and remove them; after it, commit |
| -// cannot fail. The caller holds f.mu. |
| +// the fill's files where finish can find and remove them; after it, the fill |
| +// is done whatever happens. The caller holds f.mu. |
| func (f *Fill) commit(m Meta, gzipCopy bool) error { |
| s := f.s |
| @@ -373,6 +414,7 @@ func (f *Fill) commit(m Meta, gzipCopy bool) error { |
| // (3) The fields the store owns. |
| m.Key = f.key |
| + m.Header = m.Header.Clone() // the store's own: the caller may reuse its map |
| m.Version = version |
| m.Size = f.written |
| m.GzipSize = gzSize |
| @@ -397,7 +439,9 @@ func (f *Fill) commit(m Meta, gzipCopy bool) error { |
| return fmt.Errorf("assetcache: %w", err) |
| } |
| } |
| - f.closeFiles() |
| + if err := f.closeBodies(); err != nil { |
| + return err |
| + } |
| dir := s.cfg.Dir |
| if err := renameTo(&f.bodyPath, filepath.Join(dir, bodyName(f.id, version))); err != nil { |
| return err |
| @@ -427,9 +471,13 @@ func (f *Fill) commit(m Meta, gzipCopy bool) error { |
| unlock() |
| return fmt.Errorf("assetcache: %w", err) |
| } |
| - // The entry is committed. A failed directory sync only means a crash |
| - // could still bring back the old entry, which the design allows. |
| - _ = syncDir(dir) |
| + // The new entry is published: its meta and bodies are on disk. If the |
| + // directory sync fails, the rename may not be durable and a crash could |
| + // bring back the old meta, so the old bodies must stay. The new entry is |
| + // still indexed and served (it is what the directory holds), the old |
| + // version is kept on disk and counted until the next Open (whose scan |
| + // removes whichever bodies no meta names), and Commit returns the error. |
| + syncErr := f.fault(faultMetaDirSync, syncDir(dir)) |
| // (7) Swap the index slot, count the new entry and release the |
| // reservation and the fill slot in one step, then retire the old |
| @@ -439,6 +487,10 @@ func (f *Fill) commit(m Meta, gzipCopy bool) error { |
| old := s.entries[f.id] |
| if old != nil { |
| s.unindexLocked(old) |
| + if syncErr != nil { |
| + old.ver.unlinking = false |
| + old.ver.kept = true |
| + } |
| } |
| s.index(ne) |
| s.reserved -= f.held |
| @@ -449,6 +501,9 @@ func (f *Fill) commit(m Meta, gzipCopy bool) error { |
| f.left = nil |
| f.done = true |
| + if syncErr != nil { |
| + return fmt.Errorf("assetcache: committed, but the meta rename may not be durable: %w", syncErr) |
| + } |
| if old != nil { |
| s.unlink(old.ver) |
| } |
diff --git a/internal/assetcache/store.go b/internal/assetcache/store.go| index 4ea3d6e39..2a6b96cb2 100644 |
| --- a/internal/assetcache/store.go |
| +++ b/internal/assetcache/store.go |
| @@ -32,8 +32,9 @@ type Stats struct { |
| Bytes int64 |
| Reserved int64 |
| // Retired is the bytes of replaced, expired, evicted or swept bodies |
| - // that are unlinked but still hold disk: open Readers keep them, or an |
| - // unlink failed and will be retried. |
| + // that still hold disk: open Readers keep them, an unlink failed and |
| + // will be retried, or a replacement could not be made durable and they |
| + // are kept for the next Open. |
| Retired int64 |
| Apps int |
| } |
| @@ -56,7 +57,7 @@ func (e *entry) bytes() int64 { return e.metaSize + e.ver.bytes } |
| // version is one committed version's body files, <id>.<v>.body and |
| // <id>.<v>.gz. Its bytes stay counted in Store.used while any of indexed, |
| -// leases, unlinking or stuck holds: the disk is not free until the files are |
| +// leases, unlinking, stuck or kept holds: the disk is not free until the files are |
| // unlinked and the last Reader has closed them. Fields are guarded by s.mu. |
| type version struct { |
| id, v string |
| @@ -65,6 +66,7 @@ type version struct { |
| leases int // open Readers |
| unlinking bool // an unlink is in progress |
| stuck bool // an unlink failed; retryStuck tries again |
| + kept bool // left on disk for the next Open: the meta that replaced it may not be durable |
| counted bool // bytes are in s.used |
| } |
| @@ -310,7 +312,7 @@ func (s *Store) retryStuck() { |
| // settleLocked stops counting v's bytes once nothing holds them. The caller |
| // holds s.mu. |
| func (s *Store) settleLocked(v *version) { |
| - if v.counted && !v.indexed && v.leases == 0 && !v.unlinking && !v.stuck { |
| + if v.counted && !v.indexed && v.leases == 0 && !v.unlinking && !v.stuck && !v.kept { |
| v.counted = false |
| s.used -= v.bytes |
| s.retired -= v.bytes |