Skip to content

Lazy executions are confusing to understand and sometimes don't work as expected #4668

Closed

Description

@marcosnils

Summary

Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions.

Issues Proposals
No withExec
  • "Default exec" #4833
  • Dockerfile build (without exec)
  • Force synchronous execution (disable laziness) #5065
  • Implicit query execution
  • Force synchronous execution (disable laziness) #5065
  • Multiple ways to execute “Pipeline builder” model
    Documentation
  • Document Lazy DAG Model #3617
  • Issue: no withExec

    We had some users report that part of their pipeline wasn't being executed, for which they had to add a WithExec(nil) statement for it to work:

    _, err := c.Container().Build(src).ExitCode(ctx)  // doesn't work
    _, err := c.Container().From("alpine").ExitCode(ctx)  // same thing

    Explanation

    Users may assume that since they know there’s an Entrypoint/Cmd in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following:

    _, err := ctr.
        WithEntrypoint([]string{}).
        WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{
            Args: []string{"/bin/sh"},
        })
        ExitCode(ctx) // nothing to execute!

    ExitCode and Stdout only return something for the last executed command. That means the equivalent of a RUN instruction in a Dockerfile or running a container with docker run.

    Workaround

    Add a WithExec() to tell dagger to execute the container:

    _, err := client.Container().
        Build(src).
    +   WithExec(nil).
        ExitCode(ctx)

    The empty (nil) argument to WithExec will execute the entrypoint and default args configured in the dagger container.

    Note
    If you replace the .ExitCode() with a Publish(), you see that Build() is called and the image is published, because Publish doesn’t depend on execution but Build is still a dependency.

    The same is true for a bound service:

    db := client.Container().From("postgres").
         WithExposedPort(5432).
    +    WithExec(nil)
    ctr := app.WithServiceBinding("db", db)

    Here, WithServiceBinding clearly needs to execute/run the postgres container so that app can connect to it, so we need the WithExec here too (with nil for default entrypoint and arguments).

    Proposals

    To avoid astonishment, a fix was added (#4716) to raise an error when fields like .ExitCode or .WithServiceBinding (that depend on WithExec) are used on a container that hasn’t been executed.

    However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container.

    This is what #4833 proposes, meaning the following would now work as expected by users:

    // ExitCode → needs execution so use default exec
    _, err := c.Container().From("alpine").ExitCode(ctx)
    
    // WithServiceBinding → needs execution so use default exec
    db := client.Container().From("postgres").WithExposedPort(5432)
    ctr := app.WithServiceBinding("db", db)
    ### No `withExec`
    - [x] #4716
    - [ ] #4833
    

    Issue: Dockerfile build (without exec)

    Some users just want to test if a Dockerfile build succeeds or not, and don’t want to execute the entrypoint (e.g., long running executable):

    _, err = client.Container().Build(src).ExitCode(ctx)

    In this case users are just using ExitCode as a way to trigger the build when they also don’t want to Publish. It’s the same problem as above, but the intent is different.

    Workarounds

    With #4919, you’ll be able to skip the entrypoint:

    _, err = client.Container().
        Build(src).
        WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{
            SkipEntrypoint: true,
        }).
        ExitCode(ctx)

    But executing the container isn’t even needed to build, so ExitCode isn’t a good choice here. It’s just simpler to use another field such as:

    - _, err = client.Container().Build(src).ExitCode(ctx)
    + _, err = client.Container().Build(src).Rootfs().Entries(ctx)

    However this isn’t intuitive and is clearly a workaround (not meant for this).

    Proposal

    Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds:

    - _, err = client.Container().Build(src).ExitCode(ctx)
    + _, err = client.Container().Build(src).Sync(ctx)
    ### `Dockerfile` build (without exec)
    - [x] #4919
    - [ ] #5065
    

    Issue: Implicit query execution

    Some functions are “lazy” and don’t result in a query execution (e.g., From, Build, WithXXX), while others execute (e.g., ExitCode, Stdout, Publish).

    It’s not clear to some users which is which.

    Explanation

    The model is implicit, with a “rule of thumb” in each language to hint which ones execute:

    • Go: functions taking a context and returning an error
    • Python and Node.js: async functions that need an await

    Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) transforms leaf fields into an implicit API request when called, and return the value from the response.

    So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand.

    This was discussed in:

    Proposal

    The same Pipeline Synchronization proposal from the previous issue helps make this a bit more explicit:

    _, err := ctr.Sync(ctx)
    ### Implicit query execution
    - [x] #3555
    - [x] #3558
    - [ ] #5065
    

    Issue: Multiple ways to execute

    “Execution” sometimes mean different things:

    • Container execution (i.e., Container.withExec)
    • Query execution (i.e., making a request to the GraphQL API)
    • ”Engine” execution (i.e., doing actual work in BuildKit)

    The ID fields like Container.ID for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see Implicit query execution above).

    More importantly, users have been using .ExitCode(ctx) as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that.

    However, adding the general .Sync() (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing WithExec(nil) because .Sync() can’t assume you want to execute the container.

    That’s a catch 22 situation! There’s no single execute function to “rule them all”.

    It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose:

    // exec the container (build since it's a dependency)
    c.Container().Build(src).ExitCode(ctx)
    
    // just build (don't exec)
    c.Container().Build(src).Sync(ctx)

    Proposal

    During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (#3555 (comment)).

    The idea was to make a clear separation between building the lazy pipeline and executing the query:

    // ExitCode doesn't implicitly execute query here! Still lazy.
    // Just setting expected output, and adding exec as a dependency.
    // Build is a dependency for exec so it also runs.
    q := c.Container().Build(src).ExitCode()
    
    // Same as above but don't care about output, just exec.
    q := c.Container().Build(src).WithExec(nil)
    
    // Same as above but don't want to exec, just build.
    q := c.Container().Build(src)
    
    // Only one way to execute query!
    client.Query(q)

    Downsides

    • It’s a big breaking change so it’s not seen as a viable solution now
    • No great solution to grab output values
    • More boilerplate for simple things

    Solution

    Embrace the laziness!

    Issue: Documentation

    We have a guide on Lazy Evaluation but it’s focused on the GraphQL API and isn’t enough to explain the above issues.

    We need better documentation to help users understand the “lazy DAG” model (#3617). It’s even more important if the “pipeline builder” model above isn’t viable.

    ### Documentation
    - [x] #3622
    - [ ] #3617
    

    Affected users

    These are only some examples of users that were affected by this:

    Activity

    1. c-p-b commented on Mar 1, 2023

      @c-p-b

      Spark has a similar concept as Dagger when it comes to lazy evaluation. It's probably worthwhile to look at how they handle this because when using their API it is much more obvious what is lazily evaluated and what is not:

      https://www.mikulskibartosz.name/difference-between-transformation-and-action-in-apache-spark/

    2. helderco commented on Mar 1, 2023

      @helderco
      Contributor

      When we look at the Spark API, we can easily spot the difference between transformations and actions. If a function returns a DataFrame, Dataset, or RDD, it is a transformation. If it returns anything else or does not return a value at all (or returns Unit in the case of Scala API), it is an action.

      We have similar rules, that were discussed in:

      The consensus at the time it was closed was that we wait for more feedback from users to know if we need to adjust.

      Summary:

      • If a method returns a leaf value1 (primitive, e.g., string, integer...), then it executes the query
        • Additional Go hint: When you need to pass the context and capture an error
        • Additional async Python & NodeJS hint: When you need to await the result
      • Exception: if it's an .id() a GraphQL query gets executed, but no BuildKit build is triggered
        • We solved it by hiding id's or avoiding the need to use them directly, in the SDKs

      You have hints in editors' autocomplete for all of them. Meaning that the editor (and reference docs) help you know which ones need to be awaited, for example, thus leading to query execution.

      Footnotes

      1. According to the spec: "GraphQL responses take the form of a hierarchical tree; the leaves of this tree are typically GraphQL Scalar types (but may also be Enum types or null values). [...] GraphQL specifies a basic set of well-defined Scalar types: Int, Float, String, Boolean, and ID." ↩

    3. samalba commented on Mar 2, 2023

      @samalba
      Contributor

      snippet to repro:

      package main
      
      import (
      	"context"
      	"os"
      
      	"dagger.io/dagger"
      )
      
      func main() {
      	ctx := context.Background()
      	c, _ := dagger.Connect(ctx, dagger.WithLogOutput(os.Stderr))
      
      	dir := c.Container().WithNewFile("Dockerfile", dagger.ContainerWithNewFileOpts{
      		Contents: `FROM alpine as final
      		RUN echo hello`,
      	}).Directory(".")
      	_, err := c.Container().Build(dir, dagger.ContainerBuildOpts{Target: "final"}).ExitCode(ctx)
      	if err != nil {
      		panic(err)
      	}
      }

      ^ when executed, the Build operation will never be invoked.

      In this example, it's tricky because there is actually nothing to run, this is why the Build is not invoked. If you replace the .ExitCode() with a Publish(), you see that the build is called and the image is published.

      _, err := c.Container().Build(dir, dagger.ContainerBuildOpts{Target: "final"}).WithExec([]string{"true"}).ExitCode(ctx)
      

      Or if you inject a .WithExec() before the .ExitCode(), the Build is also invoked.

      _, err := c.Container().Build(dir, dagger.ContainerBuildOpts{Target: "final"}).Publish(ctx, "ttl.sh/random12312342345435:1m")
      

      In other term a single Build() has the same effect as a .WithXXX() with no leaf value, it does not execute anything. The behavior is not a bug, it works as expected, but it's not trivial to understand.

    4. shykes commented on Mar 3, 2023

      @shykes
      Contributor

      We have similar rules, that were discussed in:

      Oh boy. This one brings back memories...

    5. vito commented on Mar 3, 2023

      @vito
      Contributor

      Just noting @phroggyy ran into this in Discord:

      with the new c2c networking, do I need to call any particular function to run the dependency container? Currently running into an issue:

      "message":"start  (aliased as db): service exited before healthcheck"
      

      Note the lack of a hostname in start <hostname> (<aliases>):. A missing hostname means WithExec(nil) was never called, probably something like this:

      client.WithServiceBinding("db", c.Container().From("postgres"))

      The fix:

      client.WithServiceBinding("db", c.Container().From("postgres").WithExec(nil))

      As others have mentioned this is technically correct, but a little less than helpful. Lots of folks are tripping on it lately. @mircubed @d3rp3tt3 I think this should be pretty high priority at this point (~3 folks tripped on it in the past few days).

      No one has suggested this so I may be preaching to the choir, but I'm very hesitant to have Dagger automatically figure out what you're trying to do and do it for you. That can make the mental model even harder to grok. My preference would be for us to detect these states and provide a helpful error message so the user understands the mental model in the end.

      My suggestion:

      • ExitCode, Stdout, and Stderr currently return null if the container has not run yet. I think we should just make these return an error. It is far more likely at this point to be a bug rather than a useful state to program against. Making things worse, the Go SDK currently turns the null into a zero-value int or string which is indistinguishable from a silent successful exit. (:scream:)
      • Binding a container with a blank hostname should error, as it means the container wasn't told to Exec.
    6. helderco commented on Mar 3, 2023

      @helderco
      Contributor

      I agree. Erroring in those conditions would be more useful and clear.

    7. vito commented on Mar 3, 2023

      @vito
      Contributor

      Another thought I had is that this is a consequence of having Container represent both images and container execs. If we had a distinct Image type, From() and Build() would return an Image which doesn't even have ExitCode/Stdout/Stderr and can't be passed to WithServiceBinding.

      A bit of a dramatic change at this point and I'm not sure if it's worth it, just another option to consider. It seems nice to make invalid states unrepresentable rather than hit them at runtime.

      Haven't thought through the rest of the implications though, for example where do all the WithWorkdir/etc. calls go. It'd be harder to do it all in one chain without flipping between Container and Image types or duplicating the method set between them.

      Seems like the relationship we'd want is "Container is an Image (and inherits all properties), but Image is not a Container".

    8. helderco commented on Mar 3, 2023

      @helderco
      Contributor

      "Container is an Image (and inherits all properties), but Image is not a Container".

      Yeah, that makes sense.

    9. samalba commented on Mar 6, 2023

      @samalba
      Contributor

      @vito or @helderco Does any one of you have some bandwidth to write a proposal to address this one?

    10. vito commented on Mar 6, 2023

      @vito
      Contributor

      @samalba It's a small enough change so I'll just submit a PR for my proposal at the end of #4668 (comment) and we can decide its fate in the PR

    11. 10 remaining items

    12. shykes commented on Mar 23, 2023

      @shykes
      Contributor

      For example: when an image has an entrypoint or default args, shouldn't it use that to resolve stdout, exitCode or serviceBinding?

      I alluded to this here:

      No one has suggested this so I may be preaching to the choir, but I'm very hesitant to have Dagger automatically figure out what you're trying to do and do it for you. That can make the mental model even harder to grok. My preference would be for us to detect these states and provide a helpful error message so the user understands the mental model in the end.

      But I could probably be talked into it. For example maybe I see "Image is subset of Container" because I'm too close to the problem and know the nitty-gritty details. Doing the opposite and consciously blurring that line could be beneficial, assuming there are no downsides. (Don't have time to think of examples at the moment.)

      I opened an issue to continue this particular path: #4833

      I 100% think we should do this, it's just weird that we don't IMO.

    13. shykes commented on Mar 23, 2023

      @shykes
      Contributor

      Why not have a single command to trigger execution? You wouldn't have all this uncertainty around what calls are lazily executed vs those that aren't.

      Since you're using graphql, maybe resolve() would be a worthwhile name. Unless there's a technical reason for this?

      There's a whole separate evolutionary path which we could follow, that would give us that. I explored it here. We decided against it. Alternative SDKs or client libraries could still explore it, the GraphQL API would support it just fine. But it would be a significant break from our current DX, not to mention the various tradeoffs which I failed to convince my fellow designers were worth it :)

      Separately, there is an incremental path we can (and IMO should) follow, that doesn't break the current DX: just add an optional lazy: bool argument to withExec, dockerBuild, git, container { from }, and any other operation that may be useful to explicitly trigger right away. If the caller sets this flag, the engine is required to resolve it immediately.

      I may be missing something, but it seems to me that 👆 would solve 90% of our "laziness is confusing" issues, in an intuitive way?

      thoughts @vito @aluzzardi @sipsma ?

    14. helderco commented on Mar 29, 2023

      @helderco
      Contributor

      Separately, there is an incremental path we can (and IMO should) follow, that doesn't break the current DX: just add an optional lazy: bool argument to withExec, dockerBuild, git, container { from }, and any other operation that may be useful to explicitly trigger right away. If the caller sets this flag, the engine is required to resolve it immediately.

      I may be missing something, but it seems to me that 👆 would solve 90% of our "laziness is confusing" issues, in an intuitive way?

      I prefer @aluzzardi's suggestions in #4205.

      When you need to execute something you need to pass the context and get the error. In Python and JS you need to await the coroutine/promise. So these methods have a different signature, it's not enough to add that parameter.

    15. shykes commented on Mar 29, 2023

      @shykes
      Contributor

      When you need to execute something you need to pass the context and get the error. In Python and JS you need to await the coroutine/promise. So these methods have a different signature, it's not enough to add that parameter.

      Sorry I didn’t understand that. Passing a lazy: bool parameter is not possible, or not convenient, or possible but doesn’t solve the problem? I didn’t get it.

    16. helderco commented on Mar 29, 2023

      @helderco
      Contributor

      I meant it's not possible because methods that send a request to the API have different signatures (context, return/raise error, coroutine/promise).

    17. helderco commented on Mar 30, 2023

      @helderco
      Contributor

      I'm repeating myself over several issues 😅

      Seems to me the confusion described in this issue is rooted in not having a synchronization primitive (to resolve the query).

      Using Container.exitCode to force resolving lazyness 👎

      There's this common pattern of using exitCode to force executing1 a lazy pipeline. But exitCode is being used mostly for the side effect of a bug, not for it's intended purpose (i.e., interrupting pipeline via failure, not needing the actual exit code value).

      We should fix exitCode to just return the exit code, and also add a new method as a convenience (example) to replace the current behavior (i.e., force execution and raise error).

      For simple cases, where you actually want to execute a container's command, it's easy to grok because you're just asking for what you actually need (run, stdout, exitCode...).

      This is being addressed in independent issues:

      Is there anything missing from this aspect of the confusion?

      We need a standardized way to resolve lazyness 👍

      The above is even worse when you don't actually want to execute the container's command, never mind not caring for the exit code. This leads to more confusion and unintuitive workarounds like going from Build().ExitCode(ctx) to Build().WithExec(nil).ExitCode(ctx) and landing on Build().Rootfs().Entries(ctx).

      What we need is a standard way to resolve any lazy pipeline. This has been discussed in multiple places, but we should focus on the same issue, and I think it should be a priority:

      Can we focus this discussion there? Or are there other aspects to consider?

      Rule of thumb

      With both of the above solved, we can go back to the rule of thumb where a pipeline is executed whenever you need to await (or pass context and get error), either from a leaf or from a synchronization primitive.

      It's perhaps too late to go back and redesign the API with a clear separation between building and executing pipelines, but this rule of thumb is simple enough to clear the confusion, I think.

      Footnotes

      1. As in sending the request for the engine to execute, not necessarily executing a Container's command. ↩

    18. assigned and unassigned on Apr 13, 2023
    19. helderco commented on Apr 24, 2023

      @helderco
      Contributor

      I just updated the description with a compilation of all the issues that I see related to this, with their explanations, workarounds and proposed solutions.

      Notes

      • The summary acts a a table of contents so you can click the issue name to jump to it's section.
      • There's a narrative if you read in order, where one issue builds upon the previous one.
      • Action steps is solving the proposed solutions in the summary.
      • Let me know if anyone has anything to add or change.
      • Whenever possible, use the proposals to further discussion on those solutions.
    20. shykes commented on May 1, 2023

      @shykes
      Contributor

      I updated the summary to reference #5065, which has a narrower scope than #4205. This is because the multi-part nature of the original proposal has complicated downstream design discussions a lot. As discussed with @helderco, decoupling the design discussions will make it easier to ship a solution to this problem.

    21. helderco commented on Jul 18, 2023

      @helderco
      Contributor

      Update: I just need to update this issue's description but the only remaining actionable item is documentation.

      With these main changes:

      Unless there's anything else, I suggest we close this and focus on the documentation:

    22. c-p-b commented on Jul 19, 2023

      @c-p-b

      As an end user I can say that I’ve switched to using sync() in my pipelines and it makes a lot more sense now than it did before. I feel pretty confident that the UX improvement has resolved the issue, at least to me, though the docs should be improved to explain what’s going on, as Helder mentioned. So I will second closing this issue and directing further action to documentation improvement

    23. helderco commented on Jul 21, 2023

      @helderco
      Contributor

      I'm closing for now to focus on the documentation in #3617. Reopen if there's anything else.

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

    Metadata

    Metadata

    Assignees

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions