-
Notifications
You must be signed in to change notification settings - Fork 292
fix(orchestrator): retry template fetch after fail #2526
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
dobrac
wants to merge
2
commits into
main
Choose a base branch
from
cursor/3c76a271
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+245
−13
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 On partial Fetch failure, fetchAndEvictOnFailure calls cache.Delete which synchronously fires the OnEviction handler in NewCache, running template.Close → closeTemplate → snapfile.Close() → os.RemoveAll(f.path) (storage_file.go:51-53). Concurrent peerserver consumers that obtained the same *storageTemplate via GetCachedTemplate (peerserver/resolve.go:39-47, peerserver/file.go:41-66) can race the deletion: they hold the path returned by t.Snapfile() but their os.Open call may land after the eviction unlinked the file. Pre-PR this was effectively impossible (eviction only fired on 25h TTL); post-PR it can fire within milliseconds. Fix by having OnEviction wait for in-use refs (refcount/handle), or skip Close when the entry was deleted due to a Fetch failure where partial state was never safely shareable.
Extended reasoning...
What changes\n\nThe PR adds
fetchAndEvictOnFailure(cache.go:343-362) so a failed initial fetch evicts the cache entry instead of poisoning the cache. The eviction goes throughc.cache.Delete(key), which fires the existingOnEvictionhandler registered at cache.go:75-84:\n\ngo\ncache.OnEviction(func(ctx context.Context, _ ttlcache.EvictionReason, item *ttlcache.Item[string, Template]) {\n peers.Purge(item.Key())\n template := item.Value()\n err := template.Close(ctx)\n ...\n})\n\n\ntemplate.ClosecallscloseTemplate(template.go:24-59), which iterates the per-field SetOnce values viaWait(), appends them to a closer list, and callsClose()on each. For*storageFile(used for snapfile),Close()isos.RemoveAll(f.path)(storage_file.go:51-53), so the on-disk cached file is unlinked.\n\n## Why partial failure is realistic\n\nstorageTemplate.Fetch(storage_template.go:74-237) launches fourerrgroup.Groupgoroutines (snapfile, metafile, memfile, rootfs). The errgroup has no parent context cancellation tied to sibling failures, so when one goroutine fails (e.g. rootfs returns anerrMsgat storage_template.go:212-220), the others continue to completion and may successfullySetValueon their own field. So thestorageTemplatereturned synchronously to callers can have a valid snapfile even when Fetch ultimately returns non-nil.\n\n## The race\n\nThe*storageTemplateis shared across concurrent callers viacache.GetOrSetingetTemplateWithFetch(cache.go:317-339), and is also exposed viaCache.GetCachedTemplate(cache.go:189-198), which the peerserver consumes:\n\n-peerserver/resolve.go:39-47builds afileSource{getFile: t.Snapfile}from the cached template.\n-peerserver/file.go:41-72then callsf.getFile()(returns the SetValue'd*storageFileand its path) and immediatelyos.Open(file.Path())(line 52).\n\nIf the partial fetch failure happens between the peer obtaining the template and callingos.Open, the eviction'sos.RemoveAllcan land first andos.Openreturns ENOENT (which the code maps toErrNotAvailableat file.go:53-55).\n\n## Why pre-PR code was safe\n\nPre-PR, eviction only happened via the 25h TTL (templateExpiration), so the file was unlinked long after any active reader was gone. Theitem.Value() != tmplguard infetchAndEvictOnFailureonly protects against deleting a different template instance — not against deleting one still in active use by other goroutines.\n\n## Step-by-step proof\n\n1. T=0ms: Sandbox A callsGetTemplate(buildID).getTemplateWithFetchdoesGetOrSet(key, tmpl)(miss), launchesgo fetchAndEvictOnFailure(ctx, key, tmpl), returnstmplto A.\n2. T=1ms: Peer X requests the snapfile.peerserver.ResolveBlobcallscache.GetCachedTemplate(buildID)and findstmpl. It returnsfileSource{getFile: tmpl.Snapfile}.\n3. T=2ms: snapfile fetch completes successfully →tmpl.snapfile.SetValue(snapfile)succeeds; the on-disk path/cache/.../snapfileexists.\n4. T=3ms: rootfs fetch fails (transient GCS error) →tmpl.rootfs.SetError(...), the rootfs goroutine returns the error.\n5. T=4ms:errgroup.Wait()returns the rootfs error;storageTemplate.Fetchreturns it;fetchAndEvictOnFailurecallsc.cache.Delete(key).\n6. T=4ms: OnEviction fires synchronously;closeTemplatecallstmpl.Snapfile().Wait()(returns the SetValue'd snapfile), appends it to closables, thensnapfile.Close()runsos.RemoveAll("/cache/.../snapfile"). File is unlinked.\n7. T=5ms: Peer X's handler reachesfileSource.Stream→f.getFile()returns the snapfile (the in-memory*storageFileis still valid), thenos.Open(file.Path())fails with ENOENT.\n\n## Scope correction\n\nOne note on the original description:closeTemplate(template.go:24-59) only closes Memfile, Rootfs, and Snapfile — it does not callt.Metadata(), so the metafile is notRemoveAll'd by eviction. Only the snapfile (via*storageFile.Close) is affected. Memfile/rootfs use*StoragewhoseCloseis a no-op for the on-disk cached chunks here.\n\n## Suggested fix\n\nOptions:\n- Have eviction skipClose(or defer it) when the eviction was triggered by a Fetch failure where readers may still hold the partial state — and rely on a later TTL or refcount-based cleanup.\n- Make consumers acquire a refcount on the template (Acquire/Release) so OnEviction's Close blocks until refs hit zero.\n- For the peerserver path specifically, treat*storageFilepaths as immutable while a reader is mid-stream by deferring removal.