Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions crates/celox/tests/frontends/systemverilog/system_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1337,6 +1337,26 @@ fn stop_suspends_the_simulation_until_it_continues() {
assert_eq!(sim.time(), 10);
assert_eq!(sim.get(count), 6u8.into());
assert_eq!(sim.get(other), 5u8.into());

// The bounded API returns false both at a new stop and when no step is
// allowed to resume it. Bindings distinguish these using the stop state
// and whether the budget allowed a step.
let mut sim = initial_simulation(source);
sim.modify(|io| io.set(rounds, 3u8)).unwrap();
for expected in [1u8, 2, 4, 5] {
assert!(!sim.run_until_bounded(10, 1).unwrap());
assert!(sim.is_stopped());
assert_eq!(sim.time(), 0);
assert_eq!(sim.get(count), expected.into());
assert!(!sim.run_until_bounded(10, 0).unwrap());
assert!(sim.is_stopped());
assert_eq!(sim.get(count), expected.into());
}
assert!(sim.run_until_bounded(10, 1).unwrap());
assert!(!sim.is_stopped());
assert_eq!(sim.time(), 10);
assert_eq!(sim.get(count), 6u8.into());
assert_eq!(sim.get(other), 5u8.into());
}

/// The time step a `$stop` suspends continues where it stopped: an edge a
Expand Down
105 changes: 105 additions & 0 deletions packages/celox/src/simulation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,111 @@ describe("Simulation", () => {
);
});

test("runUntil with maxSteps: returns normally at $stop and can resume", () => {
const mock = createMockNative();
let stopped = false;
mock.handle.isStopped = vi.fn(() => stopped);
vi.mocked(mock.handle.runUntilBounded!).mockImplementationOnce(() => {
mock.handle.step();
stopped = true;
return false;
});
const sim = Simulation.create(TopModule, {
__nativeCreate: mock.create,
});
sim.dut.d = 42n;

expect(() => sim.runUntil(25, { maxSteps: 1 })).not.toThrow();
expect(sim.time()).toBe(5);
expect(sim.isStopped()).toBe(true);
expect(sim.dut.q).toBe(42n);
expect(mock.handle.evalComb).not.toHaveBeenCalled();

// No step was allowed to resume the stopped process, so this is
// still a budget exhaustion rather than a newly encountered stop.
expect(() => sim.runUntil(25, { maxSteps: 0 })).toThrow(
SimulationTimeoutError,
);
expect(sim.isStopped()).toBe(true);
expect(sim.time()).toBe(5);

vi.mocked(mock.handle.step).mockImplementationOnce(() => {
stopped = false;
return 5;
});
sim.runUntil(25, { maxSteps: 5 });
expect(sim.isStopped()).toBe(false);
expect(sim.time()).toBe(25);
});

test.each([0.5, -0.5, Number.NaN])(
"runUntil normalizes an effective zero budget while stopped (%s)",
(maxSteps) => {
const mock = createMockNative();
mock.handle.isStopped = vi.fn(() => true);
vi.mocked(mock.handle.runUntilBounded!).mockReturnValue(false);
const sim = Simulation.create(TopModule, {
__nativeCreate: mock.create,
});
sim.dut.d = 42n;

expect(() => sim.runUntil(25, { maxSteps })).toThrow(
SimulationTimeoutError,
);
expect(mock.handle.runUntilBounded).toHaveBeenCalledWith(25, 0);
expect(sim.isStopped()).toBe(true);
expect(sim.time()).toBe(0);
expect(sim.dut.q).toBe(42n);
expect(mock.handle.evalComb).toHaveBeenCalledOnce();
},
);

test("runUntil truncates a fractional positive budget before passing it to native code", () => {
const mock = createMockNative();
const sim = Simulation.create(TopModule, {
__nativeCreate: mock.create,
});

sim.runUntil(25, { maxSteps: 5.9 });
expect(mock.handle.runUntilBounded).toHaveBeenCalledWith(25, 5);
});

