Rust in Everything
基于 cu29-derive 1.3.1

编译期拓扑排序与执行计划生成

主线位置:编译期主线第 2 站。本页剖析 compute_runtime_plan 如何根据节点的出入边判定任务类型(Source / Regular / Sink),并生成确定性的 CuExecutionLoop。

从 CuGraph 到 CuExecutionLoop

在 core/cu29_runtime/src/curuntime.rs#L4627 中,执行计划由递归的 CuExecutionUnit 树构成:

// core/cu29_runtime/src/curuntime.rs#L4627-L4652
#[derive(Debug, Clone)]
pub struct CuExecutionStep {
  pub node_id: NodeId,
  pub node: Node,
  pub task_type: CuTaskType, // Source, Regular, Sink, BridgeRx, BridgeTx
  pub input_msg_indices_types: Vec<CuInputMsg>,
  pub output_msg_pack: Option<CuOutputPack>,
  pub phase: CuStepPhase,
}

#[derive(Debug, Clone)]
pub enum CuExecutionUnit {
  Step(CuExecutionStep),
  Loop(CuExecutionLoop),
}
flowchart TB
  g["CuGraph (StableDiGraph)"] --> role["find_task_type_for_id\n入度=0 -> Source\n出度=0 -> Sink\n有入有出 -> Regular"]
  role --> sort["assemble_runtime_plan_for_mission\nKahn 拓扑排序 + 确定性平局决胜"]
  sort --> idx["为每个有输出的步骤分配递增 culist_index (0, 1, 2...)"]
  idx --> codegen["cu29_derive 遍历 steps\n生成 tasks.N.process(&ctx, &msgs.i, &mut msgs.j)"]

槽位下标如何与上下游边精准缝合?

当 compute_runtime_plan 按拓扑顺序遍历节点时:

  1. 每遇到一个会产生输出消息的步骤(CuTaskType::Source、Regular 或 BridgeRx),就为它在 CopperList.msgs 元组中分配一个唯一的槽位下标 culist_index(记录在 CuOutputPack 中)。
  2. 当下游节点读取某条入边 Cnx 时,计划器查找该边源节点的 culist_index 与输出端口偏移,填入下游步骤的 input_msg_indices_types: Vec<CuInputMsg>。
  3. 在 core/cu29_derive/src/lib.rs 生成代码时,直接将 culist_index 转为 syn::Index(如 msgs.0、msgs.1),生成编译期静态借用表达式!
❗IMPORTANT

动脑筋:如果两个同层级的传感器节点 imu 和 baro 之间没有任何数据依赖,拓扑排序的顺序重要吗?如果每次编译顺序随机变化会导致什么后果?

动脑筋答案

极其重要!如果同层节点的拓扑顺序不固定,那么:① CopperList.msgs 元组中字段的排列顺序会发生变化,导致旧录制的 .copper 二进制日志无法反序列化;② 若两个节点共享底层 SPI 总线或随机数发生器,调用顺序变化会破坏确定性重放。因此 planner/schedule.rs 在拓扑排序入度为 0 的候选集中始终按确定的 NodeId 顺序选取,保证跨编译、跨平台的 100% 确定性调度序列。

小结

  • find_task_type_for_id 根据节点在图中的入度与出度自动推导 Source、Regular、Sink 角色。
  • compute_runtime_plan 在编译期完成拓扑排序与消息元组下标分配,运行期只需按固定顺序执行指令。

💬 关联讨论

加载中...