Files @ d06da4e9296c
Branch filter:

Location: CSY/reowolf/src/runtime2/component/component_pdl.rs

d06da4e9296c 29.6 KiB application/rls-services+xml Show Annotation Show as Raw Download as Raw
mh
WIP: Reimplementing messaging and consensus
  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
use crate::protocol::*;
use crate::protocol::eval::{
    PortId as EvalPortId, Prompt,
    ValueGroup, Value,
    EvalContinuation, EvalResult, EvalError
};

use crate::runtime2::runtime::*;
use crate::runtime2::scheduler::SchedulerCtx;
use crate::runtime2::communication::*;

use super::*;
use super::control_layer::*;
use super::consensus::Consensus;

pub enum CompScheduling {
    Immediate,
    Requeue,
    Sleep,
    Exit,
}

pub struct CompCtx {
    pub id: CompId,
    pub ports: Vec<Port>,
    pub peers: Vec<Peer>,
    pub messages: Vec<Option<DataMessage>>, // same size as "ports"
    pub port_id_counter: u32,
}

impl Default for CompCtx {
    fn default() -> Self {
        return Self{
            id: CompId(0),
            ports: Vec::new(),
            peers: Vec::new(),
            messages: Vec::new(),
            port_id_counter: 0,
        }
    }
}

struct MessageView<'a> {
    index: usize,
    pub message: &'a DataMessage,
}

impl CompCtx {
    fn create_channel(&mut self) -> Channel {
        let putter_id = PortId(self.take_port_id());
        let getter_id = PortId(self.take_port_id());
        self.ports.push(Port{
            self_id: putter_id,
            peer_id: getter_id,
            kind: PortKind::Putter,
            state: PortState::Open,
            peer_comp_id: self.id,
        });
        self.ports.push(Port{
            self_id: getter_id,
            peer_id: putter_id,
            kind: PortKind::Getter,
            state: PortState::Closed,
            peer_comp_id: self.id,
        });

        return Channel{ putter_id, getter_id };
    }

    pub(crate) fn get_port(&self, port_id: PortId) -> &Port {
        let index = self.get_port_index(port_id).unwrap();
        return &self.ports[index];
    }

    pub(crate) fn get_port_mut(&mut self, port_id: PortId) -> &mut Port {
        let index = self.get_port_index(port_id).unwrap();
        return &mut self.ports[index];
    }

    pub(crate) fn get_port_index(&self, port_id: PortId) -> Option<usize> {
        for (index, port) in self.ports.iter().enumerate() {
            if port.self_id == port_id {
                return Some(index);
            }
        }

        return None;
    }

    pub(crate) fn get_peer(&self, peer_id: CompId) -> &Peer {
        let index = self.get_peer_index(peer_id).unwrap();
        return &self.peers[index];
    }

    fn get_peer_mut(&mut self, peer_id: CompId) -> &mut Peer {
        let index = self.get_peer_index(peer_id).unwrap();
        return &mut self.peers[index];
    }

    pub(crate) fn get_peer_index(&self, peer_id: CompId) -> Option<usize> {
        for (index, peer) in self.peers.iter().enumerate() {
            if peer.id == peer_id {
                return Some(index);
            }
        }

        return None;
    }

    fn take_port_id(&mut self) -> u32 {
        let port_id = self.port_id_counter;
        self.port_id_counter = self.port_id_counter.wrapping_add(1);
        return port_id;
    }
}

pub enum ExecStmt {
    CreatedChannel((Value, Value)),
    PerformedPut,
    PerformedGet(ValueGroup),
    None,
}

impl ExecStmt {
    fn take(&mut self) -> ExecStmt {
        let mut value = ExecStmt::None;
        std::mem::swap(self, &mut value);
        return value;
    }

    fn is_none(&self) -> bool {
        match self {
            ExecStmt::None => return true,
            _ => return false,
        }
    }
}

pub struct ExecCtx {
    stmt: ExecStmt,
}

impl RunContext for ExecCtx {
    fn performed_put(&mut self, _port: EvalPortId) -> bool {
        match self.stmt.take() {
            ExecStmt::None => return false,
            ExecStmt::PerformedPut => return true,
            _ => unreachable!(),
        }
    }

    fn performed_get(&mut self, _port: EvalPortId) -> Option<ValueGroup> {
        match self.stmt.take() {
            ExecStmt::None => return None,
            ExecStmt::PerformedGet(value) => return Some(value),
            _ => unreachable!(),
        }
    }

    fn fires(&mut self, _port: EvalPortId) -> Option<Value> {
        todo!("remove fires")
    }

    fn performed_fork(&mut self) -> Option<bool> {
        todo!("remove fork")
    }

    fn created_channel(&mut self) -> Option<(Value, Value)> {
        match self.stmt.take() {
            ExecStmt::None => return None,
            ExecStmt::CreatedChannel(ports) => return Some(ports),
            _ => unreachable!(),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum Mode {
    NonSync, // not in sync mode
    Sync, // in sync mode, can interact with other components
    SyncFail, // something went wrong during sync mode (deadlocked, error, whatever)
    SyncEnd, // awaiting a solution, i.e. encountered the end of the sync block
    BlockedGet,
    BlockedPut,
}

impl Mode {
    fn can_run(&self) -> bool {
        match self {
            Mode::NonSync | Mode::Sync =>
                return true,
            Mode::SyncFail | Mode::SyncEnd | Mode::BlockedGet | Mode::BlockedPut =>
                return false,
        }
    }
}

pub(crate) struct CompPDL {
    pub mode: Mode,
    pub mode_port: PortId, // when blocked on a port
    pub mode_value: ValueGroup, // when blocked on a put
    pub prompt: Prompt,
    pub control: ControlLayer,
    pub consensus: Consensus,
    pub sync_counter: u32,
    pub exec_ctx: ExecCtx,
    // TODO: Temporary field, simulates future plans of having one storage place
    //  reserved per port.
    // Should be same length as the number of ports. Corresponding indices imply
    // message is intended for that port.
    pub inbox_main: Vec<Option<DataMessage>>,
    pub inbox_backup: Vec<DataMessage>,
}

impl CompPDL {
    pub(crate) fn new(initial_state: Prompt, num_ports: usize) -> Self {
        let mut inbox_main = Vec::new();
        inbox_main.reserve(num_ports);
        for _ in 0..num_ports {
            inbox_main.push(None);
        }

        return Self{
            mode: Mode::NonSync,
            mode_port: PortId::new_invalid(),
            mode_value: ValueGroup::default(),
            prompt: initial_state,
            control: ControlLayer::default(),
            consensus: Consensus::new(),
            sync_counter: 0,
            exec_ctx: ExecCtx{
                stmt: ExecStmt::None,
            },
            inbox_main,
            inbox_backup: Vec::new(),
        }
    }

    pub(crate) fn handle_message(&mut self, sched_ctx: &mut SchedulerCtx, comp_ctx: &mut CompCtx, message: Message) {
        sched_ctx.log(&format!("handling message: {:?}", message));
        if let Some(new_target) = self.control.should_reroute(&message) {
            let target = sched_ctx.runtime.get_component_public(new_target);
            target.inbox.push(message);

            return;
        }

        match message {
            Message::Data(message) => {
                self.handle_incoming_data_message(sched_ctx, comp_ctx, message);
            },
            Message::Control(message) => {
                self.handle_incoming_control_message(sched_ctx, comp_ctx, message);
            },
            Message::Sync(message) => {
                self.handle_incoming_sync_message(sched_ctx, comp_ctx, message);
            }
        }
    }

    pub(crate) fn run(&mut self, sched_ctx: &mut SchedulerCtx, comp_ctx: &mut CompCtx) -> Result<CompScheduling, EvalError> {
        use EvalContinuation as EC;

        let can_run = self.mode.can_run();
        sched_ctx.log(&format!("Running component (mode: {:?}, can run: {})", self.mode, can_run));
        if !can_run {
            return Ok(CompScheduling::Sleep);
        }

        let run_result = self.execute_prompt(&sched_ctx)?;

        match run_result {
            EC::Stepping => unreachable!(), // execute_prompt runs until this is no longer returned
            EC::BranchInconsistent | EC::NewFork | EC::BlockFires(_) => todo!("remove these"),
            // Results that can be returned in sync mode
            EC::SyncBlockEnd => {
                debug_assert_eq!(self.mode, Mode::Sync);
                self.handle_sync_end(sched_ctx, comp_ctx);
                return Ok(CompScheduling::Immediate);
            },
            EC::BlockGet(port_id) => {
                debug_assert_eq!(self.mode, Mode::Sync);
                debug_assert!(self.exec_ctx.stmt.is_none());

                let port_id = port_id_from_eval(port_id);
                let port_index = comp_ctx.get_port_index(port_id).unwrap();
                if let Some(message) = &self.inbox_main[port_index] {
                    // Check if we can actually receive the message
                    if self.consensus.try_receive_data_message(message) {
                        // Message was received. Make sure any blocked peers and
                        // pending messages are handled.
                        let message = self.inbox_main[port_index].take().unwrap();

                        self.exec_ctx.stmt = ExecStmt::PerformedGet(message.content);
                        return Ok(CompScheduling::Immediate);
                    } else {
                        self.mode = Mode::SyncFail;
                        return Ok(CompScheduling::Sleep);
                    }
                } else {
                    // We need to wait
                    self.mode = Mode::BlockedGet;
                    self.mode_port = port_id;
                    return Ok(CompScheduling::Sleep);
                }
            },
            EC::Put(port_id, value) => {
                debug_assert_eq!(self.mode, Mode::Sync);
                let port_id = port_id_from_eval(port_id);
                let port_info = comp_ctx.get_port(port_id);
                if port_info.state == PortState::Blocked {
                    todo!("handle blocked port");
                }
                self.send_data_message_and_wake_up(sched_ctx, comp_ctx, port_id, value);
                self.exec_ctx.stmt = ExecStmt::PerformedPut;
                return Ok(CompScheduling::Immediate);
            },
            // Results that can be returned outside of sync mode
            EC::ComponentTerminated => {
                debug_assert_eq!(self.mode, Mode::NonSync);
                return Ok(CompScheduling::Exit);
            },
            EC::SyncBlockStart => {
                debug_assert_eq!(self.mode, Mode::NonSync);
                self.handle_sync_start(sched_ctx, comp_ctx);
                return Ok(CompScheduling::Immediate);
            },
            EC::NewComponent(definition_id, monomorph_idx, arguments) => {
                debug_assert_eq!(self.mode, Mode::NonSync);

                let mut ports = Vec::new(); // TODO: Optimize
                let protocol = &sched_ctx.runtime.protocol;
                find_ports_in_value_group(&arguments, &mut ports);
                let prompt = Prompt::new(
                    &protocol.types, &protocol.heap,
                    definition_id, monomorph_idx, arguments
                );
                self.create_component_and_transfer_ports(sched_ctx, comp_ctx, prompt, &ports);
                return Ok(CompScheduling::Requeue);
            },
            EC::NewChannel => {
                debug_assert_eq!(self.mode, Mode::NonSync);
                debug_assert!(self.exec_ctx.stmt.is_none());
                let channel = comp_ctx.create_channel();
                self.exec_ctx.stmt = ExecStmt::CreatedChannel((
                    Value::Output(port_id_to_eval(channel.putter_id)),
                    Value::Input(port_id_to_eval(channel.getter_id))
                ));
                return Ok(CompScheduling::Immediate);
            }
        }
    }

    fn execute_prompt(&mut self, sched_ctx: &SchedulerCtx) -> EvalResult {
        let mut step_result = EvalContinuation::Stepping;
        while let EvalContinuation::Stepping = step_result {
            step_result = self.prompt.step(
                &sched_ctx.runtime.protocol.types, &sched_ctx.runtime.protocol.heap,
                &sched_ctx.runtime.protocol.modules, &mut self.exec_ctx,
            )?;
        }

        return Ok(step_result)
    }

    fn handle_sync_start(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx) {
        self.consensus.notify_sync_start(comp_ctx);
        debug_assert_eq!(self.mode, Mode::NonSync);
        self.mode = Mode::Sync;
    }

    fn handle_sync_end(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx) {
        self.consensus.notify_sync_end();
        debug_assert_eq!(self.mode, Mode::Sync);
        self.mode = Mode::SyncEnd;
    }

    fn send_data_message_and_wake_up(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &CompCtx, source_port_id: PortId, value: ValueGroup) {
        use std::sync::atomic::Ordering;

        let port_info = comp_ctx.get_port(source_port_id);
        let peer_info = comp_ctx.get_peer(port_info.peer_comp_id);
        let annotated_message = self.consensus.annotate_data_message(comp_ctx, port_info, value);
        peer_info.handle.inbox.push(Message::Data(annotated_message));

        wake_up_if_sleeping(sched_ctx, peer_info.id, &peer_info.handle);
    }

    /// Handles a message that came in through the public inbox. This function
    /// will handle putting it in the correct place, and potentially blocking
    /// the port in case too many messages are being received.
    fn handle_incoming_data_message(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx, message: DataMessage) {
        // Check if we can insert it directly into the storage associated with
        // the port
        let target_port_id = message.data_header.target_port;
        let port_index = comp_ctx.get_port_index(target_port_id).unwrap();
        if self.inbox_main[port_index].is_none() {
            self.inbox_main[port_index] = Some(message);

            // After direct insertion, check if this component's execution is 
            // blocked on receiving a message on that port
            debug_assert_ne!(comp_ctx.ports[port_index].state, PortState::Blocked); // because we could insert directly
            if self.mode == Mode::BlockedGet && self.mode_port == target_port_id {
                // We were indeed blocked
                self.mode = Mode::Sync;
                self.mode_port = PortId::new_invalid();
            }
            
            return;
        }

        // The direct inbox is full, so the port will become (or was already) blocked
        let port_info = &mut comp_ctx.ports[port_index];
        debug_assert!(port_info.state == PortState::Open || port_info.state == PortState::Blocked);
        let _peer_comp_id = port_info.peer_comp_id;

        if port_info.state == PortState::Open {
            let (target_comp_id, block_message) =
                self.control.set_port_and_peer_blocked(target_port_id, comp_ctx);
            debug_assert_eq!(_peer_comp_id, target_comp_id);

            let peer = comp_ctx.get_peer(target_comp_id);
            peer.handle.inbox.push(Message::Control(block_message));
            wake_up_if_sleeping(sched_ctx, target_comp_id, &peer.handle);
        }

        // But we still need to remember the message, so:
        self.inbox_backup.push(message);
    }

    /// Handles when a message has been handed off from the inbox to the PDL
    /// code. We check to see if there are more messages waiting and, if not,
    /// then we handle the case where the port might have been blocked
    /// previously.
    fn handle_received_data_message(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx, port_id: PortId) {
        let port_index = comp_ctx.get_port_index(port_id).unwrap();
        debug_assert!(self.inbox_main[port_index].is_none()); // because we just received it

        // Check for any more messages
        for message_index in 0..self.inbox_backup.len() {
            let message = &self.inbox_backup[message_index];
            if message.data_header.target_port == port_id {
                // One more message for this port
                let message = self.inbox_backup.remove(message_index);
                debug_assert_eq!(comp_ctx.get_port(port_id).state, PortState::Blocked); // since we had >1 message on the port
                self.inbox_main[port_index] = Some(message);
                return;
            }
        }

        // Did not have any more messages. So if we were blocked, then we need
        // to send the "unblock" message.
        let port_info = &comp_ctx.ports[port_index];
        if port_info.state == PortState::Blocked {
            let (peer_comp_id, message) = self.control.set_port_and_peer_unblocked(port_id, comp_ctx);
            let peer_info = comp_ctx.get_peer(peer_comp_id);
            peer_info.handle.inbox.push(Message::Control(message));
            wake_up_if_sleeping(sched_ctx, peer_comp_id, &peer_info.handle);
        }
    }

    fn handle_incoming_control_message(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx, message: ControlMessage) {
        match message.content {
            ControlMessageContent::Ack => {
                let mut to_ack = message.id;
                loop {
                    let action = self.control.handle_ack(to_ack, sched_ctx, comp_ctx);
                    match action {
                        AckAction::SendMessageAndAck(target_comp, message, new_to_ack) => {
                            // FIX @NoDirectHandle
                            let handle = sched_ctx.runtime.get_component_public(target_comp);
                            handle.inbox.push(Message::Control(message));
                            wake_up_if_sleeping(sched_ctx, target_comp, &handle);
                            to_ack = new_to_ack;
                        },
                        AckAction::ScheduleComponent(to_schedule) => {
                            // FIX @NoDirectHandle
                            let handle = sched_ctx.runtime.get_component_public(to_schedule);
                            wake_up_if_sleeping(sched_ctx, to_schedule, &handle);
                            break;
                        },
                        AckAction::None => {
                            break;
                        }
                    }
                }
            },
            ControlMessageContent::BlockPort(port_id) => {
                // On of our messages was accepted, but the port should be
                // blocked.
                let port_info = comp_ctx.get_port_mut(port_id);
                debug_assert_eq!(port_info.kind, PortKind::Putter);
                if port_info.state != PortState::Closed {
                    debug_assert_ne!(port_info.state, PortState::Blocked); // implies unnecessary messages
                    port_info.state = PortState::Blocked;
                }
            },
            ControlMessageContent::ClosePort(port_id) => {
                // Request to close the port. We immediately comply and remove
                // the component handle as well
                let port_index = comp_ctx.get_port_index(port_id).unwrap();
                let port_info = &mut comp_ctx.ports[port_index];
                let peer_comp_id = port_info.peer_comp_id;
                port_info.state = PortState::Closed;

                let peer_index = comp_ctx.get_peer_index(peer_comp_id).unwrap();
                let peer_info = &mut comp_ctx.peers[peer_index];
                peer_info.num_associated_ports -= 1;
                if peer_info.num_associated_ports == 0 {
                    // TODO: @Refactor clean up all these uses of "num_associated_ports"
                    let should_remove = peer_info.handle.decrement_users();
                    if should_remove {
                        let comp_key = unsafe{ peer_info.id.upgrade() };
                        sched_ctx.runtime.destroy_component(comp_key);
                    }

                    comp_ctx.peers.remove(peer_index);
                }
            }
            ControlMessageContent::UnblockPort(port_id) => {
                // We were previously blocked (or already closed)
                let port_info = comp_ctx.get_port(port_id);
                debug_assert_eq!(port_info.kind, PortKind::Putter);
                debug_assert!(port_info.state == PortState::Blocked || port_info.state == PortState::Closed);
                if port_info.state == PortState::Blocked {
                    self.unblock_local_port(sched_ctx, comp_ctx, port_id);
                }
            },
            ControlMessageContent::PortPeerChangedBlock(port_id) => {
                // The peer of our port has just changed. So we are asked to
                // temporarily block the port (while our original recipient is
                // potentially rerouting some of the in-flight messages) and
                // Ack. Then we wait for the `unblock` call.
                debug_assert_eq!(message.target_port_id, Some(port_id));
                let port_info = comp_ctx.get_port_mut(port_id);
                debug_assert!(port_info.state == PortState::Open || port_info.state == PortState::Blocked);
                if port_info.state == PortState::Open {
                    port_info.state = PortState::Blocked;
                }
            },
            ControlMessageContent::PortPeerChangedUnblock(port_id, new_comp_id) => {
                debug_assert_eq!(message.target_port_id, Some(port_id));
                let port_info = comp_ctx.get_port_mut(port_id);
                debug_assert!(port_info.state == PortState::Blocked);
                port_info.peer_comp_id = new_comp_id;
                self.unblock_local_port(sched_ctx, comp_ctx, port_id);
            }
        }
    }

    fn handle_incoming_sync_message(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx, message: SyncMessage) {

    }

    /// Marks the local port as being unblocked. If the execution was blocked on
    /// sending a message over this port, then execution will continue and the
    /// message will be sent.
    fn unblock_local_port(&mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx, port_id: PortId) {
        let port_info = comp_ctx.get_port_mut(port_id);
        debug_assert_eq!(port_info.state, PortState::Blocked);
        port_info.state = PortState::Open;

        if self.mode == Mode::BlockedPut && port_id == self.mode_port {
            // We were blocked on the port that just became unblocked, so
            // send the message.
            debug_assert_eq!(port_info.kind, PortKind::Putter);
            let mut replacement = ValueGroup::default();
            std::mem::swap(&mut replacement, &mut self.mode_value);
            self.send_data_message_and_wake_up(sched_ctx, comp_ctx, port_id, replacement);

            self.mode = Mode::Sync;
            self.mode_port = PortId::new_invalid();
        }
    }

    fn create_component_and_transfer_ports(&mut self, sched_ctx: &SchedulerCtx, creator_ctx: &mut CompCtx, prompt: Prompt, ports: &[PortId]) {
        let component = CompPDL::new(prompt, ports.len());
        let (comp_key, component) = sched_ctx.runtime.create_pdl_component(component, true);
        let created_ctx = &mut component.ctx;

        let mut has_reroute_entry = false;
        let schedule_entry_id = self.control.add_schedule_entry(created_ctx.id);

        for port_id in ports.iter().copied() {
            // Create temporary reroute entry if the peer is another component
            let port_info = creator_ctx.get_port(port_id);
            debug_assert_ne!(port_info.state, PortState::Blocked);
            if port_info.peer_comp_id == creator_ctx.id {
                // We own the peer port. So retrieve it and modify the peer directly
                let peer_port_id = port_info.peer_id;
                let port_info = creator_ctx.get_port_mut(peer_port_id);
                port_info.peer_comp_id = created_ctx.id;
            } else {
                // We don't own the port, so send the appropriate messages and
                // notify the control layer
                has_reroute_entry = true;
                let message = self.control.add_reroute_entry(
                    creator_ctx.id, port_info.peer_id, port_info.peer_comp_id,
                    port_info.self_id, created_ctx.id, schedule_entry_id
                );
                let peer_info = creator_ctx.get_peer(port_info.peer_comp_id);
                peer_info.handle.inbox.push(message);
            }

            // Transfer port and create temporary reroute entry
            let (port_info, peer_info) = Self::remove_port_from_component(creator_ctx, port_id);
            if port_info.state == PortState::Blocked {
                todo!("Think about this when you're not tired!");
            }
            Self::add_port_to_component(sched_ctx, created_ctx, port_info);

            // Maybe remove peer from the creator
            if let Some(mut peer_info) = peer_info {
                let remove_from_runtime = peer_info.handle.decrement_users();
                if remove_from_runtime {
                    let removed_comp_key = unsafe{ peer_info.id.upgrade() };
                    sched_ctx.runtime.destroy_component(removed_comp_key);
                }
            }
        }

        if !has_reroute_entry {
            // We can schedule the component immediately
            self.control.remove_schedule_entry(schedule_entry_id);
            sched_ctx.runtime.enqueue_work(comp_key);
        } // else: wait for the `Ack`s, they will trigger the scheduling of the component
    }

    /// Removes a port from a component. Also decrements the port counter in
    /// the peer component's entry. If that hits 0 then it will be removed and
    /// returned. If returned then the caller is responsible for decrementing
    /// the atomic counters of the peer component's handle.
    fn remove_port_from_component(comp_ctx: &mut CompCtx, port_id: PortId) -> (Port, Option<Peer>) {
        let port_index = comp_ctx.get_port_index(port_id).unwrap();
        let port_info = comp_ctx.ports.remove(port_index);

        // If the component owns the peer, then we don't have to decrement the
        // number of peers (because we don't have an entry for ourselves)
        if port_info.peer_comp_id == comp_ctx.id {
            return (port_info, None);
        }

        let peer_index = comp_ctx.get_peer_index(port_info.peer_comp_id).unwrap();
        let peer_info = &mut comp_ctx.peers[peer_index];
        peer_info.num_associated_ports -= 1;

        // Check if we still have other ports referencing this peer
        if peer_info.num_associated_ports != 0 {
            return (port_info, None);
        }

        let peer_info = comp_ctx.peers.remove(peer_index);
        return (port_info, Some(peer_info));
    }

    fn add_port_to_component(sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx, port_info: Port) {
        // Add the port info
        let peer_comp_id = port_info.peer_comp_id;
        debug_assert!(!comp_ctx.ports.iter().any(|v| v.self_id == port_info.self_id));
        comp_ctx.ports.push(port_info);

        // Increment counters on peer, or create entry for peer if it doesn't
        // exist yet.
        match comp_ctx.peers.iter().position(|v| v.id == peer_comp_id) {
            Some(peer_index) => {
                let peer_info = &mut comp_ctx.peers[peer_index];
                peer_info.num_associated_ports += 1;
            },
            None => {
                let handle = sched_ctx.runtime.get_component_public(peer_comp_id);
                comp_ctx.peers.push(Peer{
                    id: peer_comp_id,
                    num_associated_ports: 1,
                    handle,
                });
            }
        }
    }

    fn change_port_peer_component(
        &mut self, sched_ctx: &SchedulerCtx, comp_ctx: &mut CompCtx,
        port_id: PortId, new_peer_comp_id: CompId
    ) {
        let port_info = comp_ctx.get_port_mut(port_id);
        let cur_peer_comp_id = port_info.peer_comp_id;
        let cur_peer_info = comp_ctx.get_peer_mut(cur_peer_comp_id);
        cur_peer_info.num_associated_ports -= 1;

        if cur_peer_info.num_associated_ports == 0 {
            let should_remove = cur_peer_info.handle.decrement_users();
            if should_remove {
                let cur_peer_comp_key = unsafe{ cur_peer_comp_id.upgrade() };
                sched_ctx.runtime.destroy_component(cur_peer_comp_key);

            }
        }
    }
}

#[inline]
fn port_id_from_eval(port_id: EvalPortId) -> PortId {
    return PortId(port_id.id);
}

#[inline]
fn port_id_to_eval(port_id: PortId) -> EvalPortId {
    return EvalPortId{ id: port_id.0 };
}

/// Recursively goes through the value group, attempting to find ports.
/// Duplicates will only be added once.
pub(crate) fn find_ports_in_value_group(value_group: &ValueGroup, ports: &mut Vec<PortId>) {
    // Helper to check a value for a port and recurse if needed.
    fn find_port_in_value(group: &ValueGroup, value: &Value, ports: &mut Vec<PortId>) {
        match value {
            Value::Input(port_id) | Value::Output(port_id) => {
                // This is an actual port
                let cur_port = PortId(port_id.id);
                for prev_port in ports.iter() {
                    if *prev_port == cur_port {
                        // Already added
                        return;
                    }
                }

                ports.push(cur_port);
            },
            Value::Array(heap_pos) |
            Value::Message(heap_pos) |
            Value::String(heap_pos) |
            Value::Struct(heap_pos) |
            Value::Union(_, heap_pos) => {
                // Reference to some dynamic thing which might contain ports,
                // so recurse
                let heap_region = &group.regions[*heap_pos as usize];
                for embedded_value in heap_region {
                    find_port_in_value(group, embedded_value, ports);
                }
            },
            _ => {}, // values we don't care about
        }
    }

    // Clear the ports, then scan all the available values
    ports.clear();
    for value in &value_group.values {
        find_port_in_value(value_group, value, ports);
    }
}