Files
SonicForgeStudio/native_bridge/debug/test_g2_stress.py
T

182 lines
7.5 KiB
Python

# G2.5 persistence-restart stress driver: N iterations of LOAD(Nexus ch5, EZkeys ch6)/PLAY
# -> kill daw_vst_bridge -> watchdog respawn -> verify: restore, preset preserved,
# LOAD-skip guard (G2.4), writeIndex advancing. Watch: no EXCEPTION/FAILED, bridge alive.
import ctypes, ctypes.wintypes as w, struct, subprocess, sys, os, time, json
from difflib import SequenceMatcher
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
APP_PID = int(sys.argv[1])
ITERS = int(sys.argv[2]) if len(sys.argv) > 2 else 3
SHM_NAME = f"SonicForge_DAW_IPC_{APP_PID}".encode()
APP_LOG = os.path.join(os.environ.get('APPDATA', '.'), 'SonicForgeDAW', 'logs', 'bridge.log')
SPAWN_LOG = os.path.join(os.environ.get('APPDATA', '.'), 'SonicForgeDAW', 'logs', 'spawn.log')
STATE = os.path.join(os.environ.get('APPDATA', '.'), 'SonicForgeDAW', 'state', 'bridge_state.json')
NEXUS = r"C:\Program Files\Common Files\VST3\Nexus.vst3"
EZKEYS = r"C:\Program Files\Common Files\VST3\Toontrack\EZkeys 2.vst3"
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.OpenFileMappingA.argtypes = [ctypes.wintypes.DWORD, w.BOOL, ctypes.c_char_p]
kernel32.OpenFileMappingA.restype = ctypes.c_void_p
kernel32.MapViewOfFile.argtypes = [ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, ctypes.c_size_t]
kernel32.MapViewOfFile.restype = ctypes.c_void_p
hMap = kernel32.OpenFileMappingA(0xF001F, False, SHM_NAME)
if not hMap:
print(f"OpenFileMapping failed err={ctypes.get_last_error()}"); sys.exit(1)
ptr = kernel32.MapViewOfFile(hMap, 0xF001F, 0, 0, 0)
print(f"SHM mapped ({SHM_NAME}) iters={ITERS}")
def w32(off, fmt, *args):
ctypes.memmove(ptr + off, struct.pack(fmt, *args), struct.calcsize(fmt))
def rd32(off):
return ctypes.c_uint32.from_address(ptr + off).value
def write_control(ctype, arg0, arg1, ch, path):
for i in range(8):
off = 2836 + i * 1040
if rd32(off) == 0:
w32(off, 'IIII', ctype, arg0, arg1, ch)
if path:
b = path.encode('utf-8')[:1023] + b'\x00'
ctypes.memmove(ptr + off + 16, b, len(b))
return i
raise RuntimeError("control queue full")
def push_controls(events):
for i in range(8):
w32(2836 + i * 1040, 'I', 0)
for (ctype, arg0, arg1, ch, path) in events:
write_control(ctype, arg0, arg1, ch, path)
w32(11156, 'I', len(events))
def log_lines(path=APP_LOG):
try:
with open(path, 'r', encoding='utf-8', errors='replace') as f:
return f.readlines()
except FileNotFoundError:
return []
def wait_log(pattern, timeout, since, path=APP_LOG):
end = time.time() + timeout
while time.time() < end:
lines = log_lines(path)
for i in range(since, len(lines)):
if pattern in lines[i]:
return lines[i]
time.sleep(0.2)
return None
def wait_load(ch, timeout, since):
# Either a real LOAD (plugin was different) or guard skip (same path already loaded).
return wait_log(f"instrument loaded ch={ch} type=0", timeout, since) or \
wait_log(f"LOAD skip ch={ch}", timeout, since)
def state():
if not os.path.exists(STATE): return None
return json.load(open(STATE, encoding='utf-8'))
def preset_of(ch, s=None):
s = s or state()
for e in (s or {}).get('instruments', []):
if e.get('channel') == ch:
return e.get('presetBase64', '') or ''
return ''
def bridge_pid():
out = subprocess.run(['powershell', '-Command',
'(Get-Process daw_vst_bridge -ErrorAction SilentlyContinue).Id'],
capture_output=True, text=True).stdout.strip().splitlines()
return [int(x) for x in out if x.strip().isdigit()]
def kill_bridge():
for pid in bridge_pid():
subprocess.run(['taskkill', '/PID', str(pid), '/F'],
capture_output=True, text=True)
time.sleep(1)
return bridge_pid()
def bad_since(since):
return [l for l in log_lines()[since:] if 'EXCEPTION' in l or 'FAILED' in l]
fails = 0
for it in range(ITERS):
print(f"--- iter {it} ---")
since = len(log_lines())
# 1. Ensure both instruments loaded (already loaded -> LOAD skip guard is fine).
push_controls([(2, 0, 0, 5, NEXUS), (2, 0, 0, 6, EZKEYS)])
m5 = wait_load(5, 20, since)
m6 = wait_load(6, 20, since)
ok = bool(m5) and bool(m6)
print(f"iter{it} LOAD pre-kill ch5={bool(m5)} ch6={bool(m6)} ({'skip' if 'skip' in (m5 or '') else 'real'} / {'skip' if 'skip' in (m6 or '') else 'real'})")
if not ok: fails += 1
time.sleep(2)
base5 = preset_of(5); base6 = preset_of(6)
print(f"iter{it} baseline preset ch5={len(base5)}B ch6={len(base6)}B")
if not base5 or not base6:
print(f"iter{it} baseline preset missing — abort"); sys.exit(1)
# 2. PLAY -> writeIndex advancing.
wi0 = rd32(4)
push_controls([(3, 1, 0, 0, "")])
if not wait_log("transport PLAY", 10, since):
print(f"iter{it} PLAY TIMEOUT"); fails += 1; continue
time.sleep(1.5)
wi1 = rd32(4)
ok = (wi1 - wi0) > 50
print(f"iter{it} PLAY writeIndex {wi0}->{wi1} delta={wi1-wi0} {'OK' if ok else 'STALLED'}")
if not ok: fails += 1
# 3. Kill bridge -> watchdog respawn.
ks = len(log_lines())
dead = kill_bridge()
print(f"iter{it} killed bridge (remaining: {dead})")
if dead:
print(f"iter{it} bridge still alive after kill"); fails += 1; continue
r = wait_log("[tauri] bridge restarted", 30, ks, APP_LOG)
print(f"iter{it} watchdog restart log: {'OK' if r else 'TIMEOUT'}")
if not r: fails += 1; continue
r5 = wait_log("restored ch=5", 30, ks)
r6 = wait_log("restored ch=6", 30, ks)
print(f"iter{it} restore ch5={bool(r5)} ch6={bool(r6)}")
if not (r5 and r6): fails += 1
# 4. LOAD-skip guard after respawn (explicit re-LOAD same path).
ls = len(log_lines())
push_controls([(2, 0, 0, 5, NEXUS), (2, 0, 0, 6, EZKEYS)])
m5b = wait_log("LOAD skip ch=5", 20, ls)
m6b = wait_log("LOAD skip ch=6", 20, ls)
print(f"iter{it} LOAD-skip post-respawn ch5={bool(m5b)} ch6={bool(m6b)}")
if not (m5b and m6b): fails += 1
# 5. Preset preserved after respawn (+ redundant LOAD).
# ch5 Nexus: byte-identical (stable). ch6 EZkeys: plugin bakes playhead pos
# into its own state (changes between NORMAL saves too) -> similarity check.
time.sleep(3)
s2 = state()
p5 = preset_of(5, s2); p6 = preset_of(6, s2)
ok5 = p5 == base5
ok6 = abs(len(p6) - len(base6)) <= 64 and SequenceMatcher(None, p6, base6).ratio() >= 0.7
okp = ok5 and ok6
print(f"iter{it} preset after respawn ch5={len(p5)}B(exact={ok5}) ch6={len(p6)}B(sim={round(SequenceMatcher(None, p6, base6).ratio(),3) if p6 else 0}) {'OK' if okp else 'CHANGED'}")
if not okp: fails += 1
# 6. writeIndex advancing after respawn (PLAY re-sent in case restored playing=false).
wi2 = rd32(4)
push_controls([(3, 1, 0, 0, "")])
time.sleep(2)
wi3 = rd32(4)
ok = (wi3 - wi2) > 50
print(f"iter{it} post-respawn writeIndex {wi2}->{wi3} delta={wi3-wi2} {'OK' if ok else 'STALLED'}")
if not ok: fails += 1
bad = bad_since(since)
if bad:
print(f"iter{it} EXCEPTION/FAILED: {bad[-2:]}"); fails += 1
# stop transport at end of iter so next iter starts clean
push_controls([(3, 0, 0, 0, "")])
time.sleep(1)
# final watch: bridge alive + no new bad
since = len(log_lines())
time.sleep(3)
bad = bad_since(since)
alive = bridge_pid()
print(f"bridge alive: {alive} (expect non-empty)") if alive else print("BRIDGE DEAD")
if not alive: fails += 1
print(f"G2.5 RESULT: {'PASS' if fails == 0 else f'FAIL ({fails} issues)'}")
sys.exit(0 if fails == 0 else 1)