Skip to content

Go SDK: skip codegen at runtime (phase 1) - #13028

Closed
eunomie wants to merge 22 commits into
dagger:mainfrom
eunomie:no-codegen-at-runtime-go
Closed

eunomie wants to merge 22 commits into
dagger:mainfrom
eunomie:no-codegen-at-runtime-go

Conversation

@eunomie

@eunomie eunomie commented Apr 24, 2026

Copy link
Copy Markdown
Member

What & why

Today, every dagger call (and any other runtime operation) re-generates Go
bindings inside a container before building the module. That's wasted work:
the generated files rarely change between two calls, but the user pays for
codegen every time.

This PR is the Go-SDK slice of a larger effort to stop doing that. After it
merges, Go module authors can commit their generated files (dagger.gen.go,
internal/dagger/) and opt out of runtime codegen entirely. The hot path
shrinks from codegen → go build → exec to just go build → exec.

How it works

Two independent changes, both needed to unlock the new path:

1. Consolidate type discovery into one codegen call.
The engine used to orchestrate two SDK calls per module (one to get the
module's types, one to generate bindings). That dual-call design made it
impossible for the SDK to skip codegen cleanly. We fold both phases into the
single codegen invocation the SDK already owns, so the engine has one
uniform entrypoint. This part introduces:

  • A shared cmd/codegen/schematool library so every SDK can merge its
    module-defined types into the GraphQL schema without re-implementing it.
  • An AST-based Go source scanner (cmd/codegen/generator/go/astscan) that
    extracts typedefs directly from .go files — no more container round-trip
    to discover them.

Side benefits:

  • The generated module entrypoint is back to a single binary with two clear
    paths — one for type discovery, one for function invocation. Easier to
    reason about and debug than the previous split-across-SDK-calls design.
  • Self-calls (modules that call themselves) no longer pay the runtime cost
    they used to. Type discovery for self happens once at codegen time; the
    entrypoint returns it directly, so there's no extra container call at
    runtime.

2. Let Go modules opt out of runtime codegen.
A new codegen.legacyCodegenAtRuntime field in dagger.json:

Value Behavior
absent / true Legacy: codegen runs on every dagger call.
false Go SDK trusts committed generated files; skips codegen at runtime. Codegen still runs on dagger init / dagger develop.

dagger init --sdk=go now writes legacyCodegenAtRuntime: false by default,
so new modules get the fast path out of the box. Existing modules are
untouched — nothing changes until they opt in.

Guardrail: automaticGitignore: true + legacyCodegenAtRuntime: false is
rejected, since the committed generated files must not be gitignored.

Scope

  • Go SDK only. Python, TypeScript, and other SDKs read the new field but
    ignore it — their runtime flow is unchanged.
  • No change to the GraphQL schema semantics or introspection JSON shape.
  • Follow-up PR will do the equivalent for the Python SDK.

What's in this PR

  • cmd/codegen/schematool/ — new shared schema-merge library + inspect-schema / merge-schema subcommands.
  • cmd/codegen/generator/go/astscan/ — new AST-based typedef scanner for Go sources.
  • core/sdk/go_sdk.go — Go SDK drops the moduleTypes path; short-circuits Runtime() when the module opts out of runtime codegen.
  • core/modules/config.go — new LegacyCodegenAtRuntime field + validation.
  • cmd/dagger/module.go — dagger init --sdk=go writes the opt-out by default.
  • core/integration/module_test.go — integration tests for both paths.
  • hack/designs/ — design docs and implementation plans.

Test plan

  • dagger init --sdk=go creates a module with legacyCodegenAtRuntime: false and no codegen container runs on dagger call.
  • An existing module (no legacyCodegenAtRuntime set) still runs codegen at runtime — no regression.
  • A module with automaticGitignore: true + legacyCodegenAtRuntime: false fails with a clear error.
  • Modules with self-calls work under the new path and skip the extra runtime call.
  • Go integration tests (core/integration/module_test.go) pass.

Comment thread core/sdk/go_sdk.go
Comment on lines +564 to +600
// requireGeneratedFiles ensures the module's committed generated
// files are present when the module has opted out of runtime codegen.
// If either the module's dagger.gen.go or internal/dagger/dagger.gen.go
// is missing, return a clear actionable error.
func requireGeneratedFiles(
ctx context.Context,
dag *dagql.Server,
contextDir dagql.ObjectResult[*core.Directory],
srcSubpath, modName string,
) error {
required := []string{
filepath.Join(srcSubpath, "dagger.gen.go"),
filepath.Join(srcSubpath, "internal", "dagger", "dagger.gen.go"),
}
for _, rel := range required {
var exists dagql.Boolean
err := dag.Select(ctx, contextDir, &exists,
dagql.Selector{
Field: "exists",
Args: []dagql.NamedInput{
{Name: "path", Value: dagql.NewString(rel)},
},
},
)
if err != nil {
return fmt.Errorf("check generated file %q: %w", rel, err)
}
if !bool(exists) {
return fmt.Errorf(
"module %q has codegen.legacyCodegenAtRuntime=false "+
"but required generated file %q is missing. "+
"Run `dagger develop` to regenerate.",
modName, rel)
}
}
return nil
}

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.

question: do we want this behavior? Good for the user, but meaning we have 2 extra calls just to check the files.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you make a quick benchmark just to see if that operation is heavy? If it takes less that 300ms we are fine

@@ -0,0 +1,968 @@
# Go SDK Skip Codegen at Runtime — Implementation Plan

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.

question: do we want to commit this file? This is the implementation plan. As much as I think the design doc is interesting, especially to allow to replicate it in other SDKs, the implementation plan I'm not sure at all.

@@ -0,0 +1,2375 @@
# moduleTypes Consolidation — PR 1 Implementation Plan

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.

question: same as for the other implementation plan, should we commit those or not?

@eunomie
eunomie force-pushed the no-codegen-at-runtime-go branch 2 times, most recently from 6183394 to 22f72dc Compare April 24, 2026 18:26
@eunomie
eunomie force-pushed the no-codegen-at-runtime-go branch 10 times, most recently from 1350485 to 8d97302 Compare May 4, 2026 13:45
@eunomie
eunomie force-pushed the no-codegen-at-runtime-go branch 3 times, most recently from 0c16636 to 19e4028 Compare May 5, 2026 12:17
eunomie added 13 commits May 6, 2026 15:27
Two design docs and their per-PR implementation plans, covering the
no-codegen-at-runtime effort:

- moduleTypes consolidation: remove the SDK moduleTypes entrypoint and
  fold type discovery into the SDK's codegen call.
- Go SDK skip-codegen-at-runtime: opt-in dagger.json flag
  codegen.legacyCodegenAtRuntime=false so the Go SDK trusts the
  committed dagger.gen.go + internal/dagger/** at module-load time.

Signed-off-by: Yves Brissaud <[email protected]>
Introduce a schema-manipulation library and two new codegen
subcommands (inspect-schema, merge-schema) usable by any SDK that
needs to reason about introspection JSON without depending on
language-specific tooling.

The schematool package exposes a small ModuleTypes shape (Objects,
Interfaces, Enums, Functions) and helpers to extract module-defined
types from an introspection JSON, merge an external module-types
JSON into the schema, and emit a focused subset for downstream
codegen.

Move the existing generate-typedefs command and its supporting
generate_typedef.go behind a //go:build legacy_typedefs tag (and
the matching main_legacy.go init), so it is no longer registered
on default builds. The legacy path can still be exercised for
parity comparison via -tags legacy_typedefs.

Signed-off-by: Yves Brissaud <[email protected]>
Introduce astscan, a go/parser + go/ast walker that extracts a
module's declared types (structs, interfaces, typed-const enums)
and functions into the language-agnostic schematool.ModuleTypes
shape. Type references are resolved against imports and the
introspection JSON; unresolved external types produce a clean
error.

Not wired into generate-module yet — the integration into the Go
codegen pipeline lands in the following commit.

Signed-off-by: Yves Brissaud <[email protected]>
Fold Phase-1 (source analysis) and Phase-2 (schema merge) into
generate-module so Go modules no longer need a separate
generate-typedefs pass. The AST-based scanner replaces the old
typedef-extraction path; schema merging happens in-process via
the schematool library.

The legacy packages.Load-based typedef path is retained behind a
//go:build legacy_typedefs tag (generate_typedefs_legacy.go) for
parity comparison and will be dropped once parity is confirmed.

Adds --legacy-typedefs and --self-calls flags to the codegen CLI
to enable opt-in to the legacy path or the experimental SELF_CALLS
feature respectively.

Signed-off-by: Yves Brissaud <[email protected]>
…spatch

Restore the runtime typedef-registration branch that generate-module
emitted before the moduleTypes SDK method was split out. The generated
invoke() dispatcher now handles parentName == "" by returning a
*dagger.Module built via dag.Module().WithObject(...) at runtime — the
same shape the engine expects when it falls back to the
empty-function-name path.

Restores TypeDefCode() methods on the parsed object / interface / enum
/ function / type-spec / sourceMap types so the generated bindings can
emit them at runtime, while keeping the newer TypeDef() runtime helpers
used by the legacy generate-typedefs path.

Prereq for dropping AsModuleTypes on the Go SDK: without this branch
the runtime returns 'unknown object' when the engine calls it to
materialise typedefs.

Signed-off-by: Yves Brissaud <[email protected]>
Go SDK now handles type discovery entirely within generate-module
(AST scan + schematool merge). AsModuleTypes returns nil,false so
the engine falls through to the Runtime + empty-function-name path
at asModule time — the same path that existed before moduleTypes
was introduced.

Drop the now-unused ModuleTypes implementation, the
goSDKExecMDDigest constant, and the imports it required.

The ModuleTypes interface and its engine-side dispatch remain in
place for module-SDKs (Python, TS, ...) which haven't migrated yet.
They will be deleted in the final cleanup PR once every SDK has
migrated.

Signed-off-by: Yves Brissaud <[email protected]>
Add a Skip'd parity test TestModuleSuite.TestGoCodegenPhase1Parity
which, when the two-build-tag harness is in place (PR 2), will
compare dagger.gen.go output between the default (astscan) and
legacy (packages.Load) paths and assert byte-identical results.

Stubbed here so the scaffold is visible in the codebase and the
PR-2 work item is explicit. No behavioral change.

Signed-off-by: Yves Brissaud <[email protected]>
Introduce codegen.legacyCodegenAtRuntime in dagger.json. The field
controls whether the SDK runs codegen during runtime operations
(dagger call, dagger functions). When explicitly false, the SDK
trusts the committed dagger.gen.go + internal/dagger files and
skips the runtime codegen pass. Codegen still runs on dagger init
and dagger develop.

Currently a structural addition only; the Go SDK wiring lands in
the following commit. Other SDKs read but ignore the field.

Validation rejects legacyCodegenAtRuntime=false combined with
automaticGitignore=true/unset (generated files must be committed).

Signed-off-by: Yves Brissaud <[email protected]>
Go SDK's Runtime() now branches on the module's
codegen.legacyCodegenAtRuntime config. When set to false, the SDK
trusts the committed dagger.gen.go + internal/dagger/**: the
runtime container mounts the module source as-is, runs go build,
and skips the codegen generate-module subprocess entirely. If the
required generated files are missing, Runtime() returns a specific
error telling the user to run dagger develop.

Codegen() is unchanged — it always runs codegen (that's what
dagger develop, dagger init and dagger install use). Only Runtime()
is affected.

Extract the VCS generated/ignored path lists into shared slices so
both branches stay in sync.

Signed-off-by: Yves Brissaud <[email protected]>
New Go modules opt out of runtime codegen by default. The init flow
post-processes the exported dagger.json to set
codegen.automaticGitignore=false and
codegen.legacyCodegenAtRuntime=false, so the generated files end up
committed and subsequent dagger call invocations skip the codegen
phase.

Other SDKs: unchanged — the flags are not written.
Existing modules upgrading via dagger develop: unchanged — the
flags are only written at init time. Migration is manual.

Signed-off-by: Yves Brissaud <[email protected]>
TestGoSDKSkipCodegenAtRuntimeOptIn: dagger init --sdk=go writes
the opt-in flags; dagger call on the resulting module succeeds
without re-running codegen.

TestGoSDKSkipCodegenAtRuntimeValidation: manually setting
legacyCodegenAtRuntime=false without automaticGitignore=false
produces the expected validation error at module load.

TestGoSDKSkipCodegenAtRuntimeMissingFiles: opt-in flag set but
dagger.gen.go removed from the module source produces a clear
'run dagger develop' error from Runtime().

All three tests land as t.Skip stubs with concrete follow-up notes,
matching the pattern used in TestGoCodegenPhase1Parity.

Signed-off-by: Yves Brissaud <[email protected]>
With Go modules now defaulting to legacyCodegenAtRuntime=false the
runtime path no longer auto-regenerates dagger.gen.go after a test
modifies main.go. Tests that previously relied on the implicit
runtime codegen pass now fail with errors like
'(*Test).<Method> undefined' before any develop-time codegen can
catch up.

Three classes of change land here:

- withModInitAt now runs dagger develop after writing the module
  source. Develop is invoked from inside the module dir (changing
  the container WORKDIR rather than using -m <dir>) so that nested
  dagger CLI sessions resolve "." against the module's WORKDIR
  and pick up the freshly written main.go. Add a parallel helper
  withModInitAtWithDaggerJSON for cases that also write a
  pre-baked dagger.json.

- Existing init+WriteFile+develop sequences across the integration
  suite are converted to the helper. Tests that update main.go
  after the helper call get an explicit dagger develop step. Tests
  with multi-module setups get develop calls in the right WORKDIR
  ordering.

- TestCall/TestArgTypes/module_args: the listing of a Go module's
  contextDirectory no longer includes .gitignore (automaticGitignore
  rides along with legacyCodegenAtRuntime=false) but does include
  the committed dagger.gen.go. Update the expected entry sets.

Verified: TestCall, TestShell, TestModule* all green under the new
runtime path.

Signed-off-by: Yves Brissaud <[email protected]>
Lift parsePragmaComment from templates/modules.go into a new
cmd/codegen/generator/go/pragma package so the AST-scan codepath
can read +optional / +default through the same parser as the
legacy packages.Load templates. The template-side function
becomes a one-liner that delegates.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added 4 commits May 6, 2026 15:27
walkFuncType now scans each parameter's leading and trailing
comments through the shared pragma parser and applies the
directives to the emitted FuncArg:

- +optional strips the outer NON_NULL on the type ref.
- +default=<json> populates DefaultValue and implies optional,
  matching the engine's FunctionArg semantics.

Without this, modules with self-calls enabled lost the optional
nature and default value of their own functions' arguments — the
generated bindings wrongly required every parameter and never
emitted the per-field <Type><Field>Opts struct, breaking calls
like dag.Test().ContainerEcho(dagger.TestContainerEchoOpts{...})
and dag.Test().ContainerEcho() (no-arg form).

A new pragma_args testdata fixture covers +optional alone,
+optional + +default="..." (string), and +default=42 (int).

Signed-off-by: Yves Brissaud <[email protected]>
moduleDirectives now emits both @sourceModuleName(name:) (kept
for engine compatibility and the alreadyMergedFor idempotency
check) and @sourcemap(module:). The latter is what codegen's
file-split relies on — Schema.DependencyNames, Include and
Exclude all read the sourceMap directive — so its presence is
what causes a self-call module's own types to land in their own
internal/dagger/<module>.gen.go file rather than being mixed
into the main internal/dagger/dagger.gen.go.

Update the schematool fixture expectations so the new directive
is part of the asserted output for object, interface and enum
merges.

Signed-off-by: Yves Brissaud <[email protected]>
The integration-test refactor (da72cd5) added explicit dagger develop
calls inside three TestLegacy cases that deliberately pin the module's
engineVersion to a pre-release value (v0.11.9, v0.13.7) to exercise
legacy schema fallbacks. Those develop calls do not pass --compat, so
the CLI's --compat default (modules.EngineVersionLatest) silently
upgrades the module to the current engineVersion and regenerates
dagger.gen.go against the current schema. Subsequent build steps then
fail because the test's main.go is written against the legacy schema
(e.g. Container.Terminal returning *Terminal, not *Container).

Pass --compat=skip on those three develop calls so the engineVersion
in dagger.json is preserved through codegen. Verified:
  - TestLegacy/TestLegacyTerminal/{from_cli,from_module}: legacy
    Terminal type round-trips through the legacy v0.11.9 view.
  - TestLegacy/TestContainerAsService/use_entrypoint_by_default:
    legacy v0.13.7 entrypoint-inheritance behavior is preserved.

Signed-off-by: Yves Brissaud <[email protected]>
hostDaggerCommand wires up a dagger CLI invocation but uses
exec.Command, so the spawned process has no link to the test's ctx.
When a dagger sub-CLI hangs (e.g. waiting on a runtime that's stuck
in module load), the test only escalates signals via cleanupExec at
test cleanup time — which fires when the package's go test -timeout
expires, not when the test's own deadline does. A single hung dagger
invocation can therefore wedge the whole core/integration package
for 30 minutes.

Switch to exec.CommandContext so ctx cancellation (test deadline,
SIGINT propagation, etc.) brings the subprocess down promptly. The
existing cleanupExec SIGINT/SIGTERM/SIGKILL escalation still runs
on test cleanup as a defensive backstop.

Signed-off-by: Yves Brissaud <[email protected]>
@eunomie
eunomie force-pushed the no-codegen-at-runtime-go branch from 2efa5ea to f28fbe2 Compare May 6, 2026 13:28
eunomie added 5 commits May 6, 2026 15:54
…Pragmas

The nakedret linter flagged two naked returns in parseParamPragmas
because the function body is over the 30-line threshold. Use explicit
return values instead for clarity.

Signed-off-by: Yves Brissaud <[email protected]>
The TestTelemetry/TestGolden/fail-effect output now renders the
parent .failEffect span as DotEmpty (○) instead of IconSuccess (✔).
This aligns with how pending/incomplete spans are surfaced when a
child effect fails after the parent returns.

Signed-off-by: Yves Brissaud <[email protected]>
…te main.go

With the no-codegen-at-runtime opt-in default for new Go modules
created via dagger init --sdk=go, runtime invocations no longer
re-run codegen. TestDaggerInit cases that overwrite main.go after
init must now run dagger develop before calling the module so
dagger.gen.go matches the freshly written sources.

- name_defaults_to_source_root_dir_name: switch the develop call
  to develop -m coolmod since the module lives in /work/coolmod
  and the container WORKDIR is /work.
- init_with_absolute_path: insert a develop step (run inside the
  module dir via WithWorkdir) before dagger call.

Signed-off-by: Yves Brissaud <[email protected]>
With the no-codegen-at-runtime opt-in default for new Go modules,
overwriting main.go after dagger init leaves dagger.gen.go stale.
The runtime build then fails compiling the legacy wrappers from the
old scaffold. Insert dagger develop after the WithNewFile main.go
calls in:

- TestConstructorArgs: develop after the test module's main.go is
  written, before dagger functions checks the module compiles.
- TestPersistence/cohexist_with_a_module_implementation/go: develop
  the .dagger module after the new main.go is written, before the
  client install loads the module's API.

Signed-off-by: Yves Brissaud <[email protected]>
The TestCustomSDK and TestContextDefaultsToSourceRoot patterns build a
Go module (cool-sdk) and then load it as another module's SDK. The
chicken-and-egg between dagger-init-go-opt-in (which writes
legacyCodegenAtRuntime=false on every dagger init --sdk=go) and
loading that module across session boundaries causes 'invalid SDK:
coolsdk' failures: the test module's dagger develop loads cool-sdk
once, but a subsequent dagger call re-resolves the SDK and the runtime
build of cool-sdk no longer sees a usable dagger.gen.go.

Add withForceLegacyCodegenAtRuntime(path) to strip the field from the
indicated dagger.json, and apply it after every withModInit call in
the cool-sdk-style tests so cool-sdk reverts to runtime codegen
(matching legacy behavior).

Signed-off-by: Yves Brissaud <[email protected]>
@eunomie
eunomie force-pushed the no-codegen-at-runtime-go branch from 5bc1abb to a1067a2 Compare May 6, 2026 19:14
@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@github-actions

Copy link
Copy Markdown
Contributor

This PR was closed because it has been stalled for 7 days with no activity.

@github-actions github-actions Bot closed this May 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants