diff --git a/README.md b/README.md index c96ea40..896807c 100644 --- a/README.md +++ b/README.md @@ -558,7 +558,7 @@ async with HeartbeatManager( Starts a background task that calls `queue.heartbeat(job_id)` every `interval` seconds. The task is cancelled when the context exits. It stops silently on `JobNotFoundError` -and retries other `JQueueError`s on the next interval. +or `JobNotInProgressError`, and retries other `JQueueError`s on the next interval. ### `Job` @@ -592,6 +592,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, # job not IN_PROGRESS; .job_id, .status StorageError, # I/O failure from the storage backend; has .cause attribute ) ``` @@ -609,6 +610,9 @@ except JobNotFoundError: pass # already removed, safe to ignore ``` +`JobNotInProgressError` is raised by `heartbeat` when the job was re-queued (e.g. as +stale): the worker no longer holds it. + ## Architecture jqueue follows the **Ports & Adapters** (hexagonal) pattern: @@ -869,8 +873,9 @@ satisfying that signature works — `BrokerQueue`, `DirectQueue`, `GroupCommitLo test double. Inside the manager, a background task sleeps for `interval` seconds, then calls -`heartbeat`. On `JobNotFoundError` the task exits silently; other `JQueueError`s are -retried on the next interval. On context exit, the task is cancelled. +`heartbeat`. On `JobNotFoundError` or `JobNotInProgressError` the task exits silently; +other `JQueueError`s are retried on the next interval. On context exit, the task is +cancelled. **Tuning guidelines:** 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 951e792..5872ba0 100644 --- a/jqueue/core/heartbeat.py +++ b/jqueue/core/heartbeat.py @@ -18,8 +18,8 @@ If the worker raises, the heartbeat task is cancelled. Callers should nack() the job in an except/finally block. -The loop stops on JobNotFoundError; other JQueueErrors are retried on the -next interval. +The loop stops on JobNotFoundError or JobNotInProgressError; other +JQueueErrors are retried on the next interval. HeartbeatManager is typed against the structural Protocol _HasHeartbeat, so it works with BrokerQueue, DirectQueue, and GroupCommitLoop without any @@ -34,7 +34,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): @@ -88,8 +88,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. return except JQueueError: # Transient: retry on the next interval. diff --git a/jqueue/core/queries.py b/jqueue/core/queries.py index 09a5cfd..22b6c0f 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,13 @@ 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. """ - 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..d726801 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,15 @@ def __init__(self, job_id: str) -> None: super().__init__(f"Job {job_id!r} not found in queue state") +class JobNotInProgressError(JQueueError): + """Raised when a job must be IN_PROGRESS but is not (e.g. re-queued).""" + + 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..cd39542 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,25 @@ 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: + 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..d833b15 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,27 @@ 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: + 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 bc6c865..c5d620e 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, ) @@ -110,6 +113,35 @@ 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: + 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: + 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"))