From e9a8c0e8d104131c1b1155787dbd797d4dfd5f16 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:20:17 +0000 Subject: [PATCH] Reject heartbeats on jobs that are not IN_PROGRESS touch() only checked that the job existed. After the stale sweep re-queued a job, the original worker's heartbeat still succeeded: it stamped heartbeat_at on a QUEUED job and HeartbeatManager kept beating, so the worker never learned it had lost the claim while another worker could pick the job up. BrokerQueue hits this by timing alone, since each batch sweeps stale jobs before applying the heartbeats in that batch. Raise the new JobNotInProgressError from touch() when the job is not IN_PROGRESS, leaving state unchanged, and stop HeartbeatManager on it. --- README.md | 13 ++++++++++--- jqueue/__init__.py | 2 ++ jqueue/core/heartbeat.py | 9 +++++---- jqueue/core/queries.py | 12 +++++++++--- jqueue/domain/errors.py | 22 ++++++++++++++++++++++ tests/test_broker_queue.py | 23 ++++++++++++++++++++++- tests/test_direct_queue.py | 28 +++++++++++++++++++++++++++- tests/test_domain_errors.py | 10 ++++++++++ tests/test_heartbeat.py | 34 ++++++++++++++++++++++++++++++++++ tests/test_queries.py | 26 +++++++++++++++++++++++++- 10 files changed, 166 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 3062755..3a29313 100644 --- a/README.md +++ b/README.md @@ -558,7 +558,8 @@ async with HeartbeatManager( Starts a background task that calls `queue.heartbeat(job_id)` every `interval` seconds. The task is cancelled when the context exits. If `heartbeat` raises `JobNotFoundError` -(e.g., the job was acked by another process), the task stops silently. Other +(e.g., the job was acked by another process) or `JobNotInProgressError` (the job went +stale and was re-queued, so this worker lost its claim), the task stops silently. Other `JQueueError`s (`StorageError`, `CASConflictError`) are treated as transient: that beat is skipped and the next one is attempted on schedule. @@ -594,6 +595,7 @@ from jqueue import ( JQueueError, # base class, catches all jqueue errors CASConflictError, # CAS write rejected (etag mismatch), usually retried internally JobNotFoundError, # job_id not in current state; has .job_id attribute + JobNotInProgressError, # heartbeat on a job that is not IN_PROGRESS; .job_id, .status StorageError, # I/O failure from the storage backend; has .cause attribute ) ``` @@ -611,6 +613,10 @@ except JobNotFoundError: pass # already removed, safe to ignore ``` +`JobNotInProgressError` is raised by `heartbeat` when the job exists but is no longer +`IN_PROGRESS` — typically because it went stale and the sweep re-queued it. The worker +no longer holds the job and another worker may pick it up. + ## Architecture jqueue follows the **Ports & Adapters** (hexagonal) pattern: @@ -871,8 +877,9 @@ satisfying that signature works — `BrokerQueue`, `DirectQueue`, `GroupCommitLo test double. Inside the manager, a background task sleeps for `interval` seconds, then calls -`heartbeat`. If the call raises `JobNotFoundError`, the task exits silently — the job -has already been handled. Any other `JQueueError` (`StorageError`, `CASConflictError`) +`heartbeat`. If the call raises `JobNotFoundError` or `JobNotInProgressError`, the task +exits silently — the job has already been handled, or was re-queued and is no longer +this worker's. Any other `JQueueError` (`StorageError`, `CASConflictError`) is treated as transient: the beat is skipped and retried on the next interval, so a single storage blip doesn't let a healthy job go stale. On context exit, the task is cancelled. diff --git a/jqueue/__init__.py b/jqueue/__init__.py index a6bb1e5..5622e58 100644 --- a/jqueue/__init__.py +++ b/jqueue/__init__.py @@ -68,6 +68,7 @@ async def write(content, if_match=None) -> str from jqueue.domain.errors import ( CASConflictError, JobNotFoundError, + JobNotInProgressError, JQueueError, StorageError, ) @@ -90,6 +91,7 @@ async def write(content, if_match=None) -> str "JQueueError", "CASConflictError", "JobNotFoundError", + "JobNotInProgressError", "StorageError", # Port (for typing custom adapters) "ObjectStoragePort", diff --git a/jqueue/core/heartbeat.py b/jqueue/core/heartbeat.py index 2250524..8be3f88 100644 --- a/jqueue/core/heartbeat.py +++ b/jqueue/core/heartbeat.py @@ -18,7 +18,8 @@ If the worker raises, the heartbeat task is cancelled. Callers should nack() the job in an except/finally block. -The heartbeat loop stops when the job no longer exists (JobNotFoundError). +The heartbeat loop stops when the job no longer exists (JobNotFoundError) +or is no longer IN_PROGRESS (JobNotInProgressError — the claim was lost). Other JQueueErrors — StorageError, CASConflictError — are treated as transient: the beat is skipped and retried on the next interval, so a single storage blip does not let the job go stale. @@ -36,7 +37,7 @@ from types import TracebackType from typing import Protocol -from jqueue.domain.errors import JobNotFoundError, JQueueError +from jqueue.domain.errors import JobNotFoundError, JobNotInProgressError, JQueueError class _HasHeartbeat(Protocol): @@ -90,8 +91,8 @@ async def _beat(self) -> None: await asyncio.sleep(self.interval.total_seconds()) try: await self.queue.heartbeat(self.job_id) - except JobNotFoundError: - # Job was acked or removed — stop silently. + except (JobNotFoundError, JobNotInProgressError): + # Job was acked, removed, or re-queued — stop silently. return except JQueueError: # Transient (storage failure, CAS retries exhausted) — retry diff --git a/jqueue/core/queries.py b/jqueue/core/queries.py index 09a5cfd..120b6a2 100644 --- a/jqueue/core/queries.py +++ b/jqueue/core/queries.py @@ -10,7 +10,7 @@ import dataclasses from datetime import datetime -from jqueue.domain.errors import JobNotFoundError +from jqueue.domain.errors import JobNotFoundError, JobNotInProgressError from jqueue.domain.models import Job, JobStatus, QueueState @@ -127,7 +127,7 @@ def release(self, job_id: str) -> Job: def touch(self, job_id: str, now: datetime) -> Job: """ - Set a job's heartbeat timestamp. + Set the heartbeat timestamp of an IN_PROGRESS job. Returns ------- @@ -138,8 +138,14 @@ def touch(self, job_id: str, now: datetime) -> Job: ------ JobNotFoundError If no job with ``job_id`` exists. + JobNotInProgressError + If the job is not IN_PROGRESS (e.g. it went stale and was + re-queued), so the caller no longer holds it. """ - updated = self._require(job_id).with_heartbeat(now) + job = self._require(job_id) + if job.status != JobStatus.IN_PROGRESS: + raise JobNotInProgressError(job_id, job.status) + updated = job.with_heartbeat(now) self.state = self.state.with_job_replaced(updated) return updated diff --git a/jqueue/domain/errors.py b/jqueue/domain/errors.py index 78228e9..cdb26af 100644 --- a/jqueue/domain/errors.py +++ b/jqueue/domain/errors.py @@ -4,6 +4,7 @@ JQueueError ├── CASConflictError — write rejected because etag did not match ├── JobNotFoundError — job_id not present in current QueueState +├── JobNotInProgressError — job exists but is not IN_PROGRESS └── StorageError — underlying I/O failure (wraps original exception) """ @@ -31,6 +32,27 @@ def __init__(self, job_id: str) -> None: super().__init__(f"Job {job_id!r} not found in queue state") +class JobNotInProgressError(JQueueError): + """ + Raised when an operation requires an IN_PROGRESS job but the job is not. + + Typically means the worker lost its claim: the job went stale and was + re-queued by the sweep. + + Attributes + ---------- + job_id : str + The job that was not IN_PROGRESS. + status : str + The job's actual status. + """ + + def __init__(self, job_id: str, status: str) -> None: + self.job_id = job_id + self.status = str(status) + super().__init__(f"Job {job_id!r} is {self.status!r}, not in_progress") + + class StorageError(JQueueError): """ Wraps an underlying I/O failure from a storage adapter. diff --git a/tests/test_broker_queue.py b/tests/test_broker_queue.py index 896ef09..fa4ed6f 100644 --- a/tests/test_broker_queue.py +++ b/tests/test_broker_queue.py @@ -1,10 +1,11 @@ import asyncio +from datetime import timedelta import pytest from jqueue.adapters.storage.memory import InMemoryStorage from jqueue.core.broker import BrokerQueue -from jqueue.domain.errors import JobNotFoundError +from jqueue.domain.errors import JobNotFoundError, JobNotInProgressError from jqueue.domain.models import JobStatus # --------------------------------------------------------------------------- @@ -143,6 +144,26 @@ async def test_heartbeat_missing_job_raises() -> None: await q.heartbeat("nonexistent") +async def test_heartbeat_queued_job_raises() -> None: + async with BrokerQueue(InMemoryStorage()) as q: + job = await q.enqueue("task", b"data") + with pytest.raises(JobNotInProgressError): + await q.heartbeat(job.id) + + +async def test_heartbeat_swept_in_same_batch_raises() -> None: + """The batch sweep runs before ops; a heartbeat it overtakes must fail.""" + async with BrokerQueue(InMemoryStorage(), stale_timeout=timedelta(0)) as q: + await q.enqueue("task", b"data") + [job] = await q.dequeue("task") + with pytest.raises(JobNotInProgressError): + await q.heartbeat(job.id) + stored = (await q.read_state()).find(job.id) + assert stored is not None + assert stored.status == JobStatus.QUEUED + assert stored.heartbeat_at is None + + # --------------------------------------------------------------------------- # read_state # --------------------------------------------------------------------------- diff --git a/tests/test_direct_queue.py b/tests/test_direct_queue.py index 2c231eb..cf0359f 100644 --- a/tests/test_direct_queue.py +++ b/tests/test_direct_queue.py @@ -6,7 +6,11 @@ from jqueue.adapters.storage.memory import InMemoryStorage from jqueue.core.direct import DirectQueue -from jqueue.domain.errors import CASConflictError, JobNotFoundError +from jqueue.domain.errors import ( + CASConflictError, + JobNotFoundError, + JobNotInProgressError, +) from jqueue.domain.models import JobStatus # --------------------------------------------------------------------------- @@ -191,6 +195,28 @@ async def test_heartbeat_missing_job_raises(queue: DirectQueue) -> None: await queue.heartbeat("nonexistent-id") +async def test_heartbeat_queued_job_raises(queue: DirectQueue) -> None: + job = await queue.enqueue("task", b"data") + with pytest.raises(JobNotInProgressError): + await queue.heartbeat(job.id) + stored = (await queue.read_state()).find(job.id) + assert stored is not None + assert stored.heartbeat_at is None + + +async def test_heartbeat_after_stale_requeue_raises(queue: DirectQueue) -> None: + """A worker whose claim was swept must be told, not silently kept alive.""" + await queue.enqueue("task", b"data") + [job] = await queue.dequeue("task") + assert await queue.requeue_stale(timedelta(seconds=-1)) == 1 + with pytest.raises(JobNotInProgressError): + await queue.heartbeat(job.id) + stored = (await queue.read_state()).find(job.id) + assert stored is not None + assert stored.status == JobStatus.QUEUED + assert stored.heartbeat_at is None + + # --------------------------------------------------------------------------- # requeue_stale # --------------------------------------------------------------------------- diff --git a/tests/test_domain_errors.py b/tests/test_domain_errors.py index d650256..0cb0b87 100644 --- a/tests/test_domain_errors.py +++ b/tests/test_domain_errors.py @@ -3,6 +3,7 @@ from jqueue.domain.errors import ( CASConflictError, JobNotFoundError, + JobNotInProgressError, JQueueError, StorageError, ) @@ -59,3 +60,12 @@ def test_storage_error_message_format(): msg = str(err) assert "GCS read failed" in msg assert "permission denied" in msg + + +def test_job_not_in_progress_stores_job_id_and_status(): + err = JobNotInProgressError("abc-123", "queued") + assert isinstance(err, JQueueError) + assert not isinstance(err, JobNotFoundError) + assert err.job_id == "abc-123" + assert err.status == "queued" + assert str(err) == "Job 'abc-123' is 'queued', not in_progress" diff --git a/tests/test_heartbeat.py b/tests/test_heartbeat.py index aefffc0..4e5fc6b 100644 --- a/tests/test_heartbeat.py +++ b/tests/test_heartbeat.py @@ -3,10 +3,13 @@ import pytest +from jqueue.adapters.storage.memory import InMemoryStorage +from jqueue.core.direct import DirectQueue from jqueue.core.heartbeat import HeartbeatManager from jqueue.domain.errors import ( CASConflictError, JobNotFoundError, + JobNotInProgressError, JQueueError, StorageError, ) @@ -111,6 +114,37 @@ async def test_job_not_found_stops_heartbeat_silently() -> None: assert len(queue.calls) == 1 +async def test_job_not_in_progress_stops_heartbeat_silently() -> None: + """_beat() exits once the claim is lost (job re-queued).""" + queue = _MockQueue(side_effect=JobNotInProgressError("job-1", "queued")) + async with HeartbeatManager( + queue=queue, job_id="job-1", interval=timedelta(milliseconds=5) + ): + await asyncio.sleep(0.04) + + assert len(queue.calls) == 1 + + +async def test_heartbeat_stops_after_real_stale_requeue() -> None: + """End to end: a swept job stops its HeartbeatManager instead of reviving it.""" + queue = DirectQueue(InMemoryStorage()) + await queue.enqueue("task", b"data") + [job] = await queue.dequeue("task") + await queue.requeue_stale(timedelta(seconds=-1)) + + hb = HeartbeatManager( + queue=queue, job_id=job.id, interval=timedelta(milliseconds=5) + ) + async with hb: + await asyncio.sleep(0.04) + assert hb._task is not None + assert hb._task.done() + + stored = (await queue.read_state()).find(job.id) + assert stored is not None + assert stored.heartbeat_at is None + + @pytest.mark.parametrize( "error", [ diff --git a/tests/test_queries.py b/tests/test_queries.py index 08f8892..570de3f 100644 --- a/tests/test_queries.py +++ b/tests/test_queries.py @@ -3,7 +3,7 @@ import pytest from jqueue.core.queries import StateQueries -from jqueue.domain.errors import JobNotFoundError +from jqueue.domain.errors import JobNotFoundError, JobNotInProgressError from jqueue.domain.models import Job, JobStatus, QueueState NOW = datetime(2024, 1, 1, tzinfo=UTC) @@ -83,10 +83,34 @@ def test_release_returns_job_to_queued() -> None: def test_touch_updates_heartbeat() -> None: job = Job.new("task", b"data") q = _queries(job) + q.claim(None, 1, NOW) later = NOW + timedelta(seconds=30) assert q.touch(job.id, later).heartbeat_at == later +def test_touch_queued_job_raises_and_leaves_state_unchanged() -> None: + job = Job.new("task", b"data") + q = _queries(job) + before = q.state + with pytest.raises(JobNotInProgressError) as exc_info: + q.touch(job.id, NOW) + assert exc_info.value.job_id == job.id + assert exc_info.value.status == JobStatus.QUEUED + assert q.state is before + + +def test_touch_after_stale_requeue_raises() -> None: + job = Job.new("task", b"data") + q = _queries(job) + q.claim(None, 1, NOW) + q.requeue_stale(NOW + timedelta(seconds=1)) + with pytest.raises(JobNotInProgressError): + q.touch(job.id, NOW + timedelta(seconds=2)) + stored = q.find(job.id) + assert stored is not None + assert stored.heartbeat_at is None + + @pytest.mark.parametrize("op", ["remove", "release", "touch"]) def test_missing_job_raises_and_leaves_state_unchanged(op: str) -> None: q = _queries(Job.new("task", b"data"))