Skip to content

DX: Pipeline Synchronization #4205

Closed as not planned
Closed as not planned

Description

@aluzzardi

UPDATE: New proposals with alternative solutions for the 3 problems described here have been created to facilitate more focused discussions:


I've noticed, either while dogfooding or looking at community demos, that the DX is lacking in synchronization mechanism and people are building workarounds around that.

Problem 1: Single pipeline synchronization

Sometimes, you want to synchronously wait for something to complete

Current workaround: Call a synchronous function and throw away the result.

, err = ctr.ExitCode(ctx)
, err = dir.Entries(ctx)

Proposed solution: Explicit Wait() function

ctr.Wait(ctx)
dir.Wait(ctx)

Problem 2: Multiple pipeline synchronization

Often times, you want to execute multiple pipelines in parallel (e.g. build & test). This is surprisingly tedious to do.

  • Workaround 1: Use a "join pipeline" + the workaround described for single pipelines
// Both return a `dagger.Container`, full async
testResult := test()
lintResult := lint()

// Do *something* that forces a wait on both
_, err := c.Container().From("alpine").
  WithMountedDirectory("/a", testResult).
  WithMountedDirectory("/b", lintResult).
  WithExec([]string{"ls"}).
  ExitCode(ctx)
return err
  • Workaround 2: Use language parallelization + above workaround
// execute synchronous functions in go routines
eg, gctx := errgroup.WithContext(ctx)
eg.Go(func() error {
  _, err := test().ExitCode(gctx)
  return err
})

eg.Go(func() error {
  _, err := lint().ExitCode(gctx)
  return err
})

return eg.Wait()

Proposed solution:

Introduce a dagger.Wait() synchronization helper:

return dagger.Wait(
  test(),
  lint(),
)

Problem 3: Orphaned pipelines

If a synchronous function is not explicitly called, the entire pipeline is orphaned:

lint()

testOutput, err := test().Stdout(ctx)

In the above example, lint is never executed.

Current workaround: Don't forget

Proposed solution: SDKs will automatically call Wait() on all pipelines upon session completion, forcing execution of "forgotten" pipelines

Activity

  1. shykes commented on Dec 15, 2022

    @shykes
    Contributor

    I like the primitive, but not sure about the name. Wait implies that something is already happening, and you want to wait for it to complete. But this primitive does more than that: it ensures that something actually happens, when otherwise it wouldn't. That's pretty different from eg. the Unix wait().

    I don't have a better name to offer though, sorry. Will try to think of alternatives.

  2. helderco commented on Dec 15, 2022

    @helderco
    Contributor

    Same. Like the idea but don't have a better name:

    await ctr.wait()  # 🤪
  3. helderco commented on Dec 15, 2022

    @helderco
    Contributor

    How about dagger.Do()?

    await dagger.do(ctr, dir, test(), lint())

    Similar to:

    $ dagger do test
  4. slumbering commented on Dec 16, 2022

    @slumbering
    Contributor

    Same. Like the idea but don't have a better name:

    await ctr.wait()  # 🤪

    Same ambiguity for Node.js.

  5. vito commented on Jan 12, 2023

    @vito
    Contributor

    I like the idea of trying to eliminate this pattern (wanted to open an issue for it, but found this one):

    code, err := ctr.ExitCode(ctx)
    if err != nil {
      return err
    }
    
    if code != 0 {
      return fmt.Errorf("container failed")
    }

    It'll appear in just about everyone's CI pipelines for running tests/smoke tests/other kinds of checks that don't have direct downstream dependents and only serve to gatekeep the pipeline.

    Right now the last 3 lines are redundant, but that's a bug (#3192). We shouldn't encourage _, err := ctr.ExitCode(ctx) because people will likely have to care about that exit code once that bug is fixed. Fixing the bug would mean all these cases silently ignore failures.

    Proposed solution:

    Introduce a dagger.Wait() synchronization helper:

    I prefer leaving this to the language runtime (option 2), but I'm not 100% sure. My motivation for that is to keep SDKs light and stay true to the promise of "pipelines as regular code" so people can use whatever concurrency primitives they normally do.

    I think my ideal would be something like (Container).Run(context.Context) error. Then you'd do something like this:

    // execute synchronous functions in go routines
    eg, gctx := errgroup.WithContext(ctx)
    eg.Go(func() error {
      return test().Run(gtcx)
    })
    
    eg.Go(func() error {
      return lint().Run(gtcx)
    })
    
    return eg.Wait()

    Even a theoretical Bash SDK should be able to handle concurrency:

    dagger do test &
    dagger do lint &
    wait
  6. marcosnils commented on Jan 13, 2023

    @marcosnils
    Contributor

    I prefer leaving this to the language runtime (option 2), but I'm not 100% sure. My motivation for that is to keep SDKs light and stay true to the promise of "pipelines as regular code" so people can use whatever concurrency primitives they normally do.

    +1. We (or the community) could build utility helpers around the SDK's to support this when needed. Following golang history, packages like errgroup weren't introduced in the language until they went through some time of the community using them and giving feedback. If we do have the necessity to use this today, we could create a new Go lib which helps until we validate it's what users really need.

  7. sagikazarmark commented on Jan 13, 2023

    @sagikazarmark
    Contributor

    Problem 3: Orphaned pipelines

    I have mixed feelings about this. On one hand, if I fail to notice that something is not executed, that could be problematic.

    On the other hand, I may want to leave certain containers out on purpose. Yes, I could just avoid creating them, but I kinda like knowing that they are lazily evaluated and only those are executed that become part of the final graph.

  8. robertu94 commented on Feb 28, 2023

    @robertu94

    I think it should be preferred to leave synchronization to the language, but ensure that is is marked in the SDK in such a way that tooling helps catch these errors. This means one less thing for users to learn and internalize when picking up docker.

    So what do I mean by tooling helps catch these errors? In languages such as C++ and Rust, it is possible to mark a struct as [[nodiscard]] or #[must_use], and the ways to create Future objects have this attribute. This means if a function returns an object of this type, the calling code must use it. That doesn't mean that the result must be acquired, but it must either be consumed with the the .get() method or it's equivalent, be explicitly canceled, or returned from the function with same restrictions. Python's asyncio.run has an option debug=True which enables similar warnings. I don't use go very often, but I believe go vet has a unusedresult warning I would expect should/could be made to catch this. I also don't use Javascript very often, but ESlint also has a no-floating-promises which also seems to do similar things.

  9. helderco commented on Mar 28, 2023

    @helderco
    Contributor

    I think we should bump the priority on figuring out a solution for this. There's lots of workarounds and confusion because we don't have this.

    Just to refresh, I like @aluzzardi proposals. I suggested "do" instead of "wait".

  10. helderco commented on Mar 28, 2023

    @helderco
    Contributor

    I prefer leaving this to the language runtime (option 2), but I'm not 100% sure. My motivation for that is to keep SDKs light and stay true to the promise of "pipelines as regular code" so people can use whatever concurrency primitives they normally do.

    I think it's good if you still have a way to use your language's primitives if you want, but still allow using a convenience where the SDK does it for you. I've seen a lot of people not reaching correctly for concurrency. It can make a bit impact on performance, not sure if people are using it enough.

    Even in Go, where it's considered easy enough to use, there's caveats to be aware of and so without a good understanding, it can become a burden to depend on that.

    TLDR: We could hide away the concurrency in SDK conveniences like this, but still allow an advanced user to use the language's primitives for more granular control.

  11. helderco commented on Mar 28, 2023

    @helderco
    Contributor

    Problem 3: Orphaned pipelines

    I have mixed feelings about this. On one hand, if I fail to notice that something is not executed, that could be problematic.

    On the other hand, I may want to leave certain containers out on purpose. Yes, I could just avoid creating them, but I kinda like knowing that they are lazily evaluated and only those are executed that become part of the final graph.

    We can just log a warning instead, silence-able by a setting or environment variable if too noisy.

  12. helderco commented on Mar 28, 2023

    @helderco
    Contributor

    This means if a function returns an object of this type, the calling code must use it. That doesn't mean that the result must be acquired, but it must either be consumed with the the .get() method or it's equivalent, be explicitly canceled, or returned from the function with same restrictions.

    Are you thinking more of "orphaned pipelines", or all of this issue's proposal? In Python, you get a warning if you ignore a coroutine (e.g., not using await). Fields like exit_code or stdout return a coroutine so the SDK is already flagging those as "must use".

    That's different from having a dynamic synchronization method to force executing an otherwise lazy pipeline, without resorting to exit_code as a common workaround, or executing multiple lazy pipelines concurrently for you.

  13. robertu94 commented on Mar 30, 2023

    @robertu94

    This means if a function returns an object of this type, the calling code must use it. That doesn't mean that the result must be acquired, but it must either be consumed with the the .get() method or it's equivalent, be explicitly canceled, or returned from the function with same restrictions.

    Are you thinking more of "orphaned pipelines", or all of this issue's proposal? In Python, you get a warning if you ignore a coroutine (e.g., not using await). Fields like exit_code or stdout return a coroutine so the SDK is already flagging those as "must use".

    Yes @helderco , I was principally addressing issue 3 with that comment. Tooling should help you identify orphaned pipelines.

    More broadly, I am advocating for Dagger to use language features and types (e.g. futures, go routines) to handle synchronization. If Dagger does this, tooling in each language should help detect orphaned pipelines.

  14. self-assigned this
    on Apr 4, 2023
  15. helderco commented on Apr 4, 2023

    @helderco
    Contributor

    Just an update: I've been thinking about this as I think it's very important for DX. I need to create a few related issues to keep discussions focused, then I'll update this with how things stand and push for a decision.

  16. helderco commented on Apr 11, 2023

    @helderco
    Contributor

    Looks to me that at least some of us like the general idea, there’s just a few concerns preventing this from moving forward.

    I’ve compiled the following list to see if we can untie these knots and move forward on a decision. I believe this is an important DX improvement that will hopeful simplify and clear some confusion linked to using other kind of workarounds.

    Anything missing here?

    Concern 1: Name

    • OP suggested .Wait() but people are unsure about the name
    • I suggested .Do() instead
    • Any more?

    Let’s not let bikesheding be the hill this dies on! 😅

    Concern 2: Orphan detection

    Some users may want to leave orphans on purpose. I suggested simply raising a warning that can be suppressed.

    I created a new issue for that, so we can keep this issue focused on synchronization:

    Concern 3: Replacing exitCode

    EDIT: Removed to not add noise. It can't replace .ExitCode as a pattern because we can't assume container execution. If you don't care about the result you need to .WithExec(nil).Wait(ctx) (or create a convenience Run(ctx) that does the same thing).

    Concern 4: Using the language’s concurrency

    Proposed solution is via an SDK helper:

    return dagger.Wait(
      test(),
      lint(),
    )

    Some users would rather depend on the language’s features for this, but I want to suggest both: this helper wouldn’t be a replacement for using the language’s concurrency, it would be a convenience or syntax sugar.

    I’ve seen users shy away from doing concurrency because they’re just not familiar with it and don’t want to invest time in learning it properly.

    I also think a lot of users aren’t well aware that using concurrency can make a big difference:

    When using an await inside an async function, some users think that it’s already asynchronous == concurrent, but that’s not true. You need a task group (in Python) or an error group (in Go) to make it concurrent.

    Perhaps some users also avoid it because it adds verbosity to their code and they don’t want that boilerplate. Ties back to not being aware that it’s probably worth it.

    I think reducing the “concurrency burden” on the user as much as possible, via an SDK helper for example, is definitely helpful (no pun intended 😁).

    It’s also useful just to reduce the boilerplate and make pipeline code simpler in (probably) most cases, including making it easier to port code between SDKs.

    Again, this would be just a convenience.

  17. changed the title [-]DX: Pipeline Synchronization[/-] [+]Proposal: Pipeline Synchronization[/+] on Apr 24, 2023
  18. gerhard commented on Apr 26, 2023

    @gerhard
    Contributor

    This keeps coming up in various conversations. Addressing it is important for moving forward.

    Having talked to @helderco about this, the primary blocker is the naming. We spoke about various names synchronously, went back-and-forth, and both settled on Sync(). The sync(1) semantics seem a natural fit for this context. There is a strong hint that this is the right name from the issue title, as well as how we talk about this problem in various comments (22 occurences of sync on this page, without the 5 hits in this comment).

    In the interest of moving this forward, if none disagrees with Sync() by May 1st, we would like to get this resolved via a new PR next week.

    cc @shykes @mircubed @d3rp3tt3 @aluzzardi @vito @marcosnils @sagikazarmark @robertu94


    Worth pointing out, this doesn't close the door on any of the concerns or ideas others mentioned. A few weeks ago, @helderco created a bunch of proposals for your concerns - see the link references a few comments above.

    Most importantly, anyone will be able to leverage their preferred language concurrency primitives, even when using Sync(). It would work exactly as @vito described above, just the name is different.

  19. d3rp3tt3 commented on Apr 26, 2023

    @d3rp3tt3
    Contributor
  20. robertu94 commented on Apr 26, 2023

    @robertu94

    After thinking about this some more. I'm not sure this is just a naming issue. Something to consider here. Laziness can be modeled and often is modeled returning a future, so why not do that here? instead of client.directory().docker_build() returning a Container, why not return a Future<Container>? I think that by returning things aren't explicitly futures, for things that are lazy is a root of this confusion.

    In C++ it is possible to explicity choose between a "lazy future" and an "eager future", but many languages default to lazy futures (python, haskell, javascript, in many cases rust), go while it doesn't have a native future type, but the paradigm recommended in the docs would be eager. Why can't we just use the Future api in each language here and use the name of the method provided by each langauge to do this?

    I realize that the API is not as ergonomic in languages without proper monadic operation support by default. But even in languages like Python that lack this you can rely on the ability to extend types to add a extension method on Future to provide .publish and other methods to chain these operations in a lazy what like it does now.

  21. shykes commented on Apr 26, 2023

    @shykes
    Contributor

    In the interest of moving this forward, if none disagrees with Sync() by May 1st, we would like to get this resolved via a new PR next week.

    I don't know exactly what proposal you're asking for a decision on?

    Currently I see this in the top comment:

    Part 1:

    Explicit Wait() function

    ctr.Wait(ctx)
    dir.Wait(ctx)
    

    Part 2:

    Introduce a dagger.Wait() synchronization helper:

    return dagger.Wait(
    test(),
     lint(),
    )
    

    Part 3:

    SDKs will automatically call Wait() on all pipelines upon session completion, forcing execution of "forgotten" pipelines

    Part 4:

    if none disagrees with Sync()

    I have several questions:

    • What parts of the proposal are renamed to Sync? Only part 1, only part 2, or both?
    • What are the types in part 1 and 2? Is this for Container only, or several types?
    • Which parts of this proposal are SDK-specific? Are there any new GraphQL API changes?
  22. helderco commented on Apr 26, 2023

    @helderco
    Contributor

    I'm working on updating this with a full proposal. Just to quickly answer your questions:

    Part 3:

    SDKs will automatically call Wait() on all pipelines upon session completion, forcing execution of "forgotten" pipelines

    In my last comment I suggested we abandon this in favor of another proposal, just for this point:

    What parts of the proposal are renamed to Sync? Only part 1, only part 2, or both?

    Both. The second is just calling the first on multiple lazy objects concurrently.

    What are the types in part 1 and 2? Is this for Container only, or several types?

    Several types, but I've yet to make a list. Whenever it can be useful to force an evaluation.

    Which parts of this proposal are SDK-specific? Are there any new GraphQL API changes?

    I'm thinking part 1 in the API (using an interface with a field for this purpose), part 2 in the SDKs (single query using the query builder or using the language's concurrency in a loop).

    I intend to put the spec in the proposal.

  23. busla commented on Apr 26, 2023

    @busla

    borrowing async/await syntax conventions from C#, JS, and eventually adopted by Python and Rust, might be helpful to streamline things between the Dagger SDKs. I'm not a Go expert (a total noob to be honest) so maybe this is out of wack, but maybe something like this?

    func main() {
    	ctx := context.Background()
    	client, err := dagger.Connect(ctx)
    	if err != nil {
    		panic(err)
    	}
    	defer client.Close()
    
    	futureContainer := client.Pipeline("test").
    		Container().
    		From("alpine").
    		WithExec([]string{"apk", "add", "curl"}).
    		WithExec([]string{"curl", "https://dagger.io"}).Async() // returns a promise
    	
    	container := futureContainer.Await()
    }
  24. changed the title [-]Proposal: Pipeline Synchronization[/-] [+]DX: Pipeline Synchronization[/+] on May 4, 2023
  25. helderco commented on May 4, 2023

    @helderco
    Contributor

    @busla, that doesn't seem worth it (also not a Go expert 😅).

    In Python and Node.js the async/await get out of the way, being actually syntax sugar for more verbose code (e.g., in Node.js it simplifies the Promise().then() syntax).

    In the non-Go SDKs, we only return "promises" on leaf values, i.e., when we want to make the GraphQL request. So the equivalent would be more like:

    out, err := client.Pipeline("test").
    	Container().
    	From("alpine").
    	WithExec([]string{"apk", "add", "curl"}).
    	WithExec([]string{"curl", "https://dagger.io"}).
    	Stdout().  // returns a generic Future[string]
    	Await(ctx)

    So this adds another step. Instead of just .Stdout(ctx) it's now .Stdout().Await(ctx), and it's still not enough to streamline like you said. Doing that in Go would add complexity without much benefit.

    We've also designed our SDKs with idiomatic code in mind.

    Anyway, this discussion is more suited to:

    It was actually the kind of thing we discussed in:

  26. helderco commented on May 4, 2023

    @helderco
    Contributor

    New proposals with alternative solutions for the 3 problems described in this issue have been created to facilitate more focused discussions:

    Please follow the appropriate issues as I'll close this one now.

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