From e95f48173583006acd96934b5b1a506f01d1850e Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 22:42:00 +0900 Subject: [PATCH 1/4] test(sv): cover bits queries in module parameter overrides The reproductions in #1437 already work on current master. Preserve that behavior in shared executable regressions rather than adding a redundant compiler change. Cover named and ordered overrides using `$bits` of typedefs and variables, arithmetic combining queries, package types, unpacked arrays and callers specialized with different parameter values. Closes #1437. Validation: both shared cases pass all five Celox execution variants (10 tests) and Verilator/Icarus (2 cases each). Shared-suite library tests, affected suite/consumer Clippy with warnings denied, formatting and diff checks pass. No retained verification evidence was changed. Change-Id: I60954450853faf4fc55242811d147f4649a887f2 --- .../src/sv/cases/hierarchy.vtest | 46 +++++++++++++++++++ .../frontends/systemverilog/hierarchy.rs | 8 ++++ 2 files changed, 54 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 9349c2ffe17..b9e4bb1b180 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -512,3 +512,49 @@ (top Top) (assert_eq added 256) (assert_eq negated 65535)) + +(case bits_query_parameter_overrides + ; IEEE 1800-2023 20.6.2: fixed-size type and variable queries are constants. + (source "bits_parameter_overrides.sv" #" + module Sub #(parameter int W = 1)(output int y); assign y = W; endmodule + module Top(output int type_bits, variable_bits, combined_bits); + typedef logic [3:0] nibble_t; + logic [11:0] value; + Sub #(.W($bits(nibble_t))) type_instance(.y(type_bits)); + Sub #($bits(value)) variable_instance(.y(variable_bits)); + Sub #(.W($bits(nibble_t) + $bits(value))) combined_instance(.y(combined_bits)); + endmodule + "#) + (top Top) + (eval) + (assert_eq type_bits 4) + (assert_eq variable_bits 12) + (assert_eq combined_bits 16)) + +(case bits_query_parameter_overrides_follow_caller_specialization + (source "specialized_bits_parameter_overrides.sv" #" + package Types; typedef logic [8:0] word_t; endpackage + module Sub #(parameter int W = 1)(output int y); assign y = W; endmodule + module Caller #(parameter int N = 2)(output int variable_bits, type_bits, array_bits); + import Types::*; + logic [N-1:0] value; + logic [N-1:0] memory [3]; + typedef logic [N:0] local_t; + Sub #(.W($bits(value))) variable_instance(.y(variable_bits)); + Sub #(.W($bits(local_t) + $bits(word_t))) type_instance(.y(type_bits)); + Sub #(.W($bits(memory))) array_instance(.y(array_bits)); + endmodule + module Top(output int default_var, default_type, default_array, + output int override_var, override_type, override_array); + Caller default_instance(default_var, default_type, default_array); + Caller #(.N(5)) override_instance(override_var, override_type, override_array); + endmodule + "#) + (top Top) + (eval) + (assert_eq default_var 2) + (assert_eq default_type 12) + (assert_eq default_array 6) + (assert_eq override_var 5) + (assert_eq override_type 15) + (assert_eq override_array 15)) diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 1c98894e89e..da8731c3e55 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,14 @@ use super::*; sv_backends! { + fn bits_query_parameter_overrides_follow_caller_specialization(sim) { + @case "hierarchy::bits_query_parameter_overrides_follow_caller_specialization"; + } + + fn bits_query_parameter_overrides(sim) { + @case "hierarchy::bits_query_parameter_overrides"; + } + fn parameter_patterns_keep_original_declarations_and_isolated_bindings(sim) { @case "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings"; } fn parameter_patterns_preserve_enclosing_expressions(sim) { @case "hierarchy::parameter_patterns_preserve_enclosing_expressions"; } fn widens_small_parameters_preserving_four_state_bits(sim) { From 5e0f7db62955df83ad87f026788f571617b82ef9 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 22:55:11 +0900 Subject: [PATCH 2/4] fix(runtime): recheck abort after parallel dependency waits A dependent task could observe a failed producer's progress and leave its wait loop without observing the abort flag. This intermittently ran work after a failed dependency and caused the merge queue checks for #1599 to fail. Reload abort with acquire ordering before executing a task, after acquiring its dependencies' progress. Extend the failure/recovery regression to 2,000 epochs each with zero and default idle spin, preserving the assertions that dependents never execute and the pool remains reusable. Validation: - Reproduced the original failure locally on iteration 303 before the fix. - cargo test --locked -p celox-runtime --lib: 42 passed. - cargo test --locked -p celox --test comb_observer --test runtime_api --test flip_flop: 2,022 passed, 44 existing ignores; includes native and Cranelift parallel variants. - cargo fmt --all -- --check - cargo clippy --locked -p celox-runtime --all-targets -- -D warnings - git diff --check Change-Id: I7f373d7051fe16a8fc59ba4a4e41e366d04988c7 --- crates/celox-runtime/src/parallel.rs | 37 +++++++++++++++++----------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/crates/celox-runtime/src/parallel.rs b/crates/celox-runtime/src/parallel.rs index fe2e149e72b..4ad73c09237 100644 --- a/crates/celox-runtime/src/parallel.rs +++ b/crates/celox-runtime/src/parallel.rs @@ -266,7 +266,10 @@ impl Shared { timing.waits.push((other, completed, start, trace.nanos())); } } - if !aborted { + // A failed producer publishes its abort before its progress. The + // acquire above may satisfy the wait without entering the loop, + // so reload abort after observing that progress. + if !aborted && !self.abort.0.load(Ordering::Acquire) { if let (Some(trace), Some(timing)) = (trace, &mut timing) { timing.start = trace.nanos(); } @@ -640,19 +643,25 @@ mod tests { #[test] fn failures_skip_pending_work_and_report_the_first_task() { let (schedule, predecessors) = chain_schedule(); - let mut pool = LanePool::new(3).unwrap(); - let runner = recorder(predecessors.clone(), Some(0)); - assert_eq!( - pool.run(&schedule, &runner), - Err(LaneTaskFailure { task: 0, code: 7 }) - ); - // Dependents of the failed task never ran. - assert!(!runner.done[1].load(Ordering::Acquire)); - assert!(!runner.done[3].load(Ordering::Acquire)); - // The pool remains usable after a failure. - let runner = recorder(predecessors, None); - pool.run(&schedule, &runner).unwrap(); - assert_eq!(runner.calls.load(Ordering::Relaxed), 4); + for idle_spin in [Duration::ZERO, LanePool::DEFAULT_IDLE_SPIN] { + let mut pool = LanePool::with_idle_spin(3, idle_spin).unwrap(); + // Exercise both parked and spinning workers across failure/recovery + // epochs: a dependent can observe progress just as abort is set. + for _ in 0..2000 { + let runner = recorder(predecessors.clone(), Some(0)); + assert_eq!( + pool.run(&schedule, &runner), + Err(LaneTaskFailure { task: 0, code: 7 }) + ); + // Dependents of the failed task never ran. + assert!(!runner.done[1].load(Ordering::Acquire)); + assert!(!runner.done[3].load(Ordering::Acquire)); + // The pool remains usable after a failure. + let runner = recorder(predecessors.clone(), None); + pool.run(&schedule, &runner).unwrap(); + assert_eq!(runner.calls.load(Ordering::Relaxed), 4); + } + } } #[test] From 2a8b48385854a10251a15807103354048efe6122 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 23:22:32 +0900 Subject: [PATCH 3/4] fix(bench): enable parallel execution in the Heliodor tiered runner Pass HELIODOR_CELOX_THREADS (default: nproc) to celox-tiered on AArch64 and x86-64. Previously only celox-parallel received --threads, so tiered measurements always used the default single simulation thread. The compiled tier can now use the existing parallel native kernels; HELIODOR_CELOX_THREADS=1 retains the previous configuration. Reject invalid tiered thread counts before preparation and invalidate successful multi-threaded results whose logs do not record the requested count. Document the configuration and the difference from historical single-threaded tiered measurements. Validation: - Bash syntax checks and Heliodor result/gate fixture suites passed. - 22 suite, workflow, and publication Node tests passed. - Regression fixtures cover ARM/QEMU argument forwarding, missing/wrong thread markers, the single-thread override, and invalid thread counts. - git diff --check passed. ARM hardware performance measurements and full Linux boot benchmarks were not run; this changes runner configuration, not backend code. Change-Id: I3e9e1831b9914e4a55a10ffd4bc935be1cb561b6 --- docs/benchmarks/heliodor.md | 7 ++++ docs/ja/benchmarks/heliodor.md | 6 +++ scripts/heliodor-suite.mjs | 4 +- scripts/run-heliodor-bench.sh | 15 ++++++-- scripts/tests/run-heliodor-bench-results.sh | 41 +++++++++++++++++++-- 5 files changed, 64 insertions(+), 9 deletions(-) diff --git a/docs/benchmarks/heliodor.md b/docs/benchmarks/heliodor.md index b96eb9fb0c8..2b1fdb2663a 100644 --- a/docs/benchmarks/heliodor.md +++ b/docs/benchmarks/heliodor.md @@ -161,6 +161,13 @@ host vCPU (`HELIODOR_CELOX_THREADS`, default `nproc`). Its own job keeps the comparison groups' time budgets unchanged. The dashboard shows it as "multi-threaded" next to single-threaded native execution. +`celox-tiered` also uses `HELIODOR_CELOX_THREADS` on both AArch64 and x86-64. +It starts on the interpreter and adopts native kernels with parallel execution +enabled once compilation finishes. The scheduler can keep sequential kernels +when parallel execution is not worthwhile. Set `HELIODOR_CELOX_THREADS=1` for +the previous single-threaded tiered configuration. Earlier tiered measurements +used one simulation thread; account for this when comparing historical timings. + Recent complete eight-hart runs total 10–13 hours on x86-64 and 17–18 hours on AArch64. AArch64 four-hart runs total 5–7 hours, so splitting them into equivalent execution modes preserves useful same-CPU comparisons with time for builds. diff --git a/docs/ja/benchmarks/heliodor.md b/docs/ja/benchmarks/heliodor.md index b8af813d6be..88337d3efd7 100644 --- a/docs/ja/benchmarks/heliodor.md +++ b/docs/ja/benchmarks/heliodor.md @@ -148,6 +148,12 @@ Linux バージョンはシミュレーション内で起動するゲストの 別ジョブにすることで、比較グループの実行時間の上限は変わりません。ダッシュボードでは シングルスレッドの native 実行と並べて「multi-threaded」として表示します。 +`celox-tiered` も AArch64・x86-64 の両方で `HELIODOR_CELOX_THREADS` を使います。 +インタープリターで実行を始め、コンパイル完了後に並列実行を有効にした native カーネルへ移行します。 +並列化の効果が小さい処理には、スケジューラーが逐次カーネルを選ぶことがあります。 +従来のシングルスレッド設定で測定する場合は `HELIODOR_CELOX_THREADS=1` を指定してください。 +過去の tiered 計測はシミュレーションを1スレッドで実行していたため、履歴との比較ではこの違いに注意してください。 + 直近の完走結果では、8 hart の合計は x86-64 で 10〜13 時間、AArch64 で 17〜18 時間です。 AArch64 の 4 hart も合計 5〜7 時間なので、同じ実行方式のペアに分け、ビルド時間を確保しつつ Celox と Veryl-CC を同じ CPU で比較します。別グループ間では同じ CPU を保証しません。 diff --git a/scripts/heliodor-suite.mjs b/scripts/heliodor-suite.mjs index 9dde905494b..4c8ddcc5e9f 100644 --- a/scripts/heliodor-suite.mjs +++ b/scripts/heliodor-suite.mjs @@ -18,8 +18,8 @@ export const workloads = [ "test_soc_71v_linux_boot", ]; export const runners = ["veryl-cc-sync", "celox", "celox-tiered", "veryl-cc-tiered"]; -// Multi-threaded Celox runs only on SMP workloads, in its own group so the -// existing comparison groups keep their time budgets. +// The synchronous multi-threaded Celox runner runs only on SMP workloads, +// in its own group so the existing comparison groups keep their time budgets. export const parallelRunner = "celox-parallel"; export const allRunners = [...runners, parallelRunner]; const isSmp = test => /_smp_linux_boot_\d+hart$/.test(test); diff --git a/scripts/run-heliodor-bench.sh b/scripts/run-heliodor-bench.sh index e4f65f1426f..342c8717639 100755 --- a/scripts/run-heliodor-bench.sh +++ b/scripts/run-heliodor-bench.sh @@ -119,7 +119,7 @@ Environment: HELIODOR_CELOX_TIMEOUT_MULTIPLIER timeout Celox after N times the fastest successful Veryl baseline HELIODOR_CELOX_THREADS - simulation threads of the celox-parallel runner (default: nproc) + simulation threads of celox-parallel and celox-tiered (default: nproc) CELOX_OPT_LEVEL O0, O1, or O2 for the Celox runner (default: O2) CELOX_SIR_PASS_OVERRIDES space-separated SIR pass overrides, e.g. "-vectorize_concat +gvn" @@ -1580,7 +1580,8 @@ run_one() { run_in_heliodor "$timeout_sec" "$log" \ "${celox_execution_command[@]}" \ --project "$HELIODOR_DIR" --test "$test" \ - "${celox_args[@]}" --backend tiered --opt-level "${CELOX_OPT_LEVEL,,}" + "${celox_args[@]}" --backend tiered --opt-level "${CELOX_OPT_LEVEL,,}" \ + --threads "$HELIODOR_CELOX_THREADS" process_status="$?" ;; celox-interpreter) @@ -1658,9 +1659,10 @@ run_one() { result_valid=0 echo "error: $CELOX_RESULT_DIAGNOSTIC" >&2 fi - if [[ "$runner" == celox-parallel && "$semantic_status" == pass ]] \ + if [[ ( "$runner" == celox-parallel || "$runner" == celox-tiered ) \ + && "$HELIODOR_CELOX_THREADS" -gt 1 && "$semantic_status" == pass ]] \ && ! grep -Fxq "CELOX_TEST_THREADS test=$test threads=$HELIODOR_CELOX_THREADS" "$log"; then - echo "error: celox-parallel log does not record $HELIODOR_CELOX_THREADS threads" >&2 + echo "error: $runner log does not record $HELIODOR_CELOX_THREADS threads" >&2 semantic_status=invalid result_valid=0 fi @@ -1733,6 +1735,11 @@ publish_result() { run_all() { validate_compile_only_runners || return "$?" validate_native_image_mode || return "$?" + if runner_enabled celox-tiered \ + && { ! is_uint "$HELIODOR_CELOX_THREADS" || ((HELIODOR_CELOX_THREADS < 1)); }; then + echo "error: HELIODOR_CELOX_THREADS must be at least 1 for celox-tiered" >&2 + return 2 + fi prepare mkdir -p "$HELIODOR_RESULTS_DIR" ensure_results_schema "$HELIODOR_RESULTS_DIR/results.tsv" || return "$?" diff --git a/scripts/tests/run-heliodor-bench-results.sh b/scripts/tests/run-heliodor-bench-results.sh index 14847b62078..66a5409ffd5 100644 --- a/scripts/tests/run-heliodor-bench-results.sh +++ b/scripts/tests/run-heliodor-bench-results.sh @@ -360,6 +360,7 @@ run_in_heliodor() { ensure_results_schema "$integration_results/results.tsv" HELIODOR_COMPILE_ONLY=0 CELOX_OPT_LEVEL=O2 +HELIODOR_CELOX_THREADS=4 HELIODOR_CELOX_BUILD_CACHE_DIR="$TMP/build-cache" CELOX_SIR_PASS_OVERRIDES="-branchify_mux +gvn" FIXTURE_RESULT_LINE=$'CELOX_TEST_TIMING test=integration_pass compile_ns=20 execute_ns=30 jit_execute_ns=25\nCELOX_TEST_RESULT test=integration_pass status=pass elapsed_ns=71' @@ -462,11 +463,13 @@ assert_eq "$(awk -F '\t' 'NR == 8 { print $10 }' "$integration_results/results.t assert_eq "$(awk -F '\t' 'NR == 8 { print $11 }' "$integration_results/results.tsv")" NA \ "run_one Veryl CLI execute elapsed" -FIXTURE_RESULT_LINE=$'CELOX_TEST_TIMING test=integration_tiered compile_ns=12 execute_ns=34 jit_execute_ns=NA\nCELOX_TIERED_STATS test=integration_tiered tier=compiled promotion=promoted interpreted_evaluations=10 compiled_evaluations=20 promoted_after_interpreted_evaluations=10 promotion_elapsed_ns=15 safe_point_polls=11 split_apply_deferrals=0 threshold_deferrals=0\nCELOX_TEST_RESULT test=integration_tiered status=pass elapsed_ns=48' +FIXTURE_RESULT_LINE=$'CELOX_TEST_THREADS test=integration_tiered threads=4\nCELOX_TEST_TIMING test=integration_tiered compile_ns=12 execute_ns=34 jit_execute_ns=NA\nCELOX_TIERED_STATS test=integration_tiered tier=compiled promotion=promoted interpreted_evaluations=10 compiled_evaluations=20 promoted_after_interpreted_evaluations=10 promotion_elapsed_ns=15 safe_point_polls=11 split_apply_deferrals=0 threshold_deferrals=0\nCELOX_TEST_RESULT test=integration_tiered status=pass elapsed_ns=48' run_one celox-tiered integration_tiered >/dev/null \ || fail "run_one rejected a fixture tiered pass" [[ " ${FIXTURE_RUN_ARGS[*]} " == *" --backend tiered "* ]] \ || fail "tiered runner did not select the tiered backend" +[[ " ${FIXTURE_RUN_ARGS[*]} " == *" --threads 4 "* ]] \ + || fail "tiered runner did not request parallel execution" assert_eq "$(awk -F '\t' 'NR == 9 { print $1 }' "$integration_results/results.tsv")" \ celox-tiered "run_one tiered runner name" assert_eq "$(awk -F '\t' 'NR == 9 { print $12 }' "$integration_results/results.tsv")" NA \ @@ -486,13 +489,15 @@ assert_eq "$(awk -F '\t' 'NR == 10 { print $1 }' "$integration_results/results.t # host-qemu mode. Native host codegen is handled separately by run_one. HELIODOR_CELOX_NATIVE_IMAGE_MODE=host-qemu CELOX_EXECUTION_PREFIX=(qemu-aarch64 -L /fixture-sysroot) -FIXTURE_RESULT_LINE=$'CELOX_TEST_TIMING test=integration_qemu_tiered compile_ns=12 execute_ns=34 jit_execute_ns=NA\nCELOX_TIERED_STATS test=integration_qemu_tiered tier=compiled promotion=promoted interpreted_evaluations=10 compiled_evaluations=20 promoted_after_interpreted_evaluations=10 promotion_elapsed_ns=15 safe_point_polls=11 split_apply_deferrals=0 threshold_deferrals=0\nCELOX_TEST_RESULT test=integration_qemu_tiered status=pass elapsed_ns=48' +FIXTURE_RESULT_LINE=$'CELOX_TEST_THREADS test=integration_qemu_tiered threads=4\nCELOX_TEST_TIMING test=integration_qemu_tiered compile_ns=12 execute_ns=34 jit_execute_ns=NA\nCELOX_TIERED_STATS test=integration_qemu_tiered tier=compiled promotion=promoted interpreted_evaluations=10 compiled_evaluations=20 promoted_after_interpreted_evaluations=10 promotion_elapsed_ns=15 safe_point_polls=11 split_apply_deferrals=0 threshold_deferrals=0\nCELOX_TEST_RESULT test=integration_qemu_tiered status=pass elapsed_ns=48' run_one celox-tiered integration_qemu_tiered >/dev/null \ || fail "run_one rejected a host-qemu tiered fixture" assert_eq "${FIXTURE_RUN_ARGS[0]}" qemu-aarch64 "tiered execution prefix command" assert_eq "${FIXTURE_RUN_ARGS[1]}" -L "tiered execution prefix option" assert_eq "${FIXTURE_RUN_ARGS[2]}" /fixture-sysroot "tiered execution prefix argument" assert_eq "${FIXTURE_RUN_ARGS[3]}" "$CELOX_RUNNER_BIN" "tiered target runner" +[[ " ${FIXTURE_RUN_ARGS[*]} " == *" --threads 4 "* ]] \ + || fail "ARM tiered runner did not request parallel execution" FIXTURE_RESULT_LINE=$'CELOX_TEST_TIMING test=integration_qemu_interpreter compile_ns=8 execute_ns=55 jit_execute_ns=NA\nCELOX_TEST_RESULT test=integration_qemu_interpreter status=pass elapsed_ns=65' run_one celox-interpreter integration_qemu_interpreter >/dev/null \ @@ -502,6 +507,36 @@ assert_eq "${FIXTURE_RUN_ARGS[3]}" "$CELOX_RUNNER_BIN" "interpreter target runne HELIODOR_CELOX_NATIVE_IMAGE_MODE=off CELOX_EXECUTION_PREFIX=() +# A successful result without the requested thread count cannot be published. +FIXTURE_RESULT_LINE=$'CELOX_TEST_TIMING test=tiered_threads compile_ns=12 execute_ns=34 jit_execute_ns=NA\nCELOX_TEST_RESULT test=tiered_threads status=pass elapsed_ns=48' +for marker in "" "CELOX_TEST_THREADS test=tiered_threads threads=2"; do + ( + FIXTURE_RESULT_LINE="$marker"$'\n'"$FIXTURE_RESULT_LINE" + if run_one celox-tiered tiered_threads >/dev/null 2>&1; then + fail "tiered accepted a missing or incorrect thread count" + fi + assert_eq "$(tail -n 1 "$integration_results/results.tsv" | cut -f 6)" invalid \ + "tiered thread mismatch must invalidate the result" + ) +done +( + HELIODOR_CELOX_THREADS=1 + run_one celox-tiered tiered_threads >/dev/null \ + || fail "tiered rejected explicit sequential execution" + [[ " ${FIXTURE_RUN_ARGS[*]} " == *" --threads 1 "* ]] \ + || fail "tiered did not honor the sequential override" +) +for invalid_threads in 0 -1 invalid; do + ( + HELIODOR_RUNNERS=celox-tiered + HELIODOR_CELOX_THREADS="$invalid_threads" + prepare() { fail "invalid thread count reached benchmark preparation"; } + status=0 + run_all >/dev/null 2>&1 || status=$? + assert_eq "$status" 2 "invalid tiered thread count" + ) +done + previous_cache="$FIXTURE_AOT_CACHE_DIR" FIXTURE_RESULT_LINE=$'VERYL_TEST_CONFIG test=integration_veryl_tiered backend=cc aot_c_async=true compile_only=false\nVERYL_TEST_TIMING test=integration_veryl_tiered compile_ns=8 execute_ns=50\nVERYL_TIERED_STATS test=integration_veryl_tiered compiled_dispatches=100 fallback_dispatches=200\nVERYL_TEST_RESULT test=integration_veryl_tiered status=pass elapsed_ns=59' run_one veryl-cc-tiered integration_veryl_tiered >/dev/null \ @@ -552,7 +587,7 @@ fi HELIODOR_PUBLISH_ARCH=x86_64 HELIODOR_COMPILE_ONLY=0 HELIODOR_CELOX_NATIVE_IMAGE_MODE=off - FIXTURE_RESULT_LINE=$'CELOX_TEST_TIMING test=publish_tiered compile_ns=12 execute_ns=34 jit_execute_ns=NA\nCELOX_TIERED_STATS test=publish_tiered tier=compiled promotion=promoted interpreted_evaluations=10 compiled_evaluations=20 promoted_after_interpreted_evaluations=10 promotion_elapsed_ns=15 safe_point_polls=11 split_apply_deferrals=0 threshold_deferrals=0\nCELOX_TEST_RESULT test=publish_tiered status=pass elapsed_ns=48' + FIXTURE_RESULT_LINE=$'CELOX_TEST_THREADS test=publish_tiered threads=4\nCELOX_TEST_TIMING test=publish_tiered compile_ns=12 execute_ns=34 jit_execute_ns=NA\nCELOX_TIERED_STATS test=publish_tiered tier=compiled promotion=promoted interpreted_evaluations=10 compiled_evaluations=20 promoted_after_interpreted_evaluations=10 promotion_elapsed_ns=15 safe_point_polls=11 split_apply_deferrals=0 threshold_deferrals=0\nCELOX_TEST_RESULT test=publish_tiered status=pass elapsed_ns=48' run_one celox-tiered publish_tiered >/dev/null \ || fail "publishing rejected a completed tiered run" FIXTURE_RESULT_LINE="${FIXTURE_RESULT_LINE/compiled_evaluations=20/compiled_evaluations=0}" From c0273d94e9ac454bd19c622292bc6c94c293fb06 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 19:03:16 +0900 Subject: [PATCH 4/4] fix(vite): resolve cached Veryl imports inside and outside the root Vitest's persistent cache replays imports as Vite root-relative URLs or /@fs/ URLs for sources outside the Vite root. Resolve both forms to their canonical source, project and watch IDs so warm runs load generated JavaScript instead of raw Veryl. Prefer the Vite-root candidate for cached URLs outside the project's absolute namespace even if an unrelated host path exists. A matching project prefix only preserves an absolute identity when that file exists; otherwise try the Vite-root candidate too. Preserve canonical absolute project IDs and explicit /@fs/ identities, virtual-module ownership and optional watch-file behavior. Add real-file collision, prefix-shaped URL (including projectRoot=/) and source/query resolution regressions. Run the injected component fixture cold and warm in both internal and external project layouts. Normalize the fixture's absolute test include path to forward slashes so Vitest also discovers the test on Windows. Validation: - External /@fs/ and colliding-host regressions reproduce before their fixes. Both prefix-shaped URL regressions also fail on the previous head. - Vite package tests: 132 passed; cold/warm fixtures pass in both layouts (8 assertions). - Dependency, source/client-build, build-watch and component-watch checks pass. - TypeScript build, plugin/playground type checks, plugin Biome and diff checks pass. - NAPI rebuilt from unmodified master Rust sources independently of the struct fix. Windows fixture follow-up validation: - Rebuilt NAPI and JS packages; reran the Vite package tests and fixture end-to-end checks on Linux. - Explicit fixture-config TypeScript check and Biome formatting/lint output check pass. - Windows execution remains to be verified by CI. Change-Id: I7613c2a332df5a43a7aac5b09e73207f05bc269d --- packages/playground/package.json | 2 +- .../injected-components/cache-e2e.mjs | 50 ++++++ .../injected-components/vitest.config.ts | 11 +- .../playground/test/vite-plugin-watch.test.ts | 148 +++++++++++++++++- packages/vite-plugin/src/index.ts | 31 ++-- 5 files changed, 227 insertions(+), 15 deletions(-) create mode 100644 packages/playground/test/fixtures/injected-components/cache-e2e.mjs diff --git a/packages/playground/package.json b/packages/playground/package.json index 3f8035c9154..74f2cbca4d3 100644 --- a/packages/playground/package.json +++ b/packages/playground/package.json @@ -9,7 +9,7 @@ "preview": "vite preview", "test": "vitest run", "typecheck": "node test/generate-sidecars.mjs && tsc -p .", - "test:vite-components": "vitest run test/vite-plugin-cache.test.ts test/generated-dts.test.ts test/vite-assertion-bytes.test.ts test/vite-plugin-cache-real.test.ts test/vite-plugin-watch.test.ts test/sidecar-orphans.test.ts test/sidecar-lock.test.ts && vitest run --config test/fixtures/injected-components/vitest.config.ts && node test/fixtures/injected-components/dependency-e2e.mjs && node test/fixtures/source-watch/watch-e2e.mjs && node test/fixtures/source-watch/build-watch-e2e.mjs && node test/fixtures/source-watch/component-watch-e2e.mjs", + "test:vite-components": "vitest run test/vite-plugin-cache.test.ts test/generated-dts.test.ts test/vite-assertion-bytes.test.ts test/vite-plugin-cache-real.test.ts test/vite-plugin-watch.test.ts test/sidecar-orphans.test.ts test/sidecar-lock.test.ts && node test/fixtures/injected-components/cache-e2e.mjs && node test/fixtures/injected-components/dependency-e2e.mjs && node test/fixtures/source-watch/watch-e2e.mjs && node test/fixtures/source-watch/build-watch-e2e.mjs && node test/fixtures/source-watch/component-watch-e2e.mjs", "test:lsp-components": "pnpm run test:vite-components && node test/fixtures/injected-components/lsp-e2e.mjs", "test:e2e": "pnpm run build && playwright test", "test:watch": "vitest", diff --git a/packages/playground/test/fixtures/injected-components/cache-e2e.mjs b/packages/playground/test/fixtures/injected-components/cache-e2e.mjs new file mode 100644 index 00000000000..e842763f1a8 --- /dev/null +++ b/packages/playground/test/fixtures/injected-components/cache-e2e.mjs @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const vitest = join( + dirname(fileURLToPath(import.meta.resolve("vitest/package.json"))), + "vitest.mjs", +); +for (const layout of ["internal", "external"]) { + const cache = mkdtempSync(join(tmpdir(), "celox-vitest-cache-")); + const client = + layout === "external" + ? mkdtempSync(join(import.meta.dirname, ".cache-client-")) + : undefined; + try { + for (const phase of ["cold", "warm"]) { + const result = spawnSync( + process.execPath, + [ + vitest, + "run", + "--config", + join(import.meta.dirname, "vitest.config.ts"), + "--fsModuleCachePath", + cache, + ], + { + cwd: import.meta.dirname, + env: { ...process.env, CELOX_TEST_EXTERNAL_VITE_ROOT: client ?? "" }, + encoding: "utf8", + timeout: 120_000, + }, + ); + process.stdout.write(result.stdout ?? ""); + process.stderr.write(result.stderr ?? ""); + assert.ifError(result.error); + assert.equal( + result.status, + 0, + `${layout} ${phase} module-cache run failed`, + ); + } + } finally { + rmSync(cache, { recursive: true, force: true }); + if (client) rmSync(client, { recursive: true, force: true }); + } +} diff --git a/packages/playground/test/fixtures/injected-components/vitest.config.ts b/packages/playground/test/fixtures/injected-components/vitest.config.ts index bc89ddd9b39..2fbd5bfe1b5 100644 --- a/packages/playground/test/fixtures/injected-components/vitest.config.ts +++ b/packages/playground/test/fixtures/injected-components/vitest.config.ts @@ -1,6 +1,6 @@ -import celox from "@celox-sim/vite-plugin"; import { resolve } from "node:path"; -import type { Plugin } from "vite"; +import celox from "@celox-sim/vite-plugin"; +import { normalizePath, type Plugin } from "vite"; import { defineConfig } from "vitest/config"; const virtualTbStep: Plugin = { @@ -14,7 +14,7 @@ const virtualTbStep: Plugin = { }; export default defineConfig({ - root: import.meta.dirname, + root: process.env.CELOX_TEST_EXTERNAL_VITE_ROOT || import.meta.dirname, resolve: { alias: { "@fixture/tb-helper": resolve( @@ -26,8 +26,11 @@ export default defineConfig({ plugins: [ virtualTbStep, celox({ + projectRoot: import.meta.dirname, testbenchComponents: "./tb-components.ts", }), ], - test: { include: ["entry.test.ts"] }, + test: { + include: [normalizePath(resolve(import.meta.dirname, "entry.test.ts"))], + }, }); diff --git a/packages/playground/test/vite-plugin-watch.test.ts b/packages/playground/test/vite-plugin-watch.test.ts index e7763c6de41..642f863615c 100644 --- a/packages/playground/test/vite-plugin-watch.test.ts +++ b/packages/playground/test/vite-plugin-watch.test.ts @@ -1,5 +1,11 @@ import { EventEmitter } from "node:events"; -import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + rmSync, + utimesSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { normalizePath } from "vite"; @@ -1045,3 +1051,143 @@ test.each([true, false])( expect(watcher.add).not.toHaveBeenCalled(); }, ); + +// Vitest's persistent module cache replays imports as URLs rooted at Vite's +// root, rather than their original paths relative to the importer. +test("cached root-relative imports retain their generated module identity", async () => { + const root = mkdtempSync(join(tmpdir(), "celox-cached-import-")); + roots.push(root); + mkdirSync(join(root, "src")); + writeFileSync(join(root, "src", "Main.veryl"), "module Main {}\n"); + writeFileSync(join(root, "Veryl.toml"), "[project]\nname = 'test'\n"); + const { plugin, context } = await initialize(root); + for (const [url, file] of [ + ["/src/Main.veryl", join(root, "src", "Main.veryl")], + [ + "/src/Main.veryl?dse=preserveAllPorts", + `${join(root, "src", "Main.veryl")}?dse=preserveAllPorts`, + ], + ["/Veryl.toml?celox-project", `${join(root, "Veryl.toml")}?celox-project`], + [ + "/src/Main.veryl?celox-watch", + `${join(root, "src", "Main.veryl")}?celox-watch`, + ], + ]) { + const id = (plugin.resolveId as Function)(url, join(root, "index.html")); + expect(id).toBe(normalizePath(file!)); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + expect((plugin.resolveId as Function)("/missing.veryl")).toBeUndefined(); +}); + +// A project outside Vite's root is replayed through the /@fs/ URL namespace. +test("cached external project imports retain their generated module identity", async () => { + const root = mkdtempSync(join(tmpdir(), "celox-external-cache-")); + const client = mkdtempSync(join(tmpdir(), "celox-external-client-")); + roots.push(root, client); + writeFileSync(join(root, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(root, "Veryl.toml"), "[project]\nname = 'test'\n"); + const plugin = celox({ projectRoot: root }); + const context = { addWatchFile: vi.fn(), warn: vi.fn() }; + await (plugin.configResolved as Function)({ root: client }); + await (plugin.buildStart as Function).call(context); + for (const query of ["", "?dse=preserveAllPorts", "?celox-watch"]) { + const file = normalizePath(join(root, "Main.veryl")) + query; + const id = (plugin.resolveId as Function)( + `/@fs/${file.replace(/^\//, "")}`, + join(client, "index.html"), + ); + expect(id).toBe(file); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + const project = `${normalizePath(join(root, "Veryl.toml"))}?celox-project`; + const id = (plugin.resolveId as Function)( + `/@fs/${project.replace(/^\//, "")}`, + ); + expect(id).toBe(project); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); +}); + +// Both the host-absolute and Vite-root-relative paths exist. Their existence +// alone must not let an unrelated host file take over a cached project URL. +test("cached URLs prefer the project over colliding host paths", async () => { + const client = mkdtempSync(join(tmpdir(), "celox-collision-client-")); + const host = mkdtempSync(join(tmpdir(), "celox-collision-host-")); + roots.push(client, host); + const urlRoot = normalizePath(host).replace(/^[A-Z]:/i, ""); + const project = join(client, urlRoot.replace(/^\//, "")); + mkdirSync(project, { recursive: true }); + for (const dir of [host, project]) { + writeFileSync(join(dir, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(dir, "Veryl.toml"), "[project]\nname = 'test'\n"); + } + const plugin = celox({ projectRoot: project }); + const context = { addWatchFile: vi.fn(), warn: vi.fn() }; + await (plugin.configResolved as Function)({ root: client }); + await (plugin.buildStart as Function).call(context); + for (const [name, query] of [ + ["Main.veryl", ""], + ["Main.veryl", "?dse=preserveAllPorts"], + ["Main.veryl", "?celox-watch"], + ["Veryl.toml", "?celox-project"], + ]) { + const file = normalizePath(join(project, name!)) + query; + const url = `${urlRoot}/${name}${query}`; + const id = (plugin.resolveId as Function)(url, join(client, "index.html")); + expect(id).toBe(file); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + + // Canonical absolute project IDs must stay stable even if their root-relative + // lookalikes also exist. Explicit /@fs/ URLs retain their absolute meaning. + const mirror = join( + client, + normalizePath(project) + .replace(/^[A-Z]:/i, "") + .replace(/^\//, ""), + ); + mkdirSync(mirror, { recursive: true }); + writeFileSync(join(mirror, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(mirror, "Veryl.toml"), "[project]\nname = 'other'\n"); + for (const name of ["Main.veryl", "Veryl.toml?celox-project"]) { + const file = normalizePath(join(project, name)); + expect((plugin.resolveId as Function)(file)).toBe(file); + } + const hostFile = normalizePath(join(host, "Main.veryl")); + expect( + (plugin.resolveId as Function)(`/@fs/${hostFile.replace(/^\//, "")}`), + ).toBe(hostFile); +}); + +test.each([false, true])( + "cached prefix-shaped URLs fall back to the Vite root (filesystem root=%s)", + async (filesystemRoot) => { + const project = mkdtempSync(join(tmpdir(), "celox-prefix-project-")); + roots.push(project); + const client = join(project, "client"); + const url = filesystemRoot + ? `/celox-prefix-${project.split(/[\\/]/).at(-1)}/Main.veryl` + : normalizePath(join(project, "Main.veryl")).replace(/^[A-Z]:/i, ""); + const rooted = join(client, url.replace(/^[A-Z]:/i, "").replace(/^\//, "")); + mkdirSync(dirname(rooted), { recursive: true }); + writeFileSync(rooted, "module Main {}\n"); + const plugin = celox({ projectRoot: filesystemRoot ? "/" : project }); + // Resolution does not need buildStart; do not generate sidecars at '/'. + await (plugin.configResolved as Function)({ root: client }); + for (const query of ["", "?dse=preserveAllPorts", "?celox-watch"]) { + expect((plugin.resolveId as Function)(url + query)).toBe( + normalizePath(rooted) + query, + ); + } + expect( + (plugin.resolveId as Function)(`/@fs/${url.replace(/^\//, "")}`), + ).toBeUndefined(); + if (!filesystemRoot) { + // Once the canonical project file exists, keep that identity even though + // the cached-root lookalike exists too. + writeFileSync(join(project, "Main.veryl"), "module Main {}\n"); + const canonical = normalizePath(join(project, "Main.veryl")); + expect((plugin.resolveId as Function)(canonical)).toBe(canonical); + } + }, +); diff --git a/packages/vite-plugin/src/index.ts b/packages/vite-plugin/src/index.ts index ad26a777148..793e66b885c 100644 --- a/packages/vite-plugin/src/index.ts +++ b/packages/vite-plugin/src/index.ts @@ -411,16 +411,29 @@ export default function celoxPlugin(options?: CeloxPluginOptions): Plugin { // Split off query string (e.g. "?dse=preserveAllPorts") const [rawPath, queryStr] = source.split("?", 2); if (source.startsWith("\0")) return; - if (queryStr === PROJECT_QUERY || queryStr === WATCH_QUERY) { - const id = normalizePath(source); - resolvedIds.add(id); - return id; - } - if (!rawPath!.endsWith(".veryl")) return; + const generatedQuery = + queryStr === PROJECT_QUERY || queryStr === WATCH_QUERY; + if (!generatedQuery && !rawPath!.endsWith(".veryl")) return; // Resolve to absolute path let absPath: string; - if (isAbsolute(rawPath!)) { + if (rawPath!.startsWith("/@fs/")) { + // Vite uses /@fs/ for files outside its root. Keep POSIX roots + // and Windows drive letters when decoding that URL namespace. + const file = normalizePath(rawPath!.slice("/@fs/".length)); + absPath = + file.startsWith("/") || /^[A-Z]:/i.test(file) ? file : `/${file}`; + } else if ( + rawPath!.startsWith("/") && + (!normalizePath(rawPath!).startsWith(projectPrefix) || + !existsSync(rawPath!)) + ) { + // Keep existing canonical project files, but a matching prefix alone + // does not make a cached URL absolute. Root other URLs at Vite's + // root even when an unrelated host file exists. + const rooted = resolve(viteConfig.root, `.${rawPath}`); + absPath = existsSync(rooted) ? rooted : rawPath!; + } else if (isAbsolute(rawPath!)) { absPath = rawPath!; } else if (importer) { absPath = resolve(dirname(importer.split("?", 1)[0]!), rawPath!); @@ -430,8 +443,8 @@ export default function celoxPlugin(options?: CeloxPluginOptions): Plugin { absPath = normalizePath(absPath); - // Only handle .veryl files that exist - if (!existsSync(absPath)) return; + // Generated watch modules may refer to optional configuration files. + if (!generatedQuery && !existsSync(absPath)) return; // Preserve the real file identity so Vite/Vitest can trace changes. const id = absPath + (queryStr ? `?${queryStr}` : "");