bladekit 4.62.0__tar.gz → 4.63.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.
Files changed (35) hide show
  1. {bladekit-4.62.0 → bladekit-4.63.0}/PKG-INFO +1 -1
  2. {bladekit-4.62.0 → bladekit-4.63.0}/pyproject.toml +1 -1
  3. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/__init__.py +2 -0
  4. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_app.py +151 -2
  5. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/cli.py +97 -22
  6. {bladekit-4.62.0 → bladekit-4.63.0}/.gitignore +0 -0
  7. {bladekit-4.62.0 → bladekit-4.63.0}/README.md +0 -0
  8. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_banner.py +0 -0
  9. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_batch.py +0 -0
  10. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_bucket.py +0 -0
  11. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_build.py +0 -0
  12. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_bundle.py +0 -0
  13. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_client.py +0 -0
  14. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_cls.py +0 -0
  15. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_constants.py +0 -0
  16. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_cron.py +0 -0
  17. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_dict.py +0 -0
  18. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_env.py +0 -0
  19. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_exported_metrics.py +0 -0
  20. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_image.py +0 -0
  21. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_loader.py +0 -0
  22. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_map.py +0 -0
  23. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_metrics_cli.py +0 -0
  24. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_preempt.py +0 -0
  25. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_queue.py +0 -0
  26. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_render.py +0 -0
  27. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_runner_api.py +0 -0
  28. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_sandbox.py +0 -0
  29. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_secret.py +0 -0
  30. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_serialize.py +0 -0
  31. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_serve.py +0 -0
  32. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_volume.py +0 -0
  33. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/_webhook.py +0 -0
  34. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/config.py +0 -0
  35. {bladekit-4.62.0 → bladekit-4.63.0}/src/bladekit/exceptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bladekit
3
- Version: 4.62.0
3
+ Version: 4.63.0
4
4
  Summary: Blade AI Fabric SDK + CLI — run Python functions on Blade's GPU fleet.
5
5
  Project-URL: Homepage, https://blade.sh
6
6
  Project-URL: Documentation, https://console.blade.sh
@@ -16,7 +16,7 @@
16
16
  # uninstalled during an upgrade, and `forge` is a different project's name on
17
17
  # public PyPI.
18
18
  name = "bladekit"
19
- version = "4.62.0"
19
+ version = "4.63.0"
20
20
  description = "Blade AI Fabric SDK + CLI — run Python functions on Blade's GPU fleet."
21
21
  readme = "README.md"
22
22
  requires-python = ">=3.10"
@@ -49,6 +49,7 @@ from ._app import (
49
49
  DeploymentManifest,
50
50
  Function,
51
51
  FunctionCall,
52
+ ScaleOn,
52
53
  complete_session,
53
54
  )
54
55
  from ._batch import BatchedFunction, batched
