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
use std::cell::RefCell;
use std::collections::HashSet;
use std::sync::Arc;
#[cfg(feature = "timing")]
use std::time::{Duration, Instant};

use atomic_refcell::AtomicRefCell;
use nando_support::{
    activation_id::ActivationId,
    ecb_id::EcbId,
    epic_control::{SpawnedTask, ECB},
    ObjectVersion,
};
use nando_support::{activation_intent, log_entry, nando_metadata, ObjectId, TxnId};
use object_lib::{
    tls::{IntoObjectMapping, ObjectMapping},
    IPtr, MaterializedObjectVersion, Object,
};
use object_tracker::ObjectTracker;
use ownership_tracker::OwnershipTracker;

use crate::txn_context::TxnContext;
use crate::{
    activation::activation_intent::{NandoArgument, NandoResult},
    nando_handle::{ActivationOutput, HandleCompletionState, SharedHandleState},
    nando_handle::{ExecutionError, TransactionStatus},
};

pub type ActivationFunction =
    dyn Fn(TxnContext, SharedHandleState, &Vec<ResolvedNandoArgument>) -> ();

#[derive(Clone)]
pub enum ObjectResolutionMode {
    Na,
    Ro,
    Rw,
    // NOTE this is useful for correctly setting the MV-enabled flag for the given object in case
    // of first access on the current worker, since the executor executing the transaction will
    // have to notify the scheduler to disable mv.
    // All objects are assumed to be mv-enabled and the only way for mv to be disabled on the
    // object is for the executor to detect that the predicate to support mv (which currently
    // consists only of a check of the object's size) stopped being satisfied because of the
    // transaction it just executed. If the object in question was moved to the current worker
    // _and_ it already didn't satisfy the multiversioning predicate, then the object will be set
    // as mv-enabled on the scheduler's side and it will never be disabled. This mode allows us to
    // special-case the handling of these objects in the executor.
    RwFirstLocalAccess,
}

impl ObjectResolutionMode {
    pub fn is_first_local_access(&self) -> bool {
        match self {
            Self::RwFirstLocalAccess => true,
            _ => false,
        }
    }
}

#[derive(Clone)]
pub enum ObjectArgument {
    RWObject(Arc<Object>),
    ROObject(Arc<MaterializedObjectVersion>),
    UnresolvedObject((IPtr, ObjectResolutionMode)),
}

impl ObjectArgument {
    pub fn as_object_ref(&self) -> Option<&Object> {
        match self {
            Self::RWObject(o) => Some(o.as_ref()),
            _ => None,
        }
    }

    pub fn as_materialized_object_ref(&self) -> Option<&MaterializedObjectVersion> {
        match self {
            Self::ROObject(o) => Some(o.as_ref()),
            _ => None,
        }
    }

    pub fn get_iptr(&self) -> IPtr {
        match self {
            Self::RWObject(ref o) => IPtr::new(o.get_id(), 0, 0),
            Self::ROObject(ref o) => IPtr::new(o.get_id(), 0, 0),
            Self::UnresolvedObject((ref iptr, _)) => iptr.clone(),
        }
    }

    pub fn get_object_id(&self) -> ObjectId {
        match self {
            Self::RWObject(ref o) => o.get_id(),
            Self::ROObject(ref o) => o.get_id(),
            Self::UnresolvedObject((ref iptr, _)) => iptr.get_object_id(),
        }
    }

    pub fn set_rw_unresolved(&mut self, first_local_access: bool) {
        match self {
            Self::UnresolvedObject((_, ref mut mode)) => {
                *mode = match first_local_access {
                    true => ObjectResolutionMode::RwFirstLocalAccess,
                    false => ObjectResolutionMode::Rw,
                };
            }
            _ => (),
        }
    }

    pub fn set_ro_unresolved(&mut self) {
        match self {
            Self::UnresolvedObject((_, ref mut mode)) => *mode = ObjectResolutionMode::Ro,
            _ => (),
        }
    }

    pub fn offset_of(&self, field: *const ()) -> IPtr {
        match self {
            Self::RWObject(ref o) => o.offset_of(field),
            _ => unreachable!("requested offset_of for non-rw object"),
        }
    }

