From 97511185d5c1fffbdbe4db12e08ce88dd3f85087 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:23:26 +0000 Subject: [PATCH] Skip the CAS write when an operation changes nothing DirectQueue and GroupCommitLoop wrote back after every operation, even when the state was unchanged: a dequeue on an empty queue, a requeue_stale with nothing stale, a batch of only failed ops. Idle pollers paid a full object write per poll, bumped the etag, and caused CAS conflicts for concurrent writers doing real work. A dequeue against a missing object also created it. StateQueries replaces its state only when an op changes it, so compare the result to the decoded snapshot by identity and skip the write when they match. The snapshot just read is a valid linearization point for an op that changed nothing. --- jqueue/core/direct.py | 9 +++- jqueue/core/group_commit.py | 9 +++- tests/test_direct_queue.py | 85 +++++++++++++++++++++++++++++++++++++ tests/test_group_commit.py | 77 +++++++++++++++++++++++++++++++++ 4 files changed, 176 insertions(+), 4 deletions(-) diff --git a/jqueue/core/direct.py b/jqueue/core/direct.py index 3db56e6..e546d96 100644 --- a/jqueue/core/direct.py +++ b/jqueue/core/direct.py @@ -117,12 +117,17 @@ async def _transaction[T](self, fn: Callable[[StateQueries], T]) -> T: Read-modify-write with CAS retry loop. fn(queries) -> result (synchronous, re-run on a fresh snapshot per retry) - Retries up to self.max_retries on CASConflictError. + Retries up to self.max_retries on CASConflictError. If fn leaves the + state unchanged (e.g. dequeue on an empty queue), no write is made: + the snapshot just read is a valid linearization point. """ for attempt in range(self.max_retries): content, etag = await self.storage.read() - queries = StateQueries(codec.decode(content)) + snapshot = codec.decode(content) + queries = StateQueries(snapshot) result = fn(queries) + if queries.state is snapshot: + return result try: await self.storage.write(codec.encode(queries.state), if_match=etag) return result diff --git a/jqueue/core/group_commit.py b/jqueue/core/group_commit.py index ea3f773..a5232f2 100644 --- a/jqueue/core/group_commit.py +++ b/jqueue/core/group_commit.py @@ -179,11 +179,13 @@ async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None: Retries on CASConflictError. Per-mutation exceptions only fail that op's future; the rest of the batch still commits on the same write. + If the batch leaves the state unchanged, no write is made. """ for attempt in range(_MAX_RETRIES): try: content, etag = await self.storage.read() - queries = StateQueries(codec.decode(content)) + snapshot = codec.decode(content) + queries = StateQueries(snapshot) # Sweep stale jobs on every write cycle (free — no extra I/O) queries.requeue_stale(datetime.now(UTC) - self.stale_timeout) @@ -196,7 +198,10 @@ async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None: except Exception as exc: per_op_errors[i] = exc - await self.storage.write(codec.encode(queries.state), if_match=etag) + # Nothing changed (e.g. only empty dequeues / failed ops): + # skip the write, the snapshot is a valid linearization point. + if queries.state is not snapshot: + await self.storage.write(codec.encode(queries.state), if_match=etag) for i, op in enumerate(batch): if op.future.done(): diff --git a/tests/test_direct_queue.py b/tests/test_direct_queue.py index cf0359f..d06825a 100644 --- a/tests/test_direct_queue.py +++ b/tests/test_direct_queue.py @@ -296,3 +296,88 @@ async def test_cas_exhausted_raises_conflict() -> None: q = DirectQueue(storage=real_storage, max_retries=2) with pytest.raises(CASConflictError): await q.enqueue("task", b"data") + + +# --------------------------------------------------------------------------- +# No-op operations skip the write +# --------------------------------------------------------------------------- + + +class _CountingStorage(InMemoryStorage): + """InMemoryStorage that counts successful writes.""" + + writes: int = 0 + + async def write(self, content: bytes, if_match: str | None = None) -> str: + etag = await super().write(content, if_match) + self.writes += 1 + return etag + + +async def test_empty_dequeue_does_not_write() -> None: + storage = _CountingStorage() + queue = DirectQueue(storage) + await queue.enqueue("task", b"data") + assert storage.writes == 1 + _, 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 + assert etag_after == etag_before + + +async def test_dequeue_on_missing_object_does_not_create_it() -> None: + storage = _CountingStorage() + queue = DirectQueue(storage) + assert await queue.dequeue() == [] + assert storage.writes == 0 + assert await storage.read() == (b"", None) + + +async def test_requeue_stale_with_nothing_stale_does_not_write() -> None: + storage = _CountingStorage() + queue = DirectQueue(storage) + await queue.enqueue("task", b"data") + await queue.dequeue("task") + writes = storage.writes + + assert await queue.requeue_stale(timedelta(hours=1)) == 0 + assert storage.writes == writes + + +async def test_failed_op_does_not_write() -> None: + storage = _CountingStorage() + queue = DirectQueue(storage) + await queue.enqueue("task", b"data") + with pytest.raises(JobNotFoundError): + await queue.ack("nonexistent-id") + assert storage.writes == 1 + + +async def test_state_changing_ops_still_write() -> None: + storage = _CountingStorage() + queue = DirectQueue(storage) + await queue.enqueue("task", b"data") + [job] = await queue.dequeue("task") + await queue.heartbeat(job.id) + await queue.nack(job.id) + await queue.dequeue("task") + assert await queue.requeue_stale(timedelta(seconds=-1)) == 1 + await queue.ack(job.id) + assert storage.writes == 7 + assert (await queue.read_state()).jobs == () + + +async def test_empty_dequeue_does_not_conflict_with_concurrent_writer() -> None: + """A no-op read cannot cause a CAS conflict for a real writer.""" + storage = AsyncMock(wraps=InMemoryStorage()) + queue = DirectQueue(storage) + await queue.enqueue("task", b"data") + await queue.dequeue("task") + storage.write.reset_mock() + + assert await queue.dequeue("task") == [] + storage.write.assert_not_called() diff --git a/tests/test_group_commit.py b/tests/test_group_commit.py index aac8eb9..978e718 100644 --- a/tests/test_group_commit.py +++ b/tests/test_group_commit.py @@ -297,3 +297,80 @@ async def flaky_write(content: bytes, if_match: str | None = None) -> str: assert fail_count == 3 finally: await gcl.stop() + + +# --------------------------------------------------------------------------- +# No-op batches skip the write +# --------------------------------------------------------------------------- + + +class _CountingStorage(InMemoryStorage): + """InMemoryStorage that counts successful writes.""" + + writes: int = 0 + + async def write(self, content: bytes, if_match: str | None = None) -> str: + etag = await super().write(content, if_match) + self.writes += 1 + return etag + + +async def test_noop_batch_does_not_write() -> None: + storage = _CountingStorage() + gcl = GroupCommitLoop(storage=storage) + await gcl.start() + try: + await gcl.enqueue("task", b"data") + writes = storage.writes + + results = await asyncio.gather( + gcl.dequeue("other"), + gcl.dequeue("other"), + gcl.ack("nonexistent"), + return_exceptions=True, + ) + + assert results[0] == [] + assert results[1] == [] + assert isinstance(results[2], JobNotFoundError) + assert storage.writes == writes + finally: + await gcl.stop() + + +async def test_batch_with_one_change_still_writes_once() -> None: + storage = _CountingStorage() + gcl = GroupCommitLoop(storage=storage) + await gcl.start() + try: + await gcl.enqueue("task", b"data") + writes = storage.writes + + empty, claimed = await asyncio.gather(gcl.dequeue("other"), gcl.dequeue("task")) + + assert empty == [] + assert len(claimed) == 1 + assert storage.writes == writes + 1 + state = await gcl.read_state() + assert state.jobs[0].status == JobStatus.IN_PROGRESS + finally: + await gcl.stop() + + +async def test_stale_sweep_alone_still_writes() -> None: + """A batch whose only change is the stale sweep must persist it.""" + storage = _CountingStorage() + gcl = GroupCommitLoop(storage=storage, stale_timeout=timedelta(0)) + await gcl.start() + try: + await gcl.enqueue("task", b"data") + await gcl.dequeue("task") + writes = storage.writes + + assert await gcl.dequeue("other") == [] + + assert storage.writes == writes + 1 + state = await gcl.read_state() + assert state.jobs[0].status == JobStatus.QUEUED + finally: + await gcl.stop()