Skip to content

Zenith Checks - #5659

Closed
sipsma wants to merge 38 commits into
dagger:mainfrom
sipsma:zenith-checks
Closed

sipsma wants to merge 38 commits into
dagger:mainfrom
sipsma:zenith-checks

Conversation

@sipsma

@sipsma sipsma commented Aug 17, 2023 •

Copy link
Copy Markdown
Contributor

This PR is the first chunk being split out from the original Zenith PR where we did prototype implementations of all the different entrypoints.

  • Splitting that monolith PR out into chunks is intended to make API bikeshedding more manageable and give us an opportunity to cleanup code from a fresh base, which should be much faster than trying to update the original PR.
  • Anyone working on Zenith should feel free to push to this PR. I'll also cherry-pick as much as feasible from the original PR.

It's intended to consist of:

  1. Base Environment API + implementation
  2. Check APIs + implementation
  3. Relevant CLI commands (dagger env ..., dagger checks)
  4. Support for the above in Go + Python SDKs
  5. Test coverage for all of the above.
  6. The ability to run the above tests as checks in the dagger CI env :-)

@sipsma
sipsma requested review from helderco, shykes and vito August 17, 2023 19:49
Comment thread core/schema/env.graphqls Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our longer term idea is for this to become an interface instead. I didn't include that here yet because I want to reserve the right to save that for follow up PRs.

The reason being that I suspect adding support for graphql interfaces may end up being a very significant chunk of work since it requires updates to the codegen for every SDK. That work will end up being worth it (I imagine we will have plenty of other use cases besides this one), but I don't necessarily want this PR to get blocked on that effort.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be pretty tricky to implement though but I can def see the benefit of supporting interface

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the rough outline would be that when there's a gql interface, the codegen produces whatever is closest to that concept in it's language:

  1. For Go and Typescript, it's literally just an interface in those language's syntax (ts has those iirc, right?)
  2. For Python, I guess it might literally just be a type annotation since the underlying objects are all dynamic anyways. Not sure though
  3. For Rust, a trait? Again, not sure
  4. etc.

I think that actually may be all that's fundamentally needed.

It would at least be nice-to-have the ability to also convert the interface into a concrete object (possible in raw graphql, in go it would be foo, ok := ifaceObject.(Foo), etc.). But I'm not sure if there is actually a hard requirement for that, so hopefully could be left out for sake of simplicity.

So honestly it might not be too much work for an individual SDK, at least in this early "theoretical" stage. I'm just more concerned that it's work * numSDKs :-)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Go and Typescript, it's literally just an interface in those language's syntax (ts has those iirc, right?)

For typescript it would be an abstract class or an interface, depending on what we want at the end.

For Rust, a trait? Again, not sure

Yep, a trait shall do the job

So honestly it might not be too much work for an individual SDK, at least in this early "theoretical" stage. I'm just more concerned that it's work * numSDKs :-)

Yeah totally but once it's done, we shall not touch it anymore, I think it's worth the time spent, I'm just scared that it change API at some point, I might be wrong tho.

I do not have a clear view of how API shall look using interface

Comment thread core/schema/env.graphqls Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am leaving out the Subresult apis in the original Zenith PR from here for now. I agree with the previous sentiments that it would be better if we can leave those out, so starting without them unless a strong need is proven.

Comment thread core/schema/env.graphqls Outdated
Comment on lines 65 to 125

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This API was suggested by @vito while he was implementing dynamic checks derived from go tests:

WithContainer(withCode.WithExec(testPkg)),

It's extremely convenient for those sorts of dynamic use cases, so I think we should start with it in the API. If we can find a better way of supporting dynamic checks that only relies on entrypoint env code, then it may become slightly redundant and we can consider whether we still need it.

Comment thread core/schema/env.graphqls Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also left out the previous APIs for check flags (i.e. parameters to checks) for now given our most recent conversation on the topic. This is another case where I think it's worth starting here and seeing how far we can get without them before considering re-adding.

Comment thread core/schema/env.graphqls Resolved

@TomChv TomChv left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left minimal comments as first review, I might fix these comments myself

Comment thread core/pythonruntime.go Outdated
Comment on lines 16 to 21

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it not be better to group these into a RuntimeConfig object to not have 7 different parameters?

Comment thread core/pythonruntime.go Resolved
@sipsma

sipsma commented Aug 19, 2023 •

Copy link
Copy Markdown
Contributor Author

Pushed an update w/ basically working refactored implementation.

Very happy with how things have cleaned up so far. A lot of the convoluted logic is just gone now via refactoring to have a clean split between core/schema doing all graphql stuff and core all the environment specific logic.

Subtleties around handling multiple possible return types for checks are still there, but it's now all concentrated into one block of code rather than splattered all over the place.

By far the biggest time sink was that I realized the previous implementation of currentEnvironment was mostly broken, only worked under extremely specific scenarios. That's fixed now.

What makes that API extremely tricky is that to be fully correct+consistent, you need to have it return the exact environment w/ ID matching the one currently being executed in, but that creates circular dependencies. After many attempts, I found a solution using CacheMap + our trick for passing uncached data to execs that seems to work so far. It's by far the most subtle behavior, but thankfully it should be totally re-usable for the rest of the entrypoint types.


Main TODOs left in terms of cleanup are to

  1. port the check result display to client-side after discovering the problems w/ doing it server-side in the Zenith branch earlier this week
  2. cleanup the go sdk code so that we don't have to write all the reflection/ast parsing in go templates (have a solution in mind for that now)

@sipsma

sipsma commented Aug 22, 2023

Copy link
Copy Markdown
Contributor Author

@vito just pushed a first attempt at the client-side display of checks; it looks okay-ish but I couldn't get the hierarchy to display exact how I want.
Screenshot 2023-08-21 at 8 26 14 PM

E.g. there it's showing sad-composite-check-from-dynamic-dep->yet-another-sad-composite-check but I really just wanted it to show yet-another-sad-composite-check. But when I tried to change it I ended up not getting any indentation at all.

Haven't totally groked the api for all that yet, so let me know if I'm just missing something obvious.

That screenshot is from running dagger checks in core/integration/testdata/environments/go/basic if you want to try it too.

@vito

vito commented Aug 22, 2023

Copy link
Copy Markdown
Contributor

@sipsma I'll see if I can figure it out! For what it's worth it took a few attempts on the zenith branch, and here's what I finally landed on:

https://github.com/sipsma/dagger/blob/d3973bf62288fab0dd3176a70aa97d53f0ac11e0/core/schema/env.go#L683-L713

In a nutshell:

  1. Create a group for each environment, so that multi-env check hierarchies are reflected. This also adds the outermost group in our demo, since there's the toplevel environment.
  2. If the current check is a leaf node, initialize a vertex for it and report the check results.
  3. Initialize another group for each vertex, after initializing the leaf node vertex, so that it's not a member of its own group. This extra group is for any Checks returned by the vertex. It's important that the leaf node's vertex itself isn't a member of this group, because that just results in extra noise. If nothing gets placed in this group, it will just not be displayed, so it doesn't hurt to create it before knowing whether we'll need it.

Comment thread core/env.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be worth cherry-picking this if you agree with the idea: sipsma@45fc541

It changes IDs to look like core.ContainerID:eyJ... and verifies the type matches the expected type when decoding. It's a little janky that it's tightly coupled to Go's %T representation, so that could be tweaked, but this is all internal plumbing at the moment anyway.

Tangentially related, I came across RFC-6920 today (via this post) which seems like a reasonable candidate format for our IDs. Maybe something like this?:

ni://dagger.io/sha-256;f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk?ct=application/x-dagger-container

