Compare commits

...
5 Commits
Author SHA1 Message Date
torbenandClaude Sonnet 5.5 1db38992cd Add SQLite job queue with jobs migration
CI / checks (pull_request) Successful in 45s
Atomic claim, terminal transitions and recover() that requeues at the old place.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 23:32:22 +01:00
torbenandClaude Sonnet 5.5 cef1a48b69 Add Job domain type and JobQueue port
Job lifecycle states, JSON types and the queue protocol with its errors.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 23:32:22 +01:00
torbenandClaude Sonnet 5.5 776cef7bc3 Add SQLite database adapter with versioned migrations
Open, create, migrate or reject a file by user_version; reject newer files
before switching to WAL. transaction() gives one BEGIN IMMEDIATE per operation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 23:32:22 +01:00
torbenandClaude Sonnet 5.5 2be30e6a3b Extend ADR 0012 and glossary for the database port
Adds port per need, migration path and WAL note to ADR 0012, links
ADR 0027, and adds four glossary terms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 23:32:22 +01:00
torbenandClaude Sonnet 5.5 6b7bca9746 Add ADR 0027: synchronous core and job queue
Records sync core with async edge, at-least-once delivery with
three attempts, and UUIDv7 jobs. Linked from architecture.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 23:32:22 +01:00
12 changed files with 950 additions and 2 deletions

No files matched your search

+4 -1
View File
@@ -32,6 +32,7 @@ Chemenu ist ein Dienst, der LLMs für eng umrissene Urteile aufruft: Code führt
| [0024](decisions/0024-schritt-bausteine-und-evals.md) | Schritt-Bausteine statt `instructions/`, Bewerter nach Vorrang, Testkorpus | Ort des Testkorpus: #21 | | [0024](decisions/0024-schritt-bausteine-und-evals.md) | Schritt-Bausteine statt `instructions/`, Bewerter nach Vorrang, Testkorpus | Ort des Testkorpus: #21 |
| [0025](decisions/0025-prozessor-plugins.md) | Plugin mit Manifest (M1–M13), Exemplar als Definition der Instanz, kein Fremdcode im Dienst | | | [0025](decisions/0025-prozessor-plugins.md) | Plugin mit Manifest (M1–M13), Exemplar als Definition der Instanz, kein Fremdcode im Dienst | |
| [0026](decisions/0026-lage-der-schritt-bausteine.md) | Schritt-Bausteine im Stack-Paket `steps`, `string.Template`, Nummer und Fingerabdruck | | | [0026](decisions/0026-lage-der-schritt-bausteine.md) | Schritt-Bausteine im Stack-Paket `steps`, `string.Template`, Nummer und Fingerabdruck | |
| [0027](decisions/0027-synchroner-kern-und-job-queue.md) | Synchroner Kern, `async` am Rand; Jobs mindestens einmal, höchstens drei Versuche; UUIDv7 | |
## Abläufe ## Abläufe
@@ -92,9 +93,11 @@ flowchart LR
* `domain`: reine Funktionen und Typen zu Seiten, Links und Herkunftsnachweisen. Kein I/O, keine Konfiguration. * `domain`: reine Funktionen und Typen zu Seiten, Links und Herkunftsnachweisen. Kein I/O, keine Konfiguration.
* `ports`: Schnittstellen (`typing.Protocol`), die die Anwendung braucht. Hängt nur von der Domäne ab. * `ports`: Schnittstellen (`typing.Protocol`), die die Anwendung braucht. Hängt nur von der Domäne ab.
* `application`: Anwendungsfälle, einer pro Job. Rechteprüfung und Transaktionsgrenzen liegen hier. Hängt nur von Domäne und Ports ab. * `application`: Anwendungsfälle, einer pro Job. Rechteprüfung und Transaktionsgrenzen (git-Commit je Entscheidungseinheit) liegen hier; Datenbank-Transaktionen liegen im Adapter ([ADR 0012](decisions/0012-sqlite-als-standard.md)). Hängt nur von Domäne und Ports ab.
* `adapters`: Implementierungen der Ports (Git, Dateisystem, Datenbank, LLM, HTTP). Instanz und Nutzer kommen als expliziter Kontext, nie als Modul-Global. * `adapters`: Implementierungen der Ports (Git, Dateisystem, Datenbank, LLM, HTTP). Instanz und Nutzer kommen als expliziter Kontext, nie als Modul-Global.
Der Kern (`domain`, `ports`, `application`, Job-Adapter) ist synchron, Jobs laufen in Threads; nur der HTTP-Adapter und ein streamender Port (Chat) dürfen `async` sein, der HTTP-Adapter ruft den Kern über den Threadpool: [ADR 0027](decisions/0027-synchroner-kern-und-job-queue.md).
`import-linter` erzwingt die Importrichtung in pre-commit und CI; die Verträge stehen in `pyproject.toml`. `chemenu/__init__.py` importiert keine Schicht. `import-linter` erzwingt die Importrichtung in pre-commit und CI; die Verträge stehen in `pyproject.toml`. `chemenu/__init__.py` importiert keine Schicht.
Neben den Schichten steht ein Werkzeug: Neben den Schichten steht ein Werkzeug:
+22 -1
View File
@@ -1,6 +1,6 @@
--- ---
status: accepted status: accepted
date: 2026-12-02 date: 2026-12-03
--- ---
# SQLite als Standard, Postgres als Option, Datenbank hinter einem Port # SQLite als Standard, Postgres als Option, Datenbank hinter einem Port
@@ -40,6 +40,27 @@ Die Datenbank liegt hinter einem Port: SQLite (FTS5, sqlite-vec) als Standard, P
Mehrere Worker-Knoten sind später nachrüstbar. Mehrere Worker-Knoten sind später nachrüstbar.
### Port je Bedarf
Das präzisiert „hinter einem Port“: Es gibt keinen großen Datenbank-Port, sondern einen Port je Bedarf (jetzt die Job-Queue, später etwa der Suchindex). Regeln:
* Was gemeinsam gelten muss, gehört in denselben Port.
* Es gibt eine Datenbankdatei.
* Adapter holen ihre Transaktionen aus `Database.transaction()`, je Operation eines Ports eine. Die Transaktionsgrenze des Anwendungsfalls ([ADR 0018](0018-backend-und-clients.md)) ist der git-Commit.
* Reicht das nicht, kommt eine Unit of Work dazu, eine gemeinsame Transaktion mehrerer Ports.
### Migrationsweg
Die Schemata migriert ein eigener Läufer, nur vorwärts. Zu SQLAlchemy Core und Alembic wechselt das Projekt, sobald Postgres gebraucht wird und zwei Schemata zu pflegen sind. Damit das möglich bleibt, gilt: SQL nur im Adapter, keine Trigger, keine SQLite-Typen in Ports.
### Dateisystem
WAL verlangt ein lokales Dateisystem. Die Datenbankdatei liegt nicht auf einem Netzlaufwerk; ohne WAL startet der Dienst nicht.
### Job-Queue
Die Queue hinter ihrem Port folgt [ADR 0027](0027-synchroner-kern-und-job-queue.md): synchroner Kern, Zustellung mindestens einmal, Job-Id als UUIDv7.
### Konsequenzen ### Konsequenzen
* Gut, weil SQLite eine Datei ist und keinen eigenen Dienst braucht. * Gut, weil SQLite eine Datei ist und keinen eigenen Dienst braucht.
@@ -0,0 +1,86 @@
---
status: accepted
date: 2026-12-03
---
# Synchroner Kern mit `async` am Rand, Job-Queue mit Zustellung mindestens einmal
## Kontext und Problemstellung
Der Dienst hat einen Kern aus Anwendungsfällen und einen HTTP-Rand mit SSE und MCP ([ADR 0018](0018-backend-und-clients.md)). Der Kern ist überwiegend blockierend: SQLite, git, Rechenzeit. Zugleich laufen Jobs in der Queue, und git und Datenbank teilen keine Transaktion (Rollen beider: [ADR 0011](0011-dienst-als-einziger-schreiber.md), Datenbank: [ADR 0012](0012-sqlite-als-standard.md)).
Ist der Kern synchron oder `async`? Wie überstehen Jobs einen Absturz, ohne doppelt zu wirken? Woran erkennt man einen Job, und was speichert die Queue von ihm? Auftrag: #16.
Bezüge: Phase A läuft parallel, Phase B seriell ([ADR 0004](0004-ingest-in-zwei-phasen.md)). Der Chat ist ein Gesprächspartner mit Lesewerkzeugen ([ADR 0021](0021-chat-mit-der-wissensbasis.md)), der Not-Aus Teil der Kostenbegrenzung ([ADR 0022](0022-budgets-und-not-aus.md)). Eine Instanz bedient eine Wissensbasis ([ADR 0017](0017-deployment.md)).
## Betrachtete Optionen
Kern:
1. Synchroner Kern, `async` am Rand.
2. Durchgehend `async`.
3. Anwendung `async` mit synchronen Ports.
Zustellung:
1. Mindestens einmal, höchstens drei Versuche.
2. Unbegrenzt wieder einreihen.
3. Nie wieder einreihen.
Job:
1. UUIDv7, Eingabe und Ergebnis als JSON.
2. Laufende Nummer als Kennung.
3. Eine Tabelle je Job-Art.
4. Kein Ergebnis in der Queue.
## Entscheidung
### Synchroner Kern, `async` am Rand
Gewählte Option: „Synchroner Kern, `async` am Rand“. `domain`, `ports`, `application` und die Adapter für Jobs sind synchron, Jobs laufen in Threads. Der HTTP-Adapter darf `async` sein (SSE, MCP) und ruft den Kern über den Threadpool. Benannte Ausnahme ist ein streamender Port (Chat, M5; [ADR 0021](0021-chat-mit-der-wissensbasis.md)).
Grund: Der Kern ist überwiegend blockierend. Ein blockierender Aufruf in der Ereignisschleife hält alles an. Gemessen (Python 3.14.10): 520 ms Stillstand bei 0,5 s Blockade, 46 ms über `to_thread`; 200 wartende Threads kosten rund 4 MB.
Preis: Der Not-Aus ([ADR 0022](0022-budgets-und-not-aus.md)) wirkt zwischen Schritten, dazu kommt ein Timeout je LLM-Aufruf. Es gibt zwei Stile, synchron im Kern und `async` am Rand.
Kippen würde die Entscheidung, wenn ein Prozess viele Instanzen und Hunderte Chats bedient; eine Instanz je Wissensbasis ([ADR 0017](0017-deployment.md)) spricht dagegen.
Verworfen:
* Durchgehend `async`: `to_thread` in fast jedem Adapter.
* Anwendung `async` mit synchronen Ports: Die Ports blockieren die Schleife.
### Mindestens einmal
Gewählte Option: „Mindestens einmal, höchstens drei Versuche“. git und Datenbank teilen keine Transaktion. Nach einem Absturz wird ein Job wieder eingereiht, höchstens drei Versuche. Fehler im Job werden nie wiederholt. Der Anwendungsfall schreibt die Job-Id in den Commit und prüft sie vor dem Anwenden (#19); so wirkt ein wiederholter Job nicht doppelt.
Das Wiedereinreihen ist ein eigener Aufruf `recover()`, den nur der Worker beim Start macht. Das Öffnen der Datenbank ändert keinen Job, sonst startete ein zweiter Prozess laufende Jobs doppelt. Wieder Eingereihte behalten ihren Platz.
Preis: Jeder Anwendungsfall muss die Job-Id prüfen. Drei harmlose Neustarts mitten im selben Job lassen auch ihn fehlschlagen.
Verworfen:
* Unbegrenzt: Endlosschleife mit LLM-Kosten.
* Nie: Handarbeit nach jedem Absturz, das widerspricht [ADR 0011](0011-dienst-als-einziger-schreiber.md).
### Job
Gewählte Option: „UUIDv7, Eingabe und Ergebnis als JSON“. Eine laufende Nummer finge nach Verlust der Datenbank neu an, und alte Commits zeigten auf fremde Jobs. Eingabe und Ergebnis sind JSON und für die Queue undurchsichtig; die Eingabe verweist nur auf kanonische Daten.
Preis: Die Queue bemerkt falsche Felder nicht, das prüft der Anwendungsfall. Die Id ist lang.
Verworfen:
* Laufende Nummer: beginnt nach Verlust der Datenbank neu.
* Tabelle je Job-Art: Jede neue Art braucht eine Migration.
* Kein Ergebnis: Jede Statusabfrage durchsuchte die Historie.
### Konsequenzen
* Gut, weil ein blockierender Aufruf die Ereignisschleife nicht anhält.
* Gut, weil der Kern einen Stil hat und ohne Ereignisschleife testbar ist.
* Gut, weil ein Absturz keine Handarbeit verlangt und die Job-Id im Commit Doppelwirkung erkennbar macht.
* Gut, weil die Job-Id auch nach Verlust der Datenbank eindeutig bleibt.
* Schlecht, weil der Not-Aus nur zwischen Schritten wirkt und jeder LLM-Aufruf ein Timeout braucht.
* Schlecht, weil es zwei Stile gibt und der streamende Port eine Ausnahme ist.
* Schlecht, weil jeder Anwendungsfall die Job-Id prüfen muss (#19).
+4
View File
@@ -41,8 +41,10 @@ Feste Begriffspaare Deutsch–Englisch. In der Doku steht das deutsche Wort, im
| Instanz | instance | eine Wissensbasis als git-Repo samt laufendem Dienst | | Instanz | instance | eine Wissensbasis als git-Repo samt laufendem Dienst |
| Inventar | inventory | Aussagen, Begründungen, Abläufe, Zahlen, Entitäten und Konzepte einer Quelle, je mit Fundstelle | | Inventar | inventory | Aussagen, Begründungen, Abläufe, Zahlen, Entitäten und Konzepte einer Quelle, je mit Fundstelle |
| Job | job | Arbeitsauftrag, den ein Anwendungsfall abarbeitet | | Job | job | Arbeitsauftrag, den ein Anwendungsfall abarbeitet |
| Job-Queue | job queue | Reihe der Jobs mit ihren Zuständen |
| Korrektur | correction | Notiz mit Ziel (Seite oder Aussage): „Das stimmt nicht, richtig ist …“ | | Korrektur | correction | Notiz mit Ziel (Seite oder Aussage): „Das stimmt nicht, richtig ist …“ |
| Manifest | manifest | Deklaration eines Plugins (M1–M13) | | Manifest | manifest | Deklaration eines Plugins (M1–M13) |
| Migration (Schema) | migration | Schritt von einer Schemaversion zur nächsten |
| Nachtrag | addendum | Kommentar zu einer Quelle, als neue Datei in ihr Bundle gelegt | | Nachtrag | addendum | Kommentar zu einer Quelle, als neue Datei in ihr Bundle gelegt |
| Not-Aus | kill switch | Teil der Kostenbegrenzung neben Tages- und Job-Budget | | Not-Aus | kill switch | Teil der Kostenbegrenzung neben Tages- und Job-Budget |
| Notausgang | escape hatch | Weg für Sonderfälle; Startpunkt ist ein Agent als API-Client unter derselben Ampel (offen) | | Notausgang | escape hatch | Weg für Sonderfälle; Startpunkt ist ein Agent als API-Client unter derselben Ampel (offen) |
@@ -72,7 +74,9 @@ Feste Begriffspaare Deutsch–Englisch. In der Doku steht das deutsche Wort, im
| Teilanwendung | partial application | grüne Teile eines Jobs laufen sofort, offene warten auf ihre Antwort | | Teilanwendung | partial application | grüne Teile eines Jobs laufen sofort, offene warten auf ihre Antwort |
| Testkorpus | test corpus | kuratierter Korpus von 20–30 Quellen mit erwarteten Eigenschaften, zugleich erster Eval-Satz | | Testkorpus | test corpus | kuratierter Korpus von 20–30 Quellen mit erwarteten Eigenschaften, zugleich erster Eval-Satz |
| Type-Spec | type spec | legt pro Abschnitt fest, ob er fortgeschrieben oder integriert wird | | Type-Spec | type spec | legt pro Abschnitt fest, ob er fortgeschrieben oder integriert wird |
| Unit of Work | unit of work | gemeinsame Transaktion mehrerer Ports |
| Verbleib | disposition | Ort (Seite und Abschnitt) eines Inventar-Eintrags oder Grund, warum er übersprungen wird | | Verbleib | disposition | Ort (Seite und Abschnitt) eines Inventar-Eintrags oder Grund, warum er übersprungen wird |
| Versuch | attempt | einmal Holen eines Jobs |
| Wissensbasis | knowledge base | Gesamtheit der Seiten | | Wissensbasis | knowledge base | Gesamtheit der Seiten |
| Worker | worker | Rolle für extrahieren, zuordnen, schreiben: zustandsloser Aufruf mit kleinem Kontext und Ausgabeschema | | Worker | worker | Rolle für extrahieren, zuordnen, schreiben: zustandsloser Aufruf mit kleinem Kontext und Ausgabeschema |
| Zustandsklasse | state class | kanonisch, abgeleitet oder betrieblich | | Zustandsklasse | state class | kanonisch, abgeleitet oder betrieblich |
+1
View File
@@ -0,0 +1 @@
"""SQLite adapter."""
+123
View File
@@ -0,0 +1,123 @@
"""SQLite database: open, create, migrate or reject a file; per-operation transactions."""
import sqlite3
import time
from collections.abc import Generator, Sequence
from contextlib import closing, contextmanager
from pathlib import Path
from typing import Literal
from chemenu.adapters.sqlite.migrations import MIGRATIONS, Migration
_TIMEOUT_SECONDS = 5
_RETRY_SECONDS = 0.01
class DatabaseTooNewError(Exception):
"""The database file has a newer schema than this code knows."""
class WalUnavailableError(Exception):
"""SQLite cannot use WAL here, for example on a network file system."""
def _user_version(conn: sqlite3.Connection) -> int:
row = conn.execute("PRAGMA user_version").fetchone()
return int(row[0])
def _switch_to_wal(conn: sqlite3.Connection) -> None:
"""Switch to WAL, retrying while the file is locked.
SQLite can report a lock here without waiting for the connection's timeout.
"""
deadline = time.monotonic() + _TIMEOUT_SECONDS
while True:
try:
row = conn.execute("PRAGMA journal_mode=WAL").fetchone()
except sqlite3.OperationalError as error:
# The low byte is the primary code; extended codes such as
# SQLITE_BUSY_RECOVERY are retried too.
busy = error.sqlite_errorcode & 0xFF == sqlite3.SQLITE_BUSY
if not busy or time.monotonic() >= deadline:
raise
time.sleep(_RETRY_SECONDS)
else:
# Without WAL support the pragma does not fail but keeps the old mode.
if row[0] != "wal":
raise WalUnavailableError(f"journal mode is {row[0]!r}")
return
def _rollback(conn: sqlite3.Connection) -> None:
"""Roll back unless SQLite already did, which would mask the original error."""
if conn.in_transaction:
conn.execute("ROLLBACK")
class Database:
"""One database file; the constructor creates, migrates or rejects it."""
def __init__(self, path: Path, migrations: Sequence[Migration] = MIGRATIONS) -> None:
self._path = path.resolve()
self._migrations = migrations
self._open_and_migrate()
def _connect(self, mode: Literal["rw", "rwc"]) -> sqlite3.Connection:
uri = f"{self._path.as_uri()}?mode={mode}"
return sqlite3.connect(uri, uri=True, autocommit=True, timeout=_TIMEOUT_SECONDS)
def _too_new(self, version: int) -> DatabaseTooNewError:
return DatabaseTooNewError(
f"{self._path}: schema version {version} is newer than the "
f"{len(self._migrations)} known migrations"
)
def _open_and_migrate(self) -> None:
target = len(self._migrations)
with closing(self._connect("rwc")) as conn:
# Reject before touching the file: both switching the journal mode and
# checkpointing a leftover WAL on close would modify it.
conn.setconfig(sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, True)
version = _user_version(conn)
if version > target:
raise self._too_new(version)
conn.setconfig(sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, False)
_switch_to_wal(conn)
while version < target:
version = self._apply_next(conn)
def _apply_next(self, conn: sqlite3.Connection) -> int:
"""Apply the next pending migration; return the resulting schema version."""
conn.execute("BEGIN IMMEDIATE")
try:
# Re-read inside the write lock: another opener may have migrated meanwhile.
version = _user_version(conn)
if version > len(self._migrations):
raise self._too_new(version)
if version < len(self._migrations):
for statement in self._migrations[version]:
conn.execute(statement)
version += 1
conn.execute(f"PRAGMA user_version = {version}")
conn.execute("COMMIT")
except BaseException:
_rollback(conn)
raise
return version
@contextmanager
def transaction(self) -> Generator[sqlite3.Connection]:
"""Yield a connection inside BEGIN IMMEDIATE; commit, or roll back on any exception."""
# Never create here: an empty file without the schema would hide the loss.
conn = self._connect("rw")
try:
conn.execute("BEGIN IMMEDIATE")
try:
yield conn
except BaseException:
_rollback(conn)
raise
conn.execute("COMMIT")
finally:
conn.close()
+136
View File
@@ -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]
+27
View File
@@ -0,0 +1,27 @@
"""Schema migrations. The schema version of a file is the number of applied migrations."""
from collections.abc import Sequence
from typing import Final
type Migration = Sequence[str]
"""One migration: SQL statements, applied together in one transaction."""
# 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)",
),
)
+28
View File
@@ -0,0 +1,28 @@
"""Job: a unit of queued work and its lifecycle state."""
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from uuid import UUID
type JsonValue = str | int | float | bool | list[JsonValue] | dict[str, JsonValue] | None
type JsonObject = dict[str, JsonValue]
class JobState(StrEnum):
QUEUED = "queued"
RUNNING = "running"
DONE = "done"
FAILED = "failed"
@dataclass(frozen=True, slots=True, kw_only=True)
class Job:
id: UUID
kind: str
payload: JsonObject
state: JobState
attempts: int
enqueued_at: datetime # aware, UTC
result: JsonObject | None = None
reason: str | None = None
+40
View File
@@ -0,0 +1,40 @@
"""Port: a durable queue of jobs."""
from typing import Protocol
from uuid import UUID
from chemenu.domain.job import Job, JsonObject
class JobNotFoundError(Exception):
"""No job with the given id exists."""
class InvalidTransitionError(Exception):
"""The job is not in a state that allows the requested change."""
class JobQueue(Protocol):
def enqueue(self, kind: str, payload: JsonObject) -> Job:
"""Add a queued job; ValueError if the payload is not valid JSON."""
...
def claim(self) -> Job | None:
"""Atomically move the oldest queued job to running; None if there is none."""
...
def complete(self, job_id: UUID, result: JsonObject) -> Job:
"""Move a running job to done.
ValueError if the result is not valid JSON; the job stays running, so the
caller must call `fail`.
"""
...
def fail(self, job_id: UUID, reason: str) -> Job: ...
def get(self, job_id: UUID) -> Job: ...
def recover(self) -> list[Job]:
"""Requeue or fail jobs left running; only a starting worker calls this."""
...
+246
View File
@@ -0,0 +1,246 @@
import shutil
import sqlite3
import threading
import time
from contextlib import closing
from pathlib import Path
import pytest
from chemenu.adapters.sqlite.database import (
Database,
DatabaseTooNewError,
WalUnavailableError,
)
from chemenu.adapters.sqlite.migrations import MIGRATIONS, Migration
M1: Migration = ["CREATE TABLE a (x INTEGER)"]
M2: Migration = ["CREATE TABLE b (y INTEGER)", "INSERT INTO b VALUES (1)"]
def _version(path: Path) -> int:
conn = sqlite3.connect(path)
try:
return int(conn.execute("PRAGMA user_version").fetchone()[0])
finally:
conn.close()
def _tables(path: Path) -> set[str]:
conn = sqlite3.connect(path)
try:
rows = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
return {r[0] for r in rows}
finally:
conn.close()
def _journal_mode(path: Path) -> str:
with closing(sqlite3.connect(path)) as conn:
return str(conn.execute("PRAGMA journal_mode").fetchone()[0])
def _no_sidecars(path: Path) -> None:
assert not Path(f"{path}-wal").exists()
assert not Path(f"{path}-shm").exists()
def test_missing_file_is_created(tmp_path: Path) -> None:
path = tmp_path / "db.sqlite"
Database(path, [M1, M2])
assert _version(path) == 2
assert _tables(path) == {"a", "b"}
assert _journal_mode(path) == "wal"
_no_sidecars(path)
def test_older_schema_is_migrated(tmp_path: Path) -> None:
path = tmp_path / "db.sqlite"
db = Database(path, [M1])
with db.transaction() as conn:
conn.execute("INSERT INTO a VALUES (7)")
assert _version(path) == 1
migrated = Database(path, [M1, M2])
with migrated.transaction() as conn:
assert conn.execute("SELECT x FROM a").fetchall() == [(7,)]
assert _version(path) == 2
assert _tables(path) == {"a", "b"}
_no_sidecars(path)
@pytest.mark.parametrize("wal", [False, True])
def test_newer_schema_is_rejected_unchanged(tmp_path: Path, *, wal: bool) -> None:
path = tmp_path / "db.sqlite"
conn = sqlite3.connect(path, autocommit=True)
conn.execute(f"PRAGMA journal_mode={'WAL' if wal else 'DELETE'}")
conn.execute("CREATE TABLE a (x INTEGER)")
conn.execute("CREATE TABLE b (y INTEGER)")
conn.execute("PRAGMA user_version = 2")
conn.close()
before = path.read_bytes()
with pytest.raises(DatabaseTooNewError):
Database(path, [M1])
assert path.read_bytes() == before
if not wal:
_no_sidecars(path)
def test_newer_schema_with_leftover_wal_is_rejected_unchanged(tmp_path: Path) -> None:
source = tmp_path / "source.sqlite"
path = tmp_path / "db.sqlite"
with closing(sqlite3.connect(source, autocommit=True)) as conn:
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA user_version = 2")
# Copy while open: this is what a crash leaves behind.
for suffix in ("", "-wal"):
shutil.copy(f"{source}{suffix}", f"{path}{suffix}")
wal = Path(f"{path}-wal")
before = (path.read_bytes(), wal.read_bytes())
with pytest.raises(DatabaseTooNewError):
Database(path, [M1])
assert (path.read_bytes(), wal.read_bytes()) == before
def test_failed_migration_rolls_back(tmp_path: Path) -> None:
path = tmp_path / "db.sqlite"
Database(path, [M1])
bad: Migration = ["CREATE TABLE c (z INTEGER)", "THIS IS NOT SQL"]
with pytest.raises(sqlite3.Error):
Database(path, [M1, bad])
assert _version(path) == 1
assert _tables(path) == {"a"}
_no_sidecars(path)
def test_concurrent_first_open(tmp_path: Path) -> None:
path = tmp_path / "db.sqlite"
count = 6
barrier = threading.Barrier(count)
errors: list[BaseException] = []
migrations: list[Migration] = [["CREATE TABLE a (x INTEGER)"], ["CREATE TABLE b (y INTEGER)"]]
def work() -> None:
try:
barrier.wait(timeout=10)
Database(path, migrations)
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 _version(path) == 2
assert _tables(path) == {"a", "b"}
_no_sidecars(path)
def test_open_waits_for_lock_on_first_open(tmp_path: Path) -> None:
path = tmp_path / "db.sqlite"
locked = threading.Event()
def hold_lock() -> None:
with closing(sqlite3.connect(path, autocommit=True)) as conn:
conn.execute("BEGIN IMMEDIATE")
locked.set()
time.sleep(0.2)
conn.execute("ROLLBACK")
holder = threading.Thread(target=hold_lock)
holder.start()
assert locked.wait(timeout=10)
Database(path, [M1])
holder.join()
assert _version(path) == 1
def test_open_gives_up_when_lock_is_held(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
path = tmp_path / "db.sqlite"
monkeypatch.setattr("chemenu.adapters.sqlite.database._TIMEOUT_SECONDS", 0.1)
with closing(sqlite3.connect(path, autocommit=True)) as conn:
# A write lock leaves reading the version possible but blocks the WAL switch.
conn.execute("BEGIN IMMEDIATE")
with pytest.raises(sqlite3.OperationalError, match="locked"):
Database(path, [M1])
def test_missing_wal_support_is_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
connect = sqlite3.connect
def in_memory(*_args: object, **_kwargs: object) -> sqlite3.Connection:
return connect(":memory:", autocommit=True)
monkeypatch.setattr("chemenu.adapters.sqlite.database.sqlite3.connect", in_memory)
with pytest.raises(WalUnavailableError):
Database(tmp_path / "db.sqlite", [M1])
def test_relative_path_survives_chdir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.chdir(tmp_path)
db = Database(Path("db.sqlite"), [M1])
(tmp_path / "sub").mkdir()
monkeypatch.chdir(tmp_path / "sub")
with db.transaction() as conn:
conn.execute("INSERT INTO a VALUES (1)")
assert list((tmp_path / "sub").iterdir()) == []
def _begin(db: Database) -> None:
with db.transaction():
pass
def test_file_missing_at_runtime_is_not_recreated(tmp_path: Path) -> None:
path = tmp_path / "db.sqlite"
db = Database(path, [M1])
path.unlink()
with pytest.raises(sqlite3.OperationalError):
_begin(db)
assert not path.exists()
def test_path_with_special_characters(tmp_path: Path) -> None:
path = tmp_path / "a b%20?#ä.sqlite"
_begin(Database(path, [M1]))
assert [p.name for p in tmp_path.iterdir()] == [path.name]
def test_migrations_are_statement_sequences() -> None:
# A forgotten comma makes a one-statement migration a plain string.
assert all(not isinstance(migration, str) for migration in MIGRATIONS)
def _insert_then_raise(db: Database, value: int, exc: type[BaseException]) -> None:
with db.transaction() as conn:
conn.execute("INSERT INTO a VALUES (?)", (value,))
raise exc
def _roll_back_then_raise(db: Database) -> None:
with db.transaction() as conn:
# SQLite rolls back on its own on errors such as a full disk.
conn.execute("ROLLBACK")
raise ValueError("original")
def test_transaction_rolls_back_on_error(tmp_path: Path) -> None:
path = tmp_path / "db.sqlite"
db = Database(path, [M1])
with db.transaction() as conn:
conn.execute("INSERT INTO a VALUES (1)")
with pytest.raises(KeyboardInterrupt):
_insert_then_raise(db, 2, KeyboardInterrupt)
with pytest.raises(RuntimeError):
_insert_then_raise(db, 3, RuntimeError)
with db.transaction() as conn:
rows = conn.execute("SELECT x FROM a").fetchall()
assert rows == [(1,)]
_no_sidecars(path)
def test_error_is_not_masked_when_sqlite_already_rolled_back(tmp_path: Path) -> None:
db = Database(tmp_path / "db.sqlite", [M1])
with pytest.raises(ValueError, match="original"):
_roll_back_then_raise(db)
+233
View File
@@ -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)