docql 0.2.0__tar.gz → 0.3.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: docql
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Python client for the DocQL document-extraction API
5
5
  Author: Finoniq
6
6
  License-Expression: Apache-2.0
@@ -133,6 +133,38 @@ binary file object:
133
133
  - There are no client-side type or size checks — the server is the authority.
134
134
  - A stream whose length cannot be measured is sent chunked; an oversized one
135
135
  may answer `503` instead of `413`. The API rejects files over 25 MiB.
136
+ - A CSV is recognised only by a file name that ends in `.csv`, in any letter
137
+ case (`sales.csv`, `SALES.CSV`). When you send `bytes` or a stream, pass the
138
+ name with `filename=`. The name is sent exactly as given and never trimmed,
139
+ so `"a.csv "` with a trailing space is refused with `unsupported_file_type`.
140
+
141
+ ## Spreadsheets
142
+
143
+ `.xlsx`, `.ods` and `.csv` files are sent like any other file. A refused
144
+ spreadsheet raises `docql.DocQLError`, whose `metadata` is the server's raw
145
+ refusal object. For `spreadsheet_too_large` it holds the measured value under
146
+ its axis key (`cells`, `runes`, `estimated_output_tokens` or `bytes`), plus
147
+ `limit`, `reason` and `request_id`. Find the axis by name, not by key order:
148
+
149
+ <!-- docql:spreadsheet:start -->
150
+ ```python
151
+ from pathlib import Path
152
+
153
+ import docql
154
+ from docql import DocQL
155
+
156
+ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
157
+ data = Path("sales.csv").read_bytes()
158
+ try:
159
+ result = client.query_document(data, query="{ region total_sales }", filename="sales.csv")
160
+ print(result.page_count)
161
+ except docql.DocQLError as err:
162
+ if err.reason != docql.REASON_SPREADSHEET_TOO_LARGE:
163
+ raise
164
+ axis = next(k for k in err.metadata if k not in ("limit", "reason", "request_id"))
165
+ print(f"too large: {axis}={err.metadata[axis]} limit={err.metadata['limit']}")
166
+ ```
167
+ <!-- docql:spreadsheet:end -->
136
168
 
137
169
  ## Modes
138
170
 
@@ -208,7 +240,7 @@ two mean the request was not processed.
208
240
  ## Versioning
209
241
 
210
242
  The SDK follows [Semantic Versioning](https://semver.org/). While the major
211
- version is 0, a minor release may change the API; pin `docql>=0.2,<0.3` until
243
+ version is 0, a minor release may change the API; pin `docql>=0.3,<0.4` until
212
244
  1.0.
213
245
 
214
246
  ## Support
@@ -111,6 +111,38 @@ binary file object:
111
111
  - There are no client-side type or size checks — the server is the authority.
112
112
  - A stream whose length cannot be measured is sent chunked; an oversized one
113
113
  may answer `503` instead of `413`. The API rejects files over 25 MiB.
114
+ - A CSV is recognised only by a file name that ends in `.csv`, in any letter
115
+ case (`sales.csv`, `SALES.CSV`). When you send `bytes` or a stream, pass the
116
+ name with `filename=`. The name is sent exactly as given and never trimmed,
117
+ so `"a.csv "` with a trailing space is refused with `unsupported_file_type`.
118
+
119
+ ## Spreadsheets
120
+
121
+ `.xlsx`, `.ods` and `.csv` files are sent like any other file. A refused
122
+ spreadsheet raises `docql.DocQLError`, whose `metadata` is the server's raw
123
+ refusal object. For `spreadsheet_too_large` it holds the measured value under
124
+ its axis key (`cells`, `runes`, `estimated_output_tokens` or `bytes`), plus
125
+ `limit`, `reason` and `request_id`. Find the axis by name, not by key order:
126
+
127
+ <!-- docql:spreadsheet:start -->
128
+ ```python
129
+ from pathlib import Path
130
+
131
+ import docql
132
+ from docql import DocQL
133
+
134
+ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
135
+ data = Path("sales.csv").read_bytes()
136
+ try:
137
+ result = client.query_document(data, query="{ region total_sales }", filename="sales.csv")
138
+ print(result.page_count)
139
+ except docql.DocQLError as err:
140
+ if err.reason != docql.REASON_SPREADSHEET_TOO_LARGE:
141
+ raise
142
+ axis = next(k for k in err.metadata if k not in ("limit", "reason", "request_id"))
143
+ print(f"too large: {axis}={err.metadata[axis]} limit={err.metadata['limit']}")
144
+ ```
145
+ <!-- docql:spreadsheet:end -->
114
146
 
115
147
  ## Modes
116
148
 
@@ -186,7 +218,7 @@ two mean the request was not processed.
186
218
  ## Versioning
187
219
 
188
220
  The SDK follows [Semantic Versioning](https://semver.org/). While the major
189
- version is 0, a minor release may change the API; pin `docql>=0.2,<0.3` until
221
+ version is 0, a minor release may change the API; pin `docql>=0.3,<0.4` until
190
222
  1.0.
191
223
 
192
224
  ## Support
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "docql"
3
- version = "0.2.0"
3
+ version = "0.3.0"
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.3.0"
4
4
  description = "Python client for the DocQL document-extraction API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -13,6 +13,7 @@ from docql._constants import (
13
13
  REASON_CONCURRENCY_LIMIT_EXCEEDED,
14
14
  REASON_CORRUPTED_FILE,
15
15
  REASON_DOCUMENT_EXCEEDS_TIME_BUDGET,
16
+ REASON_DOCUMENT_TOO_COMPLEX,
16
17
  REASON_IDEMPOTENCY_IN_PROGRESS,
17
18
  REASON_IDEMPOTENCY_KEY_CONFLICT,
18
19
  REASON_INVALID_API_KEY,
@@ -26,6 +27,8 @@ from docql._constants import (
26
27
  REASON_QUEUE_FULL,
27
28
  REASON_RATE_LIMIT_EXCEEDED,
28
29
  REASON_SERVICE_OVERLOADED,
30
+ REASON_SPREADSHEET_TOO_LARGE,
31
+ REASON_TOO_MANY_PAGES,
29
32
  REASON_UNSUPPORTED_FILE_TYPE,
30
33
  REASON_UNSUPPORTED_MEDIA_TYPE,
31
34
  REASON_UPLOAD_TOO_LARGE,
@@ -65,6 +68,7 @@ __all__ = [
65
68
  "REASON_CONCURRENCY_LIMIT_EXCEEDED",
66
69
  "REASON_CORRUPTED_FILE",
67
70
  "REASON_DOCUMENT_EXCEEDS_TIME_BUDGET",
71
+ "REASON_DOCUMENT_TOO_COMPLEX",
68
72
  "REASON_IDEMPOTENCY_IN_PROGRESS",
69
73
  "REASON_IDEMPOTENCY_KEY_CONFLICT",
70
74
  "REASON_INVALID_API_KEY",
@@ -78,6 +82,8 @@ __all__ = [
78
82
  "REASON_QUEUE_FULL",
79
83
  "REASON_RATE_LIMIT_EXCEEDED",
80
84
  "REASON_SERVICE_OVERLOADED",
85
+ "REASON_SPREADSHEET_TOO_LARGE",
86
+ "REASON_TOO_MANY_PAGES",
81
87
  "REASON_UNSUPPORTED_FILE_TYPE",
82
88
  "REASON_UNSUPPORTED_MEDIA_TYPE",
83
89
  "REASON_UPLOAD_TOO_LARGE",
@@ -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
 
@@ -35,9 +35,10 @@ 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, 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
38
+ # Reason constants (D-05, D-09, D-12): exactly the 25 non-null reasons of the
39
+ # vendored contract kit — contract/sdk-cases.json (the sync stub and gateway
40
+ # errors), contract/job-cases.json (the job errors) and contract/sheet-cases.json
41
+ # (the kit v5 spreadsheet refusals). The engine's wider class table stays
41
42
  # reachable through the open ``reason: str``; adding constants later is
42
43
  # backward compatible, removing them is not.
43
44
  REASON_INVALID_API_KEY: Final[str] = "invalid_api_key"
@@ -62,6 +63,9 @@ REASON_QUEUE_FULL: Final[str] = "queue_full"
62
63
  REASON_IDEMPOTENCY_KEY_CONFLICT: Final[str] = "idempotency_key_conflict"
63
64
  REASON_IDEMPOTENCY_IN_PROGRESS: Final[str] = "idempotency_in_progress"
64
65
  REASON_JOB_INTERRUPTED: Final[str] = "job_interrupted"
66
+ REASON_DOCUMENT_TOO_COMPLEX: Final[str] = "document_too_complex"
67
+ REASON_SPREADSHEET_TOO_LARGE: Final[str] = "spreadsheet_too_large"
68
+ REASON_TOO_MANY_PAGES: Final[str] = "too_many_pages"
65
69
 
66
70
  # Async jobs (JSDK-01). Status values are open strings (D-09): an unknown status
67
71
  # from a future DocQL release is kept verbatim on Job.status, never an error.
@@ -35,6 +35,15 @@ class DocQLError(DocQLException):
35
35
  cancel error). ``idempotency_key`` is set on errors from
36
36
  ``submit_document`` so the caller can retry with the same key; it is a
37
37
  field only and never appears in :func:`str` or :func:`repr` (D-08).
38
+
39
+ ``metadata`` is the server's raw refusal metadata object, as a dict (D-06).
40
+ For ``spreadsheet_too_large`` it holds the measured value under its axis
41
+ key (``cells``, ``runes``, ``estimated_output_tokens`` or ``bytes``),
42
+ ``limit``, ``reason`` and ``request_id``; for ``too_many_pages`` it holds
43
+ ``pages`` and ``limit``. Every occurrence of the API key in its keys and
44
+ string values is replaced with ``***``. It is ``{}`` when the answer
45
+ carried no metadata object, and it never appears in :func:`str` or
46
+ :func:`repr`.
38
47
  """
39
48
 
40
49
  def __init__(
@@ -49,6 +58,7 @@ class DocQLError(DocQLException):
49
58
  body: str,
50
59
  job_id: str | None = None,
51
60
  idempotency_key: str | None = None,
61
+ metadata: dict[str, Any] | None = None,
52
62
  ) -> None:
53
63
  super().__init__()
54
64
  self.status = status
@@ -60,6 +70,7 @@ class DocQLError(DocQLException):
60
70
  self.body = body
61
71
  self.job_id = job_id
62
72
  self.idempotency_key = idempotency_key
73
+ self.metadata: dict[str, Any] = {} if metadata is None else metadata
63
74
 
64
75
  def __str__(self) -> str:
65
76
  if self.reason is not None:
@@ -106,6 +117,7 @@ class DocQLError(DocQLException):
106
117
  "body": self.body,
107
118
  "job_id": self.job_id,
108
119
  "idempotency_key": self.idempotency_key,
120
+ "metadata": self.metadata,
109
121
  },
110
122
  )
111
123
 
@@ -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
@@ -50,6 +50,22 @@ def _scrub_and_truncate(text: str, api_key: str) -> str:
50
50
  return text[:ERROR_BODY_KEEP_CHARS]
51
51
 
52
52
 
53
+ def _scrub_deep(value: Any, api_key: str) -> Any:
54
+ """Replace the key in every string inside ``value``, dict keys included (D-06).
55
+
56
+ Used for the error metadata, which a developer may log or store: a
57
+ reflecting server must never get the key into it. Numbers, booleans and
58
+ None pass through unchanged.
59
+ """
60
+ if isinstance(value, str):
61
+ return value.replace(api_key, "***") if api_key else value
62
+ if isinstance(value, dict):
63
+ return {_scrub_deep(k, api_key): _scrub_deep(v, api_key) for k, v in value.items()}
64
+ if isinstance(value, list):
65
+ return [_scrub_deep(item, api_key) for item in value]
66
+ return value
67
+
68
+
53
69
  def parse_retry_after(value: str | None, now: datetime | None = None) -> int | None:
54
70
  """``Retry-After`` as whole seconds, or None when absent/unparsable.
55
71
 
@@ -146,18 +162,25 @@ def decode_error(
146
162
 
147
163
  Classification is by status, never by body shape. An envelope is present
148
164
  only when the JSON body is a dict whose ``metadata`` is a dict with a str
149
- ``reason``. Neither the stored ``body`` nor ``message`` ever contains the
150
- API key, even when the server echoes it back.
165
+ ``reason``. Neither the stored ``body``, ``message`` nor ``metadata`` ever
166
+ contains the API key, even when the server echoes it back.
167
+
168
+ ``metadata`` is parsed from the whole bounded body, before the stored body
169
+ is cut, and is filled whenever the body carries a metadata object, for
170
+ every reason (D-06, D-12); otherwise the error keeps the default ``{}``.
151
171
  """
152
172
  reason: str | None = None
153
173
  message: str | None = None
154
174
  request_id: str | None = None
175
+ metadata_out: dict[str, Any] | None = None
155
176
  try:
156
177
  doc: Any = json.loads(body)
157
178
  except ValueError:
158
179
  doc = None
159
180
  if isinstance(doc, dict):
160
181
  metadata = doc.get("metadata")
182
+ if isinstance(metadata, dict):
183
+ metadata_out = _scrub_deep(metadata, api_key)
161
184
  if isinstance(metadata, dict) and isinstance(metadata.get("reason"), str):
162
185
  reason = metadata["reason"]
163
186
  error_info = doc.get("error_info")
@@ -182,4 +205,5 @@ def decode_error(
182
205
  retryable=status in (429, 503),
183
206
  message=message,
184
207
  body=_scrub_and_truncate(body.decode("utf-8", "replace"), api_key),
208
+ metadata=metadata_out,
185
209
  )
File without changes
File without changes
File without changes
File without changes