dryrun.py

clew/propose/dryrun.py

Measure a candidate declaration by RUNNING it — never by projecting it.

_count

int clew.propose.dryrun._count(sqlite3.Connection conn, str sql)

Count rows in a table, tolerating its absence.

clew/propose/dryrun.py:120

Source · 8 lines
def _count(conn: sqlite3.Connection, sql: str) -> int:
    """@brief Run one COUNT, degrading to 0 on a table-less database."""
    try:
        return int(conn.execute(sql).fetchone()[0])
    except sqlite3.Error:
        return 0

Activity · 4 steps
lines 122–122trylines 123–123return int(conn.execute(sql).fetchone()[0])lines 124–124except sqlite3.Errorlines 125–125return 0

Flows

_defect_reason

str clew.propose.dryrun._defect_reason(bool has_table, int count)

Turn a memberdef presence/row count into a defect reason.

clew/propose/dryrun.py:105

Source · 9 lines
def _defect_reason(has_table: bool, count: int) -> str:
    """@brief Describe what is wrong with an index, if anything."""
    if not has_table:
        return "has no `memberdef` table — it is not a clew index"
    if count == 0:
        return "has an empty `memberdef` — no functions were indexed"
    return ""

Activity · 5 steps
lines 107–107◇ if not has_tablelines 108–108return "has no `memberdef` table — it is not a clew index"lines 109–109◇ if count == 0lines 110–110return "has an empty `memberdef` — no functions were indexed"lines 111–111return ""

Flows

db_copy

Iterator[Path] clew.propose.dryrun.db_copy(Path db_path)

A throwaway copy of a database, deleted on exit.

clew/propose/dryrun.py:46

Source · 14 lines
def db_copy(db_path: Path) -> Iterator[Path]:
    """`copy2` rather than a sqlite backup: the pipeline databases are not in
    WAL mode, so the file IS the database, and a plain copy cannot disturb a
    concurrent reader of the original.

    @brief Copy a database into a temp directory for the duration of a block.
    @version 3
    """
    with tempfile.TemporaryDirectory(prefix="clew-dryrun-") as tmp:
        copy = Path(tmp) / "clew.db"
        shutil.copy2(db_path, copy)
        yield copy

Activity · 4 steps
lines 54–54with tempfile.TemporaryDirectory(prefix="clew-dryrun-") as tmplines 55–55copy = Path(tmp) / "clew.db"lines 56–56shutil.copy2(db_path, copy)lines 57–57yield copy

Requirements

REQ-DDB-CONFIG-001

index_defect

str clew.propose.dryrun.index_defect(Path db_path)

Why a database cannot be dry-run against, if it cannot.

clew/propose/dryrun.py:65

Source · 34 lines
def index_defect(db_path: Path) -> str:
    """Checked BEFORE any measurement, because the pipeline importers a dry run
    calls are not defensive about their inputs: `_build_function_indexes` selects
    straight from `memberdef` and raises `OperationalError` on a database that
    does not have it. A zero-byte `clew.db` left in a repo is enough to reach that
    — and the discovery order can pick one up on its own, so the crash is not a
    hypothetical.

    An index with the table but NO rows is refused too. It would measure 0 for
    every candidate, and every candidate would then be rejected with the gate's
    own wording ("never a key across two functions") — a specific, false claim
    about the repo, where the truth is that nothing was indexed.

    @brief Validate that an index can be measured against.
    @version 2
    """
    try:
        conn = sqlite3.connect(str(db_path))
    except sqlite3.Error as exc:
        return f"cannot be opened ({exc})"
    try:
        count = _count(conn, "SELECT COUNT(*) FROM memberdef")
        has_table = bool(
            conn.execute(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name='memberdef'"
            ).fetchone()
        )
    except sqlite3.Error as exc:
        return f"is not a readable SQLite database ({exc})"
    finally:
        conn.close()
    return _defect_reason(has_table, count)

