Repository navigation
Description
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
- Design consensus: ✅
- Implementation: Feat/context directory #7744
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
shykes commentedon Jun 13, 2024
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.
sagikazarmark commentedon Jun 13, 2024
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?)helderco commentedon Jun 13, 2024
I have questions about the implementation.
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?
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?
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
backendis a sibling directory of<module source>: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:
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 usingdaghere).Just making a point on why relative to source code file isn't optimal.
👍
shykes commentedon Jun 13, 2024
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.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.
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?
shykes commentedon Jun 13, 2024
Yes agreed! And by the way the
ignorepart 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.I think the context directory is always the current module's git repo.
Yes I think so.
We haven't discussed it, do you have a preference? @sipsma @jedevc are both technically possible?
sagikazarmark commentedon Jun 13, 2024
'.git' is often required by build tools, so my preference would be to preserve it.
rawkode commentedon Jun 13, 2024
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:
The example covers 1, but not 2.
If I am in the frontend directory and I run a build, what happens?
shykes commentedon Jun 13, 2024
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.
rawkode commentedon Jun 13, 2024
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?
rawkode commentedon Jun 13, 2024
Nevermind, I've reread this. I think I'm on the same page now.
Sorry 😔
vito commentedon Jun 14, 2024
@shykes
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.shykes commentedon Jun 14, 2024
../makes sense when the source dir is not the module root. For example in our repo:sdk/python/devneeds to access the source code of/sdk/python. It makes sense to use..in that case. If I movesdk/pythonto 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.sipsma commentedon Jun 14, 2024
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.
helderco commentedon Jun 14, 2024
@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?sipsma commentedon Jun 14, 2024
@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:
ModuleFunctionas a field in that struct), set the arg to the ID of that directoryThere'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.
32 remaining items
helderco commentedon Jul 1, 2024
TL:DR; at the end.
I’m going to use mostly Python to balance two options for setting this default:
Go doesn’t support default values for parameters so the Dagger Go SDK implements defaults as metadata.
Example (for comparison)
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
Note:
Annotatedreceives a type as first argument, and a variable number of metadata that can be anything we want:Annotated[<type>, <metadata>...].Why?
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:
dagger.Directoryduring executiondagger.Directoryduring registrationType checking hurdles
If you have something that’s not a
dagger.Directory:You get a type check error:
But you can trick the type checker by wrapping it in a function that returns
Any:However, now the linter complains:
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
Nonein the parameter and set the default within the body of the function (won’t work for us), or use a sentinel value like this: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
ContextDirectoryobject, 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 actualdagger.Directory:But:
dagger.Directorybecause the engine needs to know that this should be loaded differently, and at a later time (laziness).dagger.Directory(when used inwith_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’sdagger.Directoryfor just this use case, which may be a leaky abstraction.Direct calls
In order to prevent
ContextDirectory(ordag.context().directory()) to be used as an actualDirectoryin body functions, we need to remove it from the function’s signature within the@functiondecorator. But when you make a direct call from another function, the magic here gets in the way of clarity:The user may expect that
ContextDirectoryis passed intowith_directoryin thetestfunction. They may even try passingFOO_SRCin 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
srcargument to be when you callbuild()directly like that? An emptyDirectory? That would be surprising. Raise an error? That would be limiting. I think the best thing here is to makesrca 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
This solves all problems listed above, and it’s actually fine.
Annotatedis 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
Annotatedfor various parameter metadata, but when there’s a default, using the actual parameter’s default is preferred:From their docs:
Pydantic
Pydantic has an equivalent
Fieldthat can be used withAnnotatedto provide extra information about a parameter, but you need to use it as a default value if you want to set a default:Typer
The Typer library (like Mage) started to adopt
Annotatedwhen 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: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:
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
Annotatedfor similarly adding metadata to function arguments. In some cases actually migrating from the parameter’s default value toAnnotatedinstead1.Ignoreanyway. 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
Python
TypeScript
Footnotes
As in using the default value being the “old” way, while
Annotatedbeing the new. ↩shykes commentedon Jul 1, 2024
FYI @sipsma @vito ⬆️
shykes commentedon Jul 1, 2024
@helderco the tradeoff seems reasonable. A few questions on the details:
This would mean 2 different ways to set default values. Developers will need help navigating that. Which way should they choose when?
Nit. This feels weird:
The entire annotation applies to an argument, including the type hint and
Doc. Feels weird that half the annotations are underArgumentand the other half isn't, when by definition they all apply to an argument.This would feel simpler and more logical:
helderco commentedon Jul 1, 2024
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.
That's actually how I started, and I agree that
Docmay 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 singledagger.Argument.Right now Python has two of those metadata objects:
Doc: for Dagger descriptionsArg: for adjusting the name that's exposed to DaggerI want to deprecate
Argand move thenameoption toArgument1, just keep it as an escape hatch if users need it.So the reason for a single
Argumentmetadata object is threefold:I considered moving
Docon over, same asArg, but there’s a reasonDocexists. 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:
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
DocwithAnnotated, Dagger will benefit from adopting it.I’m open to implement as multiple objects instead of a single one though.
Footnotes
The main reason that was created was to support names that are reserved keywords.
fromis 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 useArg("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. ↩shykes commentedon Jul 1, 2024
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?
helderco commentedon Jul 1, 2024
Oh, If I understand you correctly, this
Default()metadata would only be used for the "default path from context", used only withdagger.Directoryordagger.Fileand erroring otherwise.I considered a more expressive name instead of just "Default", but it's too verbose and it's just
// +defaultin 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.
shykes commentedon Jul 1, 2024
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?
helderco commentedon Jul 1, 2024
Not necessarily. Revisit for example Typer's case:
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
Annotatedis 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: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
Annotatedis also appropriate for that specific case too.shykes commentedon Jul 1, 2024
In that case, would it be acceptable to show the
Annotatedway 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.
helderco commentedon Jul 1, 2024
I don't think so. I understand the appeal but using
Annotatedshould 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.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
Annotatedfor 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: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
Annotatedas 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.
helderco commentedon Jul 1, 2024
I just realized something about the name
dagger.Argument, btw.In Python,
Doccan be used in both function arguments and object attributes:The attributes of an
@object_typehowever, become arguments in the auto-generated constructor:If we use
Argument(default=...), then it’s weird as an attribute:But with separate metadata objects, it works as both an attribute or an argument:
shykes commentedon Jul 2, 2024
OK, makes sense.
In that case I think we should change the name of the metadata object, to reduce its scope. Instead of
DefaultI propose we call itDefaultPath. That way it will apply toFileandDirectory. The name will better align with the behavior, and everything will be more intuitive.DocDocumentation string for an argument, function or fieldDefaultPathOnly applies to arguments of type File or Directory. If the argument is not set, load it from the given path in the context directoryIgnoreOnly 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
DefaultPathisn't a general alternative to regular default values, but a specific tool for a specific job.We would align it in Go as well:
// +defaultSet a default value for the argument. Value must be a json-encoded literal value// +defaultPathOnly applies to arguments of type File or Directory. If the argument is not set, load it from the given path in the context directory// +ignoreOnly 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.shykes commentedon Jul 8, 2024
Preemptively replying to @jedevc's concern from another thread:
What do you mean by "distinct at the API level"?
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.
jedevc commentedon Jul 8, 2024
We have a distinction between different types of default values (path and values) in the API.
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
defaultlater, 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.