docql 0.1.0__tar.gz → 0.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.
- {docql-0.1.0 → docql-0.2.0}/PKG-INFO +42 -3
- {docql-0.1.0 → docql-0.2.0}/README.md +41 -2
- {docql-0.1.0 → docql-0.2.0}/pyproject.toml +1 -1
- {docql-0.1.0 → docql-0.2.0}/pyproject.toml.orig +1 -1
- {docql-0.1.0 → docql-0.2.0}/src/docql/__init__.py +30 -0
- {docql-0.1.0 → docql-0.2.0}/src/docql/_client.py +96 -1
- {docql-0.1.0 → docql-0.2.0}/src/docql/_constants.py +44 -3
- {docql-0.1.0 → docql-0.2.0}/src/docql/_errors.py +53 -4
- docql-0.2.0/src/docql/_jobs.py +514 -0
- {docql-0.1.0 → docql-0.2.0}/LICENSE +0 -0
- {docql-0.1.0 → docql-0.2.0}/src/docql/_request.py +0 -0
- {docql-0.1.0 → docql-0.2.0}/src/docql/_response.py +0 -0
- {docql-0.1.0 → docql-0.2.0}/src/docql/_version.py +0 -0
- {docql-0.1.0 → docql-0.2.0}/src/docql/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: docql
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Python client for the DocQL document-extraction API
|
|
5
5
|
Author: Finoniq
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -53,6 +53,45 @@ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
|
53
53
|
The query uses DocQL's brace-and-field syntax; pass `prompt=` instead for a
|
|
54
54
|
natural-language instruction. A call takes exactly one of `query` or `prompt`.
|
|
55
55
|
|
|
56
|
+
## Long documents: jobs
|
|
57
|
+
|
|
58
|
+
Use a job for a long document: a proxied edge cuts a single call at about
|
|
59
|
+
100–120 s, while `mode=standard` may take up to 540 s. `submit_document` uploads
|
|
60
|
+
the file and answers at once with a queued job, and `wait` polls it until it
|
|
61
|
+
finishes.
|
|
62
|
+
|
|
63
|
+
<!-- docql:jobs:start -->
|
|
64
|
+
```python
|
|
65
|
+
from docql import DocQL
|
|
66
|
+
|
|
67
|
+
with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
68
|
+
job = client.submit_document("invoice.pdf", query="{ invoice_number total_amount }")
|
|
69
|
+
job = client.wait(job.job_id) # polls until succeeded or cancelled
|
|
70
|
+
print(job.status)
|
|
71
|
+
if job.result is not None:
|
|
72
|
+
print(job.result.data)
|
|
73
|
+
```
|
|
74
|
+
<!-- docql:jobs:end -->
|
|
75
|
+
|
|
76
|
+
- `get_job(job_id)` makes one poll and answers the job as it is; a `failed` job
|
|
77
|
+
is answered too (read `job.error`), never raised.
|
|
78
|
+
- `cancel_job(job_id)` asks DocQL to cancel and answers the job at that moment,
|
|
79
|
+
which may still be `running`: poll to confirm.
|
|
80
|
+
- `wait` answers a `succeeded` or `cancelled` job and raises the job's
|
|
81
|
+
`DocQLError` for a `failed` one. It gives up after 15 minutes by default
|
|
82
|
+
(`timeout=` in seconds) with `DocQLWaitTimeoutError`, and never sends a poll
|
|
83
|
+
at or past that deadline. It never cancels the job: `get_job` or another
|
|
84
|
+
`wait` picks it up again.
|
|
85
|
+
- Every submit carries an `Idempotency-Key`, generated for you unless you pass
|
|
86
|
+
`idempotency_key=`; it is on the returned job and on every error the submit
|
|
87
|
+
raises. DocQL scopes the key to your organisation. Unlike `query_document`,
|
|
88
|
+
`submit_document` retries a 503 with the same key (a 503 may mean the job was
|
|
89
|
+
created anyway), but only for a path, `bytes` or a seekable file. A job that
|
|
90
|
+
ended `failed`, `job_interrupted` included, needs a new key: the old one
|
|
91
|
+
replays the failure.
|
|
92
|
+
- `job.pages_done` stays 0 while DocQL runs OCR, so show progress as
|
|
93
|
+
indeterminate while a running job reports 0 pages done.
|
|
94
|
+
|
|
56
95
|
## Configuration
|
|
57
96
|
|
|
58
97
|
| Keyword | Env variable | Default | Notes |
|
|
@@ -137,7 +176,7 @@ text, truncated to about 2 KB). Every reason below is also exported as a
|
|
|
137
176
|
|
|
138
177
|
## Retrying
|
|
139
178
|
|
|
140
|
-
|
|
179
|
+
`query_document` never retries — every call is billed. Retry it yourself, only on
|
|
141
180
|
`retryable` errors, sleeping `retry_after` when the server sent one and a
|
|
142
181
|
capped exponential backoff otherwise:
|
|
143
182
|
|
|
@@ -169,7 +208,7 @@ two mean the request was not processed.
|
|
|
169
208
|
## Versioning
|
|
170
209
|
|
|
171
210
|
The SDK follows [Semantic Versioning](https://semver.org/). While the major
|
|
172
|
-
version is 0, a minor release may change the API; pin `docql>=0.
|
|
211
|
+
version is 0, a minor release may change the API; pin `docql>=0.2,<0.3` until
|
|
173
212
|
1.0.
|
|
174
213
|
|
|
175
214
|
## Support
|
|
@@ -31,6 +31,45 @@ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
|
31
31
|
The query uses DocQL's brace-and-field syntax; pass `prompt=` instead for a
|
|
32
32
|
natural-language instruction. A call takes exactly one of `query` or `prompt`.
|
|
33
33
|
|
|
34
|
+
## Long documents: jobs
|
|
35
|
+
|
|
36
|
+
Use a job for a long document: a proxied edge cuts a single call at about
|
|
37
|
+
100–120 s, while `mode=standard` may take up to 540 s. `submit_document` uploads
|
|
38
|
+
the file and answers at once with a queued job, and `wait` polls it until it
|
|
39
|
+
finishes.
|
|
40
|
+
|
|
41
|
+
<!-- docql:jobs:start -->
|
|
42
|
+
```python
|
|
43
|
+
from docql import DocQL
|
|
44
|
+
|
|
45
|
+
with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
46
|
+
job = client.submit_document("invoice.pdf", query="{ invoice_number total_amount }")
|
|
47
|
+
job = client.wait(job.job_id) # polls until succeeded or cancelled
|
|
48
|
+
print(job.status)
|
|
49
|
+
if job.result is not None:
|
|
50
|
+
print(job.result.data)
|
|
51
|
+
```
|
|
52
|
+
<!-- docql:jobs:end -->
|
|
53
|
+
|
|
54
|
+
- `get_job(job_id)` makes one poll and answers the job as it is; a `failed` job
|
|
55
|
+
is answered too (read `job.error`), never raised.
|
|
56
|
+
- `cancel_job(job_id)` asks DocQL to cancel and answers the job at that moment,
|
|
57
|
+
which may still be `running`: poll to confirm.
|
|
58
|
+
- `wait` answers a `succeeded` or `cancelled` job and raises the job's
|
|
59
|
+
`DocQLError` for a `failed` one. It gives up after 15 minutes by default
|
|
60
|
+
(`timeout=` in seconds) with `DocQLWaitTimeoutError`, and never sends a poll
|
|
61
|
+
at or past that deadline. It never cancels the job: `get_job` or another
|
|
62
|
+
`wait` picks it up again.
|
|
63
|
+
- Every submit carries an `Idempotency-Key`, generated for you unless you pass
|
|
64
|
+
`idempotency_key=`; it is on the returned job and on every error the submit
|
|
65
|
+
raises. DocQL scopes the key to your organisation. Unlike `query_document`,
|
|
66
|
+
`submit_document` retries a 503 with the same key (a 503 may mean the job was
|
|
67
|
+
created anyway), but only for a path, `bytes` or a seekable file. A job that
|
|
68
|
+
ended `failed`, `job_interrupted` included, needs a new key: the old one
|
|
69
|
+
replays the failure.
|
|
70
|
+
- `job.pages_done` stays 0 while DocQL runs OCR, so show progress as
|
|
71
|
+
indeterminate while a running job reports 0 pages done.
|
|
72
|
+
|
|
34
73
|
## Configuration
|
|
35
74
|
|
|
36
75
|
| Keyword | Env variable | Default | Notes |
|
|
@@ -115,7 +154,7 @@ text, truncated to about 2 KB). Every reason below is also exported as a
|
|
|
115
154
|
|
|
116
155
|
## Retrying
|
|
117
156
|
|
|
118
|
-
|
|
157
|
+
`query_document` never retries — every call is billed. Retry it yourself, only on
|
|
119
158
|
`retryable` errors, sleeping `retry_after` when the server sent one and a
|
|
120
159
|
capped exponential backoff otherwise:
|
|
121
160
|
|
|
@@ -147,7 +186,7 @@ two mean the request was not processed.
|
|
|
147
186
|
## Versioning
|
|
148
187
|
|
|
149
188
|
The SDK follows [Semantic Versioning](https://semver.org/). While the major
|
|
150
|
-
version is 0, a minor release may change the API; pin `docql>=0.
|
|
189
|
+
version is 0, a minor release may change the API; pin `docql>=0.2,<0.3` until
|
|
151
190
|
1.0.
|
|
152
191
|
|
|
153
192
|
## Support
|
|
@@ -2,16 +2,29 @@
|
|
|
2
2
|
|
|
3
3
|
from docql._client import DocQL
|
|
4
4
|
from docql._constants import (
|
|
5
|
+
JOB_STATUS_CANCELLED,
|
|
6
|
+
JOB_STATUS_FAILED,
|
|
7
|
+
JOB_STATUS_QUEUED,
|
|
8
|
+
JOB_STATUS_RUNNING,
|
|
9
|
+
JOB_STATUS_SUCCEEDED,
|
|
5
10
|
MODE_FAST,
|
|
6
11
|
MODE_STANDARD,
|
|
7
12
|
REASON_BODY_NOT_JSON,
|
|
13
|
+
REASON_CONCURRENCY_LIMIT_EXCEEDED,
|
|
8
14
|
REASON_CORRUPTED_FILE,
|
|
9
15
|
REASON_DOCUMENT_EXCEEDS_TIME_BUDGET,
|
|
16
|
+
REASON_IDEMPOTENCY_IN_PROGRESS,
|
|
17
|
+
REASON_IDEMPOTENCY_KEY_CONFLICT,
|
|
10
18
|
REASON_INVALID_API_KEY,
|
|
11
19
|
REASON_INVALID_PARAMS,
|
|
20
|
+
REASON_JOB_EXPIRED,
|
|
21
|
+
REASON_JOB_INTERRUPTED,
|
|
22
|
+
REASON_JOB_NOT_FOUND,
|
|
12
23
|
REASON_MISSING_BODY_FIELD,
|
|
13
24
|
REASON_MISSING_FILE_PART,
|
|
14
25
|
REASON_MISSING_QUERY_OR_PROMPT,
|
|
26
|
+
REASON_QUEUE_FULL,
|
|
27
|
+
REASON_RATE_LIMIT_EXCEEDED,
|
|
15
28
|
REASON_SERVICE_OVERLOADED,
|
|
16
29
|
REASON_UNSUPPORTED_FILE_TYPE,
|
|
17
30
|
REASON_UNSUPPORTED_MEDIA_TYPE,
|
|
@@ -25,7 +38,9 @@ from docql._errors import (
|
|
|
25
38
|
DocQLError,
|
|
26
39
|
DocQLException,
|
|
27
40
|
DocQLTimeoutError,
|
|
41
|
+
DocQLWaitTimeoutError,
|
|
28
42
|
)
|
|
43
|
+
from docql._jobs import Job
|
|
29
44
|
from docql._response import QueryResult
|
|
30
45
|
from docql._version import __version__
|
|
31
46
|
|
|
@@ -35,18 +50,33 @@ __all__ = [
|
|
|
35
50
|
"DocQLError",
|
|
36
51
|
"DocQLException",
|
|
37
52
|
"DocQLTimeoutError",
|
|
53
|
+
"DocQLWaitTimeoutError",
|
|
54
|
+
"JOB_STATUS_CANCELLED",
|
|
55
|
+
"JOB_STATUS_FAILED",
|
|
56
|
+
"JOB_STATUS_QUEUED",
|
|
57
|
+
"JOB_STATUS_RUNNING",
|
|
58
|
+
"JOB_STATUS_SUCCEEDED",
|
|
59
|
+
"Job",
|
|
38
60
|
"MODE_FAST",
|
|
39
61
|
"MODE_STANDARD",
|
|
40
62
|
"Mode",
|
|
41
63
|
"QueryResult",
|
|
42
64
|
"REASON_BODY_NOT_JSON",
|
|
65
|
+
"REASON_CONCURRENCY_LIMIT_EXCEEDED",
|
|
43
66
|
"REASON_CORRUPTED_FILE",
|
|
44
67
|
"REASON_DOCUMENT_EXCEEDS_TIME_BUDGET",
|
|
68
|
+
"REASON_IDEMPOTENCY_IN_PROGRESS",
|
|
69
|
+
"REASON_IDEMPOTENCY_KEY_CONFLICT",
|
|
45
70
|
"REASON_INVALID_API_KEY",
|
|
46
71
|
"REASON_INVALID_PARAMS",
|
|
72
|
+
"REASON_JOB_EXPIRED",
|
|
73
|
+
"REASON_JOB_INTERRUPTED",
|
|
74
|
+
"REASON_JOB_NOT_FOUND",
|
|
47
75
|
"REASON_MISSING_BODY_FIELD",
|
|
48
76
|
"REASON_MISSING_FILE_PART",
|
|
49
77
|
"REASON_MISSING_QUERY_OR_PROMPT",
|
|
78
|
+
"REASON_QUEUE_FULL",
|
|
79
|
+
"REASON_RATE_LIMIT_EXCEEDED",
|
|
50
80
|
"REASON_SERVICE_OVERLOADED",
|
|
51
81
|
"REASON_UNSUPPORTED_FILE_TYPE",
|
|
52
82
|
"REASON_UNSUPPORTED_MEDIA_TYPE",
|
|
@@ -11,6 +11,7 @@ from docql._constants import (
|
|
|
11
11
|
CONNECT_TIMEOUT,
|
|
12
12
|
DEFAULT_API_URL,
|
|
13
13
|
DEFAULT_TIMEOUT,
|
|
14
|
+
DEFAULT_WAIT_TIMEOUT,
|
|
14
15
|
ENV_API_KEY,
|
|
15
16
|
ENV_API_URL,
|
|
16
17
|
ERROR_BODY_READ_LIMIT,
|
|
@@ -18,6 +19,13 @@ from docql._constants import (
|
|
|
18
19
|
QUERY_PATH,
|
|
19
20
|
)
|
|
20
21
|
from docql._errors import DocQLConnectionError, DocQLTimeoutError
|
|
22
|
+
from docql._jobs import (
|
|
23
|
+
Job,
|
|
24
|
+
cancel,
|
|
25
|
+
fetch_job,
|
|
26
|
+
submit_with_retry,
|
|
27
|
+
wait_for,
|
|
28
|
+
)
|
|
21
29
|
from docql._request import Upload, _ShortReadError, prepare_upload
|
|
22
30
|
from docql._response import QueryResult, decode_error, parse_result
|
|
23
31
|
from docql._version import __version__
|
|
@@ -53,6 +61,11 @@ class DocQL:
|
|
|
53
61
|
production default. The key travels on each request, never as a client
|
|
54
62
|
default, and redirects are never followed, so it cannot leave the
|
|
55
63
|
configured host.
|
|
64
|
+
|
|
65
|
+
``query_document`` is one request that is never retried (calls are paid).
|
|
66
|
+
The job methods (``submit_document``, ``get_job``, ``wait``,
|
|
67
|
+
``cancel_job``) are the async alternative: ``wait`` is the only one that
|
|
68
|
+
repeats requests, and only GETs.
|
|
56
69
|
"""
|
|
57
70
|
|
|
58
71
|
def __init__(
|
|
@@ -134,7 +147,8 @@ class DocQL:
|
|
|
134
147
|
|
|
135
148
|
``file`` is a path (``str`` or ``os.PathLike``), raw ``bytes``, or a
|
|
136
149
|
binary file object read from its current position and never closed
|
|
137
|
-
(D-13/D-16).
|
|
150
|
+
(D-13/D-16). This is exactly one request and it is never retried; for
|
|
151
|
+
long documents use ``submit_document`` and ``wait``.
|
|
138
152
|
"""
|
|
139
153
|
with prepare_upload(
|
|
140
154
|
file, query=query, prompt=prompt, mode=mode, filename=filename
|
|
@@ -193,6 +207,87 @@ class DocQL:
|
|
|
193
207
|
return parse_result(response.status_code, response.headers, body, self._api_key)
|
|
194
208
|
raise decode_error(response.status_code, response.headers, body, self._api_key)
|
|
195
209
|
|
|
210
|
+
def submit_document(
|
|
211
|
+
self,
|
|
212
|
+
file: str | os.PathLike[str] | bytes | BinaryIO,
|
|
213
|
+
*,
|
|
214
|
+
query: str | None = None,
|
|
215
|
+
prompt: str | None = None,
|
|
216
|
+
mode: str | None = None,
|
|
217
|
+
filename: str | None = None,
|
|
218
|
+
idempotency_key: str | None = None,
|
|
219
|
+
) -> Job:
|
|
220
|
+
"""Submit one document as an async job and answer the queued Job (JSDK-01, JSDK-02).
|
|
221
|
+
|
|
222
|
+
The upload is built exactly as ``query_document`` builds it. Every
|
|
223
|
+
submit carries one ``Idempotency-Key``: ``idempotency_key`` when given
|
|
224
|
+
(1-255 printable ASCII characters, 0x20-0x7E, else ValueError before any
|
|
225
|
+
I/O), else a fresh random key. DocQL scopes the key to your organisation
|
|
226
|
+
and remembers it for 24 h (OD-14).
|
|
227
|
+
|
|
228
|
+
A 503 may mean the job was created anyway, so a 503 and a 409
|
|
229
|
+
``idempotency_in_progress`` are retried with the same key, at most 4
|
|
230
|
+
attempts in total, sleeping the server's ``Retry-After`` (clamped to
|
|
231
|
+
[1, 30] s) or 1, 2, 4 s. The retry happens only when the input can be
|
|
232
|
+
replayed: a path, ``bytes``, or a seekable file object, which is rewound
|
|
233
|
+
to the position it had when you called this method and to no other
|
|
234
|
+
position; it is never closed. Any other input is sent once. A 429,
|
|
235
|
+
every other error, a connection error and a timeout are never retried.
|
|
236
|
+
|
|
237
|
+
The key is on the returned Job and on every error this call raises, so
|
|
238
|
+
you can retry safely with it. A job that ended ``failed`` (including
|
|
239
|
+
``job_interrupted``) needs a new key: the old one replays the failure.
|
|
240
|
+
"""
|
|
241
|
+
return submit_with_retry(
|
|
242
|
+
self,
|
|
243
|
+
file,
|
|
244
|
+
query=query,
|
|
245
|
+
prompt=prompt,
|
|
246
|
+
mode=mode,
|
|
247
|
+
filename=filename,
|
|
248
|
+
idempotency_key=idempotency_key,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
def get_job(self, job_id: str) -> Job:
|
|
252
|
+
"""Fetch the job once and answer it (T-E2).
|
|
253
|
+
|
|
254
|
+
A failed job is answered with ``.error`` set, not raised. A non-2xx
|
|
255
|
+
answer (``job_not_found``, ``job_expired``, a 503, ...) raises
|
|
256
|
+
:class:`DocQLError` with ``job_id`` set. Exactly one request, never
|
|
257
|
+
retried.
|
|
258
|
+
"""
|
|
259
|
+
return fetch_job(self, job_id)
|
|
260
|
+
|
|
261
|
+
def wait(
|
|
262
|
+
self,
|
|
263
|
+
job_id: str,
|
|
264
|
+
*,
|
|
265
|
+
timeout: float = DEFAULT_WAIT_TIMEOUT,
|
|
266
|
+
poll_interval: float | None = None,
|
|
267
|
+
) -> Job:
|
|
268
|
+
"""Poll the job until it finishes and answer it (JSDK-01, D-03..D-05, OD-5).
|
|
269
|
+
|
|
270
|
+
A succeeded or cancelled job is answered (check ``status``); a failed
|
|
271
|
+
job raises its :class:`DocQLError` with ``job_id`` set. Each sleep is
|
|
272
|
+
the server's ``Retry-After`` clamped to [1, 30] s, raised to
|
|
273
|
+
``poll_interval`` when that is longer. Network errors, 429 and 503 are
|
|
274
|
+
retried; any other error raises at once. When ``timeout`` seconds
|
|
275
|
+
(default 900) run out before the job finishes it raises
|
|
276
|
+
:class:`DocQLWaitTimeoutError`; no poll is ever sent at or past that
|
|
277
|
+
deadline, and the job is never cancelled.
|
|
278
|
+
"""
|
|
279
|
+
return wait_for(self, job_id, timeout=timeout, poll_interval=poll_interval)
|
|
280
|
+
|
|
281
|
+
def cancel_job(self, job_id: str) -> Job:
|
|
282
|
+
"""Ask DocQL to cancel the job and answer the Job at answer time (OD-10).
|
|
283
|
+
|
|
284
|
+
A queued or running job may still be ``running`` in the answer; poll to
|
|
285
|
+
confirm (``get_job`` or ``wait``). A job that was already finished is
|
|
286
|
+
answered unchanged. A non-2xx answer raises :class:`DocQLError` with
|
|
287
|
+
``job_id`` set. Exactly one request, never retried.
|
|
288
|
+
"""
|
|
289
|
+
return cancel(self, job_id)
|
|
290
|
+
|
|
196
291
|
def close(self) -> None:
|
|
197
292
|
"""Close the httpx client the SDK created; an injected one stays open (D-06)."""
|
|
198
293
|
if self._owns_client:
|
|
@@ -35,9 +35,9 @@ ERROR_BODY_READ_LIMIT: Final[int] = 65536
|
|
|
35
35
|
# because an early RST may have discarded the 413 (research Pitfall 4).
|
|
36
36
|
MAX_UPLOAD_BYTES: Final[int] = 26_214_400
|
|
37
37
|
|
|
38
|
-
# Reason constants (D-05): exactly the
|
|
39
|
-
#
|
|
40
|
-
#
|
|
38
|
+
# Reason constants (D-05, D-09): exactly the 22 non-null reasons of the vendored
|
|
39
|
+
# contract kit — contract/sdk-cases.json (the sync stub and gateway errors) plus
|
|
40
|
+
# contract/job-cases.json (the job errors). The engine's wider class table stays
|
|
41
41
|
# reachable through the open ``reason: str``; adding constants later is
|
|
42
42
|
# backward compatible, removing them is not.
|
|
43
43
|
REASON_INVALID_API_KEY: Final[str] = "invalid_api_key"
|
|
@@ -54,3 +54,44 @@ REASON_DOCUMENT_EXCEEDS_TIME_BUDGET: Final[str] = "document_exceeds_time_budget"
|
|
|
54
54
|
REASON_SERVICE_OVERLOADED: Final[str] = "service_overloaded"
|
|
55
55
|
REASON_UPSTREAM_UNAVAILABLE: Final[str] = "upstream_unavailable"
|
|
56
56
|
REASON_UPSTREAM_AUTH_FAILED: Final[str] = "upstream_auth_failed"
|
|
57
|
+
REASON_CONCURRENCY_LIMIT_EXCEEDED: Final[str] = "concurrency_limit_exceeded"
|
|
58
|
+
REASON_RATE_LIMIT_EXCEEDED: Final[str] = "rate_limit_exceeded"
|
|
59
|
+
REASON_JOB_NOT_FOUND: Final[str] = "job_not_found"
|
|
60
|
+
REASON_JOB_EXPIRED: Final[str] = "job_expired"
|
|
61
|
+
REASON_QUEUE_FULL: Final[str] = "queue_full"
|
|
62
|
+
REASON_IDEMPOTENCY_KEY_CONFLICT: Final[str] = "idempotency_key_conflict"
|
|
63
|
+
REASON_IDEMPOTENCY_IN_PROGRESS: Final[str] = "idempotency_in_progress"
|
|
64
|
+
REASON_JOB_INTERRUPTED: Final[str] = "job_interrupted"
|
|
65
|
+
|
|
66
|
+
# Async jobs (JSDK-01). Status values are open strings (D-09): an unknown status
|
|
67
|
+
# from a future DocQL release is kept verbatim on Job.status, never an error.
|
|
68
|
+
JOBS_PATH: Final[str] = "/v1/jobs"
|
|
69
|
+
JOB_STATUS_QUEUED: Final[str] = "queued"
|
|
70
|
+
JOB_STATUS_RUNNING: Final[str] = "running"
|
|
71
|
+
JOB_STATUS_SUCCEEDED: Final[str] = "succeeded"
|
|
72
|
+
JOB_STATUS_FAILED: Final[str] = "failed"
|
|
73
|
+
JOB_STATUS_CANCELLED: Final[str] = "cancelled"
|
|
74
|
+
|
|
75
|
+
# One poll (get_job, cancel_job, each wait() poll): 30 s read, 10 s connect, never
|
|
76
|
+
# the 660 s upload timeout (research Pitfall 3). wait() also caps it by the time left.
|
|
77
|
+
POLL_READ_TIMEOUT: Final[float] = 30.0
|
|
78
|
+
|
|
79
|
+
# OD-5: wait() gives up after 15 minutes by default (540 s standard budget plus
|
|
80
|
+
# queue time) and never cancels the job.
|
|
81
|
+
DEFAULT_WAIT_TIMEOUT: Final[float] = 900.0
|
|
82
|
+
|
|
83
|
+
# Wait pacing, matching the kit's reference waitForJob (research F6, D-03): each
|
|
84
|
+
# Retry-After is clamped to [1, 30] s; a 200 without one sleeps 1 s.
|
|
85
|
+
RETRY_AFTER_FLOOR: Final[int] = 1
|
|
86
|
+
RETRY_AFTER_CAP: Final[int] = 30
|
|
87
|
+
RETRY_AFTER_ABSENT: Final[int] = 1
|
|
88
|
+
|
|
89
|
+
# Transient poll failures without Retry-After back off 1, 2, 4, 8, 16, 30 s (D-04).
|
|
90
|
+
TRANSIENT_BACKOFF_CAP: Final[int] = 30
|
|
91
|
+
|
|
92
|
+
# Submit safety (D-07, DocQL handoff Revision 2026-10-21: "treat every submit 503 as
|
|
93
|
+
# 'a job may exist' and retry with the same Idempotency-Key"). One submit_document()
|
|
94
|
+
# call makes at most 4 attempts, all with the same key; a retry without Retry-After
|
|
95
|
+
# sleeps 1, 2, then 4 s. Go and Java use the same two numbers.
|
|
96
|
+
SUBMIT_MAX_ATTEMPTS: Final[int] = 4
|
|
97
|
+
SUBMIT_BACKOFF: Final[tuple[int, ...]] = (1, 2, 4)
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"""Exception tree for the DocQL client (D-09/D-11/D-12).
|
|
2
2
|
|
|
3
3
|
DocQLException(Exception)
|
|
4
|
-
├── DocQLError # the server answered non-2xx
|
|
4
|
+
├── DocQLError # the server answered non-2xx, or a job failed
|
|
5
5
|
└── DocQLConnectionError # no response: connect, TLS, reset, early RST
|
|
6
6
|
└── DocQLTimeoutError
|
|
7
|
+
└── DocQLWaitTimeoutError # wait() ran out of time; the job was not cancelled
|
|
7
8
|
"""
|
|
8
9
|
|
|
9
10
|
from collections.abc import Callable
|
|
@@ -29,6 +30,11 @@ class DocQLError(DocQLException):
|
|
|
29
30
|
Neither :func:`str` nor :func:`repr` ever contains anything beyond the
|
|
30
31
|
stored fields, and ``body`` is scrubbed by the decoder before it is
|
|
31
32
|
stored, so no form leaks the API key.
|
|
33
|
+
|
|
34
|
+
``job_id`` is set on errors from the job methods (a failed job, a poll or
|
|
35
|
+
cancel error). ``idempotency_key`` is set on errors from
|
|
36
|
+
``submit_document`` so the caller can retry with the same key; it is a
|
|
37
|
+
field only and never appears in :func:`str` or :func:`repr` (D-08).
|
|
32
38
|
"""
|
|
33
39
|
|
|
34
40
|
def __init__(
|
|
@@ -41,6 +47,8 @@ class DocQLError(DocQLException):
|
|
|
41
47
|
retryable: bool,
|
|
42
48
|
message: str | None,
|
|
43
49
|
body: str,
|
|
50
|
+
job_id: str | None = None,
|
|
51
|
+
idempotency_key: str | None = None,
|
|
44
52
|
) -> None:
|
|
45
53
|
super().__init__()
|
|
46
54
|
self.status = status
|
|
@@ -50,6 +58,8 @@ class DocQLError(DocQLException):
|
|
|
50
58
|
self.retryable = retryable
|
|
51
59
|
self.message = message
|
|
52
60
|
self.body = body
|
|
61
|
+
self.job_id = job_id
|
|
62
|
+
self.idempotency_key = idempotency_key
|
|
53
63
|
|
|
54
64
|
def __str__(self) -> str:
|
|
55
65
|
if self.reason is not None:
|
|
@@ -61,12 +71,19 @@ class DocQLError(DocQLException):
|
|
|
61
71
|
extras.append(f"request_id={self.request_id}")
|
|
62
72
|
if self.retry_after is not None:
|
|
63
73
|
extras.append(f"retry_after={self.retry_after}s")
|
|
74
|
+
if self.job_id is not None:
|
|
75
|
+
extras.append(f"job_id={self.job_id}")
|
|
64
76
|
if extras:
|
|
65
77
|
text = f"{text} ({', '.join(extras)})"
|
|
66
78
|
return text
|
|
67
79
|
text = f"{self.status} (non-DocQL response): {_snippet(self.body)}"
|
|
80
|
+
tail = []
|
|
68
81
|
if self.request_id is not None:
|
|
69
|
-
|
|
82
|
+
tail.append(f"request_id={self.request_id}")
|
|
83
|
+
if self.job_id is not None:
|
|
84
|
+
tail.append(f"job_id={self.job_id}")
|
|
85
|
+
if tail:
|
|
86
|
+
text = f"{text} ({', '.join(tail)})"
|
|
70
87
|
return text
|
|
71
88
|
|
|
72
89
|
def __repr__(self) -> str:
|
|
@@ -87,6 +104,8 @@ class DocQLError(DocQLException):
|
|
|
87
104
|
"retryable": self.retryable,
|
|
88
105
|
"message": self.message,
|
|
89
106
|
"body": self.body,
|
|
107
|
+
"job_id": self.job_id,
|
|
108
|
+
"idempotency_key": self.idempotency_key,
|
|
90
109
|
},
|
|
91
110
|
)
|
|
92
111
|
|
|
@@ -96,11 +115,41 @@ def _rebuild_docql_error(fields: dict[str, Any]) -> DocQLError:
|
|
|
96
115
|
|
|
97
116
|
|
|
98
117
|
class DocQLConnectionError(DocQLException):
|
|
99
|
-
"""No DocQL response arrived: connect, TLS, reset or early connection close.
|
|
118
|
+
"""No DocQL response arrived: connect, TLS, reset or early connection close.
|
|
119
|
+
|
|
120
|
+
``idempotency_key`` is set when the failed request was a
|
|
121
|
+
``submit_document`` call, so the caller can retry it with the same key
|
|
122
|
+
(D-08). It never appears in the message.
|
|
123
|
+
"""
|
|
100
124
|
|
|
101
|
-
def __init__(self, message: str) -> None:
|
|
125
|
+
def __init__(self, message: str, *, idempotency_key: str | None = None) -> None:
|
|
102
126
|
super().__init__(message)
|
|
127
|
+
self.idempotency_key = idempotency_key
|
|
103
128
|
|
|
104
129
|
|
|
105
130
|
class DocQLTimeoutError(DocQLConnectionError):
|
|
106
131
|
"""The DocQL request timed out. The call may still have been billed."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class DocQLWaitTimeoutError(DocQLTimeoutError):
|
|
135
|
+
"""``wait()`` ran out of time before the job finished (OD-5).
|
|
136
|
+
|
|
137
|
+
The job was not cancelled: it may still finish, and ``get_job(job_id)``
|
|
138
|
+
or another ``wait(job_id)`` picks it up again.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
def __init__(self, *, job_id: str, timeout: float) -> None:
|
|
142
|
+
super().__init__(
|
|
143
|
+
f"wait for job {job_id} timed out after {timeout:g} s; the job was not cancelled"
|
|
144
|
+
)
|
|
145
|
+
self.job_id = job_id
|
|
146
|
+
self.timeout = timeout
|
|
147
|
+
|
|
148
|
+
def __reduce__(
|
|
149
|
+
self,
|
|
150
|
+
) -> tuple[Callable[[str, float], "DocQLWaitTimeoutError"], tuple[str, float]]:
|
|
151
|
+
return _rebuild_wait_timeout, (self.job_id, self.timeout)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _rebuild_wait_timeout(job_id: str, timeout: float) -> DocQLWaitTimeoutError:
|
|
155
|
+
return DocQLWaitTimeoutError(job_id=job_id, timeout=timeout)
|
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
"""Async jobs: the Job model, one-request primitive, the submit retry and the wait (JSDK-01/02).
|
|
2
|
+
|
|
3
|
+
The wait loop is a copy of the contract kit's reference ``waitForJob``
|
|
4
|
+
(docql-console ``apps/docql-stub/test/job-kit.ts``), so every SDK makes the same
|
|
5
|
+
requests and reaches the same outcome on the kit's ``waitCases``:
|
|
6
|
+
|
|
7
|
+
* D-03 (as adjusted to the kit, research F6): each sleep is the answer's
|
|
8
|
+
``Retry-After`` clamped to [1, 30] s, 1 s when a 200 carries none; a caller
|
|
9
|
+
``poll_interval`` raises the sleep to ``max(poll_interval, server value)``.
|
|
10
|
+
There is no jitter.
|
|
11
|
+
* D-04: a network error, a per-poll timeout, a 503 and a 429 are retried inside
|
|
12
|
+
``wait()``; without ``Retry-After`` they back off 1, 2, 4, 8, 16, 30 s, reset
|
|
13
|
+
after any 200. A 401, any 404 and every other status raise at once.
|
|
14
|
+
* D-05: ``succeeded`` and ``cancelled`` return the Job; ``failed`` raises the
|
|
15
|
+
job's :class:`DocQLError` (``job_id`` set, ``retryable`` False).
|
|
16
|
+
* OD-5: the wait gives up when the next sleep would pass the deadline (900 s by
|
|
17
|
+
default) and raises :class:`DocQLWaitTimeoutError`. It never polls at or past
|
|
18
|
+
the deadline: a sleep that ends exactly on it ends the wait too (as Go and
|
|
19
|
+
Java; the kit's reference runner polls once more at that instant, an edge no
|
|
20
|
+
kit case reaches). The wait never cancels the job, on any path: cancelling is
|
|
21
|
+
only the caller's explicit ``cancel_job()``.
|
|
22
|
+
|
|
23
|
+
Submits (:func:`submit_with_retry`, D-07) carry one ``Idempotency-Key`` and
|
|
24
|
+
retry a 503 or a 409 ``idempotency_in_progress`` with that same key, at most 4
|
|
25
|
+
attempts, and only when the input can be replayed from its start.
|
|
26
|
+
|
|
27
|
+
This module does not touch ``query_document``: its send block is copied, not
|
|
28
|
+
shared, so the v0.1 request path stays byte-identical (research Pitfall 12).
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import platform
|
|
36
|
+
import secrets
|
|
37
|
+
import time
|
|
38
|
+
import urllib.parse
|
|
39
|
+
from collections.abc import Mapping
|
|
40
|
+
from dataclasses import dataclass, field
|
|
41
|
+
from datetime import UTC, datetime
|
|
42
|
+
from typing import TYPE_CHECKING, Any, BinaryIO, cast
|
|
43
|
+
|
|
44
|
+
import httpx
|
|
45
|
+
|
|
46
|
+
from docql._constants import (
|
|
47
|
+
CONNECT_TIMEOUT,
|
|
48
|
+
JOB_STATUS_CANCELLED,
|
|
49
|
+
JOB_STATUS_FAILED,
|
|
50
|
+
JOB_STATUS_SUCCEEDED,
|
|
51
|
+
JOBS_PATH,
|
|
52
|
+
POLL_READ_TIMEOUT,
|
|
53
|
+
REASON_IDEMPOTENCY_IN_PROGRESS,
|
|
54
|
+
RETRY_AFTER_ABSENT,
|
|
55
|
+
RETRY_AFTER_CAP,
|
|
56
|
+
RETRY_AFTER_FLOOR,
|
|
57
|
+
SUBMIT_BACKOFF,
|
|
58
|
+
SUBMIT_MAX_ATTEMPTS,
|
|
59
|
+
TRANSIENT_BACKOFF_CAP,
|
|
60
|
+
)
|
|
61
|
+
from docql._errors import (
|
|
62
|
+
DocQLConnectionError,
|
|
63
|
+
DocQLError,
|
|
64
|
+
DocQLTimeoutError,
|
|
65
|
+
DocQLWaitTimeoutError,
|
|
66
|
+
)
|
|
67
|
+
from docql._request import (
|
|
68
|
+
Upload,
|
|
69
|
+
_is_binary_stream,
|
|
70
|
+
_remaining_length,
|
|
71
|
+
_ShortReadError,
|
|
72
|
+
prepare_upload,
|
|
73
|
+
)
|
|
74
|
+
from docql._response import (
|
|
75
|
+
QueryResult,
|
|
76
|
+
_header,
|
|
77
|
+
_int_or_none,
|
|
78
|
+
_unusable_result,
|
|
79
|
+
decode_error,
|
|
80
|
+
parse_result,
|
|
81
|
+
parse_retry_after,
|
|
82
|
+
)
|
|
83
|
+
from docql._version import __version__
|
|
84
|
+
|
|
85
|
+
if TYPE_CHECKING:
|
|
86
|
+
from docql._client import DocQL
|
|
87
|
+
|
|
88
|
+
# Module-level seams, looked up at call time: tests replace both with a fake
|
|
89
|
+
# clock to replay the kit's waitCases without real sleeps.
|
|
90
|
+
_sleep = time.sleep
|
|
91
|
+
_monotonic = time.monotonic
|
|
92
|
+
|
|
93
|
+
# Same origin rule as the client: h11/httpcore failures map to a connection error.
|
|
94
|
+
_INTERNAL_MODULE_ROOTS = ("h11", "httpcore")
|
|
95
|
+
|
|
96
|
+
_IDEMPOTENCY_KEY_ERROR = "idempotency_key must be 1-255 printable ASCII characters (0x20-0x7E)"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass(frozen=True)
|
|
100
|
+
class Job:
|
|
101
|
+
"""One DocQL job as the API answered it.
|
|
102
|
+
|
|
103
|
+
``status`` is an open string (D-09): compare it with the ``JOB_STATUS_*``
|
|
104
|
+
constants; an unknown value from a newer DocQL release is kept verbatim.
|
|
105
|
+
``result`` is set on a succeeded job and typed like ``query_document``'s
|
|
106
|
+
answer; ``error`` is set on a failed job. ``request_id`` is the
|
|
107
|
+
``X-Request-Id`` of the answer that produced this Job. ``retry_after`` is
|
|
108
|
+
the answer's ``Retry-After`` in seconds, for callers who poll
|
|
109
|
+
``get_job()`` themselves. ``idempotency_key`` is set only on the Job
|
|
110
|
+
``submit_document()`` returns; ``get_job()`` cannot know it.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
job_id: str
|
|
114
|
+
status: str
|
|
115
|
+
page_count: int | None
|
|
116
|
+
pages_done: int | None
|
|
117
|
+
request_id: str | None
|
|
118
|
+
created_at: datetime | None
|
|
119
|
+
started_at: datetime | None
|
|
120
|
+
finished_at: datetime | None
|
|
121
|
+
expires_at: datetime | None
|
|
122
|
+
result: QueryResult | None = field(repr=False)
|
|
123
|
+
error: DocQLError | None
|
|
124
|
+
retry_after: int | None
|
|
125
|
+
idempotency_key: str | None = field(repr=False)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def job_path(job_id: str) -> str:
|
|
129
|
+
"""The job URL path: the id as one percent-encoded segment, every ``.`` as %2E.
|
|
130
|
+
|
|
131
|
+
This is the gateway's own encoder (``job-routes.ts`` encodeJobIdSegment), so
|
|
132
|
+
``.`` and ``..`` ids are never normalised away. The id is opaque: only an
|
|
133
|
+
empty or non-str id is refused, its format is never checked.
|
|
134
|
+
"""
|
|
135
|
+
if not isinstance(job_id, str) or not job_id:
|
|
136
|
+
raise ValueError("job_id must be a non-empty string")
|
|
137
|
+
return JOBS_PATH + "/" + urllib.parse.quote(job_id, safe="").replace(".", "%2E")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def new_idempotency_key() -> str:
|
|
141
|
+
"""A fresh Idempotency-Key: 256 bits from the stdlib CSPRNG, URL-safe (D-07)."""
|
|
142
|
+
return secrets.token_urlsafe(32)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def validate_idempotency_key(key: str) -> str:
|
|
146
|
+
"""Return ``key`` unchanged when DocQL accepts it, else raise ValueError.
|
|
147
|
+
|
|
148
|
+
DocQL's rule: 1-255 bytes, every byte 0x20-0x7E. The message never echoes
|
|
149
|
+
the value, which DocQL and the gateway treat as sensitive (Pitfall 9).
|
|
150
|
+
"""
|
|
151
|
+
if not isinstance(key, str):
|
|
152
|
+
raise ValueError(_IDEMPOTENCY_KEY_ERROR)
|
|
153
|
+
raw = key.encode("utf-8")
|
|
154
|
+
if not 1 <= len(raw) <= 255 or any(byte < 0x20 or byte > 0x7E for byte in raw):
|
|
155
|
+
raise ValueError(_IDEMPOTENCY_KEY_ERROR)
|
|
156
|
+
return key
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _timestamp(value: Any) -> datetime | None:
|
|
160
|
+
if not isinstance(value, str):
|
|
161
|
+
return None
|
|
162
|
+
try:
|
|
163
|
+
parsed = datetime.fromisoformat(value)
|
|
164
|
+
except ValueError:
|
|
165
|
+
return None
|
|
166
|
+
if parsed.tzinfo is None:
|
|
167
|
+
parsed = parsed.replace(tzinfo=UTC)
|
|
168
|
+
return parsed
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def parse_job(
|
|
172
|
+
status: int,
|
|
173
|
+
headers: Mapping[str, str],
|
|
174
|
+
body: bytes,
|
|
175
|
+
api_key: str,
|
|
176
|
+
*,
|
|
177
|
+
idempotency_key: str | None = None,
|
|
178
|
+
) -> Job:
|
|
179
|
+
"""Decode a 2xx job answer (submit 202, poll 200, cancel 200/202) into a Job.
|
|
180
|
+
|
|
181
|
+
A body that is not a JSON object with a string ``job_id`` and ``status`` is
|
|
182
|
+
unusable and raises the same :class:`DocQLError` shape ``parse_result``
|
|
183
|
+
uses for an unusable 2xx. A succeeded job's ``result`` decodes through
|
|
184
|
+
``parse_result``; a failed job's ``error`` through ``decode_error`` with
|
|
185
|
+
the embedded ``status_code``, then ``job_id`` set and ``retryable`` False
|
|
186
|
+
(a failed job is final: retrying it replays the same failure).
|
|
187
|
+
"""
|
|
188
|
+
try:
|
|
189
|
+
doc: Any = json.loads(body)
|
|
190
|
+
except ValueError:
|
|
191
|
+
doc = None
|
|
192
|
+
if not isinstance(doc, dict):
|
|
193
|
+
raise _unusable_result(status, headers, body, api_key, "unexpected non-JSON response")
|
|
194
|
+
job_id = doc.get("job_id")
|
|
195
|
+
job_status = doc.get("status")
|
|
196
|
+
if not isinstance(job_id, str) or not isinstance(job_status, str):
|
|
197
|
+
raise _unusable_result(
|
|
198
|
+
status, headers, body, api_key, "unexpected response: not a DocQL job object"
|
|
199
|
+
)
|
|
200
|
+
metadata = doc.get("metadata")
|
|
201
|
+
if not isinstance(metadata, dict):
|
|
202
|
+
metadata = {}
|
|
203
|
+
|
|
204
|
+
result: QueryResult | None = None
|
|
205
|
+
raw_result = doc.get("result")
|
|
206
|
+
if job_status == JOB_STATUS_SUCCEEDED and isinstance(raw_result, dict):
|
|
207
|
+
result = parse_result(200, headers, json.dumps(raw_result).encode("utf-8"), api_key)
|
|
208
|
+
|
|
209
|
+
error: DocQLError | None = None
|
|
210
|
+
raw_error = doc.get("error")
|
|
211
|
+
if job_status == JOB_STATUS_FAILED and isinstance(raw_error, dict):
|
|
212
|
+
code = raw_error.get("status_code")
|
|
213
|
+
error = decode_error(
|
|
214
|
+
code if type(code) is int else 500,
|
|
215
|
+
{},
|
|
216
|
+
json.dumps(raw_error).encode("utf-8"),
|
|
217
|
+
api_key,
|
|
218
|
+
)
|
|
219
|
+
error.job_id = job_id
|
|
220
|
+
error.retryable = False
|
|
221
|
+
|
|
222
|
+
return Job(
|
|
223
|
+
job_id=job_id,
|
|
224
|
+
status=job_status,
|
|
225
|
+
page_count=_int_or_none(metadata.get("page_count")),
|
|
226
|
+
pages_done=_int_or_none(metadata.get("pages_done")),
|
|
227
|
+
request_id=_header(headers, "x-request-id"),
|
|
228
|
+
created_at=_timestamp(doc.get("created_at")),
|
|
229
|
+
started_at=_timestamp(doc.get("started_at")),
|
|
230
|
+
finished_at=_timestamp(doc.get("finished_at")),
|
|
231
|
+
expires_at=_timestamp(doc.get("expires_at")),
|
|
232
|
+
result=result,
|
|
233
|
+
error=error,
|
|
234
|
+
retry_after=parse_retry_after(_header(headers, "retry-after")),
|
|
235
|
+
idempotency_key=idempotency_key,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _send_once(
|
|
240
|
+
client: DocQL,
|
|
241
|
+
method: str,
|
|
242
|
+
path: str,
|
|
243
|
+
*,
|
|
244
|
+
upload: Upload | None = None,
|
|
245
|
+
idempotency_keys: tuple[str, ...] = (),
|
|
246
|
+
timeout: httpx.Timeout,
|
|
247
|
+
) -> tuple[int, httpx.Headers, bytes]:
|
|
248
|
+
"""Send exactly one job request and return ``(status, headers, body)``.
|
|
249
|
+
|
|
250
|
+
The query_document send block, copied: X-API-Key and User-Agent on every
|
|
251
|
+
request, Content-Type (and Content-Length when known) plus one
|
|
252
|
+
``Idempotency-Key`` line per given key on an upload; any X-Request-Id or
|
|
253
|
+
``x-docql-*`` header (an injected client's defaults included) is removed;
|
|
254
|
+
redirects are never followed. It never decodes and never retries.
|
|
255
|
+
"""
|
|
256
|
+
# The client's bounded error read, reused as-is (imported here: _client imports this module).
|
|
257
|
+
from docql._client import _read_error_body
|
|
258
|
+
|
|
259
|
+
for key in idempotency_keys:
|
|
260
|
+
validate_idempotency_key(key)
|
|
261
|
+
one_key = idempotency_keys[0] if len(idempotency_keys) == 1 else None
|
|
262
|
+
headers: list[tuple[str, str]] = [
|
|
263
|
+
("X-API-Key", client._api_key),
|
|
264
|
+
(
|
|
265
|
+
"User-Agent",
|
|
266
|
+
f"docql-python/{__version__} "
|
|
267
|
+
f"(python {platform.python_version()}; httpx {httpx.__version__})",
|
|
268
|
+
),
|
|
269
|
+
]
|
|
270
|
+
if upload is not None:
|
|
271
|
+
headers.append(("Content-Type", upload.content_type))
|
|
272
|
+
if upload.content_length is not None:
|
|
273
|
+
headers.append(("Content-Length", str(upload.content_length)))
|
|
274
|
+
for key in idempotency_keys:
|
|
275
|
+
headers.append(("Idempotency-Key", key))
|
|
276
|
+
request = client._client.build_request(
|
|
277
|
+
method,
|
|
278
|
+
client._api_url + path,
|
|
279
|
+
content=upload.iter_bytes() if upload is not None else None,
|
|
280
|
+
headers=headers,
|
|
281
|
+
timeout=timeout,
|
|
282
|
+
)
|
|
283
|
+
for header_name in list(request.headers.keys()):
|
|
284
|
+
lowered = header_name.lower()
|
|
285
|
+
if lowered == "x-request-id" or lowered.startswith("x-docql-"):
|
|
286
|
+
del request.headers[header_name]
|
|
287
|
+
|
|
288
|
+
def connection_message(exc: Exception) -> str:
|
|
289
|
+
if upload is not None:
|
|
290
|
+
return client._connection_message(exc, upload)
|
|
291
|
+
return client._scrub(f"connection to {client._api_url} failed: {type(exc).__name__}")
|
|
292
|
+
|
|
293
|
+
response: httpx.Response | None = None
|
|
294
|
+
body: bytes
|
|
295
|
+
try:
|
|
296
|
+
response = client._client.send(request, follow_redirects=False, stream=True)
|
|
297
|
+
body = response.read() if 200 <= response.status_code < 300 else _read_error_body(response)
|
|
298
|
+
except httpx.TimeoutException as exc:
|
|
299
|
+
raise DocQLTimeoutError(
|
|
300
|
+
client._scrub(f"DocQL request timed out after {timeout}"), idempotency_key=one_key
|
|
301
|
+
) from exc
|
|
302
|
+
except (_ShortReadError, httpx.RequestError) as exc:
|
|
303
|
+
raise DocQLConnectionError(connection_message(exc), idempotency_key=one_key) from exc
|
|
304
|
+
except Exception as exc:
|
|
305
|
+
if type(exc).__module__.split(".", 1)[0] in _INTERNAL_MODULE_ROOTS:
|
|
306
|
+
raise DocQLConnectionError(connection_message(exc), idempotency_key=one_key) from exc
|
|
307
|
+
raise
|
|
308
|
+
finally:
|
|
309
|
+
if response is not None:
|
|
310
|
+
response.close()
|
|
311
|
+
return response.status_code, response.headers, body
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _job_error(
|
|
315
|
+
status: int, headers: Mapping[str, str], body: bytes, api_key: str, job_id: str
|
|
316
|
+
) -> DocQLError:
|
|
317
|
+
error = decode_error(status, headers, body, api_key)
|
|
318
|
+
error.job_id = job_id
|
|
319
|
+
return error
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _is_replayable(file: object) -> bool:
|
|
323
|
+
"""True when the submit body can be rebuilt byte for byte from its start (D-07).
|
|
324
|
+
|
|
325
|
+
A path (``str`` / ``os.PathLike``) is re-opened and ``bytes`` are kept, so
|
|
326
|
+
both replay. A binary file object replays only when ``seekable()`` is True
|
|
327
|
+
and ``tell()``/``seek()`` work (v0.1's ``_remaining_length`` measures it):
|
|
328
|
+
the retry rewinds it to the position recorded before the first attempt.
|
|
329
|
+
Anything else (a pipe, a socket, ``sys.stdin.buffer``, an HTTP response
|
|
330
|
+
stream) cannot be replayed, so its submit is never retried.
|
|
331
|
+
"""
|
|
332
|
+
if isinstance(file, (str, os.PathLike, bytes)):
|
|
333
|
+
return True
|
|
334
|
+
if not _is_binary_stream(file):
|
|
335
|
+
return False
|
|
336
|
+
seekable = getattr(file, "seekable", None)
|
|
337
|
+
if not callable(seekable):
|
|
338
|
+
return False
|
|
339
|
+
try:
|
|
340
|
+
if not seekable():
|
|
341
|
+
return False
|
|
342
|
+
except (OSError, ValueError):
|
|
343
|
+
return False
|
|
344
|
+
return _remaining_length(cast("BinaryIO", file)) is not None
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def submit_with_retry(
|
|
348
|
+
client: DocQL,
|
|
349
|
+
file: str | os.PathLike[str] | bytes | BinaryIO,
|
|
350
|
+
*,
|
|
351
|
+
query: str | None,
|
|
352
|
+
prompt: str | None,
|
|
353
|
+
mode: str | None,
|
|
354
|
+
filename: str | None,
|
|
355
|
+
idempotency_key: str | None,
|
|
356
|
+
) -> Job:
|
|
357
|
+
"""Submit a job with one Idempotency-Key and a bounded same-key retry (JSDK-02, D-07, D-08).
|
|
358
|
+
|
|
359
|
+
DocQL's handoff (Revision 2026-10-21) says a submit 503 may already have
|
|
360
|
+
created the job: "treat every submit 503 as 'a job may exist' and retry
|
|
361
|
+
with the same Idempotency-Key". So, with the same key on every attempt and
|
|
362
|
+
at most ``SUBMIT_MAX_ATTEMPTS`` attempts:
|
|
363
|
+
|
|
364
|
+
* any 503, and a 409 ``idempotency_in_progress`` (another submit with this
|
|
365
|
+
key is still being persisted), is retried when the input is replayable
|
|
366
|
+
(:func:`_is_replayable`); each sleep is ``Retry-After`` clamped to
|
|
367
|
+
[1, 30] s, else 1, 2, 4 s (``SUBMIT_BACKOFF``);
|
|
368
|
+
* a 429 (``queue_full``, ``rate_limit_exceeded``,
|
|
369
|
+
``concurrency_limit_exceeded``: no job exists), every other status, a
|
|
370
|
+
transport error and a timeout are raised at once;
|
|
371
|
+
* a key is never regenerated for a retry (a new key could create a second
|
|
372
|
+
billable job), and a stream is only ever rewound to its recorded start.
|
|
373
|
+
|
|
374
|
+
Every error raised here carries ``idempotency_key`` so the caller can retry
|
|
375
|
+
safely with it. Go (``SubmitDocument``) and Java (``submitDocument``) copy
|
|
376
|
+
this loop: same cap, same backoff, same retryable set.
|
|
377
|
+
"""
|
|
378
|
+
key = (
|
|
379
|
+
validate_idempotency_key(idempotency_key)
|
|
380
|
+
if idempotency_key is not None
|
|
381
|
+
else new_idempotency_key()
|
|
382
|
+
)
|
|
383
|
+
replayable = _is_replayable(file)
|
|
384
|
+
stream: BinaryIO | None = None
|
|
385
|
+
start = 0
|
|
386
|
+
if replayable and not isinstance(file, (str, os.PathLike, bytes)):
|
|
387
|
+
stream = file
|
|
388
|
+
start = stream.tell()
|
|
389
|
+
attempt = 0
|
|
390
|
+
while True:
|
|
391
|
+
attempt += 1
|
|
392
|
+
if attempt > 1 and stream is not None:
|
|
393
|
+
stream.seek(start)
|
|
394
|
+
with prepare_upload(
|
|
395
|
+
file, query=query, prompt=prompt, mode=mode, filename=filename
|
|
396
|
+
) as upload:
|
|
397
|
+
status, headers, body = _send_once(
|
|
398
|
+
client,
|
|
399
|
+
"POST",
|
|
400
|
+
JOBS_PATH,
|
|
401
|
+
upload=upload,
|
|
402
|
+
idempotency_keys=(key,),
|
|
403
|
+
timeout=client._timeout,
|
|
404
|
+
)
|
|
405
|
+
if 200 <= status < 300:
|
|
406
|
+
try:
|
|
407
|
+
return parse_job(status, headers, body, client._api_key, idempotency_key=key)
|
|
408
|
+
except DocQLError as unusable:
|
|
409
|
+
unusable.idempotency_key = key
|
|
410
|
+
raise
|
|
411
|
+
error = decode_error(status, headers, body, client._api_key)
|
|
412
|
+
error.idempotency_key = key
|
|
413
|
+
retryable = status == 503 or (
|
|
414
|
+
status == 409 and error.reason == REASON_IDEMPOTENCY_IN_PROGRESS
|
|
415
|
+
)
|
|
416
|
+
if not (retryable and replayable and attempt < SUBMIT_MAX_ATTEMPTS):
|
|
417
|
+
raise error
|
|
418
|
+
server = parse_retry_after(_header(headers, "retry-after"))
|
|
419
|
+
if server is not None:
|
|
420
|
+
_sleep(min(max(server, RETRY_AFTER_FLOOR), RETRY_AFTER_CAP))
|
|
421
|
+
else:
|
|
422
|
+
_sleep(SUBMIT_BACKOFF[attempt - 1])
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def fetch_job(client: DocQL, job_id: str) -> Job:
|
|
426
|
+
"""One GET of the job: a Job for any 2xx (a failed job included), else DocQLError."""
|
|
427
|
+
path = job_path(job_id)
|
|
428
|
+
status, headers, body = _send_once(
|
|
429
|
+
client, "GET", path, timeout=httpx.Timeout(POLL_READ_TIMEOUT, connect=CONNECT_TIMEOUT)
|
|
430
|
+
)
|
|
431
|
+
if 200 <= status < 300:
|
|
432
|
+
return parse_job(status, headers, body, client._api_key)
|
|
433
|
+
raise _job_error(status, headers, body, client._api_key, job_id)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def cancel(client: DocQL, job_id: str) -> Job:
|
|
437
|
+
"""One DELETE of the job (OD-10): the Job as answered, else DocQLError with job_id.
|
|
438
|
+
|
|
439
|
+
A 202 answers the job as it is right after the cancel request; a 200 answers
|
|
440
|
+
a job that was already terminal. This is the only DELETE in the SDK, and only
|
|
441
|
+
the caller's explicit ``cancel_job()`` reaches it.
|
|
442
|
+
"""
|
|
443
|
+
path = job_path(job_id)
|
|
444
|
+
status, headers, body = _send_once(
|
|
445
|
+
client, "DELETE", path, timeout=httpx.Timeout(POLL_READ_TIMEOUT, connect=CONNECT_TIMEOUT)
|
|
446
|
+
)
|
|
447
|
+
if 200 <= status < 300:
|
|
448
|
+
return parse_job(status, headers, body, client._api_key)
|
|
449
|
+
raise _job_error(status, headers, body, client._api_key, job_id)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def wait_for(client: DocQL, job_id: str, *, timeout: float, poll_interval: float | None) -> Job:
|
|
453
|
+
"""Poll the job until it is succeeded or cancelled; the kit's waitForJob (module docstring)."""
|
|
454
|
+
path = job_path(job_id)
|
|
455
|
+
if not timeout > 0:
|
|
456
|
+
raise ValueError("timeout must be greater than 0 seconds")
|
|
457
|
+
if poll_interval is not None and not poll_interval > 0:
|
|
458
|
+
raise ValueError("poll_interval must be greater than 0 seconds")
|
|
459
|
+
deadline = _monotonic() + timeout
|
|
460
|
+
backoff = 1
|
|
461
|
+
while True:
|
|
462
|
+
remaining = max(deadline - _monotonic(), 1.0)
|
|
463
|
+
poll_timeout = httpx.Timeout(
|
|
464
|
+
min(POLL_READ_TIMEOUT, remaining), connect=min(CONNECT_TIMEOUT, remaining)
|
|
465
|
+
)
|
|
466
|
+
server: int | None
|
|
467
|
+
try:
|
|
468
|
+
status, headers, body = _send_once(client, "GET", path, timeout=poll_timeout)
|
|
469
|
+
except DocQLConnectionError:
|
|
470
|
+
# A network error or a per-poll timeout: transient.
|
|
471
|
+
transient = True
|
|
472
|
+
server = None
|
|
473
|
+
else:
|
|
474
|
+
if 200 <= status < 300:
|
|
475
|
+
job = parse_job(status, headers, body, client._api_key)
|
|
476
|
+
if job.status in (JOB_STATUS_SUCCEEDED, JOB_STATUS_CANCELLED):
|
|
477
|
+
return job
|
|
478
|
+
if job.status == JOB_STATUS_FAILED:
|
|
479
|
+
if job.error is not None:
|
|
480
|
+
raise job.error
|
|
481
|
+
raise _unusable_result(
|
|
482
|
+
status,
|
|
483
|
+
headers,
|
|
484
|
+
body,
|
|
485
|
+
client._api_key,
|
|
486
|
+
"unexpected response: failed job without an error object",
|
|
487
|
+
)
|
|
488
|
+
# queued, running or a status this SDK does not know (D-09).
|
|
489
|
+
transient = False
|
|
490
|
+
backoff = 1
|
|
491
|
+
elif status in (429, 503):
|
|
492
|
+
transient = True
|
|
493
|
+
else:
|
|
494
|
+
raise _job_error(status, headers, body, client._api_key, job_id)
|
|
495
|
+
server = parse_retry_after(_header(headers, "retry-after"))
|
|
496
|
+
|
|
497
|
+
sleep: float
|
|
498
|
+
if server is not None:
|
|
499
|
+
sleep = min(max(server, RETRY_AFTER_FLOOR), RETRY_AFTER_CAP)
|
|
500
|
+
elif transient:
|
|
501
|
+
sleep = backoff
|
|
502
|
+
backoff = min(backoff * 2, TRANSIENT_BACKOFF_CAP)
|
|
503
|
+
else:
|
|
504
|
+
sleep = RETRY_AFTER_ABSENT
|
|
505
|
+
if poll_interval is not None:
|
|
506
|
+
sleep = max(poll_interval, sleep)
|
|
507
|
+
if _monotonic() + sleep > deadline:
|
|
508
|
+
raise DocQLWaitTimeoutError(job_id=job_id, timeout=timeout)
|
|
509
|
+
_sleep(sleep)
|
|
510
|
+
# A sleep that ends exactly on the deadline (or a real sleep that
|
|
511
|
+
# overshoots it) leaves no time for a poll: never poll at or past the
|
|
512
|
+
# deadline (owner decision 2026-10-26, as Go and Java).
|
|
513
|
+
if _monotonic() >= deadline:
|
|
514
|
+
raise DocQLWaitTimeoutError(job_id=job_id, timeout=timeout)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|