Skip to content

support for custom digests in dagql - #9204

Merged
sipsma merged 10 commits into
dagger:mainfrom
sipsma:simplify-module-load-take2
Jan 24, 2025
Merged

sipsma merged 10 commits into
dagger:mainfrom
sipsma:simplify-module-load-take2

Conversation

@sipsma

@sipsma sipsma commented Dec 14, 2024 •

Copy link
Copy Markdown
Contributor

After banging my head for a while, figured out a good approach to the module loading improvements (that were in turn enabled by the filesync improvements) which should both fix the excessive cache invalidation of module loads and clean up a decent chunk of the core API.

The idea here is to add support for customizing the digests associated with a given call. There's currently two places the digest can be customized:

  • Before the operation associated with the call actually executes
    • The current use case is to simplify all the cases where we marked something as impure and then returned a pure result that had the client ID mixed in somehow so that the operation was cached just for that client.
      • Those cases now just mix in the client ID to the cache key before the operation runs.
      • The follow-up to this PR that fixes/simplifies module loading will use this to allow local module loading to be cached per-client without needing to add weird "internal-only" type APIs that are just used to make something pure for a given client
    • Conceptually, this is comparable to the "fast cache key" in buildkit (but in dagql now), I think in the longer run it will be an important foundational feature to migrate more caching logic to dagql
  • In the returned ID when using a NodeFunc
    • At the moment, the use case is to allow a content-based cache key to be associated with results in the case where one is known and should be the canonical digest for the operation. This replaces the blob API (which is rm'd now).

The initial motivation was for the follow-ups in simplifying+enhancing module loading but the immediate practical benefits are:

  • Scoping an operation to be cached per-client is way way simpler now (just mark the API as cached per client, see the PR diff)
  • blob is gone, which is for the better since it only existed for internal purposes and thus really should never be in the public user-facing API anyways

The benefits to module loading are:

  • No need for internal-only APIs when trying to purify impure loads of local module source
  • Ability to force module source digests to be content based when provided to SDK calls, which fixes tons of cases where module loading should be cached but currently is not

There's also a little bit of dagql internal refactoring, which was needed to ensure it always uses the digest specified in an ID rather than recalculating it (which was a bit wasteful in some codepaths anyways).

@sipsma
sipsma force-pushed the simplify-module-load-take2 branch 3 times, most recently from 9ad76ca to 47b5dce Compare December 17, 2024 08:44
}
addModulesWithDeps(1, curDeps)

modGen = modGen.With(configFile("..", &rootCfg))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cwlbraa noticed this recently; this line is doing nothing and makes this complicated test more complicated, so just rm'ing it while here

Comment thread core/moddeps.go
},
},
if err := dag.Select(ctx, dag.Root(), &loadedSchemaJSONFile,
dagql.Selector{Field: "__schemaJSONFile"},

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to move this step to an API call because this code can run outside of any API call (during session init) and thus doesn't always have a current ID to create instances from.

I think after I made this change I added some stuff that could allow us to go back to just doing this all inline, but I don't really mind having this encapsulated in an API call, so will leave as is unless there's objections.

Comment thread core/modfunc.go
ctxArgs = append(ctxArgs, arg)
}
ctxArgVals := make([]*FunctionCallArgValue, len(ctxArgs))
eg, ctx := errgroup.WithContext(ctx)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change to load contextual dir args in parallel is not technically related, just something I noticed that would be an easy little win along the way. It's possible to do this now since there's no longer any downside to loading local dirs in parallel after the filesync changes.

Comment thread core/schema/host.go

