Skip to content

Context directory #7647

Closed
Closed

Description

@shykes

This design is a subset of #7199 and #7432 . It intentionally keeps a narrow focus, to allow for rapid implementation, and easing user pain as soon as possible.

Problem

Dagger modules are often contextual: they are used in the context of another software projet. Almost always, these modules need to access their context directory - typically the project's source code.

  • Today a module cannot directly access its context directory. Instead it must be passed by the caller as an argument. This is inconvenient.
  • To make things worse, modules cannot filter the contents of the context directory. This is essential to avoid the prohibitive cost of uploading a huge monorepo on every task.

Solution

Give modules the ability to access their context directory at runtime.

Proposed design

Status

Spec

To access the context directory, simply set a default value to your directory arguments. When applying the default value, the engine will interpret it as a path in the module's context directory, and pass the corresponding directory.

  • The context directory is the git repository containing the module. If there is not git repository, the context is simply the module.
  • Relative paths are relative to the current source file, scoped to the context directory for security
  • Absolute paths are rooted in the context directory
  • There is no limit to the number of directories which can have default values of this sort
  • Optionally, directories can be filtered with a gitignore-style annotation

In this example, we use this technique for several files and directories, with a mix of relative and absolute paths.

// Build the app
func (app *App) Build(
  // Frontend source code
  // +default="./frontend/src"
  frontend *Directory,
  // Backend source code
  // +default="./backend/app/src"
  // +ignore=["*", "!**/*.go", "!go.mod", "!go.sum"]
  backend *Directory,
  // Build tool configuration, shared across the monorepo
  // +default="/tools/builder.conf"
  buildConfig *File,
) *Directory {
  // Execute the build as usual
}

Caching considerations

We favored a design that used function arguments, rather than core function calls (dag.Foo()) because it makes it easier to protect caching. In this design, the engine always knows exactly which subset of the context directory, if any, a function needs. So it can invalidate cache if, and only if, that subset changes. This allows for massive performance optimizations in large monorepos especially.

Relationship to other proposals

This design is a subset of #7199 and #7432 . It intentionally keeps a narrow focus, to allow for rapid implementation, and easing user pain as soon as possible.

