Просмотр исходного кода

paint gate: --confirm-callgrind tells a failing cell's growth from glibc allocator noise (round 190tz, queue item 108)

Step 29's paint gate failed Patience / channel rack / playhead column by +1.18 % against step 27. Round 190tz measured it under
callgrind: LYNX's own code (with JUCE and HarfBuzz) moved by -80 instructions out of 51.8 M, the malloc / realloc / new counts were
equal, and all of the growth sat in glibc's _int_malloc / _int_free (heap state). The same binary against itself moved +0.96 %.

scripts/paint-gate.sh --confirm-callgrind re-checks each failing instruction cell with the new scripts/paint-callgrind.sh (that
view and frame kind, both builds, the gate's own --paintbench under callgrind; scripts/paint_cgself.py reads the profiles). A NOISE
verdict (own code moved <= 0.05 %, allocation calls equal) is listed as "NOISE (callgrind)" and the cell passes; REAL GROWTH /
REAL CHANGE, pixel changes and missing cells still fail. Without the flag the gate behaves as before. Needs valgrind (VG).
Ka1-S 3 дней назад
Родитель
Сommit
6ecbfe9da0
3 измененных файлов с 126 добавлено и 2 удалено
  1. 45 0
      scripts/paint-callgrind.sh
  2. 36 2
      scripts/paint-gate.sh
  3. 45 0
      scripts/paint_cgself.py

+ 45 - 0
scripts/paint-callgrind.sh

@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+# paint-callgrind.sh (round 190tz, queue item 108): tells a paint-gate cell's growth from allocator noise. Runs one view of one
+# project under callgrind for two LYNX builds (the gate's own --paintbench, every frame kind in the gate's order, so the caches are
+# in the same state), keeps the asked frame kind alone (a dump after each measure's sort), and compares the self cost per object
+# and per function plus the allocation call counts. LYNX's own code (with JUCE and HarfBuzz, linked into the binary) is
+# deterministic under callgrind to a few hundred instructions; glibc's malloc internals are not (heap state: the same binary
+# against itself moved a playhead column by +0.96 %). scripts/paint-gate.sh --confirm-callgrind runs this for each failing cell.
+# usage: scripts/paint-callgrind.sh <LYNX before> <LYNX after> <thief|patience|exoplanet|file> <view> <whole|cached|column> <out dir>
+# env: DISPLAY (a private Xvfb), VG (valgrind, default `valgrind`), OWN_LIMIT=0.05 (% of own self cost),
+#      QUIETWAIT (a command run before each build's run, e.g. a wait for another job's quiet window), FL_ROOT, LIVE_DEMO
+# verdict: NOISE when the binary's own self cost moved <= OWN_LIMIT % and malloc/realloc/calloc/new counts are equal; else
+# REAL GROWTH (own code dearer by more than OWN_LIMIT %) or REAL CHANGE (the code path changed, not dearer).
+set -u
+[ $# -ge 6 ] || { sed -n 2,12p "$0" >&2; exit 2; }
+B=$1; A=$2; P=$3; V=$4; K=$5; O=$6; mkdir -p "$O" || exit 2
+VG=${VG:-valgrind}; HERE=$(cd "$(dirname "$0")" && pwd)
+FL_ROOT=${FL_ROOT:-"/mnt/c/Program Files/Image-Line/FL Studio 2026"}
+LIVE_DEMO=${LIVE_DEMO:-"/mnt/c/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Lessons/Demo Songs/Chuck Sutton - Patience (Live 12 Suite Demo).als"}
+case $P in
+  thief) P="$FL_ROOT/Data/Demo projects/Demo songs/Ookay - Thief.flp" ;;
+  exoplanet) P="$FL_ROOT/Data/Demo projects/Demo songs/Eric Kauffmann & NrgMind - Exoplanet.flp" ;;
+  patience) P="$LIVE_DEMO" ;;
+esac
+case $K in whole) d=1 ;; cached) d=3 ;; column) d=5 ;; *) echo "frame kind: whole|cached|column" >&2; exit 2 ;; esac
+for side in before after; do
+  app=$B; [ $side = after ] && app=$A
+  [ -n "${QUIETWAIT:-}" ] && $QUIETWAIT
+  rm -rf "$O/prof-$side"
+  env LYNX_TEST_MODE=1 LYNX_PROFILE_DIR="$O/prof-$side" XDG_CONFIG_HOME="$O/xdg-$side" LYNX_PAINTBENCH_FRAMES=20 LYNX_PAINTBENCH_FRAMES_OUT=1 LYNX_PAINTBENCH_VIEWS="$V" \
+    timeout 1800 nice -n 10 "$VG" --tool=callgrind --collect-atstart=no \
+    --toggle-collect='*runPaintBench*lambda(juce::String const&, int)*' \
+    --dump-after='void std::__sort<__gnu_cxx::__normal_iterator<double*,*' \
+    --callgrind-out-file="$O/cg-$side.out" "$app" --paintbench "$P" "$O/paint-$side.txt" > "$O/cg-$side.log" 2>&1
+  [ -f "$O/cg-$side.out.$d" ] || { echo "paint-callgrind: $side gave no dump $d (see $O/cg-$side.log)" >&2; exit 2; }
+done
+python3 "$HERE/paint_cgself.py" "$O/cg-before.out.$d" "$O/cg-after.out.$d" 15 | tee "$O/diff.txt"
+python3 - "$HERE" "$O/cg-before.out.$d" "$O/cg-after.out.$d" "${OWN_LIMIT:-0.05}" <<'PY' | tee -a "$O/diff.txt"
+import sys; sys.path.insert(0, sys.argv[1]); import paint_cgself as cgself
+a, ca, oa = cgself.parse(sys.argv[2]); b, cb, ob = cgself.parse(sys.argv[3]); lim = float(sys.argv[4])
+own = lambda s, o: sum(v for f, v in s.items() if cgself.short(o.get(f)) == 'LYNX')
+oa_, ob_ = own(a, oa), own(b, ob); d = 100.0 * (ob_ - oa_) / max(1, oa_)
+same = all(ca[k] == cb[k] for k in ('malloc', 'realloc', 'calloc', 'operator new(unsigned long)', 'operator new[](unsigned long)'))
+ta, tb = sum(a.values()), sum(b.values())
+print(f"verdict: {'NOISE' if abs(d) <= lim and same else ('REAL GROWTH' if d > lim else 'REAL CHANGE')} (own code {d:+.4f} %, allocation calls {'equal' if same else 'DIFFERENT'}, all {100.0*(tb-ta)/max(1,ta):+.3f} %)")
+PY

+ 36 - 2
scripts/paint-gate.sh

@@ -11,7 +11,12 @@
 # per build. A build without per-frame output (before 190sz: 0.1.32 ... step 14) gives medians only: such a cell is compared on
 # both sides' medians, and the table says so. Results before and after this change are not directly comparable.
 #
-# usage: scripts/paint-gate.sh <LYNX before> <LYNX after> [results dir]
+# --confirm-callgrind (round 190tz, item 108): each failing instruction cell is re-checked under callgrind for both builds
+# (scripts/paint-callgrind.sh: that view and frame kind; LYNX's own self cost and the allocation call counts). A NOISE verdict
+# (own code moved <= 0.05 %, allocation calls equal: glibc's heap state) is listed as "NOISE (callgrind)" and passes; REAL GROWTH
+# / REAL CHANGE, pixels and missing cells stay FAIL. Needs valgrind (VG) and ~2 min per build per failing cell.
+#
+# usage: scripts/paint-gate.sh [--confirm-callgrind] <LYNX before> <LYNX after> [results dir]
 # env:
 #   PROJECTS="thief patience"   which projects (also: exoplanet, or a path to an .flp / .als / .lynx)
 #   RUNS=3                      runs per build and project (alternating before / after; at least 3)
@@ -22,7 +27,8 @@
 #   FL_ROOT, LIVE_DEMO          as scripts/perf-gate.sh
 # Needs a display for the app (DISPLAY, e.g. a private Xvfb); keep the results dir on a local disk.
 set -u
-[ $# -ge 2 ] || { sed -n 2,20p "$0" >&2; exit 2; }
+CONFIRM_CG=0; [ "${1:-}" = --confirm-callgrind ] && { CONFIRM_CG=1; shift; }
+[ $# -ge 2 ] || { sed -n 2,30p "$0" >&2; exit 2; }
 BEFORE=$1; AFTER=$2
 OUT=${3:-$(cd "$(dirname "$0")/.." && pwd)/build-paintgate/$(date +%Y%m%d-%H%M%S)}
 mkdir -p "$OUT" || exit 2
@@ -103,3 +109,31 @@ open(os.path.join(out, "summary-paint.md"), "w").write("\n".join(lines) + "\n")
 print("\n".join(lines))
 sys.exit(1 if failed else 0)
 EOF
+rc=$?
+[ $rc = 1 ] && [ $CONFIRM_CG = 1 ] || exit $rc
+# --confirm-callgrind: the failing cells again under callgrind; the summary's last line is rewritten
+last=$(tail -1 "$OUT/summary-paint.md"); left=(); noise=()
+cell_re='^([^ /]+) / (.+) / (whole frame|cached frame|playhead column) [+-][0-9.]+%$'
+while IFS= read -r item; do
+  [ -n "$item" ] || continue
+  if [[ $item =~ $cell_re ]]; then
+    name=${BASH_REMATCH[1]}; view=${BASH_REMATCH[2]}; kind=${BASH_REMATCH[3]}; proj=
+    for p in $PROJECTS; do [ "$(basename "$p" | tr -c 'A-Za-z0-9\n' '_')" = "$name" ] && proj=$p; done
+    case $kind in "whole frame") k=whole ;; "cached frame") k=cached ;; *) k=column ;; esac
+    dir=$OUT/callgrind-$name-$(echo "$view" | tr -c 'A-Za-z0-9\n' '_')-$k
+    verdict=
+    [ -n "$proj" ] && FL_ROOT="$FL_ROOT" LIVE_DEMO="$LIVE_DEMO" "$(dirname "$0")/paint-callgrind.sh" "$BEFORE" "$AFTER" "$proj" "$view" "$k" "$dir" > "$dir.log" 2>&1
+    verdict=$(grep '^verdict: ' "$dir/diff.txt" 2> /dev/null | tail -1 | sed 's/^verdict: //')
+    case $verdict in
+      NOISE*) noise+=("NOISE (callgrind) $item: $verdict") ;;
+      "") left+=("$item (callgrind run failed: $dir.log)") ;;
+      *) left+=("$item: $verdict") ;;
+    esac
+  else left+=("$item"); fi
+done < <(echo "$last" | sed 's/.*FAIL: //; s/; /\n/g')
+worst=${last%%; FAIL: *}
+{ for n in "${noise[@]}"; do echo "$n"; done
+  if [ ${#left[@]} = 0 ]; then echo "$worst; PASS (callgrind: ${#noise[@]} failing cell(s) were allocator noise)"
+  else echo "$worst; FAIL: $(IFS=';'; echo "${left[*]}" | sed 's/;/; /g')"; fi
+} | tee -a "$OUT/summary-paint.md"
+[ ${#left[@]} = 0 ]

+ 45 - 0
scripts/paint_cgself.py

@@ -0,0 +1,45 @@
+# paint_cgself.py (round 190tz, used by scripts/paint-callgrind.sh): self cost per (object, function) from a callgrind.out file, plus call counts
+import re,sys,collections
+def parse(p):
+    names={}; objs={}; selfc=collections.Counter(); calls=collections.Counter()
+    ob=fn=None; cfn=None; after_calls=False; fnobj={}
+    for l in open(p,errors='replace'):
+        l=l.rstrip('\n')
+        m=re.match(r'(ob|fl|fi|fe|cob|cfi|cfl)=\((\d+)\)(?: (.*))?$',l)
+        if m:
+            k,i,n=m.groups()
+            if k in('ob','cob'):
+                if n: objs[i]=n
+                if k=='ob': ob=objs[i]
+            continue
+        m=re.match(r'(c?fn)=\((\d+)\)(?: (.*))?$',l)
+        if m:
+            k,i,n=m.groups()
+            if n: names[i]=n
+            if k=='fn': fn=names[i]; fnobj[fn]=ob
+            else: cfn=names[i]
+            continue
+        m=re.match(r'calls=(\d+)',l)
+        if m: calls[cfn]+=int(m.group(1)); after_calls=True; continue
+        m=re.match(r'^[+-]?(?:\d+|\*|0x[0-9a-f]+)?\s+(\d+)$',l) or re.match(r'^(?:[+-]?\d+|\*)\s+(\d+)$',l)
+        if m and fn is not None:
+            if after_calls: after_calls=False
+            else: selfc[fn]+=int(m.group(1))
+    return selfc,calls,fnobj
+def short(o): o=(o or '???').split('/')[-1]; return 'LYNX' if o.startswith('LYNX') else o
+if __name__=='__main__':
+    a,ca,oa=parse(sys.argv[1]); b,cb,ob=parse(sys.argv[2]); n=int(sys.argv[3]) if len(sys.argv)>3 else 15
+    agg=collections.defaultdict(lambda:[0,0])
+    for f,v in a.items(): agg[short(oa.get(f))][0]+=v
+    for f,v in b.items(): agg[short(ob.get(f))][1]+=v
+    ta=sum(a.values()); tb=sum(b.values())
+    print(f"{'object (self cost)':28} {'before':>13} {'after':>13} {'diff':>11}")
+    for o,(x,y) in sorted(agg.items(),key=lambda r:-r[1][0]):
+        print(f"{o:28} {x:>13,} {y:>13,} {y-x:+11,} {100*(y-x)/max(1,x):+.3f}%")
+    print(f"{'TOTAL':28} {ta:>13,} {tb:>13,} {tb-ta:+11,} {100*(tb-ta)/max(1,ta):+.3f}%")
+    print("top functions by self-cost change:")
+    rows=sorted(((b.get(f,0)-a.get(f,0),f) for f in set(a)|set(b)),key=lambda r:-abs(r[0]))[:n]
+    for d,f in rows: print(f"  {a.get(f,0):>12,} {b.get(f,0):>12,} {d:+10,}  [{short((ob.get(f) or oa.get(f)))}] {f[:110]}")
+    print("call counts:", ', '.join(f"{k} {ca[k]:,}->{cb[k]:,}" for k in ['malloc','free','realloc','operator new(unsigned long)','pthread_mutex_lock']))
+    dc=[(cb[k]-ca[k],k) for k in set(ca)|set(cb) if ca[k]!=cb[k] and not k.startswith('0x')]
+    print("named functions with a different call count:", len(dc), dc[:8])