Skip to content

feat(runtime)!: wake processes on events in front of the batch step - #1361

Merged
mergify[bot] merged 26 commits into
masterfrom
feature/1123-runtime-core
Oct 17, 2026
Merged

mergify[bot] merged 26 commits into
masterfrom
feature/1123-runtime-core

Conversation

@tignear

@tignear tignear commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

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)

  • New statuses: InactiveDelay (IEEE #0), Wait/Pending (event and level waits), Nba and Yield.
  • New ProcessKernelBuilder methods: inactive_delay, yield_now, suspend_wait + wake_if, wait_level and nonblocking.
  • Wait and NBA sites are runtime-schema metadata, numbered per process.

Watched vs counted signals (frontend-core::watch, assembly)

  • A waited signal is checked by value against the waiter's baseline (IEEE 1800-2023 Table 9-2), at the points where it can change.
  • A signal is counted only if a unit may store it twice without a check in between, and an FF domain or wait watches it. Assembly then instruments exactly those stores, in kernels and combinational process units, with changes/rises/falls counters in plain SIR. No backend changes.
  • Combinational process units are gated on input changes (9.2.2.2). The SV imperative comb units already were; the new tests confirm it on every backend.

Time slot (celox-runtime)

  • A round is today's step_round with a process phase in front: active region, then inactive #0, and NBA only after both are empty (4.5).
  • A process woken by @(posedge clk) runs before that edge's flip-flops publish, so it reads the old flip-flop outputs.
  • Domains triggered before an inactive region evaluate first and publish in the NBA region. A domain evaluated twice keeps the earlier working state.
  • Kernel NBAs use an ordered queue, or a single pending value per site when nothing else assigns the destination. A pending site re-executed within the slot falls back to the queue before re-evaluating its RHS.
  • A design without processes or counted signals runs the previous batch step unchanged, as its own function.
  • Each round and each pass of the process phase counts against the slot's budget (SimulationState::set_slot_budgets), so zero-time loops end a step with an error.

Finish

  • Halt::Finish propagates with ? and freezes Simulator, so eval, modify and dump become no-ops.
  • An RTL $finish ends a timed Simulation only. The untimed Simulator keeps "host decides".

Host writes

  • IOContext setters count and log writes to counted or waited signals.
  • Simulation::modify makes the next step settle the current time. This removes the host_edges_after_time_zero_clock_flip_flops oracle exclusion.
  • Raw writes through the memory view are reported with Simulation::note_raw_writes (NAPI noteHostWrites). The TS Simulation reports DUT input writes before it steps, runs, peeks at the next event or saves state.
  • Host writes never hold the simulation at one time: a step settles them at the current time and goes on to the next event (SimulationState::step_until keeps run_until within its end time). Only waiting processes and counted signals make a write pending.

Persistence

  • Waiter baselines, ready/inactive sets, the NBA queue and domain counter baselines go into checkpoints, export_schedule/import_schedule and state files.
  • State files are now version 2 (v1 still loads) and support designs with processes, so StateError::Processes is no longer returned.
  • Native image container version 13.

SDK and JS

  • SDK format 3 adds InactiveDelay, WaitEvent, WaitLevel, Nonblocking and ModuleBuilder::comb_process.
  • Simulation::run_until_bounded; NAPI and TS runUntil({ 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_tests runs each case on interpreter, Cranelift, wasm, tiered, native and a native image that went through its container:
    • a 0→1→0 pulse wakes @(posedge) and the FF once;
    • repeated edges in one slot evaluate a domain twice and publish both in order;
    • host-write edges;
    • level waits;
    • #0 vs FF evaluation, NBA and a zero Delay;
    • two NBAs to one destination and a re-executed single-site NBA;
    • finish freezes outputs;
    • checkpoint/restore of a waiting process;
    • a state file of a waiting process saved on the interpreter and loaded into every backend;
    • an edge-woken process reads FF outputs from before the edge;
    • comb pulse gating (SDK, and an SV $urandom imperative comb unit): steady inputs with repeated settles and reads give zero spurious wakeups, and an input change gives the intra-unit pulse.
  • A recording-executor test shows that a clock-edge step calls comb, eval_apply, comb with or without a waiting testbench process (native, 1 and 4 threads); the woken process only adds its own run in front.
  • Unit tests cover candidate detection, Table 9-2 on plane images, state-file v2 and v1, and SDK format 3.

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.

instructions vs (a)
(a) pure RTL, master b0237fa 1,017,825,328
(a) pure RTL, this PR (rebased onto b0237fa) 1,018,254,409 (+0.04% vs master)
(b) + typical testbench: @(posedge clk) stimulus every cycle, one-shot #100; wait(acc[0]) 1,283,140,334 +265.7 M
(c) (b) + a counted intra-slot pulse every negedge 1,789,958,901
(d) stress: a level wait re-armed every 3 time units 1,595,486,321

(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_round body 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:

part instructions
kernel body (JIT) 3.9 M
waiter + check points (check_waits, advance, record_transitions, event-value reads) 101.9 M
extra eval_comb / FF evaluation 0 (identical call counts)
rest 159.9 M

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:

  1. 657b51a: wait-term signals are timing read roots, so DSE keeps a combinational store that only a wait reads (dead_store_elimination_keeps_signals_a_wait_watches, O2).
  2. c58b416: the single-domain fused path marks the NBA publications' occurrences again after its stable-edge filter (nonblocking_pulses_after_a_single_domain_trigger_their_domain).
  3. 35e4b69: the latest value of each event signal carries over the waves of a round; it restarts with the round and where the baseline moves (a_pulse_across_two_waves_of_a_slot_is_an_edge).
  4. 6480eea: every round and process-phase pass is charged against the slot budget (zero_time_loops_exhaust_the_slot_budget: forever #0 and two processes waking each other).
  5. 9d037a0: TS DUT input writes reach the scheduler through noteHostWrites (raw_host_writes_wake_waits_at_the_current_time on every backend; a TS test for the call order).
  6. 30bd77f: SDK combinational processes gate on the bit ranges they read outside what they write (comb_processes_rerun_on_bits_they_do_not_write).
  7. 9268d54: triggered_bits_from_bytes for every backend; (a) is back to master's count.
  • Nits fixed in 1dec92c: celox re-exports ProcessRecord, WaiterRecord, BaselineRecord, NbaRecord; is_finished's rustdoc; the StateError::Processes message.

Rebase onto #1364: master's derived-clock handling is in both rounds. batch_round is master's new step_round body. In the timed round, mark_scheduled_edges records gating sources and settle_marked judges their derived clocks, as master does after its settle, with edge_approved exempting them from the cascaded stable-edge test. Event reads use event_level. derived_tick runs on the Halt executor. Only Simulation::new arms the RTL $finish check, so a bare Simulator's ticks leave $finish to the host.

Review fixes (second owner review, of 3a439b8)

Each with a test on every backend, reproduced before the fix:

  1. 93aa888: derived-clock edges judged at a settle are marked again at each later settle of the round until their domain evaluates; the inactive region's evaluation honours them, and a domain it passes on keeps its edge (gated_clocks_see_their_edges_with_processes: gclk = clk & en with a process woken by clk, with and without #0).
  2. a6594fa: a step settles pending host writes at the current time and goes on to the next event; only waiting processes and counted signals make a write pending (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_activity now samples its reference after the write too, where the simulator's VCD shows it.
  3. da88fc6: a counted wait term keeps the signal's value next to the counter and wakes on an occurrence a write the counter misses shows; state files record that value since c60f8d5 (waits_on_counted_signals_see_uncounted_writers, with a state-file round trip).
  4. 76e26ff: waits on driven signals are checked after each settle of the round's main loop (waits_see_combinational_pulses_between_flip_flop_waves).
  5. a740353: bounded TS runUntil(time(), { maxSteps }) reports host writes first and runs when something is due at the target (TS test, reproduced against the previous simulation.ts).
  • Nits fixed: SDK loops that may not suspend yield (every 2^16 iterations since 35619d7), so 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); runUntilBounded is 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:

  1. 35619d7: an SDK loop that may not suspend counts its iterations in a hidden 16-bit object and yields when the count wraps, not every iteration. A finite loop pays one counter update per iteration, and only about 2^40 iterations in one slot exhaust the return budget (long_finite_loops_yield_rarely: 2^17 iterations within a return budget of 2; zero_time_loops_exhaust_the_slot_budget still catches Forever { Assign }).
  2. c60f8d5: the counter record of a counted wait term carries the value baseline, so a write settled by save_state still wakes the loaded wait (waits_on_counted_signals_see_uncounted_writers now writes, saves, loads, then steps).
  • Nit: SimulationState::step_until checks 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) and RUSTDOCFLAGS=-D warnings cargo doc --no-deps for the affected crates: clean.
  • cargo test -p celox --features systemverilog --lib plus systemverilog, 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_flop and testbench_string: 4376 passed.
  • Unit tests of celox-design, -frontend-core, -frontend-sdk, -frontend-sv, -test-suite and -runtime; celox-runtime --test parallel_tracing; celox-vpi --test basic_vpi.
  • The timing oracle's host_edges_after_time_zero_clock_flip_flops passes. The other timing exclusions remain; they need SV lowering (step 4).
  • NAPI debug build, then pnpm -r test (excluding NAPI and playground), pnpm run typecheck and pnpm run lint (on da37d93; the third round changes no TypeScript or NAPI code).

Not in this PR / found along the way

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-17T00:07:15.285504Z 6c3d395 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

self.simulator.load_state(file)?;
self.state.import_schedule(parts);

P2 Badge Synchronize the simulator freeze state on load

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".

Comment on lines +999 to +1002
restore_working_image(executor.backend_mut(), image);
if let Some(event) = self.event_info[*id].apply_event {
executor.apply_ff_at(event)?;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment on lines +111 to +113
fn take_host_writes(&mut self) -> Vec<(SignalRef, celox_runtime::timing::Value)> {
self.host_watch.take_log()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +157 to +161
fn runtime_finish(&mut self) -> Result<(), Halt> {
if !self.finish_sites {
return Ok(());
}
if self.take_runtime_finish() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/celox-runtime/src/simulation.rs Outdated
Comment on lines +498 to +501
self.queue_nba(executor.backend_mut(), process, site)?;
*returns += 1;
self.charge(*returns, Some(process))?;
continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@mergify

mergify Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

@tignear

tignear commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Re the review-level finding (freeze state on load): fixed in 018705d. Simulation::load_state now sets the simulator's frozen state from the loaded schedule, in both directions. Test: loading_a_finished_state_freezes_the_simulation.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/celox-runtime/src/simulation.rs Outdated
Comment on lines +1055 to +1058
let was_nonzero = previous
.filter(|(last, _)| *last == id)
.map_or(self.last_clock_values.contains(id), |(_, value)| value);
previous = Some((id, is_nonzero));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +85 to +87
fn eval_comb(&mut self) -> Result<(), Halt> {
self.eval_comb_checked()?;
self.runtime_finish()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +639 to +643
Some(&target) => nba_queue.push(celox_runtime::NbaUpdate {
target,
lsb: update.lsb as usize,
width: update.width as usize,
value: (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +625 to +630
.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),
)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1494 to +1495
for target in comb_process_targets(&body) {
self.record_driver_target(target)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread crates/celox-runtime/src/simulation.rs Outdated
Comment on lines +756 to +758
for &(id, is_nonzero) in values {
round.track_stable_edges = true;
let was_nonzero = self.last_clock_values.contains(id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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| {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;).

Comment on lines +381 to +383
Err(Halt::Finish) => {
self.finish(executor);
Ok(Some(self.scheduler.time))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@tignear tignear left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. DSE removes comb stores to signals that only a wait watches — crates/celox-frontend-core/src/symbolic/assembly.rs:1469. timing_read_roots holds counters and NBA slots but not the wait-term signals, and WaitEvent lowers to suspend_wait + wake_if(1), so no unit loads the term. Internal y = a & b with a process @(posedge y) at O2 (PreserveTopPorts): the store to y is eliminated and the process never wakes. Add every wait-term signal to the roots.

  2. Several NBAs pulsing an event signal are lost on the single-domain fused path — crates/celox-runtime/src/simulation.rs:1397-1403. publish_nba marks occurrences, then replace_triggers_with_stable_edges clears them and, unlike the multi-domain path (1513-1515), does not re-mark round.occurrences. Scheduled posedge clk triggers only domain A; a kernel woken by it does p <= 1; p <= 0;; domain B on @(posedge p) never evaluates. With a second domain on clk, B does evaluate.

  3. A pulse across two wake waves of one slot is lost for FF domains — simulation.rs:790-795 with 1162-1166. Each wave's mark_scheduled_edges calls begin_scan, so the earlier wave's value falls back to last_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.

  4. Zero-time loops inside one round hang without a budget error — simulation.rs:1154-1190. process_phase repeats while ready/inactive is non-empty; charge runs only for Nba/Yield. SDK Forever { InactiveDelay(0) }, or two kernels waking each other through waits, loop forever inside one step, which run_until_bounded cannot stop. Charge every pass of the process phase against the slot budget.

  5. Host writes from TS never reach waits, counters or host_pending — only Rust Simulation::modify goes through HostWatch/note_host_writes; TS setters write the buffer and set dirty. SDK design via from_frontend, kernel @(posedge go) done = 1; TS dut.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 before runUntil/step (treat it as a logged host write for the whole input set, or reconcile at entry and settle the current time).

  6. SDK comb_process drops inputs at whole-signal granularity — crates/celox-frontend-core/src/sdk.rs:1473, 1503. Reading v[1] while writing v[0] removes v from the gate and the sources (IEEE 1800-2023 9.2.2.2.1 uses the longest static prefix; SV lowering does it by range in subtract_written_sensitivity). assign v[1] = a; + comb_process { v[0] = v[1]; } runs once and v[0] stays stale. Filter by written range.

  7. Pure RTL +4.0% vs master — the PR body attributes +71.4 M to get_triggered_bits no longer being inlined. That function builds a BitSet bit 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 after eval_apply_ff_at (NBAs committed), the split path after eval_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 @* $random units 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:13 overwrites the read roots and drops the timing roots (harmless today).
  • celox does not re-export ProcessRecord, WaiterRecord, BaselineRecord, NbaRecord while ScheduleRecord.processes is public.
  • is_finished's rustdoc landed on run_until_bounded (crates/celox/src/simulation.rs:569-574).
  • resolve_processes accepts a process listed twice or wakeups before record.time.
  • celox state dump/diff ignore the process section.
  • StateError::Processes is 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.

@tignear
tignear force-pushed the feature/1123-runtime-core branch from fe1e38b to 3a439b8 Compare October 16, 2026 22:34
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@tignear

tignear commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in 709749c..3a439b8, rebased onto a1c6987 (#1364). Each should-fix item was reproduced by a new all-backend test before its fix:

  1. 709749c: wait-term signals are timing read roots (dead_store_elimination_keeps_signals_a_wait_watches, O2).
  2. 725984f: the fused single-domain path re-marks round.occurrences after its stable-edge filter (nonblocking_pulses_after_a_single_domain_trigger_their_domain).
  3. 77955da: the latest value per event signal carries over the waves of a round; it restarts with the round and after the baseline moves before an inactive region (a_pulse_across_two_waves_of_a_slot_is_an_edge).
  4. a50b707: every round and process-phase pass is charged against the slot budget; SimulationState::set_slot_budgets (zero_time_loops_exhaust_the_slot_budget, forever #0 and a ping-pong pair; both hung before).
  5. c45c346: Simulation::note_raw_writes / NAPI noteHostWrites; the TS DUT records input writes apart from dirty and Simulation reports them before stepping, running, peeking or saving (raw_host_writes_wake_waits_at_the_current_time plus a TS call-order test).
  6. ce2f0a8: SDK comb processes gate on the bit ranges read outside the written ranges; GateInput has an lsb (comb_processes_rerun_on_bits_they_do_not_write).
  7. 4c27fff: triggered_bits_from_bytes for all backends. (a) is 1,017,413,662 vs master's 1,017,684,978 (−0.03%).

Nits: the re-exports, is_finished's rustdoc and the StateError::Processes message are in 3a439b8. The others are listed as follow-ups in the PR body.

Rebase: #1364 is ported into both rounds. batch_round is the new step_round body. The timed round records gating sources in mark_scheduled_edges and judges them at the end of settle_marked, with edge_approved. derived_tick runs on the Halt executor, and only Simulation::new arms the RTL $finish check, so untimed ticks keep "host decides".

@tignear tignear left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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_marked sees scheduled_trigger_ids non-empty, clears the triggered bits and re-marks only those ids; the gclk id that judge_derived_edges approved in wave 1 (and whose baseline it already moved) is not re-marked, and gating_sources is already consumed. After the commit the stable-edge pass compares 1 with 1.
    • evaluate_before_inactive runs the cascaded stable-edge test without edge_approved, and synchronize_event_values moves 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_approved in settle_marked, consult it in evaluate_before_inactive, and only rebase the ids that evaluated.
  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.processes is the static kernel list, so this holds after every process is Done and no waiter exists. SV initial begin #5 rst = 0; end + TS for (...) { dut.d = i; sim.step(); }: time never advances (on master each step advanced). Same for Rust modify. Use registered waiters (and counted signals only if a host write can reach them unbumped), not the process list.

  3. A wait on a counted signal misses writers that are not instrumented — simulation.rs:655-656 with instrument_counted_signals in symbolic/assembly.rs. Counted is per whole variable, but only kernels and comb-process units bump the counter, and a counted term keeps only Baseline::Counter. SDK: assign v[1] = a;, P0 forever { v[0]=1; v[0]=0; #10 } (makes v a candidate), P1 WaitEvent{v, Change}. Host sets a=1: eval_comb writes v[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.

  4. A wait misses a combinational pulse between cascaded FF waves of one round — simulation.rs:1600-1654: waits are checked after finish_publications and after the loop, not after each outer-loop settle. A a <= ~a on clk, B b <= a on 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). Run observe_driven after each outer-loop settle when waiters exist.

  5. Bounded TS runUntil(time(), { maxSteps }) drops pending host writes — packages/celox/src/simulation.ts:457-458 returns on >= before noteHostWrites(); the unbounded path and Rust run_until_bounded settle the equal case. Use < and report the writes first.

Nits

  • NbaSite::pending rustdoc and design condition 1 say "not a port", but single_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:44 always writes v2, even with an empty process section; older releases then reject pure-RTL files. Write the oldest version that fits.
  • runUntilBounded is a required member of the exported NativeSimulationHandle / RawNapiSimulationHandle; make it optional like noteHostWrites, or say it in the breaking-change note.
  • docs/guide/external-frontends.md (en/ja) mention the settle-current-time behaviour only for Simulation::modify; TS DUT writes do it too.
  • ProcessKernelBuilder::yield_now is documented as placed in timing-free loops, but nothing places it, so SDK Forever { Assign } still spins inside run_process (pre-existing). Fix the comments that claim the budget covers it, or place the yield in the SDK While/Forever lowering.

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.
@tignear
tignear force-pushed the feature/1123-runtime-core branch from 3a439b8 to da37d93 Compare October 16, 2026 23:38
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@tignear

tignear commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

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 simulation.ts):

  1. 93aa888: settle_marked marks edge_approved again at every settle until the domain evaluates. evaluate_before_inactive honours it, drops the ids it evaluates, and approves the unsplit ids it passes on, so the resync no longer hides their edge (gated_clocks_see_their_edges_with_processes, gclk = clk & en with a clk-woken process, with and without #0).
  2. a6594fa: only waiters and counted signals make a host write pending. A step also settles pending writes at the current time and goes on to the next event; with only the narrower condition, a waiting process would still have held a loop of writes and steps at one time. run_until/run_until_bounded use SimulationState::step_until(limit). Test: host_writes_do_not_hold_steps_at_the_current_time, with a finished and with a waiting process. The VCD test's reference now samples after the host write, where the simulator records it.
  3. da88fc6: a counted term keeps the signal's value next to the counter and wakes on an occurrence the value shows; it is sampled after a state file loads (waits_on_counted_signals_see_uncounted_writers, including a state-file round trip). FF domains already see such writes through the stable-edge pass.
  4. 76e26ff: observe_driven after each settle of the main loop (waits_see_combinational_pulses_between_flip_flop_waves).
  5. a740353: the bounded path reports host writes first and returns early only when nothing is due at the target.

Nits fixed:

  • 32fb4a8: SDK While/Forever bodies without a top-level delay, #0 or event wait yield each iteration, so Forever { Assign } ends the step with an error.
  • 4695d6a: SDK ports never get a single-site NBA flag.
  • da37d93: state files without process state are written as version 1.
  • a740353: runUntilBounded is optional on the handle types.
  • a6594fa: external-frontends (en/ja) and the architecture notes cover TS DUT writes.

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 tignear left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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 at crates/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 runs record_transitions and observe_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.

  2. 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::Counter stores only the counter, and the value is re-sampled after loading. With counted_with_comb_writer: modify(a = 1), save_state() (which settles comb, so the file holds v = 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 ignores limit on 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 a step() runs two slots; and check_waits reads 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.
@tignear

tignear commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Third review addressed in 35619d7..6c3d395. Each fix has a test on every backend that fails on da37d93:

  1. 35619d7: an SDK loop that may not suspend counts iterations in a hidden 16-bit object and yields when it wraps (long_finite_loops_yield_rarely: 2^17 iterations with a return budget of 2; Forever { Assign } is still caught in zero_time_loops_exhaust_the_slot_budget).
  2. c60f8d5: BaselineRecord::Counter { seen, value, mask }. The value baseline is in the record, and the post-load sampling is gone. waits_on_counted_signals_see_uncounted_writers now does modify → save → load → run.
  • 6c3d395: step_until checks its limit before every pass; the doc says no time after it runs.
  • The counted host-write cost is listed as a follow-up in the PR body.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@tignear tignear added the merge-ready Request merging through Mergify after required checks label Oct 17, 2026
@mergify mergify Bot added the queued Mergify queue entry label Oct 17, 2026
@mergify

mergify Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

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
  • check-success = Conventional Commit title
  • check-success = Queue validation
  • any of [🛡 GitHub repository ruleset rule master]:
    • check-success = @github-actions/Lint & Format
    • check-neutral = @github-actions/Lint & Format
    • check-skipped = @github-actions/Lint & Format
  • any of [🛡 GitHub repository ruleset rule master]:
    • check-success = @github-actions/NAPI Build (Linux ARM64 GNU)
    • check-neutral = @github-actions/NAPI Build (Linux ARM64 GNU)
    • check-skipped = @github-actions/NAPI Build (Linux ARM64 GNU)
  • any of [🛡 GitHub repository ruleset rule master]:
    • check-success = @github-actions/NAPI Build (Windows)
    • check-neutral = @github-actions/NAPI Build (Windows)
    • check-skipped = @github-actions/NAPI Build (Windows)
  • any of [🛡 GitHub repository ruleset rule master]:
    • check-success = @github-actions/Rust Test & NAPI Build
    • check-neutral = @github-actions/Rust Test & NAPI Build
    • check-skipped = @github-actions/Rust Test & NAPI Build
  • any of [🛡 GitHub repository ruleset rule master]:
    • check-success = @github-actions/JS Test (Ubuntu)
    • check-neutral = @github-actions/JS Test (Ubuntu)
    • check-skipped = @github-actions/JS Test (Ubuntu)
  • any of [🛡 GitHub repository ruleset rule master]:
    • check-success = @github-actions/JS Test (Windows)
    • check-neutral = @github-actions/JS Test (Windows)
    • check-skipped = @github-actions/JS Test (Windows)
  • any of [🛡 GitHub repository ruleset rule master]:
    • check-success = @github-actions/Conventional Commit title
    • check-neutral = @github-actions/Conventional Commit title
    • check-skipped = @github-actions/Conventional Commit title

@mergify
mergify Bot merged commit 2610a99 into master Oct 17, 2026
22 checks passed
@mergify
mergify Bot deleted the feature/1123-runtime-core branch October 17, 2026 01:17
@mergify mergify Bot removed the queued Mergify queue entry label Oct 17, 2026
tignear added a commit that referenced this pull request Oct 17, 2026
… $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
tignear added a commit that referenced this pull request Oct 17, 2026
… $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
tignear added a commit that referenced this pull request Oct 17, 2026
… $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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-ready Request merging through Mergify after required checks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant