diff --git a/rsm_rise/scripts/real/patchexport_checkenv_capdiff.sh b/rsm_rise/scripts/real/patchexport_checkenv_capdiff.sh new file mode 100644 index 0000000000000000000000000000000000000000..b05ebbeafa0145cd8c8ef12012a3a2e231b80c69 --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_checkenv_capdiff.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# rsm_real#5 -- the add/add resolution for scripts/check_env.py, measured as CAPABILITIES, not lines. +# +# Run 21 established that the 4 "hand-merge" files are two independently written versions, and that +# every gate I have run resolves them by taking the #6-#10 side whole. A line diff cannot say whether +# that loses anything that MATTERS: ours generalised the patch-completeness check to every repo, so a +# line present only on #11's side may be the same check in different words. The unit that matters is +# the capability the report prints. So RUN both implementations on the same tree and diff the report. +# +# check_env.py is by design a report that always exits 0, so both sides run anywhere; the MISSING lines +# are as informative as the PASS lines because the question is which capabilities are NAMED at all. +set -uo pipefail +source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh +SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run38} +PRS=${PRS:-"6 7 8 9 10"} +SC_PR=${SC_PR:-11} +export GIT_TERMINAL_PROMPT=0 +scrub(){ sed 's#https://[^@]*@#https://@#g'; } +hdr(){ echo; echo "=================== $* ==================="; } +mkdir -p "${SCRATCH:?}" || exit 1 +M=$SCRATCH/capdiff + +hdr "0 context" +echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH python=$(python3 -V 2>&1)" + +hdr "1 order-A merge, then the PUBLISHED resolution (take the #6-#10 side of the 4 add/add files)" +TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') +[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; } +rm -rf "${M:?}"; git init --quiet "$M" || exit 1 +printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config" +unset TOK +git -C "$M" fetch --quiet origin main 2>&1 | scrub +git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub +[ -f "$M/README.md" ] || { echo "CLONE FAILED"; exit 1; } +git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "capdiff gate" +for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub || exit 1; done +SC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR") +LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}') +[ -n "$LIVE" ] && [ "$LIVE" = "$SC_SHA" ] || { echo "STALENESS GUARD FAILED: sc=$(echo "$SC_SHA"|cut -c1-7) live=$(echo "${LIVE:-none}"|cut -c1-7)"; exit 2; } +echo "staleness guard: OK -- sc == live head of PR #$SC_PR ($(echo "$LIVE"|cut -c1-7))" +for n in $PRS; do git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1 || { echo "#$n UNEXPECTED CONFLICT"; exit 2; }; done +FIVE=$(git -C "$M" rev-parse HEAD) +git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1 +# keep BOTH sides of check_env.py before resolving, so each can be executed against the same tree +git -C "$M" show ":2:scripts/check_env.py" > "$SCRATCH/ours.py" || exit 2 +git -C "$M" show ":3:scripts/check_env.py" > "$SCRATCH/theirs.py" || exit 2 +pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py +[ -z "$(git -C "$M" diff --name-only --diff-filter=U)" ] || { echo "RESOLUTION INCOMPLETE"; exit 2; } +git -C "$M" commit --quiet -m "scratch: order-A merge + take-ours resolution" || true +echo "resolved tree = $(git -C "$M" rev-parse --short HEAD^{tree})" +echo "shipped scripts/check_env.py == ours side: $(cmp -s "$M/scripts/check_env.py" "$SCRATCH/ours.py" && echo YES || echo NO)" + +hdr "2 run BOTH implementations on the SAME resolved tree" +cp "$SCRATCH/ours.py" "$M/scripts/_ce_ours.py" +cp "$SCRATCH/theirs.py" "$M/scripts/_ce_theirs.py" +for s in ours theirs; do + echo "--- $s: python3 scripts/_ce_$s.py ---" + ( cd "$M" && python3 "scripts/_ce_$s.py" > "$SCRATCH/report_$s.txt" 2> "$SCRATCH/report_$s.err" ) + rc=$? + echo " rc=$rc stdout=$(wc -l < "$SCRATCH/report_$s.txt") lines stderr=$(wc -l < "$SCRATCH/report_$s.err") lines" + if [ "$rc" -ne 0 ]; then echo " !! did not exit 0 -- check_env.py is documented to always exit 0"; sed -n '1,20p' "$SCRATCH/report_$s.err" | sed 's/^/ /'; fi +done + +hdr "3 the reports, verbatim" +for s in ours theirs; do echo; echo "----- $s -----"; cat "$SCRATCH/report_$s.txt"; done + +hdr "4 CAPABILITY-NAME diff -- what the published resolution stops REPORTING" +python3 - "$SCRATCH/report_ours.txt" "$SCRATCH/report_theirs.txt" <<'PY' +import re, sys +def caps(p): + out=[] + for l in open(p,encoding='utf-8',errors='replace'): + m=re.match(r"^ (PASS|MISSING|n/a|INFO|)\s{2,}(\S.*?)\s{2,}", l) + if m and m.group(2).strip(): out.append((m.group(1).strip() or '-', m.group(2).strip())) + return out +o,t=caps(sys.argv[1]),caps(sys.argv[2]) +def norm(n): return re.sub(r"\s+"," ",n.lstrip('^ ').strip()).lower() +no={norm(n) for _,n in o}; nt={norm(n) for _,n in t} +print(f"capability lines: ours={len(o)} theirs={len(t)}") +print(f"\nREPORTED ONLY BY #11's SIDE -- lost when the resolution takes ours ({len(nt-no)}):") +for st,n in t: + if norm(n) in nt-no: print(f" [{st}] {n}") +print(f"\nREPORTED ONLY BY THE #6-#10 SIDE -- gained ({len(no-nt)}):") +for st,n in o: + if norm(n) in no-nt: print(f" [{st}] {n}") +print(f"\nin both ({len(no&nt)}): {sorted(no&nt)}") +print("\nVERDICT:", "take-ours loses NO named capability" if not (nt-no) + else f"take-ours stops reporting {len(nt-no)} capability name(s) listed above") +PY + +hdr "5 structural diff of the two docs (headings, not lines)" +for f in SETUP.md rise_stack/openpi/README.md; do + s=$(echo "$f" | tr '/' '_') + git -C "$M" show ":2:$f" > "$SCRATCH/$s.ours" 2>/dev/null || git -C "$M" show "$FIVE:$f" > "$SCRATCH/$s.ours" + git -C "$M" show "$SC_SHA:$f" > "$SCRATCH/$s.theirs" + echo; echo "--- $f headings ---" + echo " ours:"; grep -nE '^#+ ' "$SCRATCH/$s.ours" | sed 's/^/ /' + echo " theirs:"; grep -nE '^#+ ' "$SCRATCH/$s.theirs" | sed 's/^/ /' +done + +hdr "OVERALL rc=0" +exit 0 diff --git a/rsm_rise/scripts/real/patchexport_cibaseline_verify.sh b/rsm_rise/scripts/real/patchexport_cibaseline_verify.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e8acbf6ac083446ac0e292a06503859241786f8 --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_cibaseline_verify.sh @@ -0,0 +1,221 @@ +#!/usr/bin/env bash +# rsm_real#5 run 30 -- (a) prove the CI-baseline differ extraction is BEHAVIOUR-PRESERVING, and +# (b) re-measure the six-way merged tree now that #11's head moved to fdfa758f, which VENDORS four +# rsm_libero modules under rise_stack/rsm/ -- the directory #8 deletes and pe_trial_merge asserts +# gone. If #11's two new rsm_libero tests are in the merged workflow but their subject is deleted +# by #8, the merged tree fails tests neither side fails alone. That is a cross-PR interaction +# nobody has measured yet, and it is exactly what this differ exists to catch. +# +# The extraction is only worth doing if it cannot change what the gates saw, so the OLD inline block +# (copied verbatim out of run 28's setup_md gate) and the NEW pe_ci_baseline run against the SAME two +# trees and must agree on all four derived sets AND on the verdict -- not "both printed OK". +set -uo pipefail +source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh +SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run96} +VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci} +export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +scrub(){ sed 's#https://[^@]*@#https://@#g'; } +hdr(){ echo; echo "=================== $* ==================="; date -u; } +die(){ echo "VERIFY FAILED: $*"; exit 7; } +PY=$VENV/bin/python; [ -x "$PY" ] || die "no venv at $VENV" +export PE_PY=$PY +mkdir -p "${SCRATCH:?}" || exit 1 + +hdr "0 context" +echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$("$PY" -V 2>&1)" + +clone(){ + local W=$1 TOK + TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') + [ -n "$TOK" ] || die "no token" + rm -rf "${W:?}"; git init --quiet "$W" || exit 1 + printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$W/.git/config" + unset TOK + git -C "$W" fetch --quiet origin 2>&1 | scrub || die "fetch failed" + git -C "$W" config user.email noreply@anthropic.com + git -C "$W" config user.name "richardrl" +} + +hdr "1 live heads" +W=$SCRATCH/merged +clone "$W" +MAIN=$(git -C "$W" rev-parse origin/main) +echo " main = ${MAIN:0:8} $(git -C "$W" log -1 --format='%ad %an | %s' --date=iso origin/main)" +for n in 6 7 8 9 10 11; do + echo " #$n head = $(git -C "$W" ls-remote origin "refs/pull/$n/head" | cut -c1-8)" +done +SC_HEAD=$(git -C "$W" ls-remote origin "refs/pull/11/head" | awk '{print $1}') + +hdr "2 the full six-way trial merge (shared pe_trial_merge)" +pe_trial_merge "$W" origin/main || die "trial merge refused/failed" +echo " shape:"; printf '%s' "$PE_TRIAL_SHAPE" | sed 's/^/ /' +echo " merged head = ${PE_TRIAL_HEAD:0:12} tree = $(git -C "$W" rev-parse --short 'HEAD^{tree}')" +printf '%s' "$PE_TRIAL_SHAPE" | grep -q "^11 conflicted" || die "shape changed: #11 no longer conflicts -- re-derive the runbook" +for n in 6 7 8 9 10; do printf '%s' "$PE_TRIAL_SHAPE" | grep -q "^$n clean" || echo " NOTE #$n is no longer clean"; done + +hdr "3 what #11's new head brought, and what the merge does with it" +echo " #11 head = ${SC_HEAD:0:8}" +git -C "$W" fetch --quiet --force origin "pull/11/head:pr-11" 2>&1 | scrub +echo " files #11 adds under rise_stack/rsm/ :" +git -C "$W" ls-tree -r --name-only pr-11 -- rise_stack/rsm | sed 's/^/ /' +echo " the SAME paths on the merged tree (#8 deletes the directory):" +got=$(git -C "$W" ls-tree -r --name-only HEAD -- rise_stack/rsm) +echo "${got:- (absent -- as pe_trial_merge asserts)}" | sed 's/^/ /' +echo " #11's rsm_libero tests, present on the merged tree?" +for t in tests/test_rise_stack_rsm_libero_closure.py tests/test_rise_stack_rsm_libero_live.py; do + if git -C "$W" cat-file -e "HEAD:$t" 2>/dev/null; then echo " PRESENT $t"; else echo " absent $t"; fi +done +echo " named by the merged workflow?" +pe_ci_set "$W" | tr ' ' '\n' | grep -E 'rsm_libero' | sed 's/^/ /' || echo " (not named)" + +hdr "3b the models.py / test_deployment_models.py UNION on the merged tree" +# #11's new head rewrote the same dependency_report RSM branch that #8 did, so the runbook grew a +# semantic union (patchexport_models_union.py). Assert the merged file carries BOTH sides, not one. +for need in "which_scorer import resolve" "_available(\"rsm_libero\")" "has_dir or _available" "rise_stack/rsm_libero/UPSTREAM_COMMIT.txt"; do + grep -qF "$need" "$W/real/deployment/models.py" || die "the merged models.py lost: $need" + echo " OK merged models.py carries: $need" +done +[ "$(grep -cF '_available("rsm_libero")' "$W/real/deployment/models.py")" = 2 ] \ + || die "ours' installed-package test is not in BOTH branches of the merged models.py" +"$PY" -c "import ast,sys; ast.parse(open(sys.argv[1]).read())" "$W/real/deployment/models.py" || die "merged models.py does not parse" +"$PY" -c "import ast,sys; ast.parse(open(sys.argv[1]).read())" "$W/tests/test_deployment_models.py" || die "merged test file does not parse" +NT=$("$PY" - "$W/tests/test_deployment_models.py" <<'PYX' +import ast,sys +t=ast.parse(open(sys.argv[1]).read()) +names=[n.name for n in t.body if isinstance(n,ast.FunctionDef)] +assert len(names)==len(set(names)), "duplicate test definitions: %s"%names +print(len(names)) +PYX +) || die "the merged test file has duplicate definitions" +echo " merged test_deployment_models.py defines $NT unique tests" +for t in test_installed_rsm_libero_satisfies_the_scorer_source_requirement test_rsm_dependencies_are_satisfied_by_the_vendored_scorer; do + grep -q "def $t(" "$W/tests/test_deployment_models.py" || die "the merged test file lost $t" + echo " OK merged test file keeps $t" +done + +hdr "4 baseline worktree: main alone" +MW=$SCRATCH/mainonly +rm -rf "${MW:?}" +git -C "$W" worktree add --quiet --detach "$MW" origin/main 2>&1 | scrub || die "cannot check out main alone" +echo " main alone at $(git -C "$W" rev-parse --short origin/main) in $MW" + +hdr "5 sync the gate venv to the MERGED tree's requirements-deployment.txt (shared pe_ci_venv_sync)" +pe_ci_venv_sync "$W" || die "venv sync failed" + +# ---- the OLD inline block, copied verbatim from run 28's setup_md gate -------------------------- +# Only difference: `die` becomes a recorded verdict, so the two implementations can be compared on +# their outputs instead of one of them exiting the harness. +legacy_ci(){ + local W=$1 MW=$2 + L_RC=0; L_FILES=""; L_BASE=""; L_FAILED=""; L_NEW="" + ci_set(){ sed -n 's#^ *\(tests/test_[a-z_]*\.py\) *$#\1#p' "$1/.github/workflows/deployment.yml" | sort -u | tr '\n' ' '; } + run_ci(){ ( cd "$1" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider $2 2>&1 ); } + newfailures(){ comm -23 <(printf '%s\n' "$1" | sed '/^$/d' | sort -u) <(printf '%s\n' "$2" | sed '/^$/d' | sort -u); } + L_FILES=$(ci_set "$W"); [ -n "$L_FILES" ] || { L_RC=1; return; } + local f; for f in $L_FILES; do [ -e "$W/$f" ] || { L_RC=1; return; }; done + local MFILES BOUT OUT CTRL_NEW + MFILES=$(ci_set "$MW") + BOUT=$(run_ci "$MW" "$MFILES") + L_BASE=$(echo "$BOUT" | grep -E "^(FAILED|ERROR)" | awk '{print $2}' | sort -u) + OUT=$(run_ci "$W" "$L_FILES") + L_FAILED=$(echo "$OUT" | grep -E "^(FAILED|ERROR)" | awk '{print $2}' | sort -u) + CTRL_NEW=$(newfailures "$L_FAILED +tests/test_FABRICATED.py::nope" "$L_BASE") + echo "$CTRL_NEW" | grep -q FABRICATED || { L_RC=1; return; } + [ -z "$L_BASE" ] || { echo "$CTRL_NEW" | grep -qF "$(echo "$L_BASE" | head -1)" && { L_RC=1; return; }; } + L_NEW=$(newfailures "$L_FAILED" "$L_BASE") + [ -z "$L_NEW" ] || L_RC=1 +} + +hdr "6 the OLD inline block" +legacy_ci "$W" "$MW" +echo " legacy rc=$L_RC" +echo " legacy CI set : $L_FILES" +echo " legacy baseline: $(echo $L_BASE)" +echo " legacy merged : $(echo $L_FAILED)" +echo " legacy NEW : $(echo $L_NEW)" + +hdr "7 the NEW pe_ci_baseline, same two trees" +pe_ci_baseline "$W" "$MW"; N_RC=$? +echo " new rc=$N_RC" + +hdr "8 equivalence: all four derived sets and the verdict must match" +eq(){ [ "$(echo $2)" = "$(echo $3)" ] && echo " OK $1 identical" || die "$1 DIFFERS: legacy=[$(echo $2)] new=[$(echo $3)]"; } +eq "CI set" "$L_FILES" "$PE_CI_FILES" +eq "baseline" "$L_BASE" "$PE_CI_BASE" +eq "merged" "$L_FAILED" "$PE_CI_FAILED" +eq "NEW" "$L_NEW" "$PE_CI_NEW" +[ "$L_RC" = "$N_RC" ] || die "verdict differs: legacy rc=$L_RC new rc=$N_RC" +echo " OK verdict identical (rc=$N_RC)" + +hdr "9 controls on the NEW function -- it must not be inert" +# 9a a fabricated failing test, named by the workflow, must come back as a NEW failure. +CW=$SCRATCH/ctrl; rm -rf "${CW:?}" +cp -a "$W" "$CW" 2>/dev/null || die "cannot copy the merged tree" +rm -rf "$CW/.git/worktrees" 2>/dev/null +cat > "$CW/tests/test_pe_ctrl_planted.py" <<'PY' +def test_planted_must_be_reported_as_new(): + assert False, "planted by patchexport_cibaseline_verify.sh step 9a" +PY +"$PY" - "$CW/.github/workflows/deployment.yml" <<'PY' +import sys,re +p=sys.argv[1]; s=open(p).read() +m=re.search(r'^([ \t]+)tests/test_[a-z_]*\.py *$', s, re.M) +assert m, "no CI test line to anchor to" +s=s[:m.end()]+"\n"+m.group(1)+"tests/test_pe_ctrl_planted.py"+s[m.end():] +open(p,'w').write(s) +print(" anchored the planted test after", m.group(0).strip()) +PY +pe_ci_set "$CW" | tr ' ' '\n' | grep -q test_pe_ctrl_planted || die "control 9a did not land in the CI set" +if pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9a.log" 2>&1; then + sed 's/^/ /' "$SCRATCH/ctrl9a.log" | tail -20; die "control 9a: a planted failing test was NOT reported" +fi +grep -q test_pe_ctrl_planted <<<"$PE_CI_NEW" || { sed 's/^/ /' "$SCRATCH/ctrl9a.log" | tail -20; die "control 9a: refused, but not for the planted test"; } +echo " OK 9a planted failure reported as NEW: $(echo $PE_CI_NEW)" +# 9b a workflow naming a test file that does not exist must be a refusal, not a silent empty set. +rm -f "$CW/tests/test_pe_ctrl_planted.py" +pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9b.log" 2>&1 && die "control 9b: a missing named test file passed" +grep -q "which does not exist" "$SCRATCH/ctrl9b.log" || { tail -5 "$SCRATCH/ctrl9b.log" | sed 's/^/ /'; die "control 9b refused for the wrong reason"; } +echo " OK 9b workflow naming a missing test file is refused" +# 9c an empty/absent workflow must refuse rather than measure nothing. +: > "$CW/.github/workflows/deployment.yml" +pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9c.log" 2>&1 && die "control 9c: an empty workflow passed" +grep -q "no CI test set in the merged workflow" "$SCRATCH/ctrl9c.log" || { tail -5 "$SCRATCH/ctrl9c.log" | sed 's/^/ /'; die "control 9c refused for the wrong reason"; } +echo " OK 9c empty workflow is refused" +# 9d the union builder must refuse to run twice (its output carries the marker). +U=$SCRATCH/union; rm -rf "$U"; mkdir -p "$U" +git -C "$W" show "origin/main:real/deployment/models.py" > "$U/base" +git -C "$W" show "pr-11:real/deployment/models.py" > "$U/theirs" +git -C "$W" show "pr-8:real/deployment/models.py" > "$U/ours" 2>/dev/null || \ + git -C "$W" fetch --quiet --force origin pull/8/head:pr-8 2>&1 | scrub && git -C "$W" show "pr-8:real/deployment/models.py" > "$U/ours" +"$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/theirs" -o "$U/once" || die "control 9d: the union does not build from the live sides" +"$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/once" -o "$U/twice" 2>"$U/e9d" && die "control 9d: the union ran twice" +grep -q "does not run twice" "$U/e9d" || { cat "$U/e9d" | sed 's/^/ /'; die "control 9d refused for the wrong reason"; } +echo " OK 9d the union refuses to run on its own output" +# 9e a side missing its own contribution must be refused, not silently half-applied. +sed 's/from rise_stack.which_scorer import resolve as _resolve_scorer/pass # stripped by control 9e/' "$U/theirs" > "$U/theirs_stripped" +"$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/theirs_stripped" -o "$U/bad" 2>"$U/e9e" && die "control 9e: a stripped theirs was accepted" +grep -q "not the side this union was written for" "$U/e9e" || { cat "$U/e9e" | sed 's/^/ /'; die "control 9e refused for the wrong reason"; } +echo " OK 9e a side without its own contribution is refused" +# 9f a moved anchor must refuse rather than write a file that lost one side. +sed 's/"vendored", "env", "env-invalid"/"vendored", "env"/' "$U/theirs" > "$U/theirs_moved" +"$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/theirs_moved" -o "$U/bad2" 2>"$U/e9f" && die "control 9f: a moved anchor was accepted" +grep -q "anchor occurs 0 times" "$U/e9f" || { cat "$U/e9f" | sed 's/^/ /'; die "control 9f refused for the wrong reason"; } +echo " OK 9f a moved anchor is refused" +rm -rf "$CW" + +hdr "10 #11's negative-control ledger on the merged tree" +if [ -x "$W/tests/controls/run_guard_controls.sh" ]; then + ( cd "$W" && PYTHONPATH= PY=$PY bash tests/controls/run_guard_controls.sh 2>&1 ) | tail -25 + echo " controls ledger rc=${PIPESTATUS[0]}" +else + echo " no tests/controls/run_guard_controls.sh on the merged tree" +fi + +hdr "11 re-poll: did anything move while this ran?" +git -C "$W" fetch --quiet origin 2>&1 | scrub +echo " main now = $(git -C "$W" rev-parse --short origin/main) (was ${MAIN:0:7})" +echo " #11 now = $(git -C "$W" ls-remote origin refs/pull/11/head | cut -c1-8) (was ${SC_HEAD:0:8})" +git -C "$W" worktree remove --force "$MW" >/dev/null 2>&1 || true + +hdr "VERIFY OK" diff --git a/rsm_rise/scripts/real/patchexport_clean_checks.py b/rsm_rise/scripts/real/patchexport_clean_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..068a50ae8328aae7f900d41c1f4dbc6dcede4a5f --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_clean_checks.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +"""rsm_real#5 item 1 acceptance checks, run INSIDE the freshly built pinned openpi env. + +C1 provenance: what was actually imported, and from where (a hidden research checkout must not be + able to satisfy the test silently). +C2 get_config("pi05_cooking_stock") + data.create() with the training split file ABSENT. +C3 the real stock BC checkpoint through the deployment adapter (rise_stack.policies), on a real + replay observation, with the split file still absent -> candidates [1, 10, 10], finite. +""" +import argparse, dataclasses, hashlib, json, os, sys, time +from pathlib import Path + +import numpy as np + +RESEARCH = "/proj/dmfexp/zwhong/rsm_rise" +DATA = f"{RESEARCH}/data/real/rsm_cooking_v5" +PROMPT = "Follow the displayed cooking state sequence" + + +def md5(path, limit=None): + h = hashlib.md5() + with open(path, "rb") as fh: + while True: + b = fh.read(1 << 20) + if not b: + break + h.update(b) + if limit and fh.tell() > limit: + break + return h.hexdigest() + + +def real_frame(ep=0, i=0): + """One logged observation: both cameras + the 10-d absolute EE state, and the logged action.""" + import av, pyarrow.parquet as pq + tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{ep:06d}.parquet").to_pandas() + state = np.stack(tab["observation.state"].values).astype(np.float32)[i] + action = np.stack(tab["action"].values).astype(np.float32)[i: i + 10] + imgs = {} + for cam, key in (("global", "observation.images.global"), ("wrist", "observation.images.wrist")): + with av.open(f"{DATA}/videos/chunk-000/{key}/episode_{ep:06d}.mp4") as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + for k, fr in enumerate(c.decode(st)): + if k == i: + imgs[cam] = fr.to_ndarray(format="rgb24") + break + return {"images": imgs, "state": state}, action + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--repo", required=True) + ap.add_argument("--ckpt", required=True) + ap.add_argument("--missing-split", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--config", default="pi05_cooking_stock") + args = ap.parse_args() + rep = {"argv": sys.argv, "when": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + + print("=== C1 provenance ===") + print("sys.executable =", sys.executable) + print("sys.prefix =", sys.prefix) + for v in ("RISE_ROOT", "RSM_LIBERO_DIR", "PYTHONPATH", "HF_HUB_OFFLINE"): + print(f"env {v:16s}= {os.environ.get(v, '')!r}") + sys.path.insert(0, args.repo) + mods = {} + import openpi, jax, numpy + import openpi.training.config as C + for m in (openpi, jax, numpy): + mods[m.__name__] = {"file": str(Path(m.__file__).resolve()), + "version": getattr(m, "__version__", None)} + import rise_stack + mods["rise_stack"] = {"file": str(Path(rise_stack.__file__).resolve()), "version": None} + for k, v in mods.items(): + print(f"{k:12s} {v['version'] or '':10s} {v['file']}") + if v["file"].startswith(RESEARCH + "/third_party") or "/rsm_rise/env/" in v["file"]: + raise SystemExit(f"FATAL: {k} was imported from the research checkout: {v['file']}") + print("jax devices =", jax.devices()) + rep["modules"] = mods + rep["jax_devices"] = [str(d) for d in jax.devices()] + + print("\n=== C2 config + inference transforms with NO training split file ===") + missing = args.missing_split + print("missing split path:", missing, "exists =", Path(missing).exists()) + orig_get = C.get_config + + def split_free(name): + cfg = orig_get(name) + if hasattr(cfg.data, "split_json"): + cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=missing)) + return cfg + + C.get_config = split_free # every consumer, incl. the deployment adapter, now gets it + cfg = C.get_config(args.config) + print("data factory =", type(cfg.data).__name__, "split_json =", cfg.data.split_json) + t0 = time.time() + dc = cfg.data.create(cfg.assets_dirs, cfg.model) + print(f"data.create() OK in {time.time()-t0:.2f}s") + print(" episodes =", dc.episodes) + print(" episodes_required_from =", getattr(dc, "episodes_required_from", "")) + print(" norm_stats from config =", None if dc.norm_stats is None else sorted(dc.norm_stats), + f"(loaded from assets_base_dir={cfg.assets_base_dir!r}, which exists on THIS machine; on a " + "deployment machine it does not and _load_norm_stats logs 'skipping' -- either way " + "create_trained_policy takes the norm stats from /assets)") + print(" data_transforms.inputs =", [type(t).__name__ for t in dc.data_transforms.inputs]) + print(" data_transforms.outputs=", [type(t).__name__ for t in dc.data_transforms.outputs]) + print(" model_transforms.inputs=", [type(t).__name__ for t in dc.model_transforms.inputs]) + print(" action_sequence_keys =", dc.action_sequence_keys, "asset_id =", dc.asset_id) + rep["C2"] = {"episodes": dc.episodes, "episodes_required_from": getattr(dc, "episodes_required_from", None), + "data_inputs": [type(t).__name__ for t in dc.data_transforms.inputs], + "data_outputs": [type(t).__name__ for t in dc.data_transforms.outputs], + "model_inputs": [type(t).__name__ for t in dc.model_transforms.inputs], + "asset_id": dc.asset_id} + + print("\n=== C3 real stock BC checkpoint through the deployment adapter ===") + ck = Path(args.ckpt) + ident = {"path": str(ck), + "metadata_md5": md5(ck / "_CHECKPOINT_METADATA") if (ck / "_CHECKPOINT_METADATA").is_file() else None, + "norm_stats": None} + ns = list(ck.glob("assets/*/*/norm_stats.json")) + if ns: + ident["norm_stats"] = {"path": str(ns[0].relative_to(ck)), "md5": md5(ns[0]), + "bytes": ns[0].stat().st_size} + print("checkpoint identity:", json.dumps(ident, indent=1)) + rep["checkpoint"] = ident + + from rise_stack.policies import build # the deployment factory used by real/deployment/models.py + t0 = time.time() + # openpi owns its normalisation inside the checkpoint, so action_norm is None for this kind + pol = build(f"openpi:{args.config}:{args.ckpt}", None, seed=0, device="cpu", openpi_batch=0) + print(f"policy built in {time.time()-t0:.1f}s: kind={pol.kind} H={pol.H} D={pol.D} " + f"jax_device={getattr(pol, 'jax_device', None)} batch={pol.batch}") + print("loaded openpi module (after construction) =", sys.modules['openpi'].__file__) + + try: + obs, logged = real_frame() + src = "logged replay frame: episode 0, frame 0" + except Exception as e: + print("replay frame unavailable (%s: %s) -- falling back to a synthetic observation" % (type(e).__name__, e)) + obs = {"images": {"global": np.zeros((224, 224, 3), np.uint8), + "wrist": np.zeros((224, 224, 3), np.uint8)}, + "state": np.zeros(10, np.float32)} + logged, src = None, "synthetic zero observation" + print("observation:", src, {k: v.shape for k, v in obs["images"].items()}, "state", obs["state"].shape) + + t0 = time.time() + cand = pol.candidates(obs, 1, 10) + dt = time.time() - t0 + cand = np.asarray(cand) + print(f"candidates shape={cand.shape} dtype={cand.dtype} finite={bool(np.isfinite(cand).all())} " + f"in {dt:.1f}s ({dt*1000:.0f} ms, CPU)") + print("first action =", np.array2string(cand[0, 0], precision=6)) + if logged is not None: + print("logged action =", np.array2string(logged[0], precision=6)) + print("xyz L2 first action vs logged = %.3f cm" % (100 * float(np.linalg.norm(cand[0, 0, :3] - logged[0, :3])))) + print("per-dim min/max over the chunk:", + np.array2string(cand[0].min(0), precision=4), np.array2string(cand[0].max(0), precision=4)) + ok = cand.shape == (1, 10, 10) and bool(np.isfinite(cand).all()) + rep["C3"] = {"shape": list(cand.shape), "dtype": str(cand.dtype), "finite": bool(np.isfinite(cand).all()), + "latency_s": dt, "obs_source": src, "first_action": cand[0, 0].tolist(), + "logged_first_action": None if logged is None else logged[0].tolist(), + "xyz_l2_first_cm": None if logged is None else 100 * float(np.linalg.norm(cand[0, 0, :3] - logged[0, :3]))} + print("C3 VERDICT:", "PASS -- finite absolute actions [1, 10, 10]" if ok else "FAIL") + rep["ok"] = ok + Path(args.out).write_text(json.dumps(rep, indent=1, default=str)) + print("wrote", args.out) + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/patchexport_clean_inference_env.sh b/rsm_rise/scripts/real/patchexport_clean_inference_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..272a77fd3d95785b405913d9003e80b67e4d40bb --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_clean_inference_env.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# rsm_real#5 item 1, validation half: build the pinned openpi INFERENCE environment from scratch +# (uv venv, openpi's own uv.lock, network) with RISE_ROOT / RSM_LIBERO_DIR / PYTHONPATH scrubbed, then +# C1 report the actually loaded module paths and revisions +# C2 get_config("pi05_cooking_stock") + data.create() with NO training split file +# C3 the real stock BC checkpoint through the deployment adapter -> candidates [1,10,10], finite +# C4/C5 python -m real.deploy proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=true +# Nothing is written inside the rsm_rise tree or the rsm_real checkout. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run2} +SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # the PR worktree (or a github clone) +PIN=215abfb217dbac7d5f1273282331b9b1866c0479 +CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999} +PATCHED=${PATCHED:-} # optional: an already-patched openpi tree to copy instead of re-patching +UV=${UV:-/u/zwhong/.local/bin/uv} + +# ---- the scrub the issue asks for --------------------------------------------------------------- +unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE OPENPI_DATA_HOME HF_LEROBOT_HOME +export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false +export UV_CACHE_DIR=$SCRATCH/uv_cache +export OPENPI_DATA_HOME=$SCRATCH/openpi_assets +export HF_HOME=$SCRATCH/hf_home +export JAX_PLATFORMS=${JAX_PLATFORMS:-cpu} + +hdr(){ echo; echo "=================== $* ==================="; date -u; } +rc_all=0 +chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; } + +hdr "0 context + env scrub" +echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH src=$SRC ckpt=$CKPT" +for v in RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_HUB_OFFLINE; do echo " $v='${!v:-}'"; done +mkdir -p "${SCRATCH:?}" || exit 1 +cd "${SCRATCH:?}" || exit 1 + +hdr "1 the repo under test" +rm -rf "${SCRATCH:?}/rsm_real" +git clone --quiet "$SRC" "${SCRATCH:?}/rsm_real" || exit 1 +REPO=$SCRATCH/rsm_real +echo "rsm_real HEAD: $(git -C "$REPO" rev-parse HEAD) $(git -C "$REPO" log -1 --pretty=%s)" +ls "$REPO/rise_stack/openpi/" && md5sum "$REPO/rise_stack/openpi/rise_on_pi05.patch" + +hdr "2 upstream openpi at the recorded pin, then the repo's patch" +rm -rf "${SCRATCH:?}/openpi" +if git clone --quiet https://github.com/Physical-Intelligence/openpi.git "${SCRATCH:?}/openpi"; then + echo "cloned openpi from GitHub" +else + echo "GitHub clone failed; falling back to the local mirror $ROOT/third_party/openpi (shallow at the pin)" + git clone --quiet --no-local "$ROOT/third_party/openpi" "${SCRATCH:?}/openpi" \ + || git clone --quiet "$ROOT/third_party/openpi" "${SCRATCH:?}/openpi" || exit 1 +fi +git -C "$SCRATCH/openpi" checkout --quiet "$(cat "$REPO/rise_stack/openpi/UPSTREAM_COMMIT.txt" | head -1)" || exit 1 +echo "openpi HEAD: $(git -C "$SCRATCH/openpi" rev-parse HEAD)" +( cd "$SCRATCH/openpi" && git apply "$REPO/rise_stack/openpi/rise_on_pi05.patch" && echo "git apply: OK" \ + && git status --porcelain | sed -n '1,20p' ) +chk $? "apply the committed patch" + +hdr "3 the pinned inference environment (uv sync from openpi's own lock, then the deployment deps)" +( cd "$SCRATCH/openpi" && "$UV" sync --frozen 2>&1 | tail -6 ) +chk $? "uv sync" +VENV=$SCRATCH/openpi/.venv +PY=$VENV/bin/python +# rsm_real/requirements-deployment.txt pins numpy==2.2.6 but openpi caps numpy<2.0.0 -> install the +# deployment deps WITHOUT that pin (reported in the PR as a genuine incompatibility). +"$UV" pip install --python "$PY" hydra-core==1.3.2 omegaconf==2.3.0 PyYAML==6.0.2 h5py av pyarrow 2>&1 | tail -4 +chk $? "deployment deps" +"$PY" -c "import numpy;print('numpy',numpy.__version__)" +"$UV" pip freeze --python "$PY" > "$SCRATCH/pip_freeze.txt"; wc -l "$SCRATCH/pip_freeze.txt" +grep -E "^(jax|jaxlib|jax-cuda|flax|orbax|numpy|torch|transformers|lerobot|hydra-core|omegaconf|opencv|openpi)" "$SCRATCH/pip_freeze.txt" + +hdr "4 C1/C2/C3: provenance, split-free config construction, real checkpoint forward pass" +MISSING=$SCRATCH/no_such_dir/cooking_v5_split.json +"$PY" "$ROOT/scripts/real/patchexport_clean_checks.py" --repo "$REPO" --ckpt "$CKPT" \ + --missing-split "$MISSING" --out "$SCRATCH/clean_checks.json" +chk $? "clean checks" + +hdr "5 C4: real.deploy --print-config (openpi proposer, vanilla_bc, hardware-free)" +( cd "$REPO" && "$PY" -m real.deploy --print-config proposer=openpi real.algorithm=vanilla_bc \ + real.simulate=true real.dry_run=true real.device=cpu "real.proposer.checkpoint=$CKPT" 2>&1 | sed -n '1,60p' ) +chk $? "real.deploy --print-config" + +hdr "6 C5: real.deploy run, hardware-free (SyntheticEnvironment), 1 episode" +( cd "$REPO" && timeout 3000 "$PY" -m real.deploy proposer=openpi real.algorithm=vanilla_bc \ + real.simulate=true real.dry_run=true real.device=cpu "real.proposer.checkpoint=$CKPT" \ + real.proposer.batch_size=0 real.evaluation.episodes=1 real.evaluation.max_episode_seconds=20 \ + real.evaluation.auto_start=true 2>&1 | tail -60 ) +chk $? "real.deploy simulate+dry_run" + +hdr "done" +echo "OVERALL rc=$rc_all" +exit $rc_all diff --git a/rsm_rise/scripts/real/patchexport_deploy_checks.sh b/rsm_rise/scripts/real/patchexport_deploy_checks.sh new file mode 100644 index 0000000000000000000000000000000000000000..7c28661fcfd66804f39cf7bfd2557a0431f3d2fc --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_deploy_checks.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# rsm_real#5 item 1, deployment-entrypoint half. Reuses the clean env built by +# patchexport_clean_inference_env.sh (default: run2b) -- no rebuild, no network. +# C5b real.deploy with proposer=openpi, vanilla_bc, simulate+dry_run, split file forced ABSENT +# C6 the same with dry_run=false, so recording + latency accounting actually run +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run2b} +CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999} +SECS=${SECS:-90} +PY=$SCRATCH/openpi/.venv/bin/python +REPO=$SCRATCH/rsm_real +unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE +export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false +export OPENPI_DATA_HOME=$SCRATCH/openpi_assets HF_HOME=$SCRATCH/hf_home +export UV_CACHE_DIR=$SCRATCH/uv_cache JAX_PLATFORMS=${JAX_PLATFORMS:-cpu} +hdr(){ echo; echo "=================== $* ==================="; date -u; } +rc_all=0 +chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; } + +hdr "0 context (reusing the prebuilt env; nothing is installed here)" +echo "host=$(hostname) job=${LSB_JOBID:-none} py=$PY repo=$REPO" +test -x "$PY" || { echo "no prebuilt env at $PY -- run patchexport_clean_inference_env.sh first"; exit 2; } +git -C "$REPO" pull --quiet 2>&1 | tail -2 +echo "repo HEAD: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)" +"$PY" -c "import sys,openpi,jax;print('python',sys.executable);print('openpi',openpi.__file__);print('jax',jax.__version__,jax.devices())" + +hdr "1 C5b real.deploy, openpi proposer, vanilla_bc, simulate+dry_run, SPLIT FILE ABSENT" +( cd "$REPO" && timeout 1200 "$PY" "$ROOT/scripts/real/patchexport_deploy_nosplit.py" \ + proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=true real.device=cpu \ + "real.proposer.checkpoint=$CKPT" real.proposer.batch_size=0 real.evaluation.episodes=1 \ + "real.evaluation.max_episode_seconds=$SECS" real.evaluation.auto_start=true 2>&1 | tail -40 ) +chk $? "C5b deploy dry_run" + +hdr "2 C6 the same with dry_run=false: recording, provenance and latency accounting" +( cd "$REPO" && timeout 1800 "$PY" "$ROOT/scripts/real/patchexport_deploy_nosplit.py" \ + proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=false real.device=cpu \ + "real.proposer.checkpoint=$CKPT" real.proposer.batch_size=0 real.evaluation.episodes=1 \ + "real.evaluation.max_episode_seconds=$SECS" real.evaluation.auto_start=true \ + real.evaluation.run_name=pxclean_openpi_smoke 2>&1 | tail -50 ) +chk $? "C6 deploy with recording" + +hdr "3 what C6 wrote" +find "$REPO/outputs" -maxdepth 4 -newermt "-40 minutes" | head -30 +for f in $(find "$REPO/outputs" -name "*.json" -newermt "-40 minutes" | head -4); do + echo "--- $f ---"; head -c 3000 "$f"; echo; done + +hdr "done" +echo "OVERALL rc=$rc_all" +exit $rc_all diff --git a/rsm_rise/scripts/real/patchexport_deploy_nosplit.py b/rsm_rise/scripts/real/patchexport_deploy_nosplit.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c5bc291c034eb1e27e99d0b18d0e656d09a372 --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_deploy_nosplit.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +"""Run `python -m real.deploy` with the openpi cooking config's training split file forced ABSENT. + +`real.deploy` builds the proposer through openpi's `create_trained_policy`, which builds the data +config; this wrapper points `split_json` at a path that does not exist before that happens, so the +deployment entry point is exercised exactly as it would be on a machine that has no training split. +Usage: patchexport_deploy_nosplit.py (run with cwd = the repo root) +""" +import dataclasses +import os +import sys +from pathlib import Path + +# this script lives outside the repo, so sys.path[0] is its own directory; the repo root is the cwd +sys.path.insert(0, os.getcwd()) + +MISSING = "/nonexistent-deployment-machine/cooking_v5_split.json" + + +def main() -> int: + assert not Path(MISSING).exists(), MISSING + import openpi.training.config as C + + original = C.get_config + + def split_free(name): + cfg = original(name) + if hasattr(cfg.data, "split_json"): + cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=MISSING)) + return cfg + + C.get_config = split_free + print(f"[nosplit] openpi.training.config.get_config patched: split_json -> {MISSING} " + f"(exists={Path(MISSING).exists()})", flush=True) + from real.deploy import main as deploy_main + deploy_main(sys.argv[1:]) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/rsm_rise/scripts/real/patchexport_deployment_yml_union.py b/rsm_rise/scripts/real/patchexport_deployment_yml_union.py new file mode 100644 index 0000000000000000000000000000000000000000..37daa246684b6ef289dbf6ac796c8608527441b8 --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_deployment_yml_union.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""rsm_real#5 run 26 -- the SEVENTH entry in the merge runbook: .github/workflows/deployment.yml. + +It appeared the moment the owner pushed `dc2d40d`/`54c054e` to main (2026-09-24 19:03-19:11Z). Until +then the workflow was one-sided and merged silently. Now BOTH sides edit it: + + main (owner) +'requirements/**', +'pyproject.toml' in both path filters; + +`pip install --no-deps -e .`; +test_deployment_actions.py, +test_deployment_startup.py + #11 (scaffold) +'tests/controls/**', +'tests/test_rise_stack_*.py', +'QUICKSTART.md', +'SETUP.md'; + +5 rise_stack test files; +a whole `guard-negative-controls` job + +The two sets are DISJOINT -- nobody changed a line the other also changed; they appended at the same +anchors, which is all git needs to refuse. So the resolution is a UNION, and unlike the other six +runbook entries it is NOT take-ours: dropping either side silently switches CI checks off. This +builds that union deterministically and refuses to emit one it cannot verify. + + patchexport_deployment_yml_union.py [-o out.yml] + +`ours` is the five-way side (which carries main's edits); `theirs` is #11. +""" +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +PATH_ITEM = re.compile(r"^(\s*)- '([^']+)'\s*$") +TEST_ITEM = re.compile(r"^(\s*)(tests/\S+\.py)\s*$") + + +def path_filter_items(text: str) -> list[str]: + return [m.group(2) for m in (PATH_ITEM.match(l) for l in text.splitlines()) if m] + + +def test_items(text: str) -> list[str]: + return [m.group(2) for m in (TEST_ITEM.match(l) for l in text.splitlines()) if m] + + +def jobs(text: str) -> list[str]: + out, in_jobs = [], False + for line in text.splitlines(): + if line.rstrip() == "jobs:": + in_jobs = True + continue + if in_jobs: + m = re.match(r"^ ([A-Za-z0-9_-]+):\s*$", line) + if m: + out.append(m.group(1)) + elif line and not line.startswith(" "): + in_jobs = False + return out + + +def build_union(base: str, ours: str, theirs: str) -> str: + """Start from THEIRS (it is the superset in structure -- it adds a whole job) and re-apply the + additions main made that theirs does not have. Each insertion is anchored on a line that must + occur an exact number of times, so a drifted input fails instead of producing a plausible file.""" + # dedupe, ORDER-PRESERVING. main's workflow repeats each new path in BOTH of its path filters, so + # the raw difference lists every addition twice; the block is then inserted at each of the two + # anchors, which multiplied it to four. Caught in run 27 by diffing this builder's output against + # #11's own independent resolution (9fefc57): 93 lines vs 89, exactly the four duplicates. + def uniq(xs): + return list(dict.fromkeys(xs)) + add_paths = uniq(p for p in path_filter_items(ours) if p not in path_filter_items(base)) + add_tests = uniq(t for t in test_items(ours) if t not in test_items(base)) + add_steps = [l for l in ours.splitlines() + if l.strip().startswith("python -m pip install") and l not in base.splitlines()] + out = theirs + # 1. path filters: main's new entries go just before the workflow's own path, in BOTH triggers. + anchor = " - '.github/workflows/deployment.yml'" + n = out.count(anchor) + if n != 2: + raise SystemExit(f"anchor {anchor!r} occurs {n} times, expected 2") + missing = [p for p in add_paths if p not in path_filter_items(theirs)] + if missing: + block = "".join(f" - '{p}'\n" for p in missing) + out = out.replace(anchor + "\n", block + anchor + "\n") + # 2. the editable install, before the torch line it must precede. + torch = [l for l in out.splitlines() if "download.pytorch.org" in l] + if len(torch) != 1: + raise SystemExit(f"expected exactly 1 torch install line, found {len(torch)}") + for step in add_steps: + if step not in out: + out = out.replace(torch[0] + "\n", step + "\n" + torch[0] + "\n") + # 3. main's new deployment tests, appended to the deployment pytest invocation. They must land + # in the SAME list as the other test_deployment_*.py entries, not in the rise_stack list. + anchor_t = [l for l in out.splitlines() if l.strip() == "tests/test_deployment_runtime.py"] + if len(anchor_t) != 1: + raise SystemExit("expected exactly 1 tests/test_deployment_runtime.py line") + add_t = [t for t in add_tests if t not in test_items(theirs)] + if add_t: + block = "".join(f"{anchor_t[0][:len(anchor_t[0]) - len(anchor_t[0].lstrip())]}{t}\n" for t in add_t) + out = out.replace(anchor_t[0] + "\n", anchor_t[0] + "\n" + block) + return out + + +def verify(base: str, ours: str, theirs: str, union: str) -> int: + bad = 0 + + def check(label, ok, detail=""): + nonlocal bad + print(f" {'OK ' if ok else 'FAIL'} {label}{(' -- ' + detail) if detail else ''}") + bad += 0 if ok else 1 + + up, tp, op = set(path_filter_items(union)), set(path_filter_items(theirs)), set(path_filter_items(ours)) + check("path filters are a superset of #11's", tp <= up, f"missing {sorted(tp - up)}") + check("path filters are a superset of main's", op <= up, f"missing {sorted(op - up)}") + ut, tt, ot = set(test_items(union)), set(test_items(theirs)), set(test_items(ours)) + check("every test file #11 runs still runs", tt <= ut, f"lost {sorted(tt - ut)}") + check("every test file main runs still runs", ot <= ut, f"lost {sorted(ot - ut)}") + check("no test file invented", ut <= (tt | ot), f"extra {sorted(ut - tt - ot)}") + uj, tj, oj = set(jobs(union)), set(jobs(theirs)), set(jobs(ours)) + check("every job from both sides is present", (tj | oj) <= uj, f"missing {sorted((tj | oj) - uj)}") + check("no conflict markers", not re.search(r"^(<<<<<<<|=======|>>>>>>>)", union, re.M)) + # Every check above is a SET comparison, which is exactly why the duplicate-entry defect this + # builder had survived a run that printed UNION OK. A repeated glob is harmless to GitHub and + # invisible to a subset test, so it needs its own check, per filter block and not globally (the + # same path legitimately appears in both the pull_request and the push filter). + dups = [] + for block in re.split(r"^\s*(?:pull_request|push|workflow_dispatch):\s*$", union, flags=re.M)[1:]: + items = path_filter_items(block) + dups += [i for i in set(items) if items.count(i) > 1] + check("no path filter entry repeats within one filter", not dups, f"repeated {sorted(set(dups))}") + try: + import yaml # noqa + d = yaml.safe_load(union) + check("parses as YAML", isinstance(d, dict) and "jobs" in d) + check("every job has steps", all("steps" in v for v in d["jobs"].values())) + except ImportError: + print(" SKIP yaml not importable -- structural checks only") + # nothing may be LOST relative to either side: every non-blank line of each side survives + for label, side in (("main", ours), ("#11", theirs)): + lost = [l for l in side.splitlines() if l.strip() and l not in union.splitlines()] + check(f"no line of {label}'s workflow dropped", not lost, f"{len(lost)} line(s): {lost[:3]}") + return bad + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("base"); ap.add_argument("ours"); ap.add_argument("theirs") + ap.add_argument("-o", "--out") + # run 27: #11 resolved this conflict on its own branch (merge 9fefc57), so the question stopped + # being "what union would I build" and became "does THEIR file satisfy the same invariants". + # Same checks, a candidate supplied instead of constructed -- otherwise a resolution that quietly + # took one side is indistinguishable from a real union in any log. + ap.add_argument("--verify-only", metavar="CANDIDATE", + help="verify an existing resolved workflow instead of building the union") + a = ap.parse_args() + base, ours, theirs = (Path(p).read_text() for p in (a.base, a.ours, a.theirs)) + if a.verify_only: + union = Path(a.verify_only).read_text() + print(f"candidate = {a.verify_only}, {len(union.splitlines())} lines " + f"(base {len(base.splitlines())}, main {len(ours.splitlines())}, #11 {len(theirs.splitlines())})") + bad = verify(base, ours, theirs, union) + print("CANDIDATE OK" if not bad else f"CANDIDATE REFUSED: {bad} check(s) failed") + return 0 if not bad else 3 + union = build_union(base, ours, theirs) + print(f"union = {len(union.splitlines())} lines " + f"(base {len(base.splitlines())}, main {len(ours.splitlines())}, #11 {len(theirs.splitlines())})") + bad = verify(base, ours, theirs, union) + if a.out and not bad: + Path(a.out).write_text(union) + print(f"wrote {a.out}") + print("UNION OK" if not bad else f"UNION REFUSED: {bad} check(s) failed") + return 0 if not bad else 3 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/real/patchexport_dotted_selector.sh b/rsm_rise/scripts/real/patchexport_dotted_selector.sh new file mode 100644 index 0000000000000000000000000000000000000000..c4f14e2a36cc8e8b81d9b80548f3ee5fc203cba7 --- /dev/null +++ b/rsm_rise/scripts/real/patchexport_dotted_selector.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# rsm_real#5 -- run 27. ATTRIBUTE THE ONE FAILING TEST ON THE MERGED TREE. +# +# 1904471 (citest2, the first merged-tree pytest run on the owner's new main dc2d40d/54c054e) reported +# H0 #11 head 163 PASSED 2 SKIPPED 0 failed +# R0 resolved 1 FAILED 197 PASSED 4 SKIPPED +# and named the one that moved: +# tests/test_deployment_config.py::test_dotted_selector_loads_algorithm_components[rsm-rsm-128] +# PASSED -> FAILED +# That is a RED merged CI, and the outcome table does not say why: the detail script records verdicts, +# not tracebacks. Two questions, and neither may be answered by reading a diff: +# (a) WHAT is the assertion? -> run the single node with --tb=long and print it verbatim. +# (b) WHOSE change causes it? -> run that same node on main alone, on #11's live head alone, and on +# main + each of #6..#11 INDIVIDUALLY, then on the full resolved six-way. A test that fails on +# main alone is the owner's and I must tell him; one that fails only in combination is ours. +# Both suspects are measured, not assumed: #8 rewrites real/deployment/models.py's rsm branch, and the +# published resolution runs `git rm -rf rise_stack/rsm` -- deleting the vendored scorer that main's +# own tests may still name by dotted path. If the single-PR sweep is clean and only the resolved tree +# fails, the resolution itself is the cause, so the tree is re-tested with the deletion put back. +# Read-only w.r.t. every real repo: fetches from GitHub, works only inside SCRATCH, pushes nothing. +set -uo pipefail +source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh +SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run89} +VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci} +NODE='tests/test_deployment_config.py::test_dotted_selector_loads_algorithm_components' +PRS="6 7 8 9 10" +SC_PR=11 +export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +scrub(){ sed 's#https://[^@]*@#https://@#g'; } +hdr(){ echo; echo "=================== $* ==================="; date -u; } +rc_all=0 +PY=$VENV/bin/python +[ -x "$PY" ] || { echo "no venv at $VENV"; exit 2; } +mkdir -p "${SCRATCH:?}" || exit 1 +M=$SCRATCH/mt + +hdr "0 context" +echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH venv=$VENV" +echo "node=$NODE" + +hdr "1 clone + fetch every side" +TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') +[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; } +rm -rf "${M:?}"; git init --quiet "$M" || exit 1 +printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config" +unset TOK +git -C "$M" fetch --quiet origin main 2>&1 | scrub +git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub +git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "dotted-selector attribution" +for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub; done +MAIN=$(git -C "$M" rev-parse main) +echo " main = $(echo "$MAIN" | cut -c1-7) $(git -C "$M" log -1 --format=%s main)" +for n in $PRS $SC_PR; do + L=$(git -C "$M" ls-remote origin "refs/pull/$n/head" 2>/dev/null | awk '{print $1}') + H=$(git -C "$M" rev-parse "pr-$n") + S=same; [ "$L" = "$H" ] || S="STALE(live=$(echo "$L"|cut -c1-7))" + echo " #$n = $(echo "$H" | cut -c1-7) $S" +done + +# run1