From f29b14a8015d3d39d232f0413f545b753bc024d5 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:18:00 +0000 Subject: [PATCH 1/2] Keep HeartbeatManager beating through transient errors _beat() caught JQueueError and returned. StorageError and CASConflictError are JQueueErrors too, so a single storage blip or exhausted CAS retries stopped heartbeats permanently and silently. The job then went stale and was re-queued while the worker was still running it, leading to duplicate execution. Stop only on JobNotFoundError (job acked/removed); skip the beat and retry on the next interval for any other JQueueError. --- README.md | 21 +++++++++------- jqueue/core/heartbeat.py | 13 ++++++++-- tests/test_heartbeat.py | 53 +++++++++++++++++++++++++++++++++++----- 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 9839778..3062755 100644 --- a/README.md +++ b/README.md @@ -557,8 +557,10 @@ 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. If `heartbeat` raises `JobNotFoundError` +(e.g., the job was acked by another process), 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. ### `Job` @@ -869,10 +871,11 @@ 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`. If the call raises `JobNotFoundError`, the task exits silently — the job +has already been handled. 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. **Tuning guidelines:** @@ -893,9 +896,9 @@ 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. The failure is treated as transient; `_beat` keeps retrying every `interval`. +3. The partition outlasts `stale_timeout`, so no heartbeat lands in time. The worker + continues processing the job, unaware that its heartbeats are not getting through. 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 diff --git a/jqueue/core/heartbeat.py b/jqueue/core/heartbeat.py index 4e139a2..2250524 100644 --- a/jqueue/core/heartbeat.py +++ b/jqueue/core/heartbeat.py @@ -18,6 +18,11 @@ 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). +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. + HeartbeatManager is typed against the structural Protocol _HasHeartbeat, so it works with BrokerQueue, DirectQueue, and GroupCommitLoop without any shared base class. @@ -31,7 +36,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): @@ -85,6 +90,10 @@ 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 (storage failure, CAS retries exhausted) — retry + # on the next interval rather than letting the job go stale. + continue diff --git a/tests/test_heartbeat.py b/tests/test_heartbeat.py index 7ba9791..aefffc0 100644 --- a/tests/test_heartbeat.py +++ b/tests/test_heartbeat.py @@ -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 @@ -95,16 +100,52 @@ 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: + """_beat() exits without raising once the job is gone.""" + 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: + """A transient JQueueError skips one beat; later beats are still sent.""" + + 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: + """Heartbeats keep being attempted while storage stays unavailable.""" + 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: From fd9578ebbd7bfdd3c42411c29af002637d7fa82a Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:47:56 +0000 Subject: [PATCH 2/2] Trim comments and docstrings --- README.md | 18 ++++++------------ jqueue/core/heartbeat.py | 9 +++------ tests/test_heartbeat.py | 3 --- 3 files changed, 9 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 3062755..c96ea40 100644 --- a/README.md +++ b/README.md @@ -557,10 +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 `JobNotFoundError` -(e.g., the job was acked by another process), 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. +The task is cancelled when the context exits. It stops silently on `JobNotFoundError` +and retries other `JQueueError`s on the next interval. ### `Job` @@ -871,11 +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 `JobNotFoundError`, the task exits silently — the job -has already been handled. 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. +`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:** @@ -896,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. The failure is treated as transient; `_beat` keeps retrying every `interval`. -3. The partition outlasts `stale_timeout`, so no heartbeat lands in time. The worker - continues processing the job, unaware that its heartbeats are not getting through. +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 diff --git a/jqueue/core/heartbeat.py b/jqueue/core/heartbeat.py index 2250524..951e792 100644 --- a/jqueue/core/heartbeat.py +++ b/jqueue/core/heartbeat.py @@ -18,10 +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). -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. +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 @@ -94,6 +92,5 @@ async def _beat(self) -> None: # Job was acked or removed — stop silently. return except JQueueError: - # Transient (storage failure, CAS retries exhausted) — retry - # on the next interval rather than letting the job go stale. + # Transient: retry on the next interval. continue diff --git a/tests/test_heartbeat.py b/tests/test_heartbeat.py index aefffc0..bc6c865 100644 --- a/tests/test_heartbeat.py +++ b/tests/test_heartbeat.py @@ -101,7 +101,6 @@ async def test_exception_in_body_still_cancels_task() -> None: async def test_job_not_found_stops_heartbeat_silently() -> None: - """_beat() exits without raising once the job is gone.""" queue = _MockQueue(side_effect=JobNotFoundError("job-1")) async with HeartbeatManager( queue=queue, job_id="job-1", interval=timedelta(milliseconds=5) @@ -120,7 +119,6 @@ async def test_job_not_found_stops_heartbeat_silently() -> None: ], ) async def test_transient_error_does_not_stop_heartbeat(error: Exception) -> None: - """A transient JQueueError skips one beat; later beats are still sent.""" class _FailOnce(_MockQueue): async def heartbeat(self, job_id: str) -> None: @@ -138,7 +136,6 @@ async def heartbeat(self, job_id: str) -> None: async def test_persistent_transient_error_keeps_retrying() -> None: - """Heartbeats keep being attempted while storage stays unavailable.""" queue = _MockQueue(side_effect=StorageError("down", RuntimeError("503"))) async with HeartbeatManager( queue=queue, job_id="job-1", interval=timedelta(milliseconds=5)