Skip to content

Filter inter-library dependencies per module - #14492

Draft
robinbb wants to merge 8 commits into
mainfrom
robinbb-issue-4572-rebased
Draft

robinbb wants to merge 8 commits into
mainfrom
robinbb-issue-4572-rebased

Conversation

@robinbb

@robinbb robinbb commented May 11, 2026

Copy link
Copy Markdown
Collaborator

Summary

Per-module library dependency filtering for #4572. A consumer module's compile rule now sees only the artefacts of libraries it actually references, so unrelated sibling modules no longer recompile when an unreferenced dependency library's cmi changes. User-facing detail is in the shipped changelog entry under doc/changes/added/.

Predecessor PRs (now closed)

Fixes #4572.

robinbb added a commit that referenced this pull request May 11, 2026
@nojb

nojb commented May 12, 2026

Copy link
Copy Markdown
Collaborator

There seems to be a regression in the latest version of this patch vs previous versions: when a library A depends on a library B and B has an PPX instrumentation, then the dependency fallback (with the glob *.cmi) is used. Repro:

cat >dune-project <<EOF
(lang dune 3.22)
EOF

cat >dune <<EOF
(library
 (name libA)
 (wrapped false)
 (instrumentation (backend foo))
 (modules modA))
(library
 (name libB)
 (wrapped false)
 (modules modB)
 (libraries libA))
EOF

cat >modA.ml <<EOF
let x = 42
EOF

cat >modB.ml <<EOF
let x = ModA.x
EOF

dune=~/dune/dune-pr

echo "dune version: $($dune --version)"

echo 'There should not be a "glob" entry next:'

opam exec -- $dune rules --format json --deps _build/default/.libB.objs/byte/modB.cmo | jq '.[].[].glob'

Output:

nicolasojedabar@LEXIFI-L58:~/sample2$ bash setup.sh
dune version: 3.23.0-203-ga5cd5fa
There should not be a "glob" entry next:
null
null
{
  "dir": [
    "In_build_dir",
    "_build/default/.libA.objs/byte"
  ],
  "predicate": "*.cmi",
  "only_generated_files": false
}

@robinbb
robinbb force-pushed the robinbb-issue-4572-rebased branch from a5cd5fa to 410fa53 Compare May 12, 2026 19:38
robinbb added a commit that referenced this pull request May 12, 2026
@robinbb

robinbb commented May 12, 2026

Copy link
Copy Markdown
Collaborator Author

@nojb I really appreciate you watching this matter, and helping with test cases. I recognise the effort that you must be putting in to give the minimal test cases as you do.

tl;dr I'll investigate adding a fix for this, now, in this PR.

Longer explanation: I (in b531a47) wanted to fix a different soundness bug - preprocessed libs whose .mli leaks a transitive type the consumer never names. My fix correctly handles the Ordinary ppx case (read ocamldep on .pp.ml), but for the instrumentation-only case, the choice was: rather than work out whether --instrument-with is enabled at this build, drop to None. That over-conservative bail-out is what you're is hitting.

robinbb added a commit that referenced this pull request May 12, 2026
is disabled at build time

[build_lib_index]'s [post_pp_module] returned [None] (non-tight-
eligible) for any [Pps] consisting only of [Instrumentation_backend]
entries, on the assumption that no [.pp.ml] is produced. That sent
such libs down the wide-glob fallback path, regressing the per-
module narrow on consumers of instrumentation-decorated libs.

A [.pp.ml] is actually produced only when the build's
[--instrument-with] argument names a backend that the lib declares;
otherwise the lib's compile pipeline reads the raw [.ml].
[Context.instrument_with] gives that argument list; consult it
when classifying each [Instrumentation_backend] entry as active
or not. If no entry is active, return [Some (Module.ml_source m)]
- raw, tight-eligible, narrow path.

Extend [cross-lib-instrumentation-barrier.t] with a [dune rules
--format=json --deps ...] assertion that the consumer's compile
rule has no glob over the instrumented lib's objdir. The original
[$ dune build consumer/consumer.exe] assertion only proved the
build succeeded - the wide-glob fallback also makes it succeed,
so the precision regression went uncaught.

Reported by @nojb on the PR:
#14492 (comment)

