"""Live retained traced allocations by source line, in fresh processes at each read."""
import json,platform,subprocess,sys,tracemalloc
from pathlib import Path
from collecte24 import measure

def snapshot(cap,mode,read):
    p=Path(__file__).with_name('collecte24.py').resolve()
    lines=p.read_text(encoding='utf8').splitlines()
    groups={}
    def observe(i):
        if i!=read:return
        snap=tracemalloc.take_snapshot()
        for st in snap.statistics('lineno'):
            frame=st.traceback[0];label='other'
            if Path(frame.filename)==p:
                line=lines[frame.lineno-1].strip()
                if line.startswith('return tuple('):label='coefficients'
                elif 'poly(' in line and ('a=poly' in line or 'p=poly' in line):label='cache calls'
                else:label='other kernel'
            row=groups.setdefault(label,[0,0]);row[0]+=st.size;row[1]+=st.count
    r=measure(cap,frozenset((2,4,6)) if mode else False,True,order=(0,7,1,6,2,5,3,4),after_read=observe)
    return dict(groups=groups,misses=r['misses'],version=platform.python_version())
def study():
    out=[]
    for cap in (64,256):
        for read in (3,5,7):
            rows=[json.loads(subprocess.check_output([sys.executable,'-B',__file__,str(cap),str(m),str(read)])) for m in (0,1)]
            assert rows[0]['misses']==rows[1]['misses']
            keys=sorted(set.union(*(set(z['groups']) for z in rows)))
            diff={k:rows[1]['groups'].get(k,[0])[0]-rows[0]['groups'].get(k,[0])[0] for k in keys}
            out.append(dict(cap=cap,read=read,rows=rows,diff=diff))
    return out
if __name__=='__main__':print(json.dumps(snapshot(*map(int,sys.argv[1:])) if len(sys.argv)>1 else study()))
