docql 0.2.0__tar.gz → 0.2.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: docql
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Python client for the DocQL document-extraction API
5
5
  Author: Finoniq
6
6
  License-Expression: Apache-2.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "docql"
3
- version = "0.2.0"
3
+ version = "0.2.1"
4
4
  description = "Python client for the DocQL document-extraction API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "docql"
3
- version = "0.2.0"
3
+ version = "0.2.1"
4
4
  description = "Python client for the DocQL document-extraction API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -237,6 +237,15 @@ class DocQL:
237
237
  The key is on the returned Job and on every error this call raises, so
238
238
  you can retry safely with it. A job that ended ``failed`` (including
239
239
  ``job_interrupted``) needs a new key: the old one replays the failure.
240
+
241
+ Once the first request has gone out a job may exist. If the input then
242
+ cannot be rewound, re-opened or re-read for a retry, this raises
243
+ :class:`DocQLConnectionError` with ``idempotency_key`` set (the original
244
+ error is its ``__cause__``) and sends nothing more. An interrupt (Ctrl-C,
245
+ ``SystemExit``) or any other non-DocQL exception after that point keeps
246
+ its type and carries the key as its ``idempotency_key`` attribute; the
247
+ key is never printed. If you must resume after a crash, pass your own
248
+ ``idempotency_key=``.
240
249
  """
241
250
  return submit_with_retry(
242
251
  self,
@@ -253,8 +262,8 @@ class DocQL:
253
262
 
254
263
  A failed job is answered with ``.error`` set, not raised. A non-2xx
255
264
  answer (``job_not_found``, ``job_expired``, a 503, ...) raises
256
- :class:`DocQLError` with ``job_id`` set. Exactly one request, never
257
- retried.
265
+ :class:`DocQLError`. Every DocQLError it raises, an unusable 2xx answer
266
+ included, carries ``job_id``. Exactly one request, never retried.
258
267
  """
259
268
  return fetch_job(self, job_id)
260
269
 
@@ -274,7 +283,9 @@ class DocQL:
274
283
  retried; any other error raises at once. When ``timeout`` seconds
275
284
  (default 900) run out before the job finishes it raises
276
285
  :class:`DocQLWaitTimeoutError`; no poll is ever sent at or past that
277
- deadline, and the job is never cancelled.
286
+ deadline, and the job is never cancelled. Every DocQLError it raises
287
+ (a failed job, an unusable answer, a non-retried error) carries
288
+ ``job_id``.
278
289
  """
279
290
  return wait_for(self, job_id, timeout=timeout, poll_interval=poll_interval)
280
291
 
@@ -283,8 +294,9 @@ class DocQL:
283
294
 
284
295
  A queued or running job may still be ``running`` in the answer; poll to
285
296
  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.
297
+ answered unchanged. A non-2xx answer raises :class:`DocQLError`. Every
298
+ DocQLError it raises, an unusable 2xx answer included, carries
299
+ ``job_id``. Exactly one request, never retried.
288
300
  """
289
301
  return cancel(self, job_id)
290
302
 
@@ -30,6 +30,7 @@ shared, so the v0.1 request path stays byte-identical (research Pitfall 12).
30
30
 
31
31
  from __future__ import annotations
32
32
 
33
+ import contextlib
33
34
  import json
34
35
  import os
35
36
  import platform
