Repository navigation
feat(runtime)!: wake processes on events in front of the batch step - #1361
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
celox/crates/celox/src/simulation.rs
Lines 410 to 411 in 5446e4c
When loading a state file whose schedule has finished = true, import_schedule updates only SimulationState; Simulator::frozen retains its previous value. A fresh simulation loaded from a finished file therefore still accepts modify and evaluation, while loading an unfinished file into an already-finished simulation leaves it permanently frozen. Set the simulator's frozen state from the imported finished value after a successful load.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| restore_working_image(executor.backend_mut(), image); | ||
| if let Some(event) = self.event_info[*id].apply_event { | ||
| executor.apply_ff_at(event)?; | ||
| } |
There was a problem hiding this comment.
Observe each deferred flip-flop publication
When one FF domain is evaluated multiple times across inactive regions, this loop publishes every saved working image without checking waits between publications. If a watched FF output changes on the first publication and the final publication restores its baseline value, the only later observe_driven sees no change, so an @(q) process misses the intra-slot pulse. Each deferred apply_ff_at publication must either update the signal counters or run the wait observation before the next image is applied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 018705d. When a domain publishes several evaluations, the runtime now records event-signal transitions and checks waits after each image. Domains that a pulse triggers stay marked through the following settles. Test: every_publication_of_a_domain_is_an_update (all backends).
| fn take_host_writes(&mut self) -> Vec<(SignalRef, celox_runtime::timing::Value)> { | ||
| self.host_watch.take_log() | ||
| } |
There was a problem hiding this comment.
Persist pending host-write observations
When a checkpoint or state file is created after modify but before the next step, the HostWatch log is the only record of intermediate writes such as a 0→1→0 pulse. Neither Checkpoint nor ProcessRecord captures this log, so after stepping and restoring that checkpoint—or loading the state file—take_host_writes returns an empty vector and an edge-waiting process never wakes because the saved final signal value still equals its baseline. The pending write log must be included in both persistence paths, not just the host_pending flag.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 018705d. SimulationCheckpoint and the state file's process section now carry the pending host-write log (by signal path in the file), and restore/load reinstate it. Test: host_write_pulses_survive_checkpoints_and_state_files.
| fn runtime_finish(&mut self) -> Result<(), Halt> { | ||
| if !self.finish_sites { | ||
| return Ok(()); | ||
| } | ||
| if self.take_runtime_finish() { |
There was a problem hiding this comment.
Propagate finish from direct timed evaluations
When combinational logic emits $finish during Simulation::eval_comb, a lazy Simulation::get, or a dump that settles dirty state, those public timed-simulation paths call the underlying Simulator evaluation directly and never invoke this new runtime_finish check. is_finished() consequently remains false and the simulator remains writable until some later scheduler step happens to scan the old event; if no event is scheduled, it never freezes at all. Route every timed evaluation entry point through the finish check.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 018705d. Simulation::eval_comb, get, dump, try_dump and modify now check for a $finish record afterwards and end the simulation. Test: finish_during_a_direct_settle_ends_the_simulation.
| self.queue_nba(executor.backend_mut(), process, site)?; | ||
| *returns += 1; | ||
| self.charge(*returns, Some(process))?; | ||
| continue; |
There was a problem hiding this comment.
Observe writes before immediately resuming NBA kernels
When a process reaches an unoptimized NBA site, this path queues the assignment and immediately resumes the kernel inside run_process, so run_ready neither samples event signals nor checks waits at that return. However, multi_store_candidates treats every SIR Return as a real suspension boundary and therefore does not add counters for stores on opposite sides of the NBA return. A sequence such as q = 1; <unoptimized NBA>; q = 0 consequently hides the pulse on q from both an event wait and a flip-flop domain; observe stable writes before the immediate resume or make the counter analysis treat NBA/Yield returns as uninterrupted execution.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 018705d. run_process now returns after a queued NBA or a yield, and run_ready treats that return as a check point (event-signal transitions and a wait check) before resuming the kernel. The candidate analysis's view of Return as a boundary therefore holds for these returns too. Test: a_pulse_around_a_queued_nonblocking_assignment_is_an_edge.
|
Queued — the merge queue status continues in this comment ↓. |
|
Re the review-level finding (freeze state on load): fixed in 018705d. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 018705d306
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let was_nonzero = previous | ||
| .filter(|(last, _)| *last == id) | ||
| .map_or(self.last_clock_values.contains(id), |(_, value)| value); | ||
| previous = Some((id, is_nonzero)); |
There was a problem hiding this comment.
Track prior values separately for each event
When successive deferred FF publications change multiple event signals, transitions interleaves their IDs (for example a↑, b↑, a↓), but this code remembers only the immediately preceding transition. The a↓ transition is therefore compared with a's slot baseline rather than its prior high value, so a negedge-triggered domain can miss an intra-slot pulse when a ultimately returns to baseline. Keep the latest value per event ID while scanning the publications.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3f00ac0. mark_occurrences keeps the latest value per event ID. The marking also now waits until the round's last publication: the final evaluation may publish in the main FF loop, after the deferred images. Test: interleaved_publications_keep_each_signals_edges, where a negedge domain on one of two interleaving outputs counts the pulse.
| if let Some(image) = image { | ||
| restore_working_image(executor.backend_mut(), image); | ||
| if let Some(event) = self.event_info[*id].apply_event { | ||
| executor.apply_ff_at(event)?; |
There was a problem hiding this comment.
Fire component hooks for every deferred publication
When a domain is evaluated more than once across inactive regions, this loop commits each superseded image but never calls fire_external_event for those commits. The caller later fires hooks only for IDs returned by apply_deferred, and that return list contains only final entries whose image is None; consequently an external component clocked by this domain observes only the last publication even though the RTL and waits observe every one. Each saved publication needs its corresponding component hook (and staged input snapshot) when it commits.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable in this PR. A domain is published from several saved images only after an evaluation deferred by an inactive-region #0 kernel, and only SDK artifacts produce those today (SV lowering still uses delay). External components exist only inside a Veryl native testbench, which rejects artifacts with processes (ProcessesInTestbench). Per-evaluation staging for component hooks belongs to the change that first lets processes and components meet; I'm noting it for the SV lowering step.
| fn eval_comb(&mut self) -> Result<(), Halt> { | ||
| self.eval_comb_checked()?; | ||
| self.runtime_finish() |
There was a problem hiding this comment.
Stop backend execution at the finish site
For $finish emitted by ordinary combinational or flip-flop logic rather than a process kernel, the backend executes the entire evaluation unit before this check runs. Thus assignments or effects after $finish still execute, and a combined eval_apply_ff_at can even commit them before the simulator freezes; for example, an always_comb block containing $finish; y = 1; leaves y updated despite termination occurring first. The generated unit or backend needs to halt at the finish site rather than detecting the event only after evaluation returns.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is the existing lowering of an RTL $finish in flip-flop and combinational units: the unit records the event and runs to its end. That is unchanged by this PR, which only makes a timed Simulation freeze once the record appears. Stopping those units at the finish site is a change to how frontends lower $finish in RTL code (SV lowering), not to the runtime's dynamic path, so I'm leaving it out here and passing it to the SV lowering step.
| Some(&target) => nba_queue.push(celox_runtime::NbaUpdate { | ||
| target, | ||
| lsb: update.lsb as usize, | ||
| width: update.width as usize, | ||
| value: ( |
There was a problem hiding this comment.
Validate queued NBA ranges before importing them
A malformed or programmatically constructed state file can supply arbitrary lsb and width values for a queued NBA, and this path accepts them without checking that the range is nonempty and contained in target. On the next step, NbaUpdate::merge_into computes masks with shifts by these values, so a very large serialized width can cause an enormous allocation or process termination instead of returning a state-file error. Reject ranges that overflow or exceed the resolved target width before adding them to nba_queue.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3f00ac0. A queued NBA whose range is empty or exceeds its target's width is now rejected as a mismatch on import. Test: state_files_reject_queued_assignments_outside_their_target.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3f00ac01c8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let mut file = self.simulator.save_state()?; | ||
| let parts = self.state.export_schedule(&self.simulator.backend); | ||
| file.schedule = Some(self.simulator.name_schedule(parts)); | ||
| let mut record = self.simulator.name_schedule(parts); |
There was a problem hiding this comment.
Synchronize finish before exporting the schedule
When save_state() settles dirty combinational logic that emits $finish—for example, after modify() changes a control input and before any read or step—Simulator::save_state records the event, but this path immediately exports SimulationState with finished = false and leaves the simulator unfrozen. Consequently both the current simulation and a simulation loaded from the saved file remain runnable until another evaluation notices the stale event. Fresh evidence beyond the previously covered get/dump paths is this newly exposed save_state evaluation path; synchronize finish before naming the schedule.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0bceff1. Simulation::save_state now checks for a $finish its settle executed before it exports the schedule. Test: saving_state_after_a_finishing_write_records_the_finish.
| .map(|baseline| match baseline { | ||
| BaselineRecord::Counter(value) => Baseline::Counter(*value), | ||
| BaselineRecord::Value { value, mask } => Baseline::Value(( | ||
| BigUint::from_bytes_le(value), | ||
| BigUint::from_bytes_le(mask), | ||
| )), |
There was a problem hiding this comment.
Reject mismatched waiter baseline variants
A malformed or programmatically constructed state file can provide a Counter baseline for an uncounted wait term, or a Value baseline for a counted term, and this conversion accepts it solely because the baseline count matches. In the former case check_waits can never wake the process because term.counter is None; in the latter it bypasses the occurrence counter and can miss an intra-slot pulse. Validate each baseline variant against whether the corresponding resolved wait term is counted and reject mismatches during import.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0bceff1. Import now requires each baseline's kind to match its term: a counter for a counted signal, a value otherwise. Test: state_files_reject_baselines_of_the_wrong_kind.
| for target in comb_process_targets(&body) { | ||
| self.record_driver_target(target)?; |
There was a problem hiding this comment.
Allow overlapping writes within one combinational process
When one combinational process assigns overlapping but non-identical slices, such as first assigning all of y and then overriding y[0], comb_process_targets retains both targets and this loop records the whole-signal target before checking the slice. The second call therefore reports a driver conflict against the same process, rejecting a valid and common procedural assignment pattern; targets from one process need to be checked as a single driver before their combined ranges are registered.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0bceff1. The SDK merges one combinational process's targets per signal before registering it as a driver, and the lowering builds one path per merged range. Tests: a_combinational_process_may_overwrite_part_of_its_own_target (SDK) and comb_processes_may_overwrite_their_own_targets (all backends).
| for &(id, is_nonzero) in values { | ||
| round.track_stable_edges = true; | ||
| let was_nonzero = self.last_clock_values.contains(id); |
There was a problem hiding this comment.
Compare each event transition with its preceding value
When an event signal changes more than once before domain evaluation, every entry in values is compared with the previous round's baseline rather than the preceding entry. For example, if a high clock is written low and then high by scheduled updates or successive ready processes, the later positive edge is compared as high→high and its flip-flop domain never runs, even though the transition list preserved the pulse. Track the latest value per event ID while scanning this list, as is already done for deferred-publication occurrences.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0bceff1. mark_scheduled_edges now compares each value with the same signal's preceding entry and falls back to the round baseline. Test: a_signal_written_again_compares_with_its_preceding_value, where two processes write a high clock low and then high.
| let backend = executor.backend_mut(); | ||
| let merged = update.merge_into(&read(backend, update.target)); | ||
| let target = update.target; | ||
| self.write_signal(backend, target, |backend| { |
There was a problem hiding this comment.
Record event edges from every queued NBA publication
When multiple queued nonblocking assignments update an event signal in one NBA region, this loop publishes each value but records no event-domain transition. An NBA-only target is not selected as a counted candidate because its process kernel writes staging slots rather than the target, so a sequence such as clk <= 1; clk <= 0; from a low baseline leaves the stable-edge check seeing only low→low and the positive-edge flip-flop domain never runs. Record each NBA publication for occurrence marking, or classify these targets for counters, rather than relying only on the final settle.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0bceff1. When the NBA region publishes several updates, the runtime records event-signal transitions after each one and marks the edges among them. Test: queued_nonblocking_pulses_trigger_flip_flops (clk <= 1; clk <= 0;).
| Err(Halt::Finish) => { | ||
| self.finish(executor); | ||
| Ok(Some(self.scheduler.time)) |
There was a problem hiding this comment.
Finalize the waveform before freezing on finish
When $finish is returned during a scheduled step, step_time unwinds before calling finish_timed_step, and this arm immediately freezes the executor. Because a frozen Simulator::try_dump is a no-op, neither the automatic step dump nor a later explicit dump records the terminating timestamp or assignments executed before $finish, so VCD output ends at the preceding step. Finalize or dump the terminating time slot before freezing, without performing further design evaluation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0bceff1. On a finish, the runtime now runs finish_timed_step for the slot before freezing. That clears the dirty flag first, so it dumps without evaluating. Test: the_waveform_records_the_finish.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
tignear
left a comment
There was a problem hiding this comment.
Review of fe1e38b (replaces the Codex review rounds). Each item was traced through the code; scenarios are concrete. Fix the should-fix items in this PR, each with a test on all backends; nits may be follow-ups.
Should-fix
-
DSE removes comb stores to signals that only a wait watches —
crates/celox-frontend-core/src/symbolic/assembly.rs:1469.timing_read_rootsholds counters and NBA slots but not the wait-term signals, andWaitEventlowers tosuspend_wait+wake_if(1), so no unit loads the term. Internaly = a & bwith a process@(posedge y)at O2 (PreserveTopPorts): the store toyis eliminated and the process never wakes. Add every wait-term signal to the roots. -
Several NBAs pulsing an event signal are lost on the single-domain fused path —
crates/celox-runtime/src/simulation.rs:1397-1403.publish_nbamarks occurrences, thenreplace_triggers_with_stable_edgesclears them and, unlike the multi-domain path (1513-1515), does not re-markround.occurrences. Scheduled posedge clk triggers only domain A; a kernel woken by it doesp <= 1; p <= 0;; domain B on@(posedge p)never evaluates. With a second domain on clk, B does evaluate. -
A pulse across two wake waves of one slot is lost for FF domains —
simulation.rs:790-795with 1162-1166. Each wave'smark_scheduled_edgescallsbegin_scan, so the earlier wave's value falls back tolast_clock_values. s=1, D on@(posedge s); kernel A sets s=0 in wave 1, kernel B (@(negedge s)) sets s=1 in wave 2 → D misses the rise. Keep the latest value per event signal across the waves of a round. -
Zero-time loops inside one round hang without a budget error —
simulation.rs:1154-1190.process_phaserepeats while ready/inactive is non-empty;chargeruns only forNba/Yield. SDKForever { InactiveDelay(0) }, or two kernels waking each other through waits, loop forever inside onestep, whichrun_until_boundedcannot stop. Charge every pass of the process phase against the slot budget. -
Host writes from TS never reach waits, counters or
host_pending— only RustSimulation::modifygoes throughHostWatch/note_host_writes; TS setters write the buffer and setdirty. SDK design viafrom_frontend, kernel@(posedge go) done = 1; TSdut.go = 1; runUntil(10)with no clock:next_event_time()is None, nothing runs. With a clock it wakes at the next edge, not the write time. Report the dirty state to the Rust side beforerunUntil/step(treat it as a logged host write for the whole input set, or reconcile at entry and settle the current time). -
SDK
comb_processdrops inputs at whole-signal granularity —crates/celox-frontend-core/src/sdk.rs:1473,1503. Readingv[1]while writingv[0]removesvfrom the gate and the sources (IEEE 1800-2023 9.2.2.2.1 uses the longest static prefix; SV lowering does it by range insubtract_written_sensitivity).assign v[1] = a;+comb_process { v[0] = v[1]; }runs once andv[0]stays stale. Filter by written range. -
Pure RTL +4.0% vs master — the PR body attributes +71.4 M to
get_triggered_bitsno longer being inlined. That function builds aBitSetbit by bit every round (crates/celox/src/backend/native/backend.rs:3282, same shape in the other backends). Build it from the bytes word-wise instead of relying on inlining; then re-measure (a). The PR must not merge with (a) above noise.
Nits / follow-ups
- RTL
$finish: the fused path halts aftereval_apply_ff_at(NBAs committed), the split path aftereval_only_ff_at(not committed) —crates/celox/src/simulation.rs:90-100. IEEE 20.2 / 4.5: the old value is correct. Make both paths leave NBAs unpublished (fine as a step-4 item, it is listed there already). - SV
always @*$randomunits include their own targets in the gate (crates/celox-frontend-sv/src/lowering/ff.rs:2418); with a counted target each re-run adds an edge. crates/celox/src/testbench_compile.rs:13overwrites the read roots and drops the timing roots (harmless today).celoxdoes not re-exportProcessRecord,WaiterRecord,BaselineRecord,NbaRecordwhileScheduleRecord.processesis public.is_finished's rustdoc landed onrun_until_bounded(crates/celox/src/simulation.rs:569-574).resolve_processesaccepts a process listed twice or wakeups beforerecord.time.celox state dump/diffignore the process section.StateError::Processesis unused and its message is stale.
Rebase
master moved (#1364, derived-clock fixes: set_combinational_derived, eval_comb_apply_ff_at). Port them into both batch_round and the timed step_round when rebasing so the two copies do not drift.
Checked and fine: Table 9-2 edge rules, waiter baselines, NBA publication order, region order (active → inactive → NBA, process before FF eval), finish/frozen across checkpoint and state files, state-file v1/v2 and image 12→13 handling, emit_watched coverage of Store/Commit paths, NBA pending rule (condition 1), batch_round identical to master's step_round.
fe1e38b to
3a439b8
Compare
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Addressed in 709749c..3a439b8, rebased onto a1c6987 (#1364). Each should-fix item was reproduced by a new all-backend test before its fix:
Nits: the re-exports, Rebase: #1364 is ported into both rounds. |
tignear
left a comment
There was a problem hiding this comment.
Second review, of 3a439b8. Fixes 1–7 of the previous round are real fixes and their tests fail without them; batch_round matches master's step_round apart from the dead process block; the word-wise triggered-bit read is correct on every backend; the RTL $finish gate leaves a bare Simulator unchanged. New findings below were traced through the code, not yet run: reproduce each first, fix it with a test on all backends, or reply if it turns out unreachable.
Should-fix
-
Derived-clock edges from the #1364 port are lost after a second wave or an inactive region —
crates/celox-runtime/src/simulation.rs:880-935,:1001-1045.- In wave 2,
settle_markedseesscheduled_trigger_idsnon-empty, clears the triggered bits and re-marks only those ids; thegclkid thatjudge_derived_edgesapproved in wave 1 (and whose baseline it already moved) is not re-marked, andgating_sourcesis already consumed. After the commit the stable-edge pass compares 1 with 1. evaluate_before_inactiveruns the cascaded stable-edge test withoutedge_approved, andsynchronize_event_valuesmoves the baseline of every event signal, including domains that did not evaluate.- Scenario:
assign gclk = clk & en; always_ff @(posedge gclk), scheduled posedge clk, plus a process@(posedge clk) x = ...;(wakes → wave 2) or@(posedge clk); #0 .... The gclk domain does not evaluate at that edge. This is the most common testbench shape; add a test of derived clocks with processes. - Fix: re-mark
edge_approvedinsettle_marked, consult it inevaluate_before_inactive, and only rebase the ids that evaluated.
- In wave 2,
-
With any process in the design, every host write makes the next
step()settle the current time instead of advancing —simulation.rs:1330,logged || !self.processes.is_empty() || !self.counted.is_empty().self.processesis the static kernel list, so this holds after every process is Done and no waiter exists. SVinitial begin #5 rst = 0; end+ TSfor (...) { dut.d = i; sim.step(); }: time never advances (on master each step advanced). Same for Rustmodify. Use registered waiters (and counted signals only if a host write can reach them unbumped), not the process list. -
A wait on a counted signal misses writers that are not instrumented —
simulation.rs:655-656withinstrument_counted_signalsinsymbolic/assembly.rs. Counted is per whole variable, but only kernels and comb-process units bump the counter, and a counted term keeps onlyBaseline::Counter. SDK:assign v[1] = a;, P0forever { v[0]=1; v[0]=0; #10 }(makesva candidate), P1WaitEvent{v, Change}. Host setsa=1: eval_comb writesv[1], no bump, P1 never wakes. Fix by instrumenting every writer of a counted signal, or keeping a value baseline next to the counter when non-instrumented writers exist. -
A wait misses a combinational pulse between cascaded FF waves of one round —
simulation.rs:1600-1654: waits are checked afterfinish_publicationsand after the loop, not after each outer-loop settle. Aa <= ~aon clk, Bb <= aon posedge a,assign y = a & ~b, kernel@(posedge y): y is 1 between the two waves, 0 at the end; an FF on posedge y fires, the kernel does not (IEEE 1800-2023 4.5: each update event schedules the sensitive processes). Runobserve_drivenafter each outer-loop settle when waiters exist. -
Bounded TS
runUntil(time(), { maxSteps })drops pending host writes —packages/celox/src/simulation.ts:457-458returns on>=beforenoteHostWrites(); the unbounded path and Rustrun_until_boundedsettle the equal case. Use<and report the writes first.
Nits
NbaSite::pendingrustdoc and design condition 1 say "not a port", butsingle_nba_targets(crates/celox-frontend-core/src/sdk.rs) flags output-port targets. Harmless for the flat SDK artifact; align code or doc.crates/celox-runtime/src/state_file.rs:44always writes v2, even with an empty process section; older releases then reject pure-RTL files. Write the oldest version that fits.runUntilBoundedis a required member of the exportedNativeSimulationHandle/RawNapiSimulationHandle; make it optional likenoteHostWrites, or say it in the breaking-change note.docs/guide/external-frontends.md(en/ja) mention the settle-current-time behaviour only forSimulation::modify; TS DUT writes do it too.ProcessKernelBuilder::yield_nowis documented as placed in timing-free loops, but nothing places it, so SDKForever { Assign }still spins insiderun_process(pre-existing). Fix the comments that claim the budget covers it, or place the yield in the SDKWhile/Foreverlowering.
Process kernels get the rest of the timing protocol: inactive-region delays, event and level waits, nonblocking assignments and yields. The timed scheduler runs them in a process phase in front of today's batch step (IEEE 1800-2023 4.5), so a round without ready or waiting processes and counted signals does exactly the batch step, with the fused evaluate-and-apply and parallel units. - Waits compare the value each waiting process last saw against the edge it waits for (Table 9-2), at every point the runtime checks. - A signal that one unit may store twice without such a check, and that a domain or wait watches, is counted: assembly instruments exactly those stores in kernels and combinational process units with changes/rises/falls counters in plain SIR, so no backend changes. - Domains triggered before an inactive region evaluate first and publish in the NBA region; a domain evaluated twice keeps the earlier working state. Kernel nonblocking assignments use an ordered queue or a single pending value per site. - $finish ends a timed simulation as a control result and freezes the simulator. A host write settles at the current time. - Checkpoints, state files (version 2) and exported schedules carry the waiting processes, queues and counter baselines; the native image container is version 13. - The SDK (format 3) gains the timing statements and combinational processes; its runtime tests run on every backend. - The timing oracle no longer excludes host clock edges. BREAKING CHANGE: SimulationExecutor methods return Halt, ProcessRefs and RuntimeSchema carry the new metadata, state files are written as version 2, native images as container version 13, and a timed Simulation ends at a design's $finish and settles host writes at the current time.
runUntil({ maxSteps }) calls the new Simulation::run_until_bounded through
NAPI instead of re-implementing the step loop in TypeScript.
Cover the timing statements and combinational processes of the frontend SDK, the round structure of a time slot, state files with processes, the bounded runUntil, and the shared-suite rule against depending on the race between an edge-woken process and the flip-flops of that edge.
Address review findings on the process phase: - Each publication of a domain evaluated more than once in a slot is an update: waits and event domains see it between images. - A queued nonblocking assignment or yield returns to the runtime between writes; the runtime checks waits and event edges at that return. - Checkpoints and state files carry the host writes the next step has yet to show the waits. - A $finish executed during a direct settle, read, dump or modify of a timed Simulation ends it. - Loading a state file sets whether the simulator is frozen.
When a domain publishes several evaluations, the edges among them are marked after the round's last publication, tracking each event signal's latest value, so a pulse that interleaves with another signal's or ends in the main flip-flop loop still triggers its domains. State files reject queued nonblocking assignments outside their target.
- Scheduled and process-driven values of one event signal compare with the preceding value, not only the round's baseline. - Several queued nonblocking assignments of a slot each count as an update for the event domains. - The waveform records the time slot of a $finish before the simulator freezes, and save_state notices a $finish its settle executed. - State files reject waiter baselines of the wrong kind. - A combinational process of the frontend SDK may overwrite part of a signal it assigned.
- A design without processes and counted signals runs the batch step's previous body as its own round; the process round is only for designs that need it. - Edge marking over a round's transitions is linear: each value compares with the latest one of its signal, kept in a generation-stamped table. - Host writes no longer reach an unreachable counter comparison. - The process round's helpers lose their inline hints.
- No unit loads the signal of a wait's event term: a kernel suspends and the runtime compares the signal with the waiter's baseline. Dead store elimination removed a combinational store to such a signal, and the wait never woke. - Every wait-term signal is a timing read root, like counters and staged nonblocking values.
- When one domain evaluates and applies in a single unit, the NBA region publishes right after it, and the stable-edge filter that follows cleared the occurrences the publications marked. A domain clocked by a pulse of two nonblocking assignments did not evaluate. - The fused path marks the round's occurrences again after the filter, as the path for several domains does.
- Each wave of the active region marked its transitions against the round's baseline, so a signal one process lowered and the process it woke raised again showed no rise, and its domain missed the pulse. - The latest value of each event signal now carries over the waves and the NBA publications of a round. It restarts with the round and where the baseline moves, before an inactive region.
- The process phase repeats while processes are ready or inactive, and only kernel returns and later rounds were charged. `forever #0`, or two processes waking each other through waits, looped inside one step, which `run_until_bounded` cannot stop. - Every round and every pass of the process phase counts against the slot's budget, and the step fails once it is spent. - `SimulationState::set_slot_budgets` sets the budgets.
- TypeScript DUT setters write the shared memory directly. The Rust `Simulation` only heard of writes through `modify`, so a write that should wake a process did nothing without a scheduled event, and woke it at the next event's time otherwise. - `Simulation::note_raw_writes` reports raw writes like `modify` does: the next step settles the current time when a process may see them or an event signal changed. NAPI exposes it as `noteHostWrites`. - The DUT records input writes apart from `dirty`, which a read clears. `Simulation` reports them before it steps, runs, peeks at the next event time, or saves a checkpoint or state file.
- A combinational process dropped every signal it wrote from its gate and sources, so reading `v[1]` while writing `v[0]` left `v` out, and the process did not run again when `v[1]` changed. - Its inputs are now the bit ranges it reads outside the ranges it writes (IEEE 1800-2023 9.2.2.2.1), as the SV lowering does. A gate input compares a range of its signal.
- Every round reads the triggered bits into a `BitSet`. The native backend tested them bit by bit, the others byte by byte. Once the process round also called the native reader, it was no longer inlined into the batch step, and a pure RTL run took 4% more instructions than master. - `celox_runtime::backend::triggered_bits_from_bytes` reads them 64 bits at a time and inserts only the set bits, for every backend.
- `celox` re-exports `ProcessRecord`, `WaiterRecord`, `BaselineRecord` and `NbaRecord`, which `ScheduleRecord::processes` holds. - `Simulation::is_finished` has its documentation back; it had landed on `run_until_bounded`. - `StateError::Processes`, no longer returned, no longer claims that state files do not support processes.
- A clock computed from a source, such as `clk & en`, is judged at the settle after the source changes, and its baseline moves then. A later settle of the round marked only the scheduled triggers, so with a process woken by the source (a second wave of the active region) the gated domain lost its edge. - Before an inactive region, the cascaded stable-edge test did not know the judged edges either, and the baseline resync hid the edge of a domain that evaluates later with the remaining domains. - Each settle of the round marks the judged edges again until their domain evaluates; the inactive region's evaluation honours them, and a domain it passes on keeps its edge approved.
- A host write that a waiting process or a counted signal may see is an update of the current time. The next step settled it and returned the current time, so a loop of writes and steps never advanced: with a process, any write did this, even after the process had finished. - A step now settles pending host writes at the current time and goes on to the next event. `run_until` and `run_until_bounded` stop at their end time (`SimulationState::step_until`). - Only waiting processes and counted signals make a host write pending; processes that finished or wait for a time do not see it.
- Only kernels and combinational process units count the writes of a counted signal, and a wait's counted term compared only the counter. A continuous assignment to other bits of the signal changed it without a count, and the wait never woke. - A counted term also keeps the signal's value at the last check and wakes on an occurrence the value shows. After a state file loads, the value is sampled once the state is in place.
- Waits were checked after the process phase, after publications and at the end of the round, not after the settle that follows each wave of flip-flop domains. A combinational value between two waves, such as `a & ~b` high after `a` rose and before `b <= a` published, triggered a flip-flop clocked by it but not a process waiting on it. - Each settle of the round's main loop checks the waits on driven signals (IEEE 1800-2023 4.5: every update event wakes the processes sensitive to it).
- `ProcessKernelBuilder::yield_now` returns so that the runtime charges a
process's time-slot budget, but the SDK lowering never placed it. A
`forever` or `while` loop without a timing control, such as `Forever {
Assign }`, spun inside the kernel and hung the step.
- A loop whose body has no delay, inactive delay or event wait at its top
level now yields at the end of each iteration, and the step fails once
the budget is spent. A level wait passes without suspending when its
condition holds, so it does not count.
- `NbaSite::pending` is only for a destination that nothing outside the module writes, so not a port, but the SDK lowering also flagged output ports with a single nonblocking site. A flat SDK module has no outside writers, so this only aligns the code with the contract.
- `runUntil(time(), { maxSteps })` returned before reporting the DUT's
input writes, so the writes stayed unseen until a later run; the
unbounded path and Rust `run_until_bounded` settle them at the target
time.
- The bounded path reports the writes first and keeps pending inputs for
lazy evaluation only when nothing is due at the target.
- `runUntilBounded` is optional on the native handle types, like
`noteHostWrites`; a handle without it reports that it does not support
bounded runs.
- Every state file was written as version 2, so older builds rejected even files of designs without processes. - A file whose processes have nothing to record is written as version 1, without the process section.
3a439b8 to
da37d93
Compare
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Second review addressed in 93aa888..da37d93, rebased onto b0237fa. Each should-fix item was reproduced by a new all-backend test before its fix (item 5 by a TS test against the previous
Nits fixed:
Perf: the step restructure keeps a single call site of the slot body, so (a) is 1,018,254,409 vs master b0237fa's 1,017,825,328 (+0.04%). |
tignear
left a comment
There was a problem hiding this comment.
Third review, of da37d93. Items 1–5 of the second review are closed and their tests fail without the fixes. The new step_until cannot overshoot, double-settle or loop; approved derived edges are cleared per round; batch_round still matches master's step_round, and the untimed path adds only the host_pending check. The accepted VCD timing change is fine.
Should-fix
-
The SDK loop yield makes long finite loops fail and slows them —
crates/celox-frontend-core/src/sdk.rs:1230,:1245, with the shared return budget atcrates/celox-runtime/src/simulation.rs:645.While { i < N, [mem[i] = 0, i += 1] }with N > 2^24 now ends with "does not suspend within one time slot" (it finished on master), and every iteration leaves the kernel and runsrecord_transitionsandobserve_driven. Yield only every 2^16 iterations of a loop that may not suspend (an iteration counter in the kernel's state), so a finite loop pays almost nothing and only a loop past ~2^40 iterations in one slot is reported;Forever { Assign }is still caught. -
A state-file round trip loses a pending wakeup of a counted-signal wait —
crates/celox/src/simulator/state_file.rs:459,:650,crates/celox/src/simulation.rs:458.BaselineRecord::Counterstores only the counter, and the value is re-sampled after loading. Withcounted_with_comb_writer:modify(a = 1),save_state()(which settles comb, so the file holdsv = 10),load_state(),step()→ the baseline is 10, the process never wakes; without the round trip it wakes. Store the value baseline in the record (checkpoints are fine, they clone the baseline).
Nits
SimulationState::step_until(limit)(simulation.rs:470,:507-509) is public and ignoreslimiton its first pass; check it on every pass or narrow the doc.- With counted signals, every host write is pending (
simulation.rs:1411), so such astep()runs two slots; andcheck_waitsreads the value of every counted term at each check (:797). Cost only; fine as a follow-up.
…suspend
- Loops that may not suspend yielded at every iteration. A long finite
loop then left the kernel, recorded transitions and checked the waits
each time, and one past 2^24 iterations exhausted the return budget it
finished within before.
- Such a loop now counts its iterations in a hidden 16-bit object and
yields when the count wraps: a finite loop pays one counter update per
iteration, and only about 2^40 iterations in one slot are reported.
`Forever { Assign }` still ends the step with an error.
- A state file recorded only the counter of a counted wait term, and the value it compares writes the counter misses with was sampled after loading. Saving settles combinational logic, so a write made before `save_state` was already in the sampled value, and the loaded wait never woke. - The counter record carries the value and its unknown bits; format version 2, new with this change set, encodes them after the counter.
- `SimulationState::step_until` checked `limit` only after settling host writes, so a call whose next time was already after the limit ran it. - Every pass now checks the limit, and the documentation says that no time after it runs.
|
Third review addressed in 35619d7..6c3d395. Each fix has a test on every backend that fails on da37d93:
|
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Merge Queue Status
This pull request spent 38 minutes 47 seconds in the queue, including 36 minutes 39 seconds running CI. Required conditions to merge
|
… $finish Since the timed runtime wakes processes on host writes (#1361), an edge's move of its clock signal is such a write: it now goes through the host watch, as IOContext writes do, so waits and counters a timed simulation keeps see it. The edge runtime takes the write as a callback (SignalWrite; set_level for hosts that observe nothing). Edges on a simulation a $finish froze change nothing, and a $finish during an edge is left to the host, as a tick does. Change-Id: If100c01610ac1c9d5169c0e64d37f7cc62b08390
… $finish Since the timed runtime wakes processes on host writes (#1361), an edge's move of its clock signal is such a write: it now goes through the host watch, as IOContext writes do, so waits and counters a timed simulation keeps see it. The edge runtime takes the write as a callback (SignalWrite; set_level for hosts that observe nothing). Edges on a simulation a $finish froze change nothing, and a $finish during an edge is left to the host, as a tick does. Change-Id: If100c01610ac1c9d5169c0e64d37f7cc62b08390
… $finish Since the timed runtime wakes processes on host writes (#1361), an edge's move of its clock signal is such a write: it now goes through the host watch, as IOContext writes do, so waits and counters a timed simulation keeps see it. The edge runtime takes the write as a callback (SignalWrite; set_level for hosts that observe nothing). Edges on a simulation a $finish froze change nothing, and a $finish during an edge is left to the host, as a tick does. Change-Id: If100c01610ac1c9d5169c0e64d37f7cc62b08390
Landing step 3 of #1123 ("runtime core"). Process kernels get the rest of the timing protocol, and the timed scheduler gains a process phase in front of today's batch step. Static classification picks the cheap mechanism per signal, domain and unit; only what it can't decide uses the dynamic one. Ordinary RTL keeps the batch path: fused evaluate-and-apply and parallel units.
What changes
Kernel protocol (
celox-design,frontend-core::process)InactiveDelay(IEEE#0),Wait/Pending(event and level waits),NbaandYield.ProcessKernelBuildermethods:inactive_delay,yield_now,suspend_wait+wake_if,wait_levelandnonblocking.Watched vs counted signals (
frontend-core::watch, assembly)Time slot (
celox-runtime)step_roundwith a process phase in front: active region, then inactive#0, and NBA only after both are empty (4.5).@(posedge clk)runs before that edge's flip-flops publish, so it reads the old flip-flop outputs.SimulationState::set_slot_budgets), so zero-time loops end a step with an error.Finish
Halt::Finishpropagates with?and freezesSimulator, so eval, modify and dump become no-ops.$finishends a timedSimulationonly. The untimedSimulatorkeeps "host decides".Host writes
IOContextsetters count and log writes to counted or waited signals.Simulation::modifymakes the next step settle the current time. This removes thehost_edges_after_time_zero_clock_flip_flopsoracle exclusion.Simulation::note_raw_writes(NAPInoteHostWrites). The TSSimulationreports DUT input writes before it steps, runs, peeks at the next event or saves state.SimulationState::step_untilkeepsrun_untilwithin its end time). Only waiting processes and counted signals make a write pending.Persistence
export_schedule/import_scheduleand state files.StateError::Processesis no longer returned.SDK and JS
InactiveDelay,WaitEvent,WaitLevel,NonblockingandModuleBuilder::comb_process.Simulation::run_until_bounded; NAPI and TSrunUntil({ maxSteps })call it instead of a TS step loop.Docs: internals architecture, the SDK guide (en/ja), checkpoints, writing-tests, and the shared-suite rule against depending on the race between an edge-woken process and that edge's flip-flops.
Tests
simulation::runtime_core_testsruns each case on interpreter, Cranelift, wasm, tiered, native and a native image that went through its container:@(posedge)and the FF once;#0vs FF evaluation, NBA and a zeroDelay;$urandomimperative comb unit): steady inputs with repeated settles and reads give zero spurious wakeups, and an input change gives the intra-unit pulse.comb, eval_apply, combwith or without a waiting testbench process (native, 1 and 4 threads); the woken process only adds its own run in front.Performance gate
Native backend, a 64-lane SDK RTL design. Instructions are callgrind counts inside
run_until(20k cycles × 7 runs, 1 thread). They are deterministic; wall time on this machine is not, so it is not reported.@(posedge clk)stimulus every cycle, one-shot#100; wait(acc[0])(b)–(d) are from the first review round (3a439b8 on a1c6987); the second round re-measured (a) only, since only the step's structure changed for designs without processes.
(a): a design without processes and counted signals runs master's
step_roundbody unchanged (batch_round). The triggered bits are now read a word at a time on every backend (9268d54); before that, (a) was +4.0% because the bit-by-bit native loop was no longer inlined.(b) − (a) = 265.7 M:
check_waits,advance,record_transitions, event-value reads)The Rust process path is the dynamic fallback; step 3b fuses statically classified kernels into their domain's JIT unit (target (b) = (a) + kernel body). (c): only the pulse signal is counted, with one counter set, and the pulse kernel is the only instrumented unit. No Heliodor.
Review fixes (owner review of fe1e38b)
Each with a test on every backend in
simulation::runtime_core_tests, reproduced before the fix:dead_store_elimination_keeps_signals_a_wait_watches, O2).nonblocking_pulses_after_a_single_domain_trigger_their_domain).a_pulse_across_two_waves_of_a_slot_is_an_edge).zero_time_loops_exhaust_the_slot_budget:forever #0and two processes waking each other).noteHostWrites(raw_host_writes_wake_waits_at_the_current_timeon every backend; a TS test for the call order).comb_processes_rerun_on_bits_they_do_not_write).triggered_bits_from_bytesfor every backend; (a) is back to master's count.celoxre-exportsProcessRecord,WaiterRecord,BaselineRecord,NbaRecord;is_finished's rustdoc; theStateError::Processesmessage.Rebase onto #1364: master's derived-clock handling is in both rounds.
batch_roundis master's newstep_roundbody. In the timed round,mark_scheduled_edgesrecords gating sources andsettle_markedjudges their derived clocks, as master does after its settle, withedge_approvedexempting them from the cascaded stable-edge test. Event reads useevent_level.derived_tickruns on theHaltexecutor. OnlySimulation::newarms the RTL$finishcheck, so a bareSimulator's ticks leave$finishto the host.Review fixes (second owner review, of 3a439b8)
Each with a test on every backend, reproduced before the fix:
gated_clocks_see_their_edges_with_processes:gclk = clk & enwith a process woken byclk, with and without#0).host_writes_do_not_hold_steps_at_the_current_time, with a finished process and with a waiting one). The waveform records such a write at its own time;vcd::activity::clock_trigger_consumption_does_not_consume_waveform_activitynow samples its reference after the write too, where the simulator's VCD shows it.waits_on_counted_signals_see_uncounted_writers, with a state-file round trip).waits_see_combinational_pulses_between_flip_flop_waves).runUntil(time(), { maxSteps })reports host writes first and runs when something is due at the target (TS test, reproduced against the previoussimulation.ts).Forever { Assign }ends a step with an error (32fb4a8,zero_time_loops_exhaust_the_slot_budget); SDK ports never get a single-site NBA flag (4695d6a); state files without process state are version 1 (da37d93);runUntilBoundedis optional on the native handle types (a740353);external-frontends(en/ja) and the architecture notes describe TS DUT writes and the new step behaviour (a6594fa).Review fixes (third owner review, of da37d93)
Each with a test on every backend that fails on da37d93:
long_finite_loops_yield_rarely: 2^17 iterations within a return budget of 2;zero_time_loops_exhaust_the_slot_budgetstill catchesForever { Assign }).save_statestill wakes the loaded wait (waits_on_counted_signals_see_uncounted_writersnow writes, saves, loads, then steps).SimulationState::step_untilchecks its limit before every pass (6c3d395).Validation
On the branch as pushed (based on b0237fa):
cargo fmt --check; clippy (affected crates, all targets,--features celox/systemverilog,--no-deps,-D warnings) andRUSTDOCFLAGS=-D warnings cargo doc --no-depsfor the affected crates: clean.cargo test -p celox --features systemverilog --libplussystemverilog,processes,simulation_step,simulation_limits,concurrent_initial_runtime,checkpoint,state_file,frontend_sdk,native_testbench,native_testbench_completion,component_method,cascade_race,clock_alias_edges,ff_comb_clock,multi_clock,reset_edge_cases,vcd,derived_register_clock,flip_flopandtestbench_string: 4376 passed.celox-design,-frontend-core,-frontend-sdk,-frontend-sv,-test-suiteand-runtime;celox-runtime --test parallel_tracing;celox-vpi --test basic_vpi.host_edges_after_time_zero_clock_flip_flopspasses. The other timing exclusions remain; they need SV lowering (step 4).pnpm -r test(excluding NAPI and playground),pnpm run typecheckandpnpm run lint(on da37d93; the third round changes no TypeScript or NAPI code).Not in this PR / found along the way
Andmask.cargo test) is fixed on master by test(runtime): isolate parallel trace capture from concurrent tests #1375.$finish: the fused path halts aftereval_apply_ff_at(NBAs committed), the split path aftereval_only_ff_at; both should leave NBAs unpublished (IEEE 20.2 / 4.5). Step 4.always @*units with$randominclude their own targets in the gate (celox-frontend-sv/src/lowering/ff.rs); with a counted target each re-run adds an edge.crates/celox/src/testbench_compile.rsoverwrites the read roots and drops the timing roots (harmless today).resolve_processesaccepts a process listed twice and wakeups beforerecord.time.celox state dump/diffignore the process section.step()runs two slots, andcheck_waitsreads the value of every counted term at each check. Cost only.