Skip to content

fix(redis): fail the task of a worker whose running slot lease expired - #1811

Open
HEOJUNFO wants to merge 4 commits into
harry0703:mainfrom
HEOJUNFO:fix/redis-crashed-worker-task-state
Open

HEOJUNFO wants to merge 4 commits into
harry0703:mainfrom
HEOJUNFO:fix/redis-crashed-worker-task-state

Conversation

@HEOJUNFO

@HEOJUNFO HEOJUNFO commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

With enable_redis = true, a task whose API process is killed while it runs (OOM kill, docker kill, power loss) stays in state=4 forever, and DELETE /api/v1/tasks/{id} keeps answering 409 task is still running. Tasks that were only queued recover; the one that was running does not.

#1742 gave every running slot a renewable lease, so the crashed worker's capacity comes back after 90 s. The task record was left out: the slot member is a random token, so once the lease is pruned nothing knows which task it belonged to, and the only cleanup is the finally: self.task_done() that a killed process never reaches.

Real run on macOS, Python 3.13, three processes: a Redis stand-in (fakeredis TcpFakeServer), an API process that accepts two requests and is kill -9ed while the first one runs, and a replacement API process that goes through the normal lifespan startup. Only tm._run_pipeline is stubbed. The 90 s lease and 30 s heartbeat are unchanged.

main
[t+0s after restart]   first (crashed while running): state=4 progress=30 error=None
[t+0s after restart]   second (was queued):           state=4 progress=0 error=None
[t+100s]               first (crashed while running): state=4 progress=30 error=None
[t+100s]               second (was queued):           state=1 progress=100 error=None
DELETE first  -> 409 task is still running
DELETE second -> 200 success

this branch
[t+100s]               first (crashed while running): state=-1 progress=30 error=the worker process stopped before the task finished
[t+100s]               second (was queued):           state=1 progress=100 error=None
DELETE first  -> 200 success
DELETE second -> 200 success

Cause: app/controllers/manager/redis_manager.py — _ADMIT_TASK_SCRIPT and _CLAIM_QUEUED_TASK_SCRIPT drop expired slots with ZREMRANGEBYSCORE and nothing else looks at the task that slot was running.

Fix:

  • Each slot records its task in a hash, <queue>:running:tasks (token -> task_id). The admission and claim scripts write the entry in the same operation that creates the lease, and it is removed before the slot is released.
  • fail_tasks_of_expired_slots() lists the recorded slots whose lease is missing or past its deadline. For each one, a single script checks again that the token still owns the task and that its lease is still expired, sets the task to failed (failed_stage="worker") only if it is still processing, and removes the entry and the slot. A task that already reached a final state keeps it. A slot that was renewed in between is left alone.
  • While a worker runs a task, its update_task() and patch_task() go through a script that first checks the token still owns the task. Once the expiry check has removed the entry, update_task() raises TaskOwnershipLostError, which stops the pipeline, and patch_task() returns False. A worker that was only paused cannot change the record or create it again after a deletion.
  • The worker holds an OS file lock for its task (storage/task_locks/, filelock) for as long as it runs it. If the lock directory cannot be created or the lock cannot be acquired, the worker fails the task through its slot token and does not run the pipeline. The API delete and the WebUI delete check that lock first and refuse (409 for the API) while a process holds it. A killed process releases it at once; a paused one keeps it until it resumes and stops. The deletion does not hold the lock itself, so two deletions of the same task still both succeed.
  • The queue dispatcher calls the expiry check before check_queue(), so it runs at startup and then at most every 5 s.

Liveness is decided by the same renewable lease that already returns the slot, not by the age of the task.

Validation:

  • Real API processes against Redis 7 (Docker) on macOS, Python 3.13, lease shortened to 6 s, only tm._run_pipeline stubbed. Each case was run on the first commit of this PR and on the current head; the outputs are in the review reply below.
    • Worker SIGSTOPped mid-task: failed after the lease, DELETE answers 409 while the process is stopped. After SIGCONT the task stays failed and the delete returns 200. The record and the directory do not come back.
    • Worker finishes while another API process is between listing the slot and writing the failure: the task stays complete with its MP4.
    • API process killed right after the claim script returned: the task is failed after the lease and can be deleted.
    • Worker SIGKILLed mid-task (the original case): failed after the lease, DELETE returns 200.
  • Tests in test/services/test_redis_queue_admission.py (they need Redis, like the rest of the file, and now keep the task records in the same Redis): the five from the first commit, plus a renewed slot is left alone, a task that completes during the check keeps its result, a crash right after admission or right after queue pickup leaves a task that gets failed, a worker that lost its slot cannot bring back a deleted task or overwrite the failure, a worker that still holds its slot writes normally, and the task directory stays held until the worker stops. test_controller_video.py and test_webui_task.py cover the two delete entry points refusing a held directory.
  • python -X utf8 -m pytest -q test/services/test_redis_queue_admission.py test/services/test_task_manager.py test/services/test_controller_video.py test/services/test_webui_task.py test/services/test_concurrent_task_delete.py → 123 passed against Redis 7 (at 02addc5).
  • aec13dc adds six tests for a lock that cannot be taken (three for the worker, two for the API delete, one for the WebUI delete). The same five files: 129 passed against a fakeredis TCP server.
  • ruff check .

Other effects of this change:

  • A live worker that cannot reach Redis for longer than the lease loses its slot today. With this change its task is failed and the pipeline stops at its next state write, instead of continuing without a slot.
  • A worker that lost its slot is stopped at its next state write, not at once. Until then it can still write intermediate files into its own task directory, which cannot be deleted while that process holds it.
  • The write check uses the token -> task_id entry, not the lease score. A worker whose lease was pruned by a new admission, but whose task the expiry check has not failed yet, can still finish and write its result.
  • Deleting a task now creates and removes a small lock file under storage/task_locks/. A killed worker leaves its lock file behind until the task is deleted.
  • Deleting a task whose directory a worker process still holds takes 0.5 s before it answers 409: the check waits that long so a concurrent deletion of the same task is not mistaken for a worker.
  • A task whose directory lock cannot be taken does not run. It is set to failed with failed_stage="worker" and the path and OS error in error. This includes a storage root that is not writable, where storage/task_locks cannot be created: main completes a task in that layout (with storage/tasks writable), and with this change every task in Redis mode ends failed there.
  • A deletion that cannot create or open the lock goes ahead when the lock file does not exist, since a worker only runs a task while it holds that file. When the file exists and cannot be opened, the deletion answers 409 until its permissions are fixed.

Not changed here:

  • The task is failed, not re-queued. The pipeline may already have paid for the script and the voice, and re-running it is a separate decision.
  • The directory lock only works when the deleting process and the worker share the storage directory (one host or one volume). I did not run it across hosts or on Windows.
  • A request whose process is killed between creating the task record and the admission script still leaves a processing record with no slot and no queue item.
  • The WebUI uses the in-memory manager even when Redis is enabled, so a WebUI restart is not covered (fix(webui): keep disk-history tasks deletable when they have no video #1706 is about that path).

🤖 Generated with Claude Code

A killed API process never reaches task_done(), so its task stayed in
processing forever and DELETE kept answering 409. The lease expiry already
frees the global slot; record which task each slot runs and fail the task
when its lease is gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@harry0703 harry0703 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for tracking this down. I reproduced the original bug locally on macOS with Redis 7.2.3 and the default 90-second lease. After a SIGKILL and API restart, main still returned 409 when I tried to delete the interrupted task. On this branch the task kept its progress, was marked failed with failed_stage=worker, and could be deleted with a 200. In both runs the queued task went on to produce an MP4.

Could you fix these three cases before we merge? I shortened the lease for the tests below so I could repeat them quickly.

  1. A paused worker can bring back a deleted task. I paused the worker with SIGSTOP, waited for a second API process to mark the task failed, then deleted it. DELETE returned 200 and GET returned 404. After SIGCONT, the same task ID reappeared as complete with a new MP4. Please use the lease token to reject state and output commits from a worker that has lost its slot. Deletion also needs to wait until that worker can no longer write to the task directory.
  2. The expiry check can overwrite a completed task. I paused the dispatcher just after it read processing, let the worker finish, then resumed the dispatcher. The API went from complete to failed with failed_stage=worker, even though progress was already 100% and the MP4 was present. Please recheck the token's ownership, lease and current task state in the same Redis operation that marks it failed.
  3. A crash during queue pickup can still leave a task stuck. I killed the API process after it popped a queued task and reserved its slot, just before it wrote the token-to-task mapping. After restart and lease expiry, the task stayed at processing with 0% progress and DELETE returned 409. Please record the task ID in the same Lua operation that takes the queue item and creates its lease.

Regression tests for those three cases would make this much easier to verify on the next pass.

HEOJUNFO and others added 2 commits November 18, 2026 15:11
…tomically

Review of the first commit found three cases it did not cover.

A worker that was paused, not killed, wrote its task again after the task
had been failed and deleted. Worker writes now go through its slot token
and are refused once the expiry check has taken the token away, and every
deletion entry point waits for an OS lock the worker process holds on the
task directory.

The expiry check read the task and wrote the failure in separate steps, so
a task that completed in between was turned into a failure. The slot, its
lease and the task state are now checked in the Redis operation that
writes the failure.

A process killed between claiming a queue item and recording its task left
a slot nobody could trace. The scripts that create a lease now record the
task themselves.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…g it

Holding the lock across the removal made two concurrent deletions of the
same finished task exclude each other: one got 409 and
test_concurrent_task_deletions_do_not_return_server_error failed in CI.
A deletion only needs to know that no worker process holds the directory.
Once it is free it stays free, because a task in a final state is never
handed to a worker again. The check waits briefly so that another
deletion asking the same question is not mistaken for a worker.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@HEOJUNFO

Copy link
Copy Markdown
Contributor Author

All three reproduce here on 660fee8 and are fixed in 9b78dde and 02addc5. Runs below are real API processes against Redis 7 (Docker) on macOS, Python 3.13, with the lease shortened to 6 s and only tm._run_pipeline stubbed.

1. A paused worker brings back a deleted task

660fee8
SIGSTOP api A while the task runs
GET task (A still stopped)     -> state=-1 progress=30 failed_stage=worker videos=0
DELETE task (A still stopped)  -> 200 success
GET task                       -> 404
SIGCONT api A
GET task (12 s after SIGCONT)  -> state=1 progress=100 failed_stage=None videos=1
task directory: final-1.mp4, stage-40.bin ... stage-90.bin

this branch
SIGSTOP api A while the task runs
GET task (A still stopped)     -> state=-1 progress=30 failed_stage=worker videos=0
DELETE task (A still stopped)  -> 409 task is still running
SIGCONT api A
GET task (12 s after SIGCONT)  -> state=-1 progress=30 failed_stage=worker videos=0
DELETE task (worker stopped)   -> 200 success
GET task (3 s later)           -> 404
task directory: gone
  • State: while a worker runs a task, update_task() and patch_task() go through a script that first checks <queue>:running:tasks[token] == task_id. The expiry check removes that entry in the operation that fails the task. After that update_task() raises TaskOwnershipLostError, which stops the pipeline, and patch_task() returns False, so the record is neither changed nor re-created.
  • Directory: Redis cannot tell a paused process from a dead one, so I could not make deletion wait with the lease alone. The worker now holds an OS file lock for its task (storage/task_locks/, filelock, same reasoning as video_project._lock) while it runs it. The API delete and the WebUI delete check that lock first and refuse while a process holds it. A killed process releases it at once, a paused one keeps it. The deletion does not hold the lock itself: my first push did, which made two concurrent deletions of one task exclude each other and failed test_concurrent_task_deletions_do_not_return_server_error in CI. 02addc5 fixes that.
  • In the run above the resumed worker wrote one more intermediate file (stage-40.bin), was refused at its next state write and stopped. The directory could not be deleted during that time, and the later delete removed all of it.

Two limits: the worker is stopped at its next state write, not at once, and the lock needs the deleting process and the worker to share the storage directory. I did not run it across hosts or on Windows.

2. The expiry check overwrites a completed task

API B is held for 6 s right before its write that marks the task failed. API A's lease is not renewed and its worker finishes during those 6 s.

660fee8
GET task when B is about to mark it failed -> state=4 progress=60
GET task (worker finished)                 -> state=1 progress=100 videos=1
GET task (after B's write)                 -> state=-1 progress=100 failed_stage=worker videos=1

this branch
GET task when B is about to mark it failed -> state=4 progress=60
GET task (worker finished)                 -> state=1 progress=100 videos=1
GET task (after B's write)                 -> state=1 progress=100 failed_stage=None videos=1

fail_tasks_of_expired_slots() still lists candidates first, but the write is now one script per slot with the slot set, the owner hash and the task as keys. It checks that the token still owns the task, that the lease is missing or past its deadline, and that the task is still processing, then writes the failure and removes the entry and the slot. A renewed slot is left alone.

3. A crash during queue pickup leaves a task stuck

API A exits right after the claim script returns, before any Python code handles the payload.

660fee8
GET second (10 s after restart) -> state=4 progress=0
DELETE second                   -> 409 task is still running

this branch
GET second (10 s after restart) -> state=-1 progress=0 failed_stage=worker
DELETE second                   -> 200 success

_CLAIM_QUEUED_TASK_SCRIPT reads kwargs.task_id from the popped payload and writes the token -> task_id entry next to the ZADD. _ADMIT_TASK_SCRIPT gets the task ID as an argument and writes the same entry for a request that takes a slot directly. That path had the same gap.

Tests

test_redis_queue_admission.py has eight new tests: a slot renewed after it was listed is left alone, a task that completes during the check keeps its result, a crash right after admission and right after queue pickup, a worker that lost its slot cannot bring back a deleted task or overwrite the failure, a worker that still holds its slot writes normally, and the task directory stays held until the worker stops. Seven of them fail on 660fee8; the eighth guards the normal path. The file now keeps its task records in the test Redis, because the slot and the task are checked in one Redis operation. The two delete entry points have a test each for refusing a held directory.

One behaviour change to be aware of: a live worker that cannot renew for longer than the lease used to keep running and flip its task back to processing. Now its task stays failed and the pipeline stops. The description is updated with this and the other effects.

@HEOJUNFO

Copy link
Copy Markdown
Contributor Author

@harry0703 The three cases from your review are fixed in 9b78dde and 02addc5; the runs are in my reply above. Could you take another look when you have time?

main has moved since (#1822, #1825 and others touch task.py, video.py, redis_manager.py and webui/Main.py), so I checked the branch against it. It still merges into main 86e45a2 without conflicts, and on that merged tree:

MPT_TEST_REDIS_HOST=127.0.0.1 MPT_TEST_REDIS_PORT=6391 MPT_TEST_REDIS_DB=15 \
  python -m pytest -q test/services/test_redis_queue_admission.py \
  test/services/test_controller_video.py test/services/test_webui_task.py
90 passed, 30 subtests passed

That run used a fakeredis TCP server, not a real Redis; the process-level runs in my earlier reply were against Redis 7. I did not push the merge. If you would rather have main merged into the branch, say so and I will.

@harry0703

Copy link
Copy Markdown
Owner

Thanks for addressing the earlier cases. I reran the queue and controller tests against real Redis on top of current main, and those checks passed.

I found one upgrade case that still leaves a task stuck. With the storage root read-only and the existing storage/tasks directory writable, main completed the task. On this branch, creating storage/task_locks raised PermissionError before the worker entered the pipeline. The slot and its task mapping were removed, but the task stayed in PROCESSING, even after an expiry sweep.

Could we handle failures to create or acquire the directory lock so a task ends in a state the user can recover from?

With a storage root that is not writable, creating storage/task_locks
raised PermissionError in the worker before the pipeline started. The
exception skipped everything except task_done(), which removed the slot
and its task entry, so the task stayed in processing and nothing was left
for the expiry check to find. A lock that could not be acquired was only
logged and the pipeline ran without it.

The worker now fails the task when the lock directory cannot be created
or the lock cannot be acquired, and does not run the pipeline. The
failure is written through the slot token, before the slot is released.

A deletion that cannot create or open the lock goes ahead when the lock
file does not exist: a worker runs a task only while it holds that file.
It still refuses when the file exists and cannot be opened. Before, the
API answered 500 and the WebUI raised.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@HEOJUNFO

Copy link
Copy Markdown
Contributor Author

This reproduces here on 02addc5 and is fixed in aec13dc. The run below is real API processes on macOS, Python 3.13, with the real pipeline (no voice, one local image). Redis is a fakeredis TCP server this time, not a real Redis.

Layout: storage is dr-xr-xr-x, storage/tasks is drwxr-xr-x, and storage/task_locks does not exist. old ran from start to end on main. first and second were accepted by main with max_concurrent_tasks = 0, so both were in the Redis queue when the API restarted on the code under test with max_concurrent_tasks = 1. <MPT_HOME> and the lock file name are shortened.

main 1d7ec49
GET first      -> state=1 progress=100 videos=1
GET second     -> state=1 progress=100 videos=1
DELETE first   -> 200 success
DELETE second  -> 200 success
DELETE old     -> 200 success

02addc5
log: PermissionError: [Errno 13] Permission denied: '<MPT_HOME>/storage/task_locks'
GET first      -> state=4 progress=0 videos=0
GET second     -> state=4 progress=0 videos=0
redis: running slots=0 token->task entries=0 queued=0
GET first  (12 s later) -> state=4 progress=0 videos=0
GET second (12 s later) -> state=4 progress=0 videos=0
DELETE first   -> 409 task is still running
DELETE second  -> 409 task is still running
DELETE old     -> 500 Internal Server Error

this commit
GET first      -> state=-1 progress=0 videos=0 failed_stage=worker error=cannot lock the task directory with <MPT_HOME>/storage/task_locks/<sha256>.lock: PermissionError: [Errno 13] Permission denied: '<MPT_HOME>/storage/task_locks'
GET second     -> state=-1 progress=0 videos=0 failed_stage=worker error=cannot lock the task directory with <MPT_HOME>/storage/task_locks/<sha256>.lock: PermissionError: [Errno 13] Permission denied: '<MPT_HOME>/storage/task_locks'
redis: running slots=0 token->task entries=0 queued=0
DELETE first   -> 200 success
DELETE second  -> 200 success
DELETE old     -> 200 success
GET first / second / old -> 404

The 500 on old is a second problem in the same place: the delete check created the lock directory too, so on 02addc5 no task could be deleted in this layout, finished ones included. The API in in-memory mode and the WebUI delete had it as well.

  • Cause: task_directory_lock() created storage/task_locks outside its try. The PermissionError left the worker before the pipeline and before anything wrote the task. Only finally: task_done() ran, which removed the slot and its token -> task_id entry, so the expiry check had nothing left to find.
  • A lock that could not be acquired was caught, logged, and the pipeline ran without it. That is gone too.
  • Worker: creating the directory is now part of taking the lock. If the directory cannot be created or the lock cannot be acquired (OSError, or the lock is held), the pipeline does not run and the task is set to failed with failed_stage="worker" and the path and OS error in error. The write goes through the slot token, like the worker's other writes, and the slot is released after it.
  • Delete: if the check cannot create or open the lock and the lock file does not exist, the deletion goes ahead. A worker only runs a task while it holds that file, so no file means no worker. If the file exists and cannot be opened, the answer stays 409, because a live worker may hold it.

Tests

Six new tests. They raise the PermissionError from a stand-in instead of using chmod, because root ignores chmod; the run above is the chmod one.

  • test_redis_queue_admission.py: the lock directory cannot be created, the lock file cannot be opened, and another process holds the lock. In the first two a second task waits in the queue: the first ends failed without its pipeline running, the slot and its entry are gone, and the second runs to completion.
  • test_controller_video.py: DELETE of a failed task over HTTP while the lock directory cannot be created returns 200, and a delete with an unusable lock returns 200 without a lock file and 409 with one.
  • test_webui_task.py: the WebUI delete of a failed task succeeds while the lock directory cannot be created.

All of them fail on 02addc5, except the 409 half of the second controller test, which passes on both.

MPT_TEST_REDIS_HOST=127.0.0.1 MPT_TEST_REDIS_PORT=6395 MPT_TEST_REDIS_DB=15 \
  python -X utf8 -m pytest -q test/services/test_redis_queue_admission.py \
  test/services/test_task_manager.py test/services/test_controller_video.py \
  test/services/test_webui_task.py test/services/test_concurrent_task_delete.py
129 passed, 52 subtests passed          (this branch)
130 passed, 52 subtests passed          (merged into main 1d7ec49, not pushed)

Both runs used the fakeredis TCP server. ruff check app cli.py main.py webui test docs/skill passes on both trees.

Limits

  • In this layout every task in Redis mode now ends failed, where main completes it. The task is recoverable, but it does not run.
  • The lock directory could live under storage/tasks instead (a dot-directory, which the WebUI task list already skips), so a layout that works on main keeps working. I left that out of this commit. Say so if you want it here.
  • A lock file that exists but cannot be opened by the deleting process keeps answering 409 until its permissions are fixed. I checked that with a chmod 000 file on macOS only.
  • If Redis cannot be reached at the moment the failure is written, the task stays in processing. I did not run that case.
  • Not run: real Redis, Linux, Windows, a process running as root.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants