Skip to content

feat: ModuleSource.generateLocalDependencies - #13715

Merged
TomChv merged 1 commit into
mainfrom
feat/module-source-generate-local-dependencies
Jul 27, 2026
Merged

TomChv merged 1 commit into
mainfrom
feat/module-source-generate-local-dependencies

Conversation

@TomChv

@TomChv TomChv commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

Adds ModuleSource.generateLocalDependencies(workspace), which generates a module's transitive local dependency closure, leaf-first, so a set of inter-dependent local modules can be codegen'd in the correct order.

Problem

TOML modules build from committed files and never runtime-codegen, and module loading is recursive (asModule -> loadDependencyModules). So editing several inter-dependent local modules at once deadlocks: to codegen app-py (python -> lib-go, go) the engine loads lib-go; if its committed bindings are stale they can't be repaired at load, so codegen fails. lib-go must be generated first, but the generator scheduler has no ordering, no staged visibility, and no cross-SDK view.

Approach

generateLocalDependencies(workspace) walks the module's local dependency closure leaf-first and, for each dependency, runs the workspace's SDK generators against a workspace scoped to that dependency (its path as the working directory) with the already-generated dependencies overlaid. It folds each dependency's changeset into an accumulator and returns it; the module's own generator overlays that before generating itself. Ordering is introduced locally, per module, on demand — the global generator scheduler stays concurrent.

The constructed workspace reaches the SDK @generate functions through a new GeneratorGroup.WorkspaceOverride, applied to the context in Run and read by loadWorkspaceArg in place of the ambient currentWorkspace. It is opt-in via an internal withWorkspace arg on Workspace.generators, so the ordinary dagger generate flow is unchanged. Cache-safe: the injected workspace lands in each generator's call ID.

Naming: the new per-dependency scoping setter is Workspace.withWorkdir (mirrors Container.withWorkdir, per review). The pre-existing Workspace.cwd getter is left as-is — renaming it to workdir touches the go/typescript SDK dang modules that read ws.cwd, so it's a coordinated follow-up.

Design: hack/designs/module-source-generate-local-dependencies.md.

Engine changes

File Change
core/schema/modulesource.go generateLocalDependencies(workspace) field + handler (leaf-first closure, per-dep scoped/overlaid workspace, fold changesets). Gated AfterVersion("v1.0.0-0")
core/generators.go GeneratorGroup.WorkspaceOverride — applied to ctx in Run, persisted, attached as a dependency result
core/schema/workspace.go internal withWorkspace arg on generators() -> sets the override; new withWorkdir setter
core/modfunc.go loadWorkspaceArg returns the override first (bypasses the module-function guard)
core/workspace.go ContextWithWorkspaceOverride / WorkspaceOverrideFromContext

Checklist

  • Design
  • generateLocalDependencies engine API + schema (version-gated; regenerated goldens)
  • SDK @generate wiring to call it — go + typescript (external SDK repos); python is a follow-up
  • E2E validation (mixed-SDK a -> b -> c closure against a dev engine) + TestLocalDepClosureLeafFirst unit test

Closes #13706. Part of #13662.

PR chain

The two SDK PRs depend on this engine PR. Related: #13727 (asSDK explicit workspace) is now ✅ merged into main, and its workspace arg landed optional — so the SDK-side asSDK-workspace changes (go-sdk#14 + TS/Python follow-ups) can merge independently of this chain.

@TomChv

This comment was marked as outdated.

@TomChv
TomChv force-pushed the feat/module-source-generate-local-dependencies branch from 5340af2 to 077c113 Compare July 23, 2026 14:16
@kpenfound

Copy link
Copy Markdown
Contributor

Quick review while this is still WIP:

Main change requested: scope each dep's generation to its owning SDK

generateOneLocalDependency currently runs the workspace's entire generator group per dependency. That relies on every foreign SDK's @generate no-op'ing under a cwd that isn't theirs (unenforced, spread across three SDK
repos), burns a container run per irrelevant SDK per dep, and bloats each dep's cache key with N-1 unrelated generators.

The workspace config already declares ownership: [[modules..as-sdk.modules]] entries (ModuleEntry.AsSDK.Modules[].Path, core/workspace/config.go) map workspace-relative module paths to their SDK module. So:

  1. Build a path → SDK module name map from the config once, up front.
  2. Look up each dep's SourceRootSubpath (clean both sides before comparing).
  3. Pass the owning name as include: alongside withWorkspace: — filterGeneratorsByInclude already matches bare module names against the reparented generator tree, so this is exactly the dagger generate dagger-go-sdk
    path. No new filtering plumbing needed.

