Skip to content

SDK: expose module type definitions - #10584

Merged
eunomie merged 60 commits into
dagger:mainfrom
eunomie:moduleTypeDefs
Oct 15, 2025
Merged

eunomie merged 60 commits into
dagger:mainfrom
eunomie:moduleTypeDefs

Conversation

@eunomie

@eunomie eunomie commented Jun 13, 2025 •

Copy link
Copy Markdown
Member

Note

This has been extracted and cleaned from #10475
This is a first step to #10336 and #8030

The main purpose of this PR is to allow SDKs to expose the module type definitions on a specific function.

This is a mandatory step to unlock the ability for modules to self invoke themselves. This pull request contains the ability to self call themselves, but it's experimental as it doesn't support all the cases.

Self Call Example

func (m *MyModule) ContainerEcho(
	// +optional
	// +default="Hello Self Calls"
	stringArg string,
) *dagger.Container {
	return dag.Container().From("alpine:latest").WithExec([]string{"echo", stringArg})
}

func (m *MyModule) Print(ctx context.Context, stringArg string) (string, error) {
	return dag.MyModule().ContainerEcho(dagger.MyModuleContainerEchoOpts{
		StringArg: stringArg,
	}).Stdout(ctx)
}

func (m *MyModule) PrintDefault(ctx context.Context) (string, error) {
	return dag.MyModule().ContainerEcho().Stdout(ctx)
}

In this example print function will call container-echo through the engine instead of directly.
This also allows to use directives like optional and default as you can see in print-default. This is something not doable by calling the function directly.

moduleDefs

The PR introduces a new moduleDefs method SDK modules can implement.

Without this PR, the container returned by moduleRuntime is called in two different ways:

  • with an empty string for parent name: the engine is asking for the type definition of the module
  • with a parent name: the engine is invoking a function defined in the module

In a module using the Go SDK for instance, this is done in the generated invoke function you can find in dagger.gen.go that is used at the entrypoint of the module container runtime. The invoke code looks like:

switch parentName {
        case "MyModule":
                // invoking module's functions
        case "":
                // code that generates the type definition
                return dag.Module()....
}

The idea of moduleDefs is to split those two responsibilities.:

  • when the engine used to call the runtime container with an empty parent name, the engine will call moduleDefs that ultimately returns a dagger.Module object (similar to what is performed inside the container when called with an empty function name)
  • when the engine used to call the runtime container with a parent name, in order to invoke a module's functions, the container from moduleRuntime will be executed

Implementation

The moduleDefs function, exposed by the SDK, needs to be executed on behalf of the module we are loading. This allows to use the right engineVersion for instance.
To do that, the moduleDefs is constructed the same way than the moduleRuntime function:

moduleDefs(
  modSource: ModuleSource!
  introspectionJSON: File!
  outputFilePath: String!
): Container!

This function takes the module source, the introspection JSON as well as a file path to write the output.
And the function returns a Container with a defined entrypoint.
The entrypoint will be called by the engine, with a specific set of parameters to run it on behalf of the module (as the module is not yet loaded those internal parameters are required).

When the moduleDefs is called, it must write, in JSON, the ID of the module representing the different types exposed by the module.

A pseudo code version could be like:

exposedTypes := dag.Module().WithObject(dag.TypeDef().WithObject()...)
json.WriteToFile(outputFilePath, exposedTypes.ToJSON())

The Engine will then read this outputFilePath file to load the module with the exposed types.

Introspection JSON

Some SDKs might require to generate Dagger types before to be able to generate the types exposed by a module.
So it requires an introspection JSON to be available.
But then the module runtime needs a new introspection JSON extended with the exposed types.

The flow is the following when loading a module:

  • get the introspection JSON based on the current types
  • call moduleDefs with this introspection JSON
  • append returned types to the module (to reference itself) -> only if self calls are enabled
  • call moduleRuntime with a new introspection JSON based on the extended types
    • the container generated by moduleRuntime will be synced so the cache is resolved, even if the container will be called only later when invoking a function
    • this is a need for Go modules that requires a specific socket that is closed between the typedefs call and the invocation

If a SDK has already access to the default types (the module and typedefs types) because of the generated files are already part of the SDK or because they are published in a library that can be used (that's not yet the case for Java) then the introspection JSON on moduleTypeDefs can be safely ignored.

Feature Flag / Compatibility

Self Calls are not enable by default. This means the SDKs must still work with the current way of doing, through runtime container. And in addition the new way with moduleTypeDefs for self calls.

Note

For compatibility reasons, if the moduleDefs function is not exposed by the module SDK, then the
moduleRuntime will be run and the container executed as before, and self calls will not be enabled.

To enable self calls, you can edit manually the dagger.json to add the experimental flag as follows:

{
  "sdk": {
    "experimental": {
      "SELF_CALLS_FEATURE": true
    }
  }
}

And it's also possible to use dagger init and dagger develop commands:

  • dagger init --with-self-calls to init a new module with self calls enabled
  • dagger develop --with-self-calls to enable it on an existing module
  • dagger develop --without-self-calls to disable it

Comment thread core/sdk.go Resolved
@eunomie
eunomie force-pushed the moduleTypeDefs branch 6 times, most recently from f7d341d to df123e0 Compare June 20, 2025 16:28
@eunomie
eunomie marked this pull request as ready for review June 20, 2025 16:44
@sipsma

sipsma commented Jun 20, 2025

Copy link
Copy Markdown
Contributor

@eunomie Looked at the socket not found error getting hit. It has to do with the fact that the new TypeDefs container and Runtime container are different (due to the new --typedefs-only arg) and thus end up as different cache entries. The Runtime container now doesn't get evaluated until the actual function invocation occurs, at which time it's running codegen (again) and looking for the SSH socket that's not available at that time.

I think the fundamental problem is that we end up running codegen twice now in this new scheme. That's not ideal for performance besides the socket issue it introduces.

I think splitting out the new TypeDefs method in the SDK interface makes perfect sense. But at least for this first step maybe it would make more sense to just implement TypeDefs for the Go SDK using the existing Runtime implementation? So TypeDefs for the go sdk just calls to Runtime and uses that container rather than trying to pass that extra --typedefs-only arg and bust cache between the two.

I haven't parsed through the exact behavior changes --typedefs-only introduces, so let me know if the suggestion above isn't actually possible. I'm just going off the idea the previously we used the Runtime container for getting typedefs, so it should theoretically be possible to continue to use it for now to implement TypeDefs.

@eunomie

eunomie commented Jun 21, 2025

Copy link
Copy Markdown
Member Author

Thanks @sipsma for the explanation.

I think the fundamental problem is that we end up running codegen twice now in this new scheme. That's not ideal for performance besides the socket issue it introduces.

I think splitting out the new TypeDefs method in the SDK interface makes perfect sense. But at least for this first step maybe it would make more sense to just implement TypeDefs for the Go SDK using the existing Runtime implementation? So TypeDefs for the go sdk just calls to Runtime and uses that container rather than trying to pass that extra --typedefs-only arg and bust cache between the two.

The goal is to run codegen twice, and to decouple typedefs from runtime.
It's not this PR specifically, but the final goal is to allow self invocation. So this means to have the typedefs independently from the runtime, as the runtime might refer to the typedefs.

A very simple example would be the following:

func (m *MyModule) ContainerEcho(stringArg string) *dagger.Container {
	return dag.Container().From("alpine:latest").WithExec([]string{"echo", stringArg})
}

func (m *MyModule) Echo(stringArg string) *dagger.Container {
	return dag.MyModule().ContainerEcho(stringArg)
}

The moduleRuntime codegen will never succeed because of the dependency to MyModule. In fact we have sort of a circular dependency here. Currently typedefs depends on runtime, that requires codegen, that requires typedefs.
So my solution was to split it in two:

  • the typedefs only codegen, that only looks at the types exposed and not at the code called
  • the runtime that doesn't care about types but only about function calling

All that means 2 codegen phases, one for typedefs, one for function calls. Right now it's the same with just a flag, that could be completely different, or use something like @jedevc is mentioning above, but my understanding is it will not really change a lot to this problem, no?

So yes, for this very first phase it would be possible to avoid the different codegen and only use the existing moduleRuntime, but it means the very next phase is to split it. So not sure that would have a lot of benefit to push back this split. Or maybe there's a benefit to have the moduleTypeDefs relying on moduleRuntime that I don't see/understand.

@eunomie

eunomie commented Jun 21, 2025

Copy link
Copy Markdown
Member Author

Regarding performances, yes there's a cost here. But I don't see a lot of different ways to avoid it.
Maybe the above suggestion to completely abstract the types and avoid to return a container to run can help, at least for the Java SDK I can see that as a good solution. But there will be a cost.

Thinking again, maybe the idea of an intermediate json might help has there's not anymore this typedefs container. Maybe.

@eunomie

eunomie commented Jun 21, 2025

Copy link
Copy Markdown
Member Author

The Runtime container now doesn't get evaluated until the actual function invocation occurs, at which time it's running codegen (again) and looking for the SSH socket that's not available at that time.

Could you detail a bit more? I'm not sure to understand the link between the container cached and not evaluated and the SSH socket.

@jedevc

jedevc commented Jun 23, 2025

Copy link
Copy Markdown
Contributor

I haven't parsed through the exact behavior changes --typedefs-only introduces, so let me know if the suggestion above isn't actually possible. I'm just going off the idea the previously we used the Runtime container for getting typedefs, so it should theoretically be possible to continue to use it for now to implement TypeDefs.

Hah, okay, I chatted with @eunomie, lemme try and summarize and explain.

So, this is part of the work to do self-calls. We need the separation into two phases for this. For the go sdk (as currently structured in main) - with self calls, we won't actually be able do the typedef analysis until after we've done codegen.

Here's why:

  1. The engine will get all the dependencies and try to do codegen, by generating a client and types and methods, etc.
  2. Now, if the module code is actually valid, we can build it using go build into the /runtime.
  3. We can then call /runtime with the empty string to get all the typedefs.

But. In the scenario of self-calls the code won't be valid after generating all the types and methods - because we'll be missing the self-bindings (we only know what those types should be after step 3). So we can't build it, so we can't get the typedefs. We have this weird circular dependency.

Thankfully, we can fix this. TypeDefs doesn't need to be dependent on codegen, it's kinda artificial - we can do all the go introspection of function signatures, and generate the typedefs without knowing every single type in the signature. One option (I think currently implemented in this PR) is to generate a single standalone binary (that doesn't even include our own source code) that only generates the typedefs, then we can build this, and actually get all the types at the end.

So, we need these two phases. To make sure that we fix the caching issue that @sipsma points out, we need to eagerly evaluate the Runtime container when we load the module. Atm in main, this is implied - we could just make that explicit (e.g. in ModuleSource.AsModule, just call .Runtime and throw away the result, so that it populates the cache) and that should solve the bug.

However, as @sipsma points out, there's a little bit of a perf issue here (curious to see how this pans out though, it might not be terrible?). For every module load, we're now having to generate, build, and execute two binaries. Ideally, the solution to this is to improve TypeDefs so that we don't need to build a binary at all - instead of generating code that builds typedefs, we could just port that code (might be automatable using an LLM?) to just directly generate the typedef structure (e.g. as JSON, see the suggestion above). Functionally, this would mean changing the method TypeDefCode to TypeDefJSON or similar:

func (spec *parsedObjectType) TypeDefCode() (*Statement, error) {

@eunomie

eunomie commented Jun 24, 2025

Copy link
Copy Markdown
Member Author

This is not a solution at all, but I just confirmed that with this change, that works:

diff --git a/core/sdk/go_sdk.go b/core/sdk/go_sdk.go
index 3d6fc8390..664aff2e9 100644
--- a/core/sdk/go_sdk.go
+++ b/core/sdk/go_sdk.go
@@ -523,13 +523,13 @@ func (sdk *goSDK) baseWithCodegen(
 	// cause failures if we also mount this in Runtime.
 	// Issue we run into is that when we try to run sdk checks
 	// using .dagger, it fails trying to find the socket
-	sshAuthSelectors, err := sdk.getUnixSocketSelector(ctx)
-	if err != nil {
-		return ctr, err
-	}
-	if len(sshAuthSelectors) > 0 {
-		selectors = append(selectors, sshAuthSelectors...)
-	}
+	//sshAuthSelectors, err := sdk.getUnixSocketSelector(ctx)
+	//if err != nil {
+	//	return ctr, err
+	//}
+	//if len(sshAuthSelectors) > 0 {
+	//	selectors = append(selectors, sshAuthSelectors...)
+	//}
 
 	// now that we are done with gitconfig and injecting env
 	// variables, we can run the codegen command.

(if there's no need for a private repo)

My understanding is the first codegen part (the one generating the typedefs) shouldn't require the ssh socket, as it shouldn't need the dependencies if I'm right (functions can return a local type or a core type, but not a dependent type, right?)

@github-actions

This comment was marked as resolved.

@eunomie
eunomie requested a review from a team as a code owner July 21, 2025 10:08
@eunomie
eunomie force-pushed the moduleTypeDefs branch 3 times, most recently from e3fe349 to e0b2efc Compare July 24, 2025 13:54
@eunomie eunomie changed the title SDK: add moduleTypeDefs to module SDK, to register type definition SDK: self invocation Jul 24, 2025
eunomie and others added 24 commits October 14, 2025 15:41
load runtime trace has been removed in dagger#10468 so removed it again,
and remove the corresponding one for type defs

Signed-off-by: Yves Brissaud <[email protected]>
In case `moduleTypeDefs` exists in the SDK, use it to get the module's
types. But if the self calls experimental flags, simply replace the
previous moduleRuntime call, do not use the results as its own dependency.

This allows to remove the previous duplication between TypeDefCode and TypeDef
in go codegen for instance, and to benefit from the moduleTypeDefs work
without the self calls that needs more work to be ready for all cases.

Signed-off-by: Yves Brissaud <[email protected]>
until we are able to fix them

Signed-off-by: Yves Brissaud <[email protected]>
Bump typescript SDK Dagger version to ensure it's using
    withEnumMember
without to fallback to
    withEnumValue
because the version (0.16) was too old.

Signed-off-by: Yves Brissaud <[email protected]>
CoolSdk is used as a wrapper on top of the Go SDK. As the Go SDK
now implements ModuleDefs, the CoolSdk needs to also do it to properly
wrap the Go SDK.

Signed-off-by: Yves Brissaud <[email protected]>
Signed-off-by: Yves Brissaud <[email protected]>
This will allow to control how the WithExec call is made, especially
this will allow to inject the module information during the call.
But this needs to happen from the engine, not from the SDKs.

To inject module data will allow to set the right engine version
at a moment the module is still not yet loaded.

Signed-off-by: Yves Brissaud <[email protected]>
shared cool-sdk updated with new moduleDefs function

Signed-off-by: Yves Brissaud <[email protected]>
Always codegen. This is the only way, with the actual implementation,
to have access to the SDK for instance.

The test is wrapping the Python SDK, in a module written in Python.
The code is calling dag.PythonSDK. But this module exists only because it
has been loaded, it's not part of the default core types.
This shouldn't be an issue, except the way the Python SDK works
is moduleDefs is using moduleRuntime container.

The ultimate solution is to cut the link between moduleDefs and moduleRuntime,
to have better performances, but in the meantime this can be a solution.

Signed-off-by: Yves Brissaud <[email protected]>
Currently performances are not good enough and those SDKs require
a bit more work.
In order to unblock the PR and allow to merge it, just remove the moduleTypes
functions for those SDKs so that they are not affected and they will be
added back in dedicated PRs.

The moduleTypes function has been renamed to moduleTypesExp for both SDKs
so it's still exposed and can be calles manually to help fix it,
but the engine is not seeing it anymore.

Signed-off-by: Yves Brissaud <[email protected]>
@eunomie

eunomie commented Oct 15, 2025

Copy link
Copy Markdown
Member Author

For performances reason and as a way to unblock this PR, the new moduleTypes behavior has been disabled for typescript and python SDKs. They will come back as dedicated follow up PR that will be easier to write and review.
That way, the new beahavior can still be included, go SDK performances are good, and we can iterate on it for the other SDKs.

@grouville grouville left a comment

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.

LGTM ✅ Let's follow-up with all the neats + python and ts / sdk port to that new implementation

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

Labels

area/engine/api needs/changelog Pull requests that require a changelog entry needs/docs Pull requests that require a docs change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants