Skip to content

codegen: Chaining syntax - When to execute query (i.e., implicit vs explicit)? #3555

Closed

Description

@helderco

I started thinking about this for Python but we got feedback from user Luis Guzman on Discord: Chaining syntax, Confusing behavior.

Go SDK

[...] I've found the chaining syntax a bit... unintuitive.

Initially, it's just not very clear what actually executes the GQL, but ultimately I've figured out - just find whatever takes a context.

Even then there's the special case of ID that takes a context but doesn't run anything, but we may be able to change it in:

Python SDK

In Python it's worse, because it's simpler:

alpine = api.container().from_("python:3.10.8-alpine")
version = alpine.exec(["python", "-V"]).stdout().contents()
assert version == "Python 3.10.8\n"

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?

Activity

  1. sipsma commented on Oct 26, 2022

    @sipsma
    Contributor

    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:

    version = alpine.exec(["python", "-V"]).stdout().contents()
    assert version == "Python 3.10.8\n"

    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.

  2. helderco commented on Oct 27, 2022

    @helderco
    ContributorAuthor

    [...] 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:

    Screen Shot 2022-10-27 at 13 15 41

    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:

    Screen Shot 2022-10-27 at 13 11 07

  3. helderco commented on Oct 27, 2022

    @helderco
    ContributorAuthor

    For the "Return leaf as an object with execute" case I made a quick experiment:

    Screen Shot 2022-10-27 at 12 56 29

    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]`
    except Error:
        ....

    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.

  4. helderco commented on Oct 27, 2022

    @helderco
    ContributorAuthor

    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:

    version, err = stdout.Contents()
    
    # vs
    
    try:
        value = stdout.Contents()
    except Error as err:
        ...

    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:

    try:
        version = stdout.Contents().execute(session)
    except Error as err:
        ....
  5. jlongtine commented on Oct 28, 2022

    @jlongtine
    Contributor

    I think this (or something similar) is biting @plaisted in #3551

  6. shykes commented on Nov 2, 2022

    @shykes
  7. aluzzardi commented on Nov 2, 2022

    @aluzzardi
    Contributor

    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:

    • Go: functions taking a context
    • Python: async functions
    • Node: functions returning a Promise

    The problems with this are

    • This model is confusing as reported in multiple instances
      • Have to understand the "rule of thumb" in each language
      • Hides the core laziness concept behind magic
    • Python (@helderco: correct me if I'm wrong)
      • "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())
    • Node
      • @slumbering mentioned implicit doesn't work in TypeScript

    Proposal: Make execution explicit

    Possible Solutions

    • Explicit Inlined Execution
      • Add a method (for instance, Execute()) at the end of chaining to trigger execution
      • Example: out, err := ...Stdout().Contents().Execute(ctx)
    • Separate Execution Phase
  8. helderco commented on Nov 2, 2022

    @helderco
    ContributorAuthor

    Python (@helderco: correct me if I'm wrong)

    • "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):

    say-wat

    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().

  9. aluzzardi commented on Nov 2, 2022

    @aluzzardi
    Contributor

    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.

  10. aluzzardi commented on Nov 2, 2022

    @aluzzardi
  11. shykes commented on Nov 2, 2022

    @shykes
  12. aluzzardi commented on Nov 2, 2022

    @aluzzardi
    Contributor

    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
    // lazy
    container := c.Container().From("alpine").Command([]string{"echo", "foo"})
    
    // Optional: Explicitly force execution of container (somehow -- not sure how it'd work) whenever you want
    container, err = container.Execute(ctx)
    
    // Explicitly execute to grab a field
    stdout, 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

    Downside:

    • It's verbose entries, err := c.Host().Directory(".").Entries().Execute(ctx)
  13. 7 remaining items

  14. sipsma commented on Nov 3, 2022

    @sipsma
    Contributor

    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:

    1. With* means lazy (I'm still just building up the object by including something with it)
    2. 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.

  15. slumbering commented on Nov 3, 2022

    @slumbering
    Contributor

    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 
    const image = await new Api()
    .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.
    const sourceAfterInstall = await new Api()
      .container({id: image.id})
      .exec({args: ["yarn", "install"]})
    ...
  16. shykes commented on Nov 3, 2022

    @shykes
    Contributor

    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).

    I completely agree.

  17. added
    area/engine
    and removed on Dec 5, 2022
  18. removed
    area/engine
    on Dec 6, 2022
  19. slumbering commented on Dec 8, 2022

    @slumbering
    Contributor

    @helderco could we close this one ?

  20. helderco commented on Dec 8, 2022

    @helderco
    ContributorAuthor

    It's not resolved but since it's pending on user feedback we can reopen later if necessary.

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