ExceptionWrapper#build_backtrace copies every resolver template cache on each exception, including routing errors (~13 MB per 404 on 8.1, ~7 MB on main)
Steps to reproduce
On 8.1, ActionDispatch::ExceptionWrapper#initialize calls build_backtrace (#58686 made it lazy on main, see below), which walks ActionView::PathRegistry.all_resolvers and calls resolver.built_templates on each of them, to map backtrace frames that fall inside a compiled template back to the template source:
FileSystemResolver#built_templates is @unbound_templates.values.flatten.flat_map(&:built_templates):
https://github.com/rails/rails/blob/v8.1.4/actionview/lib/action_view/template/resolver.rb#L126-L128
Concurrent::Map#values copies the whole map, and @unbound_templates holds one entry per looked-up template path, misses included — so every resolver searched before the one holding a template gets an entry for it. The cost therefore grows with templates × resolvers, and it is paid by every exception, twice per request with the production error pages (once by DebugExceptions, once by ShowExceptions). A routing error, whose backtrace can never go through a template, pays it too — which makes every 404 from a vulnerability scanner allocate megabytes.
The script below renders 5,000 templates once each (what a long-running process ends up doing, or what ActionView::Precompiler now does at boot on main), with 15 extra view paths standing in for engines, then measures one 404 with the production error pages.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails", "8.1.4"
end
require "action_controller/railtie"
require "objspace"
require "tmpdir"
# TEMPLATES: templates rendered once each, as a long-running process ends up doing (or as
# ActionView::Precompiler does at boot on main).
# RESOLVERS: view paths searched before the one holding the templates, as engines and gems add.
TEMPLATES = Integer(ENV.fetch("TEMPLATES", "5000"))
RESOLVERS = Integer(ENV.fetch("RESOLVERS", "15"))
ROOT = Dir.mktmpdir
view_paths = Array.new(RESOLVERS) { |i| File.join(ROOT, "engine_#{i}", "app", "views").tap { |p| FileUtils.mkdir_p(p) } }
app_views = File.join(ROOT, "app", "views")
FileUtils.mkdir_p(File.join(app_views, "pages"))
TEMPLATES.times { |i| File.write(File.join(app_views, "pages", "page_#{i}.html.erb"), "<p>page <%= #{i} %></p>\n") }
class TestApp < Rails::Application
config.root = ROOT
config.load_defaults 8.1
config.eager_load = false
config.enable_reloading = false
config.secret_key_base = "secret"
config.hosts.clear
config.logger = Logger.new(nil)
# Production error pages: no debug page, only ShowExceptions.
config.consider_all_requests_local = false
config.action_dispatch.show_exceptions = :all
routes.append { get "/pages/:id", to: "pages#show" }
end
class PagesController < ActionController::Base
def show
render "pages/page_#{params[:id]}"
end
end
PagesController.view_paths = view_paths + [app_views]
TestApp.initialize!
def request(path)
TestApp.call(Rack::MockRequest.env_for(path))
end
TEMPLATES.times { |i| request("/pages/#{i}") }
cached = ActionView::PathRegistry.all_resolvers.sum { |r| r.instance_variable_get(:@unbound_templates)&.size.to_i }
puts "Rails #{Rails.version}, #{ActionView::PathRegistry.all_resolvers.size} resolvers, #{cached} cached template lookups"
3.times { request("/wp-login.php") }
GC.start
GC.disable
ObjectSpace.trace_object_allocations { request("/wp-login.php") }
bytes = 0
ObjectSpace.each_object { |o| bytes += ObjectSpace.memsize_of(o) if ObjectSpace.allocation_sourcefile(o) }
GC.enable
puts "one 404: #{(bytes / 1_048_576.0).round(2)} MB allocated, status #{request('/wp-login.php').first}"
n = 100
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
n.times { request("/wp-login.php") }
puts "#{n} x 404: #{((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000 / n).round(2)} ms per request"Expected behavior
A 404 costs the same whatever the number of templates the process has compiled: the backtrace of an ActionController::RoutingError has no template frame to map.
Actual behavior
Ruby 4.0.7, Rails 8.1.4, 16 resolvers:
| Allocated by one 404 | Time per 404 | |
|---|---|---|
TEMPLATES=0 |
0.06 MB | 0.18 ms |
TEMPLATES=5000 |
13.33 MB | 27.65 ms |
TEMPLATES=5000, with the change below |
0.05 MB | 0.14 ms |
On our production application (about 81,000 cached lookups across 15 resolvers, templates precompiled at boot), measured on a staging container: 10.0 MB allocated and 16.9 ms per 404, of which 9.7 MB are allocated by built_templates (the Concurrent::Map#values copies and the arrays built from them). With the change below, 0.24 MB and 0.9 ms.
On main, #58686 builds the backtrace lazily, which removes the ShowExceptions half. But build_backtrace itself is unchanged, and DebugExceptions#log_error still reads wrapper.exception_trace whenever rescued responses are logged, which is the default. Replaying the script above on 8.1.4 with the change from #58686 copied in:
| Allocated by one 404 | Time per 404 | build_backtrace calls |
|
|---|---|---|---|
| 8.1.4 | 13.33 MB | 27.65 ms | 2 |
| #58686, default settings | 7.08 MB | 14.05 ms | 1 (DebugExceptions) |
#58686, log_rescued_responses = false |
0.03 MB | 0.09 ms | 0 |
So with the default settings every 404 still walks every resolver once. main also has ActionView::Precompiler, which fills these caches at boot, so a process pays that cost from its first exception.
Possible fix
A compiled template method is named by ActionView::Template#method_name, "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}" with - replaced by _, where identifier_method_name only keeps [a-z_]:
https://github.com/rails/rails/blob/v8.1.4/actionview/lib/action_view/template.rb#L402-L408
So the resolvers only need to be walked when at least one frame has that shape; otherwise no frame can be mapped, and the original method returns the locations unchanged anyway. This is what we run as a patch:
TEMPLATE_METHOD_NAME = /\A_[a-z_]*__\d+_\d+\z/
def build_backtrace
locations = @exception.backtrace_locations || []
return super if locations.any? { |location| TEMPLATE_METHOD_NAME.match?(location.base_label) }
locations.dup
endThe pattern accepts negative hashes (___ before the digits) and does not match ordinary underscore-prefixed methods such as _run_process_action_callbacks; a false positive only falls back to the current behavior. A sturdier fix in Rails itself could avoid depending on the method name format altogether, for instance by keeping a registry from method name to template filled when a template is compiled, instead of rebuilding it from every resolver on each exception. Happy to open a PR for whichever approach you prefer.
System configuration
Rails version: 8.1.4 (build_backtrace and built_templates identical on main)
Ruby version: 4.0.7
Source: rails/rails