Skip to content

Fix pipeline depth guard - #118

Merged
olivervogel merged 3 commits into
Intervention:developfrom
nlemoine:fix/pipeline-depth-guard
Aug 21, 2026
Merged

olivervogel merged 3 commits into
Intervention:developfrom
nlemoine:fix/pipeline-depth-guard

Conversation

@nlemoine

Copy link
Copy Markdown
Contributor

Deep chains of lazy operations kill the PHP process

A long enough chain of operations on a vips-backed image takes the whole process down with SIGBUS (exit 138) or SIGSEGV. No exception, no PHP error, nothing on stderr. It's not intermittent, and it doesn't depend on canvas size. It tracks the number of chained nodes.

Repro, no Intervention involved:

$base = Image::black(64, 64)->add(128)->cast('uchar');
$base = $base->bandjoin([$base, $base])->copy(['interpretation' => 'srgb'])->copyMemory();
$tile = Image::black(8, 8)->add(255)->cast('uchar');
$tile = $tile->bandjoin([$tile, $tile, $tile])->copy(['interpretation' => 'srgb'])->copyMemory();

$out = $base;
for ($i = 0; $i < 400; $i++) {
    $out = $out->composite2($tile, BlendMode::OVER, ['x' => $i % 56, 'y' => ($i * 3) % 56]);
}
$out->writeToBuffer('.png');   // dies here

Where it dies, bisected with that exact script:

platform libvips last depth that works
macOS arm64 (Homebrew) 8.18.5 198
Alpine 3.22, musl 8.16.1 1843
Debian, glibc (this repo's Dockerfile) 8.18.1 2009

Under lldb it faults on a thread named libvips worker, EXC_BAD_ACCESS on what looks like the stack guard page. The backtrace is one cycle of about 8 frames, repeated once per chained node:

vips_composite_base_gen -> vips_region_prepare_to -> vips_region_prepare_to_generate
  -> vips_region_generate -> vips_copy_gen -> vips_region_prepare -> vips_region_fill
  -> vips_region_generate -> vips_composite_base_gen -> ...

I think libvips recurses once per node when it evaluates, and a worker thread's stack is fixed when the thread is created, so the ceiling ends up being the platform's default thread stack size. ulimit -s doesn't move the macOS number, which would fit (worker threads get the pthread default, not RLIMIT_STACK). I can't vouch for libvips internals past what the backtrace shows, but the numbers move the way you'd expect if that's what's going on.

Which makes it a libvips property, not a bug in this driver. The driver can't stop a caller from chaining, but it can bound the depth. That's the third commit. The first two are separate bugs I ran into on the way, both reachable on main today.

fix: read a decoded insert element only once. A watermark decoded from a file or a buffer opens a sequential libvips source, readable once and in order. InsertModifier folds it into the target pipeline by reference, so it gets read again on every evaluation. Two ordinary things do that: inserting the same decoded image more than once, and encoding the result twice. Both fail on main with pngload: out of order read. The animated branch already worked around this per call, with a comment naming the same cause. This hoists it onto the element's own core, so it happens once instead of once per call.

perf: composite the text stroke in a single operation. A stroke of width w is (2w + 1)^2 stamps, and each one was chained as its own composite. On macOS a stroke of 6 or more kills the process. Width 10, the cap Intervention allows, is 441 stamps. libvips composites any number of overlays in one call, which is a single node whatever the width.

fix: render the pipeline to memory past 32 chained operations. Core counts the operations chained through setNative() and calls copyMemory() every 32.

What it costs:

case before after
cover(800,300) + jpeg85 (bench/) 12.5 ms 12.6 ms
decode 2000x1500 + one 50x50 PNG insert + jpeg85 14.6 ms 15.1 ms
text stroke width 5, 400x120 16.9 ms 8.8 ms
text stroke width 6 to 10 SIGBUS renders
tiled mark on 1200x900, 20px (depth 105) 252 ms 138 ms
tiled mark on 1200x900, 10px (depth 210) SIGBUS 185 ms
tiled mark on 1200x900, 5px (depth 420) SIGBUS 305 ms

Output is identical wherever both sides complete, except the stroke. Compositing one overlay at a time rounds to uchar at every stamp, one call accumulates in premultiplied float and rounds once. Over the widths that used to work, the difference is at most 2/255 and only on antialiased edges: 64 to 109 pixels out of 16000, mean 0.003.

Caveats:

The counter counts calls, not libvips nodes. A modifier that chains several nodes per call burns through the budget faster, so 32 is a bound rather than a measurement. TextModifier was the extreme case at 225 nodes for one call, which is why it's fixed here instead of left to the guard.

Past 32 operations a rendered image is a whole image, so a crop at the end of a long chain no longer narrows what the chain computes. Below 32 nothing changes, and 32 covers every normal use I can think of.

setNative() can throw now, since the render can fail. CoreInterface::setNative() declares no exceptions, so PHPStan only caught one site by itself. I found the rest by adding @throws to the interface in a scratch tree and re-running, then declared them here. 19 sites, docblocks only. If you'd rather the interface carried it, tell me and I'll drop that part.

Testing: docker compose run --rm tests is green, 394 tests, and analysis and standards too. I reverted each fix in turn to check its test actually fails. One exception, the 1000-insert chain test only crashes where the stack is small, so on Linux CI it asserts that rendering mid-chain leaves the result alone and nothing else. Reaching the glibc ceiling from a test isn't portable, and it would kill the runner instead of reporting a failure.

Unrelated, but so you know it's not me: on macOS FontProcessorTest::testBoxSizeTtf fails before and after these commits, 241 against an expected 155. Probably a font stack difference.

A watermark decoded from a file or a buffer opens a libvips sequential
source, which may only be read once, in order. InsertModifier folds that
element into the target's pipeline by reference, so it is read again
every time the pipeline is evaluated. Two ordinary things do that:

    $image->insert($decoded);
    $image->encode(...);
    $image->encode(...);   // pngload: out of order read

    $image->insert($decoded);
    $image->insert($decoded);
    ...                    // same, once the reads interleave

The animated branch already worked around this per call, with a comment
naming the same cause. Hoisting the materialisation onto the element's
own core covers the single-frame path too, and does it once rather than
once per call: decoded images are shared by reference, so a watermark
inserted many times pays for one read.

It costs one render of the element when there is only one insert, which
is the common case. Measured on a 2000x1500 base with a 50x50 PNG mark,
decode + insert + jpeg85 goes from 14.6 ms to 15.1 ms, output identical.
The cost is the element's size, not the base's.
A stroke of width w is (2w + 1)^2 stamps, and each one was chained onto
the frame as its own composite. libvips recurses once per pipeline node
when it evaluates, so the chain overran the worker thread stack: on
macOS a stroke of 6 or more killed the process with SIGBUS, no exception
and nothing on stderr. Width 10, which is the cap Intervention allows,
is 441 stamps.

libvips composites any number of overlays in one operation, which is a
single node whatever the width. Measured on 400x120 with an 11 character
string, best-of-10: width 1 goes 2.9 to 2.3 ms, width 3 goes 7.7 to
4.4 ms, width 5 goes 16.9 to 8.8 ms, and widths 6 to 10 go from killing
the process to rendering.

Compositing one overlay at a time rounds to uchar at every stamp, where
one operation accumulates in premultiplied float and rounds once, so the
output moves very slightly. Over the stroke widths that used to work the
difference is at most 2/255, on the antialiased edges only: 64 to 109
pixels of 16000, mean 0.003.
libvips evaluates a pipeline by recursing once per node, on a worker
thread whose stack is fixed when the thread is created. A long enough
chain overruns that stack and takes the PHP process down with SIGBUS or
SIGSEGV, with no catchable error and nothing on stderr.

The ceiling is the platform's default thread stack size. Bisected on a
chain of composite2 calls over a 64x64 base, one node per call:

  macOS arm64, libvips 8.18.5    198
  Alpine 3.22 musl, 8.16.1      1843
  Debian glibc, 8.18.1          2009

Callers reach it with ordinary inputs. Tiling a watermark across a
1200x900 image with a 10px mark is 210 chained inserts, which is fine on
Linux and dead on macOS. That gap makes it look like a local-only bug.

Core now counts the operations chained through setNative() and renders
to memory every 32, which keeps the depth well under the lowest ceiling.
Chains shorter than 32, which is every normal use of the driver, never
pay for it: cover(800,300)+jpeg85 is unchanged at 12.6 ms. Past it the
render gets faster, because a shallower pipeline is cheaper to walk per
region. The 1200x900 tiling case with a 20px mark goes from 252 ms to
138 ms, and the 10px one from a crash to 185 ms, byte-identical output
where both complete.

Two things this is not. It counts calls, not libvips nodes, so it is a
bound and not a measurement: a modifier that chains several nodes per
call spends the budget faster. And a rendered image is a whole image, so
past 32 an operation that later narrows the region of interest no longer
narrows what the chain computes. Both are noted where the limit is set.

setNative() can now throw, since rendering can fail. The interface it
implements declares no exceptions, so PHPStan only caught one site on
its own; the rest were found by annotating the interface in a scratch
tree and are declared here.

This is a libvips property, not a driver bug, and it reproduces in 20
lines of plain jcupitt/vips. The driver cannot stop a caller from
chaining, but it can bound the depth.
@olivervogel
olivervogel merged commit d998f64 into Intervention:develop Aug 21, 2026
6 checks passed
@olivervogel

Copy link
Copy Markdown
Member

Thank you @nlemoine

@nlemoine

Copy link
Copy Markdown
Contributor Author

Thanks!

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.

3 participants