    pub fn get_version(&self) -> Option<ObjectVersion> {
        match self {
            Self::RWObject(ref o) => Some(o.get_version()),
            Self::ROObject(ref o) => Some(o.get_version()),
            _ => None,
        }
    }
}

impl std::fmt::Debug for ObjectArgument {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ObjectArgument::RWObject(o) => {
                f.write_fmt(format_args!("Object {{ {} }}", o.get_id(),))
            }
            ObjectArgument::ROObject(o) => {
                f.write_fmt(format_args!("RO Object {{ {} }}", o.get_id()))
            }
            ObjectArgument::UnresolvedObject((i, _)) => i.fmt(f),
        }
    }
}

impl Into<NandoResult> for &ObjectArgument {
    fn into(self) -> NandoResult {
        match self {
            ObjectArgument::RWObject(o) => NandoResult::Ref(o.iptr_of()),
            ObjectArgument::ROObject(o) => NandoResult::Ref(o.iptr_of()),
            ObjectArgument::UnresolvedObject((i, _)) => NandoResult::Ref(*i),
        }
    }
}

#[derive(Clone)]
pub enum ResolvedNandoArgument {
    Object(ObjectArgument),
    Objects(Vec<ObjectArgument>),
    Value(activation_intent::ScalarValue),
    ControlBlock(EcbId),
}

impl ResolvedNandoArgument {
    pub fn get_inner_object_argument(&self) -> Option<&ObjectArgument> {
        match self {
            Self::Object(ref oa) => Some(oa),
            _ => None,
        }
    }

    // FIXME should return some iterator instead.
    pub fn get_inner_object_arguments(&self) -> Vec<&ObjectArgument> {
        match self {
            Self::Object(ref oa) => vec![oa],
            Self::Objects(os) => os.iter().collect(),
            _ => Vec::default(),
        }
    }

    pub fn get_inner_object_argument_mut(&mut self) -> Option<&mut ObjectArgument> {
        match self {
            Self::Object(ref mut oa) => Some(oa),
            _ => None,
        }
    }
}

impl std::fmt::Debug for ResolvedNandoArgument {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Object(o) => o.fmt(f),
            Self::Objects(ref os) => {
                f.write_str("Refs {")
                    .expect("failed to fmt refs ResolvedNandoArgument");
                for o in os {
                    o.fmt(f).expect("failed to fmt object ref");
                    f.write_str(",").expect("failed to write list separator");
                }
                f.write_str("}")
            }
            Self::Value(v) => v.fmt(f),
            Self::ControlBlock(ecb_id) => {
                f.write_fmt(format_args!("Control Block {{ {} }}", ecb_id))
            }
        }
    }
}

impl Into<NandoResult> for &ResolvedNandoArgument {
    fn into(self) -> NandoResult {
        match self {
            ResolvedNandoArgument::Object(o) => o.into(),
            o @ ResolvedNandoArgument::Objects(_) => o.into(),
            ResolvedNandoArgument::Value(ref v) => v.into(),
            ResolvedNandoArgument::ControlBlock(_) => {
                panic!("cannot convert control block into result")
            }
        }
    }
}

#[cfg(feature = "timing")]
pub struct TimingInfo {
    transaction_start: Instant,
    transaction_end: Instant,

    // This captures the moment the activation was placed on a processor queue.
    scheduled_at: Instant,
    execution_start: Instant,
    execution_end: Instant,

    logging_start: Instant,
    logging_end: Instant,

    // queueing times
    tm_to_sched_queue_start: Instant,
    tm_to_sched_queue_end: Instant,
    sched_to_exec_queue_start: Instant,
    sched_to_exec_queue_end: Instant,
    exec_to_logger_queue_start: Instant,
    exec_to_logger_queue_end: Instant,
    logger_to_sched_queue_start: Instant,
    logger_to_sched_queue_end: Instant,
}

#[cfg(feature = "timing")]
impl TimingInfo {
    fn new() -> Self {
        let init = Instant::now();
        Self {
            transaction_start: init,
            transaction_end: init,
            scheduled_at: init,
            execution_start: init,
            execution_end: init,
            logging_start: init,
            logging_end: init,
            tm_to_sched_queue_start: init,
            tm_to_sched_queue_end: init,
            sched_to_exec_queue_start: init,
            sched_to_exec_queue_end: init,
            exec_to_logger_queue_start: init,
            exec_to_logger_queue_end: init,
            logger_to_sched_queue_start: init,
            logger_to_sched_queue_end: init,
        }
    }
}

pub enum EpicTaskInfo {
    NonEpic,
    TaskDependency(SpawnedTask),
    ControlBlock(Arc<RefCell<ECB>>),
}

impl EpicTaskInfo {
    fn is_epic(&self) -> bool {
        match self {
            Self::NonEpic => false,
            _ => true,
        }
    }

    fn is_spawned_task(&self) -> bool {
        match self {
            Self::TaskDependency(_) => true,
            _ => false,
        }
    }

    fn get_ecb_id(&self) -> Option<EcbId> {
        match self {
            Self::ControlBlock(ecb) => Some(ecb.borrow().id),
            _ => None,
        }
    }
}

pub enum ActivationEpicInformation {
    NotPartOfEpic,
    TopLevel,
    NonTopLevel,
}

#[allow(dead_code)]
pub struct NandoActivation {
    pub activation_id: ActivationId,
    pub activation_intent: activation_intent::NandoActivationIntent,
    pub activation_log_entry: Arc<RefCell<log_entry::TransactionLogEntry>>,

    // NOTE this is shared with the handle the local scheduler returns to the transaction manager
    pub handle_state: Option<SharedHandleState>,

    pub executor: usize,

    resolved_args: RefCell<Vec<ResolvedNandoArgument>>,
    target: Arc<ActivationFunction>,

    pub meta: nando_metadata::NandoMetadata,
    // pub is_top_level: bool,
    pub epic_information: ActivationEpicInformation,

    pub ecb: EpicTaskInfo,
    pub status: TransactionStatus,
    pub execution_error: Option<ExecutionError>,

    pub mv_updates: RefCell<Vec<(ObjectId, bool)>>,

    #[cfg(feature = "timing")]
    timing_info: RefCell<TimingInfo>,
}

unsafe impl Send for NandoActivation {}

impl NandoActivation {
    pub fn new(
        mut activation_intent: activation_intent::NandoActivationIntent,
        txn_id: TxnId,
        handle_state: Option<SharedHandleState>,
        nando_closure: Arc<ActivationFunction>,
        meta: nando_metadata::NandoMetadata,
    ) -> Self {
        let resolved_args: Vec<_> = activation_intent
            .args
            .drain(..)
            .map(|a| match a {
                NandoArgument::Value(v) => ResolvedNandoArgument::Value(v),
                NandoArgument::Ref(i) => ResolvedNandoArgument::Object(
                    ObjectArgument::UnresolvedObject((i, ObjectResolutionMode::Na)),
                ),
                NandoArgument::MRef(ref is) => {
                    let objects = is
                        .get_inner()
                        .iter()
                        .map(|i| ObjectArgument::UnresolvedObject((*i, ObjectResolutionMode::Na)))
                        .collect();

                    ResolvedNandoArgument::Objects(objects)
                }
                _ => unreachable!(),
            })
            .collect();
        let num_args = resolved_args.len();

        Self {
            activation_intent,
            activation_id: ActivationId::new_for_txn(txn_id),
            activation_log_entry: Arc::new(RefCell::new(log_entry::TransactionLogEntry::new(
                txn_id, None,
            ))),
            handle_state,
            target: nando_closure,
            resolved_args: RefCell::new(resolved_args),

            meta,
            executor: 0,

            epic_information: ActivationEpicInformation::NotPartOfEpic,
            ecb: EpicTaskInfo::NonEpic,

            status: TransactionStatus::Pending,
            execution_error: None,

            mv_updates: RefCell::new(Vec::with_capacity(num_args)),

            #[cfg(feature = "timing")]
            timing_info: RefCell::new(TimingInfo::new()),
        }
    }

    pub fn from_intent(
        mut intent: activation_intent::NandoActivationIntent,
        activation_id: ActivationId,
        nando_closure: Arc<ActivationFunction>,
        meta: nando_metadata::NandoMetadata,
    ) -> Self {
        let resolved_args: Vec<_> = intent
            .args
            .drain(..)
            .map(|a| match a {
                NandoArgument::Value(v) => ResolvedNandoArgument::Value(v),
                NandoArgument::Ref(i) => ResolvedNandoArgument::Object(
                    ObjectArgument::UnresolvedObject((i, ObjectResolutionMode::Na)),
                ),
                NandoArgument::MRef(ref is) => {
                    let objects = is
                        .get_inner()
                        .iter()
                        .map(|i| ObjectArgument::UnresolvedObject((*i, ObjectResolutionMode::Na)))
                        .collect();

                    ResolvedNandoArgument::Objects(objects)
                }
                _ => unreachable!(),
            })
            .collect();
        let num_args = resolved_args.len();

        Self {
            activation_id,
            activation_intent: intent,
            activation_log_entry: Arc::new(RefCell::new(log_entry::TransactionLogEntry::new(
                0, None,
            ))),
            handle_state: None,
            executor: 0,
            resolved_args: RefCell::new(resolved_args),
            target: nando_closure,
            meta,

            // is_top_level: false,
            epic_information: ActivationEpicInformation::NonTopLevel,
            ecb: EpicTaskInfo::NonEpic,
            status: TransactionStatus::Pending,
            execution_error: None,

            mv_updates: RefCell::new(Vec::with_capacity(num_args)),

            #[cfg(feature = "timing")]
            timing_info: RefCell::new(TimingInfo::new()),
        }
    }

    pub fn set_top_level(&mut self) {
        self.epic_information = ActivationEpicInformation::TopLevel;
    }

    pub fn set_non_top_level(&mut self) {
        self.epic_information = ActivationEpicInformation::NonTopLevel;
    }

    pub fn handle_is_dummy(&self) -> bool {
        self.handle_state.is_none() || self.handle_state.as_ref().unwrap().borrow().is_dummy()
    }

    pub fn get_result(&self) -> ActivationOutput {
        self.handle_state.as_ref().unwrap().borrow().get_result()
    }

    pub fn get_object_references(&self) -> Vec<ObjectId> {
        self.resolved_args
            .borrow()
            .iter()
            .fold(HashSet::new(), |mut acc, arg| {
                match arg {
                    ResolvedNandoArgument::Object(o) => {
                        acc.insert(o.get_object_id());
                    }
                    ResolvedNandoArgument::Objects(ref os) => {
                        for o in os {
                            acc.insert(o.get_object_id());
                        }
                    }
                    _ => {}
                };

                acc
            })
            .into_iter()
            .collect()
    }

    pub fn mark_done_and_wake(&self) {
        if self.handle_state.is_none() {
            #[cfg(debug_assertions)]
            println!("no handle state for activation, cannot wake");
            return;
        }

        let completion_handle = self.handle_state.as_ref();
        let completion_state = completion_handle.unwrap().borrow();
        completion_state.mark_done_and_wake();
    }

    pub fn mark_triggered_and_wake(&self) {
        if self.handle_state.is_none() {
            return;
        }

        let completion_handle = self.handle_state.as_ref();
        let completion_state = completion_handle.unwrap().borrow();
        completion_state.mark_triggered_and_wake();
    }

    // FIXME add reason for failure
    pub fn mark_failed_and_wake(&self) {
        if self.handle_state.is_none() {
            return;
        }

        let completion_handle = self.handle_state.as_ref();
        let mut completion_state = completion_handle.unwrap().borrow_mut();
        completion_state.mark_failed_and_wake(
            self.execution_error
                .clone()
                .expect("no error set for failed activation"),
        );
    }

    pub fn set_handle_state(&mut self, handle_state: SharedHandleState) {
        if self.handle_state.is_some() {
            // FIXME no need to panic
            panic!("attempt to override activation handle state");
        }

        self.handle_state = Some(handle_state);
    }

