Skip to content

feat(auto-build): add vite:auto_build task to build stale assets up front - #59

Merged
skryukov merged 9 commits into
skryukov:mainfrom
brodienguyen:auto-build-rake-task
Nov 12, 2026
Merged

skryukov merged 9 commits into
skryukov:mainfrom
brodienguyen:auto-build-rake-task

Conversation

@brodienguyen

@brodienguyen brodienguyen commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

After #58, parallel test workers share a single auto build instead of each running their own. That fixed the clashes, but the build still happens in the middle of the test run: whichever worker gets to a page first starts it, the others wait on the lock, and the build eats CPU the remaining workers would have used. For us that's about 20 seconds of build time landing on whatever spec files happened to run first. It skews the per-file timings our runner uses to split work, and it keeps tripping a spec runtime check we have.

The simple answer is to build once before the workers start. rake vite:build doesn't quite fit that job, though. It always does a full build, even when nothing has changed, and it doesn't know about #58's lock or remembered failures. What I wanted was "whatever auto build would do on the first request, but do it now", so that's what this adds:

RAILS_ENV=test bin/rails vite:auto_build && bundle exec parallel_rspec

If the assets are fresh, it does nothing and returns straight away. If they're stale, it builds them, or waits if another process is already building. If the build fails, it raises RailsVite::BuildError, so the command exits non-zero and the test run never starts. It follows the same rules as the middleware, so it also does nothing when auto build is off or a dev server is running.

The same thing is available from Ruby as RailsVite::AutoBuild.build_if_stale, for scripts that start their own workers. Under the hood, the middleware's call now goes through that same method, and the "is auto build on?" check lives in one place (AutoBuild.enabled?), shared by the engine and the task. Nothing changes for existing apps.

A couple of things I left as they are, but I'm happy to change either:

  • test:prepare still runs vite:build. Switching it to vite:auto_build would skip unnecessary rebuilds for bin/rails test, but it changes current behaviour, so I didn't want to slip it in here.
  • The task is quiet when there's nothing to do, the same as auto build.

Repro

The script below fakes a parallel run: 4 forked workers, each timing its first request through the middleware, the way a test runner times its first spec file. It runs once with the build left to the first request and once with vite:auto_build before the workers start. Then it runs the task on fresh assets and with a failing build. vite build is replaced by a shell script that sleeps for 1 second, so you don't need Node.

ruby repro.rb /path/to/rails_vite
repro.rb
# frozen_string_literal: true

# Usage: ruby repro.rb /path/to/rails_vite
#
# Stands in for a parallel test run with stale assets: a few forked workers
# each time their first request through AutoBuild, the way a runner records
# per-file runtimes. It runs once with the build left to the first request,
# and once with `rake vite:auto_build` before forking. Then it runs the task
# on fresh assets and on a failing build. `vite build` is swapped for a tiny
# shell script that logs, sleeps, and then either writes the manifest or fails.

require "fileutils"
require "logger"
require "pathname"
require "rake"
require "tmpdir"

gem_path = ARGV.fetch(0) { abort "usage: ruby repro.rb /path/to/rails_vite" }
$LOAD_PATH.unshift(File.join(gem_path, "lib"))
require "rails"
require "rails_vite"

WORKERS = 4
BUILD_SECONDS = 1.0

Rake::Task.define_task(:environment) # the app is already "loaded" below
load File.join(gem_path, "lib/tasks/rails_vite/build.rake")

def with_app(build_succeeds: true, manifest_fresh: false)
  Dir.mktmpdir do |dir|
    root = Pathname(dir)
    FileUtils.mkdir_p(root.join("app/javascript"))
    File.write(root.join("app/javascript/app.js"), "")
    log = root.join("builds.log")
    manifest = root.join("public/vite/manifest.json")
    if manifest_fresh
      FileUtils.mkdir_p(manifest.dirname)
      File.write(manifest, "{}")
      FileUtils.touch(manifest, mtime: Time.now + 10)
    end

    fake_vite = root.join("fake-vite")
    File.write(fake_vite, <<~SH)
      #!/bin/sh
      echo "build $$" >> #{log}
      sleep #{BUILD_SECONDS}
      #{build_succeeds ? "mkdir -p #{manifest.dirname} && echo '{}' > #{manifest}" : "exit 1"}
    SH
    File.chmod(0o755, fake_vite)

    Rails.singleton_class.define_method(:root) { root }
    Rails.logger = Logger.new(File::NULL)
    RailsVite::Tasks.singleton_class.define_method(:build_command) { fake_vite.to_s }
    RailsVite::Tasks.singleton_class.define_method(:build_env) { {} } # no Rails app to read
    RailsVite.reset!
    RailsVite.config.manifest_path = manifest

    yield -> { File.exist?(log) ? File.readlines(log).size : 0 }
  end
end

def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)

# Runs the task in a child process, like `bin/rails vite:auto_build` would,
# and returns its exit status and run time.
def run_task
  return [nil, 0] unless Rake::Task.task_defined?("vite:auto_build")

  started = now
  pid = fork do
    Rake::Task["vite:auto_build"].invoke
  rescue RailsVite::BuildError => e
    warn "  vite:auto_build: #{e.class}"
    exit 1
  end
  Process.wait(pid)
  [$?.exitstatus, now - started]
end

