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.
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
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.
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
Flows
_fast_ms
int | None refresh_bench._fast_ms(Path db)
The recorded cost of the last fast refresh, if one is pending.
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
Flows
_stamped
tuple[int, dict[str, int]] refresh_bench._stamped(Path db)
Read the refresh total and stage breakdown the build stamped.
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
Flows
main
int refresh_bench.main()
Clone, build, edit-and-refresh N times, report, clean up.
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