external.py

clew/external.py

Per-file EXTERNAL provenance — which indexed files belong to someone else's repo.

ensure_external_provenance

None clew.external.ensure_external_provenance(sqlite3.Connection conn)

Add the provenance columns to path , idempotently.

clew/external.py:86

Source · 29 lines
def ensure_external_provenance(conn: sqlite3.Connection) -> None:
    """`path` is DOXYGEN'S table — its sqlite3 backend creates it and we copy the
    file — so the column is namespaced (`dg_`) for the same reason `dg_source` is on
    `memberdef`: an unprefixed `external` would collide the day doxygen grows one,
    and the failure mode of that collision is not a loud `duplicate column name` but
    an idempotent ADD COLUMN finding a column already there and our reader then
    interpreting doxygen's semantics as ours.

    NULL, not `0`, is the untagged value, and the distinction is load-bearing on a
    partial build: `NULL` means "this row was never considered", while a stamped
    empty string would assert first-party membership the walk never checked. The
    reader treats NULL as first party for reporting and says so, rather than
    pretending the two are the same fact.

    TWO COLUMNS, because "owned by a named foreign tree" and "not a file of this
    repository at all" are different facts. Doxygen registers a `path` row for every
    unresolvable `#include`, spelled as a bare filename; those are neither first
    party nor attributable, and folding them into the external column would put a
    fabricated root into every `DISTINCT dg_external_root` listing.

    @brief Ensure `path` carries the external-root and unresolved columns.
    @version 2
    """
    if not _has_column(conn, "path", EXTERNAL_ROOT_COLUMN):
        conn.execute(f"ALTER TABLE path ADD COLUMN {EXTERNAL_ROOT_COLUMN} TEXT")
    if not _has_column(conn, "path", UNRESOLVED_PATH_COLUMN):
        conn.execute(f"ALTER TABLE path ADD COLUMN {UNRESOLVED_PATH_COLUMN} INTEGER")

Activity · 4 steps
lines 109–109◇ if not _has_column(conn, "path", EXTERNAL_ROOT_COLUMN)lines 110–110conn.execute(f"ALTER TABLE path ADD COLUMN {EXTERNAL_ROOT_COLUMN} TEXT")lines 111–111◇ if not _has_column(conn, "path", UNRESOLVED_PATH_COLUMN)lines 112–112conn.execute(f"ALTER TABLE path ADD COLUMN {UNRESOLVED_PATH_COLUMN} INTEGER")

Requirements

REQ-DDB-INDEX-005

external_roots

list[str] clew.external.external_roots(Path repo_root)

The external roots for a repo, repo-relative and outermost-first.

clew/external.py:147

Source · 26 lines
def external_roots(repo_root: Path) -> list[str]:
    """A THIN WRAPPER OVER `scope.dependency_roots` ON PURPOSE. The detection is
    the scope module's, and duplicating its walk here would produce a second answer
    to "which trees are foreign" that could disagree with the one the build actually
    indexed under.

    IT WRAPS `dependency_roots`, NOT `nested_repo_roots`, since gh#352 half 2. The wider
    walk answers "is there a separate git tree here?", which the scope tier needs so it can
    honour each tree's own `.gitignore`; this one answers "did the repository DECLARE this as
    somebody else's code?", which is a claim about the committed tree rather than about whoever
    happened to build it. Measured on entropic, the difference was three tagged roots against
    the one `.gitmodules` declares.

    Imported inside the function because `scope` pulls in the declaration loader and
    this module is reached from the query layer as well as the pipeline.

    @brief List the trees a repo declares as dependencies, repo-relative.
    @return Repo-relative paths.
    @version 2
    """
    from .scope import dependency_roots

    root = Path(repo_root).expanduser().resolve()
    return [rel for rel in (_relative_root(root, n) for n in dependency_roots(root)) if rel]

Activity · 3 steps
lines 167–167from .scope import dependency_rootslines 169–169root = Path(repo_root).expanduser().resolve()lines 170–170return [rel for rel in (_relative_root(root, n) for n in dependency_roots(root)) if rel]

Requirements

REQ-DDB-INDEX-005

stamp_external_provenance

tuple[int, list[str]] clew.external.stamp_external_provenance(Path db_path, Path repo_root)

Tag every indexed file that belongs to a nested foreign git tree.

clew/external.py:201

