Skip to content

Close and delete multipart upload tempfiles once the response is closed - #3086

Merged
ericproulx merged 1 commit into
masterfrom
fix/tempfile-reaper-around-router
Nov 25, 2026
Merged

ericproulx merged 1 commit into
masterfrom
fix/tempfile-reaper-around-router

Conversation

@ericproulx

Copy link
Copy Markdown
Contributor

Summary

Rack's multipart parser creates a tempfile for each uploaded file and leaves it to whatever reaps it. Rails runs Rack::TempfileReaper, but a Grape API served on its own did not, so every upload stayed on disk until garbage collection or the process exited (#2487). Grape now closes and deletes those tempfiles once the response is closed, or as soon as an exception escapes the API.

This picks up #3041 by @anyingiit (credited as co-author) and addresses the review there.

  • Around the router, not each endpoint. The reaper wraps the router in API::Instance#initialize, next to Rack::Head (Wrap the router in Rack::Head instead of each endpoint's stack #3042). In an endpoint's stack it would fire when a route cascades and the router closes that route's body, before the next route reads the same upload (IOError: closed stream). It would also miss a Rack app mounted with mount, which goes through no endpoint's stack. Both cases have a spec, and both specs fail with the reaper in build_stack.
  • On by default, as dblock concluded on Add Rack::TempfileReaper to the endpoint middleware stack #3041. A Grape API inside Rails gets a second reaper, and closing a closed tempfile does nothing. A spec runs the API under an outer Rack::TempfileReaper.
  • An unrescued exception also reaps the files. On Add Rack::TempfileReaper to the endpoint middleware stack #3041 I noted Rack 2.2 didn't do this; Grape now requires Rack 3.1, where Rack::TempfileReaper does it too.

Why not Rack::TempfileReaper itself

Wrapping the router with Rack's middleware made a bare GET 13–18% slower (5.0 → 5.8 µs in three A/B pairs) and added 5 allocations per request (11 → 16). It allocates the rack.tempfiles Array and a BodyProxy for every request, and the BodyProxy forwards each through method_missing. Most requests upload nothing.

Rack's multipart parser records the tempfiles it creates in env['rack.tempfiles'] (Rack 3.1 and 3.2 alike). So Grape::Middleware::TempfileReaper looks there once the app has answered, and wraps the body only when the request uploaded something. A request without an upload allocates 11 objects, as on master, and the three A/B pairs came out +2.5%, −0.3% and +1.1%.

It also returns a new triplet instead of writing into the one it got: a mounted Rack app may answer a frozen one, which Rack::TempfileReaper would have raised FrozenError on. A spec covers that too.

The one thing Rack's reaper covers and this one doesn't: a tempfile created after the response is returned, by a body that parses the upload while it streams. Such a file is left to garbage collection, as it was before this change.

Tests

spec/grape/integration/rack_spec.rb, describe 'multipart tempfiles' (#3041's two examples plus four), checking that the tempfile is gone after:

  • a 201;
  • an error! 422;
  • an exception that escapes the API;
  • a route that cascades to another that reads the same upload;
  • a mounted Rack app that answers a frozen triplet;
  • an outer Rack::TempfileReaper, as in Rails.

The first five fail on master. All pass on Rack 3.2.8 and 3.1.23, and bundle exec rake passes.

UPGRADING has an entry, since code that keeps an uploaded tempfile after the response now has to copy it first. The README says so too.

Replaces #3041. Fixes #2487.

🤖 Generated with Claude Code

@ericproulx
ericproulx force-pushed the fix/tempfile-reaper-around-router branch from 98ea28d to bbd182e Compare November 20, 2026 22:36
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Danger Report

No issues found.

View run

@ericproulx
ericproulx requested a review from dblock November 21, 2026 09:59
@ericproulx
ericproulx force-pushed the fix/tempfile-reaper-around-router branch from bbd182e to 42ba85a Compare November 21, 2026 10:02
Rack's multipart parser leaves its tempfiles to whatever reaps them, and
outside Rails nothing did, so a standalone Grape API kept every upload on
disk until garbage collection or exit (#2487). A reaper now wraps the
router, next to Rack::Head. There it also covers a mounted Rack app. Unlike
one in each endpoint's stack, it doesn't fire when a route cascades and the
router closes that route's body before the next route reads the same upload.

Rack::TempfileReaper allocates an Array and a BodyProxy for every request,
which cost 13-18% of a bare GET. Grape's reaper instead reads rack.tempfiles
once the app has answered, and wraps the body only when the request
uploaded something.

Replaces #3041. Fixes #2487.

Co-Authored-By: anyingiit <49945850+anyingiit@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ericproulx
ericproulx force-pushed the fix/tempfile-reaper-around-router branch from 42ba85a to b5b20a4 Compare November 25, 2026 09:58
@github-actions

Copy link
Copy Markdown

🔻 Duel: 2 benchmarks failed

Compared b5b20a4 (merged with master) with 4e2c657 (where HEAD left origin/master).

Benchmark Failure
compile: an API of 20 routes allocations 6840 → 6841
compile: an API that mounts others allocations 2500 → 2501
Details: 39 benchmarks in 209s, 9 unsettled

compile: an API of 20 routes: worse allocations in every measurement

allocations: 6840 → 6841 an iteration

compile: an API that mounts others: worse allocations in every measurement

allocations: 2500 → 2501 an iteration
Benchmark Verdict Timings (ratio [interval]) Counts an iteration
compile: an API of 20 routes regressed cpu 1.003 [0.986, 1.015] allocations 6840 → 6841
compile: an API that mounts others regressed cpu 1.004 [0.991, 1.019] allocations 2500 → 2501
callbacks: before, validation, after and finally callbacks, with helpers unsettled cpu 1.003 [0.972, 1.033] unsettled
mount: GET a route of a mounted API unsettled cpu 1.016 [1.001, 1.119] unsettled
errors: error! with a message unsettled cpu 1.017 [1.002, 1.031] unsettled
errors: rescue_from a class with a handler unsettled cpu 1.011 [0.982, 1.167] unsettled
format: render a small JSON object unsettled cpu 1.011 [0.997, 1.029] unsettled
params: validate a JSON body with a custom validator unsettled cpu 1.010 [0.997, 1.030] unsettled
params: validate a form body unsettled cpu 1.008 [0.996, 1.021] unsettled
routing: GET a static route unsettled cpu 1.009 [0.850, 1.033] unsettled
routing: 404 among 200 routes unsettled cpu 1.022 [0.999, 1.036] unsettled
callbacks: a before callback that halts with error! same cpu 1.002 [0.950, 1.014]
declared: all declared params, with missing ones as nil same cpu 0.984 [0.974, 0.999]
declared: only the params sent same cpu 0.980 [0.963, 0.997]
declared: with string keys same cpu 0.993 [0.973, 1.019]
errors: error! with a hash and headers same cpu 1.001 [0.987, 1.018]
errors: rescue_from :all with a handler same cpu 1.001 [0.985, 1.019]
errors: rescue_from :all with the default handler same cpu 1.002 [0.987, 1.016]
format: render a JSON array of 50 hashes same cpu 1.001 [0.992, 1.012]
format: present 50 objects with a representer same cpu 0.994 [0.976, 1.006]
format: present one object with a representer same cpu 0.999 [0.971, 1.010]
format: negotiate the format from a browser Accept header same cpu 1.001 [0.941, 1.015]
format: take the format from the extension same cpu 1.005 [0.995, 1.017]
params: coerce a path param to an Integer same cpu 0.994 [0.977, 1.008]
params: coerce and validate a query string of 10 params same cpu 0.991 [0.943, 1.015]
params: fill in defaults for missing optional params same cpu 1.001 [0.988, 1.014]
params: validate a nested JSON body of 20 items same cpu 1.000 [0.986, 1.020]
params: reject invalid params with 400 same cpu 0.994 [0.902, 1.018]
routing: GET a route with a path param same cpu 1.000 [0.968, 1.016]
routing: GET the last static route of 200 same cpu 1.005 [0.979, 1.020]
routing: GET the last param route of 200 same cpu 0.993 [0.841, 1.006]
routing: 405 for a method a path does not answer same cpu 1.005 [0.994, 1.019]
routing: GET three levels of nested namespaces with requirements same cpu 1.007 [0.987, 1.018]
routing: GET a wildcard route same cpu 1.006 [0.998, 1.020]
versioning: a version in the path same cpu 1.001 [0.988, 1.016]
versioning: a vendor media type in the Accept header same cpu 1.004 [0.989, 1.018]
versioning: an Accept header cascading past a newer version same cpu 1.004 [0.995, 1.014]
versioning: the Accept-Version header same cpu 0.997 [0.977, 1.013]
versioning: a version param same cpu 0.993 [0.978, 1.006]

An unsettled timing was too close to the limit to settle. It doesn't fail the run, but one that's unsettled in run after run is noisy.

Across the board:

  • cpu 1.002 [0.999, 1.007] unsettled (limit 1.0050, 39 benchmarks)

A timing is slower when a 99.0% confidence interval for its ratio, the candidate's to the baseline's, is above 1.02. How Duel decides

@ericproulx ericproulx added the duel: accept Accept a performance regression that Duel flags label Nov 25, 2026
@ericproulx
ericproulx merged commit 96c4b89 into master Nov 25, 2026
29 of 30 checks passed
@ericproulx
ericproulx deleted the fix/tempfile-reaper-around-router branch November 25, 2026 10:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

duel: accept Accept a performance regression that Duel flags

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Include Rack::TempFileReaper in Grape ?

2 participants