    pub fn get_handle_state(&self) -> Option<SharedHandleState> {
        match &self.handle_state {
            None => None,
            Some(ref hs) => Some(Arc::clone(hs)),
        }
    }

    pub fn resolve_intent_arg(&mut self, idx: usize, resolved_arg: NandoArgument) {
        self.activation_intent.resolve_intent_arg(idx, resolved_arg);
    }

    pub fn call(&self, object_tracker: Arc<ObjectTracker>) {
        // FIXME eliminate the need for this dummy handle state
        let handle_state = match self.handle_state {
            Some(ref hs) => Arc::clone(hs),
            None => Arc::new(AtomicRefCell::new(HandleCompletionState::new())),
        };

        // TODO panic and signal handling.
        let ownership_tracker = OwnershipTracker::get_ownership_tracker(None);
        let resolved_args = self.resolved_args.borrow();

        let mut ctx = TxnContext::new(
            Arc::clone(&self.activation_log_entry),
            Arc::clone(&object_tracker),
            ownership_tracker,
            resolved_args.len(),
        );
        ctx.set_ecb(self.get_ecb());

        (self.target)(ctx, Arc::clone(&handle_state), &resolved_args);
    }

    pub fn get_resolved_args(&self) -> &RefCell<Vec<ResolvedNandoArgument>> {
        &self.resolved_args
    }

    pub fn get_resolved_object_arg_mappings(&self) -> Vec<ObjectMapping> {
        self.resolved_args
            .borrow()
            .iter()
            .fold(vec![], |mut acc, ra| {
                if let Some(oa) = ra.get_inner_object_argument() {
                    match oa {
                        ObjectArgument::RWObject(o) => acc.push(o.into_mapping()),
                        ObjectArgument::ROObject(o) => acc.push(o.into_mapping()),
                        ObjectArgument::UnresolvedObject(_) => unreachable!(),
                    }
                }

                acc
            })
    }

    pub fn is_part_of_epic(&self) -> bool {
        if self.meta.spawns_nandos {
            return true;
        }

        match self.epic_information {
            ActivationEpicInformation::NotPartOfEpic => false,
            _ => true,
        }
    }

    pub fn set_ecb(&mut self, ecb: ECB) {
        if self.ecb.is_epic() && !self.ecb.is_spawned_task() {
            panic!(
                "attempt to overwrite ecb with id {:?}",
                self.ecb.get_ecb_id()
            );
        }
        self.ecb = EpicTaskInfo::ControlBlock(Arc::new(RefCell::new(ecb)));
    }

    pub fn get_ecb(&self) -> Option<Arc<RefCell<ECB>>> {
        match self.ecb {
            EpicTaskInfo::ControlBlock(ref e) => Some(Arc::clone(e)),
            _ => None,
        }
    }

    pub fn set_top_level_ecb(&mut self, host_idx: u64) {
        let ecb = {
            let mut ecb = ECB::new_top_level(host_idx, self.activation_id);
            match &self.ecb {
                EpicTaskInfo::TaskDependency(st) => {
                    // FIXME avoid clone
                    ecb.planning_context = st.planning_context.clone();
                }
                _ => unreachable!(),
            }
            ecb
        };

        self.set_ecb(ecb);
    }

    pub fn set_ecb_from_dependency_info(mut self) -> Self {
        self.ecb = match self.ecb {
            EpicTaskInfo::TaskDependency(task) => {
                EpicTaskInfo::ControlBlock(Arc::new(RefCell::new(task.into_ecb())))
            }
            _ => panic!("not allowed"),
        };

        self
    }

    #[cfg(feature = "object-caching")]
    pub fn should_mask_invalidations(&self) -> bool {
        match self.ecb {
            EpicTaskInfo::TaskDependency(ref task) => task.should_mask_invalidations(),
            EpicTaskInfo::ControlBlock(ref block) => {
                let block = block.borrow();
                block.should_mask_invalidations()
            }
            EpicTaskInfo::NonEpic => false,
        }
    }

    pub fn set_task_control_info(&mut self, task_control_info: SpawnedTask) {
        self.ecb = EpicTaskInfo::TaskDependency(task_control_info);
    }

