Repository navigation
perf: make generate-all performant - #13745
Conversation
Engine CPU profiles of Dang SDK generation showed Directory.withDirectory dominating, with almost all of its time spent resolving destination paths rather than moving data. Add a benchmark that reproduces that shape: copy a deep source tree onto a destination that already contains it, with CopyDirContents and ReplaceExisting set, matching the options the engine passes for withDirectory. Depth is as important as file count here, because destination paths are resolved by walking from the root for every entry, so the tree is built six levels deep rather than wide and shallow. Signed-off-by: Alex Suraci <[email protected]>
copyNode called removeForReplace and then immediately called realPath on the same destination path, so the write-root path was resolved twice per entry. Each resolution walks the destination from the root and materializes every ancestor directory, so the duplicate was not cheap. Return the resolved path from removeForReplace when it removed something and reuse it in copyNode, falling back to resolving only when nothing was removed. On a repeated merge of a six-level tree this cuts wall time by about 38% and allocations by about 42%. Signed-off-by: Alex Suraci <[email protected]>
Ensuring a destination directory resolved the path from the destination root and then recursed on the parent, which resolved from the root again, and so on up the tree. Resolution lstats every component, so ensuring one directory cost work quadratic in its depth, and every copied entry ensured its parent. The recursion was never necessary: the relative path being recursed on comes out of rootPath, so it is already fully resolved and none of its ancestors can be a symlink. Walk them directly instead, materializing parent-first. Ancestors already known to exist in the write root are recorded so the walk can stop at the first one it recognizes, which makes descending into a subtree cost one lookup per new directory rather than one per entry. Directory removals clear that set, since removing a directory is the only way for it to become wrong; file removals cannot invalidate it and stay on the fast path. On the repeated-merge benchmark this cuts wall time by a further 45% and lstat calls by 69%. Signed-off-by: Alex Suraci <[email protected]>
Copying a tree walks it depth first, so by the time an entry is copied its destination directory has just been resolved and materialized. That result was thrown away, and every entry resolved its own destination from the destination root again. Thread the resolved directory down into the entries inside it. Its relative path is symlink-free by construction, so an entry's write path is the parent plus its final component with no resolution at all, and stat'ing the entry in the view only has to consider whether that final component is itself a symlink. When it is, the bounded resolution still runs, which is what keeps symlinked destination directories behaving as before. Together with the previous two commits this takes the repeated-merge benchmark from 104ms to 16ms per merge, allocations from 1.28M to 62K, and lstat calls from 201K to 11K. Signed-off-by: Alex Suraci <[email protected]>
This currently blows up when calling Workspace.asModuleSource from a module since it ties to do a Host.findUp, which hits a 10 second timeout because it can't reach the client. Rather than grant client access to a new path, it seems safer to just let this return nothing; we're probably just gonna nuke the user defaults .env path later anyway. Signed-off-by: Alex Suraci <[email protected]>
Merging changesets first unions their before directories, one withDirectory per changeset. Changesets merged together are normally diffs taken against a common base, so those directories are usually the same directory repeated: merging one onto itself changes nothing, but still walks the whole tree, so a merge of N changesets pays N full-tree copies to produce what the first one already produced. Collapse consecutive repeats, comparing content-preferred digests the same way changeset path computation already does. Only consecutive repeats are dropped, since removing every repeat would reorder a sequence like A, B, A, where the trailing A is what decides paths that A and B disagree on. Signed-off-by: Alex Suraci <[email protected]>
TomChv
left a comment
There was a problem hiding this comment.
Traced the resolvedParent threading through every call path and the materializedDirs invariant against every removal site — the layercopy group holds up, and TestCopyDirectoryFollowsOverlayDestSymlinkDir really does cover the symlink fallback. My vote is to keep it: the reasoning is sound, it's the best-tested part of the PR, and withDirectory is hot well beyond generation.
Worth noting test-split:test-base runs pkg: "./...", so the new util/layercopy tests and TestChangeset did run in CI, not just locally.
Main asks are on the outerEnvFile commit: a regression test and a changie entry, plus one design question inline. Nothing blocking.
| if err != nil { | ||
| return nil, "", err | ||
| } | ||
| if inModule { |
There was a problem hiding this comment.
The rationale — resolving through the caller's client "would hand a module the caller's .env for any module source it can synthesize" — is already the behavior for local sources. LoadUserDefaults swaps the ctx to the non-module parent before calling this:
if src.Kind == ModuleSourceKindLocal {
localSourceClientMetadata, err := query.NonModuleParentClientMetadata(ctx)
ctx = engine.ContextWithClientMetadata(ctx, localSourceClientMetadata)
}So runningInsideModule sees the already-swapped metadata and returns false, and module code calling dag.moduleSource("/some/path") still gets the caller's .env (namespaced by module name). The guard only closes the dir/git-kind door.
Is that asymmetry intended, or is the local path a hole that wants the same treatment? Either way this is strictly better than the current 10s hang — just want to make sure the security story is the one you meant.
Also: this is the same check core/schema/git.go:607 does inline for host git credentials, which pairs it with a core.IsModuleDependencyResolution(ctx) escape hatch. Probably right to omit that here, but worth a word on why.
Separately — worth a .changes/unreleased/Fixed-*.yaml for this one? check-for-changelog is gated on the needs/changelog label so CI won't ask, but this is user-visible. And core/integration/workspace_compat_env_test.go:250 (TestOuterEnvFile) looks like the natural place to mirror this: it already pins the dir-kind + non-module-client case that has to keep working, so a sibling subtest calling the same thing from inside a module would pin the new branch (and the local-kind asymmetry above).
| if err := d.applyMetadataPath(realPath, src, opts); err != nil { | ||
| return "", false, err | ||
| } | ||
| d.markMaterialized(cleanRel(rel)) |
There was a problem hiding this comment.
This can mark a path that isn't a directory. If os.Mkdir above returns EEXIST and opts.ReplaceExisting is false, replaceCreateDir returns nil immediately without checking anything, and we fall through to here.
Reachable with an overlay dest, ReplaceExisting: false, and a whiteout in the upper: invisible in the merged view, so ensureExistingDir reports not-found and we land in createDir, then Mkdir gets EEXIST. The whiteout is now in materializedDirs, so a later materializeExistingDir returns success instead of "destination upper path %q exists and is not a directory", and materializeAncestors breaks its walk there — a descendant then fails with a bare ENOTDIR instead of the clear message.
Narrow (all four core/directory.go call sites set ReplaceExisting: true) and createDir already tolerated the non-dir before this PR, but the map propagates it now. Could mark only when we know it's a directory — Mkdir succeeded, or replaceCreateDir reports it actually replaced.
| // subtree stop re-stat'ing every ancestor. It holds an invariant relied on | ||
| // when walking ancestors: if a path is present, so are all of its parents. | ||
| // Directory removals drop the whole set; file removals cannot invalidate it. | ||
| materializedDirs map[string]struct{} |
There was a problem hiding this comment.
The invariant needs one more clause: nothing may mutate the write root outside the Copier for its lifetime. True today, but not stated — and there's already external mutation nearby. core/directory.go withChanges calls removeChangesetPaths(root, ...) (plain os.RemoveAll) between NewCopier and the first copier.Copy; it's safe purely because the map is still empty at that point.
Worth spelling out here or on NewCopier so a future reorder doesn't quietly poison the cache.
| return err | ||
| } | ||
| if err := os.RemoveAll(realPath); err != nil { | ||
| if err := c.dest.removeAll(realPath, !opts.ReplaceExisting); err != nil { |
There was a problem hiding this comment.
Correct, but worth flagging: with ReplaceExisting false this clears the entire materializedDirs map for every symlink, device node, and hardlink copied — same at lines 289, 310, 322. That's the engine/filesync/localfs.go:656 import path, so on a symlink-heavy tree (node_modules) the new ancestor cache gets discarded repeatedly and that path may see little of the win.
Not asking for a change now, just noting the fast path is effectively off there in case a cheaper invalidation is worth it later.
| // reorder a sequence like A, B, A, where the trailing A is what decides | ||
| // paths that A and B disagree on. | ||
| var lastDigest digest.Digest | ||
| appendBefore := func(before dagql.ObjectResult[*Directory]) error { |
There was a problem hiding this comment.
Two small things on this closure:
-
The old code distinguished
"before ID"from"other before ID", so a failure said which changeset it came from. That's gone, while theAsPatchloop just below still does"get patch for changeset %d: %w". Threading an index through, or dropping the closure for a loop overslices.Concat([]*Changeset{ch}, others), would restore it and shed the duplicated error-return boilerplate. -
lastDigeststarts as the zero digest, so a("", nil)fromContentPreferredDigestwould silently drop the first before directory and change the merge base. I tracedcontentPreferredDigestWithVisiting— it always sets either a digest or an error for a non-nil frame — so this isn't reachable today. An explicitfirstflag would make it unreachable by construction instead of by invariant.
These historically were taking a stored SpanContext from somewhere, pre-thesus. I suppose somewhere in Theseus these got converted into this form which looks harmless but actually effectively prevented any telemetry from being attached to that ctx. Signed-off-by: Alex Suraci <[email protected]>
* drop empty changesets early * compute paths in parallel * pass modified paths to `git diff` to avoid diffing entire trees * add a ton of instrumentation along the way Still more to go - we can probably avoid the octopus merge path entirely when we know that paths don't overlap. Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
Collapsing repeated before directories compared each digest against a lastDigest that started at the zero value, so a ContentPreferredDigest returning an empty digest would read as a repeat of nothing and drop the first before directory, silently changing the merge base of the whole merge. Nothing reaches that today: contentPreferredDigestWithVisiting only returns an empty digest for a nil frame, and Result.ContentPreferredDigest errors on a nil call frame before it can. That is an invariant two layers away holding up a silent wrong answer, so track whether a digest was actually recorded instead and make it unreachable by construction. Signed-off-by: Alex Suraci <[email protected]>
The comment on the module-code guard claimed the restriction was uniform, but LoadUserDefaults swaps in the non-module parent's client metadata for local sources before outerEnvFile runs, so runningInsideModule sees the already-swapped metadata and the guard never fires for them. Only dir- and git-kind sources are affected. Say so, and say why extending the local treatment to them would be a wider grant rather than the same one. Also record why the IsModuleDependencyResolution escape hatch that core/schema/git.go pairs with this same check has no analogue here: find-up from a nested client only ever timed out, so there is no working behavior to preserve. Signed-off-by: Alex Suraci <[email protected]>
The materializedDirs invariant only holds if the write root is mutated exclusively through the Copier for its lifetime, which the comment did not state. There is already one caller that reaches around it: withChanges removes changeset paths with a plain RemoveAll between NewCopier and the first Copy, safe purely because the set is still empty at that point. Spell out the assumption so a future reorder does not quietly poison the cache. Signed-off-by: Alex Suraci <[email protected]>
The instrumentation added to ComputePaths logs the computed paths unconditionally, but computePathsOnce returns a nil ChangesetPaths alongside its error, so any failure to compute paths dereferenced nil and panicked the engine instead of surfacing the error. Return early when the computation failed, and close the SpanStdio while here so the stream emits its EOF record rather than leaving the span's output open forever. Signed-off-by: Alex Suraci <[email protected]>
Limiting the patch diff to the changed paths passes them straight to git as pathspecs, which has three problems. A path starting with - is parsed as a flag and fails the diff outright; one starting with : is parsed as pathspec magic and silently drops the file from the patch; and the list is unbounded, so a large enough changeset overflows argv and fails where diffing the whole tree would have worked. Separate the pathspecs from the options with --, run git with GIT_LITERAL_PATHSPECS so nothing in a path is interpreted, and collapse the list to parent directories when it grows too large, giving up on it entirely once even those don't fit. Pathspecs only narrow work that is correct without them, so dropping them is always safe. Renamed paths no longer get an entry of their own either, since ChangesetPaths already records them under both names in Added and Removed. The no-op changeset shortcut now tests the paths directly rather than the pathspec list, which no longer means the same thing. Signed-off-by: Alex Suraci <[email protected]>
New returned an unexported type, so callers could build a job set with := but could not name one, which rules out factoring a configured pool out into a helper that hands it back. Rename it to Jobs; every existing caller infers the type and is unaffected. Signed-off-by: Alex Suraci <[email protected]>
The empty-changeset filter asked IsEmpty, which mounts both of a changeset's snapshots and walks them, and memoizes nothing. Every surviving changeset then had its paths computed from scratch moments later, so the filter cost a whole extra mount and walk each for the common case of a changeset that isn't empty. Filter on ComputePaths instead: it is memoized, the result is needed either way, and unlike IsEmpty it counts directory-only changes, so a changeset that only adds an empty directory is no longer dropped. Both fan-outs also spawned one goroutine per changeset with no ceiling, each holding mounts for its duration. Run them through a util/parallel pool capped at a fixed limit instead, and put the per-changeset AsPatch calls -- the expensive part, and previously a serial loop -- through the same pool. Signed-off-by: Alex Suraci <[email protected]>
Restore the task span around the git diff, which an earlier commit dropped by accident along with it the SpanStdio it scopes, and fix the three things that were wrong with it. The closure took an unnamed context, so the stdio and the command bound to the enclosing context instead: the git output was logged against the parent span and the task span was created empty, which is the opposite of the point. Name it and use it. Naming the span after the full argv put every pathspec in it, so the name grew without bound with the size of the changeset. Name it for the command and log the argv, where the detail belongs. Finally, git diff exits 1 whenever the trees differ, which is the normal case and is deliberately tolerated below. Returning it from the task ended the span in error for every patch that wasn't empty, so check the exit code inside the task and report success for it. Signed-off-by: Alex Suraci <[email protected]>
|
@TomChv Addressed the main points there - I'm skipping changie since it'd be re-arranging deck chairs on the Titanic, the change is more to help bridge the gap than an intentional feature. Pushed some more changes on top, and did a self-review + addressed things it found, so gonna go ahead and merge to unblock the rest of the stack. |
Semver prerelease ordering puts v1.0.0-0 below v1.0.0-beta.7, so the root module declared a looser requirement than its own e2e module. Match the e2e declaration. This still under-declares the real requirement — loading a dir-kind module source needs the outerEnvFile change from dagger/dagger#13745 — but that has no released version to point at yet, which is why the PR stays blocked on it landing; bump again once the release carrying it exists. Signed-off-by: Alex Suraci <[email protected]>
Semver prerelease ordering puts v1.0.0-0 below v1.0.0-beta.7, so the root module declared a looser requirement than its own e2e module. Match the e2e declaration. This still under-declares the real requirement — loading a dir-kind module source needs the outerEnvFile change from dagger/dagger#13745 — but that has no released version to point at yet, which is why the PR stays blocked on it landing; bump again once the release carrying it exists. Signed-off-by: Alex Suraci <[email protected]>
Engine-side changes needed before
generate-allcan be performant across a workspace with many modules. Split out from the 1.0 conversion work so it can be deployed first.The three groups below are independent, and they are not equally load-bearing — please read the caveat on the
layercopygroup before reviewing it.modulesource:outerEnvFilefrom module codeThis one is the point of the PR. It is motivated entirely by dagger/polyfill#6, which deletes 1023 lines by asking the engine for a module's generated-context changeset directly instead of round-tripping it through a nested privileged Go helper. That polyfill change is blocked on this commit.
innerEnvFilerefuses non-local sources "for safety", butouterEnvFilehad no such guard and unconditionally reached forhost.findUp(".env"). Module code has no host session, so loading a dir-kind module source from inside a module blocked until the context deadline and then failed withfailed to get requester session: context deadline exceeded.Workspace.moduleSourceproduces dir-kind sources, which made that whole API unreachable from module code — and it is the API that lets an SDK module generate without shelling out to a nested session.outerEnvFilenow returns empty when the caller is module code. Resolving it through the caller's client instead would also have worked, but that would hand a module the caller's.envfor any module source it can synthesize.This is the change most worth careful review. It changes when user defaults get loaded, and it is the only one here whose behavior isn't pinned by an existing test.
changeset: repeatedbeforedirectoriesMerging changesets first unions their
beforedirectories, onewithDirectoryper changeset. Changesets merged together are normally diffs taken against a common base, so those directories are usually the same directory repeated — merging one onto itself changes nothing but still walks the whole tree. A merge of N changesets paid N full-tree copies to produce what the first one already produced. This showed up directly in traces ofgenerate-allas a run of identicalwithDirectory(path: "", source: Host.directory(...))calls, one per module.Consecutive repeats are now collapsed, comparing content-preferred digests the same way changeset path computation already does. Only consecutive repeats are dropped: removing every repeat would reorder a sequence like
A, B, A, where the trailingAis what decides paths thatAandBdisagree on.layercopy: destination path resolution — and a caveatThese were tried first and had little to no effect on real
generate-allperformance. Happy to drop them from this PR if we'd rather not carry them.They came out of a CPU profile showing
Directory.withDirectoryat over half of engine CPU, with 88% of syscall time inlstat. The optimizations do what they claim in isolation, but a profile taken after deploying them showed total engine CPU down only ~27%, with the real cost sitting elsewhere — which is what led to the two changes above. They stand on their own as a large reduction in per-entry copy cost, andwithDirectoryis hot for plenty besides generation, but they are not what makesgenerate-allfast.Three commits, each measured against a new benchmark reproducing the shape the engine hits — a deep source tree copied onto a destination that already contains it, with
CopyDirContentsandReplaceExistingset.copyNoderesolved the write-root path twice per entry, once insideremoveForReplaceand again immediately after. The first result is now returned and reused.lstats every component, so ensuring one directory cost work quadratic in its depth, and every copied entry ensured its parent. The recursion was never necessary: the relative path being recursed on comes out ofrootPath, so it is already fully resolved and none of its ancestors can be a symlink.On the benchmark (2032 files, six levels deep):
lstatcalls over a fixed workload drop from 201,160 to 11,196.Testing
util/layercopyunit tests pass, including two added cases: materializing several levels of pre-existing overlay directories in one step (parent-first ordering), and the existing symlinked-destination-directory case, which covers the new resolved-parent fast path's symlink fallback.TestChangesetintegration suite passes in full, covering both callers ofmergeBeforeDirectories— the two-wayWithChangesetand the N-wayWithChangesets.Not measured
The benchmark and syscall numbers above are real and reproducible. The end-to-end effect on a large
generate-allrun is not measured here — that needs dagger/polyfill#6 and the corresponding dang-sdk change deployed together.🤖 Generated with Claude Code