-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathtransitions.py
More file actions
3325 lines (2989 loc) · 144 KB
/
transitions.py
File metadata and controls
3325 lines (2989 loc) · 144 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 state machine: all DB-mutating transitions live here.
Read-only queries do NOT belong here — callers use db.read_snapshot() directly.
"""
import enum
import threading
import time
from collections import defaultdict
import json
import logging
from dataclasses import dataclass, field
from collections.abc import Callable, Iterable
from typing import Any, NamedTuple
from iris.cluster.constraints import AttributeValue, Constraint, constraints_from_resources, merge_constraints
from iris.cluster.controller.budget import UserBudgetDefaults
from iris.cluster.controller.db import (
ACTIVE_TASK_STATES,
EXECUTING_TASK_STATES,
FAILURE_TASK_STATES,
TERMINAL_JOB_STATES,
TERMINAL_TASK_STATES,
ControllerDB,
TransactionCursor,
task_row_can_be_scheduled,
task_row_is_finished,
)
from iris.cluster.controller.schema import (
JOB_DETAIL_PROJECTION,
TASK_DETAIL_PROJECTION,
WORKER_DETAIL_PROJECTION,
EndpointRow,
JobDetailRow,
WorkerDetailRow,
proto_cache,
proto_decoder,
)
from iris.cluster.types import (
JobName,
WorkerId,
get_gpu_count,
get_tpu_count,
)
from iris.rpc import job_pb2
from iris.rpc import controller_pb2
from iris.time_proto import duration_from_proto
from rigging.timing import Duration, Timestamp
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class ReservationClaim:
"""A claim binding a worker to a specific reservation entry.
The controller assigns unclaimed workers to unsatisfied reservation entries
each scheduling cycle. Once every entry for a job is claimed, the
reservation gate opens and the job's tasks can be scheduled.
"""
job_id: str
entry_idx: int
MAX_REPLICAS_PER_JOB = 10000
"""Maximum replicas allowed per job to prevent resource exhaustion."""
DEFAULT_MAX_RETRIES_PREEMPTION = 100
"""Default preemption retries. High because worker failures are typically transient."""
RESERVATION_HOLDER_JOB_NAME = ":reservation:"
"""Well-known name component for synthetic reservation holder child jobs.
Uses colons to clearly distinguish from user-created jobs and avoid
accidental collision with normal job names."""
HEARTBEAT_FAILURE_THRESHOLD = 10
"""Consecutive heartbeat failures before marking worker as failed."""
HEARTBEAT_STALENESS_THRESHOLD = Duration.from_seconds(900)
"""If a worker's last successful heartbeat is older than this, it is failed
immediately. Catches workers restored from a checkpoint whose backing VMs
no longer exist — without this, the controller would need 10 consecutive
RPC failures (50s) per worker to notice, during which they appear healthy
in the dashboard and block scheduling capacity."""
WORKER_TASK_HISTORY_RETENTION = 500
"""Maximum worker_task_history rows retained per worker."""
WORKER_RESOURCE_HISTORY_RETENTION = 500
"""Maximum worker_resource_history rows retained per worker."""
TASK_RESOURCE_HISTORY_RETENTION = 200
"""Maximum task_resource_history rows retained per (task_id, attempt_id).
Logarithmic downsampling triggers at 2x this value."""
DIRECT_PROVIDER_PROMOTION_RATE = 128
"""Token bucket capacity for task promotion (pods per minute).
The direct provider relies on the Kubernetes scheduler (and the cloud
autoscaler) for placement and capacity management. Pods that cannot be
scheduled immediately stay Pending — that signal drives node provisioning.
This rate limit exists only to bound API server pressure."""
@dataclass(frozen=True)
class PruneResult:
"""Counts of rows deleted by prune_old_data."""
jobs_deleted: int = 0
workers_deleted: int = 0
logs_deleted: int = 0
txn_actions_deleted: int = 0
profiles_deleted: int = 0
@property
def total(self) -> int:
return (
self.jobs_deleted
+ self.workers_deleted
+ self.logs_deleted
+ self.txn_actions_deleted
+ self.profiles_deleted
)
class HeartbeatAction(enum.Enum):
"""Result of processing a single heartbeat response."""
OK = "ok"
TRANSIENT_FAILURE = "transient_failure"
WORKER_FAILED = "worker_failed"
@dataclass
class WorkerConfig:
"""Static worker configuration for v0.
Args:
worker_id: Unique worker identifier
address: Worker RPC address (host:port)
metadata: Worker environment metadata
"""
worker_id: str
address: str
metadata: job_pb2.WorkerMetadata
@dataclass(frozen=True)
class TaskUpdate:
"""Single task state update applied in a batch."""
task_id: JobName
attempt_id: int
new_state: int
error: str | None = None
exit_code: int | None = None
resource_usage: job_pb2.ResourceUsage | None = None
container_id: str | None = None
@dataclass(frozen=True)
class HeartbeatApplyRequest:
"""Batch of worker heartbeat updates applied atomically."""
worker_id: WorkerId
worker_resource_snapshot: job_pb2.WorkerResourceSnapshot | None
updates: list[TaskUpdate]
@dataclass(frozen=True)
class Assignment:
"""Scheduler assignment decision."""
task_id: JobName
worker_id: WorkerId
@dataclass(frozen=True)
class TxResult:
"""Result payload from a state command transaction."""
tasks_to_kill: set[JobName] = field(default_factory=set)
task_kill_workers: dict[JobName, WorkerId] = field(default_factory=dict)
has_real_dispatch: bool = False
@dataclass(frozen=True)
class AssignmentResult(TxResult):
"""Result of queue_assignments."""
accepted: list[Assignment] = field(default_factory=list)
rejected: list[Assignment] = field(default_factory=list)
@dataclass(frozen=True)
class SubmitJobResult:
job_id: JobName
task_ids: list[JobName]
@dataclass(frozen=True)
class WorkerRegistrationResult:
worker_id: WorkerId
@dataclass(frozen=True)
class HeartbeatApplyResult(TxResult):
action: HeartbeatAction = HeartbeatAction.OK
@dataclass(frozen=True)
class HeartbeatFailureResult(TxResult):
worker_removed: bool = False
action: HeartbeatAction = HeartbeatAction.TRANSIENT_FAILURE
@dataclass(frozen=True)
class WorkerFailureBatchResult(TxResult):
"""Result of applying a batch of worker failures."""
removed_workers: list[tuple[WorkerId, str | None]] = field(default_factory=list)
results: list[HeartbeatFailureResult] = field(default_factory=list)
class RunningTaskEntry(NamedTuple):
"""Task ID and attempt ID pair captured at snapshot time."""
task_id: JobName
attempt_id: int
@dataclass(frozen=True)
class DispatchBatch:
"""Drained worker dispatch plus running-task snapshot."""
worker_id: WorkerId
worker_address: str | None
running_tasks: list[RunningTaskEntry]
tasks_to_run: list[job_pb2.RunTaskRequest] = field(default_factory=list)
tasks_to_kill: list[str] = field(default_factory=list)
@dataclass(frozen=True)
class SchedulingEvent:
"""A scheduling event from the execution backend (e.g. k8s events)."""
task_id: str
attempt_id: int
event_type: str
reason: str
message: str
timestamp: Timestamp
@dataclass(frozen=True)
class ClusterCapacity:
"""Aggregate capacity reported by the execution backend."""
schedulable_nodes: int
total_cpu_millicores: int
available_cpu_millicores: int
total_memory_bytes: int
available_memory_bytes: int
@dataclass(frozen=True)
class DirectProviderBatch:
"""Work batch for a KubernetesProvider sync cycle.
Unlike DispatchBatch, there is no worker_id — tasks run without a registered
worker daemon. task_attempts rows use NULL worker_id.
"""
tasks_to_run: list[job_pb2.RunTaskRequest] = field(default_factory=list)
running_tasks: list[RunningTaskEntry] = field(default_factory=list)
tasks_to_kill: list[str] = field(default_factory=list)
@dataclass(frozen=True)
class DirectProviderSyncResult:
"""Result from a KubernetesProvider sync cycle."""
updates: list[TaskUpdate] = field(default_factory=list)
scheduling_events: list[SchedulingEvent] = field(default_factory=list)
capacity: ClusterCapacity | None = None
def _has_reservation_flag(request: controller_pb2.Controller.LaunchJobRequest) -> int:
"""Return 1 if the request carries reservation entries, else 0."""
return 1 if request.HasField("reservation") and request.reservation.entries else 0
def delete_task_endpoints(cur: TransactionCursor, task_id: str) -> None:
"""Remove all registered endpoints for a task."""
cur.execute("DELETE FROM endpoints WHERE task_id = ?", (task_id,))
def enqueue_run_dispatch(
cur: TransactionCursor,
worker_id: str,
payload_proto: bytes,
now_ms: int,
) -> None:
"""Queue a 'run' dispatch entry for delivery on the next heartbeat."""
cur.execute(
"INSERT INTO dispatch_queue(worker_id, kind, payload_proto, task_id, created_at_ms) "
"VALUES (?, 'run', ?, NULL, ?)",
(worker_id, payload_proto, now_ms),
)
def enqueue_kill_dispatch(
cur: TransactionCursor,
worker_id: str | None,
task_id: str,
now_ms: int,
) -> None:
"""Queue a 'kill' dispatch entry for delivery on the next heartbeat."""
cur.execute(
"INSERT INTO dispatch_queue(worker_id, kind, payload_proto, task_id, created_at_ms) "
"VALUES (?, 'kill', NULL, ?, ?)",
(worker_id, task_id, now_ms),
)
def insert_task_attempt(
cur: TransactionCursor,
task_id: str,
attempt_id: int,
worker_id: str | None,
state: int,
now_ms: int,
) -> None:
"""Record a new task attempt row."""
cur.execute(
"INSERT INTO task_attempts(task_id, attempt_id, worker_id, state, created_at_ms) " "VALUES (?, ?, ?, ?, ?)",
(task_id, attempt_id, worker_id, state, now_ms),
)
def _decommit_worker_resources(
cur: TransactionCursor,
worker_id: str,
resources: "job_pb2.ResourceSpecProto",
) -> None:
"""Subtract a task's resource reservation from a worker, flooring at zero."""
cur.execute(
"UPDATE workers SET committed_cpu_millicores = MAX(0, committed_cpu_millicores - ?), "
"committed_mem_bytes = MAX(0, committed_mem_bytes - ?), "
"committed_gpu = MAX(0, committed_gpu - ?), committed_tpu = MAX(0, committed_tpu - ?) "
"WHERE worker_id = ?",
(
int(resources.cpu_millicores),
int(resources.memory_bytes),
int(get_gpu_count(resources.device)),
int(get_tpu_count(resources.device)),
worker_id,
),
)
def _remove_worker(cur: TransactionCursor, worker_id: str) -> None:
"""Remove a worker and sever all its foreign-key references.
Must be called inside an existing transaction. The four statements
enforce the multi-table invariant: no dangling worker_id references
remain in task_attempts, tasks, or dispatch_queue after the worker
row is deleted.
"""
cur.execute("UPDATE task_attempts SET worker_id = NULL WHERE worker_id = ?", (worker_id,))
cur.execute("UPDATE tasks SET current_worker_id = NULL WHERE current_worker_id = ?", (worker_id,))
cur.execute("DELETE FROM dispatch_queue WHERE worker_id = ?", (worker_id,))
cur.execute("DELETE FROM workers WHERE worker_id = ?", (worker_id,))
def _assign_task(
cur: TransactionCursor,
task_id: str,
worker_id: str | None,
worker_address: str | None,
attempt_id: int,
now_ms: int,
) -> None:
"""Create an attempt and mark a task as ASSIGNED in one consistent step.
worker_id may be None for direct-provider tasks that have no backing
worker daemon.
"""
insert_task_attempt(cur, task_id, attempt_id, worker_id, job_pb2.TASK_STATE_ASSIGNED, now_ms)
if worker_id is not None:
cur.execute(
"UPDATE tasks SET state = ?, current_attempt_id = ?, "
"current_worker_id = ?, current_worker_address = ?, "
"started_at_ms = COALESCE(started_at_ms, ?) WHERE task_id = ?",
(job_pb2.TASK_STATE_ASSIGNED, attempt_id, worker_id, worker_address, now_ms, task_id),
)
else:
cur.execute(
"UPDATE tasks SET state = ?, current_attempt_id = ?, "
"started_at_ms = COALESCE(started_at_ms, ?) WHERE task_id = ?",
(job_pb2.TASK_STATE_ASSIGNED, attempt_id, now_ms, task_id),
)
def _terminate_task(
cur: TransactionCursor,
task_id: str,
attempt_id: int | None,
state: int,
error: str | None,
now_ms: int,
*,
attempt_state: int | None = None,
worker_id: str | None = None,
resources: "job_pb2.ResourceSpecProto | None" = None,
failure_count: int | None = None,
preemption_count: int | None = None,
) -> None:
"""Move a task (and its current attempt) out of active state consistently.
Enforces the multi-table invariant: attempt is marked terminal,
task state/error/finished_at are updated, endpoints are deleted,
and worker resources are released.
``attempt_state`` overrides the state written to the attempt row when it
differs from the task state (e.g. attempt=WORKER_FAILED while task retries
to PENDING). Defaults to ``state`` when not provided.
attempt_id < 0 means no attempt exists; the attempt UPDATE is skipped.
"""
finished_at_ms = None if state in ACTIVE_TASK_STATES or state == job_pb2.TASK_STATE_PENDING else now_ms
effective_attempt_state = attempt_state if attempt_state is not None else state
if attempt_id is not None and attempt_id >= 0:
cur.execute(
"UPDATE task_attempts SET state = ?, "
"finished_at_ms = COALESCE(finished_at_ms, ?), error = ? "
"WHERE task_id = ? AND attempt_id = ?",
(effective_attempt_state, now_ms, error, task_id, attempt_id),
)
# Build the UPDATE tasks statement dynamically based on optional counters.
# Use COALESCE for finished_at_ms when non-NULL to preserve any existing
# timestamp (defensive against double-termination). When NULL (retrying to
# PENDING), assign directly so the column is cleared.
if finished_at_ms is not None:
set_clauses = ["state = ?", "error = ?", "finished_at_ms = COALESCE(finished_at_ms, ?)"]
else:
set_clauses = ["state = ?", "error = ?", "finished_at_ms = ?"]
params: list[object] = [state, error, finished_at_ms]
if failure_count is not None:
set_clauses.append("failure_count = ?")
params.append(failure_count)
if preemption_count is not None:
set_clauses.append("preemption_count = ?")
params.append(preemption_count)
# Always clear worker columns when leaving active state.
if state not in ACTIVE_TASK_STATES:
set_clauses.append("current_worker_id = NULL")
set_clauses.append("current_worker_address = NULL")
params.append(task_id)
cur.execute(
f"UPDATE tasks SET {', '.join(set_clauses)} WHERE task_id = ?",
tuple(params),
)
delete_task_endpoints(cur, task_id)
if worker_id is not None and resources is not None:
_decommit_worker_resources(cur, worker_id, resources)
_LAUNCH_JOB_DECODER = proto_decoder(controller_pb2.Controller.LaunchJobRequest)
def _kill_non_terminal_tasks(
cur: Any,
job_id_wire: str,
reason: str,
now_ms: int,
) -> tuple[set[JobName], dict[JobName, WorkerId]]:
"""Kill all non-terminal tasks for a single job, decommit resources, and delete endpoints."""
terminal_states = tuple(sorted(TERMINAL_TASK_STATES))
placeholders = ",".join("?" * len(terminal_states))
rows = cur.execute(
"SELECT t.task_id, t.current_attempt_id, t.current_worker_id, j.request_proto "
"FROM tasks t "
"JOIN jobs j ON j.job_id = t.job_id "
f"WHERE t.job_id = ? AND t.state NOT IN ({placeholders})",
(job_id_wire, *terminal_states),
).fetchall()
tasks_to_kill: set[JobName] = set()
task_kill_workers: dict[JobName, WorkerId] = {}
for row in rows:
task_id = str(row["task_id"])
worker_id = row["current_worker_id"]
task_name = JobName.from_wire(task_id)
resources = None
if worker_id is not None:
req = proto_cache.get_or_decode(row["request_proto"], _LAUNCH_JOB_DECODER)
resources = req.resources
task_kill_workers[task_name] = WorkerId(str(worker_id))
_terminate_task(
cur,
task_id,
int(row["current_attempt_id"]),
job_pb2.TASK_STATE_KILLED,
reason,
now_ms,
worker_id=str(worker_id) if worker_id is not None else None,
resources=resources,
)
tasks_to_kill.add(task_name)
return tasks_to_kill, task_kill_workers
def _cascade_children(
cur: Any,
job_id: JobName,
now_ms: int,
reason: str,
exclude_reservation_holders: bool = False,
) -> tuple[set[JobName], dict[JobName, WorkerId]]:
"""Kill descendant jobs (not the job itself) when a parent reaches terminal state or is preempted.
When exclude_reservation_holders is True, reservation holder jobs and their
descendants are left alive. This is used during preemption retry: the parent
goes back to PENDING and needs its reservation to survive so the scheduler
can re-satisfy it.
"""
tasks_to_kill: set[JobName] = set()
task_kill_workers: dict[JobName, WorkerId] = {}
if exclude_reservation_holders:
# Skip reservation holder jobs and anything below them.
descendants = cur.execute(
"WITH RECURSIVE subtree(job_id) AS ("
" SELECT job_id FROM jobs WHERE parent_job_id = ? AND is_reservation_holder = 0 "
" UNION ALL "
" SELECT j.job_id FROM jobs j JOIN subtree s ON j.parent_job_id = s.job_id"
" WHERE j.is_reservation_holder = 0"
") SELECT job_id FROM subtree",
(job_id.to_wire(),),
).fetchall()
else:
descendants = cur.execute(
"WITH RECURSIVE subtree(job_id) AS ("
" SELECT job_id FROM jobs WHERE parent_job_id = ? "
" UNION ALL "
" SELECT j.job_id FROM jobs j JOIN subtree s ON j.parent_job_id = s.job_id"
") SELECT job_id FROM subtree",
(job_id.to_wire(),),
).fetchall()
for child_row in descendants:
child_job_id = str(child_row["job_id"])
child_tasks_to_kill, child_task_kill_workers = _kill_non_terminal_tasks(cur, child_job_id, reason, now_ms)
tasks_to_kill.update(child_tasks_to_kill)
task_kill_workers.update(child_task_kill_workers)
terminal_placeholders = ",".join("?" for _ in TERMINAL_JOB_STATES)
cur.execute(
"UPDATE jobs SET state = ?, error = ?, finished_at_ms = COALESCE(finished_at_ms, ?) "
f"WHERE job_id = ? AND state NOT IN ({terminal_placeholders})",
(
job_pb2.JOB_STATE_KILLED,
reason,
now_ms,
child_job_id,
*TERMINAL_JOB_STATES,
),
)
return tasks_to_kill, task_kill_workers
def _cascade_terminal_job(
cur: Any,
job_id: JobName,
now_ms: int,
reason: str,
) -> tuple[set[JobName], dict[JobName, WorkerId]]:
"""Kill remaining tasks and descendant jobs when a job reaches a terminal state."""
tasks_to_kill, task_kill_workers = _kill_non_terminal_tasks(cur, job_id.to_wire(), reason, now_ms)
child_tasks_to_kill, child_task_kill_workers = _cascade_children(cur, job_id, now_ms, reason)
tasks_to_kill.update(child_tasks_to_kill)
task_kill_workers.update(child_task_kill_workers)
return tasks_to_kill, task_kill_workers
@dataclass(frozen=True, slots=True)
class _CoscheduledSibling:
task_id: str # wire format
attempt_id: int
max_retries_preemption: int
worker_id: str | None
def _find_coscheduled_siblings(
cur: Any,
job_id: JobName,
exclude_task_id: JobName,
job_req: "controller_pb2.Controller.LaunchJobRequest",
) -> list[_CoscheduledSibling]:
"""Find active siblings in a coscheduled job (read-only)."""
if not job_req.HasField("coscheduling"):
return []
rows = cur.execute(
"SELECT t.task_id, t.current_attempt_id, t.max_retries_preemption, "
"t.current_worker_id AS worker_id "
"FROM tasks t "
"WHERE t.job_id = ? AND t.task_id != ? AND t.state IN (?, ?, ?)",
(
job_id.to_wire(),
exclude_task_id.to_wire(),
job_pb2.TASK_STATE_ASSIGNED,
job_pb2.TASK_STATE_BUILDING,
job_pb2.TASK_STATE_RUNNING,
),
).fetchall()
return [
_CoscheduledSibling(
task_id=str(r["task_id"]),
attempt_id=int(r["current_attempt_id"]),
max_retries_preemption=int(r["max_retries_preemption"]),
worker_id=str(r["worker_id"]) if r["worker_id"] is not None else None,
)
for r in rows
]
def _terminate_coscheduled_siblings(
cur: Any,
siblings: Iterable[_CoscheduledSibling],
failed_task_id: JobName,
job_req: "controller_pb2.Controller.LaunchJobRequest",
now_ms: int,
) -> tuple[set[JobName], dict[JobName, WorkerId]]:
"""Terminate coscheduled siblings and decommit their resources.
Each sibling is marked WORKER_FAILED with exhausted preemption count so it
will not be retried.
"""
tasks_to_kill: set[JobName] = set()
task_kill_workers: dict[JobName, WorkerId] = {}
error = f"Coscheduled sibling {failed_task_id.to_wire()} failed"
for sib in siblings:
_terminate_task(
cur,
sib.task_id,
sib.attempt_id,
job_pb2.TASK_STATE_WORKER_FAILED,
error,
now_ms,
worker_id=sib.worker_id,
resources=job_req.resources if sib.worker_id is not None else None,
preemption_count=sib.max_retries_preemption + 1,
)
if sib.worker_id is not None:
task_kill_workers[JobName.from_wire(sib.task_id)] = WorkerId(sib.worker_id)
tasks_to_kill.add(JobName.from_wire(sib.task_id))
return tasks_to_kill, task_kill_workers
def _resolve_preemption_policy(cur: Any, job_id: JobName) -> int:
"""Resolve the effective preemption policy for a job.
Defaults: single-task jobs → TERMINATE_CHILDREN, multi-task → PRESERVE_CHILDREN.
"""
row = cur.execute("SELECT request_proto FROM jobs WHERE job_id = ?", (job_id.to_wire(),)).fetchone()
if row is None:
return job_pb2.JOB_PREEMPTION_POLICY_TERMINATE_CHILDREN
req = proto_cache.get_or_decode(row["request_proto"], _LAUNCH_JOB_DECODER)
if req.preemption_policy != job_pb2.JOB_PREEMPTION_POLICY_UNSPECIFIED:
return req.preemption_policy
if req.replicas <= 1:
return job_pb2.JOB_PREEMPTION_POLICY_TERMINATE_CHILDREN
return job_pb2.JOB_PREEMPTION_POLICY_PRESERVE_CHILDREN
_TERMINAL_STATE_REASONS: dict[int, str] = {
job_pb2.JOB_STATE_FAILED: "Job exceeded max_task_failures",
job_pb2.JOB_STATE_KILLED: "Job was terminated.",
job_pb2.JOB_STATE_UNSCHEDULABLE: "Job could not be scheduled.",
job_pb2.JOB_STATE_WORKER_FAILED: "Worker failed",
}
def _finalize_terminal_job(
cur: Any,
job_id: JobName,
terminal_state: int,
now_ms: int,
) -> tuple[set[JobName], dict[JobName, WorkerId]]:
"""Kill remaining tasks and optionally cascade to children when a job goes terminal.
Called after _recompute_job_state determines a job has reached a terminal
state. Kills the job's own non-terminal tasks and, depending on preemption
policy, cascades to descendant jobs.
Succeeded jobs always cascade (children are no longer needed).
Non-succeeded jobs cascade only if the preemption policy is TERMINATE_CHILDREN.
"""
reason = _TERMINAL_STATE_REASONS.get(terminal_state, "Job finalized")
tasks_to_kill, task_kill_workers = _kill_non_terminal_tasks(cur, job_id.to_wire(), reason, now_ms)
should_cascade = True
if terminal_state != job_pb2.JOB_STATE_SUCCEEDED:
policy = _resolve_preemption_policy(cur, job_id)
should_cascade = policy == job_pb2.JOB_PREEMPTION_POLICY_TERMINATE_CHILDREN
if should_cascade:
child_tasks_to_kill, child_task_kill_workers = _cascade_children(cur, job_id, now_ms, reason)
tasks_to_kill.update(child_tasks_to_kill)
task_kill_workers.update(child_task_kill_workers)
return tasks_to_kill, task_kill_workers
def _resolve_task_failure_state(
prior_state: int,
preemption_count: int,
max_preemptions: int,
terminal_state: int,
) -> tuple[int, int]:
"""Determine new task state after a worker failure or preemption.
Assigned tasks always retry. Executing tasks retry if preemption budget remains,
otherwise go to the given terminal state.
Returns (new_task_state, updated_preemption_count).
"""
if prior_state == job_pb2.TASK_STATE_ASSIGNED:
return job_pb2.TASK_STATE_PENDING, preemption_count
if prior_state in EXECUTING_TASK_STATES:
preemption_count += 1
if preemption_count <= max_preemptions:
return job_pb2.TASK_STATE_PENDING, preemption_count
return terminal_state, preemption_count
# =============================================================================
# Batch helpers for apply_heartbeats_batch
# =============================================================================
def _batch_worker_health(
cur: TransactionCursor,
requests: list["HeartbeatApplyRequest"],
now_ms: int,
) -> set[str]:
"""Batch-update worker health, resource snapshots, and history.
Returns the set of worker IDs that actually exist in the DB so callers
can skip updates from stale/removed workers.
"""
worker_ids = [str(req.worker_id) for req in requests]
if not worker_ids:
return set()
placeholders = ",".join("?" * len(worker_ids))
rows = cur.execute(
f"SELECT worker_id FROM workers WHERE worker_id IN ({placeholders})",
tuple(worker_ids),
).fetchall()
existing = {str(r["worker_id"]) for r in rows}
health_params = []
history_params = []
for req in requests:
wid = str(req.worker_id)
if wid not in existing:
continue
snapshot_payload = (
req.worker_resource_snapshot.SerializeToString() if req.worker_resource_snapshot is not None else None
)
health_params.append((now_ms, snapshot_payload, wid))
if snapshot_payload is not None:
history_params.append((wid, snapshot_payload, now_ms))
if health_params:
cur.executemany(
"UPDATE workers SET healthy = 1, active = 1, consecutive_failures = 0, "
"last_heartbeat_ms = ?, resource_snapshot_proto = COALESCE(?, resource_snapshot_proto) "
"WHERE worker_id = ?",
health_params,
)
if history_params:
cur.executemany(
"INSERT INTO worker_resource_history(worker_id, snapshot_proto, timestamp_ms) " "VALUES (?, ?, ?)",
history_params,
)
return existing
def _bulk_fetch_tasks(cur: TransactionCursor, task_ids: list[str]) -> dict[str, Any]:
"""Fetch task rows for all given IDs in chunked IN queries."""
result: dict[str, Any] = {}
for chunk_start in range(0, len(task_ids), 900):
chunk = task_ids[chunk_start : chunk_start + 900]
ph = ",".join("?" * len(chunk))
rows = cur.execute(
f"SELECT * FROM tasks WHERE task_id IN ({ph})",
tuple(chunk),
).fetchall()
for r in rows:
result[str(r["task_id"])] = r
return result
# =============================================================================
# Controller Transitions
# =============================================================================
class ControllerTransitions:
"""State machine for controller entities.
All methods that mutate DB state live here. Each is a single atomic
transaction. Read-only queries do NOT belong here — callers use
db.read_snapshot() directly.
SQLite is the sole source of truth. Any in-memory values are transient
helpers and must never be required for correctness across restarts.
"""
def __init__(
self,
db: ControllerDB,
heartbeat_failure_threshold: int = HEARTBEAT_FAILURE_THRESHOLD,
user_budget_defaults: UserBudgetDefaults | None = None,
):
self._db = db
self._heartbeat_failure_threshold = heartbeat_failure_threshold
self._user_budget_defaults = user_budget_defaults or UserBudgetDefaults()
def _record_transaction(
self,
cur: Any,
kind: str,
actions: list[tuple[str, str, dict[str, object]]],
*,
payload: dict[str, object] | None = None,
) -> None:
created_ms = Timestamp.now().epoch_ms()
cur.execute(
"INSERT INTO txn_log(kind, payload_json, created_at_ms) VALUES (?, ?, ?)",
(kind, json.dumps(payload or {}), created_ms),
)
txn_id = int(cur.lastrowid)
for action, entity_id, details in actions:
cur.execute(
"INSERT INTO txn_actions(txn_id, action, entity_id, details_json, created_at_ms) VALUES (?, ?, ?, ?, ?)",
(txn_id, action, entity_id, json.dumps(details), created_ms),
)
def _recompute_job_state(self, cur: Any, job_id: JobName) -> int | None:
row = cur.execute(
"SELECT request_proto, state, started_at_ms FROM jobs WHERE job_id = ?",
(job_id.to_wire(),),
).fetchone()
if row is None:
return None
current_state = int(row["state"])
if current_state in TERMINAL_JOB_STATES:
return current_state
req = controller_pb2.Controller.LaunchJobRequest()
req.ParseFromString(row["request_proto"])
counts_rows = cur.execute(
"SELECT state, COUNT(*) AS c FROM tasks WHERE job_id = ? GROUP BY state",
(job_id.to_wire(),),
).fetchall()
counts = {int(r["state"]): int(r["c"]) for r in counts_rows}
total = sum(counts.values())
new_state = current_state
now_ms = Timestamp.now().epoch_ms()
if total > 0 and counts.get(job_pb2.TASK_STATE_SUCCEEDED, 0) == total:
new_state = job_pb2.JOB_STATE_SUCCEEDED
elif counts.get(job_pb2.TASK_STATE_FAILED, 0) > int(req.max_task_failures):
new_state = job_pb2.JOB_STATE_FAILED
elif counts.get(job_pb2.TASK_STATE_UNSCHEDULABLE, 0) > 0:
new_state = job_pb2.JOB_STATE_UNSCHEDULABLE
elif counts.get(job_pb2.TASK_STATE_KILLED, 0) > 0:
new_state = job_pb2.JOB_STATE_KILLED
elif (
total > 0
and (counts.get(job_pb2.TASK_STATE_WORKER_FAILED, 0) + counts.get(job_pb2.TASK_STATE_PREEMPTED, 0)) > 0
and all(s in TERMINAL_TASK_STATES for s in counts)
):
new_state = job_pb2.JOB_STATE_WORKER_FAILED
elif (
counts.get(job_pb2.TASK_STATE_ASSIGNED, 0) > 0
or counts.get(job_pb2.TASK_STATE_BUILDING, 0) > 0
or counts.get(job_pb2.TASK_STATE_RUNNING, 0) > 0
):
new_state = job_pb2.JOB_STATE_RUNNING
elif row["started_at_ms"] is not None:
# Retries put tasks back into PENDING; keep job running once it has started.
new_state = job_pb2.JOB_STATE_RUNNING
elif total > 0:
new_state = job_pb2.JOB_STATE_PENDING
if new_state == current_state:
return new_state
terminal_placeholders = ",".join("?" for _ in TERMINAL_JOB_STATES)
error_row = cur.execute(
"SELECT error FROM tasks WHERE job_id = ? AND error IS NOT NULL ORDER BY task_index LIMIT 1",
(job_id.to_wire(),),
).fetchone()
error = str(error_row["error"]) if error_row is not None else None
cur.execute(
"UPDATE jobs SET state = ?, "
"started_at_ms = CASE WHEN ? = ? THEN COALESCE(started_at_ms, ?) ELSE started_at_ms END, "
f"finished_at_ms = CASE WHEN ? IN ({terminal_placeholders}) THEN ? ELSE finished_at_ms END, "
"error = CASE WHEN ? IN (?, ?, ?, ?) THEN ? ELSE error END "
"WHERE job_id = ?",
(
new_state,
new_state,
job_pb2.JOB_STATE_RUNNING,
now_ms,
new_state,
*TERMINAL_JOB_STATES,
now_ms,
new_state,
job_pb2.JOB_STATE_FAILED,
job_pb2.JOB_STATE_KILLED,
job_pb2.JOB_STATE_UNSCHEDULABLE,
job_pb2.JOB_STATE_WORKER_FAILED,
error,
job_id.to_wire(),
),
)
return new_state
def replace_reservation_claims(self, claims: dict[WorkerId, ReservationClaim]) -> None:
"""Replace all reservation claims atomically."""
with self._db.transaction() as cur:
cur.execute("DELETE FROM reservation_claims")
for worker_id, claim in claims.items():
cur.execute(
"INSERT INTO reservation_claims(worker_id, job_id, entry_idx) VALUES (?, ?, ?)",
(str(worker_id), claim.job_id, claim.entry_idx),
)
# =========================================================================
# Command API
# =========================================================================
def submit_job(
self,
job_id: JobName,
request: controller_pb2.Controller.LaunchJobRequest,
ts: Timestamp,
) -> SubmitJobResult:
"""Submit a job and expand its tasks in one DB transaction."""
submitted_ms = ts.epoch_ms()
actions: list[tuple[str, str, dict[str, object]]] = []
created_task_ids: list[JobName] = []
with self._db.transaction() as cur:
row = cur.execute("SELECT value FROM meta WHERE key = 'last_submission_ms'").fetchone()
last_submission_ms = int(row["value"]) if row is not None else 0
effective_submission_ms = max(submitted_ms, last_submission_ms + 1)
if row is None:
cur.execute("INSERT INTO meta(key, value) VALUES ('last_submission_ms', ?)", (effective_submission_ms,))
else:
cur.execute("UPDATE meta SET value = ? WHERE key = 'last_submission_ms'", (effective_submission_ms,))
parent_job_id = job_id.parent.to_wire() if job_id.parent is not None else None
if parent_job_id is not None:
parent_exists = cur.execute("SELECT 1 FROM jobs WHERE job_id = ?", (parent_job_id,)).fetchone()
if parent_exists is None:
parent_job_id = None
root_submitted_ms = effective_submission_ms
if parent_job_id is not None:
parent = cur.execute(
"SELECT root_submitted_at_ms FROM jobs WHERE job_id = ?",
(parent_job_id,),
).fetchone()
if parent is not None:
root_submitted_ms = int(parent["root_submitted_at_ms"])
deadline_epoch_ms: int | None = None
if request.HasField("scheduling_timeout") and request.scheduling_timeout.milliseconds > 0:
deadline_epoch_ms = (
Timestamp.from_ms(effective_submission_ms)
.add(duration_from_proto(request.scheduling_timeout))
.epoch_ms()
)
cur.execute(
"INSERT OR IGNORE INTO users(user_id, created_at_ms) VALUES (?, ?)",
(job_id.user, effective_submission_ms),
)
# Create default user budget row alongside user creation.