Skip to content

Proposal: Replace exitCode, stdout and stderr with new pattern #4921

Closed as not planned

Description

@helderco

Context

We have an outstanding bug when using exitCode, stdout and stderr:

These fields trigger the configured command to execute. Problem is that if the command fails, the common code that they all share returns an error. That isn’t the proper behavior. A proper GraphQL error would be for example that no exec was actually configured, or the network connection was suddenly killed.

This happened initially because we had a technical limitation, but it seems we can fix it now with the shim:

[…] this should be easier to fix now that we have the plumbing for collecting the stdout/stderr/exit status that we added for better error messages.

- Originally posted by @vito in #3192 (comment)

Problem

There’s a lot of confusion around using exitCode as a way to trigger command execution in a lazy pipeline:

Some users are doing things like if exitCode != 0, which doesn’t work now but would if the bug was fixed. In the meantime, they’re probably not aware that branch of their pipeline code never gets executed.

On another hand, users that are aware of the issue, find themselves in the need of parsing the error message to extract these fields (e.g., using a regex pattern), which is the only workaround they can use, but one I’d love to make obsolete.

Adding to that, you need to be aware that a GraphQL error here could be something that’s not related to the command that was executed (e.g., command not configured or network error):

func exec(ctr *dagger.Container, ctx context.Context) (bool, error) {
    exitCode, err := ctr.ExitCode(ctx)
    if err != nil {
        msg := err.Error()
        // This could be a network error,
        // or command not configured,
        // for example.
        if strings.Contains(msg, "exit code:") {
            return false, nil
        }
        return false, err
    }
    // FIXME: will never be != 0 so need to 
    // extract the actual code from error message
    return exitCode == 0, nil
}

And in case of success, you have to make multiple network requests to get the other fields:

exitCode, err := ctr.ExitCode(ctx)
if err != nil {
    return err
}
stdout, err = ctr.Stdout(ctx)
if err != nil {
    return err
}
stderr, err = ctr.Stderr(ctx)
if err != nil {
    return err
}

There’s also the very common pattern of using .ExitCode(ctx) to just force command execution in a lazy pipeline, not caring about the actual exit code value and maybe relying on the side effect of a bug (GraphQL error) to abort the pipeline (exceptions in Python and NodeJS).

This pattern has become so common that users reach for .ExitCode(ctx) even when they don’t actually want the configured command to execute, they just want to synchronize laziness (e.g., see if a Dockerfile build succeeds).

Because of all of this, fixing these fields has been flagged as a priority, but it’s currently stuck because so many users rely on it now.

Solution

I think the best way to move past this problem is to:

  1. Create new API call to get the exit code, stdout and stderr as values, even on command failure;
  2. Deprecate current exitCode, stdout and stderr (i.e., print warning when these are used);
  3. Encourage users to migrate to new pattern to run commands (e.g., update docs);

This deprecation path into a new pattern solves the backwards compatibility problem, while also seizing the opportunity of improving it.

Option 1: Returning a new simple object

This is my preferred solution. It’s explained in more detail in:

In summary, I think it would be great to get all of these fields in a single API request at once:

query {
    withExec(...) {
        execResult {
            exitCode
            stdout
            stderr
            error
        }
    }
}

And without relying on a GraphQL error:

res, err := alpine.WithExec(...).ExecResult(ctx)
if err != nil {
    // example: no command has been executed, or network error
    return err
}
// no need for `res.exitCode != 0`
if res.Error {
    // can do anything: abort pipeline, just log, switch behavior...
    // depends on what user wants, as it's not always the same
    fmt.Printf("Failed with exit code %d\n", res.ExitCode)
}
// all fields are always received as values, even on non-zero exit code
fmt.Println(res.stdout)
fmt.Fprint(os.Stderr, res.stderr)

That’s the best DX in my opinion.

Option 2: Returning a new object, but without codegen

Without codegen returning the multiple fields in the same request, you can still use the same API change to encapsulate these fields and allow migrating to a new pattern while deprecating the old.

You’d still need to make multiple network requests to get the multiple fields which isn’t fun though.

Option 3: SDK helper

If we can’t make an API change that every SDK benefits from, but there’s still a pattern where everyone is reinventing the same wheel, we should at least provide helpers in the SDKs that can be imported an reused by everyone.

