qaechi-parser 2.0.0__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {qaechi_parser-2.0.0/qaechi_parser.egg-info → qaechi_parser-2.2.0}/PKG-INFO +15 -4
  2. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/README.md +4 -1
  3. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/pyproject.toml +16 -3
  4. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/__init__.py +1 -1
  5. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/api.py +22 -4
  6. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/cli.py +21 -0
  7. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/config.py +58 -0
  8. qaechi_parser-2.2.0/qaechi/parser/jobqueue.py +158 -0
  9. qaechi_parser-2.2.0/qaechi/parser/pgstore.py +146 -0
  10. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/__init__.py +31 -6
  11. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/graph.py +7 -2
  12. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/schemas.py +2 -0
  13. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/store.py +45 -5
  14. qaechi_parser-2.2.0/qaechi/parser/telemetry.py +208 -0
  15. qaechi_parser-2.2.0/qaechi/parser/worker.py +180 -0
  16. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0/qaechi_parser.egg-info}/PKG-INFO +15 -4
  17. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi_parser.egg-info/SOURCES.txt +8 -1
  18. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi_parser.egg-info/requires.txt +13 -2
  19. qaechi_parser-2.2.0/tests/test_integration.py +112 -0
  20. qaechi_parser-2.2.0/tests/test_telemetry.py +80 -0
  21. qaechi_parser-2.2.0/tests/test_worker.py +148 -0
  22. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/LICENSE +0 -0
  23. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/NOTICE +0 -0
  24. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/__main__.py +0 -0
  25. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/llm.py +0 -0
  26. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/parsers/__init__.py +0 -0
  27. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/parsers/ledger.py +0 -0
  28. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/chunk.py +0 -0
  29. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/extract.py +0 -0
  30. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/grade.py +0 -0
  31. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/index.py +0 -0
  32. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/load.py +0 -0
  33. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/nodes.py +0 -0
  34. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/prompts.py +0 -0
  35. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/retrieve.py +0 -0
  36. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/state.py +0 -0
  37. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/pipeline/verbatim.py +0 -0
  38. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/registry.py +0 -0
  39. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi/parser/sources.py +0 -0
  40. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi_parser.egg-info/dependency_links.txt +0 -0
  41. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi_parser.egg-info/entry_points.txt +0 -0
  42. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/qaechi_parser.egg-info/top_level.txt +0 -0
  43. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/setup.cfg +0 -0
  44. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/tests/test_api.py +0 -0
  45. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/tests/test_ledger.py +0 -0
  46. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/tests/test_loaders.py +0 -0
  47. {qaechi_parser-2.0.0 → qaechi_parser-2.2.0}/tests/test_pipeline.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: qaechi-parser
3
- Version: 2.0.0
3
+ Version: 2.2.0
4
4
  Summary: Evidence-first document extraction engine: every value comes with its quote and page.
5
5
  Author: Taeyong Kang
6
6
  License-Expression: Apache-2.0
@@ -36,10 +36,18 @@ Provides-Extra: llm
36
36
  Requires-Dist: langchain-openai<2,>=1.0; extra == "llm"
37
37
  Requires-Dist: langchain-text-splitters<2,>=1.0; extra == "llm"
38
38
  Requires-Dist: langgraph<2,>=1.0; extra == "llm"
39
+ Provides-Extra: otel
40
+ Requires-Dist: opentelemetry-api<2,>=1.45.2; extra == "otel"
41
+ Requires-Dist: opentelemetry-sdk<2,>=1.45.2; extra == "otel"
42
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.45.2; extra == "otel"
43
+ Provides-Extra: kafka
44
+ Requires-Dist: confluent-kafka<3,>=2.16.2; extra == "kafka"
45
+ Provides-Extra: postgres
46
+ Requires-Dist: psycopg[binary,pool]<4,>=3.3.9; extra == "postgres"
39
47
  Provides-Extra: all
40
- Requires-Dist: qaechi-parser[llm,parse,server]; extra == "all"
48
+ Requires-Dist: qaechi-parser[kafka,llm,otel,parse,postgres,server]; extra == "all"
41
49
  Provides-Extra: dev
42
- Requires-Dist: qaechi-parser[server]; extra == "dev"
50
+ Requires-Dist: qaechi-parser[kafka,otel,postgres,server]; extra == "dev"
43
51
  Requires-Dist: pytest<10,>=8; extra == "dev"
44
52
  Requires-Dist: httpx<1,>=0.27; extra == "dev"
45
53
  Requires-Dist: openpyxl<4,>=3.1; extra == "dev"
@@ -330,7 +338,10 @@ All variables: [`.env.example`](https://github.com/qaechi/qaechi-parser/blob/mai
330
338
  | `server` | the HTTP service (`qaechi-parser serve`): FastAPI, Uvicorn |
331
339
  | `parse` | PDF, PPTX, XLSX, HTTP sources |
332
340
  | `llm` | LLM extraction, grading, LangGraph |
333
- | `all` | `parse`, `llm` and `server` |
341
+ | `otel` | OpenTelemetry metrics and traces ([Observability](https://qaechi.github.io/qaechi-parser/latest/observability/)) |
342
+ | `kafka` | queue mode: `qaechi-parser worker` and `POST /jobs` publishing to Kafka ([Queue mode](https://qaechi.github.io/qaechi-parser/latest/queue-mode/)) |
343
+ | `postgres` | PostgreSQL job and result store shared by the API and workers |
344
+ | `all` | all of the above |
334
345
 
335
346
  Docker: `docker build -t qaechi-parser . && docker run -p 127.0.0.1:3100:3100 --env-file .env qaechi-parser`
336
347
 
@@ -281,7 +281,10 @@ All variables: [`.env.example`](https://github.com/qaechi/qaechi-parser/blob/mai
281
281
  | `server` | the HTTP service (`qaechi-parser serve`): FastAPI, Uvicorn |
282
282
  | `parse` | PDF, PPTX, XLSX, HTTP sources |
283
283
  | `llm` | LLM extraction, grading, LangGraph |
284
- | `all` | `parse`, `llm` and `server` |
284
+ | `otel` | OpenTelemetry metrics and traces ([Observability](https://qaechi.github.io/qaechi-parser/latest/observability/)) |
285
+ | `kafka` | queue mode: `qaechi-parser worker` and `POST /jobs` publishing to Kafka ([Queue mode](https://qaechi.github.io/qaechi-parser/latest/queue-mode/)) |
286
+ | `postgres` | PostgreSQL job and result store shared by the API and workers |
287
+ | `all` | all of the above |
285
288
 
286
289
  Docker: `docker build -t qaechi-parser . && docker run -p 127.0.0.1:3100:3100 --env-file .env qaechi-parser`
287
290
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "qaechi-parser"
7
- version = "2.0.0"
7
+ version = "2.2.0"
8
8
  description = "Evidence-first document extraction engine: every value comes with its quote and page."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -46,9 +46,22 @@ llm = [
46
46
  "langchain-text-splitters>=1.0,<2",
47
47
  "langgraph>=1.0,<2",
48
48
  ]
49
- all = ["qaechi-parser[parse,llm,server]"]
49
+ otel = [
50
+ "opentelemetry-api>=1.45.2,<2",
51
+ "opentelemetry-sdk>=1.45.2,<2",
52
+ "opentelemetry-exporter-otlp-proto-http>=1.45.2,<2",
53
+ ]
54
+ # Queue mode: `qaechi-parser worker` and POST /jobs publishing to Kafka.
55
+ kafka = [
56
+ "confluent-kafka>=2.16.2,<3",
57
+ ]
58
+ # Shared job and result store for several processes or hosts.
59
+ postgres = [
60
+ "psycopg[binary,pool]>=3.3.9,<4",
61
+ ]
62
+ all = ["qaechi-parser[parse,llm,server,otel,kafka,postgres]"]
50
63
  dev = [
51
- "qaechi-parser[server]",
64
+ "qaechi-parser[server,otel,kafka,postgres]",
52
65
  "pytest>=8,<10",
53
66
  "httpx>=0.27,<1",
54
67
  "openpyxl>=3.1,<4",
@@ -2,7 +2,7 @@
2
2
 
3
3
  from .schemas import Extraction, FieldSpec, FieldValue, JobRequest, LineItem, Provenance
4
4
 
5
- __version__ = "2.0.0" # x-release-please-version
5
+ __version__ = "2.2.0" # x-release-please-version
6
6
 
7
7
  __all__ = [
8
8
  "Extraction",
@@ -16,14 +16,14 @@ import uuid
16
16
 
17
17
  from fastapi import APIRouter, BackgroundTasks, Depends, FastAPI, Header, HTTPException, Query
18
18
 
19
- from . import __version__, config, registry, sources, store
19
+ from . import __version__, config, jobqueue, registry, sources, store, telemetry
20
20
  from .pipeline import graph, run_job
21
21
  from .schemas import Extraction, ExtractionList, ExtractionSummary, Job, JobRequest, ParserInfo
22
22
 
23
23
  log = logging.getLogger(__name__)
24
24
 
25
25
  OPTIONAL_MODULES = ("httpx", "pymupdf", "pymupdf4llm", "openpyxl", "pptx", "langchain_openai",
26
- "langgraph")
26
+ "langgraph", "confluent_kafka", "psycopg")
27
27
  MAX_LIMIT = 200
28
28
 
29
29
 
@@ -45,8 +45,20 @@ router = APIRouter()
45
45
  def create_job(req: JobRequest, background: BackgroundTasks) -> Job:
46
46
  # Return right away. Parsing takes minutes and callers should not hold a connection.
47
47
  job_id = str(uuid.uuid4())
48
- job = store.get_store().insert_job(job_id, req)
49
- background.add_task(run_job, job_id, req)
48
+ db = store.get_store()
49
+ job = db.insert_job(job_id, req)
50
+ if config.queue_mode() != "kafka":
51
+ background.add_task(run_job, job_id, req)
52
+ return job
53
+ # Queue mode: a worker picks it up. The job row exists first, so a fast worker finds it.
54
+ with telemetry.span("qaechi.submit", **{"qaechi.job_id": job_id,
55
+ "qaechi.document_id": req.document_id}):
56
+ try:
57
+ jobqueue.submit(job_id, req, telemetry.inject())
58
+ except jobqueue.QueueError as exc:
59
+ log.error("job %s not queued: %s", job_id, exc)
60
+ db.update_job(job_id, "failed", error=f"not queued: {exc}"[:500])
61
+ raise HTTPException(status_code=503, detail="queue unavailable, try again") from exc
50
62
  return job
51
63
 
52
64
 
@@ -90,6 +102,7 @@ def health() -> dict[str, object]:
90
102
  "source": sources.backend() or "none",
91
103
  "llm": config.llm_available(),
92
104
  "store": store.backend_name(),
105
+ "queue": config.queue_mode(),
93
106
  "pipeline_engine": graph.engine(),
94
107
  "retrieve": config.retrieve_enabled(),
95
108
  "rewrite": config.rewrite_enabled(),
@@ -101,6 +114,7 @@ def health() -> dict[str, object]:
101
114
 
102
115
 
103
116
  def create_app() -> FastAPI:
117
+ telemetry.setup()
104
118
  docs = config.api_docs_enabled()
105
119
  app = FastAPI(
106
120
  title="qaechi-parser",
@@ -113,6 +127,10 @@ def create_app() -> FastAPI:
113
127
  app.add_api_route("/health", health, methods=["GET"])
114
128
  app.include_router(router, dependencies=[Depends(verify_token)])
115
129
  registry.load_plugins()
130
+ if config.queue_mode() == "kafka" and store.backend_name() == "memory":
131
+ # Workers are other processes: they cannot see this process's memory.
132
+ log.warning("QAECHI_QUEUE=kafka with the in-memory store: set QAECHI_DATABASE_URL so "
133
+ "workers and this API share job status")
116
134
  return app
117
135
 
118
136
 
@@ -1,6 +1,7 @@
1
1
  """Command line.
2
2
 
3
3
  qaechi-parser serve run the HTTP service on 127.0.0.1:3100
4
+ qaechi-parser worker [--processes N] run Kafka workers (queue mode)
4
5
  qaechi-parser parse FILE --doc-type T parse one file and print JSON
5
6
  qaechi-parser parsers list registered parsers
6
7
  """
@@ -35,6 +36,21 @@ def _serve(args: argparse.Namespace) -> int:
35
36
  return 0
36
37
 
37
38
 
39
+ def _worker(args: argparse.Namespace) -> int:
40
+ try:
41
+ import confluent_kafka # noqa: F401
42
+ except ImportError:
43
+ print("The worker needs the kafka extra: pip install 'qaechi-parser[kafka,postgres]'",
44
+ file=sys.stderr)
45
+ return 2
46
+ from . import config, worker
47
+
48
+ if not config.kafka_bootstrap_servers():
49
+ print("Set QAECHI_KAFKA_BOOTSTRAP_SERVERS (for example kafka:9092).", file=sys.stderr)
50
+ return 2
51
+ return worker.run(args.processes or config.worker_processes())
52
+
53
+
38
54
  def _parse(args: argparse.Namespace) -> int:
39
55
  from .pipeline import parse_file
40
56
 
@@ -65,6 +81,11 @@ def main(argv: list[str] | None = None) -> int:
65
81
  serve.add_argument("--reload", action="store_true")
66
82
  serve.set_defaults(func=_serve)
67
83
 
84
+ work = sub.add_parser("worker", help="run Kafka workers (queue mode)")
85
+ work.add_argument("--processes", type=int, default=0,
86
+ help="consumer processes (default QAECHI_WORKER_PROCESSES or 1)")
87
+ work.set_defaults(func=_worker)
88
+
68
89
  parse = sub.add_parser("parse", help="parse one local file")
69
90
  parse.add_argument("file")
70
91
  parse.add_argument("--doc-type", required=True)
@@ -148,3 +148,61 @@ def api_docs_enabled() -> bool:
148
148
 
149
149
  def memory_max_results() -> int:
150
150
  return _int("QAECHI_MEMORY_MAX_RESULTS", 1_000)
151
+
152
+
153
+ # Storage
154
+ def database_url() -> str | None:
155
+ # postgresql://user:pass@host:5432/db. Unset keeps the in-memory store (one process only).
156
+ return _get("QAECHI_DATABASE_URL")
157
+
158
+
159
+ def database_pool_size() -> int:
160
+ return _int("QAECHI_DATABASE_POOL_SIZE", 5)
161
+
162
+
163
+ # Queue (Kafka). QAECHI_QUEUE=kafka makes POST /jobs publish instead of running in-process.
164
+ def queue_mode() -> str:
165
+ return "kafka" if (_get("QAECHI_QUEUE") or "").lower() == "kafka" else "inline"
166
+
167
+
168
+ def kafka_bootstrap_servers() -> str | None:
169
+ return _get("QAECHI_KAFKA_BOOTSTRAP_SERVERS")
170
+
171
+
172
+ def kafka_topic_jobs() -> str:
173
+ return _get("QAECHI_KAFKA_TOPIC_JOBS") or "qaechi.parse.jobs"
174
+
175
+
176
+ def kafka_topic_results() -> str:
177
+ return _get("QAECHI_KAFKA_TOPIC_RESULTS") or "qaechi.parse.results"
178
+
179
+
180
+ def kafka_topic_dlq() -> str:
181
+ return _get("QAECHI_KAFKA_TOPIC_DLQ") or "qaechi.parse.jobs.dlq"
182
+
183
+
184
+ def kafka_group_id() -> str:
185
+ return _get("QAECHI_KAFKA_GROUP_ID") or "qaechi-parser-worker"
186
+
187
+
188
+ KAFKA_CONF_PREFIX = "QAECHI_KAFKA_CONF_"
189
+
190
+
191
+ def kafka_conf() -> dict[str, str]:
192
+ """Extra librdkafka settings: QAECHI_KAFKA_CONF_SECURITY_PROTOCOL=SASL_SSL becomes
193
+ security.protocol=SASL_SSL. This is how SASL, TLS and AWS MSK settings get in."""
194
+ conf: dict[str, str] = {}
195
+ for name, value in os.environ.items():
196
+ if name.startswith(KAFKA_CONF_PREFIX) and value.strip():
197
+ key = name[len(KAFKA_CONF_PREFIX):].lower().replace("_", ".")
198
+ conf[key] = value.strip()
199
+ return conf
200
+
201
+
202
+ def worker_processes() -> int:
203
+ return _int("QAECHI_WORKER_PROCESSES", 1)
204
+
205
+
206
+ def worker_max_attempts() -> int:
207
+ # Deliveries of the same job before it is marked failed (a crash mid-job redelivers it).
208
+ return _int("QAECHI_WORKER_MAX_ATTEMPTS", 3)
@@ -0,0 +1,158 @@
1
+ """Kafka messages for queue mode.
2
+
3
+ pip install "qaechi-parser[kafka]"
4
+ QAECHI_QUEUE=kafka QAECHI_KAFKA_BOOTSTRAP_SERVERS=kafka:9092
5
+
6
+ Topics (names configurable):
7
+ qaechi.parse.jobs job requests, key = documentId, consumed by `qaechi-parser worker`
8
+ qaechi.parse.results one event per finished job, key = documentId
9
+ qaechi.parse.jobs.dlq messages a worker could not read, with the reason in a header
10
+
11
+ Any system can publish a job, not only the HTTP API (for example a transactional outbox).
12
+ A job message:
13
+
14
+ {"specVersion": "1", "jobId": "<uuid>", "request": {<JobRequest, camelCase>}}
15
+
16
+ Delivery is at least once. Workers commit after a job finishes and skip jobs that are
17
+ already done, so a redelivery does not parse the document twice.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import logging
24
+ import threading
25
+ from datetime import datetime
26
+ from typing import Any
27
+
28
+ from pydantic import ValidationError
29
+
30
+ from . import config
31
+ from .schemas import Job, JobRequest
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+ SPEC_VERSION = "1"
36
+ Headers = list[tuple[str, bytes]]
37
+
38
+
39
+ class QueueError(RuntimeError):
40
+ pass
41
+
42
+
43
+ def encode_job(job_id: str, req: JobRequest) -> bytes:
44
+ return json.dumps({"specVersion": SPEC_VERSION, "jobId": job_id,
45
+ "request": req.model_dump(mode="json", by_alias=True)},
46
+ ensure_ascii=False).encode()
47
+
48
+
49
+ def decode_job(value: bytes | None) -> tuple[str, JobRequest]:
50
+ """Raises ValueError with a short reason for anything a worker cannot run."""
51
+ if not value:
52
+ raise ValueError("empty message")
53
+ try:
54
+ body = json.loads(value)
55
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
56
+ raise ValueError(f"not JSON: {exc}") from exc
57
+ if not isinstance(body, dict):
58
+ raise ValueError("not a JSON object")
59
+ if str(body.get("specVersion")) != SPEC_VERSION:
60
+ raise ValueError(f"unsupported specVersion {body.get('specVersion')!r}")
61
+ job_id = body.get("jobId")
62
+ if not isinstance(job_id, str) or not 0 < len(job_id) <= 200:
63
+ raise ValueError("jobId missing or invalid")
64
+ try:
65
+ req = JobRequest.model_validate(body.get("request"))
66
+ except ValidationError as exc:
67
+ raise ValueError(f"invalid request: {exc.error_count()} error(s)") from exc
68
+ return job_id, req
69
+
70
+
71
+ def encode_result(job: Job, route: str | None = None,
72
+ groundedness: str | None = None) -> bytes:
73
+ def iso(value: datetime | None) -> str | None:
74
+ return value.isoformat() if value else None
75
+
76
+ return json.dumps({
77
+ "specVersion": SPEC_VERSION,
78
+ "jobId": job.job_id,
79
+ "documentId": job.document_id,
80
+ "docType": job.doc_type,
81
+ "status": job.status,
82
+ "resultId": job.result_id,
83
+ "route": route,
84
+ "groundedness": groundedness,
85
+ "error": job.error,
86
+ "attempts": job.attempts,
87
+ "finishedAt": iso(job.finished_at),
88
+ }, ensure_ascii=False).encode()
89
+
90
+
91
+ def headers_from(carrier: dict[str, str]) -> Headers:
92
+ return [(k, v.encode()) for k, v in carrier.items()]
93
+
94
+
95
+ def carrier_from(headers: Headers | None) -> dict[str, str]:
96
+ out: dict[str, str] = {}
97
+ for key, value in headers or []:
98
+ if isinstance(value, bytes):
99
+ try:
100
+ out[key] = value.decode()
101
+ except UnicodeDecodeError:
102
+ continue
103
+ return out
104
+
105
+
106
+ def client_conf() -> dict[str, Any]:
107
+ servers = config.kafka_bootstrap_servers()
108
+ if not servers:
109
+ raise QueueError("QAECHI_KAFKA_BOOTSTRAP_SERVERS is not set")
110
+ return {"bootstrap.servers": servers, **config.kafka_conf()}
111
+
112
+
113
+ _producer: Any = None
114
+ _producer_lock = threading.Lock()
115
+
116
+
117
+ def producer() -> Any:
118
+ global _producer
119
+ if _producer is None:
120
+ with _producer_lock:
121
+ if _producer is None:
122
+ try:
123
+ from confluent_kafka import Producer
124
+ except ImportError as exc:
125
+ raise QueueError("queue mode needs the kafka extra: "
126
+ "pip install 'qaechi-parser[kafka]'") from exc
127
+ # Idempotent producer with acks=all: no duplicates or reordering on retry.
128
+ _producer = Producer({"acks": "all", "enable.idempotence": True,
129
+ "compression.type": "zstd", **client_conf()})
130
+ return _producer
131
+
132
+
133
+ def publish(topic: str, key: str, value: bytes, headers: Headers | None = None,
134
+ timeout: float = 10.0) -> None:
135
+ """Publish and wait for the broker to acknowledge. Raises QueueError on failure."""
136
+ errors: list[Any] = []
137
+
138
+ def delivered(err: Any, _msg: Any) -> None:
139
+ if err is not None:
140
+ errors.append(err)
141
+
142
+ p = producer()
143
+ try:
144
+ p.produce(topic, value=value, key=key.encode(), headers=headers or [],
145
+ on_delivery=delivered)
146
+ except BufferError as exc:
147
+ raise QueueError(f"producer queue is full: {exc}") from exc
148
+ except Exception as exc: # noqa: BLE001 - KafkaException and friends
149
+ raise QueueError(f"could not publish to {topic}: {exc}") from exc
150
+ if p.flush(timeout) > 0:
151
+ raise QueueError(f"no acknowledgement from Kafka within {timeout:.0f}s ({topic})")
152
+ if errors:
153
+ raise QueueError(f"Kafka rejected the message ({topic}): {errors[0]}")
154
+
155
+
156
+ def submit(job_id: str, req: JobRequest, carrier: dict[str, str] | None = None) -> None:
157
+ publish(config.kafka_topic_jobs(), req.document_id, encode_job(job_id, req),
158
+ headers_from(carrier or {}))
@@ -0,0 +1,146 @@
1
+ """PostgreSQL store: jobs and results shared by the API and every worker.
2
+
3
+ pip install "qaechi-parser[postgres]"
4
+ QAECHI_DATABASE_URL=postgresql://qaechi:secret@db:5432/qaechi
5
+
6
+ Tables are created on first use (`qaechi_jobs`, `qaechi_results`). Results are kept as JSONB
7
+ so the wire format and the stored format stay the same.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from typing import Any
14
+
15
+ from .schemas import Extraction, Job, JobRequest, JobStatus
16
+ from .store import Claim
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+ SCHEMA = """
21
+ CREATE TABLE IF NOT EXISTS qaechi_jobs (
22
+ job_id text PRIMARY KEY,
23
+ status text NOT NULL,
24
+ document_id text NOT NULL,
25
+ doc_type text NOT NULL,
26
+ request jsonb NOT NULL,
27
+ attempts integer NOT NULL DEFAULT 0,
28
+ error text,
29
+ result_id text,
30
+ created_at timestamptz NOT NULL DEFAULT now(),
31
+ finished_at timestamptz
32
+ );
33
+ CREATE TABLE IF NOT EXISTS qaechi_results (
34
+ id text PRIMARY KEY,
35
+ job_id text,
36
+ document_id text NOT NULL,
37
+ doc_type text NOT NULL,
38
+ created_at timestamptz NOT NULL,
39
+ body jsonb NOT NULL
40
+ );
41
+ CREATE INDEX IF NOT EXISTS qaechi_results_document_idx
42
+ ON qaechi_results (document_id, created_at DESC);
43
+ CREATE INDEX IF NOT EXISTS qaechi_results_created_idx ON qaechi_results (created_at DESC);
44
+ """
45
+
46
+ JOB_COLUMNS = "job_id, status, document_id, doc_type, created_at, finished_at, error, result_id, attempts"
47
+
48
+
49
+ class PostgresStore:
50
+ backend = "postgres"
51
+
52
+ def __init__(self, url: str, *, pool_size: int = 5) -> None:
53
+ try:
54
+ from psycopg.types.json import Jsonb
55
+ from psycopg_pool import ConnectionPool
56
+ except ImportError as exc:
57
+ raise RuntimeError("QAECHI_DATABASE_URL needs the postgres extra: "
58
+ "pip install 'qaechi-parser[postgres]'") from exc
59
+ self._jsonb = Jsonb
60
+ self._pool = ConnectionPool(url, min_size=1, max_size=pool_size, open=True,
61
+ kwargs={"autocommit": True})
62
+ self._migrate()
63
+
64
+ def _migrate(self) -> None:
65
+ # Several workers may start at once: serialize schema creation with an advisory lock.
66
+ with self._pool.connection() as conn, conn.transaction():
67
+ conn.execute("SELECT pg_advisory_xact_lock(hashtext('qaechi_schema'))")
68
+ conn.execute(SCHEMA)
69
+
70
+ def close(self) -> None:
71
+ self._pool.close()
72
+
73
+ def _job(self, sql: str, params: tuple[Any, ...]) -> Job | None:
74
+ with self._pool.connection() as conn:
75
+ row = conn.execute(sql, params).fetchone()
76
+ if row is None:
77
+ return None
78
+ keys = JOB_COLUMNS.split(", ")
79
+ return Job.model_validate(dict(zip(keys, row, strict=True)))
80
+
81
+ def insert_job(self, job_id: str, req: JobRequest) -> Job:
82
+ # Idempotent: a job published by another system may already exist.
83
+ with self._pool.connection() as conn:
84
+ conn.execute(
85
+ "INSERT INTO qaechi_jobs (job_id, status, document_id, doc_type, request) "
86
+ "VALUES (%s, 'queued', %s, %s, %s) ON CONFLICT (job_id) DO NOTHING",
87
+ (job_id, req.document_id, req.doc_type,
88
+ self._jsonb(req.model_dump(mode="json", by_alias=True))))
89
+ job = self.get_job(job_id)
90
+ assert job is not None
91
+ return job
92
+
93
+ def get_job(self, job_id: str) -> Job | None:
94
+ return self._job(f"SELECT {JOB_COLUMNS} FROM qaechi_jobs WHERE job_id = %s", (job_id,))
95
+
96
+ def update_job(self, job_id: str, status: JobStatus, *, error: str | None = None,
97
+ result_id: str | None = None) -> None:
98
+ done = status in ("succeeded", "failed")
99
+ with self._pool.connection() as conn:
100
+ conn.execute(
101
+ "UPDATE qaechi_jobs SET status = %s, error = %s, "
102
+ "result_id = COALESCE(%s, result_id), "
103
+ "finished_at = CASE WHEN %s THEN now() ELSE NULL END WHERE job_id = %s",
104
+ (status, error, result_id, done, job_id))
105
+
106
+ def claim(self, job_id: str, max_attempts: int) -> Claim:
107
+ with self._pool.connection() as conn:
108
+ row = conn.execute(
109
+ "UPDATE qaechi_jobs SET status = 'running', attempts = attempts + 1 "
110
+ "WHERE job_id = %s AND status IN ('queued', 'running') AND attempts < %s "
111
+ "RETURNING attempts", (job_id, max_attempts)).fetchone()
112
+ if row is not None:
113
+ return "run"
114
+ row = conn.execute(
115
+ "UPDATE qaechi_jobs SET status = 'failed', finished_at = now(), "
116
+ "error = 'gave up after ' || attempts || ' attempts' "
117
+ "WHERE job_id = %s AND status IN ('queued', 'running') RETURNING attempts",
118
+ (job_id,)).fetchone()
119
+ return "gave_up" if row is not None else "done"
120
+
121
+ def save_result(self, result: Extraction) -> str:
122
+ with self._pool.connection() as conn:
123
+ conn.execute(
124
+ "INSERT INTO qaechi_results (id, job_id, document_id, doc_type, created_at, body) "
125
+ "VALUES (%s, %s, %s, %s, %s, %s) ON CONFLICT (id) DO NOTHING",
126
+ (result.id, result.job_id, result.document_id, result.doc_type, result.created_at,
127
+ self._jsonb(result.model_dump(mode="json", by_alias=True))))
128
+ return result.id
129
+
130
+ def get_result(self, result_id: str) -> Extraction | None:
131
+ with self._pool.connection() as conn:
132
+ row = conn.execute("SELECT body FROM qaechi_results WHERE id = %s",
133
+ (result_id,)).fetchone()
134
+ return Extraction.model_validate(row[0]) if row else None
135
+
136
+ def list_results(self, *, document_id: str | None, limit: int,
137
+ offset: int) -> tuple[list[Extraction], int]:
138
+ where, params = ("WHERE document_id = %s", (document_id,)) if document_id else ("", ())
139
+ with self._pool.connection() as conn:
140
+ total = conn.execute(f"SELECT count(*) FROM qaechi_results {where}",
141
+ params).fetchone()[0]
142
+ rows = conn.execute(
143
+ f"SELECT body FROM qaechi_results {where} "
144
+ "ORDER BY created_at DESC, id LIMIT %s OFFSET %s",
145
+ (*params, limit, offset)).fetchall()
146
+ return [Extraction.model_validate(r[0]) for r in rows], int(total)
@@ -12,6 +12,7 @@ import time
12
12
  import uuid
13
13
  from typing import Any
14
14
 
15
+ from .. import telemetry
15
16
  from ..schemas import Extraction, FieldSpec, JobRequest
16
17
  from ..store import get_store
17
18
  from . import graph
@@ -37,19 +38,34 @@ def run_job(job_id: str, req: JobRequest) -> Extraction | None:
37
38
  store.update_job(job_id, "running")
38
39
  run: dict[str, Any] = {}
39
40
  log.info("job %s started doc=%s type=%s", job_id, req.document_id, req.doc_type)
41
+ telemetry.setup()
42
+ result: Extraction | None = None
40
43
  try:
41
- final = graph.run({"job_id": job_id, "req": req, "started": started,
42
- "run": run, "attempts": 0})
44
+ with telemetry.span("qaechi.job", **{"qaechi.job_id": job_id, "qaechi.doc_type": req.doc_type,
45
+ "qaechi.document_id": req.document_id}):
46
+ final = graph.run({"job_id": job_id, "req": req, "started": started,
47
+ "run": run, "attempts": 0})
48
+ result = final.get("result")
43
49
  log.info("job %s finished in %.1fs", job_id, time.monotonic() - started)
44
- return final.get("result")
50
+ return result
45
51
  except Exception as exc: # noqa: BLE001 - every failure becomes a job status
46
52
  log.exception("job %s failed", job_id)
47
53
  store.update_job(job_id, "failed", error=f"{type(exc).__name__}: {exc}"[:500])
48
54
  return None
49
55
  finally:
56
+ _record(req, result, started)
50
57
  _cleanup(run)
51
58
 
52
59
 
60
+ def _record(req: JobRequest, result: Extraction | None, started: float) -> None:
61
+ seconds = time.monotonic() - started
62
+ if result is None:
63
+ telemetry.record_job(None, req.doc_type, "failed", seconds)
64
+ return
65
+ telemetry.record_job(result.route, req.doc_type, "succeeded", seconds)
66
+ telemetry.record_result(result)
67
+
68
+
53
69
  def parse_file(path: str, doc_type: str, *, fields: list[FieldSpec | dict[str, Any]] | None = None,
54
70
  lines: bool = False, period: str | None = None, source_kind: str | None = None,
55
71
  document_id: str | None = None) -> Extraction:
@@ -60,6 +76,15 @@ def parse_file(path: str, doc_type: str, *, fields: list[FieldSpec | dict[str, A
60
76
  source_kind=source_kind)
61
77
  if not os.path.isfile(path):
62
78
  raise FileNotFoundError(path)
63
- final = graph.run({"job_id": None, "req": req, "local_path": os.path.abspath(path),
64
- "started": time.monotonic(), "run": {}, "attempts": 0})
65
- return final["result"]
79
+ telemetry.setup()
80
+ started = time.monotonic()
81
+ result: Extraction | None = None
82
+ try:
83
+ with telemetry.span("qaechi.job", **{"qaechi.doc_type": doc_type,
84
+ "qaechi.document_id": req.document_id}):
85
+ final = graph.run({"job_id": None, "req": req, "local_path": os.path.abspath(path),
86
+ "started": started, "run": {}, "attempts": 0})
87
+ result = final["result"]
88
+ return result
89
+ finally:
90
+ _record(req, result, started)
@@ -18,7 +18,7 @@ import time
18
18
  from collections.abc import Callable
19
19
  from typing import Any
20
20
 
21
- from .. import config
21
+ from .. import config, telemetry
22
22
  from . import nodes
23
23
  from .state import PipelineState
24
24
 
@@ -73,7 +73,12 @@ def guarded(name: str, fn: NodeFn) -> NodeFn:
73
73
  # Never drop a finished result just because the deadline passed.
74
74
  if name != "save" and started is not None and time.monotonic() - started > limit:
75
75
  raise JobTimeout(f"job exceeded {limit}s before step '{name}'")
76
- return fn(state)
76
+ t0 = time.monotonic()
77
+ with telemetry.span(f"qaechi.step.{name}", **{"qaechi.step": name,
78
+ "qaechi.route": state.get("route")}):
79
+ out = fn(state)
80
+ telemetry.record_step(name, out.get("route") or state.get("route"), time.monotonic() - t0)
81
+ return out
77
82
 
78
83
  return run
79
84
 
@@ -122,6 +122,8 @@ class Job(Base):
122
122
  finished_at: datetime | None = None
123
123
  error: str | None = None
124
124
  result_id: str | None = None
125
+ # Deliveries so far when a worker runs the job (queue mode). 0 for in-process jobs.
126
+ attempts: int = 0
125
127
 
126
128
 
127
129
  class ParserInfo(Base):