Repository navigation
Description
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.
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 thingExplanation
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 aPublish(), you see thatBuild()is called and the image is published, becausePublishdoesn’t depend on execution butBuildis 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:
asyncfunctions that need anawait
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:
- codegen: Chaining syntax - When to execute query (i.e., implicit vs explicit)? #3555
- Consider hiding the need for IDs in codegen clients #3558
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:
- from @RonanQuigley
DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out.
- https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972
- https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766
- https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766
- 🐞 Dagger stop running when use docker dind as a service binding #5010
Activity
c-p-b commentedon Mar 1, 2023
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/
helderco commentedon Mar 1, 2023
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:
awaitthe result.id()a GraphQL query gets executed, but no BuildKit build is triggeredYou 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
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." ↩
samalba commentedon Mar 2, 2023
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 aPublish(), you see that the build is called and the image is published.Or if you inject a
.WithExec()before the.ExitCode(), the Build is also invoked.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.shykes commentedon Mar 3, 2023
Oh boy. This one brings back memories...
vito commentedon Mar 3, 2023
Just noting @phroggyy ran into this in Discord:
Note the lack of a hostname in
start <hostname> (<aliases>):. A missing hostname meansWithExec(nil)was never called, probably something like this:The fix:
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, andStderrcurrently returnnullif 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 thenullinto a zero-valueintorstringwhich is indistinguishable from a silent successful exit. (:scream:)Exec.helderco commentedon Mar 3, 2023
I agree. Erroring in those conditions would be more useful and clear.
vito commentedon Mar 3, 2023
Another thought I had is that this is a consequence of having
Containerrepresent both images and container execs. If we had a distinctImagetype,From()andBuild()would return anImagewhich doesn't even haveExitCode/Stdout/Stderrand can't be passed toWithServiceBinding.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 betweenContainerandImagetypes 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".
helderco commentedon Mar 3, 2023
Yeah, that makes sense.
samalba commentedon Mar 6, 2023
@vito or @helderco Does any one of you have some bandwidth to write a proposal to address this one?
vito commentedon Mar 6, 2023
@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
10 remaining items
shykes commentedon Mar 23, 2023
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.
shykes commentedon Mar 23, 2023
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: boolargument towithExec,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 ?
helderco commentedon Mar 29, 2023
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.
shykes commentedon Mar 29, 2023
Sorry I didn’t understand that. Passing a
lazy: boolparameter is not possible, or not convenient, or possible but doesn’t solve the problem? I didn’t get it.helderco commentedon Mar 29, 2023
I meant it's not possible because methods that send a request to the API have different signatures (context, return/raise error, coroutine/promise).
helderco commentedon Mar 30, 2023
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.exitCodeto force resolving lazyness 👎There's this common pattern of using
exitCodeto force executing1 a lazy pipeline. ButexitCodeis 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
exitCodeto 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:
Container { exitCode }doesn't work if the command fails #3192Runhelper #4723Is 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)toBuild().WithExec(nil).ExitCode(ctx)and landing onBuild().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
As in sending the request for the engine to execute, not necessarily executing a
Container's command. ↩helderco commentedon Apr 24, 2023
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
shykes commentedon May 1, 2023
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.helderco commentedon Jul 18, 2023
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:
c-p-b commentedon Jul 19, 2023
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
helderco commentedon Jul 21, 2023
I'm closing for now to focus on the documentation in #3617. Reopen if there's anything else.