The downside is that it has to be re-implemented in every SDK, but at least it would allow hiding the error parsing and getting all values concurrently in case of success, from users.

(pseudo) Python POC
@dataclass
class ExecResult:
    stdout: str
    stderr: str
    exit_code: int
    error: str | None = None


async def exec(ctr: dagger.Container) -> ExecResult:
    try:
        return ExecResult(
            await ctr.stdout(),
            await ctr.stderr(),
            await ctr.exit_code(),
        )
    except dagger.QueryError as e:
        msg = str(e)
        if "exit code:" not in msg:
            # This could be a network error,
            # or command not configured,
            # for example.
            raise
        # basically extract the various components from the error message
        # this is the format:
        #     process “<command>” did not complete successfully: exit code: <exit code>">
        #     Stdout:
        #     <stdout>
        #     Stderr:
        #     <stderr>
        return ExecResult(
            stdout_from_error(msg),
            stderr_from_error(msg),
            exit_code_from_error(msg),
            error_message(msg),
        )


async def lint():
    ctr = dagger.container(...)
    result = await exec(ctr)
    
    # you can choose what to do with the error
    # (e.g., abort, log, ignore...)
    if result.error:
        raise MyCustomError(result.error)

Alternative proposals

@vito proposed the following:

It depends on keeping the same GraphQL error, while ignoring the return value for exit code. However, as I said in Context, using the GraphQL error is not an appropriate use for this. It would be better to return a new Error type as a value instead, but then I think the above solution is a better implementation of that.

Activity

  1. mircubed commented on Apr 10, 2023

    @mircubed
    Contributor

    @samalba @gerhard can you confirm who needs to approve this proposal, so we can move forward with implementation?

  2. vito commented on Apr 10, 2023

    @vito
    Contributor

    Thanks for putting this together! Glad to see progress around this thorny area.

    Some scattered feedback from a couple different perspectives, but all just my $.02c:

    • I don't think users should feel compelled to write code like if res.failed { print("failed:", res.code) }, or even write code to print stdout/stderr in the happy path. It seems like a lot of overhead for something you're doing with Dagger 99% of the time. I think this pattern is mostly a result of having poor visibility when running Dagger, but we have dagger run now which should help a lot.

    • As an end user scripting pipelines in Dagger, in most cases I don't really care about the different types of errors that might happen. I just want to write optimistic code with minimal error handling noise, similar to Bash with set -e. I want to be able to identify the root cause for any errors that might come out, but I don't want to have to code against those all the time. Personally, I don't think I would ever handle a GraphQL, network error, or "command not found" error any differently from a command failing, but again I'm talking about the typical case here, not saying it never happens.

    • On the other hand, as someone hypothetically writing an orchestration layer on top of Dagger (say a CI control plane, or Bass's Dagger runtime), I can see value in programmatically identifying the root cause for errors. For example, Concourse made a distinction between "errored" and "failed" CI build states, which let the user know if there was an internal infra failure (=> rerun build) or if their build legitimately failed (=> investigate). It's worth noting that "command not found" was classified as a failure, not an error, since that's not likely to recover on its own.

    • There will be cases where the API caller wants to fetch exitCode but specifically avoid fetching stdout and stderr. For example, a CI control plane that's already equipped to collect stdout/stderr via the progress stream won't need to collect them again, and in fact would probably not want to fetch them just in case someone printed 1GB of logs. (It can easily happen with a runaway loop and a long enough timeout.)

    • If we're adding the ability to distinguish error cases for Container.WithExec, wouldn't we need to make the same consideration for other APIs? For example, Container.Build might fail when running the Dockerfile, but it also might fail to even locate the Dockerfile, which is analogous to "command failed" vs "command not found."

  3. helderco commented on Apr 11, 2023

    @helderco
    ContributorAuthor

    Thanks for the feedback @vito 🙂

    What to do with field error?

    I don't think users should feel compelled to write code like if res.failed { print("failed:", res.code) }, or even write code to print stdout/stderr in the happy path. It seems like a lot of overhead for something you're doing with Dagger 99% of the time. I think this pattern is mostly a result of having poor visibility when running Dagger, but we have dagger run now which should help a lot.

    As an end user scripting pipelines in Dagger, in most cases I don't really care about the different types of errors that might happen.

    You shouldn’t feel compelled to do anything with stdout/stderr/exitCode. At a minimum, just an if res.Error allows a distinction between error types. I still think it’s useful to make that distinction:

    res, err := ctr.WithExec(...).ExecResult(ctx)
    if err != nil {
        // example: no command has been executed, or network error
        return err
    }
    if res.Error {
        // can do anything: abort pipeline, just log, switch behavior...
        // hard to generalize, it depends on needs
    }
    
    // continue with pipeline

    If you’re executing a go test, having a failed network connection would make you believe the tests failed, which isn’t the case.

    I’ve seen multiple different needs for what to do when a command fails (abort, log, switch behavior…). Even on the same project. You’re focusing on just printing the error but that’s not on my mind when I think of it.

    The “happy path”: Run() convenience?

    I just want to write optimistic code with minimal error handling noise, similar to Bash with set -e. I want to be able to identify the root cause for any errors that might come out, but I don't want to have to code against those all the time.

    I get what you’re saying, I also want that as much as possible. But it feels like we need a convenience on top, as I still think we need to replace exitCode.

    Initially I also wanted to write another proposal to add a convenience like .Run(ctx) for that happy path and when you don’t care about any result, just success or failure. The reason I didn’t submit it is that now we’d have two ways to execute a container command, while this attempts to simplify things.

    Maybe the usefulness of this added convenience trumps the disadvantage of having multiple ways to do the same thing. If so, this is how I was going to suggest it.

    Still attached to the idea of not depending on the GraphQL error for command as a normal condition, seemed better to return a Error type in data on command failure, while keeping errors for “failing to resolve a field”.

    interface Error {
        message: String!
    }
    type ExecError implements Error {
        exitCode: Int!
        stdout: String!
        stderr: String!
    }
    type Container {
        run(): ExecError
    }

    So this means returning null on success, and ExecError on failure. Notice that I’m avoiding using a Union for success and error conditions because of Go.

    In Python I just want two different exception types (e.g., QueryError vs ExecError), so the happy path is still await ctr.run(), nothing to return, but if I choose to capture that exception, I can capture either one, or both if I want to.

    In codegen, you can check if a value implements the Error interface and raise an exception, instead of returning a value:

    # don't care, just abort!
    await ctr.run()
    
    # abort only on server errors,
    # but catch command failure
    try:
        await ctr.run()
    except dagger.ExecError as e:
        log.error(e)
        return False
    return True

    NodeJS is similar and the same can be done in Go:

    // don't care, just abort!
    err := ctr.Run(ctx)
    if err != nil {
        panic(err)
    }
    
    // abort only on server errors,
    // but catch command failure
    err := ctr.Run(ctx)
    if err != nil {
        if execErr, ok := err.(dagger.ExecError); ok {
            log.Error(execErr)
            return false
        }
        panic(err)
    }
    return true

    Although that second case looks simpler with ExecResult in Go:

    res, err := ctr.ExecResult(ctx)
    if err != nil {
        panic(err)
    }
    if res.Error {
        log.Error(res.Error)
        return false
    }
    return true

    Different error types don’t matter?

    Personally, I don't think I would ever handle a GraphQL, network error, or "command not found" error any differently from a command failing, but again I'm talking about the typical case here, not saying it never happens.

    We lack hard data on what’s the most common use cases, so we can only rely on our impressions. 😇

    Don’t agree with this part though. Of course it depends on personal needs, but I’ve seen enough cases where users simply aren’t aware of this difference and always treat the error as if the command failed. Whenever I’ve pointed out that you need to look in the error message for “exit code:” (especially on bigger pipelines), no one has told me they don’t care that, but it always feels like a big, non-intuitive caveat to teach/learn. A stop gap, really.

    Based on what I’ve seen, I don’t think I can generalize not caring about this difference as the most typical case (after considering awareness that there’s a difference in the first place). I’d rather have the distinction be clearer and provide a convenience for that “happy path” or when it doesn’t matter.

    Errored vs failed

    On the other hand, as someone hypothetically writing an orchestration layer on top of Dagger (say a CI control plane, or Bass's Dagger runtime), I can see value in programmatically identifying the root cause for errors. For example, Concourse made a distinction between "errored" and "failed" CI build states, which let the user know if there was an internal infra failure (=> rerun build) or if their build legitimately failed (=> investigate). It's worth noting that "command not found" was classified as a failure, not an error, since that's not likely to recover on its own.

    Just to be clear, there’s a difference between a “no command has been executed” error and a “command not found” error that we actually never return. What gets returned instead is process "wat" did not complete successfully: exit code: 1 (with empty stdout and stderr).

    The latter one is handled the same as any existing command’s non-zero exit. Perhaps it should be a GraphQL error there. How can a command that doesn’t exist return any exit code? Unless you run it in a shell sh -c "wat". Even then, it’s a 127 exit code, not 1.

    But yes, some users are making a report for the result status of multiple sub-pipelines (even concurrent), and they need to differentiate between a “pipeline authoring” error and a “code under test” error, for example.

    When stdout is unwanted?

    There will be cases where the API caller wants to fetch exitCode but specifically avoid fetching stdout and stderr. For example, a CI control plane that's already equipped to collect stdout/stderr via the progress stream won't need to collect them again, and in fact would probably not want to fetch them just in case someone printed 1GB of logs. (It can easily happen with a runaway loop and a long enough timeout.)

    I actually didn’t think about that. Fetching the other 2 values when you only care about 1 seemed harmless enough, but I didn’t consider a huge stdout/stderr.

    However, in case of an error, we’re already sending all 3! In the case of success, I suggest maybe using the .Run() convenience from above.

    When you only need exit code, in the success path, it’s always zero. On error it can be returned on ExecError. The only problem is if you only need stdout and really don’t want stderr, or vice versa.

    To be clear, I’m assuming option 1 for ExecResult here. Not an issue otherwise.

    Different error types in the API

    If we're adding the ability to distinguish error cases for Container.WithExec, wouldn't we need to make the same consideration for other APIs? For example, Container.Build might fail when running the Dockerfile, but it also might fail to even locate the Dockerfile, which is analogous to "command failed" vs "command not found."

    Yes, you’re totally right. That’s part of why I reported this:

    That was my priority a little over a month ago, but put in on pause to deal with other things. It’s high on my list to return to next.

  4. vito commented on Apr 13, 2023

    @vito
    Contributor

    Thanks for the breakdown! 😄

    I don't want to dominate the airwaves with just my perspective, but my main concern is that this addresses the problem of "the user doesn't know what failed" by forcing them to handle those different cases in their code. That extra 3 lines of error checking seems like it will become pretty tiring because it applies to Dagger's "bread and butter" (running commands). My concern with if res.error { print } wasn't necessarily about printing, it was about having to do anything at all - including just propagating the "inner" error. I'd almost immediately write a helper to hide it away.

    If the goal is just to elucidate failure modes, there are other approaches we could consider:

    • Returning structured errors from the API + SDK (Go error types, Python exception classes etc)
    • Improving error messages in general (inspiration)
      • This is probably challenging with all our SDKs, but seems worth considering
    • Better UIs for seeing the whole system and pinpointing where failures happen (dagger run)

    dagger run addresses a lot of these issues, and it only just came out, so I'm hesitant to put a lot of weight on patterns and failure modes that emerged from a world where it didn't exist.

    Also: still totally in support of being able to distinguish errors in code somehow, as I mentioned it would be useful for Dagger based CI systems/etc. Really just worried about getting grumpy with all the error checking I already have to write in Go. 😅

    Also pt. 2: if we have this API but also ship a helper that lets you write less code, I have no qualms, though I suspect #4700 might still be a more fruitful investment for the rest of the API.

  5. helderco commented on Apr 17, 2023

    @helderco
    ContributorAuthor

    [...] Really just worried about getting grumpy with all the error checking I already have to write in Go. 😅

    I think I've addressed this, but I'll re-organize things to make your concerns clearer.

    Also pt. 2: if we have this API but also ship a helper that lets you write less code, I have no qualms, though I suspect #4700 might still be a more fruitful investment for the rest of the API.

    I always take #4700 into consideration because that's something that should be done regardless. I just haven't had time yet to formalize that design change.

  6. helderco commented on May 10, 2023

    @helderco
    ContributorAuthor

    I’ve thought about this some more and I’m withdrawing this proposal.

    Considering the following issues:

    We’re left with just stdout and stderr.

    All that remains then is to be able to get the full output (not truncated) in case of a failure:

    I’ve been thinking on a few solutions for that as well, so I’ll discuss it in that issue.

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

Metadata

Metadata

Assignees

No one assigned

    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