Long-running queue workers keep a stale (and unrecoverable) EntityManager
laravel-doctrine/orm version & Laravel version
laravel-doctrine/orm3.2.0 — measured at runtime; the relevant bindings inIlluminateRegistryandDoctrineServiceProviderare unchanged on3.3.x(3.3.3)doctrine/orm3.6.3,doctrine/dbal4.4.3- Laravel 12, PHP 8.3
- Workers run under supervisor:
queue:work --max-time=3600 --tries=3 --sleep=3
Expected behaviour
Doctrine's identity map behaves correctly here — a worker process is simply one long unit of work, and nothing marks a job boundary the way a request boundary is marked. What I would expect is for the package to offer a hook where a worker can be given a clean slate, since the closed-manager half of this cannot be solved from application code at all.
Actual behaviour
Nothing clears the manager between jobs, so a long-running queue:work process never gets a fresh view. Restarting the worker hourly does not help either; the window is a single job-to-job gap. Symfony fixed the same thing in DoctrineBundle; their reasons were memory consumption and, more importantly, avoiding this:
if an entity is fetched from the database, it may not be refresh between two messages handling. For example, in the case of an user account recovery process (email sent async with messenger and amqp), if the email address is updated after the first try, the second email is send to the old email address.
— https://github.com/symfony/symfony/issues/29662
Ours was the same shape, except the stale value was written back, so it destroyed existing data rather than sending to the wrong address. Nothing threw, so the job was recorded as successful.
Steps to reproduce
Run queue:work as a daemon and change a row from another process between two jobs:
$em->find(Post::class, 1)->getTitle(); // "Original"
// another process updates the row
$em->find(Post::class, 1)->getTitle(); // "Original" (same via a repository lookup)
$em->clear();
$em->find(Post::class, 1)->getTitle(); // "Updated"Query::HINT_REFRESH on the parent query is not enough either — it refreshes the root entity's own fields but does not re-initialize collections that are already initialized.
Prior art
Symfony's DoctrineClearEntityManagerWorkerSubscriber (symfony/doctrine-bridge) clears all managers on WorkerMessageHandledEvent / WorkerMessageFailedEvent, and DoctrineBundle registers it by default — not even opt-in.
On the Laravel side this keeps coming back: maxbrokman/SafeQueue was written for Laravel 5.4, and pinnacle/doctrine-queue-worker covers the same ground for Laravel 11. Both replace the worker rather than hooking into it.
Proposal
A listener on Illuminate\Queue\Events\Looping:
public function handle(Looping $event): null
{
foreach ($this->registry->getManagers() as $name => $manager) {
if ($manager instanceof EntityManagerInterface && ! $manager->isOpen()) {
$this->registry->resetManager($name);
continue;
}
$manager->clear();
}
return null;
}Looping is dispatched only from Worker::daemonShouldRun(), so it stays out of the request lifecycle. The events that mirror Symfony's placement do not: SyncQueue dispatches JobProcessing and JobProcessed (and the failure path) itself, so a job dispatched synchronously during a request would clear that request's manager. Looping is evaluated as until($event) === false, so returning false stops the worker — hence the null return type. Its trade-off is that it clears before a job rather than after, so the last job's entities stay in memory while the worker idles: worse than Symfony's placement for the memory half of the rationale, but correct for the staleness half.
The part I would most like your opinion on: resetManager() alone does not fully recover a closed manager. resetService() forgets doctrine.managers.default, but registerEntityManager() separately binds 'em' as a singleton aliased to EntityManager / EntityManagerInterface, and the facade caches its own root. Measured on 3.2.0, right after resetManager():
registry->getManager() isOpen : true
app(EntityManagerInterface::class) isOpen : false <- still the closed instance
EntityManager facade isOpen : false <- still the closed instanceSo recovery only works when ManagerRegistry is injected; anything type-hinting EntityManagerInterface keeps the closed manager, and working around that from application code means forgetInstance('em') plus Facade::clearResolvedInstance('em'). That is why I think this belongs in the package rather than in each application — and it is not a rare edge case, because a closed manager fails asymmetrically: find() keeps succeeding while writes fail with EntityManagerClosed.
Preferred direction?
- Documentation only — though that leaves the closed-manager case unsolvable from outside
- Ship the listener, opt-in — e.g.
'clear_manager_on_worker_loop' => env('DOCTRINE_CLEAR_ON_WORKER_LOOP', false) - Opt-in on
3.3.x, default in4.0 - Default now, as DoctrineBundle does
2–4 are the same code with a different default, so I am happy to implement it and let you pick. My guess is 3, since enabling it by default does change one thing visibly: work left unflushed at the end of a job is discarded on the next loop rather than picked up by a later flush.
Happy to send a PR against 3.3.x with tests. If you would rather not take this at all, that is fine too — a short note about long-running workers in docs/entity-manager.rst or docs/troubleshooting.rst would already help.
Source: laravel-doctrine/orm