datamodel.py

clew/datamodel.py

TIER 4: a generated data model's OWN manifests, read as the key catalog they are.

_ensure_table

None clew.datamodel._ensure_table(sqlite3.Connection conn)

Create the data_model_keys table if it does not already exist.

clew/datamodel.py:1183

Source · 40 lines
def _ensure_table(conn: sqlite3.Connection) -> None:
    """UNIQUE on `(define_name, manifest)` rather than on `define_name` alone, because two
    manifests declaring the same name is a real condition in a repository mid-refactor and
    silently keeping one of them would hide it. Every enumerated column's clause comes from
    `vocabulary`, which is the only place a CHECK literal may live.

    `unresolved_fields` CARRIES NO CHECK, and that is a decision rather than an omission: its
    value is a SET of declared field names, not one of them, so no `IN` clause can express it.
    It is NULL when nothing was unresolved rather than an empty string, so a consumer's test
    for it is the same NULL test every other optional column here takes.

    @brief Idempotent data_model_keys table creation.
    @version 2
    """
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS data_model_keys (
            define_name   TEXT NOT NULL,
            namespace     TEXT NOT NULL,
            class_name    TEXT NOT NULL,
            key_id        TEXT NOT NULL,
            value_type    TEXT,
            default_value TEXT,
            enum_name     TEXT,
            helpers       INTEGER {bool_check("helpers")},
            dialect       TEXT NOT NULL {check("data_model_keys", "dialect")},
            manifest      TEXT NOT NULL,
            unresolved_fields TEXT,
            listed        INTEGER NOT NULL {bool_check("listed")},
            observed      INTEGER NOT NULL {bool_check("observed")},
            UNIQUE(define_name, manifest)
        )
        """,
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_data_model_keys_define ON data_model_keys(define_name)",
    )
    conn.commit()

Activity · 3 steps
lines 1197–1216conn.execute( f""" CREATE TABLE IF NOT EXISTS data_model_keys ( define_name TEXT NOT NULL, namespace TEXT NOT NULL, class_name TEXT NOT NULL, key_id TEXT NOT NULL, value_type TEXT, default_value TEXT, enum_name TEXT, helpers INTEGER {bool_check("helpers")}, dialect TEXT NOT NULL {check("data_model_keys", "dialect")}, manifest TEXT NOT NULL, unresolved_fields TEXT, listed INTEGER NOT NULL {bool_check("listed")}, observed INTEGER NOT NULL {bool_check("observed")}, UNIQUE(define_name, manifest) ) """, )lines 1217–1219conn.execute( "CREATE INDEX IF NOT EXISTS idx_data_model_keys_define ON data_model_keys(define_name)", )lines 1220–1220conn.commit()

Requirements

REQ-DDB-SCHEMA-013

as_meta

dict[str, str] clew.datamodel.ManifestSet.as_meta(self)

Flatten to build_meta rows for this build.

clew/datamodel.py:238

Show on the map →

Called by none

Calls _unresolved_note, dialects

Source · 40 lines
    def as_meta(self) -> dict[str, str]:
        """COUNTS ARE STRINGS, non-negotiably: `write_build_signature` drops falsy values, so
        an int `0` vanishes and `"0"` survives. The whole point of this section is that a
        measured zero is recorded, and passing an int would reproduce the silent zero one
        layer down — in the persistence rather than in the detector.

        `keys_by_dialect` exists because `dialect` alone stops being informative the moment
        two dialects appear: a reader would see both names and one total, and could not tell a
        repository with 1,600 keys from one generator and 100 from another from the reverse.

        `unresolved_note` is emitted ONLY when some dialect present actually declares fields
        this index does not resolve, and it is prose on purpose — a consumer reading a NULL
        `default_value` needs to be told that the NULL is BY DIALECT rather than by absence,
        and a count cannot say that. Falsy when nothing is unresolved, so it disappears from
        the payload rather than asserting a policy that did not apply.

        @brief This manifest set as build_meta values.
        @return Unprefixed key to string value.
        @version 2
        """
        per_dialect = {
            dialect: sum(1 for k in self.keys if k.dialect == dialect)
            for dialect in self.dialects()
        }
        return {
            "dialect": "+".join(self.dialects()),
            "keys_by_dialect": ",".join(f"{d}={n}" for d, n in per_dialect.items()),
            "manifests": str(len(self.manifests)),
            "classes": str(len({(k.namespace, k.class_name) for k in self.keys})),
            "keys": str(len(self.keys)),
            "keys_listed": str(sum(1 for k in self.keys if k.define_name in self.listed)),
            "keys_with_unresolved_fields": str(sum(1 for k in self.keys if k.unresolved_fields)),
            "key_lists": str(self.list_count),
            "manifests_unlisted": str(self.manifests_unlisted),
            "manifests_unparsed": str(self.unparsed),
            "documents_oversized": str(self.oversized),
            "toml_unavailable": str(int(self.toml_unavailable)),
            "unresolved_note": self._unresolved_note(),
        }
Activity · 2 steps
lines 258–261per_dialect = { dialect: sum(1 for k in self.keys if k.dialect == dialect) for dialect in self.dialects() }lines 262–276return { "dialect": "+".join(self.dialects()), "keys_by_dialect": ",".join(f"{d}={n}" for d, n in per_dialect.items()), "manifests": str(len(self.manifests)), "classes": str(len({(k.namespace, k.class_name) for k in self.keys})), "keys": str(len(self.keys)), "keys_listed": str(sum(1 for k in self.keys if k.define_name in self.listed)), "keys_with_unresolved_fields": str(sum(1 for k in self.keys if k.unresolved_fields)), "key_lists": str(self.list_count), "manifests_unlisted": str(self.manifests_unlisted), "manifests_unparsed": str(self.unparsed), "documents_oversized": str(self.oversized), "toml_unavailable": str(int(self.toml_unavailable)), "unresolved_note": self._unresolved_note(), }

Requirements

REQ-DDB-CONFIG-007

define_name

str clew.datamodel.define_name(str namespace, str class_name, str key_id)

Compose one manifest triple into the generated accessor's key spelling.

clew/datamodel.py:318

Source · 19 lines
def define_name(namespace: str, class_name: str, key_id: str) -> str:
    """THE ONE PLACE the composition rule is spelled, and the rule is measured. See the
    module docstring: underscores inside a segment are preserved and only characters a C
    identifier cannot carry are dropped, which is the difference between 104 and 135 of 135
    against a real target's own key list.

    THE SPACE RULE IS PER-DIALECT AND LIVES AT THE CALL SITE (gh#42). Ingot converts a space to
    an underscore and UDM's measured behaviour drops it; applying ingot's rule here broke three
    UDM tests pinning the 135-of-135 result above, which is exactly the measurement this
    docstring cites. A composer shared by two dialects must not carry one dialect's rule.

    @brief Compose a define name from a manifest triple.
    @return The composed key spelling.
    @version 3
    """
    parts = (namespace, class_name, key_id)
    return "_".join(_DROPPED_FROM_SEGMENT.sub("", str(part)).upper() for part in parts)

Activity · 2 steps
lines 333–333parts = (namespace, class_name, key_id)lines 334–334return "_".join(_DROPPED_FROM_SEGMENT.sub("", str(part)).upper() for part in parts)

Requirements

REQ-DDB-SCHEMA-013

dialects

tuple[str, ...] clew.datamodel.ManifestSet.dialects(self)

The dialects that contributed rows, in a stable order.

clew/datamodel.py:223

Show on the map →

Called by as_meta

Calls none

Source · 11 lines
    def dialects(self) -> tuple[str, ...]:
        """DERIVED from the rows rather than stored, so it cannot disagree with them. Two
        dialects in one repository is a real state — an app can pull one generator's model in
        while migrating off another's — so this is a tuple and not a single value.

        @brief The dialects present in this manifest set.
        @return Sorted dialect names.
        @version 1
        """
        return tuple(sorted({key.dialect for key in self.keys}))
Activity · 1 steps
lines 232–232return tuple(sorted({key.dialect for key in self.keys}))

Requirements

REQ-DDB-CONFIG-007

discover

ManifestSet clew.datamodel.discover(Path|None repo_root, tuple[Path,...] excludes=(), Any cache=None, Path|None declared=None)

Discover a repository's declared data-model manifest set.

clew/datamodel.py:831

Show on the map →

Called by none

Calls _candidates, _classify_yaml, _declared_manifest, _oversized_count, _select, toml_module

Source · 62 lines
def discover(
    repo_root: Path | None,
    excludes: tuple[Path, ...] = (),
    cache: Any = None,
    declared: Path | None = None,
) -> ManifestSet:
    """TWO PASSES, and the ORDER is the fail-closed rule: every key list is collected first,
    and only then is a manifest admitted — on the evidence that the repository's own list
    names at least one of its keys. A one-pass version that took every shape-matching
    document would index a vendored generator's examples as though they were the
    repository's model, and would report a plausible count while doing it.

    A target with no data model returns the empty set. That is a CORRECT NEGATIVE and never
    an error: most repositories have no generated data model, and raising here would make
    the stage a gate on a feature nobody asked for.

    A MISSING TOML PARSER NO LONGER STOPS THE WHOLE PASS, and that changed when the second
    dialect became readable. The ingot dialect is TOML and the UDM dialect is YAML, so an
    interpreter with no `tomllib` and no `tomli` backport can still read a UDM model in full —
    returning early here would have reported "could not look" about a half that was perfectly
    readable. `toml_unavailable` narrows to exactly what it can still honestly claim: the
    INGOT half could not be looked at.

    @brief Discover and select a repository's data-model manifest set.
    @return The discovered manifest set.
    @version 4
    """
    if repo_root is None:
        return ManifestSet()
    no_toml = toml_module() is None
    if no_toml:
        logger.warning(
            "data_model: no TOML parser is importable, so no INGOT manifest could be READ — a "
            "zero ingot key count means 'could not look', not 'looked and found none'. The "
            "UDM dialect is YAML and was still read. Install the tomli backport to read both.",
        )
    toml_paths, yaml_paths = _candidates(repo_root, excludes)
    listed, list_count, udm_paths = _classify_yaml(yaml_paths, repo_root, cache)
    found = _select(toml_paths, udm_paths, repo_root, listed, list_count, cache)
    ## gh#42. A DECLARED MANIFEST IS ADMITTED WITHOUT A KEY LIST, and the fail-closed rule above
    ## is untouched for everything else. That rule exists because a vendored generator ships
    ## example manifests which parse identically to a real one — a hazard of WALKING, and one
    ## nobody stating a path is exposed to. On the reporting repository the model is declared in
    ## TOML alone, so all 14 shape-matching documents were declined and every key in the
    ## repository's own data model was missing from the index.
    if declared is not None:
        manifest, keys = _declared_manifest(declared, repo_root)
        if manifest not in found.manifests:
            found = replace(
                found,
                keys=(*found.keys, *keys),
                manifests=(*found.manifests, manifest),
                ## It was counted as declined by the walk that has just been overruled.
                manifests_unlisted=max(0, found.manifests_unlisted - 1),
            )
    return replace(
        found,
        oversized=_oversized_count([*toml_paths, *yaml_paths]),
        toml_unavailable=no_toml,
    )

Activity · 13 steps
lines 858–858◇ if repo_root is Nonelines 859–859return ManifestSet()lines 860–860no_toml = toml_module() is Nonelines 861–861◇ if no_tomllines 862–866logger.warning( "data_model: no TOML parser is importable, so no INGOT manifest could be READ — a " "zero ingot key count means 'could not look', not 'looked and found none'. The " "UDM dialect is YAML and was still read. Install the tomli backport to read both.", )lines 867–867toml_paths, yaml_paths = _candidates(repo_root, excludes)lines 868–868listed, list_count, udm_paths = _classify_yaml(yaml_paths, repo_root, cache)lines 869–869found = _select(toml_paths, udm_paths, repo_root, listed, list_count, cache)lines 876–876◇ if declared is not Nonelines 877–877manifest, keys = _declared_manifest(declared, repo_root)lines 878–878◇ if manifest not in found.manifestslines 879–885found = replace( found, keys=(*found.keys, *keys), manifests=(*found.manifests, manifest), ## It was counted as declined by the walk that has just been overruled. manifests_unlisted=max(0, found.manifests_unlisted - 1), )lines 886–890return replace( found, oversized=_oversized_count([*toml_paths, *yaml_paths]), toml_unavailable=no_toml, )

Requirements

REQ-DDB-SCHEMA-013

import_data_model_keys

ManifestSet clew.datamodel.import_data_model_keys(Path db_path, Path|None repo_root, tuple[Path,...] excludes=(), Any cache=None, Path|None declared=None)

Layer: persist a repository's declared data-model key catalog.

clew/datamodel.py:1254

Source · 59 lines
def import_data_model_keys(
    db_path: Path,
    repo_root: Path | None,
    excludes: tuple[Path, ...] = (),
    cache: Any = None,
    declared: Path | None = None,
) -> ManifestSet:
    """RUNS AFTER the shared-key stages, because `observed` is a join against the vocabulary
    they wrote. That ordering is load-bearing and not incidental: run above them and every
    row would read `observed = 0`, which is a plausible answer — the declared-vs-observed
    diagnostic would report a repository touching none of its own data model.

    THE TABLE IS CREATED EVEN WHEN THERE ARE NO ROWS, so an empty answer is distinguishable
    from a table that was never built. A consumer querying a target with no data model gets
    zero rows from a real table, which is a measurement; a missing table is not — it cannot
    be told from an index built before this layer existed.

    @brief Import the declared data-model key catalog.
    @return The discovered manifest set.
    @version 3
    """
    found = discover(repo_root, excludes, cache, declared)
    conn = sqlite3.connect(str(db_path))
    try:
        _ensure_table(conn)
        observed = _observed_keys(conn)
        conn.executemany(
            """
            INSERT OR IGNORE INTO data_model_keys
                (define_name, namespace, class_name, key_id, value_type, default_value,
                 enum_name, helpers, dialect, manifest, unresolved_fields, listed, observed)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            [
                (
                    key.define_name,
                    key.namespace,
                    key.class_name,
                    key.key_id,
                    key.value_type,
                    key.default_value,
                    key.enum_name,
                    None if key.helpers is None else int(key.helpers),
                    key.dialect,
                    key.manifest,
                    ",".join(key.unresolved_fields) or None,
                    int(key.define_name in found.listed),
                    int(observed_match(key.define_name, observed)),
                )
                for key in found.keys
            ],
        )
        conn.commit()
    finally:
        conn.close()
    _log(found, observed)
    return found

Activity · 9 steps
lines 1275–1275found = discover(repo_root, excludes, cache, declared)lines 1276–1276conn = sqlite3.connect(str(db_path))lines 1277–1277trylines 1278–1278_ensure_table(conn)lines 1279–1279observed = _observed_keys(conn)lines 1280–1305conn.executemany( """ INSERT OR IGNORE INTO data_model_keys (define_name, namespace, class_name, key_id, value_type, default_value, enum_name, helpers, dialect, manifest, unresolved_fields, listed, observed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, [ ( key.define_name, key.namespace, key.class_name, key.key_id, key.value_type, key.default_value, key.enum_name, None if key.helpers is None else int(key.helpers), key.dialect, key.manifest, ",".join(key.unresolved_fields) or None, int(key.define_name in found.listed), int(observed_match(key.define_name, observed)), ) for key in found.keys ], )lines 1306–1306conn.commit()lines 1309–1309_log(found, observed)lines 1310–1310return found

Requirements

REQ-DDB-SCHEMA-013

observed_match

bool clew.datamodel.observed_match(str declared, frozenset[str] observed)

Whether a declared key is present in the observed vocabulary, by any of ingot's spellings.

clew/datamodel.py:351

Source · 27 lines
def observed_match(declared: str, observed: frozenset[str]) -> bool:
    """MATCHES THE WAY INGOT MATCHES, and the third spelling exists for a reason its own source
    states: `filter.rs::normalize` strips underscores "so that TOML snake_case IDs (e.g.
    STATE_OF_CHARGE) match YAML-era names (STATEOFCHARGE)". A repository that migrated dialects
    carries both, and an exact-string join reports the declared key as unobserved while the
    identical key sits in the vocabulary beside it.

    WHICH SPELLING A CODEBASE USES IS NOT KNOWABLE FROM THE MANIFEST. `key_definitions.h` emits
    the `DM_KEY_` form while the accessor spelling carries no prefix, so the observed vocabulary
    depends on which generated artifact the code calls — and both are correct. Accepting all
    three is what makes `observed` a fact about the code rather than about the generator's
    output selection.

    NOT A FUZZY MATCH. Each alternative is a spelling ingot itself treats as the same key;
    nothing here matches on a prefix, a substring or an edit distance, so two different keys
    cannot collide.

    @brief Test a declared key against the observed vocabulary.
    @return True when observed under any accepted spelling.
    @version 1
    """
    if declared in observed or f"{_INGOT_KEY_PREFIX}{declared}" in observed:
        return True
    normalized = declared.replace("_", "")
    return any(name.replace("_", "") == normalized for name in observed)

Activity · 4 steps
lines 372–372◇ if declared in observed or f"{_INGOT_KEY_PREFIX}{declared}" in observedlines 373–373return Truelines 374–374normalized = declared.replace("_", "")lines 375–375return any(name.replace("_", "") == normalized for name in observed)

Requirements

REQ-DDB-SCHEMA-013

parse_ingot_manifest

tuple[DeclaredKey, ...] | None clew.datamodel.parse_ingot_manifest(Path path, Path repo_root)

Parse one document as an ingot data-model manifest.

clew/datamodel.py:442

Source · 39 lines
def parse_ingot_manifest(path: Path, repo_root: Path) -> tuple[DeclaredKey, ...] | None:
    """SHAPE-GATED, and the gate is the whole discriminator: a document qualifies only when
    it carries a `classes` list whose entries carry both an `id` and a `keys` list. Ordinary
    project TOML — a lint config, a tool manifest — has no such shape, so nothing needs to
    know a filename.

    Returns None for "not this kind of document" and `()` for "one of these and it declares
    nothing", which are different answers: the first must not count against the target and
    the second is a manifest that contributed no rows. Collapsing them would make an empty
    manifest look like a lint file.

    THE TOLERANT TOML LOADER, not the strict one, and the difference matters here. This is a
    DISCOVERY path over every TOML document in a repository, reached whether or not anyone
    declared a data model — so on the declared 3.10 floor without the backport installed, the
    strict loader would fail the build of every target, including the overwhelming majority
    that have no data model at all. `discover` reports the absence instead (`toml_unavailable`).
    The strict loader is right where an owner DECLARED a manifest and it cannot be read; that
    is a different situation and it has a different caller.

    @brief Parse an ingot manifest, or decline the document.
    @return Declared keys, or None when the shape does not match.
    @version 2
    """
    toml = toml_module()
    text = _small_text(path) if toml is not None else None
    if toml is None or text is None:
        return None
    try:
        doc = toml.loads(text)
    except toml.TOMLDecodeError:
        return None
    classes = doc.get("classes")
    if not isinstance(classes, list) or not _is_ingot_class_list(classes):
        return None
    namespace = str(doc.get("meta", {}).get("id", "")) if isinstance(doc.get("meta"), dict) else ""
    manifest = rel_key(path, repo_root)
    return tuple(_ingot_keys(classes, namespace, manifest))

Activity · 14 steps
lines 465–465toml = toml_module()lines 466–466text = _small_text(path) if toml is not None else Nonelines 467–467◇ if toml is None or text is Nonelines 468–468return Nonelines 469–469trylines 470–470doc = toml.loads(text)lines 471–471except toml.TOMLDecodeErrorlines 472–472return Nonelines 473–473classes = doc.get("classes")lines 474–474◇ if not isinstance(classes, list) or not _is_ingot_class_list(classes)lines 475–475return Nonelines 476–476namespace = str(doc.get("meta", {}).get("id", "")) if isinstance(doc.get("meta"), dict) else ""lines 477–477manifest = rel_key(path, repo_root)lines 478–478return tuple(_ingot_keys(classes, namespace, manifest))

Requirements

REQ-DDB-SCHEMA-013

parse_udm_manifest

tuple[DeclaredKey, ...] | None clew.datamodel.parse_udm_manifest(Path path, Path repo_root)

Parse one document as a UDM data-model manifest.

clew/datamodel.py:585

Source · 22 lines
def parse_udm_manifest(path: Path, repo_root: Path) -> tuple[DeclaredKey, ...] | None:
    """A SECOND PARSER, not a second branch of the first, and the field mapping below is the
    argument for it: `namespace` / `name` / `name` / `type.mem` shares not one spelling with
    ingot's `meta.id` / `id` / `id` / `type`, and the key table sits a level deeper. A unified
    mapping would have to guess which dialect it was reading; the shape gate decides once and
    each parser then knows exactly what it is looking at.

    Returns None for "not this kind of document" and `()` for "one of these and it declares
    nothing", the same two distinct answers `parse_ingot_manifest` returns and for the same
    reason.

    @brief Parse a UDM manifest, or decline the document.
    @return Declared keys, or None when the shape does not match.
    @version 1
    """
    doc = _udm_document(path)
    if doc is None:
        return None
    namespace = str(doc.get("namespace", ""))
    return tuple(_udm_keys(doc["classes"], namespace, rel_key(path, repo_root)))

Activity · 5 steps
lines 600–600doc = _udm_document(path)lines 601–601◇ if doc is Nonelines 602–602return Nonelines 603–603namespace = str(doc.get("namespace", ""))lines 604–604return tuple(_udm_keys(doc["classes"], namespace, rel_key(path, repo_root)))

Requirements

REQ-DDB-SCHEMA-013

read_key_list

frozenset[str] | None clew.datamodel.read_key_list(Path path)

Read a flat key list, if the document is one.

clew/datamodel.py:686

Show on the map →

Called by _classify_yaml

Tested by

1 teststest_key_list_recognition

Calls _small_text, all

Source · 30 lines
def read_key_list(path: Path) -> frozenset[str] | None:
    """RECOGNISED BY SHAPE, and the shape has to be tight enough that an ordinary YAML
    sequence does not qualify. Every entry must be a define-name token — uppercase, digits
    and underscores, starting with a letter — and the list must be non-empty, so a
    sequence of file paths, of lowercase words or of mappings is declined.

    This function does NOT decide what the list MEANS. Include, deny and persistent-key
    lists are the same shape and only the build invocation tells them apart; see the module
    docstring on why `listed` is the honest column.

    @brief Read a flat define-name list, or decline the document.
    @return The listed names, or None.
    @version 1
    """
    import yaml

    text = _small_text(path)
    if text is None:
        return None
    try:
        doc = yaml.safe_load(text)
    except yaml.YAMLError:
        return None
    if not isinstance(doc, list) or not doc:
        return None
    if not all(isinstance(item, str) and _LIST_ENTRY.match(item) for item in doc):
        return None
    return frozenset(doc)

Activity · 13 steps
lines 700–700import yamllines 702–702text = _small_text(path)lines 703–703◇ if text is Nonelines 704–704return Nonelines 705–705trylines 706–706doc = yaml.safe_load(text)lines 707–707except yaml.YAMLErrorlines 708–708return Nonelines 709–709◇ if not isinstance(doc, list) or not doclines 710–710return Nonelines 711–711◇ if not all(isinstance(item, str) and _LIST_ENTRY.match(item) for item in doc)lines 712–712return Nonelines 713–713return frozenset(doc)

Requirements

REQ-DDB-SCHEMA-013