@@ -133,6 +134,7 @@ __all__ = [
133
134
  "App",
134
135
  "app",
135
136
  "Autoscale",
137
+ "ScaleOn",
136
138
  "ExportMetric",
137
139
  "Function",
138
140
  "FunctionCall",
@@ -19,7 +19,7 @@ import time
19
19
  import re
20
20
  from dataclasses import dataclass, field
21
21
  from pathlib import Path
22
- from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, TYPE_CHECKING
22
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Union, cast, TYPE_CHECKING
23
23
 
24
24
  if TYPE_CHECKING: # pragma: no cover — typing only, avoids an import cycle
25
25
  from ._map import MapHandle
@@ -144,6 +144,86 @@ def _emit_run_warnings(run: dict) -> None:
144
144
  pass
145
145
 
146
146
 
147
+ # Mirrors control-plane internal/core/scaling_policy.go's MetricScaler validation.
148
+ _METRIC_SCALER_NAME_RE = re.compile(r"^[a-zA-Z_:][a-zA-Z0-9_:]{0,127}$")
149
+ _METRIC_LABEL_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]{0,63}$")
150
+ _METRIC_SCALER_FILTER_VALUE_RE = re.compile(r'^[^"\\{}\x00-\x1f]+$')
151
+ _RESERVED_METRIC_LABELS = frozenset({
152
+ "le", "quantile", "app", "app_id", "endpoint",
153
+ "replica", "replica_id", "gpu", "gpu_uuid",
154
+ "instance", "job", "function", "deployment",
155
+ "container_id", "node_id", "endpoint_id",
156
+ })
157
+
158
+
159
+ def _rewritten_metric_name(src: str) -> str:
160
+ """Mirror core.RewrittenMetricName: the CP<->node metric-name rewrite."""
161
+ prefix = "forge_app_custom_"
162
+ if src.startswith("vllm:"):
163
+ prefix = "forge_vllm_"
164
+ src = src[len("vllm:"):]
165
+ out = [prefix]
166
+ for c in src:
167
+ out.append(c if c.isalnum() or c == "_" else "_")
168
+ return "".join(out)
169
+
170
+
171
+ @dataclass(frozen=True)
172
+ class ScaleOn:
173
+ """One metric-driven scaling signal (``docs/specs/autoscaling-v2.md`` §17).
174
+
175
+ Pass a list of these as ``Autoscale(metrics=[...])``. ``web_server`` only,
176
+ at most 3 per endpoint. Validation mirrors the control plane's so a bad
177
+ scaler fails at decorator-application time, before any network call.
178
+ """
179
+
180
+ name: str
181
+ stat: str
182
+ target_per_replica: float
183
+ filter: Optional[str] = None
184
+
185
+ def __post_init__(self) -> None:
186
+ # field/reason mirror core.validateMetricScalers's *ScalingPolicyFieldError verbatim
187
+ # (minus the "scaling_policy."/"metrics[i]." prefixes a standalone ScaleOn can't know).
188
+ def fail(field: str, reason: str) -> None:
189
+ raise exc.InvalidArgumentError(
190
+ "SCALING_POLICY_INVALID", f"{field}: {reason}", details={"field": field}
191
+ )
192
+
193
+ if not isinstance(self.name, str) or not _METRIC_SCALER_NAME_RE.match(self.name):
194
+ fail("name", "must match ^[a-zA-Z_:][a-zA-Z0-9_:]{0,127}$")
195
+ if self.name.startswith("vllm:") or self.name.startswith("forge_"):
196
+ fail("name", "must not start with vllm: or forge_ (platform-reserved)")
197
+ if self.stat not in ("value", "rate"):
198
+ fail("stat", "must be value or rate")
199
+ if (
200
+ not isinstance(self.target_per_replica, (int, float))
201
+ or isinstance(self.target_per_replica, bool)
202
+ or not (0.01 <= self.target_per_replica <= 1e6)
203
+ ):
204
+ fail("target_per_replica", "must be between 0.01 and 1e6")
205
+ if self.filter is not None:
206
+ label, _, value = str(self.filter).partition("=")
207
+ if (
208
+ "=" not in self.filter
209
+ or not _METRIC_LABEL_RE.match(label)
210
+ or label.startswith("__")
211
+ or label in _RESERVED_METRIC_LABELS
212
+ ):
213
+ fail("filter", "must be label=value with a valid Prometheus label name")
214
+ if not (1 <= len(value.encode("utf-8")) <= 128) or not _METRIC_SCALER_FILTER_VALUE_RE.match(value):
215
+ fail(
216
+ "filter",
217
+ "value must be 1..128 bytes with no control characters, quotes, backslashes or braces",
218
+ )
219
+
220
+ def to_wire(self) -> dict:
221
+ d: dict = {"name": self.name, "stat": self.stat, "target_per_replica": self.target_per_replica}
222
+ if self.filter is not None:
223
+ d["filter"] = self.filter
224
+ return d
225
+
226
+
147
227
  @dataclass(frozen=True)
148
228
  class Autoscale:
149
229
  """Per-endpoint autoscaling policy (autoscaling v2).
@@ -175,6 +255,11 @@ class Autoscale:
175
255
  Unset = no ``health`` key, as before. ``Autoscale(health={...})`` alone adds
176
256
  no scaling target. ``web_server`` / ``asgi_app`` only (``web_endpoint`` is out
177
257
  of scope); ``vllm_slow_peer_ratio`` needs ``web_server``.
258
+ - ``metrics``: up to 3 metric-driven scaling signals (``docs/specs/
259
+ autoscaling-v2.md`` §17), each a ``ScaleOn(...)`` (validated client-side,
260
+ mirroring the server) or a raw mapping (validated server-side only, a
261
+ passthrough like ``health``). Sent as ``scaling_policy.metrics``.
262
+ ``web_server`` only. Unset = no ``metrics`` key, as before.
178
263
 
179
264
  Example::
180
265
 
@@ -193,6 +278,7 @@ class Autoscale:
193
278
  vllm_target_waiting: Optional[int] = None
194
279
  scaledown_window: Optional[int] = None
195
280
  health: Optional[Mapping[str, Any]] = None
281
+ metrics: Optional[Sequence[Union[Mapping[str, Any], "ScaleOn"]]] = None
196
282
 
197
283
  def __post_init__(self) -> None:
198
284
  if (
@@ -201,11 +287,12 @@ class Autoscale:
201
287
  and self.vllm_target_waiting is None
202
288
  and self.scaledown_window is None
203
289
  and self.health is None
290
+ and self.metrics is None
204
291
  ):
205
292
  raise exc.InvalidArgumentError(
206
293
  "SCALING_POLICY_INVALID",
207
294
  "bladekit.Autoscale requires at least one of target_inputs, "
208
- "buffer_replicas, vllm_target_waiting, scaledown_window, health",
295
+ "buffer_replicas, vllm_target_waiting, scaledown_window, health, metrics",
209
296
  )
210
297
  if self.health is not None:
211
298
  if not isinstance(self.health, Mapping) or not self.health or not all(
@@ -222,6 +309,50 @@ class Autoscale:
222
309
  raise exc.InvalidArgumentError(
223
310
  "SCALING_POLICY_INVALID", f"health must be JSON-serializable: {e}"
224
311
  ) from None
312
+ if self.metrics is not None:
313
+ shape_ok = (
314
+ isinstance(self.metrics, Sequence)
315
+ and not isinstance(self.metrics, (str, bytes))
316
+ and self.metrics
317
+ and all(
318
+ isinstance(m, ScaleOn)
319
+ or (isinstance(m, Mapping) and m and all(isinstance(k, str) for k in m))
320
+ for m in self.metrics
321
+ )
322
+ )
323
+ if not shape_ok:
324
+ raise exc.InvalidArgumentError(
325
+ "SCALING_POLICY_INVALID",
326
+ "metrics must be a non-empty sequence of ScaleOn or non-empty mappings with string keys",
327
+ )
328
+ if len(self.metrics) > 3:
329
+ raise exc.InvalidArgumentError(
330
+ "SCALING_POLICY_INVALID",
331
+ f"metrics: must have at most 3 metric scalers (got {len(self.metrics)})",
332
+ details={"field": "metrics"},
333
+ )
334
+ raw = [m.to_wire() if isinstance(m, ScaleOn) else dict(m) for m in self.metrics]
335
+ seen: Dict[str, str] = {}
336
+ for i, m in enumerate(raw):
337
+ name = m.get("name")
338
+ if not isinstance(name, str):
339
+ continue
340
+ rewritten = _rewritten_metric_name(name)
341
+ if rewritten in seen:
342
+ field = f"metrics[{i}].name"
343
+ raise exc.InvalidArgumentError(
344
+ "SCALING_POLICY_INVALID",
345
+ f'{field}: collides with {seen[rewritten]} after rewrite to "{rewritten}"',
346
+ details={"field": field},
347
+ )
348
+ seen[rewritten] = f"metrics[{i}]"
349
+ try:
350
+ canonical = json.loads(json.dumps(raw, allow_nan=False))
351
+ object.__setattr__(self, "metrics", canonical)
352
+ except (TypeError, ValueError) as e:
353
+ raise exc.InvalidArgumentError(
354
+ "SCALING_POLICY_INVALID", f"metrics must be JSON-serializable: {e}"
355
+ ) from None
225
356
  if self.target_inputs is not None and (
226
357
  not isinstance(self.target_inputs, int)
227
358
  or isinstance(self.target_inputs, bool)
@@ -2323,6 +2454,12 @@ def _validate_endpoint_autoscale(kind: str, autoscale: Optional[Autoscale]) -> N
2323
2454
  "SCALING_POLICY_INVALID",
2324
2455
  f"vllm_slow_peer_ratio requires @app.web_server (got {kind})",
2325
2456
  )
2457
+ if autoscale.metrics is not None and kind != "web_server":
2458
+ raise exc.InvalidArgumentError(
2459
+ "SCALING_POLICY_INVALID",
2460
+ f"metrics: metric scalers require a web_server endpoint (got {kind})",
2461
+ details={"field": "metrics"},
2462
+ )
2326
2463
 
2327
2464
 
2328
2465
  def _autoscaling_spec(
@@ -2391,6 +2528,7 @@ def _scaling_policy_spec(
2391
2528
  vllm_waiting: Optional[int] = None
2392
2529
  scaledown_window: Optional[int] = None
2393
2530
  health: Optional[Mapping[str, Any]] = None
2531
+ metrics: Optional[Sequence[Mapping[str, Any]]] = None
2394
2532
  if autoscale is not None:
2395
2533
  if autoscale.target_inputs is not None:
2396
2534
  if target is not None:
@@ -2404,12 +2542,15 @@ def _scaling_policy_spec(
2404
2542
  vllm_waiting = autoscale.vllm_target_waiting
2405
2543
  scaledown_window = autoscale.scaledown_window
2406
2544
  health = autoscale.health
2545
+ # __post_init__ already canonicalized every ScaleOn to a plain dict (json round-trip).
2546
+ metrics = cast(Optional[Sequence[Mapping[str, Any]]], autoscale.metrics)
2407
2547
  if (
2408
2548
  target is None
2409
2549
  and buffer_replicas is None
2410
2550
  and vllm_waiting is None
2411
2551
  and scaledown_window is None
2412
2552
  and health is None
2553
+ and metrics is None
2413
2554
  ):
2414
2555
  return None
2415
2556
  if target is not None and target > max_concurrent_inputs:
@@ -2424,6 +2565,12 @@ def _scaling_policy_spec(
2424
2565
  "vllm_target_waiting requires a @app.web_server endpoint "
2425
2566
  f"(got {kind})",
2426
2567
  )
2568
+ if metrics is not None and kind != "web_server":
2569
+ raise exc.InvalidArgumentError(
2570
+ "SCALING_POLICY_INVALID",
2571
+ f"metrics: metric scalers require a web_server endpoint (got {kind})",
2572
+ details={"field": "metrics"},
2573
+ )
2427
2574
  policy: dict[str, Any] = {"v": 1}
2428
2575
  if target is not None:
2429
2576
  policy["target_inputs"] = target
@@ -2437,6 +2584,8 @@ def _scaling_policy_spec(
2437
2584
  policy["scaledown_window_seconds"] = scaledown_window
2438
2585
  if health is not None:
2439
2586
  policy["health"] = dict(health)
2587
+ if metrics is not None:
2588
+ policy["metrics"] = [dict(m) for m in metrics]
2440
2589
  if len(policy) == 1:
2441
2590
  return None # only {"v":1} left (e.g. buffer_replicas=0): no policy
2442
2591
  return policy
@@ -25,7 +25,7 @@ import json
25
25
  import sys
26
26
  from collections.abc import Callable
27
27
  from pathlib import Path
28
- from typing import Any, NamedTuple, Optional, TypeVar
28
+ from typing import Any, List, NamedTuple, Optional, TypeVar
29
29
 
30
30
  import typer
31
31
 
@@ -1280,6 +1280,75 @@ def app_stop(app_name_or_id: str = typer.Argument(..., help="App name or app_ id
1280
1280
  client.close()
1281
1281
 
1282
1282
 
1283
+ _METRIC_FLAG_USAGE = (
1284
+ "--metric must be name=<name>,stat=<stat>,target=<target_per_replica>[,filter=<label>=<value>], "
1285
+ "e.g. name=jobs_waiting,stat=value,target=4"
1286
+ )
1287
+
1288
+
1289
+ def _parse_metric_flag(raw: str) -> dict:
1290
+ """Parse ``--metric name=...,stat=...,target=...[,filter=...]`` via ScaleOn (key=value: a metric name may itself contain ``:``)."""
1291
+ from ._app import ScaleOn
1292
+
1293
+ rest = raw
1294
+ fields: dict[str, str] = {}
1295
+ for key in ("name", "stat", "target"):
1296
+ prefix = key + "="
1297
+ if not rest.startswith(prefix):
1298
+ raise ValueError(_METRIC_FLAG_USAGE)
1299
+ rest = rest[len(prefix):]
1300
+ if key == "target":
1301
+ value, _, rest = rest.partition(",")
1302
+ else:
1303
+ if "," not in rest:
1304
+ raise ValueError(_METRIC_FLAG_USAGE)
1305
+ value, rest = rest.split(",", 1)
1306
+ fields[key] = value
1307
+ filt: Optional[str] = None
1308
+ if rest:
1309
+ if not rest.startswith("filter="):
1310
+ raise ValueError(_METRIC_FLAG_USAGE)
1311
+ filt = rest[len("filter="):]
1312
+ try:
1313
+ target = float(fields["target"])
1314
+ except ValueError:
1315
+ raise ValueError(f"--metric target {fields['target']!r} must be a number") from None
1316
+ return ScaleOn(name=fields["name"], stat=fields["stat"], target_per_replica=target, filter=filt).to_wire()
1317
+
1318
+
1319
+ def _merge_scale_policy(
1320
+ cur_policy: dict,
1321
+ *,
1322
+ target: Optional[int],
1323
+ buffer: Optional[int],
1324
+ vllm_waiting: Optional[int],
1325
+ metrics: Optional[List[str]] = None,
1326
+ clear_metrics: bool = False,
1327
+ ) -> tuple[Optional[dict], bool]:
1328
+ """Merge --target/--buffer/--vllm-waiting/--metric into cur_policy; unset keys (health, ...) pass through untouched."""
1329
+ policy = dict(cur_policy)
1330
+ policy["v"] = 1
1331
+ if target is not None:
1332
+ policy["target_inputs"] = target
1333
+ if buffer is not None:
1334
+ if buffer > 0:
1335
+ policy["buffer_replicas"] = buffer
1336
+ else:
1337
+ policy.pop("buffer_replicas", None)
1338
+ if vllm_waiting is not None:
1339
+ if vllm_waiting > 0:
1340
+ policy["vllm"] = {"target_waiting": vllm_waiting}
1341
+ else:
1342
+ policy.pop("vllm", None)
1343
+ if clear_metrics:
1344
+ policy.pop("metrics", None)
1345
+ elif metrics:
1346
+ policy["metrics"] = [_parse_metric_flag(m) for m in metrics]
1347
+ if set(policy.keys()) == {"v"}:
1348
+ return None, True
1349
+ return policy, False
1350
+
1351
+
1283
1352
  @app_app.command("scale")
1284
1353
  def app_scale(
1285
1354
  app_name_or_id: str = typer.Argument(..., help="App name or app_ id."),
@@ -1311,6 +1380,15 @@ def app_scale(
1311
1380
  None, "--vllm-waiting",
1312
1381
  help="vLLM preset: target requests waiting in vLLM's queue per replica (1-1000; 0 removes the preset; web_server only).",
1313
1382
  ),
1383
+ metric: Optional[List[str]] = typer.Option(
1384
+ None, "--metric",
1385
+ help="Metric scaler: name=<name>,stat=<stat>,target=<target_per_replica>[,filter=<label>=<value>] "
1386
+ "(repeatable, up to 3; web_server only). Replaces every stored metric scaler.",
1387
+ ),
1388
+ clear_metrics: bool = typer.Option(
1389
+ False, "--clear-metrics",
1390
+ help="Remove every metric scaler from the policy, keeping its other knobs.",
1391
+ ),
1314
1392
  clear_policy: bool = typer.Option(
1315
1393
  False, "--clear-policy",
1316
1394
  help="Clear the scaling policy entirely (back to default concurrency autoscaling).",
@@ -1332,14 +1410,18 @@ def app_scale(
1332
1410
  if (min_replicas is None and max_replicas is None and concurrency is None
1333
1411
  and idle is None and reserved is None
1334
1412
  and target is None and buffer is None and vllm_waiting is None
1413
+ and not metric and not clear_metrics
1335
1414
  and not clear_policy):
1336
1415
  console.print(
1337
1416
  "[red]Nothing to change.[/red] Pass at least one of "
1338
- "--min/--max/--concurrency/--idle/--reserved/--target/--buffer/--vllm-waiting/--clear-policy."
1417
+ "--min/--max/--concurrency/--idle/--reserved/--target/--buffer/--vllm-waiting/--metric/--clear-metrics/--clear-policy."
1339
1418
  )
1340
1419
  raise typer.Exit(2)
1341
- if clear_policy and (target is not None or buffer is not None or vllm_waiting is not None):
1342
- console.print("[red]--clear-policy cannot be combined with --target/--buffer/--vllm-waiting.[/red]")
1420
+ if clear_policy and (target is not None or buffer is not None or vllm_waiting is not None or metric or clear_metrics):
1421
+ console.print("[red]--clear-policy cannot be combined with --target/--buffer/--vllm-waiting/--metric/--clear-metrics.[/red]")
1422
+ raise typer.Exit(2)
1423
+ if metric and clear_metrics:
1424
+ console.print("[red]--metric cannot be combined with --clear-metrics.[/red]")
1343
1425
  raise typer.Exit(2)
1344
1426
 
1345
1427
  client, _ = _make_client()
@@ -1362,25 +1444,18 @@ def app_scale(
1362
1444
  # v2 policy: read-modify-write. The server replaces the policy wholesale
1363
1445
  # (never merges), so the CLI merges the flags into the CURRENT policy.
1364
1446
  policy: Optional[dict] = None
1365
- if target is not None or buffer is not None or vllm_waiting is not None:
1447
+ if target is not None or buffer is not None or vllm_waiting is not None or metric or clear_metrics:
1366
1448
  cur = next((e for e in endpoints if e["name"] == target_ep), None)
1367
- policy = dict(((cur or {}).get("autoscaling") or {}).get("scaling_policy") or {})
1368
- policy["v"] = 1
1369
- if target is not None:
1370
- policy["target_inputs"] = target
1371
- if buffer is not None:
1372
- if buffer > 0:
1373
- policy["buffer_replicas"] = buffer
1374
- else:
1375
- policy.pop("buffer_replicas", None)
1376
- if vllm_waiting is not None:
1377
- if vllm_waiting > 0:
1378
- policy["vllm"] = {"target_waiting": vllm_waiting}
1379
- else:
1380
- policy.pop("vllm", None)
1381
- if set(policy.keys()) == {"v"}:
1382
- # Everything removed → clear rather than send an empty policy.
1383
- policy = None
1449
+ cur_policy = ((cur or {}).get("autoscaling") or {}).get("scaling_policy") or {}
1450
+ try:
1451
+ policy, policy_emptied = _merge_scale_policy(
1452
+ cur_policy, target=target, buffer=buffer, vllm_waiting=vllm_waiting,
1453
+ metrics=metric, clear_metrics=clear_metrics,
1454
+ )
1455
+ except (ValueError, exc.InvalidArgumentError) as e:
1456
+ console.print(f"[red]{e}[/red]")
1457
+ raise typer.Exit(2) from None
1458
+ if policy_emptied:
1384
1459
  clear_policy = True
1385
1460
 
1386
1461
  updated = client.scale_endpoint(
File without changes
File without changes