    pub fn get_task_control_info(&self) -> Option<SpawnedTask> {
        match self.ecb {
            EpicTaskInfo::TaskDependency(ref spawned_task) => Some(spawned_task.clone()),
            _ => None,
        }
    }

    pub fn get_task_control_id(&self) -> Option<EcbId> {
        match self.ecb {
            EpicTaskInfo::TaskDependency(ref spawned_task) => Some(spawned_task.id),
            EpicTaskInfo::ControlBlock(ref ecb) => Some(ecb.borrow().id),
            _ => None,
        }
    }

    pub fn is_top_level(&self) -> bool {
        match self.epic_information {
            ActivationEpicInformation::TopLevel => true,
            _ => false,
        }
    }

    pub fn set_status_done(&mut self) {
        self.status = TransactionStatus::Done;
    }

    pub fn set_status_failed(&mut self, err: ExecutionError) {
        self.status = TransactionStatus::Failed;
        self.execution_error = Some(err);
    }

    pub fn is_pending(&self) -> bool {
        match self.status {
            TransactionStatus::Pending => true,
            _ => false,
        }
    }

    pub fn is_failed(&self) -> bool {
        match self.status {
            TransactionStatus::Failed => true,
            _ => false,
        }
    }

    pub fn add_mv_update(&self, object_id: ObjectId, mv_enabled: bool) {
        let mut mv_updates = self.mv_updates.borrow_mut();
        mv_updates.push((object_id, mv_enabled));
    }

    pub fn get_object_arg_at_idx(&self, arg_idx: usize) -> Option<ObjectId> {
        let resolved_args = self.resolved_args.borrow();

        match resolved_args.get(arg_idx) {
            None => None,
            Some(arg) => {
                let object_args = arg.get_inner_object_arguments();
                if object_args.is_empty() {
                    return None;
                }

                match object_args.len() > 1 {
                    false => Some(object_args[0].get_object_id()),
                    // NOTE this might be surprising, but there should be a separate function to
                    // get some id(s) in case of a ref vec.
                    true => None,
                }
            }
        }
    }

    pub fn get_object_args_at_idx(&self, arg_idx: usize) -> Vec<ObjectId> {
        let resolved_args = self.resolved_args.borrow();

        match resolved_args.get(arg_idx) {
            None => panic!("no resolved arg for idx {arg_idx}"),
            Some(arg) => {
                let object_args = arg.get_inner_object_arguments();
                object_args.iter().map(|oa| oa.get_object_id()).collect()
            }
        }
    }

    pub fn get_args_as_intent_args(&self) -> Vec<NandoArgument> {
        let args = self.resolved_args.borrow();
        args.iter()
            .map(|a| match a {
                ResolvedNandoArgument::Value(v) => NandoArgument::Value(v.clone()),
                ResolvedNandoArgument::Object((ObjectArgument::UnresolvedObject((o, _)))) => {
                    NandoArgument::Ref(*o)
                }
                ResolvedNandoArgument::Objects(os) => {
                    NandoArgument::MRef(activation_intent::IPtrList::from_vec(
                        os.iter().map(|o| o.get_iptr()).collect(),
                    ))
                }
                _ => panic!(),
            })
            .collect()
    }

    #[cfg(feature = "timing")]
    pub fn set_timing_entity(&self, entity: &str, value: Instant) {
        let timing_info = &mut self.timing_info.borrow_mut();
        match entity {
            "transaction_start" => timing_info.transaction_start = value,
            "transaction_end" => timing_info.transaction_end = value,
            "scheduled_at" => timing_info.scheduled_at = value,
            "execution_start" => timing_info.execution_start = value,
            "execution_end" => timing_info.execution_end = value,
            "logging_start" => timing_info.logging_start = value,
            "logging_end" => timing_info.logging_end = value,
            "tm_to_sched_queue_start" => timing_info.tm_to_sched_queue_start = value,
            "tm_to_sched_queue_end" => timing_info.tm_to_sched_queue_end = value,
            "sched_to_exec_queue_start" => timing_info.sched_to_exec_queue_start = value,
            "sched_to_exec_queue_end" => timing_info.sched_to_exec_queue_end = value,
            "exec_to_logger_queue_start" => timing_info.exec_to_logger_queue_start = value,
            "exec_to_logger_queue_end" => timing_info.exec_to_logger_queue_end = value,
            "logger_to_sched_queue_start" => timing_info.logger_to_sched_queue_start = value,
            "logger_to_sched_queue_end" => timing_info.logger_to_sched_queue_end = value,
            _ => panic!("unrecognized timing field {}", entity),
        }
    }

