-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathservice.py
More file actions
2603 lines (2285 loc) · 105 KB
/
service.py
File metadata and controls
2603 lines (2285 loc) · 105 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
# Copyright The Marin Authors
# SPDX-License-Identifier: Apache-2.0
"""Controller RPC service implementation handling job, task, and worker operations.
The controller expands jobs into tasks at submission time (a job with replicas=N
creates N tasks). Tasks are the unit of scheduling and execution. Job state is
aggregated from task states.
"""
import json
import logging
import re
import secrets
import uuid
import dataclasses
from dataclasses import dataclass
from typing import Any, Protocol
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from connectrpc.request import RequestContext
from iris.cluster.constraints import Constraint, constraints_from_resources, merge_constraints, validate_tpu_request
from iris.cluster.redaction import redact_request_env_vars
from iris.cluster.controller.codec import (
constraints_from_json,
proto_from_json,
reservation_entries_from_json,
resource_spec_from_scalars,
)
from iris.cluster.controller.budget import (
UserTask,
compute_effective_band,
compute_user_spend,
interleave_by_user,
resource_value,
)
from iris.rpc.proto_utils import priority_band_name
from iris.cluster.controller.auth import (
DEFAULT_JWT_TTL_SECONDS,
ControllerAuth,
create_api_key,
list_api_keys,
revoke_api_key,
revoke_login_keys_for_user,
)
from iris.rpc.auth import (
AuthzAction,
authorize,
authorize_resource_owner,
get_verified_identity,
get_verified_user,
require_identity,
)
from iris.cluster.bundle import BundleStore
from iris.cluster.controller.db import (
ACTIVE_TASK_STATES,
ControllerDB,
EndpointQuery,
TaskJobSummary,
UserStats,
attempt_is_worker_failure,
running_tasks_by_worker,
task_row_can_be_scheduled,
)
from iris.cluster.controller.schema import (
API_KEY_PROJECTION,
ATTEMPT_PROJECTION,
JOB_CONFIG_JOIN,
JOB_DETAIL_PROJECTION,
JOB_ROW_PROJECTION,
TASK_DETAIL_PROJECTION,
TASK_ROW_PROJECTION,
TXN_ACTION_PROJECTION,
WORKER_DETAIL_PROJECTION,
AttemptRow,
EndpointRow,
JobDetailRow,
JobRow,
TaskDetailRow,
TransactionActionRow,
WorkerDetailRow,
WorkerRow,
tasks_with_attempts,
)
from iris.cluster.controller.autoscaler.status import PendingHint, build_job_pending_hints
from iris.cluster.controller.query import execute_raw_query
from iris.rpc import query_pb2
from iris.cluster.controller.scheduler import SchedulingContext
from iris.cluster.controller.transitions import ControllerTransitions, TASK_RESOURCE_HISTORY_RETENTION
from iris.cluster.controller.provider import ProviderError
from iris.cluster.log_store import build_log_source, worker_log_key
from iris.cluster.process_status import get_process_status
from iris.cluster.runtime.profile import is_system_target, parse_profile_target, profile_local_process
from iris.cluster.types import (
TERMINAL_JOB_STATES,
TERMINAL_TASK_STATES,
JobName,
WorkerId,
get_gpu_count,
get_tpu_count,
is_job_finished,
)
from iris.log_server.client import LogServiceProxy
from iris.log_server.server import LogServiceImpl
from iris.rpc import logging_pb2, vm_pb2
from iris.rpc import job_pb2
from iris.rpc import controller_pb2
from iris.rpc import worker_pb2
from iris.rpc.proto_utils import job_state_friendly, job_state_name, task_state_name
from iris.time_proto import timestamp_to_proto
from rigging.timing import Timestamp, Timer
logger = logging.getLogger(__name__)
DEFAULT_TRANSACTION_LIMIT = 50
DEFAULT_MAX_TOTAL_LINES = 100000
# Maximum bundle size in bytes (25 MB) - matches client-side limit
MAX_BUNDLE_SIZE_BYTES = 25 * 1024 * 1024
USER_TASK_STATES = (
job_pb2.TASK_STATE_PENDING,
job_pb2.TASK_STATE_ASSIGNED,
job_pb2.TASK_STATE_BUILDING,
job_pb2.TASK_STATE_RUNNING,
job_pb2.TASK_STATE_SUCCEEDED,
job_pb2.TASK_STATE_FAILED,
job_pb2.TASK_STATE_KILLED,
job_pb2.TASK_STATE_UNSCHEDULABLE,
job_pb2.TASK_STATE_WORKER_FAILED,
job_pb2.TASK_STATE_PREEMPTED,
)
USER_JOB_STATES = (
job_pb2.JOB_STATE_PENDING,
job_pb2.JOB_STATE_BUILDING,
job_pb2.JOB_STATE_RUNNING,
job_pb2.JOB_STATE_SUCCEEDED,
job_pb2.JOB_STATE_FAILED,
job_pb2.JOB_STATE_KILLED,
job_pb2.JOB_STATE_WORKER_FAILED,
job_pb2.JOB_STATE_UNSCHEDULABLE,
)
def _current_attempt(task: TaskDetailRow) -> AttemptRow | None:
"""Get the latest attempt for a task detail row."""
if not task.attempts:
return None
return task.attempts[-1]
def _task_worker_id(task: TaskDetailRow) -> WorkerId | None:
"""Get the effective worker_id for a task detail row."""
current = _current_attempt(task)
if current is None:
return task.current_worker_id
return current.worker_id
def _active_worker_id(task: TaskDetailRow) -> WorkerId | None:
"""Get the active worker_id (None for pending tasks)."""
if task.state == job_pb2.TASK_STATE_PENDING:
return None
return _task_worker_id(task)
def task_to_proto(task: TaskDetailRow, worker_address: str = "") -> job_pb2.TaskStatus:
"""Convert a task row to a TaskStatus proto.
Handles attempt conversion and timestamps. resource_usage is NOT populated
here — callers must attach it separately from task_resource_history.
The caller is responsible for resolving worker_address from worker_id if needed.
"""
current_attempt = _current_attempt(task)
attempts = []
for attempt in task.attempts:
proto_attempt = job_pb2.TaskAttempt(
attempt_id=attempt.attempt_id,
worker_id=str(attempt.worker_id) if attempt.worker_id else "",
state=attempt.state,
exit_code=attempt.exit_code or 0,
error=attempt.error or "",
is_worker_failure=attempt_is_worker_failure(attempt.state),
)
if attempt.started_at is not None:
proto_attempt.started_at.CopyFrom(timestamp_to_proto(attempt.started_at))
if attempt.finished_at is not None:
proto_attempt.finished_at.CopyFrom(timestamp_to_proto(attempt.finished_at))
attempts.append(proto_attempt)
active_wid = _active_worker_id(task)
proto = job_pb2.TaskStatus(
task_id=task.task_id.to_wire(),
state=task.state,
worker_id=str(active_wid) if active_wid else "",
worker_address=worker_address or task.current_worker_address or "",
exit_code=task.exit_code or 0,
error=task.error or "",
current_attempt_id=task.current_attempt_id,
attempts=attempts,
)
if current_attempt and current_attempt.started_at:
proto.started_at.CopyFrom(timestamp_to_proto(current_attempt.started_at))
if current_attempt and current_attempt.finished_at:
proto.finished_at.CopyFrom(timestamp_to_proto(current_attempt.finished_at))
if task.container_id:
proto.container_id = task.container_id
# For pending tasks with prior terminal attempts, surface retry context.
if task.state == job_pb2.TASK_STATE_PENDING and task.attempts and task.attempts[-1].state in TERMINAL_TASK_STATES:
last = task.attempts[-1]
proto.pending_reason = (
f"Retrying (attempt {len(task.attempts)}, " f"last: {job_pb2.TaskState.Name(last.state).lower()})"
)
proto.can_be_scheduled = True
return proto
def worker_status_message(w: WorkerDetailRow) -> str:
"""Build a human-readable status message for unhealthy workers."""
if w.healthy:
return ""
if w.consecutive_failures > 0:
age = w.last_heartbeat.age_ms()
return f"Heartbeat timeout ({w.consecutive_failures} failures, last seen {age // 1000}s ago)"
return "Unhealthy (no failures recorded)"
_WORKER_TARGET_PREFIX = "/system/worker/"
def _parse_worker_target(target: str) -> str | None:
"""Extract worker_id from a /system/worker/<worker_id> target.
Returns the worker_id string, or None if the target does not match.
"""
if target.startswith(_WORKER_TARGET_PREFIX):
worker_id = target[len(_WORKER_TARGET_PREFIX) :]
if worker_id:
return worker_id
return None
def _task_state_key(state: int) -> str:
"""Return the lowercase RPC key for a task state enum."""
return task_state_name(state).removeprefix("TASK_STATE_").lower()
def _job_state_key(state: int) -> str:
"""Return the lowercase RPC key for a job state enum."""
return job_state_name(state).removeprefix("JOB_STATE_").lower()
def _active_job_count(job_state_counts: dict[int, int]) -> int:
"""Return the count of non-terminal jobs in a user aggregate."""
return sum(count for state, count in job_state_counts.items() if state not in TERMINAL_JOB_STATES)
def _task_state_counts_for_summary(task_state_counts: dict[int, int]) -> dict[str, int]:
"""Convert enum-keyed task counts to the string-keyed RPC shape."""
counts = {_task_state_key(state): 0 for state in USER_TASK_STATES}
for state, count in task_state_counts.items():
counts[_task_state_key(state)] = count
return counts
def _job_state_counts_for_summary(job_state_counts: dict[int, int]) -> dict[str, int]:
"""Convert enum-keyed job counts to the string-keyed RPC shape."""
counts = {_job_state_key(state): 0 for state in USER_JOB_STATES}
for state, count in job_state_counts.items():
counts[_job_state_key(state)] = count
return counts
# =============================================================================
# DB query helpers — thin wrappers over snapshot() for common read patterns
# =============================================================================
def _read_job(db: ControllerDB, job_id: JobName) -> JobDetailRow | None:
with db.read_snapshot() as q:
return JOB_DETAIL_PROJECTION.decode_one(
q.fetchall(
f"SELECT {JOB_DETAIL_PROJECTION.select_clause()} " f"FROM jobs j {JOB_CONFIG_JOIN} WHERE j.job_id = ?",
(job_id.to_wire(),),
)
)
def _read_task_with_attempts(db: ControllerDB, task_id: JobName) -> TaskDetailRow | None:
task_wire = task_id.to_wire()
with db.read_snapshot() as q:
task = TASK_DETAIL_PROJECTION.decode_one(
q.fetchall(
f"SELECT {TASK_DETAIL_PROJECTION.select_clause()} FROM tasks t WHERE t.task_id = ?",
(task_wire,),
)
)
if task is None:
return None
attempts = ATTEMPT_PROJECTION.decode(
q.fetchall(
f"SELECT {ATTEMPT_PROJECTION.select_clause()} FROM task_attempts ta "
"WHERE ta.task_id = ? ORDER BY ta.attempt_id ASC",
(task_wire,),
),
)
return tasks_with_attempts([task], attempts)[0]
def _read_worker(db: ControllerDB, worker_id: WorkerId) -> WorkerDetailRow | None:
with db.read_snapshot() as q:
return WORKER_DETAIL_PROJECTION.decode_one(
q.fetchall(
f"SELECT {WORKER_DETAIL_PROJECTION.select_clause()} FROM workers w WHERE w.worker_id = ?",
(str(worker_id),),
)
)
def _job_state(db: ControllerDB, job_id: JobName) -> int | None:
"""Fetch only the state column for a job, avoiding proto decode."""
with db.read_snapshot() as q:
row = q.fetchone("SELECT state FROM jobs WHERE job_id = ?", (job_id.to_wire(),))
return int(row[0]) if row else None
def _worker_address(db: ControllerDB, worker_id: WorkerId) -> str | None:
"""Fetch only the address column for a worker, avoiding proto decode."""
with db.read_snapshot() as q:
row = q.fetchone("SELECT address FROM workers WHERE worker_id = ?", (str(worker_id),))
return str(row[0]) if row else None
def _resource_spec_from_job_row(job: Any) -> job_pb2.ResourceSpecProto:
"""Reconstruct a ResourceSpecProto from native job columns."""
return resource_spec_from_scalars(
job.res_cpu_millicores, job.res_memory_bytes, job.res_disk_bytes, job.res_device_json
)
_SNAPSHOT_FIELD_MAP = (
("snapshot_host_cpu_percent", "host_cpu_percent"),
("snapshot_memory_used_bytes", "memory_used_bytes"),
("snapshot_memory_total_bytes", "memory_total_bytes"),
("snapshot_disk_used_bytes", "disk_used_bytes"),
("snapshot_disk_total_bytes", "disk_total_bytes"),
("snapshot_running_task_count", "running_task_count"),
("snapshot_total_process_count", "total_process_count"),
("snapshot_net_recv_bps", "net_recv_bps"),
("snapshot_net_sent_bps", "net_sent_bps"),
)
def _snapshot_row_to_proto(row: Any, timestamp_ms: int | None = None) -> job_pb2.WorkerResourceSnapshot:
"""Reconstruct a WorkerResourceSnapshot proto from scalar columns."""
snap = job_pb2.WorkerResourceSnapshot()
for col, proto_field in _SNAPSHOT_FIELD_MAP:
val = getattr(row, col)
if val is not None:
setattr(snap, proto_field, val)
if timestamp_ms is not None:
snap.timestamp.epoch_ms = timestamp_ms
return snap
def _reconstruct_launch_job_request(job: JobDetailRow) -> controller_pb2.Controller.LaunchJobRequest:
"""Reconstruct a LaunchJobRequest proto from native JobDetailRow columns."""
req = controller_pb2.Controller.LaunchJobRequest(
name=job.name,
bundle_id=job.bundle_id,
max_task_failures=job.max_task_failures,
max_retries_failure=job.max_retries_failure,
max_retries_preemption=job.max_retries_preemption,
replicas=job.num_tasks,
preemption_policy=job.preemption_policy,
existing_job_policy=job.existing_job_policy,
priority_band=job.priority_band,
task_image=job.task_image,
fail_if_exists=job.fail_if_exists,
)
req.entrypoint.CopyFrom(proto_from_json(job.entrypoint_json, job_pb2.RuntimeEntrypoint))
req.environment.CopyFrom(proto_from_json(job.environment_json, job_pb2.EnvironmentConfig))
req.resources.CopyFrom(
resource_spec_from_scalars(job.res_cpu_millicores, job.res_memory_bytes, job.res_disk_bytes, job.res_device_json)
)
for c in constraints_from_json(job.constraints_json):
req.constraints.append(c.to_proto())
for port in json.loads(job.ports_json):
req.ports.append(port)
for arg in json.loads(job.submit_argv_json):
req.submit_argv.append(arg)
if job.has_coscheduling:
req.coscheduling.CopyFrom(job_pb2.CoschedulingConfig(group_by=job.coscheduling_group_by))
if job.scheduling_timeout_ms is not None and job.scheduling_timeout_ms > 0:
req.scheduling_timeout.milliseconds = job.scheduling_timeout_ms
if job.timeout_ms is not None and job.timeout_ms > 0:
req.timeout.milliseconds = job.timeout_ms
if job.reservation_json:
for entry in reservation_entries_from_json(job.reservation_json):
req.reservation.entries.append(entry)
return req
def _worker_metadata_to_proto(worker: WorkerDetailRow) -> job_pb2.WorkerMetadata:
"""Reconstruct a WorkerMetadata proto from scalar columns."""
md = job_pb2.WorkerMetadata(
hostname=worker.md_hostname,
ip_address=worker.md_ip_address,
cpu_count=worker.md_cpu_count,
memory_bytes=worker.md_memory_bytes,
disk_bytes=worker.md_disk_bytes,
tpu_name=worker.md_tpu_name,
tpu_worker_hostnames=worker.md_tpu_worker_hostnames,
tpu_worker_id=worker.md_tpu_worker_id,
tpu_chips_per_host_bounds=worker.md_tpu_chips_per_host_bounds,
gpu_count=worker.md_gpu_count,
gpu_name=worker.md_gpu_name,
gpu_memory_mb=worker.md_gpu_memory_mb,
gce_instance_name=worker.md_gce_instance_name,
gce_zone=worker.md_gce_zone,
git_hash=worker.md_git_hash,
)
if worker.md_device_json and worker.md_device_json != "{}":
md.device.CopyFrom(proto_from_json(worker.md_device_json, job_pb2.DeviceConfig))
# Populate attributes from the worker_attributes table data stored on the row.
for key, value in worker.attributes.items():
av = job_pb2.AttributeValue()
if isinstance(value, str):
av.string_value = value
elif isinstance(value, int):
av.int_value = value
elif isinstance(value, float):
av.float_value = value
md.attributes[key].CopyFrom(av)
return md
def _decode_attribute_value(row: Any) -> tuple[str, str | int | float]:
"""Decode a worker_attributes row into a (key, value) pair."""
vtype = str(row["value_type"])
key = str(row["key"])
if vtype == "str":
return key, str(row["str_value"])
elif vtype == "int":
return key, int(row["int_value"])
elif vtype == "float":
return key, float(row["float_value"])
raise ValueError(f"Unknown attribute value_type: {vtype!r}")
@dataclass(frozen=True)
class _WorkerDetail:
worker: WorkerDetailRow
running_tasks: frozenset[JobName]
resource_history: tuple[job_pb2.WorkerResourceSnapshot, ...]
def _read_worker_detail(
db: ControllerDB, worker_id: WorkerId, *, resource_history_limit: int = 200
) -> _WorkerDetail | None:
with db.read_snapshot() as q:
worker = WORKER_DETAIL_PROJECTION.decode_one(
q.fetchall(
f"SELECT {WORKER_DETAIL_PROJECTION.select_clause()} FROM workers w WHERE w.worker_id = ?",
(str(worker_id),),
),
)
if worker is None:
return None
attr_rows = q.fetchall(
"SELECT key, value_type, str_value, int_value, float_value " "FROM worker_attributes WHERE worker_id = ?",
(str(worker_id),),
)
attrs = dict(_decode_attribute_value(row) for row in attr_rows)
if attrs:
worker = dataclasses.replace(worker, attributes=attrs)
running_rows = q.raw(
"SELECT t.task_id FROM tasks t "
"JOIN task_attempts a ON t.task_id = a.task_id AND t.current_attempt_id = a.attempt_id "
"WHERE a.worker_id = ? AND t.state IN (?, ?, ?)",
(str(worker_id), *ACTIVE_TASK_STATES),
decoders={"task_id": JobName.from_wire},
)
resource_rows = q.raw(
"SELECT wrh.snapshot_host_cpu_percent, wrh.snapshot_memory_used_bytes, "
"wrh.snapshot_memory_total_bytes, wrh.snapshot_disk_used_bytes, "
"wrh.snapshot_disk_total_bytes, wrh.snapshot_running_task_count, "
"wrh.snapshot_total_process_count, wrh.snapshot_net_recv_bps, "
"wrh.snapshot_net_sent_bps, wrh.timestamp_ms "
"FROM worker_resource_history wrh "
"WHERE wrh.worker_id = ? ORDER BY wrh.id DESC LIMIT ?",
(str(worker_id), max(resource_history_limit, 0)),
)
resource_history = tuple(reversed([_snapshot_row_to_proto(r, timestamp_ms=r.timestamp_ms) for r in resource_rows]))
return _WorkerDetail(
worker=worker,
running_tasks=frozenset(r.task_id for r in running_rows),
resource_history=resource_history,
)
def _tasks_for_listing(db: ControllerDB, *, job_id: JobName) -> list[TaskDetailRow]:
with db.read_snapshot() as q:
tasks = TASK_DETAIL_PROJECTION.decode(
q.fetchall(
f"SELECT {TASK_DETAIL_PROJECTION.select_clause()} "
"FROM tasks t WHERE t.job_id = ? ORDER BY t.job_id ASC, t.task_index ASC",
(job_id.to_wire(),),
),
)
if not tasks:
return []
task_wires = [t.task_id.to_wire() for t in tasks]
placeholders = ",".join("?" for _ in task_wires)
attempts = ATTEMPT_PROJECTION.decode(
q.fetchall(
f"SELECT {ATTEMPT_PROJECTION.select_clause()} FROM task_attempts ta "
f"WHERE ta.task_id IN ({placeholders}) "
"ORDER BY ta.task_id ASC, ta.attempt_id ASC",
tuple(task_wires),
),
)
return tasks_with_attempts(tasks, attempts)
def _worker_addresses_for_tasks(db: ControllerDB, tasks: list[TaskDetailRow]) -> dict[WorkerId, str]:
"""Fetch addresses only for workers referenced by the given tasks."""
worker_ids = {_task_worker_id(t) for t in tasks}
worker_ids.discard(None)
if not worker_ids:
return {}
placeholders = ",".join("?" for _ in worker_ids)
with db.read_snapshot() as q:
rows = q.raw(
f"SELECT worker_id, address FROM workers WHERE worker_id IN ({placeholders})",
tuple(str(wid) for wid in worker_ids),
)
return {WorkerId(str(row.worker_id)): row.address for row in rows}
# State display order for sorting (active states first)
_STATE_SORT_EXPR = (
"CASE j.state"
" WHEN 3 THEN 0" # RUNNING
" WHEN 2 THEN 1" # BUILDING
" WHEN 1 THEN 2" # PENDING
" WHEN 4 THEN 3" # SUCCEEDED
" WHEN 5 THEN 4" # FAILED
" WHEN 6 THEN 5" # KILLED
" WHEN 7 THEN 6" # WORKER_FAILED
" WHEN 8 THEN 7" # UNSCHEDULABLE
" ELSE 99 END"
)
_SORT_FIELD_TO_SQL: dict[int, str] = {
controller_pb2.Controller.JOB_SORT_FIELD_DATE: "j.submitted_at_ms",
controller_pb2.Controller.JOB_SORT_FIELD_NAME: "j.name",
controller_pb2.Controller.JOB_SORT_FIELD_STATE: _STATE_SORT_EXPR,
controller_pb2.Controller.JOB_SORT_FIELD_FAILURES: "agg_failures",
controller_pb2.Controller.JOB_SORT_FIELD_PREEMPTIONS: "agg_preemptions",
}
MAX_LIST_JOBS_LIMIT = 500
def _resolve_state_filter(state_filter: str) -> tuple[int, ...] | None:
"""Resolve a ``JobQuery.state_filter`` string into concrete state ids.
Returns ``USER_JOB_STATES`` when no filter is set, a single-element tuple
when it matches a known user-visible state, or ``None`` when the filter
does not match any known state (caller should return an empty page).
"""
if not state_filter:
return USER_JOB_STATES
normalized = state_filter.lower()
for st in USER_JOB_STATES:
if job_state_friendly(st) == normalized:
return (st,)
return None
def _query_jobs(
db: ControllerDB,
query: controller_pb2.Controller.JobQuery,
state_ids: tuple[int, ...],
) -> tuple[list[JobRow], int]:
"""Execute a ``JobQuery`` and return ``(rows, total_count)``.
``state_ids`` is the pre-resolved state filter (always non-empty); the
caller owns "unknown state -> empty page" handling so that a bad filter
never reaches SQL.
"""
assert state_ids, "_query_jobs requires at least one state id"
conditions: list[str] = []
params: list[object] = []
scope = query.scope or controller_pb2.Controller.JOB_QUERY_SCOPE_ALL
if scope == controller_pb2.Controller.JOB_QUERY_SCOPE_ROOTS:
conditions.append("j.depth = 1")
elif scope == controller_pb2.Controller.JOB_QUERY_SCOPE_CHILDREN:
if not query.parent_job_id:
raise ConnectError(
Code.INVALID_ARGUMENT,
"query.parent_job_id is required for JOB_QUERY_SCOPE_CHILDREN",
)
conditions.append("j.parent_job_id = ?")
params.append(query.parent_job_id)
# JOB_QUERY_SCOPE_ALL: no ancestry constraint.
state_placeholders = ",".join("?" for _ in state_ids)
conditions.append(f"j.state IN ({state_placeholders})")
params.extend(state_ids)
if query.name_filter:
conditions.append("j.name LIKE ?")
params.append(f"%{query.name_filter.lower()}%")
where_clause = " AND ".join(conditions)
sort_field = query.sort_field or controller_pb2.Controller.JOB_SORT_FIELD_DATE
sort_direction = query.sort_direction
if sort_direction == controller_pb2.Controller.SORT_DIRECTION_UNSPECIFIED:
sort_direction = (
controller_pb2.Controller.SORT_DIRECTION_DESC
if sort_field == controller_pb2.Controller.JOB_SORT_FIELD_DATE
else controller_pb2.Controller.SORT_DIRECTION_ASC
)
direction = "DESC" if sort_direction == controller_pb2.Controller.SORT_DIRECTION_DESC else "ASC"
order_expr = _SORT_FIELD_TO_SQL.get(sort_field, "j.submitted_at_ms")
count_sql = f"SELECT COUNT(*) FROM jobs j {JOB_CONFIG_JOIN} WHERE {where_clause}"
# Only join tasks when sorting by failure/preemption aggregates.
# The common case (sort by date, name, state) skips the expensive LEFT JOIN + GROUP BY.
needs_task_agg = sort_field in (
controller_pb2.Controller.JOB_SORT_FIELD_FAILURES,
controller_pb2.Controller.JOB_SORT_FIELD_PREEMPTIONS,
)
if needs_task_agg:
select_sql = f"""
SELECT {JOB_ROW_PROJECTION.select_clause()},
COALESCE(SUM(t.failure_count), 0) AS agg_failures,
COALESCE(SUM(t.preemption_count), 0) AS agg_preemptions
FROM jobs j {JOB_CONFIG_JOIN}
LEFT JOIN tasks t ON j.job_id = t.job_id
WHERE {where_clause}
GROUP BY j.job_id
ORDER BY {order_expr} {direction}
"""
else:
select_sql = f"""
SELECT {JOB_ROW_PROJECTION.select_clause()}
FROM jobs j {JOB_CONFIG_JOIN}
WHERE {where_clause}
ORDER BY {order_expr} {direction}
"""
offset = max(query.offset, 0)
limit = max(query.limit, 0)
select_params = list(params)
if limit > 0:
select_sql += " LIMIT ? OFFSET ?"
select_params.extend([limit, offset])
with db.read_snapshot() as q:
rows = q.execute_sql(select_sql, tuple(select_params)).fetchall()
# Skip the COUNT query when we can infer the total from the result set:
# first page + short result means we already have everything.
if offset == 0 and limit > 0 and len(rows) < limit:
total = len(rows)
else:
total = q.execute_sql(count_sql, tuple(params)).fetchone()[0]
return JOB_ROW_PROJECTION.decode(rows), total
def _query_from_list_jobs_request(
request: controller_pb2.Controller.ListJobsRequest,
) -> controller_pb2.Controller.JobQuery:
"""Normalize a ``ListJobsRequest`` into a single ``JobQuery``.
If ``request.query`` is set, it is used verbatim. Otherwise the legacy
flat fields on ``ListJobsRequest`` are mapped into an equivalent
``JobQuery`` so the rest of the server only ever sees one shape.
The legacy-field path exists only to keep older clients working during
the JobQuery rollout; delete it together with the legacy fields when
https://github.com/marin-community/marin/issues/4573 is resolved.
"""
if request.HasField("query"):
query = controller_pb2.Controller.JobQuery()
query.CopyFrom(request.query)
else:
# Legacy parent_job_id is only honored under SCOPE_CHILDREN; without
# this mapping the filter is silently dropped and all jobs are
# returned. See https://github.com/marin-community/marin/issues/4705.
scope = (
controller_pb2.Controller.JOB_QUERY_SCOPE_CHILDREN
if request.parent_job_id
else controller_pb2.Controller.JOB_QUERY_SCOPE_ALL
)
query = controller_pb2.Controller.JobQuery(
scope=scope,
parent_job_id=request.parent_job_id,
name_filter=request.name_filter,
state_filter=request.state_filter,
sort_field=request.sort_field,
sort_direction=request.sort_direction,
offset=request.offset,
limit=request.limit,
)
# Clamp paging: 0 (unset) defaults to MAX; explicit values are capped at MAX.
# We no longer support unbounded listing — callers that previously relied on
# limit=0 must paginate. Unbounded queries scale poorly because downstream
# per-page work (_task_summaries_for_jobs, _parent_ids_with_children) grows
# an IN-clause with one placeholder per returned row.
if query.limit <= 0 or query.limit > MAX_LIST_JOBS_LIMIT:
query.limit = MAX_LIST_JOBS_LIMIT
if query.offset < 0:
query.offset = 0
return query
def _parent_ids_with_children(db: ControllerDB, job_ids: list[JobName]) -> set[JobName]:
"""Return the subset of *job_ids* that currently have direct children."""
if not job_ids:
return set()
placeholders = ",".join("?" for _ in job_ids)
sql = f"""
SELECT DISTINCT j.parent_job_id
FROM jobs j
WHERE j.parent_job_id IN ({placeholders})
"""
with db.read_snapshot() as q:
rows = q.raw(sql, tuple(job_id.to_wire() for job_id in job_ids))
return {JobName.from_wire(row.parent_job_id) for row in rows if row.parent_job_id}
def _task_summaries_for_jobs(db: ControllerDB, job_ids: set[JobName] | None = None) -> dict[JobName, TaskJobSummary]:
"""Aggregate task counts per job using SQL GROUP BY instead of Python-side iteration."""
if job_ids is not None:
placeholders = ",".join("?" for _ in job_ids)
where = f"WHERE t.job_id IN ({placeholders})"
params: tuple[object, ...] = tuple(j.to_wire() for j in job_ids)
else:
where = ""
params = ()
sql = f"""
SELECT t.job_id,
t.state,
COUNT(*) as cnt,
SUM(t.failure_count) as total_failures,
SUM(t.preemption_count) as total_preemptions
FROM tasks t
{where}
GROUP BY t.job_id, t.state
"""
completed_states = (job_pb2.TASK_STATE_SUCCEEDED, job_pb2.TASK_STATE_KILLED)
with db.read_snapshot() as q:
rows = q.raw(sql, params, decoders={"job_id": JobName.from_wire})
summaries: dict[JobName, TaskJobSummary] = {}
for row in rows:
prev = summaries.get(row.job_id, TaskJobSummary(job_id=row.job_id))
summaries[row.job_id] = TaskJobSummary(
job_id=row.job_id,
task_count=prev.task_count + row.cnt,
completed_count=prev.completed_count + (row.cnt if row.state in completed_states else 0),
failure_count=prev.failure_count + row.total_failures,
preemption_count=prev.preemption_count + row.total_preemptions,
task_state_counts={**prev.task_state_counts, row.state: row.cnt},
)
return summaries
def _worker_roster(db: ControllerDB) -> list[WorkerDetailRow]:
with db.read_snapshot() as q:
workers = WORKER_DETAIL_PROJECTION.decode(
q.fetchall(f"SELECT {WORKER_DETAIL_PROJECTION.select_clause()} FROM workers w")
)
# Populate attributes from worker_attributes table.
if workers:
worker_ids = tuple(str(w.worker_id) for w in workers)
placeholders = ",".join("?" for _ in worker_ids)
attr_rows = q.fetchall(
f"SELECT worker_id, key, value_type, str_value, int_value, float_value "
f"FROM worker_attributes WHERE worker_id IN ({placeholders})",
worker_ids,
)
attrs_by_worker: dict[str, dict[str, str | int | float]] = {}
for row in attr_rows:
wid = str(row["worker_id"])
key, value = _decode_attribute_value(row)
attrs_by_worker.setdefault(wid, {})[key] = value
workers = [dataclasses.replace(w, attributes=attrs_by_worker.get(str(w.worker_id), {})) for w in workers]
return workers
def _descendant_jobs(db: ControllerDB, job_id: JobName) -> list[JobDetailRow]:
# PK range scan: '0' (ASCII 48) is the next char after '/' (ASCII 47),
# so this matches all job_ids starting with "<job_id>/" without LIKE.
prefix = job_id.to_wire() + "/"
upper = job_id.to_wire() + chr(ord("/") + 1)
with db.read_snapshot() as q:
return JOB_DETAIL_PROJECTION.decode(
q.fetchall(
f"SELECT {JOB_DETAIL_PROJECTION.select_clause()} FROM jobs j {JOB_CONFIG_JOIN} "
f"WHERE j.job_id >= ? AND j.job_id < ?",
(prefix, upper),
),
)
def _transaction_actions(db: ControllerDB, limit: int = 100) -> list[TransactionActionRow]:
with db.read_snapshot() as q:
actions = TXN_ACTION_PROJECTION.decode(
q.fetchall(
f"SELECT {TXN_ACTION_PROJECTION.select_clause()} " "FROM txn_actions ta2 ORDER BY ta2.id DESC LIMIT ?",
(limit,),
),
)
return list(reversed(actions))
def _live_user_stats(db: ControllerDB) -> list[UserStats]:
"""Aggregate job/task counts per user for active (non-terminal) jobs."""
active_states = ",".join(
str(s)
for s in (
job_pb2.JOB_STATE_PENDING,
job_pb2.JOB_STATE_BUILDING,
job_pb2.JOB_STATE_RUNNING,
)
)
with db.read_snapshot() as q:
job_rows = q.raw(
f"SELECT j.user_id, j.state, COUNT(*) as cnt FROM jobs j "
f"WHERE j.state IN ({active_states}) GROUP BY j.user_id, j.state"
)
task_rows = q.raw(
f"SELECT j.user_id, t.state, COUNT(*) as cnt "
f"FROM tasks t JOIN jobs j ON t.job_id = j.job_id "
f"WHERE j.state IN ({active_states}) "
f"GROUP BY j.user_id, t.state"
)
by_user: dict[str, UserStats] = {}
for row in job_rows:
stats = by_user.setdefault(row.user_id, UserStats(user=row.user_id))
stats.job_state_counts[row.state] = row.cnt
for row in task_rows:
stats = by_user.setdefault(row.user_id, UserStats(user=row.user_id))
stats.task_state_counts[row.state] = row.cnt
return list(by_user.values())
def _tasks_for_worker(db: ControllerDB, worker_id: WorkerId, limit: int = 50) -> list[TaskDetailRow]:
with db.read_snapshot() as q:
history_rows = q.raw(
"SELECT wth.task_id FROM worker_task_history wth "
"WHERE wth.worker_id = ? ORDER BY wth.assigned_at_ms DESC LIMIT ?",
(str(worker_id), limit),
decoders={"task_id": JobName.from_wire},
)
task_ids = [r.task_id for r in history_rows]
if not task_ids:
return []
task_wires = [tid.to_wire() for tid in task_ids]
placeholders = ",".join("?" for _ in task_wires)
tasks = TASK_DETAIL_PROJECTION.decode(
q.fetchall(
f"SELECT {TASK_DETAIL_PROJECTION.select_clause()} "
f"FROM tasks t WHERE t.task_id IN ({placeholders}) ORDER BY t.task_id ASC",
tuple(task_wires),
),
)
attempts = ATTEMPT_PROJECTION.decode(
q.fetchall(
f"SELECT {ATTEMPT_PROJECTION.select_clause()} FROM task_attempts ta "
f"WHERE ta.task_id IN ({placeholders}) "
"ORDER BY ta.task_id ASC, ta.attempt_id ASC",
tuple(task_wires),
),
)
task_map = {t.task_id: t for t in tasks_with_attempts(tasks, attempts)}
return [task for tid in task_ids if (task := task_map.get(tid)) is not None]
class AutoscalerProtocol(Protocol):
"""Protocol for autoscaler operations used by ControllerServiceImpl."""
def get_status(self) -> vm_pb2.AutoscalerStatus:
"""Get autoscaler status."""
...
def get_vm(self, vm_id: str) -> vm_pb2.VmInfo | None:
"""Get info for a specific VM."""
...
def job_feasibility(
self,
constraints: list[Constraint],
*,
replicas: int | None = None,
) -> str | None:
"""Check if a job can ever be scheduled. Returns error message or None."""
...
def get_init_log(self, vm_id: str, tail: int | None = None) -> str:
"""Get initialization log for a VM."""
...
class ControllerProtocol(Protocol):
"""Protocol for controller operations used by ControllerServiceImpl."""
def wake(self) -> None: ...
def kill_tasks_on_workers(
self,
task_ids: set[JobName],
task_kill_workers: dict[JobName, WorkerId] | None = None,
) -> None: ...
def create_scheduling_context(self, workers: list[WorkerRow]) -> SchedulingContext: ...
def get_job_scheduling_diagnostics(self, job_wire_id: str) -> str | None: ...
def begin_checkpoint(self) -> tuple[str, Any]: ...
@property
def autoscaler(self) -> AutoscalerProtocol | None: ...
@property
def provider(self) -> Any: ...
@property
def has_direct_provider(self) -> bool: ...
@property
def provider_scheduling_events(self) -> list: ...
@property
def provider_capacity(self) -> Any: ...
def _inject_resource_constraints(
request: controller_pb2.Controller.LaunchJobRequest,
) -> controller_pb2.Controller.LaunchJobRequest:
"""Merge auto-generated device constraints into a job submission request.
Constraints derived from ResourceSpecProto.device (device-type, device-variant)
are merged with any explicit user constraints on the request. For canonical
keys the user's explicit constraints replace auto-generated ones, so e.g.
a user-provided multi-variant IN constraint overrides the single-variant
EQ constraint from the resource spec.
"""
auto = constraints_from_resources(request.resources)
if not auto:
return request
user = [Constraint.from_proto(c) for c in request.constraints]
merged = merge_constraints(auto, user)
new_request = controller_pb2.Controller.LaunchJobRequest()
new_request.CopyFrom(request)
del new_request.constraints[:]
for c in merged:
new_request.constraints.append(c.to_proto())
return new_request
class ControllerServiceImpl:
"""ControllerService RPC implementation.
Args:
transitions: State machine for DB mutations (submit, cancel, register, etc.)
db: Query interface for direct DB reads
controller: Controller runtime for scheduling and worker management
bundle_store: Bundle store for zip storage.
log_service: LogService for fetching logs (in-process or remote proxy).
"""
def __init__(
self,