feat: background workers = non-HTTP workers with shared state#2287
feat: background workers = non-HTTP workers with shared state#2287nicolas-grekas wants to merge 1 commit intophp:mainfrom
Conversation
e1655ab to
867e9b3
Compare
|
Interesting approach to parallelism, what would be a concrete use case for only letting information flow one way from the sidekick to the http workers? Usually the flow would be inverted, where a http worker offloads work to a pool of 'sidekick' workers and can optionally wait for a task to complete. |
da54ab8 to
a06ba36
Compare
|
Thank you for the contribution. Interesting idea, but I'm thinking we should merge the approach with #1883. The kind of worker is the same, how they are started is but a detail. @nicolas-grekas the Caddyfile setting should likely be per |
ad71bfe to
05e9702
Compare
|
@AlliBalliBaba The use case isn't task offloading (HTTP->worker), but out-of-band reconfigurability (environment->worker->HTTP). Sidekicks observe external systems (Redis Sentinel failover, secret rotation, feature flag changes, etc.) and publish updated configuration that HTTP workers pick up on their next request; with per-request consistency guaranteed via Task offloading (what you describe) is a valid and complementary pattern, but it solves a different problem. The non-HTTP worker foundation here could support both. @henderkes Agreed that the underlying non-HTTP worker type overlaps with #1883. The foundation (skip HTTP startup/shutdown, immediate readiness, cooperative shutdown) is the same. The difference is the API layer and the DX goals:
Happy to follow up with your proposals now that this is hopefully clarified. |
05e9702 to
8a56d4c
Compare
|
Great PR! Couldn't we create a single API that covers both use case? We try to keep the number of public symbols and config option as small as possible! |
Yes, that's why I'd like to unify the two API's and background implementations into one. Unfortunately the first task worker attempt didn't make it into |
|
The PHP-side API has been significantly reworked since the initial iteration: I replaced The old design used
Key improvements:
Other changes:
|
cb65f46 to
4dda455
Compare
|
Thanks @dunglas and @henderkes for the feedback. I share the goal of keeping the API surface minimal. Thinking about it more, the current API is actually quite small and already general:
The name "sidekick" works as a generic concept: a helper running alongside. The current set_vars/get_vars protocol covers the config-publishing use case. For task offloading (HTTP->worker) later, the same sidekick infrastructure could support:
Same worker type, same So the path would be:
The foundation (non-HTTP threads, cooperative shutdown, crash recovery, per-php_server scoping) is shared. Only the communication primitives differ. WDYT? |
b3734f5 to
ed79f46
Compare
|
|
|
Hmm, it seems they are on some versions, for example here: https://github.com/php/frankenphp/actions/runs/23192689128/job/67392820942?pr=2287#step:10:3614 For the cache, I'm not aware of a Github feature that allow to clear everything unfortunately 🙁 |
|
Split zones implemented, see last commit. |
|
I think it would still be nice to declare the workers in the global scope so you could also have a process only running background scripts. Doesn't need to be in this PR though. |
If it doesn't have to be connected to any specific application, https://github.com/Baldinof/caddy-supervisor should do the trick. Also still using it to run my messenger queues. |
|
We actually do support this already. Workers declared in the global frankenphp block get their own scope (empty string) and the lookup falls back to it when no php_server scope matches. So a FrankenPHP instance with only global background workers (no php_server) would work: get_vars resolves against the global scope. What we don't do (by design) is let php_server-scoped workers access global-scope background workers. Each scope is isolated. If that cross-scope access is needed in the future, we could add a fallback chain (check own scope first, then global), but I'd rather keep it strict for now. Do you have something else in mind? |
I think that's a great compromise.
I'm mostly on-board with the concept now, but there's still one thing I'd like to see solved a bit better: it's an issue that workers are implicitly marked as ready. I would much prefer that a background worker must explicitly reach some function for it to be considered in a ready state. This goes together with my intuition that streams are just a tiny bit too complicated for most people for this to be the best option. I don't really want to circle back to a |
|
Isn't calling |
|
Note that I would love to have workers available for CLI scripts. Something that's entirely skipped for now. |
You're absolutely right. The point about the stream logic being quite low level for users still stands, though.
Should wait for that first. The current solution with an emulated cli through the embed sapi is a bit hacky and causes issues. I'd prefer not to add much to it until we get a proper cli sapi embedded. |
frankenphp.c
Outdated
| static bool bg_worker_validate_zval(zval *z) { | ||
| switch (Z_TYPE_P(z)) { | ||
| case IS_NULL: | ||
| case IS_FALSE: | ||
| case IS_TRUE: | ||
| case IS_LONG: | ||
| case IS_DOUBLE: | ||
| case IS_STRING: | ||
| return true; | ||
| case IS_OBJECT: | ||
| return (Z_OBJCE_P(z)->ce_flags & ZEND_ACC_ENUM) != 0; | ||
| case IS_ARRAY: { | ||
| zval *val; | ||
| ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(z), val) { | ||
| if (!bg_worker_validate_zval(val)) | ||
| return false; | ||
| } | ||
| ZEND_HASH_FOREACH_END(); | ||
| return true; | ||
| } | ||
| default: | ||
| return false; | ||
| } | ||
| } |
There was a problem hiding this comment.
theoretically, if validation fails, we could also fallback to serialization.
There was a problem hiding this comment.
That'd break SRP, I explained this above. Practically, that'd mean set_vars() could throw unattended exceptions. Better tell ppl they should split codepaths (serialize on their own or use a Symfony's DeepCloner or similar.)
|
after discussion with @nicolas-grekas today at symfony live, i tried out if we could offer a polyfill for this functionality. it is still very rough, but it shows the basic PoC by writing to a filesystem: https://github.com/dbu/shared-state-polyfill i'd be happy to evolve on it a bit, after getting input - though probably its best to wait until this PR is merged or at least the contract is sure to be final. (i don't want to hijack this thread, please open issues in my PoC repository to discuss the polyfill. @nicolas-grekas if you could review the basic thing before the frankenphp changes get merged, we can do a sanity check if we maybe should change something of the pattern to make it polyfill friendly. the notification stream is a bit funny for the polyfill as it would be unnecessary as each worker is its own process that receives the signals directly. and the name of the background worker being implicit makes polyfill a bit awkward, but is great for a smooth experience with frankenphp. |
| struct itimerspec its; | ||
| its.it_value.tv_sec = 0; | ||
| its.it_value.tv_nsec = 1; | ||
| its.it_interval.tv_sec = 0; | ||
| its.it_interval.tv_nsec = 0; | ||
| timer_settime(thread_php_timers[idx], 0, &its, NULL); |
There was a problem hiding this comment.
Not sure this is safe or a good idea. Would be better to store a reference to execution globals and do this instead:
zend_atomic_bool_store_ex(&EG(vm_interrupt), true);There might also be a way to access EG directly via TSRM, haven't looked into it too much yet though.
| func (registry *backgroundWorkerRegistry) Entrypoint() string { | ||
| return registry.entrypoint | ||
| } | ||
|
|
||
| func (registry *backgroundWorkerRegistry) Num() int { | ||
| if registry.num <= 0 { | ||
| return 0 | ||
| } | ||
| return registry.num | ||
| } | ||
|
|
||
| func (registry *backgroundWorkerRegistry) MaxThreads() int { | ||
| if registry.num > 0 { | ||
| return registry.num | ||
| } | ||
| return 1 | ||
| } | ||
|
|
||
| func (registry *backgroundWorkerRegistry) SetNum(num int) { | ||
| registry.num = num | ||
| } |
There was a problem hiding this comment.
I think some function here are unused
| num int // threads per background worker (0 = lazy-start with 1 thread) | ||
| maxWorkers int // max lazy-started instances (0 = unlimited) | ||
| autoStartNames []string // names to start at boot when num >= 1 |
There was a problem hiding this comment.
do you need these values here, aren't they already defined on the worker?
num 0 = lazy start
num 1 = autostart
| preparedEnvNeedsReplacement bool | ||
| logger *slog.Logger | ||
| requestOptions []frankenphp.RequestOption | ||
| backgroundScope string |
There was a problem hiding this comment.
The scope can also just be an integer. It should probably be requested from and managed by the frankenphp package.
|
Would be nice if someone with fresh eyes could look over this PR. Short summary from my side:
|
|
Another reason I dislike streams is that the polling api from (this RFC) might already be in PHP 8.6. |
Summary
Background workers are long-running PHP workers that run outside the HTTP cycle. They observe their environment (Redis, DB, filesystem, etc.) and publish configuration that HTTP workers read per-request - enabling real-time reconfiguration without restarts or polling.
PHP API
frankenphp_worker_set_vars(array $vars)- publishes config from a background worker (persistent memory, cross-thread). Skips all work when data is unchanged (===check).frankenphp_worker_get_vars(string|array $name, float $timeout = 30.0)- reads config from HTTP workers (blocks until first publish, generational cache)frankenphp_worker_get_signaling_stream()- returns a pipe-based stream forstream_select()integration (cooperative shutdown)Caddyfile configuration
backgroundmarks a worker as non-HTTPnamespecifies an exact worker name; workers withoutnameare catch-all for lazy-started namesmax_threadson catch-all sets a safety cap for lazy-started instances (defaults to 16)max_consecutive_failuresdefaults to 6 (same as HTTP workers)max_execution_timeautomatically disabled for background workersphp_serverblock has its own isolated scope - workers in different blocks can use the same names without conflictShutdown
Background workers are stopped cooperatively via the signaling stream: FrankenPHP writes
"stop\n"which is picked up bystream_select(). Workers have a 5-second grace period.After the grace period, a best-effort force-kill is attempted:
max_execution_timetimer cross-thread viatimer_settime(EG(max_execution_timer_timer))CancelSynchronousIo+QueueUserAPCinterrupts blocking I/O and alertable waitsArchitecture
php_serverscope isolation with internal registry (unexported types, minimal public API)backgroundWorkerThreadhandler implementingthreadHandlerinterface - noisBackgroundWorkerchecks in HTTP worker code pathsdrain()on the handler interface for clean shutdown signalingpemalloc) withRWMutexfor safe cross-thread sharingset_varsskip: uses PHP's===(zend_is_identical) to detect unchanged data - skips validation, persistent copy, write lock, and version bump. Cache updated to enable pointer equality on next call.get_varscalls return the same array instance (===is O(1))IS_ARRAY_IMMUTABLE)ZSTR_IS_INTERNED) - skip copy/free for shared memory stringsstream_select()- compatible with amphp/ReactPHP event loops$_SERVER['FRANKENPHP_WORKER_NAME']set for all workers (HTTP and background)$_SERVER['FRANKENPHP_WORKER_BACKGROUND']set for all workers (true/false)Example
Test coverage
16 tests covering: basic vars, at-most-once start, validation, type support (enums, binary-safe strings), multiple background workers, multiple entrypoints, crash restart, signaling stream, worker restart lifecycle, non-background-worker error handling, identity detection, generational cache.
All tests pass on PHP 8.2, 8.3, 8.4, and 8.5 with
-race. Zero memory leaks on PHP debug builds.Documentation
Full docs at
docs/background-workers.md.