doxygen_splice.py

clew/doxygen_splice.py

Incremental doxygen regeneration: re-read a SUBSET and splice it into the master.

include_expansion

set[str] clew.doxygen_splice.include_expansion(Path subset_db, Path master_db, set[str] changed, set[str] have, Path repo_root)

Files a first subset run reveals it needs but did not have.

clew/doxygen_splice.py:243

Source · 106 lines
def include_expansion(
    subset_db: Path,
    master_db: Path,
    changed: set[str],
    have: set[str],
    repo_root: Path,
) -> set[str]:
    """WHY `xref_closure` ALONE IS NOT ENOUGH, and this is the defect that motivated it.
    `xref_closure` reads the PRE-EDIT master, so it can only re-supply the callees a changed
    file ALREADY called. A change set is exactly where NEW calls appear: the callee's file was
    never in the old xref table, never joins the subset, and doxygen cannot resolve the name —
    so the edge is silently absent, `xrefs_unresolved` cannot count it because the row never
    exists, and the report looks healthy. Reproduced on the C fixture: adding
    `sound_play_findme(1)` to `main.c` produced a subset with no `src/sound/*` file and lost
    exactly that edge against a full rebuild.

    THE SIGNAL IS THE INCLUDE GRAPH, AND IT COMES FROM DOXYGEN RATHER THAN FROM A REGEX. In
    C and C++ a cross-file call requires a visible declaration, so a NEW call implies a header
    the changed file includes. The first subset run records those includes even for a header
    it could not follow, so pass one tells us what pass two needs. Every header the changed
    files include is considered, not only the newly added ones: a file may already have
    included a header it never called into, which leaves no xref to close over either.

    Mapping a header to its implementation uses the MASTER, which is sound because a header's
    definitions living elsewhere is not something the edit changed.

    ONE EXTRA ITERATION, not a fixed point. That resolves a call introduced directly by the
    edit, which is the measured case. A call reachable only through two new hops would still
    need a full rebuild, and the generation limit bounds how long any such gap can persist.

    C AND C++ ONLY, AND THAT IS A REAL GAP RATHER THAN A CAVEAT. The signal is the `includes`
    table, and doxygen populates it from `#include`. Measured: this repository's own index has
    42 include rows and ZERO of them come from a `.py` file, against 2130 on a C++ target. So
    on a Python or Rust target this function returns the empty set and a newly-added cross-file
    call is still lost until the next full rebuild. The equivalent signal there is `import`,
    which doxygen does not record — closing it needs the tree-sitter layer, not this one. Said
    plainly because the sibling fix for the Doxyfile surface claimed a closure it did not have,
    and an overclaim is worse than an open gap.

    @brief Compute the second-pass expansion from the include graph.
    @return Paths to add, empty when none are needed.
    @version 1
    """
    if not changed:
        return set()
    headers: set[str] = set()
    sub = sqlite3.connect(subset_db)
    try:
        rows = sub.execute(
            "SELECT s.name, d.name FROM includes i "
            "JOIN path s ON s.rowid = i.src_id JOIN path d ON d.rowid = i.dst_id"
        ).fetchall()
    except sqlite3.OperationalError:
        return set()
    finally:
        sub.close()
    for raw_src, raw_dst in rows:
        if normalize_path(str(raw_src), repo_root) in changed:
            headers.add(normalize_path(str(raw_dst), repo_root))
    if not headers:
        return set()

    wanted: set[str] = set()
    conn = sqlite3.connect(master_db)
    try:
        known = [
            normalize_path(str(name), repo_root)
            for (name,) in conn.execute("SELECT name FROM path WHERE type = 1")
        ]
        ## AN UNRESOLVED INCLUDE IS RECORDED AS ITS LITERAL TEXT, and that is the whole reason
        ## the first version of this found nothing. When the includee is not in the subset
        ## INPUT, doxygen stores the `#include` string itself — `sound/sound_service.h`,
        ## `../sound/sound_service.h` — with `found = 0`, NOT the repo-relative path. Matching
        ## those against the master's `src/sound/sound_service.h` by equality misses every
        ## time, which is exactly the case this function exists to catch.
        ##
        ## Resolved by PATH-SUFFIX at a `/` boundary. Over-matching is safe here: the only
        ## effect is a slightly wider second-pass INPUT, and a wider subset cannot produce a
        ## wrong edge — it can only resolve more of them.
        resolved: set[str] = set()
        for header in headers:
            fragment = header.lstrip("./")
            for candidate in known:
                if candidate == fragment or candidate.endswith("/" + fragment):
                    resolved.add(candidate)
        wanted |= resolved
        ## NORMALISED IN PYTHON, NOT MATCHED IN SQL. `path.name` in a raw doxygen database is
        ## ABSOLUTE whenever the Doxyfile's INPUT was absolute, so an `IN (...)` against
        ## repo-relative names silently returns nothing — the same absolute-versus-relative
        ## mismatch as the unresolved include text above, one query over. Pulling the pairs and
        ## comparing after normalisation cannot drift from whatever spelling doxygen chose.
        for raw_decl, raw_body in conn.execute(
            "SELECT fp.name, bp.name FROM memberdef m "
            "JOIN path fp ON fp.rowid = m.file_id "
            "JOIN path bp ON bp.rowid = m.bodyfile_id "
            "WHERE m.bodyfile_id IS NOT NULL"
        ):
            if normalize_path(str(raw_decl), repo_root) in resolved:
                wanted.add(normalize_path(str(raw_body), repo_root))
    except sqlite3.OperationalError:
        return set()
    finally:
        conn.close()
    return {p for p in wanted if p and p not in have}