Source · 80 lines
def stamp_external_provenance(db_path: Path, repo_root: Path) -> tuple[int, list[str]]:
    """FAILS SOFT, like every other measurement stamped onto an already-successful
    build. A walk that raises must not destroy the index it is describing; the column
    then stays NULL everywhere, which the reader reports as "not recorded" rather
    than as "all first party".

    Returns the CONTRIBUTING roots as well as the count, because the caller stamps
    them into `build_meta` and re-deriving them there would walk the tree a second
    time. Contributing, not detected: a nested tree that some other rule already
    excluded owns no indexed row, and naming it would both mislead and publish a
    directory name this index deliberately does not cover.

    THE UNRESOLVED PASS IS WHAT MAKES THE FIRST-PARTY FIGURES INVARIANT, and it was
    added because the invariance was measured FAILING. On entropic, admitting the
    llama.cpp submodule added 324 bare-filename rows from its Ascend and Hexagon
    backends — unresolvable `#include` targets, all counted as first party because a
    bare filename matches no external root — and `indexed_files` moved 488 → 804 on a
    change that must move no first-party figure. The ratios held throughout, purely
    because those files do not exist on disk and the line count already dropped them
    from the substantive set. An invariant preserved by an accident one layer down is
    not preserved.

    @brief Stamp per-file external and unresolved provenance into the index.
    @return Rows tagged external, and the roots that own at least one of them.
    @version 3
    """
    root = Path(repo_root).expanduser().resolve()
    roots = external_roots(root)
    ## RUNS EVEN WITH NO NESTED TREE. The unresolved half is unconditional — a repo
    ## that vendors nothing still has unresolvable `#include` targets — and an early
    ## return on `not roots` would leave the columns absent, which the readers
    ## correctly report as "not recorded" and would therefore make every such repo
    ## look like an index that predates gh#335.
    try:
        conn = sqlite3.connect(str(db_path))
    except sqlite3.Error as exc:
        logger.warning("external provenance not recorded (%s)", exc)
        return 0, roots
    try:
        ensure_external_provenance(conn)
        rows = conn.execute(
            "SELECT rowid, name FROM path WHERE type=?", (PATH_TYPE_FILE,)
        ).fetchall()
        owned = [(_owning_root(name, roots), rid) for rid, name in rows if name]
        updates = [pair for pair in owned if pair[0]]
        conn.executemany(f"UPDATE path SET {EXTERNAL_ROOT_COLUMN}=? WHERE rowid=?", updates)
        missing = [(rid,) for rid, name in rows if name and not (root / name).is_file()]
        conn.executemany(f"UPDATE path SET {UNRESOLVED_PATH_COLUMN}=1 WHERE rowid=?", missing)
        conn.commit()
        tagged = len(updates)
    except sqlite3.Error as exc:
        logger.warning("external provenance not recorded (%s)", exc)
        return 0, []
    finally:
        conn.close()
    ## ONLY THE ROOTS THAT ACTUALLY OWN A ROW ARE REPORTED, and the empty ones are
    ## counted rather than named. Two independent reasons, and either alone is enough:
    ##
    ## - A root that contributed nothing is a fact about the FILESYSTEM, not about
    ##   this index, and publishing it as an `external_roots` entry invites the exact
    ##   misreading that cost a measurement here — "0 files belong to 1 nested tree"
    ##   reads like a broken detector and is usually a tree some other rule excluded.
    ## - ANYTHING STAMPED HERE IS PUBLISHED OVER MCP. A nested tree that is excluded
    ##   from the index is precisely the one whose NAME we have no business emitting;
    ##   this walk sees every directory on disk, including ones no rule wants indexed.
    contributing = sorted({owner for owner, _ in updates})
    logger.info(
        "external provenance: %d indexed file(s) belong to %d nested git tree(s) (%s); "
        "%d further nested tree(s) contributed no indexed file and are not listed; "
        "%d row(s) resolve to no file in this repository (unresolved #include targets, "
        "which doxygen records by bare filename). The nested trees are INDEXED and "
        "queryable — chain_trace and callers/callees cross the boundary — but coverage, "
        "orphan and file counts report FIRST PARTY by default.",
        tagged,
        len(contributing),
        ", ".join(contributing) or "none",
        len(roots) - len(contributing),
        len(missing),
    )
    return tagged, contributing

1 more lines, not shown

Activity · 23 steps
lines 227–227root = Path(repo_root).expanduser().resolve()lines 228–228roots = external_roots(root)lines 234–234trylines 235–235conn = sqlite3.connect(str(db_path))lines 236–236except sqlite3.Error as exclines 237–237logger.warning("external provenance not recorded (%s)", exc)lines 238–238return 0, rootslines 239–239trylines 240–240ensure_external_provenance(conn)lines 241–243rows = conn.execute( "SELECT rowid, name FROM path WHERE type=?", (PATH_TYPE_FILE,) ).fetchall()lines 244–244owned = [(_owning_root(name, roots), rid) for rid, name in rows if name]lines 245–245updates = [pair for pair in owned if pair[0]]lines 246–246conn.executemany(f"UPDATE path SET {EXTERNAL_ROOT_COLUMN}=? WHERE rowid=?", updates)lines 247–247missing = [(rid,) for rid, name in rows if name and not (root / name).is_file()]lines 248–248conn.executemany(f"UPDATE path SET {UNRESOLVED_PATH_COLUMN}=1 WHERE rowid=?", missing)lines 249–249conn.commit()lines 250–250tagged = len(updates)lines 251–251except sqlite3.Error as exclines 252–252logger.warning("external provenance not recorded (%s)", exc)lines 253–253return 0, []lines 266–266contributing = sorted({owner for owner, _ in updates})lines 267–279logger.info( "external provenance: %d indexed file(s) belong to %d nested git tree(s) (%s); " "%d further nested tree(s) contributed no indexed file and are not listed; " "%d row(s) resolve to no file in this repository (unresolved #include targets, " "which doxygen records by bare filename). The nested trees are INDEXED and " "queryable — chain_trace and callers/callees cross the boundary — but coverage, " "orphan and file counts report FIRST PARTY by default.", tagged, len(contributing), ", ".join(contributing) or "none", len(roots) - len(contributing), len(missing), )lines 280–280return tagged, contributing

Requirements

REQ-DDB-INDEX-005