signature.py

clew/signature.py

Build-version signature stamped into every built clew.db.

index_unusable_reason

str clew.signature.index_unusable_reason(Path|str db_path)

Why a path is not a usable index, or "" when it is one.

clew/signature.py:514

Show on the map →

Called by none

Calls _filesystem_problem, _sqlite_problem

Source · 31 lines
def index_unusable_reason(db_path: Path | str) -> str:
    """ONE rule, in one place, because there were two behaviours and the wrong one
    shipped in the more visible surface.

    `sqlite3.connect` on a nonexistent path CREATES an empty database. Nothing
    raises; every `table_exists` guard downstream correctly answers False; and the
    HTML explorer emitted a structurally valid document describing zero functions.
    That is worse than a traceback: a traceback is a question, and a plausible
    empty report is a wrong answer. The proposer already refused a zero-byte
    `clew.db` for exactly this reason — this makes that the shared rule rather than
    one module's good habit.

    Deliberately NOT used by `query/_common.connect`. The query layer's contract is
    the opposite one and was settled on purpose: it DEGRADES on a partial database
    so a consumer gets empty results rather than an exception, since a stale index
    missing a later layer is a normal thing to query. This helper is for surfaces
    that PRODUCE something — an emitted document, a served page, a build — where
    proceeding means publishing a falsehood.

    Returns a reason rather than raising or returning a bool: the caller decides
    the exit code and gets a message it can print next to a rebuild command,
    without either restating the checks or losing which one failed.

    @brief Judge whether a path holds a usable index, and say why not.
    @return Reason string, empty when usable.
    @version 2
    """
    path = Path(db_path)
    return _filesystem_problem(path) or _sqlite_problem(path)

Activity · 2 steps
lines 541–541path = Path(db_path)lines 542–542return _filesystem_problem(path) or _sqlite_problem(path)

Requirements

REQ-DDB-PIPE-005

read_build_signature

int | None clew.signature.read_build_signature(Path|str db_path)

Read the build version stamped into a DB, or None if absent/unreadable.

clew/signature.py:482

Source · 20 lines
def read_build_signature(db_path: Path | str) -> int | None:
    row = None
    try:
        conn = sqlite3.connect(str(db_path))
        try:
            row = conn.execute(
                "SELECT value FROM build_meta WHERE key = 'build_version'"
            ).fetchone()
        finally:
            conn.close()
    except sqlite3.Error:
        row = None
    if not row:
        return None
    try:
        return int(row[0])
    except (TypeError, ValueError):
        return None

Activity · 13 steps
lines 483–483row = Nonelines 484–484trylines 485–485conn = sqlite3.connect(str(db_path))lines 486–486trylines 487–489row = conn.execute( "SELECT value FROM build_meta WHERE key = 'build_version'" ).fetchone()lines 492–492except sqlite3.Errorlines 493–493row = Nonelines 494–494◇ if not rowlines 495–495return Nonelines 496–496trylines 497–497return int(row[0])lines 498–498except (TypeError, ValueError)lines 499–499return None

Requirements

REQ-DDB-PIPE-005

Flows

write_build_signature

None clew.signature.write_build_signature(Path|str db_path, int version=CLEW_BUILD_VERSION, dict[str, str]|None scope=None, dict[str, str]|None coverage=None, dict[str, str]|None preprocessor=None, dict[str, str]|None kconfig=None, dict[str, str]|None refresh=None, dict[str, str]|None options=None, dict[str, str]|None diagnostics=None, dict[str, str]|None data_model=None, dict[str, str]|None declaration=None, dict[str, str]|None tool=None)

Stamp the build version, scope, coverage and preprocessor config into build_meta.

clew/signature.py:299

Show on the map →

Called by _build_stages, _index, _stamp, _stamp_manifest, _stamp_refresh_metrics, run_real_stages

Tested by

