-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathdeployment.py
More file actions
1597 lines (1506 loc) · 65.3 KB
/
deployment.py
File metadata and controls
1597 lines (1506 loc) · 65.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Deployment adapter bridging DTOs and Processors."""
from __future__ import annotations
import uuid
from collections.abc import Sequence
from functools import lru_cache
from pathlib import PurePosixPath
from uuid import UUID
from ai.backend.common.api_handlers import Sentinel
from ai.backend.common.data.model_deployment.types import (
DeploymentStrategy,
RouteHealthStatus,
RouteStatus,
RouteTrafficStatus,
)
from ai.backend.common.dto.manager.v2.auto_scaling_rule.request import (
CreateAutoScalingRuleInput,
DeleteAutoScalingRuleInput,
UpdateAutoScalingRuleInput,
)
from ai.backend.common.dto.manager.v2.deployment.request import (
ActivateRevisionInput,
AddRevisionGQLInputDTO,
AdminSearchDeploymentsInput,
AdminSearchRevisionsInput,
CreateAccessTokenInput,
CreateDeploymentInput,
DeleteDeploymentInput,
DeploymentOrder,
ReplicaOrder,
RevisionOrder,
RouteOrder,
SearchAccessTokensInput,
SearchAutoScalingRulesInput,
SearchDeploymentPoliciesInput,
SearchReplicasInput,
SearchRoutesInput,
SyncReplicaInput,
UpdateDeploymentInput,
UpsertDeploymentPolicyInput,
)
from ai.backend.common.dto.manager.v2.deployment.response import (
AccessTokenNode,
ActivateRevisionPayload,
AddRevisionPayload,
AdminSearchDeploymentsPayload,
AdminSearchRevisionsPayload,
AutoScalingRuleNode,
CreateAccessTokenPayload,
CreateAutoScalingRulePayload,
CreateDeploymentPayload,
DeleteAutoScalingRulePayload,
DeleteDeploymentPayload,
DeploymentNode,
DeploymentPolicyNode,
GetAutoScalingRulePayload,
GetDeploymentPolicyPayload,
ReplicaNode,
RevisionNode,
RouteNode,
SearchAccessTokensPayload,
SearchAutoScalingRulesPayload,
SearchDeploymentPoliciesPayload,
SearchReplicasPayload,
SearchRoutesPayload,
SyncReplicaPayload,
UpdateAutoScalingRulePayload,
UpdateDeploymentPayload,
UpsertDeploymentPolicyPayload,
)
from ai.backend.common.dto.manager.v2.deployment.types import (
BlueGreenConfigInfo,
BlueGreenStrategySpecInfo,
ClusterConfigInfoDTO,
DeploymentMetadataInfoDTO,
DeploymentNetworkAccessInfoDTO,
DeploymentOrderField,
DeploymentPolicyInfo,
DeploymentStrategyInfoDTO,
EnvironmentVariableEntryInfoDTO,
EnvironmentVariablesInfoDTO,
ExtraVFolderMountGQLDTO,
ModelDefinitionInfoDTO,
ModelMountConfigInfoDTO,
ModelRuntimeConfigInfoDTO,
OrderDirection,
ReplicaOrderField,
ReplicaStateInfo,
ResourceConfigInfoDTO,
RevisionOrderField,
RollingUpdateConfigInfo,
RollingUpdateStrategySpecInfo,
RouteOrderField,
)
from ai.backend.common.dto.manager.v2.fair_share.types import (
ResourceSlotEntryInfo,
ResourceSlotInfo,
)
from ai.backend.common.dto.manager.v2.resource_slot.types import (
ResourceOptsEntryInfoDTO,
ResourceOptsInfoDTO,
)
from ai.backend.common.types import RuntimeVariant
from ai.backend.manager.data.deployment.access_token import ModelDeploymentAccessTokenCreator
from ai.backend.manager.data.deployment.creator import (
DeploymentPolicyConfig,
ModelRevisionCreator,
NewDeploymentCreator,
VFolderMountsCreator,
)
from ai.backend.manager.data.deployment.scale import ModelDeploymentAutoScalingRuleCreator
from ai.backend.manager.data.deployment.scale_modifier import (
ModelDeploymentAutoScalingRuleModifier,
)
from ai.backend.manager.data.deployment.types import (
AccessTokenSearchScope,
AutoScalingRuleSearchScope,
DeploymentMetadata,
DeploymentNetworkSpec,
DeploymentPolicyData,
ExecutionSpec,
ModelDeploymentAccessTokenData,
ModelDeploymentAutoScalingRuleData,
ModelDeploymentData,
ModelReplicaData,
ModelRevisionData,
MountInfo,
ReplicaSearchScope,
ReplicaSpec,
ResourceSpec,
RevisionSearchScope,
RouteInfo,
RouteSearchScope,
)
from ai.backend.manager.data.deployment.types import (
RouteHealthStatus as ManagerRouteHealthStatus,
)
from ai.backend.manager.data.deployment.types import (
RouteStatus as ManagerRouteStatus,
)
from ai.backend.manager.data.deployment.types import (
RouteTrafficStatus as ManagerRouteTrafficStatus,
)
from ai.backend.manager.data.deployment.upserter import DeploymentPolicyUpserter
from ai.backend.manager.errors.deployment import DeploymentRevisionNotFound
from ai.backend.manager.models.deployment_policy import BlueGreenSpec, RollingUpdateSpec
from ai.backend.manager.models.deployment_policy.conditions import DeploymentPolicyConditions
from ai.backend.manager.models.deployment_policy.row import DeploymentPolicyRow
from ai.backend.manager.models.deployment_revision import DeploymentRevisionRow
from ai.backend.manager.models.deployment_revision.conditions import RevisionConditions
from ai.backend.manager.models.deployment_revision.orders import RevisionOrders
from ai.backend.manager.models.endpoint import (
EndpointAutoScalingRuleRow,
EndpointRow,
EndpointTokenRow,
)
from ai.backend.manager.models.endpoint.conditions import (
AccessTokenConditions,
AutoScalingRuleConditions,
DeploymentConditions,
)
from ai.backend.manager.models.endpoint.orders import (
AccessTokenOrders,
AutoScalingRuleOrders,
DeploymentOrders,
)
from ai.backend.manager.models.routing import RoutingRow
from ai.backend.manager.models.routing.conditions import RouteConditions
from ai.backend.manager.models.routing.orders import RouteOrders
from ai.backend.manager.repositories.base import (
BatchQuerier,
NoPagination,
OffsetPagination,
QueryCondition,
QueryOrder,
Updater,
)
from ai.backend.manager.repositories.deployment.updaters import (
DeploymentMetadataUpdaterSpec,
DeploymentNetworkSpecUpdaterSpec,
DeploymentUpdaterSpec,
ReplicaSpecUpdaterSpec,
RevisionStateUpdaterSpec,
)
from ai.backend.manager.services.deployment.actions.access_token.create_access_token import (
CreateAccessTokenAction,
)
from ai.backend.manager.services.deployment.actions.access_token.search_access_tokens import (
SearchAccessTokensAction,
)
from ai.backend.manager.services.deployment.actions.auto_scaling_rule.create_auto_scaling_rule import (
CreateAutoScalingRuleAction,
)
from ai.backend.manager.services.deployment.actions.auto_scaling_rule.delete_auto_scaling_rule import (
DeleteAutoScalingRuleAction,
)
from ai.backend.manager.services.deployment.actions.auto_scaling_rule.get_auto_scaling_rule import (
GetAutoScalingRuleAction,
)
from ai.backend.manager.services.deployment.actions.auto_scaling_rule.search_auto_scaling_rules import (
SearchAutoScalingRulesAction,
)
from ai.backend.manager.services.deployment.actions.auto_scaling_rule.update_auto_scaling_rule import (
UpdateAutoScalingRuleAction,
)
from ai.backend.manager.services.deployment.actions.create_deployment import CreateDeploymentAction
from ai.backend.manager.services.deployment.actions.deployment_policy.get_deployment_policy import (
GetDeploymentPolicyAction,
)
from ai.backend.manager.services.deployment.actions.deployment_policy.search_deployment_policies import (
SearchDeploymentPoliciesAction,
)
from ai.backend.manager.services.deployment.actions.deployment_policy.upsert_deployment_policy import (
UpsertDeploymentPolicyAction,
)
from ai.backend.manager.services.deployment.actions.destroy_deployment import (
DestroyDeploymentAction,
)
from ai.backend.manager.services.deployment.actions.get_deployment_by_id import (
GetDeploymentByIdAction,
)
from ai.backend.manager.services.deployment.actions.get_replica_by_id import (
GetReplicaByIdAction,
)
from ai.backend.manager.services.deployment.actions.model_revision.add_model_revision import (
AddModelRevisionAction,
)
from ai.backend.manager.services.deployment.actions.model_revision.get_revision_by_id import (
GetRevisionByIdAction,
)
from ai.backend.manager.services.deployment.actions.model_revision.search_revisions import (
SearchRevisionsAction,
)
from ai.backend.manager.services.deployment.actions.revision_operations import (
ActivateRevisionAction,
)
from ai.backend.manager.services.deployment.actions.route.search_routes import SearchRoutesAction
from ai.backend.manager.services.deployment.actions.route.update_route_traffic_status import (
UpdateRouteTrafficStatusAction,
)
from ai.backend.manager.services.deployment.actions.search_deployments import (
SearchDeploymentsAction,
)
from ai.backend.manager.services.deployment.actions.search_replicas import SearchReplicasAction
from ai.backend.manager.services.deployment.actions.sync_replicas import SyncReplicaAction
from ai.backend.manager.services.deployment.actions.update_deployment import UpdateDeploymentAction
from ai.backend.manager.types import OptionalState, TriState
from .base import BaseAdapter
from .pagination import PaginationSpec
DEFAULT_PAGINATION_LIMIT = 10
@lru_cache(maxsize=1)
def _get_deployment_pagination_spec() -> PaginationSpec:
return PaginationSpec(
forward_order=DeploymentOrders.created_at(ascending=False),
backward_order=DeploymentOrders.created_at(ascending=True),
forward_condition_factory=DeploymentConditions.by_cursor_forward,
backward_condition_factory=DeploymentConditions.by_cursor_backward,
tiebreaker_order=EndpointRow.id.asc(),
)
def _get_deployment_policy_pagination_spec() -> PaginationSpec:
return PaginationSpec(
forward_order=DeploymentPolicyRow.created_at.desc(),
backward_order=DeploymentPolicyRow.created_at.asc(),
forward_condition_factory=DeploymentConditions.by_cursor_forward,
backward_condition_factory=DeploymentConditions.by_cursor_backward,
tiebreaker_order=DeploymentPolicyRow.id.asc(),
)
@lru_cache(maxsize=1)
def _get_revision_pagination_spec() -> PaginationSpec:
return PaginationSpec(
forward_order=RevisionOrders.created_at(ascending=False),
backward_order=RevisionOrders.created_at(ascending=True),
forward_condition_factory=RevisionConditions.by_cursor_forward,
backward_condition_factory=RevisionConditions.by_cursor_backward,
tiebreaker_order=DeploymentRevisionRow.id.asc(),
)
@lru_cache(maxsize=1)
def _get_route_pagination_spec() -> PaginationSpec:
return PaginationSpec(
forward_order=RouteOrders.created_at(ascending=False),
backward_order=RouteOrders.created_at(ascending=True),
forward_condition_factory=RouteConditions.by_cursor_forward,
backward_condition_factory=RouteConditions.by_cursor_backward,
tiebreaker_order=RoutingRow.id.asc(),
)
@lru_cache(maxsize=1)
def _get_access_token_pagination_spec() -> PaginationSpec:
return PaginationSpec(
forward_order=AccessTokenOrders.created_at(ascending=False),
backward_order=AccessTokenOrders.created_at(ascending=True),
forward_condition_factory=AccessTokenConditions.by_cursor_forward,
backward_condition_factory=AccessTokenConditions.by_cursor_backward,
tiebreaker_order=EndpointTokenRow.id.asc(),
)
@lru_cache(maxsize=1)
def _get_auto_scaling_rule_pagination_spec() -> PaginationSpec:
return PaginationSpec(
forward_order=AutoScalingRuleOrders.created_at(ascending=False),
backward_order=AutoScalingRuleOrders.created_at(ascending=True),
forward_condition_factory=AutoScalingRuleConditions.by_cursor_forward,
backward_condition_factory=AutoScalingRuleConditions.by_cursor_backward,
tiebreaker_order=EndpointAutoScalingRuleRow.id.asc(),
)
@lru_cache(maxsize=1)
def _get_replica_pagination_spec() -> PaginationSpec:
return PaginationSpec(
forward_order=RouteOrders.created_at(ascending=False),
backward_order=RouteOrders.created_at(ascending=True),
forward_condition_factory=RouteConditions.by_cursor_forward,
backward_condition_factory=RouteConditions.by_cursor_backward,
tiebreaker_order=RoutingRow.id.asc(),
)
class DeploymentAdapter(BaseAdapter):
"""Adapter for deployment domain operations."""
# ------------------------------------------------------------------
# Core deployment operations
# ------------------------------------------------------------------
async def create(
self,
input: CreateDeploymentInput,
created_user_id: UUID,
) -> CreateDeploymentPayload:
"""Create a new deployment."""
initial_revision = input.initial_revision
if initial_revision is None:
raise ValueError("initial_revision is required for deployment creation")
mounts_creator = VFolderMountsCreator(
model_vfolder_id=initial_revision.model_mount_config.vfolder_id,
model_definition_path=initial_revision.model_mount_config.definition_path,
model_mount_destination=initial_revision.model_mount_config.mount_destination,
extra_mounts=[
MountInfo(
vfolder_id=m.vfolder_id,
kernel_path=PurePosixPath(m.mount_destination) if m.mount_destination else None,
)
for m in (initial_revision.extra_mounts or [])
],
)
model_revision_creator = ModelRevisionCreator(
image_id=initial_revision.image.id,
resource_group=initial_revision.resource_config.resource_group.name,
resource_spec=ResourceSpec(
cluster_mode=initial_revision.cluster_config.mode,
cluster_size=initial_revision.cluster_config.size,
resource_slots={
e.resource_type: e.quantity
for e in initial_revision.resource_config.resource_slots.entries
},
resource_opts={
e.name: e.value for e in initial_revision.resource_config.resource_opts.entries
}
if initial_revision.resource_config.resource_opts
else None,
),
mounts=mounts_creator,
model_definition=initial_revision.model_definition,
revision_preset_id=initial_revision.revision_preset_id,
execution=ExecutionSpec(
runtime_variant=RuntimeVariant(
initial_revision.model_runtime_config.runtime_variant
),
environ={
e.name: e.value for e in initial_revision.model_runtime_config.environ.entries
}
if initial_revision.model_runtime_config.environ
else None,
),
)
strategy = input.default_deployment_strategy
policy: DeploymentPolicyConfig | None = None
if strategy.rolling_update is not None:
policy = DeploymentPolicyConfig(
strategy=DeploymentStrategy.ROLLING,
strategy_spec=RollingUpdateSpec(
max_surge=strategy.rolling_update.max_surge,
max_unavailable=strategy.rolling_update.max_unavailable,
),
)
elif strategy.blue_green is not None:
policy = DeploymentPolicyConfig(
strategy=DeploymentStrategy.BLUE_GREEN,
strategy_spec=BlueGreenSpec(
auto_promote=strategy.blue_green.auto_promote,
promote_delay_seconds=strategy.blue_green.promote_delay_seconds,
),
)
else:
policy = DeploymentPolicyConfig(
strategy=strategy.type,
strategy_spec=RollingUpdateSpec(),
)
meta = input.metadata
creator = NewDeploymentCreator(
metadata=DeploymentMetadata(
name=meta.name or f"deployment-{created_user_id.hex[:8]}",
domain=meta.domain_name,
project=meta.project_id,
resource_group=initial_revision.resource_config.resource_group.name,
created_user=created_user_id,
session_owner=created_user_id,
created_at=None,
revision_history_limit=10,
tag=",".join(meta.tags) if meta.tags else None,
),
replica_spec=ReplicaSpec(replica_count=input.desired_replica_count),
network=DeploymentNetworkSpec(
open_to_public=input.network_access.open_to_public,
preferred_domain_name=input.network_access.preferred_domain_name,
),
model_revision=model_revision_creator,
policy=policy,
)
action_result = await self._processors.deployment.create_deployment.wait_for_complete(
CreateDeploymentAction(creator=creator)
)
return CreateDeploymentPayload(deployment=self._deployment_data_to_dto(action_result.data))
async def admin_search(
self,
input: AdminSearchDeploymentsInput,
) -> AdminSearchDeploymentsPayload:
"""Search deployments (admin, no scope)."""
querier = self._build_deployment_querier(input)
action_result = await self._processors.deployment.search_deployments.wait_for_complete(
SearchDeploymentsAction(querier=querier)
)
return AdminSearchDeploymentsPayload(
items=[self._deployment_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
async def get(self, deployment_id: UUID) -> DeploymentNode:
"""Retrieve a single deployment by ID."""
action_result = await self._processors.deployment.get_deployment_by_id.wait_for_complete(
GetDeploymentByIdAction(deployment_id=deployment_id)
)
return self._deployment_data_to_dto(action_result.data)
async def get_current_revision(self, deployment_id: UUID) -> RevisionNode:
"""Retrieve the current active revision of a deployment."""
deployment = await self.get(deployment_id)
if deployment.current_revision_id is None:
raise DeploymentRevisionNotFound(f"Deployment {deployment_id} has no current revision")
return await self.get_revision(deployment.current_revision_id)
async def update(
self,
input: UpdateDeploymentInput,
deployment_id: UUID,
) -> UpdateDeploymentPayload:
"""Update deployment metadata and configuration."""
metadata_spec: DeploymentMetadataUpdaterSpec | None = None
if input.name is not None:
tag_str: str | None = None
if not isinstance(input.tags, Sentinel) and input.tags is not None:
tag_str = ",".join(input.tags)
elif not isinstance(input.tags, Sentinel) and input.tags is None:
tag_str = None
metadata_spec = DeploymentMetadataUpdaterSpec(
name=OptionalState.update(input.name)
if input.name is not None
else OptionalState.nop(),
tag=(
TriState[str].nop()
if isinstance(input.tags, Sentinel)
else TriState[str].from_graphql(tag_str)
),
)
elif not isinstance(input.tags, Sentinel):
tag_str = ",".join(input.tags) if input.tags is not None else None
metadata_spec = DeploymentMetadataUpdaterSpec(
tag=TriState[str].from_graphql(tag_str),
)
replica_spec: ReplicaSpecUpdaterSpec | None = None
if input.desired_replica_count is not None:
replica_spec = ReplicaSpecUpdaterSpec(
desired_replica_count=OptionalState.update(input.desired_replica_count),
)
network_spec: DeploymentNetworkSpecUpdaterSpec | None = None
if input.open_to_public is not None:
network_spec = DeploymentNetworkSpecUpdaterSpec(
open_to_public=OptionalState.from_graphql(input.open_to_public),
)
revision_state_spec: RevisionStateUpdaterSpec | None = None
if input.active_revision_id is not None:
revision_state_spec = RevisionStateUpdaterSpec(
current_revision=TriState[UUID].from_graphql(input.active_revision_id),
)
spec = DeploymentUpdaterSpec(
metadata=metadata_spec,
replica_spec=replica_spec,
network=network_spec,
revision_state=revision_state_spec,
)
updater: Updater[EndpointRow] = Updater(spec=spec, pk_value=deployment_id)
action_result = await self._processors.deployment.update_deployment.wait_for_complete(
UpdateDeploymentAction(updater=updater)
)
return UpdateDeploymentPayload(deployment=self._deployment_data_to_dto(action_result.data))
async def sync_replicas(self, input: SyncReplicaInput) -> SyncReplicaPayload:
"""Force sync replica information for a deployment."""
await self._processors.deployment.sync_replicas.wait_for_complete(
SyncReplicaAction(deployment_id=input.model_deployment_id)
)
return SyncReplicaPayload(success=True)
async def activate_revision(self, input: ActivateRevisionInput) -> ActivateRevisionPayload:
"""Activate a specific revision as the current revision."""
action_result = await self._processors.deployment.activate_revision.wait_for_complete(
ActivateRevisionAction(
deployment_id=input.deployment_id,
revision_id=input.revision_id,
)
)
return ActivateRevisionPayload(
deployment=self._deployment_data_to_dto(action_result.deployment),
previous_revision_id=action_result.previous_revision_id,
activated_revision_id=action_result.activated_revision_id,
deployment_policy=self._policy_data_to_dto(action_result.deployment_policy),
)
async def delete(self, input: DeleteDeploymentInput) -> DeleteDeploymentPayload:
"""Delete a deployment."""
await self._processors.deployment.destroy_deployment.wait_for_complete(
DestroyDeploymentAction(endpoint_id=input.id)
)
return DeleteDeploymentPayload(id=input.id)
# ------------------------------------------------------------------
# Access token operations
# ------------------------------------------------------------------
async def create_access_token(
self,
input: CreateAccessTokenInput,
) -> CreateAccessTokenPayload:
"""Create a new access token for a deployment."""
creator = ModelDeploymentAccessTokenCreator(
model_deployment_id=input.deployment_id,
valid_until=input.valid_until,
)
action_result = await self._processors.deployment.create_access_token.wait_for_complete(
CreateAccessTokenAction(creator=creator)
)
return CreateAccessTokenPayload(
access_token=self._access_token_data_to_dto(action_result.data)
)
async def search_access_tokens(
self,
scope: AccessTokenSearchScope,
input: SearchAccessTokensInput,
) -> SearchAccessTokensPayload:
"""Search access tokens scoped to a specific deployment."""
querier = self._build_access_token_querier(input, scope=scope)
action_result = await self._processors.deployment.search_access_tokens.wait_for_complete(
SearchAccessTokensAction(querier=querier)
)
return SearchAccessTokensPayload(
items=[self._access_token_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
# ------------------------------------------------------------------
# Auto-scaling rule operations
# ------------------------------------------------------------------
async def create_rule(
self,
input: CreateAutoScalingRuleInput,
) -> CreateAutoScalingRulePayload:
"""Create a new auto-scaling rule for a deployment."""
creator = ModelDeploymentAutoScalingRuleCreator(
model_deployment_id=input.model_deployment_id,
metric_source=input.metric_source,
metric_name=input.metric_name,
min_threshold=input.min_threshold,
max_threshold=input.max_threshold,
step_size=input.step_size,
time_window=input.time_window,
min_replicas=input.min_replicas,
max_replicas=input.max_replicas,
)
action_result = (
await self._processors.deployment.create_auto_scaling_rule.wait_for_complete(
CreateAutoScalingRuleAction(creator=creator)
)
)
return CreateAutoScalingRulePayload(
rule=self._auto_scaling_rule_data_to_dto(action_result.data)
)
async def search_rules(
self,
scope: AutoScalingRuleSearchScope,
input: SearchAutoScalingRulesInput,
) -> SearchAutoScalingRulesPayload:
"""Search auto-scaling rules scoped to a specific deployment."""
querier = self._build_auto_scaling_rule_querier(input, scope=scope)
action_result = (
await self._processors.deployment.search_auto_scaling_rules.wait_for_complete(
SearchAutoScalingRulesAction(querier=querier)
)
)
return SearchAutoScalingRulesPayload(
items=[self._auto_scaling_rule_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
async def get_rule(self, rule_id: UUID) -> GetAutoScalingRulePayload:
"""Retrieve a single auto-scaling rule by ID."""
action_result = await self._processors.deployment.get_auto_scaling_rule.wait_for_complete(
GetAutoScalingRuleAction(auto_scaling_rule_id=rule_id)
)
return GetAutoScalingRulePayload(
rule=self._auto_scaling_rule_data_to_dto(action_result.data)
)
async def update_rule(
self,
input: UpdateAutoScalingRuleInput,
) -> UpdateAutoScalingRulePayload:
"""Update an auto-scaling rule."""
modifier = ModelDeploymentAutoScalingRuleModifier(
metric_source=(
OptionalState.update(input.metric_source)
if input.metric_source is not None
else OptionalState.nop()
),
metric_name=(
OptionalState.update(input.metric_name)
if input.metric_name is not None
else OptionalState.nop()
),
min_threshold=(
OptionalState.update(input.min_threshold)
if not isinstance(input.min_threshold, Sentinel) and input.min_threshold is not None
else OptionalState.nop()
),
max_threshold=(
OptionalState.update(input.max_threshold)
if not isinstance(input.max_threshold, Sentinel) and input.max_threshold is not None
else OptionalState.nop()
),
step_size=(
OptionalState.update(input.step_size)
if input.step_size is not None
else OptionalState.nop()
),
time_window=(
OptionalState.update(input.time_window)
if input.time_window is not None
else OptionalState.nop()
),
min_replicas=(
OptionalState.update(input.min_replicas)
if not isinstance(input.min_replicas, Sentinel) and input.min_replicas is not None
else OptionalState.nop()
),
max_replicas=(
OptionalState.update(input.max_replicas)
if not isinstance(input.max_replicas, Sentinel) and input.max_replicas is not None
else OptionalState.nop()
),
)
action_result = (
await self._processors.deployment.update_auto_scaling_rule.wait_for_complete(
UpdateAutoScalingRuleAction(auto_scaling_rule_id=input.id, modifier=modifier)
)
)
return UpdateAutoScalingRulePayload(
rule=self._auto_scaling_rule_data_to_dto(action_result.data)
)
async def delete_rule(self, input: DeleteAutoScalingRuleInput) -> DeleteAutoScalingRulePayload:
"""Delete an auto-scaling rule."""
await self._processors.deployment.delete_auto_scaling_rule.wait_for_complete(
DeleteAutoScalingRuleAction(auto_scaling_rule_id=input.id)
)
return DeleteAutoScalingRulePayload(id=input.id)
# ------------------------------------------------------------------
# Deployment policy operations
# ------------------------------------------------------------------
async def get_policy(self, deployment_id: UUID) -> GetDeploymentPolicyPayload:
"""Retrieve a deployment policy by deployment ID."""
action_result = await self._processors.deployment.get_deployment_policy.wait_for_complete(
GetDeploymentPolicyAction(endpoint_id=deployment_id)
)
return GetDeploymentPolicyPayload(policy=self._policy_data_to_dto(action_result.data))
async def search_policies(
self,
input: SearchDeploymentPoliciesInput,
) -> SearchDeploymentPoliciesPayload:
"""Search deployment policies with filters and pagination."""
querier = self._build_policy_querier(input)
action_result = (
await self._processors.deployment.search_deployment_policies.wait_for_complete(
SearchDeploymentPoliciesAction(querier=querier)
)
)
return SearchDeploymentPoliciesPayload(
items=[self._policy_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
async def upsert_policy(
self,
input: UpsertDeploymentPolicyInput,
) -> UpsertDeploymentPolicyPayload:
"""Create or update a deployment policy."""
strategy_spec: RollingUpdateSpec | BlueGreenSpec
match input.strategy:
case DeploymentStrategy.ROLLING:
rolling = input.rolling_update
if rolling is not None:
strategy_spec = RollingUpdateSpec(
max_surge=rolling.max_surge,
max_unavailable=rolling.max_unavailable,
)
else:
strategy_spec = RollingUpdateSpec()
case DeploymentStrategy.BLUE_GREEN:
bg = input.blue_green
strategy_spec = BlueGreenSpec(
auto_promote=bg.auto_promote if bg is not None else False,
promote_delay_seconds=bg.promote_delay_seconds if bg is not None else 0,
)
upserter = DeploymentPolicyUpserter(
deployment_id=input.deployment_id,
strategy=input.strategy,
strategy_spec=strategy_spec,
)
action_result = (
await self._processors.deployment.upsert_deployment_policy.wait_for_complete(
UpsertDeploymentPolicyAction(upserter=upserter)
)
)
return UpsertDeploymentPolicyPayload(policy=self._policy_data_to_dto(action_result.data))
# ------------------------------------------------------------------
# Model revision operations
# ------------------------------------------------------------------
async def add_revision(
self,
input: AddRevisionGQLInputDTO,
) -> AddRevisionPayload:
"""Add a new model revision to a deployment."""
mounts_creator = VFolderMountsCreator(
model_vfolder_id=input.model_mount_config.vfolder_id,
model_definition_path=input.model_mount_config.definition_path,
model_mount_destination=input.model_mount_config.mount_destination,
extra_mounts=[
MountInfo(
vfolder_id=m.vfolder_id,
kernel_path=PurePosixPath(m.mount_destination) if m.mount_destination else None,
)
for m in (input.extra_mounts or [])
],
)
adder = ModelRevisionCreator(
image_id=input.image.id,
resource_group=input.resource_config.resource_group.name,
resource_spec=ResourceSpec(
cluster_mode=input.cluster_config.mode,
cluster_size=input.cluster_config.size,
resource_slots={
e.resource_type: e.quantity
for e in input.resource_config.resource_slots.entries
},
resource_opts={e.name: e.value for e in input.resource_config.resource_opts.entries}
if input.resource_config.resource_opts
else None,
),
mounts=mounts_creator,
execution=ExecutionSpec(
runtime_variant=RuntimeVariant(input.model_runtime_config.runtime_variant),
environ={e.name: e.value for e in input.model_runtime_config.environ.entries}
if input.model_runtime_config.environ
else None,
inference_runtime_config=input.model_runtime_config.inference_runtime_config,
),
model_definition=input.model_definition,
revision_preset_id=input.revision_preset_id,
)
action_result = await self._processors.deployment.add_model_revision.wait_for_complete(
AddModelRevisionAction(model_deployment_id=input.deployment_id, adder=adder)
)
return AddRevisionPayload(revision=self._revision_data_to_dto(action_result.revision))
async def get_revision(self, revision_id: UUID) -> RevisionNode:
"""Retrieve a single revision by ID."""
action_result = await self._processors.deployment.get_revision_by_id.wait_for_complete(
GetRevisionByIdAction(revision_id=revision_id)
)
return self._revision_data_to_dto(action_result.data)
async def search_revisions(
self,
scope: RevisionSearchScope,
input: AdminSearchRevisionsInput,
) -> AdminSearchRevisionsPayload:
"""Search model revisions scoped to a specific deployment."""
querier = self._build_revision_querier(input, scope=scope)
action_result = await self._processors.deployment.search_revisions.wait_for_complete(
SearchRevisionsAction(querier=querier)
)
return AdminSearchRevisionsPayload(
items=[self._revision_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
async def admin_search_revisions(
self,
input: AdminSearchRevisionsInput,
) -> AdminSearchRevisionsPayload:
"""Search model revisions without scope (admin, all deployments)."""
querier = self._build_revision_querier(input)
action_result = await self._processors.deployment.search_revisions.wait_for_complete(
SearchRevisionsAction(querier=querier)
)
return AdminSearchRevisionsPayload(
items=[self._revision_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
# ------------------------------------------------------------------
# Route operations
# ------------------------------------------------------------------
async def search_routes(
self,
scope: RouteSearchScope,
input: SearchRoutesInput,
) -> SearchRoutesPayload:
"""Search routes scoped to a specific deployment."""
querier = self._build_route_querier(input, scope=scope)
action_result = await self._processors.deployment.search_routes.wait_for_complete(
SearchRoutesAction(querier=querier)
)
return SearchRoutesPayload(
items=[self._route_info_to_dto(item) for item in action_result.routes],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
# ------------------------------------------------------------------
# Replica operations
# ------------------------------------------------------------------
async def search_replicas(
self,
scope: ReplicaSearchScope,
input: SearchReplicasInput,
) -> SearchReplicasPayload:
"""Search replicas scoped to a specific deployment."""
querier = self._build_replica_querier(input, scope=scope)
action_result = await self._processors.deployment.search_replicas.wait_for_complete(
SearchReplicasAction(querier=querier)
)
return SearchReplicasPayload(
items=[self._replica_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
async def admin_search_replicas(
self,
input: SearchReplicasInput,
) -> SearchReplicasPayload:
"""Search replicas without scope (admin, all deployments)."""
querier = self._build_replica_querier(input)
action_result = await self._processors.deployment.search_replicas.wait_for_complete(
SearchReplicasAction(querier=querier)
)
return SearchReplicasPayload(
items=[self._replica_data_to_dto(item) for item in action_result.data],
total_count=action_result.total_count,
has_next_page=action_result.has_next_page,
has_previous_page=action_result.has_previous_page,
)
async def get_replica(self, replica_id: UUID) -> ReplicaNode | None:
"""Retrieve a single replica by ID."""
action_result = await self._processors.deployment.get_replica_by_id.wait_for_complete(
GetReplicaByIdAction(replica_id=replica_id)
)
if action_result.data is None:
return None
return self._replica_data_to_dto(action_result.data)
async def update_route_traffic(
self,
route_id: UUID,
traffic_status: RouteTrafficStatus,
) -> RouteNode:
"""Update the traffic status of a route."""
action_result = (
await self._processors.deployment.update_route_traffic_status.wait_for_complete(
UpdateRouteTrafficStatusAction(
route_id=route_id,
traffic_status=ManagerRouteTrafficStatus(traffic_status.value),
)
)
)
return self._route_info_to_dto(action_result.route)
# ------------------------------------------------------------------
# Batch load methods for DataLoader use
# ------------------------------------------------------------------
async def batch_load_by_ids(
self,
deployment_ids: Sequence[uuid.UUID],
) -> list[DeploymentNode | None]:
"""Batch load deployments by ID for DataLoader use.
Returns DeploymentNode DTOs in the same order as the input deployment_ids list.
"""
if not deployment_ids:
return []
querier = BatchQuerier(
pagination=OffsetPagination(limit=len(deployment_ids)),
conditions=[DeploymentConditions.by_ids(deployment_ids)],
)
action_result = await self._processors.deployment.search_deployments.wait_for_complete(
SearchDeploymentsAction(querier=querier)
)
deployment_map = {
data.id: self._deployment_data_to_dto(data) for data in action_result.data
}
return [deployment_map.get(deployment_id) for deployment_id in deployment_ids]
async def batch_load_revisions_by_ids(
self,
revision_ids: Sequence[uuid.UUID],
) -> list[RevisionNode | None]:
"""Batch load revisions by ID for DataLoader use.
Returns RevisionNode DTOs in the same order as the input revision_ids list.
"""
if not revision_ids:
return []
querier = BatchQuerier(
pagination=OffsetPagination(limit=len(revision_ids)),
conditions=[RevisionConditions.by_ids(revision_ids)],
)
action_result = await self._processors.deployment.search_revisions.wait_for_complete(
SearchRevisionsAction(querier=querier)
)
revision_map = {data.id: self._revision_data_to_dto(data) for data in action_result.data}
return [revision_map.get(revision_id) for revision_id in revision_ids]
async def batch_load_replicas_by_ids(
self,
replica_ids: Sequence[uuid.UUID],
) -> list[ReplicaNode | None]:
"""Batch load replicas by ID for DataLoader use.
Returns ReplicaNode DTOs in the same order as the input replica_ids list.