diff --git a/src/runtime2/native.rs b/src/runtime2/native.rs index 73ac568570c9bbfd328c4b774335232f1de83c09..10a1ec47a20a917d4a33df1692de024d68190edc 100644 --- a/src/runtime2/native.rs +++ b/src/runtime2/native.rs @@ -4,6 +4,9 @@ use std::sync::atomic::Ordering; use crate::protocol::ComponentCreationError; use crate::protocol::eval::ValueGroup; +use crate::runtime2::branch::{FakeTree, QueueKind, SpeculativeState}; +use crate::runtime2::consensus::{Consensus, Consistency}; +use crate::runtime2::inbox::{DataContent, DataMessage, SyncMessage}; use super::{ConnectorKey, ConnectorId, RuntimeInner}; use super::scheduler::{SchedulerCtx, ComponentCtx}; @@ -27,14 +30,38 @@ type JobQueue = Arc>>; enum ApplicationJob { NewChannel((Port, Port)), NewConnector(ConnectorPDL, Vec), + SyncRound(Vec), Shutdown, } +// ----------------------------------------------------------------------------- +// ConnectorApplication +// ----------------------------------------------------------------------------- + /// The connector which an application can directly interface with. Once may set /// up the next synchronous round, and retrieve the data afterwards. +// TODO: Strong candidate for logic reduction in handling put/get. A lot of code +// is an approximate copy-pasta from the regular component logic. pub struct ConnectorApplication { + // Communicating about new jobs and setting up sync rounds sync_done: SyncDone, job_queue: JobQueue, + is_in_sync: bool, + // Handling current sync round + sync_desc: Vec, + exec_tree: FakeTree, + consensus: Consensus, + branch_extra: Vec, // instruction counter per branch +} + +impl Connector for ConnectorApplication { + fn run(&mut self, sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling { + if self.is_in_sync { + return self.run_in_sync_mode(sched_ctx, comp_ctx); + } else { + return self.run_in_deterministic_mode(sched_ctx, comp_ctx); + } + } } impl ConnectorApplication { @@ -44,17 +71,16 @@ impl ConnectorApplication { let connector = ConnectorApplication { sync_done: sync_done.clone(), - job_queue: job_queue.clone() + job_queue: job_queue.clone(), + is_in_sync: false, + sync_desc: Vec::new(), }; let interface = ApplicationInterface::new(sync_done, job_queue, runtime); return (connector, interface); } -} -impl Connector for ConnectorApplication { - fn run(&mut self, _sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling { - // Handle any incoming messages if we're participating in a round + fn handle_new_messages(&mut self, comp_ctx: &mut ComponentCtx) { while let Some(message) = comp_ctx.read_next_message() { match message { Message::Data(_) => todo!("data message in API connector"), @@ -62,52 +88,230 @@ impl Connector for ConnectorApplication { Message::Control(_) => todo!("impossible control message"), } } + } + + pub fn handle_new_data_message(&mut self, message: DataMessage, ctx: &mut ComponentCtx) { + // Go through all branches that are awaiting new messages and see if + // there is one that can receive this message. + debug_assert!(ctx.workspace_branches.is_empty()); + let mut branches = Vec::new(); // TODO: @Remove + if !self.consensus.handle_new_data_message(&self.tree, &message, ctx, &mut branches) { + // Old message, so drop it + return; + } - // Handle requests coming from the API - { - let mut queue = self.job_queue.lock().unwrap(); - while let Some(job) = queue.pop_front() { - match job { - ApplicationJob::NewChannel((endpoint_a, endpoint_b)) => { - comp_ctx.push_port(endpoint_a); - comp_ctx.push_port(endpoint_b); + for branch_id in branches.drain(..) { + // This branch can receive, so fork and given it the message + let receiving_branch_id = self.tree.fork_branch(branch_id); + self.consensus.notify_of_new_branch(branch_id, receiving_branch_id); + let receiving_branch = &mut self.tree[receiving_branch_id]; + + receiving_branch.insert_message(message.data_header.target_port, message.content.as_message().unwrap().clone()); + self.consensus.notify_of_received_message(receiving_branch_id, &message.sync_header, &message.data_header, &message.content); + + // And prepare the branch for running + self.tree.push_into_queue(QueueKind::Runnable, receiving_branch_id); + } + } + + pub fn handle_new_sync_message(&mut self, message: SyncMessage, ctx: &mut ComponentCtx) { + if let Some(solution_branch_id) = self.consensus.handle_new_sync_message(message, ctx) { + self.collapse_sync_to_solution_branch(solution_branch_id, ctx); + } + } + + fn run_in_sync_mode(&mut self, _sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling { + debug_assert!(self.is_in_sync); + + self.handle_new_messages(comp_ctx); + + let branch_id = self.exec_tree.pop_from_queue(QueueKind::Runnable); + if branch_id.is_none() { + return ConnectorScheduling::NotNow; + } + + let branch_id = branch_id.unwrap(); + let branch = &mut self.exec_tree[branch_id]; + let mut instruction_idx = self.branch_extra[branch_id.index as usize]; + + if instruction_idx >= self.sync_desc.len() { + // Performed last instruction, so this branch is officially at the + // end of the synchronous interaction. + let consistency = self.consensus.notify_of_finished_branch(branch_id); + if consistency == Consistency::Valid { + branch.sync_state = SpeculativeState::ReachedSyncEnd; + self.exec_tree.push_into_queue(QueueKind::FinishedSync, branch_id); + } else { + branch.sync_state = SpeculativeState::Inconsistent; + } + } else { + // We still have instructions to perform + let cur_instruction = &self.sync_desc[instruction_idx]; + self.branch_extra[branch_id.index as usize] += 1; + + match &cur_instruction { + ApplicationSyncAction::Put(port_id, content) => { + let port_id = *port_id; + let consistency = self.consensus.notify_of_speculative_mapping(branch_id, port_id, true); + if consistency == Consistency::Valid { + let (sync_header, data_header) = self.consensus.handle_message_to_send(branch_id, port_id, &content, ctx); + let message = Message::Data(DataMessage { + sync_header, + data_header, + content: DataContent::Message(content.clone()), + }); + comp_ctx.submit_message(message); + self.exec_tree.push_into_queue(QueueKind::Runnable, branch_id); + return ConnectorScheduling::Immediate; + } else { + branch.sync_state = SpeculativeState::Inconsistent; } - ApplicationJob::NewConnector(connector, initial_ports) => { - comp_ctx.push_component(connector, initial_ports); - }, - ApplicationJob::Shutdown => { - debug_assert!(queue.is_empty()); - return ConnectorScheduling::Exit; + }, + ApplicationSyncAction::Get(port_id) => { + let port_id = *port_id; + let consistency = self.consensus.notify_of_speculative_mapping(branch_id, port_id, true); + if consistency == Consistency::Valid { + branch.sync_state = SpeculativeState::HaltedAtBranchPoint; + branch.awaiting_port = port_id; + self.exec_tree.push_into_queue(QueueKind::AwaitingMessage, branch_id); + + let mut any_message_received = false; + for message in comp_ctx.get_read_data_messages(port_id) { + if self.consensus.branch_can_receive(branch_id, &message.sync_header, &message.data_header, &message.content) { + // This branch can receive the message, so we do the + // fork-and-receive dance + let receiving_branch_id = self.exec_tree.fork_branch(branch_id); + let branch = &mut self.exec_tree[receiving_branch_id]; + debug_assert!(receiving_branch_id.index as usize == self.branch_extra.len()); + self.branch_extra.push(instruction_idx + 1); + + branch.insert_message(port_id, message.content.as_message().unwrap().clone()); + + self.consensus.notify_of_new_branch(branch_id, receiving_branch_id); + self.consensus.notify_of_received_message(receiving_branch_id, &message.sync_header, &message.data_header, &message.content); + self.exec_tree.push_into_queue(QueueKind::Runnable, receiving_branch_id); + + any_message_received = true; + } + } + + if any_message_received { + return ConnectorScheduling::Immediate; + } + } else { + branch.sync_state = SpeculativeState::Inconsistent; } } } } + if self.exec_tree.queue_is_empty(QueueKind::Runnable) { + return ConnectorScheduling::NotNow; + } else { + return ConnectorScheduling::Later; + } + } + + fn run_in_deterministic_mode(&mut self, _sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling { + debug_assert!(!self.is_in_sync); + + // In non-sync mode the application component doesn't really do anything + // except performing jobs submitted from the API. This is the only + // case where we expect to be woken up. + let mut queue = self.job_queue.lock().unwrap(); + while let Some(job) = queue.pop_front() { + match job { + ApplicationJob::NewChannel((endpoint_a, endpoint_b)) => { + comp_ctx.push_port(endpoint_a); + comp_ctx.push_port(endpoint_b); + } + ApplicationJob::NewConnector(connector, initial_ports) => { + comp_ctx.push_component(connector, initial_ports); + }, + ApplicationJob::SyncRound(mut description) => { + // Entering sync mode + if description.is_empty() { + // To simplify logic we always have one instruction + description.push(ApplicationSyncAction::Noop); + } + + self.sync_desc = description; + self.is_in_sync = true; + debug_assert!(self.branch_extra.is_empty()); + + let first_branch_id = self.exec_tree.start_sync(); + self.exec_tree.push_into_queue(QueueKind::Runnable, first_branch_id); + self.consensus.start_sync(ctx); + self.branch_extra.push(0); // set first branch to first instruction + + return ConnectorScheduling::Immediate; + }, + ApplicationJob::Shutdown => { + debug_assert!(queue.is_empty()); + return ConnectorScheduling::Exit; + } + } + } + return ConnectorScheduling::NotNow; } } +// ----------------------------------------------------------------------------- +// ApplicationInterface +// ----------------------------------------------------------------------------- + +#[derive(Debug)] +pub enum ChannelCreationError { + InSync, +} + +#[derive(Debug)] +pub enum ApplicationStartSyncError { + AlreadyInSync, + NoSyncActions, + IncorrectPortKind, + UnownedPort, +} + +#[derive(Debug)] +pub enum ApplicationEndSyncError { + NotInSync, +} + +pub enum ApplicationSyncAction { + Put(PortIdLocal, ValueGroup), + Get(PortIdLocal), +} + /// The interface to a `ApplicationConnector`. This allows setting up the /// interactions the `ApplicationConnector` performs within a synchronous round. pub struct ApplicationInterface { sync_done: SyncDone, job_queue: JobQueue, runtime: Arc, + is_in_sync: bool, connector_id: ConnectorId, - owned_ports: Vec, + owned_ports: Vec<(PortKind, PortIdLocal)>, } impl ApplicationInterface { fn new(sync_done: SyncDone, job_queue: JobQueue, runtime: Arc) -> Self { return Self{ sync_done, job_queue, runtime, + is_in_sync: false, connector_id: ConnectorId::new_invalid(), owned_ports: Vec::new(), } } - /// Creates a new channel. - pub fn create_channel(&mut self) -> Channel { + /// Creates a new channel. Can only fail if the application interface is + /// currently in sync mode. + pub fn create_channel(&mut self) -> Result { + if self.is_in_sync { + return Err(ChannelCreationError::InSync); + } + let (getter_port, putter_port) = self.runtime.create_channel(self.connector_id); debug_assert_eq!(getter_port.kind, PortKind::Getter); let getter_id = getter_port.self_id; @@ -120,10 +324,10 @@ impl ApplicationInterface { // Add to owned ports for error checking while creating a connector self.owned_ports.reserve(2); - self.owned_ports.push(putter_id); - self.owned_ports.push(getter_id); + self.owned_ports.push((PortKind::Putter, putter_id)); + self.owned_ports.push((PortKind::Getter, getter_id)); - return Channel{ putter_id, getter_id }; + return Ok(Channel{ putter_id, getter_id }); } /// Creates a new connector. Note that it is not scheduled immediately, but @@ -131,6 +335,10 @@ impl ApplicationInterface { /// connector being scheduled. // TODO: Yank out scheduler logic for common use. pub fn create_connector(&mut self, module: &str, routine: &str, arguments: ValueGroup) -> Result<(), ComponentCreationError> { + if self.is_in_sync { + return Err(ComponentCreationError::InSync); + } + // Retrieve ports and make sure that we own the ones that are currently // specified. This is also checked by the scheduler, but that is done // asynchronously. @@ -162,15 +370,58 @@ impl ApplicationInterface { return Ok(()); } - /// Check if the next sync-round is finished. - pub fn try_wait(&self) -> bool { - let (is_done, _) = &*self.sync_done; - let lock = is_done.lock().unwrap(); - return *lock; + /// Queues up a description of a synchronous round to run. Will not actually + /// run the synchronous behaviour in blocking fashion. The results *must* be + /// retrieved using `try_wait` or `wait` for the interface to be considered + /// in non-sync mode. + pub fn perform_sync_round(&mut self, actions: Vec) -> Result<(), ApplicationStartSyncError> { + if self.is_in_sync { + return Err(ApplicationStartSyncError::AlreadyInSync); + } + + // Check the action ports for consistency + for action in &actions { + let (port_id, expected_kind) = match action { + ApplicationSyncAction::Put(port_id, _) => (*port_id, PortKind::Putter), + ApplicationSyncAction::Get(port_id) => (*port_id, PortKind::Getter), + }; + + match self.find_port_by_id(port_id) { + Some(port_kind) => { + if port_kind != expected_kind { + return Err(ApplicationStartSyncError::IncorrectPortKind) + } + }, + None => { + return Err(ApplicationStartSyncError::UnownedPort); + } + } + } + + // Everything is consistent, go into sync mode and send the actions off + // to the component that will actually perform the sync round + self.is_in_sync = true; + { + let (is_done, _) = &*self.sync_done; + let mut lock = is_done.lock().unwrap(); + *lock = false; + } + + { + let mut lock = self.job_queue.lock().unwrap(); + lock.push_back(ApplicationJob::SyncRound(actions)); + } + + self.wake_up_connector_with_ping(); + return Ok(()) } /// Wait until the next sync-round is finished - pub fn wait(&self) { + pub fn wait(&self) -> Result, ApplicationEndSyncError> { + if !self.is_in_sync { + return Err(ApplicationEndSyncError::NotInSync); + } + let (is_done, condition) = &*self.sync_done; let lock = is_done.lock().unwrap(); condition.wait_while(lock, |v| !*v).unwrap(); // wait while not done @@ -198,6 +449,12 @@ impl ApplicationInterface { self.runtime.push_work(key); } } + + fn find_port_by_id(&self, port_id: PortIdLocal) -> Option { + return self.owned_ports.iter() + .find(|(_, owned_id)| *owned_id == port_id) + .map(|(port_kind, _)| *port_kind); + } } impl Drop for ApplicationInterface {