diff --git a/src/runtime2/branch.rs b/src/runtime2/branch.rs index 1b296960bcfabfc69b0176b84cd9b13b012e6bd3..511dfc1597390034c4913bd4a68a0b566fd6df2e 100644 --- a/src/runtime2/branch.rs +++ b/src/runtime2/branch.rs @@ -6,6 +6,13 @@ use crate::protocol::eval::{Value, ValueGroup}; use super::port::PortIdLocal; +// To share some logic between the FakeTree and ExecTree implementation +trait BranchListItem { + fn get_id(&self) -> BranchId; + fn set_next_id(&mut self, id: BranchId); + fn get_next_id(&self) -> BranchId; +} + /// Generic branch ID. A component will always have one branch: the /// non-speculative branch. This branch has ID 0. Hence in a speculative context /// we use this fact to let branch ID 0 denote the ID being invalid. @@ -45,6 +52,35 @@ pub(crate) enum SpeculativeState { Inconsistent, // branch can never represent a local solution, so halted } +#[derive(Debug)] +pub(crate) enum PreparedStatement { + CreatedChannel((Value, Value)), + ForkedExecution(bool), + PerformedPut, + PerformedGet(ValueGroup), + None, +} + +impl PreparedStatement { + pub(crate) fn is_none(&self) -> bool { + if let PreparedStatement::None = self { + return true; + } else { + return false; + } + } + + pub(crate) fn take(&mut self) -> PreparedStatement { + if let PreparedStatement::None = self { + return PreparedStatement::None; + } else { + let mut replacement = PreparedStatement::None; + std::mem::swap(self, &mut replacement); + return replacement; + } + } +} + /// The execution state of a branch. This envelops the PDL code and the /// execution state. And derived from that: if we're ready to keep running the /// code, or if we're halted for some reason (e.g. waiting for a message). @@ -56,8 +92,13 @@ pub(crate) struct Branch { pub sync_state: SpeculativeState, pub awaiting_port: PortIdLocal, // only valid if in "awaiting message" queue. TODO: Maybe put in enum pub next_in_queue: BranchId, // used by `ExecTree`/`BranchQueue` - pub inbox: HashMap, // TODO: Remove, currently only valid in single-get/put mode - pub prepared_channel: Option<(Value, Value)>, // TODO: Maybe remove? + pub prepared: PreparedStatement, +} + +impl BranchListItem for Branch { + #[inline] fn get_id(&self) -> BranchId { return self.id; } + #[inline] fn set_next_id(&mut self, id: BranchId) { self.next_in_queue = id; } + #[inline] fn get_next_id(&self) -> BranchId { return self.next_in_queue; } } impl Branch { @@ -70,19 +111,18 @@ impl Branch { sync_state: SpeculativeState::RunningNonSync, awaiting_port: PortIdLocal::new_invalid(), next_in_queue: BranchId::new_invalid(), - inbox: HashMap::new(), - prepared_channel: None, + prepared: PreparedStatement::None, } } /// Constructs a sync branch. The provided branch is assumed to be the /// parent of the new branch within the execution tree. fn new_sync(new_index: u32, parent_branch: &Branch) -> Self { - debug_assert!( - (parent_branch.sync_state == SpeculativeState::RunningNonSync && !parent_branch.parent_id.is_valid()) || - (parent_branch.sync_state == SpeculativeState::HaltedAtBranchPoint) - ); // forking from non-sync, or forking from a branching point - debug_assert!(parent_branch.prepared_channel.is_none()); + // debug_assert!( + // (parent_branch.sync_state == SpeculativeState::RunningNonSync && !parent_branch.parent_id.is_valid()) || + // (parent_branch.sync_state == SpeculativeState::HaltedAtBranchPoint) + // ); // forking from non-sync, or forking from a branching point + debug_assert!(parent_branch.prepared.is_none()); Branch { id: BranchId::new(new_index), @@ -91,19 +131,9 @@ impl Branch { sync_state: SpeculativeState::RunningInSync, awaiting_port: parent_branch.awaiting_port, next_in_queue: BranchId::new_invalid(), - inbox: parent_branch.inbox.clone(), - prepared_channel: None, + prepared: PreparedStatement::None, } } - - /// Inserts a message into the branch for retrieval by a corresponding - /// `get(port)` call. - pub(crate) fn insert_message(&mut self, target_port: PortIdLocal, contents: ValueGroup) { - debug_assert!(target_port.is_valid()); - debug_assert!(self.awaiting_port == target_port); - self.awaiting_port = PortIdLocal::new_invalid(); - self.inbox.insert(target_port, contents); - } } /// Queue of branches. Just a little helper. @@ -131,7 +161,7 @@ impl BranchQueue { const NUM_QUEUES: usize = 3; -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] pub(crate) enum QueueKind { Runnable, AwaitingMessage, @@ -148,6 +178,10 @@ impl QueueKind { } } +// ----------------------------------------------------------------------------- +// ExecTree +// ----------------------------------------------------------------------------- + /// Execution tree of branches. Tries to keep the extra information stored /// herein to a minimum. So the execution tree is aware of the branches, their /// execution state and the way they're dependent on each other, but the @@ -188,32 +222,12 @@ impl ExecTree { /// Pops a branch (ID) from a queue. pub fn pop_from_queue(&mut self, kind: QueueKind) -> Option { debug_assert_ne!(kind, QueueKind::FinishedSync); // for purposes of logic we expect the queue to grow during a sync round - let queue = &mut self.queues[kind.as_index()]; - if queue.is_empty() { - return None; - } else { - let first_branch = &mut self.branches[queue.first.index as usize]; - queue.first = first_branch.next_in_queue; - first_branch.next_in_queue = BranchId::new_invalid(); - if !queue.first.is_valid() { - queue.last = BranchId::new_invalid(); - } - - return Some(first_branch.id); - } + return pop_from_queue(&mut self.queues[kind.as_index()], &mut self.branches); } /// Pushes a branch (ID) into a queue. pub fn push_into_queue(&mut self, kind: QueueKind, id: BranchId) { - let queue = &mut self.queues[kind.as_index()]; - if queue.is_empty() { - queue.first = id; - queue.last = id; - } else { - let last_branch = &mut self.branches[queue.last.index as usize]; - last_branch.next_in_queue = id; - queue.last = id; - } + push_into_queue(&mut self.queues[kind.as_index()], &mut self.branches, id); } /// Returns the non-sync branch (TODO: better name?) @@ -222,27 +236,24 @@ impl ExecTree { return &mut self.branches[0]; } - /// Returns an iterator over all the elements in the queue of the given - /// kind. One can start the iteration at the branch *after* the provided - /// branch. Just make sure it actually is in the provided queue. - pub fn iter_queue(&self, kind: QueueKind, start_at: Option) -> BranchQueueIter { + /// Returns the branch ID of the first branch in a particular queue. + pub fn get_queue_first(&self, kind: QueueKind) -> Option { let queue = &self.queues[kind.as_index()]; + if queue.first.is_valid() { + return Some(queue.first); + } else { + return None; + } + } - let index = match start_at { - Some(branch_id) => { - debug_assert!(self.iter_queue(kind, None).any(|v| v.id == branch_id)); - let branch = &self.branches[branch_id.index as usize]; - - branch.next_in_queue.index as usize - }, - None => { - queue.first.index as usize - } - }; - - return BranchQueueIter { - branches: self.branches.as_slice(), - index, + /// Returns the next branch ID of a branch (assumed to be in a particular + /// queue. + pub fn get_queue_next(&self, branch_id: BranchId) -> Option { + let branch = &self.branches[branch_id.index as usize]; + if branch.next_in_queue.is_valid() { + return Some(branch.next_in_queue); + } else { + return None; } } @@ -285,7 +296,6 @@ impl ExecTree { /// using the provided branch as the final sync result. pub fn end_sync(&mut self, branch_id: BranchId) { debug_assert!(self.is_in_sync()); - debug_assert!(self.iter_queue(QueueKind::FinishedSync, None).any(|v| v.id == branch_id)); // Swap indicated branch into the first position self.branches.swap(0, branch_id.index as usize); @@ -298,8 +308,7 @@ impl ExecTree { branch.sync_state = SpeculativeState::RunningNonSync; debug_assert!(!branch.awaiting_port.is_valid()); branch.next_in_queue = BranchId::new_invalid(); - branch.inbox.clear(); - debug_assert!(branch.prepared_channel.is_none()); + debug_assert!(branch.prepared.is_none()); // Clear out all the queues for queue_idx in 0..NUM_QUEUES { @@ -324,41 +333,224 @@ impl IndexMut for ExecTree { } } -pub(crate) struct BranchQueueIter<'a> { +/// Iterator over the parents of an `ExecTree` branch. +pub(crate) struct BranchParentIter<'a> { branches: &'a [Branch], index: usize, } -impl<'a> Iterator for BranchQueueIter<'a> { +impl<'a> Iterator for BranchParentIter<'a> { type Item = &'a Branch; fn next(&mut self) -> Option { if self.index == 0 { - // i.e. the invalid branch index return None; } let branch = &self.branches[self.index]; - self.index = branch.next_in_queue.index as usize; + self.index = branch.parent_id.index as usize; return Some(branch); } } -pub(crate) struct BranchParentIter<'a> { - branches: &'a [Branch], - index: usize, +// ----------------------------------------------------------------------------- +// FakeTree +// ----------------------------------------------------------------------------- + +/// Generic fake branch. This is supposed to be used in conjunction with the +/// fake tree. The purpose is to have a branching-like tree to use in +/// combination with a consensus algorithm in places where we don't have PDL +/// code. +pub(crate) struct FakeBranch { + pub id: BranchId, + pub parent_id: BranchId, + pub sync_state: SpeculativeState, + pub awaiting_port: PortIdLocal, + pub next_in_queue: BranchId, + pub inbox: HashMap, } -impl<'a> Iterator for BranchParentIter<'a> { - type Item = &'a Branch; +impl BranchListItem for FakeBranch { + #[inline] fn get_id(&self) -> BranchId { return self.id; } + #[inline] fn set_next_id(&mut self, id: BranchId) { self.next_in_queue = id; } + #[inline] fn get_next_id(&self) -> BranchId { return self.next_in_queue; } +} - fn next(&mut self) -> Option { - if self.index == 0 { +impl FakeBranch { + fn new_root(_index: u32) -> FakeBranch { + debug_assert!(_index == 1); + return FakeBranch{ + id: BranchId::new(1), + parent_id: BranchId::new_invalid(), + sync_state: SpeculativeState::RunningInSync, + awaiting_port: PortIdLocal::new_invalid(), + next_in_queue: BranchId::new_invalid(), + inbox: HashMap::new(), + } + } + + fn new_branching(index: u32, parent_branch: &FakeBranch) -> FakeBranch { + return FakeBranch { + id: BranchId::new(index), + parent_id: parent_branch.id, + sync_state: SpeculativeState::RunningInSync, + awaiting_port: parent_branch.awaiting_port, + next_in_queue: BranchId::new_invalid(), + inbox: parent_branch.inbox.clone(), + } + } + + pub fn insert_message(&mut self, target_port: PortIdLocal, contents: ValueGroup) { + debug_assert!(target_port.is_valid()); + debug_assert!(self.awaiting_port == target_port); + self.awaiting_port = PortIdLocal::new_invalid(); + self.inbox.insert(target_port, contents); + } +} + +/// A little helper for native components that don't have a set of branches that +/// are actually executing code, but just have to manage the idea of branches +/// due to them performing the equivalent of a branching `get` call. +pub(crate) struct FakeTree { + pub branches: Vec, + queues: [BranchQueue; NUM_QUEUES], +} + +impl FakeTree { + pub fn new() -> Self { + // TODO: Don't like this? Cause is that now we don't have a non-sync + // branch. But we assumed BranchId=0 means the branch is invalid. We + // can do the rusty Option stuff. But we still need a token + // value within the protocol to signify no-branch-id. Maybe the high + // bit? Branches are crazy expensive, no-one is going to have 2^32 + // branches anyway. 2^31 isn't too bad. + return Self { + branches: vec![FakeBranch{ + id: BranchId::new_invalid(), + parent_id: BranchId::new_invalid(), + sync_state: SpeculativeState::RunningNonSync, + awaiting_port: PortIdLocal::new_invalid(), + next_in_queue: BranchId::new_invalid(), + inbox: HashMap::new(), + }], + queues: [BranchQueue::new(); 3] + } + } + + fn is_in_sync(&self) -> bool { + return self.branches.len() > 1; + } + + pub fn queue_is_empty(&self, kind: QueueKind) -> bool { + return self.queues[kind.as_index()].is_empty(); + } + + pub fn pop_from_queue(&mut self, kind: QueueKind) -> Option { + debug_assert_ne!(kind, QueueKind::FinishedSync); + return pop_from_queue(&mut self.queues[kind.as_index()], &mut self.branches); + } + + pub fn push_into_queue(&mut self, kind: QueueKind, id: BranchId) { + push_into_queue(&mut self.queues[kind.as_index()], &mut self.branches, id); + } + + pub fn get_queue_first(&self, kind: QueueKind) -> Option { + let queue = &self.queues[kind.as_index()]; + if queue.first.is_valid() { + return Some(queue.first) + } else { return None; } + } - let branch = &self.branches[self.index]; - self.index = branch.parent_id.index as usize; - return Some(branch); + pub fn get_queue_next(&self, branch_id: BranchId) -> Option { + let branch = &self.branches[branch_id.index as usize]; + if branch.next_in_queue.is_valid() { + return Some(branch.next_in_queue); + } else { + return None; + } + } + + pub fn start_sync(&mut self) -> BranchId { + debug_assert!(!self.is_in_sync()); + + // Create the first branch + let sync_branch = FakeBranch::new_root(1); + let sync_branch_id = sync_branch.id; + self.branches.push(sync_branch); + + return sync_branch_id; + } + + pub fn fork_branch(&mut self, parent_branch_id: BranchId) -> BranchId { + debug_assert!(self.is_in_sync()); + let parent_branch = &self[parent_branch_id]; + let new_branch = FakeBranch::new_branching(self.branches.len() as u32, parent_branch); + let new_branch_id = new_branch.id; + self.branches.push(new_branch); + + return new_branch_id; + } + + pub fn end_sync(&mut self, branch_id: BranchId) -> FakeBranch { + debug_assert!(branch_id.is_valid()); + debug_assert!(self.is_in_sync()); + + // Take out the succeeding branch, then just clear all fake branches. + self.branches.swap(1, branch_id.index as usize); + self.branches.truncate(2); + let result = self.branches.pop().unwrap(); + + for queue_index in 0..NUM_QUEUES { + self.queues[queue_index] = BranchQueue::new(); + } + + return result; + } +} + +impl Index for FakeTree { + type Output = FakeBranch; + + fn index(&self, index: BranchId) -> &Self::Output { + return &self.branches[index.index as usize]; + } +} + +impl IndexMut for FakeTree { + fn index_mut(&mut self, index: BranchId) -> &mut Self::Output { + return &mut self.branches[index.index as usize]; + } +} + +// ----------------------------------------------------------------------------- +// Shared logic +// ----------------------------------------------------------------------------- + +fn pop_from_queue(queue: &mut BranchQueue, branches: &mut [B]) -> Option { + if queue.is_empty() { + return None; + } else { + let first_branch = &mut branches[queue.first.index as usize]; + queue.first = first_branch.get_next_id(); + first_branch.set_next_id(BranchId::new_invalid()); + if !queue.first.is_valid() { + queue.last = BranchId::new_invalid(); + } + + return Some(first_branch.get_id()); + } +} + +fn push_into_queue(queue: &mut BranchQueue, branches: &mut [B], branch_id: BranchId) { + debug_assert!(!branches[branch_id.index as usize].get_next_id().is_valid()); + if queue.is_empty() { + queue.first = branch_id; + queue.last = branch_id; + } else { + let last_branch = &mut branches[queue.last.index as usize]; + last_branch.set_next_id(branch_id); + queue.last = branch_id; } } \ No newline at end of file