From b2b9d3a27bd60781912d74073217b7873027d0e0 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:03:39 +0000 Subject: [PATCH 1/2] Split queue logic into StateQueries and CAS-owning services Adapt the Queries/Services ADR to jqueue's object-storage model: StateQueries (core/queries.py) holds pure, synchronous job lifecycle operations on one QueueState snapshot; DirectQueue and GroupCommitLoop are services that own storage I/O and the CAS transaction boundary. This removes the duplicated claim/nack/heartbeat closures in both services and replaces nonlocal result passing with typed Callable[[StateQueries], T] units of work. Public API is unchanged. Adds queries-and-services.md (ADR) and tests/test_queries.py. --- AGENTS.md | 5 + jqueue/__init__.py | 3 +- jqueue/core/direct.py | 89 +++++------------ jqueue/core/group_commit.py | 91 +++++------------ jqueue/core/queries.py | 187 +++++++++++++++++++++++++++++++++++ queries-and-services.md | 192 ++++++++++++++++++++++++++++++++++++ tests/test_queries.py | 119 ++++++++++++++++++++++ 7 files changed, 558 insertions(+), 128 deletions(-) create mode 100644 jqueue/core/queries.py create mode 100644 queries-and-services.md create mode 100644 tests/test_queries.py diff --git a/AGENTS.md b/AGENTS.md index d5cf20f..ea9de40 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,6 +81,7 @@ jqueue/ ├── core/ # Business logic │ ├── broker.py # BrokerQueue (high-throughput with group commit) │ ├── direct.py # DirectQueue (simple one-operation-per-write) +│ ├── queries.py # StateQueries (pure ops on one QueueState snapshot) │ ├── group_commit.py # Group commit batching algorithm │ ├── heartbeat.py # HeartbeatManager for job liveness │ └── codec.py # JSON serialization @@ -98,6 +99,9 @@ jqueue/ - **Dependency injection**: Via constructor parameters - **Async-first**: All I/O operations use async/await - **CAS semantics**: Compare-and-set for concurrency safety +- **Queries vs services**: `StateQueries` holds pure, synchronous domain operations on one + `QueueState` snapshot; services (`DirectQueue`, `GroupCommitLoop`) own storage I/O and + the CAS cycle, and each public method is one unit of work (see `queries-and-services.md`) ## Code Style Guidelines @@ -246,6 +250,7 @@ class CustomStorage: ## References - **Architecture**: See `ports-and-adapters.md` for detailed design rationale +- **Queries & Services**: See `queries-and-services.md` for the query/service split - **README**: Comprehensive usage examples and API documentation - **Repository**: https://github.com/janbjorge/jqueue - **License**: MIT diff --git a/jqueue/__init__.py b/jqueue/__init__.py index 07f4217..a6bb1e5 100644 --- a/jqueue/__init__.py +++ b/jqueue/__init__.py @@ -53,7 +53,8 @@ async def write(content, if_match=None) -> str Follows the Ports & Adapters pattern: domain/ — pure value types (Job, QueueState, JobStatus) ports/ — Protocol interfaces (ObjectStoragePort) - core/ — business logic (DirectQueue, BrokerQueue, GroupCommitLoop) + core/ — services (DirectQueue, BrokerQueue, GroupCommitLoop) and + pure state queries (StateQueries) adapters/ — concrete storage implementations """ diff --git a/jqueue/core/direct.py b/jqueue/core/direct.py index db79049..3db56e6 100644 --- a/jqueue/core/direct.py +++ b/jqueue/core/direct.py @@ -24,20 +24,25 @@ from datetime import UTC, datetime, timedelta from jqueue.core import codec -from jqueue.domain.errors import CASConflictError, JobNotFoundError -from jqueue.domain.models import Job, JobStatus, QueueState +from jqueue.core.queries import StateQueries +from jqueue.domain.errors import CASConflictError +from jqueue.domain.models import Job, QueueState from jqueue.ports.storage import ObjectStoragePort -MutationFn = Callable[[QueueState], QueueState] - @dataclasses.dataclass class DirectQueue: """ - Thin stateless wrapper around ObjectStoragePort. + Thin stateless service around ObjectStoragePort. All methods are async and safe to call from multiple coroutines; - each operation performs a full CAS cycle independently. + each operation performs a full CAS cycle independently. Each public + method is one unit of work: it either commits entirely or raises. + + Parameters + ---------- + storage : any ObjectStoragePort implementation + max_retries : CAS attempts before CASConflictError is re-raised """ storage: ObjectStoragePort @@ -55,8 +60,7 @@ async def enqueue( ) -> Job: """Add a new job to the queue. Returns the committed Job.""" job = Job.new(entrypoint, payload, priority) - await self._mutate(lambda state: state.with_job_added(job)) - return job + return await self._transaction(lambda q: q.add(job)) async def dequeue( self, @@ -70,51 +74,21 @@ async def dequeue( Optionally filter by entrypoint. Returns the list of claimed jobs. Returns an empty list if no jobs are available. """ - claimed: list[Job] = [] - - def _fn(state: QueueState) -> QueueState: - nonlocal claimed - available = state.queued_jobs(entrypoint)[:batch_size] - claimed = [] - new_state = state - for job in available: - updated = job.with_status(JobStatus.IN_PROGRESS).with_heartbeat( - datetime.now(UTC) - ) - new_state = new_state.with_job_replaced(updated) - claimed.append(updated) - return new_state - - await self._mutate(_fn) - return claimed + return await self._transaction( + lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) + ) async def ack(self, job_id: str) -> None: """Mark a job as done and remove it from the queue.""" - await self._mutate(lambda state: state.with_job_removed(job_id)) + await self._transaction(lambda q: q.remove(job_id)) async def nack(self, job_id: str) -> None: """Return a job to QUEUED status (worker failed or declined it).""" - - def _fn(state: QueueState) -> QueueState: - job = state.find(job_id) - if job is None: - raise JobNotFoundError(job_id) - return state.with_job_replaced( - job.with_status(JobStatus.QUEUED).with_heartbeat(None) - ) - - await self._mutate(_fn) + await self._transaction(lambda q: q.release(job_id)) async def heartbeat(self, job_id: str) -> None: """Update the heartbeat timestamp of an IN_PROGRESS job.""" - - def _fn(state: QueueState) -> QueueState: - job = state.find(job_id) - if job is None: - raise JobNotFoundError(job_id) - return state.with_job_replaced(job.with_heartbeat(datetime.now(UTC))) - - await self._mutate(_fn) + await self._transaction(lambda q: q.touch(job_id, datetime.now(UTC))) async def requeue_stale(self, timeout: timedelta) -> int: """ @@ -123,18 +97,7 @@ async def requeue_stale(self, timeout: timedelta) -> int: Returns the number of jobs re-queued. """ cutoff = datetime.now(UTC) - timeout - requeued = 0 - - def _fn(state: QueueState) -> QueueState: - nonlocal requeued - old_in_progress = {j.id for j in state.in_progress_jobs()} - new_state = state.requeue_stale(cutoff) - new_in_progress = {j.id for j in new_state.in_progress_jobs()} - requeued = len(old_in_progress - new_in_progress) - return new_state - - await self._mutate(_fn) - return requeued + return await self._transaction(lambda q: q.requeue_stale(cutoff)) # ------------------------------------------------------------------ # # Read operations (no CAS needed) # @@ -149,22 +112,22 @@ async def read_state(self) -> QueueState: # Internal CAS loop # # ------------------------------------------------------------------ # - async def _mutate(self, fn: MutationFn) -> None: + async def _transaction[T](self, fn: Callable[[StateQueries], T]) -> T: """ Read-modify-write with CAS retry loop. - fn(state) -> new_state (synchronous) + fn(queries) -> result (synchronous, re-run on a fresh snapshot per retry) Retries up to self.max_retries on CASConflictError. """ for attempt in range(self.max_retries): content, etag = await self.storage.read() - state = codec.decode(content) - new_state = fn(state) - new_content = codec.encode(new_state) + queries = StateQueries(codec.decode(content)) + result = fn(queries) try: - await self.storage.write(new_content, if_match=etag) - return + await self.storage.write(codec.encode(queries.state), if_match=etag) + return result except CASConflictError: if attempt == self.max_retries - 1: raise await asyncio.sleep(0.01 * (attempt + 1)) + raise CASConflictError("Max CAS retries exceeded") diff --git a/jqueue/core/group_commit.py b/jqueue/core/group_commit.py index d95f713..ea3f773 100644 --- a/jqueue/core/group_commit.py +++ b/jqueue/core/group_commit.py @@ -30,23 +30,23 @@ import dataclasses from collections.abc import Callable from datetime import UTC, datetime, timedelta +from typing import Any from jqueue.core import codec +from jqueue.core.queries import StateQueries from jqueue.domain.errors import CASConflictError, JQueueError -from jqueue.domain.models import Job, JobStatus, QueueState +from jqueue.domain.models import Job, QueueState from jqueue.ports.storage import ObjectStoragePort -MutationFn = Callable[[QueueState], QueueState] - _MAX_RETRIES: int = 20 @dataclasses.dataclass -class _PendingOp: - """A buffered mutation waiting to be committed to object storage.""" +class _PendingOp[T]: + """A buffered operation waiting to be committed to object storage.""" - fn: MutationFn - future: asyncio.Future[None] + fn: Callable[[StateQueries], T] + future: asyncio.Future[T] @dataclasses.dataclass @@ -68,7 +68,7 @@ class GroupCommitLoop: storage: ObjectStoragePort stale_timeout: timedelta = timedelta(minutes=5) - _pending: list[_PendingOp] = dataclasses.field( + _pending: list[_PendingOp[Any]] = dataclasses.field( default_factory=list, init=False, repr=False ) _wakeup: asyncio.Event = dataclasses.field( @@ -111,12 +111,7 @@ async def enqueue( ) -> Job: """Add a new job. Returns the committed Job (UUID stable across retries).""" job = Job.new(entrypoint, payload, priority) - - def _fn(state: QueueState) -> QueueState: - return state.with_job_added(job) - - await self._submit(_fn) - return job + return await self._submit(lambda q: q.add(job)) async def dequeue( self, @@ -125,53 +120,21 @@ async def dequeue( batch_size: int = 1, ) -> list[Job]: """Claim up to batch_size QUEUED jobs and mark them IN_PROGRESS.""" - claimed: list[Job] = [] - - def _fn(state: QueueState) -> QueueState: - nonlocal claimed - available = state.queued_jobs(entrypoint)[:batch_size] - claimed = [] - new_state = state - for job in available: - updated = job.with_status(JobStatus.IN_PROGRESS).with_heartbeat( - datetime.now(UTC) - ) - new_state = new_state.with_job_replaced(updated) - claimed.append(updated) - return new_state - - await self._submit(_fn) - return claimed + return await self._submit( + lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) + ) async def ack(self, job_id: str) -> None: """Remove a completed job from the queue.""" - await self._submit(lambda state: state.with_job_removed(job_id)) + await self._submit(lambda q: q.remove(job_id)) async def nack(self, job_id: str) -> None: """Return a job to QUEUED status.""" - from jqueue.domain.errors import JobNotFoundError - - def _fn(state: QueueState) -> QueueState: - job = state.find(job_id) - if job is None: - raise JobNotFoundError(job_id) - return state.with_job_replaced( - job.with_status(JobStatus.QUEUED).with_heartbeat(None) - ) - - await self._submit(_fn) + await self._submit(lambda q: q.release(job_id)) async def heartbeat(self, job_id: str) -> None: """Refresh the heartbeat timestamp for an IN_PROGRESS job.""" - from jqueue.domain.errors import JobNotFoundError - - def _fn(state: QueueState) -> QueueState: - job = state.find(job_id) - if job is None: - raise JobNotFoundError(job_id) - return state.with_job_replaced(job.with_heartbeat(datetime.now(UTC))) - - await self._submit(_fn) + await self._submit(lambda q: q.touch(job_id, datetime.now(UTC))) async def read_state(self) -> QueueState: """Read-only snapshot of current queue state (bypasses the write pipeline).""" @@ -182,19 +145,19 @@ async def read_state(self) -> QueueState: # Internal machinery # # ------------------------------------------------------------------ # - async def _submit(self, fn: MutationFn) -> None: + async def _submit[T](self, fn: Callable[[StateQueries], T]) -> T: """ - Enqueue a mutation and block until it is committed. + Enqueue an operation and block until it is committed. Appends the op to _pending, wakes the writer, then awaits the future that resolves when the batch containing this op successfully commits. """ if self._stopped: raise JQueueError("GroupCommitLoop is stopped") - future: asyncio.Future[None] = asyncio.get_running_loop().create_future() + future: asyncio.Future[T] = asyncio.get_running_loop().create_future() self._pending.append(_PendingOp(fn=fn, future=future)) self._wakeup.set() - await future + return await future async def _writer_loop(self) -> None: """Background coroutine — runs until stopped and all pending ops drain.""" @@ -210,7 +173,7 @@ async def _writer_loop(self) -> None: self._pending.clear() await self._commit_batch(batch) - async def _commit_batch(self, batch: list[_PendingOp]) -> None: + async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None: """ Apply all ops in `batch` to the current state and CAS write. @@ -220,20 +183,20 @@ async def _commit_batch(self, batch: list[_PendingOp]) -> None: for attempt in range(_MAX_RETRIES): try: content, etag = await self.storage.read() - state = codec.decode(content) + queries = StateQueries(codec.decode(content)) # Sweep stale jobs on every write cycle (free — no extra I/O) - cutoff = datetime.now(UTC) - self.stale_timeout - state = state.requeue_stale(cutoff) + queries.requeue_stale(datetime.now(UTC) - self.stale_timeout) + results: dict[int, Any] = {} per_op_errors: dict[int, Exception] = {} for i, op in enumerate(batch): try: - state = op.fn(state) + results[i] = op.fn(queries) except Exception as exc: per_op_errors[i] = exc - await self.storage.write(codec.encode(state), if_match=etag) + await self.storage.write(codec.encode(queries.state), if_match=etag) for i, op in enumerate(batch): if op.future.done(): @@ -241,7 +204,7 @@ async def _commit_batch(self, batch: list[_PendingOp]) -> None: if i in per_op_errors: op.future.set_exception(per_op_errors[i]) else: - op.future.set_result(None) + op.future.set_result(results[i]) return except CASConflictError: @@ -256,7 +219,7 @@ async def _commit_batch(self, batch: list[_PendingOp]) -> None: return -def _fail_batch(batch: list[_PendingOp], exc: Exception) -> None: +def _fail_batch(batch: list[_PendingOp[Any]], exc: Exception) -> None: """Set exception on all unresolved futures in the batch.""" for op in batch: if not op.future.done(): diff --git a/jqueue/core/queries.py b/jqueue/core/queries.py new file mode 100644 index 0000000..9a59963 --- /dev/null +++ b/jqueue/core/queries.py @@ -0,0 +1,187 @@ +""" +StateQueries — pure operations on a single QueueState snapshot. + +This is the "query" layer described in ``queries-and-services.md``. A +StateQueries instance wraps the snapshot read at the start of one CAS cycle +and exposes the domain operations (add, claim, release, touch, remove, +requeue_stale) that services compose into a unit of work. + +StateQueries never performs I/O and never touches ObjectStoragePort. The +caller (a service such as DirectQueue or GroupCommitLoop) owns the storage +round-trip: it reads the state, builds a StateQueries, runs operations, and +CAS-writes ``queries.state`` back. + +Each operation is atomic with respect to ``self.state``: the new snapshot is +computed first and only assigned on success, so an operation that raises +leaves the state untouched. GroupCommitLoop relies on this for per-operation +error isolation within a batch. + +Usage +----- + content, etag = await storage.read() + queries = StateQueries(codec.decode(content)) + claimed = queries.claim("send_email", batch_size=5, now=datetime.now(UTC)) + await storage.write(codec.encode(queries.state), if_match=etag) +""" + +from __future__ import annotations + +import dataclasses +from datetime import datetime + +from jqueue.domain.errors import JobNotFoundError +from jqueue.domain.models import Job, JobStatus, QueueState + + +@dataclasses.dataclass +class StateQueries: + """ + Domain operations over one QueueState snapshot. + + Parameters + ---------- + state : QueueState + The snapshot to operate on. Replaced (never mutated) by each + successful write operation. + """ + + state: QueueState + + # ------------------------------------------------------------------ # + # Reads # + # ------------------------------------------------------------------ # + + def find(self, job_id: str) -> Job | None: + """Return the job with the given id, or None if absent.""" + return self.state.find(job_id) + + # ------------------------------------------------------------------ # + # Writes # + # ------------------------------------------------------------------ # + + def add(self, job: Job) -> Job: + """ + Append a job to the queue. + + The job is built by the caller so its id stays stable across CAS + retries. + + Returns + ------- + Job + The added job. + """ + self.state = self.state.with_job_added(job) + return job + + def claim( + self, + entrypoint: str | None, + batch_size: int, + now: datetime, + ) -> list[Job]: + """ + Mark up to ``batch_size`` QUEUED jobs IN_PROGRESS. + + Parameters + ---------- + entrypoint : str | None + Only claim jobs for this entrypoint; None claims from any. + batch_size : int + Maximum number of jobs to claim. + now : datetime + Heartbeat timestamp for the claimed jobs. + + Returns + ------- + list[Job] + The claimed jobs, in priority order. Empty if none are available. + """ + state = self.state + claimed: list[Job] = [] + for job in state.queued_jobs(entrypoint)[:batch_size]: + updated = job.with_status(JobStatus.IN_PROGRESS).with_heartbeat(now) + state = state.with_job_replaced(updated) + claimed.append(updated) + self.state = state + return claimed + + def remove(self, job_id: str) -> Job: + """ + Remove a job from the queue. + + Returns + ------- + Job + The removed job. + + Raises + ------ + JobNotFoundError + If no job with ``job_id`` exists. + """ + job = self._require(job_id) + self.state = self.state.with_job_removed(job_id) + return job + + def release(self, job_id: str) -> Job: + """ + Return a job to QUEUED and clear its heartbeat. + + Returns + ------- + Job + The updated job. + + Raises + ------ + JobNotFoundError + If no job with ``job_id`` exists. + """ + updated = ( + self._require(job_id).with_status(JobStatus.QUEUED).with_heartbeat(None) + ) + self.state = self.state.with_job_replaced(updated) + return updated + + def touch(self, job_id: str, now: datetime) -> Job: + """ + Set a job's heartbeat timestamp. + + Returns + ------- + Job + The updated job. + + Raises + ------ + JobNotFoundError + If no job with ``job_id`` exists. + """ + updated = self._require(job_id).with_heartbeat(now) + self.state = self.state.with_job_replaced(updated) + return updated + + def requeue_stale(self, cutoff: datetime) -> int: + """ + Return IN_PROGRESS jobs with a heartbeat older than ``cutoff`` to QUEUED. + + Returns + ------- + int + The number of jobs re-queued. + """ + before = {j.id for j in self.state.in_progress_jobs()} + self.state = self.state.requeue_stale(cutoff) + after = {j.id for j in self.state.in_progress_jobs()} + return len(before - after) + + # ------------------------------------------------------------------ # + # Internal # + # ------------------------------------------------------------------ # + + def _require(self, job_id: str) -> Job: + job = self.state.find(job_id) + if job is None: + raise JobNotFoundError(job_id) + return job diff --git a/queries-and-services.md b/queries-and-services.md new file mode 100644 index 0000000..592f9b0 --- /dev/null +++ b/queries-and-services.md @@ -0,0 +1,192 @@ +# Queries and Services + +## Status + +Accepted + +## Context + +jqueue has two write paths over the same storage port: + +- `DirectQueue` runs one CAS cycle per operation. +- `GroupCommitLoop` (behind `BrokerQueue`) batches many operations into one CAS cycle. + +Both used to carry their own copy of the job lifecycle logic (claim, nack, heartbeat, +stale re-queue) as ad-hoc closures of type `QueueState -> QueueState`. Results such as the +list of claimed jobs were smuggled out through `nonlocal` variables. The two copies could +drift apart, and the only way to test the lifecycle logic was through a storage adapter. + +This ADR adapts the "Queries and Services" split, originally written for a +Postgres/FastAPI codebase, to jqueue's object-storage model. It builds on +`ports-and-adapters.md`. + +## Mapping from the database version + +| Database concept | jqueue equivalent | +|--------------------------|------------------------------------------------------| +| `Pool` | `ObjectStoragePort` | +| `Connection` | one `QueueState` snapshot, read at the start of a CAS cycle | +| Transaction | read → operate → `write(if_match=etag)`, retried on `CASConflictError` | +| Query class | `StateQueries` (`jqueue/core/queries.py`) | +| Service class | `DirectQueue`, `GroupCommitLoop` (and `BrokerQueue` as its facade) | +| Endpoint / `deps.py` | the caller's composition root: `BrokerQueue(S3Storage(...))` | +| HTTP-free `errors.py` | `jqueue/domain/errors.py` | + +## Decision + +### Query class: `StateQueries` + +`StateQueries` holds one `QueueState` snapshot and exposes the domain operations on it: + +```python +@dataclasses.dataclass +class StateQueries: + state: QueueState + + def find(self, job_id: str) -> Job | None: ... + def add(self, job: Job) -> Job: ... + def claim(self, entrypoint: str | None, batch_size: int, now: datetime) -> list[Job]: ... + def remove(self, job_id: str) -> Job: ... + def release(self, job_id: str) -> Job: ... + def touch(self, job_id: str, now: datetime) -> Job: ... + def requeue_stale(self, cutoff: datetime) -> int: ... +``` + +**Rules:** + +1. Operate on a `QueueState`, never on `ObjectStoragePort`. No I/O, no `async`. + The service owns the storage round-trip, just as the database version's service owns + connection acquisition. +2. Use `@dataclass`. The snapshot is the only field (the database version's Option A: + "connection at class level"). +3. Inputs are basic types or domain models. The clock is an input (`now`, `cutoff`), + so query behaviour is deterministic and testable without patching time. +4. Return domain values: `Job`, `list[Job]`, `int`. Never return raw bytes or a codec payload. +5. Writes return the affected record: `add`, `remove`, `release`, `touch` return the job; + `claim` returns the claimed jobs; `requeue_stale` returns the affected count. + Reads return `None` when nothing is found. +6. Writes on a missing job raise `JobNotFoundError`, not `None`, because the enclosing + unit of work must fail visibly. +7. Every operation is atomic with respect to `self.state`: compute the new snapshot, then + assign it. An operation that raises leaves `state` untouched. `GroupCommitLoop` relies + on this so that one failing operation does not corrupt the rest of its batch. + +**Where Pydantic fits.** The database version bans Pydantic below the API boundary. +In jqueue, `QueueState` and `Job` *are* the persisted wire format (see `codec.py`), so +they remain frozen Pydantic models. The rule that carries over is that queries return +immutable domain values, not live or mutable objects. + +### Service classes: `DirectQueue`, `GroupCommitLoop` + +Services accept the storage port and own the transaction boundary. Each public method is +one unit of work: it either commits entirely or raises. + +```python +@dataclasses.dataclass +class DirectQueue: + storage: ObjectStoragePort + max_retries: int = 10 + + async def dequeue(self, entrypoint: str | None = None, *, batch_size: int = 1) -> list[Job]: + return await self._transaction( + lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) + ) + + async def _transaction[T](self, fn: Callable[[StateQueries], T]) -> T: + for attempt in range(self.max_retries): + content, etag = await self.storage.read() + queries = StateQueries(codec.decode(content)) + result = fn(queries) + try: + await self.storage.write(codec.encode(queries.state), if_match=etag) + return result + except CASConflictError: + ... +``` + +**Rules:** + +1. Accept `ObjectStoragePort`, never a `QueueState`. Services decide when to read and write. +2. Use `@dataclass`. Store the port and configuration such as retries and stale timeout. +3. Build a fresh `StateQueries` inside each CAS attempt. The unit-of-work function is + re-run on the new snapshot after a conflict, so it must be a pure function of that snapshot. + Build values that must stay stable across retries, such as `Job.new(...)` and its + UUID, *outside* the function. +4. Return results from the unit-of-work function directly (`Callable[[StateQueries], T]`). + Do not pass them out through `nonlocal` state. +5. Services supply the clock (`datetime.now(UTC)`) and pass it into queries. +6. Raise domain exceptions (`JobNotFoundError`, `CASConflictError`, `StorageError`). + A failed method commits nothing. +7. The transaction strategy is what distinguishes services, not the domain logic. + `DirectQueue` commits one operation per write. `GroupCommitLoop` applies a batch of + `Callable[[StateQueries], T]` operations to one `StateQueries` and commits them in a + single write, resolving each caller's future with its own result or exception. + +### Wiring (the `deps.py` equivalent) + +jqueue is a library and has no DI container. The composition root is the caller: + +```python +async with BrokerQueue(S3Storage(bucket="jobs", key="queue.json")) as q: + ... +``` + +Adapters are injected through constructors only. Services never construct adapters, and +queries never see them. + +### Error handling + +Domain errors live in `jqueue/domain/errors.py` and inherit from `JQueueError`. They +describe queue semantics (a job is missing, a CAS write lost, storage failed) and carry +no transport concerns. Applications that expose jqueue over HTTP translate them at their +own boundary. + +## Consequences + +### Positive + +- One implementation of the job lifecycle, shared by both write paths. +- Lifecycle logic is unit-testable synchronously, without storage or event loops + (`tests/test_queries.py`). +- Transaction boundaries are explicit and live in exactly one method per service + (`DirectQueue._transaction`, `GroupCommitLoop._commit_batch`). +- Typed results replace `nonlocal` result passing. + +### Negative + +- One more module in `core/`. +- Contributors must remember that unit-of-work functions may run more than once. + +## Alternatives Considered + +- **Keep `QueueState -> QueueState` closures in each service.** Rejected because it + duplicates logic and hides results in `nonlocal` state. +- **Put the operations on `QueueState` itself.** Partly done already (`with_job_added` + and similar). Operations that need a clock and return a result alongside the new state + (`claim`, `requeue_stale`) do not fit a pure value type cleanly, and `QueueState` should + stay a serialisable snapshot. +- **Free functions returning `(new_state, result)` tuples.** Workable, but noisier at every + call site and harder to compose in a batch than a single stateful `StateQueries`. + +## Appendix + +``` + ┌──────────────────────────────────────────────────────────┐ + │ Caller / composition root │ + │ BrokerQueue(S3Storage(...)), DirectQueue(GCSStorage()) │ + └──────────────┬───────────────────────────────┬───────────┘ + │ │ + ┌──────────────┴─────────────┐ ┌──────────────┴───────────┐ + │ DirectQueue │ │ BrokerQueue │ + │ 1 op → 1 CAS write │ │ └─ GroupCommitLoop │ + │ │ │ N ops → 1 CAS write │ + └──────────────┬─────────────┘ └──────────────┬───────────┘ + │ services: own the CAS cycle │ + ├───────────────┬───────────────┤ + │ │ │ + ┌──────────────┴──────┐ ┌─────┴───────────────┴────────────┐ + │ StateQueries │ │ ObjectStoragePort (port) │ + │ pure ops on one │ │ read() / write(if_match) │ + │ QueueState │ │ ← memory, filesystem, s3, gcs │ + └─────────────────────┘ └──────────────────────────────────┘ +``` diff --git a/tests/test_queries.py b/tests/test_queries.py new file mode 100644 index 0000000..08f8892 --- /dev/null +++ b/tests/test_queries.py @@ -0,0 +1,119 @@ +from datetime import UTC, datetime, timedelta + +import pytest + +from jqueue.core.queries import StateQueries +from jqueue.domain.errors import JobNotFoundError +from jqueue.domain.models import Job, JobStatus, QueueState + +NOW = datetime(2024, 1, 1, tzinfo=UTC) + + +def _queries(*jobs: Job) -> StateQueries: + return StateQueries(QueueState(jobs=jobs)) + + +# --------------------------------------------------------------------------- +# find / add +# --------------------------------------------------------------------------- + + +def test_find_returns_none_when_absent() -> None: + assert _queries().find("missing") is None + + +def test_add_returns_job_and_updates_state() -> None: + q = _queries() + job = Job.new("task", b"data") + assert q.add(job) is job + assert q.find(job.id) == job + assert q.state.version == 1 + + +# --------------------------------------------------------------------------- +# claim +# --------------------------------------------------------------------------- + + +def test_claim_empty_returns_empty_list() -> None: + q = _queries() + assert q.claim(None, 5, NOW) == [] + assert q.state.version == 0 + + +def test_claim_marks_in_progress_with_heartbeat() -> None: + q = _queries(Job.new("task", b"a")) + [claimed] = q.claim("task", 1, NOW) + assert claimed.status == JobStatus.IN_PROGRESS + assert claimed.heartbeat_at == NOW + assert q.find(claimed.id) == claimed + + +def test_claim_respects_priority_batch_size_and_entrypoint() -> None: + low = Job.new("task", b"low", priority=5) + high = Job.new("task", b"high", priority=0) + other = Job.new("other", b"x") + q = _queries(low, high, other) + claimed = q.claim("task", 1, NOW) + assert [j.id for j in claimed] == [high.id] + assert [j.id for j in q.state.queued_jobs()] == [other.id, low.id] + + +# --------------------------------------------------------------------------- +# remove / release / touch +# --------------------------------------------------------------------------- + + +def test_remove_returns_removed_job() -> None: + job = Job.new("task", b"data") + q = _queries(job) + assert q.remove(job.id) == job + assert q.state.jobs == () + + +def test_release_returns_job_to_queued() -> None: + job = Job.new("task", b"data") + q = _queries(job) + [claimed] = q.claim(None, 1, NOW) + released = q.release(claimed.id) + assert released.status == JobStatus.QUEUED + assert released.heartbeat_at is None + + +def test_touch_updates_heartbeat() -> None: + job = Job.new("task", b"data") + q = _queries(job) + later = NOW + timedelta(seconds=30) + assert q.touch(job.id, later).heartbeat_at == later + + +@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")) + before = q.state + with pytest.raises(JobNotFoundError): + if op == "touch": + q.touch("missing", NOW) + else: + getattr(q, op)("missing") + assert q.state is before + + +# --------------------------------------------------------------------------- +# requeue_stale +# --------------------------------------------------------------------------- + + +def test_requeue_stale_returns_count() -> None: + q = _queries(Job.new("task", b"a"), Job.new("task", b"b")) + q.claim(None, 2, NOW) + assert q.requeue_stale(NOW + timedelta(seconds=1)) == 2 + assert q.state.in_progress_jobs() == () + + +def test_requeue_stale_ignores_fresh_jobs() -> None: + q = _queries(Job.new("task", b"a")) + q.claim(None, 1, NOW) + before = q.state + assert q.requeue_stale(NOW - timedelta(seconds=1)) == 0 + assert q.state is before From 76dde3f2f41f8344b6d3b3e2cb04748c9d21ebc9 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:03:39 +0000 Subject: [PATCH 2/2] Trim queries/services ADR and docstrings --- AGENTS.md | 4 +- jqueue/core/queries.py | 27 +----- queries-and-services.md | 198 ++++++---------------------------------- 3 files changed, 31 insertions(+), 198 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ea9de40..da9796c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,9 +99,7 @@ jqueue/ - **Dependency injection**: Via constructor parameters - **Async-first**: All I/O operations use async/await - **CAS semantics**: Compare-and-set for concurrency safety -- **Queries vs services**: `StateQueries` holds pure, synchronous domain operations on one - `QueueState` snapshot; services (`DirectQueue`, `GroupCommitLoop`) own storage I/O and - the CAS cycle, and each public method is one unit of work (see `queries-and-services.md`) +- **Queries vs services**: `StateQueries` is pure state logic; services own I/O and CAS (see `queries-and-services.md`) ## Code Style Guidelines diff --git a/jqueue/core/queries.py b/jqueue/core/queries.py index 9a59963..09a5cfd 100644 --- a/jqueue/core/queries.py +++ b/jqueue/core/queries.py @@ -1,27 +1,8 @@ """ -StateQueries — pure operations on a single QueueState snapshot. - -This is the "query" layer described in ``queries-and-services.md``. A -StateQueries instance wraps the snapshot read at the start of one CAS cycle -and exposes the domain operations (add, claim, release, touch, remove, -requeue_stale) that services compose into a unit of work. - -StateQueries never performs I/O and never touches ObjectStoragePort. The -caller (a service such as DirectQueue or GroupCommitLoop) owns the storage -round-trip: it reads the state, builds a StateQueries, runs operations, and -CAS-writes ``queries.state`` back. - -Each operation is atomic with respect to ``self.state``: the new snapshot is -computed first and only assigned on success, so an operation that raises -leaves the state untouched. GroupCommitLoop relies on this for per-operation -error isolation within a batch. - -Usage ------ - content, etag = await storage.read() - queries = StateQueries(codec.decode(content)) - claimed = queries.claim("send_email", batch_size=5, now=datetime.now(UTC)) - await storage.write(codec.encode(queries.state), if_match=etag) +StateQueries — pure operations on one QueueState snapshot. + +No I/O. Services (DirectQueue, GroupCommitLoop) own the storage read/CAS write. +An operation that raises leaves ``state`` unchanged. """ from __future__ import annotations diff --git a/queries-and-services.md b/queries-and-services.md index 592f9b0..f73f6b2 100644 --- a/queries-and-services.md +++ b/queries-and-services.md @@ -6,187 +6,41 @@ Accepted ## Context -jqueue has two write paths over the same storage port: - -- `DirectQueue` runs one CAS cycle per operation. -- `GroupCommitLoop` (behind `BrokerQueue`) batches many operations into one CAS cycle. - -Both used to carry their own copy of the job lifecycle logic (claim, nack, heartbeat, -stale re-queue) as ad-hoc closures of type `QueueState -> QueueState`. Results such as the -list of claimed jobs were smuggled out through `nonlocal` variables. The two copies could -drift apart, and the only way to test the lifecycle logic was through a storage adapter. - -This ADR adapts the "Queries and Services" split, originally written for a -Postgres/FastAPI codebase, to jqueue's object-storage model. It builds on -`ports-and-adapters.md`. - -## Mapping from the database version - -| Database concept | jqueue equivalent | -|--------------------------|------------------------------------------------------| -| `Pool` | `ObjectStoragePort` | -| `Connection` | one `QueueState` snapshot, read at the start of a CAS cycle | -| Transaction | read → operate → `write(if_match=etag)`, retried on `CASConflictError` | -| Query class | `StateQueries` (`jqueue/core/queries.py`) | -| Service class | `DirectQueue`, `GroupCommitLoop` (and `BrokerQueue` as its facade) | -| Endpoint / `deps.py` | the caller's composition root: `BrokerQueue(S3Storage(...))` | -| HTTP-free `errors.py` | `jqueue/domain/errors.py` | +`DirectQueue` and `GroupCommitLoop` each duplicated the job lifecycle logic (claim, nack, +heartbeat, stale re-queue) as closures, passing results out via `nonlocal`. ## Decision -### Query class: `StateQueries` - -`StateQueries` holds one `QueueState` snapshot and exposes the domain operations on it: - -```python -@dataclasses.dataclass -class StateQueries: - state: QueueState - - def find(self, job_id: str) -> Job | None: ... - def add(self, job: Job) -> Job: ... - def claim(self, entrypoint: str | None, batch_size: int, now: datetime) -> list[Job]: ... - def remove(self, job_id: str) -> Job: ... - def release(self, job_id: str) -> Job: ... - def touch(self, job_id: str, now: datetime) -> Job: ... - def requeue_stale(self, cutoff: datetime) -> int: ... -``` - -**Rules:** - -1. Operate on a `QueueState`, never on `ObjectStoragePort`. No I/O, no `async`. - The service owns the storage round-trip, just as the database version's service owns - connection acquisition. -2. Use `@dataclass`. The snapshot is the only field (the database version's Option A: - "connection at class level"). -3. Inputs are basic types or domain models. The clock is an input (`now`, `cutoff`), - so query behaviour is deterministic and testable without patching time. -4. Return domain values: `Job`, `list[Job]`, `int`. Never return raw bytes or a codec payload. -5. Writes return the affected record: `add`, `remove`, `release`, `touch` return the job; - `claim` returns the claimed jobs; `requeue_stale` returns the affected count. - Reads return `None` when nothing is found. -6. Writes on a missing job raise `JobNotFoundError`, not `None`, because the enclosing - unit of work must fail visibly. -7. Every operation is atomic with respect to `self.state`: compute the new snapshot, then - assign it. An operation that raises leaves `state` untouched. `GroupCommitLoop` relies - on this so that one failing operation does not corrupt the rest of its batch. - -**Where Pydantic fits.** The database version bans Pydantic below the API boundary. -In jqueue, `QueueState` and `Job` *are* the persisted wire format (see `codec.py`), so -they remain frozen Pydantic models. The rule that carries over is that queries return -immutable domain values, not live or mutable objects. - -### Service classes: `DirectQueue`, `GroupCommitLoop` - -Services accept the storage port and own the transaction boundary. Each public method is -one unit of work: it either commits entirely or raises. +Split pure state logic (queries) from storage and transaction handling (services). -```python -@dataclasses.dataclass -class DirectQueue: - storage: ObjectStoragePort - max_retries: int = 10 +| Database term | jqueue | +|---------------|--------------------------------------------------| +| Pool | `ObjectStoragePort` | +| Connection | one `QueueState` snapshot | +| Transaction | read → operate → `write(if_match=etag)`, retry on conflict | +| Query | `StateQueries` (`core/queries.py`) | +| Service | `DirectQueue`, `GroupCommitLoop` | - async def dequeue(self, entrypoint: str | None = None, *, batch_size: int = 1) -> list[Job]: - return await self._transaction( - lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)) - ) +**Queries (`StateQueries`)** - async def _transaction[T](self, fn: Callable[[StateQueries], T]) -> T: - for attempt in range(self.max_retries): - content, etag = await self.storage.read() - queries = StateQueries(codec.decode(content)) - result = fn(queries) - try: - await self.storage.write(codec.encode(queries.state), if_match=etag) - return result - except CASConflictError: - ... -``` +1. Operate on a `QueueState`. No I/O, no `async`. +2. Take the clock as an argument (`now`, `cutoff`). +3. Writes return the affected job(s) or a count. Reads return `None` if nothing is found. +4. Writes on a missing job raise `JobNotFoundError`. +5. Each operation either fully applies or leaves `state` unchanged. -**Rules:** +**Services** -1. Accept `ObjectStoragePort`, never a `QueueState`. Services decide when to read and write. -2. Use `@dataclass`. Store the port and configuration such as retries and stale timeout. -3. Build a fresh `StateQueries` inside each CAS attempt. The unit-of-work function is - re-run on the new snapshot after a conflict, so it must be a pure function of that snapshot. - Build values that must stay stable across retries, such as `Job.new(...)` and its - UUID, *outside* the function. -4. Return results from the unit-of-work function directly (`Callable[[StateQueries], T]`). - Do not pass them out through `nonlocal` state. -5. Services supply the clock (`datetime.now(UTC)`) and pass it into queries. -6. Raise domain exceptions (`JobNotFoundError`, `CASConflictError`, `StorageError`). - A failed method commits nothing. -7. The transaction strategy is what distinguishes services, not the domain logic. - `DirectQueue` commits one operation per write. `GroupCommitLoop` applies a batch of - `Callable[[StateQueries], T]` operations to one `StateQueries` and commits them in a - single write, resolving each caller's future with its own result or exception. +1. Accept `ObjectStoragePort`. Own the CAS cycle. +2. Build a fresh `StateQueries` per attempt. Units of work may re-run, so they must be pure. + Build values that must be stable across retries (e.g. `Job.new`) outside them. +3. Units of work are `Callable[[StateQueries], T]` and return their result directly. +4. Each public method commits fully or raises a domain error. -### Wiring (the `deps.py` equivalent) - -jqueue is a library and has no DI container. The composition root is the caller: - -```python -async with BrokerQueue(S3Storage(bucket="jobs", key="queue.json")) as q: - ... -``` - -Adapters are injected through constructors only. Services never construct adapters, and -queries never see them. - -### Error handling - -Domain errors live in `jqueue/domain/errors.py` and inherit from `JQueueError`. They -describe queue semantics (a job is missing, a CAS write lost, storage failed) and carry -no transport concerns. Applications that expose jqueue over HTTP translate them at their -own boundary. +`Job` and `QueueState` stay Pydantic, since they are the stored format. ## Consequences -### Positive - -- One implementation of the job lifecycle, shared by both write paths. -- Lifecycle logic is unit-testable synchronously, without storage or event loops - (`tests/test_queries.py`). -- Transaction boundaries are explicit and live in exactly one method per service - (`DirectQueue._transaction`, `GroupCommitLoop._commit_batch`). -- Typed results replace `nonlocal` result passing. - -### Negative - -- One more module in `core/`. -- Contributors must remember that unit-of-work functions may run more than once. - -## Alternatives Considered - -- **Keep `QueueState -> QueueState` closures in each service.** Rejected because it - duplicates logic and hides results in `nonlocal` state. -- **Put the operations on `QueueState` itself.** Partly done already (`with_job_added` - and similar). Operations that need a clock and return a result alongside the new state - (`claim`, `requeue_stale`) do not fit a pure value type cleanly, and `QueueState` should - stay a serialisable snapshot. -- **Free functions returning `(new_state, result)` tuples.** Workable, but noisier at every - call site and harder to compose in a batch than a single stateful `StateQueries`. - -## Appendix - -``` - ┌──────────────────────────────────────────────────────────┐ - │ Caller / composition root │ - │ BrokerQueue(S3Storage(...)), DirectQueue(GCSStorage()) │ - └──────────────┬───────────────────────────────┬───────────┘ - │ │ - ┌──────────────┴─────────────┐ ┌──────────────┴───────────┐ - │ DirectQueue │ │ BrokerQueue │ - │ 1 op → 1 CAS write │ │ └─ GroupCommitLoop │ - │ │ │ N ops → 1 CAS write │ - └──────────────┬─────────────┘ └──────────────┬───────────┘ - │ services: own the CAS cycle │ - ├───────────────┬───────────────┤ - │ │ │ - ┌──────────────┴──────┐ ┌─────┴───────────────┴────────────┐ - │ StateQueries │ │ ObjectStoragePort (port) │ - │ pure ops on one │ │ read() / write(if_match) │ - │ QueueState │ │ ← memory, filesystem, s3, gcs │ - └─────────────────────┘ └──────────────────────────────────┘ -``` +- One lifecycle implementation, unit-testable without storage. +- Transaction boundaries live in one place per service. +- Units of work can run more than once; keep them side-effect free.