# Each worker times its first request, as a runner times its first spec file.
def run_workers
  readers = WORKERS.times.map do
    reader, writer = IO.pipe
    fork do
      reader.close
      middleware = RailsVite::AutoBuild.new(->(_env) { [200, {}, []] }, RailsVite.config)
      started = now
      middleware.call({})
      writer.puts(now - started)
    end
    writer.close
    reader
  end
  Process.waitall
  readers.map { it.read.to_f }
end

def report(name, builds:, task: nil, workers: nil)
  status, seconds = task
  parts = ["builds: #{builds}"]
  parts << (status.nil? ? "vite:auto_build: not defined" : format("vite:auto_build: exit %d in %.1fs", status, seconds)) if task
  parts << format("slowest worker's first request: %.1fs", workers.max) if workers
  puts format("%-34s %s", name, parts.join("   "))
end

puts "rails_vite at #{gem_path} (#{WORKERS} workers, #{BUILD_SECONDS}s build)"

with_app do |builds|
  workers = run_workers
  report("build on first request", builds: builds.call, workers: workers)
end

with_app do |builds|
  task = run_task
  workers = run_workers
  report("vite:auto_build, then workers", builds: builds.call, task: task, workers: workers)
end

with_app(manifest_fresh: true) do |builds|
  task = run_task
  report("vite:auto_build, fresh assets", builds: builds.call, task: task)
end

with_app(build_succeeds: false) do |builds|
  task = run_task
  report("vite:auto_build, build fails", builds: builds.call, task: task)
end

Results against #58 and against this branch:

Scenario #58 This branch
Build on the first request 1 build; slowest worker's first request 1.6 s same
vite:auto_build, then start workers no such task 1 build, done in the task; slowest worker's first request 0.0 s
vite:auto_build with fresh assets no such task no build, exits 0 immediately
vite:auto_build with a failing build no such task 1 build, then BuildError, exits 1

The build still takes the same time. It just happens before the workers start, so it isn't charged to any spec.

Also: a manifest that disappears during another process's build

Running the task alongside parallel workers turned up a race in stale?, so this PR also carries one small fix for it (1fe3c46). stale? called File.exist? and then File.mtime outside the build lock. Vite empties the build directory before it writes, so when another process was rebuilding, the manifest could vanish between those two calls. The request then raised Errno::ENOENT instead of waiting for that build. We hit it in CI as a flaky request spec.

Now stale? reads the mtime once and treats a missing manifest as stale. Stale takes the build lock, which waits for the other build and then checks again, so the request serves the fresh build. The new test test_waits_when_the_manifest_vanishes_under_another_process_build raises Errno::ENOENT without the fix and passes with it:

bundle exec ruby -Ilib -Itest test/auto_build_test.rb -n test_waits_when_the_manifest_vanishes_under_another_process_build

One stat call instead of two also makes the per-request check on fresh assets a little cheaper:

build_if_stale on fresh assets, 200,000 calls, median of 11 Before After
Per call 4.2 µs 2.4 µs

I'm happy to split this into its own PR if you'd rather review it separately.

AutoBuild's mutex only covers one process, so parallel test workers, or a
server beside a test run, each find stale assets and run `vite build` into
the same directory at once. Vite empties that directory before writing, so
one process can read a missing or half-written manifest while another
builds. The README worked around this by telling parallel runners to turn
auto build off.

Builds now hold an exclusive lock on tmp/rails-vite-build-<build_dir>.lock
(outside the directory Vite empties). A process that waited checks
freshness again and reuses the build it waited for.
A failed build leaves the manifest untouched, so the assets stay stale and
every following request runs the whole build again, only to log "build
failed" and serve the previous assets. With several processes, each one
repeats it.

The lock file now records the failed sources' timestamp, so no process
rebuilds them until a source changes, and the request raises
RailsVite::BuildError, as a missing manifest or entry already does, instead
of rendering with stale assets. `rake vite:build` still builds them, and a
fresh manifest ends the failure.
…tions

Emit an event around each auto build, including the time spent waiting
for another process's build, so apps can log or subtract build time; for
example, a parallel test runner can keep the build out of the runtime it
records for the spec file that happened to trigger it.
A process that finds a recorded failure raises BuildError without running
Vite, so pointing at the errors in the output above was wrong. It now says
the build failed earlier and how to see its errors.
…uest

AutoBuild.build_if_stale runs the middleware's staleness check, lock and
failure record without a request, under the same conditions the engine uses
to add the middleware. AutoBuild.enabled? now holds those conditions for
both.
…ront

A parallel test runner can build once before it forks its workers, instead
of the first worker's request building while the others wait or compete for
CPU. The task does nothing when assets are fresh, the dev server runs or auto
build is off, and fails with BuildError when the build fails.
stale? checked File.exist? and then read File.mtime outside the build lock. Vite empties the build directory first, so a manifest another process was rebuilding could vanish between the two calls, and the request raised Errno::ENOENT instead of waiting for that build. Read the mtime once and treat a missing manifest as stale; the build lock then waits for the other build and checks again. One stat call instead of two also makes the per-request check faster.
@brodienguyen
brodienguyen marked this pull request as ready for review November 7, 2026 13:10
@skryukov
skryukov merged commit 93d18b4 into skryukov:main Nov 12, 2026
7 checks passed
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.

2 participants