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
15 changes: 6 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -557,8 +557,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 `JQueueError`
(e.g., the job was acked by another process), the task stops silently.
The task is cancelled when the context exits. It stops silently on `JobNotFoundError`
and retries other `JQueueError`s on the next interval.

### `Job`

Expand Down Expand Up @@ -869,10 +869,8 @@ 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 `JQueueError` (which includes `JobNotFoundError` and
`StorageError`), the task exits silently — the assumption is that the job has already
been handled or the connection is lost and there's no useful action to take. On context
exit, the task is cancelled.
`heartbeat`. On `JobNotFoundError` the task exits silently; other `JQueueError`s are
retried on the next interval. On context exit, the task is cancelled.

**Tuning guidelines:**

Expand All @@ -893,9 +891,8 @@ understand. A worker is processing a job and sending heartbeats normally. Then a
network partition separates it from storage. What happens next:

1. The `_beat` coroutine tries to send a heartbeat, which fails with `StorageError`.
2. Because `StorageError` is a subclass of `JQueueError` (`domain/errors.py:34`), the
`except JQueueError` handler catches it and the heartbeat task exits silently.
3. The worker continues processing the job, unaware that heartbeats have stopped.
2. `_beat` keeps retrying every `interval`.
3. The partition outlasts `stale_timeout`; the worker keeps processing, unaware.
4. After `stale_timeout`, `BrokerQueue` (on a different machine) requeues the job.
5. Another worker picks it up — now two workers are processing the same job.
6. When the original worker finishes and calls `ack()`, the job may no longer exist
Expand Down
10 changes: 8 additions & 2 deletions jqueue/core/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
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.

HeartbeatManager is typed against the structural Protocol _HasHeartbeat, so
it works with BrokerQueue, DirectQueue, and GroupCommitLoop without any
shared base class.
Expand All @@ -31,7 +34,7 @@
from types import TracebackType
from typing import Protocol

from jqueue.domain.errors import JQueueError
from jqueue.domain.errors import JobNotFoundError, JQueueError


class _HasHeartbeat(Protocol):
Expand Down Expand Up @@ -85,6 +88,9 @@ async def _beat(self) -> None:
await asyncio.sleep(self.interval.total_seconds())
try:
await self.queue.heartbeat(self.job_id)
except JQueueError:
except JobNotFoundError:
# Job was acked or removed — stop silently.
return
except JQueueError:
# Transient: retry on the next interval.
continue
50 changes: 44 additions & 6 deletions tests/test_heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import pytest

from jqueue.core.heartbeat import HeartbeatManager
from jqueue.domain.errors import JQueueError
from jqueue.domain.errors import (
CASConflictError,
JobNotFoundError,
JQueueError,
StorageError,
)

# ---------------------------------------------------------------------------
# Minimal queue stub
Expand Down Expand Up @@ -95,16 +100,49 @@ async def test_exception_in_body_still_cancels_task() -> None:
# ---------------------------------------------------------------------------


async def test_jqueue_error_stops_heartbeat_silently() -> None:
"""_beat() exits without raising when JQueueError is raised by queue.heartbeat."""
queue = _MockQueue(side_effect=JQueueError("job was acked"))
async def test_job_not_found_stops_heartbeat_silently() -> None:
queue = _MockQueue(side_effect=JobNotFoundError("job-1"))
async with HeartbeatManager(
queue=queue, job_id="job-1", interval=timedelta(milliseconds=5)
):
await asyncio.sleep(0.04)

# Called at least once (then stopped)
assert len(queue.calls) >= 1
assert len(queue.calls) == 1


@pytest.mark.parametrize(
"error",
[
StorageError("S3 write failed", RuntimeError("timeout")),
CASConflictError("Max CAS retries exceeded"),
JQueueError("generic"),
],
)
async def test_transient_error_does_not_stop_heartbeat(error: Exception) -> None:

class _FailOnce(_MockQueue):
async def heartbeat(self, job_id: str) -> None:
self.calls.append(job_id)
if len(self.calls) == 1:
raise error

queue = _FailOnce()
async with HeartbeatManager(
queue=queue, job_id="job-1", interval=timedelta(milliseconds=5)
):
await asyncio.sleep(0.05)

assert len(queue.calls) >= 3


async def test_persistent_transient_error_keeps_retrying() -> None:
queue = _MockQueue(side_effect=StorageError("down", RuntimeError("503")))
async with HeartbeatManager(
queue=queue, job_id="job-1", interval=timedelta(milliseconds=5)
):
await asyncio.sleep(0.05)

assert len(queue.calls) >= 3


async def test_non_jqueue_error_propagates_through_exit() -> None:
Expand Down
Loading