Signed-off-by: Robin Bate Boerop <[email protected]>
@robinbb

robinbb commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

@nojb, your test is now reproduced by test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-instrumentation-barrier.t, which passes after 2f264b6. Could you retry against the updated branch?

@robinbb

robinbb commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Tests Added/Changed for this PR

  • All pass

Why each category relates to 14492

§ Category In 14492 Not in 14492 Why related to 14492
A Precision-gap markers 0 3 Each documents a precision gap that 14492's conservative Lib.closure wrapped-glob design deliberately leaves on the table; they would flip under a future BFS-through-wrapped-children walker but do not flip under this PR
B Explicit soundness guards 2 11 Prose names the filter explicitly ("future per-module dep filter must preserve X"); each pins an invariant 14492's narrowing must not break (vlib-impl short-circuit, ppx-runtime exemption, transparent-alias closure, action-pp barrier, etc.)
C Behavioural baselines 0 7 Each asserts a current value (sandbox cmi presence, opaque .cmx shape, vlib + private-modules incremental correctness, menhir --infer -I path) that 14492 changes the underlying mechanism for but preserves the observed value of
D Bug-reproduction baselines 0 1 Documents an over-rebuild bug (top_module's derived cctx triggers can_filter=false → wide deps_of_entries) that 14492 deliberately does not address; see #14477
E NEW tests added by 14492 9 5 Each exercises a code mechanism 14492 introduces: Lib_index.create, cross_lib_tight_set BFS, want_cmx=true per-module branch, build_lib_index's instrumentation classification, mixed per-module preprocess soundness, wrapped-from-vlib soundness, no_ocamldep_lib classification for singleton-with-requires, per-module narrowing on explicit (modules ...), stanza-open BFS expansion, pps_runtime_libs cctx-field propagation for cinaps/toplevel/melange stanzas
F per-module-lib-deps/ core semantic flips 22 0 Each is a direct test-side proof of the narrowing: rebuild count 2→0 when an unreferenced sibling lib/module changes, -I/-H flag list shrinks, byte-side cmi rule drops, transitive cmi closure replaced by per-module specific deps
G Outside per-module-lib-deps/ 4 0 Each is tied to a 14492-induced side-effect: alias-cycle walk-path nodes change shape under the new dep graph; strict-package-deps fixtures need actual cross-package refs (empty touch foo.ml no longer triggers anything); multiple-errors trace expands; cross-compile invokes the per-module ocamldep wrapper on the wrapper alias module
Totals 37 27 64 tests
ID Path Standalone PR
A1 per-module-lib-deps/wrapped-closure-precision.t —
A2 per-module-lib-deps/auto-wrapped-child-reexport.t —
A3 per-module-lib-deps/wrapped-reexport-via-open-flag.t —
B4 per-module-lib-deps/consumer-is-virtual-impl.t —
B5 per-module-lib-deps/modules-without-implementation-cross-lib.t —
B6 per-module-lib-deps/ppx-runtime-libraries.t —
B7 per-module-lib-deps/lib-vs-lib-name-collision.t —
B8 per-module-lib-deps/menhir-incremental-lib-cmi.t —
B9 per-module-lib-deps/transparent-alias-chain.t —
B10 per-module-lib-deps/transparent-alias.t —
B11 per-module-lib-deps/alias-reexport.t —
B12 per-module-lib-deps/cross-lib-action-preprocess.t —
B13 per-module-lib-deps/cross-lib-walk-pre-pp-implicit-transitive.t —
B14 per-module-lib-deps/module-name-shadowing.t —
B15 per-module-lib-deps/no-ocamldep-leaf-lib.t —
B16 root-module/incremental-rebuild.t —
C17 per-module-lib-deps/sandbox-lib-deps.t —
C18 per-module-lib-deps/virtual-library.t —
C19 per-module-lib-deps/private-modules.t —
C20 per-module-lib-deps/opaque-cmx-deps-external.t —
C21 per-module-lib-deps/opaque-cmx-deps-local.t —
C22 virtual-libraries/impl-private-modules-incremental.t —
C23 menhir/with-library-deps.t —
D24 top-module/over-rebuild-from-intf-only-dep.t #14476
E25 per-module-lib-deps/cmx-native-tight-deps.t #14583
E26 per-module-lib-deps/cross-lib-instrumentation-barrier.t/run.t #14584
E27 per-module-lib-deps/cross-lib-pps-runtime-no-ocamldep-barrier.t/run.t #14584
E28 per-module-lib-deps/cross-lib-preprocess-barrier.t #14584
E29 per-module-lib-deps/mixed-per-module-preprocess.t/run.t #14586
E30 per-module-lib-deps/mixed-per-module-preprocess-precision.t/run.t #14586
E31 per-module-lib-deps/wrapped-from-vlib-soundness.t #14444
E32 per-module-lib-deps/wrapped-transition-soundness.t #14444
E33 per-module-lib-deps/singleton-with-requires.t #14582
E34 per-module-lib-deps/unwrapped-explicit-modules.t #14585
E35 per-module-lib-deps/cross-lib-open-flag-barrier.t #14584
E36 per-module-lib-deps/cinaps-pps-runtime-libs.t #14607
E37 per-module-lib-deps/melange-pps-runtime-libs.t #14608
E38 per-module-lib-deps/toplevel-pps-runtime-libs.t #14606
F39 per-module-lib-deps/add-unreferenced-sibling-lib.t —
F40 per-module-lib-deps/basic-wrapped.t —
F41 per-module-lib-deps/cross-lib-walk-pre-pp-source.t —
F42 per-module-lib-deps/implicit-transitive-deps-false.t —
F43 per-module-lib-deps/lib-deps-preserved.t —
F44 per-module-lib-deps/lib-to-lib-unwrapped.t —
F45 per-module-lib-deps/lib-to-lib-wrapped.t —
F46 per-module-lib-deps/multiple-libraries.t —
F47 per-module-lib-deps/opaque-mli-change.t —
F48 per-module-lib-deps/opaque.t —
F49 per-module-lib-deps/per-module-include-flags.t —
F50 per-module-lib-deps/sibling-unreferenced-lib.t —
F51 per-module-lib-deps/single-module-lib.t —
F52 per-module-lib-deps/single-module-unreferenced-lib.t —
F53 per-module-lib-deps/stdlib-modules.t —
F54 per-module-lib-deps/transitive.t —
F55 per-module-lib-deps/transitive-unreferenced-lib.t —
F56 per-module-lib-deps/transitive-unreferenced-module.t —
F57 per-module-lib-deps/unwrapped.t —
F58 per-module-lib-deps/unwrapped-tight-deps.t —
F59 per-module-lib-deps/wrapped-compat.t —
F60 per-module-lib-deps/wrapped-internal-leak.t —
G61 inline-tests/alias-cycle.t —
G62 strict-package-deps.t —
G63 watching/multiple-errors-output.t/run.t —
G64 custom-cross-compilation/cross-compilation-ocamlfind.t —

@robinbb robinbb self-assigned this May 12, 2026
@robinbb
robinbb force-pushed the robinbb-issue-4572-rebased branch 2 times, most recently from 4fa889a to b80622a Compare May 12, 2026 22:02
@robinbb
robinbb requested a review from Copilot May 12, 2026 22:02

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Implements per-module inter-library dependency filtering using ocamldep results, and aligns per-module -I/-H include flags and rule file-dependencies with that filtered dependency set to reduce unnecessary recompilation (fixes #4572).

Changes:

  • Add per-module, cross-library dependency narrowing (including a cross-library BFS for tight-eligible unwrapped local libs) and use it to compute module compile-rule deps.
  • Filter per-module include flags (-I/-H) to match the dependency filter, and adjust library file-dep computation to support both glob and per-entry-module dep shapes.
  • Add/adjust extensive blackbox regression tests and ship a changelog entry describing the behavior change.

Reviewed changes

Copilot reviewed 68 out of 68 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
test/blackbox-tests/test-cases/watching/multiple-errors-output.t/run.t Update expected watch-mode output to include an additional reported syntax error.
test/blackbox-tests/test-cases/strict-package-deps.t Make test sources actually reference dependencies to exercise strict package dep inference.
test/blackbox-tests/test-cases/reporting-of-cycles.t/b/x.ml Add module to help exercise/report cycle behavior.
test/blackbox-tests/test-cases/reporting-of-cycles.t/a/a2/x.ml Add module to help exercise/report cycle behavior.
test/blackbox-tests/test-cases/reporting-of-cycles.t/a/a1/x.ml Add module to help exercise/report cycle behavior.
test/blackbox-tests/test-cases/per-module-lib-deps/wrapped-transition-soundness.t New regression guard for wrapped (transition) soundness with per-module deps.
test/blackbox-tests/test-cases/per-module-lib-deps/wrapped-internal-leak.t Assert wrapped-internal mangled-module access no longer compiles under narrowed deps/includes.
test/blackbox-tests/test-cases/per-module-lib-deps/wrapped-from-vlib-soundness.t New regression guard for wrapped-setting inherited from virtual libs.
test/blackbox-tests/test-cases/per-module-lib-deps/wrapped-compat.t Update expected rebuild counts under per-module filtering.
test/blackbox-tests/test-cases/per-module-lib-deps/unwrapped.t Update narrative/expectations for unwrapped per-module rebuild behavior.
test/blackbox-tests/test-cases/per-module-lib-deps/unwrapped-tight-deps.t Update expectations to reflect tight per-module deps (empty rebuild target lists).
test/blackbox-tests/test-cases/per-module-lib-deps/transitive.t Update expected rebuild counts for transitive unreferenced consumers.
test/blackbox-tests/test-cases/per-module-lib-deps/transitive-unreferenced-module.t Update expectations to no rebuild when a transitively-unreferenced module changes.
test/blackbox-tests/test-cases/per-module-lib-deps/transitive-unreferenced-lib.t Update expectations to no rebuild when a transitively-unreferenced library changes.
test/blackbox-tests/test-cases/per-module-lib-deps/stdlib-modules.t Update expected rebuild counts for stdlib-only consumer.
test/blackbox-tests/test-cases/per-module-lib-deps/single-module-unreferenced-lib.t Update expectations for single-module consumer with zero references.
test/blackbox-tests/test-cases/per-module-lib-deps/single-module-lib.t Update expectations for single-module consumer where ocamldep is now used when deps exist.
test/blackbox-tests/test-cases/per-module-lib-deps/sibling-unreferenced-lib.t Update expectations for non-referencing sibling module in a library stanza.
test/blackbox-tests/test-cases/per-module-lib-deps/per-module-include-flags.t Assert per-module -I filtering drops unrelated lib objdirs.
test/blackbox-tests/test-cases/per-module-lib-deps/opaque.t Update expected rebuild counts in opaque scenarios.
test/blackbox-tests/test-cases/per-module-lib-deps/opaque-mli-change.t Update expected rebuild target lists for .mli changes under opaque rules.
test/blackbox-tests/test-cases/per-module-lib-deps/multiple-libraries.t Update expectations for multiple direct deps with per-module filtering.
test/blackbox-tests/test-cases/per-module-lib-deps/modules-without-implementation-cross-lib.t Minor test text update; keeps regression guard intent.
test/blackbox-tests/test-cases/per-module-lib-deps/mixed-per-module-preprocess.t/run.t New reproducer for mixed per-module preprocessing soundness edge case.
test/blackbox-tests/test-cases/per-module-lib-deps/mixed-per-module-preprocess-precision.t/run.t New guard ensuring mixed-pp libs stay precise when only Some entries are referenced.
test/blackbox-tests/test-cases/per-module-lib-deps/lib-to-lib-wrapped.t Update expected rebuild counts for wrapped lib-to-lib case.
test/blackbox-tests/test-cases/per-module-lib-deps/lib-to-lib-unwrapped.t Update expected rebuild counts for unwrapped lib-to-lib case.
test/blackbox-tests/test-cases/per-module-lib-deps/lib-deps-preserved.t Update assertions around cm_kind/-opaque behavior for library deps.
test/blackbox-tests/test-cases/per-module-lib-deps/implicit-transitive-deps-false.t Update expectations under (implicit_transitive_deps false) with narrowed deps.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-walk-pre-pp-source.t Assert per-module deps use correct .cmi basename and avoid pre-pp source deps.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-preprocess-barrier.t New guard for transitive .cmi reads through a preprocessed intermediate library.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-pps-runtime-no-ocamldep-barrier.t/run.t New guard ensuring ppx runtime deps prevent “no-ocamldep” misclassification.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-instrumentation-barrier.t/run.t New reproducer/guard for instrumentation-disabled .pp.ml mapping and deps globbing.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-instrumentation-barrier.t/ppx/hello.ml Add runtime lib for instrumentation test fixture.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-instrumentation-barrier.t/ppx/hello_ppx.ml Add ppx fixture for instrumentation test.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-instrumentation-barrier.t/ppx/dune-project Add dune-project for ppx fixture.
test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-instrumentation-barrier.t/ppx/dune Add dune file for ppx fixture.
test/blackbox-tests/test-cases/per-module-lib-deps/consumer-is-virtual-impl.t Adjust wording to keep regression guard relevant after refactoring.
test/blackbox-tests/test-cases/per-module-lib-deps/cmx-native-tight-deps.t New guard exercising native .cmx per-module deps under release (opaque=false).
test/blackbox-tests/test-cases/per-module-lib-deps/basic-wrapped.t Update expected rebuild counts for wrapped dependency case.
test/blackbox-tests/test-cases/per-module-lib-deps/add-unreferenced-sibling-lib.t Update expectations: adding an unreferenced lib no longer rebuilds other modules.
test/blackbox-tests/test-cases/inline-tests/alias-cycle.t Make cycle test assert only stable invariants of the dependency-cycle error.
test/blackbox-tests/test-cases/custom-cross-compilation/cross-compilation-ocamlfind.t Update expected trace to include an additional -modules invocation.
src/dune_rules/virtual_rules.mli Expose helper to detect virtual/parameter implementers.
src/dune_rules/virtual_rules.ml Implement is_virtual_or_parameter.
src/dune_rules/parameterised_rules.ml Pass has_library_deps into dep-graph rule generation.
src/dune_rules/ocamldep.mli Add API to read raw ocamldep module-name output.
src/dune_rules/ocamldep.ml Add shared ocamldep output caching and raw dependency reading.
src/dune_rules/ocaml_flags.mli Add API to extract module names from -open flags.
src/dune_rules/ocaml_flags.ml Implement extraction of -open module names.
src/dune_rules/modules.mli Add Modules.as_singleton and document wrapped entry modules.
src/dune_rules/modules.ml Include wrapped-compat shims in wrapped entry modules and add as_singleton.
src/dune_rules/module_compilation.ml Core implementation: per-module lib deps + per-module include-flag filtering.
src/dune_rules/lib.mli Document closure memoization/key considerations.
src/dune_rules/lib.ml Memoize Lib.closure by (linking, for_, libs).
src/dune_rules/lib_rules.ml Compute and pass ppx runtime libs into compilation context.
src/dune_rules/lib_file_deps.mli Add per-entry-module dep APIs and Lib_index for cross-lib filtering.
src/dune_rules/lib_file_deps.ml Implement per-entry-module deps and Lib_index classification/lookup helpers.
src/dune_rules/exe_rules.ml Compute and pass ppx runtime libs into compilation context for executables.
src/dune_rules/dep_rules.mli Extend dep-graph rule API with has_library_deps.
src/dune_rules/dep_rules.ml Only skip ocamldep for singleton stanzas when safe (no lib deps / Melange).
src/dune_rules/dep_graph.mli Add dir and mem helpers for safety checks in filtering.
src/dune_rules/dep_graph.ml Implement dir and mem.
src/dune_rules/compilation_context.mli Add raw-refs/include filtering APIs; add ppx runtime libs plumbing.
src/dune_rules/compilation_context.ml Build lib index, memoize raw refs and filtered include flags, wire into dep-graph creation.
src/dune_lang/lib_mode.mli Add Lib_mode.hash.
src/dune_lang/lib_mode.ml Implement Lib_mode.hash.
doc/changes/added/14492.md Changelog entry describing the new per-module inter-library dep filtering behavior.

Comment thread src/dune_rules/ocamldep.ml Resolved
@nojb

nojb commented May 13, 2026

Copy link
Copy Markdown
Collaborator

@nojb, your test is now reproduced by test/blackbox-tests/test-cases/per-module-lib-deps/cross-lib-instrumentation-barrier.t, which passes after 2f264b6. Could you retry against the updated branch?

I confirm the fix. Thanks!

@robinbb

robinbb commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Performance status: null builds of Dune take 3.8 seconds on 'main' branch, and 5.9 seconds on this branch, 55% longer.

@robinbb

robinbb commented May 13, 2026

Copy link
Copy Markdown
Collaborator Author

Result of Dune Dev meeting today: maintainers want this PR merged piece-wise, and are willing to accept pieces that themselves would not be justified to merge without being part of the solution that this PR proves exists.

@robinbb

robinbb commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

I will produce a sequence of 9 PRs that "sum" to this PR, with the following layers:

Layer PR Ins Del Total Cum Ins % of #14492 Tests Modified
L1 #14513 311 39 350 311 16% 0
L2 #14514 138 0 138 449 23% 0
L3 #14515 75 45 120 524 27% 0
L4 #14516 443 276 719 967 23% 29
L5 #14517 815 96 911 1782 42% 12
L6 #14518 52 45 97 1834 3% 2
L7 #14519 78 14 92 1912 4% 0
L8 #14520 123 10 133 2035 6% 0
L9 #14521 49 5 54 2084 3% 0

@robinbb

robinbb commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator Author

@Alizter Be aware that this is L1..L9, which you reviewed, plus L10 (#14732) which was reviewed by @anmonteiro. If we merge this PR, it all goes into 'main'.

@Alizter

Alizter commented Jun 23, 2026

Copy link
Copy Markdown
Collaborator

Dear compiler people @nojb @alainfrisch (cc @gasche),

The rules in this PR are currently tracking dependencies that are finer than the -I flags can observe. There is a mechanism in this PR to make sure the refinement is sound but it essentially hinges on the following assumption about the compiler:

Given ocamlopt -c m.ml -I dir, the compiler will not load dir/X.{cmi,cmx} unless X (or a module that transitively references X via an interface) appears in m.{ml,mli} after preprocessing.

Can we for the foreseeable future make this assumption? Will or could the compiler ever break this assumption in the future? This will effect the soundness of the rules if broken, i.e. if a compiler invocation is able to observe undeclared dependencies.

We don't sandbox compiler rules by default, so there is no safety mechanism preventing the compiler from observing extra things.

On a related note, OxCaml has a manifest mechanism where you can provide -I with a list of all the files it should see allowing the compiler to only observe those files. We don't have the same for the compiler, so we have to make some assumptions on the dune side in order to take advantage of finer deps.

@gasche

gasche commented Jun 23, 2026

Copy link
Copy Markdown
Member

In general having ways to add a single file to the load path is something we would welcome upstream, see previous work at ocaml/ocaml#9056 . If you were interested in trying to propose something for inclusion yourself, this would be warmly welcome. (I don't know if the OxCaml mechanism is similar or not; if you are convinced that its design is better, you should also feel free to propose going in that direction.)

@nojb

nojb commented Jun 23, 2026

Copy link
Copy Markdown
Collaborator

On a related note, OxCaml has a manifest mechanism where you can provide -I with a list of all the files it should see allowing the compiler to only observe those files. We don't have the same for the compiler, so we have to make some assumptions on the dune side in order to take advantage of finer deps.

(I don't know if the OxCaml mechanism is similar or not; if you are convinced that its design is better, you should also feel free to propose going in that direction.)

I second this!

@Alizter

Alizter commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

Regarding the OxCaml feature I was referring to, it is the -I-manifest and -H-manifest flags. These let you specify a manifest file with a list of cmis etc. that the compiler can observe.

@gasche

gasche commented Jun 23, 2026

Copy link
Copy Markdown
Member

The compiler already supports an -args <file> argument to read additional options from a file, so if you have an option -I <file> you can do the equivalent of -I-manifest with a file with one -I option per line, but maybe the manifest is simpler or more expressive for some other reason.

@robinbb

robinbb commented Jun 23, 2026

Copy link
Copy Markdown
Collaborator Author

Can we for the foreseeable future make this assumption? Will or could the compiler ever break this assumption in the future? This will effect the soundness of the rules if broken, i.e. if a compiler invocation is able to observe undeclared dependencies.

We don't sandbox compiler rules by default, so there is no safety mechanism preventing the compiler from observing extra things.

This is a legit concern, and it will be present in any design in which we attempt to determine analytically in advance of the first compilation (as we do in this PR's design) what the dependencies are. My preference is that we simply accept that the compiler may change its behaviour in future, and that Dune will have to change accordingly.

This is handled in certain other build tools by an alternative design in which no attempt is made to determine the dependencies in advance, but rather the dependencies are determined by the actual files inspected during the compiler invocation by way of tracing (the file-open operations at the OS level). This design has 2 properties superior to the design implicit in this PR. First, it does not have to do any reasoning whatsoever in advance of the (first) compiler invocation. This reduces the complexity burden upon the tool (precisely the complexity in this PR). Second, it is guaranteed to perfectly capture the actual dependencies, not merely the supposed dependencies that the compiler claims to have. That latter property avoids the concern in your question above, and does not necessitate that the compiler make guarantees one way or the other.

@gasche

gasche commented Jun 23, 2026

Copy link
Copy Markdown
Member

This is handled in certain other build tools by an alternative design in which no attempt is made to determine the dependencies in advance, but rather the dependencies are determined by the actual files inspected during the compiler invocation by way of tracing (the file-open operations at the OS level).

This approach often called "tracing" also has strong points but also various disadvantages (in general: more fragility), see the discussion on jyn.dev for example.

@gasche

gasche commented Jun 23, 2026

Copy link
Copy Markdown
Member

@Alizter regarding your initial question, my understand is that your question is: "it is correct that the only compilation units the compiler depends on are those that are named in the files and their build command?". And the answer is, hrm, in general yes, but in some corner cases no:

  • OCaml has some CamlinternalFoo modules that the compiler will link to certain source files due to the use of certain language features, notably CamlinternalLazy for lazy (which can be used without directly referencing the Lazy module of the standard library), and CamlinternalOO for objects.
  • The way that the initial environment is built from the -I options is weird and I suspect breaks this rule, but only for the "initially opened library" (the compilation units that are in the same directory as the initially-loaded pervasives/stdlib compilation unit). See Reproducible env summaries ocaml#9345 (comment) for an example of discussion of these finicky details.
  • In practice the compiler lists all the files in all the -I directories at the beginning and caches them, and then only opens some of them depending on actual compilation dependencies. This should be just an optimization, indistinguishable from looking only at the dependencies, but it avoids repeated filesystem traversals. (This caching is disable for the toplevel, and Merlin does thing differently as well.)

In general (as said before) I think we would be happy to have the means available to restrict the files visible to the compiler, so that mistakes in dependency detection by the build tool become clean build failures.

One way we could end up depending on more things in the future would be if some form of comptime evaluation was added to the language. Then we may need to compile M to actually run code from its comptime dependencies, which means that M will not depend only on X and what is transitively reachable from its interface, but also from its implementation and its transitive dependencies.
(We in fact have some very simple form of this as the cross-module inlining information in foo.cmx, but I suppose you include this in the notion of "interface file for Foo" in your question above.)

@Alizter

Alizter commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks @gasche, that's exactly the kind of thing I was after.

@robinbb, Rudi, I and some others discussed this in last Wednesday's dev meeting. My aim with the discussion was pinning down exactly what we need to do in order to get this work merged.

For this to be more convincing given the performance constraints we should give an example of a large OCaml project that benefits from the perceived increased parallelism. Our typical example is usually dune itself, however due to our import module idiom we cannot directly make benefit of this work AFAICT at this very moment. (See #14061).

We should therefore find another large OCaml project that would greatly benefit from this speedup. I know that @nojb and @alainfrish have reported speedups within LexiFi, but obviously we don't have access to said projects so it would be good to find a more concrete examples.

The thing that @gasche mentioned earlier about compile time evaluation could conceivably be seen as a constraint today since OxCaml itself has compile-time metaprogramming, or so I am told. However we are less concerned with this since we don't appear to have any users. I therefore think we should concern ourselves with it.

@alainfrisch

Copy link
Copy Markdown

Can we for the foreseeable future make this assumption? Will or could the compiler ever break this assumption in the future? This will effect the soundness of the rules if broken, i.e. if a compiler invocation is able to observe undeclared dependencies.

Do I understand correctly that the question is roughly equivalent to "does the transitive closure of ocamldep's output provide a safe over-approximation of the actual dependencies"? It seems to me that dune already makes this assumption, currently only inside a given library/executable.

We don't sandbox compiler rules by default, so there is no safety mechanism preventing the compiler from observing extra things.

I think it would be a worthwhile addition to "OCaml+Dune" if (i) the ocaml tools could be told to output a list of all files they have read/written/observed the absence of, and (ii) dune would use this information to cross check against its own vision of supposed dependencies. (This could also be used to produce, as a side effect of a full build, a very exact dependency graph that could be fed to other, more static, build systems.)

@alainfrisch

Copy link
Copy Markdown

For this to be more convincing given the performance constraints we should give an example of a large OCaml project that benefits from the perceived increased parallelism.

It's true that the finer-grained dependency tracking can improve parallelism on a null build (i.e. avoid idle CPUs during the build), but as far as I understand, the main expected benefit is rather a better experience for incremental builds (less total CPU time, because we just end up recompiling fewer modules).

robinbb and others added 8 commits August 26, 2026 19:36
Narrow each module compile's library .cmi dependencies to those actually reachable — via ocamldep raw references plus effective `-open` flags — rather than globbing every dependency library's objdir. Per-module `-I`/`-H` include flags are scoped to the kept libraries, with caches for the filtered includes, per-cctx raw ocamldep references, and `Lib.closure`. Soundness recoveries cover wrapped libraries, ppx-runtime dependencies, virtual-impl dependencies, and stanza/env `-open` barriers.

Squashed reconstruction of the L1–L9 stack (#14513–#14521) onto current main; see those PRs for per-layer detail. Tests live under test/blackbox-tests/test-cases/per-module-lib-deps/.

Signed-off-by: Robin Bate Boerop <[email protected]>
Signed-off-by: Ali Caglayan <[email protected]>
## Summary

Lifts the `can_filter` Melange opt-out installed by #14516 (L4). The BFS
per-module narrowing pipeline now activates for Melange consumer
compiles on the same terms as OCaml — same `Lib_index`, same wrapped-lib
soundness recovery, same `must_glob_set` / `tight_set` split.

`Module_compilation.lib_deps_for_module` drops the `match
Lib_mode.of_cm_kind cm_kind` arm from `can_filter`. `Dep_rules.rules`
drops the `|| Compilation_mode.equal for_ Melange` disjunct from the
singleton-stanza short-circuit. `Lib_file_deps.deps_of_entry_modules`
gains a `want_cmj` arm symmetric with `want_cmx`, so `Melange Cmj`
consumers see per-module `.cmj` deps in addition to `.cmi`.

The original stack promoted six Melange cram tests for trace-only output
drift. Current main no longer snapshots those unstable traces, so this
rebased commit carries no test-output changes. No artefact changes; same
exit codes.

## Stack

Rebases on #14521 (L9). Part of #14492.

## Validation

- All 112 `test/blackbox-tests/test-cases/melange/*.t` pass after
promotion.
- melange-re/melange 6.0.1-54 unit-test suite: 84/84 OUnit tests pass
against this branch with melange-re/melange's
`test/unit-tests/ounit_unicode_tests.ml` re-routed through
`Melange_ppx.String_interp` (a 3-line patch that's a no-op for upstream
Melange and that the project is welcome to absorb).
- Pristine 6.0.1-54 fails with `module String_interp is an alias for
module Melange_ppx__String_interp, which is missing` — the same
alias-form issue already documented by `wrapped-internal-leak.t` on L4.
The pattern is essentially absent outside Melange's own ppx (zero GitHub
code-search hits for `= Core__`, `= Async__`, `= Ppxlib__`, `=
Bonsai__`).

## Fixes

Part of #14492.

---------

Signed-off-by: Robin Bate Boerop <[email protected]>
Signed-off-by: Ali Caglayan <[email protected]>
@Alizter

Alizter commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

I've rebased and fixed issues on a recent main. I'm marking as draft for the time being so I can re-reivew. Others are also welcome to pitch in until I can work on this again.

This branch has not been deployed

No deployments
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.

Finer dependency analysis between libraries

7 participants