Skip to content

Mitigate 3.25.0-RC performance regression on Rocq builds - #16543

Closed
pgiarrusso-sl wants to merge 5 commits into
ocaml:mainfrom
pgiarrusso-sl:codex/rocq-plugin-memoization
Closed

pgiarrusso-sl wants to merge 5 commits into
ocaml:mainfrom
pgiarrusso-sl:codex/rocq-plugin-memoization

Conversation

@pgiarrusso-sl

Copy link
Copy Markdown

Human Description

@rlepigre-skylabs-ai noticed a big regression in 3.25.0-RC, and Codex confirmed and offered a partial fix; @rlepigre-skylabs-ai found it plausible and suggested opening a PR.

Top-line numbers on the SkyLabs composed workspace for a zero build.

Unchanged Skylabs workspace build Dune 3.24.2 Unpatched RC Patched RC
Runs 6 4 4
Median elapsed time 7.080 s 33.825 s 11.545 s
Elapsed-time range 4.95–8.03 s 33.63–34.31 s 10.70–11.79 s
Median peak RSS 721.8 MiB 6697.4 MiB 1478.0 MiB

Checklist

  • Tests added, if applicable.
  • Change log entry added for any user-facing changes.
  • Documentation added for any user-facing changes.

From Codex GPT-6.1 Sol (high)

Memoize the Rocq plugin-layout action builder so that a theory's proof rules
share its computed result and dependency facts.

ml_flags_and_plugin_ocamlpath creates one plugin_ocamlpath action builder
per theory, but its consumers repeatedly evaluate it. Each evaluation of
Install_layout.For_rocq_only.lib_root reconstructs the layout's Lib/Libexec
dependency set. An allocation profile identifies
Map.Make.bal -> Dep.Set.of_files -> Action_builder.paths -> Install_layout.For_rocq_only.lib_root as a major allocation hot spot.

The three-line change wraps this builder in Action_builder.memoize. It
preserves the declared plugin dependencies, private-plugin checks, and
OCAMLPATH handling.

The benchmark is the Skylabs workspace build, measuring an unchanged
invocation on an already-built workspace with OCaml 5.4.1 + Flambda, -j32,
and --cache=enabled. Candidate binaries were built with make release from
3.25.0-rc at 96db197309ae5c09474246411c9b255a817b5ad6.

An initial six-run comparison measured median elapsed times of 7.08 s with
Dune 3.24.2 and 35.87 s with the unpatched RC. A separate patch comparison
alternated unpatched and patched RC binaries on the same workspace worktree,
with four runs per binary:

The 3.24.2 column uses the initial version comparison; the RC columns use
the separate patch comparison.

Unchanged Skylabs workspace build Dune 3.24.2 Unpatched RC Patched RC
Runs 6 4 4
Median elapsed time 7.080 s 33.825 s 11.545 s
Elapsed-time range 4.95–8.03 s 33.63–34.31 s 10.70–11.79 s
Median peak RSS 721.8 MiB 6697.4 MiB 1478.0 MiB

The paired comparison shows a 2.93x speedup and a 77.9% reduction in peak RSS.
Both binaries discovered and validated 142,177 rules, launched the same 40
helper processes, and performed zero build actions or proof compilations.
Separately recorded GC traces show minor allocation falling from about
4.70 billion words to 1.21 billion words. Timing runs did not use
--dump-gc-stats, which forces additional collections at exit.

This removes a substantial part of the regression, with a remaining gap to
the separately measured 3.24.2 baseline. These are repeated measurements on a
shared host. Clean builds and edited-proof rebuilds were not benchmarked with
the patch.

The preceding test commit extends rocq/plugin-meta.t to check dependency
preservation: two proof modules share one plugin, unchanged builds compile
neither module, and changing the plugin recompiles both. Performance is
validated by the measurements above rather than a timing threshold in Cram.

Validation:

  • make dev, ./dune.exe fmt --preview, and ./dune.exe build @check @fmt
    pass.
  • The extended plugin-materialization/invalidation test passes before and
    after the patch. The existing private-plugin rejection test also passes
    after it, using Rocq 9.2 built with the same OCaml compiler.
  • Local @check @fmt @runtest runs have the same five failing tests before
    and after the patch, with no new failures: the two trace-follow tests
    (trace-cat-follow.t and trace-cat-follow-nested.t),
    landlock-policy.t, and otherlibs/dune-site/test/run{,_2_9}.t.

Check that multiple modules retain plugin dependencies across unchanged builds and both recompile when the workspace plugin changes.

Signed-off-by: Paolo G. Giarrusso <[email protected]>
Reuse the plugin OCAMLPATH action builder result and dependency facts across the rules of a theory instead of rebuilding the layout dependency set for each proof rule.

On an unchanged FM workspace build, the tested RC patch reduced median wall time from 33.825s to 11.545s and peak RSS from 6697.4 MiB to 1478.0 MiB. Plugin materialization, no-op behavior, and recompilation after plugin changes remain covered by the preceding test commit.

Signed-off-by: Paolo G. Giarrusso <[email protected]>
@rlepigre-skylabs-ai rlepigre-skylabs-ai added the rocq Dune support for the Rocq proof assistant label Oct 5, 2026
Comment thread doc/changes/fixed/5.md
@@ -0,0 +1,2 @@
- Reduce time and memory spent evaluating plugin dependencies when building
large Rocq theories. (#5, @pgiarrusso-sl)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
large Rocq theories. (#5, @pgiarrusso-sl)
large Rocq theories. (#16543, @pgiarrusso-sl)

@Alizter Alizter added the regression A defect in previously working behavior, generally breaks existing user workflows label Oct 5, 2026
@pgiarrusso-sl

pgiarrusso-sl commented Oct 5, 2026 •

Copy link
Copy Markdown
Author

@Alizter There is some evidence this regression comes from #14373, even if other work has already reduced the regression. We're investigating additional mitigations via Codex.

• git blame points to commit 95da007 (95da007), introduced by PR #14373 (#14373): “install layouts for package sets.”

That commit added both sides of the expensive path:

• Install_layout.For_rocq_only.lib_root (dune-3.25.0-rc/src/dune_rules/install_layout.ml:198) collects the package-layout files as dependencies.
• Each Rocq proof rule (dune-3.25.0-rc/src/dune_rules/rocq/rocq_rules.ml:884) evaluates that dependency builder. Without memoization, it repeatedly constructs the same large dependency set.

The three-line patch addresses that repeated construction. The remaining regression comes largely from processing the expanded dependencies: after the patch, an unchanged workspace build still hashes 14.3 million layout-file facts. Instrumented dependency hashing takes about 4.6 seconds, versus 0.06 seconds
before #14373. Map merging takes only about 0.07 seconds.

For the requested historical comparison, the exact #14373 binary fails because its layout omits native plugins. This also fails on a prepared workspace. The successful historical measurements therefore include the later Libexec compatibility fix:

Historical version Median time Peak RSS
Parent of #14373 8.68 s 0.68 GiB
Exact #14373 Build fails —
#14373 + native-plugin fix 79.35 s 9.45 GiB
Above + three-line memoization 37.15 s 2.20 GiB

Those are six-run medians for the Skylabs workspace build, after preparation. A separate fresh RC series measured 36.56 → 12.56 seconds with the patch; its parent control measured 7.31 seconds.

This identifies the introducing change and the main residual CPU cost. The extra layout rules also add memory overhead, though I haven’t precisely apportioned the remaining RSS.

@pgiarrusso-sl

pgiarrusso-sl commented Oct 6, 2026 •

Copy link
Copy Markdown
Author

In additional work (pgiarrusso-sl#6, being added here), Rodolphe suggested additional memoization — and Codex autonomously fixed (EDIT) almost all the remaining time performance regression. Memory use remains doubled.

From Codex GPT-6.1 Sol (high)

When several Rocq theories use the same OCaml plugins, Dune repeatedly hashes the same installed plugin files for their proof rules, even during builds with unchanged inputs. This PR lets those rules share the cached result. In the benchmark below, that reduces unchanged-build time by 38%.

The earlier fix caches construction of the dependency list within each theory. Hashing that list still repeats across proof rules. This follow-up puts the files in a Dune alias—a named dependency group—so Dune's existing alias machinery computes their combined digest once during the build for each build context and set of plugin packages.

A plugin change still rebuilds every affected proof. The group uses the existing Lib and Libexec file selection and excludes compiled theory files to avoid dependency cycles. The regression test covers three proof files in two theories: all rebuild after a plugin change, and the next unchanged build performs no proof compilation.

One engine change is needed: install layouts live in build contexts without source directories, where Dune currently discards aliases. This PR retains explicitly defined aliases there. Implicit default aliases remain limited to source contexts.

For the Skylabs workspace build, with unchanged inputs:

Dune variant Samples Median elapsed time Median peak memory
3.24.2 (earlier reference measurements) 6 7.08 s 721.8 MiB
3.25.0-rc + the earlier fix 6 12.37 s 1,478.7 MiB
3.25.0-rc + the earlier fix + this change 6 7.64 s 1,375.7 MiB

The two RC variants were measured in six alternating samples each, after successful full builds in separate worktrees with identical input revisions. The 3.24.2 row is an earlier reference measurement, outside that alternating comparison. These results measure the cost of checking an already-built project; they do not measure fresh proof compilation.

This PR is based on the earlier fix, so its diff contains the additional dependency-group caching and test coverage. The repeated hashing originates in the plugin install layouts introduced by ocaml/dune#14373.

make dev, dune build @check @fmt, and the expanded plugin-invalidation test pass. The full test suite does not pass in the test container, so this remains a draft. The Rocq suite has the same two failures before and after the change. Each full-suite run reported 11 failures; six cases whose outcomes differed between those runs all passed fresh targeted runs in both variants.

Benchmark setup and profiling details

The measurements used ghcr.io/skylabsai/workspace:fm-default, OCaml 5.4.1 with Flambda, and Dune built from source with make release.

dune build -j32 --display=quiet --cache=enabled @vendored/install @fmdeps/all

The benchmark source base was 96db197309ae5c09474246411c9b255a817b5ad6 on 3.25.0-rc. This PR applies the same change to the earlier fix's branch, using that branch's Alias_spec.to_list API. The timings above are measurements of the RC variants.

Changing the dependency representation changes rule fingerprints, so switching to the patch requires an initial rebuild. Both variants completed that preparation before timing began.

Separate diagnostic runs, excluded from the table, reduced per-rule dependency hashing from 4.59 s to 0.10 s and file facts traversed from 14,500,917 to 224,959. That timer excludes construction of the alias's combined digest; the elapsed build timings include it. Both variants still validate 142,177 rules.

Test-suite limitations

The two Rocq failures are config-no-coqc.t (expected missing-library diagnostics differ) and coqdoc-with-boot.t (jq parsing).

The full-suite runs had eight common failing cases and three varying cases each. The common failures concern dune-site installation, trace-follow timeouts, landlock, a build-info PPX warning, readonly-cache expectations, and an opam variable expectation. The six varying cases passed fresh targeted executions in both variants, including after removing temporary (universe) dependencies used to ensure fresh execution.

Tests ran as the normal workspace user after installing missing stable development and test dependencies in the disposable container. Pre-release Dune was built from source throughout.

# From Codex GPT-6.1 Sol (high)

When several Rocq theories use the same OCaml plugins, Dune repeatedly
hashes the same installed plugin files for their proof rules, even
during builds with unchanged inputs. This commit lets those rules share
the cached result. In the benchmark below, that reduces unchanged-build
time by 38%.

The prerequisite fix (ef1e908,
#5) caches construction of the
dependency list within each theory. Hashing that list still repeats
across proof rules. This follow-up puts the files in a Dune alias—a
named dependency group—so Dune's existing alias machinery computes their
combined digest once during the build for each build context and set of
plugin packages.

A plugin change still rebuilds every affected proof. The group uses the
existing `Lib` and `Libexec` file selection and excludes compiled theory
files to avoid dependency cycles. The regression test covers three proof
files in two theories: all rebuild after a plugin change, and the next
unchanged build performs no proof compilation.

One engine change is needed: install layouts live in build contexts
without source directories, where Dune currently discards aliases. This
commit retains explicitly defined aliases there. Implicit default
aliases remain limited to source contexts.

For the Skylabs workspace build, with unchanged inputs:

| Dune variant | Samples | Median elapsed time | Median peak memory |
| --- | ---: | ---: | ---: |
| 3.24.2 (earlier reference measurements) | 6 | 7.08 s | 721.8 MiB |
| 3.25.0-rc + the earlier fix | 6 | 12.37 s | 1,478.7 MiB |
| 3.25.0-rc + the earlier fix + this change | 6 | 7.64 s | 1,375.7 MiB |

The two RC variants were measured in six alternating samples each, after
successful full builds in separate worktrees with identical input
revisions. The 3.24.2 row is an earlier reference measurement, outside
that alternating comparison. These results measure the cost of checking
an already-built project; they do not measure fresh proof compilation.

This commit follows the prerequisite fix and the cross-theory
regression-test commit; it adds dependency-group caching. The repeated
hashing originates in the plugin install layouts introduced by
ocaml#14373 (ocaml#14373).

`make dev`, `dune build @check @fmt`, and the expanded
plugin-invalidation test passed during validation. The full test suite
did not pass in the test container. The Rocq suite had the same two
failures before and after the change. Each full-suite run reported 11
failures; six cases whose outcomes differed between those runs all
passed fresh targeted runs in both variants.

Benchmark setup and profiling:

The measurements used `ghcr.io/skylabsai/workspace:fm-default`, OCaml
5.4.1 with Flambda, and Dune built from source with `make release`.

```sh
dune build -j32 --display=quiet --cache=enabled @vendored/install @fmdeps/all
```

The benchmark source base was `96db197309ae5c09474246411c9b255a817b5ad6`
on `3.25.0-rc`. This commit applies the same change to the earlier fix's
branch, using that branch's `Alias_spec.to_list` API. The timings above
are measurements of the RC variants.

Changing the dependency representation changes rule fingerprints, so
switching to the patch requires an initial rebuild. Both variants
completed that preparation before timing began.

Separate diagnostic runs, excluded from the table, reduced per-rule
dependency hashing from 4.59 s to 0.10 s and file facts traversed from
14,500,917 to 224,959. That timer excludes construction of the alias's
combined digest; the elapsed build timings include it. Both variants
still validate 142,177 rules.

Test-suite limitations:

The two Rocq failures are `config-no-coqc.t` (expected missing-library
diagnostics differ) and `coqdoc-with-boot.t` (jq parsing).

The full-suite runs had eight common failing cases and three varying
cases each. The common failures concern dune-site installation,
trace-follow timeouts, landlock, a build-info PPX warning,
readonly-cache expectations, and an opam variable expectation. The six
varying cases passed fresh targeted executions in both variants,
including after removing temporary `(universe)` dependencies used to
ensure fresh execution.

Tests ran as the normal workspace user after installing missing stable
development and test dependencies in the disposable container.
Pre-release Dune was built from source throughout.

Signed-off-by: Paolo G. Giarrusso <[email protected]>
@pgiarrusso-sl pgiarrusso-sl mentioned this pull request Oct 6, 2026
Comment on lines -894 to +895
(* There are no aliases in contexts without sources *)
Memo.return Alias.Name.Map.empty
Memo.return
(Alias.Name.Map.map collected.aliases ~f:Rules.Dir_rules.Alias_spec.to_list)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The agent called out this change:

One engine change is needed: install layouts live in build contexts without source directories, where Dune currently discards aliases. This PR retains explicitly defined aliases there. Implicit default aliases remain limited to source contexts.

This is needed because the agent adds an alias to help memoization – computations on that alias node are cached instead of repeated.

@Alizter Alizter self-assigned this Oct 6, 2026
@shonfeder shonfeder mentioned this pull request Oct 6, 2026
62 tasks done
The package build can report the missing Corelib through either the
Common theory or extraction. Checking one dependency chain makes
config-no-coqc.t depend on which failing rule is evaluated first.

Capture stderr and omit only those intermediate Coq paths. Keep the
missing-Corelib message, package install target, install alias, failure
exit status, and assertion that no install manifest was produced.

Signed-off-by: Paolo G. Giarrusso <[email protected]>
@Alizter

Alizter commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

There are a few ways we can improve the performance here. I've reviewed the patches, and I think adding more memoization or changing the engine should be a last resort. More memoization will increase memory usage as you've found out, and changing the engine has the potential to penalise non-rocq projects.

I've therefore opened #16622 which tries to avoid the useless work that we are doing by making sure certain layouts and deps are computed once. I would be interested to see the performance increase that you have on your internal repository.

After that patch, we have a few more patches that we can try, and if it still is slow we may consider memoization, if its still relevant (I suspect not by then).

Alizter added a commit that referenced this pull request Oct 19, 2026
## Description

Group Lib and Libexec files in all-library directories with
unconditional generated-file selectors. Reuse their dependency hashes
across discovery, compilation, and extraction while materializing the
files in sandboxes without requiring alias expansion.

Construct the groups lazily within the existing layout-entry memo and
force them only for Rocq consumers. Ordinary package dependencies and
layout rule generation do not construct unused groups or selectors.

Keep directory entries and library files in mixed-section directories as
explicit dependencies. This excludes root-section theory outputs without
cycles or quadratic literal-name filtering.

Preserve the existing dependency set and proof rebuild behavior. No
engine changes, new memo table, or changes to Rocq rule generation are
needed. Dependency narrowing and environment construction remain
separate changes.

<!-- Thank you for contributing to dune!

 For general guidelines on contributing to dune, see
https://github.com/ocaml/dune/blob/main/CONTRIBUTING.md#developing-dune
-->

<!-- Briefly describe your changes -->

## Related Issue and Motivation

Addresses perf regression reported in
#16543.

cc @rlepigre-skylabs-ai @pgiarrusso-sl could you benchmark this change
on your internal repo? I have some more perf improvements so I'm mostly
interested in 3.24 vs 3.25-rc vs this.

## Checklist

- [x] Tests added, if applicable.
- [ ] [Change log entry
added](../CONTRIBUTING.md#updating-the-changelog) for any user-facing
changes.
- [x] Documentation added for any user-facing changes.
Alizter added a commit that referenced this pull request Oct 19, 2026
Rename the fragment added by #16622 and point it at that PR rather than
#16543, which contains the alternative performance proposal.

Signed-off-by: Ali Caglayan <[email protected]>
Alizter added a commit that referenced this pull request Oct 19, 2026
Correct the changelog fragment added by #16622: rename `16543.md` to
`16622.md` and update its PR reference. #16543 is the alternative
performance proposal, not the merged change described by this entry.

No code or wording changes beyond the PR reference. The same correction
is included in the 3.25 backport, #16647.

Validation: `./dune.exe build -j4 @check @fmt` passes. Tests skipped for
this documentation-only change.
Alizter added a commit that referenced this pull request Oct 19, 2026
…#16647)

Backport #16622 to `3.25.0-rc`, reducing repeated Rocq plugin-layout
dependency processing in unchanged builds. Related to the performance
regression discussed in #16543; tracked in #15593.

Includes the three existing regression-test commits before the fix:
conservative proof invalidation, shared layout dependencies and actual
sandbox inputs, and mixed-directory dependency representation. The
implementation, tests, and developer documentation match the merged PR.
The changelog fragment is renamed to `16622.md` and corrected to
reference #16622 rather than #16543.

No dependency narrowing, environment-construction optimization, or
engine changes are included. Existing dependencies and rebuild behavior
are preserved.

Validation using the release branch's Nix environment (including
#16599's dependency-builder pin):
- `@check`, `@fmt`, and `@runtest-rocq` pass on all four commits.
- Package-materialization tests pass on the final commit.

Full `@runtest` was not run; validation was limited to the focused
checks above.
@pgiarrusso-sl

Copy link
Copy Markdown
Author

Closing for now.

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

Labels

regression A defect in previously working behavior, generally breaks existing user workflows rocq Dune support for the Rocq proof assistant

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants