Skip to content

Start long dependency chains first in deps.partition - #16171

Closed
pmargreff wants to merge 1 commit into
elixir-lang:mainfrom
pmargreff:deps-partition-size-order
Closed

pmargreff wants to merge 1 commit into
elixir-lang:mainfrom
pmargreff:deps-partition-size-order

Conversation

@pmargreff

@pmargreff pmargreff commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

With MIX_OS_DEPS_COMPILE_PARTITION_COUNT, each free partition gets the first dependency, in converger order, whose children have compiled. The converger order says nothing about how much work comes after each dependency, so the start of a long chain can wait behind small dependencies that nothing depends on. Near the end of the build, the other partitions then have nothing to compile while that chain compiles on one of them, and the CPU sits idle. With 8 partitions on 16 cores, the CPU is idle for 45% of the Plausible build and 27% of the hexpm build.

This PR cuts that idle time. It sorts the dependencies once by the source size of their longest chain of dependents: the .ex, .erl, .xrl, .yrl and C/C++ files under a dependency's lib, src and c_src, plus the largest such value among its dependents.

Results

Fresh builds of four projects (deps/ as mix deps.get leaves it, then mix deps.compile --force), 10 rounds per partition count, with Elixir main and this PR back to back in each round. Median build time in seconds, main → this PR, then the median per-round change and the rounds where this PR was faster:

Project (deps) Serial 2 partitions 4 partitions 6 partitions 8 partitions 12 partitions
Plausible (164) 140.3 78.2 → 73.8 −4.9%, 10/10 49.2 → 45.5 −7.9%, 10/10 48.5 → 42.0 −10.7%, 10/10 47.7 → 43.1 −8.7%, 7/10 48.9 → 46.1 −5.6%, 8/10
hexpm (153) 45.9 25.2 → 25.1 −0.2%, 8/10 17.1 → 16.0 −6.5%, 10/10 15.6 → 13.9 −11.0%, 10/10 15.5 → 14.5 −6.5%, 10/10 15.9 → 15.2 −4.5%, 9/10
Livebook (51) 37.5 21.1 → 21.2 +0.3%, 3/10 14.3 → 15.4 +7.7%, 0/10 14.4 → 14.1 −1.8%, 10/10 13.9 → 14.2 +2.7%, 0/10 14.0 → 14.0 +0.7%, 3/10
Tuist server (236) 190.5 109.8 → 105.2 −4.4%, 10/10 66.9 → 65.2 −2.6%, 10/10 58.4 → 57.3 −1.7%, 10/10 56.0 → 57.2 +2.2%, 1/10 56.4 → 57.4 +2.2%, 4/10

Build time by partition count

The dashed line is a reference: a benchmark-only build of Mix that weighs each dependency by its compile time in the previous build.

Less idle CPU

Idle CPU is the share of the 16 cores' time that no partition used during the build: 16 × the build time, minus the CPU time of all partitions. Median over the rounds, main → this PR:

Project Serial 2 partitions 4 partitions 6 partitions 8 partitions 12 partitions
Plausible 84% 70% → 69% 50% → 46% 47% → 39% 45% → 38% 44% → 40%
hexpm 78% 58% → 59% 36% → 31% 29% → 19% 27% → 21% 26% → 23%
Livebook 82% 66% → 66% 46% → 51% 45% → 44% 41% → 43% 39% → 40%
Tuist server 82% 68% → 66% 45% → 43% 34% → 32% 29% → 29% 27% → 27%
Idle CPU round by round, for every project

Change in idle CPU

The work barely changes: CPU time is at most 2.5% higher with this PR, so the CPU is less idle because the same work finishes sooner. Peak memory is higher in most cells, by up to 13% (Plausible with 2 partitions), and lower in a few, by up to 12% (Tuist with 2).

The idle CPU comes from partitions with nothing to compile. With 8 partitions, the partitions are busy 70% of the build instead of 61% in Plausible, and 81% instead of 69% in hexpm.

Plausible, 8 partitions

The median build of each order for Plausible with 8 partitions. Each bar is a dependency on the partition that compiled it, and the bars with a dashed outline are the critical chain, the longest chain of dependencies by serial compile time: decimal → jason → ex_cldr → ex_cldr_currencies → ex_cldr_numbers → ex_money. Under the schedules is the number of partitions busy over time. The dashed vertical line is where the reference build finished.

The interactive version of these charts, for every project and partition count, is in the schedule Livebook.

Where it does not help

Source size only sees what is in lib, src and c_src. When a slow dependency's cost is somewhere else, this order sends it late:

  • Livebook (+7.7% with 4 partitions and +2.7% with 8, slower in every round at both): most of makeup_erlang's 9.1 s is code that NimbleParsec generates at compile time.
  • Tuist (+2.2% with 8 and 12 partitions): this order starts the CLDR chain earlier than main (ex_cldr at 17.3 s instead of 19.5 s with 8 partitions), but ex_cldr_numbers takes 21.9 s instead of 18.9 s.

Shortening the critical chain

From 6 partitions on, these builds wait mostly on their critical chain, and the dependencies on it have to compile faster. I am working on identifying and addressing some of those bottlenecks in OTP or in popular Elixir dependency repos:

These projects are anecdotal, but they were very prominent during this investigation. I will eventually check the 100 or 200 most popular Hex deps and see if they contain any compilation bottlenecks that can be patch on OTP.

Other options

I also tried other weights: counting dependencies instead of bytes, sending C, Erlang and NIF dependencies first, per-language weights and a fixed cost per rebar3 dependency. None did better than source size on these projects, as the long chains are mostly Elixir packages.

Weighing each dependency by its compile time in the previous build would improve the Livebook and Tuist cases. This strategy is highlighted in most of charts as Time order, and I used it as the benchmark. Ninja tried that for its critical path scheduler (ninja-build/ninja#2019) and merged a static weight instead (ninja-build/ninja#2177). It does not seem worth it here: Mix would have to store and invalidate each dependency's compile time next to its manifest, and a first or cold build would take a different path than the builds after it.

Using only dependency depth could also work but would then favor long chain with small deps in comparison with shallow chain with big files, they are not the standard case but can still happen.

Benchmark

The notebooks, the data and the scripts are in pmargreff/mix-deps-partition-benchmark.

main is Elixir main at 3bce30a and HEAD is this PR on top of it, both built from the same tree. Since the run, the branch has been rebased on d8f5192, and the sizing has moved to a task that runs while the partitions connect; it gives the same sizes for all 627 dependencies of these projects.

Each build copies deps/ as mix deps.get left it and runs mix deps.compile --force with MIX_DEBUG=1 on the packages that mix deps.tree --only dev lists. The projects are hexpm at 7bcd3a9, Plausible at 418da46, the server directory of the Tuist repository as of 2026-11-19, and Livebook at 427774a.

The machine is an Intel Core Ultra 9 285HX (8 P-cores, 16 E-cores) with 48 GB of memory, running Linux 7.2 and OTP 29.1.2.

  • Every build runs on the 16 E-cores (taskset -c 8-23), and every partition VM inherits that, so no partition lands on a faster P-core.
  • The E-cores are held at 3.5 GHz, a speed they sustain for the whole run, so no build runs faster on boost or slower when the chip heats up. No core throttled during any build.
  • Benchee and everything else run on the P-cores.
  • Each build runs in a cgroup of its own (systemd-run --user --scope), only to measure the peak memory and CPU time of all its partitions together.

Benchee takes all the samples of a scenario back to back, which would run every main build before every HEAD build. Instead:

  • Benchee collects each build on its own, and the script merges the builds of each job and input before Benchee computes its statistics.
  • In each round, the inputs run in a shuffled order, and the order of the jobs is reversed every round.
  • main, again (the noise check) runs at 8 partitions in every round. The benchmark-only build of Mix also ran in some rounds; the script and the output below leave it out.
Benchmark script
# Benchmarks `mix deps.compile` with the dependencies compiled across partitions
# (MIX_OS_DEPS_COMPILE_PARTITION_COUNT), with Benchee. It compares Elixir main
# ("main", converger order) with this PR ("HEAD", size order).
#
#     taskset -c 0-7 elixir deps_compile.exs CONFIG.json          # run (resumes)
#     taskset -c 0-7 elixir deps_compile.exs CONFIG.json report   # tables again
#
# Every build starts from `deps/` exactly as `mix deps.get` left it (a reflink
# copy of a pristine directory) and runs `mix deps.compile --force`, pinned to the
# same cores, in a cgroup of its own, so its peak memory and CPU time cover every
# partition. Throttle counters of those cores are read before and after each build.
#
# Benchee takes all samples of a scenario back to back, which would run every main
# build before every HEAD build. Instead, Benchee collects each build on its own,
# the jobs alternate their order every round (ABBA), the order of the inputs is
# shuffled every round, and the samples are merged per scenario for Benchee's
# statistics and tables. Each build is saved as JSON (wall time, Benchee's sample,
# every output line with its timestamp, memory, CPU and throttling), so an
# interrupted run resumes where it stopped.
#
# CONFIG.json:
#
#     {
#       "workspace": "/path",               # holds pristine/<project>, runs/, build/
#       "out": "/path/results",
#       "otp_bin": "/path/to/erlang/bin",
#       "cores": "8-23",                    # the cores every build is pinned to
#       "rounds": 10, "partitions": [2, 4, 6, 8, 12], "serial_rounds": 3,
#       "jobs": [["main", "/path/elixir-main/bin"], ["HEAD", "/path/elixir-head/bin"]],
#       "control": {"job": "main", "name": "main, again", "partitions": [8]},
#       "projects": [{"name": "hexpm", "label": "hexpm", "dir": "/path/hexpm",
#                     "env": {}, "packages": ["..."]}]
#     }
Mix.install([{:benchee, "~> 1.5"}])

defmodule Bench do
  def config(path) do
    cfg = path |> File.read!() |> JSON.decode!()
    File.mkdir_p!(cfg["out"])
    cfg
  end

  def cores(cfg) do
    for part <- String.split(cfg["cores"], ","), reduce: [] do
      acc ->
        case String.split(part, "-") do
          [a, b] -> acc ++ Enum.to_list(String.to_integer(a)..String.to_integer(b))
          [a] -> acc ++ [String.to_integer(a)]
        end
    end
  end

  def input_name(project, n), do: "#{project["label"]}, #{n} partitions"

  def key(project, job, n, round) do
    slug = job |> String.replace(~r/[^A-Za-z0-9]+/, "_") |> String.trim("_")
    "#{project["name"]}_#{slug}_n#{n}_r#{round}"
  end

  def result_path(cfg, key), do: Path.join(cfg["out"], key <> ".json")

  defp job_bin(cfg, job), do: Enum.find_value(cfg["jobs"], fn [name, bin] -> name == job && bin end)

  # Everything a build needs, done before Benchee starts timing it
  def prepare(cfg, project, job, n, round) do
    key = key(project, job, n, round)
    run_dir = Path.join([cfg["workspace"], "runs", Path.basename(cfg["out"]), project["name"],
                         "#{key}_#{System.os_time()}"])
    File.mkdir_p!(run_dir)
    deps = Path.join(run_dir, "deps")
    pristine = Path.join([cfg["workspace"], "pristine", project["name"]])
    {_, 0} = System.cmd("cp", ["-a", "--reflink=always", pristine, deps])

    # The Mix being measured is "main, again" for the control, but runs as its job
    bin_job = if job == get_in(cfg, ["control", "name"]), do: cfg["control"]["job"], else: job

    env =
      Map.merge(project["env"] || %{}, %{
        "PATH" => "#{job_bin(cfg, bin_job)}:#{cfg["otp_bin"]}:#{System.get_env("PATH")}",
        "MIX_ENV" => project["mix_env"] || "dev",
        "MIX_DEBUG" => "1",
        "MIX_DEPS_PATH" => deps,
        "MIX_BUILD_ROOT" => Path.join([cfg["workspace"], "build", project["name"]]),
        "MIX_OS_DEPS_COMPILE_PARTITION_COUNT" => if(n > 1, do: Integer.to_string(n)),
        "BENCH_STATS" => Path.join(run_dir, "cgroup_stats")
      })

    %{
      cfg: cfg, project: project, job: job, partitions: n, round: round, key: key,
      run_dir: run_dir, env: env,
      throttle_before: throttle(cfg)
    }
  end

  # The build itself: what Benchee times
  def run(prep) do
    cfg = prep.cfg
    # The shell runs inside the build's cgroup and reports its peak memory and CPU
    # time once the build is over
    script = ~S"""
    cg=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)
    "$@"; rc=$?
    { cat "$cg/memory.peak"; cat "$cg/cpu.stat"; } > "$BENCH_STATS"
    exit $rc
    """

    args =
      ["--user", "--scope", "--quiet", "--collect", "--", "taskset", "-c", cfg["cores"],
       "bash", "-c", script, "bash", "mix", "deps.compile", "--force" | prep.project["packages"]]

    env = Enum.map(prep.env, fn {k, v} -> {String.to_charlist(k), if(v, do: String.to_charlist(v), else: false)} end)
    t0 = System.monotonic_time(:microsecond)

    port =
      Port.open({:spawn_executable, System.find_executable("systemd-run")}, [
        :binary, :exit_status, :stderr_to_stdout, {:line, 1_000_000},
        args: args, env: env, cd: prep.project["dir"]
      ])

    {lines, exit} = read(port, t0, [], "")
    Map.merge(prep, %{lines: lines, exit: exit, total_ms: (System.monotonic_time(:microsecond) - t0) / 1000})
  end

  defp read(port, t0, lines, partial) do
    receive do
      {^port, {:data, {:noeol, chunk}}} ->
        read(port, t0, lines, partial <> chunk)

      {^port, {:data, {:eol, chunk}}} ->
        t = Float.round((System.monotonic_time(:microsecond) - t0) / 1000, 1)
        read(port, t0, [[t, String.replace_invalid(partial <> chunk)] | lines], "")

      {^port, {:exit_status, status}} ->
        {Enum.reverse(lines), status}
    end
  end

  def throttle(cfg) do
    for core <- cores(cfg), kind <- ["core", "package"], reduce: %{} do
      acc ->
        path = "/sys/devices/system/cpu/cpu#{core}/thermal_throttle/#{kind}_throttle_count"

        case File.read(path) do
          {:ok, count} -> Map.update(acc, kind, String.to_integer(String.trim(count)), &(&1 + String.to_integer(String.trim(count))))
          _ -> acc
        end
    end
  end

  # One build, collected by Benchee on its own
  def collect(cfg, project, job, n, round) do
    prep = prepare(cfg, project, job, n, round)
    parent = self()

    suite =
      [
        inputs: [{input_name(project, n), prep}],
        warmup: 0,
        time: 7200,
        memory_time: 0,
        reduction_time: 0,
        max_sample_size: 1,
        pre_check: false,
        formatters: [],
        print: [benchmarking: false, configuration: false, fast_warning: false],
        after_each: fn result -> send(parent, {:build, result}) end
      ]
      |> Benchee.init()
      |> Benchee.system()
      |> Benchee.benchmark(job, &run/1)
      |> Benchee.collect()

    [%{run_time_data: %{samples: [sample]}}] = suite.scenarios
    result = receive do: ({:build, result} -> result)
    save(cfg, result, sample)
  end

  defp save(cfg, result, sample) do
    stats = parse_stats(Path.join(result.run_dir, "cgroup_stats"))
    after_ = throttle(cfg)

    record = %{
      "project" => result.project["name"],
      "job" => result.job,
      "partitions" => result.partitions,
      "round" => result.round,
      "exit" => result.exit,
      "total_ms" => Float.round(result.total_ms, 1),
      "benchee_ns" => sample,
      "memory_peak_bytes" => stats["memory.peak"],
      "cpu_s" => stats["usage_usec"] && stats["usage_usec"] / 1.0e6,
      "user_s" => stats["user_usec"] && stats["user_usec"] / 1.0e6,
      "sys_s" => stats["system_usec"] && stats["system_usec"] / 1.0e6,
      "throttle" => Map.new(after_, fn {k, v} -> {k, v - Map.get(result.throttle_before, k, v)} end),
      "lines" => result.lines
    }

    path = result_path(cfg, result.key)

    # A failed build is kept aside, so the build runs again on resume
    path = if result.exit == 0, do: path, else: String.replace_suffix(path, ".json", ".failed_#{System.os_time()}.json")
    File.write!(path, JSON.encode!(record))

    IO.puts(
      "#{Calendar.strftime(NaiveDateTime.local_now(), "%H:%M:%S")} #{result.key}: exit=#{result.exit} " <>
        "#{Float.round(result.total_ms / 1000, 1)} s, peak #{div(stats["memory.peak"] || 0, 1_000_000)} MB, " <>
        "CPU #{Float.round((stats["usage_usec"] || 0) / 1.0e6, 1)} s, throttled #{inspect(record["throttle"])}"
    )

    record
  end

  defp parse_stats(path) do
    case File.read(path) do
      {:ok, text} ->
        [peak | rest] = String.split(text, "\n", trim: true)

        rest
        |> Map.new(fn line -> [k, v] = String.split(line); {k, String.to_integer(v)} end)
        |> Map.put("memory.peak", String.to_integer(peak))

      _ ->
        %{}
    end
  end

  def done?(cfg, project, job, n, round), do: File.exists?(result_path(cfg, key(project, job, n, round)))

  def build(cfg, project, job, n, round) do
    if done?(cfg, project, job, n, round) do
      :skipped
    else
      record = collect(cfg, project, job, n, round)

      # One retry right away for an intermittent failure
      if record["exit"] != 0, do: collect(cfg, project, job, n, round), else: record
    end
  end

  def jobs_for(cfg, n, round) do
    jobs = Enum.map(cfg["jobs"], &hd/1)
    control = cfg["control"]
    jobs = if control && n in control["partitions"], do: jobs ++ [control["name"]], else: jobs
    if rem(round, 2) == 1, do: jobs, else: Enum.reverse(jobs)
  end

  def run_all(cfg) do
    inputs = for project <- cfg["projects"], n <- cfg["partitions"], do: {project, n}

    # Serial builds first: the serial times, and they warm the page cache
    for round <- 1..cfg["serial_rounds"]//1, project <- cfg["projects"] do
      build(cfg, project, cfg["jobs"] |> hd() |> hd(), 1, round)
    end

    for round <- 1..cfg["rounds"] do
      :rand.seed(:exsss, {2026, 11, round})

      for {project, n} <- Enum.shuffle(inputs), job <- jobs_for(cfg, n, round) do
        build(cfg, project, job, n, round)
      end
    end
  end

  # Benchee's statistics and tables over every successful timed build, plus the
  # peak memory and CPU time of the same builds, which Benchee cannot see
  def report(cfg) do
    records =
      cfg["out"]
      |> Path.join("*.json")
      |> Path.wildcard()
      |> Enum.reject(&String.contains?(&1, ".failed_"))
      |> Enum.map(&(&1 |> File.read!() |> JSON.decode!()))
      |> Enum.filter(&(&1["exit"] == 0 and &1["round"] >= 1 and &1["partitions"] > 1))

    projects = Map.new(cfg["projects"], &{&1["name"], &1})
    inputs = for project <- cfg["projects"], n <- cfg["partitions"], do: {input_name(project, n), %{}}
    jobs = Enum.map(cfg["jobs"], &hd/1) ++ List.wrap(get_in(cfg, ["control", "name"]))

    samples =
      Enum.group_by(records, &{&1["job"], input_name(projects[&1["project"]], &1["partitions"])}, & &1["benchee_ns"])

    suite =
      [inputs: inputs, warmup: 0, time: 1, memory_time: 0, formatters: [Benchee.Formatters.Console],
       print: [benchmarking: false, configuration: false]]
      |> Benchee.init()
      |> Benchee.system()

    # The builds ran on the pinned cores, not on the cores this process sees
    suite = put_in(suite.system.num_cores, length(cores(cfg)))
    s = suite.system

    # Benchee prints this header when it collects, which the report does not do
    IO.puts("""
    Operating System: #{s.os}
    CPU Information: #{s.cpu_speed}
    Number of Available Cores: #{s.num_cores} (every build pinned to CPUs #{cfg["cores"]})
    Available memory: #{s.available_memory}
    Elixir #{s.elixir}
    Erlang #{s.erlang}
    JIT enabled: #{s.jit_enabled?}
    """)
    suite = Enum.reduce(jobs, suite, &Benchee.benchmark(&2, &1, fn _ -> :ok end))

    scenarios =
      Enum.flat_map(suite.scenarios, fn scenario ->
        case Map.get(samples, {scenario.job_name, scenario.input_name}) do
          nil -> []
          data -> [put_in(scenario.run_time_data.samples, data)]
        end
      end)

    %{suite | scenarios: scenarios}
    |> Benchee.statistics()
    |> Benchee.relative_statistics()
    |> Benchee.Formatter.output()

    IO.puts("\nPeak memory and CPU time of the whole build (all partitions), medians:\n")
    IO.puts(String.pad_trailing("input / job", 44) <> String.pad_leading("peak memory", 12) <>
              String.pad_leading("CPU", 10) <> String.pad_leading("builds", 8) <> String.pad_leading("throttled", 11))
    IO.puts("(throttled: builds during which a core of #{cfg["cores"]} was throttled)\n")

    for {name, _} <- inputs, job <- jobs do
      rows = Enum.filter(records, &(&1["job"] == job and input_name(projects[&1["project"]], &1["partitions"]) == name))

      if rows != [] do
        # Only per-core throttling: the package counter also counts zero-length events
        throttled = Enum.count(rows, &(Map.get(&1["throttle"], "core", 0) > 0))

        IO.puts(
          String.pad_trailing("#{name} / #{job}", 44) <>
            String.pad_leading("#{round(median(Enum.map(rows, & &1["memory_peak_bytes"])) / 1.0e6)} MB", 12) <>
            String.pad_leading("#{Float.round(median(Enum.map(rows, & &1["cpu_s"])), 1)} s", 10) <>
            String.pad_leading("#{length(rows)}", 8) <> String.pad_leading("#{throttled}", 11)
        )
      end
    end
  end

  defp median(values) do
    sorted = Enum.sort(values)
    mid = div(length(sorted), 2)
    if rem(length(sorted), 2) == 1, do: Enum.at(sorted, mid), else: (Enum.at(sorted, mid - 1) + Enum.at(sorted, mid)) / 2
  end
end

case System.argv() do
  [config] -> config |> Bench.config() |> tap(&Bench.run_all/1) |> Bench.report()
  [config, "report"] -> config |> Bench.config() |> Bench.report()
end
Benchee output
Operating System: Linux
CPU Information: Intel(R) Core(TM) Ultra 9 285HX
Number of Available Cores: 16 (every build pinned to CPUs 8-23)
Available memory: 48 GB
Elixir 1.21.0-dev
Erlang 29.1.2
JIT enabled: true


##### With input Plausible, 2 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0135       1.23 min     ±1.08%       1.23 min       1.25 min
main        0.0129       1.29 min     ±2.17%       1.30 min       1.31 min

Comparison:
HEAD        0.0135
main        0.0129 - 1.05x slower +0.0589 min

##### With input Plausible, 4 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0222        45.04 s     ±2.52%        45.46 s        45.75 s
main        0.0203        49.33 s     ±5.48%        49.22 s        52.33 s

Comparison:
HEAD        0.0222
main        0.0203 - 1.10x slower +4.29 s

##### With input Plausible, 6 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0237        42.14 s     ±4.47%        42.02 s        44.50 s
main        0.0211        47.37 s     ±4.88%        48.52 s        49.10 s

Comparison:
HEAD        0.0237
main        0.0211 - 1.12x slower +5.23 s

##### With input Plausible, 8 partitions #####
Name                  ips        average  deviation         median         99th %
HEAD               0.0232        43.10 s     ±2.56%        43.10 s        44.52 s
main               0.0217        46.13 s     ±6.80%        47.70 s        48.85 s
main, again        0.0211        47.39 s     ±6.06%        48.17 s        51.10 s

Comparison:
HEAD               0.0232
main               0.0217 - 1.07x slower +3.03 s
main, again        0.0211 - 1.10x slower +4.30 s

##### With input Plausible, 12 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0218        45.89 s     ±3.06%        46.13 s        48.54 s
main        0.0211        47.46 s     ±5.44%        48.89 s        49.92 s

Comparison:
HEAD        0.0218
main        0.0211 - 1.03x slower +1.57 s

##### With input hexpm, 2 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0398        25.15 s     ±0.50%        25.10 s        25.46 s
main        0.0397        25.21 s     ±0.50%        25.17 s        25.52 s

Comparison:
HEAD        0.0398
main        0.0397 - 1.00x slower +0.0591 s

##### With input hexpm, 4 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0617        16.20 s     ±2.98%        16.01 s        17.26 s
main        0.0576        17.35 s     ±3.64%        17.10 s        18.86 s

Comparison:
HEAD        0.0617
main        0.0576 - 1.07x slower +1.15 s

##### With input hexpm, 6 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0711        14.07 s     ±4.40%        13.88 s        15.77 s
main        0.0636        15.73 s     ±2.70%        15.57 s        16.86 s

Comparison:
HEAD        0.0711
main        0.0636 - 1.12x slower +1.66 s

##### With input hexpm, 8 partitions #####
Name                  ips        average  deviation         median         99th %
HEAD               0.0682        14.66 s     ±3.22%        14.55 s        15.90 s
main               0.0641        15.59 s     ±2.48%        15.45 s        16.56 s
main, again        0.0629        15.90 s     ±4.22%        15.67 s        17.79 s

Comparison:
HEAD               0.0682
main               0.0641 - 1.06x slower +0.93 s
main, again        0.0629 - 1.08x slower +1.24 s

##### With input hexpm, 12 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0652        15.33 s     ±2.29%        15.25 s        16.06 s
main        0.0628        15.93 s     ±1.52%        15.87 s        16.49 s

Comparison:
HEAD        0.0652
main        0.0628 - 1.04x slower +0.60 s

##### With input Livebook, 2 partitions #####
Name           ips        average  deviation         median         99th %
main        0.0473        21.14 s     ±0.65%        21.10 s        21.37 s
HEAD        0.0471        21.22 s     ±0.71%        21.19 s        21.54 s

Comparison:
main        0.0473
HEAD        0.0471 - 1.00x slower +0.0748 s

##### With input Livebook, 4 partitions #####
Name           ips        average  deviation         median         99th %
main        0.0697        14.34 s     ±0.90%        14.31 s        14.60 s
HEAD        0.0645        15.50 s     ±2.49%        15.38 s        16.55 s

Comparison:
main        0.0697
HEAD        0.0645 - 1.08x slower +1.16 s

##### With input Livebook, 6 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0708        14.11 s     ±0.59%        14.12 s        14.28 s
main        0.0695        14.40 s     ±0.82%        14.41 s        14.56 s

Comparison:
HEAD        0.0708
main        0.0695 - 1.02x slower +0.28 s

##### With input Livebook, 8 partitions #####
Name                  ips        average  deviation         median         99th %
main               0.0722        13.85 s     ±1.16%        13.87 s        14.11 s
main, again        0.0716        13.96 s     ±2.03%        13.91 s        14.70 s
HEAD               0.0701        14.27 s     ±1.50%        14.19 s        14.71 s

Comparison:
main               0.0722
main, again        0.0716 - 1.01x slower +0.116 s
HEAD               0.0701 - 1.03x slower +0.42 s

##### With input Livebook, 12 partitions #####
Name           ips        average  deviation         median         99th %
main        0.0715        13.98 s     ±0.66%        13.99 s        14.14 s
HEAD        0.0713        14.03 s     ±0.94%        14.04 s        14.21 s

Comparison:
main        0.0715
HEAD        0.0713 - 1.00x slower +0.0487 s

##### With input Tuist (server), 2 partitions #####
Name           ips        average  deviation         median         99th %
HEAD       0.00951       1.75 min     ±1.06%       1.75 min       1.78 min
main       0.00910       1.83 min     ±1.30%       1.83 min       1.86 min

Comparison:
HEAD       0.00951
main       0.00910 - 1.04x slower +0.0781 min

##### With input Tuist (server), 4 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0154       1.08 min     ±2.22%       1.09 min       1.11 min
main        0.0150       1.11 min     ±1.06%       1.12 min       1.13 min

Comparison:
HEAD        0.0154
main        0.0150 - 1.03x slower +0.0356 min

##### With input Tuist (server), 6 partitions #####
Name           ips        average  deviation         median         99th %
HEAD        0.0175        57.01 s     ±1.59%        57.30 s        58.05 s
main        0.0172        58.19 s     ±0.82%        58.36 s        58.83 s

Comparison:
HEAD        0.0175
main        0.0172 - 1.02x slower +1.18 s

##### With input Tuist (server), 8 partitions #####
Name                  ips        average  deviation         median         99th %
main               0.0179        55.92 s     ±1.14%        55.97 s        57.06 s
main, again        0.0177        56.52 s     ±2.11%        56.77 s        57.80 s
HEAD               0.0176        56.87 s     ±2.23%        57.21 s        58.24 s

Comparison:
main               0.0179
main, again        0.0177 - 1.01x slower +0.60 s
HEAD               0.0176 - 1.02x slower +0.95 s

##### With input Tuist (server), 12 partitions #####
Name           ips        average  deviation         median         99th %
main        0.0178        56.24 s     ±3.40%        56.44 s        58.76 s
HEAD        0.0174        57.35 s     ±1.71%        57.38 s        58.79 s

Comparison:
main        0.0178
HEAD        0.0174 - 1.02x slower +1.12 s

Peak memory and CPU time of the whole build (all partitions), medians:

input / job                                  peak memory       CPU  builds  throttled
(throttled: builds during which a core of 8-23 was throttled)

Plausible, 2 partitions / main                   1611 MB   378.1 s      10          0
Plausible, 2 partitions / HEAD                   1827 MB   372.3 s      10          0
Plausible, 4 partitions / main                   2336 MB   390.9 s      10          0
Plausible, 4 partitions / HEAD                   2435 MB   391.7 s      10          0
Plausible, 6 partitions / main                   2917 MB   409.0 s      10          0
Plausible, 6 partitions / HEAD                   2996 MB   413.3 s      10          0
Plausible, 8 partitions / main                   3530 MB   421.1 s      10          0
Plausible, 8 partitions / HEAD                   3430 MB   428.2 s      10          0
Plausible, 8 partitions / main, again            3497 MB   420.7 s      10          0
Plausible, 12 partitions / main                  4481 MB   435.5 s      10          0
Plausible, 12 partitions / HEAD                  4147 MB   439.7 s      10          0
hexpm, 2 partitions / main                       1206 MB   167.4 s      10          0
hexpm, 2 partitions / HEAD                       1215 MB   166.6 s      10          0
hexpm, 4 partitions / main                       1750 MB   173.8 s      10          0
hexpm, 4 partitions / HEAD                       1672 MB   175.1 s      10          0
hexpm, 6 partitions / main                       2259 MB   178.1 s      10          0
hexpm, 6 partitions / HEAD                       2317 MB   181.0 s      10          0
hexpm, 8 partitions / main                       2728 MB   181.6 s      10          0
hexpm, 8 partitions / HEAD                       2842 MB   184.1 s      10          0
hexpm, 8 partitions / main, again                2742 MB   181.2 s      10          0
hexpm, 12 partitions / main                      3618 MB   187.4 s      10          0
hexpm, 12 partitions / HEAD                      3624 MB   188.6 s      10          0
Livebook, 2 partitions / main                    1329 MB   115.2 s      10          0
Livebook, 2 partitions / HEAD                    1386 MB   115.5 s      10          0
Livebook, 4 partitions / main                    1854 MB   123.2 s      10          0
Livebook, 4 partitions / HEAD                    1991 MB   122.0 s      10          0
Livebook, 6 partitions / main                    2178 MB   126.0 s      10          0
Livebook, 6 partitions / HEAD                    2326 MB   127.5 s      10          0
Livebook, 8 partitions / main                    2571 MB   130.6 s      10          0
Livebook, 8 partitions / HEAD                    2608 MB   130.5 s      10          0
Livebook, 8 partitions / main, again             2570 MB   130.5 s      10          0
Livebook, 12 partitions / main                   3196 MB   135.2 s      10          0
Livebook, 12 partitions / HEAD                   3215 MB   135.4 s      10          0
Tuist (server), 2 partitions / main              2153 MB   569.0 s      10          0
Tuist (server), 2 partitions / HEAD              1892 MB   569.8 s      10          0
Tuist (server), 4 partitions / main              2944 MB   591.1 s      10          0
Tuist (server), 4 partitions / HEAD              3079 MB   594.5 s      10          0
Tuist (server), 6 partitions / main              3929 MB   618.1 s      10          0
Tuist (server), 6 partitions / HEAD              4050 MB   628.5 s      10          0
Tuist (server), 8 partitions / main              4563 MB   639.9 s      10          0
Tuist (server), 8 partitions / HEAD              4812 MB   648.4 s      10          0
Tuist (server), 8 partitions / main, again       4600 MB   642.1 s      10          0
Tuist (server), 12 partitions / main             5335 MB   655.4 s      10          0
Tuist (server), 12 partitions / HEAD             5911 MB   672.0 s      10          0

AI disclosure

I used Claude Code (Claude Opus 5.5) to analyze the scheduler, write the change and its test, and run the benchmarks. I reviewed and validated the code and the results myself.

Each free partition gets the first dependency whose children have
compiled. Sort the dependencies once, while the partitions boot, by the
source size of their longest chain of dependents, so the root of a long
chain does not wait behind small dependencies nothing depends on.

Signed-off-by: Pablo Margreff <pmargreff@gmail.com>
Assisted-by: Claude Code:claude-opus-5-5
@josevalim

Copy link
Copy Markdown
Member

Thank you @pmargreff! This is great work and the PRs upstream are excellent too.

Unfortunately, I am not very comfortable with the file size heuristic approach, I'd prefer something more reliable, like:

  1. Length of the dependency chain
  2. The number of dependents (i.e. compiling :telemetry early is likely to unblock a bunch of work next)
  3. A combination of the above

You said you already measured those but what are the numbers? If they are relatively close to the source ones (and an improvement over today), then I'd rather take those!

@pmargreff

pmargreff commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, José! That makes sense. I didn't keep the numbers from those earlier trials with the same statistical rigor, so I'm measuring all three properly now, on the same four projects with the same parameters. It takes a while, so I'll probably come back by tomorrow with the Livebooks updated to compare the approaches.

Early signs from a shorter run look good for [1] and [3]: both are close to the source size version and faster than main, followed by [2]. Once the benchmarks are finished it can be weighing the gain against the complexity.

Unfinished runs:

screenshot-2026-11-22_17-56-47-partition-order-by-workers

The hard problem with statistics is sampling. I am using a very specific sample of projects, which may not be representative of all projects. That said, what should it be optimized for? It seems that which of [1] and [3] performs better depends on the project. If that holds true, we go with [1], the simpler solution, or with [3], expecting it to pay off in complex scenarios that aren't in the sample?

@josevalim

Copy link
Copy Markdown
Member

Right, we only need something that is better than today. If we can't really distinguish those, then we pick whatever is simpler.

@pmargreff

pmargreff commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Here are the full results. I ran the three options and the size version on nine projects: the four from before (Plausible, hexpm, Livebook, Tuist) plus Blockscout, Sequin, Lightning, Bonfire and a fresh mix phx.new app. 10 rounds at 2, 4, 6, 8 and 12 partitions, the orders alternating every round, every build from a clean deps/ pinned to the same 16 cores.

Dependents on its own isn't in the table because I screened it out earlier: a shorter run (3 rounds at 4, 6 and 8 partitions on the first four projects) and it was behind chain length and chain length + dependents, so I left it out of the full run.

Result table
Build time vs main Size (this PR) Chain length Chain length + dependents
Plausible −8.4% −11.9% −6.7%
hexpm −5.8% −5.6% −5.6%
Livebook +2.1% +2.4% +2.0%
Tuist −2.3% +0.6% −4.5%
Blockscout −3.3% −11.8% −7.3%
Sequin +16.2% +11.1% +11.4%
Lightning −11.6% −8.6% −8.5%
Bonfire −12.2% −10.2% −10.0%
Phoenix app +2.0% +0.4% −0.8%
All nine −2.9% −4.0% −3.5%

Each cell is the median change per round against the main build that ran next to it, as a geometric mean over the five partition counts. Running main twice as a control gives medians within ±1%.

Result chart build-time
Result table with Dependents length strategy included
Shorter run, build time vs main Size Chain length Dependents Chain length + dependents
Plausible −9.3% −14.3% −3.7% −10.3%
hexpm −7.8% −8.0% −8.9% −7.9%
Livebook +3.6% +2.1% +1.8% +5.6%
Tuist −1.4% +0.3% +1.8% −4.2%
All four −3.9% −5.2% −2.3% −4.4%

So chain length and chain length + dependents are both better than today and about the same as size (−1.0% and −0.6% against it), and they don't have statistical difference. Chain length is ahead in Plausible and Blockscout (about 5% each), chain length + dependents in Tuist (about 4%).

Numerical comparison between your proposed strategies

difference

On the left, we have the comparison between the main. On the right chain length and chain length + dependents against each other.

The notebooks, data and scripts are in https://github.com/pmargreff/mix-deps-partition-benchmark, and the Livebooks compare all the orders and have the full data in case you want to take a closer look.

If that works for you, I'll open a new PR with chain length to replace this one. Seems like it's the simplest one that brings significant improvement.

@josevalim

Copy link
Copy Markdown
Member

Beautiful work, yes, please do send a PR for chain length!

@pmargreff

Copy link
Copy Markdown
Contributor Author

Close in favor of #16193

@pmargreff pmargreff closed this Nov 24, 2026
@pmargreff
pmargreff deleted the deps-partition-size-order branch November 24, 2026 07:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants