Pipeline Redis batch pruning and keep custom repository lookups in Horizon search
Summary
Follow-up to #760 and #761. Pruning Redis-backed batches now sends its Lua scripts in one pipeline per stage instead of one round trip per batch. Horizon's batch search keeps calling a custom repository's find() and loads each result's progress before returning it. The queue guide and the Bus README gain two notes, and six tests are added.
Contribution category: bug fixes and a performance improvement to the Redis batch driver from #761, plus documentation corrections.
Purpose
- Shorten the time
queue:prune-batchesholds SQL parent-row locks while it talks to Redis. - Keep Horizon's search results consistent with its batch detail page when an application customizes
find(). - Tell developers which state a custom-serialized batch job has to keep, and what a repository bound to
BatchRepositorytakes over.
Problem
Prune round trips. RedisBatchRepository::deleteBatches() ran one Redis round trip per batch for the finish-marker check and another for the known-total invalidation, both inside the transaction that locks the parent rows. After the commit, deleteJobResults() ran one more per batch.
Horizon search. BatchesController::searchBatches() used findMany() for any DatabaseBatchRepository instance. A subclass bound to BatchRepository that overrides only find() was bypassed, so a batch it hides still appeared in search results while its detail page returned null.
Undocumented requirements.
- A batchable job that customizes its serialization can drop
batchPositionId. A redelivered chain link then counts its successor more than once, and the batch can finish early. - Rebinding
DatabaseBatchRepositoryorRedisBatchRepositorydoes not change lookups such asBus::findBatch(), and a repository bound toBatchRepositoryreplaces the routing between the two results drivers. Neither was documented.
Architecture and Implementation
Redis pipeline. A new private RedisBatchRepository::evalEach(string $script, array $calls) runs one script per batch.
- On a single node with more than one batch, it queues
EVALcalls in a native phpredis pipeline and reads the results in one round trip. - With one batch, or on Redis Cluster, it keeps the per-batch
evalWithShaCache()calls. readSnapshots(), the finish-marker check and known-total invalidation indeleteBatches(), anddeleteJobResults()all use it. The two inline Lua snippets became theFINISH_MARKERandINVALIDATE_TOTALconstants.- The pipeline calls the native
exec(). If it throws, the helper callsRedisConnection::invalidate()before rethrowing, so a failover error such asREADONLYkeeps the client out of the pool. This mirrors the callback pipeline inRedisProxy::executeMultiExec(). - The connection's WATCH tracking is left alone. A pipeline does not consume the server-side watch, so a connection that still watches a key is discarded on release, as before #777.
- A script that fails inside the pipeline raises
LuaScriptException, the class the per-batch path raises. The client's last error is cleared before the pipeline is queued.
The order of operations is unchanged: the known total is invalidated under the parent lock, and results are unlinked after the commit.
Horizon search. searchBatches() uses findMany() only when the bound repository's find() is still declared by DatabaseBatchRepository. Otherwise it calls find($id)?->loadMissingJobCounts() per ID, the same call the batch detail page and Telescope make. A batch deleted between the lookup and the response is left out. The default RoutingBatchRepository does not override find(), so built-in repositories keep the grouped lookup.
Repository tidy-up. RedisBatchRepository compares the finished total and finish time strictly after normalizing their types, renames $args to $arguments, and resolves the connection once where it is used.
Design Decisions and Trade-offs
EVALinside the pipeline. The pipeline sends the script text, as the snapshot pipeline in #761 did, so a cold script cache needs no mid-pipelineNOSCRIPTretry. The per-batch path still uses the SHA cache.- Native
exec()with explicit invalidation. Executing throughRedisConnection::exec()would also invalidate on failover, but it clears the connection's WATCH tracking. The explicitinvalidate()keeps both guarantees. LuaScriptExceptionfor pipeline failures. #761's snapshot pipeline raised a plainRuntimeException.LuaScriptExceptionextends it, so code catching either class keeps working, and the class no longer depends on how many batches a prune handles.- Reflection check in Horizon. The declaring-class check mirrors
Queue::usesCustomBatchDelivery(). A repository that overridesfind()gives up the grouped lookup and pays one lookup and one progress read per result, as upstream Horizon pays one lookup per result. - Documentation only for custom serialization. The chain format is unchanged. The guide names
batchIdandbatchPositionIdbecause a custom__serializeor__unserializecannot keep the position without knowing the property. - README states the consequence only. It says a replacement owns hydration, accounting and pruning for every batch. It does not name
RoutingBatchRepositoryas an extension point. - Stubbed failover test. The
READONLYregression test uses a stubbed phpredis client. Demoting the shared test server would break tests running in parallel.
Changes
Bus
RedisBatchRepository: addevalEach()and theFINISH_MARKERandINVALIDATE_TOTALconstants, and route snapshot reads, prune checks and result cleanup through the shared pipeline.RedisBatchRepository: invalidate the connection when the pipeline throws, and raiseLuaScriptExceptionwhen a pipelined script fails.RedisBatchRepository: strict comparisons and naming clean-up, with no behavior change.README.md: explain thatBatchRepositoryis the binding to replace when customizingfind()orget(), and what that replacement owns.
Horizon
BatchesController::searchBatches(): keep a customfind()in control of search results and load each result's progress before returning it.
Documentation
queues.md, "Defining Batchable Jobs": list the state a batchable job must keep when it customizes serialization or restoration.
Tests
tests/Bus/RedisBatchRepositoryTest.php: aREADONLYreply during the pipelined scripts invalidates the connection, and a failed pipelined script raisesLuaScriptException.tests/Integration/Bus/Redis/RedisBatchRepositoryTest.php:- Horizon search through a custom
find()still serializes after the batch is deleted. - Loading a page of two batches on a watching connection leaves that connection to be discarded.
- One prune of three unfinished batches restores an unprojected finish and deletes the other two with their Redis results.
- Horizon search through a custom
BatchesControllerTest::testSearchUsesACustomRepositoryFindMethod: a customfind()can exclude a batch from search.BatchChainRedeliveryTest::testAMidChainJobThatAddsItselfCountsItsSuccessorOnce: a chain job with a successor adds itself to its batch, and the successor's position is counted once.
Validation
Run on macOS with PHP 8.4.27, phpredis 6.3.0, SQLite and a single-node Redis 7.0.11.
Run on the final tree (a581d31be):
| Check | Result |
|---|---|
tests/Bus | 201 passed |
tests/Integration/Bus | 59 tests, 19 skipped, the rest passed |
tests/Horizon | 74 passed |
tests/Integration/Horizon | 254 tests, 1 skipped, the rest passed |
tests/Telescope | 516 passed |
PHPStan on src/bus/src and BatchesController.php | No errors |
| PHPStan test rules on the two Redis batch repository test files | No errors |
| php-cs-fixer dry run on the four PHP files changed by the last six commits | Nothing to fix |
Regression checks:
- The Horizon custom-
find()test and the WATCH test failed before their fixes and pass after. - The
READONLYtest fails when theinvalidate()call is removed. - Before the fix, a two-batch prune against a
WRONGTYPEstate key raisedRuntimeExceptionwhile a one-batch prune raisedLuaScriptException. Both now raiseLuaScriptException.
Run at e756907fb and not repeated after the six later commits, which do not touch the queue package: tests/Queue (1,263 passed), tests/Integration/Queue and tests/Integration/Database/Queue.
Not run:
- The full
composer analyse, the full test suite, MySQL, MariaDB, PostgreSQL and Redis Cluster. - A before-and-after benchmark of the prune path.
- The manual failover check against a demoted Redis replica. It was run for the earlier
RedisConnection::exec()implementation and has not been repeated for the nativeexec()withinvalidate(). The stubbed test covers that path. - The reasons for skipped tests were not checked individually.
Risks and Review Notes
Decisions needed from a maintainer
- Horizon pagination with a filtering
find(). Search takes up to 50 candidate IDs and then filters them throughfind(). The dashboard disables "Next" when fewer than 50 rows come back and hides the pagination row when none do, so older matches become unreachable from the UI although the API still returns them withbefore_id. Upstream Laravel Horizon behaves the same way. This PR makes it reachable forDatabaseBatchRepositorysubclasses that overridefind(). It already applied to independent repositories. It is not changed here because the #761 plan records "No new Horizon search or pruning contract". Should it be fixed, and in which form? - Internal property in the docs. The queue guide names
batchPositionId, which is marked@internalinBatchableand described as internal in the #760 plan. Should the guide keep the name, or describe the requirement without it? RoutingBatchRepositoryas an extension point. A repository that overridesfind()and still wants per-driver routing has to extend it today. Should the README say so?
Behavior to review
- Snapshot reads share the new helper. Multi-batch snapshot reads now also invalidate the connection when the pipeline throws, and raise
LuaScriptExceptionon a script error. - Error message. A failed pipeline reports
Unable to run the Redis batch scriptinstead ofUnable to load Redis batch progress. No test in the repository asserts the old text. - Per-result cost for custom
find(). Each search result now performs its progress read inside the request instead of at serialization. The number of reads is unchanged. - Redis Cluster. The Cluster branch keeps the previous per-batch calls but was not exercised locally.
- Pipeline coverage. No test covers a pipelined result cleanup that fails and is retried by a later prune.
Related Information
- #760: Count each logical batch job's success once.
- #761: Add Redis storage for job batch results and preserve counts across delivery failures.
docs/plans/2026-11-21-0712-redis-batch-results.md: the Horizon search and repository binding rules this PR follows.docs/plans/2026-11-20-1036-batch-success-counting.md: the batch position identity the queue guide note refers to.
Summary by CodeRabbit
- Bug Fixes
- Improved Redis batch operations when processing multiple batches, including clearer handling of connection failures and script errors.
- Improved batch search results when using customized repositories, including progress details and correct handling of missing batches.
- Fixed batch progress tracking for jobs that are redelivered in a chain.
- Documentation
- Clarified which batch state to preserve when customizing job serialization or restoration.
- Explained how custom batch repositories affect lookups, hydration, accounting, and cleanup.
[!NOTE]
Pipeline Redis batch Lua scripts and honor custom find() in Horizon search
- Adds
RedisBatchRepository::evalEach, which pipelines multiple Lua script calls on non-cluster connections, evaluates them individually on cluster connections, and raises LuaScriptException on failed script results
- Routes finish-marker lookups, known-total invalidations, result-key unlinks, and snapshot reads through
evalEach, replacing per-row and snapshot-specific evaluation loops in RedisBatchRepository.php
BatchesController::searchBatches uses reflection to detect a custom find() override and then loads results through find() with loadMissingJobCounts(), instead of always using findMany() in BatchesController.php
- Fixes strict comparisons by casting stored finish totals and non-null finish timestamps to integers in
releaseFromBatch and loadSnapshots
- Behavioral Change: a failed pipelined snapshot script now throws
LuaScriptException instead of RuntimeException, and a thrown pipeline execution invalidates the Redis connection — see readSnapshots and evalEach in RedisBatchRepository.php
Macroscope summarized 81b778b.