What the agent does
Cancelling a Celery task means two different things depending on whether a worker has picked it up, and the agent handles each. In an app like miguelgrinberg/flask-celery-example, long_task in app.py is a bound task that loops between 10 and 50 times, sleeps one second per step and reports progress with self.update_state(state='PROGRESS', ...). POST /longtask starts it and answers 202 with a Location header pointing at /status/<task_id>, and the script in templates/index.html polls that URL every two seconds until the state is neither PENDING nor PROGRESS. There is no way to stop a task once started.
For a task still waiting in the queue, the agent calls celery.control.revoke(task_id), and a worker that later receives the message discards it. For a task that is already running it does not use revoke(..., terminate=True). That option signals the worker process, not the task, and Celery's documentation describes it as a last resort because the process may have moved on to another task by the time the signal lands. The agent makes the task cooperative. A new POST /cancel/<task_id> route sets a short-lived key in the Redis instance the app already uses as broker and result backend, and long_task checks that key at the top of each step. When it is set, the task runs its cleanup, records a CANCELLED state with the step it reached, and raises celery.exceptions.Ignore so the worker does not overwrite that state with a success.
The status route needs a fix that is easy to miss. taskstatus treats every state other than PENDING and FAILURE as a progress report and calls task.info.get(...). For a revoked task the state is REVOKED and task.info is an exception object with no get, so the first poll after a revoke would answer 500. The agent gives REVOKED and CANCELLED their own branch with a plain JSON body. It also handles a limit of Celery itself: an id the backend has never seen reports PENDING, the same as a task waiting in the queue, so the cancel route cannot tell a typo from a queued task. It answers 202 for both and says so in the pull request. In the page, each progress bar gets a Cancel button, and the existing polling loop already stops and prints the state when it sees one it does not know.
To prove it, the agent finds a Python version the 2019 and 2020 pins in requirements.txt install on, installs Redis with sudo apt-get install -y redis-server, and starts a worker with --concurrency=1, so that a second task has to wait. It starts two tasks, cancels the second while it is queued and looks in the worker log for the line that says a revoked task was discarded. It cancels the first mid-run and checks that the progress updates stop within one step and that /status/<task_id> answers CANCELLED with a 200. It repeats the sequence in the sandbox's browser with the new button. It adds pytest tests for the status route's new branch and for the task's check, with the Redis flag set before the task body is called.
Start it with one API call
POST https://api.phoenix.so/o/{org}/sessions with this body:
{
"agent": "codex",
"input": "A Linear issue moved to Ready for agent asks for a way to cancel a long-running task in this Flask and Celery app. Read requirements.txt, app.py, templates/index.html and README.md first. Add POST /cancel/<task_id>. For a task that has not started, call celery.control.revoke so a worker discards it. For a running task do not use terminate=True: set a key with a time to live in the Redis instance the app already uses, have long_task check it on every step, and when it is set record a CANCELLED state with the step reached and raise celery.exceptions.Ignore. Fix /status/<task_id> so REVOKED and CANCELLED answer 200 with a JSON body; read how it handles task.info today and say in the pull request what a revoked task would have returned. Say how the cancel route treats an id that was never issued, given that Celery reports PENDING for it. Add a Cancel button beside each progress bar in templates/index.html and make the polling stop on the new states. Do not upgrade pinned dependencies; report the Python version they install on. Install redis-server with apt, start Redis and a worker with --concurrency=1, start two tasks, cancel the queued one and the running one, and paste the worker log lines and the status responses for both. Repeat it in the browser with the button. Add pytest tests for the status branches and the cooperative check. State in the pull request that revokes are held in worker memory and what --statedb changes. Open a pull request that links the issue.",
"resources": [
{
"url": "https://github.com/your-org/your-app"
}
]
}- Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
- Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
- Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.
What comes back
The pull request changes app.py and templates/index.html and adds tests. The description separates the two cases and gives the evidence for each: for the queued task, the worker's discard line and the REVOKED status response; for the running task, the last progress update before the cancel, the absence of any after it, and the CANCELLED response with the step it stopped at. A screenshot from the sandbox's browser shows one bar stopped part-way next to one that finished.
It lists the limits. Revoked ids live in each worker's memory, so a worker that restarts before it receives a revoked message will run it; starting workers with --statedb keeps the list on disk, and the description says where that flag would go. A cooperative cancel takes effect at the next check, so a task stuck inside one long call does not stop until that call returns. The cancel route has no notion of who started a task, because this app has no users; anyone who holds a task id can cancel it.
A reviewer reads the cleanup path first, since a cancelled task that leaves half-written state is worse than one that runs to the end. Next comes the flag's time to live: it must be long enough to outlast a full queue and short enough that keys do not pile up in Redis. For tasks in your own app that do real work, the reviewer also decides where the checks belong, because the agent can only place them between steps it can see.
Run it on every Linear issue moved to Ready for agent
Some teams triage by workflow state instead of labels. A linear trigger also fires on linear.issue.state_changed: in the automation's settings, map the state name Ready for agent to exec, and each issue dragged into that column starts one run with the issue placed after the saved prompt. Mapping a state to plan instead starts a read-only run that posts its plan as a comment on the issue, which suits a column where someone wants to see the approach before any code is written.
The automation runs as the member who last changed it and needs that member's Linear connection, made in the console under Settings → Connections. It fires only when the person who moved the issue is in your Rush org. Set its max runs per hour to match how many issues a planning session moves at once; issues past the cap wait as queued runs.
The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.
Why run it on Rush?
Cancellation is a race, and races are settled by running them. Whether the queued task was discarded, whether the running one stopped at the next step or ten steps later, whether the status route survives the new state: each needs a real broker and a real worker, with the timing visible. The agent runs Redis and a single-slot worker in its sandbox, cancels at both moments and keeps the worker log and every status response in the transcript. The pull request quotes them, so the reviewer sees the ordering and does not have to reproduce it.
The 500 on a revoked task is the kind of bug a careful read might catch and a run always does. Because the agent polls the status URL after cancelling, the failure shows up as a response, not a suspicion, and the fix arrives with a test. A sandbox per run also means the experiment needs no shared staging worker, where revoking tasks would interfere with someone else's jobs.
Frequently asked questions
Why not just call revoke with terminate=True?
It kills the worker's child process with a signal. The task gets no chance to clean up, and if that process has already moved to the next task, the wrong one dies. Celery's documentation calls it a last resort for stuck tasks. A flag the task checks itself stops the right work at a point where state is consistent.
What if my task is one long database query or HTTP call with no loop?
Then there is no step to check between, and a cooperative cancel only prevents the work that comes after the call. Say so in the issue; the agent can add a timeout to the call or split the work into chunks, and the pull request states which tasks could not be made cancellable.
Does it work with RabbitMQ as the broker?
Revoking works with any broker that supports Celery's remote control commands, and RabbitMQ does. The cancel flag needs a small shared store, so with no Redis in the stack the agent uses what the project already has, such as the database or a cache, and names its choice in the description.
Will a cancelled task show up as a failure in monitoring?
No. The task records its own CANCELLED state and raises Ignore, so the worker logs neither a success nor an error for it. A revoked queued task is recorded as REVOKED. The status route reports both with a 200.