From a51b01204badec6e2953bf13798f21e76c954b09 Mon Sep 17 00:00:00 2001 From: sdouglas Date: Wed, 25 Nov 2026 06:28:51 +0000 Subject: [PATCH 1/2] fix(git): rebuild a cached delta bundle once the mirror tip moves Delta bundles are cached under the snapshot base alone for bundle-cache-ttl (2h). The first bundle built after a snapshot was served to every later clone, so each clone fetched the rest of the gap from upstream. On cash-server that GitHub freshen took 18-22s per clone, because GitHub took 18s to build a 47-commit pack. Cached bundles now record the mirror HEAD they were built to. A plain GET whose replica mirror has moved past that tip rebuilds through the existing bundleBuilds coalescing. Ranged resumes keep the entry they started on. A tip this replica lacks came from a newer replica and is served as-is, so replicas don't rebuild each other's bundles. Rebuilds are synchronous. They stay cheap because bundles are built without bitmaps: about 1s for 47 commits on the staging mirror. Co-authored-by: Sleeper Service --- internal/gitclone/manager.go | 10 ++++ internal/strategy/git/bundlecoord_test.go | 50 +++++++++++++++++- internal/strategy/git/export_test.go | 2 +- internal/strategy/git/snapshot.go | 64 +++++++++++++++++------ 4 files changed, 109 insertions(+), 17 deletions(-) diff --git a/internal/gitclone/manager.go b/internal/gitclone/manager.go index 1000f7d4..3d2f6ba6 100644 --- a/internal/gitclone/manager.go +++ b/internal/gitclone/manager.go @@ -1268,3 +1268,13 @@ func (r *Repository) HasCommit(ctx context.Context, ref string) bool { err := cmd.Run() return err == nil } + +// HasAncestor reports whether ancestor is in the mirror and reachable from descendant. +func (r *Repository) HasAncestor(ctx context.Context, ancestor, descendant string) bool { + r.mu.RLock() + defer r.mu.RUnlock() + + // #nosec G204 - r.path is controlled by us; callers pass commit SHAs + cmd := exec.CommandContext(ctx, "git", "-C", r.path, "merge-base", "--is-ancestor", ancestor, descendant) + return cmd.Run() == nil +} diff --git a/internal/strategy/git/bundlecoord_test.go b/internal/strategy/git/bundlecoord_test.go index eea33eb8..fdf5a274 100644 --- a/internal/strategy/git/bundlecoord_test.go +++ b/internal/strategy/git/bundlecoord_test.go @@ -367,7 +367,7 @@ func TestBundleBuildCancellationReleasesFetchLock(t *testing.T) { done = completed go func() { defer close(completed) - file, err := s.createBundle(ctx, repo, base) + file, _, err := s.createBundle(ctx, repo, base) if file != nil { _ = file.Close() } @@ -395,3 +395,51 @@ func TestBundleBuildCancellationReleasesFetchLock(t *testing.T) { }) } } + +func commitToMirror(t *testing.T, repo *gitclone.Repository, message string) string { + t.Helper() + cmd := exec.CommandContext(t.Context(), "git", "-C", repo.Path(), "commit", "--allow-empty", "-m", message) + cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=Test", "GIT_AUTHOR_EMAIL=test@example.com", + "GIT_COMMITTER_NAME=Test", "GIT_COMMITTER_EMAIL=test@example.com") + out, err := cmd.CombinedOutput() + assert.NoError(t, err, string(out)) + head, err := mirrorHead(t.Context(), repo.Path()) + assert.NoError(t, err) + return head +} + +func TestBundleRebuiltWhenMirrorTipMoves(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s, repo, base, gate := newBundleBuildTest(t) + close(gate.release) + oldTip := s.getMirrorHead(s.ctx, repo) + first := serveTestBundle(s.ctx, s, base) + assert.Equal(t, http.StatusOK, first.Code) + assert.Contains(t, first.Body.String(), oldTip) + synctest.Wait() + + newTip := commitToMirror(t, repo, "after snapshot") + second := serveTestBundle(s.ctx, s, base) + assert.Equal(t, http.StatusOK, second.Code) + assert.Contains(t, second.Body.String(), newTip) + synctest.Wait() + + third := serveTestBundle(s.ctx, s, base) + assert.Equal(t, second.Body.String(), third.Body.String()) + synctest.Wait() + assert.Equal(t, int32(2), gate.creates.Load()) + }) +} + +func TestBundleFromNewerReplicaIsKept(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s, repo, base, gate := newBundleBuildTest(t) + close(gate.release) + key := bundleCacheKey(repo.UpstreamURL(), base) + assert.NoError(t, s.cacheBundle(s.ctx, key, strings.Repeat("ab", 20), strings.NewReader("peer bundle"))) + response := serveTestBundle(s.ctx, s, base) + assert.Equal(t, http.StatusOK, response.Code) + assert.Equal(t, "peer bundle", response.Body.String()) + assert.Equal(t, int32(1), gate.creates.Load()) + }) +} diff --git a/internal/strategy/git/export_test.go b/internal/strategy/git/export_test.go index aa8564b0..be9e62d4 100644 --- a/internal/strategy/git/export_test.go +++ b/internal/strategy/git/export_test.go @@ -41,7 +41,7 @@ func (s *Strategy) RunFailingCoordinatedSnapshot(ctx context.Context, repo *gitc // CacheBundle exports cacheBundle for testing. func (s *Strategy) CacheBundle(ctx context.Context, key cache.Key, r io.Reader) error { - return s.cacheBundle(ctx, key, r) + return s.cacheBundle(ctx, key, "", r) } // MirrorPreparationScheduled lets tests check for a queued or active preparation job. diff --git a/internal/strategy/git/snapshot.go b/internal/strategy/git/snapshot.go index 6535276b..5d3e161d 100644 --- a/internal/strategy/git/snapshot.go +++ b/internal/strategy/git/snapshot.go @@ -35,6 +35,9 @@ const lfsFetchTimeout = 25 * time.Minute const bundleBuildTimeout = 5 * time.Minute +// bundleTipHeader records the mirror HEAD a cached bundle was built up to. +const bundleTipHeader = "X-Cachew-Bundle-Tip" + type bundleBuild struct { done chan struct{} verifiedEmpty bool @@ -76,7 +79,7 @@ func (s *Strategy) finishBundleBuild(key cache.Key, build *bundleBuild) { build.release() } -func (s *Strategy) publishBundle(ctx context.Context, key cache.Key, build *bundleBuild, file *os.File) error { +func (s *Strategy) publishBundle(ctx context.Context, key cache.Key, build *bundleBuild, file *os.File, tip string) error { info, err := file.Stat() if err != nil { _ = file.Close() @@ -91,7 +94,7 @@ func (s *Strategy) publishBundle(ctx context.Context, key cache.Key, build *bund defer s.bundleBuilds.Delete(key) publishCtx, cancel := context.WithDeadline(s.ctx, deadline) defer cancel() - if err := s.cacheBundle(publishCtx, key, build.reader()); err != nil { + if err := s.cacheBundle(publishCtx, key, tip, build.reader()); err != nil { logging.FromContext(ctx).WarnContext(publishCtx, "Failed to cache bundle", "key", key, "error", err) } }() @@ -710,6 +713,11 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h releaseBuild := func() {} for acquired := false; ; { reader, headers, openErr := s.cache.Open(ctx, bKey, httputil.ConditionalOptions(r)...) + // Resumed downloads must keep reading the entry they started on, so only plain GETs re-check the tip. + if openErr == nil && r.Header.Get("Range") == "" && s.cachedBundleStale(ctx, s.cloneManager.Get(upstreamURL), headers) { + _ = reader.Close() + openErr = os.ErrNotExist + } switch { case openErr == nil, errors.Is(openErr, cache.ErrNotModified), @@ -808,7 +816,7 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h } } - bundleFile, err := s.createBundle(ctx, repo, base) + bundleFile, tip, err := s.createBundle(ctx, repo, base) if errors.Is(err, errEmptyBundle) { if freshenErr := s.doFetchVerified(ctx, repo); freshenErr != nil { source = "miss_stale" @@ -823,7 +831,7 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h http.Error(w, "Bundle not available", http.StatusNotFound) return } - bundleFile, err = s.createBundle(ctx, repo, base) + bundleFile, tip, err = s.createBundle(ctx, repo, base) if errors.Is(err, errEmptyBundle) { build.verifiedEmpty = true releaseBuild() @@ -838,7 +846,7 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h span.RecordError(err) return } - if err := s.publishBundle(ctx, bKey, build, bundleFile); err != nil { + if err := s.publishBundle(ctx, bKey, build, bundleFile, tip); err != nil { logger.WarnContext(ctx, "Failed to publish bundle", "upstream", upstreamURL, "error", err) http.Error(w, "Bundle not available", http.StatusServiceUnavailable) span.RecordError(err) @@ -928,11 +936,13 @@ func (s *Strategy) pregenerateBundle(ctx context.Context, repo *gitclone.Reposit defer cancel() bgCtx = logging.ContextWithLogger(bgCtx, logging.FromContext(ctx)) logger := logging.FromContext(bgCtx) - if reader, _, err := s.cache.Open(bgCtx, bKey); err == nil { + if reader, headers, err := s.cache.Open(bgCtx, bKey); err == nil { _ = reader.Close() - return + if !s.cachedBundleStale(bgCtx, repo, headers) { + return + } } - bundleFile, err := s.createBundle(bgCtx, repo, snapshotCommit) + bundleFile, tip, err := s.createBundle(bgCtx, repo, snapshotCommit) if err != nil { if errors.Is(err, errEmptyBundle) { return @@ -940,7 +950,7 @@ func (s *Strategy) pregenerateBundle(ctx context.Context, repo *gitclone.Reposit logger.WarnContext(bgCtx, "Failed to pre-generate bundle", "upstream", upstreamURL, "error", err) return } - if err := s.publishBundle(bgCtx, bKey, build, bundleFile); err != nil { + if err := s.publishBundle(bgCtx, bKey, build, bundleFile, tip); err != nil { logger.WarnContext(bgCtx, "Failed to publish bundle", "upstream", upstreamURL, "error", err) } }() @@ -980,8 +990,11 @@ func applySnapshotCacheHeaders(w http.ResponseWriter, headers http.Header) { //n } } -func (s *Strategy) cacheBundle(ctx context.Context, key cache.Key, r io.Reader) error { +func (s *Strategy) cacheBundle(ctx context.Context, key cache.Key, tip string, r io.Reader) error { headers := http.Header{"Content-Type": {"application/x-git-bundle"}} + if tip != "" { + headers.Set(bundleTipHeader, tip) + } wc, err := s.cache.Create(ctx, key, headers, s.config.BundleCacheTTL) if err != nil { return errors.Wrap(err, "create cache entry") @@ -1006,16 +1019,37 @@ func (s *Strategy) getMirrorHead(ctx context.Context, repo *gitclone.Repository) return head } +// cachedBundleStale reports whether this replica's mirror HEAD has moved past the tip a cached bundle was built to. +// +// A bundle is keyed by its base alone, so without this every clone gets the first bundle built after a snapshot +// until the TTL expires. A tip this mirror lacks came from a newer replica and is kept, so replicas never ping-pong. +func (s *Strategy) cachedBundleStale(ctx context.Context, repo *gitclone.Repository, headers http.Header) bool { //nolint:privatedoc // explains why + if repo == nil || repo.State() != gitclone.StateReady { + return false + } + head := s.getMirrorHead(ctx, repo) + tip := headers.Get(bundleTipHeader) + if head == "" || head == tip { + return false + } + if tip == "" { + return true + } + return commitSHARe.MatchString(tip) && repo.HasAncestor(ctx, tip, head) +} + // createBundle writes a git bundle of the commits between baseCommit and the mirror's HEAD to a temp file. // -// The returned file is already removed from the filesystem, so the open descriptor keeps the -// data alive. The caller must Close it. -func (s *Strategy) createBundle(ctx context.Context, repo *gitclone.Repository, baseCommit string) (*os.File, error) { //nolint:privatedoc // documents a non-obvious contract +// It also returns that HEAD. The returned file is already removed from the filesystem, so the open +// descriptor keeps the data alive. The caller must Close it. +func (s *Strategy) createBundle(ctx context.Context, repo *gitclone.Repository, baseCommit string) (*os.File, string, error) { //nolint:privatedoc // documents a non-obvious contract ctx, cancel := context.WithTimeout(ctx, bundleBuildTimeout) defer cancel() var bundleFile *os.File + var head string err := repo.WithFetchExclusion(ctx, func() error { - head, err := mirrorHead(ctx, repo.Path()) + var err error + head, err = mirrorHead(ctx, repo.Path()) if err != nil { return err } @@ -1025,7 +1059,7 @@ func (s *Strategy) createBundle(ctx context.Context, repo *gitclone.Repository, bundleFile, err = createBundleFile(ctx, repo, baseCommit) return err }) - return bundleFile, errors.WithStack(err) + return bundleFile, head, errors.WithStack(err) } func createBundleFile(ctx context.Context, repo *gitclone.Repository, baseCommit string) (*os.File, error) { From 7b643992177e84077e3985840675285cdd5c3c95 Mon Sep 17 00:00:00 2001 From: sdouglas Date: Tue, 24 Nov 2026 21:50:16 +0000 Subject: [PATCH 2/2] feat(git): freshen to a client-supplied bundle tip A client's ensure-refs and its delta bundle GET can reach different replicas, so the bundle replica's mirror may still be behind the HEAD ensure-refs just fetched, and the stale-tip check then misses. The bundle URL now accepts an optional tip=, the HEAD the client's ensure-refs resolved. A cached bundle that already contains tip is served as-is. Otherwise, a replica whose mirror lacks tip runs freshenMirror before deciding, the same fetch the unknown-base path uses. Its ref-check gate (10s) and the fetch timeout bound that work, so a bogus or unreachable tip costs at most one fetch per interval. A tip that isn't a full commit SHA is ignored. Older clients send no tip and are unaffected. Co-authored-by: Sleeper Service --- internal/strategy/git/bundlecoord_test.go | 94 +++++++++++++++++++++++ internal/strategy/git/snapshot.go | 56 +++++++++++--- 2 files changed, 138 insertions(+), 12 deletions(-) diff --git a/internal/strategy/git/bundlecoord_test.go b/internal/strategy/git/bundlecoord_test.go index fdf5a274..24fbd97f 100644 --- a/internal/strategy/git/bundlecoord_test.go +++ b/internal/strategy/git/bundlecoord_test.go @@ -443,3 +443,97 @@ func TestBundleFromNewerReplicaIsKept(t *testing.T) { assert.Equal(t, int32(1), gate.creates.Load()) }) } + +func gitIn(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...) + cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=Test", "GIT_AUTHOR_EMAIL=test@example.com", + "GIT_COMMITTER_NAME=Test", "GIT_COMMITTER_EMAIL=test@example.com") + out, err := cmd.CombinedOutput() + assert.NoError(t, err, string(out)) + return strings.TrimSpace(string(out)) +} + +func newBundleTipTest(t *testing.T) (s *Strategy, repo *gitclone.Repository, upstream, base string, gate *bundlePublishGate) { + t.Helper() + ctx := logging.ContextWithLogger(t.Context(), slog.Default()) + t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + upstream = t.TempDir() + gitIn(t, upstream, "init", "-b", "main") + gitIn(t, upstream, "commit", "--allow-empty", "-m", "base") + base = gitIn(t, upstream, "rev-parse", "HEAD") + gitIn(t, upstream, "commit", "--allow-empty", "-m", "next") + manager, err := gitclone.NewManager(ctx, gitclone.Config{MirrorRoot: t.TempDir()}, nil) + assert.NoError(t, err) + repo, err = manager.GetOrCreate(ctx, "https://example.com/org/repo") + assert.NoError(t, err) + gitIn(t, upstream, "clone", "--mirror", upstream, repo.Path()) + repo.MarkReady() + mem, err := cache.NewMemory(ctx, cache.MemoryConfig{MaxTTL: time.Hour}) + assert.NoError(t, err) + gate = &bundlePublishGate{Cache: mem, started: make(chan context.Context, 32), release: make(chan struct{})} + close(gate.release) + s = &Strategy{ctx: ctx, cache: gate, cloneManager: manager, metrics: newGitMetrics(), config: Config{BundleCacheTTL: time.Hour}} + return s, repo, upstream, base, gate +} + +func serveTestBundleWithTip(ctx context.Context, s *Strategy, base, tip string) *httptest.ResponseRecorder { + r := httptest.NewRequestWithContext(ctx, http.MethodGet, "/git/example.com/org/repo/snapshot.bundle?base="+base+"&tip="+tip, nil) + w := httptest.NewRecorder() + s.handleBundleRequest(w, r, "example.com", "org/repo/snapshot.bundle") + return w +} + +func TestBundleTipFreshensMirrorBehindClient(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s, repo, upstream, base, gate := newBundleTipTest(t) + first := serveTestBundle(s.ctx, s, base) + assert.Equal(t, http.StatusOK, first.Code) + synctest.Wait() + + gitIn(t, upstream, "commit", "--allow-empty", "-m", "pushed after this replica fetched") + tip := gitIn(t, upstream, "rev-parse", "HEAD") + assert.False(t, repo.HasCommit(s.ctx, tip)) + time.Sleep(s.cloneManager.Config().RefCheckInterval) + + second := serveTestBundleWithTip(s.ctx, s, base, tip) + assert.Equal(t, http.StatusOK, second.Code) + assert.Contains(t, second.Body.String(), tip) + assert.True(t, repo.HasCommit(s.ctx, tip)) + synctest.Wait() + assert.Equal(t, int32(2), gate.creates.Load()) + + // The cached bundle now contains tip, so the same hint is served without another build. + third := serveTestBundleWithTip(s.ctx, s, base, tip) + assert.Equal(t, second.Body.String(), third.Body.String()) + synctest.Wait() + assert.Equal(t, int32(2), gate.creates.Load()) + }) +} + +func TestBundleBogusTipFetchesAtMostOncePerInterval(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s, repo, _, base, gate := newBundleTipTest(t) + first := serveTestBundle(s.ctx, s, base) + assert.Equal(t, http.StatusOK, first.Code) + synctest.Wait() + + bogus := strings.Repeat("0f", 20) + time.Sleep(s.cloneManager.Config().RefCheckInterval) + before := repo.LastFetch() + second := serveTestBundleWithTip(s.ctx, s, base, bogus) + assert.Equal(t, first.Body.String(), second.Body.String()) + fetched := repo.LastFetch() + assert.True(t, fetched.After(before)) + + third := serveTestBundleWithTip(s.ctx, s, base, bogus) + assert.Equal(t, first.Body.String(), third.Body.String()) + assert.Equal(t, fetched, repo.LastFetch()) + + notSHA := serveTestBundleWithTip(s.ctx, s, base, "main") + assert.Equal(t, http.StatusOK, notSHA.Code) + synctest.Wait() + assert.Equal(t, int32(1), gate.creates.Load()) + }) +} diff --git a/internal/strategy/git/snapshot.go b/internal/strategy/git/snapshot.go index 5d3e161d..f990251b 100644 --- a/internal/strategy/git/snapshot.go +++ b/internal/strategy/git/snapshot.go @@ -689,6 +689,11 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h return } span.SetAttributes(attribute.String("cachew.base_commit", base)) + // The client's ensure-refs may have reached another replica; tip is the HEAD it saw there. + want := r.URL.Query().Get("tip") + if !commitSHARe.MatchString(want) { + want = "" + } bKey := bundleCacheKey(upstreamURL, base) @@ -714,9 +719,15 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h for acquired := false; ; { reader, headers, openErr := s.cache.Open(ctx, bKey, httputil.ConditionalOptions(r)...) // Resumed downloads must keep reading the entry they started on, so only plain GETs re-check the tip. - if openErr == nil && r.Header.Get("Range") == "" && s.cachedBundleStale(ctx, s.cloneManager.Get(upstreamURL), headers) { - _ = reader.Close() - openErr = os.ErrNotExist + if openErr == nil && r.Header.Get("Range") == "" { + stale, staleErr := s.cachedBundleStale(ctx, s.cloneManager.Get(upstreamURL), headers, want) + if staleErr != nil { + logger.WarnContext(ctx, "Failed to freshen mirror for bundle tip", "upstream", upstreamURL, "tip", want, "error", staleErr) + } + if stale { + _ = reader.Close() + openErr = os.ErrNotExist + } } switch { case openErr == nil, @@ -816,6 +827,9 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h } } + if err := s.freshenForBundleTip(ctx, repo, want); err != nil { + logger.WarnContext(ctx, "Failed to freshen mirror for bundle tip", "upstream", upstreamURL, "tip", want, "error", err) + } bundleFile, tip, err := s.createBundle(ctx, repo, base) if errors.Is(err, errEmptyBundle) { if freshenErr := s.doFetchVerified(ctx, repo); freshenErr != nil { @@ -938,7 +952,7 @@ func (s *Strategy) pregenerateBundle(ctx context.Context, repo *gitclone.Reposit logger := logging.FromContext(bgCtx) if reader, headers, err := s.cache.Open(bgCtx, bKey); err == nil { _ = reader.Close() - if !s.cachedBundleStale(bgCtx, repo, headers) { + if stale, err := s.cachedBundleStale(bgCtx, repo, headers, ""); err == nil && !stale { return } } @@ -1021,21 +1035,39 @@ func (s *Strategy) getMirrorHead(ctx context.Context, repo *gitclone.Repository) // cachedBundleStale reports whether this replica's mirror HEAD has moved past the tip a cached bundle was built to. // -// A bundle is keyed by its base alone, so without this every clone gets the first bundle built after a snapshot -// until the TTL expires. A tip this mirror lacks came from a newer replica and is kept, so replicas never ping-pong. -func (s *Strategy) cachedBundleStale(ctx context.Context, repo *gitclone.Repository, headers http.Header) bool { //nolint:privatedoc // explains why +// Bundles are keyed by base alone, so this stops clones getting the first one built after a snapshot. A tip this +// mirror lacks came from a newer replica and is kept; a want the bundle lacks freshens this mirror first. +func (s *Strategy) cachedBundleStale(ctx context.Context, repo *gitclone.Repository, headers http.Header, want string) (bool, error) { //nolint:privatedoc // explains why if repo == nil || repo.State() != gitclone.StateReady { - return false + return false, nil } - head := s.getMirrorHead(ctx, repo) tip := headers.Get(bundleTipHeader) + validTip := commitSHARe.MatchString(tip) + if want != "" && validTip && (tip == want || repo.HasAncestor(ctx, want, tip)) { + return false, nil + } + freshenErr := s.freshenForBundleTip(ctx, repo, want) + head := s.getMirrorHead(ctx, repo) if head == "" || head == tip { - return false + return false, freshenErr } if tip == "" { - return true + return true, freshenErr } - return commitSHARe.MatchString(tip) && repo.HasAncestor(ctx, tip, head) + return validTip && repo.HasAncestor(ctx, tip, head), freshenErr +} + +// freshenForBundleTip fetches upstream when the client saw a tip this replica's mirror lacks. +// +// freshenMirror's ref-check gate allows one fetch per interval, so a bogus or unreachable tip cannot repeat it. +func (s *Strategy) freshenForBundleTip(ctx context.Context, repo *gitclone.Repository, want string) error { //nolint:privatedoc // explains why + if want == "" || repo.HasCommit(ctx, want) { + return nil + } + if err := s.freshenMirror(ctx, repo); err != nil { + return errors.Wrap(err, "freshen mirror for bundle tip") + } + return nil } // createBundle writes a git bundle of the commits between baseCommit and the mirror's HEAD to a temp file.