test.each([true, false])(
"runUntil preserves input writes when resuming a stopped slot (stops again: %s)",
(stopsAgain) => {
const mock = createMockNative();
let stopped = true;
mock.handle.isStopped = vi.fn(() => stopped);
// Resuming the suspended slot can return before pending host
// writes are settled, both at another stop and at the step limit.
vi.mocked(mock.handle.runUntilBounded!).mockImplementationOnce(() => {
stopped = stopsAgain;
return false;
});
const sim = Simulation.create(TopModule, {
__nativeCreate: mock.create,
});
sim.dut.d = 42n;

if (stopsAgain) {
expect(() => sim.runUntil(25, { maxSteps: 1 })).not.toThrow();
} else {
expect(() => sim.runUntil(25, { maxSteps: 1 })).toThrow(
SimulationTimeoutError,
);
}
expect(sim.time()).toBe(0);
expect(sim.isStopped()).toBe(stopsAgain);
expect(mock.handle.evalComb).not.toHaveBeenCalled();
expect(sim.dut.q).toBe(42n);
expect(mock.handle.evalComb).toHaveBeenCalledOnce();
// Reading twice must not evaluate twice or notify the scheduler again.
expect(sim.dut.q).toBe(42n);
expect(mock.handle.evalComb).toHaveBeenCalledOnce();
expect(mock.handle.noteHostWrites).toHaveBeenCalledOnce();
},
);

test("runUntil with maxSteps: timeout error has correct properties", () => {
const mock = createMockNative();
const sim = Simulation.create(TopModule, {
Expand Down
15 changes: 11 additions & 4 deletions packages/celox/src/simulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,8 @@ export class Simulation<P = Record<string, unknown>> {
*
* When `maxSteps` is provided, the Rust run loop takes at most that many
* steps and a `SimulationTimeoutError` is thrown if the budget is
* exhausted before reaching `endTime`.
* exhausted before reaching `endTime`. A design that executes `$stop`
* returns normally; use `isStopped()` to detect the suspension.
*/
runUntil(endTime: number, opts?: { maxSteps?: number }): void {
this.ensureAlive();
Expand All @@ -451,7 +452,8 @@ export class Simulation<P = Record<string, unknown>> {
this._state.dirty = false;
return;
}
const max = opts.maxSteps;
// Normalize zero-step budgets before interpreting the native result.
const max = Math.max(0, Math.trunc(opts.maxSteps) || 0);
if (!this._handle.runUntilBounded) {
throw new Error("This simulation does not support bounded runs");
}
Expand All @@ -463,9 +465,14 @@ export class Simulation<P = Record<string, unknown>> {
const next = this._handle.nextEventTime();
if (next == null || next > endTime) return;
}
const wasStopped = this.isStopped();
if (!this._handle.runUntilBounded(endTime, max)) {
// A step took the pending inputs unless none was allowed.
if (max > 0) this._state.dirty = false;
if (max > 0) {
// A resumed slot can stop or exhaust the budget before pending
// host writes are consumed. Keep them eligible for lazy evaluation.
if (!wasStopped) this._state.dirty = false;
if (this.isStopped()) return;
Comment on lines +470 to +474

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 Normalize maxSteps before treating a stop as newly encountered

When a caller resumes an already-stopped simulation with a fractional positive budget below 1, the NAPI boundary truncates max_steps to zero (crates/celox-napi/src/lib.rs:2048), so the bounded run returns false without executing a step and leaves the old stopped state set. Because the original JavaScript value still satisfies max > 0, this branch mistakes that old state for a newly encountered $stop and returns normally instead of reporting budget exhaustion. Validate or normalize maxSteps before both the native call and this test so the effective zero-step budget retains the documented timeout behavior.

Useful? React with 👍 / 👎.

}
throw new SimulationTimeoutError(
`runUntil: exceeded ${max} steps at time ${this._handle.time()} (target ${endTime})`,
this._handle.time(),
Expand Down
Loading