-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathactor.rs
More file actions
1804 lines (1661 loc) · 67.7 KB
/
Copy pathactor.rs
File metadata and controls
1804 lines (1661 loc) · 67.7 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.
*/
use std::error::Error;
use std::fmt::Debug;
use std::future::pending;
use std::ops::Deref;
use std::sync::OnceLock;
use async_trait::async_trait;
use hyperactor::Actor;
use hyperactor::ActorHandle;
use hyperactor::Context;
use hyperactor::Handler;
use hyperactor::Instance;
use hyperactor::OncePortHandle;
use hyperactor::PortHandle;
use hyperactor::Proc;
use hyperactor::RemoteSpawn;
use hyperactor::actor::ActorError;
use hyperactor::actor::ActorErrorKind;
use hyperactor::actor::ActorStatus;
use hyperactor::actor::Signal;
use hyperactor::context::Actor as ContextActor;
use hyperactor::mailbox::MessageEnvelope;
use hyperactor::mailbox::Undeliverable;
use hyperactor::message::Bind;
use hyperactor::message::Bindings;
use hyperactor::message::IndexedErasedUnbound;
use hyperactor::message::Unbind;
use hyperactor::supervision::ActorSupervisionEvent;
use hyperactor_config::Flattrs;
use hyperactor_mesh::casting::update_undeliverable_envelope_for_casting;
use hyperactor_mesh::comm::multicast::CAST_POINT;
use hyperactor_mesh::comm::multicast::CastInfo;
use hyperactor_mesh::supervision::MeshFailure;
use hyperactor_mesh::transport::default_bind_spec;
use hyperactor_mesh::value_mesh::ValueOverlay;
use monarch_types::PickledPyObject;
use monarch_types::SerializablePyErr;
use monarch_types::py_global;
use ndslice::Point;
use ndslice::extent;
use pyo3::IntoPyObjectExt;
use pyo3::exceptions::PyBaseException;
use pyo3::exceptions::PyRuntimeError;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3::types::PyList;
use pyo3::types::PyType;
use serde::Deserialize;
use serde::Serialize;
use serde_multipart::Part;
use tokio::sync::oneshot;
use typeuri::Named;
use crate::buffers::FrozenBuffer;
use crate::config::ACTOR_QUEUE_DISPATCH;
use crate::config::SHARED_ASYNCIO_RUNTIME;
use crate::context::PyInstance;
use crate::local_state_broker::BrokerId;
use crate::local_state_broker::LocalStateBrokerMessage;
use crate::mailbox::EitherPortRef;
use crate::mailbox::PyMailbox;
use crate::mailbox::PythonPortHandle;
use crate::mailbox::PythonUndeliverableMessageEnvelope;
use crate::metrics::ENDPOINT_ACTOR_COUNT;
use crate::metrics::ENDPOINT_ACTOR_ERROR;
use crate::metrics::ENDPOINT_ACTOR_LATENCY_US_HISTOGRAM;
use crate::metrics::ENDPOINT_ACTOR_PANIC;
use crate::pickle::pickle_to_part;
use crate::proc::PyActorId;
use crate::pympsc;
use crate::pytokio::PythonTask;
use crate::runtime::get_proc_runtime;
use crate::runtime::get_tokio_runtime;
use crate::runtime::monarch_with_gil;
use crate::runtime::monarch_with_gil_blocking;
use crate::supervision::PyMeshFailure;
py_global!(
unhandled_fault_hook_exception,
"monarch._src.actor.supervision",
"UnhandledFaultHookException"
);
#[pyclass(module = "monarch._rust_bindings.monarch_hyperactor.actor")]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum UnflattenArg {
Mailbox,
PyObject,
}
#[pyclass(module = "monarch._rust_bindings.monarch_hyperactor.actor")]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum MethodSpecifier {
/// Call method 'name', send its return value to the response port.
ReturnsResponse { name: String },
/// Call method 'name', send the response port as the first argument.
ExplicitPort { name: String },
/// Construct the object
Init {},
}
impl std::fmt::Display for MethodSpecifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name())
}
}
#[pymethods]
impl MethodSpecifier {
#[getter(name)]
fn py_name(&self) -> &str {
self.name()
}
}
impl MethodSpecifier {
pub(crate) fn name(&self) -> &str {
match self {
MethodSpecifier::ReturnsResponse { name } => name,
MethodSpecifier::ExplicitPort { name } => name,
MethodSpecifier::Init {} => "__init__",
}
}
}
/// The payload of a single actor response, without rank information.
///
/// The rank is captured by the overlay's range key, so it is stripped
/// from the value to enable RLE dedup: two ranks returning the same
/// payload will have byte-identical values and can be coalesced into
/// a single run.
#[derive(Clone, Debug, Serialize, Deserialize, Named, PartialEq, Eq)]
pub enum PythonResponseMessage {
Result(serde_multipart::Part),
Exception(serde_multipart::Part),
}
wirevalue::register_type!(PythonResponseMessage);
wirevalue::register_type!(ValueOverlay<PythonResponseMessage>);
/// Newtype wrapper around [`ValueOverlay<PythonResponseMessage>`] needed
/// because `PythonMessageKind` is a `#[pyclass]` enum, requiring all variant
/// fields to implement PyO3 traits. `ValueOverlay` is defined in another crate
/// and does not implement `PyClass`.
#[pyclass(frozen, module = "monarch._rust_bindings.monarch_hyperactor.actor")]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct AccumulatedResponses(ValueOverlay<PythonResponseMessage>);
#[pyclass(module = "monarch._rust_bindings.monarch_hyperactor.actor")]
#[derive(Clone, Debug, Serialize, Deserialize, Named, PartialEq)]
pub enum PythonMessageKind {
CallMethod {
name: MethodSpecifier,
response_port: Option<EitherPortRef>,
},
Result {
rank: Option<usize>,
},
Exception {
rank: Option<usize>,
},
Uninit {},
CallMethodIndirect {
name: MethodSpecifier,
local_state_broker: (String, usize),
id: usize,
// specify whether the argument to unflatten the local mailbox,
// or the next argument of the local state.
unflatten_args: Vec<UnflattenArg>,
},
AccumulatedResponses(AccumulatedResponses),
}
wirevalue::register_type!(PythonMessageKind);
impl Default for PythonMessageKind {
fn default() -> Self {
PythonMessageKind::Uninit {}
}
}
fn mailbox<'py, T: Actor>(py: Python<'py>, cx: &Context<'_, T>) -> Bound<'py, PyAny> {
let mailbox: PyMailbox = cx.mailbox_for_py().clone().into();
mailbox.into_bound_py_any(py).unwrap()
}
#[pyclass(frozen, module = "monarch._rust_bindings.monarch_hyperactor.actor")]
#[derive(Clone, Serialize, Deserialize, Named, Default, PartialEq)]
pub struct PythonMessage {
pub kind: PythonMessageKind,
pub message: Part,
}
/// Extract the endpoint method name from a [`PythonMessage`].
fn python_message_endpoint_name(msg: &PythonMessage) -> Option<String> {
match &msg.kind {
PythonMessageKind::CallMethod { name, .. }
| PythonMessageKind::CallMethodIndirect { name, .. } => Some(name.name().to_string()),
_ => None,
}
}
// We use manual `submit!` instead of `register_type!` because PythonMessage is a
// struct, so the default `endpoint_name` (which delegates to `arm_unchecked`)
// always returns None. The custom implementation inspects `PythonMessageKind` to
// extract the method name. This registration handles direct (non-cast) dispatch.
wirevalue::submit! {
wirevalue::TypeInfo {
typename: <PythonMessage as wirevalue::Named>::typename,
typehash: <PythonMessage as wirevalue::Named>::typehash,
typeid: <PythonMessage as wirevalue::Named>::typeid,
port: <PythonMessage as wirevalue::Named>::port,
dump: Some(<PythonMessage as wirevalue::NamedDumpable>::dump),
arm_unchecked: <PythonMessage as wirevalue::Named>::arm_unchecked,
endpoint_name: |ptr| {
// SAFETY: ptr points to a PythonMessage.
let msg = unsafe { &*(ptr as *const PythonMessage) };
python_message_endpoint_name(msg)
},
}
}
// Cast messages arrive as IndexedErasedUnbound<PythonMessage>, which wraps a
// serialized PythonMessage. This type has no `register_type!` by default (it
// shares ErasedUnbound's wire format), so we register it explicitly. The
// endpoint_name deserializes the inner payload to read the method name. This
// costs one extra deserialization per message, but the Part payload uses
// zero-copy Bytes refcounting, and Python actor throughput is GIL-bounded,
// so the serde overhead is negligible relative to Python-side processing.
wirevalue::submit! {
wirevalue::TypeInfo {
typename: <IndexedErasedUnbound<PythonMessage> as wirevalue::Named>::typename,
typehash: <IndexedErasedUnbound<PythonMessage> as wirevalue::Named>::typehash,
typeid: <IndexedErasedUnbound<PythonMessage> as wirevalue::Named>::typeid,
port: <IndexedErasedUnbound<PythonMessage> as wirevalue::Named>::port,
dump: None,
arm_unchecked: <IndexedErasedUnbound<PythonMessage> as wirevalue::Named>::arm_unchecked,
endpoint_name: |ptr| {
// SAFETY: ptr points to an IndexedErasedUnbound<PythonMessage>.
let erased = unsafe { &*(ptr as *const IndexedErasedUnbound<PythonMessage>) };
erased
.inner_any()
.deserialized_unchecked::<PythonMessage>()
.ok()
.and_then(|msg| python_message_endpoint_name(&msg))
},
}
}
impl From<ValueOverlay<PythonResponseMessage>> for PythonMessage {
fn from(overlay: ValueOverlay<PythonResponseMessage>) -> Self {
PythonMessage {
kind: PythonMessageKind::AccumulatedResponses(AccumulatedResponses(overlay)),
message: Default::default(),
}
}
}
impl PythonMessage {
/// Consume this message and extract a `ValueOverlay<PythonResponseMessage>`.
///
/// Handles both already-collected responses and leaf `Result`/`Exception`
/// messages by wrapping them in a single-run overlay.
pub fn into_overlay(self) -> anyhow::Result<ValueOverlay<PythonResponseMessage>> {
match self.kind {
PythonMessageKind::AccumulatedResponses(overlay) => Ok(overlay.0),
PythonMessageKind::Result { rank, .. } => {
let rank = rank.expect("accumulated response should have a rank");
let mut overlay = ValueOverlay::new();
overlay.push_run(rank..rank + 1, PythonResponseMessage::Result(self.message))?;
Ok(overlay)
}
PythonMessageKind::Exception { rank, .. } => {
let rank = rank.expect("accumulated exception should have a rank");
let mut overlay = ValueOverlay::new();
overlay.push_run(
rank..rank + 1,
PythonResponseMessage::Exception(self.message),
)?;
Ok(overlay)
}
other => {
anyhow::bail!(
"unexpected message kind {:?} in collected responses reducer",
other
);
}
}
}
}
struct ResolvedCallMethod {
method: MethodSpecifier,
bytes: FrozenBuffer,
local_state: Option<Py<PyAny>>,
/// Implements PortProtocol
/// Concretely either a Port, DroppingPort, or LocalPort
response_port: ResponsePort,
}
enum ResponsePort {
Dropping,
Port(Port),
Local(LocalPort),
}
impl ResponsePort {
fn into_py_any(self, py: Python<'_>) -> PyResult<Py<PyAny>> {
match self {
ResponsePort::Dropping => DroppingPort.into_py_any(py),
ResponsePort::Port(port) => port.into_py_any(py),
ResponsePort::Local(port) => port.into_py_any(py),
}
}
}
/// Message sent through the queue in queue-dispatch mode.
/// Contains pre-resolved components ready for Python consumption.
#[pyclass(frozen, module = "monarch._rust_bindings.monarch_hyperactor.actor")]
pub struct QueuedMessage {
#[pyo3(get)]
pub context: Py<crate::context::PyContext>,
#[pyo3(get)]
pub method: MethodSpecifier,
#[pyo3(get)]
pub bytes: FrozenBuffer,
#[pyo3(get)]
pub local_state: Py<PyAny>,
#[pyo3(get)]
pub response_port: Py<PyAny>,
}
impl PythonMessage {
pub fn new_from_buf(kind: PythonMessageKind, message: impl Into<Part>) -> Self {
Self {
kind,
message: message.into(),
}
}
pub fn into_rank(self, rank: usize) -> Self {
let rank = Some(rank);
match self.kind {
PythonMessageKind::Result { .. } => PythonMessage {
kind: PythonMessageKind::Result { rank },
message: self.message,
},
PythonMessageKind::Exception { .. } => PythonMessage {
kind: PythonMessageKind::Exception { rank },
message: self.message,
},
_ => panic!("PythonMessage is not a response but {:?}", self),
}
}
async fn resolve_indirect_call(
self,
cx: &Context<'_, PythonActor>,
) -> anyhow::Result<ResolvedCallMethod> {
match self.kind {
PythonMessageKind::CallMethodIndirect {
name,
local_state_broker,
id,
unflatten_args,
} => {
let broker = BrokerId::new(local_state_broker).resolve(cx).await;
let (send, recv) = cx.open_once_port();
broker.send(cx, LocalStateBrokerMessage::Get(id, send))?;
let state = recv.recv().await?;
let mut state_it = state.state.into_iter();
monarch_with_gil(|py| {
let mailbox = mailbox(py, cx);
let local_state = Some(
PyList::new(
py,
unflatten_args.into_iter().map(|x| -> Bound<'_, PyAny> {
match x {
UnflattenArg::Mailbox => mailbox.clone(),
UnflattenArg::PyObject => {
state_it.next().unwrap().into_bound(py)
}
}
}),
)
.unwrap()
.into(),
);
let response_port = ResponsePort::Local(LocalPort {
instance: cx.into(),
inner: Some(state.response_port),
});
Ok(ResolvedCallMethod {
method: name,
bytes: FrozenBuffer {
inner: self.message.into_bytes(),
},
local_state,
response_port,
})
})
.await
}
PythonMessageKind::CallMethod {
name,
response_port,
} => {
let response_port = response_port.map_or(ResponsePort::Dropping, |port_ref| {
let point = cx.cast_point();
ResponsePort::Port(Port {
port_ref,
instance: cx.instance().clone_for_py(),
rank: Some(point.rank()),
})
});
Ok(ResolvedCallMethod {
method: name,
bytes: FrozenBuffer {
inner: self.message.into_bytes(),
},
local_state: None,
response_port,
})
}
_ => {
panic!("unexpected message kind {:?}", self.kind)
}
}
}
}
impl std::fmt::Debug for PythonMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PythonMessage")
.field("kind", &self.kind)
.field(
"message",
&wirevalue::HexFmt(&(*self.message.to_bytes())[..]).to_string(),
)
.finish()
}
}
impl Unbind for PythonMessage {
fn unbind(&self, bindings: &mut Bindings) -> anyhow::Result<()> {
match &self.kind {
PythonMessageKind::CallMethod { response_port, .. } => response_port.unbind(bindings),
_ => Ok(()),
}
}
}
impl Bind for PythonMessage {
fn bind(&mut self, bindings: &mut Bindings) -> anyhow::Result<()> {
match &mut self.kind {
PythonMessageKind::CallMethod { response_port, .. } => response_port.bind(bindings),
_ => Ok(()),
}
}
}
#[pymethods]
impl PythonMessage {
#[new]
#[pyo3(signature = (kind, message))]
pub fn new<'py>(kind: PythonMessageKind, message: PyRef<'py, FrozenBuffer>) -> PyResult<Self> {
Ok(PythonMessage::new_from_buf(kind, message.inner.clone()))
}
#[getter]
fn kind(&self) -> PythonMessageKind {
self.kind.clone()
}
#[getter]
fn message(&self) -> FrozenBuffer {
FrozenBuffer {
inner: self.message.to_bytes(),
}
}
}
#[pyclass(module = "monarch._rust_bindings.monarch_hyperactor.actor")]
pub(super) struct PythonActorHandle {
pub(super) inner: ActorHandle<PythonActor>,
}
#[pymethods]
impl PythonActorHandle {
// TODO: do the pickling in rust
fn send(&self, instance: &PyInstance, message: &PythonMessage) -> PyResult<()> {
self.inner
.send(instance.deref(), message.clone())
.map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
Ok(())
}
fn bind(&self) -> PyActorId {
self.inner.bind::<PythonActor>().into_actor_id().into()
}
}
/// Dispatch mode for Python actors.
#[derive(Debug)]
pub enum PythonActorDispatchMode {
/// Direct dispatch: Rust acquires the GIL and calls Python handlers directly.
Direct,
/// Queue dispatch: Rust enqueues messages to a channel; Python dequeues and dispatches.
Queue {
/// Channel sender for enqueuing messages to Python.
sender: pympsc::Sender,
/// Channel receiver, taken during Actor::init to start the message loop.
receiver: Option<pympsc::PyReceiver>,
},
}
/// An actor for which message handlers are implemented in Python.
#[derive(Debug)]
#[hyperactor::export(
spawn = true,
handlers = [
PythonMessage { cast = true },
MeshFailure { cast = true },
],
)]
pub struct PythonActor {
/// The Python object that we delegate message handling to.
actor: Py<PyAny>,
/// Stores a reference to the Python event loop to run Python coroutines on.
/// This is None when using single runtime mode, Some when using per-actor mode.
task_locals: Option<pyo3_async_runtimes::TaskLocals>,
/// Instance object that we keep across handle calls so that we can store
/// information from the Init (spawn rank, controller) and provide it to other calls.
instance: Option<Py<crate::context::PyInstance>>,
/// Dispatch mode for this actor.
dispatch_mode: PythonActorDispatchMode,
/// The location in the actor mesh at which this actor was spawned.
spawn_point: OnceLock<Option<Point>>,
/// Initial message to process during PythonActor::init.
init_message: Option<PythonMessage>,
}
impl PythonActor {
pub(crate) fn new(
actor_type: PickledPyObject,
init_message: Option<PythonMessage>,
spawn_point: Option<Point>,
) -> Result<Self, anyhow::Error> {
let use_queue_dispatch = hyperactor_config::global::get(ACTOR_QUEUE_DISPATCH);
Ok(monarch_with_gil_blocking(
|py| -> Result<Self, SerializablePyErr> {
let unpickled = actor_type.unpickle(py)?;
let class_type: &Bound<'_, PyType> = unpickled.downcast()?;
let actor: Py<PyAny> = class_type.call0()?.into_py_any(py)?;
// Only create per-actor TaskLocals if not using shared runtime
let task_locals = (!hyperactor_config::global::get(SHARED_ASYNCIO_RUNTIME))
.then(|| Python::detach(py, create_task_locals));
let dispatch_mode = if use_queue_dispatch {
let (sender, receiver) = pympsc::channel().map_err(|e| {
let py_err = PyRuntimeError::new_err(e.to_string());
SerializablePyErr::from(py, &py_err)
})?;
PythonActorDispatchMode::Queue {
sender,
receiver: Some(receiver),
}
} else {
PythonActorDispatchMode::Direct
};
Ok(Self {
actor,
task_locals,
instance: None,
dispatch_mode,
spawn_point: OnceLock::from(spawn_point),
init_message,
})
},
)?)
}
/// Get the TaskLocals to use for this actor.
/// Returns either the shared TaskLocals or this actor's own TaskLocals based on configuration.
fn get_task_locals(&self, py: Python) -> &pyo3_async_runtimes::TaskLocals {
self.task_locals
.as_ref()
.unwrap_or_else(|| shared_task_locals(py))
}
/// Bootstrap the root client actor, creating a new proc for it.
/// This is the legacy entry point that creates its own proc.
pub(crate) fn bootstrap_client(py: Python<'_>) -> (&'static Instance<Self>, ActorHandle<Self>) {
static ROOT_CLIENT_INSTANCE: OnceLock<Instance<PythonActor>> = OnceLock::new();
let client_proc = Proc::direct(
default_bind_spec().binding_addr(),
"mesh_root_client_proc".into(),
)
.unwrap();
Self::bootstrap_client_inner(py, client_proc, &ROOT_CLIENT_INSTANCE)
}
/// Bootstrap the client proc, storing the root client instance in given static.
/// This is passed in because we require storage, as the instance is shared.
/// This can be simplified when we remove v0.
pub(crate) fn bootstrap_client_inner(
py: Python<'_>,
client_proc: Proc,
root_client_instance: &'static OnceLock<Instance<PythonActor>>,
) -> (&'static Instance<Self>, ActorHandle<Self>) {
let actor_mesh_mod = py
.import("monarch._src.actor.actor_mesh")
.expect("import actor_mesh");
let root_client_class = actor_mesh_mod
.getattr("RootClientActor")
.expect("get RootClientActor");
let actor_type =
PickledPyObject::pickle(&actor_mesh_mod.getattr("_Actor").expect("get _Actor"))
.expect("pickle _Actor");
let init_frozen_buffer: FrozenBuffer = root_client_class
.call_method0("_pickled_init_args")
.expect("call RootClientActor._pickled_init_args")
.extract()
.expect("extract FrozenBuffer from _pickled_init_args");
let init_message = PythonMessage::new_from_buf(
PythonMessageKind::CallMethod {
name: MethodSpecifier::Init {},
response_port: None,
},
init_frozen_buffer,
);
let mut actor = PythonActor::new(
actor_type,
Some(init_message),
Some(extent!().point_of_rank(0).unwrap()),
)
.expect("create client PythonActor");
let ai = client_proc
.actor_instance(
root_client_class
.getattr("name")
.expect("get RootClientActor.name")
.extract()
.expect("extract RootClientActor.name"),
)
.expect("root instance create");
let handle = ai.handle;
let signal_rx = ai.signal;
let supervision_rx = ai.supervision;
let work_rx = ai.work;
root_client_instance
.set(ai.instance)
.map_err(|_| "already initialized root client instance")
.unwrap();
let instance = root_client_instance.get().unwrap();
// The root client PythonActor uses a custom run loop that
// bypasses Actor::init, so mark it as system explicitly
// (matching GlobalClientActor::fresh_instance).
instance.set_system();
// Bind to ensure the Signal and Undeliverable<MessageEnvelope> ports
// are bound.
let _client_ref = handle.bind::<PythonActor>();
get_tokio_runtime().spawn(async move {
// This is gross. Sorry.
actor.init(instance).await.unwrap();
let mut signal_rx = signal_rx;
let mut supervision_rx = supervision_rx;
let mut work_rx = work_rx;
let mut need_drain = false;
let mut err = 'messages: loop {
tokio::select! {
work = work_rx.recv() => {
let work = work.expect("inconsistent work queue state");
if let Err(err) = work.handle(&mut actor, instance).await {
// Check for UnhandledFaultHookException on the raw
// anyhow::Error before wrapping in ActorErrorKind.
// If __supervise__ already processed the supervision
// event and the hook raised, don't re-handle it via
// handle_supervision_event — that would call
// __supervise__ a second time.
let is_hook_exception = monarch_with_gil(|py| {
err.downcast_ref::<pyo3::PyErr>()
.is_some_and(|pyerr| {
pyerr.is_instance(
py,
&unhandled_fault_hook_exception(py),
)
})
}).await;
let kind = ActorErrorKind::processing(err);
let err = ActorError {
actor_id: Box::new(instance.self_id().clone()),
kind: Box::new(kind),
};
if is_hook_exception {
break Some(err);
}
// Give the actor a chance to handle the error produced
// in its own message handler. This is important because
// we want Undeliverable<MessageEnvelope>, which returns
// an Err typically, to create a supervision event and
// call __supervise__.
let supervision_event = actor_error_to_event(instance, &actor, err);
// If the immediate supervision event isn't handled, continue with
// exiting the loop.
// Else, continue handling messages.
if let Err(err) = instance.handle_supervision_event(&mut actor, supervision_event).await {
for supervision_event in supervision_rx.drain() {
if let Err(err) = instance.handle_supervision_event(&mut actor, supervision_event).await {
break 'messages Some(err);
}
}
break Some(err);
}
}
}
signal = signal_rx.recv() => {
let signal = signal.map_err(ActorError::from);
tracing::info!(actor_id = %instance.self_id(), "client received signal {signal:?}");
match signal {
Ok(signal@(Signal::Stop(_) | Signal::DrainAndStop(_))) => {
need_drain = matches!(signal, Signal::DrainAndStop(_));
break None;
},
Ok(Signal::ChildStopped(_)) => {},
Ok(Signal::Abort(reason)) => {
break Some(ActorError { actor_id: Box::new(instance.self_id().clone()), kind: Box::new(ActorErrorKind::Aborted(reason)) })
},
Err(err) => break Some(err),
}
}
Ok(supervision_event) = supervision_rx.recv() => {
if let Err(err) = instance.handle_supervision_event(&mut actor, supervision_event).await {
break Some(err);
}
}
};
};
if need_drain {
let mut n = 0;
while let Ok(work) = work_rx.try_recv() {
if let Err(e) = work.handle(&mut actor, instance).await {
err = Some(ActorError {
actor_id: Box::new(instance.self_id().clone()),
kind: Box::new(ActorErrorKind::processing(e)),
});
break;
}
n += 1;
}
tracing::debug!(actor_id = %instance.self_id(), "client drained {} messages before stopping", n);
}
if let Some(err) = err {
let event = actor_error_to_event(instance, &actor, err);
// The proc supervision handler will send to ProcAgent, which
// just records it in v1. We want to crash instead, as nothing will
// monitor the client ProcAgent for now.
tracing::error!(
actor_id = %instance.self_id(),
"could not propagate supervision event {} because it reached the global client: signaling KeyboardInterrupt to main thread",
event,
);
// This is running in a background thread, and thus cannot run
// Py_FinalizeEx when it exits the process to properly shut down
// all python objects.
// We use _thread.interrupt_main to raise a KeyboardInterrupt
// to the main thread at some point in the future.
// There is no way to propagate the exception message, but it
// will at least run proper shutdown code as long as BaseException
// isn't caught.
monarch_with_gil_blocking(|py| {
// Use _thread.interrupt_main to force the client to exit if it has an
// unhandled supervision event.
let thread_mod = py.import("_thread").expect("import _thread");
let interrupt_main = thread_mod
.getattr("interrupt_main")
.expect("get interrupt_main");
// Ignore any exception from calling interrupt_main
if let Err(e) = interrupt_main.call0() {
tracing::error!("unable to interrupt main, exiting the process instead: {:?}", e);
eprintln!("unable to interrupt main, exiting the process with code 1 instead: {:?}", e);
std::process::exit(1);
}
});
} else {
tracing::info!(actor_id = %instance.self_id(), "client stopped");
}
});
(root_client_instance.get().unwrap(), handle)
}
}
fn actor_error_to_event(
instance: &Instance<PythonActor>,
actor: &PythonActor,
err: ActorError,
) -> ActorSupervisionEvent {
match *err.kind {
ActorErrorKind::UnhandledSupervisionEvent(event) => *event,
_ => {
let status = ActorStatus::generic_failure(err.kind.to_string());
ActorSupervisionEvent::new(
instance.self_id().clone(),
actor.display_name(),
status,
None,
)
}
}
}
pub(crate) fn root_client_actor(py: Python<'_>) -> &'static Instance<PythonActor> {
static ROOT_CLIENT_ACTOR: OnceLock<&'static Instance<PythonActor>> = OnceLock::new();
// Release the GIL before waiting on ROOT_CLIENT_ACTOR, because PythonActor::bootstrap_client
// may release/reacquire the GIL; if thread 0 holds the GIL blocking on ROOT_CLIENT_ACTOR.get_or_init
// while thread 1 blocks on acquiring the GIL inside PythonActor::bootstrap_client, we get
// a deadlock.
py.detach(|| {
ROOT_CLIENT_ACTOR.get_or_init(|| {
monarch_with_gil_blocking(|py| {
let (client, _handle) = PythonActor::bootstrap_client(py);
client
})
})
})
}
#[async_trait]
impl Actor for PythonActor {
async fn init(&mut self, this: &Instance<Self>) -> Result<(), anyhow::Error> {
if let PythonActorDispatchMode::Queue { receiver, .. } = &mut self.dispatch_mode {
let receiver = receiver.take().unwrap();
// Create an error port that converts PythonMessage to an abort signal.
// This allows Python to send errors that trigger actor supervision.
let error_port: hyperactor::PortHandle<PythonMessage> =
this.port::<Signal>().contramap(|msg: PythonMessage| {
monarch_with_gil_blocking(|py| {
let err = match msg.kind {
PythonMessageKind::Exception { .. } => {
// Deserialize the error from the message
let cloudpickle = py.import("cloudpickle").unwrap();
let err_obj = cloudpickle
.call_method1("loads", (msg.message.to_bytes().as_ref(),))
.unwrap();
let py_err = pyo3::PyErr::from_value(err_obj);
SerializablePyErr::from(py, &py_err)
}
_ => {
let py_err = PyRuntimeError::new_err(format!(
"expected Exception, got {:?}",
msg.kind
));
SerializablePyErr::from(py, &py_err)
}
};
Signal::Abort(err.to_string())
})
});
let error_port_handle = PythonPortHandle::new(error_port);
monarch_with_gil(|py| {
let tl = self
.task_locals
.as_ref()
.unwrap_or_else(|| shared_task_locals(py));
let awaitable = self.actor.call_method(
py,
"_dispatch_loop",
(receiver, error_port_handle),
None,
)?;
let future =
pyo3_async_runtimes::into_future_with_locals(tl, awaitable.into_bound(py))?;
tokio::spawn(async move {
if let Err(e) = future.await {
tracing::error!("message loop error: {}", e);
}
});
Ok::<_, anyhow::Error>(())
})
.await?;
}
if let Some(init_message) = self.init_message.take() {
let spawn_point = self.spawn_point.get().unwrap().as_ref().expect("PythonActor should never be spawned with init_message unless spawn_point also specified").clone();
let mut headers = Flattrs::new();
headers.set(CAST_POINT, spawn_point);
let cx = Context::new(this, headers);
<Self as Handler<PythonMessage>>::handle(self, &cx, init_message).await?;
}
Ok(())
}
async fn cleanup(
&mut self,
this: &Instance<Self>,
err: Option<&ActorError>,
) -> anyhow::Result<()> {
// Calls the "__cleanup__" method on the python instance to allow the actor
// to control its own cleanup.
// No headers because this isn't in the context of a message.
let cx = Context::new(this, Flattrs::new());
// Turn the ActorError into a representation of the error. We may not
// have an original exception object or traceback, so we just pass in
// the message.
let err_as_str = err.map(|e| e.to_string());
let future = monarch_with_gil(|py| {
let py_cx = match &self.instance {
Some(instance) => crate::context::PyContext::new(&cx, instance.clone_ref(py)),
None => {
let py_instance: crate::context::PyInstance = this.into();
crate::context::PyContext::new(
&cx,
py_instance
.into_py_any(py)?
.downcast_bound(py)
.map_err(PyErr::from)?
.clone()
.unbind(),
)
}
}
.into_bound_py_any(py)?;
let actor = self.actor.bind(py);
// Some tests don't use the Actor base class, so add this check
// to be defensive.
match actor.hasattr("__cleanup__") {
Ok(false) | Err(_) => {
// No cleanup found, default to returning None
return Ok(None);
}
_ => {}
}
let awaitable = actor
.call_method("__cleanup__", (&py_cx, err_as_str), None)
.map_err(|err| anyhow::Error::from(SerializablePyErr::from(py, &err)))?;
if awaitable.is_none() {
Ok(None)
} else {
pyo3_async_runtimes::into_future_with_locals(self.get_task_locals(py), awaitable)
.map(Some)
.map_err(anyhow::Error::from)
}
})
.await?;
if let Some(future) = future {
future.await.map_err(anyhow::Error::from)?;
}
Ok(())
}
fn display_name(&self) -> Option<String> {
self.instance.as_ref().and_then(|instance| {
monarch_with_gil_blocking(|py| instance.bind(py).str().ok().map(|s| s.to_string()))
})
}
async fn handle_undeliverable_message(
&mut self,
ins: &Instance<Self>,
mut envelope: Undeliverable<MessageEnvelope>,
) -> Result<(), anyhow::Error> {
if envelope.0.sender() != ins.self_id() {
// This can happen if the sender is comm. Update the envelope.
envelope = update_undeliverable_envelope_for_casting(envelope);
}
assert_eq!(
envelope.0.sender(),