diff --git a/.claude/commands/diagnose-pr-head.md b/.claude/commands/diagnose-pr-head.md new file mode 100644 index 0000000000..6a3a06bc8a --- /dev/null +++ b/.claude/commands/diagnose-pr-head.md @@ -0,0 +1,199 @@ +Diagnose pr-head CI instabilities for an ORFS pull request by checking build determinism. + +Usage: /diagnose-pr-head + +## Known non-determinism sources + +- **`repair_timing` (RSZ) is non-deterministic with threads > 1** — the multi-threaded STA timing analysis produces different results between runs, causing different repair decisions. With `-threads 1` it is deterministic. Filed as https://github.com/The-OpenROAD-Project/OpenROAD/issues/9781 +- The following are **deterministic** (even multi-threaded): `pin_access`, `global_route`, `repair_design`, `detailed_placement` +- The non-determinism in `repair_timing` propagates through subsequent incremental GRT, affecting final metrics + +## Arguments + +- `$ARGUMENTS` contains a GitHub PR URL (e.g., https://github.com/The-OpenROAD-Project/OpenROAD-flow-scripts/pull/3991) + +## Procedure + +### 1. Fetch PR information + +Extract the PR number from `$ARGUMENTS` (the number after `/pull/`). Extract owner/repo from the URL. + +```bash +gh pr view --repo / --json number,title,headRefName,headRefOid,baseRefName,state,statusCheckRollup +gh pr checks --repo / +``` + +For failed Jenkins checks, get the details URL and fetch status context: +```bash +HEAD_SHA=$(gh pr view --repo / --json headRefOid -q .headRefOid) +gh api repos///statuses/$HEAD_SHA +``` + +### 2. Identify failed designs + +Parse CI output for design/platform pairs and metric threshold violations. If specific failing designs cannot be determined from CI output, proceed — the idempotency sweep will still reveal systemic issues. + +### 3. Save current state and check out pr-head + +```bash +ORIG_BRANCH=$(git branch --show-current || git rev-parse HEAD) +git stash +gh pr checkout +``` + +Do NOT use `--recurse-submodules` or `git submodule update --init --recursive` — it's unnecessary and slow. + +### 4. Build OpenROAD + +Build from inside the `tools/OpenROAD` directory (it has its own MODULE.bazel). First ensure `src/sta` matches: +```bash +cd tools/OpenROAD +git submodule update --init src/sta +bazelisk run //:install +``` + +**Common build issue:** If the build fails with STA API mismatches (e.g., `StringSeq` vs `StdStringSeq`, pointer vs value), the `src/sta` submodule inside `tools/OpenROAD` is likely at the wrong commit (left over from a previous checkout). Fix with: +```bash +cd tools/OpenROAD && git submodule update --init src/sta +``` +Do NOT try to fix the API mismatches in OpenROAD source — just get the right STA version. + +Verify the binary: +```bash +tools/install/OpenROAD/bin/openroad -version +``` + +### 5. Idempotency sweep — escalate from fast to slow designs + +Use `flow/util/test_idempotency.sh` to run each design twice and compare per-stage ODB hashes automatically: + +```bash +cd flow +./util/test_idempotency.sh asap7/gcd +./util/test_idempotency.sh nangate45/gcd +./util/test_idempotency.sh / +``` + +Test in this order, stopping as soon as non-determinism is found: + +1. **asap7/gcd** — fastest (~1-2 min), catches systemic issues +2. **nangate45/gcd** — different platform, still fast +3. **The specific failing design** from step 2 (e.g., nangate45/swerv_wrapper) +4. If all deterministic so far, keep testing progressively larger designs from the CI job + +The script exits 0 if deterministic, 1 if non-deterministic. If ALL designs pass, the failure is a real regression or flaky threshold, not non-determinism. Report and stop. + +If ANY design fails, note the earliest diverging stage. Proceed to step 6. + +### 6. Drilldown with A/B tricks + +Run the drilldown script which tests all A/B perturbation tricks in parallel, each using a unique `FLOW_VARIANT` so they write to independent directories: + +```bash +cd flow +./util/drilldown_idempotency.sh +``` + +This tests: plain re-run, single-threaded (`NUM_CORES=1`), ASLR disabled, `MALLOC_PERTURB_=1`. All run in parallel. + +If any variant diverges from the baseline, you've found an A/B pair. + +### 7. Bisect within a stage's TCL script + +The flow stages (e.g., `5_1_grt`) often run multiple OpenROAD commands internally. Use `make _issue` to create an isolated environment, then bisect by creating TCL scripts that include progressively more commands: + +```bash +make DESIGN_CONFIG=./designs///config.mk _issue +``` + +Inside the issue directory, create bisection TCL scripts adding one command at a time. Run each twice and compare hashes to find the specific command that introduces non-determinism. Test with `-threads 1` vs `-threads N` to determine if it's threading-related. + +Use `FLOW_VARIANT` overrides for each run so they write to separate directories and can run in parallel. + +### 8. Restore and report + +```bash +git checkout $ORIG_BRANCH +git stash pop 2>/dev/null || true +``` + +Print a structured report: + +``` +## pr-head Idempotency Diagnosis + +**PR:** # - +**PR Head Commit:** <sha> +**Failed Designs:** <list> + +### Idempotency Results + +| Design | Stage | Run 1 Hash | Run 2 Hash | Match? | +|--------|-------|------------|------------|--------| +| asap7/gcd | 1_1_yosys | abc123... | abc123... | YES | +| ... | ... | ... | ... | ... | + +### Conclusion + +- Build is DETERMINISTIC / NON-DETERMINISTIC at stage <X>. +- Root cause: <command> is non-deterministic with threads > 1. +``` + +## Reference: checking build determinism + +The flow logs SHA1 hashes of each stage's `.odb` via `genElapsedTime.py`: + + python3 flow/util/genElapsedTime.py -d flow/logs/<platform>/<design>/base/ + +The `sha1sum .odb [0:20)` column is the hash to compare. Use `FLOW_VARIANT` to run A/B tests in parallel with independent output directories. + +To diff divergent ODB files as human-readable DEF: + + openroad -exit -cmd "read_db run1.odb; write_def run1.def" + openroad -exit -cmd "read_db run2.odb; write_def run2.def" + diff run1.def run2.def + +## Reference: common sources of non-determinism + +- **Thread scheduling** — parallel algorithms (OpenMP `schedule(dynamic)`, thread pools) accumulate results in arrival order. Test with `-threads 1`. +- **Unordered container iteration** — `std::unordered_map`/`set` iterate in implementation-defined order. Replace with `std::map`/`set` or sort keys before iterating. +- **Pointer-based sorting** — sorting by pointer value varies due to ASLR. Test with `setarch $(uname -m) -R`. +- **Uninitialized memory** — use of freed/uninitialized memory. Test with `MALLOC_PERTURB_=1`. +- **Random seeds** — algorithms using `rand()` or `std::mt19937` without a fixed seed. + +## Reference: A/B techniques + +Use these make variables to perturb runs (each with its own `FLOW_VARIANT`): + +| Technique | Make override | What it tests | +|-----------|--------------|---------------| +| Single thread | `NUM_CORES=1` | Thread scheduling | +| No ASLR | wrap with `setarch $(uname -m) -R` | Pointer-dependent ordering | +| Malloc perturb | `env MALLOC_PERTURB_=1` | Uninitialized memory | + +## Reference: whittle.py for non-determinism + +For non-determinism the "error" is that two runs differ. Create a wrapper that runs the stage twice, compares hashes, and prints a marker: + +```bash +#!/bin/bash +STAGE_ODB=results/<platform>/<design>/base/<stage>.odb +make DESIGN_CONFIG=... EQUIVALENCE_CHECK=0 <stage> +HASH1=$(sha1sum $STAGE_ODB | cut -c1-40) +make DESIGN_CONFIG=... EQUIVALENCE_CHECK=0 clean_<stage> <stage> +HASH2=$(sha1sum $STAGE_ODB | cut -c1-40) +[ "$HASH1" != "$HASH2" ] && echo "NON_DETERMINISTIC" +``` + +Then: `whittle.py --error_string NON_DETERMINISTIC --step ./wrapper.sh --base_db_path <input>.odb` + +Only whittle if the reproducer takes >10 minutes. For fast reproducers, whittling can make the bug harder to trigger. + +## Important + +- Always use `EQUIVALENCE_CHECK=0` to skip the eqy dependency +- Use relative paths from the repo root +- Use `git commit -s` for DCO sign-off on any commits +- If the PR modifies `tools/OpenROAD`, the build step is essential +- Do NOT recurse submodules from the ORFS root — only the top-level checkout is needed +- Before building OpenROAD, ALWAYS run `git submodule update --init src/sta` inside `tools/OpenROAD/` to ensure `src/sta` matches the pinned commit. A stale `src/sta` from a previous checkout causes misleading API mismatch errors. NEVER try to "fix" these mismatches in OpenROAD source — the fix is always to get the right submodule version. diff --git a/flow/util/drilldown_idempotency.sh b/flow/util/drilldown_idempotency.sh new file mode 100755 index 0000000000..4fc9f48c25 --- /dev/null +++ b/flow/util/drilldown_idempotency.sh @@ -0,0 +1,162 @@ +#!/bin/bash +# Drilldown into idempotency for a single design using every A/B trick +# in the book. Each trick uses a unique FLOW_VARIANT so all tests run +# in parallel with independent output directories. +# +# Usage: ./util/drilldown_idempotency.sh <platform/design> +# e.g.: ./util/drilldown_idempotency.sh asap7/gcd +# +# Make variables used for perturbation (from variables.mk): +# FLOW_VARIANT — output directory selector (logs/results/objects/reports) +# NUM_CORES — thread count, feeds into OPENROAD_ARGS via -threads +# OR_ARGS — extra args appended to OPENROAD_ARGS +# OPENROAD_EXE — path to openroad binary (can be a wrapper) +# +# Environment perturbations: +# MALLOC_PERTURB_ — fills freed memory to detect uninitialized reads +# setarch -R — disables ASLR +# +# Exit code: 0 if all match baseline, 1 if any trick reveals divergence. + +set -euo pipefail + +if [ $# -lt 1 ]; then + echo "Usage: $0 <platform/design>" >&2 + exit 2 +fi + +DESIGN="$1" +DESIGN_CONFIG="./designs/${DESIGN}/config.mk" +PLATFORM=$(echo "$DESIGN" | cut -d/ -f1) +DESIGN_NAME=$(echo "$DESIGN" | cut -d/ -f2) + +if [ ! -f "$DESIGN_CONFIG" ]; then + echo "ERROR: Design config not found: $DESIGN_CONFIG" >&2 + exit 2 +fi + +# Common make arguments shared by all variants +MAKE="make DESIGN_CONFIG=$DESIGN_CONFIG EQUIVALENCE_CHECK=0" + +extract_hashes() { + local variant="$1" + python3 util/genElapsedTime.py -d "logs/${PLATFORM}/${DESIGN_NAME}/${variant}/" 2>/dev/null \ + | awk 'NF>=4 && $4 ~ /^[0-9a-f]/ {print $1, $4}' +} + +echo "Drilldown idempotency: $DESIGN" +echo "" + +# --- Define variants --- +# Each entry: "variant_name|shell command" +# Uses make VAR=val syntax for readability; env wrappers where needed. + +VARIANTS=( + # Baseline: two identical runs + "plain_a|$MAKE FLOW_VARIANT=plain_a finish" + "plain_b|$MAKE FLOW_VARIANT=plain_b finish" + + # Single-threaded: eliminates thread scheduling non-determinism + "thread1|$MAKE FLOW_VARIANT=thread1 NUM_CORES=1 finish" + + # ASLR disabled: eliminates pointer-address-dependent ordering + "noaslr|setarch $(uname -m) -R $MAKE FLOW_VARIANT=noaslr finish" + + # Memory perturbation: detects use of uninitialized memory + "mallocperturb|env MALLOC_PERTURB_=1 $MAKE FLOW_VARIANT=mallocperturb finish" +) + +echo "Variants to test:" +for entry in "${VARIANTS[@]}"; do + name="${entry%%|*}" + echo " - $name" +done +echo "" + +# --- Clean all variants --- +for entry in "${VARIANTS[@]}"; do + name="${entry%%|*}" + $MAKE FLOW_VARIANT="$name" clean_all >/dev/null 2>&1 || true +done + +# --- Launch all in parallel --- +declare -A PIDS LOGS +for entry in "${VARIANTS[@]}"; do + name="${entry%%|*}" + cmd="${entry#*|}" + logfile="/tmp/drill_${PLATFORM}_${DESIGN_NAME}_${name}.log" + LOGS[$name]="$logfile" + echo "Starting: $name" + bash -c "$cmd" > "$logfile" 2>&1 & + PIDS[$name]=$! +done + +# --- Wait for all --- +echo "" +echo "Waiting for all variants to complete..." +VARIANT_NAMES=() +for entry in "${VARIANTS[@]}"; do + name="${entry%%|*}" + VARIANT_NAMES+=("$name") + if wait "${PIDS[$name]}"; then + echo " $name: completed" + else + echo " $name: FAILED (check ${LOGS[$name]})" + fi +done + +# --- Extract hashes --- +echo "" +echo "========================================" +echo "Hash results" +echo "========================================" + +declare -A HASH_FILES +for name in "${VARIANT_NAMES[@]}"; do + hfile="/tmp/drill_hashes_${PLATFORM}_${DESIGN_NAME}_${name}.txt" + extract_hashes "$name" > "$hfile" + HASH_FILES[$name]="$hfile" + echo "" + echo "--- $name ---" + cat "$hfile" +done + +# --- Compare against baseline (plain_a) --- +echo "" +echo "========================================" +echo "Comparisons against baseline (plain_a)" +echo "========================================" + +BASELINE="${HASH_FILES[plain_a]}" +FAIL=0 +DIVERGENT=() + +for name in "${VARIANT_NAMES[@]}"; do + [ "$name" = "plain_a" ] && continue + echo "" + echo "--- plain_a vs $name ---" + if diff -q "$BASELINE" "${HASH_FILES[$name]}" >/dev/null 2>&1; then + echo "MATCH" + else + echo "DIVERGENT!" + diff "$BASELINE" "${HASH_FILES[$name]}" || true + FAIL=1 + DIVERGENT+=("$name") + fi +done + +# --- Summary --- +echo "" +echo "========================================" +if [ $FAIL -eq 0 ]; then + echo "DRILLDOWN: $DESIGN — all variants match. Build is robust." +else + echo "DRILLDOWN: $DESIGN — DIVERGENCE in: ${DIVERGENT[*]}" + echo "" + echo "Next steps:" + echo " 1. Identify which stage first diverges in: ${DIVERGENT[*]}" + echo " 2. Create issue: make DESIGN_CONFIG=$DESIGN_CONFIG <stage>_issue" + echo " 3. Whittle: python3 tools/OpenROAD/etc/whittle.py --error_string NON_DETERMINISTIC ..." +fi +echo "========================================" +exit $FAIL diff --git a/flow/util/sweep_idempotency.sh b/flow/util/sweep_idempotency.sh new file mode 100755 index 0000000000..30e2378bde --- /dev/null +++ b/flow/util/sweep_idempotency.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# Sweep multiple designs for idempotency, running ALL designs in parallel. +# Each design runs two flows (idem_run1, idem_run2) via FLOW_VARIANT, +# and each design uses its own results/logs directory, so everything +# is fully parallel. +# +# Usage: ./util/sweep_idempotency.sh [extra_design1 extra_design2 ...] +# e.g.: ./util/sweep_idempotency.sh nangate45/swerv_wrapper +# +# Always tests asap7/gcd and nangate45/gcd first, plus any extra designs. +# Exit code: 0 if all deterministic, 1 if any non-determinism found. + +set -euo pipefail + +DESIGNS=("asap7/gcd" "nangate45/gcd" "$@") + +# Remove duplicates while preserving order +UNIQUE_DESIGNS=() +declare -A SEEN +for d in "${DESIGNS[@]}"; do + if [ -z "${SEEN[$d]:-}" ]; then + UNIQUE_DESIGNS+=("$d") + SEEN[$d]=1 + fi +done + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +echo "Running idempotency tests for ${#UNIQUE_DESIGNS[@]} designs IN PARALLEL:" +for d in "${UNIQUE_DESIGNS[@]}"; do echo " - $d"; done +echo "" + +# Launch all designs in parallel +declare -A PIDS +declare -A LOGS +for design in "${UNIQUE_DESIGNS[@]}"; do + logfile="/tmp/idempotency_sweep_${design//\//_}.log" + LOGS[$design]="$logfile" + "$SCRIPT_DIR/test_idempotency.sh" "$design" > "$logfile" 2>&1 & + PIDS[$design]=$! +done + +# Wait for all and collect results +FAIL=0 +for design in "${UNIQUE_DESIGNS[@]}"; do + echo "========================================" + echo "Waiting for: $design (PID ${PIDS[$design]})" + if wait "${PIDS[$design]}"; then + echo "PASS: $design" + else + echo "FAIL: $design — NON-DETERMINISTIC" + FAIL=1 + fi + echo "--- Output ---" + cat "${LOGS[$design]}" + echo "" +done + +echo "========================================" +if [ $FAIL -eq 0 ]; then + echo "SWEEP RESULT: All ${#UNIQUE_DESIGNS[@]} designs are DETERMINISTIC" +else + echo "SWEEP RESULT: NON-DETERMINISM DETECTED in one or more designs" +fi +echo "========================================" +exit $FAIL diff --git a/flow/util/test_idempotency.sh b/flow/util/test_idempotency.sh new file mode 100755 index 0000000000..099db83e40 --- /dev/null +++ b/flow/util/test_idempotency.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# Test build idempotency for a given design by running the flow twice +# SEQUENTIALLY with different FLOW_VARIANTs and comparing per-stage hashes. +# +# Usage: ./util/test_idempotency.sh <platform/design> +# e.g.: ./util/test_idempotency.sh asap7/gcd +# ./util/test_idempotency.sh nangate45/swerv_wrapper +# +# Uses FLOW_VARIANT=idem_run1 and FLOW_VARIANT=idem_run2. +# Runs are sequential to avoid resource contention affecting results. +# +# Exit code: 0 if deterministic, 1 if non-deterministic, 2 on usage error + +set -euo pipefail + +if [ $# -lt 1 ]; then + echo "Usage: $0 <platform/design>" >&2 + exit 2 +fi + +DESIGN="$1" +DESIGN_CONFIG="./designs/${DESIGN}/config.mk" +PLATFORM=$(echo "$DESIGN" | cut -d/ -f1) +DESIGN_NAME=$(echo "$DESIGN" | cut -d/ -f2) + +if [ ! -f "$DESIGN_CONFIG" ]; then + echo "ERROR: Design config not found: $DESIGN_CONFIG" >&2 + exit 2 +fi + +MAKE="make DESIGN_CONFIG=$DESIGN_CONFIG EQUIVALENCE_CHECK=0" + +extract_hashes() { + local variant="$1" + python3 util/genElapsedTime.py -d "logs/${PLATFORM}/${DESIGN_NAME}/${variant}/" 2>/dev/null \ + | awk 'NF>=4 && $4 ~ /^[0-9a-f]/ {print $1, $4}' +} + +echo "Testing idempotency: $DESIGN (sequential runs)" +echo "================================" + +# Run 1 +echo "Run 1 (FLOW_VARIANT=idem_run1)..." +$MAKE FLOW_VARIANT=idem_run1 clean_all >/dev/null 2>&1 || true +$MAKE FLOW_VARIANT=idem_run1 finish 2>&1 | tail -1 + +# Run 2 +echo "Run 2 (FLOW_VARIANT=idem_run2)..." +$MAKE FLOW_VARIANT=idem_run2 clean_all >/dev/null 2>&1 || true +$MAKE FLOW_VARIANT=idem_run2 finish 2>&1 | tail -1 + +# Extract and compare +extract_hashes idem_run1 > /tmp/idempotency_run1_${PLATFORM}_${DESIGN_NAME}.txt +extract_hashes idem_run2 > /tmp/idempotency_run2_${PLATFORM}_${DESIGN_NAME}.txt + +echo "" +echo "Run 1 hashes:" +cat /tmp/idempotency_run1_${PLATFORM}_${DESIGN_NAME}.txt +echo "" +echo "Run 2 hashes:" +cat /tmp/idempotency_run2_${PLATFORM}_${DESIGN_NAME}.txt +echo "" + +if diff -q /tmp/idempotency_run1_${PLATFORM}_${DESIGN_NAME}.txt \ + /tmp/idempotency_run2_${PLATFORM}_${DESIGN_NAME}.txt >/dev/null 2>&1; then + echo "RESULT: $DESIGN is DETERMINISTIC (all hashes match)" + exit 0 +else + echo "RESULT: $DESIGN is NON-DETERMINISTIC!" + echo "" + echo "Diverging stages:" + diff /tmp/idempotency_run1_${PLATFORM}_${DESIGN_NAME}.txt \ + /tmp/idempotency_run2_${PLATFORM}_${DESIGN_NAME}.txt || true + exit 1 +fi