Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down Expand Up @@ -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
)
```
Expand All @@ -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:
Expand Down Expand Up @@ -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:**

Expand Down
2 changes: 2 additions & 0 deletions jqueue/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ async def write(content, if_match=None) -> str
from jqueue.domain.errors import (
CASConflictError,
JobNotFoundError,
JobNotInProgressError,
JQueueError,
StorageError,
)
Expand All @@ -90,6 +91,7 @@ async def write(content, if_match=None) -> str
"JQueueError",
"CASConflictError",
"JobNotFoundError",
"JobNotInProgressError",
"StorageError",
# Port (for typing custom adapters)
"ObjectStoragePort",
Expand Down
10 changes: 5 additions & 5 deletions jqueue/core/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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.
Expand Down
11 changes: 8 additions & 3 deletions jqueue/core/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
-------
Expand All @@ -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

Expand Down
10 changes: 10 additions & 0 deletions jqueue/domain/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
"""

Expand Down Expand Up @@ -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.
Expand Down
22 changes: 21 additions & 1 deletion tests/test_broker_queue.py
Original file line number Diff line number Diff line change
@@ -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

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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
# ---------------------------------------------------------------------------
Expand Down
27 changes: 26 additions & 1 deletion tests/test_direct_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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
# ---------------------------------------------------------------------------
Expand Down
10 changes: 10 additions & 0 deletions tests/test_domain_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from jqueue.domain.errors import (
CASConflictError,
JobNotFoundError,
JobNotInProgressError,
JQueueError,
StorageError,
)
Expand Down Expand Up @@ -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"
32 changes: 32 additions & 0 deletions tests/test_heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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",
[
Expand Down
26 changes: 25 additions & 1 deletion tests/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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"))
Expand Down
Loading