-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathtest_distributed_telemetry.py
More file actions
2772 lines (2448 loc) · 104 KB
/
Copy pathtest_distributed_telemetry.py
File metadata and controls
2772 lines (2448 loc) · 104 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 (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
"""Tests for distributed telemetry with automatic callback registration."""
import json
import os
import shutil
import time
import types
import unittest.mock
import uuid
from collections import Counter
from typing import Any, cast
import monarch._src.job.telemetry_actor as job_telemetry_actor
import monarch.actor
import pytest
from isolate_in_subprocess import isolate_in_subprocess
from monarch._rust_bindings.monarch_hyperactor.proc import ActorAddr
from monarch._rust_bindings.monarch_hyperactor.supervision import SupervisionError
from monarch._src.actor.actor_mesh import Actor, ActorMesh, current_rank
from monarch._src.actor.endpoint import endpoint
from monarch.actor import span
from monarch.config import configured
from monarch.distributed_telemetry.engine import QueryEngine
from monarch.job import MeshAdminConfig, ProcessJob, TelemetryConfig
from scoped_state import scoped_state
class WorkerActor(Actor):
"""Simple test actor with a no-op ping endpoint."""
@endpoint
def ping(self) -> None:
pass
@endpoint
def emit_trace(self, name: str) -> None:
"""Emit a named user span."""
with span(name):
pass
class SenderActor(Actor):
"""Actor that sends messages to another actor mesh."""
@endpoint
def send_ping(self, target: WorkerActor) -> None:
"""Cast to the target actor mesh from within this actor."""
target.ping.call().get()
class _TelemetryActorFailure(BaseException):
pass
class _CrashingTelemetryActor(job_telemetry_actor.TelemetryActor):
@endpoint
def crash(self) -> None:
raise _TelemetryActorFailure("intentional telemetry actor failure")
class _FailureTestTelemetryRoot(job_telemetry_actor.TelemetryActor):
@endpoint
def start_failing_collector(self, host_mesh: Any, apply_id: str) -> Any:
failing = self._start_worker_collector(
host_mesh,
_CrashingTelemetryActor,
apply_id,
"telemetry_failure_procs",
)
if failing is None:
raise RuntimeError("failure test collector did not activate")
return failing
@endpoint
def start_healthy_collector(self, host_mesh: Any, apply_id: str) -> Any:
healthy = self._start_worker_collector(
host_mesh,
job_telemetry_actor.TelemetryActor,
apply_id,
"telemetry_healthy_procs",
)
if healthy is None:
raise RuntimeError("healthy test collector did not activate")
return healthy
@endpoint
def worker_collector_count(self) -> int:
return len(self._worker_collectors)
class TelemetryWorkerActor(Actor):
"""Worker that exercises multi-hop actor messaging."""
@endpoint
def start(self, coordinator: Any) -> None:
coordinator.request.call_one(current_rank().rank).get()
@endpoint
def reply(self) -> None:
pass
class TelemetryCoordinatorActor(Actor):
"""Coordinator that replies to the requesting worker."""
def __init__(self, workers: Any) -> None:
self.workers = workers
@endpoint
def request(self, rank: int) -> None:
self.workers.slice(replica=rank).reply.broadcast()
class TelemetryFailureActor(Actor):
"""Actor whose fire-and-forget endpoint fails the actor."""
@endpoint
def fail(self) -> None:
raise RuntimeError("telemetry failure")
def _telemetry_config(**kwargs: Any) -> TelemetryConfig:
kwargs.setdefault("dashboard_port", 0)
return TelemetryConfig(**kwargs)
def _sidecar_telemetry_config(**kwargs: Any) -> TelemetryConfig:
kwargs.setdefault("retention_secs", 0)
return _telemetry_config(**kwargs)
def _assert_sidecar(state) -> None:
assert state.query_engine is None
assert state.query_engine_client is not None
def _sidecar_query_rows(state, sql: str) -> list[dict[str, Any]]:
client = state.query_engine_client
assert client is not None
return client.query(sql).get("rows", [])
def _rows_to_pydict(rows: list[dict[str, Any]]) -> dict[str, list[Any]]:
if not rows:
return {}
return {column: [row.get(column) for row in rows] for column in rows[0].keys()}
def _pydict_to_rows(columns: dict[str, list[Any]]) -> list[dict[str, Any]]:
if not columns:
return []
names = list(columns)
return [
dict(zip(names, values, strict=True))
for values in zip(*(columns[name] for name in names), strict=True)
]
def _query(
state, sql: str, *, min_rows: int = 1, timeout_secs: float = 20.0
) -> dict[str, list[Any]]:
deadline = time.monotonic() + timeout_secs
rows: list[dict[str, Any]] = []
while time.monotonic() < deadline:
rows = _sidecar_query_rows(state, sql)
if len(rows) >= min_rows:
break
time.sleep(0.2)
return _rows_to_pydict(rows)
def _store_pyspy_dump(
state, dump_id: str, proc_ref: str, pyspy_result_json: str
) -> dict[str, Any]:
client = state.query_engine_client
assert client is not None
return client.store_pyspy_dump(dump_id, proc_ref, pyspy_result_json)
def _new_apply_id() -> str:
return f"test_{uuid.uuid4().hex}"
def _remove_socket_dir(apply_id: str) -> None:
shutil.rmtree(
job_telemetry_actor.telemetry_socket_dir(apply_id), ignore_errors=True
)
@pytest.fixture(autouse=True)
def _ephemeral_mesh_admin_addr():
with configured(mesh_admin_addr="[::]:0"):
yield
def _sample_pyspy_dump_json() -> str:
return json.dumps(
{
"Ok": {
"pid": 1234,
"binary": "python3",
"stack_traces": [
{
"pid": 1234,
"thread_id": 1,
"thread_name": "MainThread",
"os_thread_id": 100,
"active": True,
"owns_gil": True,
"frames": [
{
"name": "main",
"filename": "app.py",
"module": "app",
"short_filename": "app.py",
"line": 5,
"locals": [],
"is_entry": True,
}
],
}
],
"warnings": [],
}
}
)
_TELEMETRY_WORKER_MESH = "telemetry_worker"
_TELEMETRY_COORDINATOR_MESH = "telemetry_coordinator"
_TELEMETRY_FAILURE_MESH = "telemetry_failure"
def _start_telemetry_workload(state) -> None:
hosts = state.hosts
worker_procs = hosts.spawn_procs(
per_host={"replica": 2}, name="telemetry_worker_procs"
)
coordinator_proc = hosts.spawn_procs(name=_TELEMETRY_COORDINATOR_MESH)
workers = worker_procs.spawn(_TELEMETRY_WORKER_MESH, TelemetryWorkerActor)
coordinator = coordinator_proc.spawn(
_TELEMETRY_COORDINATOR_MESH, TelemetryCoordinatorActor, workers
)
workers.initialized.get()
coordinator.initialized.get()
workers.start.broadcast(coordinator)
def _start_failed_actor(state) -> tuple[int, int]:
monarch.actor.unhandled_fault_hook = lambda failure: None
failure_procs = state.hosts.spawn_procs(name="telemetry_failure_procs")
failure_actor = failure_procs.spawn(_TELEMETRY_FAILURE_MESH, TelemetryFailureActor)
failure_actor.initialized.get()
actor_id = _query(
state,
"SELECT a.id FROM actors a JOIN meshes m ON a.mesh_id = m.id "
f"WHERE m.given_name = '{_TELEMETRY_FAILURE_MESH}'",
)["id"][0]
failure_actor.fail.broadcast()
_query(
state,
"SELECT id FROM actor_status_events "
f"WHERE actor_id = {actor_id} AND new_status = 'Failed'",
)
message_id = _query(
state,
"SELECT msg.id FROM messages msg "
"JOIN actors a ON msg.to_actor_id = a.id "
"JOIN meshes m ON a.mesh_id = m.id "
f"WHERE m.given_name = '{_TELEMETRY_FAILURE_MESH}' "
"AND msg.endpoint = 'fail'",
)["id"][0]
return actor_id, message_id
@pytest.mark.timeout(30)
def test_telemetry_actor_starts_local_socket_collector() -> None:
apply_id = _new_apply_id()
_remove_socket_dir(apply_id)
try:
actor = job_telemetry_actor.TelemetryActor(apply_id, retention_secs=0)
with (
unittest.mock.patch.object(
job_telemetry_actor,
"current_rank",
return_value=types.SimpleNamespace(rank=0),
),
unittest.mock.patch.object(
job_telemetry_actor,
"_start_socket_ingest",
) as start_ingest,
):
assert actor._activate_impl()
assert actor._scanner is not None
# Second call is a no-op.
assert actor._activate_impl()
socket_dir = job_telemetry_actor.telemetry_socket_dir(apply_id)
socket_path = job_telemetry_actor.telemetry_socket_path(apply_id)
assert os.stat(socket_dir).st_mode & 0o777 == 0o700
start_ingest.assert_called_once()
assert start_ingest.call_args.args[1] == socket_path
finally:
_remove_socket_dir(apply_id)
@pytest.mark.timeout(30)
def test_telemetry_actor_reports_live_collector_activation_failure() -> None:
apply_id = _new_apply_id()
_remove_socket_dir(apply_id)
try:
actor = job_telemetry_actor.TelemetryActor(apply_id, retention_secs=0)
with (
unittest.mock.patch.object(
job_telemetry_actor,
"current_rank",
return_value=types.SimpleNamespace(rank=0),
),
unittest.mock.patch.object(
job_telemetry_actor,
"_start_socket_ingest",
side_effect=RuntimeError(
"telemetry socket already has a live collector"
),
),
):
assert not actor._activate_impl()
assert actor._scanner is None
with pytest.raises(RuntimeError, match="not an active telemetry collector"):
actor._scanner_or_raise()
finally:
_remove_socket_dir(apply_id)
@pytest.mark.timeout(30)
def test_telemetry_actor_reports_activation_failure() -> None:
apply_id = _new_apply_id()
_remove_socket_dir(apply_id)
try:
actor = job_telemetry_actor.TelemetryActor(apply_id, retention_secs=0)
with (
unittest.mock.patch.object(
job_telemetry_actor,
"current_rank",
return_value=types.SimpleNamespace(rank=0),
),
unittest.mock.patch.object(
job_telemetry_actor,
"_start_socket_ingest",
side_effect=RuntimeError("boom"),
),
):
assert not actor._activate_impl()
assert actor._scanner is None
finally:
_remove_socket_dir(apply_id)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_collector_telemetry_is_ingested_once() -> None:
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
result = _query(
state,
"SELECT id, COUNT(*) AS copies FROM meshes "
"WHERE given_name = 'telemetry_hosts' GROUP BY id",
)
assert len(result.get("id", [])) == 1, result
assert result["copies"] == [1], result
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_actors_table() -> None:
"""Test that the actors table is populated when actors are spawned."""
# Spawn some worker actors - this should trigger notify_actor_created
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
hosts = state.hosts
worker_procs = hosts.spawn_procs(per_host={"workers": 2})
workers = worker_procs.spawn("test_worker", WorkerActor)
workers.initialized.get()
# Query the actors table to verify actors were recorded
result_dict = _query(
state,
"SELECT a.* FROM actors a "
"JOIN meshes mesh ON a.mesh_id = mesh.id "
"WHERE mesh.given_name = 'test_worker'",
)
# We should have at least some actors recorded
# (the exact count depends on internal actors created)
actor_count = len(result_dict.get("id", []))
assert actor_count > 0, f"Expected at least one actor, got {actor_count}"
# Verify the schema has the expected columns
expected_columns = {
"id",
"timestamp_us",
"mesh_id",
"rank",
"full_name",
"display_name",
}
actual_columns = set(result_dict.keys())
assert expected_columns == actual_columns, (
f"Expected columns {expected_columns}, got {actual_columns}"
)
# Verify full_name is populated with canonical actor identifiers.
full_names = result_dict.get("full_name", [])
assert all(full_names), (
f"Expected non-empty full_name values, got: {full_names}"
)
# Verify display_name carries the user-facing supervision name.
display_names = result_dict.get("display_name", [])
has_test_worker = any(
name is not None and "test_worker" in name for name in display_names
)
assert has_test_worker, (
f"Expected to find 'test_worker' in actor display names, got: {display_names}"
)
# Verify that the bootstrap client actor is recorded with display_name "<root>".
result_dict = _query(state, "SELECT display_name FROM actors")
root_display_names = result_dict.get("display_name", [])
assert "<root>" in root_display_names, (
f"Expected bootstrap client actor with display_name '<root>', got: {root_display_names}"
)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_telemetry_workload_actor_topology() -> None:
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
_start_telemetry_workload(state)
result = _query(
state,
"SELECT a.id, a.timestamp_us, a.rank, a.full_name, "
"m.given_name, m.class FROM actors a "
"JOIN meshes m ON a.mesh_id = m.id "
f"WHERE m.given_name IN ('{_TELEMETRY_WORKER_MESH}', "
f"'{_TELEMETRY_COORDINATOR_MESH}')",
min_rows=4,
)
rows = _pydict_to_rows(result)
assert len(rows) == 4, rows
assert Counter(row["class"] for row in rows) == {
"Proc": 1,
"Python<TelemetryWorkerActor>": 2,
"Python<TelemetryCoordinatorActor>": 1,
}
workers = [
row for row in rows if row["class"] == "Python<TelemetryWorkerActor>"
]
assert sorted(row["rank"] for row in workers) == [0, 1]
assert [
row["rank"]
for row in rows
if row["class"] == "Python<TelemetryCoordinatorActor>"
] == [0]
assert len({row["id"] for row in rows}) == 4
assert all(row["timestamp_us"] > 0 for row in rows)
assert all(ActorAddr.from_string(row["full_name"]) for row in rows)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_meshes_table() -> None:
"""Test that the meshes table is populated when actor meshes are spawned."""
# Spawn some worker actors - this should trigger notify_mesh_created
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
hosts = state.hosts
worker_procs = hosts.spawn_procs(per_host={"workers": 2})
workers = worker_procs.spawn("test_mesh_worker", WorkerActor)
workers.initialized.get()
# Query the meshes table to verify actor meshes were recorded
result_dict = _query(
state,
"SELECT * FROM meshes WHERE given_name = 'test_mesh_worker'",
)
# We should have at least some actor meshes recorded
mesh_count = len(result_dict.get("id", []))
assert mesh_count > 0, f"Expected at least one actor mesh, got {mesh_count}"
# Verify the schema has the expected columns
expected_columns = {
"id",
"timestamp_us",
"class",
"given_name",
"full_name",
"shape_json",
"parent_mesh_id",
"parent_view_json",
}
actual_columns = set(result_dict.keys())
assert expected_columns == actual_columns, (
f"Expected columns {expected_columns}, got {actual_columns}"
)
# Verify given_name is the user-provided name (not the full name with UUID suffix)
given_names = result_dict.get("given_name", [])
full_names = result_dict.get("full_name", [])
assert "test_mesh_worker" in given_names, (
f"Expected exact 'test_mesh_worker' in given_names, got: {given_names}"
)
for gn, fn in zip(given_names, full_names):
if gn == "test_mesh_worker":
# full_name includes a UUID suffix, so it should differ from given_name
assert fn != gn, (
f"Expected full_name to differ from given_name, but both are '{gn}'"
)
assert fn.startswith("test_mesh_worker"), (
f"Expected full_name to start with 'test_mesh_worker', got: {fn}"
)
# Verify parent_view_json is populated (serialized Region from ndslice)
parent_views = result_dict.get("parent_view_json", [])
for name, view in zip(given_names, parent_views):
if name == "test_mesh_worker":
assert view is not None, (
f"Expected parent_view_json to be populated for '{name}', got None"
)
parsed_view = json.loads(view)
# Region serializes as {"labels": [...], "slice": {"offset": ..., "sizes": [...], "strides": [...]}}
assert "slice" in parsed_view, (
f"Expected parent_view_json to contain 'slice' key (ndslice Region), got: {parsed_view}"
)
assert "labels" in parsed_view, (
f"Expected parent_view_json to contain 'labels' key, got: {parsed_view}"
)
# Verify shape_json describes the actor mesh's shape (serialized Extent from ndslice)
shape_jsons = result_dict.get("shape_json", [])
for name, shape in zip(given_names, shape_jsons):
if name == "test_mesh_worker":
assert shape is not None and shape != "", (
f"Expected shape_json to be populated for '{name}', got '{shape}'"
)
parsed_shape = json.loads(shape)
# Extent serializes as {"inner": {"labels": [...], "sizes": [...]}}
assert "inner" in parsed_shape, (
f"Expected shape_json to contain 'inner' key (ndslice Extent), got: {parsed_shape}"
)
labels = parsed_shape["inner"]["labels"]
sizes = parsed_shape["inner"]["sizes"]
assert "workers" in labels, (
f"Expected shape_json labels to contain 'workers', got: {labels}"
)
workers_idx = labels.index("workers")
assert sizes[workers_idx] == 2, (
f"Expected 2 workers in shape, got: {sizes[workers_idx]}"
)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_telemetry_workload_mesh_topology() -> None:
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
_start_telemetry_workload(state)
rows = _pydict_to_rows(
_query(
state,
"SELECT id, timestamp_us, class, given_name, shape_json, "
"parent_mesh_id FROM meshes "
f"WHERE given_name IN ('{_TELEMETRY_WORKER_MESH}', "
f"'{_TELEMETRY_COORDINATOR_MESH}')",
min_rows=3,
)
)
assert len(rows) == 3, rows
assert Counter(row["class"] for row in rows) == {
"Proc": 1,
"Python<TelemetryWorkerActor>": 1,
"Python<TelemetryCoordinatorActor>": 1,
}
assert len({row["id"] for row in rows}) == 3
assert all(row["timestamp_us"] > 0 for row in rows)
worker_mesh = next(
row for row in rows if row["class"] == "Python<TelemetryWorkerActor>"
)
worker_shape = json.loads(worker_mesh["shape_json"])["inner"]
assert worker_shape == {
"labels": ["hosts", "replica"],
"sizes": [1, 2],
}
coordinator_proc = next(row for row in rows if row["class"] == "Proc")
coordinator_actor_mesh = next(
row for row in rows if row["class"] == "Python<TelemetryCoordinatorActor>"
)
assert coordinator_actor_mesh["parent_mesh_id"] == coordinator_proc["id"]
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_proc_mesh_in_meshes_table() -> None:
"""Test that ProcMesh creation is recorded in the meshes table with class 'Proc'."""
# Spawn a named proc mesh — this should emit a mesh event with class "Proc"
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
hosts = state.hosts
worker_procs = hosts.spawn_procs(per_host={"workers": 2}, name="proc_mesh_test")
workers = worker_procs.spawn("proc_mesh_test_worker", WorkerActor)
workers.initialized.get()
# Query meshes with class "Proc"
result_dict = _query(
state,
"SELECT given_name, full_name, class, shape_json, parent_mesh_id, parent_view_json "
"FROM meshes WHERE class = 'Proc' AND given_name = 'proc_mesh_test'",
)
# Verify our named proc mesh appears with the correct given_name.
# The bootstrap path also emits a "local" proc mesh, so filter for ours.
given_names = result_dict.get("given_name", [])
assert "proc_mesh_test" in given_names, (
f"Expected 'proc_mesh_test' in given_names, got: {given_names}"
)
# Verify full_name differs from given_name (includes UUID suffix)
full_names = result_dict.get("full_name", [])
for gn, fn in zip(given_names, full_names):
if gn == "proc_mesh_test":
assert fn != gn, (
f"Expected full_name to differ from given_name, but both are '{gn}'"
)
assert fn.startswith("proc_mesh_test"), (
f"Expected full_name to start with 'proc_mesh_test', got: {fn}"
)
# Verify shape_json is populated for the proc mesh
shape_jsons = result_dict.get("shape_json", [])
for gn, shape in zip(given_names, shape_jsons):
if gn == "proc_mesh_test":
assert shape is not None and shape != "", (
f"Expected shape_json to be populated for '{gn}', got '{shape}'"
)
parsed_shape = json.loads(shape)
assert "inner" in parsed_shape, (
f"Expected shape_json to contain 'inner' key (ndslice Extent), got: {parsed_shape}"
)
labels = parsed_shape["inner"]["labels"]
sizes = parsed_shape["inner"]["sizes"]
assert "workers" in labels, (
f"Expected shape_json labels to contain 'workers', got: {labels}"
)
workers_idx = labels.index("workers")
assert sizes[workers_idx] == 2, (
f"Expected 2 workers in shape, got: {sizes[workers_idx]}"
)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_actors_join_meshes_on_mesh_id() -> None:
"""Test that actors.mesh_id matches meshes.id, enabling joins."""
# Spawn actors — this populates both the actors and meshes tables
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
hosts = state.hosts
worker_procs = hosts.spawn_procs(per_host={"workers": 2})
workers = worker_procs.spawn("join_test_worker", WorkerActor)
workers.initialized.get()
# Join actors with meshes on mesh_id = id
result_dict = _query(
state,
"""SELECT a.full_name AS actor_name,
a.mesh_id,
a.rank,
m.given_name AS mesh_name,
m.class AS mesh_class
FROM actors a
INNER JOIN meshes m ON a.mesh_id = m.id
WHERE m.given_name = 'join_test_worker'
ORDER BY a.rank""",
min_rows=2,
)
# The join should produce results — if mesh_id doesn't match, this is empty
joined_count = len(result_dict.get("actor_name", []))
assert joined_count > 0, (
"Expected actors to join with meshes on mesh_id, but got 0 rows. "
"This means actors.mesh_id does not match any meshes.id."
)
# Every joined row should reference our mesh name
mesh_names = result_dict.get("mesh_name", [])
assert all("join_test_worker" in name for name in mesh_names), (
f"Expected all joined rows to reference 'join_test_worker', got: {mesh_names}"
)
actor_names = result_dict.get("actor_name", [])
assert all(actor_names), (
f"Expected canonical actor names to be populated, got: {actor_names}"
)
# With 2 workers, we should see 2 joined rows
assert joined_count == 2, (
f"Expected 2 joined rows for 2 workers, got: {joined_count}"
)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_all_actors_in_proc_mesh() -> None:
"""Test that all actor meshes within a proc mesh have actors in the actors table."""
# Spawn a named proc mesh and user actors
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
hosts = state.hosts
worker_procs = hosts.spawn_procs(per_host={"workers": 2}, name="workers_procs")
workers = worker_procs.spawn("worker_actors", WorkerActor)
workers.initialized.get()
# Get the proc mesh entry so we can filter child meshes by parent_mesh_id
proc_dict = _query(
state,
"SELECT id FROM meshes WHERE class = 'Proc' AND given_name = 'workers_procs'",
)
proc_ids = proc_dict.get("id", [])
assert len(proc_ids) == 1, f"Expected exactly 1 proc mesh, got {len(proc_ids)}"
proc_mesh_id = proc_ids[0]
# ProcAgent actors have mesh_id pointing directly to the proc mesh
proc_agents = _query(
state,
f"SELECT DISTINCT id FROM actors WHERE mesh_id = {proc_mesh_id}",
min_rows=2,
)
proc_agents_count = len(proc_agents.get("id", []))
assert proc_agents_count == 2, (
f"Expected 2 ProcAgent actors, got {proc_agents_count}"
)
# Query all child actor meshes of this proc mesh
child_dict = _query(
state,
f"SELECT id, class, given_name FROM meshes WHERE parent_mesh_id = {proc_mesh_id}",
min_rows=4,
)
child_classes = child_dict.get("class", [])
child_names = child_dict.get("given_name", [])
child_ids = child_dict.get("id", [])
assert set(child_names) == {
"worker_actors",
"logger",
"setup",
}
# For every child actor mesh, verify that actors exist in the actors table
for mesh_id, mesh_class, mesh_name in zip(
child_ids, child_classes, child_names
):
actor_dict = _query(
state,
f"SELECT DISTINCT id, rank, full_name, display_name "
f"FROM actors WHERE mesh_id = {mesh_id}",
min_rows=2,
)
actor_count = len(actor_dict.get("id", []))
# Each mesh on a 2-worker proc mesh should have exactly 2 actors
assert actor_count == 2, (
f"Expected 2 actors for mesh '{mesh_name}' (class={mesh_class}), "
f"got {actor_count}: {actor_dict}"
)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_all_actors_in_host_mesh() -> None:
"""Test that all actor meshes within a proc mesh have actors in the actors table."""
# Spawn a named proc mesh and user actors
with scoped_state(
ProcessJob({"hosts": 2}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
hosts = state.hosts
worker_procs = hosts.spawn_procs(per_host={"workers": 2}, name="workers_procs")
workers = worker_procs.spawn("worker_actors", WorkerActor)
workers.initialized.get()
# Get the hosts mesh entry so we can filter child meshes by parent_mesh_id
host_mesh_result = _query(
state,
"SELECT hosts.id FROM meshes hosts "
"JOIN meshes proc ON proc.parent_mesh_id = hosts.id "
"WHERE hosts.class = 'Host' "
"AND hosts.given_name = 'hosts' "
"AND proc.given_name = 'workers_procs'",
)
host_mesh_ids = host_mesh_result.get("id", [])
assert len(host_mesh_ids) == 1, (
f"Expected exactly 1 hosts mesh, got {len(host_mesh_ids)}"
)
host_mesh_id = host_mesh_ids[0]
# HostAgent actors have mesh_id pointing directly to the host mesh
host_agents = _query(
state, f"SELECT DISTINCT id FROM actors WHERE mesh_id = {host_mesh_id}"
)
host_agents_count = len(host_agents.get("id", []))
assert host_agents_count > 0, (
f"Expected HostAgent actors, got {host_agents_count}"
)
# Query all proc meshes of this hosts mesh
proc_dict = _query(
state,
f"SELECT id, class, given_name FROM meshes WHERE parent_mesh_id = {host_mesh_id}",
)
proc_given_names = set(proc_dict.get("given_name", []))
assert "workers_procs" in proc_given_names
# Query all child actor meshes of this hosts mesh
child_dict = _query(
state,
f"""
SELECT m.id, m.class, m.given_name
FROM meshes m
INNER JOIN meshes proc ON m.parent_mesh_id = proc.id
INNER JOIN meshes hosts ON proc.parent_mesh_id = hosts.id
WHERE hosts.id = {host_mesh_id}
AND proc.given_name = 'workers_procs'
""",
min_rows=4,
)
child_classes = child_dict.get("class", [])
child_names = child_dict.get("given_name", [])
child_ids = child_dict.get("id", [])
assert set(child_names) == {
"worker_actors",
"logger",
"setup",
}
# For every child actor mesh, verify that actors exist in the actors table
for mesh_id, mesh_class, mesh_name in zip(
child_ids, child_classes, child_names
):
actor_dict = _query(
state,
f"SELECT DISTINCT id FROM actors WHERE mesh_id = {mesh_id}",
min_rows=4,
)
actor_count = len(actor_dict.get("id", []))
assert actor_count == 4, (
f"Expected 4 actors for mesh '{mesh_name}' (class={mesh_class}), "
f"got {actor_count}"
)
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_actor_status_events_table() -> None:
"""Test that the actor_status_events table is populated when actors change status."""
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
hosts = state.hosts
worker_procs = hosts.spawn_procs(per_host={"workers": 2})
workers = worker_procs.spawn("status_test_worker", WorkerActor)
workers.initialized.get()
result_dict = _query(state, "SELECT * FROM actor_status_events")
expected_columns = {
"id",
"timestamp_us",
"actor_id",
"new_status",
"reason",
}
actual_columns = set(result_dict.keys())
assert expected_columns == actual_columns, (
f"Expected columns {expected_columns}, got {actual_columns}"
)
worker_rows = _pydict_to_rows(
_query(
state,
"SELECT ase.actor_id, ase.new_status, ase.reason "
"FROM actor_status_events ase "
"JOIN actors a ON ase.actor_id = a.id "
"JOIN meshes m ON a.mesh_id = m.id "
"WHERE m.given_name = 'status_test_worker'",
min_rows=6,
)
)
statuses_by_actor = {
actor_id: {
row["new_status"] for row in worker_rows if row["actor_id"] == actor_id
}
for actor_id in {row["actor_id"] for row in worker_rows}
}
assert len(statuses_by_actor) == 2
assert all(
statuses == {"Created", "Initializing", "Idle"}
for statuses in statuses_by_actor.values()
), statuses_by_actor
assert all(row["reason"] is None for row in worker_rows)
client_rows = _query(
state,
"SELECT ase.id FROM actor_status_events ase "
"JOIN actors a ON ase.actor_id = a.id "
"WHERE a.display_name = '<root>' AND ase.new_status = 'Client'",
)
assert client_rows["id"]
valid_statuses = {
"Unknown",
"Created",
"Initializing",
"Client",
"Idle",
"Processing",
"Stopping",
"Stopped",
"Failed",
}
new_statuses = set(
_query(state, "SELECT DISTINCT new_status FROM actor_status_events")[
"new_status"
]
)
assert new_statuses.issubset(valid_statuses), (
f"Found unexpected status values: {new_statuses - valid_statuses}"
)
assert "Unknown" not in new_statuses
@pytest.mark.timeout(120)
@isolate_in_subprocess
def test_user_actor_status_lifecycle() -> None:
with scoped_state(
ProcessJob({"hosts": 1}).enable_telemetry(_sidecar_telemetry_config()),
cached_path=None,
) as state:
_assert_sidecar(state)
_start_telemetry_workload(state)
_query(
state,
"SELECT msg.id FROM messages msg "
"JOIN actors a ON msg.to_actor_id = a.id "
"JOIN meshes m ON a.mesh_id = m.id "