Activity

  1. shykes commented on Jun 13, 2024

    @shykes
    ContributorAuthor

    FYI @vito @sipsma @sagikazarmark @TomChv @kpenfound @rawkode

    As previously discussed. This is the more narrowly scoped "phase 1" of contextual modules, that hopefully we can fast-track.

  2. sagikazarmark commented on Jun 13, 2024

    @sagikazarmark
    Contributor

    I like it. Also, good job on narrowing the scope. I suspect this will stay useful even if the concept of contextual modules change in the future.

    How is this going to behave in reusable modules? What's the context directory in those cases (when the module is actually called from another module)?

    I know I already asked this, but just to clarify: if I call a remote module, the context directory is going to be that module's repository, right? (Is .git. preserved for remote module calls?)

  3. helderco commented on Jun 13, 2024

    @helderco
    Contributor

    I have questions about the implementation.

    To access the context directory, simply set a default value to your directory arguments. When applying the default value, the engine will interpret it as a path in the module's context directory, and pass the corresponding directory.

    The SDK still needs an API to communicate this to the engine. Would it be the new dag.Context().Directory(...)? For SDKs that support default values, that API would be used directly.

    However, I suppose the engine needs this information during load so it would have to be reported in the argument definition itself in the TypeDef system somehow, is that right @sipsma?

    • The context directory is the git repository containing the module. If there is not git repository, the context is simply the module.

    This matches today’s context directory, but If this is a stepping stone into #7199 where the context directory is the parent directory it will be a breaking change later. Does it make sense for this path to match that proposal instead?

    • Relative paths are relative to the current source file, scoped to the context directory for security

    The engine doesn’t have any knowledge of source files, so the SDK needs to resolve the path in relation to what? "source" directory is what makes the most sense because that’s what the SDK’s language code knows about.

    I think it would be easier to be relative from the source dir from the get go (user facing), instead of the source file. For example, assuming backend is a sibling directory of <module source>:

    # <module source>/src/main/main.py
    def build(
        self,
        frontend: dagger.Directory = dag.context().directory("../backend/app/src"),
    ) -> dagger.Directory:
        ...

    Otherwise, this would be pretty common in Python because the function code isn’t in the root of the module’s sources like in Go:

    # <module source>/src/main/main.py
    def build(
        self,
        frontend: dagger.Directory = dag.context().directory("../../../../backend/app/src"),
    ) -> dagger.Directory:
        ...

    Note that using dag.context().directory() doesn't make sense that the relative path is not the context directory, so this would have to be a different API method. Also, the solution may require that this be done through the TypeDef registration phase so it would look even more different (but less consistent if not using dag here).

    Just making a point on why relative to source code file isn't optimal.

    • Absolute paths are rooted in the context directory

    👍

  4. shykes commented on Jun 13, 2024

    @shykes
    ContributorAuthor

    To access the context directory, simply set a default value to your directory arguments. When applying the default value, the engine will interpret it as a path in the module's context directory, and pass the corresponding directory.

    The SDK still needs an API to communicate this to the engine. Would it be the new dag.Context().Directory(...)? For SDKs that support default values, that API would be used directly.

    I don't know. Ideally we would not add a new dag.Foo() call to the API to implement this, just to keep the user-facing change as simple as possible.

    • The context directory is the git repository containing the module. If there is not git repository, the context is simply the module.

    This matches today’s context directory, but If this is a stepping stone into #7199 where the context directory is the parent directory it will be a breaking change later. Does it make sense for this path to match that proposal instead?

    I think we should focus on this, and accept that it might require adapting #7199. I'm OK with that.

    Note that in this proposal, the term "context directory" becomes less important to the user. Not much different from today actually.

    • Relative paths are relative to the current source file, scoped to the context directory for security

    The engine doesn’t have any knowledge of source files, so the SDK needs to resolve the path in relation to what? "source" directory is what makes the most sense because that’s what the SDK’s language code knows about.

    Yeah that makes sense. It's unfortunate from a UX point of view, but I see how it might be unavoidable. @vito you suggested the relative-to-file idea, wdyt? Is relative-to-source-dir ok?

  5. shykes commented on Jun 13, 2024

    @shykes
    ContributorAuthor

    I like it. Also, good job on narrowing the scope. I suspect this will stay useful even if the concept of contextual modules change in the future.

    Yes agreed! And by the way the ignore part is actually orthogonal to context: even if the caller overrides the default value for a directory, the ignores will still be applied. So it's basically a better version of views, and will be a major improvement for monorepos I believe.

    How is this going to behave in reusable modules? What's the context directory in those cases (when the module is actually called from another module)?

    I think the context directory is always the current module's git repo.

    I know I already asked this, but just to clarify: if I call a remote module, the context directory is going to be that module's repository, right?

    Yes I think so.

    (Is .git. preserved for remote module calls?)

    We haven't discussed it, do you have a preference? @sipsma @jedevc are both technically possible?

  6. sagikazarmark commented on Jun 13, 2024

    @sagikazarmark
    Contributor

    '.git' is often required by build tools, so my preference would be to preserve it.

  7. rawkode commented on Jun 13, 2024

    @rawkode
    Contributor

    One thing I don't understand from this example is how we build in isolation?

    There's a few modalities, two of which are more important:

    1. Build Everything (CI)
    2. Build One Thing (Local)

    The example covers 1, but not 2.

    If I am in the frontend directory and I run a build, what happens?

  8. shykes commented on Jun 13, 2024

    @shykes
    ContributorAuthor

    One thing I don't understand from this example is how we build in isolation?

    There's a few modalities, two of which are more important:

    1. Build Everything (CI)
    2. Build One Thing (Local)

    The example covers 1, but not 2.

    If I am in the frontend directory and I run a build, what happens?

    The idea is that once a module can access its context, it becomes easier to create a dedicated module for each component of your monorepo. So in your case, you would probably create a dedicated dagger module under the frontend directory, and call build there.

  9. rawkode commented on Jun 13, 2024

    @rawkode
    Contributor

    Maybe I'm missing something. How would it work if my backend calls the frontend to get the static build and each module needs its own context?

    I would need to define the front ends context directory in every caller?

  10. rawkode commented on Jun 13, 2024

    @rawkode
    Contributor

    Nevermind, I've reread this. I think I'm on the same page now.

    Sorry 😔

  11. vito commented on Jun 14, 2024

    @vito
    Contributor

    @shykes

    Yeah that makes sense. It's unfortunate from a UX point of view, but I see how it might be unavoidable. @vito you suggested the relative-to-file idea, wdyt? Is relative-to-source-dir ok?

    That sounds like a good compromise.

    I suggested relative-to-current-file('s dir) just because that's always my first guess, but the downside would be having to tweak these values as you move module code around. (../ => ../../ 🤢)

    Also FWIW I'd hope relative paths are mostly used to pass files from within the source dir. Using ../ too much seems kinda weird, vs. absolute paths. But maybe there are repo layouts where it makes sense.

  12. shykes commented on Jun 14, 2024

    @shykes
    ContributorAuthor

    ../ makes sense when the source dir is not the module root. For example in our repo: sdk/python/dev needs to access the source code of /sdk/python. It makes sense to use .. in that case. If I move sdk/python to another location, I don't want to have to change a bunch of absolute paths in the code of its dev module. Same reason I hate that go doesn't support relative imports.

  13. sipsma commented on Jun 14, 2024

    @sipsma
    Contributor

    RE: .git, agree it's needed often enough that we can't just always exclude it. The problems with it though are that A) it changes often in ways that unexpectedly invalidate the cache and B) can be quite large, which is a waste when it's not needed.

    So we just need support for include/exclude. We can choose whether it's excluded by default and requires the user override that to explicitly include or it's just like any other dir and needs to be explicitly excluded if not desired.

    I'd probably air on not treating it specially right now for conceptual simplicity, just include by default and require explicit exclude, but could still be convinced otherwise.

  14. helderco commented on Jun 14, 2024

    @helderco
    Contributor

    @sipsma, can you clarify the implementation detail on the engine, whether it needs to be hooked into some larger "process" like adding patterns to the context directory upload or if it's just a lazy dag.Host().Directory() underneath as a default value?

  15. sipsma commented on Jun 14, 2024

    @sipsma
    Contributor

    @helderco I think we'll want to start relatively simple. There will be some performance deficiencies for local context dirs (as opposed to git, etc.) due to how local filesync works in buildkit but we can address those over time.

    Very high level outline would be:

    1. Add support for the pragma/annotation in the SDKs and TypeDefs, to mark args as being from the context dir + params like path/include/exclude/etc.
    2. Pick up those settings when constructing the args to module function calls, somewhere around this line or so
    3. If context dir, load the context from the context dir (which can be plumbed into ModuleFunction as a field in that struct), set the arg to the ID of that directory

    There's a lot of variations on how to approach it, that's just one, but I think they all have that general shape.

    The performance deficiency around local dirs is that right now when you load the same local directory repeatedly with different filter patterns, the cache of that local dir will be updated to match those patterns by either deleting files which shouldn't exist or loading ones that don't exist in the engine's cache. So if you use different filter patterns you can end up e.g. deleting a file that was previously loaded, but then later reloading it if it's needed for a different context dir arg with different filters.

    • There are some ideas on how to fix that, ranging from "relatively straightforward" to "very complicated but highly efficient", but we should probably not rope all that into the first iteration unless proven utterly necessary.
  16. 32 remaining items

  17. helderco commented on Jul 1, 2024

    @helderco
    Contributor

    @helderco would it be possible to summarize the issues and tradeoffs here, for the record?

    TL:DR; at the end.

    I’m going to use mostly Python to balance two options for setting this default:

    • As a parameter default value
    • As a parameter metadata

    Go doesn’t support default values for parameters so the Dagger Go SDK implements defaults as metadata.

    Example (for comparison)
    // Build the app
    func (app *App) Build(
      // Frontend source code
      // +default="./frontend/src"
      frontend *Directory,
      // Backend source code
      // +default="./backend/app/src"
      // +ignore=["*", "!**/*.go", "!go.mod", "!go.sum"]
      backend *Directory,
      // Build tool configuration, shared across the monorepo
      // +default="/tools/builder.conf"
      buildConfig *File,
    ) *Directory {
      // Execute the build as usual
    }

    In Python, the most natural DX here would be, at first glance, to use the language’s default value for function parameters. It’s technically possible to do it in both Python and TypeScript, but you have to jump through hoops and well… it’s a bit awkward.

    As a parameter default value

    @function
    def build(
        self,
     
        frontend: Annotated[
            dagger.Directory,
            Doc("Frontend source code"),
        ] = from_context("./frontend/src"),
    
        backend: Annotated[
            dagger.Directory,
            Doc("Backend source code"),
            Ignore(["*", "!**/*.go", "!go.mod", "!go.sum"]),
        ] = from_context("./backend/app/src"),
    
        build_config: Annotated[
            dagger.File,
            Doc("Build tool configuration, shared across the monorepo"),
        ] = from_context("/tools/builder.conf"),
    
    ) -> dagger.Directory:
        """Build the app"""
        # Execute the build as usual

    Note: Annotated receives a type as first argument, and a variable number of metadata that can be anything we want: Annotated[<type>, <metadata>...].

    Why?

    • It’s a default, so it feels more natural to define as the parameter’s default rather than metadata.
    • Don’t have to worry about the user also setting a default for the parameter, when using metadata (like ignore).

    Why not?

    The general issue is that it’s like trying to fit a square peg in a round hole because there’s some constraints that make it tricky to implement:

    • Should only be used in function signatures, not function bodies
    • Needs to be a dagger.Directory during execution
    • But needs to be slightly different than dagger.Directory during registration

    Type checking hurdles

    If you have something that’s not a dagger.Directory:

    # ContextDirectory provided by the SDK
    
    @function
    def build(src: Directory = ContextDirectory("..")) -> Directory:
        ...

    You get a type check error:

    Pyright: ... "ContextDirectory" is incompatible with "Directory"
    

    But you can trick the type checker by wrapping it in a function that returns Any:

    # `from_context` provided by the SDK
    def from_context(path: str) -> Any:
        return ContextDirectory("..")
        
    @function
    def build(src: Directory = from_context("..")) -> Directory:
        ...

    However, now the linter complains:

    Ruff: Do not perform function call `from_context` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable [B008]
    

    The linter is trying to protect us against a known footgun in Python that I won’t go into right now. What’s usually done is to either allow None in the parameter and set the default within the body of the function (won’t work for us), or use a sentinel value like this:

    FOO_SRC: Any = ContextDirectory("..")
    
    @function
    def build(
        src: Annotated[Directory, Ignore(["**/.venv"])] = FOO_SRC,
    ) -> Directory:
        ...

    That satisfies both the type checker and the linter, but requires users to set the path outside the function, which isn’t great.

    API call

    What if, instead of an SDK specific ContextDirectory object, we use an API to reduce the burden on SDKs? In this case, you have less freedom to mess with the types. The simplest thing would be for the API call to return an actual dagger.Directory:

    @function
    def build(
        src: Annotated[Directory, Ignore(["**/.venv"])] = dag.context().directory(".."),
    ) -> Directory:
        ...

    But:

    • It can’t be quite the same dagger.Directory because the engine needs to know that this should be loaded differently, and at a later time (laziness).
    • The engine needs to be aware if this is being used during registration or execution, in order to prevent it from being used directly in the function body. It would be the only API call that can only be used in a function’s signature.
    • If the SDK sees a dagger.Directory (when used in with_directory, for example), it’ll try to serialize it by getting its ID, but the ID from a context directory is different. We need to be careful about caching and other subtleties. Probably having to store some private field in core’s dagger.Directory for just this use case, which may be a leaky abstraction.
    • If, instead of being lazy, we make a sync call during registration, it would fix a lot issues, but not performance. We only want to load the files from the context when the function is executed and that parameter is omitted. Otherwise you’ll always load the files, even when not needed.

    Direct calls

    In order to prevent ContextDirectory (or dag.context().directory()) to be used as an actual Directory in body functions, we need to remove it from the function’s signature within the @function decorator. But when you make a direct call from another function, the magic here gets in the way of clarity:

    FOO_SRC: Any = ContextDirectory("..")
    
    @function
    def build(
        src: Annotated[Directory, Ignore(["**/.venv"])] = FOO_SRC,
    ) -> Directory:
        ...
    
    @function
    def test() -> Container:
        return dag.container().from_("alpine").with_directory("/dist", build())

    The user may expect that ContextDirectory is passed into with_directory in the test function. They may even try passing FOO_SRC in directly. So we need to try to detect if it’s used directly, to raise an error, but not if used in the signature.

    There’s a bigger issue though. What would you expect the src argument to be when you call build() directly like that? An empty Directory? That would be surprising. Raise an error? That would be limiting. I think the best thing here is to make src a required argument in this case.

    There’s an epiphany. It’s optional only for Dagger, but not Python. The best way to express that is with metadata, because you can control both independently.

    As metadata

    @function
    def build(
        self,
        frontend: Annotated[
            dagger.Directory,
            Doc("Frontend source code"),
            Argument(default="./frontend/src"),
        ],
        backend: Annotated[
            dagger.Directory,
            Doc("Backend source code"),
            Argument(
                default="./backend/app/src",
                ignore=["*", "!**/*.go", "!go.mod", "!go.sum"],
            ),
        ],
        build_config: Annotated[
            dagger.File,
            Doc("Build tool configuration, shared across the monorepo"),
            Argument("/tools/builder.conf"),
        ],
    ) -> dagger.Directory:
        """Build the app"""
        # Execute the build as usual

    This solves all problems listed above, and it’s actually fine. Annotated is a part of Python’s standard library. It’s known and used by libraries and tooling, including IDEs.

    Prior art

    FastAPI

    The very popular FastAPI framework uses Annotated for various parameter metadata, but when there’s a default, using the actual parameter’s default is preferred:

    # not allowed
    q: Annotated[str, Query(default="rick")] = "morty"
    
    # preferred
    q: Annotated[str, Query()] = "rick"
    
    # old alternative
    q: str = Query(default="rick")

    From their docs:

    When you don't use Annotated and instead use the (old) default value style, if you call that function without FastAPI in other place, you have to remember to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. QueryInfo or something similar instead of str). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out.

    Pydantic

    Pydantic has an equivalent Field that can be used with Annotated to provide extra information about a parameter, but you need to use it as a default value if you want to set a default:

    @validate_call
    def how_many(num: Annotated[int, Field(gt=10)]):
        return num
    
    @validate_call
    def when(dt: datetime = Field(default_factory=datetime.now)):
        return dt

    Typer

    The Typer library (like Mage) started to adopt Annotated when it became available too. In this case, if the default is static you use the parameter’s natural default value, but if it’s dynamic, you set in as metadata:

    def get_name():
        return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])
    
    # static default
    def main(name: Annotated[str, typer.Argument()] = "Wade Wilson"):
        print(f"Hello {name}")
    
    # dynamic default
    def main(name: Annotated[str, typer.Argument(default_factory=get_name)]):
        print(f"Hello {name}")

    That’s the most similar to us. We want a default that Dagger will fill in for us, but where it could be different between different invocations (dynamic).

    TypeScript

    TypeScript has the same downsides for using the parameter’s default value. The main issue is direct calls. It can implement the metadata as a parameter decorator though:

    /**
     * Build the app
     * 
     * @param frontend Frontend source code
     * @param backend Backend source code
     * @param buildConfig Build tool configuration, shared across the monorepo
     */
    @func()
    build(
      @argument({ default: "./frontend/src" })
      frontend: Directory,
      
      @argument({
        default: "./backend/app/src",
        ignore: ["*", "!**/*.go", "!go.mod", "!go.sum"],
      })
      backend: Directory,
    
      @argument({ default: "/tools/builder.conf" })
      buildConfig: File,
      
    ): Directory {
      // Execute the build as usual
    }

    Note: Python doesn’t support decorators in function arguments.

    However, I’m not familiar with any prior art here. Decorators don’t seem like widely used (long time in experimental stage), but when it is (and we do), it’s a viable solution.


    TL;DR

    • Using the parameter’s default value seems like the best DX at first glance, but in the end it’s like trying to fit a square peg in a round hole. It takes a lot of effort to make it be something that it isn’t, and that makes it awkward.
      • Tricking the type checker and linter
      • Handling direct calls within the same process (it's optional for Dagger, but not for the language)
      • It’s not a static value at import time like parameter defaults need to be, it’s dynamic and needs to be evaluated during runtime
    • There’s very popular Python libraries that also use Annotated for similarly adding metadata to function arguments. In some cases actually migrating from the parameter’s default value to Annotated instead1.
    • We already need to support extra metadata in all SDKs for Ignore anyway. It’s much easier to implement in Python and TypeScript, but if a certain language doesn’t have the same issues with parameter default values, then it should use it if that’s what’s most natural in the language.
    Go
    // Build the app
    func (app *App) Build(
      // Frontend source code
      // +default="./frontend/src"
      frontend *Directory,
      // Backend source code
      // +default="./backend/app/src"
      // +ignore=["*", "!**/*.go", "!go.mod", "!go.sum"]
      backend *Directory,
      // Build tool configuration, shared across the monorepo
      // +default="/tools/builder.conf"
      buildConfig *File,
    ) *Directory {
      // Execute the build as usual
    }
    Python
    @function
    def build(
        self,
        frontend: Annotated[
            dagger.Directory,
            Doc("Frontend source code"),
            Argument(default="./frontend/src"),
        ],
        backend: Annotated[
            dagger.Directory,
            Doc("Backend source code"),
            Argument(
                default="./backend/app/src",
                ignore=["*", "!**/*.go", "!go.mod", "!go.sum"],
            ),
        ],
        build_config: Annotated[
            dagger.File,
            Doc("Build tool configuration, shared across the monorepo"),
            Argument("/tools/builder.conf"),
        ],
    ) -> dagger.Directory:
        """Build the app"""
        # Execute the build as usual
    TypeScript
    /**
     * Build the app
     * 
     * @param frontend Frontend source code
     * @param backend Backend source code
     * @param buildConfig Build tool configuration, shared across the monorepo
     */
    @func()
    build(
      @argument({ default: "./frontend/src" })
      frontend: Directory,
      
      @argument({
        default: "./backend/app/src",
        ignore: ["*", "!**/*.go", "!go.mod", "!go.sum"],
      })
      backend: Directory,
    
      @argument({ default: "/tools/builder.conf" })
      buildConfig: File,
      
    ): Directory {
      // Execute the build as usual
    }

    Footnotes

    1. As in using the default value being the “old” way, while Annotated being the new. ↩

  18. shykes commented on Jul 1, 2024

    @shykes
    ContributorAuthor

    FYI @sipsma @vito ⬆️

  19. shykes commented on Jul 1, 2024

    @shykes
    ContributorAuthor

    @helderco the tradeoff seems reasonable. A few questions on the details:

    1. This would mean 2 different ways to set default values. Developers will need help navigating that. Which way should they choose when?

    2. Nit. This feels weird:

        backend: Annotated[
            dagger.Directory,
            Doc("Backend source code"),
            Argument(
                default="./backend/app/src",
                ignore=["*", "!**/*.go", "!go.mod", "!go.sum"],
            ),
        ],

    The entire annotation applies to an argument, including the type hint and Doc. Feels weird that half the annotations are under Argument and the other half isn't, when by definition they all apply to an argument.

    This would feel simpler and more logical:

        backend: Annotated[
            dagger.Directory,
            Doc("Backend source code"),
            Default("./backend/app/src"),
            Ignore("*", "!**/*.go", "!go.mod", "!go.sum"),
        ],
  20. helderco commented on Jul 1, 2024

    @helderco
    Contributor

    @helderco the tradeoff seems reasonable. A few questions on the details:

    1. This would mean 2 different ways to set default values. Developers will need help navigating that. Which way should they choose when?

    The SDK should raise an error if the parameter also has a default value. They should be mutually exclusive. There's a use case of setting the default value, for when you use direct calls for example, but the annotation would take precedence when the call comes from Dagger. I suggest for now to just error to keep things simpler, and revisit that possibility when there's demand for it.

    1. Nit. This feels weird:
        backend: Annotated[
            dagger.Directory,
            Doc("Backend source code"),
            Argument(
                default="./backend/app/src",
                ignore=["*", "!**/*.go", "!go.mod", "!go.sum"],
            ),
        ],

    The entire annotation applies to an argument, including the type hint and Doc. Feels weird that half the annotations are under Argument and the other half isn't, when by definition they all apply to an argument.

    This would feel simpler and more logical:

        backend: Annotated[
            dagger.Directory,
            Doc("Backend source code"),
            Default("./backend/app/src"),
            Ignore("*", "!**/*.go", "!go.mod", "!go.sum"),
        ],

    That's actually how I started, and I agree that Doc may look out of place, but there’s a reason it’s separate. Only today while writing the previous comment and talking to Tom I changed the examples to use a single dagger.Argument.

    Right now Python has two of those metadata objects:

    • Doc: for Dagger descriptions
    • Arg: for adjusting the name that's exposed to Dagger

    I want to deprecate Arg and move the name option to Argument1, just keep it as an escape hatch if users need it.

    So the reason for a single Argument metadata object is threefold:

    • Allows future expansion while reducing the boilerplate to read the metadata, and avoiding more imports (same with TS).
    • It’s consistent with other popular Python libraries that do something similar.
    • Tom’s feedback is that it looks weird with multiple different decorators on top of each other, so if TypeScript implements as a single object it would keep consistency between Py and TS.

    I considered moving Doc on over, same as Arg, but there’s a reason Doc exists. It’s because there’s an actual PEP trying to make this a standard way to provide documentation strings for Python symbols: PEP 727 – Documentation in Annotated Metadata.

    It’s already available from the Typing Extensions library, which backports latest and future features to older Python versions.

    The goal is to make it easier to access these programmatically. For example, I could document a class property with a docstring below it:

    class Human:
        name: str
        """The name of this human"""

    Depending on the IDE, they can show that description, but it’s not available at runtime to use programmatically like with classes and functions.

    If it becomes a standard to use Doc with Annotated, Dagger will benefit from adopting it.

    I’m open to implement as multiple objects instead of a single one though.

    Footnotes

    1. The main reason that was created was to support names that are reserved keywords. from is a reserved keyword, so if you want a function with a parameter called "from", you can’t. Recommendation is to append an underscore (from_), and use Arg("from") to override that name. This used to be documented but now it isn’t, so Python users don’t know how to get around it. This can be done automatically by having the SDK remove the last underscore in names, though. I’d just keep it anyway in case there’s other use cases that need it. ↩

  21. shykes commented on Jul 1, 2024

    @shykes
    ContributorAuthor
    1. This would mean 2 different ways to set default values. Developers will need help navigating that. Which way should they choose when?

    The SDK should raise an error if the parameter also has a default value. They should be mutually exclusive. There's a use case of setting the default value, for when you use direct calls for example, but the annotation would take precedence when the call comes from Dagger. I suggest for now to just error to keep things simpler, and revisit that possibility when there's demand for it.

    I understand and agree with that part, but my question was about all the other times that developers have to think about default values, and decide how to define them.

    For example: "my function has a string argument, I want to set a default value. I asked on Discord, and I was told there are two different ways to set them, and it depends. Now I'm confused. It's just my first day learning Dagger and I'm feeling out of my depth already".

    What do we answer to that?

  22. helderco commented on Jul 1, 2024

    @helderco
    Contributor

    I understand and agree with that part, but my question was about all the other times that developers have to think about default values, and decide how to define them.

    Oh, If I understand you correctly, this Default() metadata would only be used for the "default path from context", used only with dagger.Directory or dagger.File and erroring otherwise.

    I considered a more expressive name instead of just "Default", but it's too verbose and it's just // +default in Go so it requires documenting this use case anyway.

    In Python and TS this documentation can be provided by the IDE itself, just by hovering on it.

  23. shykes commented on Jul 1, 2024

    @shykes
    ContributorAuthor

    Oh, If I understand you correctly, this Default() metadata would only be used for the "default path from context", used only with dagger.Directory or dagger.File and erroring otherwise.

    But isn't that different from the prior art you linked to, where the annotation is presented as the preferred way to set defaults, not specific to a certain type?

  24. helderco commented on Jul 1, 2024

    @helderco
    Contributor

    But isn't that different from the prior art you linked to, where the annotation is presented as the preferred way to set defaults, not specific to a certain type?

    Not necessarily. Revisit for example Typer's case:

    def get_name():
        return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])
    
    # static default
    def main(name: Annotated[str, typer.Argument()] = "Wade Wilson"):
        print(f"Hello {name}")
    
    # dynamic default
    def main(name: Annotated[str, typer.Argument(default_factory=get_name)]):
        print(f"Hello {name}")

    In general terms, the distinguishing factor is the following. The parameter's default value is preferred when it's a static value. If it's dynamic then the use of Annotated is preferred. Typer already tries to explain this to users in their documentation.

    In Dagger it means this could be open to all types for more dynamic use cases, by allowing a callable in Default:

    def something_dynamic() -> Platform:
        ...
    
    @function
    def build(platform: Annotated[Platform, Default(something_dynamic)]) -> Directory:
        ...

    But if, same as with context directory, some other use case comes along with a specifc need for a default for another type that can't be defined as the parameter's default, then using Annotated is also appropriate for that specific case too.

  25. shykes commented on Jul 1, 2024

    @shykes
    ContributorAuthor

    In that case, would it be acceptable to show the Annotated way for all examples everywhere, for consistency? When users ask "can I also use regular default values", then we explain that yes, but only for static values.

    The benefit is that it will be one less rule that every Dagger developer has has to know.

  26. helderco commented on Jul 1, 2024

    @helderco
    Contributor

    In that case, would it be acceptable to show the Annotated way for all examples everywhere, for consistency? When users ask "can I also use regular default values", then we explain that yes, but only for static values.

    I don't think so. I understand the appeal but using Annotated should be the exception to the rule, not the other way around. In general, using the parameter's default value should be the preferred approach when the value is static.

    The benefit is that it will be one less rule that every Dagger developer has has to know.

    We aren't alone in this. Other libraries also need to explain when to use one vs the other.

    If you look at Field in Pydantic, they make you use Annotated for that metadata, but if you need to use "default", then you're told to put all the metadata in the default value, instead of just the default:

    @validate_call
    def how_many(num: Annotated[int, Field(gt=10)]):
        return num
    
    @validate_call
    def when(dt: datetime = Field(default_factory=datetime.now)):
        return dt

    Notice the first one is in Annotated, while the other one is in the default value.

    If I use this very popular library in my own code and lint it with Ruff using Hatch's defaults, it'll show me an error on the second function, for using a callable as a default.

    You could argue that that linter error is not a concern because users can silence or ignore it in their configs, and the consistency is more valuable. But you're still left with the other issues I mentioned when using this approach.

    I think adapting to Annotated as an exception to the rule is more technically sound, and I think Python users will appreciate that more because it follows the way Python works, so it's easier to understand or reason about if you know enough of the language, and it's a pattern seen elsewhere too.

    It's better to avoid having more situations where it's needed if we can.

  27. helderco commented on Jul 1, 2024

    @helderco
    Contributor

    I just realized something about the name dagger.Argument, btw.

    In Python, Doc can be used in both function arguments and object attributes:

    @object_type
    class PythonDev:
        src: Annotated[Directory, Doc("The source code")]

    The attributes of an @object_type however, become arguments in the auto-generated constructor:

    @object_type
    class PythonDev:
        ...
    
        # note: __init__ is automatically generated with @object_type
        def __init__(self, src: Annotated[Directory, Doc("The source code")]):
            self.src = src

    If we use Argument(default=...), then it’s weird as an attribute:

    @object_type
    class PythonDev:
        src: Annotated[Directory, Doc("The source code"), Argument(default="..")]

    But with separate metadata objects, it works as both an attribute or an argument:

    @object_type
    class PythonDev:
        src: Annotated[Directory, Doc("The source code"), Default("..")]
    
        # note: __init__ is automatically generated with @object_type
        def __init__(
            self, 
            src: Annotated[
                Directory,
                Doc("The source code"),
                Default(".."),
            ],
        ):
            self.src = src 
  28. shykes commented on Jul 2, 2024

    @shykes
    ContributorAuthor

    [...] using Annotated should be the exception to the rule, not the other way around. In general, using the parameter's default value should be the preferred approach when the value is static.
    [...sound arguments...]

    OK, makes sense.

    In that case I think we should change the name of the metadata object, to reduce its scope. Instead of Default I propose we call it DefaultPath. That way it will apply to File and Directory. The name will better align with the behavior, and everything will be more intuitive.

    Annotation Description
    Doc Documentation string for an argument, function or field
    DefaultPath Only applies to arguments of type File or Directory. If the argument is not set, load it from the given path in the context directory
    Ignore Only applies to arguments of type Directory. The ignore patterns are applied to the input directory, and matching entries are filtered out, in a cache-efficient manner.

    This way, there is no confusion as to when to use which. It's very intuitive that DefaultPath isn't a general alternative to regular default values, but a specific tool for a specific job.

    We would align it in Go as well:

    Pragma Description
    // +default Set a default value for the argument. Value must be a json-encoded literal value
    // +defaultPath Only applies to arguments of type File or Directory. If the argument is not set, load it from the given path in the context directory
    // +ignore Only applies to arguments of type Directory. The ignore patterns are applied to the input directory, and matching entries are filtered out, in a cache-efficient manner.
  29. shykes commented on Jul 8, 2024

    @shykes
    ContributorAuthor

    Preemptively replying to @jedevc's concern from another thread:

    I'm not a huge fan of using defaultPath as the pragma here (even though it's distinct at the API level).

    What do you mean by "distinct at the API level"?

    Could we just use default here?
    It doesn't make sense to use defaultPath on a non File/Directory arg, and it doesn't make sense to use default on a File/Directory arg: we should condense this down into one default.

    I am also sad that we can't use default, but consistency between SDKs is more important IMO. If there's a "default path" in Python and Typescript, we need one in Go also, or it's weird.

  30. jedevc commented on Jul 8, 2024

    @jedevc
    Contributor

    What do you mean by "distinct at the API level"?

    We have a distinction between different types of default values (path and values) in the API.

    but consistency between SDKs is more important IMO

    I suppose so, the issue is that the behavior for all of the default paths is currently wildly different per SDK - using annotations, types, pragmas, etc. We could always let this play out, and maybe add default later, since it'd be an easy change if users want it.'

    We already need some level of non-consistency to fit in with the patterns of the language, it's just about walking that line. I think I'd prefer to break consistency here, but it's not a particularly strongly held opinion.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions