You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
codegen: Chaining syntax - When to execute query (i.e., implicit vs explicit)? #3555
The query executes automatically when you call a method that returns a leaf value (i.e., scalar or enum) but this implicit behavior may be too confusing.
I'm wondering what's better:
# Pass client session as argument to leaf as in Go
...stdout().contents(session)
# Execute explicitly:value=session.execute(version)
# Return leaf as an object with `execute`
...stdout().contents().execute()
The last two options are also more flexible, opening up the possibility of selecting sibling fields into a single query.
Prior art
Database queries in Django return lazy objects. They are resolved when they're used. It's not exactly explicit but it's documented that some methods return a new QuerySet, while others return results.
It's also documented when the query is evaluated. It's not intuitive if you don't read the documentation otherwise you could be making a bunch of unnecessary queries. We're not optimizing for that yet, what I'm focusing on is the implicit vs explicit behavior.
Is documentation enough to keep usage simple or should we prefer more verbose but also more explicit usage?
Reacted by Steven Tobias, Erik Sipsma and Andrea Luzzardi
If you had skipped the .contents() then version would be some sort of object, not a string, right? And so wouldn't IDEs and the mypy linter (or however that works in python) notice that and highlight it/fail the type check?
I guess that's sort of the current approach in general: if the returned type is either a primitive value or a list/object consisting just of primitive values, then that means evaluation will run.
I'm not saying that's better than the other options, just kind of thinking out loud and trying to verify assumptions about type checking in Python are correct.
Luis Guzman on discord also said that the explicit execute makes sense:
makes some sense to me with an explicit call to eval. Especially considering your earlier comments about multiple commands being put together for more efficient llb solves. I could imagine chaining multiple commands together, then making a bigger call to execute() , with LLB doing the dirty work of solving parallel execution (like multi-stage docker)
I think we discussed something like that way early on but figured it would be unintuitive; was nicer to try and hide the laziness. Maybe it's worth reconsidering that though?
Is documentation enough to keep usage simple
I guess this is the absolute bare minimum we have to do; doc strings on the objects should indicate whether they are synchronously evaluated or not.
As a one off case, I think we should even consider just making Stdout and Stderr return strings directly rather than requiring an additional .Contents. That doesn't solve the general problem but it feels more intuitive to me.
[...] wouldn't IDEs and the mypy linter (or however that works in python) notice that and highlight it/fail the type check?
It depends on the usage. In this example there'd be no warning because we're doing a comparison. It'll just return False that File isn't that string.
If you try to access a string attribute (e.g., .lower()), in VS Code there's no warning:
I may need to tune Pyright (VS Code's type checker from Microsoft), not sure what's happening there. For now I've been focused on mypy which does raise the issue:
For the "Return leaf as an object with execute" case I made a quick experiment:
So this tells you that the version variable is a Result with a str value and we can say that these are executed when you try to access that .value. It's both lazy but also conventional.
You could also use it to call execute manually:
try:
value=version.execute() # inferred `value: str` because `version: Result[str]`exceptError:
....
I ok with the lazy behavior since I'm used to it. In Django you use laziness everywhere. You certainly don't need it to be lazy in this case, you can execute and return Result with the value already, but it does open up other possibilities do add something to that object which affects the query for example.
My opinion is that I'm ok with a some "implicit" if it has a convention. Either if it's passing the ctx in Go or just knowing that leaf values cause execution. Problem with that is that if it's a custom scalar it won't be obvious that's a leaf value. I can fix that with the Result or Leaf wrapper object.
In Go, you can also tell you're executing if you need to capture an error. I could do the same in Python, problem is it's not very Pythonic:
I don't want to be blocked on this so I think I'll move ahead with returning the wrapper object. It should be ok to change later if faced with overwhelming feedback in favor of something a bit more explicit like:
"rule of thumb" is not as clear as Go (no context and no error return)
"rule of thumb" is the async keyword: only works with async Python, no equivalent for sync
Python sync/async may require one function per resolver (e.g. contents() vs syncContents())
The rule of thumb is actually getting a Result object. That's because it supports sync as well and allows for easier testing/debugging. It's only an added "hint" in async that you only get coroutines (same as a promise in JS) only when you need to execute.
You can see in my latest PR, with the screenshot, that I'm trying to show off the type hint from the IDE. You can also see what is the expected type of .value (str in this case):
If you don't have type hints in your editor, you still have that Result object where you need to get result.value from, and it should be in the reference docs as well.
If I can't get leaves to support both sync and async at the same time, you're right that it becomes weird. It's easier to reason with .contents().execute() and .contents().execute_sync().
The rule of thumb is actually getting a Result object
Right. What I meant is, in Go, if you don't follow the rule of thumb, the code will NOT compile. Missing context, wrong number of return arguments. In Python it's much more subtle: you have to look at the return type from the editor hints.
Elaborating the Explicit Inlined Execution which to me right now is the one that makes most sense.
Nothing is ever implicit -- the API is always lazy (you're always building a "query")
There is an explicit Execute(), across all languages
optional nit: Exec() is renamed Command() or something
// lazycontainer:=c.Container().From("alpine").Command([]string{"echo", "foo"})
// Optional: Explicitly force execution of container (somehow -- not sure how it'd work) whenever you wantcontainer, err=container.Execute(ctx)
// Explicitly execute to grab a fieldstdout, err:=container.Stdout().Contents().Execute(ctx)
Rule:
Execute executes the query, including its parents and siblings (dependencies)
If you didn't Execute, it didn't happen
Execute is cached -- Executing the same nodes will yield the same result and is a no op if already done
Sort of late to the party here, but for Go I agree that we should wait for feedback from users after they start using the SDK w/ hidden IDs. Previously, any intuition users could develop about the model was shattered by ID being lazy yet returning error. I want to see whether intuition can develop now or if it's just shattered somewhere else (and if so, where).
If we do want more changes I think what @vito hinted at here is worth expanding on:
Maybe it's just a naming problem; Exec sounds more synchronous than WithX. I
We could make it so all our non-synchronous APIs are prefixed with With. So WithExec instead of Exec. This could also be combined with part of @shykes's suggestion: we could also change all synchronous APIs to be prefixed with Get.
So then the intuition becomes:
With* means lazy (I'm still just building up the object by including something with it)
Get* means "get me that value right now".
Part of this would imply that we change .Stdout().Contents() because .WithStdout().GetContents() doesn't make any sense. But tbh I already don't think it makes sense for those two to be split. .GetStdout() would make perfect sense to me though.
Maybe it's a good thing that this sort of naming scheme can guide us like that. Or maybe it's way too restrictive. We'd need to sit down and go through the whole API to find any gotchas where it breaks and results in unintuitive names.
Not convinced by this at all, just throwing it out there, but the more general idea of baking the lazy vs. sync intuition in the naming scheme does seem nice in that it would probably work across any language too.
Node @slumbering mentioned implicit doesn't work in TypeScript
However I'm concerned about the Typescript SDK, since the execution needs to be async, we cannot really apply for an implicit pattern.
Actually implicit does work, sorry if my explanation from yesterday was confusing. The problem was more how I was passing a container ID to another container while I was building a use case. The real issue is coming from how my Api works.
// Run the Engine, execute the query implicitely and return the result constimage=awaitnewApi().container().from({address: "alpine"}).exec({args: ["apk","add","yarn"]}).fs().id()// Re run an engine, so the image.id from above doesn't make sens anymore.constsourceAfterInstall=awaitnewApi().container({id: image.id}).exec({args: ["yarn","install"]})...
for Go I agree that we should wait for feedback from users after they start using the SDK w/ hidden IDs. Previously, any intuition users could develop about the model was shattered by ID being lazy yet returning error. I want to see whether intuition can develop now or if it's just shattered somewhere else (and if so, where).
Activity
sipsma commentedon Oct 26, 2022
Just some initial unsorted thoughts.
I think the options you listed are all worth considering, I do have some questions about the current state too though.
In this example:
If you had skipped the
.contents()then version would be some sort of object, not a string, right? And so wouldn't IDEs and the mypy linter (or however that works in python) notice that and highlight it/fail the type check?I guess that's sort of the current approach in general: if the returned type is either a primitive value or a list/object consisting just of primitive values, then that means evaluation will run.
I'm not saying that's better than the other options, just kind of thinking out loud and trying to verify assumptions about type checking in Python are correct.
Luis Guzman on discord also said that the explicit execute makes sense:
I think we discussed something like that way early on but figured it would be unintuitive; was nicer to try and hide the laziness. Maybe it's worth reconsidering that though?
I guess this is the absolute bare minimum we have to do; doc strings on the objects should indicate whether they are synchronously evaluated or not.
As a one off case, I think we should even consider just making
StdoutandStderrreturn strings directly rather than requiring an additional.Contents. That doesn't solve the general problem but it feels more intuitive to me.helderco commentedon Oct 27, 2022
It depends on the usage. In this example there'd be no warning because we're doing a comparison. It'll just return
FalsethatFileisn't that string.If you try to access a string attribute (e.g.,
.lower()), in VS Code there's no warning:I may need to tune Pyright (VS Code's type checker from Microsoft), not sure what's happening there. For now I've been focused on
mypywhich does raise the issue:helderco commentedon Oct 27, 2022
For the "Return leaf as an object with
execute" case I made a quick experiment:So this tells you that the
versionvariable is aResultwith astrvalue and we can say that these are executed when you try to access that.value. It's both lazy but also conventional.You could also use it to call execute manually:
I ok with the lazy behavior since I'm used to it. In Django you use laziness everywhere. You certainly don't need it to be lazy in this case, you can execute and return
Resultwith the value already, but it does open up other possibilities do add something to that object which affects the query for example.helderco commentedon Oct 27, 2022
My opinion is that I'm ok with a some "implicit" if it has a convention. Either if it's passing the
ctxin Go or just knowing that leaf values cause execution. Problem with that is that if it's a custom scalar it won't be obvious that's a leaf value. I can fix that with theResultorLeafwrapper object.In Go, you can also tell you're executing if you need to capture an error. I could do the same in Python, problem is it's not very Pythonic:
I don't want to be blocked on this so I think I'll move ahead with returning the wrapper object. It should be ok to change later if faced with overwhelming feedback in favor of something a bit more explicit like:
jlongtine commentedon Oct 28, 2022
I think this (or something similar) is biting @plaisted in #3551
shykes commentedon Nov 2, 2022
aluzzardi commentedon Nov 2, 2022
Summary of the situation
Today, some functions are "lazy" and don't result in an execution (e.g.
Stdout()) while others execute (e.g.Stdout().Contents(ctx)).The model is implicit (depending on whether it's a leaf node or not) with a "rule of thumb" in each language to hint which one is which:
The problems with this are
contents()vssyncContents())Proposal: Make execution explicit
Possible Solutions
Execute()) at the end of chaining to trigger executionout, err := ...Stdout().Contents().Execute(ctx)q := ...Exce().Foo().Bar(); client.Query(q)helderco commentedon Nov 2, 2022
The rule of thumb is actually getting a
Resultobject. That's because it supports sync as well and allows for easier testing/debugging. It's only an added "hint" in async that you only get coroutines (same as a promise in JS) only when you need to execute.You can see in my latest PR, with the screenshot, that I'm trying to show off the type hint from the IDE. You can also see what is the expected type of
.value(strin this case):If you don't have type hints in your editor, you still have that
Resultobject where you need to getresult.valuefrom, and it should be in the reference docs as well.If I can't get leaves to support both sync and async at the same time, you're right that it becomes weird. It's easier to reason with
.contents().execute()and.contents().execute_sync().aluzzardi commentedon Nov 2, 2022
Right. What I meant is, in Go, if you don't follow the rule of thumb, the code will NOT compile. Missing context, wrong number of return arguments. In Python it's much more subtle: you have to look at the return type from the editor hints.
aluzzardi commentedon Nov 2, 2022
shykes commentedon Nov 2, 2022
aluzzardi commentedon Nov 2, 2022
Elaborating the Explicit Inlined Execution which to me right now is the one that makes most sense.
Execute(), across all languagesExec()is renamedCommand()or somethingRule:
Execute, it didn't happenExecuteis cached --Executingthe same nodes will yield the same result and is a no op if already doneDownside:
entries, err := c.Host().Directory(".").Entries().Execute(ctx)7 remaining items
sipsma commentedon Nov 3, 2022
Sort of late to the party here, but for Go I agree that we should wait for feedback from users after they start using the SDK w/ hidden IDs. Previously, any intuition users could develop about the model was shattered by
IDbeing lazy yet returning error. I want to see whether intuition can develop now or if it's just shattered somewhere else (and if so, where).If we do want more changes I think what @vito hinted at here is worth expanding on:
We could make it so all our non-synchronous APIs are prefixed with
With. SoWithExecinstead ofExec. This could also be combined with part of @shykes's suggestion: we could also change all synchronous APIs to be prefixed withGet.So then the intuition becomes:
With*means lazy (I'm still just building up the object by including something with it)Get*means "get me that value right now".Part of this would imply that we change
.Stdout().Contents()because.WithStdout().GetContents()doesn't make any sense. But tbh I already don't think it makes sense for those two to be split..GetStdout()would make perfect sense to me though.Not convinced by this at all, just throwing it out there, but the more general idea of baking the lazy vs. sync intuition in the naming scheme does seem nice in that it would probably work across any language too.
slumbering commentedon Nov 3, 2022
Actually implicit does work, sorry if my explanation from yesterday was confusing. The problem was more how I was passing a container ID to another container while I was building a use case. The real issue is coming from how my Api works.
shykes commentedon Nov 3, 2022
I completely agree.
slumbering commentedon Dec 8, 2022
@helderco could we close this one ?
helderco commentedon Dec 8, 2022
It's not resolved but since it's pending on user feedback we can reopen later if necessary.