Activity · 30 steps
lines 286–286◇ if not changedlines 287–287return set()lines 288–288headers: set[str] = set()lines 289–289sub = sqlite3.connect(subset_db)lines 290–290trylines 291–294rows = sub.execute( "SELECT s.name, d.name FROM includes i " "JOIN path s ON s.rowid = i.src_id JOIN path d ON d.rowid = i.dst_id" ).fetchall()lines 295–295except sqlite3.OperationalErrorlines 296–296return set()lines 299–299◇ for raw_src, raw_dst in rowslines 300–300◇ if normalize_path(str(raw_src), repo_root) in changedlines 301–301headers.add(normalize_path(str(raw_dst), repo_root))lines 302–302◇ if not headerslines 303–303return set()lines 305–305wanted: set[str] = set()lines 306–306conn = sqlite3.connect(master_db)lines 307–307trylines 308–311known = [ normalize_path(str(name), repo_root) for (name,) in conn.execute("SELECT name FROM path WHERE type = 1") ]lines 322–322resolved: set[str] = set()lines 323–323◇ for header in headerslines 324–324fragment = header.lstrip("./")lines 325–325◇ for candidate in knownlines 326–326◇ if candidate == fragment or candidate.endswith("/" + fragment)lines 327–327resolved.add(candidate)lines 328–328wanted |= resolvedlines 334–334◇ for raw_decl, raw_body in conn.execute(lines 340–340◇ if normalize_path(str(raw_decl), repo_root) in resolvedlines 341–341wanted.add(normalize_path(str(raw_body), repo_root))lines 342–342except sqlite3.OperationalErrorlines 343–343return set()lines 346–346return {p for p in wanted if p and p not in have}

Requirements

REQ-DDB-INDEX-002

normalize_path

str clew.doxygen_splice.normalize_path(str name, Path repo_root)

Reduce a doxygen path row to its repo-relative form.

clew/doxygen_splice.py:124

Show on the map →

Called by _file_rowids, _insert_includes, _remap_optional_path, _snapshot, include_expansion, xref_closure

Calls none

Source · 19 lines
def normalize_path(name: str, repo_root: Path) -> str:
    """Doxygen emits MOSTLY repo-relative names but not exclusively — the pipeline's
    `fix_doxygen_paths` stage rewrites the remainder later, and this splice runs BEFORE
    that. So two databases can spell the same file differently and a naive string compare
    would treat one file as two, silently declining to delete the stale rows.

    @brief Normalise a doxygen path to repo-relative.
    @return Repo-relative string.
    @version 1
    """
    candidate = Path(name)
    if not candidate.is_absolute():
        return candidate.as_posix()
    try:
        return candidate.relative_to(repo_root).as_posix()
    except ValueError:
        return candidate.as_posix()

Activity · 7 steps
lines 134–134candidate = Path(name)lines 135–135◇ if not candidate.is_absolute()lines 136–136return candidate.as_posix()lines 137–137trylines 138–138return candidate.relative_to(repo_root).as_posix()lines 139–139except ValueErrorlines 140–140return candidate.as_posix()

Requirements

REQ-DDB-INDEX-002

splice_doxygen

SpliceReport clew.doxygen_splice.splice_doxygen(Path master_db, Path|None subset_db, set[str] changed, Path out, Path repo_root, set[str]|None removed=None)

Rebuild the master doxygen database by re-reading only the changed files.

clew/doxygen_splice.py:959

Show on the map →

Called by _incremental_doxygen

Tested by

2 teststest_editing_a_base_class_keeps_its_derived_classes_in_other_files, test_incremental_splice_matches_a_full_rebuild

Calls _delete_file_rows, _file_rowids, _insert_compounds, _insert_includes, _insert_members, _insert_params, _insert_relations, _insert_xrefs

Source · 86 lines
def splice_doxygen(
    master_db: Path,
    subset_db: Path | None,
    changed: set[str],
    out: Path,
    repo_root: Path,
    removed: set[str] | None = None,
) -> SpliceReport:
    """THE COPY HAPPENS FIRST, and that ordering is load-bearing. Every key in
    `doxygen_cache` names the SAME output path and each build OVERWRITES it, so a subset run
    clobbers the very database being spliced from. `master_db` must therefore be copied to
    `out` BEFORE the subset run — the caller's ordering, enforced here by refusing to run
    when the copy source is missing.

    Only the CHANGED files' rows are replaced. Closure files were re-read so their edges
    resolve; their own rows in the master are still correct and are left alone.

    `removed` is DELETE-ONLY and exists so an ordinary deletion does not force a full
    rebuild. A deleted file appears in no subset run — there is nothing to re-read — so
    without this it would land in `skipped` and its rows would persist as a phantom symbol
    the index still answers about. Branch switches make that common, not exotic.

    @brief Splice a subset doxygen run into the master database.
    @return The splice report.
    @version 3
    """
    report = SpliceReport()
    if not master_db.exists():
        report.skipped.append("master database missing")
        return report
    if subset_db is not None and not subset_db.exists():
        report.skipped.append("subset database missing")
        return report

    if out.resolve() != master_db.resolve():
        shutil.copy2(master_db, out)

    work = sqlite3.connect(out)
    ## DELETIONS-ONLY takes no subset run. Feeding the master back in as its own subset
    ## would re-insert the very rows the removal loop just deleted, so there is no
    ## connection to open and the insert phase is skipped outright.
    sub = sqlite3.connect(subset_db) if subset_db is not None else None
    try:
        work.execute("PRAGMA foreign_keys = OFF")
        ctx = {
            "repo_root": repo_root,
            "work_paths": _file_rowids(work, repo_root),
            "sub_paths": _file_rowids(sub, repo_root) if sub is not None else {},
        }
        for rel in sorted(removed or ()):
            gone = ctx["work_paths"].get(rel)
            if gone is not None:
                _delete_file_rows(work, gone, report)
                report.files_removed += 1
        for rel in sorted(changed):
            if rel not in ctx["sub_paths"]:
                ## The subset run did not produce this file. Refusing to delete its master
                ## rows is the fail-closed choice: dropping them would silently shrink the
                ## graph, where keeping them merely leaves them one build stale.
                report.skipped.append(rel)
                continue
            existing = ctx["work_paths"].get(rel)
            if existing is not None:
                _delete_file_rows(work, existing, report)
            _insert_compounds(work, sub, rel, ctx, report)
            _insert_members(work, sub, rel, ctx, report)
            report.files_replaced += 1
        if sub is not None:
            _insert_relations(work, sub, changed, ctx, report)
            _insert_params(work, sub, changed, ctx, report)
            _insert_includes(work, sub, changed, ctx, report)
            _insert_xrefs(work, sub, changed, ctx, report)
        work.commit()
    finally:
        if sub is not None:
            sub.close()
        work.close()

    if report.skipped:
        logger.warning(
            "doxygen splice: %d file(s) absent from the subset run and left stale: %s",
            len(report.skipped),
            ", ".join(report.skipped[:5]),
        )
    logger.info("doxygen splice: %s", report.describe())
    return report

1 more lines, not shown

Activity · 39 steps
lines 985–985report = SpliceReport()lines 986–986◇ if not master_db.exists()lines 987–987report.skipped.append("master database missing")lines 988–988return reportlines 989–989◇ if subset_db is not None and not subset_db.exists()lines 990–990report.skipped.append("subset database missing")lines 991–991return reportlines 993–993◇ if out.resolve() != master_db.resolve()lines 994–994shutil.copy2(master_db, out)lines 996–996work = sqlite3.connect(out)lines 1000–1000sub = sqlite3.connect(subset_db) if subset_db is not None else Nonelines 1001–1001trylines 1002–1002work.execute("PRAGMA foreign_keys = OFF")lines 1003–1007ctx = { "repo_root": repo_root, "work_paths": _file_rowids(work, repo_root), "sub_paths": _file_rowids(sub, repo_root) if sub is not None else {}, }lines 1008–1008◇ for rel in sorted(removed or ())lines 1009–1009gone = ctx["work_paths"].get(rel)lines 1010–1010◇ if gone is not Nonelines 1011–1011_delete_file_rows(work, gone, report)lines 1012–1012report.files_removed += 1lines 1013–1013◇ for rel in sorted(changed)lines 1014–1014◇ if rel not in ctx["sub_paths"]lines 1018–1018report.skipped.append(rel)lines 1019–1019continuelines 1020–1020existing = ctx["work_paths"].get(rel)lines 1021–1021◇ if existing is not Nonelines 1022–1022_delete_file_rows(work, existing, report)lines 1023–1023_insert_compounds(work, sub, rel, ctx, report)lines 1024–1024_insert_members(work, sub, rel, ctx, report)lines 1025–1025report.files_replaced += 1lines 1026–1026◇ if sub is not Nonelines 1027–1027_insert_relations(work, sub, changed, ctx, report)lines 1028–1028_insert_params(work, sub, changed, ctx, report)lines 1029–1029_insert_includes(work, sub, changed, ctx, report)lines 1030–1030_insert_xrefs(work, sub, changed, ctx, report)lines 1031–1031work.commit()lines 1037–1037◇ if report.skippedlines 1038–1042logger.warning( "doxygen splice: %d file(s) absent from the subset run and left stale: %s", len(report.skipped), ", ".join(report.skipped[:5]), )lines 1043–1043logger.info("doxygen splice: %s", report.describe())lines 1044–1044return report

Requirements

REQ-DDB-INDEX-002

xref_closure

set[str] clew.doxygen_splice.xref_closure(Path master_db, set[str] changed, Path repo_root)

The files a correct subset run must include alongside the changed set.

clew/doxygen_splice.py:188

Source · 45 lines
def xref_closure(master_db: Path, changed: set[str], repo_root: Path) -> set[str]:
    """BOTH DIRECTIONS, and the asymmetry is the whole point. A subset run can only emit an
    edge when it can see BOTH endpoints, so:

      - inbound  — files holding members that refer INTO a changed file. Without them the
        edges arriving at the change cannot be re-emitted.
      - outbound — files holding the members a changed file refers TO. Without them the
        edges leaving the change cannot be re-emitted. Measured: 0 of 38 survived a
        changed-file-only run.

    Returns the union including `changed` itself, so the result is directly the doxygen
    INPUT list.

    @brief Compute the bidirectional one-hop xref closure.
    @return Paths to re-read.
    @version 1
    """
    if not changed:
        return set()
    conn = sqlite3.connect(master_db)
    try:
        pairs = [row for sql in _CLOSURE_EDGES for row in conn.execute(sql).fetchall()]
    except sqlite3.OperationalError as exc:
        logger.warning(
            "doxygen splice: cannot read xrefs from %s (%s) — falling back to a full run",
            master_db,
            exc,
        )
        return set()
    finally:
        conn.close()

    result = set(changed)
    for raw_src, raw_dst in pairs:
        src = normalize_path(str(raw_src), repo_root)
        dst = normalize_path(str(raw_dst), repo_root)
        ## Outbound: the change refers to dst, so dst's definitions must be visible.
        if src in changed:
            result.add(dst)
        ## Inbound: src refers to the change, so src's call sites must be visible.
        if dst in changed:
            result.add(src)
    return result

Activity · 17 steps
lines 205–205◇ if not changedlines 206–206return set()lines 207–207conn = sqlite3.connect(master_db)lines 208–208trylines 209–209pairs = [row for sql in _CLOSURE_EDGES for row in conn.execute(sql).fetchall()]lines 210–210except sqlite3.OperationalError as exclines 211–215logger.warning( "doxygen splice: cannot read xrefs from %s (%s) — falling back to a full run", master_db, exc, )lines 216–216return set()lines 220–220result = set(changed)lines 221–221◇ for raw_src, raw_dst in pairslines 222–222src = normalize_path(str(raw_src), repo_root)lines 223–223dst = normalize_path(str(raw_dst), repo_root)lines 225–225◇ if src in changedlines 226–226result.add(dst)lines 228–228◇ if dst in changedlines 229–229result.add(src)lines 230–230return result

Requirements

REQ-DDB-INDEX-002