-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathrow.py
More file actions
2045 lines (1872 loc) · 72.8 KB
/
row.py
File metadata and controls
2045 lines (1872 loc) · 72.8 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
from __future__ import annotations
import asyncio
import enum
import logging
from collections.abc import AsyncIterator, Callable, Iterable, Mapping, Sequence
from contextlib import asynccontextmanager as actxmgr
from dataclasses import dataclass, field
from datetime import datetime
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Self,
cast,
override,
)
from uuid import UUID
import aiotools
import sqlalchemy as sa
import yarl
from dateutil.tz import tzutc
from sqlalchemy.dialects import postgresql as pgsql
from sqlalchemy.ext.asyncio import AsyncConnection as SAConnection
from sqlalchemy.ext.asyncio import AsyncSession as SASession
from sqlalchemy.orm import (
Mapped,
contains_eager,
foreign,
joinedload,
load_only,
mapped_column,
noload,
relationship,
selectinload,
)
from sqlalchemy.orm.strategy_options import _AbstractLoad
from ai.backend.common.defs.session import SESSION_PRIORITY_DEFAULT
from ai.backend.common.exception import BackendAIError
from ai.backend.common.types import (
AccessKey,
ClusterMode,
KernelId,
ResourceSlot,
SessionId,
SessionResult,
SessionTypes,
VFolderMount,
)
from ai.backend.logging import BraceStyleAdapter
from ai.backend.manager.data.kernel.types import KernelStatus
from ai.backend.manager.data.session.types import (
ImageSpec,
MountSpec,
ResourceSpec,
SessionData,
SessionExecution,
SessionIdentity,
SessionInfo,
SessionLifecycle,
SessionMetadata,
SessionMetrics,
SessionNetwork,
SessionStatus,
)
from ai.backend.manager.data.user.types import UserData
from ai.backend.manager.defs import DEFAULT_ROLE
from ai.backend.manager.errors.kernel import (
KernelCreationFailed,
KernelDestructionFailed,
KernelExecutionFailed,
KernelNotFound,
KernelRestartFailed,
MainKernelNotFound,
SessionNotFound,
TooManyKernelsFound,
TooManySessionsMatched,
)
from ai.backend.manager.exceptions import AgentError
from ai.backend.manager.models.base import (
GUID,
Base,
EnumType,
ResourceSlotColumn,
SessionIDColumnType,
StrEnumType,
StructuredJSONObjectListColumn,
URLColumn,
)
from ai.backend.manager.models.group import GroupRow
from ai.backend.manager.models.image import ImageRow
from ai.backend.manager.models.kernel import KernelRow
from ai.backend.manager.models.minilang.queryfilter import FieldSpecType, QueryFilterParser
from ai.backend.manager.models.network import NetworkRow, NetworkType
from ai.backend.manager.models.rbac import (
AbstractPermissionContext,
AbstractPermissionContextBuilder,
DomainScope,
ProjectScope,
ScopeType,
get_predefined_roles_in_scope,
)
from ai.backend.manager.models.rbac import (
UserScope as UserRBACScope,
)
from ai.backend.manager.models.rbac.context import ClientContext
from ai.backend.manager.models.rbac.permission_defs import ComputeSessionPermission
from ai.backend.manager.models.resource_slot import ResourceAllocationRow
from ai.backend.manager.models.routing import RoutingRow
from ai.backend.manager.models.types import (
QueryCondition,
QueryOption,
)
from ai.backend.manager.models.utils import (
ExtendedAsyncSAEngine,
JSONCoalesceExpr,
execute_with_retry,
execute_with_txn_retry,
sql_json_merge,
)
if TYPE_CHECKING:
from ai.backend.manager.models.domain import DomainRow
from ai.backend.manager.models.keypair import KeyPairRow
from ai.backend.manager.models.scaling_group import ScalingGroupRow
from ai.backend.manager.models.user import UserRow
log = BraceStyleAdapter(logging.getLogger(__spec__.name))
__all__ = (
"AGENT_RESOURCE_OCCUPYING_SESSION_STATUSES",
"ALLOWED_IMAGE_ROLES_FOR_SESSION_TYPE",
"DEAD_SESSION_STATUSES",
"PRIVATE_SESSION_TYPES",
"SESSION_STATUS_TRANSITION_MAP",
"USER_RESOURCE_OCCUPYING_SESSION_STATUSES",
"KernelLoadingStrategy",
"SessionDependencyRow",
"SessionRow",
"check_all_dependencies",
"determine_session_status_by_kernels",
"handle_session_exception",
)
log = BraceStyleAdapter(logging.getLogger("ai.backend.manager.models.session"))
FOLLOWING_SESSION_STATUSES = (
# Session statuses that need to wait all kernels belonging to the session
SessionStatus.PREPARED,
SessionStatus.RUNNING,
SessionStatus.TERMINATED,
)
LEADING_SESSION_STATUSES = tuple(
# Session statuses that declare first, do not need to wait any sibling kernel
s
for s in SessionStatus
if s not in FOLLOWING_SESSION_STATUSES
)
DEAD_SESSION_STATUSES = frozenset([
SessionStatus.CANCELLED,
SessionStatus.TERMINATED,
])
# statuses to consider when calculating current resource usage
AGENT_RESOURCE_OCCUPYING_SESSION_STATUSES = tuple(
e
for e in SessionStatus
if e
not in (
SessionStatus.TERMINATED,
SessionStatus.PENDING,
SessionStatus.CANCELLED,
)
)
# statuses that occupy user resources
# these statuses are used to calculate user resource usage
USER_RESOURCE_OCCUPYING_SESSION_STATUSES = tuple(
e
for e in SessionStatus
if e
not in (
SessionStatus.TERMINATED,
SessionStatus.PENDING,
SessionStatus.CANCELLED,
)
)
PRIVATE_SESSION_TYPES = (SessionTypes.SYSTEM,)
OP_EXC = {
"create_session": KernelCreationFailed,
"restart_session": KernelRestartFailed,
"destroy_session": KernelDestructionFailed,
"execute": KernelExecutionFailed,
"shutdown_service": KernelExecutionFailed,
"upload_file": KernelExecutionFailed,
"download_file": KernelExecutionFailed,
"download_single": KernelExecutionFailed,
"list_files": KernelExecutionFailed,
"get_logs_from_agent": KernelExecutionFailed,
"refresh_session": KernelExecutionFailed,
"commit_session": KernelExecutionFailed,
"commit_session_to_file": KernelExecutionFailed,
"trigger_batch_execution": KernelExecutionFailed,
}
KERNEL_SESSION_STATUS_MAPPING: Mapping[KernelStatus, SessionStatus] = {
KernelStatus.PENDING: SessionStatus.PENDING,
KernelStatus.SCHEDULED: SessionStatus.SCHEDULED,
KernelStatus.PREPARING: SessionStatus.PREPARING,
KernelStatus.BUILDING: SessionStatus.PREPARING,
KernelStatus.PULLING: SessionStatus.PULLING,
KernelStatus.PREPARED: SessionStatus.PREPARED,
KernelStatus.CREATING: SessionStatus.CREATING,
KernelStatus.RUNNING: SessionStatus.RUNNING,
KernelStatus.RESTARTING: SessionStatus.RESTARTING,
KernelStatus.RESIZING: SessionStatus.RUNNING,
KernelStatus.SUSPENDED: SessionStatus.ERROR,
KernelStatus.TERMINATING: SessionStatus.TERMINATING,
KernelStatus.TERMINATED: SessionStatus.TERMINATED,
KernelStatus.ERROR: SessionStatus.ERROR,
KernelStatus.CANCELLED: SessionStatus.CANCELLED,
}
SESSION_KERNEL_STATUS_MAPPING: Mapping[SessionStatus, KernelStatus] = {
SessionStatus.PENDING: KernelStatus.PENDING,
SessionStatus.SCHEDULED: KernelStatus.SCHEDULED,
SessionStatus.PREPARING: KernelStatus.PREPARING,
SessionStatus.PULLING: KernelStatus.PULLING,
SessionStatus.PREPARED: KernelStatus.PREPARED,
SessionStatus.CREATING: KernelStatus.CREATING,
SessionStatus.RUNNING: KernelStatus.RUNNING,
SessionStatus.RESTARTING: KernelStatus.RESTARTING,
SessionStatus.TERMINATING: KernelStatus.TERMINATING,
SessionStatus.TERMINATED: KernelStatus.TERMINATED,
SessionStatus.ERROR: KernelStatus.ERROR,
SessionStatus.CANCELLED: KernelStatus.CANCELLED,
}
SESSION_STATUS_TRANSITION_MAP: Mapping[SessionStatus, set[SessionStatus]] = {
SessionStatus.PENDING: {
SessionStatus.SCHEDULED,
SessionStatus.ERROR,
SessionStatus.CANCELLED,
},
SessionStatus.SCHEDULED: {
SessionStatus.PREPARING,
SessionStatus.PULLING,
SessionStatus.PREPARED,
SessionStatus.ERROR,
SessionStatus.CANCELLED,
},
SessionStatus.PREPARING: {
SessionStatus.PULLING,
SessionStatus.PREPARED,
SessionStatus.ERROR,
SessionStatus.CANCELLED,
},
SessionStatus.PULLING: {
SessionStatus.PREPARED,
SessionStatus.ERROR,
SessionStatus.CANCELLED,
},
SessionStatus.PREPARED: {
SessionStatus.PREPARING,
SessionStatus.ERROR,
SessionStatus.CANCELLED,
},
SessionStatus.CREATING: {
SessionStatus.RUNNING,
SessionStatus.ERROR,
SessionStatus.CANCELLED,
},
SessionStatus.RUNNING: {
SessionStatus.RESTARTING,
SessionStatus.RUNNING_DEGRADED,
SessionStatus.TERMINATING,
SessionStatus.TERMINATED,
SessionStatus.ERROR,
},
SessionStatus.RESTARTING: {
SessionStatus.RUNNING,
SessionStatus.RUNNING_DEGRADED,
SessionStatus.TERMINATING,
SessionStatus.TERMINATED,
SessionStatus.ERROR,
},
SessionStatus.RUNNING_DEGRADED: {
SessionStatus.RUNNING,
SessionStatus.TERMINATING,
SessionStatus.TERMINATED,
SessionStatus.ERROR,
},
SessionStatus.TERMINATING: {SessionStatus.TERMINATED, SessionStatus.ERROR},
SessionStatus.TERMINATED: set(),
SessionStatus.ERROR: {SessionStatus.TERMINATING, SessionStatus.TERMINATED},
SessionStatus.CANCELLED: set(),
}
# TODO:
def determine_session_status_by_kernels(kernels: Sequence[KernelRow]) -> SessionStatus:
if not kernels:
raise KernelNotFound
candidate = KERNEL_SESSION_STATUS_MAPPING[kernels[0].status]
if len(kernels) == 1:
return candidate
for k in kernels:
match k.status:
case KernelStatus.ERROR:
# If any kernel status is ERROR, determines session status as ERROR
return SessionStatus.ERROR
case (
KernelStatus.BUILDING
| KernelStatus.RESTARTING
| KernelStatus.RESIZING
| KernelStatus.SUSPENDED
):
raise RuntimeError("Status not used.")
match candidate:
case SessionStatus.PENDING:
match k.status:
case KernelStatus.PENDING:
continue
case KernelStatus.CANCELLED:
candidate = SessionStatus.CANCELLED
case _:
return SessionStatus.ERROR
case SessionStatus.SCHEDULED:
match k.status:
case KernelStatus.SCHEDULED | KernelStatus.PREPARED:
continue
case KernelStatus.CANCELLED:
candidate = SessionStatus.CANCELLED
case KernelStatus.PULLING:
candidate = SessionStatus.PULLING
case _:
return SessionStatus.ERROR
case SessionStatus.PREPARING:
match k.status:
case KernelStatus.PREPARING | KernelStatus.PREPARED:
continue
case KernelStatus.PULLING:
candidate = SessionStatus.PULLING
case KernelStatus.CANCELLED:
candidate = SessionStatus.CANCELLED
case _:
return SessionStatus.ERROR
case SessionStatus.PULLING:
match k.status:
case KernelStatus.PULLING | KernelStatus.PREPARING | KernelStatus.PREPARED:
continue
case KernelStatus.CANCELLED:
candidate = SessionStatus.CANCELLED
case _:
return SessionStatus.ERROR
case SessionStatus.PREPARED:
match k.status:
case KernelStatus.PREPARED:
continue
case KernelStatus.PREPARING:
candidate = SessionStatus.PREPARING
case KernelStatus.PULLING:
candidate = SessionStatus.PULLING
case KernelStatus.CANCELLED:
candidate = SessionStatus.CANCELLED
case _:
return SessionStatus.ERROR
case SessionStatus.CREATING:
match k.status:
case KernelStatus.CREATING | KernelStatus.RUNNING:
continue
case KernelStatus.CANCELLED:
candidate = SessionStatus.CANCELLED
case _:
# Set status to ERROR if any kernel is in exceptional state
return SessionStatus.ERROR
case SessionStatus.CANCELLED:
match k.status:
case (
KernelStatus.CANCELLED
| KernelStatus.PENDING
| KernelStatus.SCHEDULED
| KernelStatus.PREPARING
| KernelStatus.PULLING
| KernelStatus.PREPARED
):
continue
case _:
return SessionStatus.ERROR
case SessionStatus.RUNNING:
match k.status:
case KernelStatus.RUNNING:
continue
case KernelStatus.CREATING:
candidate = SessionStatus.CREATING
case _:
return SessionStatus.ERROR
case SessionStatus.TERMINATING:
match k.status:
case KernelStatus.TERMINATING | KernelStatus.TERMINATED:
continue
case _:
return SessionStatus.ERROR
case SessionStatus.TERMINATED:
match k.status:
case KernelStatus.TERMINATED:
continue
case KernelStatus.TERMINATING:
candidate = SessionStatus.TERMINATING
case _:
return SessionStatus.ERROR
case SessionStatus.RESTARTING | SessionStatus.RUNNING_DEGRADED:
raise RuntimeError("Status not used.")
return candidate
@actxmgr
async def handle_session_exception(
db: ExtendedAsyncSAEngine,
op: str,
session_id: SessionId,
error_callback: Callable[[], Any] | None = None,
cancellation_callback: Callable[[], Any] | None = None,
set_error: bool = False,
) -> AsyncIterator[None]:
exc_class = OP_EXC[op]
try:
yield
except TimeoutError:
if set_error:
await SessionRow.set_session_status(
db,
session_id,
SessionStatus.ERROR,
reason=f"operation-timeout ({op})",
)
if error_callback:
await error_callback()
raise exc_class("TIMEOUT") from None
except asyncio.CancelledError:
if cancellation_callback:
await cancellation_callback()
raise
except AgentError as e:
if set_error:
await SessionRow.set_session_status(
db,
session_id,
SessionStatus.ERROR,
reason=f"agent-error ({e!r})",
status_data={
"error": {
"src": "agent",
"agent_id": e.agent_id,
"name": e.exc_name,
"repr": e.exc_repr,
},
},
)
if error_callback:
await error_callback()
raise exc_class("FAILURE", e) from None
except BackendAIError:
# silently re-raise to make them handled by gateway http handlers
raise
except Exception as e:
if set_error:
await SessionRow.set_session_status(
db,
session_id,
SessionStatus.ERROR,
reason=f"other-error ({e!r})",
status_data={
"error": {
"src": "other",
"name": e.__class__.__name__,
"repr": repr(e),
},
},
)
if error_callback:
await error_callback()
raise
def _build_session_fetch_query(
base_cond: Any,
access_key: AccessKey | None = None,
*,
allow_stale: bool = True,
for_update: bool = False,
do_ordering: bool = False,
max_matches: int | None = None,
eager_loading_op: Sequence[_AbstractLoad] | None = None,
) -> sa.sql.Select[Any]:
cond = base_cond
if access_key:
cond = cond & (SessionRow.access_key == access_key)
if not allow_stale:
cond = cond & (~SessionRow.status.in_(DEAD_SESSION_STATUSES))
query = (
sa.select(SessionRow)
.where(cond)
.order_by(sa.desc(SessionRow.created_at))
.execution_options(populate_existing=True)
)
if max_matches is not None:
query = query.limit(max_matches).offset(0)
if for_update:
query = query.with_for_update()
if do_ordering:
query = query.order_by(SessionRow.created_at)
if eager_loading_op is not None:
query = query.options(*eager_loading_op)
return query
async def _match_sessions_by_id(
db_session: SASession,
session_id_or_list: SessionId | list[SessionId],
access_key: AccessKey | None = None,
*,
allow_prefix: bool = False,
allow_stale: bool = True,
for_update: bool = False,
max_matches: int | None = None,
eager_loading_op: Sequence[_AbstractLoad] | None = None,
) -> Sequence[SessionRow]:
cond: sa.sql.elements.ColumnElement[bool]
if isinstance(session_id_or_list, list):
cond = SessionRow.id.in_(session_id_or_list)
else:
if allow_prefix:
cond = sa.sql.expression.cast(SessionRow.id, sa.String).like(f"{session_id_or_list}%")
else:
cond = SessionRow.id == session_id_or_list
query = _build_session_fetch_query(
cond,
access_key,
max_matches=max_matches,
allow_stale=allow_stale,
for_update=for_update,
eager_loading_op=eager_loading_op,
)
result = await db_session.execute(query)
return result.scalars().all()
async def _match_sessions_by_name(
db_session: SASession,
session_name: str,
access_key: AccessKey,
*,
allow_prefix: bool = False,
allow_stale: bool = True,
for_update: bool = False,
max_matches: int | None = None,
eager_loading_op: Sequence[_AbstractLoad] | None = None,
) -> Sequence[SessionRow]:
cond: sa.sql.elements.ColumnElement[bool]
if allow_prefix:
cond = sa.sql.expression.cast(SessionRow.name, sa.String).like(f"{session_name}%")
else:
cond = SessionRow.name == session_name
query = _build_session_fetch_query(
cond,
access_key,
max_matches=max_matches,
allow_stale=allow_stale,
for_update=for_update,
eager_loading_op=eager_loading_op,
)
result = await db_session.execute(query)
return result.scalars().all()
COMPUTE_CONCURRENCY_USED_KEY_PREFIX = "keypair.concurrency_used."
SYSTEM_CONCURRENCY_USED_KEY_PREFIX = "keypair.sftp_concurrency_used."
@dataclass
class ConcurrencyUsed:
access_key: AccessKey
compute_session_ids: set[SessionId] = field(default_factory=set)
system_session_ids: set[SessionId] = field(default_factory=set)
@property
def compute_concurrency_used_key(self) -> str:
return f"{COMPUTE_CONCURRENCY_USED_KEY_PREFIX}{self.access_key}"
@property
def system_concurrency_used_key(self) -> str:
return f"{SYSTEM_CONCURRENCY_USED_KEY_PREFIX}{self.access_key}"
def to_cnt_map(self) -> Mapping[str, int]:
return {
self.compute_concurrency_used_key: len(self.compute_session_ids),
self.system_concurrency_used_key: len(self.system_session_ids),
}
class SessionOp(enum.StrEnum):
CREATE = "create_session"
DESTROY = "destroy_session"
RESTART = "restart_session"
EXECUTE = "execute"
REFRESH = "refresh_session"
SHUTDOWN_SERVICE = "shutdown_service"
UPLOAD_FILE = "upload_file"
DOWNLOAD_FILE = "download_file"
LIST_FILE = "list_files"
GET_AGENT_LOGS = "get_logs_from_agent"
class KernelLoadingStrategy(enum.StrEnum):
ALL_KERNELS = "all"
MAIN_KERNEL_ONLY = "main"
NONE = "none"
ALLOWED_IMAGE_ROLES_FOR_SESSION_TYPE: Mapping[SessionTypes, tuple[str, ...]] = {
SessionTypes.BATCH: ("COMPUTE",),
SessionTypes.INTERACTIVE: ("COMPUTE",),
SessionTypes.INFERENCE: ("INFERENCE",),
SessionTypes.SYSTEM: ("SYSTEM",),
}
# Defined for avoiding circular import
def _get_keypair_row_join_condition() -> sa.sql.elements.ColumnElement[Any]:
from ai.backend.manager.models.keypair import KeyPairRow
return KeyPairRow.access_key == foreign(SessionRow.access_key)
def _get_user_row_join_condition() -> sa.sql.elements.ColumnElement[Any]:
from ai.backend.manager.models.user import UserRow
return UserRow.uuid == foreign(SessionRow.user_uuid)
class SessionRow(Base): # type: ignore[misc]
__tablename__ = "sessions"
id: Mapped[SessionId] = mapped_column(
"id", SessionIDColumnType, primary_key=True, server_default=sa.text("uuid_generate_v4()")
)
creation_id: Mapped[str | None] = mapped_column(
"creation_id", sa.String(length=32), unique=False, index=False
)
name: Mapped[str | None] = mapped_column(
"name", sa.String(length=128), unique=False, index=True
)
session_type: Mapped[SessionTypes] = mapped_column(
"session_type",
StrEnumType(SessionTypes, use_name=True),
index=True,
nullable=False, # previously sess_type
default=SessionTypes.INTERACTIVE,
server_default=SessionTypes.INTERACTIVE.name,
)
priority: Mapped[int] = mapped_column(
"priority",
sa.Integer(),
nullable=False,
default=SESSION_PRIORITY_DEFAULT,
index=True,
)
is_preemptible: Mapped[bool] = mapped_column(
"is_preemptible",
sa.Boolean(),
nullable=False,
default=True,
server_default=sa.text("true"),
)
cluster_mode: Mapped[str] = mapped_column(
"cluster_mode",
sa.String(length=16),
nullable=False,
default=ClusterMode.SINGLE_NODE,
server_default=ClusterMode.SINGLE_NODE.name,
)
cluster_size: Mapped[int] = mapped_column("cluster_size", sa.Integer, nullable=False, default=1)
agent_ids: Mapped[list[str] | None] = mapped_column(
"agent_ids", sa.ARRAY(sa.String), nullable=True
)
designated_agent_ids: Mapped[list[str] | None] = mapped_column(
"designated_agent_ids", sa.ARRAY(sa.String), nullable=True
)
kernels: Mapped[list[KernelRow]] = relationship("KernelRow", back_populates="session")
# Resource ownership
scaling_group_name: Mapped[str | None] = mapped_column(
"scaling_group_name", sa.ForeignKey("scaling_groups.name"), index=True, nullable=True
)
scaling_group: Mapped[ScalingGroupRow | None] = relationship(
"ScalingGroupRow", back_populates="sessions"
)
target_sgroup_names: Mapped[list[str] | None] = mapped_column(
"target_sgroup_names",
sa.ARRAY(sa.String(length=64)),
default=None,
server_default="{}",
nullable=True,
)
domain_name: Mapped[str] = mapped_column(
"domain_name", sa.String(length=64), sa.ForeignKey("domains.name"), nullable=False
)
domain: Mapped[DomainRow] = relationship("DomainRow", back_populates="sessions")
group_id: Mapped[UUID] = mapped_column(
"group_id", GUID, sa.ForeignKey("groups.id"), nullable=False
)
group: Mapped[GroupRow] = relationship("GroupRow", back_populates="sessions")
user_uuid: Mapped[UUID] = mapped_column(
"user_uuid", GUID, server_default=sa.text("uuid_generate_v4()"), nullable=False
)
user: Mapped[UserRow] = relationship(
"UserRow",
primaryjoin=_get_user_row_join_condition,
back_populates="sessions",
foreign_keys=[user_uuid],
)
access_key: Mapped[str | None] = mapped_column("access_key", sa.String(length=20))
access_key_row: Mapped[KeyPairRow | None] = relationship(
"KeyPairRow",
primaryjoin=_get_keypair_row_join_condition,
back_populates="sessions",
foreign_keys=[access_key],
)
# `image` column is identical to kernels `image` column.
images: Mapped[list[str] | None] = mapped_column("images", sa.ARRAY(sa.String), nullable=True)
tag: Mapped[str | None] = mapped_column("tag", sa.String(length=64), nullable=True)
# Resource occupation
# DEPRECATED (Phase 3, BA-4308): No longer written to.
# Resource allocations are now tracked by the normalized
# resource_allocations / agent_resources tables.
# Retained for historical audit; will be dropped in a future major version.
occupying_slots: Mapped[ResourceSlot] = mapped_column(
"occupying_slots", ResourceSlotColumn(), nullable=False
)
requested_slots: Mapped[ResourceSlot] = mapped_column(
"requested_slots", ResourceSlotColumn(), nullable=False
)
vfolder_mounts: Mapped[list[VFolderMount] | None] = mapped_column(
"vfolder_mounts", StructuredJSONObjectListColumn(VFolderMount), nullable=True
)
environ: Mapped[dict[str, Any] | None] = mapped_column(
"environ", pgsql.JSONB(), nullable=True, default={}
)
bootstrap_script: Mapped[str | None] = mapped_column(
"bootstrap_script", sa.String(length=16 * 1024), nullable=True
)
use_host_network: Mapped[bool] = mapped_column(
"use_host_network", sa.Boolean(), default=False, nullable=False
)
# Lifecycle
# Deprecated: Not used anymore
timeout: Mapped[int | None] = mapped_column("timeout", sa.BigInteger(), nullable=True)
batch_timeout: Mapped[int | None] = mapped_column(
"batch_timeout", sa.BigInteger(), nullable=True
) # Used to set timeout of batch sessions
created_at: Mapped[datetime | None] = mapped_column(
"created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), index=True
)
terminated_at: Mapped[datetime | None] = mapped_column(
"terminated_at", sa.DateTime(timezone=True), nullable=True, default=sa.null(), index=True
)
starts_at: Mapped[datetime | None] = mapped_column(
"starts_at", sa.DateTime(timezone=True), nullable=True, default=sa.null()
)
status: Mapped[SessionStatus] = mapped_column(
"status",
StrEnumType(SessionStatus),
default=SessionStatus.PENDING,
server_default=SessionStatus.PENDING.name,
nullable=False,
index=True,
)
status_info: Mapped[str | None] = mapped_column(
"status_info", sa.Unicode(), nullable=True, default=sa.null()
)
status_data: Mapped[dict[str, Any] | None] = mapped_column(
"status_data", pgsql.JSONB(), nullable=True, default=sa.null()
)
# status_data contains a JSON object that contains detailed data for the last status change.
# During scheduling (as PENDING + ("no-available-instances" | "predicate-checks-failed")):
# {
# "scheduler": {
# // shceudler attempt information
# // NOTE: the whole field may be NULL before the first attempt!
# "retries": 5,
# // the number of scheudling attempts (used to avoid HoL blocking as well)
# "last_try": "2021-05-01T12:34:56.123456+09:00",
# // an ISO 8601 formatted timestamp of the last attempt
# "failed_predicates": [
# { "name": "concurrency", "msg": "You cannot run more than 30 concurrent sessions." },
# // see the manager.scheduler.predicates module for possible messages
# ...
# ],
# "passed_predicates": [ {"name": "reserved_time"}, ... ], // names only
# }
# }
#
# While running: the field is NULL.
#
# After termination:
# {
# "kernel": {
# // termination info for the individual kernel
# "exit_code": 123,
# // maybe null during termination
# },
# "session": {
# // termination info for the session
# "status": "terminating" | "terminated"
# // "terminated" means all kernels that belong to the same session has terminated.
# // used to prevent duplication of SessionTerminatedEvent
# }
# }
status_history: Mapped[dict[str, Any] | None] = mapped_column(
"status_history", pgsql.JSONB(), nullable=True, default=sa.null()
)
callback_url: Mapped[yarl.URL | None] = mapped_column(
"callback_url", URLColumn, nullable=True, default=sa.null()
)
startup_command: Mapped[str | None] = mapped_column("startup_command", sa.Text, nullable=True)
result: Mapped[SessionResult] = mapped_column(
"result",
EnumType(SessionResult),
default=SessionResult.UNDEFINED,
server_default=SessionResult.UNDEFINED.name,
nullable=False,
index=True,
)
# Resource metrics measured upon termination
num_queries: Mapped[int | None] = mapped_column("num_queries", sa.BigInteger(), default=0)
last_stat: Mapped[dict[str, Any] | None] = mapped_column(
"last_stat", pgsql.JSONB(), nullable=True, default=sa.null()
)
network_type: Mapped[NetworkType | None] = mapped_column(
"network_type", StrEnumType(NetworkType), nullable=True
)
"""Setting this column to null means this session does not utilize inter-container networking feature"""
network_id: Mapped[str | None] = mapped_column(
"network_id", sa.String(length=128), nullable=True
)
"""
Depending on the network_type, this column may contain a network ID or other information.
Use `get_network_ref()` method to reveal actual network ref (generated by network plugin).
"""
routing: Mapped[list[RoutingRow]] = relationship("RoutingRow", back_populates="session_row")
__table_args__ = (
# indexing
sa.Index(
"ix_sessions_updated_order",
sa.func.greatest(
"created_at",
"terminated_at",
),
unique=False,
),
sa.Index("ix_sessions_vfolder_mounts", "vfolder_mounts", postgresql_using="gin"),
sa.Index("ix_session_status_with_priority", "status", "priority"),
# Unique index for session names per user excluding terminal statuses
sa.Index(
"ix_sessions_unique_name_per_user_nonterminal",
"name",
"user_uuid",
unique=True,
postgresql_where=sa.text("status NOT IN ('ERROR', 'TERMINATED', 'CANCELLED')"),
),
)
@classmethod
def kernel_load_option(cls, already_joined: bool = False) -> _AbstractLoad:
return selectinload(cls.kernels) if not already_joined else contains_eager(cls.kernels)
@classmethod
def user_load_option(cls, already_joined: bool = False) -> _AbstractLoad:
return joinedload(cls.user) if not already_joined else contains_eager(cls.user)
@classmethod
def project_load_option(cls, already_joined: bool = False) -> _AbstractLoad:
return joinedload(cls.group) if not already_joined else contains_eager(cls.group)
@classmethod
def from_dataclass(cls, session_data: SessionData) -> SessionRow:
vfolder_mounts = []
if session_data.vfolder_mounts:
vfolder_mounts = [
VFolderMount.from_dataclass(mount) for mount in session_data.vfolder_mounts
]
instance = cls(
name=session_data.name,
session_type=session_data.session_type,
priority=session_data.priority,
cluster_mode=session_data.cluster_mode,
cluster_size=session_data.cluster_size,
agent_ids=session_data.agent_ids,
scaling_group_name=session_data.scaling_group_name,
target_sgroup_names=session_data.target_sgroup_names,
domain_name=session_data.domain_name,
group_id=session_data.group_id,
user_uuid=session_data.user_uuid,
access_key=session_data.access_key,
images=session_data.images,
tag=session_data.tag,
occupying_slots=session_data.occupying_slots,
requested_slots=session_data.requested_slots,
vfolder_mounts=vfolder_mounts,
environ=session_data.environ,
bootstrap_script=session_data.bootstrap_script,
use_host_network=session_data.use_host_network,
timeout=session_data.timeout,
batch_timeout=session_data.batch_timeout,
status_history={},
status=session_data.status,
status_info=session_data.status_info,
status_data=session_data.status_data,
callback_url=session_data.callback_url,
startup_command=session_data.startup_command,
result=session_data.result,
num_queries=session_data.num_queries,
last_stat=session_data.last_stat,
network_type=session_data.network_type,
network_id=session_data.network_id,
created_at=session_data.created_at,
terminated_at=session_data.terminated_at,
starts_at=session_data.starts_at,
)
instance.id = SessionId(session_data.id)
return instance
def to_dataclass(self, owner: UserData | None = None) -> SessionData:
return SessionData(
id=self.id,
creation_id=self.creation_id,
name=self.name,
session_type=self.session_type,
priority=self.priority,
is_preemptible=self.is_preemptible,
cluster_mode=ClusterMode(self.cluster_mode),
cluster_size=self.cluster_size,
agent_ids=self.agent_ids,
scaling_group_name=self.scaling_group_name,
target_sgroup_names=self.target_sgroup_names,
domain_name=self.domain_name,
group_id=self.group_id,
user_uuid=self.user_uuid,
access_key=AccessKey(self.access_key) if self.access_key else None,
images=self.images,
tag=self.tag,
occupying_slots=self.occupying_slots,
requested_slots=self.requested_slots,
vfolder_mounts=[mount.to_dataclass() for mount in self.vfolder_mounts]
if self.vfolder_mounts
else None,
environ=self.environ,
bootstrap_script=self.bootstrap_script,
use_host_network=self.use_host_network,
timeout=self.timeout,
batch_timeout=self.batch_timeout,
created_at=self.created_at or datetime.now(tzutc()),
terminated_at=self.terminated_at,
starts_at=self.starts_at,
status=self.status,
status_info=self.status_info,
status_data=self.status_data,
status_history=self.status_history,
callback_url=str(self.callback_url) if self.callback_url else None,
startup_command=self.startup_command,
result=self.result,
num_queries=self.num_queries or 0,
last_stat=self.last_stat,
network_type=self.network_type,
network_id=self.network_id,
service_ports=str(self.main_kernel.service_ports)
if self.main_kernel.service_ports