[11.x] Fix unique job lock is not released on model not found exception, lock gets stuck. #54000
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.



Description
When using
SerializesModelson aUnique joband the model is deleted before the job is being processed,ModelNotFoundExceptionwill be thrown and the job will fail and that's okay and well documented.However the unique lock is not released and gets stuck until expired, this happens a lot with delayed jobs.
Related issues: #50211, #49890, possibly #37729
Steps to reproduce
1- Create or open a laravel project, for ease of inspecting use
databasecache driver.2- Create
TestJob.phpin your app/Jobs :3- Add a test route to your
web.php:4- Run the web and queue servers via
composer run devand hit the/testroute5- Refresh the page and inspect your database's
cache_locksandfailed_jobstablesCause
TLDR
No serialized job command instance = no unique lock to release
In depth
callQueuedHanlder.php'scall()is responsible for handling the queued job, when we try to unserialize the payload of the jobModelNotFoundExceptionis thrown because the model was deleted.In this case we don't have a job command instance which is currently required to release the lock.
after
$this->handleMedelNotFound(...)is done the job is marked asfailedand thefailed()method will be called:Solution
The idea
Wrap the job with a hidden context in order to have access to the lock key and the cache driver used, here's a simple overview of the flow:
Now when handling
ModelNotFoundExceptionvia thehandleModelNotFound()method, we can forceRelease the lock by using the providedcache_driverandlock_keyfrom the hidden contextImplementation
See code diff.If this gets closed for any reason use my test to research and implement another possible solution, add this to
tests/Integration/Queue/UniqueTestJob.php