Open decision: what to do when a dep's path isn't claimed by any as-sdk.modules entry — loud error (actionable config-hygiene signal, avoids the silent-empty-changeset → confusing downstream stale-bindings failure) vs.
silent skip (tolerant of hand-authored modules and partial configs). Either is defensible; whichever you pick, a slog line on skip would keep it debuggable.

Bugs to fix

  • Root-module receiver generates nothing (moduleSourceGenerateLocalDependencies): the srcPath != "" && srcPath != "." guard skips dependency re-resolution for a synthetic source at the workspace root, and a root-level
    module with local deps is a real case. Re-resolve for the root path too (e.g. always re-resolve when Dependencies is empty).
  • withCwd accepts escaping paths: cleanWorkspaceRelPath is just filepath.Clean, so ../.. and absolute paths land in Cwd unchecked. Since withCwd is public schema surface, reject absolute paths and anything cleaning to a
    ../ prefix.

Minor

  • localDepClosureLeafFirst silently depends on workspace root == repo root for SourceRootSubpath to be workspace-relative — a safe assumption per team convention, but worth a one-line comment since the dedup and reroot
    logic both lean on it.
  • Cycle back to the receiver would include src in its own closure (src's key is never seeded into visited). Almost certainly unreachable given load-time cycle detection (ErrCacheRecursiveCall), but seeding it is one
    line.
  • generateOneLocalDependency's overlay bool param is redundant with acc.Self() != nil.

Tests

Fine to defer E2E to the SDK-wiring phase per the checklist, but localDepClosureLeafFirst is pure and cheap to unit-test now (diamond dedup, leaf-first order, git-skip). Worth adding before this leaves WIP.

@TomChv
TomChv force-pushed the feat/module-source-generate-local-dependencies branch from e5b3881 to def29c4 Compare July 24, 2026 11:13
@TomChv

TomChv commented Jul 24, 2026

Copy link
Copy Markdown
Member Author

Thanks @kpenfound — all applied in afad187.

Main change — scope each dep to its owning SDK: done. Build a path → SDK module name map from [[modules.<name>.as-sdk.modules]] (via readWorkspaceConfig) once up front, look up each dep's cleaned SourceRootSubpath, and pass include:[<sdk-name>] alongside withWorkspace: — no new filtering plumbing, exactly the dagger generate <sdk-name> path.

  • Open decision (unclaimed dep): went with skip + slog.Warn rather than a hard error — keeps it tolerant of partial/hand-authored configs; if the dep is genuinely needed, the dependent's load failure surfaces it, and the warning is the breadcrumb.

Bugs:

  • Root-module receiver: now re-resolves whenever Dependencies is empty (covers SourceRootSubpath ""/".").
  • withCwd: rejects absolute paths and anything cleaning to a ../ prefix.

Minors:

  • Seeded the receiver's key into visited (cycle guard).
  • Extracted a generic leafFirstClosure; localDepClosureLeafFirst is now a thin wrapper.
  • Dropped the redundant overlay bool (derived from acc.Self() != nil).
  • Added the workspace-root == repo-root note on localDepClosureLeafFirst.

Tests: added TestLocalDepClosureLeafFirst — leaf-first chain (excludes receiver), diamond dedup, git-skip, empty.

Re-validated E2E against a dev engine on the a → b → c (go → go → ts) repro: cd b, cd c (transitive), and the workspace root all ✔ pass — root produces a+b+c at their correct paths with no changeset conflict and no unmanaged-dep warnings.

@TomChv

TomChv commented Jul 24, 2026 •

Copy link
Copy Markdown
Member Author

go:generate-dagger-runtimes Fails but I tried : dagger --x-release=9e860eaa45dbcb4d216d85218b562f498fe803b8 generate go:generate-dagger-runtimes with the engine version used in the CI and I got no changes to apply...
I tried also with main, I'm not sure how to handle that

Comment thread core/schema/workspace.go Outdated
Args(
dagql.Arg("changes").Doc("Changes to apply."),
),
dagql.NodeFunc("withCwd", s.withCwd).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like this should mirror withWorkdir on Container 🤔

Maybe we should do Workspace.cwd => Workspace.workdir too? Wouldn't block this PR on that since we've got enough to coordinate, but in the long run it feels weird to have different terminology for the same concept

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on mirroring Container.withWorkdir. Renamed the new setter withCwd → withWorkdir (f736136100).

Left the pre-existing Workspace.cwd getter (and its ~39 doc mentions) as-is for now: renaming it to workdir breaks the ws.cwd reads in 4 SDK dang modules (go-sdk go-sdk.dang/mod.dang, typescript-sdk typescript-sdk.dang/mod.dang), which is the coordination you didn't want to block on. So there's a temporary withWorkdir-sets / cwd-reads asymmetry that a follow-up can resolve atomically across engine + SDKs. I'll track that.

@TomChv
TomChv force-pushed the feat/module-source-generate-local-dependencies branch 3 times, most recently from f3a271c to 245624e Compare July 27, 2026 11:50
@TomChv
TomChv marked this pull request as ready for review July 27, 2026 11:50
@TomChv
TomChv requested review from a team as code owners July 27, 2026 11:50
Adds ModuleSource.generateLocalDependencies(workspace), which generates a
module's transitive local dependency closure leaf-first, so a set of
inter-dependent local modules can be codegen'd in the correct order.

TOML modules build from committed files and never runtime-codegen, and
module loading is recursive. Editing several inter-dependent local modules
at once therefore deadlocks: to codegen a module the engine loads its
dependencies, and stale committed bindings can't be repaired at load time.
generateLocalDependencies walks the closure leaf-first and, for each
dependency, runs the workspace's SDK generators against a workspace scoped
to that dependency (its path as the working directory) with the
already-generated dependencies overlaid, folding each changeset into an
accumulator. The module's own generator overlays that before generating
itself. Ordering is introduced locally, per module, on demand; the global
generator scheduler stays concurrent.

The constructed workspace reaches the SDK @generate functions through a new
GeneratorGroup.WorkspaceOverride, applied to the context in Run and read by
loadWorkspaceArg in place of the ambient currentWorkspace. It is opt-in via
an internal withWorkspace arg on Workspace.generators, so the ordinary
dagger generate flow is unchanged.

Engine changes:
- core/schema/modulesource.go: generateLocalDependencies(workspace) field +
  handler (leaf-first closure, per-dep scoped/overlaid workspace, fold
  changesets), gated AfterVersion("v1.0.0-0")
- core/generators.go: GeneratorGroup.WorkspaceOverride
- core/schema/workspace.go: internal withWorkspace arg on generators(); new
  withWorkdir setter
- core/modfunc.go: loadWorkspaceArg returns the override first
- core/workspace.go: ContextWithWorkspaceOverride / WorkspaceOverrideFromContext

Design: hack/designs/module-source-generate-local-dependencies.md

Closes #13706. Part of #13662.

Signed-off-by: Tom Chauveau <[email protected]>
@TomChv
TomChv force-pushed the feat/module-source-generate-local-dependencies branch from 245624e to 0c1ca57 Compare July 27, 2026 12:09
@TomChv
TomChv requested review from tiborvass and vito July 27, 2026 12:11

@vito vito left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some nits, nothing blocking - the withWorkdir thing is a cheap clean-up though if you want to get it out of the way, the rest is mostly "hey my PR did this too but in some other way" which doesn't make sense to block on (I can just address it in my own PR).

Comment on lines +3029 to +3046
for _, dep := range deps {
depPath := dep.Self().SourceRootSubpath
depChanges, err := s.generateOneLocalDependency(ctx, dag, workspace, depPath, acc, owners)
if err != nil {
return res, fmt.Errorf("generate local dependency %q: %w", depPath, err)
}
if depChanges.Self() == nil {
continue // dependency not managed by any SDK; skipped with a warning
}
if acc.Self() == nil {
acc = depChanges
continue
}
acc, err = mergeChangesets(ctx, dag, acc, depChanges)
if err != nil {
return res, fmt.Errorf("merge local dependency %q changes: %w", depPath, err)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: would be nice to do this in parallel, but I guess that's complicated when there are dependencies between them; you'd need DAG-derived grouped parallelism of some sort

Field: "generators",
Args: []dagql.NamedInput{
{Name: "include", Value: dagql.Opt(dagql.ArrayInput[dagql.String]{dagql.String(owner)})},
{Name: "withWorkspace", Value: dagql.Opt(dagql.NewID[*core.Workspace](wsDID))},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: what is this withWorkspace argument doing? How does it compare to the Workspace it's being called against? 🤔 Trying to sus out why we can't just call generators against it. I ran into something kind of similar in #13635 and resolved it by storing the BoundWorkspace on GeneratorGroup (and related): f454788#diff-9623ae30098c2cd5d35ce1d7cd378ef0b10344322868e5de6434c2d30fbcf2c0 - wondering if the same approach would have solved this.

(Not blocking though if so, I can clean it up in my PR.)

Comment thread core/schema/workspace.go
}, nil)
}

func (s *workspaceSchema) withWorkdir(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: technically if I do Workspace.withWorkdir("a") and then withWorkdir("b") that should give me a/b to be consistent with Container. Right now it gives you b. (If I withWorkdir("/b") that would yield /b)

Comment thread core/generators.go
@@ -90,6 +90,14 @@ type GeneratorGroup struct {
// workspace.generators().run()) would execute in the calling module's runtime
// client, where workspace auto-injection is disabled.
WorkspaceClientID string `json:"workspaceClientID,omitempty"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Continuing the note from before, just for context - in my PR I got rid of WorkspaceClientID in all these places, since it's just an inferior form of storing the entire BoundWorkspace which stores any ClientID it depends on anyway (if any)

Comment thread core/workspace.go
// a workspace's generators against a scoped/overlaid workspace the engine
// constructed — e.g. ModuleSource.generateLocalDependencies staging a
// dependency's codegen before generating the dependent.
func ContextWithWorkspaceOverride(ctx context.Context, ws dagql.ObjectResult[*Workspace]) context.Context {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haha OK yeah we both ended up doing this style of solution - my PR also introduced WorkspaceToContext/WorkspaceFromContext, only it was LLM-motivated and not transitive-codegen-motivated.

@TomChv

TomChv commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

Thanks for the review, I let you take care of these nits in your follow up so I can continue my work on SDK

@TomChv
TomChv merged commit da3f970 into main Jul 27, 2026
87 checks passed
@TomChv
TomChv deleted the feat/module-source-generate-local-dependencies branch July 27, 2026 14:26
@TomChv

TomChv commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

Validation report from testing the two SDK PRs that consume this API (dagger/go-sdk#12, dagger/typescript-sdk#12) against --x-release=da3f97055661a3104e5e1ebce9d79d6329304e24.

generateLocalDependencies fails on local dependency chains of 4+ modules whenever a Go module is in the closure. Both SDK PRs are blocked by it. The feature itself works — cross-SDK bindings generate correctly at shallower depths.

Failure

generate local dependency ".dagger/modules/c": generate local dependency ".dagger/modules/b":
generate local dependency ".dagger/modules/a": apply ours patch:
git [apply --allow-empty /tmp/dagger-mountXXX/.dagger-patch]: exit status 1:
error: .dagger/modules/a/.gitattributes: already exists in working directory
error: .dagger/modules/a/dagger-module.toml: patch does not apply
error: .dagger/modules/b/.dagger/modules/a/.gitattributes: already exists in working directory   <-- nested
error: .dagger/modules/b/.dagger/modules/a/go.mod: already exists in working directory           <-- nested
error: .dagger/modules/b/internal/dagger/a.gen.go: already exists in working directory

Two distinct symptoms: doubly-prefixed paths (b/.dagger/modules/a/… — a staged inside b) and duplicate application (already exists / patch does not apply).

Minimal repro — 4 plain Go modules, no TypeScript needed

mkdir -p repro/.dagger/modules/{a,b,e,f} && cd repro && git init -q   # .git is required
for m in a:. b:a e:b f:e; do
  n=${m%%:*}; dep=${m##*:}
  printf 'package main\n\ntype %s struct{}\n' "$(echo $n | tr a-z A-Z)" > .dagger/modules/$n/main.go
  { echo "name = \"$n\""; echo 'engineVersion = "v1.0.0-beta.8"'; echo; echo '[runtime]'; echo '  source = "go"'
    [ "$dep" != "." ] && { echo; echo '[[dependencies]]'; echo "  name = \"$dep\""; echo "  source = \"../$dep\""; }
  } > .dagger/modules/$n/dagger-module.toml
done
{ echo '[modules.dagger-go-sdk]'; echo 'source = "github.com/dagger/go-sdk@main"'; echo
  for m in a b e f; do echo "[modules.$m]"; echo "source = \".dagger/modules/$m\""; echo; done
  echo '[modules.dagger-go-sdk.as-sdk]'; echo 'name = "go"'; echo
  for m in a b e f; do echo '[[modules.dagger-go-sdk.as-sdk.modules]]'; echo "path = \".dagger/modules/$m\""; echo; done
} > dagger.toml

dagger generate --no-apply    # -> apply ours patch: ... already exists in working directory

Dropping f (3-module chain a<-b<-e) makes it pass — the boundary is a closure of 3+ dependencies.

Bisect matrix

Chain (leaf←…←top) SDKs Modules Closure size Result
a←b Go 2 1 ✅
a←b←e Go 3 2 ✅
a←b←e←f Go 4 3 ❌
c←d TS 2 1 ✅
c←d←g←h TS 4 3 ✅
a←c Go→TS 2 1 ✅
a←b←c Go,Go→TS 3 2 ✅
a←c←d←g Go→TS,TS,TS 4 3 ❌
a←b←c←d Go,Go→TS,TS 4 3 ❌

Trigger: closure size ≥3 with at least one Go module anywhere in the chain. Pure-TS chains are immune at the same depth; cross-SDK is not required (pure Go reproduces it).

Root-cause hypothesis

In moduleSourceGenerateLocalDependencies (core/schema/modulesource.go:3024-3046) the accumulator acc is root-relative, and each iteration passes it to generateOneLocalDependency → scopedStagedWorkspace (core/schema/modulesource.go:3253), which does:

withWorkdir(cwd = depPath)   // workdir becomes .dagger/modules/b
withChanges(acc)             // acc is workspace-root-relative

If withChanges resolves paths against the workdir rather than the workspace root, a root-relative acc entry .dagger/modules/a/go.mod lands at .dagger/modules/b/.dagger/modules/a/go.mod — exactly the nesting in the error. The mis-rooted copies then collide with the correctly-rooted ones on the next mergeChangesets/apply, which is why it only surfaces once acc is non-empty for two consecutive iterations (closure ≥3; the first dep runs with acc == nil and skips withChanges entirely).

Swapping the order (withChanges before withWorkdir), or re-rooting acc relative to cwd, is where I'd look first. Note this is the same root-relative-changeset-applied-at-cwd class as dagger/eslint#12 and dagger/biomejs#2.

What works — please don't regress it

  • Cross-SDK closure generation is correct where it completes: a TS module gets real bindings for a Go dependency (c/sdk/b.gen.ts, c/sdk/a.gen.ts), and Go gets b/internal/dagger/a.gen.go.
  • The "ephemeral dep codegen cancels out" property holds in every passing case — changesets contain only each module's own files, never staged dependency artifacts. No leakage observed.

Unrelated footgun spotted

A workspace without .git silently reports no changes to apply and dagger generate -l lists zero generators — no error, no warning. Pre-existing, but it produces a convincing false negative.

@TomChv

TomChv commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

Root-caused and fixed — thanks for the thorough report and bisect, they pinned it exactly. The fix is entirely in dagger/go-sdk#12 (14fdae2); no engine change was needed.

Not the engine's withChanges rooting. I checked that path — Workspace.withChanges applies workspace-root-relative (via overlayEdit's sparse host base rooted at .), so a root-relative acc entry does not land under the cwd there.

Actual cause: the Go SDK's @generate folded ws.changes back into its result. generate assembled the changeset as ws.changes.withChangesets(changes) (introduced in go-sdk#13 to parallelize + fix a "no changes" bug). When the engine's generateLocalDependencies invokes that generator per-dependency, the workspace it passes already has the leaf closure staged, so ws.changes is the accumulator acc. Folding it back in re-included the staged closure, producing both symptoms:

  • Doubly-prefixed paths — the engine re-rooted the re-included acc under the dependent's path → b/.dagger/modules/a/….
  • Duplicate application — go-sdk's own octopus-merge collided that staged closure with the freshly generated, overlapping files → apply ours patch: … already exists.

This is exactly why pure-TS was immune: the TS SDK's generateAll reduces over pws.fork and never folds ws.changes — so the staged closure never re-enters.

Fix (go-sdk#12): fold each module's changes onto pws.fork.changes (an empty changeset) instead of ws.changes — a one-expression diff that keeps go-sdk#13's parallel map + {{isEmpty}} force intact, so its parallelism and "no changes" fix are preserved.

Validated against a dev engine on both failing shapes from your matrix:

Chain Result
a←b←c←d (Go, Go→TS, TS — closure 3) ✅ 0 errors, 0 nested leaks, cross-SDK bindings correct (c/sdk/b.gen.ts, d/sdk/c.gen.ts, b/internal/dagger/a.gen.go)
a←b←e←f (pure Go — closure 3) ✅ 0 errors, 0 nested leaks, leaf-first bindings correct

Real apply lands all files at the right paths with 0 nested-leak dirs, and a second run reports no changes to apply (idempotent). The "what works — please don't regress" properties all hold.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

New API: ModuleSource.GenerateLocalDependencies

3 participants