#!/usr/bin/env python3
"""Paired, resumable causal-state/overlap decoder experiment; no package patches."""
from __future__ import annotations

import argparse
import csv
import gc
import hashlib
import importlib.metadata
import importlib.util
import json
import math
import shutil
import sys
import time
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import soundfile as sf
import torch
import torchaudio

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / 'scripts'))
from backend.codecs import get_codec, unload_codecs
from scripts.benchmark_decoder_degradation import OUT, METRICS, Spectra, decode, write_csv, SEED
from scripts.benchmark_decoder_overlap_add import taper, window_geometry
from build_decoder_listening_report import export_audio, digest

MODELS = ['fish-dac-s2', 'qwen3-tts-tokenizer-12hz']
WIDTHS = [1, 2, 4, 8, 12, 16, 24, 32, 48, 64]
STATE_LABELS = {'none': 'Reset all state', 'kv-only': 'KV only',
                'conv-only': 'Convolution only', 'all': 'KV + convolution',
                'replay32': 'Replay 32 frames (not KV)'}
METHODS = [{'id': mode+'-'+assembly, 'label': label+' · '+('hard joins' if assembly=='hard' else 'Hann 50%'),
            'state_mode': mode, 'assembly': assembly}
           for mode, label in STATE_LABELS.items() for assembly in ['hard', 'hann50']]


def helper_for(model, mid, mode):
    if mode in ['none', 'replay32']:
        return None
    if mid == 'fish-dac-s2':
        from scripts.decoder_fish_state import FishStateDecoder
        return FishStateDecoder(model, mode=mode)
    from scripts.decoder_qwen_state import QwenStateDecoder
    return QwenStateDecoder(model.decoder)


def state_info(helper, mid, mode):
    if helper is None:
        return {'state_tensor_bytes': 0, 'kv_tensor_bytes': 0, 'conv_tensor_bytes': 0}
    if mid == 'fish-dac-s2':
        info = {'state_tensor_bytes': helper.state_bytes(), 'committed_frames': helper.cursor}
        def size(value):
            if torch.is_tensor(value): return value.numel()*value.element_size()
            if isinstance(value, dict): return sum(size(v) for v in value.values())
            return 0
        info['kv_tensor_bytes'] = sum(size(v) for k,v in helper.state.items() if k.startswith('kv.'))
        info['conv_tensor_bytes'] = info['state_tensor_bytes'] - info['kv_tensor_bytes']
        return info
    info = helper.state_info()
    # Qwen stores scratch state within a window even when its boundary state is
    # reset; report only components deliberately retained across windows.
    if mode == 'kv-only': info['conv_tensor_bytes'] = 0
    if mode == 'conv-only': info['kv_tensor_bytes'] = 0
    info['state_tensor_bytes'] = info['kv_tensor_bytes'] + info['conv_tensor_bytes']
    return info


@torch.inference_mode()
def reconstruct(model, codes, width, mid, spec, method):
    """One sequential stream. Return audio and actual implementation work."""
    mode, assembly = method['state_mode'], method['assembly']
    stride = width if assembly == 'hard' else max(1, math.floor(width*.5+.5))
    geometry = window_geometry(codes.shape[-1], width, stride)
    helper = helper_for(model, mid, mode)
    hop = spec['hop_length']
    total = torch.zeros(codes.shape[-1]*hop, device=codes.device)
    weights = torch.zeros_like(total) if assembly != 'hard' else None
    work = calls = 0
    peak_state = 0
    first_ms = None
    torch.cuda.synchronize()
    started = time.perf_counter()
    for i, (start, length) in enumerate(geometry):
        part = codes[..., start:start+length]
        if helper is None:
            replay = min(32, start) if mode == 'replay32' else 0
            wave = decode(model, codes[..., start-replay:start+length], mid)[..., replay*hop:]
            work += length + replay
            calls += 1
        elif mid == 'fish-dac-s2':
            wave = helper.decode(part) if assembly == 'hard' else helper.decode_window(part, min(stride, length))
            work += helper.last_work_frames
            calls += 1 if assembly == 'hard' or length <= stride else 2
        else:
            flags = {'carry_kv': mode in ['kv-only', 'all'], 'carry_conv': mode in ['conv-only', 'all']}
            wave = helper.decode_chunk(part, **flags) if assembly == 'hard' else helper.decode_window(part, min(stride,length), **flags)
            work += length
            calls += 1 if assembly == 'hard' or length <= stride else 2
        if wave.shape != (1,1,length*hop):
            raise RuntimeError(f'Wrong decode geometry {mid}/{method["id"]}/{wave.shape}')
        left, right = start*hop, (start+length)*hop
        if assembly == 'hard':
            total[left:right] = wave[0,0]
        else:
            w = taper(length*hop, 'hann', codes.device)
            total[left:right] += wave[0,0]*w
            weights[left:right] += w
        info = state_info(helper, mid, mode)
        peak_state = max(peak_state, info['state_tensor_bytes'])
        if i == 0:
            torch.cuda.synchronize()
            first_ms = 1000*(time.perf_counter()-started)
    if weights is not None:
        if not torch.all(weights>0): raise RuntimeError('Uncovered overlap samples')
        total = total/weights
    torch.cuda.synchronize()
    seconds = time.perf_counter()-started
    if not torch.isfinite(total).all(): raise RuntimeError('Nonfinite reconstruction')
    info = state_info(helper, mid, mode)
    if helper is not None and mode == 'all' and info['committed_frames'] != codes.shape[-1]:
        raise RuntimeError('State timeline contains skipped or duplicated token frames')
    return total, {'stride_frames':stride, 'window_count':len(geometry), 'work_frames':work,
                   'decoder_calls':calls, 'decoded_frame_work_ratio':work/codes.shape[-1],
                   'decode_seconds':seconds, 'first_chunk_decode_ms':first_ms,
                   'state_info':info, 'state_bytes_max':peak_state}


def waveform_metrics(full, rec, starts, spec, radius_seconds=.040):
    diff = rec-full
    rms = float(diff.square().mean().sqrt())
    peak = float(diff.abs().max())
    full_rms = float(full.square().mean().sqrt())
    boundary = torch.zeros(full.numel(), dtype=torch.bool, device=full.device)
    radius = round(24000*radius_seconds)
    seams = [round(start*spec['hop_length']*24000/spec['sample_rate']) for start in starts if start>0]
    seams = [p for p in seams if 0<p<full.numel()]
    for p in seams: boundary[max(0,p-radius):min(full.numel(),p+radius)] = True
    seam_rms = float(diff[boundary].square().mean().sqrt()) if boundary.any() else None
    interior_rms = float(diff[~boundary].square().mean().sqrt()) if (~boundary).any() else None
    jumps = (diff[torch.tensor(seams,device=full.device)]-diff[torch.tensor(seams,device=full.device)-1]).abs() if seams else None
    return {'rms':rms, 'peak':peak, 'relative_rms':rms/max(full_rms,1e-12)}, {
        'coverage_percent':100*float(boundary.float().mean()), 'radius_ms':40,
        'seam_count':len(seams), 'seam_rms':seam_rms, 'interior_rms':interior_rms,
        'mean_seam_jump_delta':float(jumps.mean()) if jumps is not None else None,
        'max_seam_jump_delta':float(jumps.max()) if jumps is not None else None}


