ap-client 0.8.1.dev0__py3-none-any.whl → 0.8.1.dev2__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.
ap_client/api.py CHANGED
@@ -5,7 +5,9 @@ import math
5
5
  import os
6
6
  import platform
7
7
  import re
8
+ import socket
8
9
  import sys
10
+ import threading
9
11
  import time
10
12
  import uuid
11
13
  from email.utils import parsedate_to_datetime
@@ -306,6 +308,266 @@ class PaginationProtocolError(RuntimeError):
306
308
  """The server stopped honoring a pagination protocol already in use."""
307
309
 
308
310
 
311
+ # Bounded canonical control-response helpers (CR 30865361 review P1 fixes).
312
+
313
+ # Upper bound for one canonical control response body (metadata JSONs are
314
+ # small; this only bounds memory and the byte-drip amortisation window).
315
+ _DEFAULT_CONTROL_BYTES = 8 * 1024 * 1024
316
+ _MAX_CONTROL_BYTES = 64 * 1024 * 1024
317
+
318
+
319
+ class CanonicalControlAPIError(APIError):
320
+ """Sanitized typed refusal for bounded canonical control requests.
321
+
322
+ Never holds a native response or raw cause; redirects are reported as
323
+ ``redirect`` only after allow_redirects=False already prevented any
324
+ credential from following the Location."""
325
+
326
+ def __init__(self, reason, *, status_code=None, biz_code=None):
327
+ self.reason = reason
328
+ detail = {"code": biz_code} if type(biz_code) is int else "canonical control request failed"
329
+ super().__init__(status_code, detail, None, None)
330
+
331
+
332
+ def _validate_control_bytes(limit: int) -> None:
333
+ if type(limit) is not int or not 1 <= limit <= _MAX_CONTROL_BYTES:
334
+ raise CanonicalControlAPIError("invalid_limit")
335
+
336
+
337
+ def _close_response_quietly(resp) -> None:
338
+ """Close a streamed response, tolerating already-closed objects."""
339
+ try:
340
+ resp.close()
341
+ except Exception:
342
+ pass
343
+
344
+
345
+ def _response_socket(resp) -> Optional[Any]:
346
+ """Best-effort extraction of the response's live socket (downgrade-safe).
347
+
348
+ urllib3 ``HTTPResponse._fp`` → http.client ``.fp`` (BufferedReader) →
349
+ ``.raw`` (SocketIO) → ``._sock``. Any missing/private-shift layer just
350
+ returns None — callers treat None as "no hard interruption available"
351
+ and rely on the in-loop deadline checks only.
352
+ """
353
+ try:
354
+ fp = getattr(resp, "raw", None)
355
+ fp = getattr(fp, "_fp", None)
356
+ if fp is None:
357
+ return None
358
+ buf = getattr(fp, "fp", None)
359
+ rawio = getattr(buf, "raw", None) if buf is not None else None
360
+ sock = getattr(rawio, "_sock", None) if rawio is not None else None
361
+ if sock is not None and callable(getattr(sock, "shutdown", None)):
362
+ return sock
363
+ except Exception:
364
+ pass
365
+ return None
366
+
367
+
368
+ class _DeadlineWatchdog:
369
+ """Force-interrupt a blocked streamed body read at the deadline.
370
+
371
+ ``requests``/``urllib3`` buffered reads block until the requested amount
372
+ (or EOF) arrives: with a Content-Length body dripping one byte per
373
+ interval, ``iter_content(chunk_size=64K)`` never returns mid-stream, so
374
+ in-loop deadline checks never run (review P1: 80ms budget exited at
375
+ ~300ms via drip). Same approach as the SDK transport's per-request
376
+ watchdog: an independent daemon timer shuts the live socket down at the
377
+ deadline; the blocked read then unblocks with a transport error, which
378
+ the callers classify against the actual clock.
379
+
380
+ Connection-reuse safety (review P2, two races):
381
+ 1. cancel/fire race: ``threading.Timer.cancel`` only prevents a callback
382
+ that has not *started*. Disarm happens under a lock in both
383
+ directions — the callback re-checks the flag — and ``__exit__``
384
+ joins the timer thread.
385
+ 2. release-before-exit race (the deeper one): urllib3 returns a
386
+ keep-alive connection to the pool as soon as ``iter_content`` drains
387
+ to EOF — BEFORE ``__exit__`` runs disarm/join. A later request can
388
+ borrow the connection in that window, and a stale timer firing then
389
+ kills an unrelated request. The callback therefore does NOT use the
390
+ socket captured at construction: at fire time it re-extracts the
391
+ socket from the response and shuts it down only when it is still the
392
+ SAME object — after EOF the response's file pointer is closed
393
+ (``_fp.fp = None``), extraction yields None, and the callback gives
394
+ up (the connection is no longer ours to interrupt). Construction
395
+ still keeps the socket purely as the identity reference.
396
+
397
+ No-socket fallback: if the layered private path is unavailable, the
398
+ watchdog stays inert and the in-loop checks remain the only guard.
399
+ """
400
+
401
+ def __init__(self, resp, deadline: Optional[float]):
402
+ self._resp = resp
403
+ self._sock = _response_socket(resp) if deadline is not None else None
404
+ self._deadline = deadline
405
+ self._timer: Optional[threading.Timer] = None
406
+ # Guards the disarmed flag AND serializes callback shutdown vs
407
+ # __exit__ disarm — the callback holds this lock while shutting the
408
+ # socket down, so once __exit__ completes the callback can never
409
+ # still be mid-shutdown.
410
+ self._lock = threading.Lock()
411
+ self._disarmed = False
412
+
413
+ def __enter__(self) -> "_DeadlineWatchdog":
414
+ sock = self._sock
415
+ if sock is not None:
416
+ delay = self._deadline - time.monotonic()
417
+ if delay > 0:
418
+ self._timer = threading.Timer(delay, self._fire)
419
+ self._timer.daemon = True
420
+ self._timer.start()
421
+ else:
422
+ self._fire()
423
+ return self
424
+
425
+ def __exit__(self, *exc_info) -> bool:
426
+ # Disarm BEFORE releasing anything: with the lock held, any in-flight
427
+ # callback has either finished its shutdown already (this read is
428
+ # being aborted anyway) or will re-check the flag and give up.
429
+ with self._lock:
430
+ self._disarmed = True
431
+ timer = self._timer
432
+ if timer is not None:
433
+ self._timer = None
434
+ timer.cancel()
435
+ # The timer thread may have passed its finished-event check and
436
+ # be running the callback right now (cancel is advisory there).
437
+ # Join it so the callback has fully exited — only then does the
438
+ # caller close the response and urllib3 release the connection
439
+ # back to the pool for reuse by later requests.
440
+ timer.join(timeout=5.0)
441
+ return False
442
+
443
+ def _fire(self) -> None:
444
+ # Runs on the timer thread (or synchronously from __enter__ when the
445
+ # budget is already spent). The lock + disarmed re-check closes the
446
+ # cancel race; the fresh re-extraction + identity check closes the
447
+ # release-before-exit race: after the stream drained to EOF urllib3
448
+ # has already returned the connection to the pool (the response's
449
+ # file pointer is closed), so the extraction yields None (or a
450
+ # different socket) and the stale fire gives up instead of killing
451
+ # whatever request borrowed the connection next.
452
+ with self._lock:
453
+ if self._disarmed:
454
+ return
455
+ current = _response_socket(self._resp)
456
+ if current is None or current is not self._sock:
457
+ return
458
+ try:
459
+ current.shutdown(socket.SHUT_RDWR)
460
+ except Exception:
461
+ pass
462
+
463
+
464
+ def _read_bounded_control_bytes(
465
+ resp, limit: int = _DEFAULT_CONTROL_BYTES, deadline: Optional[float] = None
466
+ ) -> bytes:
467
+ """Stream one bounded canonical control response via public requests APIs.
468
+
469
+ Content-Length pre-check plus streamed chunk reads keep memory at
470
+ O(cap+chunk) — a byte-drip response cannot grow unbounded. With a finite
471
+ ``deadline`` the read is ALSO hard-interruptible: a watchdog shuts the
472
+ response socket down at the deadline, so a slow drip cannot outlive the
473
+ budget even while ``iter_content`` is blocked mid-block (its buffered
474
+ read waits for the full chunk/EOF and would otherwise defer every
475
+ in-loop deadline check until the body finishes)."""
476
+ _validate_control_bytes(limit)
477
+ if deadline is not None and time.monotonic() >= deadline:
478
+ raise CanonicalControlAPIError("deadline")
479
+ length = resp.headers.get("Content-Length")
480
+ if isinstance(length, str) and length.isascii() and length.isdecimal():
481
+ digits, cap = length.lstrip("0") or "0", str(limit)
482
+ if len(digits) > len(cap) or (len(digits) == len(cap) and digits > cap):
483
+ raise CanonicalControlAPIError("response_limit", status_code=resp.status_code)
484
+ data = bytearray()
485
+ try:
486
+ with _DeadlineWatchdog(resp, deadline):
487
+ for block in resp.iter_content(chunk_size=min(65536, max(1, limit))):
488
+ if block:
489
+ if deadline is not None and time.monotonic() >= deadline:
490
+ # The stream is interrupted by the operation budget
491
+ # itself, not by body completion.
492
+ raise CanonicalControlAPIError("deadline")
493
+ if len(block) > limit - len(data):
494
+ raise CanonicalControlAPIError(
495
+ "response_limit", status_code=resp.status_code
496
+ )
497
+ data.extend(block)
498
+ except CanonicalControlAPIError:
499
+ raise
500
+ except Exception:
501
+ # Hard interruption (watchdog shutdown) or transport error: classify
502
+ # against the actual clock — a spent budget is a deadline refusal,
503
+ # never a raw exception or a partial-body success.
504
+ if deadline is not None and time.monotonic() >= deadline:
505
+ raise CanonicalControlAPIError("deadline") from None
506
+ raise
507
+ if deadline is not None and time.monotonic() >= deadline:
508
+ # Body completed but the budget is spent: refuse the late success.
509
+ raise CanonicalControlAPIError("deadline")
510
+ return bytes(data)
511
+
512
+
513
+ def _bounded_response_prefix(
514
+ resp, limit: int = _DEFAULT_CONTROL_BYTES, deadline: Optional[float] = None
515
+ ) -> bytes:
516
+ """Read one bounded first block of an error body for typed classification.
517
+
518
+ Oversized bodies contribute only this bounded prefix; their real status
519
+ stays reportable. With a finite ``deadline`` the same watchdog
520
+ hard-interrupts a blocked first-block read; a deadline reached mid-prefix
521
+ (or a transport interruption with the budget spent) is reported as
522
+ ``deadline`` — never a late ``http_error`` classification of an unread
523
+ body."""
524
+ try:
525
+ if deadline is not None and time.monotonic() >= deadline:
526
+ raise CanonicalControlAPIError("deadline")
527
+ with _DeadlineWatchdog(resp, deadline):
528
+ for block in resp.iter_content(chunk_size=min(65536, max(1, limit))):
529
+ if block:
530
+ if deadline is not None and time.monotonic() >= deadline:
531
+ raise CanonicalControlAPIError("deadline")
532
+ return bytes(block[:limit])
533
+ except CanonicalControlAPIError:
534
+ raise
535
+ except Exception:
536
+ if deadline is not None and time.monotonic() >= deadline:
537
+ # The read was interrupted (watchdog shutdown or read timeout)
538
+ # with the budget already spent: report the deadline, not a
539
+ # post-hoc classification of an unread error body.
540
+ raise CanonicalControlAPIError("deadline") from None
541
+ return b""
542
+ return b""
543
+
544
+
545
+ def _bounded_error_biz_code(prefix: bytes) -> Optional[int]:
546
+ """Typed numeric classification only; never message/data.
547
+
548
+ Decodes the dual envelope (bare ``{code,message,data}`` or FastAPI
549
+ ``{detail}``) from a bounded prefix so raw error text is never
550
+ forwarded; only the typed numeric family survives."""
551
+ parsed = None
552
+ if prefix:
553
+ try:
554
+ parsed = json.loads(prefix.decode("utf-8", errors="replace"))
555
+ except (ValueError, UnicodeError, RecursionError):
556
+ pass
557
+ detail = parsed.get("detail", parsed) if isinstance(parsed, dict) else None
558
+ if isinstance(detail, str):
559
+ decoded = None
560
+ try:
561
+ decoded = json.loads(detail)
562
+ except (ValueError, RecursionError):
563
+ pass
564
+ detail = decoded
565
+ code = detail.get("code") if isinstance(detail, dict) else None
566
+ if type(code) is bool or not isinstance(code, int):
567
+ code = None
568
+ return code
569
+
570
+
309
571
  def _ensure_next_token_honored(response: dict, *, next_token: Optional[str], endpoint: str) -> None:
310
572
  # An old server ignores the unknown next_token param and answers with its
311
573
  # default first page, so a `response.get("next_token")` loop would silently
@@ -441,8 +703,17 @@ class APIClient:
441
703
  timeout: TimeoutType = None,
442
704
  deadline: Optional[float] = None,
443
705
  _return_response: bool = False,
706
+ _single_attempt: bool = False,
707
+ _bounded: bool = False,
444
708
  ) -> Any:
445
- """Send an HTTP request with X-Request-ID and optional verbose logging."""
709
+ """Send through the normal authenticated HTTP channel.
710
+
711
+ ``_bounded`` (canonical adapter control requests) opts this single
712
+ request into the bounded canonical response projection: redirects
713
+ refused (auth headers never follow a cross-origin Location), a
714
+ finite timeout owns ONE deadline across retries, streamed bounded
715
+ reads (O(cap+chunk) memory), and late successes refused.
716
+ """
446
717
  self._require_cluster_config()
447
718
  return self._request_http(
448
719
  method,
@@ -452,6 +723,8 @@ class APIClient:
452
723
  timeout=timeout,
453
724
  deadline=deadline,
454
725
  _return_response=_return_response,
726
+ _single_attempt=_single_attempt,
727
+ _bounded=_bounded,
455
728
  )
456
729
 
457
730
  def _request_http(
@@ -464,6 +737,8 @@ class APIClient:
464
737
  timeout: TimeoutType = None,
465
738
  deadline: Optional[float] = None,
466
739
  _return_response: bool = False,
740
+ _single_attempt: bool = False,
741
+ _bounded: bool = False,
467
742
  ) -> Any:
468
743
  """One retry budget shared by cluster and central requests.
469
744
 
@@ -474,8 +749,20 @@ class APIClient:
474
749
  timeout = _default_timeout()
475
750
  else:
476
751
  timeout = _normalize_explicit_timeout(timeout)
752
+ # Bounded canonical projection (P1 fix): a finite per-request duration
753
+ # owns ONE deadline across this request's retries, never per attempt,
754
+ # so a slow byte-drip response cannot outlive its budget.
755
+ if (
756
+ _bounded
757
+ and deadline is None
758
+ and isinstance(timeout, (int, float))
759
+ and not isinstance(timeout, bool)
760
+ and math.isfinite(timeout)
761
+ and timeout >= 0
762
+ ):
763
+ deadline = time.monotonic() + timeout
477
764
  verbose = self.config.verbose
478
- max_attempts = max(1, self.config.http_max_attempts)
765
+ max_attempts = 1 if _single_attempt else max(1, self.config.http_max_attempts)
479
766
  max_wait = self.config.http_max_wait
480
767
  read_only = method.upper() in _RETRYABLE_METHODS
481
768
  recovery_deadline = None
@@ -506,16 +793,72 @@ class APIClient:
506
793
  max_attempts=max_attempts,
507
794
  )
508
795
  start = time.perf_counter()
796
+ resp = None
509
797
  try:
798
+ # A single-attempt mutation must also stop on redirects.
799
+ # Read the body separately so a truncated error still keeps its HTTP status.
800
+ # Bounded canonical requests always refuse redirects (auth
801
+ # headers must never follow a cross-origin Location) and read
802
+ # the body streamed-bounded instead of unbounded .content.
803
+ if _single_attempt or _bounded:
804
+ options = {"allow_redirects": False, "stream": True}
805
+ else:
806
+ options = {}
807
+ if _bounded:
808
+ # Watchdog pool isolation (review P2, final round): the
809
+ # deadline watchdog interrupts a blocked read by shutting
810
+ # the response's socket down. A keep-alive connection is
811
+ # returned to the pool as soon as iter_content drains to
812
+ # EOF — BEFORE the watchdog context exits — so any
813
+ # "check ownership then shutdown" sequence retains a
814
+ # check-then-act window in which the connection is
815
+ # borrowed by the NEXT request and killed by the stale
816
+ # fire. Closing the connection for this one request
817
+ # (``Connection: close``) removes the pooled connection
818
+ # from the equation entirely: the socket is never
819
+ # released back to the pool, a late fire hits an
820
+ # already-closed socket (OSError, swallowed), and later
821
+ # requests always get a fresh connection. Bounded control
822
+ # requests are short-lived metadata calls; the extra
823
+ # connection setup stays inside the same finite budget.
824
+ request_headers = {**headers, "Connection": "close"}
825
+ else:
826
+ request_headers = headers
510
827
  resp = self.session.request(
511
828
  method,
512
829
  url,
513
830
  params=params,
514
831
  json=json_body,
515
- headers=headers,
832
+ headers=request_headers,
516
833
  timeout=attempt_timeout,
834
+ **options,
517
835
  )
836
+ if _single_attempt and not _bounded:
837
+ # Legacy single-attempt semantics: read the body so a
838
+ # truncated error keeps its status. The bounded projection
839
+ # reads the body itself (streamed, bounded).
840
+ _ = resp.content
518
841
  except requests.RequestException as exc:
842
+ if _bounded:
843
+ # Bounded canonical projection: a network failure during a
844
+ # streamed bounded read is a typed refusal, not a retry of
845
+ # an unbounded request.
846
+ resp_is_error = resp is not None and not 200 <= resp.status_code < 300
847
+ if resp_is_error:
848
+ resp.close()
849
+ reason = (
850
+ "deadline"
851
+ if (deadline is not None and time.monotonic() >= deadline)
852
+ else "network"
853
+ )
854
+ raise CanonicalControlAPIError(reason) from None
855
+ if _single_attempt and resp is not None:
856
+ status = resp.status_code
857
+ resp.close()
858
+ if not 200 <= status < 300:
859
+ raise APIError(
860
+ status, "Incomplete HTTP error response", request_id, resp
861
+ ) from None
519
862
  if deadline is not None:
520
863
  _manifest_budget_remaining(deadline)
521
864
  duration_ms = (time.perf_counter() - start) * 1000
@@ -546,7 +889,80 @@ class APIClient:
546
889
  duration_ms = (time.perf_counter() - start) * 1000
547
890
  if verbose:
548
891
  self._log_response(method, url, request_id, resp, duration_ms)
549
- if not resp.ok:
892
+ if _bounded:
893
+ # Bounded canonical projection: sanitize every exit — refusals
894
+ # never carry a cause; redirects are refused before any auth
895
+ # header could follow the Location; the body is read streamed
896
+ # and bounded, and a late success (budget exhausted mid-read)
897
+ # is refused.
898
+ try:
899
+ if deadline is not None and time.monotonic() >= deadline:
900
+ raise CanonicalControlAPIError("deadline")
901
+ if _return_response:
902
+ raise CanonicalControlAPIError("invalid_request")
903
+ if 300 <= resp.status_code < 400:
904
+ # Request had allow_redirects=False: the redirect was
905
+ # NOT followed — the Location was never requested and
906
+ # auth headers were never sent there. Refuse.
907
+ raise CanonicalControlAPIError("redirect", status_code=resp.status_code)
908
+ if not 200 <= resp.status_code < 300:
909
+ if (
910
+ read_only
911
+ and attempt < max_attempts
912
+ and _is_retryable_status(resp.status_code)
913
+ ):
914
+ delay = _retry_delay(attempt, resp, max_wait=max_wait)
915
+ if not math.isfinite(delay):
916
+ delay = _retry_delay(attempt)
917
+ if deadline is not None:
918
+ remaining = deadline - time.monotonic()
919
+ if remaining <= 0:
920
+ raise CanonicalControlAPIError("deadline")
921
+ delay = min(delay, remaining)
922
+ resp.close()
923
+ if deadline is not None:
924
+ _deadline_sleep(delay, deadline)
925
+ else:
926
+ time.sleep(delay)
927
+ continue
928
+ if deadline is not None and time.monotonic() >= deadline:
929
+ # The error body would be classified only after a
930
+ # bounded read that the budget can no longer fund:
931
+ # report the deadline, never a late http_error.
932
+ raise CanonicalControlAPIError("deadline")
933
+ prefix = _bounded_response_prefix(
934
+ resp, _DEFAULT_CONTROL_BYTES, deadline=deadline
935
+ )
936
+ code = _bounded_error_biz_code(prefix)
937
+ raise CanonicalControlAPIError(
938
+ "http_error", status_code=resp.status_code, biz_code=code
939
+ )
940
+ data = _read_bounded_control_bytes(
941
+ resp, _DEFAULT_CONTROL_BYTES, deadline=deadline
942
+ )
943
+ if not data:
944
+ resp.close()
945
+ return None
946
+ refusal = None
947
+ try:
948
+ parsed = data.decode("utf-8", errors="strict")
949
+ except UnicodeError:
950
+ refusal = "invalid_utf8"
951
+ if refusal is None:
952
+ try:
953
+ result = json.loads(parsed)
954
+ except (ValueError, RecursionError):
955
+ refusal = "invalid_json"
956
+ if refusal is not None:
957
+ raise CanonicalControlAPIError(refusal, status_code=resp.status_code)
958
+ if deadline is not None and time.monotonic() >= deadline:
959
+ # Refuse a late success; the budget is already spent.
960
+ raise CanonicalControlAPIError("deadline")
961
+ resp.close()
962
+ return result
963
+ finally:
964
+ _close_response_quietly(resp)
965
+ if not resp.ok or (_single_attempt and not 200 <= resp.status_code < 300):
550
966
  pop_rejected = _is_pop_rejection(resp)
551
967
  if pop_rejected and recovery_deadline is None:
552
968
  recovery_deadline = time.monotonic() + self.config.http_retry_window
@@ -611,6 +1027,11 @@ class APIClient:
611
1027
  raise APIError(resp.status_code, detail, request_id, resp) from exc
612
1028
  raise RuntimeError("unreachable retry state")
613
1029
 
1030
+ def _max_attempts_for(self, method: str) -> int:
1031
+ if method.upper() not in _RETRYABLE_METHODS:
1032
+ return 1
1033
+ return max(1, self.config.http_max_attempts)
1034
+
614
1035
  def _require_cluster_config(self) -> None:
615
1036
  if has_cluster_header(self.config.headers):
616
1037
  return
@@ -1220,6 +1641,8 @@ class APIClient:
1220
1641
  transparency: Optional[Literal["whitebox", "blackbox"]] = None,
1221
1642
  idempotency_key: Optional[str] = None,
1222
1643
  group_concurrency_policy: Optional[dict] = None,
1644
+ visibility: Optional[Literal["queue", "private"]] = None,
1645
+ metrics_retry_policy: Optional[dict] = None,
1223
1646
  ) -> dict:
1224
1647
  """Create a group with optional scheduling defaults for its Jobs.