@@ -61,6 +62,7 @@ from docql._constants import (
61
62
  from docql._errors import (
62
63
  DocQLConnectionError,
63
64
  DocQLError,
65
+ DocQLException,
64
66
  DocQLTimeoutError,
65
67
  DocQLWaitTimeoutError,
66
68
  )
@@ -95,6 +97,23 @@ _INTERNAL_MODULE_ROOTS = ("h11", "httpcore")
95
97
 
96
98
  _IDEMPOTENCY_KEY_ERROR = "idempotency_key must be 1-255 printable ASCII characters (0x20-0x7E)"
97
99
 
100
+ # The DocQLConnectionError a same-key submit retry raises when the body cannot be
101
+ # rebuilt (WR-01, D-08). It never names the key: the key is a field only.
102
+ _REREAD_ERROR = (
103
+ "could not re-read the document for the same-key submit retry; "
104
+ "the job may exist, so retry with this error's idempotency_key"
105
+ )
106
+
107
+ # The note a non-DocQL exception (Ctrl-C, SystemExit, ...) gains when it leaves a
108
+ # submit after its first request (WR-01). It names the attribute, never the key:
109
+ # notes are printed in every traceback (D-08, research Pitfall 9).
110
+ _KEY_NOTE = (
111
+ "docql: submit_document stopped after its first request; a job may exist. "
112
+ "This exception's idempotency_key attribute holds the Idempotency-Key that was "
113
+ "sent; resubmit with idempotency_key= set to it, or pass your own "
114
+ "idempotency_key= so a resubmit after a crash cannot create a second job"
115
+ )
116
+
98
117
 
99
118
  @dataclass(frozen=True)
100
119
  class Job:
@@ -319,6 +338,45 @@ def _job_error(
319
338
  return error
320
339
 
321
340
 
341
+ def _job_or_raise(
342
+ status: int, headers: Mapping[str, str], body: bytes, api_key: str, job_id: str
343
+ ) -> Job:
344
+ """A job-id method's answer as a Job; every DocQLError it raises names ``job_id`` (WR-02).
345
+
346
+ A non-2xx raises :func:`_job_error`; an unusable 2xx (not a job object, or
347
+ a succeeded job whose result cannot be decoded) raises ``parse_job``'s
348
+ error with the caller's ``job_id`` set, as Go's ``withJobID`` and Java's
349
+ ``withJob`` do.
350
+ """
351
+ if not 200 <= status < 300:
352
+ raise _job_error(status, headers, body, api_key, job_id)
353
+ try:
354
+ return parse_job(status, headers, body, api_key)
355
+ except DocQLError as error:
356
+ if error.job_id is None:
357
+ error.job_id = job_id
358
+ raise
359
+
360
+
361
+ def _carry_key(exc: BaseException, key: str) -> None:
362
+ """Attach the sent Idempotency-Key to a non-DocQL exception leaving a submit (WR-01).
363
+
364
+ The exception keeps its type (``except KeyboardInterrupt`` still works); the
365
+ key goes on its ``idempotency_key`` attribute and one key-free note says
366
+ where to find it. A DocQL error already carries the key as a field, and an
367
+ exception that already has the attribute is left alone. The store goes
368
+ through the instance ``__dict__``; if the object refuses it, the original
369
+ exception is re-raised unchanged rather than masked.
370
+ """
371
+ if isinstance(exc, DocQLException):
372
+ return
373
+ with contextlib.suppress(AttributeError, TypeError):
374
+ if hasattr(exc, "idempotency_key"):
375
+ return
376
+ exc.__dict__["idempotency_key"] = key
377
+ exc.add_note(_KEY_NOTE)
378
+
379
+
322
380
  def _is_replayable(file: object) -> bool:
323
381
  """True when the submit body can be rebuilt byte for byte from its start (D-07).
324
382
 
@@ -374,6 +432,17 @@ def submit_with_retry(
374
432
  Every error raised here carries ``idempotency_key`` so the caller can retry
375
433
  safely with it. Go (``SubmitDocument``) and Java (``submitDocument``) copy
376
434
  this loop: same cap, same backoff, same retryable set.
435
+
436
+ Once the first request has gone out a job may exist, so on attempts 2-4 any
437
+ failure to rewind, re-open, re-read or re-send the input is raised as
438
+ :class:`DocQLConnectionError` with the key, chained from the original, and
439
+ nothing more is sent (Go's ``*ConnectionError``, Java's
440
+ ``DocQLConnectionException``). Any other exception that leaves a send or a
441
+ retry sleep (a ``KeyboardInterrupt``, ``SystemExit``, ...) keeps its type
442
+ and carries the key as its ``idempotency_key`` attribute, with a note that
443
+ names the attribute but never the key (:func:`_carry_key`). Before the
444
+ first request nothing is wrapped. Callers who must resume after a crash
445
+ pass their own ``idempotency_key=`` (DocQL scopes it to the org, OD-14).
377
446
  """
378
447
  key = (
379
448
  validate_idempotency_key(idempotency_key)
@@ -389,19 +458,31 @@ def submit_with_retry(
389
458
  attempt = 0
390
459
  while True:
391
460
  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
- )
461
+ # True once a request with this key may have reached the transport.
462
+ handed = attempt > 1
463
+ try:
464
+ if attempt > 1 and stream is not None:
465
+ stream.seek(start)
466
+ with prepare_upload(
467
+ file, query=query, prompt=prompt, mode=mode, filename=filename
468
+ ) as upload:
469
+ handed = True
470
+ status, headers, body = _send_once(
471
+ client,
472
+ "POST",
473
+ JOBS_PATH,
474
+ upload=upload,
475
+ idempotency_keys=(key,),
476
+ timeout=client._timeout,
477
+ )
478
+ except BaseException as exc:
479
+ if attempt > 1 and isinstance(exc, Exception) and not isinstance(exc, DocQLException):
480
+ # A job may exist from an earlier attempt: never send a partial
481
+ # or different body under this key, and never lose the key.
482
+ raise DocQLConnectionError(_REREAD_ERROR, idempotency_key=key) from exc
483
+ if handed:
484
+ _carry_key(exc, key)
485
+ raise
405
486
  if 200 <= status < 300:
406
487
  try:
407
488
  return parse_job(status, headers, body, client._api_key, idempotency_key=key)
@@ -416,10 +497,16 @@ def submit_with_retry(
416
497
  if not (retryable and replayable and attempt < SUBMIT_MAX_ATTEMPTS):
417
498
  raise error
418
499
  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])
500
+ delay = (
501
+ min(max(server, RETRY_AFTER_FLOOR), RETRY_AFTER_CAP)
502
+ if server is not None
503
+ else SUBMIT_BACKOFF[attempt - 1]
504
+ )
505
+ try:
506
+ _sleep(delay)
507
+ except BaseException as exc:
508
+ _carry_key(exc, key)
509
+ raise
423
510
 
424
511
 
425
512
  def fetch_job(client: DocQL, job_id: str) -> Job:
@@ -428,9 +515,7 @@ def fetch_job(client: DocQL, job_id: str) -> Job:
428
515
  status, headers, body = _send_once(
429
516
  client, "GET", path, timeout=httpx.Timeout(POLL_READ_TIMEOUT, connect=CONNECT_TIMEOUT)
430
517
  )
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)
518
+ return _job_or_raise(status, headers, body, client._api_key, job_id)
434
519
 
435
520
 
436
521
  def cancel(client: DocQL, job_id: str) -> Job:
@@ -444,9 +529,7 @@ def cancel(client: DocQL, job_id: str) -> Job:
444
529
  status, headers, body = _send_once(
445
530
  client, "DELETE", path, timeout=httpx.Timeout(POLL_READ_TIMEOUT, connect=CONNECT_TIMEOUT)
446
531
  )
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)
532
+ return _job_or_raise(status, headers, body, client._api_key, job_id)
450
533
 
451
534
 
452
535
  def wait_for(client: DocQL, job_id: str, *, timeout: float, poll_interval: float | None) -> Job:
@@ -472,19 +555,21 @@ def wait_for(client: DocQL, job_id: str, *, timeout: float, poll_interval: float
472
555
  server = None
473
556
  else:
474
557
  if 200 <= status < 300:
475
- job = parse_job(status, headers, body, client._api_key)
558
+ job = _job_or_raise(status, headers, body, client._api_key, job_id)
476
559
  if job.status in (JOB_STATUS_SUCCEEDED, JOB_STATUS_CANCELLED):
477
560
  return job
478
561
  if job.status == JOB_STATUS_FAILED:
479
562
  if job.error is not None:
480
563
  raise job.error
481
- raise _unusable_result(
564
+ no_error = _unusable_result(
482
565
  status,
483
566
  headers,
484
567
  body,
485
568
  client._api_key,
486
569
  "unexpected response: failed job without an error object",
487
570
  )
571
+ no_error.job_id = job_id
572
+ raise no_error
488
573
  # queued, running or a status this SDK does not know (D-09).
489
574
  transient = False
490
575
  backoff = 1
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes