nyx/scripts/cached-cargo-test.sh

150 lines
4.5 KiB
Bash
Raw Permalink Normal View History

Prerelease cleanup (#46) * feat: Add const_bound_vars tracking to prevent false positives in ownership checks * feat: Introduce field interner and typed bounded vars for enhanced type tracking * feat: Add typed_call_receivers and typed_bounded_dto_fields for enhanced type tracking * feat: Centralize method name extraction with bare_method_name helper * feat: Implement Phase-6 hierarchy fan-out for runtime virtual dispatch * feat: Enhance C++ taint tracking with additional container operations and inline method resolution * feat: Introduce field-sensitive points-to analysis for enhanced resource tracking * feat: Implement Pointer-Phase 6 subscript handling for enhanced container analysis * test: Add comprehensive tests for JavaScript control flow constructs and lattice operations * docs: Update advanced analysis documentation with field-sensitive points-to and hierarchy fan-out details * test: Add comprehensive tests for lattice algebra laws and SSA edge cases * feat: Add destructured session user handling and safe user ID access patterns * feat: Implement row-population reverse-walk for enhanced authorization checks * feat: Enhance authorization checks with local alias chain for self-actor types * feat: Introduce ActiveRecord query safety checks and enhance snippet extraction * feat: Implement chained method call inner-gate rebinding for SSRF prevention * feat: Add observability and error modules, enhance debug functionality, and implement theme context * feat: Remove Auth Analysis page and update navigation to redirect to Explorer * feat: Optimize SSA lowering by sharing results between taint engine and artifact extractor * feat: Optimize SSA lowering by sharing results between taint engine and artifact extractor * feat: Reset path-safe-suppressed spans before lowering to maintain analysis integrity * fix(ssa): ungate debug_assert_bfs_ordering for release-tests build The helper at src/ssa/lower.rs was gated `#[cfg(debug_assertions)]` while the unit test at the bottom of the file was gated only `#[cfg(test)]`. Since `cfg(test)` is set in release builds with `--tests` but `cfg(debug_assertions)` is not, `cargo build --release --tests` failed with E0425. Removing the gate fixes the build; the body is `debug_assert!` only, so the helper is free in release. Also drop the gate at the call site to avoid a `dead_code` warning when the lib is built without `--tests`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(closure-capture): flip JS/TS fixtures to required-finding The JS and TS closure-capture fixtures pinned the old broken behaviour via `forbidden_findings: [{ "id_prefix": "taint-" }]`. The engine now correctly traces taint through the closure boundary (env source captured by an arrow function, sunk via `child_process.exec` inside the body), so the formerly-forbidden finding is a true positive. Match the Python sibling's shape — `required_findings` with `id_prefix` + `min_count` plus a small `noise_budget` — and rewrite the companion READMEs and the phase8_fragility_tests doc-comments from "known gap" to "regression guard". Verified: - cargo test --release --test phase8_fragility_tests → 8/8 pass - cargo test --release --lib bfs_assertion → pass - corpus benchmark F1 = 0.9976 (TP=205, FP=1, FN=0) — unchanged Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: Add OWASP mapping and baseline mutation hooks for enhanced security analysis * feat: Introduce health module and enhance health score computation with calibration tests * feat: Add expectations configuration and cleanup .gitignore for log files * feat: Implement theme selection and enhance settings panel for triage sync * feat: Suppress false positives for strcpy calls with literal sources in AST * feat: Update analyse_function_ssa to return body CFG for accurate analysis * feat: Add bug report and feature request templates for improved issue tracking * feat: removed dev scripts * feat: update README.md for clarity and consistency in fixture descriptions * feat: removed dev docs * feat: clean up error handling and UI elements for improved user experience * feat: adjust button sizes in HeaderBar for better UI consistency * feat: enhance taint analysis with additional context for sanitizer and taint findings * cargo fmt * prettier * refactor: simplify conditional checks and improve code readability in AST and screenshot capture scripts * feat: add script to frame PNG screenshots with brand gradient * feat: add fuzzing support with new targets and CI workflows * refactor: streamline match expressions and improve formatting in CLI and output handling * feat: enhance configuration display with detailed output options * feat: stage demo configuration for improved CLI screenshot output * feat: expose merge_configs function for user-configurable settings * refactor: simplify code structure and improve readability in config handling * refactor: improve descriptions for vulnerability patterns in various languages * feat: update MIT License section with additional usage details and copyright information * feat: update screenshots * refactor: update build process and paths for frontend assets * feat: add cross-file taint fuzzing target and supporting dictionary * refactor: clean up formatting and comments in fuzz configuration and example files * refactor: remove outdated comments and clean up CI configuration files * chore: update changelog dates and improve formatting in documentation * refactor: update Cargo.toml and CI configuration for improved packaging and build process * refactor: enhance quote-stripping logic to prevent panics and add regression tests --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 00:58:38 -04:00
#!/bin/bash
# Cached cargo test wrapper.
#
# Returns the cached output of a prior identical `cargo test` run when
# the source tree hasn't changed. Concurrent invocations with the same
# cache key serialize via a mkdir-based lock — only one cargo run
# actually executes; later callers wait, then return the cached result
# instantly.
#
# Usage:
# scripts/cached-cargo-test.sh [cargo-test-args...]
#
# Bypass:
# FORCE_CARGO=1 scripts/cached-cargo-test.sh ...
#
# When to use: full-suite invocations like
# scripts/cached-cargo-test.sh --lib
# scripts/cached-cargo-test.sh --tests
# scripts/cached-cargo-test.sh --test benchmark_test benchmark_evaluation -- --ignored --nocapture
#
# When NOT to use: narrow per-test runs like
# cargo test --test integration_tests rust_web_app
# cargo test some_function_name
# Those are fast on their own and would just clutter the cache.
set -uo pipefail
NYX_DIR="$(cd "$(dirname "$0")/.." && pwd)"
CACHE_DIR="${NYX_CARGO_CACHE_DIR:-/tmp/nyx-cargo-cache}"
LOCK_TIMEOUT_SECS=7200 # 2h max wait for a concurrent leader
POLL_INTERVAL_SECS=1
mkdir -p "$CACHE_DIR"
cd "$NYX_DIR"
# ---- portable sha256 ----
sha256_cmd() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$@"
else
# macOS ships `shasum`; -a 256 selects sha256 and outputs the same
# `<hash> <file>` format as sha256sum.
shasum -a 256 "$@"
fi
}
# ---- compute cache key ----
# Hash everything that could affect cargo-test outcomes. Filename of each
# input is included in the per-file sha256 line, so renames + additions +
# deletions all change the rolled-up hash. The [ -f ] filter drops
# deleted-but-still-indexed files so we don't error out on them.
compute_source_hash() {
{
git ls-files src tests benches 2>/dev/null
git ls-files --others --exclude-standard src tests benches 2>/dev/null
for f in Cargo.toml Cargo.lock build.rs rust-toolchain rust-toolchain.toml; do
[ -f "$f" ] && echo "$f"
done
} | sort -u | while IFS= read -r f; do
[ -f "$f" ] && sha256_cmd "$f"
done | sha256_cmd | awk '{print $1}'
}
# Hash the args verbatim. -separating with NUL bytes so "--lib" and
# "--li b" hash differently.
compute_args_hash() {
if [ "$#" -eq 0 ]; then
printf '' | sha256_cmd | awk '{print $1}'
else
printf '%s\0' "$@" | sha256_cmd | awk '{print $1}'
fi
}
# Hash env vars that can change build/test outcomes.
compute_env_hash() {
env | grep -E '^(RUST|CARGO|NYX)_' | LC_ALL=C sort \
| sha256_cmd | awk '{print $1}'
}
SOURCE_HASH=$(compute_source_hash)
ARGS_HASH=$(compute_args_hash "$@")
ENV_HASH=$(compute_env_hash)
KEY="${SOURCE_HASH:0:16}-${ARGS_HASH:0:8}-${ENV_HASH:0:8}"
LOG_FILE="$CACHE_DIR/$KEY.log"
RC_FILE="$CACHE_DIR/$KEY.rc"
LOCK_DIR="$CACHE_DIR/$KEY.lock.d"
# ---- bypass ----
if [ "${FORCE_CARGO:-0}" != "0" ]; then
echo "[cached-cargo-test] FORCE_CARGO=1 — bypassing cache" >&2
exec cargo test "$@"
fi
# ---- fast path: cache hit, no lock needed ----
if [ -f "$LOG_FILE" ] && [ -f "$RC_FILE" ]; then
RC=$(cat "$RC_FILE")
echo "[cached-cargo-test] cache hit (key $KEY, rc $RC) — source unchanged since prior run" >&2
cat "$LOG_FILE"
exit "$RC"
fi
# ---- slow path: acquire lock, double-check, run if leader ----
attempts=0
while true; do
if mkdir "$LOCK_DIR" 2>/dev/null; then
echo "$$" > "$LOCK_DIR/pid"
break
fi
# Stale-lock detection
if [ -f "$LOCK_DIR/pid" ]; then
OLD_PID=$(cat "$LOCK_DIR/pid" 2>/dev/null || echo "")
if [ -n "$OLD_PID" ] && ! kill -0 "$OLD_PID" 2>/dev/null; then
echo "[cached-cargo-test] reaping stale lock from dead pid $OLD_PID" >&2
rm -rf "$LOCK_DIR" 2>/dev/null
continue
fi
fi
if [ "$attempts" -eq 0 ]; then
echo "[cached-cargo-test] another invocation is running this same test set; waiting..." >&2
fi
attempts=$((attempts + 1))
if [ "$attempts" -gt "$LOCK_TIMEOUT_SECS" ]; then
echo "[cached-cargo-test] gave up waiting for lock after ${LOCK_TIMEOUT_SECS}s" >&2
exit 1
fi
sleep "$POLL_INTERVAL_SECS"
done
# Always release the lock on exit, even on failure
trap 'rm -rf "$LOCK_DIR" 2>/dev/null' EXIT
# Double-check: the leader may have populated the cache while we waited.
if [ -f "$LOG_FILE" ] && [ -f "$RC_FILE" ]; then
RC=$(cat "$RC_FILE")
echo "[cached-cargo-test] cache hit after waiting (concurrent leader populated cache, rc $RC)" >&2
cat "$LOG_FILE"
exit "$RC"
fi
# We're the leader — actually run cargo.
echo "[cached-cargo-test] cache miss (key $KEY) — running cargo test $*" >&2
cargo test "$@" 2>&1 | tee "$LOG_FILE"
RC="${PIPESTATUS[0]}"
echo "$RC" > "$RC_FILE"
exit "$RC"