ap-client 0.7.1.dev4__py3-none-any.whl → 0.8.0.dev0__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/__init__.py CHANGED
@@ -9,7 +9,7 @@ from .exporter import ExportSummary
9
9
  try:
10
10
  __version__ = version("ap-client")
11
11
  except PackageNotFoundError:
12
- __version__ = "0.7.1.dev4"
12
+ __version__ = "0+unknown"
13
13
 
14
14
  __all__ = [
15
15
  "APIClient",
ap_client/api.py CHANGED
@@ -6,7 +6,6 @@ import os
6
6
  import platform
7
7
  import re
8
8
  import sys
9
- import threading
10
9
  import time
11
10
  import uuid
12
11
  from email.utils import parsedate_to_datetime
@@ -288,14 +287,6 @@ class APIError(Exception):
288
287
  return f"API Error {self.status_code}: {self.detail} (request_id={self.request_id})"
289
288
 
290
289
 
291
- class CanonicalControlAPIError(APIError):
292
- """Operation-only sanitized error; never holds a native response or cause."""
293
- def __init__(self, reason, *, status_code=None, biz_code=None):
294
- self.reason = reason
295
- detail = {"code": biz_code} if type(biz_code) is int else "canonical control request failed"
296
- super().__init__(status_code, detail, None, None)
297
-
298
-
299
290
  class PaginationProtocolError(RuntimeError):
300
291
  """The server stopped honoring a pagination protocol already in use."""
301
292
 
@@ -380,8 +371,6 @@ class APIClient:
380
371
 
381
372
  def __init__(self, config: Config):
382
373
  self.config = config
383
- self._control_channel = None
384
- self._control_channel_lock = threading.Lock()
385
374
  self.session = requests.Session()
386
375
  headers = dict(config.headers)
387
376
  user_agent = _build_user_agent(headers.get("User-Agent"))
@@ -437,13 +426,8 @@ class APIClient:
437
426
  timeout: TimeoutType = None,
438
427
  deadline: Optional[float] = None,
439
428
  _return_response: bool = False,
440
- max_response_bytes: Optional[int] = None,
441
429
  ) -> Any:
442
- """Send through the normal channel unless bounded control is opted in."""
443
- if max_response_bytes is not None:
444
- return self._request_control_json(method, path, params=params,
445
- json_body=json_body, timeout=timeout, deadline=deadline,
446
- max_response_bytes=max_response_bytes, return_response=_return_response)
430
+ """Send an HTTP request with X-Request-ID and optional verbose logging."""
447
431
  self._require_cluster_config()
448
432
  return self._request_http(
449
433
  method,
@@ -612,130 +596,6 @@ class APIClient:
612
596
  raise APIError(resp.status_code, detail, request_id, resp) from exc
613
597
  raise RuntimeError("unreachable retry state")
614
598
 
615
- def _request_control_json(self, method, path, *, params, json_body, timeout,
616
- deadline, max_response_bytes, return_response):
617
- from .control_http import (ControlHTTPError, OwnedControlChannel, validate_limit,
618
- _check_deadline)
619
-
620
- if return_response:
621
- raise CanonicalControlAPIError("invalid_request")
622
- self._require_cluster_config()
623
- failure = None
624
- try:
625
- validate_limit(max_response_bytes)
626
- _check_deadline(deadline)
627
- if isinstance(timeout, bool):
628
- raise ControlHTTPError('invalid_deadline')
629
- if isinstance(timeout, (int, float)):
630
- if not math.isfinite(timeout) or timeout < 0:
631
- raise ControlHTTPError('invalid_deadline')
632
- if deadline is None:
633
- # A finite SDK per-request remaining duration owns one
634
- # deadline across this request's retries, never per attempt.
635
- deadline = time.monotonic() + timeout
636
- _check_deadline(deadline)
637
- except ControlHTTPError as exc:
638
- failure = CanonicalControlAPIError(exc.reason)
639
- if failure is not None:
640
- raise failure
641
- with self._control_channel_lock:
642
- if self._control_channel is None:
643
- self._control_channel = OwnedControlChannel(self.session)
644
- channel = self._control_channel
645
- timeout = _default_timeout() if timeout is None else _normalize_explicit_timeout(timeout)
646
- url = self._url(path)
647
- attempts = self._max_attempts_for(method)
648
- for attempt in range(1, attempts + 1):
649
- if deadline is not None and time.monotonic() >= deadline:
650
- raise CanonicalControlAPIError("deadline")
651
- failure = response = None
652
- try:
653
- response = channel.request(method, url, headers={"X-Request-ID": str(uuid.uuid4())},
654
- params=params, json_body=json_body,
655
- timeout=_deadline_timeout(timeout, deadline), deadline=deadline,
656
- max_response_bytes=max_response_bytes)
657
- except ControlHTTPError as exc:
658
- failure = CanonicalControlAPIError(exc.reason, status_code=exc.status)
659
- retryable = exc.retryable or (exc.status is not None and
660
- _is_retryable_status(exc.status) and exc.reason != "redirect")
661
- except APIError:
662
- failure = CanonicalControlAPIError("deadline")
663
- retryable = False
664
- if failure is not None:
665
- if attempt < attempts and retryable:
666
- delay = _retry_delay(attempt)
667
- if deadline is not None:
668
- remaining = deadline - time.monotonic()
669
- if remaining <= 0:
670
- raise CanonicalControlAPIError("deadline")
671
- delay = min(delay, remaining)
672
- time.sleep(delay)
673
- continue
674
- raise failure
675
- if deadline is not None and time.monotonic() >= deadline:
676
- raise CanonicalControlAPIError("deadline")
677
- if not 200 <= response.status_code < 300:
678
- if attempt < attempts and _is_retryable_status(response.status_code):
679
- try:
680
- delay = _retry_delay(attempt, response)
681
- except (ValueError, TypeError, OverflowError, OSError):
682
- delay = _retry_delay(attempt)
683
- if not math.isfinite(delay):
684
- delay = _retry_delay(attempt)
685
- if deadline is not None:
686
- remaining = deadline - time.monotonic()
687
- if remaining <= 0:
688
- raise CanonicalControlAPIError("deadline")
689
- delay = min(delay, remaining)
690
- time.sleep(delay)
691
- continue
692
- parsed = None
693
- if response.refusal is None:
694
- try:
695
- parsed = json.loads(response.content.decode("utf-8", errors="replace"))
696
- except (ValueError, UnicodeError, RecursionError):
697
- pass
698
- # Preserve both existing API envelope shapes while retaining
699
- # only the typed numeric classification, never message/data.
700
- detail = parsed.get("detail", parsed) if isinstance(parsed, dict) else None
701
- if isinstance(detail, str):
702
- decoded = None
703
- try:
704
- decoded = json.loads(detail)
705
- except (ValueError, RecursionError):
706
- pass
707
- detail = decoded
708
- code = detail.get("code") if isinstance(detail, dict) else None
709
- raise CanonicalControlAPIError("http_error", status_code=response.status_code,
710
- biz_code=code if type(code) is int else None)
711
- if not response.content:
712
- return None
713
- text = None
714
- try:
715
- text = response.content.decode("utf-8", errors="strict")
716
- except UnicodeError:
717
- pass
718
- if text is None:
719
- raise CanonicalControlAPIError("invalid_utf8", status_code=response.status_code)
720
- parsed = None
721
- valid_json = False
722
- try:
723
- parsed = json.loads(text)
724
- valid_json = True
725
- except (ValueError, RecursionError):
726
- pass
727
- if not valid_json:
728
- raise CanonicalControlAPIError("invalid_json", status_code=response.status_code)
729
- if deadline is not None and time.monotonic() >= deadline:
730
- raise CanonicalControlAPIError("deadline")
731
- return parsed
732
- raise CanonicalControlAPIError("network")
733
-
734
- def _max_attempts_for(self, method: str) -> int:
735
- if method.upper() not in _RETRYABLE_METHODS:
736
- return 1
737
- return max(1, self.config.http_max_attempts)
738
-
739
599
  def _require_cluster_config(self) -> None:
740
600
  if has_cluster_header(self.config.headers):
741
601
  return
@@ -3779,34 +3639,12 @@ def _redact_url_query_secrets(value: str) -> str:
3779
3639
 
3780
3640
 
3781
3641
  def _response_error_detail(resp: requests.Response) -> Any:
3782
- """错误响应体 → detail(兼容两代服务端错误形态,G2 修复)。
3783
-
3784
- * FastAPI ``{"detail": <str|dict>}``:保持旧语义——detail 键优先
3785
- (dict 时**整个内层 dict** 作为 detail 返回,不只是取 message);
3786
- * Go/Gin 裸信封 ``{code, message, data}``(apiserver
3787
- ``pkg/api/response/response.go writeErrorData``):**整个响应 dict**
3788
- 作为 detail 返回——9404x 数字 code 与 ``data``(error_code/
3789
- apply_url 等结构化负载)不再被降级成 message 字符串丢失;
3790
- * 旧 ``{"message": ...}``(无 detail)形态:保持旧语义取 message
3791
- 字符串(detail/message 缺省回退 resp.text)。
3792
-
3793
- detail 消费方(如 shared_adapter._decode_api_error)按"dict 即结构化
3794
- 错误体"自行解 code/data;str detail 继续支持(旧展示路径不变)。
3795
- """
3796
3642
  try:
3797
3643
  err_data = resp.json()
3798
3644
  except Exception:
3799
3645
  return resp.text
3800
3646
  if isinstance(err_data, dict):
3801
- if "detail" in err_data:
3802
- inner = err_data["detail"]
3803
- if isinstance(inner, dict):
3804
- return inner # FastAPI detail=dict:内层即结构化错误体
3805
- return inner # detail=str:旧语义
3806
- if "code" in err_data:
3807
- # Go 裸信封 {code, message, data}:保留完整结构化错误体
3808
- return err_data
3809
- return err_data.get("message", resp.text)
3647
+ return err_data.get("detail", err_data.get("message", resp.text))
3810
3648
  return err_data
3811
3649
 
3812
3650
 
ap_client/cli.py CHANGED
@@ -37,6 +37,7 @@ from ap_client.managed_ak import (
37
37
  from ap_client.profile_commands import profile_app
38
38
  from ap_client.submission_metadata import (
39
39
  assess_submission_metadata,
40
+ emit_metadata_completion_on_failure,
40
41
  has_submitted_jobs,
41
42
  render_metadata_completion,
42
43
  warn_submission_metadata,
@@ -302,19 +303,31 @@ def _parse_json_object(
302
303
  # literal dot and never splits a dot-path.
303
304
  _DOT_PATH_ESCAPE = "\\."
304
305
 
305
-
306
- def _split_dot_path(key: str) -> tuple[Optional[str], str]:
307
- r"""Resolve ``\.`` escapes in *key* and split it at its first bare ``.``.
308
-
309
- Returns ``(parent, sub_key)`` for a dot-path and ``(None, key)`` when the
310
- key has no bare dot (a flat key). Escaped dots become literal dots in the
311
- yielded halves, so the backslash never reaches the request body; any other
312
- backslash (``a\b``) is preserved verbatim. An empty parent or sub-key is
313
- returned as-is so the caller can reject it.
306
+ # Hard cap on how many segments one dot-path may expand into. A segment costs
307
+ # about two bytes of input (``a.``), so an uncapped expansion let a ~2 KB
308
+ # ``-p/--params`` build a 1100-level tree (the baseline split at the first bare
309
+ # dot only and never built one, so this cap is a new bound that also rejects
310
+ # 65+ segment keys the baseline used to send as one literal sub-key); the
311
+ # server's ``deep_merge_params`` recurses once per level (verified: 64 levels
312
+ # fine, 1100 levels RecursionError) and the pretty-printed request body grows
313
+ # quadratically (~50 MB at 5000 levels). Only paths produced by the top-level
314
+ # dot-path syntax are counted: a flat key (no bare dot) and a native object
315
+ # value keep their shape.
316
+ _MAX_DOT_PATH_SEGMENTS = 64
317
+
318
+
319
+ def _split_dot_path(key: str) -> list[str]:
320
+ r"""Resolve ``\.`` escapes in *key* and split it on every bare ``.``.
321
+
322
+ Returns the segments in order, so ``a.b.c`` yields ``["a", "b", "c"]`` and a
323
+ key without a bare dot yields a single-element list (a flat key). Escaped
324
+ dots become literal dots inside their segment, so the backslash never reaches
325
+ the request body and the decoded dot never splits again; any other backslash
326
+ (``a\b``) is preserved verbatim. An empty segment (leading, trailing or
327
+ consecutive bare dot) is returned as-is so the caller can reject it.
314
328
  """
315
- parent: list[str] = []
316
- sub_key: list[str] = []
317
- current = parent
329
+ segments: list[str] = []
330
+ current: list[str] = []
318
331
  index = 0
319
332
  while index < len(key):
320
333
  if key.startswith(_DOT_PATH_ESCAPE, index):
@@ -323,76 +336,210 @@ def _split_dot_path(key: str) -> tuple[Optional[str], str]:
323
336
  continue
324
337
  char = key[index]
325
338
  index += 1
326
- if char == "." and current is parent:
327
- current = sub_key
339
+ if char == ".":
340
+ segments.append("".join(current))
341
+ current = []
328
342
  continue
329
343
  current.append(char)
330
- if current is parent:
331
- return None, "".join(parent)
332
- return "".join(parent), "".join(sub_key)
344
+ segments.append("".join(current))
345
+ return segments
346
+
347
+
348
+ class _DotPathLeaf:
349
+ """Final value of one ``-p/--params`` dot-path, held by the prefix trie."""
350
+
351
+ __slots__ = ("key", "value")
352
+
353
+ def __init__(self, value: Any, key: str) -> None:
354
+ self.value = value
355
+ self.key = key
356
+
357
+
358
+ def _first_dot_path_key(trie: dict[str, Any]) -> str:
359
+ """Return the raw key of any leaf below *trie* (conflict messages only)."""
360
+ node = trie
361
+ while True:
362
+ child = next(iter(node.values()), None)
363
+ if isinstance(child, _DotPathLeaf):
364
+ return child.key
365
+ if not isinstance(child, dict): # pragma: no cover - 构造器保证子树非空
366
+ return "<unknown>"
367
+ node = child
368
+
369
+
370
+ def _build_dot_path_trie(dotted: list[tuple[list[str], Any, str]]) -> dict[str, Any]:
371
+ """Lay dot-path entries out in a prefix trie, rejecting ancestor/descendant pairs.
372
+
373
+ Insertion visits every segment exactly once, so the whole build is
374
+ O(total segments) and independent of how many keys share a prefix - the
375
+ earlier implementation compared every pair of keys and sorted them first,
376
+ which is quadratic on wide inputs. A node is either a ``dict`` of children
377
+ or a :class:`_DotPathLeaf`, so ``{"a.b": 1, "a.b.c": 2}`` (one entry wants
378
+ ``a.b`` to be a value, the other wants it to be an object) is caught on the
379
+ way in whichever entry comes first, with the same message both times. Only
380
+ key paths are echoed: params values are frequently credentials.
381
+ """
382
+ root: dict[str, Any] = {}
383
+ for segments, value, key in dotted:
384
+ node = root
385
+ last = len(segments) - 1
386
+ for depth, segment in enumerate(segments):
387
+ existing = node.get(segment)
388
+ if depth == last:
389
+ if isinstance(existing, dict):
390
+ _emit_error(
391
+ f"conflicting -p/--params keys {key!r} and "
392
+ f"{_first_dot_path_key(existing)!r}: a dot-path cannot set "
393
+ "a value and a nested path below it"
394
+ )
395
+ raise typer.Exit(1)
396
+ node[segment] = _DotPathLeaf(value, key)
397
+ break
398
+ if isinstance(existing, _DotPathLeaf):
399
+ _emit_error(
400
+ f"conflicting -p/--params keys {existing.key!r} and {key!r}: "
401
+ "a dot-path cannot set a value and a nested path below it"
402
+ )
403
+ raise typer.Exit(1)
404
+ if existing is None:
405
+ existing = {}
406
+ node[segment] = existing
407
+ node = existing
408
+ return root
409
+
410
+
411
+ def _copy_params_dict(source: dict[str, Any]) -> dict[str, Any]:
412
+ """Shallow-copy one params object so a dot-path write never reaches the caller."""
413
+ return dict(source)
414
+
415
+
416
+ def _merge_dot_path_trie(target: dict[str, Any], trie: dict[str, Any], owned: set[int]) -> None:
417
+ """Write *trie* into *target*, copying each modified path node at most once.
418
+
419
+ *owned* holds the ``id()`` of every object this function may write into (the
420
+ result dict plus each copy it made), so an intermediate object that came from
421
+ the caller is shallow-copied before it is descended into. The copy count is
422
+ bounded by modified path nodes, not by caller objects: sibling keys below one
423
+ node share that node's single copy, while one caller object reached through
424
+ distinct logical paths is copied once per path on purpose, so a write under
425
+ one path never shows up under another. (The earlier per-key copy re-copied a
426
+ growing parent for every sibling key: quadratic work and quadratic allocation
427
+ on wide inputs.) Total merge work is O(total segments + entries of every
428
+ copied dict), because a shallow copy costs the entry count of its source. A
429
+ non-object intermediate is a hard conflict that names the parent path only.
430
+
431
+ ``id()`` is safe as an ownership marker only because of an invariant this
432
+ function maintains, and every write below is ordered to uphold it: an object
433
+ is stored into the tree (``node[segment] = ...``) before its id is added to
434
+ *owned*, so no id in *owned* ever refers to an object that only a local
435
+ variable still references. That keeps the object alive until the call returns
436
+ and makes id reuse by a fresh object impossible. Any refactor that reorders
437
+ those two statements, or drops the store, must switch to an explicit marker
438
+ instead.
439
+ """
440
+ stack: list[tuple[dict[str, Any], dict[str, Any], str]] = [(target, trie, "")]
441
+ while stack:
442
+ node, trie_node, prefix = stack.pop()
443
+ for segment, child in trie_node.items():
444
+ if isinstance(child, _DotPathLeaf):
445
+ node[segment] = child.value
446
+ continue
447
+ # Display only: a segment can hold a literal dot decoded from ``\.``, so
448
+ # re-escape it to keep the reported path writable as a raw key.
449
+ display = segment.replace(".", _DOT_PATH_ESCAPE)
450
+ parent_path = f"{prefix}.{display}" if prefix else display
451
+ if segment not in node:
452
+ created: dict[str, Any] = {}
453
+ node[segment] = created
454
+ owned.add(id(created))
455
+ stack.append((created, child, parent_path))
456
+ continue
457
+ existing = node[segment]
458
+ if not isinstance(existing, dict):
459
+ _emit_error(
460
+ f"conflicting -p/--params parent {parent_path!r}: "
461
+ "set both as a non-object value and as a dot-path parent"
462
+ )
463
+ raise typer.Exit(1)
464
+ if id(existing) not in owned:
465
+ existing = _copy_params_dict(existing)
466
+ node[segment] = existing
467
+ owned.add(id(existing))
468
+ stack.append((existing, child, parent_path))
333
469
 
334
470
 
335
471
  def _expand_params_dot_paths(params: dict) -> dict:
336
- r"""Expand one level of ``parent.subkey`` keys inside a ``-p/--params`` object.
472
+ r"""Expand ``parent.subkey`` keys into arbitrarily deep nested objects.
337
473
 
338
474
  ``{"proxy_envs.HTTPS_PROXY": "http://p"}`` becomes
339
- ``{"proxy_envs": {"HTTPS_PROXY": "http://p"}}`` so a single dict param can be
340
- patched without hand-escaping the whole embedded JSON string. Only the first
341
- bare ``.`` splits, so ``a.b.c`` yields ``{"a": {"b.c": value}}``; keys without
342
- a bare dot keep their place and their value, and values keep their JSON type
343
- (``null`` included - the server turns a ``null`` sub-key into a deletion).
475
+ ``{"proxy_envs": {"HTTPS_PROXY": "http://p"}}`` and ``{"a.b.c": 1}`` becomes
476
+ ``{"a": {"b": {"c": 1}}}``, so a nested dict param can be patched one leaf at
477
+ a time without hand-escaping a whole embedded JSON string. Keys without a
478
+ bare dot keep their place and their value, and values keep their JSON type
479
+ (``null`` included - the server turns a ``null`` leaf into a deletion). Only
480
+ top-level ``-p/--params`` keys are interpreted: keys inside a supplied value
481
+ are never expanded further.
344
482
 
345
483
  A backslash-escaped dot (``\.``) is a literal dot and never splits, and the
346
484
  backslash is stripped from the resulting key: the decoded key ``kp1\.kp2``
347
485
  lands as the flat key ``kp1.kp2`` while ``a.kp1\.kp2`` becomes
348
486
  ``{"a": {"kp1.kp2": value}}``. Only the exact ``\.`` pair is special, so a
349
- backslash that is not followed by a dot (``a\b``) is preserved verbatim.
487
+ backslash that is not followed by a dot (``a\b``) is preserved verbatim, and
488
+ a decoded dot is never re-split.
350
489
 
351
490
  Expansion is two-pass so the result never depends on JSON key order: native
352
491
  objects are placed first, then dot-path entries are layered on top. Dot-path
353
- entries win on a duplicate sub-key while unmentioned sibling sub-keys of the
354
- native object survive.
355
-
356
- A ``parent`` that is already a scalar / list / ``null`` cannot be read as an
357
- object, so mixing it with ``parent.subkey`` is a hard client-side error
358
- rather than a silent replacement. Error messages name the offending key or
359
- parent only: params values are frequently credentials, so they must never be
360
- echoed into stdout/stderr (and from there into logs).
492
+ entries win on a duplicate leaf while unmentioned sibling keys of the native
493
+ object survive. An ancestor leaf plus a descendant path in the same input is
494
+ a conflict in either order, and so is an intermediate node that is already a
495
+ scalar / list / ``null``: both are hard client-side errors rather than silent
496
+ replacements. Error messages name the offending key or parent only: params
497
+ values are frequently credentials, so they must never be echoed into
498
+ stdout/stderr (and from there into logs).
361
499
 
362
500
  ``params`` must already be a validated JSON object (see
363
501
  :func:`_parse_json_object`): coercion must happen at the CLI boundary, so a
364
502
  falsy non-object such as ``null`` / ``[]`` / ``false`` / ``0`` / ``""`` is
365
503
  never silently rewritten into an empty patch. An empty object is a no-op.
504
+
505
+ One dot-path may expand into at most :data:`_MAX_DOT_PATH_SEGMENTS`
506
+ segments; a deeper key is rejected through the same dot-path parameter error
507
+ channel (exit code 1, key named, value never echoed). Flat keys and native
508
+ object values are not depth-checked: the cap only bounds nesting generated by
509
+ the top-level dot-path syntax, the cheapest input amplification vector (its
510
+ segments cost ~2 bytes each) but not the only one - a native object nests
511
+ too yet is never checked here, so whether a 65+ level native object succeeds
512
+ is a separate question answered by the server's recursion limit.
513
+
514
+ Work is O(input length + total segments + entries of every copied dict): one
515
+ trie build over the segments (which also detects ancestor/descendant pairs)
516
+ plus one copy-on-write merge that shallow-copies each modified path node at
517
+ most once - one caller object reached through k logical paths is copied k
518
+ times so the paths stay isolated - and each copy costs its source's entries.
366
519
  """
367
520
  expanded: dict[str, Any] = {}
368
- dotted: dict[str, dict[str, Any]] = {}
521
+ dotted: list[tuple[list[str], Any, str]] = []
369
522
  for key, value in params.items():
370
523
  if not isinstance(key, str):
371
524
  expanded[key] = value
372
525
  continue
373
- parent_key, sub_key = _split_dot_path(key)
374
- if parent_key is None:
375
- expanded[sub_key] = value
526
+ segments = _split_dot_path(key)
527
+ if len(segments) == 1:
528
+ expanded[segments[0]] = value
376
529
  continue
377
- if not parent_key or not sub_key:
378
- _emit_error(
379
- f"invalid -p/--params key {key!r}: dot-path needs a non-empty parent and sub-key"
380
- )
530
+ if any(not segment for segment in segments):
531
+ _emit_error(f"invalid -p/--params key {key!r}: dot-path needs non-empty segments")
381
532
  raise typer.Exit(1)
382
- dotted.setdefault(parent_key, {})[sub_key] = value
383
-
384
- for parent_key, sub_values in dotted.items():
385
- base = expanded.get(parent_key)
386
- if base is None and parent_key not in expanded:
387
- expanded[parent_key] = dict(sub_values)
388
- continue
389
- if not isinstance(base, dict):
533
+ if len(segments) > _MAX_DOT_PATH_SEGMENTS:
390
534
  _emit_error(
391
- f"conflicting -p/--params parent {parent_key!r}: "
392
- "set both as a non-object value and as a dot-path parent"
535
+ f"invalid -p/--params key {key!r}: dot-path has {len(segments)} segments, "
536
+ f"more than the maximum of {_MAX_DOT_PATH_SEGMENTS}"
393
537
  )
394
538
  raise typer.Exit(1)
395
- expanded[parent_key] = {**base, **sub_values}
539
+ dotted.append((segments, value, key))
540
+
541
+ trie = _build_dot_path_trie(dotted)
542
+ _merge_dot_path_trie(expanded, trie, {id(expanded)})
396
543
  return expanded
397
544
 
398
545
 
@@ -3168,8 +3315,10 @@ def job_create(
3168
3315
  "--params",
3169
3316
  "-p",
3170
3317
  help=(
3171
- "Parameters (JSON object). A dotted key expands one level, e.g. "
3172
- '\'{"proxy_envs.HTTPS_PROXY":"http://proxy"}\'; escape a literal dot as \\.'
3318
+ "Parameters (JSON object). A dotted key expands into nested objects "
3319
+ f"(depth up to {_MAX_DOT_PATH_SEGMENTS} levels), e.g. "
3320
+ '\'{"proxy_envs.HTTPS_PROXY":"http://proxy"}\'; '
3321
+ "escape a literal dot as \\."
3173
3322
  ),
3174
3323
  ),
3175
3324
  params_list_input: Optional[str] = typer.Option(
@@ -3892,6 +4041,7 @@ def job_create(
3892
4041
  except WaitTimeoutError as exc:
3893
4042
  emit_profile_retry_hint_once()
3894
4043
  typer.echo(f"error: {exc}", err=True)
4044
+ emit_metadata_completion_on_failure(metadata_completion)
3895
4045
  raise typer.Exit(1)
3896
4046
 
3897
4047
  if output_format != "plain":
@@ -4573,6 +4723,7 @@ def job_create(
4573
4723
  except WaitTimeoutError as exc:
4574
4724
  emit_retry_hint_once()
4575
4725
  typer.echo(f"error: {exc}", err=True)
4726
+ emit_metadata_completion_on_failure(metadata_completion)
4576
4727
  raise typer.Exit(1)
4577
4728
  if output_format != "plain":
4578
4729
  payload = {"submission": result}
@@ -4885,11 +5036,9 @@ def job_cancel(job_ids: List[str] = typer.Argument(..., help="Job IDs")):
4885
5036
  _print_job_cancel_plain(result)
4886
5037
 
4887
5038
 
4888
- # ---- RBAC v2 实例级委托:job/group 访问授权(scope=resource 绑定) ----
5039
+ # ---- RBAC v2 实例级委托:Group 访问授权(scope=resource 绑定) ----
4889
5040
 
4890
5041
  _RESOURCE_ROLE_IDS = {
4891
- ("job", "reader"): "built-in:job-reader",
4892
- ("job", "writer"): "built-in:job-writer",
4893
5042
  ("group", "reader"): "built-in:group-reader",
4894
5043
  ("group", "blackbox-reader"): "built-in:blackbox-reader",
4895
5044
  ("group", "writer"): "built-in:group-writer",
@@ -4901,18 +5050,14 @@ _RESOURCE_ROLE_IDS = {
4901
5050
  def _resource_role_id(resource: str, role: str) -> str:
4902
5051
  key = (resource, (role or "").strip().lower())
4903
5052
  if key not in _RESOURCE_ROLE_IDS:
4904
- choices = (
4905
- "reader, writer, cloner, blackbox-reader, admin"
4906
- if resource == "group"
4907
- else "reader, writer"
4908
- )
5053
+ choices = "reader, writer, cloner, blackbox-reader, admin"
4909
5054
  raise typer.BadParameter(f"role must be one of: {choices}")
4910
5055
  return _RESOURCE_ROLE_IDS[key]
4911
5056
 
4912
5057
 
4913
5058
  def _resolve_instance_workspace(client, resource: str, instance_id: str) -> str:
4914
- """解析 job/group 实例所属 queue_id(= workspace_id),供绑定门控使用。"""
4915
- doc = client.get_job(instance_id) if resource == "job" else client.get_group(instance_id)
5059
+ """解析 Group 所属 queue_id(= workspace_id),供绑定门控使用。"""
5060
+ doc = client.get_group(instance_id)
4916
5061
  ws = (doc or {}).get("queue_id")
4917
5062
  if not ws:
4918
5063
  raise typer.BadParameter(
@@ -4976,40 +5121,6 @@ def _print_instance_access(resource, instance_id):
4976
5121
  print(f" - {b.get('principal_type')}:{b.get('principal_id')} role={b.get('role_id')}")
4977
5122
 
4978
5123
 
4979
- @job_app.command("grant")
4980
- def job_grant(
4981
- job_id: str = typer.Argument(..., help="Job ID"),
4982
- user: Optional[str] = typer.Option(None, "--user", help="Grant to this user_id"),
4983
- user_group: Optional[str] = typer.Option(
4984
- None, "--user-group", help="Grant to this user_group_id"
4985
- ),
4986
- role: str = typer.Option(
4987
- "reader", "--role", help="reader (view) or writer (view+cancel/update)"
4988
- ),
4989
- ):
4990
- """Grant a user/user-group access to a specific job (RBAC v2 instance delegation)."""
4991
- _grant_instance_access("job", job_id, role, user, user_group)
4992
-
4993
-
4994
- @job_app.command("revoke")
4995
- def job_revoke(
4996
- job_id: str = typer.Argument(..., help="Job ID"),
4997
- user: Optional[str] = typer.Option(None, "--user", help="Revoke from this user_id"),
4998
- user_group: Optional[str] = typer.Option(
4999
- None, "--user-group", help="Revoke from this user_group_id"
5000
- ),
5001
- role: str = typer.Option("reader", "--role", help="reader or writer"),
5002
- ):
5003
- """Revoke a user/user-group's instance access to a specific job."""
5004
- _revoke_instance_access("job", job_id, role, user, user_group)
5005
-
5006
-
5007
- @job_app.command("access-list")
5008
- def job_access_list(job_id: str = typer.Argument(..., help="Job ID")):
5009
- """List who has instance-level access to a specific job."""
5010
- _print_instance_access("job", job_id)
5011
-
5012
-
5013
5124
  @job_app.command("retry")
5014
5125
  def job_retry(
5015
5126
  job_ids: List[str] = typer.Argument(..., help="Job IDs"),
@@ -5019,8 +5130,8 @@ def job_retry(
5019
5130
  "-p",
5020
5131
  help=(
5021
5132
  "Params patch (JSON object) to merge into existing params; "
5022
- 'a dotted key expands one level (e.g. \'{"proxy_envs.HTTPS_PROXY":"..."}\'); '
5023
- "escape a literal dot as \\."
5133
+ f"a dotted key expands into nested objects (depth up to {_MAX_DOT_PATH_SEGMENTS} levels, "
5134
+ "e.g. '{\"a.b.c\":1}'); escape a literal dot as \\."
5024
5135
  ),
5025
5136
  ),
5026
5137
  delete_params: Optional[str] = typer.Option(
@@ -6299,8 +6410,9 @@ def group_clone(
6299
6410
  "--params",
6300
6411
  "-p",
6301
6412
  help=(
6302
- "Top-level Job params patch (JSON object); a dotted key expands one "
6303
- 'level (e.g. \'{"proxy_envs.HTTPS_PROXY":"..."}\'); escape a literal dot as \\.'
6413
+ "Top-level Job params patch (JSON object); a dotted key expands into nested "
6414
+ f"objects (depth up to {_MAX_DOT_PATH_SEGMENTS} levels, e.g. '{{\"a.b.c\":1}}'); "
6415
+ "escape a literal dot as \\."
6304
6416
  ),
6305
6417
  ),
6306
6418
  delete_param: Optional[list[str]] = typer.Option(