php-src icon indicating copy to clipboard operation
php-src copied to clipboard

opcache.consistency_checks > 0 causes segfaults in PHP >= 8.1.5 in fpm context

Open CyberLine opened this issue 4 years ago • 29 comments

Description

After upgrading some projects to PHP 8.1.0 and 8.1.2 we could see requests getting slower and slower over time. Restart of the correspondig fpm-pool fixed that for short. After digging in the problem we could isolate and reproduce it:

  • use a Debian 10 or 11 maschine and install php8.1-fpm and php8.1-opcache.
  • modify opcache.ini:
zend_extension=opcache.so

[opcache]
opcache.consistency_checks=1
  • require laminas: composer require laminas/laminas-servicemanager
  • create a test script (we use laminas-servicemanager here):
<?php

declare(strict_types=1);

chdir(dirname(__DIR__));
require 'vendor/autoload.php';

use Laminas\ServiceManager\ServiceManager;
$container = new ServiceManager();
  • call that script in a loop 1000 or more times while running htop in another terminal: for i in {1..10000}; do curl localhost/test.php; done;

You would see an increment usage of memory that will not getting freed after all. Set opcache.consistency_checks to 0 to check that it will not keep any used memory.

PHP Version

8.1.0

Operating System

Debian 10/11

CyberLine avatar Feb 09 '22 09:02 CyberLine

Do you get any "Checksum failed for" log entries, if you set opcache.error_log=… and opcache.log_verbosity_level=4?

cmb69 avatar Feb 09 '22 13:02 cmb69

Wed Feb  9 15:15:47 2022 (222625): Message Checksum failed for '/home/alexander/test/vendor/laminas/laminas-config-aggregator/src/PhpFileProvider.php':  expected=0x68e34d40, found=0x35584fc2
Wed Feb  9 15:15:47 2022 (222625): Message Cached script '/home/alexander/test/vendor/laminas/laminas-config-aggregator/src/PhpFileProvider.php'
Wed Feb  9 15:15:47 2022 (222625): Message Added key '/home/alexander/test/vendor/composer/../laminas/laminas-config-aggregator/src/PhpFileProvider.php'
Wed Feb  9 15:15:47 2022 (222625): Message Checksum failed for '/home/alexander/test/vendor/laminas/laminas-servicemanager/src/ServiceManager.php':  expected=0x76daed23, found=0x478bef0e
Wed Feb  9 15:15:47 2022 (222625): Message Cached script '/home/alexander/test/vendor/laminas/laminas-servicemanager/src/ServiceManager.php'
Wed Feb  9 15:15:47 2022 (222625): Message Added key '/home/alexander/test/vendor/composer/../laminas/laminas-servicemanager/src/ServiceManager.php'
Wed Feb  9 15:15:47 2022 (222625): Message Checksum failed for '/home/alexander/test/vendor/laminas/laminas-servicemanager/src/ServiceLocatorInterface.php':  expected=0xb598eac3, found=0x7ae8ecda
Wed Feb  9 15:15:47 2022 (222625): Message Cached script '/home/alexander/test/vendor/laminas/laminas-servicemanager/src/ServiceLocatorInterface.php'
Wed Feb  9 15:15:47 2022 (222625): Message Added key '/home/alexander/test/vendor/composer/../laminas/laminas-servicemanager/src/ServiceLocatorInterface.php'
Wed Feb  9 15:15:47 2022 (222625): Message Checksum failed for '/home/alexander/test/vendor/container-interop/container-interop/src/Interop/Container/ContainerInterface.php':  expected=0x20efdca4, found=0x5182df08
Wed Feb  9 15:15:47 2022 (222625): Message Cached script '/home/alexander/test/vendor/container-interop/container-interop/src/Interop/Container/ContainerInterface.php'
Wed Feb  9 15:15:47 2022 (222625): Message Added key '/home/alexander/test/vendor/composer/../container-interop/container-interop/src/Interop/Container/ContainerInterface.php'

CyberLine avatar Feb 09 '22 14:02 CyberLine

Thanks!

If the checksum comparison fails, the file is compiled again, and the old oparray is not freed – that is by design, to avoid copying shared memory. As such, this doesn't look like a bug, but I wonder why the checksum comparison fails in the first place. Are these files modified during script execution?

cmb69 avatar Feb 09 '22 14:02 cmb69

Are these files modified during script execution?

No, they aren't. You can run the same code on PHP 7.4 or 8.0 without "Checksum failed" error 🤷

Same output with php7.4 or 8.0:

Wed Feb  9 15:32:07 2022 (222628): Message Cached script '/home/alexander/test/vendor/laminas/laminas-servicemanager/src/ServiceManager.php'
Wed Feb  9 15:32:07 2022 (222628): Message Added key '/home/alexander/workspace/test/vendor/composer/../laminas/laminas-servicemanager/src/ServiceManager.php'
Wed Feb  9 15:32:07 2022 (222628): Message Cached script '/home/alexander/test/vendor/laminas/laminas-servicemanager/src/ServiceLocatorInterface.php'
Wed Feb  9 15:32:07 2022 (222628): Message Added key '/home/alexander/test/vendor/composer/../laminas/laminas-servicemanager/src/ServiceLocatorInterface.php'
Wed Feb  9 15:32:07 2022 (222628): Message Cached script '/home/alexander/test/vendor/psr/container/src/ContainerInterface.php'
Wed Feb  9 15:32:07 2022 (222628): Message Added key '/home/alexander/test/vendor/composer/../psr/container/src/ContainerInterface.php'
Wed Feb  9 15:32:07 2022 (222628): Message Cached script '/home/alexander/test/vendor/container-interop/container-interop/src/Interop/Container/ContainerInterface.php'
Wed Feb  9 15:32:07 2022 (222628): Message Added key '/home/alexander/test/vendor/composer/../container-interop/container-interop/src/Interop/Container/ContainerInterface.php'

CyberLine avatar Feb 09 '22 14:02 CyberLine

So with PHP 8.1.5 this causes random SIGSEGV instead of wasting just memory

CyberLine avatar May 02 '22 13:05 CyberLine

Ugh.

cmb69 avatar May 02 '22 13:05 cmb69

I went down this rabbit hole for a few hours and I have an incomplete explanation. This seems to be related to multiple changes in PHP 8.1. The following fields differ for each new creation of zend_persistent_script for 4 files per request.

  • zend_class_entry.inheritance_cache
  • zend_class_entry.info.user.filename
  • zend_class_entry.info.user.doc_comment

inheritance_cache is a new addition in PHP 8.1, why filename and doc_comment are different, I don't know. I'd assume they should be interned.

Also, I noticed that there's likely a mistake in the hash calculation.

https://github.com/php/php-src/blob/be9adc4fbc253d5409bee29b4a52b13be927752e/ext/opcache/zend_accelerator_util_funcs.c#L478

I think this line should be:

checksum = zend_adler32(checksum, mem, persistent_script_check_block_size);

As zend_adler32 doesn't seem to be modifying the buffer and thus has no effect.

I'll take a closer look soon but wanted to document my findings, even if small.

iluuu1994 avatar May 07 '22 17:05 iluuu1994

Nice one. Dunno if it could help, but even with checksums disabled, our prod fpm is segfaulting randomly on deploy when we call opcache_reset() on the pool. Eventually i can catch a core dump.

CyberLine avatar May 07 '22 17:05 CyberLine

Also, I noticed that there's likely a mistake in the hash calculation.

Oh, good catch! The code as is makes no sense.

cmb69 avatar May 09 '22 13:05 cmb69

Is there anything where I can be of help here? I do work together with @CyberLine and we also have some reports from other parts of our company where random segfaults do appear after production deployments.

From my PoV, the suggestion from @iluuu1994 might be a first step?

Any hint on how to create a failing test case for this would be awesome, I'd be happy to contribute as much as I can if that brings us closer to a fix here.

boesing avatar Jul 06 '22 11:07 boesing

I completely forgot about this one.

From my PoV, the suggestion from @iluuu1994 might be a first step?

I don't think that will solve the issue. If anything, the mistake in the hash calculation would lead to stale cache being used but we're having the opposite problem here. (it should still be fixed of course, or at least removed). I'll have another look at this soon.

iluuu1994 avatar Jul 06 '22 12:07 iluuu1994

@iluuu1994 anything we can help with? we discovered this bug in production yesterday.

grafik

The SIGSEV's are coming after 128GB of ram, went full.

ItsReddi avatar Aug 18 '22 13:08 ItsReddi

I'm looking more into it right now.

iluuu1994 avatar Aug 18 '22 13:08 iluuu1994

I have looked at this issue in detail and documented my findings here: https://github.com/php/php-src/pull/9377. The result is not very satisfactory, I'm not sure if there's a complete solution. I'm not even sure opcache.consistency_checks make sense at this point. What was your use-case for enabling opcache.consistency_checks, other than to help us uncover php-src bugs? :slightly_smiling_face:

Also, thank you for your patience!

iluuu1994 avatar Aug 19 '22 14:08 iluuu1994

I am not 100% sure if we have a need for consistency checks as the opcache is created by filepath and thus should be unique in case the path changes. However, we already have it disabled now but sometimes, when calling opcache_clear();, FPM segfaults even with disabled consistency checks. Not sure if it is the same issue as described here, but on some non-prod machines, we du have opcache enabled but files may change due to development progress. That would be the only use-case I could think of tho.


we do clear the opcache because we do not want it to pollute with multiple paths as on production, for every deoloyment the path changes but only one path is active at the same time. if we never clear opcache, it might grow for every deoloyment until it is full.

boesing avatar Aug 19 '22 16:08 boesing

@boesing

I am not 100% sure if we have a need for consistency checks as the opcache is created by filepath and thus should be unique in case the path changes.

As far as I understand it opcache.consistency_checks has no other purpose than to verify that the memory block that is shared between PHP processes that is supposed to be immutable does not change between requests. When compiling a file a checksum is generated by essentially looping over that memory block. The checksum is then stored in shared memory too. If on the next request the memory block doesn't match the checksum anymore the script is considered "broken" and is compiled again. This mechanism is skipped if opcache.consistency_checks is disabled. So, at the moment opcache.consistency_checks makes opcache completely useless as almost every script will just be recompiled.

Note that the checksum should never actually change, even if the actual PHP file on your machine changes. These changes won't be reflected until you either clear opcache, or have opcache.validate_timestamps enabled. So, a consistency failure would essentially always be a bug in PHP.

Now, the problem is that the memory block above is not actually immutable. There are now a few things that can change, and it's very hard to "filter" those things when generating the checksum as it's essentially just a pointer into memory with a given size. But at this point I'm not sure this is even worth fixing.

We have other mechanisms in place to make sure that the shared memory doesn't get modified, namely opcache.protect_memory which uses mprotect to guarantee it doesn't get modified (for the time it's protected).

However, we already have it disabled now but sometimes, when calling opcache_clear();, FPM segfaults even with disabled consistency checks. Not sure if it is the same issue as described here, but on some non-prod machines, we du have opcache enabled but files may change due to development progress.

Yeah, that sounds like a different issue. Would it be possible to generate a backtrace? Or is the issue completely unpredictable?

we do clear the opcache because we do not want it to pollute with multiple paths as on production, for every deoloyment the path changes but only one path is active at the same time. if we never clear opcache, it might grow for every deoloyment until it is full.

That makes sense, if the majority of your scripts become invalid they would just waste shared memory.

Also note that the docs do explicitly say that opcache.consistency_checks is not recommended for production:

https://www.php.net/manual/en/opcache.configuration.php#ini.opcache.consistency-checks

This should only be enabled when debugging, as it will impair performance.

The docs are very imprecise on the purpose of the flag.

iluuu1994 avatar Aug 19 '22 18:08 iluuu1994

Maybe @CyberLine can provide some more details regarding the backtrace as he already has access to a project with PHP 8.1, FPM and the segfaults when running opcache_clear.


Thanks for the very detailed explanation @iluuu1994 Really appreciating that - Thanks for your time!

boesing avatar Aug 19 '22 21:08 boesing

Now, the problem is that the memory block above is not actually immutable. There are now a few things that can change, and it's very hard to "filter" those things when generating the checksum as it's essentially just a pointer into memory with a given size. But at this point I'm not sure this is even worth fixing.

We have other mechanisms in place to make sure that the shared memory doesn't get modified, namely opcache.protect_memory which uses mprotect to guarantee it doesn't get modified (for the time it's protected).

I want to point out that generally we compute the checksum by looking into the persistent_script structure, with everything we know about its semantics - factoring in our knowledge on which parts are immutable - while ignoring the parts that aren’t. It’s not just a pointer to a piece of memory, and he checksum should perfectly reflect the immutable parts of the structure and it’s underlying structures.

At his is definitely worth fixing. Unlike opcache.protect_memory - this is a production-oriented feature, a safety net against situations where bugs in PHP - or more likely, an underlying library - could corrupt and crash not just a single request - but potentially bring down the entire server (if such corruption occurs in a common file, for example).

Of course, right now it seems to be useless because it’s implementation is broken - resulting in false corruption detections. But the feature is just as valid and important as the day it was introduced - as long as we can get it back in order. Most probably, new or modified parts in the persistent_script structure weren’t properly reflected in the checksum code. Once that’s fixed - everything would be back in order. There’s also a worse possibility, that a part that is supposed to be immutable is actually updated - and if that’s the case we definitely want to figure out what it is and fix it…

I pinged @dstogov to see if he can figure out what went wrong in there, hopefully he can take a look when he’s back.

zsuraski avatar Aug 20 '22 12:08 zsuraski

@zsuraski Thank you for your assessment!

I want to point out that generally we compute the checksum by looking into the persistent_script structure, with everything we know about its semantics - factoring in our knowledge on which parts are immutable - while ignoring the parts that aren’t.

Note that this is different from the things that were already mutable because those things were all at the end of zend_persistent_script and thus easily skippable during hash calculation. The things that break the calculation right now are in the middle of the mem block, as they are changes in classes or op_arrays.

If you take a look at https://github.com/php/php-src/pull/9377, the inheritance_cache case is relatively easy to fix because the number of classes in a script are usually limited, so we can just loop over them and temporarily reset them. However, for JIT it's not as trivial because the JIT replaces various opcode handlers and managing this would just be increasingly complex.

Another option is to, instead of just iterating over mem, traverse the zend_persistent_script manually but this is also complex and will need to be updated every time something changes in the data structures which seems like something that can be forgotten easily (apart from also being much slower).

Of course, if we can find a simple way to fix this it's preferable to keep the consistency checks. Maybe there's a simple solution that I'm missing.

his is a production-oriented feature

In this case the documentation is wrong, which states this should not be enabled in production.

https://www.php.net/manual/en/opcache.configuration.php#ini.opcache.consistency-checks

iluuu1994 avatar Aug 20 '22 12:08 iluuu1994

Thanks @iluuu1994!

I want to point out that generally we compute the checksum by looking into the persistent_script structure, with everything we know about its semantics - factoring in our knowledge on which parts are immutable - while ignoring the parts that aren’t.

Note that this is different from the things that were already mutable because those things were all at the end of zend_persistent_script and thus easily skippable during hash calculation. The things that break the calculation right now are in the middle of the mem block, as they are changes in classes or op_arrays.

To be perfectly honest - I remembered an entirely different implementation of the checksum code, that accounts for things that can change within op_arrays (most notably refcounts on zvals). But either my memory is wrong, or this somehow evolved into not being necessary - as early as when we open source opcache. Either way - what I remembered - diving into the structures inside ->mem in order to calculate the checksums, clearly doesn't happen in the current codebase.

If you take a look at #9377, the inheritance_cache case is relatively easy to fix because the number of classes in a script are usually limited, so we can just loop over them and temporarily reset them. However, for JIT it's not as trivial because the JIT replaces various opcode handlers and managing this would just be increasingly complex.

Another option is to, instead of just iterating over mem, traverse the zend_persistent_script manually but this is also complex and will need to be updated every time something changes in the data structures which seems like something that can be forgotten easily (apart from also being much slower).

Of course, if we can find a simple way to fix this it's preferable to keep the consistency checks. Maybe there's a simple solution that I'm missing.

his is a production-oriented feature

In this case the documentation is wrong, which states this should not be enabled in production.

It may be that since the (apparent) change to the way checksums are calculated - mprotect is as good as consistency_checks. But I think we need to get to the bottom of this before moving forward:

  1. consistency_checks definitely used to be a production-quality feature, of course that came with a penalty of a certain performance hit - but running a checksum every now and again is often not a huge price to pay for the safety net it used to provide. Can it go back into being that? If it can be, then the docs should be updated. But we're certainly not there right now, and we need to figure out whether we can go back to it.
  2. protect_memory is positioned as a debug-only feature, without explanation as to why. IIRC, there are elements inside ->mem that actually can actually get updated in the course of a perfectly normal run, that in the past we used to filter out from the checksum calculation. If I'm right and it isn't just my inventive memory, perhaps that's why protect_memory isn't entirely reliable - but it doesn't explain why until recently, consistency_checks worked fine while doing a whole ->mem checksum. If this is a thing of the past, then perhaps protect_memory is just as good as consistency_checks reliability-wise, but likely better in terms of performance.

I'll wait for Dmitry to weigh in - maybe he remembers more about the evolution of consistency_checks, and he's certainly a lot more into the current codebase than I am...

zsuraski avatar Aug 21 '22 13:08 zsuraski