From fa3f895c89000ac388468797d4346080fbbaecd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rom=C3=A1n=20C=C3=A1rdenas=20Rodr=C3=ADguez?= Date: Wed, 11 Nov 2026 19:05:00 +0900 Subject: [PATCH 1/2] feat(dag): add per-node WCET estimation --- applications/rd_gen_to_dags/src/build_dag.rs | 3 + applications/tests/test_dag/src/lib.rs | 34 +- awkernel_async_lib/src/dag.rs | 556 ++++++++++++++++++- userland/src/lib.rs | 4 +- 4 files changed, 559 insertions(+), 38 deletions(-) diff --git a/applications/rd_gen_to_dags/src/build_dag.rs b/applications/rd_gen_to_dags/src/build_dag.rs index b6af74cad..a7731c057 100644 --- a/applications/rd_gen_to_dags/src/build_dag.rs +++ b/applications/rd_gen_to_dags/src/build_dag.rs @@ -103,6 +103,7 @@ macro_rules! register_source { pub_topics, $sched_type, convert_duration($node_data.get_period().expect("Source node's period should always be Some.")), + None, ).await; Ok(()) } @@ -153,6 +154,7 @@ macro_rules! register_sink { sub_topics, $sched_type, convert_duration($node_data.get_end_to_end_deadline().expect("Sink node's relative_deadline should always be Some.")), + None, ).await; Ok(()) } @@ -215,6 +217,7 @@ macro_rules! register_intermediate { sub_topics, pub_topics, $sched_type, + None, ).await; Ok(()) } diff --git a/applications/tests/test_dag/src/lib.rs b/applications/tests/test_dag/src/lib.rs index 0d2f5efbf..bbe286399 100644 --- a/applications/tests/test_dag/src/lib.rs +++ b/applications/tests/test_dag/src/lib.rs @@ -1,19 +1,20 @@ #![no_std] extern crate alloc; -use alloc::{borrow::Cow, vec}; -use awkernel_async_lib::dag::{create_dag, finish_create_dags}; +use alloc::{borrow::Cow, vec, vec::Vec}; +use awkernel_async_lib::dag::{create_dag, finish_create_dags, DagError}; use awkernel_async_lib::scheduler::SchedulerType; use awkernel_lib::{cpu::CpuSet, delay::wait_microsec}; use core::time::Duration; const LOG_ENABLE: bool = true; +const SOURCE_EXECUTION_TIME_US: u64 = 100_000; -pub async fn run() { +pub async fn run() -> Result<(), Vec> { wait_microsec(1000000); - let period = Duration::from_nanos(1000000000); - let exe_time = (period.as_micros() as f64 * 0.1) as u64; + let period = Duration::from_secs(1); + let exe_time = SOURCE_EXECUTION_TIME_US; log::debug!("period is {} [ns]", period.as_nanos()); @@ -32,6 +33,7 @@ pub async fn run() { vec![Cow::from("topic0")], SchedulerType::EDF(5, CpuSet::all()), period, + Some(Duration::from_micros(SOURCE_EXECUTION_TIME_US)), ) .await; @@ -48,6 +50,7 @@ pub async fn run() { vec![Cow::from("topic0")], vec![Cow::from("topic1"), Cow::from("topic2")], SchedulerType::EDF(10, CpuSet::all()), + Some(Duration::from_millis(100)), ) .await; @@ -63,6 +66,7 @@ pub async fn run() { vec![Cow::from("topic1")], vec![Cow::from("topic3")], SchedulerType::EDF(10, CpuSet::all()), + Some(Duration::from_millis(50)), ) .await; @@ -78,6 +82,7 @@ pub async fn run() { vec![Cow::from("topic2")], vec![Cow::from("topic4")], SchedulerType::EDF(10, CpuSet::all()), + Some(Duration::from_millis(50)), ) .await; @@ -92,22 +97,13 @@ pub async fn run() { vec![Cow::from("topic3"), Cow::from("topic4")], SchedulerType::EDF(10, CpuSet::all()), Duration::from_secs(1), + Some(Duration::from_millis(100)), ) .await; - let result = finish_create_dags(&[dag.clone()]).await; - - match result { - Ok(_) => { - if LOG_ENABLE { - log::info!("DAG created successfully"); - } - } - Err(errors) => { - log::error!("Failed to create DAGs"); - for error in errors { - log::error!("- {error}"); - } - } + finish_create_dags(core::slice::from_ref(&dag)).await?; + if LOG_ENABLE { + log::info!("DAG created successfully"); } + Ok(()) } diff --git a/awkernel_async_lib/src/dag.rs b/awkernel_async_lib/src/dag.rs index 9b19750c2..8f251c3a6 100644 --- a/awkernel_async_lib/src/dag.rs +++ b/awkernel_async_lib/src/dag.rs @@ -35,6 +35,16 @@ //! - **No Dangling Edges**: Every published topic must be subscribed to by another node, and every subscribed topic must have a publisher. //! - **Globally Unique Topics (Inter-DAG)**: A topic name must be unique across all active DAGs in the system. This prevents different data pipelines from unintentionally interfering with each other. //! +//! ## Estimated WCET and feasibility +//! +//! Registration methods accept an optional estimated WCET. An absent estimate is treated as zero +//! by DAG validation, which computes each node's estimated earliest start and latest finish and +//! rejects estimates whose longest dependency path exceeds the sink's relative deadline. +//! +//! WCET estimates are used for feasibility validation only. They do not change interval-tick job +//! release times or the existing GEDF deadline assignment: GEDF continues to use the job release +//! time and the sink's relative deadline. +//! //! # Example Usage //! //! See the `applications/tests/test_dag` example for practical usage. @@ -54,12 +64,12 @@ mod visit; #[cfg(feature = "perf")] mod performance; +pub use crate::dag::graph::NodeIndex; use crate::{ dag::{ graph::{ algo::{connected_components, is_cyclic_directed}, direction::Direction, - NodeIndex, }, visit::{EdgeRef, IntoNodeReferences, NodeRef}, }, @@ -130,6 +140,7 @@ impl_tuple_size!(T1, T2, T3); pub enum DagError { NodeNotFound(u32, usize), MissingSinkDeadline(u32), + InfeasibleWcet(u32, usize), NotWeaklyConnected(u32), ContainsCycle(u32), MissingPendingTasks(u32), @@ -152,6 +163,9 @@ impl core::fmt::Display for DagError { match self { DagError::NodeNotFound(dag_id, node_id) => write!(f, "DAG#{dag_id} Node#{node_id} not found"), DagError::MissingSinkDeadline(dag_id) => write!(f, "DAG#{dag_id} has no sink relative deadline"), + DagError::InfeasibleWcet(dag_id, node_id) => { + write!(f, "DAG#{dag_id} Node#{node_id}: estimated WCETs exceed the sink relative deadline") + } DagError::NotWeaklyConnected(dag_id) => write!(f, "DAG#{dag_id} is not weakly connected"), DagError::ContainsCycle(dag_id) => write!(f, "DAG#{dag_id} contains a cycle"), DagError::MissingPendingTasks(dag_id) => write!(f, "DAG#{dag_id} has missing pending tasks"), @@ -197,6 +211,41 @@ pub(crate) struct JobInfo { pub(crate) absolute_deadline: u64, } +/// Timing estimates for a node, expressed as offsets from the DAG job's release. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct NodeTiming { + /// Estimated worst-case execution time. An absent estimate is treated as zero in the analysis. + pub estimated_wcet: Duration, + /// Earliest estimated start, computed from the node's predecessors during DAG validation. + pub estimated_earliest_start: Duration, + /// Latest estimated finish, computed from the node's successors during DAG validation. + pub estimated_latest_finish: Duration, + /// True if the node is on a critical path, that is, a longest path of the DAG by WCET. + /// Such a node has the least slack, which is `D` minus the length of that path. + pub is_critical: bool, +} + +impl NodeTiming { + /// Returns the earliest finish, or `None` if the sum cannot be represented. + pub fn estimated_earliest_finish(&self) -> Option { + self.estimated_earliest_start + .checked_add(self.estimated_wcet) + } + + /// Returns the latest start, or `None` if the WCET exceeds the latest finish. + pub fn estimated_latest_start(&self) -> Option { + self.estimated_latest_finish + .checked_sub(self.estimated_wcet) + } + + /// Returns the slack, or `None` if the earliest finish overflows or + /// exceeds the latest finish. + pub fn slack(&self) -> Option { + self.estimated_latest_finish + .checked_sub(self.estimated_earliest_finish()?) + } +} + impl DagGraph { #[inline] fn get_sink_relative_deadline(&self) -> Option { @@ -214,6 +263,51 @@ impl DagGraph { None => false, } } + + #[inline] + fn get_node_wcet(&self, node_idx: NodeIndex) -> Option { + self.node_weight(node_idx) + .map(|info| info.wcet.unwrap_or(Duration::ZERO)) + } + + /// Returns the nodes in topological order: every node comes after all its predecessors. + /// + /// Returns an error for a cycle or an inconsistent predecessor count. + fn topological_order(&self, dag_id: u32) -> Result, DagError> { + let mut in_degree: BTreeMap = self + .node_indices() + .map(|idx| { + ( + idx, + self.neighbors_directed(idx, Direction::Incoming).count(), + ) + }) + .collect(); + let mut ready: Vec = in_degree + .iter() + .filter(|(_, degree)| **degree == 0) + .map(|(idx, _)| *idx) + .collect(); + let mut order: Vec = Vec::with_capacity(in_degree.len()); + while let Some(idx) = ready.pop() { + order.push(idx); + for succ in self.neighbors_directed(idx, Direction::Outgoing) { + let degree = in_degree + .get_mut(&succ) + .ok_or(DagError::NodeNotFound(dag_id, succ.index()))?; + *degree = degree + .checked_sub(1) + .ok_or(DagError::ContainsCycle(dag_id))?; + if *degree == 0 { + ready.push(succ); + } + } + } + if order.len() != self.node_count() { + return Err(DagError::ContainsCycle(dag_id)); + } + Ok(order) + } } pub struct Dag { @@ -279,12 +373,15 @@ impl Dag { &self, subscribe_topic_names: &[Cow<'static, str>], publish_topic_names: &[Cow<'static, str>], + wcet: Option, ) -> NodeIndex { let add_node_info = NodeInfo { task_id: 0, // Temporary task_id subscribe_topic_names: subscribe_topic_names.to_vec(), publish_topic_names: publish_topic_names.to_vec(), relative_deadline: None, + timing: NodeTiming::default(), + wcet, num_finished: 0, deadline_job: None, }; @@ -348,6 +445,7 @@ impl Dag { subscribe_topic_names: Vec>, publish_topic_names: Vec>, sched_type: SchedulerType, + wcet: Option, ) where F: Fn( ::Item, @@ -361,7 +459,8 @@ impl Dag { ::Item: TupleSize, ::Item: TupleSize, { - let node_idx = self.add_node_with_topic_edges(&subscribe_topic_names, &publish_topic_names); + let node_idx = + self.add_node_with_topic_edges(&subscribe_topic_names, &publish_topic_names, wcet); self.check_subscribe_mismatch::(&subscribe_topic_names, node_idx); self.check_publish_mismatch::(&publish_topic_names, node_idx); @@ -396,13 +495,14 @@ impl Dag { publish_topic_names: Vec>, sched_type: SchedulerType, period: Duration, + wcet: Option, ) where F: Fn() -> ::Item + Send + 'static, Ret: VectorToPublishers, Ret::Publishers: Send, ::Item: TupleSize, { - let node_idx = self.add_node_with_topic_edges(&Vec::new(), &publish_topic_names); + let node_idx = self.add_node_with_topic_edges(&[], &publish_topic_names, wcet); self.check_publish_mismatch::(&publish_topic_names, node_idx); let measure_f: Option = { @@ -448,13 +548,14 @@ impl Dag { subscribe_topic_names: Vec>, sched_type: SchedulerType, relative_deadline: Duration, + wcet: Option, ) where F: Fn(::Item) + Send + 'static, Args: VectorToSubscribers, Args::Subscribers: Send, ::Item: TupleSize, { - let node_idx = self.add_node_with_topic_edges(&subscribe_topic_names, &Vec::new()); + let node_idx = self.add_node_with_topic_edges(&subscribe_topic_names, &[], wcet); self.set_relative_deadline(node_idx, relative_deadline) .unwrap(); self.check_subscribe_mismatch::(&subscribe_topic_names, node_idx); @@ -682,6 +783,8 @@ struct NodeInfo { subscribe_topic_names: Vec>, publish_topic_names: Vec>, relative_deadline: Option, + timing: NodeTiming, + wcet: Option, num_finished: u64, // Number of DAG jobs that this node finished. deadline_job: Option, // Job whose deadline the last wake of this node got. } @@ -837,6 +940,8 @@ fn validate_all_rules(dags: &[Arc]) -> Result<(), Vec> { errors.extend(pubsub_duplicate_errors); } else if let Err(duplicate_error) = validate_single_publisher_per_topic(dag) { errors.extend(duplicate_error); + } else if let Err(timing_error) = compute_timing(dag) { + errors.push(timing_error); } } @@ -934,6 +1039,118 @@ fn validate_dag(dag: &Dag) -> Result<(), DagError> { Ok(()) } +/// Computes per-node earliest starts and latest finishes from declared WCETs and the sink +/// relative deadline. This runs during DAG setup, not in the scheduler or reactor execution +/// paths. Its work is bounded by the configured graph size and edge count. +/// +/// The forward pass is `ES(v) = max(ES(p) + C(p))` over predecessors. The backward pass is +/// `LF(v) = min(LF(s) - C(s))` over successors, with the sink's latest finish fixed at its +/// relative deadline. The computed values are committed to the graph only if every node is +/// feasible. +fn compute_timing(dag: &Dag) -> Result<(), DagError> { + let dag_id = dag.id; + let mut node = MCSNode::new(); + let mut graph = dag.graph.lock(&mut node); + let sink_deadline = graph + .get_sink_relative_deadline() + .ok_or(DagError::MissingSinkDeadline(dag_id))?; + + let order = graph.topological_order(dag_id)?; + + // Forward pass to compute per-node earliest start times. + let mut earliest_start: BTreeMap = BTreeMap::new(); + for &idx in &order { + let mut start = Duration::ZERO; + for pred in graph.neighbors_directed(idx, Direction::Incoming) { + let pred_start = earliest_start + .get(&pred) + .copied() + .ok_or(DagError::NodeNotFound(dag_id, pred.index()))?; + let pred_wcet = graph + .get_node_wcet(pred) + .ok_or(DagError::NodeNotFound(dag_id, pred.index()))?; + let pred_finish = pred_start + .checked_add(pred_wcet) + .ok_or(DagError::InfeasibleWcet(dag_id, pred.index()))?; + start = start.max(pred_finish); + } + earliest_start.insert(idx, start); + } + + // Backward pass to compute per-node latest finish times. + let mut latest_finish: BTreeMap = BTreeMap::new(); + for &idx in order.iter().rev() { + let mut finish = sink_deadline; + let mut has_successor = false; + for succ in graph.neighbors_directed(idx, Direction::Outgoing) { + let succ_finish = latest_finish + .get(&succ) + .copied() + .ok_or(DagError::NodeNotFound(dag_id, succ.index()))?; + let succ_wcet = graph + .get_node_wcet(succ) + .ok_or(DagError::NodeNotFound(dag_id, succ.index()))?; + let succ_start = succ_finish + .checked_sub(succ_wcet) + .ok_or(DagError::InfeasibleWcet(dag_id, succ.index()))?; + finish = if has_successor { + finish.min(succ_start) + } else { + succ_start + }; + has_successor = true; + } + latest_finish.insert(idx, finish); + } + + // Check feasibility, and find the slack of every node. + let mut slacks: BTreeMap = BTreeMap::new(); + let mut timings: BTreeMap = BTreeMap::new(); + for &idx in &order { + let timing = NodeTiming { + estimated_wcet: graph + .get_node_wcet(idx) + .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?, + estimated_earliest_start: earliest_start + .get(&idx) + .copied() + .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?, + estimated_latest_finish: latest_finish + .get(&idx) + .copied() + .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?, + is_critical: false, + }; + let slack = timing + .slack() + .ok_or_else(|| DagError::InfeasibleWcet(dag_id, idx.index()))?; + slacks.insert(idx, slack); + timings.insert(idx, timing); + } + + // A node is critical if it has the least slack, which only the nodes on a longest path have. + let min_slack = slacks + .values() + .min() + .copied() + .ok_or(DagError::MissingSinkDeadline(dag_id))?; + + for (&idx, timing) in &mut timings { + let slack = slacks + .get(&idx) + .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?; + timing.is_critical = *slack == min_slack; + } + for (idx, timing) in timings { + let info = graph + .node_weight_mut(idx) + .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?; + info.timing = timing; + } + + Ok(()) +} + /// NOTE: On the architecture for this arity validation. /// /// Ideally, this validation would be performed at an earlier stage, such as inside @@ -1331,8 +1548,8 @@ mod tests { #[test] fn late_node_keeps_the_deadline_of_its_job() { let dag = create_dag(); - let source = dag.add_node_with_topic_edges(&[], &["deadline_test_topic".into()]); - let sink = dag.add_node_with_topic_edges(&["deadline_test_topic".into()], &[]); + let source = dag.add_node_with_topic_edges(&[], &["deadline_test_topic".into()], None); + let sink = dag.add_node_with_topic_edges(&["deadline_test_topic".into()], &[], None); dag.set_relative_deadline(sink, Duration::from_micros(50)) .unwrap(); @@ -1377,10 +1594,13 @@ mod tests { #[test] fn deadline_stays_until_every_node_finishes_its_job() { let dag = create_dag(); - let source = dag.add_node_with_topic_edges(&[], &["retention_test_a".into()]); - let middle = dag - .add_node_with_topic_edges(&["retention_test_a".into()], &["retention_test_b".into()]); - let sink = dag.add_node_with_topic_edges(&["retention_test_b".into()], &[]); + let source = dag.add_node_with_topic_edges(&[], &["retention_test_a".into()], None); + let middle = dag.add_node_with_topic_edges( + &["retention_test_a".into()], + &["retention_test_b".into()], + None, + ); + let sink = dag.add_node_with_topic_edges(&["retention_test_b".into()], &[], None); dag.set_relative_deadline(sink, Duration::from_micros(50)) .unwrap(); @@ -1446,8 +1666,8 @@ mod tests { #[test] fn deadlines_of_a_stopped_node_are_capped() { let dag = create_dag(); - let source = dag.add_node_with_topic_edges(&[], &["cap_test_topic".into()]); - let sink = dag.add_node_with_topic_edges(&["cap_test_topic".into()], &[]); + let source = dag.add_node_with_topic_edges(&[], &["cap_test_topic".into()], None); + let sink = dag.add_node_with_topic_edges(&["cap_test_topic".into()], &[], None); dag.set_relative_deadline(sink, Duration::from_micros(50)) .unwrap(); @@ -1482,7 +1702,7 @@ mod tests { Err(DagError::MissingSinkDeadline(id)) if id == dag.id )); - let sink = dag.add_node_with_topic_edges(&[], &[]); + let sink = dag.add_node_with_topic_edges(&[], &[], None); assert!(matches!( dag.get_sink_relative_deadline(), Err(DagError::MissingSinkDeadline(id)) if id == dag.id @@ -1505,8 +1725,8 @@ mod tests { use crate::task::{DagInfo, State}; let dag = create_dag(); - let source = dag.add_node_with_topic_edges(&[], &["dag_deadline_test_topic".into()]); - let sink = dag.add_node_with_topic_edges(&["dag_deadline_test_topic".into()], &[]); + let source = dag.add_node_with_topic_edges(&[], &["dag_deadline_test_topic".into()], None); + let sink = dag.add_node_with_topic_edges(&["dag_deadline_test_topic".into()], &[], None); dag.set_relative_deadline(sink, Duration::from_micros(50)) .unwrap(); let source_info = DagInfo { @@ -1572,8 +1792,8 @@ mod tests { use crate::task::{DagInfo, State}; let dag = create_dag(); - let source = dag.add_node_with_topic_edges(&[], &["fixed_deadline_topic".into()]); - let sink = dag.add_node_with_topic_edges(&["fixed_deadline_topic".into()], &[]); + let source = dag.add_node_with_topic_edges(&[], &["fixed_deadline_topic".into()], None); + let sink = dag.add_node_with_topic_edges(&["fixed_deadline_topic".into()], &[], None); dag.set_relative_deadline(sink, Duration::from_micros(50)) .unwrap(); let source_info = DagInfo { @@ -1620,7 +1840,307 @@ mod tests { #[should_panic(expected = "The DAG source released a job before its next release time was set")] fn source_release_requires_tick_target() { let dag = create_dag(); - let source = dag.add_node_with_topic_edges(&[], &[]); + let source = dag.add_node_with_topic_edges(&[], &[], None); dag.get_or_release_job(source, true); } + + fn timing_chain(wcets: [Option; 3]) -> (Arc, [NodeIndex; 3]) { + let dag = create_dag(); + let source_topic: Cow<'static, str> = alloc::format!("timing_{}_source", dag.id).into(); + let sink_topic: Cow<'static, str> = alloc::format!("timing_{}_sink", dag.id).into(); + let source = + dag.add_node_with_topic_edges(&[], core::slice::from_ref(&source_topic), wcets[0]); + let middle = dag.add_node_with_topic_edges( + core::slice::from_ref(&source_topic), + core::slice::from_ref(&sink_topic), + wcets[1], + ); + let sink = dag.add_node_with_topic_edges(&[sink_topic], &[], wcets[2]); + dag.set_relative_deadline(sink, Duration::from_millis(100)) + .unwrap(); + (dag, [source, middle, sink]) + } + + fn timing_diamond(wcets: [Option; 4]) -> (Arc, [NodeIndex; 4]) { + let dag = create_dag(); + let source_to_a: Cow<'static, str> = alloc::format!("timing_{}_source_a", dag.id).into(); + let source_to_b: Cow<'static, str> = alloc::format!("timing_{}_source_b", dag.id).into(); + let a_to_sink: Cow<'static, str> = alloc::format!("timing_{}_a_sink", dag.id).into(); + let b_to_sink: Cow<'static, str> = alloc::format!("timing_{}_b_sink", dag.id).into(); + let source = dag.add_node_with_topic_edges( + &[], + &[source_to_a.clone(), source_to_b.clone()], + wcets[0], + ); + let a = dag.add_node_with_topic_edges( + core::slice::from_ref(&source_to_a), + core::slice::from_ref(&a_to_sink), + wcets[1], + ); + let b = dag.add_node_with_topic_edges( + core::slice::from_ref(&source_to_b), + core::slice::from_ref(&b_to_sink), + wcets[2], + ); + let sink = dag.add_node_with_topic_edges(&[a_to_sink, b_to_sink], &[], wcets[3]); + dag.set_relative_deadline(sink, Duration::from_millis(100)) + .unwrap(); + (dag, [source, a, b, sink]) + } + + fn timing_of(dag: &Dag, idx: NodeIndex) -> NodeTiming { + let mut node = MCSNode::new(); + let graph = dag.graph.lock(&mut node); + graph.node_weight(idx).unwrap().timing + } + + #[test] + fn node_timing_helpers_return_derived_times_and_boundaries() { + let timing = NodeTiming { + estimated_wcet: Duration::from_millis(20), + estimated_earliest_start: Duration::from_millis(10), + estimated_latest_finish: Duration::from_millis(70), + is_critical: false, + }; + assert_eq!( + timing.estimated_earliest_finish(), + Some(Duration::from_millis(30)) + ); + assert_eq!( + timing.estimated_latest_start(), + Some(Duration::from_millis(50)) + ); + assert_eq!(timing.slack(), Some(Duration::from_millis(40))); + + for duration in [Duration::ZERO, Duration::MAX] { + let boundary = NodeTiming { + estimated_earliest_start: duration, + estimated_latest_finish: duration, + ..NodeTiming::default() + }; + assert_eq!(boundary.estimated_earliest_finish(), Some(duration)); + assert_eq!(boundary.estimated_latest_start(), Some(duration)); + assert_eq!(boundary.slack(), Some(Duration::ZERO)); + } + } + + #[test] + fn node_timing_helpers_propagate_overflow_and_underflow() { + let overflowing = NodeTiming { + estimated_wcet: Duration::from_nanos(1), + estimated_earliest_start: Duration::MAX, + estimated_latest_finish: Duration::MAX, + is_critical: false, + }; + assert_eq!(overflowing.estimated_earliest_finish(), None); + assert_eq!(overflowing.slack(), None); + + let uncomputed = NodeTiming { + estimated_wcet: Duration::from_nanos(1), + ..NodeTiming::default() + }; + assert_eq!(uncomputed.estimated_latest_start(), None); + assert_eq!(uncomputed.slack(), None); + + let infeasible = NodeTiming { + estimated_wcet: Duration::from_millis(10), + estimated_earliest_start: Duration::from_millis(20), + estimated_latest_finish: Duration::from_millis(25), + is_critical: false, + }; + assert_eq!( + infeasible.estimated_latest_start(), + Some(Duration::from_millis(15)) + ); + assert_eq!(infeasible.slack(), None); + } + + #[test] + fn chain_timing_uses_predecessor_and_successor_wcets() { + let (dag, [source, middle, sink]) = timing_chain([ + Some(Duration::from_millis(10)), + Some(Duration::from_millis(20)), + Some(Duration::from_millis(30)), + ]); + + assert!(compute_timing(&dag).is_ok()); + assert_eq!( + timing_of(&dag, source), + NodeTiming { + estimated_wcet: Duration::from_millis(10), + estimated_earliest_start: Duration::ZERO, + estimated_latest_finish: Duration::from_millis(50), + is_critical: true, + } + ); + assert_eq!( + timing_of(&dag, middle), + NodeTiming { + estimated_wcet: Duration::from_millis(20), + estimated_earliest_start: Duration::from_millis(10), + estimated_latest_finish: Duration::from_millis(70), + is_critical: true, + } + ); + assert_eq!( + timing_of(&dag, sink), + NodeTiming { + estimated_wcet: Duration::from_millis(30), + estimated_earliest_start: Duration::from_millis(30), + estimated_latest_finish: Duration::from_millis(100), + is_critical: true, + } + ); + } + + #[test] + fn branch_join_timing_uses_the_longest_predecessor_path() { + let (dag, [source, a, b, sink]) = timing_diamond([ + Some(Duration::from_millis(10)), + Some(Duration::from_millis(30)), + Some(Duration::from_millis(5)), + Some(Duration::from_millis(20)), + ]); + + assert!(compute_timing(&dag).is_ok()); + assert_eq!( + timing_of(&dag, sink).estimated_earliest_start, + Duration::from_millis(40) + ); + assert_eq!( + timing_of(&dag, a).estimated_latest_finish, + Duration::from_millis(80) + ); + assert_eq!( + timing_of(&dag, b).estimated_latest_finish, + Duration::from_millis(80) + ); + assert_eq!( + timing_of(&dag, source).estimated_latest_finish, + Duration::from_millis(50) + ); + for idx in [source, a, sink] { + let timing = timing_of(&dag, idx); + assert!(timing.is_critical); + assert_eq!(timing.slack(), Some(Duration::from_millis(40))); + } + let noncritical = timing_of(&dag, b); + assert!(!noncritical.is_critical); + assert_eq!(noncritical.slack(), Some(Duration::from_millis(65))); + } + + #[test] + fn critical_path_equal_to_deadline_is_feasible() { + let (dag, [source, _middle, sink]) = timing_chain([ + Some(Duration::from_millis(10)), + Some(Duration::from_millis(20)), + Some(Duration::from_millis(30)), + ]); + dag.set_relative_deadline(sink, Duration::from_millis(60)) + .unwrap(); + + assert!(compute_timing(&dag).is_ok()); + assert_eq!( + timing_of(&dag, source).estimated_latest_finish, + Duration::from_millis(10) + ); + } + + #[test] + fn timing_overflow_returns_infeasible_wcet() { + let (dag, [_, middle, sink]) = + timing_chain([Some(Duration::MAX), Some(Duration::from_nanos(1)), None]); + dag.set_relative_deadline(sink, Duration::MAX).unwrap(); + + assert!(matches!( + compute_timing(&dag), + Err(DagError::InfeasibleWcet(id, index)) + if id == dag.id && index == middle.index() + )); + } + + #[test] + fn sink_wcet_over_deadline_returns_infeasible_wcet() { + let (dag, [_, _, sink]) = timing_chain([None, None, Some(Duration::from_millis(101))]); + assert!(matches!( + compute_timing(&dag), + Err(DagError::InfeasibleWcet(id, index)) + if id == dag.id && index == sink.index() + )); + } + + #[test] + fn maximum_duration_critical_path_is_feasible() { + let (dag, [source, middle, sink]) = timing_chain([Some(Duration::MAX), None, None]); + dag.set_relative_deadline(sink, Duration::MAX).unwrap(); + compute_timing(&dag).unwrap(); + + for idx in [source, middle, sink] { + let timing = timing_of(&dag, idx); + assert!(timing.is_critical); + assert_eq!(timing.estimated_earliest_finish(), Some(Duration::MAX)); + assert_eq!(timing.slack(), Some(Duration::ZERO)); + } + } + + #[test] + fn timing_rejects_a_partial_topological_order() { + let (dag, [source, middle, _]) = timing_chain([None; 3]); + { + let mut node = MCSNode::new(); + let mut graph = dag.graph.lock(&mut node); + graph.add_edge( + middle, + source, + EdgeInfo { + topic_name: "cycle".into(), + }, + ); + } + assert!(matches!( + compute_timing(&dag), + Err(DagError::ContainsCycle(id)) if id == dag.id + )); + } + + #[test] + fn zero_wcets_fit_a_zero_relative_deadline() { + let dag = create_dag(); + let source = dag.add_node_with_topic_edges(&[], &[], None); + dag.set_relative_deadline(source, Duration::ZERO).unwrap(); + + assert!(compute_timing(&dag).is_ok()); + assert_eq!( + timing_of(&dag, source), + NodeTiming { + is_critical: true, + ..NodeTiming::default() + } + ); + } + + #[test] + fn timing_without_sink_deadline_returns_missing_sink_deadline() { + let dag = create_dag(); + dag.add_node_with_topic_edges(&[], &[], None); + + assert!(matches!( + compute_timing(&dag), + Err(DagError::MissingSinkDeadline(id)) if id == dag.id + )); + } + + #[test] + fn absent_and_zero_wcets_remain_distinct_but_analyze_as_zero() { + let dag = create_dag(); + let absent = dag.add_node_with_topic_edges(&[], &[], None); + let zero = dag.add_node_with_topic_edges(&[], &[], Some(Duration::ZERO)); + let mut node = MCSNode::new(); + let graph = dag.graph.lock(&mut node); + + assert_eq!(graph.node_weight(absent).unwrap().wcet, None); + assert_eq!(graph.node_weight(zero).unwrap().wcet, Some(Duration::ZERO)); + assert_eq!(graph.get_node_wcet(absent), Some(Duration::ZERO)); + assert_eq!(graph.get_node_wcet(zero), Some(Duration::ZERO)); + } } diff --git a/userland/src/lib.rs b/userland/src/lib.rs index a21a1450c..f45866dcf 100644 --- a/userland/src/lib.rs +++ b/userland/src/lib.rs @@ -45,7 +45,9 @@ pub async fn run() -> Result<(), Cow<'static, str>> { test_measure_channel_heavy::run().await; // measure channel heavy #[cfg(feature = "test_dag")] - test_dag::run().await; // test for DAG + test_dag::run() + .await + .map_err(|errors| Cow::Owned(alloc::format!("DAG test failed: {errors:?}")))?; // test for DAG #[cfg(feature = "test_dvfs")] test_dvfs::run().await; // test for DVFS From aac4096375f1c96a5a3f2e4e0c88ffe8476e0a53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rom=C3=A1n=20C=C3=A1rdenas=20Rodr=C3=ADguez?= Date: Wed, 18 Nov 2026 15:16:09 +0900 Subject: [PATCH 2/2] address comments --- applications/rd_gen_to_dags/src/build_dag.rs | 6 +- applications/tests/test_dag/src/lib.rs | 20 +- awkernel_async_lib/src/dag.rs | 592 ++++++++----------- userland/src/lib.rs | 4 +- 4 files changed, 255 insertions(+), 367 deletions(-) diff --git a/applications/rd_gen_to_dags/src/build_dag.rs b/applications/rd_gen_to_dags/src/build_dag.rs index a7731c057..6e52c5691 100644 --- a/applications/rd_gen_to_dags/src/build_dag.rs +++ b/applications/rd_gen_to_dags/src/build_dag.rs @@ -103,7 +103,7 @@ macro_rules! register_source { pub_topics, $sched_type, convert_duration($node_data.get_period().expect("Source node's period should always be Some.")), - None, + Some(convert_duration(execution_time)), ).await; Ok(()) } @@ -154,7 +154,7 @@ macro_rules! register_sink { sub_topics, $sched_type, convert_duration($node_data.get_end_to_end_deadline().expect("Sink node's relative_deadline should always be Some.")), - None, + Some(convert_duration(execution_time)), ).await; Ok(()) } @@ -217,7 +217,7 @@ macro_rules! register_intermediate { sub_topics, pub_topics, $sched_type, - None, + Some(convert_duration(execution_time)), ).await; Ok(()) } diff --git a/applications/tests/test_dag/src/lib.rs b/applications/tests/test_dag/src/lib.rs index bbe286399..68ea4ae2e 100644 --- a/applications/tests/test_dag/src/lib.rs +++ b/applications/tests/test_dag/src/lib.rs @@ -10,7 +10,7 @@ use core::time::Duration; const LOG_ENABLE: bool = true; const SOURCE_EXECUTION_TIME_US: u64 = 100_000; -pub async fn run() -> Result<(), Vec> { +pub async fn run() { wait_microsec(1000000); let period = Duration::from_secs(1); @@ -101,9 +101,19 @@ pub async fn run() -> Result<(), Vec> { ) .await; - finish_create_dags(core::slice::from_ref(&dag)).await?; - if LOG_ENABLE { - log::info!("DAG created successfully"); + match finish_create_dags(core::slice::from_ref(&dag)).await { + Ok(_) => { + if LOG_ENABLE { + log::info!("DAG created successfully"); + } + } + Err(errors) => { + if LOG_ENABLE { + log::error!("DAG creation failed:"); + for error in errors { + log::error!("- {error}"); + } + } + } } - Ok(()) } diff --git a/awkernel_async_lib/src/dag.rs b/awkernel_async_lib/src/dag.rs index 8f251c3a6..cf588d13c 100644 --- a/awkernel_async_lib/src/dag.rs +++ b/awkernel_async_lib/src/dag.rs @@ -35,15 +35,14 @@ //! - **No Dangling Edges**: Every published topic must be subscribed to by another node, and every subscribed topic must have a publisher. //! - **Globally Unique Topics (Inter-DAG)**: A topic name must be unique across all active DAGs in the system. This prevents different data pipelines from unintentionally interfering with each other. //! -//! ## Estimated WCET and feasibility +//! ## 4. Estimated WCET and feasibility //! //! Registration methods accept an optional estimated WCET. An absent estimate is treated as zero -//! by DAG validation, which computes each node's estimated earliest start and latest finish and -//! rejects estimates whose longest dependency path exceeds the sink's relative deadline. +//! by DAG validation, which rejects estimates whose longest dependency path exceeds the sink's +//! relative deadline. //! //! WCET estimates are used for feasibility validation only. They do not change interval-tick job -//! release times or the existing GEDF deadline assignment: GEDF continues to use the job release -//! time and the sink's relative deadline. +//! release times or the DAG deadline assignment used by the EDF scheduler. //! //! # Example Usage //! @@ -64,14 +63,17 @@ mod visit; #[cfg(feature = "perf")] mod performance; -pub use crate::dag::graph::NodeIndex; use crate::{ dag::{ graph::{ algo::{connected_components, is_cyclic_directed}, direction::Direction, + NodeIndex, + }, + visit::{ + dfsvisit::{depth_first_search, DfsEvent}, + EdgeRef, IntoNodeReferences, NodeRef, }, - visit::{EdgeRef, IntoNodeReferences, NodeRef}, }, scheduler::SchedulerType, task::{DagInfo, State}, @@ -140,7 +142,11 @@ impl_tuple_size!(T1, T2, T3); pub enum DagError { NodeNotFound(u32, usize), MissingSinkDeadline(u32), - InfeasibleWcet(u32, usize), + InfeasibleWcet { + dag_id: u32, + critical_path: Option, + deadline: Duration, + }, NotWeaklyConnected(u32), ContainsCycle(u32), MissingPendingTasks(u32), @@ -163,8 +169,11 @@ impl core::fmt::Display for DagError { match self { DagError::NodeNotFound(dag_id, node_id) => write!(f, "DAG#{dag_id} Node#{node_id} not found"), DagError::MissingSinkDeadline(dag_id) => write!(f, "DAG#{dag_id} has no sink relative deadline"), - DagError::InfeasibleWcet(dag_id, node_id) => { - write!(f, "DAG#{dag_id} Node#{node_id}: estimated WCETs exceed the sink relative deadline") + DagError::InfeasibleWcet { dag_id, critical_path: Some(critical_path), deadline } => { + write!(f, "DAG#{dag_id}: estimated critical path {critical_path:?} exceeds sink relative deadline {deadline:?}") + } + DagError::InfeasibleWcet { dag_id, critical_path: None, deadline } => { + write!(f, "DAG#{dag_id}: estimated critical path exceeds Duration::MAX (sink relative deadline {deadline:?})") } DagError::NotWeaklyConnected(dag_id) => write!(f, "DAG#{dag_id} is not weakly connected"), DagError::ContainsCycle(dag_id) => write!(f, "DAG#{dag_id} contains a cycle"), @@ -211,41 +220,6 @@ pub(crate) struct JobInfo { pub(crate) absolute_deadline: u64, } -/// Timing estimates for a node, expressed as offsets from the DAG job's release. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct NodeTiming { - /// Estimated worst-case execution time. An absent estimate is treated as zero in the analysis. - pub estimated_wcet: Duration, - /// Earliest estimated start, computed from the node's predecessors during DAG validation. - pub estimated_earliest_start: Duration, - /// Latest estimated finish, computed from the node's successors during DAG validation. - pub estimated_latest_finish: Duration, - /// True if the node is on a critical path, that is, a longest path of the DAG by WCET. - /// Such a node has the least slack, which is `D` minus the length of that path. - pub is_critical: bool, -} - -impl NodeTiming { - /// Returns the earliest finish, or `None` if the sum cannot be represented. - pub fn estimated_earliest_finish(&self) -> Option { - self.estimated_earliest_start - .checked_add(self.estimated_wcet) - } - - /// Returns the latest start, or `None` if the WCET exceeds the latest finish. - pub fn estimated_latest_start(&self) -> Option { - self.estimated_latest_finish - .checked_sub(self.estimated_wcet) - } - - /// Returns the slack, or `None` if the earliest finish overflows or - /// exceeds the latest finish. - pub fn slack(&self) -> Option { - self.estimated_latest_finish - .checked_sub(self.estimated_earliest_finish()?) - } -} - impl DagGraph { #[inline] fn get_sink_relative_deadline(&self) -> Option { @@ -263,51 +237,6 @@ impl DagGraph { None => false, } } - - #[inline] - fn get_node_wcet(&self, node_idx: NodeIndex) -> Option { - self.node_weight(node_idx) - .map(|info| info.wcet.unwrap_or(Duration::ZERO)) - } - - /// Returns the nodes in topological order: every node comes after all its predecessors. - /// - /// Returns an error for a cycle or an inconsistent predecessor count. - fn topological_order(&self, dag_id: u32) -> Result, DagError> { - let mut in_degree: BTreeMap = self - .node_indices() - .map(|idx| { - ( - idx, - self.neighbors_directed(idx, Direction::Incoming).count(), - ) - }) - .collect(); - let mut ready: Vec = in_degree - .iter() - .filter(|(_, degree)| **degree == 0) - .map(|(idx, _)| *idx) - .collect(); - let mut order: Vec = Vec::with_capacity(in_degree.len()); - while let Some(idx) = ready.pop() { - order.push(idx); - for succ in self.neighbors_directed(idx, Direction::Outgoing) { - let degree = in_degree - .get_mut(&succ) - .ok_or(DagError::NodeNotFound(dag_id, succ.index()))?; - *degree = degree - .checked_sub(1) - .ok_or(DagError::ContainsCycle(dag_id))?; - if *degree == 0 { - ready.push(succ); - } - } - } - if order.len() != self.node_count() { - return Err(DagError::ContainsCycle(dag_id)); - } - Ok(order) - } } pub struct Dag { @@ -380,7 +309,6 @@ impl Dag { subscribe_topic_names: subscribe_topic_names.to_vec(), publish_topic_names: publish_topic_names.to_vec(), relative_deadline: None, - timing: NodeTiming::default(), wcet, num_finished: 0, deadline_job: None, @@ -783,7 +711,6 @@ struct NodeInfo { subscribe_topic_names: Vec>, publish_topic_names: Vec>, relative_deadline: Option, - timing: NodeTiming, wcet: Option, num_finished: u64, // Number of DAG jobs that this node finished. deadline_job: Option, // Job whose deadline the last wake of this node got. @@ -1039,113 +966,54 @@ fn validate_dag(dag: &Dag) -> Result<(), DagError> { Ok(()) } -/// Computes per-node earliest starts and latest finishes from declared WCETs and the sink -/// relative deadline. This runs during DAG setup, not in the scheduler or reactor execution -/// paths. Its work is bounded by the configured graph size and edge count. +/// Checks whether the longest declared WCET path fits within the sink's relative deadline. +/// This runs during DAG setup, not in the scheduler or reactor execution paths. /// -/// The forward pass is `ES(v) = max(ES(p) + C(p))` over predecessors. The backward pass is -/// `LF(v) = min(LF(s) - C(s))` over successors, with the sink's latest finish fixed at its -/// relative deadline. The computed values are committed to the graph only if every node is -/// feasible. +/// A forward pass computes `EF(v) = max(EF(p)) + C(v)` over predecessors, including the +/// sink's own WCET. fn compute_timing(dag: &Dag) -> Result<(), DagError> { let dag_id = dag.id; let mut node = MCSNode::new(); - let mut graph = dag.graph.lock(&mut node); + let graph = dag.graph.lock(&mut node); let sink_deadline = graph .get_sink_relative_deadline() .ok_or(DagError::MissingSinkDeadline(dag_id))?; - let order = graph.topological_order(dag_id)?; + let mut order = Vec::with_capacity(graph.node_count()); + depth_first_search(&*graph, graph.node_indices(), |event| match event { + DfsEvent::Finish(idx, _) => { + order.push(idx); + Ok(()) + } + DfsEvent::BackEdge(_, _) => Err(DagError::ContainsCycle(dag_id)), + _ => Ok(()), + })?; + let mut earliest_finish: Vec = graph + .node_references() + .map(|(_, info)| info.wcet.unwrap_or(Duration::ZERO)) + .collect(); - // Forward pass to compute per-node earliest start times. - let mut earliest_start: BTreeMap = BTreeMap::new(); - for &idx in &order { + let mut critical_path = Duration::ZERO; + for &idx in order.iter().rev() { let mut start = Duration::ZERO; for pred in graph.neighbors_directed(idx, Direction::Incoming) { - let pred_start = earliest_start - .get(&pred) - .copied() - .ok_or(DagError::NodeNotFound(dag_id, pred.index()))?; - let pred_wcet = graph - .get_node_wcet(pred) - .ok_or(DagError::NodeNotFound(dag_id, pred.index()))?; - let pred_finish = pred_start - .checked_add(pred_wcet) - .ok_or(DagError::InfeasibleWcet(dag_id, pred.index()))?; + let pred_finish = earliest_finish[pred.index()]; // Safe: pred is a valid index start = start.max(pred_finish); } - earliest_start.insert(idx, start); - } - - // Backward pass to compute per-node latest finish times. - let mut latest_finish: BTreeMap = BTreeMap::new(); - for &idx in order.iter().rev() { - let mut finish = sink_deadline; - let mut has_successor = false; - for succ in graph.neighbors_directed(idx, Direction::Outgoing) { - let succ_finish = latest_finish - .get(&succ) - .copied() - .ok_or(DagError::NodeNotFound(dag_id, succ.index()))?; - let succ_wcet = graph - .get_node_wcet(succ) - .ok_or(DagError::NodeNotFound(dag_id, succ.index()))?; - let succ_start = succ_finish - .checked_sub(succ_wcet) - .ok_or(DagError::InfeasibleWcet(dag_id, succ.index()))?; - finish = if has_successor { - finish.min(succ_start) - } else { - succ_start - }; - has_successor = true; - } - latest_finish.insert(idx, finish); - } - - // Check feasibility, and find the slack of every node. - let mut slacks: BTreeMap = BTreeMap::new(); - let mut timings: BTreeMap = BTreeMap::new(); - for &idx in &order { - let timing = NodeTiming { - estimated_wcet: graph - .get_node_wcet(idx) - .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?, - estimated_earliest_start: earliest_start - .get(&idx) - .copied() - .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?, - estimated_latest_finish: latest_finish - .get(&idx) - .copied() - .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?, - is_critical: false, - }; - let slack = timing - .slack() - .ok_or_else(|| DagError::InfeasibleWcet(dag_id, idx.index()))?; - slacks.insert(idx, slack); - timings.insert(idx, timing); - } - - // A node is critical if it has the least slack, which only the nodes on a longest path have. - let min_slack = slacks - .values() - .min() - .copied() - .ok_or(DagError::MissingSinkDeadline(dag_id))?; - - for (&idx, timing) in &mut timings { - let slack = slacks - .get(&idx) - .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?; - timing.is_critical = *slack == min_slack; - } - for (idx, timing) in timings { - let info = graph - .node_weight_mut(idx) - .ok_or(DagError::NodeNotFound(dag_id, idx.index()))?; - info.timing = timing; + let finish = &mut earliest_finish[idx.index()]; // Safe: idx is a valid index + *finish = start.checked_add(*finish).ok_or(DagError::InfeasibleWcet { + dag_id, + critical_path: None, + deadline: sink_deadline, + })?; + critical_path = critical_path.max(*finish); + } + if critical_path > sink_deadline { + return Err(DagError::InfeasibleWcet { + dag_id, + critical_path: Some(critical_path), + deadline: sink_deadline, + }); } Ok(()) @@ -1888,150 +1756,81 @@ mod tests { (dag, [source, a, b, sink]) } - fn timing_of(dag: &Dag, idx: NodeIndex) -> NodeTiming { - let mut node = MCSNode::new(); - let graph = dag.graph.lock(&mut node); - graph.node_weight(idx).unwrap().timing - } - #[test] - fn node_timing_helpers_return_derived_times_and_boundaries() { - let timing = NodeTiming { - estimated_wcet: Duration::from_millis(20), - estimated_earliest_start: Duration::from_millis(10), - estimated_latest_finish: Duration::from_millis(70), - is_critical: false, - }; - assert_eq!( - timing.estimated_earliest_finish(), - Some(Duration::from_millis(30)) - ); - assert_eq!( - timing.estimated_latest_start(), - Some(Duration::from_millis(50)) - ); - assert_eq!(timing.slack(), Some(Duration::from_millis(40))); - - for duration in [Duration::ZERO, Duration::MAX] { - let boundary = NodeTiming { - estimated_earliest_start: duration, - estimated_latest_finish: duration, - ..NodeTiming::default() - }; - assert_eq!(boundary.estimated_earliest_finish(), Some(duration)); - assert_eq!(boundary.estimated_latest_start(), Some(duration)); - assert_eq!(boundary.slack(), Some(Duration::ZERO)); - } - } - - #[test] - fn node_timing_helpers_propagate_overflow_and_underflow() { - let overflowing = NodeTiming { - estimated_wcet: Duration::from_nanos(1), - estimated_earliest_start: Duration::MAX, - estimated_latest_finish: Duration::MAX, - is_critical: false, - }; - assert_eq!(overflowing.estimated_earliest_finish(), None); - assert_eq!(overflowing.slack(), None); - - let uncomputed = NodeTiming { - estimated_wcet: Duration::from_nanos(1), - ..NodeTiming::default() - }; - assert_eq!(uncomputed.estimated_latest_start(), None); - assert_eq!(uncomputed.slack(), None); - - let infeasible = NodeTiming { - estimated_wcet: Duration::from_millis(10), - estimated_earliest_start: Duration::from_millis(20), - estimated_latest_finish: Duration::from_millis(25), - is_critical: false, - }; - assert_eq!( - infeasible.estimated_latest_start(), - Some(Duration::from_millis(15)) - ); - assert_eq!(infeasible.slack(), None); - } - - #[test] - fn chain_timing_uses_predecessor_and_successor_wcets() { - let (dag, [source, middle, sink]) = timing_chain([ + fn chain_wcets_below_deadline_are_feasible() { + let (dag, _) = timing_chain([ Some(Duration::from_millis(10)), Some(Duration::from_millis(20)), Some(Duration::from_millis(30)), ]); assert!(compute_timing(&dag).is_ok()); - assert_eq!( - timing_of(&dag, source), - NodeTiming { - estimated_wcet: Duration::from_millis(10), - estimated_earliest_start: Duration::ZERO, - estimated_latest_finish: Duration::from_millis(50), - is_critical: true, - } - ); - assert_eq!( - timing_of(&dag, middle), - NodeTiming { - estimated_wcet: Duration::from_millis(20), - estimated_earliest_start: Duration::from_millis(10), - estimated_latest_finish: Duration::from_millis(70), - is_critical: true, - } + } + + #[test] + fn timing_uses_node_indices_when_registration_order_is_reversed() { + let dag = create_dag(); + let source_topic: Cow<'static, str> = + alloc::format!("reverse_timing_{}_source", dag.id).into(); + let sink_topic: Cow<'static, str> = alloc::format!("reverse_timing_{}_sink", dag.id).into(); + let sink = dag.add_node_with_topic_edges( + core::slice::from_ref(&sink_topic), + &[], + Some(Duration::from_millis(30)), ); - assert_eq!( - timing_of(&dag, sink), - NodeTiming { - estimated_wcet: Duration::from_millis(30), - estimated_earliest_start: Duration::from_millis(30), - estimated_latest_finish: Duration::from_millis(100), - is_critical: true, - } + dag.add_node_with_topic_edges( + core::slice::from_ref(&source_topic), + core::slice::from_ref(&sink_topic), + Some(Duration::from_millis(20)), ); + dag.add_node_with_topic_edges(&[], &[source_topic], Some(Duration::from_millis(10))); + dag.set_relative_deadline(sink, Duration::from_millis(60)) + .unwrap(); + + compute_timing(&dag).unwrap(); + + dag.set_relative_deadline(sink, Duration::from_millis(59)) + .unwrap(); + assert!(matches!( + compute_timing(&dag), + Err(DagError::InfeasibleWcet { + dag_id: id, + critical_path: Some(path), + deadline, + }) if id == dag.id + && path == Duration::from_millis(60) + && deadline == Duration::from_millis(59) + )); } #[test] - fn branch_join_timing_uses_the_longest_predecessor_path() { - let (dag, [source, a, b, sink]) = timing_diamond([ + fn branch_join_feasibility_uses_the_longest_path_not_the_sum_of_branches() { + let (dag, [_, _, _, sink]) = timing_diamond([ Some(Duration::from_millis(10)), + Some(Duration::from_millis(60)), Some(Duration::from_millis(30)), - Some(Duration::from_millis(5)), Some(Duration::from_millis(20)), ]); + // The longest path is 90 ms, although the sum of all WCETs is 120 ms. assert!(compute_timing(&dag).is_ok()); - assert_eq!( - timing_of(&dag, sink).estimated_earliest_start, - Duration::from_millis(40) - ); - assert_eq!( - timing_of(&dag, a).estimated_latest_finish, - Duration::from_millis(80) - ); - assert_eq!( - timing_of(&dag, b).estimated_latest_finish, - Duration::from_millis(80) - ); - assert_eq!( - timing_of(&dag, source).estimated_latest_finish, - Duration::from_millis(50) - ); - for idx in [source, a, sink] { - let timing = timing_of(&dag, idx); - assert!(timing.is_critical); - assert_eq!(timing.slack(), Some(Duration::from_millis(40))); - } - let noncritical = timing_of(&dag, b); - assert!(!noncritical.is_critical); - assert_eq!(noncritical.slack(), Some(Duration::from_millis(65))); + dag.set_relative_deadline(sink, Duration::from_millis(89)) + .unwrap(); + assert!(matches!( + compute_timing(&dag), + Err(DagError::InfeasibleWcet { + dag_id: id, + critical_path: Some(path), + deadline, + }) if id == dag.id + && path == Duration::from_millis(90) + && deadline == Duration::from_millis(89) + )); } #[test] fn critical_path_equal_to_deadline_is_feasible() { - let (dag, [source, _middle, sink]) = timing_chain([ + let (dag, [_, _, sink]) = timing_chain([ Some(Duration::from_millis(10)), Some(Duration::from_millis(20)), Some(Duration::from_millis(30)), @@ -2040,69 +1839,159 @@ mod tests { .unwrap(); assert!(compute_timing(&dag).is_ok()); + } + + #[test] + fn chain_path_over_deadline_returns_infeasible_wcet() { + let (dag, _) = timing_chain([ + Some(Duration::from_millis(50)), + Some(Duration::from_millis(40)), + Some(Duration::from_millis(30)), + ]); + let error = compute_timing(&dag).unwrap_err(); + assert!(matches!( + error, + DagError::InfeasibleWcet{dag_id: id, critical_path: Some(path), deadline} + if id == dag.id + && path == Duration::from_millis(120) + && deadline == Duration::from_millis(100) + )); assert_eq!( - timing_of(&dag, source).estimated_latest_finish, - Duration::from_millis(10) + alloc::format!("{error}"), + alloc::format!( + "DAG#{}: estimated critical path 120ms exceeds sink relative deadline 100ms", + dag.id + ) ); } + #[test] + fn diamond_path_over_deadline_returns_infeasible_wcet() { + let (dag, _) = timing_diamond([ + Some(Duration::from_millis(50)), + Some(Duration::from_millis(40)), + Some(Duration::from_millis(5)), + Some(Duration::from_millis(30)), + ]); + // The long branch takes 120 ms, while the other branch fits in 85 ms. + assert!(matches!( + compute_timing(&dag), + Err(DagError::InfeasibleWcet{dag_id: id, critical_path: Some(path), deadline}) + if id == dag.id + && path == Duration::from_millis(120) + && deadline == Duration::from_millis(100) + )); + } + + #[test] + fn public_registration_validates_the_combined_wcet_of_all_reactor_types() { + use futures::FutureExt; + + let dag = create_dag(); + let source_topic: Cow<'static, str> = + alloc::format!("registered_timing_{}_source", dag.id).into(); + let sink_topic: Cow<'static, str> = + alloc::format!("registered_timing_{}_sink", dag.id).into(); + + async { + dag.register_periodic_reactor::<_, (u32,)>( + "timing_source".into(), + || (1,), + alloc::vec![source_topic.clone()], + SchedulerType::PrioritizedFIFO(0), + Duration::from_millis(100), + Some(Duration::from_millis(50)), + ) + .await; + dag.register_reactor::<_, (u32,), (u32,)>( + "timing_middle".into(), + |value| value, + alloc::vec![source_topic], + alloc::vec![sink_topic.clone()], + SchedulerType::PrioritizedFIFO(0), + Some(Duration::from_millis(40)), + ) + .await; + dag.register_sink_reactor::<_, (u32,)>( + "timing_sink".into(), + |_| {}, + alloc::vec![sink_topic], + SchedulerType::PrioritizedFIFO(0), + Duration::from_millis(100), + Some(Duration::from_millis(30)), + ) + .await; + } + .now_or_never() + .expect("registration must complete without spawning or waiting for reactors"); + + let result = validate_all_rules(core::slice::from_ref(&dag)); + remove_dag(dag.id); + + // Dropping any one registration's WCET would make this 120 ms chain feasible. + let errors = result.unwrap_err(); + assert!(matches!( + errors.as_slice(), + [DagError::InfeasibleWcet{dag_id: id, critical_path: Some(path), deadline}] + if *id == dag.id + && *path == Duration::from_millis(120) + && *deadline == Duration::from_millis(100) + )); + } + #[test] fn timing_overflow_returns_infeasible_wcet() { - let (dag, [_, middle, sink]) = + let (dag, [_, _, sink]) = timing_chain([Some(Duration::MAX), Some(Duration::from_nanos(1)), None]); dag.set_relative_deadline(sink, Duration::MAX).unwrap(); + let error = compute_timing(&dag).unwrap_err(); assert!(matches!( - compute_timing(&dag), - Err(DagError::InfeasibleWcet(id, index)) - if id == dag.id && index == middle.index() + error, + DagError::InfeasibleWcet{dag_id: id, critical_path: None, deadline: Duration::MAX} if id == dag.id )); + assert_eq!( + alloc::format!("{error}"), + alloc::format!( + "DAG#{}: estimated critical path exceeds Duration::MAX (sink relative deadline {:?})", + dag.id, + Duration::MAX + ) + ); } #[test] fn sink_wcet_over_deadline_returns_infeasible_wcet() { - let (dag, [_, _, sink]) = timing_chain([None, None, Some(Duration::from_millis(101))]); + let (dag, _) = timing_chain([None, None, Some(Duration::from_millis(101))]); assert!(matches!( compute_timing(&dag), - Err(DagError::InfeasibleWcet(id, index)) - if id == dag.id && index == sink.index() + Err(DagError::InfeasibleWcet{dag_id: id, critical_path: Some(path), deadline}) + if id == dag.id + && path == Duration::from_millis(101) + && deadline == Duration::from_millis(100) )); } #[test] - fn maximum_duration_critical_path_is_feasible() { - let (dag, [source, middle, sink]) = timing_chain([Some(Duration::MAX), None, None]); + fn sink_wcet_is_included_when_the_critical_path_overflows() { + let (dag, [_, _, sink]) = + timing_chain([Some(Duration::MAX), None, Some(Duration::from_nanos(1))]); dag.set_relative_deadline(sink, Duration::MAX).unwrap(); - compute_timing(&dag).unwrap(); - - for idx in [source, middle, sink] { - let timing = timing_of(&dag, idx); - assert!(timing.is_critical); - assert_eq!(timing.estimated_earliest_finish(), Some(Duration::MAX)); - assert_eq!(timing.slack(), Some(Duration::ZERO)); - } - } - #[test] - fn timing_rejects_a_partial_topological_order() { - let (dag, [source, middle, _]) = timing_chain([None; 3]); - { - let mut node = MCSNode::new(); - let mut graph = dag.graph.lock(&mut node); - graph.add_edge( - middle, - source, - EdgeInfo { - topic_name: "cycle".into(), - }, - ); - } assert!(matches!( compute_timing(&dag), - Err(DagError::ContainsCycle(id)) if id == dag.id + Err(DagError::InfeasibleWcet{dag_id: id, critical_path: None, deadline: Duration::MAX}) if id == dag.id )); } + #[test] + fn maximum_duration_critical_path_is_feasible() { + let (dag, [_, _, sink]) = timing_chain([Some(Duration::MAX), None, None]); + dag.set_relative_deadline(sink, Duration::MAX).unwrap(); + + assert!(compute_timing(&dag).is_ok()); + } + #[test] fn zero_wcets_fit_a_zero_relative_deadline() { let dag = create_dag(); @@ -2110,13 +1999,6 @@ mod tests { dag.set_relative_deadline(source, Duration::ZERO).unwrap(); assert!(compute_timing(&dag).is_ok()); - assert_eq!( - timing_of(&dag, source), - NodeTiming { - is_critical: true, - ..NodeTiming::default() - } - ); } #[test] @@ -2132,15 +2014,13 @@ mod tests { #[test] fn absent_and_zero_wcets_remain_distinct_but_analyze_as_zero() { - let dag = create_dag(); - let absent = dag.add_node_with_topic_edges(&[], &[], None); - let zero = dag.add_node_with_topic_edges(&[], &[], Some(Duration::ZERO)); + let (dag, [absent, zero, sink]) = timing_chain([None, Some(Duration::ZERO), None]); + dag.set_relative_deadline(sink, Duration::ZERO).unwrap(); + + compute_timing(&dag).unwrap(); let mut node = MCSNode::new(); let graph = dag.graph.lock(&mut node); - assert_eq!(graph.node_weight(absent).unwrap().wcet, None); assert_eq!(graph.node_weight(zero).unwrap().wcet, Some(Duration::ZERO)); - assert_eq!(graph.get_node_wcet(absent), Some(Duration::ZERO)); - assert_eq!(graph.get_node_wcet(zero), Some(Duration::ZERO)); } } diff --git a/userland/src/lib.rs b/userland/src/lib.rs index f45866dcf..e376f8ded 100644 --- a/userland/src/lib.rs +++ b/userland/src/lib.rs @@ -45,9 +45,7 @@ pub async fn run() -> Result<(), Cow<'static, str>> { test_measure_channel_heavy::run().await; // measure channel heavy #[cfg(feature = "test_dag")] - test_dag::run() - .await - .map_err(|errors| Cow::Owned(alloc::format!("DAG test failed: {errors:?}")))?; // test for DAG + test_dag::run().await; #[cfg(feature = "test_dvfs")] test_dvfs::run().await; // test for DVFS