Activity · 10 steps
lines 81–81trylines 82–82conn = sqlite3.connect(str(db_path))lines 83–83except sqlite3.Error as exclines 84–84return f"cannot be opened ({exc})"lines 85–85trylines 86–86count = _count(conn, "SELECT COUNT(*) FROM memberdef")lines 87–91has_table = bool( conn.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name='memberdef'" ).fetchone() )lines 92–92except sqlite3.Error as exclines 93–93return f"is not a readable SQLite database ({exc})"lines 96–96return _defect_reason(has_table, count)

Requirements

REQ-DDB-CONFIG-001

Flows

measure_shared_key

dict[str, Any] clew.propose.dryrun.measure_shared_key(Path db_path, Path repo_root, dict|None section)

Run the inferred shared-key pass with a section and read the result.

clew/propose/dryrun.py:220

Source · 26 lines
def measure_shared_key(db_path: Path, repo_root: Path, section: dict | None) -> dict[str, Any]:
    """Callers diff two of these — one with the candidate, one with `None` — so
    the yield attributed to a candidate excludes whatever the built-in ingot
    defaults would have produced on their own.

    @brief Measure the inferred shared-key layer under one candidate section.
    @version 2
    """
    from ..shared_key_edges import (
        import_shared_key_edges_inferred,
    )

    with db_copy(db_path) as copy:
        import_shared_key_edges_inferred(copy, repo_root, section, None)
        conn = sqlite3.connect(str(copy))
        measured: dict[str, Any] = {
            "edges": _count(conn, "SELECT COUNT(*) FROM shared_key_edges"),
            "self_loops": _count(
                conn, "SELECT COUNT(*) FROM shared_key_edges WHERE writer_rowid = reader_rowid"
            ),
            "by_key": _key_counts(conn),
        }
        conn.close()
    return measured

Activity · 7 steps
lines 228–230from ..shared_key_edges import ( import_shared_key_edges_inferred, )lines 232–232with db_copy(db_path) as copylines 233–233import_shared_key_edges_inferred(copy, repo_root, section, None)lines 234–234conn = sqlite3.connect(str(copy))lines 235–241measured: dict[str, Any] = { "edges": _count(conn, "SELECT COUNT(*) FROM shared_key_edges"), "self_loops": _count( conn, "SELECT COUNT(*) FROM shared_key_edges WHERE writer_rowid = reader_rowid" ), "by_key": _key_counts(conn), }lines 242–242conn.close()lines 243–243return measured

Requirements

REQ-DDB-CONFIG-001

measure_threads

dict[str, int] clew.propose.dryrun.measure_threads(Path db_path, Path repo_root, list[dict] spawns, frozenset[str] param_names=frozenset())

Run extract_threads with a candidate spawn list and measure the delta.

clew/propose/dryrun.py:151

Show on the map →

Called by measure_candidate

Calls _count, _thread_keys, _thread_metrics, db_copy, extract_threads

Source · 32 lines
def measure_threads(
    db_path: Path,
    repo_root: Path,
    spawns: list[dict],
    param_names: frozenset[str] = frozenset(),
) -> dict[str, int]:
    """`param_named` is the fabrication metric that matters. A wrapper whose own
    call sites forward a parameter rather than naming a function produces a
    thread named after that parameter, with a NULL entry and therefore no
    closure — measured at 1 such row for a C/POSIX library's out-of-scope
    `SYSTEM_TASKCREATE` and 0 for the wrapper that is proposed.

    @brief Measure a candidate spawn declaration's real yield.
    @version 3
    """
    from ..threads import extract_threads

    with db_copy(db_path) as copy:
        conn = sqlite3.connect(str(copy))
        before = _thread_keys(conn)
        measured = {
            "threads_before": len(before),
            "membership_before": _count(conn, "SELECT COUNT(*) FROM thread_membership"),
        }
        conn.close()
        extract_threads(copy, repo_root, {"spawns": spawns}, None)
        conn = sqlite3.connect(str(copy))
        measured.update(_thread_metrics(conn, before, param_names))
        conn.close()
    return measured

Activity · 11 steps
lines 166–166from ..threads import extract_threadslines 168–168with db_copy(db_path) as copylines 169–169conn = sqlite3.connect(str(copy))lines 170–170before = _thread_keys(conn)lines 171–174measured = { "threads_before": len(before), "membership_before": _count(conn, "SELECT COUNT(*) FROM thread_membership"), }lines 175–175conn.close()lines 176–176extract_threads(copy, repo_root, {"spawns": spawns}, None)lines 177–177conn = sqlite3.connect(str(copy))lines 178–178measured.update(_thread_metrics(conn, before, param_names))lines 179–179conn.close()lines 180–180return measured

Requirements

REQ-DDB-CONFIG-001