import sys, pathlib
root = pathlib.Path(sys.argv[1])
p = root / "arbi_serve/engine/step_phase_probe.py"
s = p.read_text()
a = '''        _DX["alloc0"] = _dx_alloc()'''
b = '''        _DX["alloc0"] = _dx_alloc()
        try:
            import torch
            _DX["segs0"] = {x["address"] for x in torch.cuda.memory_snapshot()}
        except Exception:  # noqa: BLE001
            _DX["segs0"] = set()'''
assert s.count(a) == 1; s = s.replace(a, b)
a = '''                snap = torch.cuda.memory._snapshot()'''
b = '''                for x in torch.cuda.memory_snapshot():
                    if x["address"] not in _DX.get("segs0", set()):
                        bl = x.get("blocks") or []
                        fr = []
                        for blk in bl:
                            for f in blk.get("frames", []) or []:
                                if "arbi_serve" in f.get("filename", "") and len(fr) < 6:
                                    fr.append(f"{f['filename'].split('arbi_serve/')[-1]}:{f['line']}:{f['name']}")
                            if fr:
                                break
                        logger.warning("DIAGSEG size=%.1fMiB pool=%s stream=%s type=%s blocks=%d frames=%s", x["total_size"] / 2**20,
                                       x.get("segment_pool_id"), x.get("stream"), x.get("segment_type"), len(bl), " <- ".join(fr))
                snap = torch.cuda.memory._snapshot()'''
assert s.count(a) == 1; s = s.replace(a, b)
p.write_text(s)
print("patched4")