1225
1648
 
@@ -1227,6 +1650,8 @@ class APIClient:
1227
1650
  """
1228
1651
  if priority is not None and priority not in {"high", "medium"}:
1229
1652
  raise ValueError("priority must be one of high/medium")
1653
+ if visibility is not None and visibility not in {"queue", "private"}:
1654
+ raise ValueError("visibility must be queue or private")
1230
1655
  if transparency is not None and transparency not in {"whitebox", "blackbox"}:
1231
1656
  raise ValueError("transparency must be whitebox or blackbox")
1232
1657
  if transparency == "blackbox" and not idempotency_key:
@@ -1239,6 +1664,10 @@ class APIClient:
1239
1664
  raise ValueError("ak_ids entries must be nonempty strings")
1240
1665
  references = list(dict.fromkeys(references))
1241
1666
  body: dict = {}
1667
+ if visibility is not None:
1668
+ body["visibility"] = visibility
1669
+ if metrics_retry_policy is not None:
1670
+ body["metrics_retry_policy"] = metrics_retry_policy
1242
1671
  if transparency is not None:
1243
1672
  body["transparency"] = transparency
1244
1673
  if idempotency_key is not None:
@@ -1367,10 +1796,13 @@ class APIClient:
1367
1796
  instance_range: Optional[str] = None,
1368
1797
  profile: Optional[str] = None,
1369
1798
  transparency: Optional[Literal["whitebox", "blackbox"]] = None,
1799
+ visibility: Optional[Literal["queue", "private"]] = None,
1800
+ metrics_retry_policy: Optional[dict] = None,
1370
1801
  ) -> dict:
1371
1802
  """Create a job."""
1372
1803
  body = self.build_create_job_body(
1373
1804
  transparency=transparency,
1805
+ visibility=visibility,
1374
1806
  template=template,
1375
1807
  params=params,
1376
1808
  params_list=params_list,
@@ -1391,6 +1823,7 @@ class APIClient:
1391
1823
  runner_options=runner_options,
1392
1824
  idempotency_key=idempotency_key,
1393
1825
  max_failure_retries=max_failure_retries,
1826
+ metrics_retry_policy=metrics_retry_policy,
1394
1827
  priority=priority,
1395
1828
  priority_weight=priority_weight,
1396
1829
  resource_mode=resource_mode,
@@ -1483,8 +1916,12 @@ class APIClient:
1483
1916
  instance_range: Optional[str] = None,
1484
1917
  profile: Optional[str] = None,
1485
1918
  transparency: Optional[Literal["whitebox", "blackbox"]] = None,
1919
+ visibility: Optional[Literal["queue", "private"]] = None,
1920
+ metrics_retry_policy: Optional[dict] = None,
1486
1921
  ) -> dict:
1487
1922
  """Build the /jobs request body for job creation."""
1923
+ if visibility is not None and visibility not in {"queue", "private"}:
1924
+ raise ValueError("visibility must be queue or private")
1488
1925
  if transparency is not None and transparency not in {"whitebox", "blackbox"}:
1489
1926
  raise ValueError("transparency must be whitebox or blackbox")
1490
1927
  if profile is not None and (profile_id is not None or profile_version is not None):
@@ -1554,6 +1991,8 @@ class APIClient:
1554
1991
  body["runner_options"] = runner_options
1555
1992
  if idempotency_key is not None:
1556
1993
  body["idempotency_key"] = idempotency_key
1994
+ if metrics_retry_policy is not None:
1995
+ body["metrics_retry_policy"] = metrics_retry_policy
1557
1996
  if max_failure_retries:
1558
1997
  body["max_failure_retries"] = max_failure_retries
1559
1998
 
@@ -1611,6 +2050,8 @@ class APIClient:
1611
2050
  if experiment is not None:
1612
2051
  body["experiment"] = experiment
1613
2052
 
2053
+ if visibility is not None:
2054
+ body["visibility"] = visibility
1614
2055
  if transparency is not None:
1615
2056
  body["transparency"] = transparency
1616
2057
  return body
@@ -1679,7 +2120,7 @@ class APIClient:
1679
2120
  upstream_job_id: Optional[str] = None,
1680
2121
  next_token: Optional[str] = None,
1681
2122
  pagination: Optional[str] = None,
1682
- include_total: bool = True,
2123
+ include_total: bool = False,
1683
2124
  ak_id: Optional[str] = None,
1684
2125
  ) -> dict:
1685
2126
  """List jobs."""
@@ -1745,8 +2186,7 @@ class APIClient:
1745
2186
  params["next_token"] = next_token
1746
2187
  if pagination:
1747
2188
  params["pagination"] = pagination
1748
- if not include_total:
1749
- params["include_total"] = False
2189
+ params["include_total"] = include_total
1750
2190
  response = self._get("/jobs", params=params)
1751
2191
  _ensure_next_token_honored(response, next_token=next_token, endpoint="/jobs")
1752
2192
  return response
@@ -1928,10 +2368,11 @@ class APIClient:
1928
2368
  upstream_platform: Optional[str] = None,
1929
2369
  upstream_job_id: Optional[str] = None,
1930
2370
  ak_id: Optional[str] = None,
2371
+ include_total: bool = False,
1931
2372
  ) -> dict:
1932
- """List groups."""
2373
+ """List groups. Exact totals are opt-in and subject to the server query budget."""
1933
2374
  validate_ak_id(ak_id)
1934
- params: dict = {"skip": skip, "limit": limit}
2375
+ params: dict = {"skip": skip, "limit": limit, "include_total": include_total}
1935
2376
  if ak_id is not None:
1936
2377
  params["ak_id"] = ak_id
1937
2378
  if name is not None:
@@ -1993,7 +2434,7 @@ class APIClient:
1993
2434
  upstream_job_id: Optional[str] = None,
1994
2435
  next_token: Optional[str] = None,
1995
2436
  pagination: Optional[str] = None,
1996
- include_total: bool = True,
2437
+ include_total: bool = False,
1997
2438
  ) -> dict:
1998
2439
  """List jobs in a group."""
1999
2440
  params: dict = {"skip": skip, "limit": limit}
@@ -2021,8 +2462,7 @@ class APIClient:
2021
2462
  params["next_token"] = next_token
2022
2463
  if pagination:
2023
2464
  params["pagination"] = pagination
2024
- if not include_total:
2025
- params["include_total"] = False
2465
+ params["include_total"] = include_total
2026
2466
  endpoint = f"/groups/{quote(group_id)}/jobs"
2027
2467
  response = self._get(endpoint, params=params)
2028
2468
  _ensure_next_token_honored(response, next_token=next_token, endpoint=endpoint)
@@ -3654,12 +4094,34 @@ def _redact_url_query_secrets(value: str) -> str:
3654
4094
 
3655
4095
 
3656
4096
  def _response_error_detail(resp: requests.Response) -> Any:
4097
+ """错误响应体 → detail(兼容两代服务端错误形态,G2 修复)。
4098
+
4099
+ * FastAPI ``{"detail": <str|dict>}``:保持旧语义——detail 键优先
4100
+ (dict 时**整个内层 dict** 作为 detail 返回,不只是取 message);
4101
+ * Go/Gin 裸信封 ``{code, message, data}``(apiserver
4102
+ ``pkg/api/response/response.go writeErrorData``):**整个响应 dict**
4103
+ 作为 detail 返回——9404x 数字 code 与 ``data``(error_code/
4104
+ apply_url 等结构化负载)不再被降级成 message 字符串丢失;
4105
+ * 旧 ``{"message": ...}``(无 detail)形态:保持旧语义取 message
4106
+ 字符串(detail/message 缺省回退 resp.text)。
4107
+
4108
+ detail 消费方(如 shared_adapter._decode_api_error)按"dict 即结构化
4109
+ 错误体"自行解 code/data;str detail 继续支持(旧展示路径不变)。
4110
+ """
3657
4111
  try:
3658
4112
  err_data = resp.json()
3659
4113
  except Exception:
3660
4114
  return resp.text
3661
4115
  if isinstance(err_data, dict):
3662
- return err_data.get("detail", err_data.get("message", resp.text))
4116
+ if "detail" in err_data:
4117
+ inner = err_data["detail"]
4118
+ if isinstance(inner, dict):
4119
+ return inner # FastAPI detail=dict:内层即结构化错误体
4120
+ return inner # detail=str:旧语义
4121
+ if "code" in err_data:
4122
+ # Go 裸信封 {code, message, data}:保留完整结构化错误体
4123
+ return err_data
4124
+ return err_data.get("message", resp.text)
3663
4125
  return err_data
3664
4126
 
3665
4127