refresh_bench.py

scripts/refresh_bench.py

Time a one-file-edit refresh on a real repository, stage by stage, and leave nothing behind.

_build

int refresh_bench._build(Path clone, Path db, str verb="")

Build the clone once through the real CLI.

scripts/refresh_bench.py:77

Show on the map →

Called by main

Calls none

Source · 30 lines
def _build(clone: Path, db: Path, verb: str = "") -> int:
    """THROUGH THE CLI, as `incremental_probe` does: the number must be what a user's build costs.

    @brief Run one build.
    @return Elapsed ms.
    @version 1
    """
    started = time.monotonic()
    proc = subprocess.run(
        [
            sys.executable,
            "-m",
            "clew",
            *([verb] if verb else []),
            "--repo-root",
            str(clone),
            "--output",
            str(db),
        ],
        cwd=str(REPO),
        capture_output=True,
        text=True,
        check=False,
    )
    if proc.returncode != 0:
        sys.stderr.write(proc.stderr[-4000:])
        raise SystemExit(f"build failed ({proc.returncode})")
    return int((time.monotonic() - started) * 1000)

Activity · 6 steps
lines 84–84started = time.monotonic()lines 85–100proc = subprocess.run( [ sys.executable, "-m", "clew", *([verb] if verb else []), "--repo-root", str(clone), "--output", str(db), ], cwd=str(REPO), capture_output=True, text=True, check=False, )lines 101–101◇ if proc.returncode != 0lines 102–102sys.stderr.write(proc.stderr[-4000:])lines 103–103raise SystemExit(f"build failed ({proc.returncode})")lines 104–104return int((time.monotonic() - started) * 1000)

Flows

_edit_text

str refresh_bench._edit_text(Path target, str edit, int i)

The text one rep appends: a comment, or a new function.

scripts/refresh_bench.py:61

Show on the map →

Called by main

Calls none

Source · 10 lines
def _edit_text(target: Path, edit: str, i: int) -> str:
    """@brief One rep's edit. @return Text."""
    if edit == "function":
        template = _FUNCTION.get(target.suffix)
        if template is None:
            raise SystemExit(f"--edit function has no template for {target.suffix}")
        return template.format(i=i)
    return f"\n{_COMMENT.get(target.suffix, '//')} refresh_bench edit {i}\n"

Activity · 6 steps
lines 63–63◇ if edit == "function"lines 64–64template = _FUNCTION.get(target.suffix)lines 65–65◇ if template is Nonelines 66–66raise SystemExit(f"--edit function has no template for {target.suffix}")lines 67–67return template.format(i=i)lines 68–68return f"\n{_COMMENT.get(target.suffix, '//')} refresh_bench edit {i}\n"

Flows

_fast_ms

int | None refresh_bench._fast_ms(Path db)

The recorded cost of the last fast refresh, if one is pending.

scripts/refresh_bench.py:131

Show on the map →

Called by main

Calls none

Source · 10 lines
def _fast_ms(db: Path) -> int | None:
    """@brief Read fast.ms. @return Ms or None."""
    conn = sqlite3.connect(db)
    try:
        row = conn.execute("SELECT value FROM build_meta WHERE key = 'fast.ms'").fetchone()
    finally:
        conn.close()
    return int(row[0]) if row else None

Activity · 4 steps
lines 133–133conn = sqlite3.connect(db)lines 134–134trylines 135–135row = conn.execute("SELECT value FROM build_meta WHERE key = 'fast.ms'").fetchone()lines 138–138return int(row[0]) if row else None

Flows

_stamped

tuple[int, dict[str, int]] refresh_bench._stamped(Path db)

Read the refresh total and stage breakdown the build stamped.

scripts/refresh_bench.py:112

Show on the map →

Called by main

Calls none

Source · 14 lines
def _stamped(db: Path) -> tuple[int, dict[str, int]]:
    """@brief Read refresh.* from build_meta. @return Duration and stages."""
    conn = sqlite3.connect(db)
    try:
        meta = dict(conn.execute("SELECT key, value FROM build_meta WHERE key LIKE 'refresh.%'"))
    finally:
        conn.close()
    stages = {}
    for part in str(meta.get("refresh.stages", "")).split():
        name, _, ms = part.partition("=")
        stages[name] = int(ms)
    return int(meta.get("refresh.duration_ms", -1)), stages

Activity · 8 steps
lines 114–114conn = sqlite3.connect(db)lines 115–115trylines 116–116meta = dict(conn.execute("SELECT key, value FROM build_meta WHERE key LIKE 'refresh.%'"))lines 119–119stages = {}lines 120–120◇ for part in str(meta.get("refresh.stages", "")).split()lines 121–121name, _, ms = part.partition("=")lines 122–122stages[name] = int(ms)lines 123–123return int(meta.get("refresh.duration_ms", -1)), stages

Flows

main

int refresh_bench.main()

Clone, build, edit-and-refresh N times, report, clean up.

scripts/refresh_bench.py:146

Source · 69 lines
def main() -> int:
    """@brief Entry point. @return 0."""
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("repo", type=Path)
    parser.add_argument("file")
    parser.add_argument("--reps", type=int, default=3)
    parser.add_argument("--keep", action="store_true", help="keep the scratch directory")
    parser.add_argument(
        "--fast", action="store_true", help="refresh with `clew refresh` (fast tier first)"
    )
    parser.add_argument(
        "--edit",
        choices=("comment", "function"),
        default="comment",
        help="what each rep appends: a comment line, or a new function (PR1)",
    )
    args = parser.parse_args()
    work = Path(tempfile.mkdtemp(prefix="clew-bench-"))
    try:
        clone, db = work / "clone", work / "clew.db"
        subprocess.run(
            ["git", "clone", "-q", "--shared", str(args.repo.resolve()), str(clone)], check=True
        )
        cold = _build(clone, db)
        target = clone / args.file
        runs = []
        for i in range(args.reps):
            with target.open("a") as handle:
                handle.write(_edit_text(target, args.edit, i))
            wall = _build(clone, db, "refresh" if args.fast else "")
            stamped, stages = _stamped(db)
            ## A FAST REFRESH STAMPS `fast.ms`, not `refresh.*` (those describe the last FULL
            ## build), so its cost is read from there. `fast_ran` SAYS WHICH: a refusal is a full
            ## build, and its time must not be reported as the fast tier's.
            fast_ms = _fast_ms(db) if args.fast else None
            stamped = fast_ms if fast_ms is not None else stamped
            runs.append(
                {
                    "wall_ms": wall,
                    "duration_ms": stamped,
                    "stages": stages,
                    "fast_ran": fast_ms is not None,
                }
            )
        median = sorted(runs, key=lambda r: r["duration_ms"])[len(runs) // 2]
        print(
            json.dumps(
                {
                    "repo": str(args.repo),
                    "file": args.file,
                    "cold_ms": cold,
                    "refresh_ms": [r["duration_ms"] for r in runs],
                    "refresh_wall_ms": [r["wall_ms"] for r in runs],
                    "edit": args.edit,
                    "fast_ran": [r["fast_ran"] for r in runs],
                    "median_refresh_ms": statistics.median(r["duration_ms"] for r in runs),
                    "median_stages": dict(sorted(median["stages"].items(), key=lambda kv: -kv[1])),
                },
                indent=1,
            )
        )
    finally:
        if args.keep:
            print(f"scratch kept at {work}", file=sys.stderr)
        else:
            shutil.rmtree(work, ignore_errors=True)
    return 0

Activity · 26 steps
lines 148–148parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])lines 149–149parser.add_argument("repo", type=Path)lines 150–150parser.add_argument("file")lines 151–151parser.add_argument("--reps", type=int, default=3)lines 152–152parser.add_argument("--keep", action="store_true", help="keep the scratch directory")lines 153–155parser.add_argument( "--fast", action="store_true", help="refresh with `clew refresh` (fast tier first)" )lines 156–161parser.add_argument( "--edit", choices=("comment", "function"), default="comment", help="what each rep appends: a comment line, or a new function (PR1)", )lines 162–162args = parser.parse_args()lines 163–163work = Path(tempfile.mkdtemp(prefix="clew-bench-"))lines 164–164trylines 165–165clone, db = work / "clone", work / "clew.db"lines 166–168subprocess.run( ["git", "clone", "-q", "--shared", str(args.repo.resolve()), str(clone)], check=True )lines 169–169cold = _build(clone, db)lines 170–170target = clone / args.filelines 171–171runs = []lines 172–172◇ for i in range(args.reps)lines 173–173with target.open("a") as handlelines 174–174handle.write(_edit_text(target, args.edit, i))lines 175–175wall = _build(clone, db, "refresh" if args.fast else "")lines 176–176stamped, stages = _stamped(db)lines 180–180fast_ms = _fast_ms(db) if args.fast else Nonelines 181–181stamped = fast_ms if fast_ms is not None else stampedlines 182–189runs.append( { "wall_ms": wall, "duration_ms": stamped, "stages": stages, "fast_ran": fast_ms is not None, } )lines 190–190median = sorted(runs, key=lambda r: r["duration_ms"])[len(runs) // 2]lines 191–206print( json.dumps( { "repo": str(args.repo), "file": args.file, "cold_ms": cold, "refresh_ms": [r["duration_ms"] for r in runs], "refresh_wall_ms": [r["wall_ms"] for r in runs], "edit": args.edit, "fast_ran": [r["fast_ran"] for r in runs], "median_refresh_ms": statistics.median(r["duration_ms"] for r in runs), "median_stages": dict(sorted(median["stages"].items(), key=lambda kv: -kv[1])), }, indent=1, ) )lines 212–212return 0

Flows