39 teststest_a_kconfig_that_cannot_be_parsed_is_recorded_rather_than_silent, test_a_measured_zero_survives_the_build_signature, test_a_non_positive_cull_age_leaves_every_current_index_alone, test_a_repo_with_no_kconfig_is_completely_unaffected, test_a_routed_build_registers_the_target_without_adopting_it, test_a_sessions_own_build_invalidates_its_stale_active_default, test_a_zero_count_survives_the_falsy_drop, test_a_zero_refresh_measurement_survives_persistence, test_an_unrecorded_toolchain_leaves_no_row, test_auto_refresh_targets_the_named_sub_index_not_a_sibling, test_build_meta_records_the_stated_declaration, test_concurrent_refreshes_of_different_targets_are_not_serialised
27 moretest_concurrent_refreshes_of_one_target_build_it_once, test_coverage_is_persisted_into_build_meta_and_reaches_status, test_cull_drops_a_never_built_row_without_touching_a_current_index, test_cull_drops_stale_and_keeps_current, test_db_status_freshness_uses_build_signature, test_db_status_reports_the_fast_section_and_counts_it_as_stale, test_dossier_and_search_route_to_the_named_sub_index, test_gate_counts_reach_the_symbol_rows, test_index_refresh_tool_forwards_sub_index_through_the_dispatcher, test_nothing_is_stated_and_nothing_replays_for_a_target_that_states_nothing, test_reading_provenance_off_an_older_index_is_empty_not_an_error, test_refresh_with_sub_index_builds_only_that_sub_index, test_stamping_the_refresh_section_preserves_scope_and_version, test_status_interprets_an_unresolvable_version_skew, test_status_names_the_options_an_operator_stated, test_status_on_a_PRE_COVERAGE_index_says_nothing_rather_than_guessing, test_status_on_a_PRE_DIAGNOSTICS_index_says_nothing_rather_than_guessing, test_status_on_a_PRE_SCOPE_index_says_nothing_rather_than_guessing, test_status_publishes_the_barren_ratio_and_offenders, test_status_reports_WHAT_THE_BUILD_DID_NOT_FIND, test_status_reports_WHY_the_file_set_is_what_it_is, test_the_alias_tier_is_stamped_beside_the_entry_pattern_tier, test_the_configured_variant_travels_beside_the_space, test_the_refresh_cost_round_trips_into_status, test_the_stamped_prefix_round_trips, test_the_stored_tables_round_trip_through_the_query_layer, test_the_tool_section_is_stamped_under_its_own_prefix

Calls none

Source · 120 lines
def write_build_signature(
    db_path: Path | str,
    version: int = CLEW_BUILD_VERSION,
    scope: dict[str, str] | None = None,
    coverage: dict[str, str] | None = None,
    preprocessor: dict[str, str] | None = None,
    kconfig: dict[str, str] | None = None,
    refresh: dict[str, str] | None = None,
    options: dict[str, str] | None = None,
    diagnostics: dict[str, str] | None = None,
    data_model: dict[str, str] | None = None,
    declaration: dict[str, str] | None = None,
    tool: dict[str, str] | None = None,
) -> None:
    """WHY THE FILE SET IS WHAT IT IS, recorded rather than only logged.

    `scope.DerivedScope` already carries the source (`clew-declaration` /
    `doxyfile` / `whole-repo`), a human-readable reason, and the roots and excludes — and its own docstring
    says it exists "so the BUILD LOG can always say which scope was used and why". The log is
    gone by the time anyone queries the index, so a consumer could see WHAT was indexed and
    never WHY.

    Measured on the entropic acceptance grid: the raw arm scored 3/3 on "checks the Doxyfile
    and reports that its INPUT does not list examples/" and the index arm 1/3 — the only
    clearly actionable gap in 56 marks. An agent could not ask why a file was or was not
    indexed, because nothing in the database answered it. `build_meta` held exactly one key.

    Written under a `scope.` prefix so the namespace stays legible as build_meta grows, and
    absent rather than empty when no scope was derived — a missing key means "not recorded",
    which is honest, while `scope.source=""` would read as a decision that was made and was
    blank.

    COVERAGE rides along for the same reason, and against the same defect: index SIZE
    was reported and index COVERAGE was not, so a build could announce thousands of
    functions for a target whose index held almost none of the library (gh#6 — 184 of
    221 implementation files yielded at most one symbol, and nothing said so). A
    coverage number that lives only in a build warning is gone by query time exactly
    as the scope decision was.

    Every section is namespaced and written by the same prefixing pass, so a further
    section is a one-line change rather than another copy of this loop. gh#17 was that
    one line, and it is the third leg of the same argument: `scope.*` says WHICH FILES
    were indexed, `coverage.*` says how much of them yielded anything, and
    `preprocessor.*` says WHICH VARIANT of them the index describes. A multi-variant
    codebase — anything with a config header — produces a different set of FUNCTIONS per
    configuration, so without that last section two indexes of one repo can disagree
    about whether a symbol exists at all and nothing in either explains it.

    `kconfig.*` is the FOURTH leg and the one that is not about this build at all.
    `scope.*` says which files were indexed, `coverage.*` how much of them yielded
    anything, `preprocessor.*` which variant of them this index describes — and
    `kconfig.*` says which variants the repository HAS, which is a fact about the
    repository rather than about the index. It carries `kconfig.error` for the same
    reason `preprocessor` records a macro count of zero: a Kconfig that was found and
    could not be parsed is a finding, and it is the finding a Zephyr application
    indexed outside its west workspace produces.

    `refresh.*` is the FIFTH leg and the only one about the BUILD rather than about the
    repository or the index's contents: what this run cost in wall milliseconds, how many
    files it reprocessed, and how many it took from cache. Same argument as the other
    four, one step further — a cost that lives only in a log line is gone by the time an
    agent has to decide whether correcting a stale index is worth it, and an agent that
    cannot measure the correction estimates it badly (gh#9: two acceptance marks demanding
    a measured number, missed in 9 of 9 cells at every model tier).

    It is also the section most exposed to the falsy-drop rule below, because a fully
    cached build legitimately reprocesses ZERO files and a small build legitimately takes
    under a millisecond. Callers pass strings; `"0"` survives where `0` would not.

    `options.*` is the SIXTH leg and the first that records a DECISION rather than a
    measurement (gh#319). The other five say what was indexed, how much of it yielded
    anything, which variant it describes, which variants exist and what the run cost;
    this one says which precedence TIER supplied a layered setting — an operator's
    flag, the target's declaration, or our own provisional guesses. Without it a
    liveness split computed from a repo's declared dispatch vocabulary is
    indistinguishable from one computed from `%handler%`, and the whole point of
    resolving in tiers is lost the moment the winner is not written down.

    Its values come from `tiers.options_meta`, which accepts only `LayeredResolution` and
    `DocumentResolution` objects — so this section cannot be populated from values whose
    provenance was discarded on the way here. A `DocumentResolution` also carries the
    stated manifest itself, as canonical JSON, because a tier-1 statement is REPLAYED onto
    a later build (gh#364) and a policy that is applied but never recorded is discarded by
    the next refresh, which then reports success over a different one.

    `diagnostics.*` is the SEVENTH leg and the only one that records what is NOT in the
    index (gh#320). The other six describe rows that exist; this one names the accessor
    families and event alias tags the build searched for, did not claim, and therefore
    wrote no rows for. It carries its counts as STRINGS for the reason the falsy-drop rule
    above demands and `refresh` already illustrates — the zero is the measurement here, so
    dropping it would leave "searched and found nothing" indistinguishable from "never
    looked", which is the exact ambiguity the section exists to remove.

    `data_model.*` is the EIGHTH leg (gh#351) and, like `kconfig.*`, it describes the
    REPOSITORY rather than the index: which generated data model the repository declares, how
    many keys and classes it carries, and how many of those keys the code was observed to
    touch. Its refusals are the actionable half — `data_model.manifests_unlisted` says
    manifest documents were found and declined for want of a key list to vouch for them,
    which is the difference between a repository with no data model and one whose model
    nothing selects. Counts are STRINGS for the falsy-drop reason above.

    `declaration.*` is the NINTH leg, and it is the only one that records what an OPERATOR
    stated rather than what the repository contains. `options.*` records which TIER won per
    option, which is not the same claim: a document stated with `--declare` can be applied,
    recorded per-option, and then partly LOST on a later build, because only tier-1 statements
    replay and a section added to the document after that build never reaches the index at all.
    Measured 2026-08-14 on the mbedtls acceptance target, and it invalidated a graded run: the
    committed declaration declared `locks`, `vendored` and `preprocessor`; the graded index
    held `options.locks.tier=explicit` (replayed from an older build) and
    `options.predefined.tier=heuristic` with no `vendored` row anywhere. The measurement looked
    healthy from every angle a reader had, because nothing recorded WHICH DOCUMENT was stated.

    CONTENT-ADDRESSED, and no per-section knowledge. `stated_sha256` is over the document's
    bytes and `stated_sections` names its top-level keys, so a checker compares the file it
    holds against the build with no map from section name to the evidence that section leaves.
    That absence of a map is the point: `preprocessor:` lands as `options.predefined.*` and
    `vendored:` leaves no `options.*` row at all, so any such map is a second vocabulary free
    to drift as sections are added — and the section it forgot would be the silent one.

    NO PATH IS STORED. The stated document lives in the CONSUMER'S tree, not the target's, so a

58 more lines, not shown

Activity · 8 steps
lines 426–426conn = sqlite3.connect(str(db_path))lines 427–427trylines 428–428conn.execute("CREATE TABLE IF NOT EXISTS build_meta (key TEXT PRIMARY KEY, value TEXT)")lines 429–429rows = [("build_version", str(version))]lines 434–434◇ for prefix, section in (lines 466–466rows += [(f"{prefix}.{k}", v) for k, v in sorted((section or {}).items()) if v]lines 467–471conn.executemany( "INSERT INTO build_meta(key, value) VALUES(?, ?) " "ON CONFLICT(key) DO UPDATE SET value = excluded.value", rows, )lines 472–472conn.commit()

Requirements

REQ-DDB-CONFIG-006 REQ-DDB-CONFIG-007 REQ-DDB-PIPE-005