diff --git a/AGENTS.md b/AGENTS.md index d5cf20f..da9796c 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,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` is pure state logic; services own I/O and CAS (see `queries-and-services.md`) ## Code Style Guidelines @@ -246,6 +248,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..09a5cfd --- /dev/null +++ b/jqueue/core/queries.py @@ -0,0 +1,168 @@ +""" +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 + +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..f73f6b2 --- /dev/null +++ b/queries-and-services.md @@ -0,0 +1,46 @@ +# Queries and Services + +## Status + +Accepted + +## Context + +`DirectQueue` and `GroupCommitLoop` each duplicated the job lifecycle logic (claim, nack, +heartbeat, stale re-queue) as closures, passing results out via `nonlocal`. + +## Decision + +Split pure state logic (queries) from storage and transaction handling (services). + +| 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` | + +**Queries (`StateQueries`)** + +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. + +**Services** + +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. + +`Job` and `QueueState` stay Pydantic, since they are the stored format. + +## Consequences + +- 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. 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