From 1130a90e8e5b9d9e1c090b941682ccf111f1f634 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:26:14 +0000 Subject: [PATCH] Reject dequeue batch_size < 1 claim() sliced queued_jobs(...)[:batch_size] without validating it, so batch_size=-1 claimed every queued job except the last, and other negative values claimed similarly surprising amounts. batch_size=0 did a full read/write round trip to claim nothing. Add check_batch_size() and raise ValueError for batch_size < 1 from StateQueries.claim and, before any I/O, from DirectQueue.dequeue and GroupCommitLoop.dequeue (and so BrokerQueue.dequeue). --- jqueue/core/direct.py | 5 ++++- jqueue/core/group_commit.py | 9 +++++++-- jqueue/core/queries.py | 21 ++++++++++++++++++++- tests/test_broker_queue.py | 9 +++++++++ tests/test_direct_queue.py | 28 +++++++++++++++++++++++++++- tests/test_group_commit.py | 26 ++++++++++++++++++++++++++ tests/test_queries.py | 14 ++++++++++++++ 7 files changed, 107 insertions(+), 5 deletions(-) diff --git a/jqueue/core/direct.py b/jqueue/core/direct.py index 77eabd1..4cf6114 100644 --- a/jqueue/core/direct.py +++ b/jqueue/core/direct.py @@ -25,7 +25,7 @@ from datetime import UTC, datetime, timedelta from jqueue.core import codec -from jqueue.core.queries import StateQueries +from jqueue.core.queries import StateQueries, check_batch_size from jqueue.domain.errors import CASConflictError from jqueue.domain.models import Job, QueueState from jqueue.ports.storage import ObjectStoragePort @@ -82,7 +82,10 @@ async def dequeue( If the caller is cancelled while the claim is in flight, the claim is allowed to finish and its jobs are then returned to QUEUED in the background, so they do not sit IN_PROGRESS with no worker. + + Raises ValueError if ``batch_size`` is less than 1. """ + check_batch_size(batch_size) claim = asyncio.ensure_future( self._transaction( lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) diff --git a/jqueue/core/group_commit.py b/jqueue/core/group_commit.py index efe74db..a9ed9ee 100644 --- a/jqueue/core/group_commit.py +++ b/jqueue/core/group_commit.py @@ -40,7 +40,7 @@ from typing import Any from jqueue.core import codec -from jqueue.core.queries import StateQueries +from jqueue.core.queries import StateQueries, check_batch_size from jqueue.domain.errors import CASConflictError, JQueueError from jqueue.domain.models import Job, QueueState from jqueue.ports.storage import ObjectStoragePort @@ -127,7 +127,12 @@ async def dequeue( *, batch_size: int = 1, ) -> list[Job]: - """Claim up to batch_size QUEUED jobs and mark them IN_PROGRESS.""" + """ + Claim up to batch_size QUEUED jobs and mark them IN_PROGRESS. + + Raises ValueError if ``batch_size`` is less than 1. + """ + check_batch_size(batch_size) return await self._submit( lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)), undo=lambda q, claimed: q.release_claims(claimed), diff --git a/jqueue/core/queries.py b/jqueue/core/queries.py index 8fb6715..eee36ba 100644 --- a/jqueue/core/queries.py +++ b/jqueue/core/queries.py @@ -14,6 +14,19 @@ from jqueue.domain.models import Job, JobStatus, QueueState +def check_batch_size(batch_size: int) -> None: + """ + Validate a dequeue ``batch_size``. + + Raises + ------ + ValueError + If ``batch_size`` is less than 1. + """ + if batch_size < 1: + raise ValueError(f"batch_size must be >= 1, got {batch_size}") + + @dataclasses.dataclass class StateQueries: """ @@ -69,7 +82,7 @@ def claim( entrypoint : str | None Only claim jobs for this entrypoint; None claims from any. batch_size : int - Maximum number of jobs to claim. + Maximum number of jobs to claim; must be >= 1. now : datetime Heartbeat timestamp for the claimed jobs. @@ -77,7 +90,13 @@ def claim( ------- list[Job] The claimed jobs, in priority order. Empty if none are available. + + Raises + ------ + ValueError + If ``batch_size`` is less than 1. """ + check_batch_size(batch_size) state = self.state claimed: list[Job] = [] for job in state.queued_jobs(entrypoint)[:batch_size]: diff --git a/tests/test_broker_queue.py b/tests/test_broker_queue.py index fa4ed6f..a063f98 100644 --- a/tests/test_broker_queue.py +++ b/tests/test_broker_queue.py @@ -219,3 +219,12 @@ async def test_enqueue_dequeue_nack_requeue_workflow() -> None: [retry] = await q.dequeue("task") assert retry.id == job.id assert retry.status == JobStatus.IN_PROGRESS + + +async def test_dequeue_rejects_negative_batch_size() -> None: + async with BrokerQueue(InMemoryStorage()) as q: + for _ in range(5): + await q.enqueue("task", b"x") + with pytest.raises(ValueError): + await q.dequeue("task", batch_size=-1) + assert (await q.read_state()).in_progress_jobs() == () diff --git a/tests/test_direct_queue.py b/tests/test_direct_queue.py index a8a3d70..e1087f6 100644 --- a/tests/test_direct_queue.py +++ b/tests/test_direct_queue.py @@ -322,7 +322,6 @@ async def test_empty_dequeue_does_not_write() -> None: _, etag_before = await storage.read() assert await queue.dequeue("other") == [] - assert await queue.dequeue("task", batch_size=0) == [] _, etag_after = await storage.read() assert storage.writes == 1 @@ -473,3 +472,30 @@ async def test_cancelled_dequeue_with_failed_claim_leaves_state_alone() -> None: state = await queue.read_state() assert state.in_progress_jobs() == () assert state.find(job.id) is not None + + +# --------------------------------------------------------------------------- +# batch_size validation +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("batch_size", [0, -1, -100]) +async def test_dequeue_rejects_non_positive_batch_size(batch_size: int) -> None: + storage = AsyncMock(wraps=InMemoryStorage()) + queue = DirectQueue(storage) + await queue.enqueue("task", b"a") + await queue.enqueue("task", b"b") + storage.reset_mock() + + with pytest.raises(ValueError, match="batch_size must be >= 1"): + await queue.dequeue("task", batch_size=batch_size) + + storage.read.assert_not_called() + storage.write.assert_not_called() + assert (await queue.read_state()).in_progress_jobs() == () + + +async def test_dequeue_batch_size_one_is_accepted(queue: DirectQueue) -> None: + await queue.enqueue("task", b"a") + await queue.enqueue("task", b"b") + assert len(await queue.dequeue("task", batch_size=1)) == 1 diff --git a/tests/test_group_commit.py b/tests/test_group_commit.py index 82cb4f4..3014138 100644 --- a/tests/test_group_commit.py +++ b/tests/test_group_commit.py @@ -506,3 +506,29 @@ async def test_cancelled_dequeue_does_not_release_job_heartbeated_since() -> Non assert stored.status == JobStatus.IN_PROGRESS finally: await gcl.stop() + + +# --------------------------------------------------------------------------- +# batch_size validation +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("batch_size", [0, -1]) +async def test_dequeue_rejects_non_positive_batch_size( + loop: GroupCommitLoop, batch_size: int +) -> None: + await loop.enqueue("task", b"a") + await loop.enqueue("task", b"b") + + with pytest.raises(ValueError, match="batch_size must be >= 1"): + await loop.dequeue("task", batch_size=batch_size) + + assert loop._pending == [] + assert (await loop.read_state()).in_progress_jobs() == () + + +async def test_dequeue_batch_size_larger_than_queue_is_accepted( + loop: GroupCommitLoop, +) -> None: + await loop.enqueue("task", b"a") + assert len(await loop.dequeue("task", batch_size=50)) == 1 diff --git a/tests/test_queries.py b/tests/test_queries.py index 89a922f..8ba258f 100644 --- a/tests/test_queries.py +++ b/tests/test_queries.py @@ -59,6 +59,20 @@ def test_claim_respects_priority_batch_size_and_entrypoint() -> None: assert [j.id for j in q.state.queued_jobs()] == [other.id, low.id] +@pytest.mark.parametrize("batch_size", [0, -1, -5]) +def test_claim_rejects_non_positive_batch_size(batch_size: int) -> None: + q = _queries(*(Job.new("task", b"x") for _ in range(5))) + before = q.state + with pytest.raises(ValueError, match="batch_size must be >= 1"): + q.claim(None, batch_size, NOW) + assert q.state is before + + +def test_claim_batch_size_one_claims_one() -> None: + q = _queries(Job.new("task", b"a"), Job.new("task", b"b")) + assert len(q.claim(None, 1, NOW)) == 1 + + # --------------------------------------------------------------------------- # remove / release / touch # ---------------------------------------------------------------------------