▮ REFACTORED PATCH
# FIX 1 — cancel() must set state=CANCELLED for in-flight jobs too:
async def cancel(self, job_id):
async with self._lock:
job = self._jobs.get(job_id)
if job is None: raise KeyError(f"Unknown job: {job_id}")
if job.state in (COMPLETED, FAILED, CANCELLED): return
job._cancelled = True
job.state = JobState.CANCELLED # set for BOTH queued AND in-flight
await self._notify(job, "cancelled")
# FIX 2 — gate cancellation checks on the flag, not the state:
# replace every `if job._cancelled and job.state == JobState.CANCELLED`
# with `if job._cancelled:`.
# FIX 3 — track spawned tasks and cancel them on stop():
# __init__: self._tasks = set()
# _worker_loop:
# t = asyncio.create_task(self._process_job(job))
# self._tasks.add(t); t.add_done_callback(self._tasks.discard)
# stop():
# for t in list(self._tasks): t.cancel()
# await asyncio.gather(*self._tasks, return_exceptions=True)
# FIX 4 — don't self-DOS the backpressure test: use max_concurrency=1 AND
# max_queue_size=10, submit 11, assert 11th rejected, then stop WITHOUT draining.