    #[cfg(feature = "timing")]
    pub fn print_timing_stats(&self) {
        let mut timing_stats_string = String::new();

        let timing_info = &self.timing_info.borrow();
        let execution_duration = timing_info
            .execution_end
            .duration_since(timing_info.execution_start);
        timing_stats_string.push_str(&format!(
            "Execution: {}us ({}ns)",
            execution_duration.as_micros(),
            execution_duration.as_nanos()
        ));

        let logging_duration = timing_info
            .logging_end
            .duration_since(timing_info.logging_start);
        if logging_duration > Duration::default() {
            timing_stats_string.push_str(&format!(
                "\nLogging: {}us ({}ns)",
                logging_duration.as_micros(),
                logging_duration.as_nanos()
            ));
        }

        let transaction_duration = timing_info
            .transaction_end
            .duration_since(timing_info.transaction_start);
        if transaction_duration > Duration::default() {
            timing_stats_string.push_str(&format!(
                "\nE2E transaction latency: {}us ({}ns)",
                transaction_duration.as_micros(),
                transaction_duration.as_nanos()
            ));
        }

        let scheduling_latency = timing_info
            .scheduled_at
            .duration_since(timing_info.transaction_start);
        if scheduling_latency > Duration::default() {
            timing_stats_string.push_str(&format!(
                "\nScheduling latency: {}us ({}ns)",
                scheduling_latency.as_micros(),
                scheduling_latency.as_nanos()
            ));
        }

        let tm_to_sched_latency = timing_info
            .tm_to_sched_queue_end
            .duration_since(timing_info.tm_to_sched_queue_start);
        if tm_to_sched_latency > Duration::default() {
            timing_stats_string.push_str(&format!(
                "\nTM<->Scheduler queue latency: {}us ({}ns)",
                tm_to_sched_latency.as_micros(),
                tm_to_sched_latency.as_nanos()
            ));
        }

        let sched_to_exec_latency = timing_info
            .sched_to_exec_queue_end
            .duration_since(timing_info.sched_to_exec_queue_start);
        if sched_to_exec_latency > Duration::default() {
            timing_stats_string.push_str(&format!(
                "\nScheduler<->Executor queue latency: {}us ({}ns)",
                sched_to_exec_latency.as_micros(),
                sched_to_exec_latency.as_nanos()
            ));
        }

        let exec_to_logger_latency = timing_info
            .exec_to_logger_queue_end
            .duration_since(timing_info.exec_to_logger_queue_start);
        if exec_to_logger_latency > Duration::default() {
            timing_stats_string.push_str(&format!(
                "\nExecutor<->logger queue latency: {}us ({}ns)",
                exec_to_logger_latency.as_micros(),
                exec_to_logger_latency.as_nanos()
            ));
        }

        let logger_to_sched_latency = timing_info
            .logger_to_sched_queue_end
            .duration_since(timing_info.logger_to_sched_queue_start);
        if logger_to_sched_latency > Duration::default() {
            timing_stats_string.push_str(&format!(
                "\nLogger<->Scheduler queue latency: {}us ({}ns)",
                logger_to_sched_latency.as_micros(),
                logger_to_sched_latency.as_nanos()
            ));
        }

        println!("====\n{}\n====", timing_stats_string);
    }
}

impl std::fmt::Debug for NandoActivation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "NandoActivation {{
            id: {}, executor: {}, args: {:#?}, status: {:?}, error: {:?}, intent: {:#?}
        }}",
            self.activation_id,
            self.executor,
            self.resolved_args,
            self.status,
            self.execution_error,
            self.activation_intent
        ))
    }
}