diff --git a/.github/actions/setup-windows-code-layout/action.yml b/.github/actions/setup-windows-code-layout/action.yml new file mode 100644 index 0000000000..f1f59b369d --- /dev/null +++ b/.github/actions/setup-windows-code-layout/action.yml @@ -0,0 +1,40 @@ +name: Set up Windows native code layout toolchain +description: Install the pinned MSVC Rust host toolchain, configure MSVC build tools, and locate lld-link. +inputs: + target: + description: Native Rust target triple (x86_64-pc-windows-msvc or aarch64-pc-windows-msvc) + required: true +runs: + using: composite + steps: + - name: Select native MSVC Rust toolchain + shell: powershell + env: + DIM_LAYOUT_TARGET: ${{ inputs.target }} + run: | + $channel = python -c "import tomllib; print(tomllib.load(open('rust-toolchain.toml', 'rb'))['toolchain']['channel'])" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $toolchain = "$channel-$env:DIM_LAYOUT_TARGET" + rustup toolchain install $toolchain --profile minimal + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + "RUSTUP_TOOLCHAIN=$toolchain" >> $env:GITHUB_ENV + - name: Configure Windows C/C++ toolchain + uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 + with: + arch: ${{ runner.arch == 'ARM64' && 'arm64' || 'amd64' }} + - name: Locate lld-link + shell: powershell + run: | + $linker = Get-Command lld-link -ErrorAction SilentlyContinue + if (!$linker) { + $linker = Get-ChildItem -Recurse -Filter lld-link.exe -ErrorAction SilentlyContinue ` + -Path "$env:ProgramFiles\LLVM\bin", "$env:ProgramFiles\Microsoft Visual Studio\2022\*\VC\Tools\Llvm\*\bin" | + Select-Object -First 1 + } + if ($linker) { + $path = if ($linker -is [System.Management.Automation.ApplicationInfo]) { $linker.Source } else { $linker.FullName } + Split-Path $path >> $env:GITHUB_PATH + Write-Output "Using $path" + } else { + Write-Output 'lld-link is not on PATH; the build will use the Rust toolchain rust-lld' + } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c8bbbc7865..e690d3834c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,6 +102,7 @@ jobs: timeout-minutes: 15 env: CARGO_INCREMENTAL: "0" + CARGO_TARGET_DIR: ${{ github.workspace }}/../.dim-windows-cli-target RUSTC_WRAPPER: "" steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -111,6 +112,34 @@ jobs: uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 with: arch: amd64 + - name: Reuse bounded Windows CLI target directory + shell: powershell + env: + CACHE_STAMP: ${{ hashFiles('rust-toolchain.toml') }}-${{ env.CARGO_PROFILE_DEV_DEBUG }} + run: | + $targetDir = [System.IO.Path]::GetFullPath($env:CARGO_TARGET_DIR) + $stampFile = Join-Path $targetDir '.cache-stamp' + $maxBytes = 6GB + $reset = $false + if (Test-Path $targetDir) { + $current = if (Test-Path $stampFile) { (Get-Content -Raw $stampFile).Trim() } else { '' } + if ($current -ne $env:CACHE_STAMP) { + Write-Output 'Resetting Windows CLI target cache (toolchain or profile stamp changed).' + $reset = $true + } else { + $bytes = (Get-ChildItem -LiteralPath $targetDir -Recurse -File -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum + if ($bytes -gt $maxBytes) { + Write-Output "Resetting Windows CLI target cache ($([math]::Round($bytes / 1GB, 2)) GiB exceeded 6 GiB budget)." + $reset = $true + } + } + } + if ($reset) { + Remove-Item -LiteralPath $targetDir -Recurse -Force + } + New-Item -ItemType Directory -Path $targetDir -Force | Out-Null + Set-Content -LiteralPath $stampFile -Value $env:CACHE_STAMP -NoNewline + "CARGO_TARGET_DIR=$targetDir" >> $env:GITHUB_ENV - name: Verify native Windows CLI boundaries run: cargo test --locked -p dim-cli --lib web: @@ -198,8 +227,9 @@ jobs: run: | echo "CPUs: $(nproc)" grep -E 'MemTotal|MemAvailable' /proc/meminfo - # Without a working bubblewrap the confined process tests return without running. - bwrap --ro-bind / / true + # The confined tests create a user namespace and a private /proc, so + # check the sandbox they use instead of a plain read-only bind. + bwrap --unshare-user --unshare-pid --proc /proc --dev /dev --ro-bind / / true - name: Build and lint the Rust workspace if: needs.changes.outputs.rust == 'true' shell: bash @@ -223,10 +253,38 @@ jobs: target/debug/xtask check - name: Run compiled workspace tests if: needs.changes.outputs.rust == 'true' + shell: bash env: DIM_TEST_TIMEOUT_MS: "900000" run: | - node scripts/run-rust-test.mjs target/test-artifacts.jsonl --workspace --test-threads=3 + set -euo pipefail + if [[ "$RUNNER_OS" == Linux ]]; then + cpus=$(nproc) + # Runner hosts may share their physical cores between instances and + # report SMT siblings as CPUs; scale by the cores this job can use. + if command -v lscpu >/dev/null; then + cores=$(lscpu -p=Core,Socket | grep -v '^#' | sort -u | wc -l) + logical=$(lscpu -p=CPU | grep -vc '^#') + (( cores > 0 )) || cores=1 + smt=$(( logical / cores )) + (( smt < 1 )) && smt=1 + physical=$(( cpus / smt )) + else + physical=$cpus + fi + (( physical < 1 )) && physical=1 + test_jobs=$(( physical / 3 )) + (( test_jobs < 3 )) && test_jobs=3 + (( test_jobs > 8 )) && test_jobs=8 + test_threads=$(( physical / 4 )) + (( test_threads < 2 )) && test_threads=2 + (( test_threads > 6 )) && test_threads=6 + else + test_jobs=3 + test_threads=3 + fi + echo "Workspace tests: DIM_TEST_JOBS=$test_jobs --test-threads=$test_threads" + DIM_TEST_JOBS="$test_jobs" node scripts/run-rust-test.mjs target/test-artifacts.jsonl --workspace "--test-threads=$test_threads" cargo test --workspace --doc --locked ${{ needs.changes.outputs.eval == 'true' && '--features xtask/eval-tests' || '' }} - name: Verify wall-clock background handoff if: needs.changes.outputs.execution == 'true' @@ -253,6 +311,8 @@ jobs: # (docs/architecture/tui-e2e.md); the remaining TUI cases still run # under the ordinary selection, so this step names the production # and line-mode flows it keeps. + cli_threads=2 + if [[ "$RUNNER_OS" == Linux ]]; then cli_threads=4; fi node scripts/run-rust-test.mjs target/test-artifacts.jsonl cli_flow \ accounts::login_reaches_the_codex_account_of_the_production_daemon \ acp::acp_stdio_temporary_mcp_calls_tools_and_settles_the_child_on_eof \ @@ -266,7 +326,7 @@ jobs: project_mcp_entries_start_disabled_and_the_user_enables_them \ real_daemon_profile_conflicts_preserve_the_running_daemon_and_endpoint \ workflow::workflow_commands_write_and_enable_against_the_real_owner \ - --ignored --test-threads=2 + --ignored --test-threads="$cli_threads" - name: Verify public Node bindings if: needs.changes.outputs.node == 'true' shell: bash @@ -283,12 +343,14 @@ jobs: export DIM_TEST_NODE="$(command -v node)" export DIM_TEST_JS_RUNTIME="$PWD/runtime/node_modules/@arcships/rutis-runtime" export DIM_TEST_RUTIS_SDK="$PWD/runtime/node_modules/@arcships/rutis/src/index.mjs" - node scripts/run-rust-test.mjs target/test-artifacts.jsonl transport_flow node_ --ignored --test-threads=2 - node scripts/run-rust-test.mjs target/test-artifacts.jsonl app_server_flow mcp_http_flow::node_ --ignored --test-threads=2 - node scripts/run-rust-test.mjs target/test-artifacts.jsonl migration_flow node_ --ignored --test-threads=2 - node scripts/run-rust-test.mjs target/test-artifacts.jsonl hub_flow node_ --ignored --test-threads=2 + node_threads=2 + if [[ "$RUNNER_OS" == Linux ]]; then node_threads=4; fi + node scripts/run-rust-test.mjs target/test-artifacts.jsonl transport_flow node_ --ignored --test-threads="$node_threads" + node scripts/run-rust-test.mjs target/test-artifacts.jsonl app_server_flow mcp_http_flow::node_ --ignored --test-threads="$node_threads" + node scripts/run-rust-test.mjs target/test-artifacts.jsonl migration_flow node_ --ignored --test-threads="$node_threads" + node scripts/run-rust-test.mjs target/test-artifacts.jsonl hub_flow node_ --ignored --test-threads="$node_threads" if [[ '${{ needs.changes.outputs.eval }}' == true ]]; then - node scripts/run-rust-test.mjs target/test-artifacts.jsonl xtask node_ --ignored --test-threads=2 + node scripts/run-rust-test.mjs target/test-artifacts.jsonl xtask node_ --ignored --test-threads="$node_threads" fi - name: Verify Python plugins if: needs.changes.outputs.node == 'true' && vars.DIM_CI_PYTHON_PLUGINS == 'true' diff --git a/.github/workflows/code-layout.yml b/.github/workflows/code-layout.yml index c5ddbd731e..61b8bac325 100644 --- a/.github/workflows/code-layout.yml +++ b/.github/workflows/code-layout.yml @@ -6,6 +6,7 @@ on: - scripts/code-layout/** - scripts/code-layout*.test.mjs - .github/workflows/code-layout.yml + - .github/actions/setup-windows-code-layout/** - rust-toolchain.toml - .node-version workflow_dispatch: @@ -71,38 +72,11 @@ jobs: with: python-version: '3.13' architecture: ${{ runner.arch == 'ARM64' && 'arm64' || 'x64' }} - - name: Select native MSVC Rust toolchain + - name: Set up Windows native code layout toolchain if: runner.os == 'Windows' - shell: powershell - run: | - $channel = python -c "import tomllib; print(tomllib.load(open('rust-toolchain.toml', 'rb'))['toolchain']['channel'])" - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - $toolchain = "$channel-${{ matrix.target }}" - rustup toolchain install $toolchain --profile minimal - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - "RUSTUP_TOOLCHAIN=$toolchain" >> $env:GITHUB_ENV - - name: Configure Windows C/C++ toolchain - if: runner.os == 'Windows' - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 + uses: ./.github/actions/setup-windows-code-layout with: - arch: ${{ runner.arch == 'ARM64' && 'arm64' || 'amd64' }} - - name: Locate lld-link - if: runner.os == 'Windows' - shell: powershell - run: | - $linker = Get-Command lld-link -ErrorAction SilentlyContinue - if (!$linker) { - $linker = Get-ChildItem -Recurse -Filter lld-link.exe -ErrorAction SilentlyContinue ` - -Path "$env:ProgramFiles\LLVM\bin", "$env:ProgramFiles\Microsoft Visual Studio\2022\*\VC\Tools\Llvm\*\bin" | - Select-Object -First 1 - } - if ($linker) { - $path = if ($linker -is [System.Management.Automation.ApplicationInfo]) { $linker.Source } else { $linker.FullName } - Split-Path $path >> $env:GITHUB_PATH - Write-Output "Using $path" - } else { - Write-Output 'lld-link is not on PATH; the build will use the Rust toolchain rust-lld' - } + target: ${{ matrix.target }} - run: rustup show - run: node --test ${{ matrix.test }} scripts/code-layout-replay.test.mjs env: @@ -160,38 +134,11 @@ jobs: with: python-version: '3.13' architecture: ${{ runner.arch == 'ARM64' && 'arm64' || 'x64' }} - - name: Select native MSVC Rust toolchain + - name: Set up Windows native code layout toolchain if: runner.os == 'Windows' - shell: powershell - run: | - $channel = python -c "import tomllib; print(tomllib.load(open('rust-toolchain.toml', 'rb'))['toolchain']['channel'])" - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - $toolchain = "$channel-${{ matrix.target }}" - rustup toolchain install $toolchain --profile minimal - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - "RUSTUP_TOOLCHAIN=$toolchain" >> $env:GITHUB_ENV - - name: Configure Windows C/C++ toolchain - if: runner.os == 'Windows' - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 + uses: ./.github/actions/setup-windows-code-layout with: - arch: ${{ runner.arch == 'ARM64' && 'arm64' || 'amd64' }} - - name: Locate lld-link - if: runner.os == 'Windows' - shell: powershell - run: | - $linker = Get-Command lld-link -ErrorAction SilentlyContinue - if (!$linker) { - $linker = Get-ChildItem -Recurse -Filter lld-link.exe -ErrorAction SilentlyContinue ` - -Path "$env:ProgramFiles\LLVM\bin", "$env:ProgramFiles\Microsoft Visual Studio\2022\*\VC\Tools\Llvm\*\bin" | - Select-Object -First 1 - } - if ($linker) { - $path = if ($linker -is [System.Management.Automation.ApplicationInfo]) { $linker.Source } else { $linker.FullName } - Split-Path $path >> $env:GITHUB_PATH - Write-Output "Using $path" - } else { - Write-Output 'lld-link is not on PATH; the build will use the Rust toolchain rust-lld' - } + target: ${{ matrix.target }} - run: rustup show - name: Provision Windows native build dependencies if: runner.os == 'Windows' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 75bfa7807c..652ce892b2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -106,7 +106,12 @@ jobs: run: | set -euo pipefail if [[ "$STAMP" == true ]]; then node scripts/alpha-version.mjs "$RELEASE_VERSION"; fi - cargo install cargo-about --version 0.9.3 --features cli --locked + cargo_about_archive="cargo-about-0.9.3-x86_64-unknown-linux-musl.tar.gz" + curl -fsSL -o "$RUNNER_TEMP/$cargo_about_archive" \ + "https://github.com/EmbarkStudios/cargo-about/releases/download/0.9.3/$cargo_about_archive" + echo "3ad1e94ea1e63d69d1961f4fb15ccbbe9575d906111f96d2cb4dce6df48f71b4 $RUNNER_TEMP/$cargo_about_archive" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/$cargo_about_archive" -C "$RUNNER_TEMP" cargo-about-0.9.3-x86_64-unknown-linux-musl/cargo-about + export PATH="$RUNNER_TEMP/cargo-about-0.9.3-x86_64-unknown-linux-musl:$PATH" cargo fetch --locked mkdir -p staging node scripts/rust-notices.mjs staging/rust-notices.txt diff --git a/Cargo.toml b/Cargo.toml index e0c4d26ce9..d8393a0aa6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,25 @@ jiff = { version = "0.2.46", features = ["serde", "tzdb-bundle-always"] } [profile.dev] debug = "line-tables-only" +[profile.dev.package] +adler2 = { opt-level = 2 } +aho-corasick = { opt-level = 2 } +crc32fast = { opt-level = 2 } +fdeflate = { opt-level = 2 } +flate2 = { opt-level = 2 } +image = { opt-level = 2 } +image-webp = { opt-level = 2 } +memchr = { opt-level = 2 } +miniz_oxide = { opt-level = 2 } +png = { opt-level = 2 } +regex = { opt-level = 2 } +regex-automata = { opt-level = 2 } +regex-syntax = { opt-level = 2 } +serde_json = { opt-level = 2 } +sha2 = { opt-level = 2 } +simd-adler32 = { opt-level = 2 } +zune-jpeg = { opt-level = 2 } + [profile.release] lto = "fat" codegen-units = 1 diff --git a/crates/dim-app-server/src/model_catalog.rs b/crates/dim-app-server/src/model_catalog.rs index e6eca55d07..2d78b6d051 100644 --- a/crates/dim-app-server/src/model_catalog.rs +++ b/crates/dim-app-server/src/model_catalog.rs @@ -27,8 +27,12 @@ fn bundled_model(bytes: &[u8]) -> ModelEntry { } fn bundled_record(bytes: &[u8]) -> T { - serde_json::from_reader(flate2::read::GzDecoder::new(bytes)) - .expect("checked-in bundled catalog records deserialize") + use std::io::Read as _; + let mut decoded = Vec::with_capacity(bytes.len().saturating_mul(3)); + flate2::read::GzDecoder::new(bytes) + .read_to_end(&mut decoded) + .expect("checked-in bundled catalog records decompress"); + serde_json::from_slice(&decoded).expect("checked-in bundled catalog records deserialize") } const REASONING_OFF: &str = include_str!("../resources/reasoning-off-overrides.json"); diff --git a/crates/dimcode/tests/cli_flow.rs b/crates/dimcode/tests/cli_flow.rs index 4dc90a7f77..407ac20e3a 100644 --- a/crates/dimcode/tests/cli_flow.rs +++ b/crates/dimcode/tests/cli_flow.rs @@ -774,6 +774,77 @@ fn configured_api_key_model_uses_production_tools_and_restores_the_same_session( model.join().unwrap(); } +/// Loopback model endpoint that answers each request with HTTP 400 so +/// `exec` fails immediately instead of sleeping through transport retries. +fn rejecting_model_config(home: &Home, requests: usize) -> (PathBuf, thread::JoinHandle<()>) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = listener.local_addr().unwrap(); + let server = thread::spawn(move || { + let body = r#"{"error":{"message":"stub offline model"}}"#; + let response = format!( + "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + for index in 0..requests { + let deadline = Instant::now() + PATIENCE; + let mut stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!( + Instant::now() < deadline, + "Rejecting model request {index} was not made" + ); + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("{error}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(PATIENCE)).unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut length = 0; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse::().unwrap(); + } + } + if length > 0 { + let mut discard = vec![0; length]; + let _ = reader.read_exact(&mut discard); + } + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }); + let config = home.0.join("model.json"); + fs::write( + &config, + json!({ + "defaultModel": { "providerId": "local", "modelId": "diagram-model" }, + "providers": [{ + "id": "local", + "kind": "openai-compatible", + "baseUrl": format!("http://{address}/v1"), + "models": [{ + "id": "diagram-model", + "contextWindow": 128000, + "maxOutputTokens": 4096, + "config": { "maxTokens": 4096 } + }] + }] + }) + .to_string(), + ) + .unwrap(); + (config, server) +} + /// `dimcode export` (Timeline export design §7, §13 item 6): the sibling /// App Server's read-only export, live and after stop, without a daemon. #[test] @@ -793,12 +864,7 @@ fn export_writes_the_timeline_without_starting_a_daemon() { .output() .unwrap() }; - let config = home.0.join("model.json"); - fs::write( - &config, - include_str!("../../dim-agent-aimux/examples/offline.json"), - ) - .unwrap(); + let (config, model) = rejecting_model_config(&home, 1); let exec = run(&[ "--model-config", config.to_str().unwrap(), @@ -806,6 +872,7 @@ fn export_writes_the_timeline_without_starting_a_daemon() { "-p", "hello", ]); + model.join().unwrap(); let stderr = String::from_utf8(exec.stderr).unwrap(); let session = stderr .lines() diff --git a/crates/dimcode/tests/cli_flow/hooks.rs b/crates/dimcode/tests/cli_flow/hooks.rs index d2616f19c6..b4a117ffff 100644 --- a/crates/dimcode/tests/cli_flow/hooks.rs +++ b/crates/dimcode/tests/cli_flow/hooks.rs @@ -379,12 +379,7 @@ fn project_hooks_start_disabled_and_the_user_enables_them() { let binary = std::env::var("DIM_TEST_APP_SERVER").unwrap(); let home = Home::new(); let _daemon = OwnedDaemon(home.0.join("rust/daemon.sock")); - let config = home.0.join("model.json"); - fs::write( - &config, - include_str!("../../../dim-agent-aimux/examples/offline.json"), - ) - .unwrap(); + let (config, model) = rejecting_model_config(&home, 2); let project = home.0.join("work"); fs::create_dir_all(project.join(".dimcode")).unwrap(); fs::write( @@ -493,10 +488,10 @@ fn project_hooks_start_disabled_and_the_user_enables_them() { "{listed}" ); // The next hook point runs the document the CLI wrote. SessionStart - // fires before the model is asked, so the offline configuration's dead - // endpoint does not keep it from running; that configuration never - // finishes a turn, so `Stop` is not reachable here. A turn's own failure - // is expected and not this test's subject. + // fires before the model is asked, so the rejecting fixture endpoint + // does not keep it from running; that endpoint fails the turn + // immediately without retrying, so `Stop` is not reachable here. A + // turn's own failure is expected and not this test's subject. let marker = project.join("user-ran.txt"); let _ = run(&["exec", "-p", "go"]); assert_eq!( @@ -522,6 +517,7 @@ fn project_hooks_start_disabled_and_the_user_enables_them() { "user-two", "the replacement did not reach the next hook point" ); + model.join().unwrap(); assert!(run(&["daemon", "stop"]).status.success()); } diff --git a/docs/architecture/build.md b/docs/architecture/build.md index bedda55a45..583d937e2b 100644 --- a/docs/architecture/build.md +++ b/docs/architecture/build.md @@ -319,9 +319,27 @@ build host, plus the archived copy's `sha256`. CI and `./dev check` run the format check as `cargo fmt --all -- --check --config error_on_line_overflow=true`: when one line in a block cannot fit `max_width`, rustfmt abandons the block without a diagnostic, so the option turns that otherwise-skipped line into a failure ([#1769](https://github.com/arcships/dim/issues/1769)). -The PR `macos-native` job has a thirty-minute deadline. The full `verify` job has a seventy-five-minute deadline on either platform. It builds all workspace targets once, checks the architecture, then runs up to three recorded test executables at a time with up to three test threads per executable. The workspace run starts `transport_flow`, `cli_flow`, `cli_tui_flow`, `cli_session_flow` and `cli_daemon_flow` first. The separate CLI profile and Node- and Python-backed Rust suites use two test threads each. The `dependencies` job allows two Cargo build jobs when installing `cargo-deny`. +The PR `macos-native` job has a thirty-minute deadline. The full `verify` job has a seventy-five-minute deadline on either platform. It builds all workspace targets once, checks the architecture, then runs recorded test executables in parallel via `scripts/run-rust-test.mjs` (`DIM_TEST_JOBS` defaults to `clamp(availableParallelism / 3, 3, 8)`). On Linux `verify`, CI scales concurrency to the runner's usable physical cores rather than its SMT siblings: it derives threads per core from `lscpu` and divides the job's CPU count by it, so several runner instances on one host are not oversubscribed. `DIM_TEST_JOBS = clamp(physical / 3, 3, 8)` and `--test-threads = clamp(physical / 4, 2, 6)` for workspace tests, with four test threads for the separate CLI profile and Node-backed Rust suites. On macOS `verify`, CI retains three target workers, three workspace test threads and two threads for the separate CLI profile, Node- and Python-backed suites. The workspace run prioritizes long flow suites (`cli_flow*`, `transport_flow`, `app_server_flow`, `storage_flow`, `xtask`, `model_catalog_flow`, `modality_flow`, `capabilities_flow`, `integration_flow`) first so they overlap from the start. Root `Cargo.toml` compiles targeted CPU-heavy third-party dependencies (compression, JSON, regex, image codecs and SHA-2) at `opt-level = 2` under `[profile.dev.package.*]` while keeping workspace crates unoptimized for fast incremental rebuilds. The `dependencies` job allows two Cargo build jobs when installing `cargo-deny`. -CI sets `CARGO_TARGET_DIR` to the checkout's `target` directory so a compiler cache's managed-target collection cannot remove binaries between the build and their later execution. Each executable keeps its Cargo package working directory and streams output immediately, with target start/end markers and exit status. A target has a ten-minute default deadline (`DIM_TEST_TIMEOUT_MS` overrides it); the full workspace step sets fifteen minutes per executable for the large flow suites at three test threads. Timeout and cancellation terminate its process tree. Failures still allow the other targets to finish and fail the step. Cargo runs documentation tests separately with the same feature selection. Local `cargo test --workspace --locked` remains available without Node. +CI sets `CARGO_TARGET_DIR` to the checkout's `target` directory in `verify`, `macos-native` and `acp-registry` so a compiler cache's managed-target collection cannot remove binaries between the build and their later execution. On the persistent self-hosted Windows x64 runner, `windows-cli` reuses a per-runner target directory outside the Git checkout (`/../.dim-windows-cli-target`), resetting it automatically whenever `rust-toolchain.toml` or `CARGO_PROFILE_DEV_DEBUG` changes or its size exceeds 6 GiB. Each executable keeps its Cargo package working directory and streams output immediately, with target start/end markers and exit status. A target has a ten-minute default deadline (`DIM_TEST_TIMEOUT_MS` overrides it); the full workspace step sets fifteen minutes per executable for the large flow suites. Timeout and cancellation terminate its process tree. Failures still allow the other targets to finish and fail the step. Cargo runs documentation tests separately with the same feature selection. Local `cargo test --workspace --locked` remains available without Node. + +### Active-gate budgets + +Per [ADR 026](../adr/026-verification-tiers-and-ci-governance.md) D4, synchronous pull-request active gates operate under recorded steady-state wall-clock and resource budgets: + +| Gate | Tier | Runner pool | Steady-state budget (p90) | Hard timeout | Resource & cache bounds | +| --- | --- | --- | --- | --- | --- | +| `changes` (routing + ADR freeze) | L1 | Self-hosted | ≤ 1 min | 5 min | Shallow fetch (`depth=2`), Node only | +| `dependencies` (`cargo-deny`) | L1 | Self-hosted Windows x64 | ≤ 2 min | 15 min | `cargo install --jobs 2` on miss | +| `web` (stage + test + lint + build) | L1 / L2 | Self-hosted Windows x64 | ≤ 5 min | 15 min | Isolated npm workspace check | +| `windows-cli` (`dim-cli --lib`) | L3 | Self-hosted Windows x64 | ≤ 1 min warm (≤ 4 min cold) | 15 min | Per-runner target dir capped at 6 GiB | +| `macos-native` (macOS Rust + packaging) | L3 | Self-hosted macOS ARM64 | ≤ 6 min | 30 min | `CARGO_BUILD_JOBS=4`, checkout `target/` | +| `verify (linux)` (build + clippy + tests) | L1 / L2 / L3 | Self-hosted Linux x64 (`dim-verify`) | ≤ 15 min target (steady state not yet measured at these settings) | 75 min | `CARGO_BUILD_JOBS=8`, `CARGO_PROFILE_DEV_DEBUG=0`, CPU-scaled `DIM_TEST_JOBS` / `--test-threads`, 15 min target cap | +| `code-layout` (native layout matrix) | L3 | Hosted Linux, macOS, Windows | Not yet recorded | 10 / 30 / 240 min per job | Hosted runners; `native-layout` runs on layout changes | + +The `verify (linux)` row records a target rather than a measurement: no full green run exists at these settings yet. The last six full runs on the `dim-verify` pool before this change completed in 18m17s (44724315336), 21m18s (44722644428), 23m42s (44719273152), 21m29s (44718768375), 30m49s (44717853591) and 25m38s (44716244403). Record the new steady state once a full green run at these settings completes. + +Approaching or exceeding a steady-state budget is treated as a regression and resolved by narrowing path scope, optimizing slow tests, improving parallelism or demoting heavy cases to Retained — never by raising job or target timeouts alone. Any change that adds a required PR check or widens path selection must disclose its incremental wall-clock cost, added compile dependencies and target runner pool. Terminal-interaction end-to-end tests for the native TUI run locally through tmux, not in CI: `node scripts/tui-tmux/run.mjs` after building `dimcode` and, for the provider scenario's `--server` profile, `dim-app-server`. A TUI case keeps running in CI until a tmux scenario proves the same behavior; [Terminal end-to-end suite](tui-e2e.md) records which cases moved and which still wait. CI keeps the component render and keyboard tests, the protocol contract tests and the line-mode CLI flows. @@ -331,7 +349,7 @@ The root `./dev` entry performs incremental CLI/App Server builds without disabl The [Web workspace](../design/web-workspace.md) frontend in `web/` is a separate artifact (`scripts/stage-web.mjs` builds it; the CLI finds the installed `dimcode-web` package or a `web/` directory beside the executable or in the product home, or `DIMCODE_WEB_ASSETS` names one), so building `dim-app-server` and `dimcode` needs neither Node nor npm. Only `cargo build --features embedded-web` compiles the frontend in; then `build.rs` runs `npm ci` and `npm run build` when that frontend changed, and a host without npm fails the build. Otherwise Node is only needed for packaging, packaging checks and TypeScript plugin execution/development. `.node-version` pins the Node version bundled into account-enabled releases. The `runtime/package-lock.json` fixes the rutis Node runtime and its transitive dependencies; `npm ci --ignore-scripts --prefix runtime` installs them for local bridge testing. -Pull requests run workspace verification on self-hosted Linux x64 runners labelled `dim-verify`, with eight Cargo build jobs. The job checks that bubblewrap can create a sandbox before running the confined process tests. The macOS ARM64 runners use four Cargo jobs for the native Rust checks on pull requests and for full workspace verification on `main`. Use `node scripts/test-macos-native.mjs --list` to inspect the Rust selection from the current Cargo targets, Rust platform guards and host-specific test fixtures. On an Apple Silicon Mac, run `node scripts/test-macos-native.mjs` to build those targets and check each selected name against its compiled test binary before execution. Tests marked for manual execution keep their normal ignore status. The [workflow guide](../release/README.md#github-workflows) describes path selection, native packaging checks and manual dispatch. The separate `windows-cli` job runs native boundary flows on a self-hosted Windows x64 runner, where its fixture writes to the clipboard. The layout workflow uses hosted `windows-2022` and `windows-11-arm` runners, with Python 3.13 and the pinned native MSVC Rust host toolchain provisioned explicitly. Release builds use GitHub-hosted VMs matching each target OS and CPU. See the [runner setup and release matrix](../release/README.md#runner-setup). +Pull requests run workspace verification on self-hosted Linux x64 runners labelled `dim-verify`, with eight Cargo build jobs. The job checks that bubblewrap can create the sandbox the confined tests use (a user namespace with a private `/proc`) before running them. The macOS ARM64 runners use four Cargo jobs for the native Rust checks on pull requests and for full workspace verification on `main`. Use `node scripts/test-macos-native.mjs --list` to inspect the Rust selection from the current Cargo targets, Rust platform guards and host-specific test fixtures. On an Apple Silicon Mac, run `node scripts/test-macos-native.mjs` to build those targets and check each selected name against its compiled test binary before execution. Tests marked for manual execution keep their normal ignore status. The [workflow guide](../release/README.md#github-workflows) describes path selection, native packaging checks and manual dispatch. The separate `windows-cli` job runs native boundary flows on a self-hosted Windows x64 runner, where its fixture writes to the clipboard. The layout workflow uses hosted `windows-2022` and `windows-11-arm` runners, with Python 3.13 and the pinned native MSVC Rust host toolchain provisioned explicitly. Release builds use GitHub-hosted VMs matching each target OS and CPU. See the [runner setup and release matrix](../release/README.md#runner-setup). The macOS clipboard flows use private pasteboards and serialize access to the shared pasteboard server; other tests remain parallel. diff --git a/docs/release/README.md b/docs/release/README.md index a72fd88bfd..42467674a6 100644 --- a/docs/release/README.md +++ b/docs/release/README.md @@ -139,7 +139,7 @@ and runtime validation before fat LTO is enabled there. Other targets still need release-profile build and runtime validation; Linux or macOS measurements do not establish their peak memory requirements. -The Ubuntu preflight generates the Rust distribution notices once with cargo-about 0.9.3 using the versioned checkout. All six targets download that artifact. Linux builds on each native host with GNU tools in a digest-pinned manylinux_2_28 container. The executable also runs in that glibc 2.28 environment. Windows uses native MSVC, clang-cl on ARM64, NASM on x64, and the Windows system tar to create ZIP archives. Actions installs Node from `.node-version` and Rust uses `rust-toolchain.toml`. Web and Release assembly run on hosted Ubuntu. +The Ubuntu preflight generates the Rust distribution notices once with the pinned prebuilt cargo-about 0.9.3 binary (verified by SHA-256) using the versioned checkout. All six targets download that artifact. Linux builds on each native host with GNU tools in a digest-pinned manylinux_2_28 container. The executable also runs in that glibc 2.28 environment. Windows uses native MSVC, clang-cl on ARM64, NASM on x64, and the Windows system tar to create ZIP archives. Actions installs Node from `.node-version` and Rust uses `rust-toolchain.toml`. Web and Release assembly run on hosted Ubuntu. The separate PR workflow uses self-hosted macOS ARM64, Windows x64, and Linux x64 runners. Register self-hosted runners with the [OS and architecture labels](https://docs.github.com/en/actions/how-tos/manage-runners/self-hosted-runners/use-in-a-workflow). A Linux x64 runner that carries workspace verification also has the `dim-verify` label and bubblewrap installed. Keep PR runner credentials and private networks isolated as required by the [CI trust model](#ci-trust-model). @@ -188,7 +188,7 @@ The `Verify downloaded Node runtime` step runs on full `main` push checks and ma ### Action pins and updates -External Actions in every workflow use full commit SHAs, including `code-layout.yml`. This policy covers both persistent self-hosted runners and GitHub-hosted runners. Pinning does not change the [CI trust boundary](#ci-trust-model). +External Actions in every workflow and local composite action (`.github/actions/*/action.yml`) use full commit SHAs, including `code-layout.yml`. This policy covers both persistent self-hosted runners and GitHub-hosted runners. Pinning does not change the [CI trust boundary](#ci-trust-model). Update an Action in a normal pull request: diff --git a/scripts/development.test.mjs b/scripts/development.test.mjs index 8693c36163..a74c3a1400 100644 --- a/scripts/development.test.mjs +++ b/scripts/development.test.mjs @@ -31,7 +31,8 @@ test('long workspace targets start first, overlap and drain the queue after a fa const artifacts = path.join(temporary, 'artifacts.jsonl'); const longTargets = ['transport_flow', 'cli_flow']; const initial = [...longTargets, 'parallel']; - const records = ['parallel', 'queued', ...longTargets].map(name => { + const workers = [...initial, 'fourth']; + const records = ['parallel', 'fourth', 'queued', ...longTargets].map(name => { const directory = path.join(temporary, name); mkdirSync(directory); return { reason: 'compiler-artifact', profile: { test: true }, target: { name }, manifest_path: path.join(directory, 'Cargo.toml'), executable: process.execPath }; @@ -60,15 +61,53 @@ test('long workspace targets start first, overlap and drain the queue after a fa }, 10); } `; - const result = spawnSync(process.execPath, [path.join(import.meta.dirname, 'run-rust-test.mjs'), artifacts, '--workspace', '--eval', fixture], { encoding: 'utf8', timeout: 10_000 }); + const result = spawnSync(process.execPath, [path.join(import.meta.dirname, 'run-rust-test.mjs'), artifacts, '--workspace', '--eval', fixture], { + encoding: 'utf8', + env: { ...process.env, DIM_TEST_JOBS: '3' }, + timeout: 10_000, + }); assert.equal(result.status, 7, result.stderr); - assert.deepEqual(Array.from(result.stderr.matchAll(/^\[test\] START (\S+)/gm), match => match[1]), [...initial, 'queued']); - assert.match(result.stderr, /\[test\] END .*\n\[test\] START queued /); + assert.deepEqual(Array.from(result.stderr.matchAll(/^\[test\] START (\S+)/gm), match => match[1]), [...initial, 'fourth', 'queued']); + assert.match(result.stderr, /\[test\] END .*\n\[test\] START fourth /); for (const record of records) { assert(existsSync(path.join(path.dirname(record.manifest_path), 'done')), result.stdout); assert.match(result.stderr, new RegExp(`START ${record.target.name}`)); assert.match(result.stderr, new RegExp(`END ${record.target.name}`)); } + for (const name of workers) { + for (const marker of ['started', 'done']) rmSync(path.join(temporary, name, marker), { force: true }); + } + const raised = ` + const fs = require('node:fs'); + const path = require('node:path'); + const root = path.dirname(process.cwd()); + fs.writeFileSync('started', ''); + const initial = ${JSON.stringify(workers)}; + const until = Date.now() + 5000; + const timer = setInterval(() => { + if (initial.every(target => fs.existsSync(path.join(root, target, 'started')))) { + clearInterval(timer); + fs.writeFileSync('done', ''); + } else if (Date.now() > until) { + clearInterval(timer); + process.exitCode = 9; + } + }, 10); + `; + const parallel = spawnSync(process.execPath, [path.join(import.meta.dirname, 'run-rust-test.mjs'), artifacts, '--workspace', '--eval', raised], { + encoding: 'utf8', + env: { ...process.env, DIM_TEST_JOBS: '4' }, + timeout: 10_000, + }); + assert.equal(parallel.status, 0, parallel.stderr); + assert.deepEqual(Array.from(parallel.stderr.matchAll(/^\[test\] START (\S+)/gm), match => match[1]), [...workers, 'queued']); + for (const name of workers) assert(existsSync(path.join(temporary, name, 'done')), `${name} never proved four workers ran together`); + const invalidJobs = spawnSync(process.execPath, [path.join(import.meta.dirname, 'run-rust-test.mjs'), artifacts, '--workspace'], { + encoding: 'utf8', + env: { ...process.env, DIM_TEST_JOBS: '0' }, + }); + assert.notEqual(invalidJobs.status, 0); + assert.match(invalidJobs.stderr, /DIM_TEST_JOBS must be a positive integer/); writeFileSync(artifacts, ''); const empty = spawnSync(process.execPath, [path.join(import.meta.dirname, 'run-rust-test.mjs'), artifacts, '--workspace'], { encoding: 'utf8' }); assert.notEqual(empty.status, 0); diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs index 371b0251c0..87d9cc6874 100644 --- a/scripts/release.test.mjs +++ b/scripts/release.test.mjs @@ -122,12 +122,25 @@ test('the release workflow writes a build stamp only when generation succeeds',{ }); test('workflow actions use immutable commits',()=>{ + const files=[]; const workflows=path.join(root,'.github/workflows'); for (const file of readdirSync(workflows).filter(file=>/\.ya?ml(?:\.disabled)?$/.test(file))) { - const source=readFileSync(path.join(workflows,file),'utf8'); + files.push({label:file,fullPath:path.join(workflows,file)}); + } + const actions=path.join(root,'.github/actions'); + if (existsSync(actions)) { + for (const entry of readdirSync(actions,{recursive:true,withFileTypes:true})) { + if (entry.isFile() && /^action\.ya?ml$/.test(entry.name)) { + const fullPath=path.join(entry.parentPath,entry.name); + files.push({label:path.relative(path.join(root,'.github'),fullPath),fullPath}); + } + } + } + for (const {label,fullPath} of files) { + const source=readFileSync(fullPath,'utf8'); for (const [,action] of source.matchAll(/^\s*(?:-\s*)?uses:\s*(\S+)/gm)) { if (action.startsWith('./')) continue; - assert.match(action,/^[\w.-]+\/[\w./-]+@[a-f0-9]{40}$/,`${file}: ${action} must use a full commit SHA`); + assert.match(action,/^[\w.-]+\/[\w./-]+@[a-f0-9]{40}$/,`${label}: ${action} must use a full commit SHA`); } } }); diff --git a/scripts/run-rust-test.mjs b/scripts/run-rust-test.mjs index 0ef868ccab..01cc85470f 100644 --- a/scripts/run-rust-test.mjs +++ b/scripts/run-rust-test.mjs @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import {spawn,spawnSync} from 'node:child_process'; import {once} from 'node:events'; import {readFileSync} from 'node:fs'; +import {availableParallelism} from 'node:os'; import {dirname} from 'node:path'; const [artifacts,target,...args]=process.argv.slice(2); @@ -9,11 +10,27 @@ assert(artifacts&&target,'Usage: node scripts/run-rust-test.mjs ARTIFACTS TARGET const workspace=target==='--workspace'; const timeout=Number(process.env.DIM_TEST_TIMEOUT_MS??600_000); assert(Number.isSafeInteger(timeout)&&timeout>0,'DIM_TEST_TIMEOUT_MS must be a positive integer'); +const defaultJobs=Math.max(3,Math.min(8,Math.floor(availableParallelism()/3))); +const jobs=workspace?Number(process.env.DIM_TEST_JOBS??defaultJobs):1; +assert(Number.isSafeInteger(jobs)&&jobs>0,'DIM_TEST_JOBS must be a positive integer'); const matches=readFileSync(artifacts,'utf8').split('\n').filter(Boolean).map(line=>JSON.parse(line)) .filter(record=>record.reason==='compiler-artifact'&&record.profile.test&&record.executable&&(workspace||record.target.name===target)); if(workspace){ assert(matches.length,'Expected compiled workspace test targets'); - const longTargets=new Set(['transport_flow','cli_flow','cli_tui_flow','cli_session_flow','cli_daemon_flow']); + const longTargets=new Set([ + 'cli_flow', + 'cli_tui_flow', + 'cli_daemon_flow', + 'cli_session_flow', + 'transport_flow', + 'app_server_flow', + 'storage_flow', + 'xtask', + 'model_catalog_flow', + 'modality_flow', + 'capabilities_flow', + 'integration_flow', + ]); matches.sort((a,b)=>Number(longTargets.has(b.target.name))-Number(longTargets.has(a.target.name))); }else{ assert.equal(matches.length,1,`Expected one compiled test target named ${target}`); @@ -51,7 +68,7 @@ for(const [signal,code] of [['SIGINT',130],['SIGTERM',143]]){ for(const child of active) terminate(child); }); } -await Promise.all(Array.from({length:workspace?3:1},async()=>{ +await Promise.all(Array.from({length:Math.min(jobs,matches.length)},async()=>{ while(matches.length&&!stopping){ const record=matches.shift(); const started=performance.now();