From cf4c82e773f17ce8a3aecf716850a132098cde51 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 05:11:51 +0900 Subject: [PATCH 01/42] feat(runtime)!: wait for clock edges in process kernels with fused ticks The timed scheduler resumed a process only after a delay, an event or a condition, one host round trip per edge. A Veryl testbench's `clk.next(n)` needs the fused tick loop the event-driven `Simulator` already has, or moving it to process kernels would cost two orders of magnitude. - `ProcessStatus::WaitClock`: a kernel waits for a number of rising edges of a process clock, named by a new clock slot among the clocks the process may wait on; the runtime schema lists them with their periods. `ProcessKernelBuilder::wait_clock` builds the wait. The native image container version becomes 12. - The scheduler generates a clock's edges from the first wait on it, in the order the Veryl testbench runner uses: rising edges due after the processes of the time have run, falling edges half a period later, and a process resumes one period after its last counted edge, before the edge that follows. When every live process waits on the one clock that is due and nothing else is pending, it runs the edges as fused ticks through `SimulationExecutor::tick_many` and advances time past them. `step_until` keeps such a run within `run_until`'s end. Snapshots and schedule parts carry the generated clocks and clock waits; `Simulation::ticks` counts the edges. - The SDK gains `Statement::ClockCycles` and `ModuleBuilder::clock_period`. A counter that one, two or four processes wait on now runs at about 515 million cycles per second on the native backend, against 401 million for the single-process testbench VM and 2.4 million for its multi-process path. --- crates/celox-design/src/lib.rs | 52 +- crates/celox-frontend-core/src/process.rs | 29 +- crates/celox-frontend-core/src/sdk.rs | 45 +- .../src/symbolic/assembly.rs | 2 +- crates/celox-frontend-sdk/src/lib.rs | 97 +++- crates/celox-frontend-sv/src/lowering.rs | 11 +- crates/celox-runtime/src/lib.rs | 3 +- crates/celox-runtime/src/simulation.rs | 459 +++++++++++++++++- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 166 ++++++- crates/celox/src/simulator/state_file.rs | 4 + crates/celox/tests/processes.rs | 198 ++++++++ docs/guide/external-frontends.md | 10 + docs/internals/architecture.md | 34 +- docs/ja/guide/external-frontends.md | 8 + 15 files changed, 1069 insertions(+), 51 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index b2cc7fc5590..e0b70d95395 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -225,6 +225,13 @@ pub enum ProcessStatus { /// It ran no statement, so no state other than its own wait bookkeeping /// changed. Pending, + /// Resume after the number of rising edges stored in + /// [`ProcessSlots::delay`] of the process clock whose index is stored in + /// [`ProcessSlots::clock`]. The runtime generates those edges: the clock + /// toggles every half period from the first wait on it, and the process + /// resumes one period after the last counted edge, before the edge that + /// follows. + WaitClock, } impl ProcessStatus { @@ -237,6 +244,7 @@ impl ProcessStatus { Self::Finish => 3, Self::Wait => 4, Self::Pending => 5, + Self::WaitClock => 6, } } @@ -247,23 +255,48 @@ impl ProcessStatus { 3 => Some(Self::Finish), 4 => Some(Self::Wait), 5 => Some(Self::Pending), + 6 => Some(Self::WaitClock), _ => None, } } } +/// A clock a process waits on with [`ProcessStatus::WaitClock`]: the clock +/// signal of a sequential domain, and the period of the edges the runtime +/// generates for it (at least two time units). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ProcessClock { + pub signal: A, + pub period: u64, +} + +impl ProcessClock { + pub fn map(self, map: impl FnOnce(A) -> B) -> ProcessClock { + ProcessClock { + signal: map(self.signal), + period: self.period, + } + } +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to /// find where it stopped; before returning it stores the next resume point, -/// a [`ProcessStatus`] code in `status` and, for a delay, the number of time -/// units in `delay`. All three are ordinary two-state state objects, so -/// checkpoints capture a suspended process. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +/// a [`ProcessStatus`] code in `status` and, for a delay or a clock wait, the +/// number of time units or edges in `delay`; a clock wait also stores the +/// index into `clocks` in `clock`. The slots are ordinary two-state state +/// objects, so checkpoints capture a suspended process. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { pub resume: A, pub status: A, pub delay: A, + pub clock: A, + /// The clocks the process may wait on, in the order its kernel numbers + /// them. + #[serde(default = "Vec::new")] + pub clocks: Vec>, } impl ProcessSlots { @@ -272,11 +305,18 @@ impl ProcessSlots { resume: map(self.resume), status: map(self.status), delay: map(self.delay), + clock: map(self.clock), + clocks: self + .clocks + .into_iter() + .map(|clock| clock.map(&mut map)) + .collect(), } } + /// The control slots, without the clock signals. pub fn iter(&self) -> impl Iterator { - [&self.resume, &self.status, &self.delay].into_iter() + [&self.resume, &self.status, &self.delay, &self.clock].into_iter() } } @@ -284,6 +324,8 @@ impl ProcessSlots { pub const PROCESS_STATUS_WIDTH: usize = 8; /// Width of [`ProcessSlots::delay`]. pub const PROCESS_DELAY_WIDTH: usize = 64; +/// Width of [`ProcessSlots::clock`]. +pub const PROCESS_CLOCK_WIDTH: usize = 32; /// Source-independent runtime diagnostics and observable event descriptions. #[derive(Clone, Debug)] diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 4cfcfb2608d..c1c2a5abc17 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -16,8 +16,8 @@ //! suspension methods where the source suspends. use celox_design::{ - PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, RegionedVarAddrBase, - STABLE_REGION, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, + RegionedVarAddrBase, STABLE_REGION, }; use celox_sir::{ BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRSwitchCase, @@ -43,6 +43,8 @@ pub const MAX_PROCESS_SUSPENSIONS: usize = (1 << PROCESS_RESUME_WIDTH) - 1; pub enum ProcessKernelError { #[error("a process has more than {MAX_PROCESS_SUSPENSIONS} suspension points")] TooManySuspensions, + #[error("a process waits on clock {0}, which its slots do not list")] + UnknownClock(u32), } /// Builder of one process kernel. @@ -117,6 +119,29 @@ impl ProcessKernelBuilder { Ok(()) } + /// Suspend until `count` rising edges of the process clock `clock` (an + /// index into the slots' clock list) have passed, and continue at a new + /// resume point one period after the last of them. `count` is an + /// unsigned two-state register of [`PROCESS_DELAY_WIDTH`] bits; a count + /// of zero continues at once. + pub fn wait_clock(&mut self, clock: u32, count: RegisterId) -> Result<(), ProcessKernelError> { + if clock as usize >= self.slots.clocks.len() { + return Err(ProcessKernelError::UnknownClock(clock)); + } + let point = self.resume_blocks.len(); + if point > MAX_PROCESS_SUSPENSIONS { + return Err(ProcessKernelError::TooManySuspensions); + } + self.store(self.slots.delay, PROCESS_DELAY_WIDTH, count); + self.store_constant(self.slots.clock, PROCESS_CLOCK_WIDTH, u64::from(clock)); + self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); + self.end(ProcessStatus::WaitClock); + let resume = self.builder.new_block(); + self.resume_blocks.push(resume); + self.builder.switch_to_block(resume); + Ok(()) + } + /// Suspend until a condition the kernel evaluates holds, and continue at /// a new resume point. The caller lowers the condition at that point /// and ends it with [`Self::wake_if`]; the runtime resumes the process diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index e5521189dfc..3f07238997f 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -2,8 +2,9 @@ use celox_design::{ BinaryOp, BitAccess, DomainKind, InitialStateData, InitialStateValue, ModuleId, - PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, - STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, VariableMetadata, WORKING_REGION, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessClock, + ProcessSlots, RegionedVarAddrBase, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, + VariableMetadata, WORKING_REGION, }; use celox_frontend_sdk::{ ActiveLevel, Direction, Edge, ExprId, ExprNode, FrontendArtifact, SignalId, SignalSlice, @@ -1034,6 +1035,7 @@ fn lower_registers( fn lower_statements( artifact: &FrontendArtifact, kernel: &mut ProcessKernelBuilder, + clocks: &[SignalId], statements: &[Statement], ) -> Result { for statement in statements { @@ -1075,7 +1077,7 @@ fn lower_statements( let mut join = None; for (block, body) in [(then_block, then_body), (else_block, else_body)] { kernel.builder().switch_to_block(block); - if lower_statements(artifact, kernel, body)? { + if lower_statements(artifact, kernel, clocks, body)? { let builder = kernel.builder(); let target = *join.get_or_insert_with(|| builder.new_block()); builder.seal_block(SIRTerminator::Jump(target, Vec::new())); @@ -1100,7 +1102,7 @@ fn lower_statements( false_block: (exit, Vec::new()), }); builder.switch_to_block(body_block); - if lower_statements(artifact, kernel, body)? { + if lower_statements(artifact, kernel, clocks, body)? { kernel .builder() .seal_block(SIRTerminator::Jump(header, Vec::new())); @@ -1112,7 +1114,7 @@ fn lower_statements( let header = builder.new_block(); builder.seal_block(SIRTerminator::Jump(header, Vec::new())); builder.switch_to_block(header); - if lower_statements(artifact, kernel, body)? { + if lower_statements(artifact, kernel, clocks, body)? { kernel .builder() .seal_block(SIRTerminator::Jump(header, Vec::new())); @@ -1129,6 +1131,20 @@ fn lower_statements( )?; kernel.delay(amount)?; } + Statement::ClockCycles { clock, count } => { + let index = clocks + .iter() + .position(|c| c == clock) + .ok_or(FrontendArtifactError::UnknownSignal(clock.index()))?; + let count = coerce_sir_expression( + artifact, + *count, + ValueType::bits(PROCESS_DELAY_WIDTH)?, + kernel.builder(), + &mut cache, + )?; + kernel.wait_clock(index as u32, count)?; + } Statement::Finish => { kernel.finish(); return Ok(false); @@ -1176,13 +1192,28 @@ fn lower_processes( .enumerate() .map(|(index, process)| { let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; + let mut clocks = Vec::new(); + celox_frontend_sdk::collect_process_clocks(process.body(), &mut clocks); let slots = ProcessSlots { resume: declare(name("resume"), PROCESS_RESUME_WIDTH), status: declare(name("status"), PROCESS_STATUS_WIDTH), delay: declare(name("delay"), PROCESS_DELAY_WIDTH), + clock: declare(name("clock"), PROCESS_CLOCK_WIDTH), + clocks: clocks + .iter() + .map(|clock| { + Ok(ProcessClock { + signal: source_id(*clock), + period: artifact + .clock_period(*clock) + .ok_or(FrontendArtifactError::UnknownSignal(clock.index()))? + .max(2), + }) + }) + .collect::, FrontendArtifactError>>()?, }; - let mut kernel = ProcessKernelBuilder::new(slots); - lower_statements(artifact, &mut kernel, process.body())?; + let mut kernel = ProcessKernelBuilder::new(slots.clone()); + lower_statements(artifact, &mut kernel, &clocks, process.body())?; Ok(SymbolicProcess { kernel: kernel.build(), slots, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index b9503847ce8..f3f3b2aaee6 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2032,7 +2032,7 @@ fn relocate_units( &runtime_event_site_map, &extern_function_map, ), - slots: process.slots.map(|var_id| AbsoluteAddr { + slots: process.slots.clone().map(|var_id| AbsoluteAddr { instance_id: *id, var_id, }), diff --git a/crates/celox-frontend-sdk/src/lib.rs b/crates/celox-frontend-sdk/src/lib.rs index 8b83123dc8d..62f729b2bb0 100644 --- a/crates/celox-frontend-sdk/src/lib.rs +++ b/crates/celox-frontend-sdk/src/lib.rs @@ -474,6 +474,13 @@ pub enum Statement { /// amount count as zero; a zero delay resumes at the same time, after /// the other processes and the registers their edges trigger. Delay { amount: ExprId }, + /// Suspend the process until `count` rising edges of `clock` have + /// passed. The runtime generates the edges of a clock from the first + /// wait on it, with the period set by [`ModuleBuilder::clock_period`], + /// and resumes the process one period after the last counted edge, + /// before the edge that follows. Unknown bits of the count count as + /// zero; a zero count continues at once. + ClockCycles { clock: SignalId, count: ExprId }, /// End the simulation. Finish, } @@ -509,6 +516,9 @@ pub struct FrontendArtifact { port_order: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] processes: Vec, + /// Periods of the clocks processes wait on, in time units. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + clock_periods: Vec<(SignalId, u64)>, } impl FrontendArtifact { @@ -906,6 +916,14 @@ impl FrontendArtifact { &self.processes } + /// The period of `clock` for [`Statement::ClockCycles`], if set. + pub fn clock_period(&self, clock: SignalId) -> Option { + self.clock_periods + .iter() + .find(|(signal, _)| *signal == clock) + .map(|(_, period)| *period) + } + fn validate_statements( &self, statements: &[Statement], @@ -955,6 +973,10 @@ pub enum BuildError { }, #[error("control signal `{name}` must be one bit wide")] InvalidControlWidth { name: String }, + #[error("a clock period must be at least two time units, not {period}")] + InvalidClockPeriod { period: u64 }, + #[error("clock `{name}` needs a period and a register it clocks before a process waits on it")] + UnknownProcessClock { name: String }, #[error("register target `{name}` must cover the complete signal")] PartialRegisterTarget { name: String }, #[error("module name must not be empty")] @@ -1014,6 +1036,7 @@ pub struct ModuleBuilder { driver_ranges: FxHashMap>, port_order: Vec, processes: Vec, + clock_periods: Vec<(SignalId, u64)>, } impl ModuleBuilder { @@ -1033,6 +1056,7 @@ impl ModuleBuilder { driver_ranges: FxHashMap::default(), port_order: Vec::new(), processes: Vec::new(), + clock_periods: Vec::new(), }) } @@ -1366,6 +1390,23 @@ impl ModuleBuilder { &|expression| self.expressions.get(expression.index() as usize), &self.driver_ranges, )?; + let mut clocks = Vec::new(); + collect_process_clocks(&body, &mut clocks); + for clock in clocks { + let known = self + .clock_periods + .iter() + .any(|(signal, _)| *signal == clock) + && self + .registers + .iter() + .any(|register| register.clock == clock); + if !known { + return Err(BuildError::UnknownProcessClock { + name: self.signal_info(clock)?.name.clone(), + }); + } + } self.processes.push(Process { body }); Ok(()) } @@ -1384,9 +1425,31 @@ impl ModuleBuilder { registers: self.registers, port_order: self.port_order, processes: self.processes, + clock_periods: self.clock_periods, } } + /// Set the period, in time units, of the edges the runtime generates + /// for `clock` when a process waits on it with + /// [`Statement::ClockCycles`]. The clock must clock a register, and + /// the period is at least two. + pub fn clock_period(&mut self, clock: SignalId, period: u64) -> Result<(), BuildError> { + let signal = self.signal_info(clock)?; + if signal.value_type.width() != 1 { + return Err(BuildError::InvalidControlWidth { + name: signal.name.clone(), + }); + } + if period < 2 { + return Err(BuildError::InvalidClockPeriod { period }); + } + match self.clock_periods.iter_mut().find(|(s, _)| *s == clock) { + Some(entry) => entry.1 = period, + None => self.clock_periods.push((clock, period)), + } + Ok(()) + } + fn signal_info(&self, signal: SignalId) -> Result<&Signal, BuildError> { self.signals .get(signal.index() as usize) @@ -1473,7 +1536,32 @@ fn collect_process_targets(statements: &[Statement], targets: &mut Vec { collect_process_targets(body, targets); } - Statement::Delay { .. } | Statement::Finish => {} + Statement::Delay { .. } | Statement::ClockCycles { .. } | Statement::Finish => {} + } + } +} + +/// The clocks the statements wait on, in order of first use. +pub fn collect_process_clocks(statements: &[Statement], clocks: &mut Vec) { + for statement in statements { + match statement { + Statement::ClockCycles { clock, .. } => { + if !clocks.contains(clock) { + clocks.push(*clock); + } + } + Statement::If { + then_body, + else_body, + .. + } => { + collect_process_clocks(then_body, clocks); + collect_process_clocks(else_body, clocks); + } + Statement::While { body, .. } | Statement::Forever { body } => { + collect_process_clocks(body, clocks); + } + Statement::Assign { .. } | Statement::Delay { .. } | Statement::Finish => {} } } } @@ -1552,6 +1640,13 @@ fn validate_statements<'a>( return Err(BuildError::DelayTooWide { width }); } } + Statement::ClockCycles { clock, count } => { + signal(*clock).ok_or(BuildError::UnknownSignal(clock.index()))?; + let width = expression_type(*count)?.width(); + if width > MAX_DELAY_WIDTH { + return Err(BuildError::DelayTooWide { width }); + } + } Statement::Finish => {} } } diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index e62e660381a..7d0d21a204d 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -11,9 +11,10 @@ use std::path::Path; use celox_design::{ BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType, - InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, - PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind, - RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, + InitialStateData, InitialStateValue, ModuleId, PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, + PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, + RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, + WORKING_REGION, }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ @@ -2008,6 +2009,8 @@ fn lower_initial_processes( resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), + clock: declare("clock", PROCESS_CLOCK_WIDTH), + clocks: Vec::new(), } }) .collect(); @@ -2030,7 +2033,7 @@ fn lower_initial_processes( .zip(slots) .map(|(process, slots)| { Ok(SymbolicProcess { - kernel: ff::Ff::new(&mut pm).lower_initial_kernel(process.body(), slots)?, + kernel: ff::Ff::new(&mut pm).lower_initial_kernel(process.body(), slots.clone())?, slots, }) }) diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 1267eac3de6..b2971573734 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -18,7 +18,8 @@ pub use reflection::{ SignalDirection, }; pub use simulation::{ - EventInfo, ProcessRefs, ScheduleParts, SimulationExecutor, SimulationSnapshot, SimulationState, + EventInfo, ProcessClockRef, ProcessClockState, ProcessRefs, ScheduleParts, SimulationExecutor, + SimulationSnapshot, SimulationState, }; pub use state_file::{ ScheduleRecord, ScheduledEvent, StateDifference, StateFile, StateFileError, StateObject, diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index f4741ce84f4..efda830f536 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1,6 +1,6 @@ use std::{ cmp::Reverse, - collections::{BTreeSet, BinaryHeap}, + collections::{BTreeMap, BTreeSet, BinaryHeap}, }; use bit_set::BitSet; @@ -39,6 +39,30 @@ pub trait SimulationExecutor { self.backend_mut().run_process(index) } + /// Run up to `count` rising edges of `event` as fused ticks: each one + /// evaluates the combinational logic and then the sequential domain, + /// without toggling the clock signal. Returns how many completed before + /// a runtime event or an error forced a return to the host. + fn tick_many( + &mut self, + event: ::Event, + count: u64, + ) -> (u64, Result<(), SimulatorErrorCode>) { + if count == 0 { + return (0, Ok(())); + } + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } + (1, self.eval_apply_ff_at(event)) + } + + /// Whether clock waits may be served by fused ticks, which skip the + /// clock signal's own edges and the host's per-edge hooks. + fn fused_ticks_allowed(&self) -> bool { + true + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( @@ -63,11 +87,85 @@ pub trait SimulationExecutor { fn finish_timed_step(&mut self, _timestamp: u64) {} } +/// A clock a process may wait on, resolved to the backend. +#[derive(Debug)] +pub struct ProcessClockRef { + pub event: B::Event, + pub signal: SignalRef, + pub period: u64, +} + +impl Clone for ProcessClockRef { + fn clone(&self) -> Self { + Self { + event: self.event, + signal: self.signal, + period: self.period, + } + } +} + /// Control slots of one process kernel, resolved to signals of the backend. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ProcessRefs { +#[derive(Debug)] +pub struct ProcessRefs { pub status: SignalRef, pub delay: SignalRef, + pub clock: SignalRef, + pub clocks: Vec>, +} + +impl Clone for ProcessRefs { + fn clone(&self) -> Self { + Self { + status: self.status, + delay: self.delay, + clock: self.clock, + clocks: self.clocks.clone(), + } + } +} + +/// A process clock some process has waited on: the runtime generates its +/// edges from then on. A rising edge is due at `next_edge` while a process +/// waits; the falling edge of the last rising edge that was applied to the +/// signal is pending at `falling_edge`. +#[derive(Debug)] +struct TickClock { + event: B::Event, + signal: SignalRef, + period: u64, + next_edge: u64, + falling_edge: Option, +} + +impl Clone for TickClock { + fn clone(&self) -> Self { + Self { + event: self.event, + signal: self.signal, + period: self.period, + next_edge: self.next_edge, + falling_edge: self.falling_edge, + } + } +} + +/// A process waiting for `remaining` more rising edges of the process clock +/// with event id `clock`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct ClockWait { + clock: usize, + remaining: u64, +} + +/// The state of one process clock, for schedules expressed by name. +#[derive(Debug)] +pub struct ProcessClockState { + pub event: B::Event, + pub signal: SignalRef, + pub period: u64, + pub next_edge: u64, + pub falling_edge: Option, } /// A process waiting for simulation time to reach `time`. Ordered so that a @@ -134,11 +232,19 @@ pub struct SimulationState { domain_kinds: Vec>, event_info: Vec>, signal_to_id: FxHashMap, - processes: Vec, + processes: Vec>, process_wakeups: BinaryHeap, /// Processes suspended at an event or level wait, which their kernels /// re-check whenever the state may have changed. waiting: BTreeSet, + /// Process clocks that have been waited on, by event id. + tick_clocks: BTreeMap>, + /// Processes waiting for rising edges of a process clock. + clock_waits: BTreeMap, + /// Processes that ran to their end. + done: BTreeSet, + /// Rising edges of process clocks so far. + ticks: u64, /// A process requested the end of the simulation. finished: bool, } @@ -188,7 +294,7 @@ impl SimulationState { topo_signals: Vec<(SignalRef, usize, usize)>, domain_kinds: Vec>, event_info: Vec>, - processes: Vec, + processes: Vec>, ) -> Self { let mut last_clock_values = BitSet::with_capacity(backend.num_events()); let mut signal_to_id = FxHashMap::default(); @@ -216,10 +322,23 @@ impl SimulationState { .collect(), processes, waiting: BTreeSet::new(), + tick_clocks: BTreeMap::new(), + clock_waits: BTreeMap::new(), + done: BTreeSet::new(), + ticks: 0, finished: false, } } + /// Rising edges of process clocks the simulation has run so far. + pub fn ticks(&self) -> u64 { + self.ticks + } + + fn clock_has_waiters(&self, clock: usize) -> bool { + self.clock_waits.values().any(|wait| wait.clock == clock) + } + pub fn add_clock( &mut self, event: B::Event, @@ -258,13 +377,26 @@ impl SimulationState { } pub fn step(&mut self, executor: &mut E) -> Result, SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.step_until(executor, u64::MAX) + } + + /// [`Self::step`], where a run of fused clock ticks stops before + /// `limit`: the time the step reaches is at most `limit`. + pub fn step_until( + &mut self, + executor: &mut E, + limit: u64, + ) -> Result, SimulatorErrorCode> where E: SimulationExecutor, { let Some(current_time) = self.next_event_time() else { return Ok(None); }; - let events_to_process = if self.scheduler.next_event_time() == Some(current_time) { + let mut events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() .map(|(_, events)| events) @@ -272,38 +404,191 @@ impl SimulationState { } else { Vec::new() }; + for clock in self.tick_clocks.values_mut() { + if clock.falling_edge == Some(current_time) { + clock.falling_edge = None; + events_to_process.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 0, + }); + } + } let ready = self.take_ready_processes(current_time); self.step_round(executor, current_time, events_to_process, ready, true)?; - self.run_remaining_rounds(executor, current_time)?; - executor.finish_timed_step(current_time); + self.run_remaining_rounds(executor, current_time, limit)?; + executor.finish_timed_step(self.scheduler.time); Ok(Some(current_time)) } - /// Run the further rounds of `current_time`: a process that waited for - /// zero time resumes in a later round, after the previous round's edges - /// have been handled, and the settled state may wake a process waiting - /// for an event or a condition. A round in which no process ran changes - /// nothing and ends the time. + /// Run the further rounds of `current_time`: the rising edges of the + /// process clocks that are due once the processes have run; a process + /// that waited for zero time resumes in a later round, after the + /// previous round's edges have been handled; and the settled state may + /// wake a process waiting for an event or a condition. A round in which + /// no process ran changes nothing and ends the time. When every live + /// process waits on the one clock that is due and nothing else is + /// pending, its edges run as fused ticks up to `limit` instead. fn run_remaining_rounds( &mut self, executor: &mut E, current_time: u64, + limit: u64, ) -> Result<(), SimulatorErrorCode> where E: SimulationExecutor, { while !self.finished { + let due: Vec = self + .tick_clocks + .iter() + .filter(|(id, clock)| { + clock.next_edge == current_time && self.clock_has_waiters(**id) + }) + .map(|(id, _)| *id) + .collect(); + if let [clock] = due[..] + && self.fused_ticks(executor, clock, current_time, limit)? + { + // Time moved on; the processes that resume run in the next step. + return Ok(()); + } + let fired = !due.is_empty(); + if fired { + self.fire_edges(executor, current_time, &due)?; + } let ready = self.take_ready_processes(current_time); if ready.is_empty() && self.waiting.is_empty() { + if fired { + // The edges may have released waits that resume now. + continue; + } break; } - if !self.step_round(executor, current_time, Vec::new(), ready, false)? { + if !self.step_round(executor, current_time, Vec::new(), ready, false)? && !fired { break; } } Ok(()) } + /// Apply the rising edges of the process clocks `due` at `time`, count + /// them against the processes waiting on them, and schedule the + /// resumptions and falling edges. + fn fire_edges( + &mut self, + executor: &mut E, + time: u64, + due: &[usize], + ) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + let events = due + .iter() + .map(|id| { + let clock = &self.tick_clocks[id]; + SimEvent { + time, + event_ref: clock.event, + signal: clock.signal, + next_val: 1, + } + }) + .collect(); + self.step_round(executor, time, events, Vec::new(), true)?; + for id in due { + self.ticks += 1; + let clock = self.tick_clocks.get_mut(id).expect("a due process clock"); + clock.next_edge = time + clock.period; + clock.falling_edge = Some(time + clock.period - clock.period / 2); + let resume_at = clock.next_edge; + self.count_edges(*id, 1, resume_at); + } + Ok(()) + } + + /// Credit `edges` rising edges of `clock` to the processes waiting on + /// it; those whose wait is over resume at `resume_at`. + fn count_edges(&mut self, clock: usize, edges: u64, resume_at: u64) { + let released: Vec = self + .clock_waits + .iter_mut() + .filter(|(_, wait)| wait.clock == clock) + .filter_map(|(process, wait)| { + wait.remaining = wait.remaining.saturating_sub(edges); + (wait.remaining == 0).then_some(*process) + }) + .collect(); + for process in released { + self.clock_waits.remove(&process); + self.process_wakeups.push(Reverse((resume_at, process))); + } + } + + /// When every live process waits on `clock`, no other event or + /// resumption is pending, and the host allows it, run the edges every + /// process waits for as fused ticks, as many as the first resumption + /// needs and `limit` permits. Returns whether that happened. + fn fused_ticks( + &mut self, + executor: &mut E, + clock: usize, + time: u64, + limit: u64, + ) -> Result + where + E: SimulationExecutor, + { + if !executor.fused_ticks_allowed() + || !self.waiting.is_empty() + || !self.process_wakeups.is_empty() + || self.scheduler.next_event_time().is_some() + || self + .tick_clocks + .values() + .any(|clock| clock.falling_edge.is_some()) + || self.clock_waits.values().any(|wait| wait.clock != clock) + || self.clock_waits.len() + self.done.len() != self.processes.len() + { + return Ok(false); + } + let Some(needed) = self.clock_waits.values().map(|wait| wait.remaining).min() else { + return Ok(false); + }; + let (event, period) = { + let clock = &self.tick_clocks[&clock]; + (clock.event, clock.period) + }; + // Edges at `time`, `time + period`, ...: the last one stays at or + // before `limit`. + let count = needed.min(limit.saturating_sub(time) / period + 1); + if count == 0 { + return Ok(false); + } + let (completed, result) = executor.tick_many(event, count); + result?; + if completed == 0 || completed > count { + return Err(SimulatorErrorCode::Runtime { + message: "the backend made invalid progress on fused clock ticks".into(), + signals: Vec::new(), + }); + } + self.ticks += completed; + let next_edge = time + completed * period; + self.tick_clocks + .get_mut(&clock) + .expect("a due process clock") + .next_edge = next_edge; + self.count_edges(clock, completed, next_edge); + // The processes that resume read the state settled after the last + // edge. + executor.eval_comb()?; + self.scheduler.time = time + (completed - 1) * period; + Ok(true) + } + /// Resume the processes waiting for an event or a condition at the /// current time, for state that was changed from outside the scheduler, /// and settle what they drive. Nothing happens when none wakes. @@ -316,7 +601,7 @@ impl SimulationState { } let time = self.scheduler.time; if self.step_round(executor, time, Vec::new(), Vec::new(), false)? { - self.run_remaining_rounds(executor, time)?; + self.run_remaining_rounds(executor, time, u64::MAX)?; executor.finish_timed_step(time); } Ok(()) @@ -352,8 +637,10 @@ impl SimulationState { { let mut progressed = false; let mut pass = ready; + let mut again = Vec::new(); loop { pass.extend(self.waiting.iter().copied()); + pass.append(&mut again); pass.sort_unstable(); pass.dedup(); if pass.is_empty() { @@ -362,7 +649,7 @@ impl SimulationState { let mut any_ran = false; for process in pass.drain(..) { executor.run_process(process)?; - let refs = self.processes[process]; + let refs = &self.processes[process]; let status: u8 = executor.backend().get_as(refs.status); match ProcessStatus::from_code(status) { Some(ProcessStatus::Delay) => { @@ -381,10 +668,12 @@ impl SimulationState { } Some(ProcessStatus::Done) => { self.waiting.remove(&process); + self.done.insert(process); any_ran = true; } Some(ProcessStatus::Finish) => { self.waiting.remove(&process); + self.done.insert(process); self.finished = true; return Ok(true); } @@ -392,6 +681,38 @@ impl SimulationState { self.waiting.insert(process); any_ran = true; } + Some(ProcessStatus::WaitClock) => { + let count: u64 = executor.backend().get_as(refs.delay); + let index: u32 = executor.backend().get_as(refs.clock); + let Some(clock) = refs.clocks.get(index as usize) else { + return Err(SimulatorErrorCode::InternalError); + }; + self.waiting.remove(&process); + if count == 0 { + // Nothing to wait for: the process continues in + // the next pass. + again.push(process); + } else { + let id = clock.event.id(); + let tick_clock = + self.tick_clocks.entry(id).or_insert_with(|| TickClock { + event: clock.event, + signal: clock.signal, + period: clock.period.max(2), + next_edge: current_time, + falling_edge: None, + }); + tick_clock.next_edge = tick_clock.next_edge.max(current_time); + self.clock_waits.insert( + process, + ClockWait { + clock: id, + remaining: count, + }, + ); + } + any_ran = true; + } // The kernel found its wait condition unmet and ran // nothing; it stays waiting. Some(ProcessStatus::Pending) => {} @@ -688,10 +1009,21 @@ impl SimulationState { return None; } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); - match (self.scheduler.next_event_time(), process) { - (Some(event), Some(process)) => Some(event.min(process)), - (event, process) => event.or(process), - } + let clocks = self + .tick_clocks + .iter() + .flat_map(|(id, clock)| { + [ + self.clock_has_waiters(*id).then_some(clock.next_edge), + clock.falling_edge, + ] + }) + .flatten() + .min(); + [self.scheduler.next_event_time(), process, clocks] + .into_iter() + .flatten() + .min() } /// Periodic clocks as (event id, period). @@ -715,6 +1047,10 @@ impl SimulationState { last_clock_values: self.last_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), + tick_clocks: self.tick_clocks.clone(), + clock_waits: self.clock_waits.clone(), + done: self.done.clone(), + ticks: self.ticks, finished: self.finished, } } @@ -747,8 +1083,25 @@ impl SimulationState { self.periodic_events.clone_from(&snapshot.periodic_events); self.last_clock_values .clone_from(&snapshot.last_clock_values); + let tick_clocks = snapshot + .tick_clocks + .iter() + .map(|(id, clock)| { + Ok(( + *id, + TickClock { + event: remap(clock.event).ok_or(clock.event)?, + ..clock.clone() + }, + )) + }) + .collect::>()?; self.process_wakeups.clone_from(&snapshot.process_wakeups); self.waiting.clone_from(&snapshot.waiting); + self.tick_clocks = tick_clocks; + self.clock_waits.clone_from(&snapshot.clock_waits); + self.done.clone_from(&snapshot.done); + self.ticks = snapshot.ticks; self.finished = snapshot.finished; Ok(()) } @@ -771,6 +1124,15 @@ pub struct ScheduleParts { pub process_wakeups: Vec<(usize, u64)>, /// Processes waiting for an event or a condition, in ascending order. pub waiting_processes: Vec, + /// Process clocks that have been waited on. + pub process_clocks: Vec>, + /// Processes waiting for edges of a process clock: the process, the + /// clock's event, and the edges still to wait for. + pub clock_waits: Vec<(usize, B::Event, u64)>, + /// Processes that ran to their end, in ascending order. + pub done_processes: Vec, + /// Rising edges of process clocks so far. + pub ticks: u64, /// A process requested the end of the simulation. pub finished: bool, } @@ -815,6 +1177,24 @@ impl SimulationState { wakeups }, waiting_processes: self.waiting.iter().copied().collect(), + process_clocks: self + .tick_clocks + .values() + .map(|clock| ProcessClockState { + event: clock.event, + signal: clock.signal, + period: clock.period, + next_edge: clock.next_edge, + falling_edge: clock.falling_edge, + }) + .collect(), + clock_waits: self + .clock_waits + .iter() + .map(|(process, wait)| (*process, events[wait.clock], wait.remaining)) + .collect(), + done_processes: self.done.iter().copied().collect(), + ticks: self.ticks, finished: self.finished, } } @@ -847,6 +1227,37 @@ impl SimulationState { .map(|(process, time)| Reverse((time, process))) .collect(); self.waiting = parts.waiting_processes.into_iter().collect(); + self.tick_clocks = parts + .process_clocks + .into_iter() + .map(|clock| { + ( + clock.event.id(), + TickClock { + event: clock.event, + signal: clock.signal, + period: clock.period, + next_edge: clock.next_edge, + falling_edge: clock.falling_edge, + }, + ) + }) + .collect(); + self.clock_waits = parts + .clock_waits + .into_iter() + .map(|(process, event, remaining)| { + ( + process, + ClockWait { + clock: event.id(), + remaining, + }, + ) + }) + .collect(); + self.done = parts.done_processes.into_iter().collect(); + self.ticks = parts.ticks; self.finished = parts.finished; } } @@ -860,6 +1271,10 @@ pub struct SimulationSnapshot { last_clock_values: BitSet, process_wakeups: BinaryHeap, waiting: BTreeSet, + tick_clocks: BTreeMap>, + clock_waits: BTreeMap, + done: BTreeSet, + ticks: u64, finished: bool, } @@ -873,6 +1288,10 @@ impl Clone for SimulationSnapshot { last_clock_values: self.last_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), + tick_clocks: self.tick_clocks.clone(), + clock_waits: self.clock_waits.clone(), + done: self.done.clone(), + ticks: self.ticks, finished: self.finished, } } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 00b887d472e..460d48c31b1 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 11; +const CONTAINER_VERSION: u16 = 12; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 918ccfb00dd..e6b810d7a80 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -98,6 +98,28 @@ impl SimulationExecutor for Simulator { .map_err(|e| self.decorate_runtime_error(e)) } + fn tick_many(&mut self, event: B::Event, count: u64) -> (u64, Result<(), RuntimeErrorCode>) { + if count == 0 { + return (0, Ok(())); + } + if !self.program.runtime_schema.comb_observers.is_empty() { + return (1, self.tick_deferred_comb(event)); + } + // Every tick settles the combinational logic first, so a clean + // state needs no special case and the whole run stays in the + // backend's loop. + let (completed, result) = self.backend.eval_comb_apply_ff_many_at(event, count); + self.dirty = true; + ( + completed, + result.map_err(|error| self.decorate_runtime_error(error)), + ) + } + + fn fused_ticks_allowed(&self) -> bool { + !self.components.has_scheduled_components() + } + fn stage_external_event( &mut self, event: B::Event, @@ -248,6 +270,19 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul .map(|slots| ProcessRefs { status: simulator.backend.resolve_signal(&slots.status), delay: simulator.backend.resolve_signal(&slots.delay), + clock: simulator.backend.resolve_signal(&slots.clock), + clocks: slots + .clocks + .iter() + .map(|clock| celox_runtime::ProcessClockRef { + event: simulator + .backend + .resolve_event_opt(&clock.signal) + .expect("a process clock is the clock of a sequential domain"), + signal: simulator.backend.resolve_signal(&clock.signal), + period: clock.period, + }) + .collect(), }) .collect(); @@ -431,7 +466,7 @@ impl Simulation { if next_time > end_time { break; } - self.state.step(&mut self.simulator)?; + self.state.step_until(&mut self.simulator, end_time)?; } if self.state.is_finished() { return Ok(()); @@ -457,6 +492,12 @@ impl Simulation { self.state.time() } + /// Rising edges of the clocks processes wait on that the simulation has + /// run so far. + pub fn ticks(&self) -> u64 { + self.state.ticks() + } + /// Periodic clocks registered with [`Self::add_clock`] (or loaded with a /// state), as (event id, period). pub fn clock_periods(&self) -> Vec<(usize, u64)> { @@ -858,3 +899,126 @@ mod wait_tests { check_all_backends(true); } } + +/// Clock waits of processes on every backend: fused where the backend +/// loops in generated code, one tick per call elsewhere. +#[cfg(all(test, feature = "host-runtime"))] +mod clock_wait_tests { + use celox_frontend_sdk::{ + BinaryOp, Constant, Edge, FrontendArtifact, ModuleBuilder, Statement, ValueType, + }; + + use super::Simulation; + use crate::{SimBackend, Simulator, SimulatorBuilder}; + + /// A counter clocked by a process clock; one process waits 1000 edges + /// and records the count, another waits 400 and then 5 more. + fn design(four_state: bool) -> FrontendArtifact { + let bit = ValueType::new(1, false, four_state).unwrap(); + let word = ValueType::new(16, false, four_state).unwrap(); + let mut module = ModuleBuilder::new("ClockWaits").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let count = module.output("count", word).unwrap(); + let late = module.output("late", word).unwrap(); + let early = module.output("early", word).unwrap(); + for signal in [count, late, early] { + module + .set_initial(signal, Constant::two_state(0u8, 16).unwrap()) + .unwrap(); + } + let count_expr = module.read(count).unwrap(); + let one = module.constant(Constant::two_state(1u8, 16).unwrap()); + let next = module.binary(BinaryOp::Add, count_expr, one, word).unwrap(); + let count_target = module.whole(count).unwrap(); + module + .register(count_target, next, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let constant = |module: &mut ModuleBuilder, value: u64| { + module.constant(Constant::two_state(value, 64).unwrap()) + }; + let thousand = constant(&mut module, 1000); + let late_target = module.whole(late).unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: thousand, + }, + Statement::Assign { + target: late_target, + value: count_expr, + }, + Statement::Finish, + ]) + .unwrap(); + let four_hundred = constant(&mut module, 400); + let five = constant(&mut module, 5); + let early_target = module.whole(early).unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: four_hundred, + }, + Statement::Assign { + target: early_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: five, + }, + ]) + .unwrap(); + module.finish() + } + + fn check(mut sim: Simulation) { + let count = sim.signal("count"); + let early = sim.signal("early"); + let late = sim.signal("late"); + sim.run_until(1601).unwrap(); + assert_eq!(sim.get(early), 400u16.into()); + assert_eq!(sim.get(count), 401u16.into()); + assert_eq!(sim.ticks(), 401); + sim.run_until(u64::MAX - 1).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 4000); + assert_eq!(sim.get(late), 1000u16.into()); + assert_eq!(sim.get(count), 1000u16.into()); + assert_eq!(sim.ticks(), 1000); + } + + fn builder(four_state: bool) -> SimulatorBuilder<'static, Simulator> { + Simulator::from_frontend(design(four_state)) + .four_state(four_state) + .emit_triggers() + } + + fn check_all_backends(four_state: bool) { + check(Simulation::new( + builder(four_state).build_interpreter().unwrap(), + )); + check(Simulation::new( + builder(four_state).build_cranelift().unwrap(), + )); + check(Simulation::new(builder(four_state).build_wasm().unwrap())); + check(Simulation::new(builder(four_state).build_tiered().unwrap())); + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + check(Simulation::new(builder(four_state).build_native().unwrap())); + } + + #[test] + fn clock_waits_run_on_every_backend() { + check_all_backends(false); + } + + #[test] + fn four_state_clock_waits_run_on_every_backend() { + check_all_backends(true); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index cd1213f77b2..46e20faa727 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -443,6 +443,10 @@ impl Simulator { // State files are rejected for designs with processes. process_wakeups: Vec::new(), waiting_processes: Vec::new(), + process_clocks: Vec::new(), + clock_waits: Vec::new(), + done_processes: Vec::new(), + ticks: 0, finished: false, }) } diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 8cf5452eb97..28af2c48568 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -622,3 +622,201 @@ fn zero_delay_pulse_triggers_registers() { assert_eq!(sim.get(clk), 1u8.into()); assert_eq!(sim.next_event_time(), None); } + +/// A counter clocked by `clk`, which only processes drive: the runtime +/// generates its edges while a process waits on it. +fn clocked_by_process_waits( + period: u64, +) -> ( + ModuleBuilder, + celox::frontend_sdk::SignalId, + celox::frontend_sdk::SignalId, +) { + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(32).unwrap(); + let mut module = ModuleBuilder::new("ClockWaits").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let count = module.output("count", word).unwrap(); + module + .set_initial(count, Constant::two_state(0u8, 32).unwrap()) + .unwrap(); + let count_expr = module.read(count).unwrap(); + let one = constant(&mut module, 1, 32); + let next = module.binary(BinaryOp::Add, count_expr, one, word).unwrap(); + let count_target = module.whole(count).unwrap(); + module + .register(count_target, next, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, period).unwrap(); + (module, clk, count) +} + +#[test] +fn clock_waits_count_rising_edges_and_resume_before_the_next() { + let (mut module, clk, count) = clocked_by_process_waits(2); + let word = ValueType::bits(32).unwrap(); + let seen = module.output("seen", word).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let count_expr = module.read(count).unwrap(); + let ten = constant(&mut module, 10, 64); + let three = constant(&mut module, 3, 64); + let zero = constant(&mut module, 0, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Assign { + target: seen_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: zero, + }, + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let count = sim.signal("count"); + let seen = sim.signal("seen"); + // Edges at 0, 2, ..., 18; the process resumes at 20, before the edge there. + sim.run_until(19).unwrap(); + assert_eq!(sim.get(count), 10u32.into()); + assert_eq!(sim.get(seen), 0u32.into()); + assert_eq!(sim.ticks(), 10); + sim.run_until(20).unwrap(); + assert_eq!(sim.get(seen), 10u32.into()); + assert!(!sim.is_finished()); + // Three more edges at 20, 22 and 24; the process finishes at 26. + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 26); + assert_eq!(sim.get(count), 13u32.into()); + assert_eq!(sim.ticks(), 13); +} + +#[test] +fn clock_waits_of_several_processes_share_fused_edges() { + let (mut module, clk, count) = clocked_by_process_waits(10); + let word = ValueType::bits(32).unwrap(); + let early = module.output("early", word).unwrap(); + let late = module.output("late", word).unwrap(); + let count_expr = module.read(count).unwrap(); + let early_target = module.whole(early).unwrap(); + let late_target = module.whole(late).unwrap(); + let a_lot = constant(&mut module, 1_000_000, 64); + let fewer = constant(&mut module, 300_000, 64); + let some = constant(&mut module, 5, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: a_lot, + }, + Statement::Assign { + target: late_target, + value: count_expr, + }, + Statement::Finish, + ]) + .unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: fewer, + }, + Statement::Assign { + target: early_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: some, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let early = sim.signal("early"); + let late = sim.signal("late"); + sim.run_until(u64::MAX - 1).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(early), 300_000u32.into()); + assert_eq!(sim.get(late), 1_000_000u32.into()); + assert_eq!(sim.ticks(), 1_000_000); + assert_eq!(sim.time(), 10_000_000); +} + +#[test] +fn clock_waits_interleave_with_delays_and_checkpoints() { + let (mut module, clk, count) = clocked_by_process_waits(2); + let word = ValueType::bits(32).unwrap(); + let bit = ValueType::bits(1).unwrap(); + let seen = module.output("seen", word).unwrap(); + let flag = module.output("flag", bit).unwrap(); + let count_expr = module.read(count).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let flag_target = module.whole(flag).unwrap(); + let ten = constant(&mut module, 10, 64); + let five = constant(&mut module, 5, 64); + let one = constant(&mut module, 1, 1); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Assign { + target: seen_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Finish, + ]) + .unwrap(); + module + .process(vec![ + Statement::Delay { amount: five }, + Statement::Assign { + target: flag_target, + value: one, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let count = sim.signal("count"); + let seen = sim.signal("seen"); + let flag = sim.signal("flag"); + let clk = sim.signal("clk"); + // Edges at 0, 2 and 4 run one by one around the delay at 5; the clock + // signal shows them. + sim.run_until(2).unwrap(); + assert_eq!(sim.get(count), 2u32.into()); + assert_eq!(sim.get(clk), 1u8.into()); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(flag), 1u8.into()); + assert_eq!(sim.get(count), 3u32.into()); + let checkpoint = sim.checkpoint().unwrap(); + sim.run_until(20).unwrap(); + // The process resumed at 20 before the edge there, and waits again, so + // that edge fires. + assert_eq!(sim.get(seen), 10u32.into()); + assert_eq!(sim.get(count), 11u32.into()); + sim.restore(&checkpoint).unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(seen), 0u32.into()); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 40); + assert_eq!(sim.get(seen), 10u32.into()); + assert_eq!(sim.get(count), 20u32.into()); +} diff --git a/docs/guide/external-frontends.md b/docs/guide/external-frontends.md index cce58382da4..cf78b51ca2b 100644 --- a/docs/guide/external-frontends.md +++ b/docs/guide/external-frontends.md @@ -131,6 +131,7 @@ in order: | `If` | Branch on a condition. A condition with unknown bits counts as false. | | `While` / `Forever` | Repeat a body while a condition holds, or forever. | | `Delay` | Suspend for an amount of time units, at most 64 bits wide. | +| `ClockCycles` | Suspend until a number of rising edges of a clock have passed. The clock must clock a register and have a period set with `ModuleBuilder::clock_period`; the runtime generates its edges from the first wait on it, and the process resumes one period after the last counted edge, before the edge that follows. | | `Finish` | End the simulation. | ```rust @@ -155,6 +156,15 @@ delay resumes the process later at the same time, after the other processes have run and the registers their edges trigger have settled, so a pulse separated by a zero delay is still an edge. +A clock that processes wait on with `ClockCycles` toggles every half period +once a process has waited on it, as long as one does. While every live +process waits on the same clock and nothing else is scheduled, the edges run +as fused ticks inside the backend's generated code, so a long wait costs no +more than the same number of ticks of an event-driven `Simulator`; such a +run skips the clock signal's own edges and the per-edge hooks of external +components, which are honored again as soon as another process or event +interleaves. + A process may write output and internal signals that no continuous assignment or register drives. Several processes may write the same signal. Checkpoints capture suspended processes, but state files are not yet supported for a diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index e58c4718cf6..a45d4f22c4a 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -184,9 +184,12 @@ to the next. Each process owns three hidden two-state state objects: - a resume slot, which the kernel's entry block dispatches on with a `Switch` (two levels beyond 255 suspension points); -- a status slot, in which the kernel reports a delay, a wait, the end of the - process, or `$finish` before it returns; -- a delay slot, which holds the wait amount. +- a status slot, in which the kernel reports a delay, a wait, a clock wait, + the end of the process, or `$finish` before it returns; +- a delay slot, which holds the wait amount: time units or clock edges; +- a clock slot, which names the process clock of a clock wait among the + clocks the process may wait on, listed with their periods in the runtime + schema. A suspension stores these slots and returns, so no backend needs a new terminator. Kernels are never merged with each other or with a phase, and @@ -215,11 +218,26 @@ waited for zero time, or that the settled state wakes, resume in a further round at the same time, which repeats the edge detection and settling; a round in which every waiting process reports a pending wait ends the time. `Simulation::step` and `run_until` also run such a round first, so a host -write between steps wakes the processes that wait for it. Because the slots -are ordinary state, a checkpoint captures suspended processes. The optimizer -does not yet optimize kernels, but it treats their accesses like those of FF -domains, so identity aliasing and dead-store elimination keep the state they -use. +write between steps wakes the processes that wait for it. + +A clock wait asks for a number of rising edges of a process clock. The +scheduler generates that clock's edges from the first wait on it: a rising +edge is due at the clock's next edge time whenever a process waits, applied +after the processes of that time have run, and its falling edge half a +period later; each rising edge counts against the waits, and a process whose +count is reached resumes one period after that edge, before the edge that +follows. When every live process waits on the single clock that is due and +no event, resumption or falling edge is pending, the scheduler instead runs +as many edges as the earliest resumption needs through +`SimulationExecutor::tick_many`, the same fused combinational-plus-sequential +loop that event-driven ticks use, and advances time past them in one step. +Those ticks leave the clock signal untouched and skip the per-edge hooks of +external components, which is why the host can veto them. Because the slots +are ordinary state, a checkpoint captures suspended processes, and the +scheduler's snapshot carries the generated clocks and clock waits. The +optimizer does not yet optimize kernels, but it treats their accesses like +those of FF domains, so identity aliasing and dead-store elimination keep +the state they use. A running simulator retains the elaborated design, source lookup, runtime schema, bound testbench bytecode, and compiled backend. The backend owns the finalized diff --git a/docs/ja/guide/external-frontends.md b/docs/ja/guide/external-frontends.md index 56c75432a36..8b613c79806 100644 --- a/docs/ja/guide/external-frontends.md +++ b/docs/ja/guide/external-frontends.md @@ -131,6 +131,7 @@ Celox artifact JSON も parse しません。build 可能な addon と load test | `If` | 条件で分岐します。不定 bit を含む条件は偽として扱います。 | | `While` / `Forever` | 条件が成り立つ間、または永久に body を繰り返します。 | | `Delay` | 指定した時間単位だけ suspend します。量は 64 bit 以下です。 | +| `ClockCycles` | clock の立ち上がりエッジが指定回数過ぎるまで suspend します。clock は register の clock で、`ModuleBuilder::clock_period` で周期を設定しておきます。runtime は最初の待ちからその clock のエッジを生成し、process は最後に数えたエッジの 1 周期後、次のエッジの前に再開します。 | | `Finish` | simulation を終了します。 | ```rust @@ -155,6 +156,13 @@ schedule された event と同様にその時刻の register を trigger しま trigger した register が settle した後で再開します。そのため 0 の delay で区切った pulse も edge になります。 +`ClockCycles` で待つ clock は、いずれかの process が待っている間、半周期ごとに +toggle します。生きている process がすべて同じ clock を待っていて他に schedule +された event がないときは、その edge は backend が生成したコードの中で fused tick +として実行されるため、長い待ちも event 駆動の `Simulator` で同じ回数 tick する +のと同程度の cost で済みます。この間は clock signal 自身の edge と外部 component +の edge ごとの hook を省略し、他の process や event が割り込むと再び有効になります。 + process が書けるのは、continuous assignment や register が駆動していない output と internal signal です。同じ signal を複数の process が書いても 構いません。checkpoint は suspend 中の process を保存しますが、process を From 310ddb6a271ee23861a04fe2be1c2d95412b8527 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 15:12:53 +0900 Subject: [PATCH 02/42] fix(runtime): address review findings of the fused clock ticks - `Simulation::run_until` bounds the fused ticks a woken process starts by its end time (`poll_waiting_until`). - A step reports the time its fused ticks reached. - A clock edge beyond simulation time is a runtime error, like a delay. - The edges a backend completed before an error count before the error is reported. - Fused ticks are not used when a register drives another event domain or when the clock is high; a high clock falls before its first counted rising edge, so every counted edge is one the registers saw. - `restore` translates every process clock before changing anything. - `FrontendArtifact::validate` checks process clocks as the builder does: a period of at least two on a one-bit signal that clocks a register. --- crates/celox-frontend-sdk/src/lib.rs | 82 +++++++++++++++ crates/celox-runtime/src/simulation.rs | 116 ++++++++++++++------- crates/celox/src/simulation.rs | 3 +- crates/celox/tests/processes.rs | 136 +++++++++++++++++++++++++ 4 files changed, 301 insertions(+), 36 deletions(-) diff --git a/crates/celox-frontend-sdk/src/lib.rs b/crates/celox-frontend-sdk/src/lib.rs index 62f729b2bb0..136ce154485 100644 --- a/crates/celox-frontend-sdk/src/lib.rs +++ b/crates/celox-frontend-sdk/src/lib.rs @@ -860,6 +860,43 @@ impl FrontendArtifact { for process in &self.processes { self.validate_statements(&process.body, &driver_ranges)?; } + // The same requirements as `ModuleBuilder::clock_period` and + // `ModuleBuilder::process` put on the clocks processes wait on. + for (clock, period) in &self.clock_periods { + let signal = self + .signal(*clock) + .ok_or(BuildError::UnknownSignal(clock.index()))?; + if signal.value_type.width() != 1 { + return Err(BuildError::InvalidControlWidth { + name: signal.name.clone(), + }); + } + if *period < 2 { + return Err(BuildError::InvalidClockPeriod { period: *period }); + } + } + for process in &self.processes { + let mut clocks = Vec::new(); + collect_process_clocks(&process.body, &mut clocks); + for clock in clocks { + let known = self + .clock_periods + .iter() + .any(|(signal, _)| *signal == clock) + && self + .registers + .iter() + .any(|register| register.clock == clock); + if !known { + let name = self + .signal(clock) + .ok_or(BuildError::UnknownSignal(clock.index()))? + .name + .clone(); + return Err(BuildError::UnknownProcessClock { name }); + } + } + } let mut ordered_ports = FxHashMap::default(); for signal in &self.port_order { let signal = self @@ -1994,6 +2031,51 @@ mod tests { )); } + #[test] + fn revalidates_process_clocks_from_json() { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("ProcessClocks").unwrap(); + let clock = module.internal("clock", bit).unwrap(); + let count = module.output("count", bit).unwrap(); + let toggled = module.read(count).unwrap(); + let toggled = module.unary(UnaryOp::BitNot, toggled, bit).unwrap(); + let target = module.whole(count).unwrap(); + module + .register(target, toggled, clock, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clock, 4).unwrap(); + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + module + .process(vec![Statement::ClockCycles { clock, count: one }]) + .unwrap(); + let artifact = module.finish(); + let json = serde_json::to_value(&artifact).unwrap(); + + // Without its period, the clock clocks nothing. + let mut unknown = json.clone(); + unknown["clock_periods"] = serde_json::json!([]); + let error = FrontendArtifact::from_json(&unknown.to_string()).unwrap_err(); + assert!( + matches!( + error, + ArtifactJsonError::InvalidArtifact(BuildError::UnknownProcessClock { .. }) + ), + "{error:?}" + ); + + // A period below two cannot have distinct edges. + let mut short = json.clone(); + short["clock_periods"][0][1] = 1.into(); + let error = FrontendArtifact::from_json(&short.to_string()).unwrap_err(); + assert!( + matches!( + error, + ArtifactJsonError::InvalidArtifact(BuildError::InvalidClockPeriod { period: 1 }) + ), + "{error:?}" + ); + } + #[test] fn rejects_input_driver_targets_in_builder_and_json() { let bit = ValueType::bits(1).unwrap(); diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index aaa6453ecd3..423459a171e 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -249,6 +249,14 @@ pub struct SimulationState { finished: bool, } +/// The error of a process clock whose next edge lies beyond simulation time. +fn clock_overflow(clock: usize) -> SimulatorErrorCode { + SimulatorErrorCode::Runtime { + message: format!("process clock {clock} overflows simulation time"), + signals: Vec::new(), + } +} + impl SimulationState { /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { @@ -419,7 +427,8 @@ impl SimulationState { self.step_round(executor, current_time, events_to_process, ready, true)?; self.run_remaining_rounds(executor, current_time, limit)?; executor.finish_timed_step(self.scheduler.time); - Ok(Some(current_time)) + // Fused ticks may have moved the time on. + Ok(Some(self.scheduler.time)) } /// Run the further rounds of `current_time`: the rising edges of the @@ -485,26 +494,34 @@ impl SimulationState { where E: SimulationExecutor, { - let events = due - .iter() - .map(|id| { - let clock = &self.tick_clocks[id]; - SimEvent { - time, - event_ref: clock.event, - signal: clock.signal, - next_val: 1, - } - }) - .collect(); - self.step_round(executor, time, events, Vec::new(), true)?; + // A clock that is high when its edge is due (the host or a previous + // run left it so) falls first, in a round of its own: the rising + // edge that counts is then a real one. + let mut events = Vec::with_capacity(due.len()); + let mut rising = Vec::with_capacity(due.len()); for id in due { + let clock = &self.tick_clocks[id]; + let high: u8 = executor.backend().get_as(clock.signal); + events.push(SimEvent { + time, + event_ref: clock.event, + signal: clock.signal, + next_val: u8::from(high == 0), + }); + if high == 0 { + rising.push(*id); + } + } + self.step_round(executor, time, events, Vec::new(), true)?; + for id in rising { self.ticks += 1; - let clock = self.tick_clocks.get_mut(id).expect("a due process clock"); - clock.next_edge = time + clock.period; + let clock = self.tick_clocks.get_mut(&id).expect("a due process clock"); + clock.next_edge = time + .checked_add(clock.period) + .ok_or_else(|| clock_overflow(id))?; clock.falling_edge = Some(time + clock.period - clock.period / 2); let resume_at = clock.next_edge; - self.count_edges(*id, 1, resume_at); + self.count_edges(id, 1, resume_at); } Ok(()) } @@ -541,6 +558,9 @@ impl SimulationState { where E: SimulationExecutor, { + // The fused kernel runs the waited-on clock's domain alone: a design + // whose registers drive another clock or reset needs the scheduler's + // rounds, and a clock that is high now needs its normalizing fall. if !executor.fused_ticks_allowed() || !self.waiting.is_empty() || !self.process_wakeups.is_empty() @@ -551,6 +571,11 @@ impl SimulationState { .any(|clock| clock.falling_edge.is_some()) || self.clock_waits.values().any(|wait| wait.clock != clock) || self.clock_waits.len() + self.done.len() != self.processes.len() + || self.event_info.iter().any(|info| info.is_cascaded) + || executor + .backend() + .get_as::(self.tick_clocks[&clock].signal) + != 0 { return Ok(false); } @@ -568,24 +593,31 @@ impl SimulationState { return Ok(false); } let (completed, result) = executor.tick_many(event, count); - result?; - if completed == 0 || completed > count { + if completed > count || (completed == 0 && result.is_ok()) { return Err(SimulatorErrorCode::Runtime { message: "the backend made invalid progress on fused clock ticks".into(), signals: Vec::new(), }); } - self.ticks += completed; - let next_edge = time + completed * period; - self.tick_clocks - .get_mut(&clock) - .expect("a due process clock") - .next_edge = next_edge; - self.count_edges(clock, completed, next_edge); + // The edges the backend completed count, also before an error, so + // the schedule agrees with the state it left. + if completed != 0 { + self.ticks += completed; + self.scheduler.time = time + (completed - 1) * period; + let next_edge = completed + .checked_mul(period) + .and_then(|span| time.checked_add(span)) + .ok_or_else(|| clock_overflow(clock))?; + self.tick_clocks + .get_mut(&clock) + .expect("a due process clock") + .next_edge = next_edge; + self.count_edges(clock, completed, next_edge); + } + result?; // The processes that resume read the state settled after the last // edge. executor.eval_comb()?; - self.scheduler.time = time + (completed - 1) * period; Ok(true) } @@ -593,6 +625,19 @@ impl SimulationState { /// current time, for state that was changed from outside the scheduler, /// and settle what they drive. Nothing happens when none wakes. pub fn poll_waiting(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.poll_waiting_until(executor, u64::MAX) + } + + /// [`Self::poll_waiting`], where the fused clock ticks a woken process + /// may start stop before `limit`, as in [`Self::step_until`]. + pub fn poll_waiting_until( + &mut self, + executor: &mut E, + limit: u64, + ) -> Result<(), SimulatorErrorCode> where E: SimulationExecutor, { @@ -601,8 +646,8 @@ impl SimulationState { } let time = self.scheduler.time; if self.step_round(executor, time, Vec::new(), Vec::new(), false)? { - self.run_remaining_rounds(executor, time, u64::MAX)?; - executor.finish_timed_step(time); + self.run_remaining_rounds(executor, time, limit)?; + executor.finish_timed_step(self.scheduler.time); } Ok(()) } @@ -1080,12 +1125,7 @@ impl SimulationState { }) }) .collect::>()?; - self.scheduler.time = snapshot.time; - self.scheduler.clocks.clone_from(&snapshot.clocks); - self.scheduler.event_queue = event_queue; - self.periodic_events.clone_from(&snapshot.periodic_events); - self.last_clock_values - .clone_from(&snapshot.last_clock_values); + // Every translation happens before anything changes. let tick_clocks = snapshot .tick_clocks .iter() @@ -1099,6 +1139,12 @@ impl SimulationState { )) }) .collect::>()?; + self.scheduler.time = snapshot.time; + self.scheduler.clocks.clone_from(&snapshot.clocks); + self.scheduler.event_queue = event_queue; + self.periodic_events.clone_from(&snapshot.periodic_events); + self.last_clock_values + .clone_from(&snapshot.last_clock_values); self.process_wakeups.clone_from(&snapshot.process_wakeups); self.waiting.clone_from(&snapshot.waiting); self.tick_clocks = tick_clocks; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 87ac6b2130b..86c0760aa81 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -470,7 +470,8 @@ impl Simulation { /// Advance time and run until `end_time` (inclusive). As for /// [`Self::step`], processes that a host write woke resume first. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { - self.state.poll_waiting(&mut self.simulator)?; + self.state + .poll_waiting_until(&mut self.simulator, end_time)?; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { break; diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 28af2c48568..baf72058fd0 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -820,3 +820,139 @@ fn clock_waits_interleave_with_delays_and_checkpoints() { assert_eq!(sim.get(seen), 10u32.into()); assert_eq!(sim.get(count), 20u32.into()); } + +/// A step whose clock waits ran as fused ticks reports the time it reached. +#[test] +fn a_fused_step_returns_the_time_it_reached() { + let (mut module, clk, _count) = clocked_by_process_waits(2); + let ten = constant(&mut module, 10, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + // Edges at 0, 2, ..., 18 run as one step. + assert_eq!(sim.step().unwrap(), Some(18)); + assert_eq!(sim.time(), 18); + assert_eq!(sim.ticks(), 10); +} + +/// A process clock that is high when a wait begins falls first: only real +/// rising edges count, so the registers see every counted edge. +#[test] +fn a_high_process_clock_falls_before_its_first_counted_edge() { + let (mut module, clk, count) = clocked_by_process_waits(2); + module + .set_initial(clk, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + let word = ValueType::bits(32).unwrap(); + let seen = module.output("seen", word).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let count_expr = module.read(count).unwrap(); + let three = constant(&mut module, 3, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Assign { + target: seen_target, + value: count_expr, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let seen = sim.signal("seen"); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(seen), 3u32.into()); + assert_eq!(sim.ticks(), 3); +} + +/// A clock edge that would lie beyond simulation time is an error, like a +/// delay that overflows. +#[test] +fn clock_edges_beyond_simulation_time_are_an_error() { + let (mut module, clk, _count) = clocked_by_process_waits(2); + let late = module.constant(Constant::two_state(u64::MAX - 2, 64).unwrap()); + let two = constant(&mut module, 2, 64); + module + .process(vec![ + Statement::Delay { amount: late }, + Statement::ClockCycles { + clock: clk, + count: two, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + loop { + match sim.step() { + Ok(Some(_)) => {} + Ok(None) => panic!("the overflowing edge was not reported"), + Err(error) => { + assert!( + error.to_string().contains("overflows simulation time"), + "{error}" + ); + break; + } + } + } +} + +/// A design whose registers drive another clock keeps the scheduler's +/// rounds: the derived clock's domain fires on every clock wait too. +#[test] +fn clock_waits_keep_derived_clocks_running() { + let (mut module, clk, _count) = clocked_by_process_waits(2); + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(32).unwrap(); + let half = module.internal("half", bit).unwrap(); + module + .set_initial(half, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + let half_expr = module.read(half).unwrap(); + let toggled = module.unary(UnaryOp::BitNot, half_expr, bit).unwrap(); + let half_target = module.whole(half).unwrap(); + module + .register(half_target, toggled, clk, Edge::Posedge, None, None) + .unwrap(); + let slow = module.output("slow", word).unwrap(); + module + .set_initial(slow, Constant::two_state(0u8, 32).unwrap()) + .unwrap(); + let slow_expr = module.read(slow).unwrap(); + let one = constant(&mut module, 1, 32); + let next = module.binary(BinaryOp::Add, slow_expr, one, word).unwrap(); + let slow_target = module.whole(slow).unwrap(); + module + .register(slow_target, next, half, Edge::Posedge, None, None) + .unwrap(); + let ten = constant(&mut module, 10, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let count = sim.signal("count"); + let slow = sim.signal("slow"); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(count), 10u32.into()); + // `half` rises on every second edge of `clk`. + assert_eq!(sim.get(slow), 5u32.into()); +} From 78390baa05fc6f6a996b796913956233bcb512a7 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 07:27:10 +0900 Subject: [PATCH 03/42] fix(runtime): preserve clock phases and simultaneous edge state --- crates/celox-frontend-sdk/src/lib.rs | 136 ++++++++++++- crates/celox-runtime/src/backend.rs | 5 +- crates/celox-runtime/src/simulation.rs | 258 ++++++++++++++----------- crates/celox/src/simulation.rs | 98 +++++++++- crates/celox/tests/processes.rs | 125 ++++++++++++ 5 files changed, 501 insertions(+), 121 deletions(-) diff --git a/crates/celox-frontend-sdk/src/lib.rs b/crates/celox-frontend-sdk/src/lib.rs index 136ce154485..e1b489b4928 100644 --- a/crates/celox-frontend-sdk/src/lib.rs +++ b/crates/celox-frontend-sdk/src/lib.rs @@ -13,9 +13,9 @@ use thiserror::Error; /// Current JSON interchange version of [`FrontendArtifact`]. /// -/// Version 2 adds [`Process`]es. An artifact without processes is still -/// written as version 1, so older consumers keep accepting it. -pub const ARTIFACT_FORMAT_VERSION: u32 = 2; +/// Version 2 adds [`Process`]es; version 3 adds [`Statement::ClockCycles`]. +/// Artifacts use the oldest version that can represent their statements. +pub const ARTIFACT_FORMAT_VERSION: u32 = 3; /// Oldest JSON interchange version [`FrontendArtifact::from_json`] accepts. pub const MIN_ARTIFACT_FORMAT_VERSION: u32 = 1; @@ -533,10 +533,25 @@ impl FrontendArtifact { /// Decode and version-check an artifact produced by an external frontend. pub fn from_json(json: &str) -> Result { + #[derive(Deserialize)] + struct Header { + format_version: u32, + } + let header: Header = serde_json::from_str(json)?; + if !(MIN_ARTIFACT_FORMAT_VERSION..=ARTIFACT_FORMAT_VERSION).contains(&header.format_version) + { + return Err(ArtifactJsonError::UnsupportedVersion { + expected: ARTIFACT_FORMAT_VERSION, + actual: header.format_version, + }); + } let artifact: Self = serde_json::from_str(json)?; - if !(MIN_ARTIFACT_FORMAT_VERSION..=ARTIFACT_FORMAT_VERSION) - .contains(&artifact.format_version) - || (artifact.format_version < 2 && !artifact.processes.is_empty()) + let mut clocks = Vec::new(); + for process in &artifact.processes { + collect_process_clocks(&process.body, &mut clocks); + } + if (artifact.format_version < 2 && !artifact.processes.is_empty()) + || (artifact.format_version < 3 && !clocks.is_empty()) { return Err(ArtifactJsonError::UnsupportedVersion { expected: ARTIFACT_FORMAT_VERSION, @@ -879,6 +894,21 @@ impl FrontendArtifact { let mut clocks = Vec::new(); collect_process_clocks(&process.body, &mut clocks); for clock in clocks { + let mut targets = Vec::new(); + for process in &self.processes { + collect_process_targets(&process.body, &mut targets); + } + if driver_ranges.contains_key(&clock) + || targets.iter().any(|target| target.signal == clock) + { + return Err(BuildError::DrivenProcessClock { + name: self + .signal(clock) + .ok_or(BuildError::UnknownSignal(clock.index()))? + .name + .clone(), + }); + } let known = self .clock_periods .iter() @@ -1014,6 +1044,8 @@ pub enum BuildError { InvalidClockPeriod { period: u64 }, #[error("clock `{name}` needs a period and a register it clocks before a process waits on it")] UnknownProcessClock { name: String }, + #[error("process clock `{name}` also has a continuous, register or process driver")] + DrivenProcessClock { name: String }, #[error("register target `{name}` must cover the complete signal")] PartialRegisterTarget { name: String }, #[error("module name must not be empty")] @@ -1429,7 +1461,20 @@ impl ModuleBuilder { )?; let mut clocks = Vec::new(); collect_process_clocks(&body, &mut clocks); + let mut targets = Vec::new(); + collect_process_targets(&body, &mut targets); + for process in &self.processes { + collect_process_targets(&process.body, &mut targets); + collect_process_clocks(&process.body, &mut clocks); + } for clock in clocks { + if self.driver_ranges.contains_key(&clock) + || targets.iter().any(|target| target.signal == clock) + { + return Err(BuildError::DrivenProcessClock { + name: self.signal_info(clock)?.name.clone(), + }); + } let known = self .clock_periods .iter() @@ -1453,7 +1498,15 @@ impl ModuleBuilder { format_version: if self.processes.is_empty() { MIN_ARTIFACT_FORMAT_VERSION } else { - ARTIFACT_FORMAT_VERSION + let mut clocks = Vec::new(); + for process in &self.processes { + collect_process_clocks(&process.body, &mut clocks); + } + if clocks.is_empty() { + 2 + } else { + ARTIFACT_FORMAT_VERSION + } }, module_name: self.name, signals: self.signals, @@ -1530,6 +1583,13 @@ impl ModuleBuilder { fn record_driver_target(&mut self, target: SignalSlice) -> Result<(), BuildError> { let signal_name = self.signal_info(target.signal)?.name.clone(); + let mut process_clocks = Vec::new(); + for process in &self.processes { + collect_process_clocks(&process.body, &mut process_clocks); + } + if process_clocks.contains(&target.signal) { + return Err(BuildError::DrivenProcessClock { name: signal_name }); + } let mut process_targets = Vec::new(); for process in &self.processes { collect_process_targets(&process.body, &mut process_targets); @@ -2031,6 +2091,23 @@ mod tests { )); } + fn module_for_driven_clock() -> Result<(), BuildError> { + let bit = ValueType::bits(1)?; + let mut module = ModuleBuilder::new("Driven")?; + let clk = module.internal("clk", bit)?; + let q = module.output("q", bit)?; + let one = module.constant(Constant::two_state(1u8, 1)?); + let target = module.whole(q)?; + module.register(target, one, clk, Edge::Posedge, None, None)?; + module.clock_period(clk, 4)?; + let target = module.whole(clk)?; + module.assign(target, one)?; + module.process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + } + #[test] fn revalidates_process_clocks_from_json() { let bit = ValueType::bits(1).unwrap(); @@ -2049,7 +2126,52 @@ mod tests { .process(vec![Statement::ClockCycles { clock, count: one }]) .unwrap(); let artifact = module.finish(); + assert_eq!(artifact.format_version(), 3); let json = serde_json::to_value(&artifact).unwrap(); + let mut old_version = json.clone(); + old_version["format_version"] = 2.into(); + assert!(matches!( + FrontendArtifact::from_json(&old_version.to_string()), + Err(ArtifactJsonError::UnsupportedVersion { actual: 2, .. }) + )); + let mut future = json.clone(); + future["format_version"] = 4.into(); + future["processes"][0]["body"][0] = serde_json::json!({"FutureStatement": {}}); + assert!(matches!( + FrontendArtifact::from_json(&future.to_string()), + Err(ArtifactJsonError::UnsupportedVersion { actual: 4, .. }) + )); + // Validate both builder orderings and the deserialization trust boundary. + let driven = module_for_driven_clock(); + assert!(matches!(driven, Err(BuildError::DrivenProcessClock { .. }))); + let mut late_driver = json.clone(); + late_driver["assignments"] = serde_json::json!([{ "target": {"signal": clock, "lsb": 0, "width": 1}, "value": toggled }]); + assert!(matches!( + FrontendArtifact::from_json(&late_driver.to_string()), + Err(ArtifactJsonError::InvalidArtifact( + BuildError::DrivenProcessClock { .. } + )) + )); + let mut later = ModuleBuilder::new("LaterDriver").unwrap(); + let clk = later.internal("clk", bit).unwrap(); + let q = later.output("q", bit).unwrap(); + let one = later.constant(Constant::two_state(1u8, 1).unwrap()); + let target = later.whole(q).unwrap(); + later + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + later.clock_period(clk, 4).unwrap(); + later + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + let target = later.whole(clk).unwrap(); + assert!(matches!( + later.assign(target, one), + Err(BuildError::DrivenProcessClock { .. }) + )); // Without its period, the clock clocks nothing. let mut unknown = json.clone(); diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index fb82fb3e8b0..ff0c70e85d7 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -53,7 +53,10 @@ pub trait SimBackend { if count == 0 { return (0, Ok(())); } - (1, self.eval_comb_apply_ff_at(event)) + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } + (1, self.eval_apply_ff_at(event)) } /// Evaluate FF domain without applying (for cascaded clocks). diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index f1097e1eb49..d2eae1cc21c 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -441,8 +441,29 @@ impl SimulationState { }); } } + let rising: Vec = self + .tick_clocks + .iter() + .filter(|(id, clock)| { + !events_to_process.is_empty() + && clock.next_edge == current_time + && self.clock_has_waiters(**id) + && executor.backend().get_as::(clock.signal) == 0 + }) + .map(|(id, _)| *id) + .collect(); + for id in &rising { + let clock = &self.tick_clocks[id]; + events_to_process.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 1, + }); + } let ready = self.take_ready_processes(current_time); self.step_round(executor, current_time, events_to_process, ready, true)?; + self.credit_rising_edges(current_time, rising)?; self.run_remaining_rounds(executor, current_time, limit)?; executor.finish_timed_step(self.scheduler.time); // Fused ticks may have moved the time on. @@ -531,6 +552,14 @@ impl SimulationState { } } self.step_round(executor, time, events, Vec::new(), true)?; + self.credit_rising_edges(time, rising) + } + + fn credit_rising_edges( + &mut self, + time: u64, + rising: Vec, + ) -> Result<(), SimulatorErrorCode> { for id in rising { self.ticks += 1; let clock = self.tick_clocks.get_mut(&id).expect("a due process clock"); @@ -580,6 +609,8 @@ impl SimulationState { // whose registers drive another clock or reset needs the scheduler's // rounds, and a clock that is high now needs its normalizing fall. if !executor.fused_ticks_allowed() + || self.domain_kinds[clock] != Some(DomainKind::ClockPosedge) + || !self.inactive.is_empty() || !self.waiting.is_empty() || !self.process_wakeups.is_empty() || self.scheduler.next_event_time().is_some() @@ -600,9 +631,9 @@ impl SimulationState { let Some(needed) = self.clock_waits.values().map(|wait| wait.remaining).min() else { return Ok(false); }; - let (event, period) = { + let (event, signal, period) = { let clock = &self.tick_clocks[&clock]; - (clock.event, clock.period) + (clock.event, clock.signal, clock.period) }; // Edges at `time`, `time + period`, ...: the last one stays at or // before `limit`. @@ -610,7 +641,12 @@ impl SimulationState { if count == 0 { return Ok(false); } + // Combinational next-state logic samples the rising level of the clock. + executor.backend_mut().set(signal, 1u8); let (completed, result) = executor.tick_many(event, count); + if completed == 0 { + executor.backend_mut().set(signal, 0u8); + } if completed > count || (completed == 0 && result.is_ok()) { return Err(SimulatorErrorCode::Runtime { message: "the backend made invalid progress on fused clock ticks".into(), @@ -626,10 +662,13 @@ impl SimulationState { .checked_mul(period) .and_then(|span| time.checked_add(span)) .ok_or_else(|| clock_overflow(clock))?; - self.tick_clocks + let tick_clock = self + .tick_clocks .get_mut(&clock) - .expect("a due process clock") - .next_edge = next_edge; + .expect("a due process clock"); + tick_clock.next_edge = next_edge; + tick_clock.falling_edge = Some(self.scheduler.time + period - period / 2); + self.last_clock_values.insert(clock); self.count_edges(clock, completed, next_edge); } result?; @@ -705,10 +744,8 @@ impl SimulationState { { let mut progressed = false; let mut pass = ready; - let mut again = Vec::new(); loop { pass.extend(self.waiting.iter().copied()); - pass.append(&mut again); pass.sort_unstable(); pass.dedup(); if pass.is_empty() { @@ -716,105 +753,107 @@ impl SimulationState { } let mut any_ran = false; for process in pass.drain(..) { - let before = self - .process_event_counters - .iter() - .map(|(_, rises, falls)| { - ( - executor.backend().get_as::(*rises), - executor.backend().get_as::(*falls), - ) - }) - .collect::>(); - executor.run_process(process)?; - for ((id, rises, falls), (old_rises, old_falls)) in - self.process_event_counters.iter().zip(before) - { - let changed = match self.domain_kinds[*id] { - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - executor.backend().get_as::(*falls) != old_falls + loop { + let before = self + .process_event_counters + .iter() + .map(|(_, rises, falls)| { + ( + executor.backend().get_as::(*rises), + executor.backend().get_as::(*falls), + ) + }) + .collect::>(); + executor.run_process(process)?; + for ((id, rises, falls), (old_rises, old_falls)) in + self.process_event_counters.iter().zip(before) + { + let changed = match self.domain_kinds[*id] { + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + executor.backend().get_as::(*falls) != old_falls + } + _ => executor.backend().get_as::(*rises) != old_rises, + }; + if changed { + executor.backend_mut().mark_triggered_bit(*id); } - _ => executor.backend().get_as::(*rises) != old_rises, - }; - if changed { - executor.backend_mut().mark_triggered_bit(*id); } - } - let refs = &self.processes[process]; - let status: u8 = executor.backend().get_as(refs.status); - match ProcessStatus::from_code(status) { - Some(ProcessStatus::Delay | ProcessStatus::InactiveDelay) => { - let delay: u64 = executor.backend().get_as(refs.delay); - let time = current_time.checked_add(delay).ok_or_else(|| { - SimulatorErrorCode::Runtime { - message: format!( - "process {process} delay overflows simulation time" - ), - signals: Vec::new(), + let refs = &self.processes[process]; + let status: u8 = executor.backend().get_as(refs.status); + match ProcessStatus::from_code(status) { + Some(ProcessStatus::Delay | ProcessStatus::InactiveDelay) => { + let delay: u64 = executor.backend().get_as(refs.delay); + let time = current_time.checked_add(delay).ok_or_else(|| { + SimulatorErrorCode::Runtime { + message: format!( + "process {process} delay overflows simulation time" + ), + signals: Vec::new(), + } + })?; + self.waiting.remove(&process); + if delay == 0 + && ProcessStatus::from_code(status) + == Some(ProcessStatus::InactiveDelay) + { + self.inactive.insert(process); + } else { + self.process_wakeups.push(Reverse((time, process))); } - })?; - self.waiting.remove(&process); - if delay == 0 - && ProcessStatus::from_code(status) - == Some(ProcessStatus::InactiveDelay) - { - self.inactive.insert(process); - } else { - self.process_wakeups.push(Reverse((time, process))); + any_ran = true; } - any_ran = true; - } - Some(ProcessStatus::Done) => { - self.waiting.remove(&process); - self.done.insert(process); - any_ran = true; - } - Some(ProcessStatus::Finish) => { - self.waiting.remove(&process); - self.done.insert(process); - self.finished = true; - return Ok(true); - } - Some(ProcessStatus::Wait) => { - self.waiting.insert(process); - any_ran = true; - } - Some(ProcessStatus::WaitClock) => { - let count: u64 = executor.backend().get_as(refs.delay); - let index: u32 = executor.backend().get_as(refs.clock); - let Some(clock) = refs.clocks.get(index as usize) else { - return Err(SimulatorErrorCode::InternalError); - }; - self.waiting.remove(&process); - if count == 0 { - // Nothing to wait for: the process continues in - // the next pass. - again.push(process); - } else { - let id = clock.event.id(); - let tick_clock = - self.tick_clocks.entry(id).or_insert_with(|| TickClock { - event: clock.event, - signal: clock.signal, - period: clock.period.max(2), - next_edge: current_time, - falling_edge: None, - }); - tick_clock.next_edge = tick_clock.next_edge.max(current_time); - self.clock_waits.insert( - process, - ClockWait { - clock: id, - remaining: count, - }, - ); + Some(ProcessStatus::Done) => { + self.waiting.remove(&process); + self.done.insert(process); + any_ran = true; + } + Some(ProcessStatus::Finish) => { + self.waiting.remove(&process); + self.done.insert(process); + self.finished = true; + return Ok(true); + } + Some(ProcessStatus::Wait) => { + self.waiting.insert(process); + any_ran = true; } - any_ran = true; + Some(ProcessStatus::WaitClock) => { + let count: u64 = executor.backend().get_as(refs.delay); + let index: u32 = executor.backend().get_as(refs.clock); + let Some(clock) = refs.clocks.get(index as usize) else { + return Err(SimulatorErrorCode::InternalError); + }; + self.waiting.remove(&process); + if count == 0 { + // A zero-count wait does not yield to another process. + continue; + } else { + let id = clock.event.id(); + let tick_clock = + self.tick_clocks.entry(id).or_insert_with(|| TickClock { + event: clock.event, + signal: clock.signal, + period: clock.period.max(2), + next_edge: current_time, + falling_edge: None, + }); + tick_clock.next_edge = tick_clock.next_edge.max(current_time); + self.clock_waits.insert( + process, + ClockWait { + clock: id, + remaining: count, + }, + ); + } + any_ran = true; + } + // The kernel found its wait condition unmet and ran + // nothing; it stays waiting. + Some(ProcessStatus::Pending) => {} + None => return Err(SimulatorErrorCode::InternalError), } - // The kernel found its wait condition unmet and ran - // nothing; it stays waiting. - Some(ProcessStatus::Pending) => {} - None => return Err(SimulatorErrorCode::InternalError), + break; } } if !any_ran { @@ -842,7 +881,7 @@ impl SimulationState { E: SimulationExecutor, { while self.next_event_time().is_some_and(|next| next < time) { - self.step(executor)?; + self.step_until(executor, time)?; } if self.finished { return Ok(None); @@ -851,7 +890,7 @@ impl SimulationState { self.step_round(executor, time, Vec::new(), ready, true)?; // A process the settled state woke may wait for zero time: the // rounds of this time are drained, as `step` drains them. - self.run_remaining_rounds(executor, time, u64::MAX)?; + self.run_remaining_rounds(executor, time, time)?; executor.finish_timed_step(time); Ok(Some(time)) } @@ -1189,7 +1228,11 @@ impl SimulationState { if self.finished { return None; } - let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); + let process = if self.inactive.is_empty() { + self.process_wakeups.peek().map(|&Reverse((time, _))| time) + } else { + Some(self.scheduler.time) + }; let clocks = self .tick_clocks .iter() @@ -1205,15 +1248,6 @@ impl SimulationState { .into_iter() .flatten() .min() - let process = if self.inactive.is_empty() { - self.process_wakeups.peek().map(|&Reverse((time, _))| time) - } else { - Some(self.scheduler.time) - }; - match (self.scheduler.next_event_time(), process) { - (Some(event), Some(process)) => Some(event.min(process)), - (event, process) => event.or(process), - } } /// Periodic clocks as (event id, period). diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 041dea26cf3..0afe586af71 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -103,6 +103,9 @@ impl SimulationExecutor for Simulator { return (0, Ok(())); } if !self.program.runtime_schema.comb_observers.is_empty() { + if let Err(error) = self.eval_comb_checked() { + return (0, Err(error)); + } return (1, self.tick_deferred_comb(event)); } // Every tick settles the combinational logic first, so a clean @@ -117,7 +120,7 @@ impl SimulationExecutor for Simulator { } fn fused_ticks_allowed(&self) -> bool { - !self.components.has_scheduled_components() + self.vcd_writer.is_none() && !self.components.has_scheduled_components() } fn stage_external_event( @@ -1184,6 +1187,99 @@ mod clock_wait_tests { fn four_state_clock_waits_run_on_every_backend() { check_all_backends(true); } + fn edge_design(edge: Edge) -> FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Edges").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let clock_value = module.read(clk).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let value = if edge == Edge::Posedge { + clock_value + } else { + one + }; + let target = module.whole(q).unwrap(); + module + .register(target, value, clk, edge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let three = module.constant(Constant::two_state(3u8, 8).unwrap()); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Finish, + ]) + .unwrap(); + module.finish() + } + + fn check_edge(mut sim: Simulation, edge: Edge) { + sim.run_until(0).unwrap(); + assert_eq!( + sim.get(sim.signal("q")), + u8::from(edge == Edge::Posedge).into() + ); + sim.run_until(1).unwrap(); + assert_eq!( + sim.get(sim.signal("q")), + u8::from(edge == Edge::Posedge).into() + ); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + sim.run_until(20).unwrap(); + assert_eq!(sim.time(), 12); + assert_eq!(sim.ticks(), 3); + assert!(sim.is_finished()); + } + + #[test] + fn clock_levels_and_falling_edges_agree_across_backends() { + for edge in [Edge::Posedge, Edge::Negedge] { + let builder = || Simulator::from_frontend(edge_design(edge)).emit_triggers(); + check_edge( + Simulation::new(builder().build_interpreter().unwrap()), + edge, + ); + check_edge(Simulation::new(builder().build_cranelift().unwrap()), edge); + check_edge(Simulation::new(builder().build_wasm().unwrap()), edge); + check_edge(Simulation::new(builder().build_tiered().unwrap()), edge); + check_edge(Simulation::new(builder().build_native().unwrap()), edge); + } + } + + #[test] + fn settle_at_does_not_fuse_past_a_delay_boundary() { + // Use a dedicated SDK design so settle_at itself advances to the due delay. + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Boundary").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let target = module.whole(q).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 2).unwrap(); + let five = module.constant(Constant::two_state(5u8, 8).unwrap()); + let ten = module.constant(Constant::two_state(10u8, 8).unwrap()); + module + .process(vec![ + Statement::Delay { amount: five }, + Statement::ClockCycles { + clock: clk, + count: ten, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + assert_eq!(sim.state.settle_at(&mut sim.simulator, 5).unwrap(), Some(5)); + assert_eq!(sim.time(), 5); + assert_eq!(sim.ticks(), 1); + } } #[cfg(all(test, feature = "systemverilog"))] diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index baf72058fd0..e3073d7b144 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -956,3 +956,128 @@ fn clock_waits_keep_derived_clocks_running() { // `half` rises on every second edge of `clk`. assert_eq!(sim.get(slow), 5u32.into()); } + +#[test] +fn zero_clock_wait_does_not_yield_to_another_process() { + let (mut module, clk, _) = clocked_by_process_waits(2); + let bit = ValueType::bits(1).unwrap(); + let x = module.output("x", bit).unwrap(); + let seen = module.output("seen", bit).unwrap(); + let x_target = module.whole(x).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let x_value = module.read(x).unwrap(); + let zero = constant(&mut module, 0, 1); + let one = constant(&mut module, 1, 1); + module + .process(vec![ + Statement::Assign { + target: x_target, + value: one, + }, + Statement::ClockCycles { + clock: clk, + count: zero, + }, + Statement::Assign { + target: seen_target, + value: x_value, + }, + ]) + .unwrap(); + module + .process(vec![Statement::Assign { + target: x_target, + value: zero, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 1u8.into()); + assert_eq!(sim.get(sim.signal("x")), 0u8.into()); + assert_eq!(sim.ticks(), 0); +} + +#[test] +fn settle_bounds_clock_waits_started_by_a_due_delay() { + let (mut module, clk, _) = clocked_by_process_waits(2); + let five = constant(&mut module, 5, 64); + let ten = constant(&mut module, 10, 64); + module + .process(vec![ + Statement::Delay { amount: five }, + Statement::ClockCycles { + clock: clk, + count: ten, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + sim.run_until(5).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("count")), 1u32.into()); +} + +#[test] +fn scheduled_and_process_clock_edges_sample_the_same_old_state() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let bit = ValueType::bits(1).unwrap(); + let manual = module.input("manual", bit).unwrap(); + let b = module.output("b", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let one = constant(&mut module, 1, 1); + let b_value = module.read(b).unwrap(); + let b_target = module.whole(b).unwrap(); + let q_target = module.whole(q).unwrap(); + module + .register(b_target, one, manual, Edge::Posedge, None, None) + .unwrap(); + module + .register(q_target, b_value, clk, Edge::Posedge, None, None) + .unwrap(); + let three = constant(&mut module, 3, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: three, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + sim.schedule("manual", 4, 1).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("b")), 1u8.into()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + sim.run_until(8).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); +} + +#[test] +fn clock_wait_vcd_records_each_edge_timestamp() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let three = constant(&mut module, 3, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Finish, + ]) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("wait.vcd"); + let mut sim = Simulation::from_frontend(module.finish()) + .vcd(&path) + .build() + .unwrap(); + sim.run_until(20).unwrap(); + sim.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + for time in [2, 4, 6, 8, 10, 12] { + assert!( + text.lines().any(|line| line == format!("#{time}")), + "missing timestamp {time}: {text}" + ); + } +} From fc0ee77bf79452b2e3207c84544c9644825dcc82 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 07:30:19 +0900 Subject: [PATCH 04/42] test(runtime): reject progress before a failed clock edge --- crates/celox/src/simulation.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 0afe586af71..4547ad70278 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1286,6 +1286,24 @@ mod clock_wait_tests { mod process_review_tests { use super::*; + fn check_failed_batch(mut sim: Simulator) { + let event = sim.event("clk"); + let (completed, result) = SimulationExecutor::tick_many(&mut sim, event, 10); + assert_eq!(completed, 0); + assert!(result.is_err()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + } + + #[test] + fn failed_pre_edge_comb_does_not_complete_a_clock_tick() { + let source = "module Top(input bit clk, input bit ok, output bit q); always_comb assert(ok) else $fatal(1, \"failed comb\"); always_ff @(posedge clk) q <= 1; endmodule"; + let builder = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("batch.sv"))], "Top"); + check_failed_batch(builder().build_interpreter().unwrap()); + check_failed_batch(builder().build_cranelift().unwrap()); + check_failed_batch(builder().build_wasm().unwrap()); + } + fn check(mut sim: Simulation) { sim.run_until(2).unwrap(); assert_eq!(sim.get(sim.signal("q")), 1u8.into()); From d24a8acc42c1da22c9bbadde38800851247d15b4 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 07:58:33 +0900 Subject: [PATCH 05/42] fix(runtime): report tiered batch progress after the edge --- crates/celox/src/backend/tiered.rs | 15 ++++++--------- crates/celox/src/simulation.rs | 1 + 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index 8bce3127048..b3038c6902e 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -311,10 +311,10 @@ impl CompiledTier { count: u64, ) -> (u64, Result<(), SimulatorErrorCode>) { match self { - Self::Jit(jit) => (1, { + Self::Jit(jit) => { let event = jit.id_to_event_slice()[id]; - jit.eval_comb_apply_ff_at(event) - }), + jit.eval_comb_apply_ff_many_at(event, count) + } #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -1268,12 +1268,9 @@ impl SimBackend for TieredBackend { match &mut self.phase { Phase::Interpreting(Some(interp)) => { self.interpreted_steps = self.interpreted_steps.saturating_add(1); - ( - 1, - interp.eval_comb_apply_ff_at(super::interp::InterpEventRef::from_parts( - event.addr(), - event.id(), - )), + interp.eval_comb_apply_ff_many_at( + super::interp::InterpEventRef::from_parts(event.addr(), event.id()), + count, ) } Phase::Compiled(compiled) => { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4547ad70278..49063d17c00 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1302,6 +1302,7 @@ mod process_review_tests { check_failed_batch(builder().build_interpreter().unwrap()); check_failed_batch(builder().build_cranelift().unwrap()); check_failed_batch(builder().build_wasm().unwrap()); + check_failed_batch(builder().build_tiered().unwrap()); } fn check(mut sim: Simulation) { From fc2ed8042e5c009f9a2620bf7cd966d2384084c1 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 09:03:49 +0900 Subject: [PATCH 06/42] fix(native): version and validate process clock metadata --- crates/celox/src/backend/native/backend.rs | 99 +++++++++++++++++++ crates/celox/src/backend/native/image_file.rs | 42 +++++++- 2 files changed, 140 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index f33d80078c7..f91eb8c2b47 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -549,6 +549,40 @@ impl NativeProgramImage { if self.process_offsets.len() != self.runtime_schema.processes.len() { return Err("process kernels and their control slots disagree".into()); } + for process in &self.runtime_schema.processes { + if !self + .design + .state_objects + .get(&process.clock) + .is_some_and(|metadata| { + metadata.width == celox_design::PROCESS_CLOCK_WIDTH + && !metadata.is_4state + && metadata.array_dims.is_empty() + }) + { + return Err("a process clock control slot has an invalid state object".into()); + } + for clock in &process.clocks { + if clock.period < 2 + || !self.event_map.contains_key(&clock.signal) + || !self + .design + .state_objects + .get(&clock.signal) + .is_some_and(|metadata| { + metadata.width == 1 + && metadata.array_dims.is_empty() + && matches!( + metadata.kind, + celox_design::DomainKind::ClockPosedge + | celox_design::DomainKind::ClockNegedge + ) + }) + { + return Err("a process clock has an invalid event domain or period".into()); + } + } + } for counters in &self.runtime_schema.process_event_counters { if !self.event_map.contains_key(&counters.signal) { return Err("a process edge counter names an unknown event domain".into()); @@ -3284,3 +3318,68 @@ impl super::super::SimBackend for NativeBackend { bs } } + +#[cfg(test)] +mod process_metadata_tests { + use super::super::image_file::NativeImageContainerError; + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn image() -> NativeProgramImage { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let target = module.whole(q).unwrap(); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 2).unwrap(); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + crate::Simulator::from_frontend(module.finish()) + .compile_native() + .unwrap() + .into_program_image() + } + + #[test] + fn process_clock_metadata_is_checked_before_image_attachment() { + let original = image(); + original.to_container_bytes().unwrap(); + for corruption in 0..4 { + let mut broken = original.clone(); + let slots = &mut broken.runtime_schema.processes[0]; + match corruption { + 0 => slots.clocks[0].signal = slots.delay, + 1 => slots.clocks[0].period = 1, + 2 => slots.clock = slots.status, + _ => { + let signal = *broken + .design + .state_objects + .iter() + .find(|(_, metadata)| { + metadata.width == 1 && metadata.kind == celox_design::DomainKind::Other + }) + .unwrap() + .0; + let event = broken.event_map[&slots.clocks[0].signal]; + broken.event_map.insert(signal, event); + slots.clocks[0].signal = signal; + } + } + assert!( + matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + ), + "accepted corruption {corruption}" + ); + } + } +} diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 460d48c31b1..e1ee091a943 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 12; +const CONTAINER_VERSION: u16 = 13; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; @@ -261,3 +261,43 @@ fn checksum(bytes: &[u8]) -> u64 { (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME) }) } + +#[cfg(test)] +mod process_metadata_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + + fn image() -> NativeProgramImage { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let target = module.whole(q).unwrap(); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 2).unwrap(); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + crate::Simulator::from_frontend(module.finish()) + .compile_native() + .unwrap() + .into_program_image() + } + + #[test] + fn the_previous_process_schema_is_rejected_before_decoding() { + let mut bytes = image().to_container_bytes().unwrap(); + let version = bytes.len() - TRAILER_SIZE + 8; + bytes[version..version + 2].copy_from_slice(&(CONTAINER_VERSION - 1).to_le_bytes()); + assert!(matches!( + NativeProgramImage::from_container_bytes(&bytes), + Err(NativeImageContainerError::UnsupportedVersion(version)) if version == CONTAINER_VERSION - 1 + )); + } +} From b5fd626fd6248add692b4c54838e7ee5485cef4b Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 10:39:59 +0900 Subject: [PATCH 07/42] fix(runtime): honor step limits and settle clock-sensitive low phases --- crates/celox-design/src/lib.rs | 3 + .../src/symbolic/assembly.rs | 1 + crates/celox-runtime/src/simulation.rs | 3 + crates/celox/src/backend/native/backend.rs | 3 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/ir.rs | 24 +++- crates/celox/src/simulation.rs | 114 +++++++++++++++++- 7 files changed, 147 insertions(+), 3 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 0e75d1c1974..007fb4a32c9 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -382,6 +382,8 @@ pub struct RuntimeSchema { /// derived from the other state, so state files recompute rather than /// compare them. pub comb_writes: HashSet, + /// Combinational execution reads a clock, so both phases must settle. + pub clock_phase_sensitive_comb: bool, /// Dead store elimination policy the program was compiled with. Together /// with `live_signals` and the design it decides which combinationally /// written state the host may observe. @@ -403,6 +405,7 @@ impl Default for RuntimeSchema { testbench_read_roots: HashSet::default(), rtl_writes: HashSet::default(), comb_writes: HashSet::default(), + clock_phase_sensitive_comb: false, dead_store_policy: DeadStorePolicy::Off, live_signals: HashSet::default(), processes: Vec::new(), diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 4e44ca9c6d1..a76f739ca21 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1430,6 +1430,7 @@ pub fn schedule_symbolic_rtl( testbench_read_roots: process_read_roots, rtl_writes, comb_writes: Default::default(), + clock_phase_sensitive_comb: false, dead_store_policy: Default::default(), live_signals: Default::default(), processes: process_slots, diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 56c221a08ef..bfe3d9aea95 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -422,6 +422,9 @@ impl SimulationState { let Some(current_time) = self.next_event_time() else { return Ok(None); }; + if current_time > limit { + return Ok(None); + } let mut events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index f91eb8c2b47..245f6ad5f80 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -388,6 +388,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) rtl_writes: HashSet>, /// Ordered so that the encoded image does not depend on hash order. pub(crate) comb_writes: std::collections::BTreeSet, + pub(crate) clock_phase_sensitive_comb: bool, pub(crate) dead_store_policy: celox_design::DeadStorePolicy, /// Ordered so that the encoded image does not depend on hash order. pub(crate) live_signals: std::collections::BTreeSet, @@ -489,6 +490,7 @@ impl NativeProgramImage { testbench_read_roots: self.runtime_schema.testbench_read_roots.clone(), rtl_writes: self.runtime_schema.rtl_writes.clone(), comb_writes: self.runtime_schema.comb_writes.iter().copied().collect(), + clock_phase_sensitive_comb: self.runtime_schema.clock_phase_sensitive_comb, dead_store_policy: self.runtime_schema.dead_store_policy, live_signals: self.runtime_schema.live_signals.iter().copied().collect(), processes: self.runtime_schema.processes.clone(), @@ -2301,6 +2303,7 @@ fn compile_program( .iter() .copied() .collect(), + clock_phase_sensitive_comb: sir.runtime().runtime_schema.clock_phase_sensitive_comb, dead_store_policy: sir.runtime().runtime_schema.dead_store_policy, live_signals: sir .runtime() diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index e1ee091a943..79a67ec75fa 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 13; +const CONTAINER_VERSION: u16 = 14; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index ffb968f88c4..47634f6ac04 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -445,7 +445,29 @@ pub struct UnoptimizedSir { } impl UnoptimizedSir { - pub(crate) fn new(sir: SirProgram, runtime: RuntimeProgram) -> Self { + pub(crate) fn new(sir: SirProgram, mut runtime: RuntimeProgram) -> Self { + runtime.runtime_schema.clock_phase_sensitive_comb = sir + .eval_comb + .iter() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + .any(|instruction| { + if let SIRInstruction::Load(_, address, _, _) = instruction { + runtime + .design + .state_objects + .get(&address.absolute_addr()) + .is_some_and(|metadata| { + matches!( + metadata.kind, + celox_design::DomainKind::ClockPosedge + | celox_design::DomainKind::ClockNegedge + ) + }) + } else { + false + } + }); Self { sir, layout_requirements: Default::default(), diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 49063d17c00..78d63066ef9 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -120,7 +120,10 @@ impl SimulationExecutor for Simulator { } fn fused_ticks_allowed(&self) -> bool { - self.vcd_writer.is_none() && !self.components.has_scheduled_components() + self.vcd_writer.is_none() + && !self.components.has_scheduled_components() + && self.program.runtime_schema.comb_observers.is_empty() + && !self.program.runtime_schema.clock_phase_sensitive_comb } fn stage_external_event( @@ -1360,3 +1363,112 @@ mod process_review_tests { } } } + +#[cfg(test)] +mod bounded_clock_phase_tests { + use super::*; + use crate::frontend_sdk::{ + BinaryOp, Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType, + }; + + fn design() -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let enable = module.output("enable", bit).unwrap(); + let v = module.output("v", bit).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let zero = module.constant(Constant::two_state(0u8, 1).unwrap()); + let target = module.whole(enable).unwrap(); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let clock = module.read(clk).unwrap(); + let enabled = module.read(enable).unwrap(); + let previous = module.read(v).unwrap(); + let low = module.unary(UnaryOp::BitNot, clock, bit).unwrap(); + let active = module.binary(BinaryOp::And, low, enabled, bit).unwrap(); + let toggled = module.unary(UnaryOp::BitNot, previous, bit).unwrap(); + let next = module.mux(active, toggled, zero).unwrap(); + let target = module.whole(v).unwrap(); + module.assign(target, next).unwrap(); + let count = module.constant(Constant::two_state(10u8, 64).unwrap()); + module + .process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + module.finish() + } + + fn check(mut sim: Simulation) { + assert!(sim.run_until(40).is_err()); + assert_eq!(sim.time(), 2); + assert_eq!(sim.ticks(), 1); + } + + #[test] + fn low_phase_comb_failures_stop_before_later_fused_edges() { + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_cranelift() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_native() + .unwrap(), + ); + } + + #[cfg(feature = "systemverilog")] + #[test] + fn step_until_leaves_later_events_queued() { + let source = + "module Top(input bit clk, output bit q); always_ff @(posedge clk) q<=1; endmodule"; + let mut sim = + Simulation::from_sv_sources(vec![(source, std::path::Path::new("limit.sv"))], "Top") + .build() + .unwrap(); + sim.schedule("clk", 5, 1).unwrap(); + assert_eq!(sim.state.step_until(&mut sim.simulator, 4).unwrap(), None); + assert_eq!(sim.time(), 0); + assert_eq!(sim.next_event_time(), Some(5)); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!( + sim.state.step_until(&mut sim.simulator, 5).unwrap(), + Some(5) + ); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } +} From ca7e626ef858fba414396797c8592f2fdb680267 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:15:52 +0900 Subject: [PATCH 08/42] fix(runtime): reject conflicting clocks and validate edge advances atomically --- crates/celox-frontend-sdk/src/lib.rs | 11 ++++ crates/celox-runtime/src/simulation.rs | 46 +++++++++++++-- crates/celox/tests/processes.rs | 79 ++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 4 deletions(-) diff --git a/crates/celox-frontend-sdk/src/lib.rs b/crates/celox-frontend-sdk/src/lib.rs index e1b489b4928..7788bf5a355 100644 --- a/crates/celox-frontend-sdk/src/lib.rs +++ b/crates/celox-frontend-sdk/src/lib.rs @@ -877,7 +877,16 @@ impl FrontendArtifact { } // The same requirements as `ModuleBuilder::clock_period` and // `ModuleBuilder::process` put on the clocks processes wait on. + let mut declared_clocks = std::collections::BTreeSet::new(); for (clock, period) in &self.clock_periods { + if !declared_clocks.insert(clock.index()) { + let name = self + .signal(*clock) + .ok_or(BuildError::UnknownSignal(clock.index()))? + .name + .clone(); + return Err(BuildError::DuplicateClockPeriod { name }); + } let signal = self .signal(*clock) .ok_or(BuildError::UnknownSignal(clock.index()))?; @@ -1042,6 +1051,8 @@ pub enum BuildError { InvalidControlWidth { name: String }, #[error("a clock period must be at least two time units, not {period}")] InvalidClockPeriod { period: u64 }, + #[error("duplicate process-clock period for `{name}`")] + DuplicateClockPeriod { name: String }, #[error("clock `{name}` needs a period and a register it clocks before a process waits on it")] UnknownProcessClock { name: String }, #[error("process clock `{name}` also has a continuous, register or process driver")] diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 4fea4f8d3cb..6a5f43008bd 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -419,12 +419,24 @@ impl SimulationState { where E: SimulationExecutor, { + for (id, clock) in &self.tick_clocks { + if self.clock_has_waiters(*id) || clock.falling_edge.is_some() { + self.check_clock_generator(*id)?; + } + } let Some(current_time) = self.next_event_time() else { return Ok(None); }; if current_time > limit { return Ok(None); } + for (id, clock) in &self.tick_clocks { + if clock.next_edge == current_time && self.clock_has_waiters(*id) { + current_time + .checked_add(clock.period) + .ok_or_else(|| clock_overflow(*id))?; + } + } let mut events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() @@ -536,6 +548,10 @@ impl SimulationState { where E: SimulationExecutor, { + for id in due { + time.checked_add(self.tick_clocks[id].period) + .ok_or_else(|| clock_overflow(*id))?; + } // A clock that is high when its edge is due (the host or a previous // run left it so) falls first, in a round of its own: the rising // edge that counts is then a real one. @@ -564,12 +580,13 @@ impl SimulationState { rising: Vec, ) -> Result<(), SimulatorErrorCode> { for id in rising { - self.ticks += 1; let clock = self.tick_clocks.get_mut(&id).expect("a due process clock"); - clock.next_edge = time + let next_edge = time .checked_add(clock.period) .ok_or_else(|| clock_overflow(id))?; - clock.falling_edge = Some(time + clock.period - clock.period / 2); + self.ticks += 1; + clock.next_edge = next_edge; + clock.falling_edge = Some(next_edge - clock.period / 2); let resume_at = clock.next_edge; self.count_edges(id, 1, resume_at); } @@ -644,6 +661,16 @@ impl SimulationState { if count == 0 { return Ok(false); } + // If the batch's resumption cannot be represented, execute normal + // bounded edges instead. They diagnose the offending edge before it + // mutates the backend, retaining the valid earlier progress. + if count + .checked_mul(period) + .and_then(|span| time.checked_add(span)) + .is_none() + { + return Ok(false); + } // Combinational next-state logic samples the rising level of the clock. executor.backend_mut().set(signal, 1u8); let (completed, result) = executor.tick_many(event, count); @@ -670,7 +697,7 @@ impl SimulationState { .get_mut(&clock) .expect("a due process clock"); tick_clock.next_edge = next_edge; - tick_clock.falling_edge = Some(self.scheduler.time + period - period / 2); + tick_clock.falling_edge = Some(next_edge - period / 2); self.last_clock_values.insert(clock); self.count_edges(clock, completed, next_edge); } @@ -681,6 +708,16 @@ impl SimulationState { Ok(true) } + fn check_clock_generator(&self, id: usize) -> Result<(), SimulatorErrorCode> { + if self.scheduler.clocks.get(id).is_some_and(Option::is_some) { + return Err(SimulatorErrorCode::Runtime { + message: format!("process clock {id} is already driven by add_clock"), + signals: Vec::new(), + }); + } + Ok(()) + } + /// Whether any process is suspended on an event or a condition. pub fn has_waiting_processes(&self) -> bool { !self.waiting.is_empty() @@ -837,6 +874,7 @@ impl SimulationState { continue; } else { let id = clock.event.id(); + self.check_clock_generator(id)?; let tick_clock = self.tick_clocks.entry(id).or_insert_with(|| TickClock { event: clock.event, diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index e3073d7b144..4b1e9317e4d 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -1081,3 +1081,82 @@ fn clock_wait_vcd_records_each_edge_timestamp() { ); } } + +#[test] +fn overflowing_generated_edges_do_not_commit_or_credit_on_retry() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let delay = constant(&mut module, u64::MAX - 3, 64); + let one = constant(&mut module, 1, 64); + module + .process(vec![ + Statement::Delay { amount: delay }, + Statement::ClockCycles { + clock: clk, + count: one, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + assert_eq!(sim.step().unwrap(), Some(0)); + for _ in 0..2 { + let error = sim.step().unwrap_err(); + assert!( + error.to_string().contains("overflows simulation time"), + "{error}" + ); + assert_eq!(sim.get(sim.signal("count")), 0u8.into()); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + assert_eq!(sim.ticks(), 0); + } +} + +#[test] +fn periodic_and_process_generators_for_one_clock_are_rejected() { + for register_first in [true, false] { + let (mut module, clk, _) = clocked_by_process_waits(4); + let two = constant(&mut module, 2, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: two, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + if !register_first { + sim.step().unwrap(); + } + let count = sim.get(sim.signal("count")); + let ticks = sim.ticks(); + sim.add_clock("clk", 4, 0); + let error = sim.step().unwrap_err(); + assert!( + error.to_string().contains("already driven by add_clock"), + "{error}" + ); + assert_eq!(sim.get(sim.signal("count")), count); + assert_eq!(sim.ticks(), ticks); + } +} + +#[test] +fn imported_clock_periods_reject_duplicate_signal_entries() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let one = constant(&mut module, 1, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + let mut value: serde_json::Value = + serde_json::from_str(&module.finish().to_json().unwrap()).unwrap(); + let periods = value["clock_periods"].as_array_mut().unwrap(); + let mut duplicate = periods[0].clone(); + duplicate[1] = 8.into(); + periods.push(duplicate); + let error = FrontendArtifact::from_json(&value.to_string()).unwrap_err(); + assert!( + error.to_string().contains("duplicate process-clock period"), + "{error}" + ); +} From 4f46a87789271ddc3377c2014f04a8565ee7e101 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:39:18 +0900 Subject: [PATCH 09/42] fix(runtime): defer generated edges until clock wait resumptions --- crates/celox-runtime/src/simulation.rs | 38 +++++++-- crates/celox/src/simulation.rs | 112 ++++++++++++++++++++++++- 2 files changed, 140 insertions(+), 10 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 6a5f43008bd..1e7e610e93b 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -467,9 +467,10 @@ impl SimulationState { }) .map(|(id, _)| *id) .collect(); + let mut generated_events = Vec::new(); for id in &rising { let clock = &self.tick_clocks[id]; - events_to_process.push(SimEvent { + generated_events.push(SimEvent { time: current_time, event_ref: clock.event, signal: clock.signal, @@ -477,7 +478,14 @@ impl SimulationState { }); } let ready = self.take_ready_processes(current_time); - self.step_round(executor, current_time, events_to_process, ready, true)?; + self.step_round( + executor, + current_time, + events_to_process, + generated_events, + ready, + true, + )?; self.credit_rising_edges(current_time, rising)?; self.run_remaining_rounds(executor, current_time, limit)?; executor.finish_timed_step(self.scheduler.time); @@ -529,7 +537,9 @@ impl SimulationState { } break; } - if !self.step_round(executor, current_time, Vec::new(), ready, false)? && !fired { + if !self.step_round(executor, current_time, Vec::new(), Vec::new(), ready, false)? + && !fired + { break; } } @@ -570,7 +580,7 @@ impl SimulationState { rising.push(*id); } } - self.step_round(executor, time, events, Vec::new(), true)?; + self.step_round(executor, time, events, Vec::new(), Vec::new(), true)?; self.credit_rising_edges(time, rising) } @@ -628,7 +638,8 @@ impl SimulationState { // The fused kernel runs the waited-on clock's domain alone: a design // whose registers drive another clock or reset needs the scheduler's // rounds, and a clock that is high now needs its normalizing fall. - if !executor.fused_ticks_allowed() + if time > limit + || !executor.fused_ticks_allowed() || self.domain_kinds[clock] != Some(DomainKind::ClockPosedge) || !self.inactive.is_empty() || !self.waiting.is_empty() @@ -744,11 +755,11 @@ impl SimulationState { where E: SimulationExecutor, { - if self.finished || self.waiting.is_empty() { + if self.finished || self.waiting.is_empty() || self.scheduler.time > limit { return Ok(false); } let time = self.scheduler.time; - if !self.step_round(executor, time, Vec::new(), Vec::new(), false)? { + if !self.step_round(executor, time, Vec::new(), Vec::new(), Vec::new(), false)? { return Ok(false); } self.run_remaining_rounds(executor, time, limit)?; @@ -933,7 +944,7 @@ impl SimulationState { return Ok(None); } let ready = self.take_ready_processes(time); - self.step_round(executor, time, Vec::new(), ready, true)?; + self.step_round(executor, time, Vec::new(), Vec::new(), ready, true)?; // A process the settled state woke may wait for zero time: the // rounds of this time are drained, as `step` drains them. self.run_remaining_rounds(executor, time, time)?; @@ -949,7 +960,8 @@ impl SimulationState { &mut self, executor: &mut E, current_time: u64, - events_to_process: Vec>, + mut events_to_process: Vec>, + generated_events: Vec>, ready_processes: Vec, settle_idle: bool, ) -> Result @@ -1017,6 +1029,14 @@ impl SimulationState { } } + // A completed clock wait resumes before the following generated + // rising edge. Apply that edge after the ready processes, then join + // it to scheduled triggers so coincident FF domains share one batch. + for event in &generated_events { + executor.backend_mut().set(event.signal, event.next_val); + } + events_to_process.extend(generated_events); + let mut triggered_domains = BitSet::with_capacity(num_events); let mut discovered_in_this_step = BitSet::with_capacity(num_events); // Counter-recorded kernel edges survive later blocking stores that diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 5ccbe46c384..b46ff91a12e 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -531,8 +531,12 @@ impl Simulation { } /// Advance time and run until `end_time` (inclusive). As for - /// [`Self::step`], processes that a host write woke resume first. + /// [`Self::step`], processes that a host write woke resume first. A time + /// before the current time leaves the simulation unchanged. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { + if end_time < self.state.time() { + return Ok(()); + } self.settle_host_writes()?; self.state .poll_waiting_until(&mut self.simulator, end_time)?; @@ -1497,4 +1501,110 @@ mod bounded_clock_phase_tests { ); assert_eq!(sim.get(sim.signal("q")), 1u8.into()); } + + #[cfg(feature = "systemverilog")] + fn check_past_limit(mut sim: Simulation) { + sim.run_until(100).unwrap(); + let gate = sim.signal("gate"); + let seen = sim.signal("seen"); + sim.set_wide(gate, 1u8.into()); + sim.run_until(60).unwrap(); + assert_eq!(sim.time(), 100); + assert_eq!(sim.get(seen), 0u8.into()); + assert!(sim.has_waiting_processes()); + sim.run_until(100).unwrap(); + assert_eq!(sim.get(seen), 1u8.into()); + } + + #[cfg(feature = "systemverilog")] + #[test] + fn past_run_limit_does_not_poll_waiters_or_rewind_time() { + let source = "module Top(input bit gate, output bit seen); initial begin wait(gate); seen=1; end endmodule"; + let builder = + || Simulation::from_sv_sources(vec![(source, std::path::Path::new("past.sv"))], "Top"); + check_past_limit(builder().build_interpreter().unwrap()); + check_past_limit(builder().build_cranelift().unwrap()); + check_past_limit(builder().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_past_limit(builder().build_native().unwrap()); + } + + fn coincident_design() -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let byte = ValueType::bits(8).unwrap(); + let mut module = ModuleBuilder::new("Coincident").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let other = module.internal("other", bit).unwrap(); + let count = module.output("count", byte).unwrap(); + let sampled = module.output("sampled", byte).unwrap(); + let seen = module.output("seen", bit).unwrap(); + let count_expr = module.read(count).unwrap(); + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + let two = module.constant(Constant::two_state(2u8, 8).unwrap()); + let next = module.binary(BinaryOp::Add, count_expr, one, byte).unwrap(); + let target = module.whole(count).unwrap(); + module + .register(target, next, clk, Edge::Posedge, None, None) + .unwrap(); + let target = module.whole(sampled).unwrap(); + module + .register(target, count_expr, other, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let target = module.whole(seen).unwrap(); + let value = module.read(clk).unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: one, + }, + Statement::Assign { target, value }, + ]) + .unwrap(); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: two, + }]) + .unwrap(); + module.finish() + } + + fn check_coincident(mut sim: Simulation) { + sim.schedule("other", 4, 1).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(sim.get(sim.signal("sampled")), 1u8.into()); + assert_eq!(sim.ticks(), 2); + sim.run_until(2).unwrap(); + assert_eq!(sim.time(), 4); + assert_eq!(sim.ticks(), 2); + } + + #[test] + fn clock_wait_resumes_before_coincident_generated_edge() { + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_interpreter() + .unwrap(), + ); + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_cranelift() + .unwrap(), + ); + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_native() + .unwrap(), + ); + } } From b57cd015a79ca5a162cc7b23191c856fe8260f8b Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:58:37 +0900 Subject: [PATCH 10/42] fix(runtime): retain generated clock progress across phase failures --- crates/celox-runtime/src/simulation.rs | 55 ++++++++++-- crates/celox/src/backend/native/backend.rs | 33 ++++++- crates/celox/src/simulation.rs | 100 +++++++++++++++++++++ 3 files changed, 179 insertions(+), 9 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 61c1487c850..266c8fa5e33 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -226,6 +226,8 @@ impl PeriodicEventKey { /// Backend-independent state and execution rules for timed simulation. pub struct SimulationState { scheduler: Scheduler, + round_published_domains: BitSet, + round_evaluated: bool, periodic_events: FxHashMap, last_clock_values: BitSet, topo_signals: Vec<(SignalRef, usize, usize)>, @@ -339,6 +341,8 @@ impl SimulationState { ticks: 0, inactive: BTreeSet::new(), finished: false, + round_published_domains: BitSet::new(), + round_evaluated: false, } } @@ -445,9 +449,10 @@ impl SimulationState { } else { Vec::new() }; - for clock in self.tick_clocks.values_mut() { + let mut falling = Vec::new(); + for (id, clock) in &self.tick_clocks { if clock.falling_edge == Some(current_time) { - clock.falling_edge = None; + falling.push(*id); events_to_process.push(SimEvent { time: current_time, event_ref: clock.event, @@ -478,15 +483,15 @@ impl SimulationState { }); } let ready = self.take_ready_processes(current_time); - self.step_round( + let result = self.step_round( executor, current_time, events_to_process, generated_events, ready, true, - )?; - self.credit_rising_edges(current_time, rising)?; + ); + self.finish_clock_round(current_time, rising, &falling, result)?; self.run_remaining_rounds(executor, current_time, limit)?; executor.finish_timed_step(self.scheduler.time); // Fused ticks may have moved the time on. @@ -580,8 +585,37 @@ impl SimulationState { rising.push(*id); } } - self.step_round(executor, time, events, Vec::new(), Vec::new(), true)?; - self.credit_rising_edges(time, rising) + let result = self.step_round(executor, time, events, Vec::new(), Vec::new(), true); + self.finish_clock_round(time, rising, &[], result) + } + + fn finish_clock_round( + &mut self, + time: u64, + rising: Vec, + falling: &[usize], + result: Result, + ) -> Result<(), SimulatorErrorCode> { + let committed = rising + .into_iter() + .filter(|id| { + result.is_ok() + || self + .round_published_domains + .contains(self.event_info[*id].canonical_id) + }) + .collect(); + self.credit_rising_edges(time, committed)?; + if self.round_evaluated { + for id in falling { + self.tick_clocks + .get_mut(id) + .expect("a pending process-clock fall") + .falling_edge = None; + self.last_clock_values.remove(*id); + } + } + result.map(|_| ()) } fn credit_rising_edges( @@ -598,6 +632,7 @@ impl SimulationState { clock.next_edge = next_edge; clock.falling_edge = Some(next_edge - clock.period / 2); let resume_at = clock.next_edge; + self.last_clock_values.insert(id); self.count_edges(id, 1, resume_at); } Ok(()) @@ -969,6 +1004,8 @@ impl SimulationState { E: SimulationExecutor, { self.scheduler.time = current_time; + self.round_published_domains.make_empty(); + self.round_evaluated = false; // Keep periodic provenance private so the public SimEvent shape stays // stable. Consume matching sidecar counts before fallible work so an @@ -1064,6 +1101,7 @@ impl SimulationState { } executor.eval_comb()?; + self.round_evaluated = true; if track_stable_edges { // Combinational settling before an active scheduled source domain // commits may expose transient derived-clock edges. In that case, @@ -1104,6 +1142,7 @@ impl SimulationState { any_new_outer_loop_trigger = true; executor.stage_external_event(event, current_time)?; executor.eval_apply_ff_at(event)?; + self.round_published_domains.insert(info.canonical_id); executor.fire_external_event(event, current_time)?; executor.eval_comb()?; if track_stable_edges { @@ -1139,6 +1178,7 @@ impl SimulationState { } else if let Some(event) = info.eval_ff_event { executor.stage_external_event(event, current_time)?; executor.eval_apply_ff_at(event)?; + self.round_published_domains.insert(info.canonical_id); } else { unreachable!( "FF trigger discovered without a corresponding execution unit" @@ -1213,6 +1253,7 @@ impl SimulationState { for id in &newly_triggered { if let Some(event) = self.event_info[*id].apply_event { executor.apply_ff_at(event)?; + self.round_published_domains.insert(*id); } } for id in &newly_triggered { diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 245f6ad5f80..08cf7a84be3 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -551,6 +551,7 @@ impl NativeProgramImage { if self.process_offsets.len() != self.runtime_schema.processes.len() { return Err("process kernels and their control slots disagree".into()); } + let mut process_clock_periods = fxhash::FxHashMap::default(); for process in &self.runtime_schema.processes { if !self .design @@ -583,6 +584,12 @@ impl NativeProgramImage { { return Err("a process clock has an invalid event domain or period".into()); } + let event = self.event_map[&clock.signal].id; + if let Some(previous) = process_clock_periods.insert(event, clock.period) + && previous != clock.period + { + return Err("process clocks for one event have conflicting periods".into()); + } } } for counters in &self.runtime_schema.process_event_counters { @@ -3046,7 +3053,10 @@ impl super::super::SimBackend for NativeBackend { if count == 0 { return (0, Ok(())); } - return (1, self.eval_comb_apply_ff_at(event)); + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } + return (1, self.eval_apply_ff_at(event)); } if self.compiled.options.native_tick_loop { let (executed, result) = self.call_func_many_timed(event.comb_apply_func, count); @@ -3060,11 +3070,14 @@ impl super::super::SimBackend for NativeBackend { } else if count == 0 { (0, Ok(())) } else { + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } if fused_sequential { self.lane_selectors .advance(super::super::lanes::LaneKernelSlot::Fused(event.id), 1); } - (1, self.call_func_timed(event.comb_apply_func)) + (1, self.eval_apply_ff_at(event)) } } @@ -3338,6 +3351,12 @@ mod process_metadata_tests { .register(target, one, clk, Edge::Posedge, None, None) .unwrap(); module.clock_period(clk, 2).unwrap(); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); module .process(vec![Statement::ClockCycles { clock: clk, @@ -3385,4 +3404,14 @@ mod process_metadata_tests { ); } } + + #[test] + fn process_clock_periods_must_agree_across_slot_tables() { + let mut broken = image(); + broken.to_container_bytes().unwrap(); + broken.runtime_schema.processes[1].clocks[0].period = 4; + assert!( + matches!(broken.to_container_bytes(), Err(NativeImageContainerError::InvalidImage(message)) if message.contains("conflicting periods")) + ); + } } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 9ca6757ebf2..c1b178d1638 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1336,6 +1336,8 @@ mod process_review_tests { check_failed_batch(builder().build_cranelift().unwrap()); check_failed_batch(builder().build_wasm().unwrap()); check_failed_batch(builder().build_tiered().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_failed_batch(builder().build_native().unwrap()); } fn check(mut sim: Simulation) { @@ -1636,3 +1638,101 @@ mod ff_counter_regressions { check(Simulation::new(builder().build_native().unwrap())); } } + +#[cfg(test)] +mod clock_failure_progress_tests { + use super::*; + use crate::frontend_sdk::{ + BinaryOp, Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType, + }; + + fn design(on_rising: bool) -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(32).unwrap(); + let mut m = ModuleBuilder::new("Progress").unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let bad = m.input("bad", bit).unwrap(); + let count = m.output("count", word).unwrap(); + let falls = m.output("falls", word).unwrap(); + let fallclk = m.internal("fallclk", bit).unwrap(); + let clk_expr = m.read(clk).unwrap(); + let low = m.unary(UnaryOp::BitNot, clk_expr, bit).unwrap(); + let count_expr = m.read(count).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 32).unwrap()); + let running = m.binary(BinaryOp::NotEqual, count_expr, zero, bit).unwrap(); + let fall_phase = m.binary(BinaryOp::And, low, running, bit).unwrap(); + let target = m.whole(fallclk).unwrap(); + m.assign(target, fall_phase).unwrap(); + for (signal, clock) in [(count, clk), (falls, fallclk)] { + let value = m.read(signal).unwrap(); + let one = m.constant(Constant::two_state(1u8, 32).unwrap()); + let next = m.binary(BinaryOp::Add, value, one, word).unwrap(); + let target = m.whole(signal).unwrap(); + m.register(target, next, clock, Edge::Posedge, None, None) + .unwrap(); + } + let v = m.output("v", bit).unwrap(); + let phase = m.read(clk).unwrap(); + let phase = if on_rising { + phase + } else { + m.unary(UnaryOp::BitNot, phase, bit).unwrap() + }; + let bad = m.read(bad).unwrap(); + let active = m.binary(BinaryOp::And, phase, bad, bit).unwrap(); + let count = m.read(count).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 32).unwrap()); + let nonzero = m.binary(BinaryOp::NotEqual, count, zero, bit).unwrap(); + let active = m.binary(BinaryOp::And, active, nonzero, bit).unwrap(); + let previous = m.read(v).unwrap(); + let toggled = m.unary(UnaryOp::BitNot, previous, bit).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 1).unwrap()); + let next = m.mux(active, toggled, zero).unwrap(); + let target = m.whole(v).unwrap(); + m.assign(target, next).unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(2u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + m.finish() + } + + fn check(mut sim: Simulation, on_rising: bool) { + sim.set_wide(sim.signal("bad"), 1u8.into()); + let time = if on_rising { 0 } else { 2 }; + assert!(sim.run_until(time).is_err()); + assert_eq!(sim.time(), time); + assert_eq!(sim.ticks(), 1); + let count = sim.signal("count"); + let falls = sim.signal("falls"); + assert_eq!(sim.simulator.backend.get_as::(count), 1); + assert_eq!(sim.simulator.backend.get_as::(falls), 0); + assert_eq!(sim.next_event_time(), Some(2)); + sim.set_wide(sim.signal("bad"), 0u8.into()); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(falls), 1u32.into()); + assert_eq!(sim.get(count), 1u32.into()); + assert_eq!(sim.ticks(), 1); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(count), 2u32.into()); + assert_eq!(sim.ticks(), 2); + } + + #[test] + fn generated_clock_failures_retain_committed_and_pending_phases() { + for on_rising in [true, false] { + let builder = || { + Simulation::from_frontend(design(on_rising)).true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check(builder().build_interpreter().unwrap(), on_rising); + check(builder().build_cranelift().unwrap(), on_rising); + check(builder().build_wasm().unwrap(), on_rising); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(builder().build_native().unwrap(), on_rising); + } + } +} From 75968b639f7ab0c2f42c035e97c7e6d2f68fcabe Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 12:11:00 +0900 Subject: [PATCH 11/42] test(native): check pre-edge failure progress with lane kernels --- crates/celox/src/backend/native/backend.rs | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 08cf7a84be3..31ed0c01f6e 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -3414,4 +3414,32 @@ mod process_metadata_tests { matches!(broken.to_container_bytes(), Err(NativeImageContainerError::InvalidImage(message)) if message.contains("conflicting periods")) ); } + + #[test] + fn lane_ticks_report_zero_progress_for_pre_edge_comb_failure() { + use crate::backend::SimBackend; + let source = r#"module Top(clk: input clock, ok: input logic, q: output logic, a: output logic, b: output logic, c: output logic, v: output logic) { + assign v = if ok ? 1'd0 : ~v; + always_ff(clk) { q=1; } + always_ff(clk) { a=1; } + always_ff(clk) { b=1; } + always_ff(clk) { c=1; } + }"#; + let mut sim = crate::Simulator::builder(source, "Top") + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .threads(4) + .parallel_partition(crate::ParallelPartition::Always) + .build_native() + .unwrap(); + let event = sim.event("clk"); + assert!(sim.backend.lane_event_kernel(event)); + let (completed, result) = sim.backend.eval_comb_apply_ff_many_at(event, 10); + assert_eq!(completed, 0); + assert!(result.is_err()); + assert_eq!(sim.backend.get_as::(sim.signal("q")), 0); + } } From 3265fda34362eaba91071183f4dee1df02fb4a06 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 13:13:14 +0900 Subject: [PATCH 12/42] fix(runtime): reject scheduled clock drivers and retry unpublished falls --- crates/celox-runtime/src/simulation.rs | 62 +++++++++++-- crates/celox/src/simulation.rs | 120 ++++++++++++++++++++++++- crates/celox/tests/processes.rs | 19 ++++ 3 files changed, 194 insertions(+), 7 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 266c8fa5e33..cc184ffa7ec 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -227,6 +227,9 @@ impl PeriodicEventKey { pub struct SimulationState { scheduler: Scheduler, round_published_domains: BitSet, + round_triggered_domains: BitSet, + scheduled_clock_drives: BitSet, + scheduled_clock_time: u64, round_evaluated: bool, periodic_events: FxHashMap, last_clock_values: BitSet, @@ -342,6 +345,9 @@ impl SimulationState { inactive: BTreeSet::new(), finished: false, round_published_domains: BitSet::new(), + round_triggered_domains: BitSet::new(), + scheduled_clock_drives: BitSet::new(), + scheduled_clock_time: 0, round_evaluated: false, } } @@ -449,6 +455,14 @@ impl SimulationState { } else { Vec::new() }; + self.scheduled_clock_drives.make_empty(); + self.scheduled_clock_time = current_time; + for event in &events_to_process { + self.scheduled_clock_drives.insert(event.event_ref.id()); + if let Some(id) = self.signal_to_id.get(&event.signal) { + self.scheduled_clock_drives.insert(*id); + } + } let mut falling = Vec::new(); for (id, clock) in &self.tick_clocks { if clock.falling_edge == Some(current_time) { @@ -465,10 +479,12 @@ impl SimulationState { .tick_clocks .iter() .filter(|(id, clock)| { - !events_to_process.is_empty() + let high = executor.backend().get_as::(clock.signal) != 0; + let pending_rise = high && !self.last_clock_values.contains(**id); + (!events_to_process.is_empty() || pending_rise) && clock.next_edge == current_time && self.clock_has_waiters(**id) - && executor.backend().get_as::(clock.signal) == 0 + && (!high || pending_rise) }) .map(|(id, _)| *id) .collect(); @@ -606,7 +622,12 @@ impl SimulationState { }) .collect(); self.credit_rising_edges(time, committed)?; - if self.round_evaluated { + if result.is_ok() + || (self.round_evaluated + && self + .round_triggered_domains + .is_subset(&self.round_published_domains)) + { for id in falling { self.tick_clocks .get_mut(id) @@ -761,6 +782,19 @@ impl SimulationState { signals: Vec::new(), }); } + if (self.scheduled_clock_time == self.scheduler.time + && self.scheduled_clock_drives.contains(id)) + || self + .scheduler + .event_queue + .iter() + .any(|event| event.event_ref.id() == id) + { + return Err(SimulatorErrorCode::Runtime { + message: format!("process clock {id} is already driven by schedule"), + signals: Vec::new(), + }); + } Ok(()) } @@ -1005,6 +1039,7 @@ impl SimulationState { { self.scheduler.time = current_time; self.round_published_domains.make_empty(); + self.round_triggered_domains.make_empty(); self.round_evaluated = false; // Keep periodic provenance private so the public SimEvent shape stays @@ -1140,9 +1175,10 @@ impl SimulationState { discovered_in_this_step.insert(single_id); triggered_domains.insert(info.canonical_id); any_new_outer_loop_trigger = true; + self.round_triggered_domains.insert(info.canonical_id); executor.stage_external_event(event, current_time)?; executor.eval_apply_ff_at(event)?; - self.round_published_domains.insert(info.canonical_id); + self.record_domain_publication(executor.backend(), info.canonical_id); executor.fire_external_event(event, current_time)?; executor.eval_comb()?; if track_stable_edges { @@ -1168,6 +1204,7 @@ impl SimulationState { triggered_domains.insert(info.canonical_id); newly_triggered.push(info.canonical_id); + self.round_triggered_domains.insert(info.canonical_id); let before = self.event_counter_values(executor.backend()); if let Some(event) = info.eval_only_event { executor.stage_external_event( @@ -1178,7 +1215,7 @@ impl SimulationState { } else if let Some(event) = info.eval_ff_event { executor.stage_external_event(event, current_time)?; executor.eval_apply_ff_at(event)?; - self.round_published_domains.insert(info.canonical_id); + self.record_domain_publication(executor.backend(), info.canonical_id); } else { unreachable!( "FF trigger discovered without a corresponding execution unit" @@ -1253,7 +1290,7 @@ impl SimulationState { for id in &newly_triggered { if let Some(event) = self.event_info[*id].apply_event { executor.apply_ff_at(event)?; - self.round_published_domains.insert(*id); + self.record_domain_publication(executor.backend(), *id); } } for id in &newly_triggered { @@ -1327,6 +1364,19 @@ impl SimulationState { Ok(true) } + fn record_domain_publication(&mut self, backend: &B, canonical: usize) { + self.round_published_domains.insert(canonical); + for (signal, id, _) in &self.topo_signals { + if *id != usize::MAX && self.event_info[*id].canonical_id == canonical { + if backend.get_as::(*signal) != 0 { + self.last_clock_values.insert(*id); + } else { + self.last_clock_values.remove(*id); + } + } + } + } + fn event_counter_values(&self, backend: &B) -> Vec<(u32, u32)> { self.process_event_counters .iter() diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index c1b178d1638..1ca07bf19bd 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1647,9 +1647,14 @@ mod clock_failure_progress_tests { }; fn design(on_rising: bool) -> crate::frontend_sdk::FrontendArtifact { + module_design(on_rising).0.finish() + } + + fn module_design(on_rising: bool) -> (ModuleBuilder, crate::frontend_sdk::SignalId) { let bit = ValueType::bits(1).unwrap(); let word = ValueType::bits(32).unwrap(); let mut m = ModuleBuilder::new("Progress").unwrap(); + let other = m.internal("other", bit).unwrap(); let clk = m.internal("clk", bit).unwrap(); let bad = m.input("bad", bit).unwrap(); let count = m.output("count", word).unwrap(); @@ -1694,7 +1699,7 @@ mod clock_failure_progress_tests { let count = m.constant(Constant::two_state(2u8, 64).unwrap()); m.process(vec![Statement::ClockCycles { clock: clk, count }]) .unwrap(); - m.finish() + (m, other) } fn check(mut sim: Simulation, on_rising: bool) { @@ -1735,4 +1740,117 @@ mod clock_failure_progress_tests { check(builder().build_native().unwrap(), on_rising); } } + + struct FailingExecutor { + sim: Simulator, + fail: Option, + in_apply: bool, + } + impl SimulationExecutor for FailingExecutor { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(&mut self.sim) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(&mut self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + if !self.in_apply && self.fail == Some(event.id()) { + return Err(RuntimeErrorCode::Runtime { + message: "injected FF failure".into(), + signals: Vec::new(), + }); + } + SimulationExecutor::eval_only_ff_at(&mut self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + if self.in_apply && self.fail == Some(event.id()) { + return Err(RuntimeErrorCode::Runtime { + message: "injected publication failure".into(), + signals: Vec::new(), + }); + } + SimulationExecutor::apply_ff_at(&mut self.sim, event) + } + fn fused_ticks_allowed(&self) -> bool { + false + } + } + + fn coincident_design() -> crate::frontend_sdk::FrontendArtifact { + let (mut m, other) = module_design(false); + let word = ValueType::bits(32).unwrap(); + let count = m.output("other_count", word).unwrap(); + let current = m.read(count).unwrap(); + let one = m.constant(Constant::two_state(1u8, 32).unwrap()); + let next = m.binary(BinaryOp::Add, current, one, word).unwrap(); + let target = m.whole(count).unwrap(); + m.register(target, next, other, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(other, 2).unwrap(); + let two = m.constant(Constant::two_state(2u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: other, + count: two, + }]) + .unwrap(); + m.finish() + } + + fn check_coincident_failure(sim: Simulator, in_apply: bool) { + let mut state = simulation_state(&sim); + let mut executor = FailingExecutor { + sim, + fail: None, + in_apply, + }; + assert_eq!(state.step_until(&mut executor, 0).unwrap(), Some(0)); + let initial_ticks = state.ticks(); + assert_eq!(state.step_until(&mut executor, 1).unwrap(), Some(1)); + let failed = executor + .sim + .event(if in_apply { "fallclk" } else { "other" }); + executor.fail = Some(failed.id()); + assert!(state.step_until(&mut executor, 2).is_err()); + assert_eq!(state.ticks(), initial_ticks + u64::from(in_apply)); + let falls = executor.sim.signal("falls"); + assert_eq!(executor.backend().get_as::(falls), 0); + assert_eq!(state.next_event_time(), Some(2)); + executor.fail = None; + assert_eq!(state.step_until(&mut executor, 2).unwrap(), Some(2)); + assert_eq!(executor.backend().get_as::(falls), 1); + assert_eq!(state.ticks(), initial_ticks + 1); + assert_eq!( + executor + .backend() + .get_as::(executor.sim.signal("other_count")), + 2 + ); + } + + #[test] + fn coincident_ff_failures_do_not_discard_unpublished_falling_domains() { + for in_apply in [false, true] { + let builder = || { + Simulator::from_frontend(coincident_design()) + .emit_triggers() + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check_coincident_failure(builder().build_interpreter().unwrap(), in_apply); + check_coincident_failure(builder().build_cranelift().unwrap(), in_apply); + check_coincident_failure(builder().build_wasm().unwrap(), in_apply); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_coincident_failure(builder().build_native().unwrap(), in_apply); + } + } } diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 4b1e9317e4d..4b603681470 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -1160,3 +1160,22 @@ fn imported_clock_periods_reject_duplicate_signal_entries() { "{error}" ); } + +#[test] +fn one_shot_events_conflict_with_new_process_clock_generators() { + for time in [0, 4] { + let (mut m, clk, _) = clocked_by_process_waits(4); + let one = constant(&mut m, 1, 64); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(m.finish()).build().unwrap(); + sim.schedule("clk", time, 1).unwrap(); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(sim.ticks(), 0); + assert_eq!(sim.get(sim.signal("count")), 0u32.into()); + } +} From 9692f11c613cf66bb1166aeb724a7faa016b0bfe Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 13:50:30 +0900 Subject: [PATCH 13/42] fix(runtime): restore same-time clock drive provenance --- crates/celox-runtime/src/simulation.rs | 15 ++++++- crates/celox/src/simulation.rs | 56 ++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index e823a83c16c..69a8dda344f 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -455,8 +455,10 @@ impl SimulationState { } else { Vec::new() }; - self.scheduled_clock_drives.make_empty(); - self.scheduled_clock_time = current_time; + if self.scheduled_clock_time != current_time { + self.scheduled_clock_drives.make_empty(); + self.scheduled_clock_time = current_time; + } for event in &events_to_process { self.scheduled_clock_drives.insert(event.event_ref.id()); if let Some(id) = self.signal_to_id.get(&event.signal) { @@ -1524,6 +1526,8 @@ impl SimulationState { done: self.done.clone(), ticks: self.ticks, inactive: self.inactive.clone(), + scheduled_clock_drives: self.scheduled_clock_drives.clone(), + scheduled_clock_time: self.scheduled_clock_time, finished: self.finished, } } @@ -1577,6 +1581,9 @@ impl SimulationState { self.done.clone_from(&snapshot.done); self.ticks = snapshot.ticks; self.inactive.clone_from(&snapshot.inactive); + self.scheduled_clock_drives + .clone_from(&snapshot.scheduled_clock_drives); + self.scheduled_clock_time = snapshot.scheduled_clock_time; self.finished = snapshot.finished; Ok(()) } @@ -1754,6 +1761,8 @@ pub struct SimulationSnapshot { done: BTreeSet, ticks: u64, inactive: BTreeSet, + scheduled_clock_drives: BitSet, + scheduled_clock_time: u64, finished: bool, } @@ -1772,6 +1781,8 @@ impl Clone for SimulationSnapshot { done: self.done.clone(), ticks: self.ticks, inactive: self.inactive.clone(), + scheduled_clock_drives: self.scheduled_clock_drives.clone(), + scheduled_clock_time: self.scheduled_clock_time, finished: self.finished, } } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 1ca07bf19bd..513ecb463c9 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1854,3 +1854,59 @@ mod clock_failure_progress_tests { } } } + +#[cfg(test)] +mod clock_provenance_checkpoint_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", ValueType::bits(1).unwrap()).unwrap(); + let q = m.output("q", ValueType::bits(1).unwrap()).unwrap(); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + let value = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(q).unwrap(); + m.register(target, value, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + m.process(vec![ + Statement::Delay { amount: one }, + Statement::ClockCycles { + clock: clk, + count: one, + }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + sim.schedule("clk", 0, 1).unwrap(); + assert_eq!(sim.step().unwrap(), Some(0)); + let checkpoint = sim.checkpoint().unwrap(); + sim.run_until(2).unwrap(); + sim.restore(&checkpoint).unwrap(); + // Model a host waking the suspended process at the restored timestamp. + let mut parts = sim.state.export_schedule(&sim.simulator.backend); + parts.process_wakeups = vec![(0, 0)]; + sim.state.import_schedule(parts); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(sim.ticks(), 0); + } + #[test] + fn restored_clock_drive_provenance_rejects_a_same_time_generator() { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} From 944ee21b4ca8108ba69af1650c97a6e8355f842b Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 15:15:01 +0900 Subject: [PATCH 14/42] fix(runtime): batch newly activated clocks with coincident domains --- crates/celox-runtime/src/simulation.rs | 54 +++++++++++++++++++++++--- crates/celox/tests/processes.rs | 49 +++++++++++++++++++++++ 2 files changed, 97 insertions(+), 6 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index f31fc64158f..0a27c8ddb81 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -231,6 +231,7 @@ pub struct SimulationState { scheduled_clock_drives: BitSet, scheduled_clock_time: u64, round_evaluated: bool, + round_new_rising: BitSet, periodic_events: FxHashMap, last_clock_values: BitSet, topo_signals: Vec<(SignalRef, usize, usize)>, @@ -351,6 +352,7 @@ impl SimulationState { scheduled_clock_drives: BitSet::new(), scheduled_clock_time: 0, round_evaluated: false, + round_new_rising: BitSet::new(), } } @@ -571,9 +573,11 @@ impl SimulationState { } break; } - if !self.step_round(executor, current_time, Vec::new(), Vec::new(), ready, false)? - && !fired - { + let result = + self.step_round(executor, current_time, Vec::new(), Vec::new(), ready, false); + let progressed = result.as_ref().is_ok_and(|ran| *ran); + self.finish_clock_round(current_time, Vec::new(), &[], result)?; + if !progressed && !fired { break; } } @@ -625,6 +629,10 @@ impl SimulationState { falling: &[usize], result: Result, ) -> Result<(), SimulatorErrorCode> { + let rising: BTreeSet<_> = rising + .into_iter() + .chain(self.round_new_rising.iter()) + .collect(); let committed = rising .into_iter() .filter(|id| { @@ -841,7 +849,10 @@ impl SimulationState { return Ok(false); } let time = self.scheduler.time; - if !self.step_round(executor, time, Vec::new(), Vec::new(), Vec::new(), false)? { + let result = self.step_round(executor, time, Vec::new(), Vec::new(), Vec::new(), false); + let progressed = result.as_ref().is_ok_and(|ran| *ran); + self.finish_clock_round(time, Vec::new(), &[], result)?; + if !progressed { return Ok(false); } self.run_remaining_rounds(executor, time, limit)?; @@ -1026,7 +1037,8 @@ impl SimulationState { return Ok(None); } let ready = self.take_ready_processes(time); - self.step_round(executor, time, Vec::new(), Vec::new(), ready, true)?; + let result = self.step_round(executor, time, Vec::new(), Vec::new(), ready, true); + self.finish_clock_round(time, Vec::new(), &[], result)?; // A process the settled state woke may wait for zero time: the // rounds of this time are drained, as `step` drains them. self.run_remaining_rounds(executor, time, time)?; @@ -1043,7 +1055,7 @@ impl SimulationState { executor: &mut E, current_time: u64, mut events_to_process: Vec>, - generated_events: Vec>, + mut generated_events: Vec>, ready_processes: Vec, settle_idle: bool, ) -> Result @@ -1054,6 +1066,7 @@ impl SimulationState { self.round_published_domains.make_empty(); self.round_triggered_domains.make_empty(); self.round_evaluated = false; + self.round_new_rising.make_empty(); // Keep periodic provenance private so the public SimEvent shape stays // stable. Consume matching sidecar counts before fallible work so an @@ -1114,6 +1127,35 @@ impl SimulationState { } } + // Ready processes may activate a clock at this timestamp. Join it + // to existing source events before any coincident FF domain commits. + // With no other event, retain the later fused-tick path. + if !events_to_process.is_empty() || !process_driven.is_empty() { + for (id, clock) in &self.tick_clocks { + if clock.next_edge == current_time + && self.clock_has_waiters(*id) + && executor.backend().get_as::(clock.signal) == 0 + && !events_to_process + .iter() + .any(|event| event.signal == clock.signal && event.next_val == 0) + && !generated_events + .iter() + .any(|event| event.event_ref.id() == *id) + { + current_time + .checked_add(clock.period) + .ok_or_else(|| clock_overflow(*id))?; + generated_events.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 1, + }); + self.round_new_rising.insert(*id); + } + } + } + // A completed clock wait resumes before the following generated // rising edge. Apply that edge after the ready processes, then join // it to scheduled triggers so coincident FF domains share one batch. diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 4b603681470..44b0ba311d4 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -1179,3 +1179,52 @@ fn one_shot_events_conflict_with_new_process_clock_generators() { assert_eq!(sim.get(sim.signal("count")), 0u32.into()); } } + +#[test] +fn newly_started_process_clocks_share_scheduled_domains_pre_edge_state() { + fn design() -> FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let a = m.internal("a", bit).unwrap(); + let b = m.input("b", bit).unwrap(); + let qa = m.output("qa", bit).unwrap(); + let qb = m.output("qb", bit).unwrap(); + let one = constant(&mut m, 1, 1); + let qb_read = m.read(qb).unwrap(); + let qa_target = m.whole(qa).unwrap(); + let qb_target = m.whole(qb).unwrap(); + m.register(qa_target, qb_read, a, Edge::Posedge, None, None) + .unwrap(); + m.register(qb_target, one, b, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(a, 4).unwrap(); + let four = constant(&mut m, 4, 64); + let count = constant(&mut m, 1, 64); + m.process(vec![ + Statement::Delay { amount: four }, + Statement::ClockCycles { clock: a, count }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + sim.schedule("b", 4, 1).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("qb")), 1u8.into()); + assert_eq!(sim.get(sim.signal("qa")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); +} From 737167d8dbeddbcef2d16c10cb3016bb48fa7550 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 16:36:44 +0900 Subject: [PATCH 15/42] fix(runtime): retain clock progress and native image invariants --- crates/celox-design/src/lib.rs | 2 +- crates/celox-runtime/src/simulation.rs | 8 ++- crates/celox/src/backend/native/backend.rs | 56 ++++++++++++++- crates/celox/src/simulation.rs | 83 ++++++++++++++++++++++ 4 files changed, 145 insertions(+), 4 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index a1b66f5e54d..7eceaa20acc 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -393,7 +393,7 @@ pub struct RuntimeSchema { /// Control slots of the process kernels, in kernel order. pub processes: Vec>, pub process_event_counters: Vec>, - /// FF evaluation domains that publish blocking stores into active state. + /// FF domains with blocking stores or finish effects in the active region. pub active_ff_events: HashSet, } diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 9ee1a955ac8..149ead4d618 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -639,7 +639,7 @@ impl SimulationState { let committed = rising .into_iter() .filter(|id| { - result.is_ok() + (result.is_ok() && !self.finished) || self .round_published_domains .contains(self.event_info[*id].canonical_id) @@ -1130,6 +1130,12 @@ impl SimulationState { } } + if self.finished { + // Suppress generated edges queued before a ready process finished. + self.round_new_rising.make_empty(); + return Ok(false); + } + // Ready processes may activate a clock at this timestamp. Join it // to existing source events before any coincident FF domain commits. // With no other event, retain the later fused-tick path. diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 84fbb5061f3..1a3e9b323f5 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -591,6 +591,14 @@ impl NativeProgramImage { { return Err("a process clock has an invalid event domain or period".into()); } + if self + .runtime_schema + .rtl_writes + .iter() + .any(|write| write.id == clock.signal) + { + return Err("a process clock is driven by design logic".into()); + } let event = self.event_map[&clock.signal].id; if let Some(previous) = process_clock_periods.insert(event, clock.period) && previous != clock.period @@ -2340,7 +2348,17 @@ fn compile_program( native_memory_size, options: NativeRuntimeOptions { four_state: options.four_state, - native_tick_loop: options.x86_options.native_tick_loop, + // A generated loop cannot distinguish a failed pre-edge + // phase from a published tick. Run fallible comb separately. + native_tick_loop: options.x86_options.native_tick_loop + && !sir + .sir + .eval_comb + .iter() + .flat_map(|unit| unit.blocks.values()) + .any(|block| { + matches!(block.terminator, celox_sir::SIRTerminator::Error(_)) + }), native_force_support: options.native_force_support, perf_map: options.x86_options.diagnostics.perf_map, kernel_selection: crate::backend::lanes::kernel_selection(options), @@ -3387,13 +3405,23 @@ mod process_metadata_tests { fn process_clock_metadata_is_checked_before_image_attachment() { let original = image(); original.to_container_bytes().unwrap(); - for corruption in 0..4 { + for corruption in 0..5 { let mut broken = original.clone(); let slots = &mut broken.runtime_schema.processes[0]; match corruption { 0 => slots.clocks[0].signal = slots.delay, 1 => slots.clocks[0].period = 1, 2 => slots.clock = slots.status, + 4 => { + let signal = slots.clocks[0].signal; + broken + .runtime_schema + .rtl_writes + .insert(celox_design::VarAtomBase { + id: signal, + access: celox_design::BitAccess::new(0, 0), + }); + } _ => { let signal = *broken .design @@ -3429,6 +3457,30 @@ mod process_metadata_tests { ); } + #[test] + fn default_native_loops_do_not_credit_a_failed_pre_edge_iteration() { + use crate::backend::SimBackend; + let source = r#"module Top(clk:input clock,enable:output logic,v:output logic){ + assign v=if enable ? ~v : 1'd0; + always_ff(clk){enable=1;} + }"#; + let mut sim = crate::Simulator::builder(source, "Top") + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_native() + .unwrap(); + let event = sim.event("clk"); + let (completed, result) = sim.backend.eval_comb_apply_ff_many_at(event, 10); + assert_eq!(completed, 1); + assert!(result.is_ok()); + let (completed, result) = sim.backend.eval_comb_apply_ff_many_at(event, 9); + assert_eq!(completed, 0); + assert!(result.is_err()); + } + #[test] fn lane_ticks_report_zero_progress_for_pre_edge_comb_failure() { use crate::backend::SimBackend; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index bbeb099978e..4fc38f5c397 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -127,6 +127,12 @@ impl SimulationExecutor for Simulator { self.vcd_writer.is_none() && !self.components.has_scheduled_components() && self.program.runtime_schema.comb_observers.is_empty() + && !self + .program + .runtime_schema + .runtime_event_sites + .iter() + .any(|site| matches!(site.kind, celox_design::RuntimeEventKind::Finish)) && !self.program.runtime_schema.clock_phase_sensitive_comb } @@ -1972,3 +1978,80 @@ mod rtl_finish_backend_tests { } } } + +#[cfg(test)] +mod finish_clock_batch_tests { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + #[test] + fn finish_suppresses_coincident_generated_edges() { + fn check(mut sim: Simulation, scheduled: bool) { + if scheduled { + sim.schedule("other", 4, 1).unwrap(); + } + sim.run_until(4).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(sim.ticks(), 2); + } + for scheduled in [false, true] { + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(8).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let other = m.internal("other", bit).unwrap(); + let q = m.output("count", word).unwrap(); + let r = m.output("other_q", bit).unwrap(); + let v = m.read(q).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, v, one, word).unwrap(); + let dst = m.whole(q).unwrap(); + m.register(dst, next, clk, Edge::Posedge, None, None) + .unwrap(); + let dst = m.whole(r).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + m.register(dst, one, other, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 2).unwrap(); + let ten = m.constant(Constant::two_state(10u8, 64).unwrap()); + let four = m.constant(Constant::two_state(4u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: ten, + }]) + .unwrap(); + m.process(vec![Statement::Delay { amount: four }, Statement::Finish]) + .unwrap(); + let design = m.finish(); + check( + Simulation::new( + Simulator::from_frontend(design.clone()) + .build_interpreter() + .unwrap(), + ), + scheduled, + ); + check( + Simulation::new( + Simulator::from_frontend(design.clone()) + .build_cranelift() + .unwrap(), + ), + scheduled, + ); + check( + Simulation::new( + Simulator::from_frontend(design.clone()) + .build_wasm() + .unwrap(), + ), + scheduled, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(Simulator::from_frontend(design).build_native().unwrap()), + scheduled, + ); + } + } +} From 504fe093e5aa4383111fdd89b0ff6f6ad91ac38a Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 17:02:29 +0900 Subject: [PATCH 16/42] fix(runtime): suppress overflowing edges after coincident finish --- crates/celox-runtime/src/simulation.rs | 17 ++++----- crates/celox/src/simulation.rs | 52 ++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 149ead4d618..b1ed5424ab4 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -456,13 +456,6 @@ impl SimulationState { if current_time > limit { return Ok(None); } - for (id, clock) in &self.tick_clocks { - if clock.next_edge == current_time && self.clock_has_waiters(*id) { - current_time - .checked_add(clock.period) - .ok_or_else(|| clock_overflow(*id))?; - } - } let mut events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() @@ -1133,13 +1126,13 @@ impl SimulationState { if self.finished { // Suppress generated edges queued before a ready process finished. self.round_new_rising.make_empty(); - return Ok(false); + generated_events.clear(); } // Ready processes may activate a clock at this timestamp. Join it // to existing source events before any coincident FF domain commits. // With no other event, retain the later fused-tick path. - if !events_to_process.is_empty() || !process_driven.is_empty() { + if !self.finished && (!events_to_process.is_empty() || !process_driven.is_empty()) { for (id, clock) in &self.tick_clocks { if clock.next_edge == current_time && self.clock_has_waiters(*id) @@ -1168,6 +1161,12 @@ impl SimulationState { // A completed clock wait resumes before the following generated // rising edge. Apply that edge after the ready processes, then join // it to scheduled triggers so coincident FF domains share one batch. + for event in &generated_events { + let id = event.event_ref.id(); + current_time + .checked_add(self.tick_clocks[&id].period) + .ok_or_else(|| clock_overflow(id))?; + } for event in &generated_events { executor.backend_mut().set(event.signal, event.next_val); } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4fc38f5c397..5d9520ae8c7 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1983,6 +1983,58 @@ mod rtl_finish_backend_tests { mod finish_clock_batch_tests { use super::*; use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + #[test] + fn coincident_finish_suppresses_an_overflowing_next_edge() { + fn check(mut sim: Simulation) { + sim.run_until(u64::MAX - 1).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let bit = ValueType::bits(1).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let q = m.output("q", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let dst = m.whole(q).unwrap(); + m.register(dst, one, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 2).unwrap(); + let start = m.constant(Constant::two_state(u64::MAX - 3, 64).unwrap()); + let end = m.constant(Constant::two_state(u64::MAX - 1, 64).unwrap()); + let two = m.constant(Constant::two_state(2u8, 64).unwrap()); + m.process(vec![ + Statement::Delay { amount: start }, + Statement::ClockCycles { + clock: clk, + count: two, + }, + ]) + .unwrap(); + m.process(vec![Statement::Delay { amount: end }, Statement::Finish]) + .unwrap(); + let design = m.finish(); + check(Simulation::new( + Simulator::from_frontend(design.clone()) + .build_interpreter() + .unwrap(), + )); + check(Simulation::new( + Simulator::from_frontend(design.clone()) + .build_cranelift() + .unwrap(), + )); + check(Simulation::new( + Simulator::from_frontend(design.clone()) + .build_wasm() + .unwrap(), + )); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new( + Simulator::from_frontend(design).build_native().unwrap(), + )); + } + #[test] fn finish_suppresses_coincident_generated_edges() { fn check(mut sim: Simulation, scheduled: bool) { From f5d75fc342c1c4a23e6deb93b48e04f579ed15c3 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 02:58:25 +0900 Subject: [PATCH 17/42] fix(runtime): retain generated clock coincidence and exported drive provenance --- crates/celox-runtime/src/simulation.rs | 9 +++- crates/celox/src/simulation.rs | 66 ++++++++++++++++++++++++ crates/celox/src/simulator/state_file.rs | 2 + 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 868e04448d7..def8c61ac66 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1162,7 +1162,7 @@ impl SimulationState { // Ready processes may activate a clock at this timestamp. Join it // to existing source events before any coincident FF domain commits. // With no other event, retain the later fused-tick path. - if !self.finished && (!events_to_process.is_empty() || !process_driven.is_empty()) { + if !self.finished && (!events_to_process.is_empty() || !process_driven.is_empty() || !generated_events.is_empty()) { for (id, clock) in &self.tick_clocks { if clock.next_edge == current_time && self.clock_has_waiters(*id) @@ -1745,6 +1745,9 @@ pub struct ScheduleParts { pub done_processes: Vec, /// Rising edges of process clocks so far. pub ticks: u64, + /// Timestamp and one-shot clock drives already consumed at that time. + pub scheduled_clock_time: u64, + pub scheduled_clock_drives: Vec, pub inactive_processes: Vec, /// A process requested the end of the simulation. pub finished: bool, @@ -1808,6 +1811,8 @@ impl SimulationState { .collect(), done_processes: self.done.iter().copied().collect(), ticks: self.ticks, + scheduled_clock_time: self.scheduled_clock_time, + scheduled_clock_drives: self.scheduled_clock_drives.iter().map(|id| events[id]).collect(), inactive_processes: self.inactive.iter().copied().collect(), finished: self.finished, } @@ -1872,6 +1877,8 @@ impl SimulationState { .collect(); self.done = parts.done_processes.into_iter().collect(); self.ticks = parts.ticks; + self.scheduled_clock_time = parts.scheduled_clock_time; + self.scheduled_clock_drives = parts.scheduled_clock_drives.into_iter().map(|event| event.id()).collect(); self.inactive = parts.inactive_processes.into_iter().collect(); self.finished = parts.finished; } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index ce01554cffb..be9fdd60b45 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1930,6 +1930,31 @@ mod clock_provenance_checkpoint_tests { assert!(error.contains("already driven by schedule"), "{error}"); assert_eq!(sim.ticks(), 0); } + fn check_transfer(mut from: Simulation, mut to: Simulation) { + from.schedule("clk",0,1).unwrap(); + from.step().unwrap(); + let design = from.simulator.checkpoint().unwrap(); + let mut parts = from.state.export_schedule(&from.simulator.backend); + parts.process_wakeups = vec![(0,0)]; + to.simulator.restore(&design).unwrap(); + to.state.import_schedule(parts); + let error = to.step().unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"),"{error}"); + assert_eq!(to.ticks(),0); + } + #[test] + fn exported_schedule_retains_consumed_clock_drives() { + let build=|| Simulation::from_frontend(design()).build_interpreter().unwrap(); + check_transfer(build(),build()); + let build=|| Simulation::from_frontend(design()).build_cranelift().unwrap(); + check_transfer(build(),build()); + let build=|| Simulation::from_frontend(design()).build_wasm().unwrap(); + check_transfer(build(),build()); + #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] { + let build=|| Simulation::from_frontend(design()).build_native().unwrap(); + check_transfer(build(),build()); + } + } #[test] fn restored_clock_drive_provenance_rejects_a_same_time_generator() { check( @@ -2328,3 +2353,44 @@ mod direct_finish_tests { check(Simulation::new(builder().build_native().unwrap())); } } + +#[cfg(test)] +mod pending_generated_clock_tests { + use super::*; + use crate::frontend_sdk::{Constant,Edge,ModuleBuilder,Statement,UnaryOp,ValueType}; + fn design()->crate::frontend_sdk::FrontendArtifact { + let mut m=ModuleBuilder::new("Top").unwrap(); + let bit=ValueType::bits(1).unwrap(); + let a=m.internal("a",bit).unwrap();let b=m.internal("b",bit).unwrap(); + let qa=m.output("qa",bit).unwrap();let qb=m.output("qb",bit).unwrap(); + let old=m.read(qb).unwrap();let next=m.unary(UnaryOp::BitNot,old,bit).unwrap(); + let qa_target=m.whole(qa).unwrap();let qb_target=m.whole(qb).unwrap(); + m.register(qa_target,old,a,Edge::Posedge,None,None).unwrap(); + m.register(qb_target,next,b,Edge::Posedge,None,None).unwrap(); + m.clock_period(a,4).unwrap();m.clock_period(b,4).unwrap(); + let two=m.constant(Constant::two_state(2u8,64).unwrap()); + let one=m.constant(Constant::two_state(1u8,64).unwrap()); + let four=m.constant(Constant::two_state(4u8,64).unwrap()); + m.process(vec![Statement::ClockCycles{clock:b,count:two}]).unwrap(); + m.process(vec![Statement::Delay{amount:four},Statement::ClockCycles{clock:a,count:one}]).unwrap(); + m.finish() + } + fn check(mut sim:Simulation) { + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("qb")),1u8.into()); + // A failed round can leave this generated drive high without publishing its FF batch. + sim.simulator.backend.set(sim.signal("b"),1u8); + sim.step().unwrap(); + assert_eq!(sim.get(sim.signal("qa")),1u8.into()); + assert_eq!(sim.get(sim.signal("qb")),0u8.into()); + assert_eq!(sim.ticks(),2); + } + #[test] + fn pending_rises_share_pre_edge_state_with_new_clocks() { + check(Simulation::from_frontend(design()).build_interpreter().unwrap()); + check(Simulation::from_frontend(design()).build_cranelift().unwrap()); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index b19429ef68a..7496cb13323 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -447,6 +447,8 @@ impl Simulator { clock_waits: Vec::new(), done_processes: Vec::new(), ticks: 0, + scheduled_clock_time: record.time, + scheduled_clock_drives: Vec::new(), inactive_processes: Vec::new(), finished: false, }) From f3446a46ba7e8fcf957678c51dc750a8bbeac0ca Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 03:54:01 +0900 Subject: [PATCH 18/42] style: format clock wait review regressions --- crates/celox-runtime/src/simulation.rs | 18 +++- crates/celox/src/simulation.rs | 113 ++++++++++++++++--------- 2 files changed, 89 insertions(+), 42 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index d19dafec053..7d899ac4c29 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1186,7 +1186,11 @@ impl SimulationState { // Ready processes may activate a clock at this timestamp. Join it // to existing source events before any coincident FF domain commits. // With no other event, retain the later fused-tick path. - if !self.finished && (!events_to_process.is_empty() || !process_driven.is_empty() || !generated_events.is_empty()) { + if !self.finished + && (!events_to_process.is_empty() + || !process_driven.is_empty() + || !generated_events.is_empty()) + { for (id, clock) in &self.tick_clocks { if clock.next_edge == current_time && self.clock_has_waiters(*id) @@ -1867,7 +1871,11 @@ impl SimulationState { done_processes: self.done.iter().copied().collect(), ticks: self.ticks, scheduled_clock_time: self.scheduled_clock_time, - scheduled_clock_drives: self.scheduled_clock_drives.iter().map(|id| events[id]).collect(), + scheduled_clock_drives: self + .scheduled_clock_drives + .iter() + .map(|id| events[id]) + .collect(), inactive_processes: self.inactive.iter().copied().collect(), finished: self.finished, } @@ -1933,7 +1941,11 @@ impl SimulationState { self.done = parts.done_processes.into_iter().collect(); self.ticks = parts.ticks; self.scheduled_clock_time = parts.scheduled_clock_time; - self.scheduled_clock_drives = parts.scheduled_clock_drives.into_iter().map(|event| event.id()).collect(); + self.scheduled_clock_drives = parts + .scheduled_clock_drives + .into_iter() + .map(|event| event.id()) + .collect(); self.inactive = parts.inactive_processes.into_iter().collect(); self.finished = parts.finished; } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4056fb3b221..4033fb0cc96 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2133,28 +2133,37 @@ mod clock_provenance_checkpoint_tests { assert_eq!(sim.ticks(), 0); } fn check_transfer(mut from: Simulation, mut to: Simulation) { - from.schedule("clk",0,1).unwrap(); + from.schedule("clk", 0, 1).unwrap(); from.step().unwrap(); let design = from.simulator.checkpoint().unwrap(); let mut parts = from.state.export_schedule(&from.simulator.backend); - parts.process_wakeups = vec![(0,0)]; + parts.process_wakeups = vec![(0, 0)]; to.simulator.restore(&design).unwrap(); to.state.import_schedule(parts); let error = to.step().unwrap_err().to_string(); - assert!(error.contains("already driven by schedule"),"{error}"); - assert_eq!(to.ticks(),0); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(to.ticks(), 0); } #[test] fn exported_schedule_retains_consumed_clock_drives() { - let build=|| Simulation::from_frontend(design()).build_interpreter().unwrap(); - check_transfer(build(),build()); - let build=|| Simulation::from_frontend(design()).build_cranelift().unwrap(); - check_transfer(build(),build()); - let build=|| Simulation::from_frontend(design()).build_wasm().unwrap(); - check_transfer(build(),build()); - #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] { - let build=|| Simulation::from_frontend(design()).build_native().unwrap(); - check_transfer(build(),build()); + let build = || { + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap() + }; + check_transfer(build(), build()); + let build = || { + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap() + }; + check_transfer(build(), build()); + let build = || Simulation::from_frontend(design()).build_wasm().unwrap(); + check_transfer(build(), build()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + let build = || Simulation::from_frontend(design()).build_native().unwrap(); + check_transfer(build(), build()); } } #[test] @@ -2557,45 +2566,71 @@ mod direct_finish_tests { #[cfg(test)] mod pending_generated_clock_tests { use super::*; - use crate::frontend_sdk::{Constant,Edge,ModuleBuilder,Statement,UnaryOp,ValueType}; - fn design()->crate::frontend_sdk::FrontendArtifact { - let mut m=ModuleBuilder::new("Top").unwrap(); - let bit=ValueType::bits(1).unwrap(); - let a=m.internal("a",bit).unwrap();let b=m.internal("b",bit).unwrap(); - let qa=m.output("qa",bit).unwrap();let qb=m.output("qb",bit).unwrap(); - let old=m.read(qb).unwrap();let next=m.unary(UnaryOp::BitNot,old,bit).unwrap(); - let qa_target=m.whole(qa).unwrap();let qb_target=m.whole(qb).unwrap(); - m.register(qa_target,old,a,Edge::Posedge,None,None).unwrap(); - m.register(qb_target,next,b,Edge::Posedge,None,None).unwrap(); - m.clock_period(a,4).unwrap();m.clock_period(b,4).unwrap(); - let two=m.constant(Constant::two_state(2u8,64).unwrap()); - let one=m.constant(Constant::two_state(1u8,64).unwrap()); - let four=m.constant(Constant::two_state(4u8,64).unwrap()); - m.process(vec![Statement::ClockCycles{clock:b,count:two}]).unwrap(); - m.process(vec![Statement::Delay{amount:four},Statement::ClockCycles{clock:a,count:one}]).unwrap(); + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let a = m.internal("a", bit).unwrap(); + let b = m.internal("b", bit).unwrap(); + let qa = m.output("qa", bit).unwrap(); + let qb = m.output("qb", bit).unwrap(); + let old = m.read(qb).unwrap(); + let next = m.unary(UnaryOp::BitNot, old, bit).unwrap(); + let qa_target = m.whole(qa).unwrap(); + let qb_target = m.whole(qb).unwrap(); + m.register(qa_target, old, a, Edge::Posedge, None, None) + .unwrap(); + m.register(qb_target, next, b, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(a, 4).unwrap(); + m.clock_period(b, 4).unwrap(); + let two = m.constant(Constant::two_state(2u8, 64).unwrap()); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + let four = m.constant(Constant::two_state(4u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: b, + count: two, + }]) + .unwrap(); + m.process(vec![ + Statement::Delay { amount: four }, + Statement::ClockCycles { + clock: a, + count: one, + }, + ]) + .unwrap(); m.finish() } - fn check(mut sim:Simulation) { + fn check(mut sim: Simulation) { sim.run_until(3).unwrap(); - assert_eq!(sim.get(sim.signal("qb")),1u8.into()); + assert_eq!(sim.get(sim.signal("qb")), 1u8.into()); // A failed round can leave this generated drive high without publishing its FF batch. - sim.simulator.backend.set(sim.signal("b"),1u8); + sim.simulator.backend.set(sim.signal("b"), 1u8); sim.step().unwrap(); - assert_eq!(sim.get(sim.signal("qa")),1u8.into()); - assert_eq!(sim.get(sim.signal("qb")),0u8.into()); - assert_eq!(sim.ticks(),2); + assert_eq!(sim.get(sim.signal("qa")), 1u8.into()); + assert_eq!(sim.get(sim.signal("qb")), 0u8.into()); + assert_eq!(sim.ticks(), 2); } #[test] fn pending_rises_share_pre_edge_state_with_new_clocks() { - check(Simulation::from_frontend(design()).build_interpreter().unwrap()); - check(Simulation::from_frontend(design()).build_cranelift().unwrap()); + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); check(Simulation::from_frontend(design()).build_wasm().unwrap()); - #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(Simulation::from_frontend(design()).build_native().unwrap()); } } -#[cfg(all(test, feature="systemverilog"))] +#[cfg(all(test, feature = "systemverilog"))] mod current_time_settle_tests { use super::*; #[test] From 75106860ba9a29cf3b8e9b26ef5f750f446cea60 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 04:00:13 +0900 Subject: [PATCH 19/42] test(runtime): count clock edges in the retry regression --- crates/celox/src/simulation.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4033fb0cc96..68e663f83c3 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2610,7 +2610,8 @@ mod pending_generated_clock_tests { sim.step().unwrap(); assert_eq!(sim.get(sim.signal("qa")), 1u8.into()); assert_eq!(sim.get(sim.signal("qb")), 0u8.into()); - assert_eq!(sim.ticks(), 2); + // B rose once at time zero; both A and B rise at time four. + assert_eq!(sim.ticks(), 3); } #[test] fn pending_rises_share_pre_edge_state_with_new_clocks() { From 511aad80878a336a80b8c0c567be55c2b8c85674 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 05:49:22 +0900 Subject: [PATCH 20/42] fix(runtime): bound clock settling and reject host drives with accurate failed tick progress --- crates/celox-runtime/src/backend.rs | 5 +- crates/celox-runtime/src/simulation.rs | 24 +++- crates/celox/src/backend/native/backend.rs | 13 +- crates/celox/src/lib.rs | 11 ++ crates/celox/src/simulation.rs | 144 ++++++++++++++++++++- crates/celox/src/simulator.rs | 35 ++++- crates/celox/src/simulator/checkpoint.rs | 4 + crates/celox/src/simulator/state_file.rs | 1 + 8 files changed, 227 insertions(+), 10 deletions(-) diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index ff0c70e85d7..67c22bc7753 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -56,7 +56,10 @@ pub trait SimBackend { if let Err(error) = self.eval_comb() { return (0, Err(error)); } - (1, self.eval_apply_ff_at(event)) + { + let result = self.eval_apply_ff_at(event); + (u64::from(result.is_ok()), result) + } } /// Evaluate FF domain without applying (for cascaded clocks). diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 3fbabf2f5b4..ad95d64c47f 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -57,7 +57,10 @@ pub trait SimulationExecutor { if let Err(error) = self.eval_comb() { return (0, Err(error)); } - (1, self.eval_apply_ff_at(event)) + { + let result = self.eval_apply_ff_at(event); + (u64::from(result.is_ok()), result) + } } /// Whether clock waits may be served by fused ticks, which skip the @@ -508,6 +511,25 @@ impl SimulationState { Ok(()) } + /// A generated process clock owns its signal, including before its first wait. + pub fn validate_host_write(&self, signal: SignalRef) -> Result<(), SimulatorErrorCode> { + if let Some(clock) = self + .processes + .iter() + .flat_map(|process| &process.clocks) + .find(|clock| clock.signal == signal) + { + return Err(SimulatorErrorCode::Runtime { + message: format!( + "process clock {} is driven by a direct host write", + clock.event.id() + ), + signals: Vec::new(), + }); + } + Ok(()) + } + pub fn step(&mut self, executor: &mut E) -> Result, SimulatorErrorCode> where E: SimulationExecutor, diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 14762763d9f..88621a83de5 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -2358,13 +2358,14 @@ fn compile_program( native_memory_size, options: NativeRuntimeOptions { four_state: options.four_state, - // A generated loop cannot distinguish a failed pre-edge - // phase from a published tick. Run fallible comb separately. + // A generated loop cannot distinguish a failed phase from + // a published tick. Run fallible comb and FF phases separately. native_tick_loop: options.x86_options.native_tick_loop && !sir .sir .eval_comb .iter() + .chain(sir.sir.eval_apply_ffs.values().flatten()) .flat_map(|unit| unit.blocks.values()) .any(|block| { matches!(block.terminator, celox_sir::SIRTerminator::Error(_)) @@ -3098,7 +3099,8 @@ impl super::super::SimBackend for NativeBackend { if let Err(error) = self.eval_comb() { return (0, Err(error)); } - return (1, self.eval_apply_ff_at(event)); + let result = self.eval_apply_ff_at(event); + return (u64::from(result.is_ok()), result); } if self.compiled.options.native_tick_loop { let (executed, result) = self.call_func_many_timed(event.comb_apply_func, count); @@ -3119,7 +3121,10 @@ impl super::super::SimBackend for NativeBackend { self.lane_selectors .advance(super::super::lanes::LaneKernelSlot::Fused(event.id), 1); } - (1, self.eval_apply_ff_at(event)) + { + let result = self.eval_apply_ff_at(event); + (u64::from(result.is_ok()), result) + } } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index ebcbb546c6b..438d0896691 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -100,14 +100,22 @@ mod host_api { pub struct IOContext<'a, B: SimBackend = DefaultBackend> { pub(crate) backend: &'a mut B, + pub(crate) host_writes: &'a mut Vec, + pub(crate) host_clock_signals: &'a [crate::SignalRef], } impl<'a, B: SimBackend> IOContext<'a, B> { pub fn set(&mut self, signal: crate::SignalRef, val: T) { + if self.host_clock_signals.contains(&signal) && !self.host_writes.contains(&signal) { + self.host_writes.push(signal); + } self.backend.set(signal, val); } pub fn set_wide(&mut self, signal: crate::SignalRef, val: crate::BigUint) { + if self.host_clock_signals.contains(&signal) && !self.host_writes.contains(&signal) { + self.host_writes.push(signal); + } self.backend.set_wide(signal, val); } @@ -117,6 +125,9 @@ mod host_api { val: crate::BigUint, mask: crate::BigUint, ) { + if self.host_clock_signals.contains(&signal) && !self.host_writes.contains(&signal) { + self.host_writes.push(signal); + } self.backend.set_four_state(signal, val, mask); } } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index b8816e05daf..2230c4860bc 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -110,7 +110,8 @@ impl SimulationExecutor for Simulator { if let Err(error) = self.eval_comb_checked() { return (0, Err(error)); } - return (1, self.tick_deferred_comb(event)); + let result = self.tick_deferred_comb(event); + return (u64::from(result.is_ok()), result); } // Every tick settles the combinational logic first, so a clean // state needs no special case and the whole run stays in the @@ -510,7 +511,8 @@ impl Simulation { /// advance. pub fn settle(&mut self) -> Result<(), RuntimeErrorCode> { let time = self.state.time(); - if self.simulator.dirty + if !self.simulator.pending_host_writes.is_empty() + || self.simulator.dirty || !self.simulator.backend.get_triggered_bits().is_empty() || self.state.has_unsettled_edges(&self.simulator.backend) || self @@ -525,7 +527,7 @@ impl Simulation { .next_event_time() .is_some_and(|next| next <= time) { - self.state.step(&mut self.simulator)?; + self.state.step_until(&mut self.simulator, time)?; drained = true; } if !drained { @@ -540,6 +542,13 @@ impl Simulation { /// Settle the combinational logic a host write left dirty, so a process /// waiting for a derived value sees it. fn settle_host_writes(&mut self) -> Result<(), RuntimeErrorCode> { + let writes = self.simulator.take_host_writes(); + for &signal in &writes { + if let Err(error) = self.state.validate_host_write(signal) { + self.simulator.pending_host_writes = writes; + return Err(error); + } + } if self.simulator.dirty { self.simulator.eval_comb()?; } @@ -2770,3 +2779,132 @@ mod scheduled_pulse_tests { } } } + +#[cfg(test)] +mod host_clock_review_tests { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut module = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(8).unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", word).unwrap(); + module + .set_initial(q, Constant::two_state(0u8, 8).unwrap()) + .unwrap(); + let value = module.read(q).unwrap(); + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + let next = module.binary(BinaryOp::Add, value, one, word).unwrap(); + let target = module.whole(q).unwrap(); + module + .register(target, next, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 2).unwrap(); + let ten = module.constant(Constant::two_state(10u8, 64).unwrap()); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: ten, + }]) + .unwrap(); + module.finish() + } + fn settle(mut sim: Simulation) { + sim.settle().unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.next_event_time(), Some(1)); + } + fn host(mut sim: Simulation, mode: u8) { + let clk = sim.signal("clk"); + let before = sim.checkpoint().unwrap(); + match mode { + 0 => sim.set_wide(clk, 1u8.into()), + 1 => sim.set_four_state(clk, 1u8.into(), 0u8.into()), + 2 => sim + .modify(|io| { + io.set(clk, 1u8); + io.set(clk, 0u8); + }) + .unwrap(), + _ => { + sim.set_wide(clk, 1u8.into()); + sim.get(sim.signal("q")); + } + } + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("direct host write"), "{error}"); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.ticks(), 0); + assert!( + sim.run_until(0) + .unwrap_err() + .to_string() + .contains("direct host write") + ); + sim.restore(&before).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn settling_a_process_clock_keeps_current_time() { + let build = || Simulator::from_frontend(design()); + settle(Simulation::new(build().build_interpreter().unwrap())); + settle(Simulation::new(build().build_cranelift().unwrap())); + settle(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + settle(Simulation::new(build().build_native().unwrap())); + } + #[test] + fn direct_host_clock_writes_are_rejected_before_activation() { + let build = || Simulator::from_frontend(design()); + for mode in 0..4 { + host(Simulation::new(build().build_interpreter().unwrap()), mode); + host(Simulation::new(build().build_cranelift().unwrap()), mode); + host(Simulation::new(build().build_wasm().unwrap()), mode); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + host(Simulation::new(build().build_native().unwrap()), mode); + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod failed_ff_progress_tests { + use super::*; + fn check(mut sim: Simulator) { + let event = sim.event("clk"); + let (completed, result) = SimulationExecutor::tick_many(&mut sim, event, 10); + assert_eq!(completed, 0, "{}", std::any::type_name::()); + assert!(result.is_err()); + assert_eq!( + sim.get(sim.signal("q")), + 0u8.into(), + "{}", + std::any::type_name::() + ); + } + #[test] + fn failed_ff_evaluation_does_not_complete_a_tick() { + let source = "module Top(input bit clk,ok,output bit q);always_ff @(posedge clk)begin assert(ok)else $fatal(1,\"failed FF\");q<=1;end endmodule"; + let build = || { + Simulator::from_sv_sources(vec![(source, std::path::Path::new("failed-ff.sv"))], "Top") + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + check(build().build_tiered().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + check(build().build_native().unwrap()); + check( + build() + .threads(4) + .parallel_partition(crate::ParallelPartition::Always) + .build_native() + .unwrap(), + ); + } + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 893479d7d40..cccb4e704ca 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -100,6 +100,8 @@ mod host { pub(crate) program: RuntimeProgram, pub(crate) vcd_writer: Option, pub(crate) dirty: bool, + pub(crate) pending_host_writes: Vec, + host_clock_signals: Vec, pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, pub(crate) component_simulation: Option>, @@ -689,11 +691,20 @@ mod host { program: RuntimeProgram, warnings: Vec, ) -> Self { + let host_clock_signals = program + .runtime_schema + .processes + .iter() + .flat_map(|process| &process.clocks) + .map(|clock| backend.resolve_signal(&clock.signal)) + .collect(); let mut sim = Self { + host_clock_signals, backend, program, vcd_writer: None, dirty: false, + pending_host_writes: Vec::new(), warnings, components: Default::default(), component_simulation: None, @@ -1148,6 +1159,11 @@ mod host { /// values and truncating bits beyond the signal width. Integer type /// size does not need to match the signal storage size. pub fn set(&mut self, signal: SignalRef, val: T) { + if self.host_clock_signals.contains(&signal) + && !self.pending_host_writes.contains(&signal) + { + self.pending_host_writes.push(signal); + } self.backend.set(signal, val); self.dirty = true; self.settle_dirty_for_runtime_event_drain(); @@ -1155,6 +1171,11 @@ mod host { /// Sets a wide signal value and marks combinational logic as dirty. pub fn set_wide(&mut self, signal: SignalRef, val: BigUint) { + if self.host_clock_signals.contains(&signal) + && !self.pending_host_writes.contains(&signal) + { + self.pending_host_writes.push(signal); + } self.backend.set_wide(signal, val); self.dirty = true; self.settle_dirty_for_runtime_event_drain(); @@ -1162,6 +1183,11 @@ mod host { /// Sets a four-state signal value and marks combinational logic as dirty. pub fn set_four_state(&mut self, signal: SignalRef, val: BigUint, mask: BigUint) { + if self.host_clock_signals.contains(&signal) + && !self.pending_host_writes.contains(&signal) + { + self.pending_host_writes.push(signal); + } self.backend.set_four_state(signal, val, mask); self.dirty = true; self.settle_dirty_for_runtime_event_drain(); @@ -1174,6 +1200,8 @@ mod host { { let mut ctx = IOContext { backend: &mut self.backend, + host_writes: &mut self.pending_host_writes, + host_clock_signals: &self.host_clock_signals, }; f(&mut ctx); self.dirty = true; @@ -1183,6 +1211,10 @@ mod host { Ok(()) } + pub(crate) fn take_host_writes(&mut self) -> Vec { + std::mem::take(&mut self.pending_host_writes) + } + pub(super) fn settle_dirty_for_runtime_event_drain(&mut self) { if self.runtime_event_drain_active.load(Ordering::Acquire) { self.eval_comb_for_runtime_event_drain().unwrap(); @@ -1499,7 +1531,8 @@ mod host { return (0, Ok(())); } if !self.program.runtime_schema.comb_observers.is_empty() || !self.dirty { - return (1, self.tick_deferred_comb(event)); + let result = self.tick_deferred_comb(event); + return (u64::from(result.is_ok()), result); } let (completed, result) = self.backend.eval_comb_apply_ff_many_at(event, count); self.dirty = true; diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 7a470a8c662..fbaba00d2a2 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -95,6 +95,7 @@ pub struct Checkpoint { comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, runtime_finish_requested: bool, + pending_host_writes: Vec, } impl Checkpoint { @@ -146,6 +147,7 @@ impl Simulator { comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, runtime_finish_requested: self.has_pending_runtime_finish(), + pending_host_writes: self.pending_host_writes.clone(), }) } @@ -165,6 +167,8 @@ impl Simulator { .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; self.reset_runtime_finish(checkpoint.runtime_finish_requested); + self.pending_host_writes + .clone_from(&checkpoint.pending_host_writes); if let Some(writer) = &mut self.vcd_writer { writer.rescan(); } diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 836b19eae6b..15e03008c92 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -278,6 +278,7 @@ impl Simulator { return Err(StateError::Runtime(error)); } self.reset_runtime_finish(false); + self.pending_host_writes.clear(); self.comb_observer_snapshots = self.snapshot_all_comb_observers(); self.comb_observer_initial_eval = false; if let Some(writer) = &mut self.vcd_writer { From d4945a5ae977513de1bc15aec8b3520246ce37c5 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 07:28:27 +0900 Subject: [PATCH 21/42] fix(runtime): settle target-time clock falls and normalize unknown levels --- crates/celox-runtime/src/simulation.rs | 28 ++++---- crates/celox/src/simulation.rs | 99 ++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 12 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index ad95d64c47f..e2c081c01e8 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -592,8 +592,10 @@ impl SimulationState { .tick_clocks .iter() .filter(|(id, clock)| { - let high = executor.backend().get_as::(clock.signal) != 0; - let pending_rise = high && !self.last_clock_values.contains(**id); + let high = sample_event_signal(executor.backend(), clock.signal) == (true, false); + let pending_rise = high + && (!self.last_clock_values.contains(**id) + || self.unknown_clock_values.contains(**id)); (!events_to_process.is_empty() || pending_rise) && clock.next_edge == current_time && self.clock_has_waiters(**id) @@ -705,14 +707,14 @@ impl SimulationState { let mut rising = Vec::with_capacity(due.len()); for id in due { let clock = &self.tick_clocks[id]; - let high: u8 = executor.backend().get_as(clock.signal); + let high = sample_event_signal(executor.backend(), clock.signal) == (true, false); events.push(SimEvent { time, event_ref: clock.event, signal: clock.signal, - next_val: u8::from(high == 0), + next_val: u8::from(!high), }); - if high == 0 { + if !high { rising.push(*id); } } @@ -827,10 +829,8 @@ impl SimulationState { || self.clock_waits.values().any(|wait| wait.clock != clock) || self.clock_waits.len() + self.done.len() != self.processes.len() || self.event_info.iter().any(|info| info.is_cascaded) - || executor - .backend() - .get_as::(self.tick_clocks[&clock].signal) - != 0 + || sample_event_signal(executor.backend(), self.tick_clocks[&clock].signal) + != (false, false) { return Ok(false); } @@ -1161,12 +1161,16 @@ impl SimulationState { where E: SimulationExecutor, { - while self.next_event_time().is_some_and(|next| next < time) { - self.step_until(executor, time)?; + let mut settled_target = false; + while self.next_event_time().is_some_and(|next| next <= time) { + settled_target |= self.step_until(executor, time)? == Some(time); } if self.finished { return Ok(None); } + if settled_target { + return Ok(Some(time)); + } let ready = self.take_ready_processes(time); let result = self.step_round(executor, time, Vec::new(), Vec::new(), ready, true); self.finish_clock_round(time, Vec::new(), &[], result)?; @@ -1288,7 +1292,7 @@ impl SimulationState { for (id, clock) in &self.tick_clocks { if clock.next_edge == current_time && self.clock_has_waiters(*id) - && executor.backend().get_as::(clock.signal) == 0 + && sample_event_signal(executor.backend(), clock.signal) != (true, false) && !events_to_process .iter() .any(|event| event.signal == clock.signal && event.next_val == 0) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 2230c4860bc..e9ba2fc6277 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2908,3 +2908,102 @@ mod failed_ff_progress_tests { } } } + +#[cfg(test)] +mod generated_phase_review_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design(unknown: Option, edge: Edge) -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("ClockPhases").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let clk = m.internal("clk", ValueType::logic(1).unwrap()).unwrap(); + m.set_initial( + clk, + match unknown { + Some(value) => Constant::four_state(value, 1u8, 1).unwrap(), + None => Constant::two_state(0u8, 1).unwrap(), + }, + ) + .unwrap(); + let q = m.output("q", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(q).unwrap(); + m.register(target, one, clk, edge, None, None).unwrap(); + m.clock_period(clk, 4).unwrap(); + let three = m.constant(Constant::two_state(3u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: three, + }]) + .unwrap(); + m.finish() + } + fn fall(mut sim: Simulation) { + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.state.settle_at(&mut sim.simulator, 2).unwrap(), Some(2)); + assert_eq!(sim.time(), 2); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.next_event_time(), Some(4)); + } + fn unknown(mut sim: Simulation, payload: u8, edge: Edge) { + assert_eq!( + sim.get_four_state(sim.signal("clk")), + (payload.into(), 1u8.into()) + ); + sim.run_until(0).unwrap(); + assert_eq!( + sim.get(sim.signal("q")), + u8::from(edge == Edge::Posedge).into() + ); + assert_eq!( + sim.get_four_state(sim.signal("clk")), + (1u8.into(), 0u8.into()) + ); + assert_eq!(sim.ticks(), 1); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + #[test] + fn settle_at_drains_a_generated_fall_at_the_target() { + let build = || Simulator::from_frontend(design(None, Edge::Negedge)); + fall(Simulation::new(build().build_interpreter().unwrap())); + fall(Simulation::new(build().build_cranelift().unwrap())); + fall(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + fall(Simulation::new(build().build_native().unwrap())); + } + #[test] + fn unknown_initial_clock_payloads_have_the_same_edge_sequence() { + for (payload, edge) in [ + (0, Edge::Posedge), + (1, Edge::Posedge), + (0, Edge::Negedge), + (1, Edge::Negedge), + ] { + let build = || Simulator::from_frontend(design(Some(payload), edge)).four_state(true); + unknown( + Simulation::new(build().build_interpreter().unwrap()), + payload, + edge, + ); + unknown( + Simulation::new(build().build_cranelift().unwrap()), + payload, + edge, + ); + unknown( + Simulation::new(build().build_wasm().unwrap()), + payload, + edge, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + unknown( + Simulation::new(build().build_native().unwrap()), + payload, + edge, + ); + } + } +} From 512ead9b74725ed9ee530b82bf67cdb561aca09e Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 08:44:27 +0900 Subject: [PATCH 22/42] fix(runtime): retain and retry normalizing clock falls --- crates/celox-runtime/src/simulation.rs | 12 ++++- crates/celox/src/simulation.rs | 72 ++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index e688baca6e4..1d1fba6792a 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -597,6 +597,7 @@ impl SimulationState { && (!self.last_clock_values.contains(**id) || self.unknown_clock_values.contains(**id)); (!events_to_process.is_empty() || pending_rise) + && !falling.contains(*id) && clock.next_edge == current_time && self.clock_has_waiters(**id) && (!high || pending_rise) @@ -705,6 +706,7 @@ impl SimulationState { // edge that counts is then a real one. let mut events = Vec::with_capacity(due.len()); let mut rising = Vec::with_capacity(due.len()); + let mut falling = Vec::new(); for id in due { let clock = &self.tick_clocks[id]; let high = sample_event_signal(executor.backend(), clock.signal) == (true, false); @@ -716,10 +718,18 @@ impl SimulationState { }); if !high { rising.push(*id); + } else { + falling.push(*id); } } + for id in &falling { + self.tick_clocks + .get_mut(id) + .expect("a normalizing clock") + .falling_edge = Some(time); + } let result = self.step_round(executor, time, events, Vec::new(), Vec::new(), true); - self.finish_clock_round(time, rising, &[], result) + self.finish_clock_round(time, rising, &falling, result) } fn finish_clock_round( diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index d5e8b51f095..7555bfeba01 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -3179,3 +3179,75 @@ mod staged_edge_review_tests { ); } } + +#[cfg(test)] +mod normalizing_fall_review_tests { + use super::*; + use crate::frontend_sdk::{ + BinaryOp, Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType, + }; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", bit).unwrap(); + m.set_initial(clk, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + let enable = m.input("enable", bit).unwrap(); + let q = m.output("q", bit).unwrap(); + let v = m.output("v", bit).unwrap(); + m.set_initial(q, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + let clock_value = m.read(clk).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 1).unwrap()); + m.register( + m.whole(q).unwrap(), + clock_value, + clk, + Edge::Negedge, + None, + None, + ) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + + let low = m.unary(UnaryOp::BitNot, clock_value, bit).unwrap(); + let enabled = m.read(enable).unwrap(); + let active = m.binary(BinaryOp::And, low, enabled, bit).unwrap(); + let previous = m.read(v).unwrap(); + let toggled = m.unary(UnaryOp::BitNot, previous, bit).unwrap(); + let next = m.mux(active, toggled, zero).unwrap(); + m.assign(m.whole(v).unwrap(), next).unwrap(); + let count = m.constant(Constant::two_state(1u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + assert_eq!(sim.get(sim.signal("clk")), 1u8.into()); + sim.set_wide(sim.signal("enable"), 1u8.into()); + assert!(sim.run_until(0).is_err()); + assert_eq!(sim.ticks(), 0); + let parts = sim.state.export_schedule(&sim.simulator.backend); + assert_eq!(parts.process_clocks[0].falling_edge, Some(0)); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + sim.set_wide(sim.signal("enable"), 0u8.into()); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn failed_initial_falls_publish_before_the_first_rise_on_retry() { + let build = || { + Simulator::from_frontend(design()).true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} From e88f3850a4049971b2f03ba606859baf9a6a7876 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 09:44:03 +0900 Subject: [PATCH 23/42] fix(runtime): keep generated edge retries in their scheduled batches --- crates/celox-runtime/src/simulation.rs | 17 +++++++++++++++++ crates/celox/src/simulation.rs | 10 +++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 884807d5b95..c7ad802a4d8 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -939,6 +939,23 @@ impl SimulationState { }) } + /// Pending external clock/reset changes, excluding drives whose phase + /// belongs to a process clock. Those must retry with their scheduled batch. + pub fn has_unsettled_host_edges(&self, backend: &B) -> bool { + self.topo_signals.iter().any(|(signal, id, _)| { + *id != usize::MAX + && !self + .processes + .iter() + .flat_map(|process| &process.clocks) + .any(|clock| clock.signal == *signal) + && ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ) != sample_event_signal(backend, *signal) + }) + } + /// Whether any process is suspended on an event or a condition. pub fn has_waiting_processes(&self) -> bool { !self.waiting.is_empty() diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 8aa37b2892e..645ad2cd995 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -517,7 +517,7 @@ impl Simulation { if self.state.poll_waiting(&mut self.simulator)? { return Ok(Some(self.state.time())); } - if self.state.has_unsettled_edges(&self.simulator.backend) { + if self.state.has_unsettled_host_edges(&self.simulator.backend) { let time = self.state.time(); if self.state.next_event_time() == Some(time) { self.state.step(&mut self.simulator)?; @@ -603,7 +603,7 @@ impl Simulation { if self.state.poll_waiting_until(&mut self.simulator, limit)? { return Ok(Some(self.state.time())); } - if self.state.has_unsettled_edges(&self.simulator.backend) { + if self.state.has_unsettled_host_edges(&self.simulator.backend) { let time = self.state.time(); if self.state.next_event_time() == Some(time) { self.state.step(&mut self.simulator)?; @@ -627,7 +627,6 @@ impl Simulation { /// [`Self::step`], processes that a host write woke resume first. A time /// before the current time leaves the simulation unchanged. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { - if self.state.is_finished() { return Ok(()); } @@ -635,8 +634,9 @@ impl Simulation { return Ok(()); } self.settle_host_writes()?; - self.state.poll_waiting_until(&mut self.simulator, end_time)?; - if self.state.has_unsettled_edges(&self.simulator.backend) { + self.state + .poll_waiting_until(&mut self.simulator, end_time)?; + if self.state.has_unsettled_host_edges(&self.simulator.backend) { let time = self.state.time(); if self.state.next_event_time() == Some(time) { self.state.step(&mut self.simulator)?; From 77d415207c7c7a3325400fb94be2235f94dd1f82 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 10:46:40 +0900 Subject: [PATCH 24/42] fix(testbench): preserve zero-progress FF failure diagnostics --- crates/celox/src/testbench.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 8319baa6363..b620f78dc87 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1983,7 +1983,7 @@ fn exec_one_detailed( let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; - if completed == 0 || completed > batch { + if (completed == 0 && result.is_ok()) || completed > batch { return ExecResult::Fail( "backend made invalid progress in a deferred tick batch".into(), ); @@ -2051,7 +2051,7 @@ fn exec_one_detailed( let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; - if completed == 0 || completed > batch { + if (completed == 0 && result.is_ok()) || completed > batch { return ExecResult::Fail( "backend made invalid progress in a reset tick batch".into(), ); From 1fbec408fce36dec0172ffd7f514e9d7a722dab2 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 11:10:57 +0900 Subject: [PATCH 25/42] test(runtime): register competing clocks at a valid current time --- crates/celox/tests/processes.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 44b0ba311d4..ceed76220f7 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -1127,7 +1127,8 @@ fn periodic_and_process_generators_for_one_clock_are_rejected() { } let count = sim.get(sim.signal("count")); let ticks = sim.ticks(); - sim.add_clock("clk", 4, 0); + // Register a valid current-time edge so this tests competing drivers. + sim.add_clock("clk", 4, sim.time()); let error = sim.step().unwrap_err(); assert!( error.to_string().contains("already driven by add_clock"), From 752cc652e1f658a191df119535babb27db17e2cd Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 12:32:02 +0900 Subject: [PATCH 26/42] fix(runtime): bound coincident host edges in timed runs --- crates/celox/src/simulation.rs | 95 ++++++++++++++++++++++++++++++++-- 1 file changed, 90 insertions(+), 5 deletions(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index f4c5cf2f874..70a3c8b7c5b 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -637,11 +637,10 @@ impl Simulation { .has_unsettled_active_edges(&self.simulator.backend); let queued = self.state.next_event_time() == Some(time); if queued { - self.state.step(&mut self.simulator)?; - } else { - self.state.settle_at(&mut self.simulator, time)?; + return self.state.step_until(&mut self.simulator, limit); } - if active || queued { + self.state.settle_at(&mut self.simulator, time)?; + if active { return Ok(Some(time)); } } @@ -672,7 +671,7 @@ impl Simulation { if self.state.has_unsettled_host_edges(&self.simulator.backend) { let time = self.state.time(); if self.state.next_event_time() == Some(time) { - self.state.step(&mut self.simulator)?; + self.state.step_until(&mut self.simulator, end_time)?; } else { self.state.settle_at(&mut self.simulator, time)?; } @@ -3689,3 +3688,89 @@ mod queued_derived_ff_review_tests { check(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(test)] +mod coincident_host_edge_limit_review_tests { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let byte = ValueType::bits(8).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let host = m.input("host", bit).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let seen = m.output("seen", bit).unwrap(); + let q = m.output("q", byte).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(seen).unwrap(); + m.register(target, one, host, Edge::Posedge, None, None) + .unwrap(); + let value = m.read(q).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, value, one, byte).unwrap(); + let target = m.whole(q).unwrap(); + m.register(target, next, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(8u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation, method: &str, limit: u64) { + sim.set_wide(sim.signal("host"), 1u8.into()); + if method == "step_until" { + let reached = sim.step_until(limit).unwrap().unwrap(); + assert_eq!(reached, sim.time()); + assert!(reached <= limit); + } else { + sim.run_until(limit).unwrap(); + } + if method == "run_until" { + assert_eq!(sim.time(), limit); + } + let ticks = 1 + sim.time() / 4; + assert_eq!(sim.ticks(), ticks); + assert_eq!(sim.get(sim.signal("q")), (ticks as u8).into()); + assert_eq!(sim.get(sim.signal("seen")), 1u8.into()); + sim.run_until(4).unwrap(); + assert_eq!(sim.time(), 4); + assert_eq!(sim.ticks(), 2); + assert_eq!(sim.get(sim.signal("q")), 2u8.into()); + sim.run_until(28).unwrap(); + assert_eq!(sim.ticks(), 8); + assert_eq!(sim.get(sim.signal("q")), 8u8.into()); + } + #[test] + fn coincident_host_edges_do_not_fuse_past_public_time_limits() { + for (method, limit) in [ + ("step_until", 0), + ("step_until", 4), + ("run_until", 0), + ("run_until", 4), + ] { + let build = || Simulator::from_frontend(design()); + check( + Simulation::new(build().build_interpreter().unwrap()), + method, + limit, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + method, + limit, + ); + check( + Simulation::new(build().build_wasm().unwrap()), + method, + limit, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + method, + limit, + ); + } + } +} From d4d5ed4a79f88f23797975303a1587c216a03477 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 14:00:32 +0900 Subject: [PATCH 27/42] fix(runtime): return the time reached by coincident steps --- crates/celox/src/simulation.rs | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index c45c3732bf0..73d5d58a4ed 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -548,11 +548,10 @@ impl Simulation { .has_unsettled_active_edges(&self.simulator.backend); let queued = self.state.next_event_time() == Some(time); if queued { - self.state.step(&mut self.simulator)?; - } else { - self.state.settle_at(&mut self.simulator, time)?; + return self.state.step(&mut self.simulator); } - if active || queued { + self.state.settle_at(&mut self.simulator, time)?; + if active { return Ok(Some(time)); } } @@ -3700,10 +3699,17 @@ mod coincident_host_edge_limit_review_tests { use super::*; use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; fn design() -> crate::frontend_sdk::FrontendArtifact { + design_with_initial_host(false) + } + fn design_with_initial_host(high: bool) -> crate::frontend_sdk::FrontendArtifact { let bit = ValueType::bits(1).unwrap(); let byte = ValueType::bits(8).unwrap(); let mut m = ModuleBuilder::new("Top").unwrap(); let host = m.input("host", bit).unwrap(); + if high { + m.set_initial(host, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + } let clk = m.internal("clk", bit).unwrap(); let seen = m.output("seen", bit).unwrap(); let q = m.output("q", byte).unwrap(); @@ -3747,6 +3753,25 @@ mod coincident_host_edge_limit_review_tests { assert_eq!(sim.ticks(), 8); assert_eq!(sim.get(sim.signal("q")), 8u8.into()); } + #[test] + fn coincident_host_edges_report_the_time_reached_by_step() { + fn check(mut sim: Simulation) { + sim.set_wide(sim.signal("host"), 0u8.into()); + let reached = sim.step().unwrap().unwrap(); + assert_eq!(reached, sim.time()); + assert_eq!(sim.get(sim.signal("q")), (sim.ticks() as u8).into()); + sim.run_until(28).unwrap(); + assert_eq!(sim.ticks(), 8); + assert_eq!(sim.get(sim.signal("q")), 8u8.into()); + } + let build = || Simulator::from_frontend(design_with_initial_host(true)); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + #[test] fn coincident_host_edges_do_not_fuse_past_public_time_limits() { for (method, limit) in [ From fe70e04a178ba2503e0eb060f501d2533f138593 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 23:56:44 +0900 Subject: [PATCH 28/42] fix(runtime): bound immediate zero-count clock continuations --- crates/celox-runtime/src/simulation.rs | 4 +++- crates/celox/tests/processes.rs | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index fdbbcaa5799..c5af892e36d 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1157,7 +1157,9 @@ impl SimulationState { }; self.waiting.remove(&process); if count == 0 { - // A zero-count wait does not yield to another process. + // A zero-count wait does not yield to another process, + // but repeated immediate continuations must be bounded. + count_delta_pass(delta_rounds)?; continue; } else { let id = clock.event.id(); diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index ceed76220f7..48f690629c8 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -1229,3 +1229,22 @@ fn newly_started_process_clocks_share_scheduled_domains_pre_edge_state() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(Simulation::from_frontend(design()).build_native().unwrap()); } + +#[test] +fn repeating_zero_count_clock_waits_report_non_progress() { + let (mut module, clk, _) = clocked_by_process_waits(2); + let zero = constant(&mut module, 0, 64); + module + .process(vec![Statement::Forever { + body: vec![Statement::ClockCycles { + clock: clk, + count: zero, + }], + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("delta limit"), "{error}"); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 0); +} From 31629232ba8663c54a54601b7c15bf9eed04ce28 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 03:53:40 +0900 Subject: [PATCH 29/42] fix(runtime): batch derived process edges and reject aliased clock drivers --- crates/celox-runtime/src/simulation.rs | 16 +++++- crates/celox/src/backend/native/backend.rs | 33 +++++++++++- crates/celox/tests/processes.rs | 62 ++++++++++++++++++++++ 3 files changed, 109 insertions(+), 2 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 5143f4b2076..bbb87a4856b 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1368,6 +1368,7 @@ impl SimulationState { executor.backend_mut().clear_triggered_bits(); let counter_values = self.event_counter_values(executor.backend()); let mut process_driven = Vec::new(); + let mut process_settled = false; if !ready_processes.is_empty() || !self.waiting.is_empty() { let before: Vec<(bool, bool)> = self .topo_signals @@ -1382,6 +1383,16 @@ impl SimulationState { if !progressed && !settle_idle && events_to_process.is_empty() { return Ok(false); } + // Discover combinationally derived edges before choosing the + // generated clocks that must share this publication round. + if progressed { + executor.eval_comb()?; + process_settled = true; + if executor.finish_requested(current_time) { + self.finished = true; + return Ok(true); + } + } for ((signal, id, _), before) in self.topo_signals.iter().zip(before) { if *id == usize::MAX { continue; @@ -1442,6 +1453,7 @@ impl SimulationState { .ok_or_else(|| clock_overflow(id))?; } for event in &generated_events { + process_settled = false; executor.backend_mut().set(event.signal, event.next_val); } events_to_process.extend(generated_events); @@ -1477,7 +1489,9 @@ impl SimulationState { } } - executor.eval_comb()?; + if !process_settled { + executor.eval_comb()?; + } self.round_evaluated = true; if executor.finish_requested(current_time) { self.finished = true; diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 88621a83de5..4166f9ff595 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -595,7 +595,11 @@ impl NativeProgramImage { .runtime_schema .rtl_writes .iter() - .any(|write| write.id == clock.signal) + .any(|write| { + let clock_bit=self.layout.offsets.get(&clock.signal).and_then(|offset|offset.checked_mul(8)); + let written=self.layout.offsets.get(&write.id).and_then(|offset|offset.checked_mul(8)).and_then(|base|Some((base.checked_add(write.access.lsb)?,base.checked_add(write.access.msb)?))); + matches!((clock_bit,written),(Some(clock),Some((first,last))) if first<=clock && clock<=last) + }) { return Err("a process clock is driven by design logic".into()); } @@ -3470,6 +3474,33 @@ mod process_metadata_tests { } } + #[test] + fn aliased_rtl_storage_cannot_drive_a_process_clock() { + let mut broken = image(); + broken.to_container_bytes().unwrap(); + let clock = broken.runtime_schema.processes[0].clocks[0].signal; + let driver = broken + .runtime_schema + .rtl_writes + .iter() + .find(|write| write.id != clock) + .unwrap() + .id; + assert_ne!(driver, clock); + assert_ne!( + broken.layout.offsets[&driver], + broken.layout.offsets[&clock] + ); + broken + .layout + .offsets + .insert(clock, broken.layout.offsets[&driver]); + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + #[test] fn process_clock_periods_must_agree_across_slot_tables() { let mut broken = image(); diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 48f690629c8..36e6d5400c4 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -1248,3 +1248,65 @@ fn repeating_zero_count_clock_waits_report_non_progress() { assert_eq!(sim.time(), 0); assert_eq!(sim.ticks(), 0); } + +#[test] +fn due_process_clock_batches_with_a_combinationally_derived_edge() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let bit = ValueType::bits(1).unwrap(); + let src = module.internal("src", bit).unwrap(); + let enable = module.input("enable", bit).unwrap(); + let gated = module.internal("gated", bit).unwrap(); + let b = module.output("b", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let src_expr = module.read(src).unwrap(); + let en_expr = module.read(enable).unwrap(); + let value = module + .binary(BinaryOp::And, src_expr, en_expr, bit) + .unwrap(); + let gate_target = module.whole(gated).unwrap(); + module.assign(gate_target, value).unwrap(); + let one = constant(&mut module, 1, 1); + let b_target = module.whole(b).unwrap(); + module + .register(b_target, one, gated, Edge::Posedge, None, None) + .unwrap(); + let b_expr = module.read(b).unwrap(); + let q_target = module.whole(q).unwrap(); + module + .register(q_target, b_expr, clk, Edge::Posedge, None, None) + .unwrap(); + let three = constant(&mut module, 3, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: three, + }]) + .unwrap(); + let four = constant(&mut module, 4, 64); + let src_target = module.whole(src).unwrap(); + module + .process(vec![ + Statement::Delay { amount: four }, + Statement::Assign { + target: src_target, + value: one, + }, + ]) + .unwrap(); + let artifact = module.finish(); + fn check(mut sim: Simulation) { + let en = sim.signal("enable"); + sim.modify(|io| io.set(en, 1u8)).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("b")), 1u8.into()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + sim.run_until(8).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let build = || Simulation::from_frontend(artifact.clone()); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} From a2bcf6a367124d0d5ba089d40c41eb287e6e1f47 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 04:40:57 +0900 Subject: [PATCH 30/42] fix(native): bind process clock controls to compiled kernels --- crates/celox/src/backend/native/backend.rs | 67 +++++++++++++++++++ crates/celox/src/backend/native/image_file.rs | 2 +- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 4166f9ff595..bc0ea6c8262 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -409,6 +409,8 @@ pub struct NativeProgramImage { comb_unit_offsets: Vec, /// Entry offset of each process kernel. process_offsets: Vec, + /// Clock-control addresses and byte offsets used to compile each process kernel. + compiled_process_clocks: Vec<(AbsoluteAddr, usize)>, required_native_features: u8, event_map: HashMap, eval_only_event_map: HashMap, @@ -558,6 +560,19 @@ impl NativeProgramImage { if self.process_offsets.len() != self.runtime_schema.processes.len() { return Err("process kernels and their control slots disagree".into()); } + if self.compiled_process_clocks.len() != self.runtime_schema.processes.len() + || self + .compiled_process_clocks + .iter() + .zip(&self.runtime_schema.processes) + .any(|((address, offset), process)| { + process.clock != *address || self.layout.offsets.get(address) != Some(offset) + }) + { + return Err( + "process clock control slots disagree with compiled kernel bindings".into(), + ); + } let mut process_clock_periods = fxhash::FxHashMap::default(); for process in &self.runtime_schema.processes { if !self @@ -2316,6 +2331,13 @@ fn compile_program( comb_offset, comb_unit_offsets, process_offsets, + compiled_process_clocks: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| (process.clock, layout.offsets[&process.clock])) + .collect(), required_native_features, event_map, eval_only_event_map, @@ -3404,6 +3426,9 @@ mod process_metadata_tests { let mut module = ModuleBuilder::new("Top").unwrap(); let clk = module.internal("clk", bit).unwrap(); let q = module.output("q", bit).unwrap(); + module + .output("unrelated", ValueType::bits(32).unwrap()) + .unwrap(); let one = module.constant(Constant::two_state(1u8, 1).unwrap()); let target = module.whole(q).unwrap(); module @@ -3428,6 +3453,48 @@ mod process_metadata_tests { .into_program_image() } + #[test] + fn process_clock_control_cannot_name_an_unrelated_register() { + let original = image(); + original.to_container_bytes().unwrap(); + let clock = original.runtime_schema.processes[0].clock; + let unrelated = *original + .design + .state_objects + .iter() + .find(|(addr, metadata)| { + **addr != clock + && metadata.width == celox_design::PROCESS_CLOCK_WIDTH + && !original + .runtime_schema + .processes + .iter() + .any(|p| [p.resume, p.status, p.delay, p.clock].contains(addr)) + }) + .unwrap() + .0; + let mut broken = original.clone(); + broken.runtime_schema.processes[0].clock = unrelated; + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + + #[test] + fn process_clock_control_layout_matches_the_compiled_kernel() { + let mut broken = image(); + let process = &broken.runtime_schema.processes[0]; + broken + .layout + .offsets + .insert(process.clock, broken.layout.offsets[&process.resume]); + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + #[test] fn process_clock_metadata_is_checked_before_image_attachment() { let original = image(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 4b2fa8babe4..94ab446af5b 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 17; +const CONTAINER_VERSION: u16 = 18; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; From 6d5f980620d320b8e7795828e36e6cf205b294b5 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:09:21 +0900 Subject: [PATCH 31/42] fix(runtime): bind native clock metadata and detect escaped clock writes --- crates/celox-runtime/src/simulation.rs | 16 +++++ crates/celox/src/backend/native/backend.rs | 68 +++++++++++++++++-- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 62 +++++++++++++++++ crates/celox/src/simulator.rs | 3 + 5 files changed, 146 insertions(+), 5 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 1d28d20de15..bab39649742 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -563,6 +563,22 @@ impl SimulationState { Ok(()) } + /// Clock signals changed outside a scheduler round through retained memory. + pub fn escaped_host_clock_writes(&self, backend: &B) -> Vec { + self.processes + .iter() + .flat_map(|process| &process.clocks) + .filter_map(|clock| { + let id = clock.event.id(); + let baseline = ( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + ); + (baseline != sample_event_signal(backend, clock.signal)).then_some(clock.signal) + }) + .collect() + } + /// A generated process clock owns its signal, including before its first wait. pub fn validate_host_write(&self, signal: SignalRef) -> Result<(), SimulatorErrorCode> { if let Some(clock) = self diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index bc0ea6c8262..01dd165c08e 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -411,6 +411,8 @@ pub struct NativeProgramImage { process_offsets: Vec, /// Clock-control addresses and byte offsets used to compile each process kernel. compiled_process_clocks: Vec<(AbsoluteAddr, usize)>, + compiled_process_clock_lists: Vec>>, + compiled_clock_phase_sensitive_comb: bool, required_native_features: u8, event_map: HashMap, eval_only_event_map: HashMap, @@ -626,6 +628,20 @@ impl NativeProgramImage { } } } + if self.compiled_process_clock_lists.len() != self.runtime_schema.processes.len() + || self + .compiled_process_clock_lists + .iter() + .zip(&self.runtime_schema.processes) + .any(|(compiled, process)| compiled != &process.clocks) + { + return Err("process clock lists disagree with compiled kernel indices".into()); + } + if self.compiled_clock_phase_sensitive_comb + != self.runtime_schema.clock_phase_sensitive_comb + { + return Err("clock phase sensitivity disagrees with compiled kernels".into()); + } for counters in &self.runtime_schema.process_event_counters { if !self.event_map.contains_key(&counters.signal) { return Err("a process edge counter names an unknown event domain".into()); @@ -2338,6 +2354,17 @@ fn compile_program( .iter() .map(|process| (process.clock, layout.offsets[&process.clock])) .collect(), + compiled_process_clock_lists: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| process.clocks.clone()) + .collect(), + compiled_clock_phase_sensitive_comb: sir + .runtime() + .runtime_schema + .clock_phase_sensitive_comb, required_native_features, event_map, eval_only_event_map, @@ -3425,6 +3452,7 @@ mod process_metadata_tests { let bit = ValueType::bits(1).unwrap(); let mut module = ModuleBuilder::new("Top").unwrap(); let clk = module.internal("clk", bit).unwrap(); + let clk2 = module.internal("clk2", bit).unwrap(); let q = module.output("q", bit).unwrap(); module .output("unrelated", ValueType::bits(32).unwrap()) @@ -3434,12 +3462,24 @@ mod process_metadata_tests { module .register(target, one, clk, Edge::Posedge, None, None) .unwrap(); + let q2 = module.output("q2", bit).unwrap(); + let target2 = module.whole(q2).unwrap(); + module + .register(target2, one, clk2, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk2, 4).unwrap(); module.clock_period(clk, 2).unwrap(); module - .process(vec![Statement::ClockCycles { - clock: clk, - count: one, - }]) + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: one, + }, + Statement::ClockCycles { + clock: clk2, + count: one, + }, + ]) .unwrap(); module .process(vec![Statement::ClockCycles { @@ -3453,6 +3493,26 @@ mod process_metadata_tests { .into_program_image() } + #[test] + fn process_clock_lists_match_the_compiled_indices() { + let original = image(); + original.to_container_bytes().unwrap(); + assert_eq!(original.runtime_schema.processes[0].clocks.len(), 2); + let mut broken = original.clone(); + broken.runtime_schema.processes[0].clocks.swap(0, 1); + assert!(broken.to_container_bytes().is_err()); + let mut broken = original.clone(); + broken.runtime_schema.processes[0].clocks[0] = + original.runtime_schema.processes[0].clocks[1]; + assert!(broken.to_container_bytes().is_err()); + } + #[test] + fn clock_phase_sensitivity_matches_compilation() { + let mut broken = image(); + broken.runtime_schema.clock_phase_sensitive_comb = + !broken.runtime_schema.clock_phase_sensitive_comb; + assert!(broken.to_container_bytes().is_err()); + } #[test] fn process_clock_control_cannot_name_an_unrelated_register() { let original = image(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 94ab446af5b..73fcb41cc13 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 18; +const CONTAINER_VERSION: u16 = 19; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index b385000881b..18a2beb88c9 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -447,6 +447,19 @@ impl Simulation { self.simulator.signal(path) } + fn record_escaped_host_clock_writes(&mut self) { + if self.simulator.escaped_mutable_memory { + for signal in self + .state + .escaped_host_clock_writes(&self.simulator.backend) + { + if !self.simulator.pending_host_writes.contains(&signal) { + self.simulator.pending_host_writes.push(signal); + } + } + } + } + fn synchronize_runtime_finish(&mut self, was_dirty: bool) { if self.simulator.has_pending_runtime_finish() { self.state.finish(); @@ -460,6 +473,7 @@ impl Simulation { /// Retrieves the current value of a variable using a pre-resolved [`SignalRef`] handle. pub fn get(&mut self, signal: SignalRef) -> num_bigint::BigUint { + self.record_escaped_host_clock_writes(); let was_dirty = self.simulator.dirty; let value = if self.state.is_finished() { self.simulator.backend.get(signal) @@ -475,6 +489,7 @@ impl Simulation { &mut self, signal: SignalRef, ) -> (num_bigint::BigUint, num_bigint::BigUint) { + self.record_escaped_host_clock_writes(); let was_dirty = self.simulator.dirty; let value = if self.state.is_finished() { self.simulator.backend.get_four_state(signal) @@ -644,6 +659,7 @@ impl Simulation { if self.state.is_finished() { return Ok(()); } + self.record_escaped_host_clock_writes(); let writes = self.simulator.take_host_writes(); for &signal in &writes { if let Err(error) = self.state.validate_host_write(signal) { @@ -773,6 +789,7 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + self.record_escaped_host_clock_writes(); let was_dirty = self.simulator.dirty; let events = if self.state.is_finished() { self.simulator.drain_runtime_events_without_evaluation() @@ -790,6 +807,10 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + self.record_escaped_host_clock_writes(); + for &signal in &self.simulator.pending_host_writes { + self.state.validate_host_write(signal)?; + } self.simulator.eval_comb()?; if self.simulator.has_pending_runtime_finish() { self.state.finish(); @@ -3004,6 +3025,47 @@ mod host_clock_review_tests { settle(Simulation::new(build().build_native().unwrap())); } #[test] + fn retained_memory_cannot_inject_generated_clock_edges() { + fn check(mut sim: Simulation, explicit: bool) { + let clk = sim.signal("clk"); + let (ptr, len) = sim.memory_as_mut_ptr(); + assert!(clk.offset < len); + sim.run_until(1).unwrap(); + assert_eq!(sim.ticks(), 1); + unsafe { + ptr.add(clk.offset).write(1); + } + let result = if explicit { + sim.eval_comb() + } else { + sim.run_until(2) + }; + assert!( + result + .unwrap_err() + .to_string() + .contains("direct host write") + ); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.time(), 1); + assert_eq!(sim.simulator.backend.get(sim.signal("q")), 1u8.into()); + } + for explicit in [false, true] { + let build = || Simulator::from_frontend(design()); + check( + Simulation::new(build().build_interpreter().unwrap()), + explicit, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + explicit, + ); + check(Simulation::new(build().build_wasm().unwrap()), explicit); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), explicit); + } + } + #[test] fn direct_host_clock_writes_are_rejected_before_activation() { let build = || Simulator::from_frontend(design()); for mode in 0..4 { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index eb9d572c66f..f47b5b84e18 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -102,6 +102,7 @@ mod host { pub(crate) dirty: bool, pub(crate) pending_host_writes: Vec, host_clock_signals: Vec, + pub(crate) escaped_mutable_memory: bool, pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, pub(crate) component_simulation: Option>, @@ -705,6 +706,7 @@ mod host { vcd_writer: None, dirty: false, pending_host_writes: Vec::new(), + escaped_mutable_memory: false, warnings, components: Default::default(), component_simulation: None, @@ -1629,6 +1631,7 @@ mod host { /// Returns a mutable raw pointer to the backend memory and its total size in bytes. pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { + self.escaped_mutable_memory = true; self.backend.memory_as_mut_ptr() } From 7d0989673eb4646a1c8f039920898298138e8c7c Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:25:51 +0900 Subject: [PATCH 32/42] fix(runtime): reject checkpoints with escaped clock mutations --- crates/celox/src/simulation.rs | 35 ++++++++++++++++++++++++ crates/celox/src/simulator/checkpoint.rs | 4 +++ 2 files changed, 39 insertions(+) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 620fa6f7404..d032b904a64 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -359,6 +359,14 @@ impl Simulation { /// Save the design state, simulation time, clocks and pending events. pub fn checkpoint(&self) -> Result, CheckpointError> { + if self.simulator.escaped_mutable_memory + && !self + .state + .escaped_host_clock_writes(&self.simulator.backend) + .is_empty() + { + return Err(CheckpointError::UntrackedHostClockWrite); + } Ok(SimulationCheckpoint { simulator: self.simulator.checkpoint()?, schedule: self.state.snapshot(), @@ -3027,6 +3035,33 @@ mod host_clock_review_tests { settle(Simulation::new(build().build_native().unwrap())); } #[test] + fn checkpoint_rejects_escaped_generated_clock_writes() { + fn check(mut sim: Simulation) { + let clk = sim.signal("clk"); + let (ptr, len) = sim.memory_as_mut_ptr(); + assert!(clk.offset < len); + sim.run_until(1).unwrap(); + sim.checkpoint().unwrap(); + unsafe { + ptr.add(clk.offset).write(1); + } + assert!(sim.checkpoint().is_err()); + unsafe { + ptr.add(clk.offset).write(0); + } + let checkpoint = sim.checkpoint().unwrap(); + sim.restore(&checkpoint).unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(sim.ticks(), 2); + } + let build = || Simulator::from_frontend(design()); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + #[test] fn retained_memory_cannot_inject_generated_clock_edges() { fn check(mut sim: Simulation, explicit: bool) { let clk = sim.signal("clk"); diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index fbaba00d2a2..e601cd720c8 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -116,6 +116,10 @@ impl std::fmt::Debug for Checkpoint { /// Reasons a checkpoint cannot be taken or restored. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CheckpointError { + #[error( + "cannot checkpoint a process clock changed by a direct host write through escaped memory" + )] + UntrackedHostClockWrite, /// External component instances hold opaque state. They currently exist /// only while a testbench runs, when no checkpoint can be taken. #[error( From 0b5300e301fee03d0e65583b634b7fbce41c5cdc Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 08:46:20 +0900 Subject: [PATCH 33/42] fix(runtime): batch captured host edges with clock activation --- crates/celox-runtime/src/simulation.rs | 7 +++- crates/celox/src/simulation.rs | 54 ++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 707eb8f1d9e..35078450373 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1072,7 +1072,8 @@ impl SimulationState { return Ok(false); } self.sample_waiting_events(executor)?; - let result = self.step_round(executor, time, Vec::new(), Vec::new(), Vec::new(), false); + let ready = self.take_ready_processes(time); + let result = self.step_round(executor, time, Vec::new(), Vec::new(), ready, false); let progressed = result.as_ref().is_ok_and(|ran| *ran); self.finish_clock_round(time, Vec::new(), &[], result)?; if !progressed { @@ -1475,12 +1476,14 @@ impl SimulationState { // to existing source events before any coincident FF domain commits. // With no other event, retain the later fused-tick path. if !self.finished - && (!events_to_process.is_empty() + && (!scheduled_edges.is_empty() + || !events_to_process.is_empty() || !process_driven.is_empty() || !generated_events.is_empty()) { for (id, clock) in &self.tick_clocks { if clock.next_edge == current_time + && clock.falling_edge != Some(current_time) && self.clock_has_waiters(*id) && sample_event_signal(executor.backend(), clock.signal) != (true, false) && !events_to_process diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index a71f39da9fc..12114a17a44 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -4989,3 +4989,57 @@ mod nba_waiter_sampling_review { check(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(test)] +mod host_clock_activation_review { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let host = m.input("host", bit).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let source = m.output("source", bit).unwrap(); + let sampled = m.output("sampled", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(source).unwrap(); + m.register(target, one, host, Edge::Posedge, None, None) + .unwrap(); + let old = m.read(source).unwrap(); + let target = m.whole(sampled).unwrap(); + m.register(target, old, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + let host = sim.signal("host"); + sim.modify(|io| io.set(host, 1u8)).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("source")), 1u8.into()); + assert_eq!(sim.get(sim.signal("sampled")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn captured_host_edges_share_pre_edge_state_with_first_clock_wait() { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} From 80e4e9737fc03c0aa31ee0ff3172eb7bad305520 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 08:50:48 +0900 Subject: [PATCH 34/42] fix(test): preserve module boundaries when integrating review regressions --- crates/celox/src/simulation.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 9e94be210f3..9bc775b49cc 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -4989,7 +4989,12 @@ mod nba_waiter_sampling_review { check(Simulation::new(build().build_interpreter().unwrap())); check(Simulation::new(build().build_cranelift().unwrap())); check(Simulation::new(build().build_wasm().unwrap())); - #[cfg(test)] + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + +#[cfg(test)] mod host_clock_activation_review { use super::*; use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; From 22812d08b2807de72019c8bdb0782475bc9b11f6 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 09:38:36 +0900 Subject: [PATCH 35/42] fix(runtime): batch transient process edges with clock activation --- crates/celox-runtime/src/simulation.rs | 8 ++- crates/celox/src/simulation.rs | 80 ++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 7c07d132ac2..0970eb1a770 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1463,6 +1463,8 @@ impl SimulationState { generated_events.clear(); } + let process_recorded_edges = self.counter_edges(executor.backend(), &counter_values); + // Ready processes may activate a clock at this timestamp. Join it // to existing source events before any coincident FF domain commits. // With no other event, retain the later fused-tick path. @@ -1470,7 +1472,9 @@ impl SimulationState { && (!scheduled_edges.is_empty() || !events_to_process.is_empty() || !process_driven.is_empty() - || !generated_events.is_empty()) + || !generated_events.is_empty() + || !process_recorded_edges.is_empty() + || !executor.backend().get_triggered_bits().is_empty()) { for (id, clock) in &self.tick_clocks { if clock.next_edge == current_time @@ -1517,7 +1521,7 @@ impl SimulationState { let mut discovered_in_this_step = BitSet::with_capacity(num_events); // Counter-recorded kernel edges survive later blocking stores that // restored the signal before the kernel returned. - let mut recorded_edges = self.counter_edges(executor.backend(), &counter_values); + let mut recorded_edges = process_recorded_edges; recorded_edges.union_with(&scheduled_edges); let mut scheduled_trigger_ids = recorded_edges.clone(); // An external drive may already have been combinationally evaluated diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index a4a43fd5792..b4371782563 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -5250,3 +5250,83 @@ mod cross_depth_write_review { } } } + +#[cfg(test)] +mod transient_clock_activation_review { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let host = m.internal("host", bit).unwrap(); + let word = ValueType::bits(32).unwrap(); + let rises = m.internal("rises", word).unwrap(); + let falls = m.internal("falls", word).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let source = m.output("source", bit).unwrap(); + let sampled = m.output("sampled", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(source).unwrap(); + m.register(target, one, host, Edge::Posedge, None, None) + .unwrap(); + let old = m.read(source).unwrap(); + let target = m.whole(sampled).unwrap(); + m.register(target, old, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + let high = m.constant(Constant::two_state(1u8, 1).unwrap()); + let low = m.constant(Constant::two_state(0u8, 1).unwrap()); + let target = m.whole(host).unwrap(); + let edge = m.constant(Constant::two_state(1u8, 32).unwrap()); + m.process(vec![ + Statement::Assign { + target, + value: high, + }, + Statement::Assign { target, value: low }, + Statement::Assign { + target: m.whole(rises).unwrap(), + value: edge, + }, + Statement::Assign { + target: m.whole(falls).unwrap(), + value: edge, + }, + Statement::ClockCycles { + clock: clk, + count: one, + }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + let signal = sim.signal("host"); + let rises = sim.signal("rises"); + let falls = sim.signal("falls"); + sim.state = sim + .state + .with_process_event_counters(vec![(signal, rises, falls)]); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("source")), 1u8.into()); + assert_eq!(sim.get(sim.signal("sampled")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn transient_process_edges_share_pre_edge_state_with_first_clock_wait() { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} From 7ffa018bbffa43244e112a3fa9c18d7d9d62f479 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 10:16:52 +0900 Subject: [PATCH 36/42] fix(runtime): retain clock drive ownership across timestamps --- crates/celox-runtime/src/simulation.rs | 10 ++++------ crates/celox/src/simulation.rs | 26 +++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 065838227a0..562f7231e19 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -634,10 +634,9 @@ impl SimulationState { } else { Vec::new() }; - if self.scheduled_clock_time != current_time { - self.scheduled_clock_drives.make_empty(); - self.scheduled_clock_time = current_time; - } + // A process owns its generated clock even before its first wait. + // Retain consumed scheduled-drive provenance across timestamps. + self.scheduled_clock_time = current_time; for event in &events_to_process { self.scheduled_clock_drives.insert(event.event_ref.id()); if let Some(id) = self.signal_to_id.get(&event.signal) { @@ -979,8 +978,7 @@ impl SimulationState { signals: Vec::new(), }); } - if (self.scheduled_clock_time == self.scheduler.time - && self.scheduled_clock_drives.contains(id)) + if self.scheduled_clock_drives.contains(id) || self .scheduler .event_queue diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 0af755f14ce..4b0cd94c8af 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2314,11 +2314,35 @@ mod clock_provenance_checkpoint_tests { .unwrap(); m.finish() } + #[test] + fn earlier_scheduled_drives_conflict_with_delayed_clock_activation() { + fn check(mut sim: Simulation) { + sim.schedule("clk", 0, 1).unwrap(); + assert_eq!(sim.step().unwrap(), Some(0)); + let error = sim.run_until(2).unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(sim.ticks(), 0); + } + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } fn check(mut sim: Simulation) { sim.schedule("clk", 0, 1).unwrap(); assert_eq!(sim.step().unwrap(), Some(0)); let checkpoint = sim.checkpoint().unwrap(); - sim.run_until(2).unwrap(); + let error = sim.run_until(2).unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); sim.restore(&checkpoint).unwrap(); // Model a host waking the suspended process at the restored timestamp. let mut parts = sim.state.export_schedule(&sim.simulator.backend); From 4d4cb13073c2c4c6e1ea9f720471acbedd254127 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 17:44:57 +0900 Subject: [PATCH 37/42] fix(runtime): retain rejected process clock activations --- crates/celox-runtime/src/simulation.rs | 4 +- crates/celox/src/simulation.rs | 54 ++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index e5964eaa832..d6d08f9eb3b 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1222,7 +1222,6 @@ impl SimulationState { continue; } else { let id = clock.event.id(); - self.check_clock_generator(id)?; let tick_clock = self.tick_clocks.entry(id).or_insert_with(|| TickClock { event: clock.event, @@ -1239,6 +1238,9 @@ impl SimulationState { remaining: count, }, ); + // Retain the activation before validation so + // retries cannot skip the failed suspension. + self.check_clock_generator(id)?; } any_ran = true; } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 62d619907c5..0dde785db8b 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2315,6 +2315,60 @@ mod clock_provenance_checkpoint_tests { m.finish() } #[test] + fn failed_clock_activations_remain_errors_on_retry() { + fn check(mut sim: Simulation, scheduled: bool) { + if scheduled { + sim.schedule("clk", 0, 1).unwrap(); + } else { + sim.add_clock("clk", 4, 0); + } + assert_eq!(sim.step().unwrap(), Some(0)); + let expected = if scheduled { + "already driven by schedule" + } else { + "already driven by add_clock" + }; + let error = sim.run_until(2).unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + let time = sim.time(); + for _ in 0..2 { + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + let error = sim.run_until(20).unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + assert_eq!(sim.time(), time); + assert_eq!(sim.ticks(), 0); + } + let saved = sim.checkpoint().unwrap(); + sim.restore(&saved).unwrap(); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + } + for scheduled in [false, true] { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + scheduled, + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + scheduled, + ); + check( + Simulation::from_frontend(design()).build_wasm().unwrap(), + scheduled, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::from_frontend(design()).build_native().unwrap(), + scheduled, + ); + } + } + #[test] fn earlier_scheduled_drives_conflict_with_delayed_clock_activation() { fn check(mut sim: Simulation) { sim.schedule("clk", 0, 1).unwrap(); From 9d14ef836f2dc44215fe43ff3fd8cbbd1420fe8a Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 20:13:10 +0900 Subject: [PATCH 38/42] fix(runtime): retain generated drive ownership across clock retries --- crates/celox-runtime/src/simulation.rs | 70 +++++++++++++++-- crates/celox/src/simulation.rs | 101 ++++++++++++++++++++++++- 2 files changed, 164 insertions(+), 7 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 74472d76a7c..15c4b285bf8 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -162,6 +162,9 @@ struct TickClock { period: u64, next_edge: u64, falling_edge: Option, + /// Last level actually driven by this generator, independent of the + /// edge-detection baseline retained until publication succeeds. + driven_value: Option, } impl Clone for TickClock { @@ -172,6 +175,7 @@ impl Clone for TickClock { period: self.period, next_edge: self.next_edge, falling_edge: self.falling_edge, + driven_value: self.driven_value, } } } @@ -192,6 +196,9 @@ pub struct ProcessClockState { pub period: u64, pub next_edge: u64, pub falling_edge: Option, + /// Last generator drive; `None` before its first drive. Retain this + /// across failed rounds independently of the sampled event baseline. + pub driven_value: Option, } /// A process waiting for simulation time to reach `time`. Ordered so that a @@ -324,6 +331,9 @@ impl SimulationState { pub fn synchronize_event_values(&mut self, backend: &B) { self.pending_host_edges.clear(); self.sample_event_values(backend); + for clock in self.tick_clocks.values_mut() { + clock.driven_value = None; + } } fn sample_event_values(&mut self, backend: &B) { @@ -343,13 +353,29 @@ impl SimulationState { } } + fn pending_generated_baseline(&self, id: usize) -> Option<(bool, bool)> { + let driven = self.tick_clocks.get(&id)?.driven_value?; + let baseline = ( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + ); + (baseline != (driven, false)).then_some(baseline) + } + /// Retain FF occurrences observed by a host evaluation until the scheduler runs. pub fn capture_host_edges(&mut self, backend: &B) { if self.finished { return; } + // A failed generated round owns its unpublished source edge. Host + // settling must neither dispatch it nor consume its retry baseline. + let generated_baselines: Vec<_> = self + .tick_clocks + .keys() + .filter_map(|&id| self.pending_generated_baseline(id).map(|value| (id, value))) + .collect(); for (_, id, _) in &self.topo_signals { - if *id == usize::MAX { + if *id == usize::MAX || self.pending_generated_baseline(*id).is_some() { continue; } let info = &self.event_info[*id]; @@ -362,6 +388,18 @@ impl SimulationState { } } self.sample_event_values(backend); + for (id, (value, unknown)) in generated_baselines { + if value { + self.last_clock_values.insert(id); + } else { + self.last_clock_values.remove(id); + } + if unknown { + self.unknown_clock_values.insert(id); + } else { + self.unknown_clock_values.remove(id); + } + } } fn stable_edge_triggered(&self, backend: &B, id: usize) -> bool { @@ -597,15 +635,28 @@ impl SimulationState { .flat_map(|process| &process.clocks) .filter_map(|clock| { let id = clock.event.id(); - let baseline = ( - self.last_clock_values.contains(id), - self.unknown_clock_values.contains(id), - ); - (baseline != sample_event_signal(backend, clock.signal)).then_some(clock.signal) + let expected = self + .tick_clocks + .get(&id) + .and_then(|clock| clock.driven_value) + .map(|value| (value, false)) + .unwrap_or(( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + )); + (expected != sample_event_signal(backend, clock.signal)).then_some(clock.signal) }) .collect() } + fn record_generated_clock_drive(&mut self, event: &SimEvent) { + if let Some(clock) = self.tick_clocks.get_mut(&event.event_ref.id()) + && clock.signal == event.signal + { + clock.driven_value = Some(event.next_val & 1 != 0); + } + } + /// A generated process clock owns its signal, including before its first wait. pub fn validate_host_write(&self, signal: SignalRef) -> Result<(), SimulatorErrorCode> { if let Some(clock) = self @@ -963,9 +1014,11 @@ impl SimulationState { } // Combinational next-state logic samples the rising level of the clock. executor.backend_mut().set(signal, 1u8); + self.tick_clocks.get_mut(&clock).unwrap().driven_value = Some(true); let (completed, result) = executor.tick_many(event, count); if completed == 0 { executor.backend_mut().set(signal, 0u8); + self.tick_clocks.get_mut(&clock).unwrap().driven_value = Some(false); } if completed > count || (completed == 0 && result.is_ok()) { return Err(SimulatorErrorCode::Runtime { @@ -1249,6 +1302,7 @@ impl SimulationState { period: clock.period.max(2), next_edge: current_time, falling_edge: None, + driven_value: None, }); tick_clock.next_edge = tick_clock.next_edge.max(current_time); self.clock_waits.insert( @@ -1411,6 +1465,7 @@ impl SimulationState { }; let before = sample_event_signal(executor.backend(), event.signal); executor.backend_mut().set(event.signal, event.next_val); + self.record_generated_clock_drive(event); let after = sample_event_signal(executor.backend(), event.signal); let mut blocking_source = false; if let Some(&id) = self.signal_to_id.get(&event.signal) @@ -1575,6 +1630,7 @@ impl SimulationState { for event in &generated_events { process_settled = false; executor.backend_mut().set(event.signal, event.next_val); + self.record_generated_clock_drive(event); } events_to_process.extend(generated_events); @@ -2389,6 +2445,7 @@ impl SimulationState { period: clock.period, next_edge: clock.next_edge, falling_edge: clock.falling_edge, + driven_value: clock.driven_value, }) .collect(), clock_waits: self @@ -2458,6 +2515,7 @@ impl SimulationState { period: clock.period, next_edge: clock.next_edge, falling_edge: clock.falling_edge, + driven_value: clock.driven_value, }, ) }) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 75c0258a575..cdb84d4c776 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2102,6 +2102,13 @@ mod clock_failure_progress_tests { } fn module_design(on_rising: bool) -> (ModuleBuilder, crate::frontend_sdk::SignalId) { + module_design_with_failure(on_rising, true) + } + + fn module_design_with_failure( + on_rising: bool, + after_first_rise: bool, + ) -> (ModuleBuilder, crate::frontend_sdk::SignalId) { let bit = ValueType::bits(1).unwrap(); let word = ValueType::bits(32).unwrap(); let mut m = ModuleBuilder::new("Progress").unwrap(); @@ -2139,7 +2146,11 @@ mod clock_failure_progress_tests { let count = m.read(count).unwrap(); let zero = m.constant(Constant::two_state(0u8, 32).unwrap()); let nonzero = m.binary(BinaryOp::NotEqual, count, zero, bit).unwrap(); - let active = m.binary(BinaryOp::And, active, nonzero, bit).unwrap(); + let active = if after_first_rise { + m.binary(BinaryOp::And, active, nonzero, bit).unwrap() + } else { + active + }; let previous = m.read(v).unwrap(); let toggled = m.unary(UnaryOp::BitNot, previous, bit).unwrap(); let zero = m.constant(Constant::two_state(0u8, 1).unwrap()); @@ -2192,6 +2203,87 @@ mod clock_failure_progress_tests { } } + #[test] + fn escaped_memory_preserves_unpublished_generated_phase_retries() { + fn check(mut sim: Simulation, on_rising: bool) { + let clock = sim.signal("clk"); + let (pointer, length) = sim.memory_as_mut_ptr(); + assert!(clock.offset < length); + if !on_rising { + sim.run_until(0).unwrap(); + } + sim.set_wide(sim.signal("bad"), 1u8.into()); + let time = if on_rising { 0 } else { 2 }; + let error = sim.run_until(time).unwrap_err().to_string(); + assert!(!error.contains("direct host write"), "{error}"); + assert_eq!(sim.ticks(), u64::from(!on_rising)); + // Merely obtaining the pointer does not invalidate a retained + // scheduler drive, even before that drive is published. + let checkpoint = sim.checkpoint().unwrap(); + for step in [true, false] { + sim.restore(&checkpoint).unwrap(); + let parts = sim.state.export_schedule(&sim.simulator.backend); + sim.state.import_schedule(parts); + let error = sim.run_until(time).unwrap_err().to_string(); + assert!(!error.contains("direct host write"), "{error}"); + sim.set_wide(sim.signal("bad"), 0u8.into()); + if step { + assert_eq!(sim.step_until(time).unwrap(), Some(time)); + } else { + sim.run_until(time).unwrap(); + } + sim.run_until(2).unwrap(); + assert_eq!( + sim.get(sim.signal("count")), + 1u32.into(), + "rising={on_rising}, step={step}" + ); + assert_eq!(sim.get(sim.signal("falls")), 1u32.into()); + assert_eq!(sim.ticks(), 1); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("count")), 2u32.into()); + assert_eq!(sim.ticks(), 2); + } + sim.restore(&checkpoint).unwrap(); + // A real pointer write back to the OLD sampling baseline must + // still be rejected while the generated drive is pending. + unsafe { + pointer.add(clock.offset).write(u8::from(!on_rising)); + } + assert!(matches!( + sim.checkpoint(), + Err(CheckpointError::UntrackedHostClockWrite) + )); + let error = sim.step_until(time).unwrap_err().to_string(); + assert!(error.contains("direct host write"), "{error}"); + sim.restore(&checkpoint).unwrap(); + sim.set_wide(sim.signal("bad"), 0u8.into()); + sim.run_until(4).unwrap(); + assert_eq!(sim.ticks(), 2); + } + for on_rising in [true, false] { + let build = || { + Simulator::from_frontend(module_design_with_failure(on_rising, false).0.finish()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + on_rising, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + on_rising, + ); + check(Simulation::new(build().build_wasm().unwrap()), on_rising); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), on_rising); + } + } + struct FailingExecutor { sim: Simulator, fail: Option, @@ -2273,6 +2365,11 @@ mod clock_failure_progress_tests { let falls = executor.sim.signal("falls"); assert_eq!(executor.backend().get_as::(falls), 0); assert_eq!(state.next_event_time(), Some(2)); + assert!( + state + .escaped_host_clock_writes(executor.backend()) + .is_empty() + ); executor.fail = None; assert_eq!(state.step_until(&mut executor, 2).unwrap(), Some(2)); assert_eq!(executor.backend().get_as::(falls), 1); @@ -3551,10 +3648,12 @@ mod normalizing_fall_review_tests { m.finish() } fn check(mut sim: Simulation) { + sim.memory_as_mut_ptr(); assert_eq!(sim.get(sim.signal("clk")), 1u8.into()); sim.set_wide(sim.signal("enable"), 1u8.into()); assert!(sim.run_until(0).is_err()); assert_eq!(sim.ticks(), 0); + sim.checkpoint().unwrap(); let parts = sim.state.export_schedule(&sim.simulator.backend); assert_eq!(parts.process_clocks[0].falling_edge, Some(0)); assert_eq!(sim.get(sim.signal("q")), 1u8.into()); From 8ff727478c5b42de0b1c3107f83a45b9b0b9eba2 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 21:18:29 +0900 Subject: [PATCH 39/42] fix(runtime): validate compiled tick loops and require fusion opt-in --- crates/celox-runtime/src/simulation.rs | 2 +- crates/celox/src/backend/native/backend.rs | 96 +++++++++++++++---- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 82 ++++++++++++++++ 4 files changed, 162 insertions(+), 20 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 15c4b285bf8..607ac25afa9 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -86,7 +86,7 @@ pub trait SimulationExecutor { /// Whether clock waits may be served by fused ticks, which skip the /// clock signal's own edges and the host's per-edge hooks. fn fused_ticks_allowed(&self) -> bool { - true + false } /// Snapshot external-component inputs immediately before an event domain diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 01dd165c08e..c44d2409676 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -413,6 +413,7 @@ pub struct NativeProgramImage { compiled_process_clocks: Vec<(AbsoluteAddr, usize)>, compiled_process_clock_lists: Vec>>, compiled_clock_phase_sensitive_comb: bool, + compiled_native_tick_loop: bool, required_native_features: u8, event_map: HashMap, eval_only_event_map: HashMap, @@ -518,6 +519,9 @@ impl NativeProgramImage { self.reflection .validate() .map_err(|error| format!("invalid design reflection: {error}"))?; + if self.options.native_tick_loop != self.compiled_native_tick_loop { + return Err("native tick-loop eligibility differs from compiled image".into()); + } if self.code.is_empty() { return Err("code image is empty".into()); } @@ -1894,6 +1898,23 @@ fn compile_program( let sir = laid_out; let layout = laid_out.layout(); let (compile_tasks, task_bindings) = collect_ff_compile_tasks(sir); + // Make the compiled ABI and serialized dispatch agree. Fallible phases + // must return to the host without crediting a failed loop iteration. + let mut effective_options = options.clone(); + effective_options.x86_options.native_tick_loop &= !sir + .sir + .eval_comb + .iter() + .chain(sir.sir.eval_apply_ffs.values().flatten()) + .chain( + compile_tasks + .iter() + .filter(|task| task.label == "eval_comb_apply_ff") + .flat_map(|task| task.units.iter().copied()), + ) + .flat_map(|unit| unit.blocks.values()) + .any(|block| matches!(block.terminator, celox_sir::SIRTerminator::Error(_))); + let options = &effective_options; let comb_blocks = sir .sir .eval_comb @@ -2361,6 +2382,7 @@ fn compile_program( .iter() .map(|process| process.clocks.clone()) .collect(), + compiled_native_tick_loop: options.x86_options.native_tick_loop, compiled_clock_phase_sensitive_comb: sir .runtime() .runtime_schema @@ -2411,18 +2433,7 @@ fn compile_program( native_memory_size, options: NativeRuntimeOptions { four_state: options.four_state, - // A generated loop cannot distinguish a failed phase from - // a published tick. Run fallible comb and FF phases separately. - native_tick_loop: options.x86_options.native_tick_loop - && !sir - .sir - .eval_comb - .iter() - .chain(sir.sir.eval_apply_ffs.values().flatten()) - .flat_map(|unit| unit.blocks.values()) - .any(|block| { - matches!(block.terminator, celox_sir::SIRTerminator::Error(_)) - }), + native_tick_loop: options.x86_options.native_tick_loop, native_force_support: options.native_force_support, perf_map: options.x86_options.diagnostics.perf_map, kernel_selection: crate::backend::lanes::kernel_selection(options), @@ -3638,6 +3649,44 @@ mod process_metadata_tests { ); } + #[test] + fn native_loop_eligibility_cannot_be_changed_in_a_checksummed_image() { + let source = r#"module Top(clk:input clock,enable:output logic,v:output logic){ + assign v=if enable ? ~v : 1'd0; + always_ff(clk){enable=1;} + }"#; + let original = crate::Simulator::builder(source, "Top") + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .compile_native() + .unwrap() + .into_program_image(); + assert!(!original.options.native_tick_loop); + let pure = image(); + assert!(pure.options.native_tick_loop); + for original in [original, pure] { + let mut changed = original.clone(); + changed.options.native_tick_loop = !changed.options.native_tick_loop; + // Bypass the writer's validation and regenerate a valid payload + // checksum, exercising the reader's attachment boundary directly. + let mut bytes = original.to_container_bytes().unwrap(); + let trailer = bytes.len() - 32; + let payload = postcard::to_stdvec(&changed).unwrap(); + assert_eq!(payload.len(), trailer); + bytes[..trailer].copy_from_slice(&payload); + let checksum = payload.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3) + }); + bytes[trailer + 24..trailer + 32].copy_from_slice(&checksum.to_le_bytes()); + assert!( + matches!(NativeProgramImage::from_container_bytes(&bytes),Err(NativeImageContainerError::InvalidImage(message)) if message.contains("tick-loop")) + ); + } + } + #[test] fn default_native_loops_do_not_credit_a_failed_pre_edge_iteration() { use crate::backend::SimBackend; @@ -3654,12 +3703,23 @@ mod process_metadata_tests { .build_native() .unwrap(); let event = sim.event("clk"); - let (completed, result) = sim.backend.eval_comb_apply_ff_many_at(event, 10); - assert_eq!(completed, 1); - assert!(result.is_ok()); - let (completed, result) = sim.backend.eval_comb_apply_ff_many_at(event, 9); - assert_eq!(completed, 0); - assert!(result.is_err()); + let bytes = sim + .backend + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = NativeProgramImage::from_container_bytes(&bytes).unwrap(); + // Safety: this round-trip image was compiled in this test. + let mut loaded = unsafe { NativeBackend::from_image(image) }.unwrap(); + for backend in [&mut sim.backend, &mut loaded] { + let (completed, result) = backend.eval_comb_apply_ff_many_at(event, 10); + assert_eq!(completed, 1); + assert!(result.is_ok()); + let (completed, result) = backend.eval_comb_apply_ff_many_at(event, 9); + assert_eq!(completed, 0); + assert!(result.is_err()); + } } #[test] diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 945add7ea02..cc5d35b5f26 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 20; +const CONTAINER_VERSION: u16 = 21; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 0066ee00f17..3ce279a54a7 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2284,6 +2284,88 @@ mod clock_failure_progress_tests { } } + #[test] + fn custom_executors_keep_per_edge_hooks_without_fusion_opt_in() { + struct Host { + sim: Simulator, + staged: Vec, + fired: Vec, + } + impl SimulationExecutor for Host { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(&mut self.sim) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(&mut self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(&mut self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(&mut self.sim, event) + } + fn stage_external_event( + &mut self, + _event: B::Event, + time: u64, + ) -> Result<(), RuntimeErrorCode> { + self.staged.push(time); + Ok(()) + } + fn fire_external_event( + &mut self, + _event: B::Event, + time: u64, + ) -> Result<(), RuntimeErrorCode> { + self.fired.push(time); + Ok(()) + } + // Intentionally rely on the default capability and tick_many. + } + fn check(sim: Simulator) { + let mut state = simulation_state(&sim); + let mut host = Host { + sim, + staged: Vec::new(), + fired: Vec::new(), + }; + while state.next_event_time().is_some_and(|time| time <= 4) { + state.step_until(&mut host, 4).unwrap(); + } + assert_eq!(state.ticks(), 3); + assert_eq!(host.staged, vec![0, 2, 4]); + assert_eq!(host.fired, vec![0, 2, 4]); + assert_eq!(host.sim.backend.get_as::(host.sim.signal("q")), 3); + } + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", ValueType::bits(1).unwrap()).unwrap(); + let word = ValueType::bits(8).unwrap(); + let q = m.output("q", word).unwrap(); + let current = m.read(q).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, current, one, word).unwrap(); + m.register(m.whole(q).unwrap(), next, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 2).unwrap(); + let count = m.constant(Constant::two_state(3u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + let design = m.finish(); + let build = || Simulator::from_frontend(design.clone()); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } + struct FailingExecutor { sim: Simulator, fail: Option, From b7fbfc3b28f4e17bb179c07fca7c38d54832d3a4 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 21:48:02 +0900 Subject: [PATCH 40/42] docs(native): clarify trust in image code and ABI metadata --- crates/celox/src/backend/native/backend.rs | 16 ++++++++++------ crates/celox/src/backend/native/image_file.rs | 4 ++++ crates/celox/src/backend/native/runtime_image.rs | 10 ++++++---- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index c44d2409676..3c0e4dd22fe 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -197,9 +197,13 @@ impl SharedNativeCode { /// /// # Safety /// - /// The image's machine code must come from a trusted source. Structural - /// validation and the container checksum detect corruption, but do not - /// authenticate code before it is mapped executable and invoked. + /// The entire compiler-produced image, including its code and metadata, + /// must come from a trusted source and preserve its compiler-produced ABI. + /// Supported API transformations, such as diagnostic path remapping, are + /// allowed. Structural validation and the container checksum do not + /// authenticate either code or metadata. + /// In particular, coherently rewritten ABI metadata cannot be checked + /// against the original compiler intent without external authentication. pub unsafe fn from_image(program_image: NativeProgramImage) -> Result { // Safety: upheld by this constructor's caller. unsafe { Self::from_image_with_dpi(program_image, &crate::DpiSymbols::default()) } @@ -2606,9 +2610,9 @@ impl NativeBackend { /// /// # Safety /// - /// The image's machine code must come from a trusted compiler or image - /// container. Structural validation does not authenticate code before it - /// is mapped executable and invoked. + /// The entire compiler-produced image, including code and ABI metadata, + /// must come from a trusted source and preserve its compiler-produced ABI. A successful + /// container checksum or structural validation does not authenticate it. pub unsafe fn from_image(image: NativeProgramImage) -> Result { // Safety: upheld by this constructor's caller. unsafe { Self::from_image_with_dpi(image, &crate::DpiSymbols::default()) } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index cc5d35b5f26..295f7ad43aa 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -172,6 +172,10 @@ impl NativeProgramImage { } /// Decode a standalone container with no runtime prefix. + /// + /// Successful decoding checks structure and consistency, not authenticity. + /// Before attaching this image, the caller must establish trust in the + /// entire compiler-produced artifact, including its ABI metadata. pub fn from_container_bytes(bytes: &[u8]) -> Result { let appended = Self::discover_appended(bytes)?.ok_or(NativeImageContainerError::MissingTrailer)?; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 7dfdf72d48e..10ce330f3aa 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -54,8 +54,9 @@ impl NativeProgramInstance { /// /// # Safety /// - /// The image's machine code must come from a trusted source. Image - /// validation is structural and does not authenticate executable code. + /// The entire compiler-produced image, including code and ABI metadata, + /// must come from a trusted source and preserve its compiler-produced ABI. Image validation + /// is structural and does not authenticate either code or metadata. pub unsafe fn from_image(image: NativeProgramImage) -> Result { // Safety: upheld by this constructor's caller. let shared = Arc::new( @@ -82,8 +83,9 @@ impl NativeProgramInstance { /// /// # Safety /// - /// The appended machine code must come from a trusted source. The - /// container checksum is not an authenticity check. + /// The entire appended image, including its code and ABI metadata, must + /// come from a trusted source and preserve its compiler-produced ABI. The checksum + /// is not an authenticity check. pub unsafe fn from_attached_bytes(bytes: &[u8]) -> Result { let appended = NativeProgramImage::discover_appended(bytes)? .ok_or(NativeProgramLoadError::MissingImage)?; From e4a7a6ea0e31fbb091d0b86cba7fb20282936afa Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 00:30:00 +0900 Subject: [PATCH 41/42] fix(runtime): bound clean waiter settling to the current time --- crates/celox/src/simulation.rs | 168 ++++++++++++++++++++++++++++++++- 1 file changed, 167 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 24e6562658d..b2a89e2fe71 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -670,7 +670,7 @@ impl Simulation { self.state.settle_at(&mut self.simulator, time)?; } } else { - self.state.poll_waiting(&mut self.simulator)?; + self.state.poll_waiting_until(&mut self.simulator, time)?; } Ok(()) } @@ -6736,3 +6736,169 @@ mod round57_sdk_tests { check(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(test)] +mod clean_waiter_settle_review { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + use celox_frontend_core::process::ProcessKernelBuilder; + use celox_sir::{SIRInstruction, SIROffset, SIRValue}; + + fn program() -> crate::ir::LaidOutProgram { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(8).unwrap(); + let go = m.input("go", bit).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let q = m.output("q", word).unwrap(); + let done = m.output("done", bit).unwrap(); + let old = m.read(q).unwrap(); + let input = m.read(go).unwrap(); + let next = m.binary(BinaryOp::Add, old, input, word).unwrap(); + m.register(m.whole(q).unwrap(), next, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(4u8, 64).unwrap()); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + m.process(vec![ + Statement::ClockCycles { clock: clk, count }, + Statement::Assign { + target: m.whole(done).unwrap(), + value: one, + }, + ]) + .unwrap(); + let (mut program, _) = crate::compile_frontend_to_sir( + &m.finish(), + &[], + &[], + false, + &Default::default(), + None, + &Default::default(), + ) + .unwrap(); + let address = |id| { + *program + .design + .state_objects + .keys() + .find(|a| { + program + .design + .variable(a) + .is_some_and(|v| v.source_id == crate::ir::SourceVarId(id)) + }) + .unwrap() + }; + let go = address(go.index()); + let done = address(done.index()); + let mut addresses = Vec::new(); + let mut intern = |address| { + let index = match addresses.iter().position(|a| *a == address) { + Some(index) => index, + None => { + addresses.push(address); + addresses.len() - 1 + } + }; + crate::ir::SourceVarId(index as u32) + }; + let slots = program.runtime_schema.processes[0].clone().map(&mut intern); + let go = intern(go); + let done = intern(done); + let stable = |var_id| celox_design::RegionedVarAddrBase { + region: celox_design::STABLE_REGION, + var_id, + }; + // The SDK has clock waits but no level-wait statement. Build the + // combined kernel through the shared frontend process contract. + let mut kernel = ProcessKernelBuilder::new(slots); + kernel.begin_wait().unwrap(); + let condition = kernel.builder().alloc_bit(1, false); + kernel.builder().emit(SIRInstruction::Load( + condition, + stable(go), + SIROffset::Static(0), + 1, + )); + kernel.wake_if(condition); + let count = kernel.builder().alloc_bit(64, false); + kernel + .builder() + .emit(SIRInstruction::Imm(count, SIRValue::new(4u8))); + kernel.wait_clock(0, count).unwrap(); + let one = kernel.builder().alloc_bit(1, false); + kernel + .builder() + .emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + kernel.builder().emit(SIRInstruction::Store( + stable(done), + SIROffset::Static(0), + 1, + one, + Vec::new(), + Vec::new(), + )); + kernel.finish(); + program.sir.processes[0] = kernel.build().into_map_addr(&mut |addr| { + let address = addresses[addr.var_id.0 as usize]; + crate::ir::RegionedAbsoluteAddr { + region: addr.region, + instance_id: address.instance_id, + var_id: address.var_id, + } + }); + program.into_laid_out(false) + } + fn check(mut simulator: Simulator) { + simulator.apply_initial_values(); + let mut sim = Simulation::new(simulator); + sim.run_until(0).unwrap(); + assert_eq!(sim.next_event_time(), None); + let go = sim.signal("go"); + let (pointer, length) = sim.memory_as_mut_ptr(); + assert!(go.offset < length); + unsafe { + pointer.add(go.offset).write(1); + } + assert!(!sim.simulator.dirty); + assert!(sim.simulator.pending_host_writes.is_empty()); + assert!(sim.simulator.backend.get_triggered_bits().is_empty()); + assert!(!sim.state.has_unsettled_edges(&sim.simulator.backend)); + sim.settle().unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.get(sim.signal("done")), 0u8.into()); + sim.run_until(16).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 4u8.into()); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + } + #[test] + fn clean_raw_level_waiter_settle_keeps_current_time() { + let program = program(); + let options = crate::SimulatorOptions { + emit_triggers: true, + ..Default::default() + }; + macro_rules! run { + ($backend:expr) => { + check(Simulator::with_backend_and_program( + $backend.unwrap(), + program.runtime().clone(), + Vec::new(), + )); + }; + } + run!(crate::backend::InterpBackend::new(&program, &options)); + run!(crate::backend::JitBackend::new(&program, &options, None)); + run!(crate::backend::wasm_runtime::WasmBackend::new( + &program, &options + )); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + run!(crate::backend::native::NativeBackend::new( + &program, &options + )); + } +} From 41bdab73cde8cbb1a16a9aca6853820245fe63fd Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 02:16:49 +0900 Subject: [PATCH 42/42] fix(runtime): retain unpublished falls and zero-wait retries --- crates/celox-runtime/src/simulation.rs | 44 ++++- crates/celox/src/simulation.rs | 225 ++++++++++++++++++++++--- 2 files changed, 240 insertions(+), 29 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index ca9526dbde8..09adb90ba33 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -263,7 +263,7 @@ pub struct SimulationState { round_triggered_domains: BitSet, scheduled_clock_drives: BitSet, scheduled_clock_time: u64, - round_evaluated: bool, + round_triggers_discovered: bool, round_new_rising: BitSet, periodic_events: FxHashMap, last_clock_values: BitSet, @@ -501,7 +501,7 @@ impl SimulationState { round_triggered_domains: BitSet::new(), scheduled_clock_drives: BitSet::new(), scheduled_clock_time: 0, - round_evaluated: false, + round_triggers_discovered: false, round_new_rising: BitSet::new(), finish_round: false, } @@ -918,7 +918,7 @@ impl SimulationState { .collect(); self.credit_rising_edges(time, committed)?; if result.is_ok() - || (self.round_evaluated + || (self.round_triggers_discovered && self .round_triggered_domains .is_subset(&self.round_published_domains)) @@ -1231,9 +1231,15 @@ impl SimulationState { if pass.is_empty() { return Ok(progressed); } - count_delta_pass(delta_rounds)?; + if let Err(error) = count_delta_pass(delta_rounds) { + for process in pass { + self.process_wakeups.push(Reverse((current_time, process))); + } + return Err(error); + } let mut any_ran = false; - for process in pass.drain(..) { + let mut remaining = std::mem::take(&mut pass).into_iter(); + while let Some(process) = remaining.next() { loop { let before = self .process_event_counters @@ -1319,7 +1325,13 @@ impl SimulationState { if count == 0 { // A zero-count wait does not yield to another process, // but repeated immediate continuations must be bounded. - count_delta_pass(delta_rounds)?; + if let Err(error) = count_delta_pass(delta_rounds) { + self.process_wakeups.push(Reverse((current_time, process))); + for process in remaining { + self.process_wakeups.push(Reverse((current_time, process))); + } + return Err(error); + } continue; } else { let id = clock.event.id(); @@ -1436,7 +1448,7 @@ impl SimulationState { self.scheduler.time = current_time; self.round_published_domains.make_empty(); self.round_triggered_domains.make_empty(); - self.round_evaluated = false; + self.round_triggers_discovered = false; self.round_new_rising.make_empty(); // Keep periodic provenance private so the public SimEvent shape stays @@ -1706,7 +1718,6 @@ impl SimulationState { if !process_settled { executor.eval_comb()?; } - self.round_evaluated = true; if executor.finish_requested(current_time) { self.finished = true; return Ok(true); @@ -1748,8 +1759,23 @@ impl SimulationState { let mut any_new_outer_loop_trigger = false; loop { - count_delta_pass(delta_rounds)?; let marked_bits = executor.backend().get_triggered_bits(); + // Discover the complete batch before any fallible sampling or FF + // execution can interrupt it. An empty set before discovery is + // not evidence that a generated falling edge was published. + for id in marked_bits.iter() { + let info = self.event_info[id]; + if !discovered_in_this_step.contains(id) + && !triggered_domains.contains(info.canonical_id) + && (!info.is_cascaded + || recorded_edges.contains(id) + || self.stable_edge_triggered(executor.backend(), id)) + { + self.round_triggered_domains.insert(info.canonical_id); + } + } + self.round_triggers_discovered = true; + count_delta_pass(delta_rounds)?; executor.backend_mut().clear_triggered_bits(); let mut can_use_eval_apply = self.processes.is_empty() diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 3e399bf0446..0b9ce5b0452 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -6795,6 +6795,9 @@ mod clean_waiter_settle_review { use celox_sir::{SIRInstruction, SIROffset, SIRValue}; fn program() -> crate::ir::LaidOutProgram { + program_with_sampling_waiter(false) + } + fn program_with_sampling_waiter(extra: bool) -> crate::ir::LaidOutProgram { let mut m = ModuleBuilder::new("Top").unwrap(); let bit = ValueType::bits(1).unwrap(); let word = ValueType::bits(8).unwrap(); @@ -6818,6 +6821,37 @@ mod clean_waiter_settle_review { }, ]) .unwrap(); + let noise = if extra { + let noise = m.input("noise", bit).unwrap(); + let echo = m.output("noise_seen", bit).unwrap(); + let value = m.read(noise).unwrap(); + m.assign(m.whole(echo).unwrap(), value).unwrap(); + let falls = m.output("falls", word).unwrap(); + let old = m.read(falls).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, old, one, word).unwrap(); + let fallclk = m.internal("fallclk", bit).unwrap(); + let clk_value = m.read(clk).unwrap(); + let go_value = m.read(go).unwrap(); + let low = m + .unary(crate::frontend_sdk::UnaryOp::BitNot, clk_value, bit) + .unwrap(); + let active_low = m.binary(BinaryOp::And, low, go_value, bit).unwrap(); + m.assign(m.whole(fallclk).unwrap(), active_low).unwrap(); + m.register( + m.whole(falls).unwrap(), + next, + fallclk, + Edge::Posedge, + None, + None, + ) + .unwrap(); + m.process(vec![Statement::Finish]).unwrap(); + Some(noise) + } else { + None + }; let (mut program, _) = crate::compile_frontend_to_sir( &m.finish(), &[], @@ -6841,7 +6875,7 @@ mod clean_waiter_settle_review { }) .unwrap() }; - let go = address(go.index()); + let go = address(noise.unwrap_or(go).index()); let done = address(done.index()); let mut addresses = Vec::new(); let mut intern = |address| { @@ -6854,7 +6888,10 @@ mod clean_waiter_settle_review { }; crate::ir::SourceVarId(index as u32) }; - let slots = program.runtime_schema.processes[0].clone().map(&mut intern); + let index = usize::from(extra); + let slots = program.runtime_schema.processes[index] + .clone() + .map(&mut intern); let go = intern(go); let done = intern(done); let stable = |var_id| celox_design::RegionedVarAddrBase { @@ -6873,25 +6910,27 @@ mod clean_waiter_settle_review { 1, )); kernel.wake_if(condition); - let count = kernel.builder().alloc_bit(64, false); - kernel - .builder() - .emit(SIRInstruction::Imm(count, SIRValue::new(4u8))); - kernel.wait_clock(0, count).unwrap(); - let one = kernel.builder().alloc_bit(1, false); - kernel - .builder() - .emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); - kernel.builder().emit(SIRInstruction::Store( - stable(done), - SIROffset::Static(0), - 1, - one, - Vec::new(), - Vec::new(), - )); + if !extra { + let count = kernel.builder().alloc_bit(64, false); + kernel + .builder() + .emit(SIRInstruction::Imm(count, SIRValue::new(4u8))); + kernel.wait_clock(0, count).unwrap(); + let one = kernel.builder().alloc_bit(1, false); + kernel + .builder() + .emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + kernel.builder().emit(SIRInstruction::Store( + stable(done), + SIROffset::Static(0), + 1, + one, + Vec::new(), + Vec::new(), + )); + } kernel.finish(); - program.sir.processes[0] = kernel.build().into_map_addr(&mut |addr| { + program.sir.processes[index] = kernel.build().into_map_addr(&mut |addr| { let address = addresses[addr.var_id.0 as usize]; crate::ir::RegionedAbsoluteAddr { region: addr.region, @@ -6901,6 +6940,152 @@ mod clean_waiter_settle_review { }); program.into_laid_out(false) } + struct SamplingFailure { + sim: Simulator, + fail: bool, + low_samples: usize, + } + impl SimulationExecutor for SamplingFailure { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(&mut self.sim) + } + fn eval_apply_ff_at(&mut self, e: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(&mut self.sim, e) + } + fn eval_only_ff_at(&mut self, e: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(&mut self.sim, e) + } + fn apply_ff_at(&mut self, e: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(&mut self.sim, e) + } + fn run_process(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { + let slots = &self.sim.program.runtime_schema.processes[index]; + let mode = self + .sim + .backend + .get_as::(self.sim.backend.resolve_signal(&slots.delay)); + let clk = self.sim.backend.get_as::(self.sim.signal("clk")); + if self.fail && index == 1 && mode == 1 && clk == 0 { + self.low_samples += 1; + // Skip sampling during scheduled-value application, then fail + // the post-settle sample before the falling-edge FF is run. + if self.low_samples == 2 { + return Err(RuntimeErrorCode::Runtime { + message: "injected wait sampling failure".into(), + signals: Vec::new(), + }); + } + } + SimulationExecutor::run_process(&mut self.sim, index) + } + } + #[test] + fn round61_failed_wait_sampling_retains_unpublished_generated_fall() { + fn check(mut sim: Simulator) { + sim.apply_initial_values(); + let go = sim.signal("go"); + sim.set_wide(go, 1u8.into()); + let mut state = simulation_state(&sim); + let mut executor = SamplingFailure { + sim, + fail: false, + low_samples: 0, + }; + assert_eq!(state.step_until(&mut executor, 0).unwrap(), Some(0)); + executor.fail = true; + let error = state.step_until(&mut executor, 2).unwrap_err().to_string(); + assert!(error.contains("injected wait sampling failure"), "{error}"); + assert_eq!(executor.low_samples, 2); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("falls")), + 0 + ); + let schedule = state.export_schedule(executor.backend()); + assert_eq!(schedule.process_clocks[0].falling_edge, Some(2)); + assert_eq!(state.next_event_time(), Some(2)); + executor.fail = false; + assert_eq!(state.step_until(&mut executor, 2).unwrap(), Some(2)); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("falls")), + 1 + ); + } + let program = program_with_sampling_waiter(true); + let options = crate::SimulatorOptions { + emit_triggers: true, + ..Default::default() + }; + macro_rules! run { + ($backend:expr) => { + check(Simulator::with_backend_and_program( + $backend.unwrap(), + program.runtime().clone(), + Vec::new(), + )); + }; + } + run!(crate::backend::InterpBackend::new(&program, &options)); + run!(crate::backend::JitBackend::new(&program, &options, None)); + run!(crate::backend::wasm_runtime::WasmBackend::new( + &program, &options + )); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + run!(crate::backend::native::NativeBackend::new( + &program, &options + )); + } + #[test] + fn round61_zero_count_delta_errors_remain_retryable() { + fn check(mut sim: Simulation) { + for _ in 0..2 { + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("delta limit"), "{error}"); + assert_eq!(sim.next_event_time(), Some(0)); + let saved = sim.checkpoint().unwrap(); + sim.restore(&saved).unwrap(); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("delta limit"), "{error}"); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 0); + } + } + let build = || { + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.input("clk", ValueType::bits(1).unwrap()).unwrap(); + let q = m.output("q", ValueType::bits(8).unwrap()).unwrap(); + let value = m.read(q).unwrap(); + m.register(m.whole(q).unwrap(), value, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 64).unwrap()); + m.process(vec![Statement::Forever { + body: vec![Statement::ClockCycles { + clock: clk, + count: zero, + }], + }]) + .unwrap(); + Simulator::from_frontend(m.finish()) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } fn check(mut simulator: Simulator) { simulator.apply_initial_values(); let mut sim = Simulation::new(simulator);