func (s *hostSchema) directory(ctx context.Context, host *core.Host, args hostDirectoryArgs) (dagql.Instance[*core.Directory], error) {
return host.Directory(ctx, s.srv, args.Path, "host.directory", args.CopyFilter)
func (s *hostSchema) directory(ctx context.Context, host dagql.Instance[*core.Host], args hostDirectoryArgs) (i dagql.Instance[*core.Directory], err error) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved this implementation inline to the schema so that any other users of it have to go through dag.Select, which makes the code simpler since otherwise use of NewInstanceForCurrentID gets confusing to think about

Comment thread dagql/builtins.go
return nil, fmt.Errorf("pointer elem: %w", err)
}
return DynamicOptional{
dynOpt := DynamicOptional{

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fixes in builtinOrInput seem like bugs that had been lurking for a long time that we just barely managed to avoid until now. The problem was that we'd never actually set any values in DynamicOptional or DynamicArrayInput and thus would always end up with no values in certain code paths.

│ ! input: module.withSource.initialize failed to initialize module: failed to call module "broken" to get functions: call constructor: process "go build -o /runtime ." did not complete successfully: exit code: 1
│ │ $ ModuleSource.resolveFromCaller: ModuleSource! X.Xs CACHED
│ │ │ ✔ upload /XXX/XXX/XXX from XXXXXXXXXXX (client id: XXXXXXXXXXX, session id: XXXXXXXXXXX) (exclude: XXXXXXXXXXX) (include: XXXXXXXXXXX) X.Xs
│ │ ✔ ModuleSource.resolveFromCaller: ModuleSource! X.Xs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't rely on buildkit caching for any of these anymore (i.e. blob source is gone), which I believe is why these don't show as cached anymore.

As we move more caching logic away from buildkit we probably will need a new way of showing operations as cached, but not a big deal yet IMO.

Comment thread dagql/nullables.go
if val == nil {
return DynamicOptional{
Elem: o,
Elem: o.Elem,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty sure this is a long-standing bug, though not sure what if anything it actually broke.

Comment thread dagql/objects.go Resolved
Comment thread dagql/server.go
Comment on lines -470 to -489
astField := &ast.Field{
Name: id.Field(),
}
vars := map[string]any{}
for _, arg := range id.Args() {
vars[arg.Name()] = arg.Value().ToInput()
astField.Arguments = append(astField.Arguments, &ast.Argument{
Name: arg.Name(),
Value: &ast.Value{
Kind: ast.Variable,
Raw: arg.Name(),
},
})
}
sel, _, err := base.ObjectType().ParseField(ctx, id.View(), astField, vars)
if err != nil {
return nil, fmt.Errorf("parse field %q: %w", astField.Name, err)
}
sel.Nth = int(id.Nth())
res, id, err := s.cachedSelect(ctx, base, sel)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This chunk of code is why cachedSelect changed from accepting a Selector to accepting an ID.

This code in Load was taking an ID, converting it into a Selector, only for it to go back to an ID in cachedSelect. I think this was a bit wasteful from a performance perspective but more importantly it broke custom digests since the Selector didn't know about those and instead just always re-calculated the ID digest from the call chain.

I fixed it by just providing the ID directly since that seems simpler overall. The other callers of cachedSelect (now renamed to cachedCall) are barely impacted since they start with a Selector but can easily turn that into an ID by Selector.AppendTo

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kinda curious what you think about https://github.com/dagger/dagger/pull/9395/files#diff-af763c875b05c71f4824382b701cb6b8075d3d8922153646f2e3e5d530b23d9cR569 - which is semi-related to the refactoring here.

Does it still seem reasonable to convert a chain of selectors into an ID? The idea being, it would be nice to be able to generate an ID for an object - but without actually performing any of the evaluation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed earlier today live, but yeah that sort of existed before and still does in this PR (it's now Instance.Select). I'm guessing you might need some variation on the exact types used there, but the idea/code should be reusable

Comment thread dagql/server.go Outdated
Comment on lines +939 to +941
var isSensitive bool
if arg, found := spec.Args.Lookup(arg.Name); found && arg.Sensitive {
continue
isSensitive = true

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic around sensitive args changed because it was previously just not including the sensitive arg in the ID at all, which no longer works in the new logic where we pass around IDs rather than Selectors in more places.

The fix works by migrating the hiding of sensitive values in the call/ pkg. It results in the same behavior as before in that an ID will never serialize (via Display, Encode, etc.) sensitive args and won't include them in digests. The difference is that the sensitive arg can still be carried around on the ID in memory.

@sipsma sipsma changed the title [Draft] dagger-native content hashing support dagger-native content hashing support Dec 17, 2024
@sipsma

sipsma commented Dec 17, 2024

Copy link
Copy Markdown
Contributor Author

I still need to update all the integ test git repos to fix TestCustomSDK (see this commit with the fix to the local version of that test), but otherwise I think this is good to go, taking out of draft.

@sipsma
sipsma marked this pull request as ready for review December 17, 2024 09:09
@sipsma
sipsma requested review from a team as code owners December 17, 2024 09:09
@sipsma
sipsma requested review from cwlbraa and jedevc December 17, 2024 09:11
@sipsma
sipsma force-pushed the simplify-module-load-take2 branch 4 times, most recently from 049d39a to e13721e Compare December 18, 2024 06:58
@sipsma

sipsma commented Dec 18, 2024

Copy link
Copy Markdown
Contributor Author

I ended up pushing an additional commit after going back to work on the follow up to this PR (that has the module loading improvements): e13721e

It takes advantage of the new ability to customize ID digests and adds the ability to customize the digest before the operation runs (whereas previously this PR just allowed you to customize the digest of the value returned by an api).

This allows us to get rid of many of our calls to Impure and replace them with CachePerClient, which is a new "cache key func" that scopes the cache key of the operation to a client (so it's cached for that client, but not across clients).

  • I purposely made the "cache key func" generic enough to handle many more use cases in the future.

I'd think of this as a first step towards "fine grain purity" that's been discussed in the past. It also chips away at bit more at migrating our cache logic from buildkit to dagger (conceptually, this is most comparable to buildkit's "fast cache key").

The immediate utility is removing a few remaining headaches around marking LocalModuleSource as impure (it doesn't have to be, it's just cache scoped to each client) and makes it completely trivial to add support for "force filesync reloads" that will be needed in the near future for the shell.

(I'll update the description of the PR with a more cohesive description of this and the rest of the changes here tomorrow)

@sipsma

sipsma commented Dec 18, 2024

Copy link
Copy Markdown
Contributor Author

#9245 has some early code showing how all this stuff is gonna be used to help module source loading improvements (the last commit there specifically), just in case that's helpful.

@vito

vito commented Dec 31, 2024 •

Copy link
Copy Markdown
Contributor

Very cool to see this taking shape. Wanted to pick your brain on one thing: mostly based on vibes, I feel a little unsettled overloading the existing call digests field for content digests. In my mind those are the digest of the 'recipe' and it may be useful to correlate all such recipes, and as a separate step correlate them to their resulting content. Also, the fact that we have a pre-computed 'digest' field was originally an optimization/implementation detail. So just keeping an ear to the ground for shifts in usage there.

Way back in my original sketch for IDs I suggested we may want to add a content digest field:

Future possibilities, need more thought:

  • Allow IDs to embed the digest of the content they create so we can verify that they created the right content, or even detect IDs that are actually impure.

What I originally had in mind was that once you got your hands on a "digested/synced" ID (aka an ID that contains its content digest, maybe returned by sync), you could later publish that ID alongside the artifact it built. Users could evaluate it, and check that the digest matches the recipe's reported content digest. Or it could be published to the Daggerverse, which could sync and ensure that the digest matches before vouching for its hermetic-ness. Things like that.

There were gaps in this design, since adding the content digest to the ID/call implies a change to the ID/call's digest if it's embedded in the recipe, but I suppose we already had to deal with that when we added the explicit digest field. I suppose a content digest would always just be tacked on to a recipe that has already had its digest computed?

Anyhow - this isn't blocking, mostly tossing up a lob in case it makes things click for a jam, and wanting to be conscious of semantic changes to existing concepts. Curious to hear if there are any major benefits I missed to just rolling forward as-is and making digests work the way this PR does things instead, since most of what I'm throwing around is conceptual and may be more detached from reality than I realize. 🙃

@sipsma

sipsma commented Jan 6, 2025

Copy link
Copy Markdown
Contributor Author

Anyhow - this isn't blocking, mostly tossing up a lob in case it makes things click for a jam, and wanting to be conscious of semantic changes to existing concepts. Curious to hear if there are any major benefits I missed to just rolling forward as-is and making digests work the way this PR does things instead, since most of what I'm throwing around is conceptual and may be more detached from reality than I realize. 🙃

@vito Yeah I started this thinking I'd be adding support for multiple digests being associated with a single call (so you could have the recipe digest plus some arbitrary number of other digests, including but not limited to content digest), but it ended up landing a little differently.

A more accurate description of this PR is probably "add support for customizing digests" (I'll update the PR title and description after leaving this comment, the current ones are from the first iterations of this).

The current cases that it impacts are:

  • When we had to go through the blob API in order to reset an operation's recipe-based digest to a content-based digest.
  • When we had to do a big dance to make an operation pure for a given client (i.e. mark as impure but then return something that was pure but had the client mixed into the cache key somehow)

The important point is that for all of those use cases, we essentially were already just customizing the digest, but by jumping through a bunch of hoops and ceremonial dances to get the recipe to have the right digest/purity (even if it's not reproducible practically, such as with the blob api). Now, we can just do that much more directly, get rid of blob, etc.

So I don't think that any of the use cases impacted here would benefit from multiple digests being associated with a single call yet. And the use cases I have in mind for follow-ups don't need that yet either.

I do think in the longer-run we're gonna need something closer to what you're describing where there could be both a recipe-based digest, content-based digest, and maybe more all associated with a single ID. Namely, to fully migrate all caching logic away from buildkit we will want that for exec mounts (which can be purely identified by recipes but also have the same content across different recipes). It's just not needed yet and wouldn't benefit any of the current use cases, so I'm not gonna tackle it until it's needed.

  • If it was utterly trivial I'd probably just do it now, but it's trickyish for the reason you mentioned in that we'd have to change how digests are calc'd to handle whether or not additional non-recipe-digests are included (maybe multiple digests are produced? idk yet). This has performance impacts since we call these digest codepaths a lot, so it's not a change we can easily make for free.

tl;dr all the current use cases for this are essentially the same as what we were doing before, just way simpler, and I think it makes sense to save support for multiple digests associated with a single call for when we actually need it

@sipsma sipsma changed the title dagger-native content hashing support support for custom digests in dagql Jan 6, 2025
@sipsma
sipsma force-pushed the simplify-module-load-take2 branch from e13721e to 546d5cf Compare January 7, 2025 20:00
@sipsma
sipsma requested a review from vito January 8, 2025 20:07
@sipsma
sipsma force-pushed the simplify-module-load-take2 branch from 546d5cf to 7be234a Compare January 13, 2025 18:49
@jedevc jedevc mentioned this pull request Jan 16, 2025
3 tasks done

@jedevc jedevc left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good 🎉 (approving now, since no major structural concerns, aside from failing CI) I think I'm struggling to fully get my head round the dagql refactors, but will probably take a bit of tinkering with it myself 😆

Definitely seems like I have a pretty hard dependency on this for #9395 - there's some conflict on AsTarball, but also some of the custom cache keying will be super useful (to get rid of the Impure hack I have).

name: "GitHub public",
gitTestRepoRef: "github.com/dagger/dagger-test-modules",
gitTestRepoCommit: "323d56c9ece3492d13f58b8b603d31a7c511cd41",
gitTestRepoCommit: "f1b295cc1bce8eeea33cc3f42f89452c6fb3429e",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀 the commit IDs for all these module no longer match. Is that intentional? (any chance we could keep them all aligned, so it's clear at a glance that they're all the same content)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to do that by just cp'ing the same files in each repo and using the same commit msg, but I'm guessing that's not sufficient to get the exact same hash. Admittedly I didn't even google it yet so I'll do that 😄

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, sadly, the commit date will be different in each of those, so you'll get different commit hashes 😢

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gonna merge now before more rebasing needed, will follow up with this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix here #9444

Comment thread core/schema/host.go
return parent.NewHost(), nil
}).Doc(`Queries the host environment.`),

dagql.Func("blob", func(ctx context.Context, parent *core.Query, args struct {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

Comment thread dagql/call/id.go
// Return a new ID that's the same as before except with the given metadata changed.
// customDigest, if not empty string, will become the ID's digest.
// tainted sets the ID's tainted flag.
func (id *ID) WithMetadata(customDigest digest.Digest, tainted bool) *ID {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Curious what the interplay between this and elective purity is - do selectors even need to be able to have the Pure field anymore? Since you can just do WithMetadata to taint the instance after the fact.

(and does that mean we could refactor the CacheVolume usage as well?)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm leaving the current impurity stuff for now where it still works, but yeah I think we could migrate everything away from it. I updated all the APIs that actually benefit from custom cache keys here.

(and does that mean we could refactor the CacheVolume usage as well?)

98fef21

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eyyy 🎉

Can confirm that with that commit, looks like we're back down to "normal" logging again - back down to our regular 50MB (will close #9428 in preference of this significantly better fix)

@sipsma
sipsma force-pushed the simplify-module-load-take2 branch from 7be234a to e57cbcb Compare January 17, 2025 01:09
@sipsma sipsma mentioned this pull request Jan 18, 2025
@sipsma
sipsma force-pushed the simplify-module-load-take2 branch from e57cbcb to 98fef21 Compare January 23, 2025 08:59
This enables implementations of API calls to set a custom digest on
returned IDs replacing the default digest calculated by the "call chain
digest".

Currently, this is used to enable content-based caching of certain calls
that previously relied on the separate `blob` API. The `blob` API is
thus removed as part of this change too.

The intention is to setup more use cases for this, including customizing
digests of different ModuleSource implementations and reducing cache
invalidation of SDK calls.

Signed-off-by: Erik Sipsma <[email protected]>
The type of introspectionJson changed from string to *File a long time
ago, but for some reason dagql never error'd out despite the type
mismatch (perhaps something to do with coercing an ID to a string?).

The previous commit accidentally fixed that validation, so this test
started correctly failing now and needs to be corrected.

Signed-off-by: Erik Sipsma <[email protected]>
After the recent filesync improvements, there's no downside to loading
multiple local dirs from the same client in parallel, so we may as well
load all contextual dir args in parallel.

Signed-off-by: Erik Sipsma <[email protected]>
LLB (un)marshalling happens a ton in buildkit and when a file op takes
up lots of space it consumes a ton of memory.

Unfortunately at the moment the best fix is to still use the LLB blob
source for schemas (since they are large files). The `blob` API in
dagger can still disappear thankfully, only the internal LLB source
still needs to exist.

Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
@sipsma
sipsma force-pushed the simplify-module-load-take2 branch from 71a30c5 to 9391d0a Compare January 24, 2025 00:23
@sipsma
sipsma merged commit 35aa68f into dagger:main Jan 24, 2025
vikram-dagger pushed a commit to vikram-dagger/dagger that referenced this pull request Feb 7, 2025
* Add support for custom ID digests to enable content hashing

This enables implementations of API calls to set a custom digest on
returned IDs replacing the default digest calculated by the "call chain
digest".

Currently, this is used to enable content-based caching of certain calls
that previously relied on the separate `blob` API. The `blob` API is
thus removed as part of this change too.

The intention is to setup more use cases for this, including customizing
digests of different ModuleSource implementations and reducing cache
invalidation of SDK calls.

Signed-off-by: Erik Sipsma <[email protected]>

* Update TestCustomSDK to use correct arg type

The type of introspectionJson changed from string to *File a long time
ago, but for some reason dagql never error'd out despite the type
mismatch (perhaps something to do with coercing an ID to a string?).

The previous commit accidentally fixed that validation, so this test
started correctly failing now and needs to be corrected.

Signed-off-by: Erik Sipsma <[email protected]>

* parallelize contextual dir loading

After the recent filesync improvements, there's no downside to loading
multiple local dirs from the same client in parallel, so we may as well
load all contextual dir args in parallel.

Signed-off-by: Erik Sipsma <[email protected]>

* add ability for cache keys to be customized before calls too

Signed-off-by: Erik Sipsma <[email protected]>

* fix excessive memory usage by still using LLB blob source for schema

LLB (un)marshalling happens a ton in buildkit and when a file op takes
up lots of space it consumes a ton of memory.

Unfortunately at the moment the best fix is to still use the LLB blob
source for schemas (since they are large files). The `blob` API in
dagger can still disappear thankfully, only the internal LLB source
still needs to exist.

Signed-off-by: Erik Sipsma <[email protected]>

* fix cache volume caching

Signed-off-by: Erik Sipsma <[email protected]>

* rm telemetry pollution with empty default values

Signed-off-by: Erik Sipsma <[email protected]>

* make currentTypeDefs impure again for now to fix shell tests

Signed-off-by: Erik Sipsma <[email protected]>

* fix setting default values when IDs are loaded

Signed-off-by: Erik Sipsma <[email protected]>

* leave deveng debug port comment out for now, it makes CI infra sad

Signed-off-by: Erik Sipsma <[email protected]>

---------

Signed-off-by: Erik Sipsma <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants