Skip to content

Proposal: Codegen: Return simple objects #4920

Closed

Description

@helderco

Summary

For simple object types where all their fields are non-parametrized scalars, make it more convenient to access the object’s properties in SDKs by returning the whole object at once as a leaf value.

Motivation

Our chainable API is pretty simple, but it also feels limiting when you want multiple related fields, especially if they’re a part of a simple object like EnvVariable, Port or Label.

For example, if I have an EnvVariable object, and I want both the name and value, I need to make two extra requests:

envVars, err := ctr.EnvVariables(ctx)
if err != nil {
    return nil
}
for _, env := range envVars {
    name, err = env.Name(ctx)
    if err != nil {
        return nil
    }
    value, err = env.Value(ctx)
    if err != nil {
        return nil
    }
    fmt.Printf("%s=%s\n", name, value)
}

Same thing with Port, Label and others like these.

This could be much simpler by making a single request that includes all fields in the result:

envVars, err := ctr.EnvVariables(ctx)
if err != nil {
    return nil
}
for _, env := range envVars {
    fmt.Printf("%s=%s\n", env.Name, env.Value)
}

While these are just two fields, Port has three and there’s an issue for adding a FileInfo type (similar to fs.FileInfo) that’ll double that (4 - 6 fields):

Specification

Definition

This proposal defines a “simple object” as:

  • A GraphQL object type;
  • Where all fields are leafs that don’t have any arguments;
  • Doesn’t have an id field (rules out CacheVolume, Socket and Secret).

Codegen

When a simple object is detected, print it the same as an input type (except it should only be used in outputs):

// A simple key value object that represents an environment variable.
type EnvVariable struct {
-	q *querybuilder.Selection
-	c graphql.Client
-
-	name  *string
+	// The environment variable name.
+	Name  string
+
-	value *string
+	// The environment variable value.
+	Value *string
}
-
-// The environment variable name.
-func (r *EnvVariable) Name(ctx context.Context) (string, error) {
-	if r.name != nil {
-		return *r.name, nil
-	}
-	q := r.q.Select("name")
-
-	var response string
-
-	q = q.Bind(&response)
-	return response, q.Execute(ctx, r.c)
-}
-
-// The environment variable value.
-func (r *EnvVariable) Value(ctx context.Context) (string, error) {
-	if r.value != nil {
-		return *r.value, nil
-	}
-	q := r.q.Select("value")
-
-	var response string
-
-	q = q.Bind(&response)
-	return response, q.Execute(ctx, r.c)
-}

Then, if a field returns a simple object, select all fields and use it directly in responses:

 // Retrieves the list of environment variables passed to commands.
 func (r *Container) EnvVariables(ctx context.Context) ([]EnvVariable, error) {
        q := r.q.Select("envVariables")

        q = q.Select("name value")

-       type envVariables struct {
-               Name  string
-               Value string
-       }
-
-       convert := func(fields []envVariables) []EnvVariable {
-               out := []EnvVariable{}
-
-               for i := range fields {
-                       out = append(out, EnvVariable{name: &fields[i].Name, value: &fields[i].Value})
-               }
-
-               return out
-       }
-       var response []envVariables
+       var response []EnvVariable

        q = q.Bind(&response)
-
-       err := q.Execute(ctx, r.c)
-       if err != nil {
-               return nil, err
-       }
-
-       return convert(response), nil
+       return response, q.Execute(ctx, r.c)
 }

We’re just moving that implementation detail to the outside, removing the need for passing context and capturing error.

Detection

With #5226, all SDKs should be able to reuse the same detection logic during introspection. But for now, I wrote a simple introspection command in Python to test the theory and as of now, these are the types that match:

"""A simple key value object that represents an environment variable."""
type EnvVariable {
  """The environment variable name."""
  name: String!

  """The environment variable value."""
  value: String!
}

"""A flag accepted by a project command."""
type ProjectCommandFlag {
  """Documentation for what this flag sets."""
  description: String

  """The name of the flag."""
  name: String!
}

"""A simple key value object that represents a label."""
type Label {
  """The label name."""
  name: String!

  """The label value."""
  value: String!
}

"""A port exposed by a container."""
type Port {
  """The port description."""
  description: String

  """The port number."""
  port: Int!

  """The transport layer network protocol."""
  protocol: NetworkProtocol!
}
See code that produced this 👆
from graphql import GraphQLNamedType, get_named_type
from graphql.utilities.print_schema import print_filtered_schema

import dagger
from dagger.codegen import (
    is_object_type,
    is_output_leaf_type,
)
from dagger.server import command


@command
def find(client: dagger.Client) -> str:
    """Find all simple objects in the schema."""
    schema = client._ctx.schema._schema
    out = print_filtered_schema(schema, lambda _: False, is_simple_object)
    print(out)
    return out


def is_simple_object(t: GraphQLNamedType) -> bool:
    t = get_named_type(t)
    if t.name.startswith("_") or not is_object_type(t):
        return False
    return not any(
        f
        for f_name, f in t.fields.items()
        if f_name == "id" or f.args or not is_output_leaf_type(f.type)
    )

Backwards compatibility

This is an obvious breaking change in SDKs (not in the API) because the signature for handling the above types is different. However, this is only a problem in Go but not in Python and Node.js because it doesn’t even work today (see more about this in Rationale: Handling lists of objects).

While we could introduce half measures to keep some sort of compatibility I think it’s better to just cluster this with other breaking changes we need to make in a single release.

Rationale

Handling lists of objects

There’s a long standing issue about SDKs not being able to return lists of objects:

Returning lists of objects were a known limitation in our chainable objects in the SDKs, so we had an undocumented convention for not supporting that until we had a good solution, but eventually it got into the API without having tests via the SDKs.

So to fix the introduced bug, @sipsma suggested:

If we are willing to trade more complexity for having the ability to return objects in lists maybe we could figure something out around autoselecting all trivial scalars for those cases, though I don't know if we'll have to apply that fix on a case-by-case basis (ugly) or if there's a way of cleanly generalizing it. Vague idea, might be a deadend, but in general it would be nice to support these return types.

- Reposted by @aluzzardi in #3457 (comment)

That idea has been adopted as the fix in Go:

However, the implementation isn’t ideal. When a list is returned, the fields are internally pre-selected and filled on private struct fields. When they are accessed, if the cached value exists then it’s short circuited:

type EnvVariable struct {
	// ...
	name  *string
	value *string
}

func (r *EnvVariable) Name(ctx context.Context) (string, error) {
	if r.name != nil {
		return *r.name, nil
	}
	// ...
}

func (r *EnvVariable) Value(ctx context.Context) (string, error) {
	if r.value != nil {
		return *r.value, nil
	}
	// ...
}

That means there’s useless verbosity when accessing these fields, i.e., context isn’t actually needed and the err is always nil:

name, err = env.Name(ctx)
if err != nil {
    return nil
}
value, err = env.Value(ctx)
if err != nil {
    return nil
}

You can ignore the errors in this case, but it’s an implementation detail and feels unsafe to depend on:

name, _ = env.Name(ctx)
value, _ = env.Value(ctx)

Yeah, I would have preferred to directly access the property instead of passing a context and unpacking the error but it's unfortunately not possible because of the current SDK API design :/

- Originally posted in #4683 (comment)

Meaning, this was desired instead:

name = env.Name
value = env.Value

I haven’t fixed this in Python yet because I wanted a better solution1, that’s why I came up with this proposal, which also solves some use cases for #3577.

Although it’s not that verbose in Python and Node.js:

name = await env.name()
value = await env.value()

# vs

name = env.name
value = env.value

But this proposal’s design would also works for any field that returns one of these objects directly, not just on lists of objects, which addresses the following concern:

Also creates a disparity between Object (need to call Object.Field(ctx) -- it's lazy) and [Object!]! (need to call Object.Field -- it's not lazy). We could have both APIs be the same, but the behavior would be different (lazy vs non-lazy) which can be confusing. Implementation would also need to be different (return "pre-fetched" field vs query the API).

- Originally posted by @aluzzardi in #3457 (comment)

I’m proposing that when these objects are returned, they’re always handled like a leaf, not just on lists.

Alternatives considered

SDK helper

At first I considered an SDK helper to hide the verbosity and boilerplate of making concurrent requests for the multiple sibling fields, but my pain point at the time was for getting exec related fields (i.e., exitCode, stdout, stderr). That’s why I added an ExecResult example to the first version of this proposal, but there’s been other solutions in the meantime.

Explicit declaration with API directive

GraphQL has input object types, used only as arguments to fields:

input BuildArg {
  name: String!
  value: String!
}

Codegen is already converting those into simple structs/objects:

type BuildArg struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

I would like to have an output EnvVariable {} type to do the same but for the return values. Since that doesn’t exist, we can simulate it with a directive:

directive @output on OBJECT

type EnvVariable @output {
  name: String!
  value: String!
}

Which would produce a similar struct/object to input types:

type EnvVariable struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

This solution makes detection much simpler in codegen and explicit in the API.

It’s not my first choice because it’s an added burden on API authors to choose correctly, potentially leaving some inconsistencies which would need extra validation in the API itself (e.g., using on a type that has non-leaf fields or fields with arguments, forgetting to use it in a new type and introducing a break in the convention….). But also when used in lists there’s an implicitness there already where this is actually required.

I chose to go with the implicit version because it’s better at enforcing the rules. However, this can become an option to have better control if in the future we find the need for it for any reason. By then, maybe other kinds of directives would be better, like marking a field as always being prefetched and used as a property, or marking a field as expensive so it gets ruled out as a property.

By then it won’t be a breaking change.

Alternative value object type

I thought about adding a second or alternative for these object types in the SDK clients, but that adds unnecessary fragmentation or inconsistency:

type EnvVariableValue struct {
	Name  string
	Value string
}

type EnvVariable struct {
	// ...
	name  *string
	value *string
}

func (r *EnvVariable) Name(ctx context.Context) (string, error) {
	// ...
}

func (r *EnvVariable) Value(ctx context.Context) (string, error) {
	// ...
}

Drawbacks

  • It’s a breaking change, but we can cluster it with other breaking changes.
  • Small benefit? Today we only have 4 object types with 2-3 fields but that’ll change (e.g., FileInfo).
  • We can find later on that we need more control over the selection (e.g., what if a leaf isn’t a “trivial” scalar?), but we can add directives if it comes to that.
  • Doesn’t entirely fix selecting sibling fields where a proper solution would fix this as well.
  • Doesn’t entirely fix returning lists of objects if you need to list an object that has at least one field that’s not a scalar.
  • Can be confusing that some fields are properties (Object.Field) while others are functions (Object.Field(ctx))

Open question

There’s only one (very recent) case for the last point above in ProjectCommand, unless we include the id field (as a method) and also recursively resolve all the fields that list simple objects themselves. This isn’t hard to do, it’ll actually still make the implementation simpler compared to today. Would this be worth doing?

"A command defined in a project that can be invoked from the CLI."
type ProjectCommand {
"A unique identifier for this command."
id: String!
"The name of the command."
name: String!
"Flags accepted by this command."
flags: [ProjectCommandFlag!]
"Documentation for what this command does."
description: String
"Subcommands, if any, that this command provides."
subcommands: [ProjectCommand!]
}

Footnotes

  1. I no longer intend to wait on a solution to fix it in Python, just haven’t made it a priority yet but will soon. ↩

Activity

  1. changed the title [-]Codegen (proposal): Return simple objects[/-] [+]Proposal : Codegen: Return simple objects[/+] on Apr 10, 2023
  2. changed the title [-]Proposal : Codegen: Return simple objects[/-] [+]Proposal: Codegen: Return simple objects[/+] on Apr 10, 2023
  3. helderco commented on Jun 15, 2023

    @helderco
    ContributorAuthor

    I just updated the proposal which was long overdue.

    I removed the example on ExecResult which was the main reason I wanted this in the first place, but there's other solutions for that and I no longer think it worth it to have a wrapping type for exitCode, stdout and stderr especially if the output could be huge and you don't want all those fields when you just need one.

  4. gerhard commented on Jul 18, 2023

    @gerhard
    Contributor

    Having spoken to @helderco sync, we are thinking of not including this in the upcoming breaking changes release since more discussions are needed. FTR:

  5. TomChv commented on Aug 31, 2023

    @TomChv
    Member

    @helderco This issue can help to improve #5557 integration (See #5557 (comment))

    Should we start working on It? I understood your proposal and have an implementation in mind for Node and Go.
    This would make our generators a bit more complex and specific (since we have special function for what you call simple object).

  6. helderco commented on Aug 31, 2023

    @helderco
    ContributorAuthor

    Should we start working on It?

    We should agree on design first.

  7. TomChv commented on Sep 1, 2023

    @TomChv
    Member

    I kinda like the design proposed in your specification! I don't know if you have something different in mind for now?
    We can have a quick sync chat if you're free to agree on the design :)

  8. helderco commented on Sep 4, 2023

    @helderco
    ContributorAuthor

    I meant we should get more feedback from the team if it's worthwhile considering the drawbacks and open question.

  9. 9 remaining items

  10. vito commented on Feb 20, 2024

    @vito
    Contributor

    For continuity from Discord conversations with @shykes:

    We agree that there's a need for state and that there is effectively a fields vs. functions distinction internally, but @shykes 's point is that fields should just be an implementation detail of modules, not distinguished in any way through the API. The main take-away is that it should be easy for a module author to switch something from a field to a function internally without any impact on users.

    So I think to address this we'll need better client support for selecting multiple fields. Right now you have to drop down to a handwritten query string. We could explore a totally different style of client based on a query building approach - there's consensus in curiosity, but not commitment. Or maybe there's a middle ground where we can integrate multiple field selection into the existing SDK in a natural way.

  11. helderco commented on Feb 20, 2024

    @helderco
    ContributorAuthor

    We could explore a totally different style of client based on a query building approach

    I summarized that in #4668 (comment). By that I mean separating query building from execution, as in:

    // build query, doesn't execute
    q := dag.Container().Build(src).Stdout()
    
    // only one way to execute query!
    err := dagger.Query(q)

    From my POV, the big issue with that approach was we didn't find a good way to extract multiple values, from a multiple selection. Solomon had a few ideas but they didn't cross language very well. We were a bit stuck discussing this (see #3555 (comment)), so it was decided at the time to just move on with the more simple solution, which is what we have today.

    After a while, when people were expressing confusion over the implicitness of execution on leafs, contrary to just building a query, we were thinking that the query builder approach could make it easier to understand for people, but also that it was too big a change and it was too late.

    Or maybe there's a middle ground where we can integrate multiple field selection into the existing SDK in a natural way.

    Yeah, in the meantime, this often pops up in my head, i.e., selecting multiple siblings with the current DX, but the thought is like a doctor's visit, which doesn't stay long. 😄

    I usually gravitate towards something to the tune of generating a second object type for each object type, that only includes the leafs but still chainable to allow for multiple selection:

    ctr, err := dag.Container().
        From("alpine").
        WithExec([]string{"printenv"}).
        Leafs().  // bikeshedding non-withdstanding
        Stdout().
        Stderr().
        Sync(ctx)  // or anything else to Execute

    Essentially there would be a Container.Leafs -> &ContainerLeafs{} where ContainerLeafs.Stdout() just adds the sibling selection to the query builder and returns "self", like the other non-leafs.

    At this point, when I need to figure out the best way to get the multiple values in a way that is type safe and has a good DX over multiple languages, my 🧠 jumps to another branch in the 🐒 🌴. 🙂

  12. locked and limited conversation to collaborators on Mar 24, 2026
  13. converted this issue into a discussion #12508 on Mar 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions