Stale OPcache bytecode served after source file update
0 reputation · 04 Jun 2023, 13:11 UTC
0 reputation · 04 Jun 2023, 13:11 UTC
The goal is to serve updated PHP source from a web-server SAPI without restarting the process, while OPcache keeps compiled bytecode in shared memory across requests.
When opcache.validate_timestamps is enabled, PHP checks the source modification time only once per opcache.revalidate_freq interval. On filesystems with one-second mtime resolution, edits made within the same second can leave the timestamp unchanged, so OPcache serves stale bytecode. CLI and web-server SAPIs maintain separate caches, and default values for these directives vary by PHP version and distribution.
Which configuration combination guarantees detection of a source change within a bounded time, and does clearing OPcache in one SAPI affect the other? Is opcache_invalidate() with force=true required for immediate removal in the web SAPI?
37775 reputation · 04 Jun 2023, 20:56 UTC
To guarantee detection of a source change within a bounded time, you must configure opcache.revalidate_freq to a value less than or equal to the filesystem's minimum modification time (mtime) resolution interval. For immediate removal in the web SAPI, opcache_invalidate(realpath('path/to/file'), true) is the required mechanism.
opcache.revalidate_freq to 0 effectively forces validation on every request, bypassing mtime resolution limitations, though this incurs a performance cost.opcache.validate_timestamps is enabled.To confirm if the issue is filesystem resolution or configuration, please confirm the specific PHP version and the operating system's filesystem mtime resolution.
Use comments to ask for clarification. Post a solution as an answer.
7,430 reputation · 04 Jun 2023, 15:55 UTC
In PHP 7.x and 8.x OPcache, opcache_invalidate($path, true) removes only the entry for the exact resolved path passed to it. The same script reached through a symlink, a different include_path variant, or a relative versus absolute path can keep a separate cache entry and continue serving stale bytecode.
Editing an included or required file also does not invalidate the parent script automatically; each changed file must be invalidated individually or wait for opcache.revalidate_freq. Confirm with opcache_get_status()['scripts'] before and after invalidation in the same SAPI.