stage_probe.py

scripts/stage_probe.py

MEASURE ONE STAGE BY RE-RUNNING IT, not by diffing two builds.

_counts

dict[str, int] stage_probe._counts(Path db)

Count the rows of interest for a stage, before and after.

scripts/stage_probe.py:56

Show on the map →

Called by main

Calls none

Source · 24 lines
def _counts(db: Path) -> dict[str, int]:
    """@brief Snapshot the edge counts a stage diff is read from.
    @return Label to count.
    @version 1
    """
    conn = sqlite3.connect(db)
    try:
        rows = dict(
            conn.execute(
                "SELECT confidence, COUNT(*) FROM call_edges "
                "WHERE source LIKE 'ast%' GROUP BY confidence"
            )
        )
        extra = {}
        for table in ("unresolved_inbound",):
            try:
                extra[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]  # noqa: S608
            except sqlite3.OperationalError:
                pass
    finally:
        conn.close()
    return {**{f"ast/{k}": v for k, v in rows.items()}, **extra}

Activity · 10 steps
lines 61–61conn = sqlite3.connect(db)lines 62–62trylines 63–68rows = dict( conn.execute( "SELECT confidence, COUNT(*) FROM call_edges " "WHERE source LIKE 'ast%' GROUP BY confidence" ) )lines 69–69extra = {}lines 70–70◇ for table in ("unresolved_inbound",)lines 71–71trylines 72–72extra[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]lines 73–73except sqlite3.OperationalErrorlines 74–74passlines 77–77return {**{f"ast/{k}": v for k, v in rows.items()}, **extra}

Flows

main

int stage_probe.main()

Copy an index, re-run one stage against the copy, and print the diff.

scripts/stage_probe.py:83

Source · 78 lines
def main() -> int:
    """@brief Re-run one stage in isolation and report what moved.
    @return 0 on success, 2 on a bad argument.
    @version 1
    """
    parser = argparse.ArgumentParser(prog="stage_probe", description=__doc__)
    parser.add_argument("--target", required=True, help="Repo root whose index to copy.")
    parser.add_argument("--stage", default="ast_call_edges", choices=sorted(_STAGES))
    parser.add_argument(
        "--out",
        default=".claude/tmp/stage_probe.db",
        help="Where to write the working COPY. The source index is never modified.",
    )
    parser.add_argument(
        "--allow-stale",
        action="store_true",
        help=(
            "Measure even when the target's sources have moved since the index was built. "
            "The diff is then not attributable to the stage — use it to explore, never to "
            "quote a figure."
        ),
    )
    args = parser.parse_args()

    target = Path(args.target).expanduser().resolve()
    registry = TargetRegistry()
    entry = registry.register(str(target))
    source = Path(entry.db_path)
    if not source.exists():
        print(f"no index for {target} at {source} — build it first", file=sys.stderr)
        return 2

    ## REFUSES ON A DRIFTED BASELINE, and that guard is the difference between a measurement
    ## and a number. Caught the first time this script was run: entropic's index read
    ## `resolved 4889` while a re-run produced 4839, because the working tree had moved since
    ## the index was built — so "before" described one source tree and "after" another, and
    ## the -50 was attributable to nothing. A diff whose two sides do not share a source tree
    ## is exactly the unreproducible instrument this approach was adopted to replace.
    status = db_status(entry)
    drifted = int(status.get("source_changed_files") or 0)
    if drifted and not args.allow_stale:
        print(
            f"REFUSING: {drifted} indexed source file(s) have changed since this index was "
            f"built, so a before/after diff would compare two different trees. Refresh the "
            f"target first, or pass --allow-stale to measure anyway and read the numbers as "
            f"indicative only.",
            file=sys.stderr,
        )
        return 2

    dest = Path(args.out)
    dest.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy(source, dest)
    ## The harvest sidecar rides along, so the re-run reuses cached per-file parses and
    ## measures the RESOLUTION logic rather than the cost of parsing the tree again.
    sidecar = source.with_suffix(source.suffix + ".idxcache")
    if sidecar.exists():
        shutil.copy(sidecar, dest.with_suffix(dest.suffix + ".idxcache"))

    predicate, run = _STAGES[args.stage]
    before = _counts(dest)
    conn = sqlite3.connect(dest)
    conn.execute(predicate)
    conn.commit()
    conn.close()

    run(dest, target)

    after = _counts(dest)
    print(f"\n{args.stage} on {target.name}, re-run against a copy:\n")
    for key in sorted(set(before) | set(after)):
        was, now = before.get(key, 0), after.get(key, 0)
        arrow = "" if was == now else f"   ({now - was:+d})"
        print(f"  {key:<24} {was:>7} -> {now:<7}{arrow}")
    print(f"\ncopy left at {dest}")
    return 0

Activity · 39 steps
lines 88–88parser = argparse.ArgumentParser(prog="stage_probe", description=__doc__)lines 89–89parser.add_argument("--target", required=True, help="Repo root whose index to copy.")lines 90–90parser.add_argument("--stage", default="ast_call_edges", choices=sorted(_STAGES))lines 91–95parser.add_argument( "--out", default=".claude/tmp/stage_probe.db", help="Where to write the working COPY. The source index is never modified.", )lines 96–104parser.add_argument( "--allow-stale", action="store_true", help=( "Measure even when the target's sources have moved since the index was built. " "The diff is then not attributable to the stage — use it to explore, never to " "quote a figure." ), )lines 105–105args = parser.parse_args()lines 107–107target = Path(args.target).expanduser().resolve()lines 108–108registry = TargetRegistry()lines 109–109entry = registry.register(str(target))lines 110–110source = Path(entry.db_path)lines 111–111◇ if not source.exists()lines 112–112print(f"no index for {target} at {source} — build it first", file=sys.stderr)lines 113–113return 2lines 121–121status = db_status(entry)lines 122–122drifted = int(status.get("source_changed_files") or 0)lines 123–123◇ if drifted and not args.allow_stalelines 124–130print( f"REFUSING: {drifted} indexed source file(s) have changed since this index was " f"built, so a before/after diff would compare two different trees. Refresh the " f"target first, or pass --allow-stale to measure anyway and read the numbers as " f"indicative only.", file=sys.stderr, )lines 131–131return 2lines 133–133dest = Path(args.out)lines 134–134dest.parent.mkdir(parents=True, exist_ok=True)lines 135–135shutil.copy(source, dest)lines 138–138sidecar = source.with_suffix(source.suffix + ".idxcache")lines 139–139◇ if sidecar.exists()lines 140–140shutil.copy(sidecar, dest.with_suffix(dest.suffix + ".idxcache"))lines 142–142predicate, run = _STAGES[args.stage]lines 143–143before = _counts(dest)lines 144–144conn = sqlite3.connect(dest)lines 145–145conn.execute(predicate)lines 146–146conn.commit()lines 147–147conn.close()lines 149–149run(dest, target)lines 151–151after = _counts(dest)lines 152–152print(f"\n{args.stage} on {target.name}, re-run against a copy:\n")lines 153–153◇ for key in sorted(set(before) | set(after))lines 154–154was, now = before.get(key, 0), after.get(key, 0)lines 155–155arrow = "" if was == now else f" ({now - was:+d})"lines 156–156print(f" {key:<24} {was:>7} -> {now:<7}{arrow}")lines 157–157print(f"\ncopy left at {dest}")lines 158–158return 0

Flows