def aggregate(rows, bootstraps=10000):
    groups = defaultdict(list)
    for row in rows:
        for scope in ['overall', row['dataset_id']]:
            groups[(row['model_id'],scope,row['window_frames'],row['method'])].append(row)
    aggregates, contrasts, performance = [], [], []
    lookup = {(r['model_id'],r['clip_id'],r['window_frames'],r['method']):r for r in rows}
    for (mid,scope,width,method), items in sorted(groups.items()):
        total_seconds = sum(r['decode_seconds'] for r in items)
        audio_seconds = sum(r['source_duration_seconds'] for r in items)
        common = {'model_id':mid, 'scope':scope, 'window_frames':width, 'window_ms':items[0]['window_ms'],
                  'stride_frames':items[0]['stride_frames'], 'stride_ms':items[0]['stride_ms'],
                  'method':method, 'clips':len(items),
                  'waveform_rms_mean':float(np.mean([r['waveform_drift']['rms'] for r in items])),
                  'waveform_peak_max':max(r['waveform_drift']['peak'] for r in items),
                  'boundary_rms_mean':float(np.mean([r['boundary']['seam_rms'] for r in items])),
                  'interior_rms_mean':float(np.mean([r['boundary']['interior_rms'] for r in items if r['boundary']['interior_rms'] is not None])) if any(r['boundary']['interior_rms'] is not None for r in items) else None,
                  'boundary_coverage_percent_mean':float(np.mean([r['boundary']['coverage_percent'] for r in items])),
                  'decode_seconds_sum':total_seconds, 'throughput_x_realtime':audio_seconds/total_seconds,
                  'decoded_frame_work_ratio_mean':float(np.mean([r['decoded_frame_work_ratio'] for r in items])),
                  'state_bytes_max':max(r['state_bytes_max'] for r in items),
                  'extra_peak_gpu_bytes_max':max(r['extra_peak_gpu_bytes'] for r in items)}
        if scope == 'overall':
            performance.append({**common, 'audio_seconds':audio_seconds, 'decode_seconds':total_seconds,
                'first_chunk_decode_ms_mean':float(np.mean([r['first_chunk_decode_ms'] for r in items])),
                'work_ratio_mean':common['decoded_frame_work_ratio_mean']})
        for metric in METRICS:
            base=np.array([r['baseline'][metric] for r in items]); treat=np.array([r['treatment'][metric] for r in items])
            rng=np.random.default_rng(SEED+width+sum(map(ord,mid+scope+method+metric)))
            indices=rng.integers(0,len(items),(bootstraps,len(items)))
            b,t=base[indices].mean(axis=1),treat[indices].mean(axis=1)
            interval=lambda x:[float(v) for v in np.percentile(x,[2.5,97.5])]
            aggregates.append({**common, 'metric':metric, 'baseline_error_mean':float(base.mean()),
                'treatment_error_mean':float(treat.mean()), 'relative_increase_percent':float(100*(treat.mean()/base.mean()-1)),
                'relative_ci95':interval(100*(t/b-1)),
                'decoder_drift_mean':float(np.mean([r['decoder_drift'][metric] for r in items])),
                'per_clip_relative_p10':float(np.percentile(100*(treat/base-1),10)),
                'per_clip_relative_p90':float(np.percentile(100*(treat/base-1),90))})
            if method!='none-hard':
                control=np.array([lookup[(mid,r['clip_id'],width,'none-hard')]['treatment'][metric] for r in items])
                c=control[indices].mean(axis=1)
                contrasts.append({**common, 'metric':metric, 'control_method':'none-hard',
                    'control_error_mean':float(control.mean()), 'treatment_error_mean':float(treat.mean()),
                    'total_error_reduction_percent':float(100*(control.mean()-treat.mean())/control.mean()),
                    'ci95':interval(100*(c-t)/c), 'added_error_removed_pp':float(100*(control.mean()-treat.mean())/base.mean()),
                    'pp_ci95':interval(100*(c-t)/b), 'improved_clips_percent':float(100*np.mean(treat<control))})
    thresholds=[]
    for mid in MODELS:
        for method in [m['id'] for m in METHODS]:
            for metric in [*METRICS,'joint']:
                points=sorted({a['window_frames'] for a in aggregates if a['model_id']==mid and a['method']==method and a['scope']=='overall' and a['clips']==60})
                for budget in [5,10,20,30,40,50]:
                    metrics=METRICS if metric=='joint' else [metric]
                    passed=next((w for w in points if all(a['relative_ci95'][1]<=budget for a in aggregates
                        if a['model_id']==mid and a['method']==method and a['scope']=='overall' and a['clips']==60 and a['window_frames']>=w and a['metric'] in metrics)),None)
                    example=next((a for a in aggregates if a['model_id']==mid and a['method']==method and a['window_frames']==passed),None)
                    thresholds.append({'model_id':mid,'method':method,'metric':metric,'budget_percent':budget,
                        'pass_frames':passed,'pass_ms':example['window_ms'] if example else None,'all60_only':True,'observed_grid_only':True})
    return aggregates,contrasts,performance,thresholds


