From 76ce948d4ad9602dbbd39e7721dd13004949e920 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:25:34 +0000 Subject: [PATCH] Release claims whose dequeue caller was cancelled If a dequeue caller was cancelled (e.g. by a timeout) after its claim reached storage, the jobs were committed IN_PROGRESS but the result was thrown away. Nobody worked them or heartbeated them, so they sat idle until the stale timeout (5 minutes by default). In GroupCommitLoop an op cancelled while still pending was also applied anyway. - StateQueries.release_claims(jobs): return jobs to QUEUED only if they are still exactly as the abandoned claim left them (IN_PROGRESS, same heartbeat), so a job heartbeated, acked or re-claimed since is left alone. Pure, never raises. - GroupCommitLoop: drop ops whose future is already done before applying them; when a dequeue is cancelled while its write is in flight, queue release_claims for its result in the next batch. - DirectQueue.dequeue: run the claim shielded; on cancellation let it finish in a tracked background task and release its jobs. --- jqueue/core/direct.py | 30 +++++++- jqueue/core/group_commit.py | 38 ++++++++++- jqueue/core/queries.py | 36 ++++++++++ tests/test_direct_queue.py | 92 +++++++++++++++++++++++++ tests/test_group_commit.py | 132 ++++++++++++++++++++++++++++++++++++ tests/test_queries.py | 49 +++++++++++++ 6 files changed, 372 insertions(+), 5 deletions(-) diff --git a/jqueue/core/direct.py b/jqueue/core/direct.py index e546d96..77eabd1 100644 --- a/jqueue/core/direct.py +++ b/jqueue/core/direct.py @@ -19,6 +19,7 @@ from __future__ import annotations import asyncio +import contextlib import dataclasses from collections.abc import Callable from datetime import UTC, datetime, timedelta @@ -48,6 +49,10 @@ class DirectQueue: storage: ObjectStoragePort max_retries: int = 10 + _cleanup: set[asyncio.Task[None]] = dataclasses.field( + default_factory=set, init=False, repr=False, compare=False + ) + # ------------------------------------------------------------------ # # Write operations # # ------------------------------------------------------------------ # @@ -73,10 +78,23 @@ async def dequeue( Optionally filter by entrypoint. Returns the list of claimed jobs. Returns an empty list if no jobs are available. + + If the caller is cancelled while the claim is in flight, the claim is + allowed to finish and its jobs are then returned to QUEUED in the + background, so they do not sit IN_PROGRESS with no worker. """ - return await self._transaction( - lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) + claim = asyncio.ensure_future( + self._transaction( + lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) + ) ) + try: + return await asyncio.shield(claim) + except asyncio.CancelledError: + task = asyncio.ensure_future(self._release_orphaned(claim)) + self._cleanup.add(task) + task.add_done_callback(self._cleanup.discard) + raise async def ack(self, job_id: str) -> None: """Mark a job as done and remove it from the queue.""" @@ -112,6 +130,14 @@ async def read_state(self) -> QueueState: # Internal CAS loop # # ------------------------------------------------------------------ # + async def _release_orphaned(self, claim: asyncio.Future[list[Job]]) -> None: + """Hand back the jobs of a claim whose caller was cancelled.""" + with contextlib.suppress(Exception): + claimed = await claim + if claimed: + await self._transaction(lambda q: q.release_claims(claimed)) + # On failure the stale sweep is the fallback. + async def _transaction[T](self, fn: Callable[[StateQueries], T]) -> T: """ Read-modify-write with CAS retry loop. diff --git a/jqueue/core/group_commit.py b/jqueue/core/group_commit.py index a5232f2..efe74db 100644 --- a/jqueue/core/group_commit.py +++ b/jqueue/core/group_commit.py @@ -22,6 +22,13 @@ ------------------------------ If one mutation in a batch raises (e.g., JobNotFoundError), that future gets the exception but the other mutations in the batch still commit normally. + +Cancellation +------------ +An op whose caller is cancelled before the batch is applied is dropped. A +dequeue whose caller is cancelled after its claim was applied has its claim +handed back (jobs returned to QUEUED) in the next batch, so the jobs do not +sit IN_PROGRESS with no worker until the stale timeout. """ from __future__ import annotations @@ -47,6 +54,7 @@ class _PendingOp[T]: fn: Callable[[StateQueries], T] future: asyncio.Future[T] + undo: Callable[[StateQueries, T], object] | None = None @dataclasses.dataclass @@ -121,7 +129,8 @@ async def dequeue( ) -> list[Job]: """Claim up to batch_size QUEUED jobs and mark them IN_PROGRESS.""" return await self._submit( - lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) + lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)), + undo=lambda q, claimed: q.release_claims(claimed), ) async def ack(self, job_id: str) -> None: @@ -145,20 +154,36 @@ async def read_state(self) -> QueueState: # Internal machinery # # ------------------------------------------------------------------ # - async def _submit[T](self, fn: Callable[[StateQueries], T]) -> T: + async def _submit[T]( + self, + fn: Callable[[StateQueries], T], + undo: Callable[[StateQueries, T], object] | None = None, + ) -> T: """ Enqueue an operation and block until it is committed. Appends the op to _pending, wakes the writer, then awaits the future that resolves when the batch containing this op successfully commits. + If the caller is cancelled after the op committed, ``undo(queries, + result)`` is submitted as a follow-up op. """ if self._stopped: raise JQueueError("GroupCommitLoop is stopped") future: asyncio.Future[T] = asyncio.get_running_loop().create_future() - self._pending.append(_PendingOp(fn=fn, future=future)) + self._pending.append(_PendingOp(fn=fn, future=future, undo=undo)) self._wakeup.set() return await future + def _submit_undo[T]( + self, undo: Callable[[StateQueries, T], object], result: T + ) -> None: + """Queue a compensating op nobody awaits (bypasses the stopped check).""" + future: asyncio.Future[object] = asyncio.get_running_loop().create_future() + # Mark any failure as retrieved; the stale sweep is the fallback. + future.add_done_callback(lambda f: f.cancelled() or f.exception()) + self._pending.append(_PendingOp(fn=lambda q: undo(q, result), future=future)) + self._wakeup.set() + async def _writer_loop(self) -> None: """Background coroutine — runs until stopped and all pending ops drain.""" while not self._stopped or self._pending: @@ -193,6 +218,9 @@ async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None: results: dict[int, Any] = {} per_op_errors: dict[int, Exception] = {} for i, op in enumerate(batch): + if op.future.done(): + # Caller cancelled before we applied it — drop it. + continue try: results[i] = op.fn(queries) except Exception as exc: @@ -205,6 +233,10 @@ async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None: for i, op in enumerate(batch): if op.future.done(): + # Cancelled while the write was in flight: the op + # committed but nobody will receive its result. + if op.undo is not None and i in results: + self._submit_undo(op.undo, results[i]) continue if i in per_op_errors: op.future.set_exception(per_op_errors[i]) diff --git a/jqueue/core/queries.py b/jqueue/core/queries.py index 120b6a2..8fb6715 100644 --- a/jqueue/core/queries.py +++ b/jqueue/core/queries.py @@ -149,6 +149,42 @@ def touch(self, job_id: str, now: datetime) -> Job: self.state = self.state.with_job_replaced(updated) return updated + def release_claims(self, claimed: list[Job]) -> list[Job]: + """ + Return jobs from an abandoned claim to QUEUED. + + Used when the caller that claimed ``claimed`` went away (was + cancelled) before receiving them. A job is released only if it is + still exactly as that claim left it — IN_PROGRESS with the claim's + heartbeat — so a job that has since been heartbeated, acked, or + re-claimed by another worker is left alone. Never raises. + + Parameters + ---------- + claimed : list[Job] + The jobs as returned by the abandoned ``claim``. + + Returns + ------- + list[Job] + The jobs that were released. + """ + state = self.state + released: list[Job] = [] + for job in claimed: + current = state.find(job.id) + if ( + current is None + or current.status != JobStatus.IN_PROGRESS + or current.heartbeat_at != job.heartbeat_at + ): + continue + updated = current.with_status(JobStatus.QUEUED).with_heartbeat(None) + state = state.with_job_replaced(updated) + released.append(updated) + self.state = state + return released + def requeue_stale(self, cutoff: datetime) -> int: """ Return IN_PROGRESS jobs with a heartbeat older than ``cutoff`` to QUEUED. diff --git a/tests/test_direct_queue.py b/tests/test_direct_queue.py index d06825a..a8a3d70 100644 --- a/tests/test_direct_queue.py +++ b/tests/test_direct_queue.py @@ -381,3 +381,95 @@ async def test_empty_dequeue_does_not_conflict_with_concurrent_writer() -> None: assert await queue.dequeue("task") == [] storage.write.assert_not_called() + + +# --------------------------------------------------------------------------- +# Cancelled dequeue does not orphan claimed jobs +# --------------------------------------------------------------------------- + + +class _GatedStorage(InMemoryStorage): + """InMemoryStorage whose writes wait on ``gate`` once ``armed``.""" + + def __post_init__(self) -> None: + super().__post_init__() + self.armed = False + self.gate = asyncio.Event() + self.write_started = asyncio.Event() + + async def write(self, content: bytes, if_match: str | None = None) -> str: + if self.armed: + self.write_started.set() + await self.gate.wait() + return await super().write(content, if_match) + + +async def _settle() -> None: + for _ in range(20): + await asyncio.sleep(0) + + +async def test_dequeue_cancelled_during_write_releases_claim() -> None: + storage = _GatedStorage() + queue = DirectQueue(storage) + job = await queue.enqueue("task", b"data") + storage.armed = True + task = asyncio.create_task(queue.dequeue("task")) + await storage.write_started.wait() + + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + storage.armed = False + storage.gate.set() + await _settle() + + assert queue._cleanup == set() + stored = (await queue.read_state()).find(job.id) + assert stored is not None + assert stored.status == JobStatus.QUEUED + assert stored.heartbeat_at is None + + +async def test_uncancelled_dequeue_keeps_claim_direct() -> None: + storage = _GatedStorage() + queue = DirectQueue(storage) + job = await queue.enqueue("task", b"data") + storage.armed = True + task = asyncio.create_task(queue.dequeue("task")) + await storage.write_started.wait() + storage.armed = False + storage.gate.set() + + [claimed] = await task + await _settle() + + assert claimed.id == job.id + stored = (await queue.read_state()).find(job.id) + assert stored is not None + assert stored.status == JobStatus.IN_PROGRESS + + +async def test_cancelled_dequeue_with_failed_claim_leaves_state_alone() -> None: + """If the in-flight claim never commits, cleanup has nothing to release.""" + storage = _GatedStorage() + queue = DirectQueue(storage, max_retries=1) + job = await queue.enqueue("task", b"data") + storage.armed = True + task = asyncio.create_task(queue.dequeue("task")) + await storage.write_started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + # A concurrent writer wins, so the gated claim hits a CAS conflict. + storage.armed = False + other = DirectQueue(storage) + await other.enqueue("task", b"other") + storage.gate.set() + await _settle() + + assert queue._cleanup == set() + state = await queue.read_state() + assert state.in_progress_jobs() == () + assert state.find(job.id) is not None diff --git a/tests/test_group_commit.py b/tests/test_group_commit.py index 978e718..82cb4f4 100644 --- a/tests/test_group_commit.py +++ b/tests/test_group_commit.py @@ -374,3 +374,135 @@ async def test_stale_sweep_alone_still_writes() -> None: assert state.jobs[0].status == JobStatus.QUEUED finally: await gcl.stop() + + +# --------------------------------------------------------------------------- +# Cancelled dequeue does not orphan claimed jobs +# --------------------------------------------------------------------------- + + +class _GatedStorage(InMemoryStorage): + """InMemoryStorage whose writes wait on ``gate`` once ``armed``.""" + + def __post_init__(self) -> None: + super().__post_init__() + self.armed = False + self.gate = asyncio.Event() + self.write_started = asyncio.Event() + + async def write(self, content: bytes, if_match: str | None = None) -> str: + if self.armed: + self.write_started.set() + await self.gate.wait() + return await super().write(content, if_match) + + +async def _settle() -> None: + for _ in range(20): + await asyncio.sleep(0) + + +async def test_dequeue_cancelled_during_write_releases_claim() -> None: + storage = _GatedStorage() + gcl = GroupCommitLoop(storage=storage) + await gcl.start() + try: + job = await gcl.enqueue("task", b"data") + storage.armed = True + task = asyncio.create_task(gcl.dequeue("task")) + await storage.write_started.wait() + + task.cancel() + storage.armed = False + storage.gate.set() + with pytest.raises(asyncio.CancelledError): + await task + await _settle() + + stored = (await gcl.read_state()).find(job.id) + assert stored is not None + assert stored.status == JobStatus.QUEUED + assert stored.heartbeat_at is None + # Nothing was lost: another worker can claim it right away. + [claimed] = await gcl.dequeue("task") + assert claimed.id == job.id + finally: + await gcl.stop() + + +async def test_op_cancelled_before_apply_is_dropped() -> None: + storage = _GatedStorage() + gcl = GroupCommitLoop(storage=storage) + await gcl.start() + try: + await gcl.enqueue("task", b"first") + storage.armed = True + # Occupy the writer so the next ops wait in _pending. + blocker = asyncio.create_task(gcl.enqueue("task", b"blocker")) + await storage.write_started.wait() + cancelled_dequeue = asyncio.create_task(gcl.dequeue("task")) + cancelled_enqueue = asyncio.create_task(gcl.enqueue("task", b"never")) + await _settle() + cancelled_dequeue.cancel() + cancelled_enqueue.cancel() + await _settle() + + storage.armed = False + storage.gate.set() + await blocker + await _settle() + + state = await gcl.read_state() + assert state.in_progress_jobs() == () + assert sorted(j.payload for j in state.jobs) == [b"blocker", b"first"] + finally: + await gcl.stop() + + +async def test_uncancelled_dequeue_keeps_claim() -> None: + storage = _GatedStorage() + gcl = GroupCommitLoop(storage=storage) + await gcl.start() + try: + job = await gcl.enqueue("task", b"data") + storage.armed = True + task = asyncio.create_task(gcl.dequeue("task")) + await storage.write_started.wait() + storage.armed = False + storage.gate.set() + + [claimed] = await task + await _settle() + + assert claimed.id == job.id + stored = (await gcl.read_state()).find(job.id) + assert stored is not None + assert stored.status == JobStatus.IN_PROGRESS + finally: + await gcl.stop() + + +async def test_cancelled_dequeue_does_not_release_job_heartbeated_since() -> None: + """The compensating release only touches jobs still as the claim left them.""" + storage = _GatedStorage() + gcl = GroupCommitLoop(storage=storage) + await gcl.start() + try: + job = await gcl.enqueue("task", b"data") + storage.armed = True + task = asyncio.create_task(gcl.dequeue("task")) + await storage.write_started.wait() + task.cancel() + # Queued behind the in-flight write, ahead of the compensating op. + hb = asyncio.create_task(gcl.heartbeat(job.id)) + await _settle() + storage.armed = False + storage.gate.set() + await hb + await _settle() + + stored = (await gcl.read_state()).find(job.id) + assert stored is not None + assert stored.status == JobStatus.IN_PROGRESS + finally: + await gcl.stop() diff --git a/tests/test_queries.py b/tests/test_queries.py index 570de3f..89a922f 100644 --- a/tests/test_queries.py +++ b/tests/test_queries.py @@ -123,6 +123,55 @@ def test_missing_job_raises_and_leaves_state_unchanged(op: str) -> None: assert q.state is before +# --------------------------------------------------------------------------- +# release_claims +# --------------------------------------------------------------------------- + + +def test_release_claims_returns_untouched_claim_to_queued() -> None: + q = _queries(Job.new("task", b"a"), Job.new("task", b"b")) + claimed = q.claim(None, 2, NOW) + + released = q.release_claims(claimed) + + assert [j.id for j in released] == [j.id for j in claimed] + assert q.state.in_progress_jobs() == () + assert all(j.heartbeat_at is None for j in q.state.jobs) + + +def test_release_claims_skips_job_heartbeated_since() -> None: + q = _queries(Job.new("task", b"a")) + [claimed] = q.claim(None, 1, NOW) + q.touch(claimed.id, NOW + timedelta(seconds=5)) + before = q.state + + assert q.release_claims([claimed]) == [] + assert q.state is before + + +def test_release_claims_skips_job_reclaimed_by_another_worker() -> None: + q = _queries(Job.new("task", b"a")) + [claimed] = q.claim(None, 1, NOW) + q.requeue_stale(NOW + timedelta(seconds=1)) + [reclaimed] = q.claim(None, 1, NOW + timedelta(seconds=2)) + + assert q.release_claims([claimed]) == [] + stored = q.find(reclaimed.id) + assert stored == reclaimed + + +def test_release_claims_skips_missing_and_queued_jobs() -> None: + kept = Job.new("task", b"a") + q = _queries(kept) + [claimed] = q.claim(None, 1, NOW) + q.release(claimed.id) + gone = Job.new("task", b"gone").with_status(JobStatus.IN_PROGRESS) + before = q.state + + assert q.release_claims([claimed, gone]) == [] + assert q.state is before + + # --------------------------------------------------------------------------- # requeue_stale # ---------------------------------------------------------------------------