Atomic claim, terminal transitions and recover() that requeues at the old place. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cef1a48b69
commit
1db38992cd
3 files changed
+388
-1
No files matched your search
@@ -0,0 +1,136 @@
|
||||
"""SQLite implementation of the job queue port."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, cast
|
||||
from uuid import UUID
|
||||
|
||||
from chemenu.adapters.sqlite.database import Database
|
||||
from chemenu.domain.job import Job, JobState, JsonObject
|
||||
from chemenu.ports.job_queue import InvalidTransitionError, JobNotFoundError
|
||||
|
||||
_SELECT_JOB = (
|
||||
"SELECT id, kind, payload, state, attempts, enqueued_at, result, reason FROM jobs WHERE id = ?"
|
||||
)
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
def _dumps(value: JsonObject) -> str:
|
||||
return json.dumps(value, allow_nan=False)
|
||||
|
||||
|
||||
def _loads(text: str) -> JsonObject:
|
||||
return cast("JsonObject", json.loads(text))
|
||||
|
||||
|
||||
def _to_job(row: tuple[Any, ...]) -> Job:
|
||||
return Job(
|
||||
id=UUID(row[0]),
|
||||
kind=row[1],
|
||||
payload=_loads(row[2]),
|
||||
state=JobState(row[3]),
|
||||
attempts=row[4],
|
||||
enqueued_at=datetime.fromisoformat(row[5]),
|
||||
result=None if row[6] is None else _loads(row[6]),
|
||||
reason=row[7],
|
||||
)
|
||||
|
||||
|
||||
def _select(conn: sqlite3.Connection, job_id: UUID) -> Job:
|
||||
row = conn.execute(_SELECT_JOB, (str(job_id),)).fetchone()
|
||||
if row is None:
|
||||
raise JobNotFoundError(str(job_id))
|
||||
return _to_job(row)
|
||||
|
||||
|
||||
class SqliteJobQueue:
|
||||
def __init__(
|
||||
self,
|
||||
database: Database,
|
||||
*,
|
||||
max_attempts: int = 3,
|
||||
clock: Callable[[], datetime] = utc_now,
|
||||
) -> None:
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be at least 1")
|
||||
self._database = database
|
||||
self._max_attempts = max_attempts
|
||||
self._clock = clock
|
||||
|
||||
def enqueue(self, kind: str, payload: JsonObject) -> Job:
|
||||
text = _dumps(payload)
|
||||
now = self._clock()
|
||||
if now.tzinfo is None or now.utcoffset() is None:
|
||||
raise ValueError("clock must return an aware datetime")
|
||||
job_id = uuid.uuid7()
|
||||
with self._database.transaction() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO jobs (id, kind, payload, state, attempts, enqueued_at)"
|
||||
" VALUES (?, ?, ?, ?, 0, ?)",
|
||||
(str(job_id), kind, text, JobState.QUEUED.value, now.astimezone(UTC).isoformat()),
|
||||
)
|
||||
return _select(conn, job_id)
|
||||
|
||||
def claim(self) -> Job | None:
|
||||
with self._database.transaction() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM jobs WHERE state = ? ORDER BY seq LIMIT 1",
|
||||
(JobState.QUEUED.value,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
conn.execute(
|
||||
"UPDATE jobs SET state = ?, attempts = attempts + 1 WHERE id = ?",
|
||||
(JobState.RUNNING.value, row[0]),
|
||||
)
|
||||
return _select(conn, UUID(row[0]))
|
||||
|
||||
def _finish(self, job_id: UUID, state: JobState, result: str | None, reason: str | None) -> Job:
|
||||
with self._database.transaction() as conn:
|
||||
current = _select(conn, job_id)
|
||||
if current.state is not JobState.RUNNING:
|
||||
raise InvalidTransitionError(f"job {job_id} is {current.state}, not running")
|
||||
conn.execute(
|
||||
"UPDATE jobs SET state = ?, result = ?, reason = ? WHERE id = ?",
|
||||
(state.value, result, reason, str(job_id)),
|
||||
)
|
||||
return _select(conn, job_id)
|
||||
|
||||
def complete(self, job_id: UUID, result: JsonObject) -> Job:
|
||||
return self._finish(job_id, JobState.DONE, _dumps(result), None)
|
||||
|
||||
def fail(self, job_id: UUID, reason: str) -> Job:
|
||||
# SQLite rejects lone surrogates, as in undecodable file names; a failure
|
||||
# that cannot be stored would leave the job running and repeat it.
|
||||
text = reason.encode("utf-8", "backslashreplace").decode("utf-8")
|
||||
return self._finish(job_id, JobState.FAILED, None, text)
|
||||
|
||||
def get(self, job_id: UUID) -> Job:
|
||||
with self._database.transaction() as conn:
|
||||
return _select(conn, job_id)
|
||||
|
||||
def recover(self) -> list[Job]:
|
||||
reason = f"aborted after {self._max_attempts} attempts"
|
||||
with self._database.transaction() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, attempts FROM jobs WHERE state = ? ORDER BY seq",
|
||||
(JobState.RUNNING.value,),
|
||||
).fetchall()
|
||||
for job_id, attempts in rows:
|
||||
if attempts < self._max_attempts:
|
||||
conn.execute(
|
||||
"UPDATE jobs SET state = ? WHERE id = ?",
|
||||
(JobState.QUEUED.value, job_id),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"UPDATE jobs SET state = ?, reason = ? WHERE id = ?",
|
||||
(JobState.FAILED.value, reason, job_id),
|
||||
)
|
||||
return [_select(conn, UUID(job_id)) for job_id, _ in rows]
|
||||
@@ -6,4 +6,22 @@ from typing import Final
|
||||
type Migration = Sequence[str]
|
||||
"""One migration: SQL statements, applied together in one transaction."""
|
||||
|
||||
MIGRATIONS: Final[tuple[Migration, ...]] = ()
|
||||
# No CHECK on jobs.state: changing it later would mean rebuilding the table.
|
||||
MIGRATIONS: Final[tuple[Migration, ...]] = (
|
||||
(
|
||||
"""
|
||||
CREATE TABLE jobs (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id TEXT NOT NULL UNIQUE,
|
||||
kind TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL,
|
||||
enqueued_at TEXT NOT NULL,
|
||||
result TEXT,
|
||||
reason TEXT
|
||||
) STRICT
|
||||
""",
|
||||
"CREATE INDEX jobs_state_seq ON jobs (state, seq)",
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,233 @@
|
||||
import os
|
||||
import threading
|
||||
from datetime import UTC, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from chemenu.adapters.sqlite.database import Database
|
||||
from chemenu.adapters.sqlite.job_queue import SqliteJobQueue
|
||||
from chemenu.domain.job import JobState, JsonObject
|
||||
from chemenu.ports.job_queue import InvalidTransitionError, JobNotFoundError, JobQueue
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(tmp_path: Path) -> Database:
|
||||
return Database(tmp_path / "db.sqlite")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def queue(db: Database) -> JobQueue:
|
||||
return SqliteJobQueue(db)
|
||||
|
||||
|
||||
def test_enqueue(queue: JobQueue) -> None:
|
||||
payload: JsonObject = {"a": [1, 2.5, None, True], "b": {"c": "d"}}
|
||||
job = queue.enqueue("k", payload)
|
||||
assert job.state is JobState.QUEUED
|
||||
assert job.id.version == 7
|
||||
assert job.kind == "k"
|
||||
assert job.attempts == 0
|
||||
assert job.payload == payload
|
||||
assert job.enqueued_at.utcoffset() == timedelta(0)
|
||||
assert job.result is None
|
||||
assert job.reason is None
|
||||
payload["a"] = "changed"
|
||||
assert queue.get(job.id).payload != payload
|
||||
|
||||
|
||||
def test_claim_oldest(queue: JobQueue) -> None:
|
||||
first = queue.enqueue("k", {})
|
||||
second = queue.enqueue("k", {})
|
||||
got = queue.claim()
|
||||
assert got is not None
|
||||
assert got.id == first.id
|
||||
assert got.state is JobState.RUNNING
|
||||
assert got.attempts == 1
|
||||
other = queue.claim()
|
||||
assert other is not None
|
||||
assert other.id == second.id
|
||||
|
||||
|
||||
def test_claim_empty(queue: JobQueue) -> None:
|
||||
assert queue.claim() is None
|
||||
job = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
assert queue.claim() is None
|
||||
assert queue.get(job.id).state is JobState.RUNNING
|
||||
|
||||
|
||||
def test_concurrent_claims_are_distinct(db: Database) -> None:
|
||||
count = 8
|
||||
queue = SqliteJobQueue(db)
|
||||
ids = {queue.enqueue("k", {}).id for _ in range(count)}
|
||||
barrier = threading.Barrier(count)
|
||||
claimed: list[UUID] = []
|
||||
errors: list[BaseException] = []
|
||||
|
||||
def work() -> None:
|
||||
try:
|
||||
barrier.wait(timeout=10)
|
||||
job = queue.claim()
|
||||
assert job is not None
|
||||
claimed.append(job.id)
|
||||
except BaseException as exc:
|
||||
errors.append(exc)
|
||||
|
||||
threads = [threading.Thread(target=work) for _ in range(count)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert errors == []
|
||||
assert sorted(claimed) == sorted(ids)
|
||||
assert queue.claim() is None
|
||||
|
||||
|
||||
def test_complete(queue: JobQueue) -> None:
|
||||
job = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
done = queue.complete(job.id, {"out": 1})
|
||||
assert done.state is JobState.DONE
|
||||
assert done.result == {"out": 1}
|
||||
assert done.reason is None
|
||||
assert queue.get(job.id) == done
|
||||
|
||||
|
||||
def test_fail(queue: JobQueue) -> None:
|
||||
job = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
failed = queue.fail(job.id, "boom")
|
||||
assert failed.state is JobState.FAILED
|
||||
assert failed.reason == "boom"
|
||||
assert failed.result is None
|
||||
assert queue.get(job.id) == failed
|
||||
|
||||
|
||||
def test_not_running_raises(queue: JobQueue) -> None:
|
||||
done = queue.enqueue("k", {})
|
||||
failed = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
queue.claim()
|
||||
queue.complete(done.id, {})
|
||||
queue.fail(failed.id, "x")
|
||||
queued = queue.enqueue("k", {})
|
||||
for job_id in (queued.id, done.id, failed.id):
|
||||
before = queue.get(job_id)
|
||||
with pytest.raises(InvalidTransitionError):
|
||||
queue.complete(job_id, {"x": 1})
|
||||
with pytest.raises(InvalidTransitionError):
|
||||
queue.fail(job_id, "y")
|
||||
assert queue.get(job_id) == before
|
||||
|
||||
|
||||
def test_unknown_job_raises(queue: JobQueue) -> None:
|
||||
unknown = uuid4()
|
||||
job = queue.enqueue("k", {})
|
||||
before = queue.claim()
|
||||
with pytest.raises(JobNotFoundError):
|
||||
queue.get(unknown)
|
||||
with pytest.raises(JobNotFoundError):
|
||||
queue.complete(unknown, {})
|
||||
with pytest.raises(JobNotFoundError):
|
||||
queue.fail(unknown, "x")
|
||||
assert queue.get(job.id) == before
|
||||
|
||||
|
||||
def test_jobs_survive_reopen(tmp_path: Path) -> None:
|
||||
path = tmp_path / "db.sqlite"
|
||||
job = SqliteJobQueue(Database(path)).enqueue("k", {"a": 1})
|
||||
assert SqliteJobQueue(Database(path)).get(job.id) == job
|
||||
|
||||
|
||||
def test_open_does_not_recover(tmp_path: Path) -> None:
|
||||
path = tmp_path / "db.sqlite"
|
||||
job = SqliteJobQueue(Database(path)).enqueue("k", {})
|
||||
SqliteJobQueue(Database(path)).claim()
|
||||
assert SqliteJobQueue(Database(path)).get(job.id).state is JobState.RUNNING
|
||||
|
||||
|
||||
def test_recover_keeps_place(queue: JobQueue) -> None:
|
||||
first = queue.enqueue("k", {})
|
||||
second = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
recovered = queue.recover()
|
||||
assert [j.id for j in recovered] == [first.id]
|
||||
assert recovered[0].state is JobState.QUEUED
|
||||
again = queue.claim()
|
||||
assert again is not None
|
||||
assert again.id == first.id
|
||||
assert again.attempts == 2
|
||||
nxt = queue.claim()
|
||||
assert nxt is not None
|
||||
assert nxt.id == second.id
|
||||
|
||||
|
||||
def test_recover_fails_after_max_attempts(db: Database) -> None:
|
||||
queue = SqliteJobQueue(db, max_attempts=2)
|
||||
job = queue.enqueue("k", {})
|
||||
untouched = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
assert [j.state for j in queue.recover()] == [JobState.QUEUED]
|
||||
queue.claim()
|
||||
recovered = queue.recover()
|
||||
assert [j.id for j in recovered] == [job.id]
|
||||
assert recovered[0].state is JobState.FAILED
|
||||
assert recovered[0].reason == "aborted after 2 attempts"
|
||||
assert queue.get(untouched.id).state is JobState.QUEUED
|
||||
assert queue.recover() == []
|
||||
|
||||
|
||||
def test_recover_allows_three_attempts_by_default(queue: JobQueue) -> None:
|
||||
job = queue.enqueue("k", {})
|
||||
for attempt in (1, 2):
|
||||
queue.claim()
|
||||
assert [(j.state, j.attempts) for j in queue.recover()] == [(JobState.QUEUED, attempt)]
|
||||
queue.claim()
|
||||
assert queue.recover() == [queue.get(job.id)]
|
||||
assert queue.get(job.id).state is JobState.FAILED
|
||||
assert queue.get(job.id).reason == "aborted after 3 attempts"
|
||||
|
||||
|
||||
def test_nan_payload_is_rejected(queue: JobQueue) -> None:
|
||||
with pytest.raises(ValueError, match="JSON"):
|
||||
queue.enqueue("k", {"x": float("nan")})
|
||||
assert queue.claim() is None
|
||||
|
||||
|
||||
def test_nan_result_leaves_job_running(queue: JobQueue) -> None:
|
||||
job = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
with pytest.raises(ValueError, match="JSON"):
|
||||
queue.complete(job.id, {"x": float("nan")})
|
||||
assert queue.get(job.id).state is JobState.RUNNING
|
||||
assert queue.fail(job.id, "bad result").state is JobState.FAILED
|
||||
|
||||
|
||||
def test_fail_accepts_undecodable_reason(queue: JobQueue) -> None:
|
||||
job = queue.enqueue("k", {})
|
||||
queue.claim()
|
||||
failed = queue.fail(job.id, os.fsdecode(b"bad \xff"))
|
||||
assert failed.state is JobState.FAILED
|
||||
assert failed.reason == "bad \\udcff"
|
||||
|
||||
|
||||
def test_naive_clock_is_rejected(db: Database) -> None:
|
||||
queue = SqliteJobQueue(db, clock=lambda: datetime(2026, 1, 1))
|
||||
with pytest.raises(ValueError, match="aware"):
|
||||
queue.enqueue("k", {})
|
||||
assert queue.claim() is None
|
||||
|
||||
|
||||
def test_enqueued_at_is_utc(db: Database) -> None:
|
||||
tz = timezone(timedelta(hours=2))
|
||||
queue = SqliteJobQueue(db, clock=lambda: datetime(2026, 1, 1, 12, tzinfo=tz))
|
||||
job = queue.enqueue("k", {})
|
||||
assert job.enqueued_at == datetime(2026, 1, 1, 10, tzinfo=UTC)
|
||||
assert job.enqueued_at.utcoffset() == timedelta(0)
|
||||
|
||||
|
||||
def test_invalid_max_attempts(db: Database) -> None:
|
||||
with pytest.raises(ValueError, match="max_attempts"):
|
||||
SqliteJobQueue(db, max_attempts=0)
|
||||
Reference in new issue
Block a user