Skip to content

migrate all caching to dagql, remove buildkit solver - #11856

Merged
grouville merged 522 commits into
dagger:mainfrom
sipsma:egraph
Apr 17, 2026
Merged

grouville merged 522 commits into
dagger:mainfrom
sipsma:egraph

Conversation

@sipsma

@sipsma sipsma commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

Status:

At first this PR was going to just be updating the cache to use a new e-graph implementation, which was setup for the final change that removed the buildkit solver and migrated all caching to dagql.

Then, during manual testing I hit a deadlock in the buildkit solver. I had codex spin on it overnight for 3 hours, it found part of the cause but not the full root cause.

It would be foolish to waste time on this, so I'm just expanding the scope of this PR to be the entire removal of the buildkit solver and replacement with dagql. The diff is gonna be gnarly, but I don't think anything else makes sense at this point.

TODOs:

  • e-graph
  • remove dag-op entirely (it was the bridge, but the bridge is no longer needed)
  • add generalized persistence to dagql cache
  • add pruning of persistent dagql cache entries
  • delete buildkit solver related everything (lots of stuff that's unused is still technically initialized, need cleanup all over)
    • There's a couple of util functions left that we use which unfortunately end up entangling a massive amount of transitive buildkit packages. Once those last threads are cut it should all fall out
  • all integ tests passing
  • update internal tech docs and this PR description with more explanation on how everything works

Overall, extremely happy with it. As things progressed, stuff fell into place super nicely and what used to be horrible conundrums that required hacks began having clear and obvious solutions

  • Lots of old cruft is gone already in this PR, with more to come!

e-graph primer

It updates the cache implementation to use smarter data structures and algorithms, namely a union-find structure wrapped up as an e-graph. This:

  • Maximizes our ability to find cache hits, which is trickier than it seems when there's multiple digests associated with an operation/result
  • Gives us good theoretical grounding, which makes correctness+performance easier. This applies not only now but also down the line as we explore more optimizations and features
  • In my experience so far, makes LLMs way less confused, probably since they have been trained on this sort of stuff
  • Simplifies other parts of the codebase since the API will end up being "associate extra digest with operation/result at any time"

A lot of the material on e-graphs is very academic and dense, but like most things of that nature it's actually 100x less complicated than it sounds once you get passed the lingo. Part of the work here is to ensure the implementation here is as clear as possible to humans too.

In the meantime, a rough sketch of why e-graphs make sense to use here:

  • In an e-graph you build up "terms" by defining operations where the result of one operation can be used as the input for another (typical DAG stuff)
  • You also keep track of operations that are "equivalent" (the e in e-graph), where "equivalent" means "this result is interchangeable for another". The union-find data structure helps you do that efficiently

Outside of dagger, an example might be that "1+3" is equivalent to "2+2". Same output "content" but different "recipes" to get there.

In dagger, operations aren't arithmetic, they are our API (core + module functions). "Content" has varying meanings depending on the operation, but a common one is a digest of a resulting filesystem. There's many recipes that result in the same end content, which makes them equivalent.

There's more to it than just that, but that's the gist of why e-graphs match dagger's use case. It frames our problem well and gives us well established algorithms to do things like check for cache hits efficiently.

other significant changes

  • CachePerClient, CachePerSession, etc. used to be modeled by creating custom recipe digests where client-id/session-id/etc. was mixed in the digest.
    • Now those have been remodeled as "implicit inputs" to the call instead. This creates the same end effect of influencing the digest, but with the subtle-yet-crucial difference that these inputs show up in the DAG rather than opaquely influence it by changing a digest in an unobvious way
    • This makes a lot of things in the cache simpler (namely, recalculating digests after changes to the DAG) and should also be extremely helpful for understanding the cache too ("why is this not cached?" type questions)

Fixes #8955

  • TestContainer/TestWithMountedDirectoryCaching started "failing" with Congrats you fixed the bug; please enable the above test and delete this line 🎉
  • Didn't intend to fix this actually, just happened at some point after I stripped buildkit away

@sipsma
sipsma force-pushed the egraph branch 9 times, most recently from b3caf71 to 8a7451a Compare February 20, 2026 22:08
@sipsma
sipsma force-pushed the egraph branch 10 times, most recently from 85f081a to 0a5b19f Compare February 24, 2026 02:38
Comment thread core/schema/container.go Resolved
Comment thread core/schema/container.go Resolved
Comment thread core/schema/container.go Resolved
Comment thread core/schema/module.go Resolved
Comment thread core/schema/module.go Resolved
Comment thread dagql/cachekey.go Resolved
Comment thread dagql/cache_inputs.go Resolved
Comment thread dagql/identity_opt_test.go Resolved
Comment thread dagql/server.go Resolved
Comment thread .gitignore Resolved
@sipsma
sipsma force-pushed the egraph branch 9 times, most recently from 0eb5943 to b525664 Compare February 24, 2026 21:06
@sipsma sipsma changed the title [wip] change cache implementation to e-graph [wip] migrate all caching to dagql Feb 25, 2026
eunomie added 6 commits April 17, 2026 13:32
dupl flagged pairs of lookalike functions in several files. Each pair
is a deliberate sibling pattern where factoring would hide the
type-specific field or lookup being mutated, and the duplicated shapes
are short and stable. Silence the linter with narrowly scoped
//nolint:dupl directives that name the paired symbol; no runtime
change.

Sites annotated (pairs unless noted):
- core/container.go: cloneDetachedDirectoryForContainerResult /
  cloneDetachedFileForContainerResult and WithMountedDirectory /
  WithMountedFile.
- core/container_exec.go: prepareMounts closure vs the
  materializeState closure inside (*ContainerExecState).Evaluate.
- core/directory.go / core/file.go: decodePersistedDirectoryWithSnapshotRole
  and decodePersistedFileWithSnapshotRole.
- core/module.go: (*Module).namespaceTypeDef — the field-vs-arg
  closures and the object/interface/input/enum branches are all
  structurally similar by design.
- core/schema/container.go: (*containerSchema).directory /
  (*containerSchema).file.
- core/schema/directory.go: withPatchFile vs withChanges,
  withoutDirectory vs withoutFile, and withSymlink vs chown.
- core/schema/module.go + module_typedef_canonical.go: the
  loadInputTypeDef / servedInputTypeDef split, plus
  typeDefWithInterface / typeDefWithEnum.
- core/secret.go / core/socket.go: resolveSessionSecret /
  ResolveSessionSocket.
- core/typedef.go: the four AttachDependencyResults methods
  (FunctionArg / FieldTypeDef / InterfaceTypeDef / EnumTypeDef)
  and the two decodePersisted*TypeDef functions.
- dagql/call/id.go + id_content.go: appendLiteralBytes vs
  appendLiteralContentPreferredBytes.
- dagql/call_request_input.go: resultCallLiteralFromRecipeLiteral vs
  resultCallLiteralFromCallLiteral.
- dagql/result_call_frame.go: appendResultCallLiteralBytes vs
  appendResultCallLiteralContentPreferredBytes.
- engine/snapshots/pull.go: (*snapshotManager).importImageLayer, where
  the blob-key and diff-key dedupe blocks are deliberately parallel.

Signed-off-by: Yves Brissaud <[email protected]>
gocyclo flagged 40+ functions above the 30-branch threshold. Each is
a long but legibly-structured state machine or switch-based encoder
where decomposing into helpers would hurt readability more than the
branch count hurts it. Silence the linter with narrowly scoped
//nolint:gocyclo directives; no runtime change.

Sites annotated:
- core/container.go: CacheUsageSize, ContainerDirectoryLazy.Evaluate,
  ContainerFileLazy.Evaluate, decodePersistedContainerLazy.
- core/container_exec.go: Container.execMeta, prepareMounts (merged
  with existing dupl directive), ContainerExecState.Evaluate (merged).
- core/directory.go: decodePersistedDirectoryLazy, Directory.WithFile,
  Directory.WithChanges.
- core/file.go: File.WithReplaced.
- core/interface.go: InterfaceType.Install.
- core/modfunc.go: ModuleFunction.DynamicInputsForCall.
- core/module.go: ApplyWorkspaceDefaultsToTypeDefs,
  ApplyLegacyCustomizationsToTypeDefs, AttachDependencyResults,
  namespaceTypeDef (merged with existing dupl directive), Patch.
- core/object.go: encodePersistedModuleObjectValue.
- core/schema/coremod.go: CoreMod.buildTypeDefs.
- core/schema/host.go: hostSchema.directory.
- core/schema/module.go: expandTypeDefClosure, currentQueryTypeDef.
- core/sdk.go: ContainerRuntime.Call.
- dagql/cache.go: Cache.initCompletedResult.
- dagql/cache_debug.go: Cache.DebugEGraphSnapshot,
  Cache.WriteDebugCacheSnapshot.
- dagql/cache_egraph.go: repairClassTermsLocked,
  teachResultIdentityLocked, indexWaitResultInEgraphLocked,
  compactEqClassesLocked.
- dagql/cache_persistence_import.go: importPersistedState,
  ensurePersistedHitValueLoaded.
- dagql/cache_persistence_self.go: decodePersistedResultEnvelope.
- dagql/cache_persistence_worker.go: snapshotPersistState,
  applyPersistStateSnapshot.
- dagql/cache_test.go: TestCacheContextCancel.
- dagql/server.go: Server.Select.
- engine/contenthash/checksum.go: cacheContext.includedPaths.
- engine/snapshots/blobs.go: snapshotManager.ensureExportBlob.
- engine/snapshots/pull.go: snapshotManager.importImageLayer (merged
  with existing dupl directive).
- util/llbtodagger/exec.go: converter.convertExec.

Signed-off-by: Yves Brissaud <[email protected]>
Follow-up for the few findings that only became reachable once the
earlier passes narrowed signatures.

- core/schema/module_typedef_canonical.go: remove
  (*moduleSchema).servedInputTypeDef. It was never registered on the
  schema; the sibling loadInputTypeDef in module.go is the real entry
  point. Drop the matching nolint:dupl from loadInputTypeDef since
  the pair no longer exists; drop the now-unused fmt import.
- core/object.go: encodePersistedModuleObjectValue's ctx was only
  passed to its own recursive calls and never to anything that
  consumed it; drop the parameter and update all recursive call
  sites.
- core/typedef.go: rename the FieldTypeDef Clone receiver from
  typeDef to field so all FieldTypeDef methods agree on the
  receiver name (ST1016).
- util/llbtodagger/metadata.go: drop the nolint:staticcheck on the
  cfg.ArgsEscaped read added in the earlier staticcheck pass. The
  configured staticcheck rules do not flag this deprecation, so the
  directive is itself flagged by nolintlint.
- gofmt: re-run gofmt on core/module.go, core/object.go,
  dagql/call/id.go, dagql/server.go after edits shifted blank-line
  formatting.

Signed-off-by: Yves Brissaud <[email protected]>
Two follow-ups that together re-green the test suite and the linter:

1. resultIsObject must treat objType.New failure as "not this object
   class", not as a hard error. Some values have a type name matching
   an object class yet are not directly instantiable as it — a
   dagql.Result[Nullable[*T]] has type name T but is not a T. The
   earlier nilerr-driven change made this failure fatal and broke
   TestNullableResults / TestNullableDerefUsesSameSharedResult. Restore
   the (false, nil) swallow and pin it with a narrowly scoped
   //nolint:nilerr plus an inline comment explaining the intent.

2. Replace the inline //nolint:staticcheck on cfg.ArgsEscaped in
   util/llbtodagger/metadata.go with a .golangci.yml exclusion
   scoped to SA1019 + path util/llbtodagger/. An inline directive
   on the deprecated-field read was flagged by nolintlint as unused
   while SA1019 still fires; the config-level exclusion is what we
   actually want (matching the pattern already used for
   idtools.IdentityMapping).

Signed-off-by: Yves Brissaud <[email protected]>
loadGroupListDetails was swapping its ctx for one anchored to a noop
span (via trace.ContextWithSpan + context.Background) before issuing the
batched GraphQL request. That was originally done to suppress per-check
name/description resolver spans in list mode.

With LoadWorkspaceModules becoming opt-in and enabled for `dagger check`,
the first request now triggers a workspace module load that can take
minutes. Because the query subtree was detached from the trace, the
engine never emitted a "POST /query" span (the guard at
engine/server/session.go gates on trace.SpanContextFromContext(ctx).IsValid),
and none of the module-load or resolver spans matched the CLI's trace ID
to be streamed back. The "fetch check information" span therefore sat
with zero children and zero activity for the full module-load window,
and dagql/dagui/db.go's auto-cancel-running-spans path eventually
flipped it to Canceled + LeftRunning, so it rendered as "∅ fetch check
information …" while dag.Do was still blocked.

Drop the detach. Start the span with telemetry.Encapsulate() instead: at
default verbosity the noisy children are still hidden, but they stay in
the trace, so the span's activity keeps it visibly running and the
auto-cancel path no longer fires. On error the children are revealed
automatically, and -v still shows them. Same helper backs `dagger up -l`
and `dagger generate -l`, so they get the same fix.

Signed-off-by: Yves Brissaud <[email protected]>
Signed-off-by: Yves Brissaud <[email protected]>
@grouville grouville changed the title [wip] migrate all caching to dagql migrate all caching to dagql Apr 17, 2026

@grouville grouville left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Bravo !

@grouville
grouville merged commit aa719a1 into dagger:main Apr 17, 2026
65 of 66 checks passed
@shykes shykes changed the title migrate all caching to dagql migrate all caching to dagql, remove buildkit solver Apr 17, 2026
tiborvass added a commit to tiborvass/dagger that referenced this pull request Apr 22, 2026
tiborvass added a commit to tiborvass/dagger that referenced this pull request Apr 22, 2026
This reverts commit aa719a1.

Signed-off-by: Tibor Vass <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request Apr 27, 2026
Restore the pre-dagger#11856 behavior where (*Module).namespaceSourceMap
records at minimum the module name when the SDK does not attach a
source map to a typedef/field/argument.

When commit aa719a1 migrated source-map handling to dagql results, the
synthesizing fallback was lost: the new namespaceSourceMap returns the
nil sourceMap unchanged, so types/fields contributed by SDKs that don't
emit source maps (dang, Java, Python, PHP, Elixir) end up in the schema
without any sourceMap directive.

That sourceMap.module directive is what cmd/codegen/introspection/filters.go
uses to identify dependency types. With the directive missing,
DependencyNames() no longer reports the dep, Exclude() no longer strips
its types from the core schema, and Include() no longer produces a
per-dep <name>.gen.go. The generated code ends up with the dep's types
duplicated between dagger.gen.go (newly inlined) and a stale
<name>.gen.go on disk, which the overlay writer leaves untouched
because the new memfs no longer contains it.

Re-create a minimal SourceMap whose only filled field is the module
name so the downstream filtering logic keeps working for any SDK that
does not provide source-position metadata.

Signed-off-by: Yves Brissaud <[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.

Second to last step is not cached

5 participants