Anyway, that's neither here nor there, just cool to see a relevant RFC, with some kind of fun implications like having https://dagger.io/.well-known/ni/sha256/f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk do... something interesting.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh nice thank you! I have a TODO: comment somewhere about backporting the cleaner fix to all this but hadn't taken the time to go track down which commit it was, appreciate it!

Tangentially related, I came across RFC-6920 today (via this post) which seems like a reasonable candidate format for our IDs. Maybe something like this?:

Ah neat! Honestly I'm still holding out that someday we'll have time to finally do the work needed to persist hash<->id mapping in the cache and be rid of needing to deal with anything like this, but the URL approach is super intriguing nonetheless since it would still probably make sense to support something akin to the current IDs externally as a "serialized DAG" format (similar to what you did w/ Bass IIRC)

@TomChv TomChv Aug 23, 2023 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tangentially related, I came across RFC-6920 today (via this post) which seems like a reasonable candidate format for our IDs. Maybe something like this?:

I love that too

Quick question about the article:

And while CDNs do support caching subsets of a whole object, there is no easy way for a RFC 6920 client to check whether their partial content is valid or not, as it uses a hash over the whole data, and not over a tree of parts.

Can this create issue with our cache? Like valid cache that should be invalidated or vice-versa? I do not have the full context of the id work but I'm trying to understand the whole logic.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this create issue with our cache? Like valid cache that should be invalidated or vice-versa? I do not have the full context of the id work but I'm trying to understand the whole logic.

@TomChv I don't think we would need to care about partial fetches/etc, since the object being referenced is relatively small - essentially a recipe for building a container image, and not the container image itself.

@sipsma

sipsma commented Aug 23, 2023

Copy link
Copy Markdown
Contributor Author

Thank you @vito for the improvements to the check output, looks much better now!

Screenshot_2023-08-22_at_6 49 06_PM

Just pushed an update to the ci/ env to delete the old project command code and now have a check for the engine integ tests, it's (mostly) working!

  • There are random test failures here and there, various things related to dagger-in-dagger (networking stuff mostly from what I can tell). Will take a closer looks but nothing that's really related to this PR deeply as far as I can tell so far.
  • One meaningful problem I ran into is that I implemented the check using dag.Check().WithContainer(...), but the container I returned had a local dir embedded in it. This caused problems because the Container is only evaluated later after the env has exited.
    • Worked around atm by just putting a .Sync call in the env code. There's various options for a "real fix"; my current favorite would be to take advantage of the fact that env entrypoints are actually just Container.WithExec calls and map any Host.Directory calls embedded in the LLB they return to read the files/dirs from the output of that Exec. I'm hoping opDAG can make that relatively straightforward
    • Will save that for a follow-up though since it's not actually related to checks per-se, independent problem that will impact entrypoints in general.

@TomChv

TomChv commented Aug 23, 2023

Copy link
Copy Markdown
Member

various things related to dagger-in-dagger (networking stuff mostly from what I can tell). Will take a closer looks but nothing that's really related to this PR deeply as far as I can tell so far.

We have that kind of issues in all our CI PR, all execution in dagger-runner are failing due to network errors (only few tests).

Do you think that it will also solve theses issues?

@sipsma

sipsma commented Aug 23, 2023 •

Copy link
Copy Markdown
Contributor Author

various things related to dagger-in-dagger (networking stuff mostly from what I can tell). Will take a closer looks but nothing that's really related to this PR deeply as far as I can tell so far.

We have that kind of issues in all our CI PR, all execution in dagger-runner are failing due to network errors (only few tests).

Do you think that it will also solve theses issues?

I sort of doubt it (would be happy to be wrong), the error I'm getting a lot in the new check is stuff like buildkitd: plugin type="bridge" failed (add): failed to create bridge "remote-cache-0env0": could not add "remote-cache-0env0": numerical result out of range, which I haven't seen anywhere else before.

Haven't tried debugging yet but I'm guessing I am just misconfiguring networking stuff or somehow hitting some new weird corner case due to the fact that this dagger-in-dagger setup is subtly different than our previous one (we are setting up the dagger-in-dagger engine from an environment, which is a nested exec that has API access back to the engine it's running in, rather than being a "host client" of the engine)

Comment thread core/schema/env.graphqls Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WDYT of adding a duration field here? I think that'd be important for measuring individual test performance over time. (And overall suite performance too.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I like that a lot! I think we'd probably want it to be measured by the shim and then persisted next to stdout/stderr/exitCode on the exec meta mount so that it's cached and linked to the exec itself.

Probably also worth storing it as startTime/stopTime unix timestamps so that we have the ability distinguish between "sum of durations of all checks" and "wall clock time" when stuff is running in parallel (maybe... some trickiness there obviously).

I don't think that's probably very difficult at all? So I'll give it a shot, but otherwise I'll just save for a followup.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some extra trickiness re startTime/stopTime: looks like JUnit XML only has a singular Time field so we're sort of painted into a corner there, unless we want to just have all three (duration / startTime / stopTime). I think we'd want to be able to do something like dag.StaticCheckResult(false, "test output", StaticCheckResultOpts{Duration: 12345}) to support JUnit. Not sure what granularity we really need. I suppose nanoseconds? 🤷‍♂️

@sipsma
sipsma force-pushed the zenith-checks branch 2 times, most recently from b88cfbb to c52f436 Compare August 26, 2023 19:11
@sipsma

sipsma commented Aug 28, 2023

Copy link
Copy Markdown
Contributor Author

Ran into some really tricky corner cases around environments and caching after adding the EngineTests check to the ci/ env. Fortunately found some pretty nice solutions that should squash those problems for both Check and the rest of our entrypoint types; they also improve the safety around how we handle local dirs in general for all of Dagger too.

The problems arose due to the fact that:

  1. The execution of environment entrypoint code and the results it returns are cached
    • This is a very good thing for performance and functionality, not a problem in and of itself.
  2. The results returned by environment entrypoint code can have various pieces of ephemeral/session-specific data embedded in them, e.g.
    • Local dir references that point to data created in the entrypoint exec (i.e. the entrypoint code creates some file and then loads it into dagger via dag.Host().Directory())
    • Service dependencies, which currently tie into session data due to DNS names being based on caller client IDs
    • Secrets created via SetSecret, which stores the secret in memory for the session

As a result, it was possible for us to load a cached entrypoint result, evaluate it, but then get errors because it refers to stuff that no longer exists (it was from a previous session where the entrypoint result was uncached and thus evaluated).

The solution comes in a few parts:

  1. Local dir imports are now implemented using a new custom source type called blob:// that lets us refer to the import as its content-addressed ID rather than as LLB instructions for loading a particular path from a particular client.
    • The implementation still does the same local dir sync as before, but rather than returning LLB for the local:// source, we put the synced dir into the content store and then create blob:// source LLB that points to that instead.
    • The part that requires extra careful handling is that buildkit would still be free to prune blob:// cache refs without pruning the entrypoint exec cache ref.
    • To solve that, after an entrypoint is evaluated, we walk the DAG of its result and gather all the blob:// contents it has a dependency on. Then we use the LeaseManager to add a dependency between the entrypoint exec cache ref and all those blobs, which ensures the blobs can't be pruned while the exec cache ref still exists.
  2. The problem w/ service DNS names is fixed by just re-arranging where the dns metadata gets provided. It used to be in Container.WithExec, which resulted in that metadata being embedded in the ContainerID, but now its set only when an Exec is actually being evaluated.
    • This is done in buildkit.Client.Solve via OpDAG rewriting
  3. The problem w/ SetSecret still exists, but the idea will be to just not allow SetSecret to be called in env code.
    • I don't believe there's any use case for this. Instead, secrets should always come from "the outside".
    • For now, "the outside" could only be client callers (where it would presumably be passed as a parameter one way or another)
    • Once we add support for SecretProvider as an entrypoint type, that will be another valid source. However, that implementation will not use SetSecret, instead it will be invoked "just-in-time" when a secret is needed (and without caching)

With all that in place, the errors I was getting when trying to run the EngineTests check after it has been cached are all gone; it runs fully cached now!

And like I mentioned, this solution will also squash the exact same problems for Artifacts and the other entrypoint types, so we should be on much more solid footing going forward now.

@vito vito left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Submitting partial review early for max async since I left a giant comment, I think I'll just go back to single comments instead of batched reviews, apologies in advance for notification spam

Comment thread cmd/dagger/check.go Resolved
Comment thread core/env.go Outdated

@vito vito Aug 29, 2023 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not blocking:

I was thinking about doing this as a quick sidequest, but I also have some broader concerns:

  1. Right now this will only give you the output of the last command you ran, which isn't always what you want. For example our own suite runs the tests but then runs a gotestsum utility to generate the test duration report. Maybe that's OK, since if it succeeded that's all we really care about, but it still seems like a potential gotcha. What if you ran tests and then added a boring command after it to clean up something-or-other or emit a metric? The test output would be more interesting there.
  2. Right now we're sort of encouraging a pattern where you load up all the output into memory and return it all at once, with that final big-bang of output being the source of truth for what we show in the CLI. We don't currently show any streaming logs to the user, which is kind of sad considering we have all of the infra for it, and I think that's what most users would want to see while they wait. You can see the last line of the earliest-started vertex in the status bar, which helps but is super limited.
    1. Returning an output string is a totally sensible API, but I wonder if we should optimize more for Containers and anything else that supports streaming output.
    2. In support of that, I think there may be practical issues with loading the full output into memory, since sometimes you can have a runaway build that generates a huge amount of logs. Not a new issue, but if we had streaming as the primary pattern it could reduce memory pressure on busy shared engines.
  3. It's often not obvious whether you need to collect Stdout or Stderr. This is solved by a combined Output API, but that's also weird because it will just fail if the command fails, and the command failing is technically part of the happy path when you're running tests, so it's kind of weird to effectively use an API that's "get me the output when it succeeds" which is the less interesting output!

Kind of a mess of scattered thoughts there, but my rough idea is to leverage WithFocus here and surface any focused vertices within a Check (whether that's a Container or through the Check entrypoint running things itself) all the way up to the CLI. But the tricky thing here is going away from the "return an output string" pattern implies some way to come up with the equivalent output, but now it might involve multiple vertices. Maybe we could handle this by streaming all output into one string, sort of like how bash scripts behave? Or maybe we somehow store Progrock events and replay them? (:grimacing: technically possible but needs more thought)

@sipsma sipsma Aug 30, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep here's my thinking on this whole topic (broadly aligned with yours, and also a set of scattered loose thoughts 🙂):

  1. It's important to our API that stdout/stderr are stored in the exec meta mount because that ties them to the cache of the exec.
    • Among other things, this ensures that our API works seamlessly with remote caching. E.g. .Stdout() is cached in the same way the filesystem of the exec is.
    • This doesn't mean that we can't support streaming or anything. It's just an important implementation constraint to keep in mind for all of this.
  2. We do indeed have the plumbing for streaming now, e.g. this method added as part of the previous re-arch mounts a file from buildkit's cache and streams it to the client (but for filesync): https://github.com/sipsma/dagger/blob/179525ff35a1e4c5b338472e47d350d4dbee8fb2/engine/buildkit/filesync.go#L254-L254
  3. Whether we stream or return giant strings or both, there's either way some low level work needed to make combined stdout/stderr work as expected
    • Namely, in order to support all 3 APIs of Stdout, Stderr and CombinedOutput, we need to store the two streams of data in such a way that they can be presented both separately and together, and when combined it would preferably be interleaved as close as possible to the same order they were written to the pipes.
    • My thought has been that we might need to continue to use separate pipes for stdout/stderr, but then as we read lines from them, store the lines structured in some way that indicates which stream they were from (e.g. with some "header" like [stdout]/[stderr]) and then write them all to the same file with that structure.
    • That way, if you want just the stdout, you read the file, grab the stdout lines, strip the structure and return that stream. Same for stderr. And for combined, just read all the lines.
    • Probably other approaches too though.
  4. I think you're spot on about "stdout/stderr of the most recent exec" being very limiting.
    • While this would be tricky in the details, I can definitely see it making sense to be able to walk the DAG underlying a container and grab all the stdout/stderr/combined streams of the focused execs only. It's just a matter of figuring out stuff like whether we only grab the "most recent series of focused execs", "all focused execs", etc.
    • I also wouldn't want this to be the only API; it should hopefully just supplement the ability to get this data from an individual exec.

If you're in agreement about 3, I think that we could at least implement that part as the foundation for everything else (whenever there's time obviously, it isn't exactly an emergency).

Comment thread cmd/dagger/check.go Resolved
Comment thread cmd/dagger/check.go Resolved
Comment thread cmd/dagger/check.go Resolved
Comment thread cmd/dagger/codegen.go Resolved
@sipsma

sipsma commented Aug 29, 2023

Copy link
Copy Markdown
Contributor Author

@vito thanks for the reviews so far! FYI I just pushed a commit that I'm almost done with. Just want to make sure that you aren't reviewing stale code (so far the comments are all applicable on a quick skim). I still need to fix up some failing tests in that most recent commit where dependency envs aren't always loaded when they need to be, but otherwise things seem to be working, so still safe to continue reviewing.

Will get back on the comments once I finish that up!

Comment thread core/schema/env.graphqls Resolved
Comment thread core/schema/env.graphqls Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking my understanding: we're able to be really restrictive here because the other side will always be implemented by one of our runtimes who uphold their end of this contract, rather than an exit code produced by running tests.

@sipsma sipsma Aug 29, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep exactly, for a little more background, the constraints we're working with here are:

  1. We want SDKs to support multiple return types for a given entrypoint
  2. We want SDKs to be as dumb as possible and implement as much server-side as possible
  3. For whatever SDKs do need to do, it's best if it's encoded in the api; or at min doc'd as part of that api
  4. For checks, we need to distinguish between "internal errors" (which should not result in execution being cached) and "check errors" (which should result in the error being cached)

So the schema you commented on here is basically where I landed in terms of the engine<->sdk contract. SDKs need to tell the server what the specific entrypoint is returning (Check, CheckResult, string, void) and use different exit codes to distinguish between "internal error" and "user code error".

  • I had a few different approaches to this earlier, but of the iterations that actually worked, this one resulted in the simplest code for the Go SDK

After that, the server does the rest of the magic needed to get the caching right. As part of this I actually added an internal ability for Container.WithExec to optionally cache execution of execs with non-zero exit codes: https://github.com/sipsma/dagger/blob/179525ff35a1e4c5b338472e47d350d4dbee8fb2/core/container.go#L1855-L1855

Which could hopefully come in use later if we want to re-use that as part of our public api.

Comment thread core/schema/env.graphqls Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Container.From gets a pass from me because it's so common and maps well to Dockerfile patterns, but this from feels like cheating. 😂

On the other hand, there's no real precedent for this. Everything else has a valid "zero" state which lets us build everything incrementally like withName and withSDK. Maybe this is just the easiest default name when there are multiple required values? Seems like the lesser evil to partial instantiation. The alternatives would be new or create but we don't want it to sound imperative, or that you are creating multiple instances when given the same args. Hmm...

@sipsma sipsma Aug 30, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haha yeah you pretty much outlined the entire saga I went through here.

I started out trying to refactor the env schema to use with* on everything, but quickly realized it gets extremely confusing (both for users and us).

So I then pivoted to only have with* on the fields which make sense to change after initialization.

And once I reached that point, my brain was consumed 100% with refactoring code, so I went with from because I didn't have time/neurons to think about it more 😄

But totally agree this name is worth re-thinking. It makes sense on some level in that you are creating an environment from those parameters, but I don't know how obvious that is.

... I'm kind of drawing a blank here still 🤔. I'll keep thinking though.

Comment thread cmd/dagger/env.go Resolved
Comment thread cmd/shim/main.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

neat!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH I hate the complication this added to the code (CurrentEnvironment is inherently complicated since it is self-referential and thus creates circular dependencies unless we are very careful), but yeah, it's neat now that it works! I'm also hopeful that we can find some simpler patterns for this in a future iteration, it felt like something that could be improved with another round of thought/eyes.

Comment thread codegen/generator/go/generator.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, so without this check would user envs have all of their entrypoints reflected on their own dag var after codegen?

Makes sense, but devil's advocate: theoretically it could be useful to call yourself through the DAG to leverage the entrypoint-level caching, instead of directly calling a sibling function. Would that "just work?" I'm not sure if it's worth exposing anyway, since it's a bit 🤯. So far I've been able to write mostly pure entrypoints that just chain API calls and don't return error, so in that case the entrypoint-level caching would be pure overhead.

BTW: is there anything stopping someone from creating an env called Container and overriding the internal API?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, so without this check would user envs have all of their entrypoints reflected on their own dag var after codegen?

Sort of, we actually stop that from happening in most cases much earlier than this code by only loading the env deps into the schema when generating for a given env.

I think this branch of code is leftover from the Zenith branch where we had universe, which was special because it was intrinsically loaded along side core. I'll try deleting this code from this branch to confirm.


Either way, yes totally agree being able to self call would be nice. The problem is the catch-22s you get yourself into when you're in the middle of writing env code, need to re-run codegen, but then it fails because your code doesn't compile. We ran into that in cloak and it was pretty maddening.

I would like to have this ability someday, but I think we'll need a radically different approach. My idea is that since we're already doing codegen + ast parsing, we can literally just take the user code and wrap it up such that when it's actually compiled, any direct call to another env entrypoint becomes wrapped in a call that goes through the actual server api (and thus wrapped in caching).

I'm pretty sure that isn't quite as crazy as it sounds; I think there's approaches to it that might actually be fairly robust. But it's still sort of crazy and thus something I'm not pursuing for now 🙂


BTW: is there anything stopping someone from creating an env called Container and overriding the internal API?

Yes, that should result in an error because there will be a conflict during the schema merging. Sounds like a good test case though to be sure :-)

@helderco helderco Aug 31, 2023 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

theoretically it could be useful to call yourself through the DAG to leverage the entrypoint-level caching, instead of directly calling a sibling function.

If I understand you correctly I plan on supporting this in Python, without needing or leveraging codegen:

# TODO: reserve __call__ for invoking resolvers within the same environment

General idea is this:

from dagger.ext import function

@function
async def build():
    ...

@function
async def test():
    await build()  # calls function directly
    # or
    await build.call()  # calls function via API/DAG
    ...

This is possible because the decorator can return an object that wraps the function and it already has everything it needs to use the query builder underneath without relying on codegen.

There's precedent for this pattern. For example, in Celery you can do my_task() to call a function in the current process vs my_task.apply_async() to send it to a worker.

In Prefect it's the opposite convention. You do my_task.fn() to call the function directly vs my_task() to run it in the Prefect task runner. Also my_task.submit() for running with the concurrent task runner (async).

I've not decided on which one should be the default or what the the method name should be for the other.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes total sense @helderco, this is definitely another area where I think we should be okay with each SDK having it's own sort of approach.

In Go, obviously nothing like that is really possible without adding overhead to the actual code the user writes (which I want to avoid at all costs, e.g. having them wrap funcs in some custom type that extends it with a method to call directly or with caching), so I think our only option there is to be more magical with some sort of codegen approach that rewrites funcs with that wrapping inherently.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're talking about always going through the API right? I was thinking on defaulting to a direct call since it seems less surprising, and explicitly requiring a my_func.call() to go through the API. That's the same as doing dagger.call(my_func), which can be done in Go as well.

You think defaulting to go through the API makes the most sense (when making a direct call)? I would want to think so, but seems like more surprising to users. It's just a matter of documentation though (like with Prefect).

However it does make a weird case if I create a @function that uses only lazy API methods (not async), because going through the API forces it to be async so there's a signature mismatch that's easier to enforce with the added my_task.call() method, or external call(my_task).

Should be the same in Go, requiring ctx and error.

@sipsma

sipsma commented Aug 31, 2023 •

Copy link
Copy Markdown
Contributor Author

@vito I just rebase on main and picked up the interactive TUI changes and made the change you suggested to delete these lines here.

When I run dagger checks -e ci --focus=false (I just like the unfocused output for those, it looks cool 😎), the output itself looks good but I can no longer exit the command (either ctrl-C or q). Did I miss something when updating?

@vito

vito commented Aug 31, 2023 •

Copy link
Copy Markdown
Contributor

@sipsma Huh, yeah that's weird. It seems to work fine for e.g. dagger run sleep 30. Maybe something is dropping the cancelable ctx that gets passed to the Run TUI callback? Looking into it!

edit: Pausing for now, I was able to confirm that the ctx passed along is indeed canceled at the right time, but I didn't find which spot is ignoring it.

Comment thread core/schema/env.graphqls
Comment on lines +176 to +177
The name of the entrypoint to invoke. If not set, then the sdk
is expected to return the environment definition.

@helderco helderco Sep 1, 2023 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about adding an Entrypoint.sync field to load the withCheck calls, etc, instead of via returnEntrypointValue?

Pseudo code (serve):

env = dagger.current_environment()
name = await env.entrypoint_input().name()

if not name:
    await env.sync()
    return

...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually started there; there were a few tricky parts because when we Sync this object in particular, the ID actually changes, so we hit the case you described here.

Those would be solvable with extra effort, but I ultimately went with the returnEntrypointValue approach anyways since not only avoids that whole problem but also ends up minimizing SDK responsibilities, moves as much to the engine as possible and gives us long term flexibility to modify how this works without updating every SDK:

  1. It's important for the implementation that the result we return is actually written to filesystem of the entrypoint exec (so that the result is cached as part of that exec).
    • Previously, that meant every SDK needed to know where to write that file. Now, they are agnostic to it; they just need to call that API.
  2. Centralizing what we write there entirely server-side is nice since we can very easily update it as needed, without any considerations around whether we'd impact the (non-internal) API of .Sync. It's highly plausible we'll want to make updates to the format of what we write or the details in how we process it since this is all intertwined with how the caching works.

@helderco helderco Sep 1, 2023 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I understand but it can be any other name like Environment.load that's marked internal. Otherwise this looks a bit odd:

await env.return_entrypoint_value(str(await env.id()))

You have to serialize/marshal in the SDK, etc, would be simpler to just:

await env.load()

I was confused if I can use the same environment instance because go sends the definition (id?) from a clean dag.CurrentEnvironment(). Is this required?

@wingyplus

Copy link
Copy Markdown
Contributor

I guess that Elixir failure because codegen handle incorrectly. Maybe it fixed with codegen improvement in #5557 plus some addtional change. I’ll looking a bit deeper tomorrow. :)

@gerhard gerhard removed this from the v0.? milestone Sep 12, 2023
@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@sipsma

sipsma commented Sep 29, 2023

Copy link
Copy Markdown
Contributor Author

Meant to close this before vacation, new iteration is here: #5757

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants