qaechi-batch 0.2.0__py3-none-any.whl
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.
- qaechi/batch/__init__.py +8 -0
- qaechi/batch/api.py +140 -0
- qaechi/batch/cli.py +258 -0
- qaechi/batch/client.py +139 -0
- qaechi/batch/config.py +91 -0
- qaechi/batch/ingest.py +201 -0
- qaechi/batch/manifest.py +349 -0
- qaechi/batch/models.py +191 -0
- qaechi/batch/publisher.py +152 -0
- qaechi/batch/report.py +329 -0
- qaechi/batch/results.py +306 -0
- qaechi/batch/service.py +123 -0
- qaechi/batch/store.py +187 -0
- qaechi/batch/telemetry.py +173 -0
- qaechi/batch/validate.py +136 -0
- qaechi_batch-0.2.0.dist-info/METADATA +303 -0
- qaechi_batch-0.2.0.dist-info/RECORD +21 -0
- qaechi_batch-0.2.0.dist-info/WHEEL +5 -0
- qaechi_batch-0.2.0.dist-info/entry_points.txt +2 -0
- qaechi_batch-0.2.0.dist-info/licenses/LICENSE +202 -0
- qaechi_batch-0.2.0.dist-info/top_level.txt +1 -0
qaechi/batch/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""qaechi-batch: run qaechi document extraction over a whole set of files.
|
|
2
|
+
|
|
3
|
+
The coordinator (`qaechi-batch serve`, extra `server`) reads a manifest, publishes one job per
|
|
4
|
+
document to the parser's Kafka topic within an in-flight window, follows the result events, retries
|
|
5
|
+
and times out jobs, and reports per run. The default install is the client and CLI that call it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.2.0" # x-release-please-version
|
qaechi/batch/api.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""The coordinator's HTTP API (extra `server`). Port 3200 by default.
|
|
2
|
+
|
|
3
|
+
Every route except /health needs the header `X-Internal-Token: $QAECHI_INTERNAL_TOKEN`, the same
|
|
4
|
+
token as the parser's. Keep the API on an internal network: it starts work on your documents.
|
|
5
|
+
|
|
6
|
+
POST /runs {manifest, spec?, runId?, name?} -> 202 Run (200: the run existed)
|
|
7
|
+
GET /runs?status&limit&offset newest first
|
|
8
|
+
GET /runs/{runId} status, counts, progress
|
|
9
|
+
GET /runs/{runId}/items?status&limit&offset
|
|
10
|
+
GET /runs/{runId}/report?format=json|csv|html
|
|
11
|
+
POST /runs/{runId}/pause | resume | cancel | retry-failed
|
|
12
|
+
GET /health
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hmac
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from typing import Any, Literal
|
|
20
|
+
|
|
21
|
+
from fastapi import BackgroundTasks, Depends, FastAPI, Header, HTTPException, Query, Response
|
|
22
|
+
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
|
|
23
|
+
from pydantic import BaseModel
|
|
24
|
+
|
|
25
|
+
from . import __version__, report, results
|
|
26
|
+
from .ingest import RunConflict, open_run
|
|
27
|
+
from .manifest import ManifestError
|
|
28
|
+
from .models import ItemStatus, Run, RunItem, RunRequest, RunStatus
|
|
29
|
+
from .store import Store
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RetryResult(BaseModel):
|
|
33
|
+
retried: int
|
|
34
|
+
run: Run
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def create_app(store: Store, *, token: str, health: Callable[[], dict[str, Any]] | None = None) -> FastAPI:
|
|
38
|
+
"""`health` adds the state of the background loops to GET /health."""
|
|
39
|
+
if not token:
|
|
40
|
+
raise ValueError("an internal token is required")
|
|
41
|
+
expected = token.encode()
|
|
42
|
+
|
|
43
|
+
def verify(x_internal_token: str | None = Header(default=None)) -> None:
|
|
44
|
+
if x_internal_token is None or not hmac.compare_digest(x_internal_token.encode(), expected):
|
|
45
|
+
raise HTTPException(401, "missing or wrong X-Internal-Token")
|
|
46
|
+
|
|
47
|
+
app = FastAPI(title="qaechi-batch", version=__version__, docs_url=None, redoc_url=None)
|
|
48
|
+
auth = [Depends(verify)]
|
|
49
|
+
|
|
50
|
+
def get(run_id: str) -> Run:
|
|
51
|
+
run = store.get_run(run_id)
|
|
52
|
+
if run is None:
|
|
53
|
+
raise HTTPException(404, f"no run {run_id}")
|
|
54
|
+
return run
|
|
55
|
+
|
|
56
|
+
@app.post("/runs", response_model=Run, response_model_by_alias=True, status_code=202, dependencies=auth)
|
|
57
|
+
def create(req: RunRequest, background: BackgroundTasks, response: Response) -> Run:
|
|
58
|
+
try:
|
|
59
|
+
run, created, work = open_run(store, req)
|
|
60
|
+
except RunConflict as exc:
|
|
61
|
+
raise HTTPException(409, str(exc)) from exc
|
|
62
|
+
except ManifestError as exc:
|
|
63
|
+
raise HTTPException(400, str(exc)) from exc
|
|
64
|
+
if work is not None:
|
|
65
|
+
background.add_task(work) # the manifest is stored after the response; status `ingesting`
|
|
66
|
+
if not created:
|
|
67
|
+
response.status_code = 200
|
|
68
|
+
return run
|
|
69
|
+
|
|
70
|
+
@app.get("/runs", response_model=list[Run], response_model_by_alias=True, dependencies=auth)
|
|
71
|
+
def list_runs(status: RunStatus | None = None, limit: int = Query(50, ge=1, le=500),
|
|
72
|
+
offset: int = Query(0, ge=0)) -> list[Run]:
|
|
73
|
+
return store.list_runs(status=status, limit=limit, offset=offset)
|
|
74
|
+
|
|
75
|
+
@app.get("/runs/{run_id}", response_model=Run, response_model_by_alias=True, dependencies=auth)
|
|
76
|
+
def show(run_id: str) -> Run:
|
|
77
|
+
return get(run_id)
|
|
78
|
+
|
|
79
|
+
@app.get("/runs/{run_id}/items", response_model=list[RunItem], response_model_by_alias=True,
|
|
80
|
+
dependencies=auth)
|
|
81
|
+
def items(run_id: str, status: ItemStatus | None = None, limit: int = Query(100, ge=1, le=1000),
|
|
82
|
+
offset: int = Query(0, ge=0)) -> list[RunItem]:
|
|
83
|
+
get(run_id)
|
|
84
|
+
return store.list_items(run_id, status=status, limit=limit, offset=offset)
|
|
85
|
+
|
|
86
|
+
@app.get("/runs/{run_id}/report", dependencies=auth)
|
|
87
|
+
def run_report(run_id: str, format: Literal["json", "csv", "html"] = "json") -> Response: # noqa: A002
|
|
88
|
+
"""Built from the database now: a running run gives a report so far."""
|
|
89
|
+
if format == "csv":
|
|
90
|
+
get(run_id)
|
|
91
|
+
return StreamingResponse(report.csv_chunks(store, run_id), media_type=report.MEDIA_TYPES["csv"],
|
|
92
|
+
headers={"Content-Disposition": f'attachment; filename="{run_id}-items.csv"'})
|
|
93
|
+
body = report.summary(store, run_id)
|
|
94
|
+
if body is None:
|
|
95
|
+
raise HTTPException(404, f"no run {run_id}")
|
|
96
|
+
if format == "html":
|
|
97
|
+
return HTMLResponse(report.render_html(body))
|
|
98
|
+
return JSONResponse(body)
|
|
99
|
+
|
|
100
|
+
def control(action: Callable[[Store, str], Any], run_id: str) -> Any:
|
|
101
|
+
try:
|
|
102
|
+
return action(store, run_id)
|
|
103
|
+
except results.NotFound as exc:
|
|
104
|
+
raise HTTPException(404, f"no run {run_id}") from exc
|
|
105
|
+
except results.InvalidState as exc:
|
|
106
|
+
raise HTTPException(409, str(exc)) from exc
|
|
107
|
+
|
|
108
|
+
@app.post("/runs/{run_id}/pause", response_model=Run, response_model_by_alias=True, dependencies=auth)
|
|
109
|
+
def pause(run_id: str) -> Run:
|
|
110
|
+
control(results.pause, run_id)
|
|
111
|
+
return get(run_id)
|
|
112
|
+
|
|
113
|
+
@app.post("/runs/{run_id}/resume", response_model=Run, response_model_by_alias=True, dependencies=auth)
|
|
114
|
+
def resume(run_id: str) -> Run:
|
|
115
|
+
control(results.resume, run_id)
|
|
116
|
+
return get(run_id)
|
|
117
|
+
|
|
118
|
+
@app.post("/runs/{run_id}/cancel", response_model=Run, response_model_by_alias=True, dependencies=auth)
|
|
119
|
+
def cancel(run_id: str) -> Run:
|
|
120
|
+
control(results.cancel, run_id)
|
|
121
|
+
return get(run_id)
|
|
122
|
+
|
|
123
|
+
@app.post("/runs/{run_id}/retry-failed", response_model=RetryResult, response_model_by_alias=True,
|
|
124
|
+
dependencies=auth)
|
|
125
|
+
def retry_failed(run_id: str) -> RetryResult:
|
|
126
|
+
n = control(results.retry_failed, run_id)
|
|
127
|
+
return RetryResult(retried=n, run=get(run_id))
|
|
128
|
+
|
|
129
|
+
@app.get("/health")
|
|
130
|
+
def health_check(response: Response) -> dict[str, Any]:
|
|
131
|
+
body: dict[str, Any] = {"version": __version__, "database": store.ping()}
|
|
132
|
+
if health is not None:
|
|
133
|
+
body.update(health())
|
|
134
|
+
ok = body["database"] and all(v for k, v in body.items() if k.startswith("loop."))
|
|
135
|
+
body["status"] = "ok" if ok else "degraded"
|
|
136
|
+
if not ok:
|
|
137
|
+
response.status_code = 503
|
|
138
|
+
return body
|
|
139
|
+
|
|
140
|
+
return app
|
qaechi/batch/cli.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Command line.
|
|
2
|
+
|
|
3
|
+
qaechi-batch validate <manifest> [--spec spec.yaml] check a manifest without publishing
|
|
4
|
+
qaechi-batch serve [--host] [--port] the coordinator (extra `server`)
|
|
5
|
+
qaechi-batch submit <manifest> [--spec] [--wait] start a run
|
|
6
|
+
qaechi-batch status|wait|pause|resume|cancel|retry-failed <runId>
|
|
7
|
+
qaechi-batch runs [--status] list runs
|
|
8
|
+
qaechi-batch items <runId> [--status failed] list a run's documents
|
|
9
|
+
|
|
10
|
+
The client commands talk to the coordinator at QAECHI_BATCH_URL (default http://127.0.0.1:3200)
|
|
11
|
+
with QAECHI_INTERNAL_TOKEN. Exit codes: 0 done, 1 the run did not succeed (or a check failed),
|
|
12
|
+
2 a usage or connection error.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import sys
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from . import __version__
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main(argv: list[str] | None = None) -> int:
|
|
26
|
+
parser = argparse.ArgumentParser(prog="qaechi-batch",
|
|
27
|
+
description="Run qaechi extraction over many documents.")
|
|
28
|
+
parser.add_argument("--version", action="version", version=f"qaechi-batch {__version__}")
|
|
29
|
+
parser.add_argument("--url", help="coordinator URL (default: QAECHI_BATCH_URL or http://127.0.0.1:3200)")
|
|
30
|
+
sub = parser.add_subparsers(dest="command", metavar="<command>")
|
|
31
|
+
|
|
32
|
+
v = sub.add_parser("validate", help="check a manifest without publishing",
|
|
33
|
+
description="Read the whole manifest: rows, invalid rows, duplicate documentIds, "
|
|
34
|
+
"and whether a sample of sources exists. Exit 1 on any problem.")
|
|
35
|
+
v.add_argument("manifest", help="file (.jsonl, .csv, optionally .gz; local or s3://) "
|
|
36
|
+
"or folder (s3://bucket/prefix/ or dir:/path)")
|
|
37
|
+
v.add_argument("--spec", help="run spec, YAML or JSON (defaults and folder rules)")
|
|
38
|
+
v.add_argument("--source-root", help="the worker's source root (default: QAECHI_BATCH_SOURCE_ROOT)")
|
|
39
|
+
v.add_argument("--sample", type=int, default=20, help="sources to check for existence (0: none)")
|
|
40
|
+
v.add_argument("--json", action="store_true", help="print the result as JSON")
|
|
41
|
+
|
|
42
|
+
s = sub.add_parser("serve", help="run the coordinator: HTTP API, publishing, results, timeouts")
|
|
43
|
+
s.add_argument("--host", default="127.0.0.1", help="address to listen on (default 127.0.0.1)")
|
|
44
|
+
s.add_argument("--port", type=int, default=3200)
|
|
45
|
+
|
|
46
|
+
sm = sub.add_parser("submit", help="start a run",
|
|
47
|
+
description="Start a run. The coordinator reads the manifest, so give a path or "
|
|
48
|
+
"s3:// URI it can reach. With the same --run-id again, returns that run.")
|
|
49
|
+
sm.add_argument("manifest")
|
|
50
|
+
sm.add_argument("--spec", help="run spec, YAML or JSON")
|
|
51
|
+
sm.add_argument("--name")
|
|
52
|
+
sm.add_argument("--run-id", help="your own id, for an idempotent submit (e.g. from a scheduler)")
|
|
53
|
+
_wait_args(sm, with_flag=True)
|
|
54
|
+
|
|
55
|
+
for name, text in (("status", "show a run"), ("pause", "stop publishing a run"),
|
|
56
|
+
("resume", "publish a paused run again"),
|
|
57
|
+
("cancel", "cancel a run's remaining documents"),
|
|
58
|
+
("retry-failed", "send a run's failed documents again")):
|
|
59
|
+
c = sub.add_parser(name, help=text)
|
|
60
|
+
c.add_argument("run_id", metavar="runId")
|
|
61
|
+
c.add_argument("--json", action="store_true")
|
|
62
|
+
w = sub.add_parser("wait", help="wait for a run to finish; exit 1 unless it succeeded")
|
|
63
|
+
w.add_argument("run_id", metavar="runId")
|
|
64
|
+
_wait_args(w)
|
|
65
|
+
|
|
66
|
+
r = sub.add_parser("runs", help="list runs, newest first")
|
|
67
|
+
r.add_argument("--status")
|
|
68
|
+
r.add_argument("--limit", type=int, default=20)
|
|
69
|
+
r.add_argument("--json", action="store_true")
|
|
70
|
+
it = sub.add_parser("items", help="list a run's documents")
|
|
71
|
+
it.add_argument("run_id", metavar="runId")
|
|
72
|
+
it.add_argument("--status", help="e.g. failed")
|
|
73
|
+
it.add_argument("--limit", type=int, default=100)
|
|
74
|
+
it.add_argument("--offset", type=int, default=0)
|
|
75
|
+
it.add_argument("--json", action="store_true")
|
|
76
|
+
|
|
77
|
+
rp = sub.add_parser("report", help="show or save a run's report",
|
|
78
|
+
description="Without --format, print a summary. json: the summary; csv: every "
|
|
79
|
+
"document; html: a page to read. Saved to -o, else printed.")
|
|
80
|
+
rp.add_argument("run_id", metavar="runId")
|
|
81
|
+
rp.add_argument("--format", choices=("json", "csv", "html"))
|
|
82
|
+
rp.add_argument("-o", "--output", help="file to save to")
|
|
83
|
+
|
|
84
|
+
args = parser.parse_args(argv)
|
|
85
|
+
if args.command == "validate":
|
|
86
|
+
return _validate(args)
|
|
87
|
+
if args.command == "serve":
|
|
88
|
+
from .service import serve
|
|
89
|
+
|
|
90
|
+
serve(args.host, args.port)
|
|
91
|
+
return 0
|
|
92
|
+
if args.command is None:
|
|
93
|
+
parser.print_help()
|
|
94
|
+
return 0
|
|
95
|
+
from .client import BatchError
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
return _client_command(args)
|
|
99
|
+
except BatchError as exc:
|
|
100
|
+
print(f"qaechi-batch: {exc}", file=sys.stderr)
|
|
101
|
+
return 1 if exc.status in (404, 409) else 2
|
|
102
|
+
except Exception as exc: # noqa: BLE001 - connection refused, timeouts
|
|
103
|
+
import httpx
|
|
104
|
+
|
|
105
|
+
if isinstance(exc, (httpx.HTTPError, TimeoutError)):
|
|
106
|
+
print(f"qaechi-batch: {exc}", file=sys.stderr)
|
|
107
|
+
return 2
|
|
108
|
+
raise
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _wait_args(p: argparse.ArgumentParser, with_flag: bool = False) -> None:
|
|
112
|
+
if with_flag:
|
|
113
|
+
p.add_argument("--wait", action="store_true", help="wait until the run finishes; exit 1 unless it succeeded")
|
|
114
|
+
p.add_argument("--poll", type=float, default=10.0, help="seconds between checks (default 10)")
|
|
115
|
+
p.add_argument("--timeout", type=float, help="give up waiting after this many seconds")
|
|
116
|
+
p.add_argument("--json", action="store_true")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def make_client(args: argparse.Namespace) -> Any:
|
|
120
|
+
from .client import BatchClient
|
|
121
|
+
|
|
122
|
+
return BatchClient(args.url)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _client_command(args: argparse.Namespace) -> int:
|
|
126
|
+
with make_client(args) as client:
|
|
127
|
+
cmd = args.command
|
|
128
|
+
if cmd == "submit":
|
|
129
|
+
from .models import load_spec
|
|
130
|
+
|
|
131
|
+
run = client.submit(args.manifest, load_spec(args.spec), run_id=args.run_id, name=args.name)
|
|
132
|
+
if not args.wait:
|
|
133
|
+
_show(run, args.json)
|
|
134
|
+
return 0
|
|
135
|
+
return _follow(client, run.run_id, args)
|
|
136
|
+
if cmd == "wait":
|
|
137
|
+
return _follow(client, args.run_id, args)
|
|
138
|
+
if cmd == "status":
|
|
139
|
+
_show(client.get(args.run_id), args.json)
|
|
140
|
+
return 0
|
|
141
|
+
if cmd in ("pause", "resume", "cancel"):
|
|
142
|
+
_show(getattr(client, cmd)(args.run_id), args.json)
|
|
143
|
+
return 0
|
|
144
|
+
if cmd == "retry-failed":
|
|
145
|
+
n, run = client.retry_failed(args.run_id)
|
|
146
|
+
if args.json:
|
|
147
|
+
print(json.dumps({"retried": n, "run": _dump(run)}, indent=2))
|
|
148
|
+
else:
|
|
149
|
+
print(f"{n} failed document(s) sent again")
|
|
150
|
+
_show(run, False)
|
|
151
|
+
return 0
|
|
152
|
+
if cmd == "runs":
|
|
153
|
+
runs = client.runs(status=args.status, limit=args.limit)
|
|
154
|
+
if args.json:
|
|
155
|
+
print(json.dumps([_dump(r) for r in runs], indent=2))
|
|
156
|
+
for r in [] if args.json else runs:
|
|
157
|
+
print(f"{r.run_id} {r.status:<24} {r.progress.done}/{r.total} {r.name or ''}")
|
|
158
|
+
return 0
|
|
159
|
+
if cmd == "items":
|
|
160
|
+
items = client.items(args.run_id, status=args.status, limit=args.limit, offset=args.offset)
|
|
161
|
+
if args.json:
|
|
162
|
+
print(json.dumps([i.model_dump(mode="json", by_alias=True) for i in items], indent=2,
|
|
163
|
+
ensure_ascii=False))
|
|
164
|
+
for i in [] if args.json else items:
|
|
165
|
+
why = f" {i.error_code or ''} {i.error or ''}".rstrip() if i.status == "failed" else ""
|
|
166
|
+
print(f"{i.seq:>7} {i.status:<10} a{i.attempt} {i.document_id}{why}")
|
|
167
|
+
return 0
|
|
168
|
+
if cmd == "report":
|
|
169
|
+
return _report(client, args)
|
|
170
|
+
raise AssertionError(cmd)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _report(client: Any, args: argparse.Namespace) -> int:
|
|
174
|
+
from .report import format_text
|
|
175
|
+
|
|
176
|
+
if args.format is None:
|
|
177
|
+
text = format_text(client.report(args.run_id))
|
|
178
|
+
if args.output:
|
|
179
|
+
with open(args.output, "w", encoding="utf-8") as f:
|
|
180
|
+
print(text, file=f)
|
|
181
|
+
else:
|
|
182
|
+
print(text)
|
|
183
|
+
else:
|
|
184
|
+
sys.stdout.flush()
|
|
185
|
+
client.download_report(args.run_id, args.output or sys.stdout.buffer, format=args.format)
|
|
186
|
+
if args.output:
|
|
187
|
+
print(f"saved {args.output}", file=sys.stderr)
|
|
188
|
+
return 0
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _follow(client: Any, run_id: str, args: argparse.Namespace) -> int:
|
|
192
|
+
last: list[str] = []
|
|
193
|
+
|
|
194
|
+
def progress(run: Any) -> None:
|
|
195
|
+
line = _line(run)
|
|
196
|
+
if not args.json and line != (last[-1] if last else None):
|
|
197
|
+
print(line, file=sys.stderr, flush=True)
|
|
198
|
+
last.append(line)
|
|
199
|
+
|
|
200
|
+
run = client.wait(run_id, poll=args.poll, timeout=args.timeout, on_progress=progress)
|
|
201
|
+
_show(run, args.json)
|
|
202
|
+
return 0 if client.ok(run) else 1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _dump(run: Any) -> dict[str, Any]:
|
|
206
|
+
return run.model_dump(mode="json", by_alias=True)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _line(run: Any) -> str:
|
|
210
|
+
p = run.progress
|
|
211
|
+
rate = f", {p.rate_per_minute:g}/min" if p.rate_per_minute else ""
|
|
212
|
+
eta = f", about {_duration(p.eta_seconds)} left" if p.eta_seconds else ""
|
|
213
|
+
return f"{run.run_id}: {run.status}, {p.done}/{run.total} done{rate}{eta}"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _duration(seconds: int) -> str:
|
|
217
|
+
if seconds < 90:
|
|
218
|
+
return f"{seconds}s"
|
|
219
|
+
if seconds < 5400:
|
|
220
|
+
return f"{round(seconds / 60)} min"
|
|
221
|
+
return f"{seconds / 3600:.1f} h"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _show(run: Any, as_json: bool) -> None:
|
|
225
|
+
if as_json:
|
|
226
|
+
print(json.dumps(_dump(run), indent=2, ensure_ascii=False))
|
|
227
|
+
return
|
|
228
|
+
print(_line(run))
|
|
229
|
+
counts = ", ".join(f"{k} {v}" for k, v in sorted(run.counts.items()))
|
|
230
|
+
if counts:
|
|
231
|
+
print(f" {counts}")
|
|
232
|
+
if run.invalid or run.duplicates:
|
|
233
|
+
print(f" manifest: {run.invalid} invalid row(s), {run.duplicates} duplicate(s) left out")
|
|
234
|
+
if run.error:
|
|
235
|
+
print(f" error: {run.error}")
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _validate(args: argparse.Namespace) -> int:
|
|
239
|
+
from pydantic import ValidationError
|
|
240
|
+
|
|
241
|
+
from .manifest import Manifest
|
|
242
|
+
from .models import load_spec
|
|
243
|
+
from .validate import format_text, validate
|
|
244
|
+
|
|
245
|
+
try:
|
|
246
|
+
spec = load_spec(args.spec)
|
|
247
|
+
except (OSError, ValueError) as exc: # missing file, YAML/JSON syntax, ValidationError
|
|
248
|
+
detail = f"{exc.error_count()} error(s): {exc.errors()[0]['loc']} {exc.errors()[0]['msg']}" \
|
|
249
|
+
if isinstance(exc, ValidationError) else str(exc)
|
|
250
|
+
print(f"spec {args.spec}: {detail}", file=sys.stderr)
|
|
251
|
+
return 2
|
|
252
|
+
report = validate(Manifest(args.manifest, spec, args.source_root), sample=max(0, args.sample))
|
|
253
|
+
print(json.dumps(report.to_json(), ensure_ascii=False, indent=2) if args.json else format_text(report))
|
|
254
|
+
return 0 if report.ok else 1
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
if __name__ == "__main__":
|
|
258
|
+
sys.exit(main())
|
qaechi/batch/client.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""BatchClient: start and follow runs from Python (an Airflow task, a script). Default install.
|
|
2
|
+
|
|
3
|
+
from qaechi.batch.client import BatchClient
|
|
4
|
+
|
|
5
|
+
with BatchClient() as batch: # QAECHI_BATCH_URL, QAECHI_INTERNAL_TOKEN
|
|
6
|
+
run = batch.submit("s3://docs/runs/2019.jsonl.gz", spec={"defaults": {"docType": "contract"}})
|
|
7
|
+
run = batch.wait(run.run_id)
|
|
8
|
+
if not batch.ok(run):
|
|
9
|
+
raise SystemExit(f"{run.run_id}: {run.status}")
|
|
10
|
+
|
|
11
|
+
The manifest URI is read by the coordinator, not here: give a path or s3:// URI it can reach.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from typing import Any, BinaryIO
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
from . import config
|
|
23
|
+
from .models import FINAL_RUN_STATUSES, Run, RunItem, RunRequest, RunSpec
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BatchError(Exception):
|
|
27
|
+
def __init__(self, status: int, detail: str) -> None:
|
|
28
|
+
super().__init__(f"HTTP {status}: {detail}")
|
|
29
|
+
self.status, self.detail = status, detail
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _check(resp: httpx.Response) -> None:
|
|
33
|
+
if resp.status_code < 400:
|
|
34
|
+
return
|
|
35
|
+
try:
|
|
36
|
+
detail = resp.json().get("detail", resp.text)
|
|
37
|
+
except ValueError:
|
|
38
|
+
detail = resp.text
|
|
39
|
+
raise BatchError(resp.status_code, str(detail))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class BatchClient:
|
|
43
|
+
def __init__(self, url: str | None = None, token: str | None = None, *, timeout: float = 30.0,
|
|
44
|
+
http: httpx.Client | None = None) -> None:
|
|
45
|
+
"""`http`: an httpx.Client to use instead (tests, proxies, custom TLS)."""
|
|
46
|
+
token = token if token is not None else config.client_token()
|
|
47
|
+
headers = {"X-Internal-Token": token} if token else {}
|
|
48
|
+
if http is None:
|
|
49
|
+
self.http = httpx.Client(base_url=url or config.batch_url(), headers=headers, timeout=timeout)
|
|
50
|
+
self._own = True
|
|
51
|
+
else:
|
|
52
|
+
self.http, self._own = http, False
|
|
53
|
+
self.http.headers.update(headers)
|
|
54
|
+
|
|
55
|
+
def __enter__(self) -> BatchClient:
|
|
56
|
+
return self
|
|
57
|
+
|
|
58
|
+
def __exit__(self, *_: Any) -> None:
|
|
59
|
+
self.close()
|
|
60
|
+
|
|
61
|
+
def close(self) -> None:
|
|
62
|
+
if self._own:
|
|
63
|
+
self.http.close()
|
|
64
|
+
|
|
65
|
+
def _call(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
66
|
+
resp = self.http.request(method, path, **kwargs)
|
|
67
|
+
_check(resp)
|
|
68
|
+
return resp.json()
|
|
69
|
+
|
|
70
|
+
# -- runs
|
|
71
|
+
def submit(self, manifest: str, spec: RunSpec | dict[str, Any] | None = None, *, run_id: str | None = None,
|
|
72
|
+
name: str | None = None) -> Run:
|
|
73
|
+
"""Start a run, or get the existing one with the same runId (idempotent)."""
|
|
74
|
+
spec = spec if isinstance(spec, RunSpec) else RunSpec.model_validate(spec or {})
|
|
75
|
+
req = RunRequest(manifest=manifest, spec=spec, run_id=run_id, name=name)
|
|
76
|
+
body = req.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
77
|
+
return Run.model_validate(self._call("POST", "/runs", json=body))
|
|
78
|
+
|
|
79
|
+
def get(self, run_id: str) -> Run:
|
|
80
|
+
return Run.model_validate(self._call("GET", f"/runs/{run_id}"))
|
|
81
|
+
|
|
82
|
+
def runs(self, *, status: str | None = None, limit: int = 50, offset: int = 0) -> list[Run]:
|
|
83
|
+
params = {"limit": limit, "offset": offset, **({"status": status} if status else {})}
|
|
84
|
+
return [Run.model_validate(r) for r in self._call("GET", "/runs", params=params)]
|
|
85
|
+
|
|
86
|
+
def items(self, run_id: str, *, status: str | None = None, limit: int = 100, offset: int = 0) -> list[RunItem]:
|
|
87
|
+
params = {"limit": limit, "offset": offset, **({"status": status} if status else {})}
|
|
88
|
+
return [RunItem.model_validate(r) for r in self._call("GET", f"/runs/{run_id}/items", params=params)]
|
|
89
|
+
|
|
90
|
+
def pause(self, run_id: str) -> Run:
|
|
91
|
+
return Run.model_validate(self._call("POST", f"/runs/{run_id}/pause"))
|
|
92
|
+
|
|
93
|
+
def resume(self, run_id: str) -> Run:
|
|
94
|
+
return Run.model_validate(self._call("POST", f"/runs/{run_id}/resume"))
|
|
95
|
+
|
|
96
|
+
def cancel(self, run_id: str) -> Run:
|
|
97
|
+
return Run.model_validate(self._call("POST", f"/runs/{run_id}/cancel"))
|
|
98
|
+
|
|
99
|
+
def retry_failed(self, run_id: str) -> tuple[int, Run]:
|
|
100
|
+
body = self._call("POST", f"/runs/{run_id}/retry-failed")
|
|
101
|
+
return body["retried"], Run.model_validate(body["run"])
|
|
102
|
+
|
|
103
|
+
def report(self, run_id: str) -> dict[str, Any]:
|
|
104
|
+
"""The run's report summary (report.json): counts, failures by errorCode, failed documents."""
|
|
105
|
+
return self._call("GET", f"/runs/{run_id}/report", params={"format": "json"})
|
|
106
|
+
|
|
107
|
+
def download_report(self, run_id: str, target: str | BinaryIO, *, format: str = "html") -> None: # noqa: A002
|
|
108
|
+
"""Save the report as `format` (json, csv: every document, html) to a path or binary file."""
|
|
109
|
+
with self.http.stream("GET", f"/runs/{run_id}/report", params={"format": format}) as resp:
|
|
110
|
+
if resp.status_code >= 400:
|
|
111
|
+
resp.read()
|
|
112
|
+
_check(resp)
|
|
113
|
+
if isinstance(target, str):
|
|
114
|
+
with open(target, "wb") as f:
|
|
115
|
+
for block in resp.iter_bytes():
|
|
116
|
+
f.write(block)
|
|
117
|
+
else:
|
|
118
|
+
for block in resp.iter_bytes():
|
|
119
|
+
target.write(block)
|
|
120
|
+
|
|
121
|
+
def wait(self, run_id: str, *, poll: float = 10.0, timeout: float | None = None,
|
|
122
|
+
on_progress: Callable[[Run], None] | None = None,
|
|
123
|
+
sleep: Callable[[float], None] = time.sleep) -> Run:
|
|
124
|
+
"""Poll until the run has finished. Raises TimeoutError after `timeout` seconds."""
|
|
125
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
126
|
+
while True:
|
|
127
|
+
run = self.get(run_id)
|
|
128
|
+
if on_progress is not None:
|
|
129
|
+
on_progress(run)
|
|
130
|
+
if run.status in FINAL_RUN_STATUSES:
|
|
131
|
+
return run
|
|
132
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
133
|
+
raise TimeoutError(f"run {run_id} is still {run.status}")
|
|
134
|
+
sleep(poll)
|
|
135
|
+
|
|
136
|
+
@staticmethod
|
|
137
|
+
def ok(run: Run) -> bool:
|
|
138
|
+
"""Finished with failures within the run's failThreshold."""
|
|
139
|
+
return run.status == "succeeded"
|
qaechi/batch/config.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Settings from environment variables."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _get(name: str) -> str | None:
|
|
9
|
+
value = os.getenv(name)
|
|
10
|
+
return value.strip() if value and value.strip() else None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def source_root() -> str | None:
|
|
14
|
+
# The worker's source root: the folder of QAECHI_SOURCE_DIR or the s3:// of QAECHI_SOURCE_S3_URI.
|
|
15
|
+
return _get("QAECHI_BATCH_SOURCE_ROOT")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def s3_endpoint_url() -> str | None:
|
|
19
|
+
# MinIO, Cloudflare R2 and other S3-compatible stores. Unset = AWS.
|
|
20
|
+
return _get("QAECHI_S3_ENDPOINT_URL") or _get("AWS_ENDPOINT_URL_S3") or _get("AWS_ENDPOINT_URL")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MissingConfig(RuntimeError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _int(name: str, default: int, minimum: int = 1) -> int:
|
|
28
|
+
try:
|
|
29
|
+
value = int(_get(name) or default)
|
|
30
|
+
except ValueError:
|
|
31
|
+
return default
|
|
32
|
+
return value if value >= minimum else default
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def database_url() -> str:
|
|
36
|
+
url = _get("QAECHI_BATCH_DATABASE_URL") or _get("QAECHI_DATABASE_URL")
|
|
37
|
+
if not url:
|
|
38
|
+
raise MissingConfig("QAECHI_BATCH_DATABASE_URL (or QAECHI_DATABASE_URL) is not set")
|
|
39
|
+
return url
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def max_in_flight() -> int:
|
|
43
|
+
# Jobs published and not yet finished, over all runs. Each run also has its own maxInFlight.
|
|
44
|
+
return _int("QAECHI_BATCH_MAX_IN_FLIGHT", 1000)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def kafka_bootstrap_servers() -> str:
|
|
48
|
+
value = _get("QAECHI_KAFKA_BOOTSTRAP_SERVERS")
|
|
49
|
+
if not value:
|
|
50
|
+
raise MissingConfig("QAECHI_KAFKA_BOOTSTRAP_SERVERS is not set")
|
|
51
|
+
return value
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def topic_jobs() -> str:
|
|
55
|
+
return _get("QAECHI_KAFKA_TOPIC_JOBS") or "qaechi.parse.jobs"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def topic_results() -> str:
|
|
59
|
+
return _get("QAECHI_KAFKA_TOPIC_RESULTS") or "qaechi.parse.results"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def group_id() -> str:
|
|
63
|
+
return _get("QAECHI_BATCH_GROUP_ID") or "qaechi-batch"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def kafka_conf() -> dict[str, str]:
|
|
67
|
+
"""QAECHI_KAFKA_CONF_SASL_MECHANISM=... -> {"sasl.mechanism": ...}, as in the parser and sink."""
|
|
68
|
+
prefix = "QAECHI_KAFKA_CONF_"
|
|
69
|
+
return {k[len(prefix):].lower().replace("_", "."): v for k, v in os.environ.items()
|
|
70
|
+
if k.startswith(prefix) and v}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def internal_token() -> str:
|
|
74
|
+
token = _get("QAECHI_INTERNAL_TOKEN")
|
|
75
|
+
if not token:
|
|
76
|
+
raise MissingConfig("QAECHI_INTERNAL_TOKEN is not set (the same token as the parser's)")
|
|
77
|
+
return token
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def report_uri() -> str | None:
|
|
81
|
+
# Where finished runs' reports are written: s3://bucket/prefix or a folder. Unset: only on request.
|
|
82
|
+
return _get("QAECHI_BATCH_REPORT_URI")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def batch_url() -> str:
|
|
86
|
+
# Where the client and CLI find the coordinator.
|
|
87
|
+
return (_get("QAECHI_BATCH_URL") or "http://127.0.0.1:3200").rstrip("/")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def client_token() -> str | None:
|
|
91
|
+
return _get("QAECHI_INTERNAL_TOKEN")
|