Repository navigation
replace root w/ root-for in dagger.json - #6386
Conversation
|
Just to update, been working on this for the last few days, with the goals of:
It's been a constant battle of having all but a few tests passing, refactoring to address the test failures, getting a new set of a few test failures, repeat. There's also been a lot trickiness around the API refactor and the new dagql world, which has all sorts of new subtleties that have taken getting used to. But nearing the end now (🤞) and reasonably happy with how it's all shaping up. But given it's taken way longer than I was expecting, it's not gonna make it for the v0.9.7 release, which is why I removed that milestone. |
|
Will this break existing |
|
Sorry to be late to the party... And I feel bad for asking the question so far into implementation, but:
Do we really need this? What's the use case? I feel obligated to ask, because that one requirement seems pretty expensive in complexity, both to you and to the user. I foresee edge cases where the user, or our code, get confused between "the module's directory" and "the source code's directory". Or questions like "when I type So, we should make sure the use case is really, really worth it... |
@shykes It will not break dagger.json files provided they weren't using With a significant amount more effort, it is probably possible to handle updating Obviously the backwards incompatible change sucks for the cases where |
That seems like the right tradeoff to me. |
It's more that it's a case that becomes possible with the new To give a more concrete example, say you have a monorepo of modules that depends on each other and also need some common config files that are stored in separate dir, like: .
├── dagger.json
└── common-config
└── some-file.txt
├── some-go-sdk-module
├── dagger.gen.go
└── main.go
├── some-python-sdk-module
├── sdk/
└── src/main.pyIt's unavoidable in these sorts of cases for there to be a single
Module refs (what you specify as the arg to So while I can see how that could be confusing, it feels like it would be fairly obscure; there would need to be some mismatch between the name of a module and the dir it's stored in for this question to even arise in a user in the first place. Also worth re-emphasizing that for all the use cases that don't need a parent directory to be loaded (which is the majority I believe), none of this has an impact. |
be266da to
0fdd994
Compare
|
I continue to have a bad feeling over breaking the 1-1 mapping of dagger.json to module. I feel there will be a butterfly effect of UX paper cuts that will accumulate over time, and by the time the pain becomes a serious issue, it will be too late to fix. I realize I don't have a bullet proof case, but have a strong gut feeling about that one, sorry for being a PITA. I think it would be cleaner to keep the 1-1 mapping, and optionally support an |
Not totally following yet, where would the configuration files for the different modules actually be in this case? My argument for the current approach: Right now, the rule is essentially just "the module will be loaded with the directory under the dagger.json configuring it", which is relatively simple (at least, relatively speaking for these sorts of complex use cases). I'm hesitant to moving to something more complicated to explain+understand than that. That rule just inherently implies that it's possible for a single directory to be shared by multiple modules. But I'd also say that in practice multiple modules being configured in the same file has not in particular been the source of significant complication in the implementation at all, it's relatively straightforward and doesn't introduce tons of corner cases or anything like that. And on the UX side, the updates to dagger.json for configuring it all automatic and in the background, so it's not something I anticipate users needing to think about. But if there's particular situations you're thinking of, let me know. The main reason it doesn't have much of an impact in practice is that modules are still uniquely identified by the path to the directory that contains their actual source code, not by the path that contains |
vito
left a comment
There was a problem hiding this comment.
Loving the expanded API, mostly paid attention to DagQL technicalities for this review, I think I only really spotted one suspicious thing (there's one place where we update a dagql.Instance in-place)
There was a problem hiding this comment.
Yeah the alternative here was to update the Rust SDK to special case this, but since this is a required arg, most (if not all?) SDKs just allow clients to provide the arg value directly rather than needing to specify the name of the arg plus the value. So the overhead of using a slightly more verbose name here felt less than needing to special case an SDK.
That being said, I agree in general that we can't just always avoid reserved names, the only general solution is for SDKs to have special handling.
There was a problem hiding this comment.
Yeah, it should be a requirement for every SDK to have a list of reserved words and deal with them from day one like Python does, rather than having to adjust manually when they come up:
dagger/sdk/python/src/dagger/_codegen/generator.py
Lines 416 to 417 in f7d1805
This comment was marked as outdated.
This comment was marked as outdated.
|
Dumping a list of use cases from today's bikeshedding session:
|
e48830c to
8d09a5a
Compare
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
257c245 to
1bd5056
Compare
vito
left a comment
There was a problem hiding this comment.
(submitting comments so far to maximize async feedback, will leave individual comments from here on, sorry in advance for spam)
There was a problem hiding this comment.
👍 - probably want to expand this in the future, but for now we're pretty narrowly scoped to git everywhere else too, so no need yet
| Query *Query | ||
|
|
||
| // The source of the module | ||
| Source dagql.Instance[*ModuleSource] `field:"true" name:"source" doc:"The source for the module."` |
There was a problem hiding this comment.
Super nice having this available, making this the canonical ID for deduping makes sense to me
| The provided Module is not fully initialized; the Runtime field will not be set yet. | ||
| */ | ||
| Codegen(context.Context, *Module, dagql.Instance[*Directory], string) (*GeneratedCode, error) | ||
| Codegen(context.Context, *Module, dagql.Instance[*ModuleSource]) (*GeneratedCode, error) |
There was a problem hiding this comment.
Always nice when two args turn into one 👨🍳😎🔥🤌💋 (someday that'll merge into the standard guy fieri chef kiss emoji)
Signed-off-by: Erik Sipsma <[email protected]>
8eef9df to
0a0f243
Compare
Signed-off-by: Erik Sipsma <[email protected]>
| }, | ||
| { | ||
| Name: "introspectionJson", | ||
| Value: dagql.String(introspectionJSON), |
There was a problem hiding this comment.
NB: this huge JSON string ends up in IDs and gets sent over telemetry, which is kind of unfortunate. Thankfully it doesn't seem to end up anywhere important like the module's initialized ID, which is what propagates to IDs produced by the module. Would be nice to find another way to do this in the future anyway (maybe something with DagQL makes it easier), but not a big deal right now.
There was a problem hiding this comment.
Yeah I agree but the immediately available alternative is to turn it into a File via withNewFile, at which point it's still going to end up in the ID. I think we could blobify it though, so then we just pass the content hash in the ID.
Will save for follow-ups though since it's more a performance optimization
vito
left a comment
There was a problem hiding this comment.
Phew - think I got through it all, didn't see any blockers so approving!
The only feedback design-wise I have is that it feels a little weird to have the logical definition of a module split between two files, imagining a scenario where you remove a module entirely but accidentally leave a dangling reference to it in the root dagger.json. But I understand there are a lot of constraints being satisfied here.
Maybe we could detect that + error until you clean it up?
| // test dagger.json source configs that aren't inherently covered in other tests | ||
|
|
||
| t.Parallel() | ||
| c, ctx := connect(t) |
There was a problem hiding this comment.
Probably worth following the pattern set forth in #6521 - basically if you expect a t.Run to take a while, give it its own client, otherwise don't mark it t.Parallel and just let them all use the root-level client.
There was a problem hiding this comment.
Ah good catch, fixing before merge
Signed-off-by: Erik Sipsma <[email protected]>
Agree that the split does lead to some weird situations like that, but yeah it comes down to tradeoffs between all the different possible implementations. That at least is more of an obscure corner case that we can also handle reasonably.
A stale entry technically wouldn't hurt anything, so I don't think we'd need to error out and can instead just have the engine detect it and automatically update the |
|
Just realized I forgot to update the title of the PR before merge 🤦♂️... So it's confusingly committed as Just as an FYI for people in the future that might look at this and be confused. |
|
Wow this is an insane amount of work! Nice job Eric! Can't wait to test out the new stuff :) |
🔥 Update Instructions for Breaking Changes
Modules that use
"root"in dagger.jsonThis update will cause existing modules that use
"root"indagger.jsonto fail loading.As an example of how to update, say your module is in directory layout like:
. └── foo └── bar ├── dagger.json └── main.goAnd
dagger.jsonhas contents:{ "name": "my-mod", "root": "../..", "sdk": "go" }To update, you should:
dagger.jsonfilecdto the directory whererootwas pointing todagger mod init -m ./foo/bar --name my-mod --sdk goAs a more concrete example, starting at this repo+commit which uses
rootin thetestcontainersanddockermodules: https://github.com/vito/daggerverse/tree/fe4bc99ba02abfb74c10ae76f1794568ece70cc3The process of updating those modules is:
Modules that use the Host API to read source files
(using go syntax below, but same idea applies to all SDKs)
Previously, module containers set their working directory to the directory containing the module's source code. You could then read files from that directory with calls like
dag.Host().File("./some/file.txt").Now, module containers are set to an initially empty scratch directory, so those calls will not work anymore.
To use files/directories from the module source code, you can instead:
dag.CurrentModule().Source().Directory("some/subdir")dag.CurrentModule().Source().File("some/file.txt")Additionally, it used to technically be possible to use files/directories from anywhere in the root dir loaded for a module in the case where
"root"was configured indagger.json. This is no longer possible; instead anything you need to use from outside the module's source code directory should be accepted as an argument to a function or the module constructor.One final use case to mention: if you need to create new files/directories and then load them into the dagger API during module execution, this is still possible.
dag.CurrentModule().Workdir("./some/dir")dag.CurrentModule().WorkdirFile("./some/file.txt")These paths will all be relative to the module's initial working directory (an initially empty scratch directory, as mentioned above).
Fixes #6291
Summary of changes
Have details on all this below, but to summarize
rootin favor ofsourcedagger.jsons automatically, except for the case whererootwas being used, which will required manual updates from the user..gitignorefiles for module generated source has been removed..gitattributesare still created thoughdag.CurrentModulefunctionality is expanded and the official API for modules to access the source dir and live files/dirs from the module container's filesystem, replacingdag.Host()in the module APIdagger.jsonchangesExpand
This change only really impacts existing advanced use cases where `root` is being used. These cases occur when a module needs something outside the directory tree under `dagger.json` in order to execute. Some examples: * When a module is depending on other modules in the same git repo but those other modules are not under the same directory tree * A module is re-using a go.mod/package.json/pyproject.toml in a repo that exists in a parent directoryThe new format inverts the existing relationship between
dagger.jsonand the source directory that is loaded into module containers:rootto point to an arbitrary parent directory. When the module container was loaded, thatrootdirectory was loaded into the container while the current working directory of the module container remained the actual source directory of module (i.e. the one containing themain.go/main.py/etc.)rootis gone. Instead, anytime a module needs a root separate from its source dir, there will be twodagger.jsons involve. There is still the samedagger.jsonthat exists today in the source dir, but there is also adagger.jsonin the root dir that specifies a"root-for"key which points to the module's source dir. The engine knows how to "find-up" the correct root of the module based on this.Note that in the simple cases where
dagger.jsonand the module source directory are the same (i.e. what happens today when you rundagger mod initwithout the--rootflag), there's no behavior change. The module'sroot-forin dagger.json just ends up being set to., but the user won't see any differences otherwise.Example
For a directory tree like this:
Where the
mod*directories contain source code for different modules. Also say thatmodAhas a dep onmodB.The top-level
dagger.jsonwill look like this:{ "root-for": [ { "source": "modA" }, { "source": "subdir/modB" } ] }modA's
dagger.jsonwill be:{ "name": "modA", "sdk": "go", "dependencies": [ { "name": "modB", "source": "../modB" } ] }modB's
dagger.jsonwill be:{ "name": "modB", "sdk": "python", "dependencies": [ { "name": "foobar", "source": "github.com/org/daggerverse/[email protected]" } ] }Important notes:
dagger.json. Any paths that point above a given dagger.json (i.e. dependencies) cannot go past theroot-forthe module being configure.Impact on CLI
Expand
Path handling
This is all ultimately internal and meant to not be thought about by users, but worth noting.
CLI commands like
init/sync/installare aware of thedagger.jsonthey are using even if it's in a parent directory and try to handle path arguments as intuitively as possible.To initialize a module with a
dagger.jsonin a parent directory, you now do e.g.dagger mod init -m ./subdir --name=foo --sdk=go. The module source code will go in./subdirand a separatedagger.jsonwithroot-forwill in the directory you ran the init from.For example, if you were in the
subdir/modBdirectory in the example above you could run this:dagger mod install ../modAto add a dependency on
modAtomodB.The CLI+Engine do all the path manipulations to know that it should update
modB(because it's in the source directory for it), where thedagger.jsonit should update is located and that../modAneeds to be made relative to that dagger.json.Support for named dependencies + sdk-less dependencies
Quoting from #6291 (comment) for the rationale behind this:
This all now works.
Additionally, when you install a dependency, you can now optionally include a
--nameflag, e.g.dagger mod install --name ts github.com/org/daggerverse/tailscale. If you don't provide it, the name defaults to the name of the dependency module as configured in its dagger.json.This is useful for the above use case but simultaneously also provides support for avoiding name conflicts. The
--nameyou choose there is actually applied to the gql schema + codegen for the module its installed to, essentially creating an alias that can be used in naming corner cases (see #6478 for details on some of those problems which this PR now mostly solves).Module Config+Ref API
Expand
In the latest version of this PR, I've switched the implementation of this to be based around core APIs. Motivation being:
This PR didn't manage to move everything to be API based; there's still the
core/modules/util package. But that package now only has some bare minimum config file utils the CLI still needs. It no longer does any of the ref parsing/management. And there are now paths to fully API-ifying everything left in that package (they just were becoming too much to scope into this effort).Refs aren't externally impacted very much by this change. They still must point to a module source directory, which is the same as before.
Internally, the implementation needs to now do some "find-up" logic for a given module ref to find the directory that contains
dagger.json. It's implemented such that it will always stop at the root of a git repo (whether due to being a git ref in the first place or even local refs that point to a directory in a local git checkout).ModuleSourceThis is the API object representation of what used to be called Refs in the util lib. The name
Sourceended up making more sense to me as the API name since refs are a way of specifying where source of the module is located, along with other metadata on where its sourced from (git url, commit, etc.).However, you still create a
ModuleSourcewith arefStringthat has the same format as refs previously, there's no change in the format of refs in their string format. They just are used to construct aModuleSourcein the API now.ModuleSourcehas different subtypes forLocalModuleSourceandGitModuleSource, with git specific metadata only being queryable fromGitModuleSource.Internally, the state of
ModuleSourceamounts to:RootDirectory, which is a directory that contains the module config + source code (possibly as subpaths)SourceSubpath, which is the subpath of the directory that contains the module source code specifically.ModuleSourcehas aasModulefield for upgrading it to a full blownModule. It internally uses the recently addedModule.withSourcefield, which has been updated to accept aModuleSourcerather than a directory+subpath it accepted previously.ModuleSourcealso has adependencyfunction for resolving a ref as a dependency relative to another one. A motivating example for its need is when you have a git module source that contains a module with dependencies on other modules locally relative to it in the git repo. In that case, those "local" deps are relative to a git source, so you want to be able to resolve them to git sources (just at a different subpath in the git repo).Modulenow also includes aSourcefield for recovering the originalSourceit was created from (and associated metdata).Config + related codegen adjustments
Obtaining the codegen for a module (i.e. for the CLI
init/install/synccommands) has been adjusted in a few ways.A
Moduleno longer returns aGeneratedCodeobject, instead there's just a field on it calledGeneratedSourceDirectoryof typeDirectory.That
Directoryis the directory wheredagger.jsonis located and includes:.gitattributesfiles based on the SDKdagger.jsoninitialization or updatesdagger.jsonis now created by the engine itself as part of the above, clients no longer create or update it themselves.To support the above,
Modulehas new fields for updating configuration:withName,withSDKandwithDependencies. If you start with aSourcethat includes nodagger.json, you can thus still turn it into a (uninitialized)Module, configure it viawithName,withSDK, etc. and then callGeneratedSourceDirectoryto get all of the generated code, including the shiny newdagger.json.dagger mod initimplementation as an exampleSiimilarly, if you load a
Modulethat already has adagger.jsonbut modify dependencies or other configuration, callingGeneratedSourceDirectorywill return a directory with the updateddagger.json(and all the sdk codegen,.gitattributes, etc.).This removes the need for clients to update
dagger.jsonthemselves (and thus handle a lot of the logic around format, versioning, dependency refs, etc.).However, as of right now the CLI does still read
dagger.jsonin order to find theinclude/excludesettings (which are pretty important for monorepo-type use cases). Those in particular are tricky because in the naive approach, if you upload a directory containingdagger.jsonto the engine and then ask for those settings, its already too late to apply them.dagger.jsonwithout actually loading everything (just a series of "remote stats" essentially) and then do the loading w/ include+exclude applied.ReadCallerFileutil in the engine, this would just require a very slight variant for "stat"). I only left it out because it raises questions around performance and security which were too much for this already too big PR. Open to us in the future if desired though.Removing automatic
.gitignoreWe've discussed for a while about removing the automatic setup of
.gitignoreof generated files. The main reason being that more often than not in our own usage we have to manually remove those.gitignores because otherwise once its pushed to a remote repo, CI can't compile dagger module code, which impacts linting.I had the choice here to either write the logic for setting up
.gitignorefiles in the update codegen process, or just not do that since we were intending to remove this soon anyways. I went with the latter to save time.Also note that
.gitattributesis still setup the same as before. This only impacts.gitignore.Misc technical details
CacheMaps wrapping api calls), so I had to implement it more "by hand".Module.WithDependenciesvia a simple walk of the DAG of deps.initializewas called or not, among other little details that modify the ID without modifying the module's "true identity".ModuleSource's ID to compare module identity. This makes conceptual sense since a Module is ultimately defined by its source.SDK + Runtime Changes
Expand
Modules run in
/scratchnowWe want any access to module source dirs to be through the API now (
dag.CurrentModule().Source()), while still allowing use cases that call for loading live dirs/files from the module containers' filesystems.The approach is that the workdir of module runtimes are set to an empty dir at
/scratchby the engine. More details underCurrentModuleAPI below.This worked pretty much out of the box for Go+Python. For Typescript, it broke nodejs module (as opposed to dagger module) loading. Eventually figured out that it was because the
tsconfig.jsonwe use to specifypathsmapping was no longer being used, with the fix being to just explicitly provide a--tsconfigarg totsx: https://github.com/sipsma/dagger/blob/07d4205730941460afd26ed01174d068a5e88964/sdk/typescript/runtime/main.go#L55-L55SDK-as-module constructor
Part of the overall changes are to make a module's root dir only strictly needed by a module's SDK (i.e. for
go.mod/package.json/etc.) and otherwise hidden from the end module (in order to reduce "shadow args").Instead, anything that previously would have been needed from a root context now needs to be an explicit argument to the module. The idea is to make this easy via support for "default-args" or "scripts" in dagger.json, but those are out of scope of this PR (too much on top of already too much).
So in the meantime, this PR does some setup for what that would look like. Namely, the Python+Typescript SDK-as-modules now have a constructor that's used to pass the full SDK source code (which previously relied on
root). The engine internally already handles these built-in SDKs specially, so it just continues to special case them a bit and knows to provide these args.The generalized idea that will come out of this in the long run will be aforementioned support for either "default-args" or "scripts" in dagger.json (where these constructor args would be encoded) and possibly a generalized idea behind "sdk config" (though that in particular is a bit vague atm admittedly).
TypeDef registration doesn't use
CurrentModuleanymoreSDKs registering the typedefs of their module now call
dag.Module().WithObject(...).<etc>rather thandag.CurrentModule().WithObject(...).<etc.>.This is all SDKs need to know, the end effect is the same.
The reason for this are a bunch of subtleties around dagql IDs and the fact that
CurrentModuleis now an object separate fromModule. Previously, the implementation heavily relied onQuery.currentModulereturning adagq.Instanceof *core.Module. In this new approach, I couldn't find any reasonable way to return a dagql.Instance[*core.CurrentModule]. It would require that the call context have an instance ofCurrentModulerather than its current instance of Module, but I couldn't find any way of doing that without hacking dagql in bizarre+probably-broken ways.So I just made the aforementioned change to have SDKs use
Module, creating an empty module and registering types on it and then the server just merges in that module definition to itself here: https://github.com/sipsma/dagger/blob/07d4205730941460afd26ed01174d068a5e88964/core/module.go#L335-L335CurrentModuleAPIExpand
As discussed in #6291, we now lean on the
dag.CurrentModule()API heavily:dag.CurrentModule().Source()returns a*Directoryfor the module's source dir only. It does not include the root directorydag.CurrentModule().Workdir("some/dir")- returns a*Directoryloaded from the container's live filesystem, but rooted under its working directory of/scratch. This is a replacement fordag.Host().Directory()for module code.dag.CurrentModule().WorkdirFile("some/file.txt")- same as above but for*File, mainly as a convenience similar to how we also have adag.Host().File()dag.CurrentModule().Name()- returns the name of the module being executed in. Only added because the python SDK needs it (here) but makes perfect sense to expose in general anyways.