def summarize(out, protocol, rows):
    aggregates,contrasts,performance,thresholds=aggregate(rows)
    expected=sum(len([c for c in protocol['conditions'] if c['window_frames']<r['token_frames']]) for r in protocol['clip_geometry'])
    report={'protocol':protocol,'complete':len(rows)==expected,'row_count':len(rows),'expected_rows':expected,
            'aggregates':aggregates,'paired_contrasts':contrasts,'performance':performance,'thresholds':thresholds}
    (out/'report.json').write_text(json.dumps(report,indent=2)+'\n')
    for name,items in [('aggregate',aggregates),('paired_contrasts',contrasts),('performance',performance),('thresholds',thresholds)]:write_csv(out/(name+'.csv'),items)
    flat=[]
    for row in rows:
        r={k:v for k,v in row.items() if k not in ['baseline','treatment','decoder_drift','waveform_drift','boundary','state_info']}
        for group in ['baseline','treatment','decoder_drift','waveform_drift','boundary','state_info']:
            r.update({group+'_'+k:v for k,v in row[group].items()})
        flat.append(r)
    fields=sorted({key for item in flat for key in item})
    write_csv(out/'per_clip.csv',[{key:item.get(key) for key in fields} for item in flat])
    print('SUMMARY',len(rows),'of',expected,'complete',report['complete'],flush=True)


def build_listening(source, out, protocol, rows, controls):
    old=json.loads((source/'listening_manifest.json').read_text())
    sources=old['sources']; assets={s['original_audio']:old['assets'][s['original_audio']] for s in sources}
    selected={s['clip_id'] for s in sources}
    groups=defaultdict(list)
    for r in rows:
        if r['clip_id'] in selected: groups[(r['model_id'],r['clip_id'],r['window_frames'])].append(r)
    examples=[]
    for (mid,cid,width),items in sorted(groups.items()):
        r=items[0]; control=controls[mid+'/'+cid]
        variants={}
        for item in items:
            audio=item['listening_audio']
            if digest(source/audio)!=item['listening_asset']['sha256']:raise RuntimeError('Listening audio changed')
            assets[audio]=item['listening_asset']
            variants[item['method']]={'audio':audio,'errors':item['treatment'],
                'relative_percent':{m:100*(item['treatment'][m]/item['baseline'][m]-1) for m in METRICS},
                'stride_frames':item['stride_frames'],'state_mode':item['state_mode'],'assembly':item['assembly'],
                'work_ratio':item['decoded_frame_work_ratio'],'boundary':item['boundary'],
                'waveform_drift':item['waveform_drift'],'state_bytes':item['state_bytes_max']}
        assets[control['audio']]=control['asset']
        examples.append({'model_id':mid,'dataset_id':r['dataset_id'],'clip_id':cid,'window_frames':width,
                         'window_ms':r['window_ms'],'scalar_tokens':width*r['codebooks'],'codebooks':r['codebooks'],
                         'baseline':r['baseline'],'full_audio':control['audio'],'variants':variants})
    manifest={'schema_version':1,'complete':len(rows)==protocol['expected_rows'],'generated_at':datetime.now(timezone.utc).isoformat(),
        'sources':sources,'models':protocol['models'],'metrics':old['metrics'],'methods':METHODS,'examples':examples,
        'controls':[c for c in controls.values() if c.get('audio')],'assets':assets,
        'report_sha256':digest(out/'report.json'),'measurements_sha256':digest(out/'per_clip.jsonl'),
        'selection':'Same fixed three illustrative clips as prior listening pages, not population averages.',
        'playback_protocol':'24kHz mono IEEE float32 WAV, exact metric-domain arrays; no lossy encoding, volume normalization or alignment.'}
    (source/'state_listening_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')


def run(args):
    source,out=args.source,args.output
    out.mkdir(parents=True,exist_ok=True)
    if args.summarize_only:
        protocol=json.loads((out/'protocol.json').read_text());rows=list(map(json.loads,(out/'per_clip.jsonl').read_text().splitlines()))
        summarize(out,protocol,rows);build_listening(source,out,protocol,rows,json.loads((out/'full_controls.json').read_text()));return
    torch.set_num_threads(4);torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
    if not torch.cuda.is_available():raise RuntimeError('CUDA is required')
    old=json.loads((source/'overlap-add/report.json').read_text())
    prior={(r['model_id'],r['clip_id'],r['window_frames'],r['policy']):r for r in map(json.loads,(source/'overlap-add/per_clip.jsonl').read_text().splitlines()) if r['model_id'] in MODELS}
    prior_one={(r['model_id'],r['clip_id']):r for r in map(json.loads,(source/'per_clip.jsonl').read_text().splitlines()) if r['model_id'] in MODELS and r['window_frames']==1}
    geometry={}
    for r in prior.values():geometry[(r['model_id'],r['clip_id'])]={'model_id':r['model_id'],'clip_id':r['clip_id'],'token_frames':r['token_frames'],'codes_sha256':r['codes_sha256']}
    selected=list(csv.DictReader((source/'selected_clips.csv').open()))
    if len(selected)!=60:raise RuntimeError('Expected paired60sample')
    conditions=[{'window_frames':w,**method} for w in WIDTHS for method in METHODS if not(w==1 and method['assembly']=='hann50')]
    qwen_source=Path(importlib.util.find_spec('qwen_tts.core.tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2').origin)
    pins={str(p.relative_to(ROOT)):digest(p) for p in [ROOT/'scripts/decoder_fish_state.py',ROOT/'scripts/decoder_qwen_state.py',
          ROOT/'vendor/fish-speech/fish_speech/models/dac/modded_dac.py',ROOT/'vendor/fish-speech/fish_speech/models/dac/rvq.py',
          ROOT/'vendor/fish-speech/fish_speech/configs/modded_dac_vq.yaml',qwen_source]}
    protocol={'version':'decoder-transformer-state-v1','created_at':datetime.now(timezone.utc).isoformat(),
        'models':[dict(s,label=('Fish DAC S2-Pro' if s['id']=='fish-dac-s2' else 'Qwen3-TTS Tokenizer 12Hz')) for s in old['protocol']['models'] if s['id'] in MODELS],
        'methods':METHODS,'widths':WIDTHS,'conditions':conditions,'clip_geometry':list(geometry.values()),
        'source_report_sha256':digest(source/'report.json'),'prior_overlap_report_sha256':digest(source/'overlap-add/report.json'),
        'prior_overlap_raw_sha256':digest(source/'overlap-add/per_clip.jsonl'),'selected_clips_sha256':digest(source/'selected_clips.csv'),
        'implementation_sha256':pins,'runner_sha256':digest(Path(__file__)),
        'metrics':old['protocol']['metrics'],'metric_definitions':old['protocol']['metric_definitions'],
        'sample':'Same60clips:20CartoonVoices,20LibriSpeechOther,20Podcast;allcodebooks/fullclipcodesfixed',
        'state':'TruecausalKVand/orcausalConv1dinputhistoryandunbiasedConvTranspose1doutputtails; resetbetweenclipsandconditions',
        'replay':'Recompute up to32 preceding tokenframes and crop their audio; not a KVcache',
        'overlap':'Hann50whole-frame stride; actual-length shorttail tapers, weighted normalization, noalignment',
        'stateful_overlap':'Commit only stride S. Qwen decodes prefix S then suffix W-S with within-window state and rolls suffix back (W frames work); Fish decodes W, restores pre-window state, decodes S to capture commit (W+S work). No repeated tokens committed.',
        'baseline':'Native full decode then source-lengthcrop and24kHzmetric-domain resample; check against prior baseline <=1e-6',
        'prior_reset_tolerance':2e-5,'full_state_waveform_peak_tolerance':1e-4,'full_state_waveform_rms_tolerance':5e-6,
        'boundary':'Full-decode-relative waveform drift in union of +-40ms intervals around stride boundaries; coverage reported; no interior=>null; seam jump is abs difference of treatment-vsfull first difference',
        'timing':'Single-stream CUDA-synchronized decoder+assembly+statehooks+snapshots including first-window sync. One pass percondition, not warmed production throughput. Model/source/features excluded. Fish stock reset/replay single-window calls; Qwen state helper uses causal-state wrappers/nativecache.',
        'latency':'Token buffering W/frame_rate (same width); newly finalized stride S/frame_rate; OLAholdback(W-S)/frame_rate, in addition measured firstwindowcompute. Not end-to-end TTS latency.',
        'memory':'Carried-state tensor bytes excluding model/input/activations; additional CUDA allocated peak over before-condition resident bytes includes copies and outputassembly, not reservedmemory',
        'statistics':'10000 pairedclipbootstraps; ratiosofarithmeticmeans; pointwise95% percentileintervals; gridthresholdsrestrictall60eligibleclips',
        'runtime':{'gpu':torch.cuda.get_device_name(),'torch':torch.__version__,'cuda':torch.version.cuda,
                   'qwen_tts':importlib.metadata.version('qwen-tts'),'transformers':importlib.metadata.version('transformers'),'tf32':False,'threads':4}}
    protocol['expected_rows']=sum(sum(c['window_frames']<r['token_frames'] for c in conditions) for r in geometry.values())
    protocol_path=out/'protocol.json'
    if protocol_path.exists():
        previous=json.loads(protocol_path.read_text())
        amendment=previous.get('numeric_control_amendment')
        if args.numerical_calibration and amendment is None:
            calibration_path=args.numerical_calibration.resolve()
            calibration=json.loads(calibration_path.read_text())
            if not calibration['complete'] or not calibration['passed']:
                raise RuntimeError('Numerical calibration must be complete and waveform-validated')
            if calibration['source_manifest_sha256']!=protocol['selected_clips_sha256'] or calibration['prior_overlap_raw_sha256']!=protocol['prior_overlap_raw_sha256']:
                raise RuntimeError('Calibration population or previous measurements changed')
            if calibration['waveform_peak_max']>1e-4 or calibration['waveform_rms_max']>5e-6:
                raise RuntimeError('Stock numerical equivalence is not established')
            largest=max(calibration['metric_max_absolute_difference'].values())
            tolerance=max(2e-5,math.ceil(2*largest/1e-5)*1e-5)
            if tolerance>1e-3:raise RuntimeError('Unexpectedly large stock metric disagreement; investigate')
            raw_path=out/'per_clip.jsonl'
            backup=out/'protocol-before-numerical-amendment.json'
            if backup.exists():raise RuntimeError('Refusing to overwrite original protocol archive')
            shutil.copy2(protocol_path,backup)
            shutil.copy2(raw_path,out/'per_clip-before-numerical-amendment.jsonl')
            amendment={'created_at':datetime.now(timezone.utc).isoformat(),
                'original_tolerance':previous['prior_reset_tolerance'],'amended_tolerance':tolerance,
                'calibration_path':str(calibration_path.relative_to(ROOT)),
                'calibration_sha256':digest(calibration_path),
                'original_protocol_sha256':digest(backup),
                'prior_runner_sha256':previous['runner_sha256'],'amended_runner_sha256':protocol['runner_sha256'],
                'retained_measurements_count':len(raw_path.read_text().splitlines()),
                'retained_measurements_sha256':digest(raw_path),
                'scope':'Post-start numerical control amendment only: independent stock serial-vs-batched calibration; all-state waveform criteria, treatments, widths, source population, weights, precision and metric definitions unchanged.'}
        if amendment:
            calibration_path=ROOT/amendment['calibration_path']
            if digest(calibration_path)!=amendment['calibration_sha256'] or protocol['runner_sha256']!=amendment['amended_runner_sha256']:
                raise RuntimeError('Amended numerical control evidence or implementation changed')
            protocol['numeric_control_amendment']=amendment
            protocol['prior_reset_tolerance']=amendment['amended_tolerance']
        for k in ['implementation_sha256','runner_sha256','prior_overlap_raw_sha256','conditions','selected_clips_sha256']:
            if previous[k]!=protocol[k] and not(k=='runner_sha256' and args.numerical_calibration and amendment and previous[k]==amendment['prior_runner_sha256']):
                raise RuntimeError(f'Cannot resume changedprotocol: {k}')
        protocol['created_at']=previous['created_at']
    protocol_path.write_text(json.dumps(protocol,indent=2)+'\n')
    raw=out/'per_clip.jsonl';rows=list(map(json.loads,raw.read_text().splitlines())) if raw.exists() else []
    done={(r['model_id'],r['clip_id'],r['window_frames'],r['method']) for r in rows}
    controls_path=out/'full_controls.json';controls=json.loads(controls_path.read_text()) if controls_path.exists() else {}
    anchors={s['clip_id'] for s in json.loads((source/'listening_manifest.json').read_text())['sources']}
    (source/'state-listening-audio').mkdir(exist_ok=True)
    spectra=Spectra('cuda');started=time.perf_counter()
    for mid in args.models:
        print('LOAD',mid,flush=True)
        adapter=get_codec(mid,'cuda');model,spec=adapter.model,adapter.spec
        pinned=next(s for s in protocol['models'] if s['id']==mid)
        if digest(ROOT/spec['checkpoint'])!=pinned['measured_checkpoint_sha256']:raise RuntimeError('Checkpoint changed')
        with torch.inference_mode(),raw.open('a') as stream:
            for i,clip in enumerate(selected,1):
                if args.limit and i>args.limit:break
                cid=clip['clip_id'];g=geometry[(mid,cid)]
                pending=[c for c in conditions if c['window_frames']<g['token_frames'] and(mid,cid,c['window_frames'],c['id']) not in done]
                if not pending:continue
                if digest(clip['audio_path'])!=clip['audio_sha256']:raise RuntimeError('Source changed')
                cache=source/'codes'/mid/(hashlib.sha256(cid.encode()).hexdigest()+'.pt')
                if digest(cache)!=g['codes_sha256']:raise RuntimeError('Code cache file changed')
                cached=torch.load(cache,weights_only=True,map_location='cuda');codes=cached['codes']
                if cached['source_sha256']!=clip['audio_sha256'] or cached['checkpoint_sha256']!=pinned['measured_checkpoint_sha256']:raise RuntimeError('Cache provenance changed')
                codes_before=codes.clone()
                array,sr=sf.read(clip['audio_path'],dtype='float32',always_2d=True);original=torch.from_numpy(array.mean(axis=1)).cuda()
                native=original if sr==spec['sample_rate'] else torchaudio.functional.resample(original,sr,spec['sample_rate'])
                reference=spectra.resample(original,sr);rf=spectra.features(reference)
                full=spectra.resample(decode(model,codes,mid)[0,0,:native.numel()],spec['sample_rate'],reference.numel());ff=spectra.features(full)
                baseline=spectra.errors(rf,ff);prior_base=next(r for r in prior.values() if r['model_id']==mid and r['clip_id']==cid)['baseline']
                baseline_delta=max(abs(baseline[m]-prior_base[m]) for m in METRICS)
                if baseline_delta>1e-6:raise RuntimeError(f'Baseline changed{baseline_delta}')
                control={'model_id':mid,'dataset_id':clip['dataset_id'],'clip_id':cid,'baseline':baseline,'prior_baseline_max_abs_difference':baseline_delta}
                if cid in anchors:
                    assets={};audio=f'state-listening-audio/{clip["dataset_id"]}-{mid}-full.wav';export_audio(source,audio,full,assets)
                    control.update(audio=audio,asset=assets[audio])
                controls[mid+'/'+cid]=control;controls_path.write_text(json.dumps(controls,indent=2)+'\n')
                # Counterbalance condition ordering reproducibly; measurements
                # remain paired, and no live state crosses a condition boundary.
                rng=np.random.default_rng(SEED+sum(map(ord,mid+cid)));rng.shuffle(pending)
                for c in pending:
                    torch.cuda.empty_cache();resident=torch.cuda.memory_allocated();torch.cuda.reset_peak_memory_stats()
                    wave,metadata=reconstruct(model,codes,c['window_frames'],mid,spec,c)
                    extra_peak=max(0,torch.cuda.max_memory_allocated()-resident)
                    rec=spectra.resample(wave[:native.numel()],spec['sample_rate'],reference.numel());features=spectra.features(rec)
                    treatment=spectra.errors(rf,features);drift=spectra.errors(ff,features)
                    starts=range(0,codes.shape[-1],metadata['stride_frames'])
                    wm,bm=waveform_metrics(full,rec,starts,spec)
                    if c['state_mode']=='all' and (wm['peak']>1e-4 or wm['rms']>5e-6):raise RuntimeError(f'Fullstateequivalencefailed:{mid}/{cid}/{c["id"]}/{c["window_frames"]}/{wm}')
                    prior_delta=None
                    oldrow=prior.get((mid,cid,c['window_frames'],'hann50'))
                    if c['state_mode']=='none' and oldrow:
                        expected=oldrow['hard'] if c['assembly']=='hard' else oldrow['overlap']
                        prior_delta=max(abs(treatment[m]-expected[m]) for m in METRICS)
                        if prior_delta>protocol['prior_reset_tolerance']:raise RuntimeError(f'Resetcontroldiff:{prior_delta}')
                    elif c['id']=='none-hard' and c['window_frames']==1:
                        expected=prior_one[(mid,cid)]['treatment']
                        prior_delta=max(abs(treatment[m]-expected[m]) for m in METRICS)
                        if prior_delta>protocol['prior_reset_tolerance']:raise RuntimeError(f'Oneframeresetcontroldiff:{prior_delta}')
                    row={'model_id':mid,'dataset_id':clip['dataset_id'],'clip_id':cid,'method':c['id'],
                         'state_mode':c['state_mode'],'assembly':c['assembly'],'window_frames':c['window_frames'],
                         'window_ms':1000*c['window_frames']/spec['frame_rate'],'stride_ms':1000*metadata['stride_frames']/spec['frame_rate'],
                         'token_frames':codes.shape[-1],'codebooks':spec['codebooks'],'audio_sha256':clip['audio_sha256'],
                         'codes_sha256':g['codes_sha256'],'source_duration_seconds':reference.numel()/24000,
                         'baseline':baseline,'treatment':treatment,'decoder_drift':drift,'waveform_drift':wm,'boundary':bm,
                         'prior_reset_metric_max_abs_difference':prior_delta,'extra_peak_gpu_bytes':extra_peak,**metadata}
                    if cid in anchors:
                        assets={};audio=f'state-listening-audio/{clip["dataset_id"]}-{mid}-{c["id"]}-{c["window_frames"]}.wav';export_audio(source,audio,rec,assets)
                        row.update(listening_audio=audio,listening_asset=assets[audio])
                    stream.write(json.dumps(row)+'\n');stream.flush();rows.append(row);done.add((mid,cid,c['window_frames'],c['id']))
                    del wave,rec,features
                if not torch.equal(codes,codes_before):raise RuntimeError('Decoder mutated cached codes')
                print(mid,i,'/60',len(rows),'rows',f'{(time.perf_counter()-started)/60:.1f}min',flush=True)
        del adapter,model,codes,cached,original,native,reference,rf,ff,full
        unload_codecs();gc.collect();torch.cuda.empty_cache()
    summarize(out,protocol,rows);build_listening(source,out,protocol,rows,controls)


if __name__=='__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('--source',type=Path,default=OUT)
    parser.add_argument('--output',type=Path,default=OUT/'transformer-state')
    parser.add_argument('--models',nargs='+',choices=MODELS,default=MODELS)
    parser.add_argument('--limit',type=int,default=0)
    parser.add_argument('--summarize-only',action='store_true')
    parser.add_argument('--numerical-calibration',type=Path,
                        help='Explicit, archived post-start numerical control amendment from an independently validated calibration')
    run(parser.parse_args())
