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.
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
Requirements
external_roots
list[str] clew.external.external_roots(Path repo_root)
The external roots for a repo, repo-relative and outermost-first.
Called by _candidates, stamp_external_provenance
Tested by 6 tests
test_a_declared_root_indexes_a_nested_repository, test_a_nested_tree_with_no_indexed_file_is_not_reported, test_a_stray_developer_clone_the_parent_tracks_is_first_party, test_a_submodule_whose_git_is_a_file_is_detected, test_only_a_directory_with_its_own_git_tree_is_external, test_the_whole_repo_scope_indexes_a_nested_repository
Calls _relative_root, dependency_roots
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
Requirements
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.
Called by _build_stages
Tested by 9 tests
test_a_nested_tree_with_no_indexed_file_is_not_reported, test_a_shared_path_prefix_does_not_misattribute_a_sibling_tree, test_a_stray_developer_clone_the_parent_tracks_is_first_party, test_admitting_a_submodule_leaves_first_party_coverage_identical, test_an_unresolved_include_is_neither_first_party_nor_external, test_directory_rollup_says_what_it_counts_and_lists_external_files, test_graph_stats_counts_first_party_and_reports_external_beside_it, test_list_files_returns_external_files_annotated_not_filtered, test_only_a_directory_with_its_own_git_tree_is_external
Calls _owning_root, ensure_external_provenance, external_roots
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, contributing1 more lines, not shown