shared_key_edges.py

clew/shared_key_edges.py

Layer 5: `shared_key_edges` — dataflow through a shared symbolic key.

_build_inferred_edges

tuple[list[tuple[int, int, str, str]], list[tuple[str, int, int]]] clew.shared_key_edges._build_inferred_edges(dict[str, set[int]] writer_by_key, dict[str, set[int]] reader_by_key, dict[tuple[str, int], str] writer_dispatch)

Build (writer, reader, key, dispatch_mode) tuples, suppressing fan-out.

clew/shared_key_edges.py:1315

Source · 40 lines
def _build_inferred_edges(
    writer_by_key: dict[str, set[int]],
    reader_by_key: dict[str, set[int]],
    writer_dispatch: dict[tuple[str, int], str],
) -> tuple[list[tuple[int, int, str, str]], list[tuple[str, int, int]]]:
    """Cross writer x reader rowids sharing a key into edge tuples, each
    tagged with the writer's accessor-class `dispatch_mode`.

    A key is suppressed when it would contribute more than `_MAX_KEY_EDGES`
    edges — `writers x readers`, the actual cost, rather than either side on its
    own. See the constant for why the per-side test discarded exactly the funnel
    and broadcast shapes the layer most wants, and why the product ceiling admits
    every key the per-side test did.

    Returns the suppressed keys as (name, writers, readers) triples rather than a
    bare count. The count alone was actively unhelpful: a reader who asked what a
    key reached, and got nothing, had no way to learn from `6 fan-out keys
    suppressed` that theirs was one of the six, and finding out meant reading this
    module (gh#28).

    @brief Cross writer/reader rowid sets into edges, suppressing quadratic keys.
    @return (edge tuples, suppressed key triples).
    @version 3
    """
    edges: list[tuple[int, int, str, str]] = []
    suppressed: list[tuple[str, int, int]] = []
    shared_keys = set(writer_by_key) & set(reader_by_key)
    for key_name in sorted(shared_keys):
        writer_rowids = writer_by_key[key_name]
        reader_rowids = reader_by_key[key_name]
        if len(writer_rowids) * len(reader_rowids) > _MAX_KEY_EDGES:
            suppressed.append((key_name, len(writer_rowids), len(reader_rowids)))
            continue
        for writer_rowid in writer_rowids:
            dispatch_mode = writer_dispatch.get((key_name, writer_rowid), "unknown")
            for reader_rowid in reader_rowids:
                edges.append((writer_rowid, reader_rowid, key_name, dispatch_mode))
    return edges, suppressed

Activity · 14 steps
lines 1339–1339edges: list[tuple[int, int, str, str]] = []lines 1340–1340suppressed: list[tuple[str, int, int]] = []lines 1341–1341shared_keys = set(writer_by_key) & set(reader_by_key)lines 1342–1342◇ for key_name in sorted(shared_keys)lines 1343–1343writer_rowids = writer_by_key[key_name]lines 1344–1344reader_rowids = reader_by_key[key_name]lines 1345–1345◇ if len(writer_rowids) * len(reader_rowids) > _MAX_KEY_EDGESlines 1346–1346suppressed.append((key_name, len(writer_rowids), len(reader_rowids)))lines 1347–1347continuelines 1348–1348◇ for writer_rowid in writer_rowidslines 1349–1349dispatch_mode = writer_dispatch.get((key_name, writer_rowid), "unknown")lines 1350–1350◇ for reader_rowid in reader_rowidslines 1351–1351edges.append((writer_rowid, reader_rowid, key_name, dispatch_mode))lines 1352–1352return edges, suppressed

Requirements

REQ-DDB-PIPE-010

_build_keyed_edges

tuple[list[_DeclaredEdge], int] clew.shared_key_edges._build_keyed_edges(list[_SubscribeSite] sites, dict[str, list[int]] name_to_rowids)

Cross harvested subscribe sites into keyed shared-key edge tuples.

clew/shared_key_edges.py:2351

Source · 33 lines
def _build_keyed_edges(
    sites: list[_SubscribeSite],
    name_to_rowids: dict[str, list[int]],
) -> tuple[list[_DeclaredEdge], int]:
    """topic→handler becomes a keyed shared-key row: writer = the registrar
    (the fn that subscribed), reader = the handler, key = topic (or the
    'dynamic' sentinel), edge_kind='event', dispatch_mode='keyed'.
    edge_triggered stays NULL (not a fire-on-change property).

    @brief Cross subscribe sites into keyed shared_key_edges tuples.
    @version 2
    """
    edges: list[_DeclaredEdge] = []
    unresolved = 0
    for site in sites:
        handler_rowids = name_to_rowids.get(site.handler_name, [])
        if not handler_rowids:
            unresolved += 1
            continue
        for handler_rowid in handler_rowids:
            edges.append(
                (
                    site.registrar_rowid,
                    handler_rowid,
                    site.topic,
                    "event",
                    "keyed",
                    None,
                ),
            )
    return edges, unresolved

Activity · 10 steps
lines 2363–2363edges: list[_DeclaredEdge] = []lines 2364–2364unresolved = 0lines 2365–2365◇ for site in siteslines 2366–2366handler_rowids = name_to_rowids.get(site.handler_name, [])lines 2367–2367◇ if not handler_rowidslines 2368–2368unresolved += 1lines 2369–2369continuelines 2370–2370◇ for handler_rowid in handler_rowidslines 2371–2380edges.append( ( site.registrar_rowid, handler_rowid, site.topic, "event", "keyed", None, ), )lines 2381–2381return edges, unresolved

Requirements

REQ-DDB-SCHEMA-004

_coerce_edge_triggered

bool | None clew.shared_key_edges._coerce_edge_triggered(Any value)

Map an optional manifest bool to 0/1/None for edge_triggered.

clew/shared_key_edges.py:1847

Show on the map →

Called by _declared_keys_from_doc

Calls none

Source · 5 lines
def _coerce_edge_triggered(value: Any) -> bool | None:
    """@brief None when the manifest omits it (stays NULL); else the bool."""
    return None if value is None else bool(value)

Activity · 1 steps
lines 1849–1849return None if value is None else bool(value)

Requirements

REQ-DDB-SCHEMA-002

_definition_preferring_name_index

dict[str, list[int]] clew.shared_key_edges._definition_preferring_name_index(sqlite3.Connection conn)

Name -> rowids index that prefers definition rows over declarations.

clew/shared_key_edges.py:1945

Source · 15 lines
def _definition_preferring_name_index(
    conn: sqlite3.Connection,
) -> dict[str, list[int]]:
    by_name: dict[str, list[tuple[int, bool]]] = {}
    for rowid, name, is_def in conn.execute(
        "SELECT rowid, name, (file_id = bodyfile_id) FROM memberdef WHERE kind = 'function'",
    ):
        by_name.setdefault(name, []).append((rowid, bool(is_def)))
    index: dict[str, list[int]] = {}
    for name, entries in by_name.items():
        defs = [r for r, is_def in entries if is_def]
        index[name] = defs if defs else [r for r, _ in entries]
    return index

Activity · 8 steps
lines 1948–1948by_name: dict[str, list[tuple[int, bool]]] = {}lines 1949–1949◇ for rowid, name, is_def in conn.execute(lines 1952–1952by_name.setdefault(name, []).append((rowid, bool(is_def)))lines 1953–1953index: dict[str, list[int]] = {}lines 1954–1954◇ for name, entries in by_name.items()lines 1955–1955defs = [r for r, is_def in entries if is_def]lines 1956–1956index[name] = defs if defs else [r for r, _ in entries]lines 1957–1957return index

Requirements

REQ-DDB-QUERY-003

_ensure_shared_key_edges_table

None clew.shared_key_edges._ensure_shared_key_edges_table(sqlite3.Connection conn)

Create the shared_key_edges table if it doesn't already exist.

clew/shared_key_edges.py:562

Source · 55 lines
def _ensure_shared_key_edges_table(conn: sqlite3.Connection) -> None:
    """Create shared_key_edges + indexes if absent; never drops existing rows.

    Either the inferred or declared stage may run first (or run alone),
    so table creation uses IF NOT EXISTS rather than the DROP-then-CREATE
    pattern used by single-owner tables like `call_edges`. edge_kind
    accepts 'unknown' alongside 'state'/'event' — AST-inferred edges
    can't tell state from event apart (see `_insert_inferred_edges`).

    R1 richness columns (extended CREATE body — no ALTER, every build is
    from-scratch copy→augment→os.replace):
      - `dispatch_mode` — the synchrony axis the explorer matrix grades:
        'inline' (sync on the writer's thread), 'queued' (buffered to a
        consumer thread), 'keyed' (topic/key routing, e.g. MQTT), 'unknown'.
        Inferred from accessor-class provenance (per-pattern) or declared.
      - `edge_triggered` — DECLARED-ONLY per-bus fire-on-change flag; NULL
        unless a manifest asserts it (setter-body property, AST-infeasible).
      - `crosses_thread` / `to_thread_id` — COMPUTED by
        `threads.annotate_thread_boundaries`; NULL when thread data is
        insufficient. `to_thread_id` forward-references `threads(id)`.

    @brief Idempotent shared_key_edges table/index creation.
    @version 5
    """
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS shared_key_edges (
            writer_rowid INTEGER NOT NULL REFERENCES memberdef(rowid),
            reader_rowid INTEGER NOT NULL REFERENCES memberdef(rowid),
            key_name      TEXT NOT NULL,
            edge_kind     TEXT NOT NULL {check("shared_key_edges", "edge_kind")},
            declared      INTEGER NOT NULL {bool_check("declared")},
            source        TEXT NOT NULL {check("shared_key_edges", "source")},
            confidence    TEXT NOT NULL {check("shared_key_edges", "confidence")},
            dispatch_mode  TEXT NOT NULL DEFAULT 'unknown'
                             {check("shared_key_edges", "dispatch_mode")},
            edge_triggered INTEGER {bool_check("edge_triggered")},
            crosses_thread INTEGER {bool_check("crosses_thread")},
            to_thread_id   INTEGER REFERENCES threads(id),
            UNIQUE(writer_rowid, reader_rowid, key_name, source)
        )
        """,
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_shared_key_edges_writer ON shared_key_edges(writer_rowid)",
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_shared_key_edges_reader ON shared_key_edges(reader_rowid)",
    )
    conn.commit()


# ─── Source A: inferred (AST pattern match) ─────────────────────────────────

Activity · 4 steps
lines 586–604conn.execute( f""" CREATE TABLE IF NOT EXISTS shared_key_edges ( writer_rowid INTEGER NOT NULL REFERENCES memberdef(rowid), reader_rowid INTEGER NOT NULL REFERENCES memberdef(rowid), key_name TEXT NOT NULL, edge_kind TEXT NOT NULL {check("shared_key_edges", "edge_kind")}, declared INTEGER NOT NULL {bool_check("declared")}, source TEXT NOT NULL {check("shared_key_edges", "source")}, confidence TEXT NOT NULL {check("shared_key_edges", "confidence")}, dispatch_mode TEXT NOT NULL DEFAULT 'unknown' {check("shared_key_edges", "dispatch_mode")}, edge_triggered INTEGER {bool_check("edge_triggered")}, crosses_thread INTEGER {bool_check("crosses_thread")}, to_thread_id INTEGER REFERENCES threads(id), UNIQUE(writer_rowid, reader_rowid, key_name, source) ) """, )lines 605–607conn.execute( "CREATE INDEX IF NOT EXISTS idx_shared_key_edges_writer ON shared_key_edges(writer_rowid)", )lines 608–610conn.execute( "CREATE INDEX IF NOT EXISTS idx_shared_key_edges_reader ON shared_key_edges(reader_rowid)", )lines 611–611conn.commit()

Requirements

REQ-DDB-SCHEMA-007

_load_subscribe_patterns

list[_SubscribePattern] clew.shared_key_edges._load_subscribe_patterns(Path|dict source)

Load a mqtt-dispatch manifest (path or inline document) into patterns.

clew/shared_key_edges.py:2147

Source · 39 lines
def _load_subscribe_patterns(source: Path | dict) -> list[_SubscribePattern]:
    """Parse the optional `--mqtt-dispatch` manifest::

        subscribe_functions:
          - fn_name: "MqttcCore_Subscribe"
            topic_arg_index: 1
            handler_arg_index: 2

    A MAPPING IS ACCEPTED, and this was a live defect rather than only groundwork for the
    inline statement form (gh#360). `cli._declared_or_flag` has always handed the `.clew.yaml`
    `mqtt_dispatch:` SECTION down as a parsed mapping — every sibling loader takes
    `Path | dict` for exactly that reason — while this one called `.read_text` on it, so a
    repository declaring that section in-tree crashed its own build with an `AttributeError`
    and no test covered the declaration route for this one manifest.

    @brief Load subscribe-function patterns from a path or an inline document.
    @version 3
    """
    if isinstance(source, dict):
        data = source
    else:
        import yaml

        data = yaml.safe_load(Path(source).read_text(encoding="utf-8")) or {}
    patterns: list[_SubscribePattern] = []
    for entry in data.get("subscribe_functions", []) or []:
        fn_name = entry.get("fn_name")
        if not fn_name:
            continue
        patterns.append(
            _SubscribePattern(
                fn_name=fn_name,
                topic_arg_index=int(entry.get("topic_arg_index", 0)),
                handler_arg_index=int(entry.get("handler_arg_index", 1)),
            ),
        )
    return patterns

Activity · 12 steps
lines 2165–2165◇ if isinstance(source, dict)lines 2166–2166data = sourcelines 2167–2167elselines 2168–2168import yamllines 2170–2170data = yaml.safe_load(Path(source).read_text(encoding="utf-8")) or {}lines 2171–2171patterns: list[_SubscribePattern] = []lines 2172–2172◇ for entry in data.get("subscribe_functions", []) or []lines 2173–2173fn_name = entry.get("fn_name")lines 2174–2174◇ if not fn_namelines 2175–2175continuelines 2176–2182patterns.append( _SubscribePattern( fn_name=fn_name, topic_arg_index=int(entry.get("topic_arg_index", 0)), handler_arg_index=int(entry.get("handler_arg_index", 1)), ), )lines 2183–2183return patterns

Requirements

REQ-DDB-SCHEMA-004

_log_suppressed_keys

None clew.shared_key_edges._log_suppressed_keys(list[tuple[str, int, int]] suppressed)

Name every suppressed fan-out key and its writer/reader counts.

clew/shared_key_edges.py:1361

Source · 23 lines
def _log_suppressed_keys(suppressed: list[tuple[str, int, int]]) -> None:
    """Silent when nothing was suppressed, so a clean build gains no line — but
    when a key IS dropped its name is said out loud, at INFO, beside the product
    that exceeded the ceiling. The absence of this line is what made gh#28 a
    source-reading exercise: the layer reported how MANY keys it discarded and
    never which, so the one key a reader was asking about looked simply absent.

    @brief Log the name and shape of each suppressed fan-out key.
    @return None.
    @version 1
    """
    for key_name, writers, readers in suppressed:
        logger.info(
            "shared_key_edges: suppressed fan-out key %s — %d writers x %d readers "
            "= %d edges, above the %d-edge ceiling",
            key_name,
            writers,
            readers,
            writers * readers,
            _MAX_KEY_EDGES,
        )

Activity · 2 steps
lines 1372–1372◇ for key_name, writers, readers in suppressedlines 1373–1381logger.info( "shared_key_edges: suppressed fan-out key %s — %d writers x %d readers " "= %d edges, above the %d-edge ceiling", key_name, writers, readers, writers * readers, _MAX_KEY_EDGES, )

Requirements

REQ-DDB-PIPE-010

_writer_dispatch_map

dict[tuple[str, int], str] clew.shared_key_edges._writer_dispatch_map(list[_KeyCallSite] sites)

Build a (key, writer_rowid) -> dispatch_mode provenance map.

clew/shared_key_edges.py:1288

Source · 19 lines
def _writer_dispatch_map(sites: list[_KeyCallSite]) -> dict[tuple[str, int], str]:
    """Map each (key, writer rowid) to its accessor-class dispatch_mode.

    When the same writer touches the same key through patterns of differing
    dispatch_mode, a non-'unknown' provenance wins over 'unknown' (an
    explicit class is more informative than the default).

    @brief Collapse writer sites into a (key, rowid) -> dispatch_mode map.
    @version 2
    """
    mapping: dict[tuple[str, int], str] = {}
    for site in sites:
        pk = (site.key_name, site.rowid)
        existing = mapping.get(pk)
        if existing is None or existing == "unknown":
            mapping[pk] = site.dispatch_mode
    return mapping

Activity · 7 steps
lines 1298–1298mapping: dict[tuple[str, int], str] = {}lines 1299–1299◇ for site in siteslines 1300–1300pk = (site.key_name, site.rowid)lines 1301–1301existing = mapping.get(pk)lines 1302–1302◇ if existing is None or existing == "unknown"lines 1303–1303mapping[pk] = site.dispatch_modelines 1304–1304return mapping

Requirements

REQ-DDB-SCHEMA-002

detect_undeclared_accessor_families

list[AccessorFamily] clew.shared_key_edges.detect_undeclared_accessor_families(sqlite3.Connection conn, list[Any] patterns)

Suggest undeclared name-based accessor families no active pattern covers.

clew/shared_key_edges.py:1516

Source · 57 lines
def detect_undeclared_accessor_families(
    conn: sqlite3.Connection,
    patterns: list[Any],
) -> list[AccessorFamily]:
    """Find set/get-shaped accessor FAMILIES (one function per key, sharing a
    long common prefix) that no active `NamePrefixPattern` matches — the
    dataflow a repo has but has not declared, so it silently produces no
    shared_key_edges (as a C/POSIX library's `topics_set_*` accessor family does).
    Purely advisory: it suggests what a `--shared-key-patterns` manifest could
    declare; it never fabricates edges. Object setters (`set_level`) carry no
    leading token and are excluded by construction; argument-based
    `AccessorPattern`s have no prefix and cannot cover a name family, so only
    `NamePrefixPattern` prefixes count as coverage.

    EACH FAMILY NOW CARRIES ITS ORIGIN (gh#352 half 3). A family whose functions live in a
    vendored submodule is not something the operator of THIS repo can declare, and naming it
    beside the ones they can is how a diagnostic trains its reader to ignore it. See
    `AccessorFamily` for the measurement.

    A FAMILY WITH FUNCTIONS ON BOTH SIDES IS FIRST PARTY, the same asymmetry
    `scope._is_dependency_of_parent` and `locks._origin_per_mutex` argue: if any part of the
    family is this repo's, declaring a prefix is an action the operator can take, and
    mislabelling it external would remove it from the list they act on.

    @brief Suggest undeclared name-based accessor families, split by origin.
    @version 7
    """
    covered = tuple(
        p.prefix.lower() for p in patterns if isinstance(p, NamePrefixPattern) and p.prefix
    )
    families: dict[str, set[str]] = {}
    origins: dict[str, set[str]] = {}
    ## The kinds live in `ACCESSOR_CORPUS_KINDS` so that `diagnostics.collect` can count
    ## the corpus this reads WITHOUT restating the predicate. Two spellings of one filter
    ## is how a denominator silently stops describing its numerator.
    for name, owner in conn.execute(_accessor_corpus_sql(conn), ACCESSOR_CORPUS_KINDS):
        match = _ACCESSOR_NAME_RE.match(name or "")
        if match is None:
            continue
        prefix, key = match.group(1), match.group(2)
        if any(prefix.lower().startswith(c) for c in covered):
            continue
        families.setdefault(prefix, set()).add(key)
        origins.setdefault(prefix, set()).add(owner or "")
    out = [
        AccessorFamily(
            prefix=prefix,
            keys=len(keys),
            ## '' wins whenever ANY row is first party — see the both-sides rule above.
            external_root="" if "" in origins[prefix] else sorted(origins[prefix])[0],
        )
        for prefix, keys in families.items()
        if len(keys) >= _MIN_ACCESSOR_FAMILY_KEYS
    ]
    return sorted(out, key=lambda f: (-f.keys, f.prefix))

Activity · 14 steps
lines 1543–1545covered = tuple( p.prefix.lower() for p in patterns if isinstance(p, NamePrefixPattern) and p.prefix )lines 1546–1546families: dict[str, set[str]] = {}lines 1547–1547origins: dict[str, set[str]] = {}lines 1551–1551◇ for name, owner in conn.execute(_accessor_corpus_sql(conn), ACCESSOR_CORPUS_KINDS)lines 1552–1552match = _ACCESSOR_NAME_RE.match(name or "")lines 1553–1553◇ if match is Nonelines 1554–1554continuelines 1555–1555prefix, key = match.group(1), match.group(2)lines 1556–1556◇ if any(prefix.lower().startswith(c) for c in covered)lines 1557–1557continuelines 1558–1558families.setdefault(prefix, set()).add(key)lines 1559–1559origins.setdefault(prefix, set()).add(owner or "")lines 1560–1569out = [ AccessorFamily( prefix=prefix, keys=len(keys), ## '' wins whenever ANY row is first party — see the both-sides rule above. external_root="" if "" in origins[prefix] else sorted(origins[prefix])[0], ) for prefix, keys in families.items() if len(keys) >= _MIN_ACCESSOR_FAMILY_KEYS ]lines 1570–1570return sorted(out, key=lambda f: (-f.keys, f.prefix))

Requirements

REQ-DDB-CONFIG-007 REQ-DDB-SCHEMA-005

harvest

Any clew.shared_key_edges._SharedKeyHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's writer/reader key sites.

clew/shared_key_edges.py:1211

Show on the map →

Called by none

Calls _walk_shared_key_calls

Source · 4 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        return _walk_shared_key_calls(tree, src_bytes, self.patterns)

Activity · 1 steps
lines 1212–1212return _walk_shared_key_calls(tree, src_bytes, self.patterns)
Any clew.shared_key_edges._SubscribeHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's subscribe call sites.

clew/shared_key_edges.py:2295

Show on the map →

Called by none

Calls _walk_subscribe_sites

Source · 4 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        return _walk_subscribe_sites(tree, src_bytes, self.patterns_by_name)

Activity · 1 steps
lines 2296–2296return _walk_subscribe_sites(tree, src_bytes, self.patterns_by_name)

Requirements

REQ-DDB-SCHEMA-005

import_mqtt_dispatch_edges

None clew.shared_key_edges.import_mqtt_dispatch_edges(Path db_path, Path repo_root, Path|dict|None mqtt_dispatch_path, IndexCache|None cache=None, Harvester|None harvester=None)

Layer 5c (optional): keyed topic→handler dispatch from mqtt-dispatch.

clew/shared_key_edges.py:2392

Source · 44 lines
def import_mqtt_dispatch_edges(
    db_path: Path,
    repo_root: Path,
    mqtt_dispatch_path: Path | dict | None,
    cache: IndexCache | None = None,
    harvester: Harvester | None = None,
) -> None:
    """Harvest topic-subscription registrations declared in an optional
    `--mqtt-dispatch` manifest and record them as keyed `shared_key_edges`
    (dispatch_mode='keyed', declared=1). No-ops cleanly when no manifest is
    given. AST inference of the runtime map-lookup
    dispatch itself remains a documented follow-on (see R1-SPEC §2e).

    @brief Import keyed topic→handler dispatch edges from --mqtt-dispatch.
    @version 5
    """
    if mqtt_dispatch_path is None:
        logger.info(
            "shared_key_edges: no --mqtt-dispatch given — skipping keyed pass",
        )
        return
    conn = sqlite3.connect(str(db_path))
    _ensure_shared_key_edges_table(conn)
    name_to_rowids = _definition_preferring_name_index(conn)
    sites = _harvest_subscribe_sites(
        conn,
        repo_root,
        # Never None here: `subscribe_harvester` returns None only for the
        # undeclared manifest this function already returned on, above.
        harvester or subscribe_harvester(mqtt_dispatch_path),  # type: ignore[arg-type]
        cache,
    )
    edges, unresolved = _build_keyed_edges(sites, name_to_rowids)
    inserted = _insert_declared_edges(conn, edges)
    conn.commit()
    conn.close()
    logger.info(
        "shared_key_edges: keyed %d topic→handler edges (of %d raw) from "
        "%d subscribe sites, %d unresolved handlers",
        inserted,
        len(edges),
        len(sites),
        unresolved,
    )

1 more lines, not shown

Activity · 12 steps
lines 2408–2408◇ if mqtt_dispatch_path is Nonelines 2409–2411logger.info( "shared_key_edges: no --mqtt-dispatch given — skipping keyed pass", )lines 2412–2412returnlines 2413–2413conn = sqlite3.connect(str(db_path))lines 2414–2414_ensure_shared_key_edges_table(conn)lines 2415–2415name_to_rowids = _definition_preferring_name_index(conn)lines 2416–2423sites = _harvest_subscribe_sites( conn, repo_root, # Never None here: `subscribe_harvester` returns None only for the # undeclared manifest this function already returned on, above. harvester or subscribe_harvester(mqtt_dispatch_path), # type: ignore[arg-type] cache, )lines 2424–2424edges, unresolved = _build_keyed_edges(sites, name_to_rowids)lines 2425–2425inserted = _insert_declared_edges(conn, edges)lines 2426–2426conn.commit()lines 2427–2427conn.close()lines 2428–2435logger.info( "shared_key_edges: keyed %d topic→handler edges (of %d raw) from " "%d subscribe sites, %d unresolved handlers", inserted, len(edges), len(sites), unresolved, )

Requirements

REQ-DDB-SCHEMA-004

import_shared_key_edges_declared

None clew.shared_key_edges.import_shared_key_edges_declared(Path db_path, Path|None data_model_path)

Layer 5b: ingest an authoritative data-model key manifest (TOML or YAML).

clew/shared_key_edges.py:2075

Source · 45 lines
def import_shared_key_edges_declared(
    db_path: Path,
    data_model_path: Path | None,
) -> None:
    """Ingest an optional ingot-style manifest declaring keys and their
    writer/reader functions directly (no AST inference needed). Accepts
    either an ingot-style TOML or a data-model-style YAML manifest (same `keys:`
    list shape), dispatched by file suffix. Keys with `event = true`
    become `edge_kind='event'` edges; others `edge_kind='state'`. No-ops
    cleanly when no manifest is given, the manifest has no keys, or the
    required parser (tomllib/tomli for TOML, PyYAML for YAML) is absent.

    @brief Import declared shared-key edges from a TOML/YAML data-model manifest.
    @version 4
    """
    if data_model_path is None:
        logger.info(
            "shared_key_edges: no --data-model given — skipping declared pass",
        )
        return

    keys = _load_declared_keys(data_model_path)
    if not keys:
        return
    conn = sqlite3.connect(str(db_path))
    _ensure_shared_key_edges_table(conn)
    name_to_rowids = _definition_preferring_name_index(conn)

    edges, unresolved = _resolve_declared_edges(keys, name_to_rowids)
    inserted = _insert_declared_edges(conn, edges)
    conn.commit()
    conn.close()
    logger.info(
        "shared_key_edges: declared %d edges (of %d raw) from %d manifest "
        "keys, %d unresolved writer/reader names",
        inserted,
        len(edges),
        len(keys),
        unresolved,
    )


# ─── Source C: keyed dispatch (MQTT/topic routing, optional D5) ─────────────

Activity · 14 steps
lines 2090–2090◇ if data_model_path is Nonelines 2091–2093logger.info( "shared_key_edges: no --data-model given — skipping declared pass", )lines 2094–2094returnlines 2096–2096keys = _load_declared_keys(data_model_path)lines 2097–2097◇ if not keyslines 2098–2098returnlines 2099–2099conn = sqlite3.connect(str(db_path))lines 2100–2100_ensure_shared_key_edges_table(conn)lines 2101–2101name_to_rowids = _definition_preferring_name_index(conn)lines 2103–2103edges, unresolved = _resolve_declared_edges(keys, name_to_rowids)lines 2104–2104inserted = _insert_declared_edges(conn, edges)lines 2105–2105conn.commit()lines 2106–2106conn.close()lines 2107–2114logger.info( "shared_key_edges: declared %d edges (of %d raw) from %d manifest " "keys, %d unresolved writer/reader names", inserted, len(edges), len(keys), unresolved, )

Requirements

REQ-DDB-SCHEMA-005

import_shared_key_edges_inferred

None clew.shared_key_edges.import_shared_key_edges_inferred(Path db_path, Path repo_root, Path|dict|None patterns_path, IndexCache|None cache=None, Path|dict|None extra=None, _SharedKeyHarvester|None harvester=None)

Import inferred shared-key edges from an AST pattern + case match.

clew/shared_key_edges.py:1696

Source · 88 lines
def import_shared_key_edges_inferred(
    db_path: Path,
    repo_root: Path,
    patterns_path: Path | dict | None,
    cache: IndexCache | None = None,
    extra: Path | dict | None = None,
    harvester: _SharedKeyHarvester | None = None,
) -> None:
    """Walk the same tree-sitter file set `import_ast_call_edges` uses,
    matching call sites against caller-supplied writer/reader accessor
    patterns AND every switch/case dispatch site (unconditional once this
    pass runs at all — see the module docstring), and emit shared_key_edges
    rows for every (writer, reader) pair sharing a literal key. With no
    patterns config given it falls back to the built-in accessor defaults.

    `extra` is a SECOND declared patterns document merged over the first — the
    `dispatch` manifest's `shared_key_wrappers` section, which IS the
    argument-keyed half of this manifest written where the rest of a repo's
    indirection story lives. It feeds the same parser and the same matcher
    rather than growing a second one (#37).

    The resolved alias prefixes are now HANDED TO THE MATCHER. They were
    resolved and then dropped, so the `DM_KEY_` normalization was plumbed
    through every walker parameter and enabled by nothing: an argument-keyed
    wrapper yielded key `DM_KEY_FOO` while the name-embedded readers of the same
    key yield `FOO`, the two could never intersect, and a declared wrapper
    produced an orphan write-half — the exact failure the dispatch SPEC calls
    out as the reason #37 needs the normalization at all.

    `harvester` is the one gh#358's shared parse pass built and warmed the cache
    with. It carries the RESOLVED patterns, which is why the resolution no longer
    happens here: doing it in both places would emit the shadowed-default warnings
    twice and would let the warmed cache key drift from the read one.

    @brief Import inferred shared-key edges from an AST pattern + case match.
    @version 12
    @req REQ-DDB-SCHEMA-005
    """
    # No --shared-key-patterns given ⇒ fall back to the built-in ingot accessor
    # defaults (they fire only where such accessors exist), rather than skipping
    # the pass entirely and leaving the causal dataflow layer empty.
    if patterns_path is None and extra is None:
        logger.info(
            "shared_key_edges: no --shared-key-patterns given — using built-in "
            "ingot accessor defaults (DataModel_Set_/Get_)",
        )
    harvester = harvester or shared_key_harvester(patterns_path, extra)
    writers = harvester.patterns.writers
    readers = harvester.patterns.readers
    conn = sqlite3.connect(str(db_path))
    _ensure_shared_key_edges_table(conn)

    collector = _walk_all_files_for_shared_keys(
        conn,
        repo_root,
        harvester,
        cache,
    )

    writer_by_key = _group_sites_by_key(collector.writer_sites)
    reader_by_key = _group_sites_by_key(collector.reader_sites)
    writer_dispatch = _writer_dispatch_map(collector.writer_sites)
    edges, suppressed = _build_inferred_edges(writer_by_key, reader_by_key, writer_dispatch)
    inserted = _insert_inferred_edges(conn, edges)
    conn.commit()
    logger.info(
        "shared_key_edges: inferred %d edges (of %d raw), %d fan-out keys "
        "suppressed, %d unresolved (non-literal) key arguments",
        inserted,
        len(edges),
        len(suppressed),
        collector.counters.unresolved,
    )
    _log_suppressed_keys(suppressed)
    # Advisory: name any set/get accessor families the active patterns miss, so a
    # repo whose dataflow uses a non-default convention learns what to declare.
    _log_undeclared_accessor_hint(conn, [*writers, *readers])
    conn.close()


# ─── Source B: declared (ingot-style TOML manifest) ─────────────────────
#
# The tomllib/tomli import used to live here as `_import_toml_module`, and it was
# the ONLY correct copy: `py_entrypoints` had a second, bare `import tomllib` with
# no fallback. That asymmetry is why the shim moved to `tomlcompat` — a duplicated
# compatibility helper is how one copy ends up without the compatibility.

Activity · 18 steps
lines 1737–1737◇ if patterns_path is None and extra is Nonelines 1738–1741logger.info( "shared_key_edges: no --shared-key-patterns given — using built-in " "ingot accessor defaults (DataModel_Set_/Get_)", )lines 1742–1742harvester = harvester or shared_key_harvester(patterns_path, extra)lines 1743–1743writers = harvester.patterns.writerslines 1744–1744readers = harvester.patterns.readerslines 1745–1745conn = sqlite3.connect(str(db_path))lines 1746–1746_ensure_shared_key_edges_table(conn)lines 1748–1753collector = _walk_all_files_for_shared_keys( conn, repo_root, harvester, cache, )lines 1755–1755writer_by_key = _group_sites_by_key(collector.writer_sites)lines 1756–1756reader_by_key = _group_sites_by_key(collector.reader_sites)lines 1757–1757writer_dispatch = _writer_dispatch_map(collector.writer_sites)lines 1758–1758edges, suppressed = _build_inferred_edges(writer_by_key, reader_by_key, writer_dispatch)lines 1759–1759inserted = _insert_inferred_edges(conn, edges)lines 1760–1760conn.commit()lines 1761–1768logger.info( "shared_key_edges: inferred %d edges (of %d raw), %d fan-out keys " "suppressed, %d unresolved (non-literal) key arguments", inserted, len(edges), len(suppressed), collector.counters.unresolved, )lines 1769–1769_log_suppressed_keys(suppressed)lines 1772–1772_log_undeclared_accessor_hint(conn, [*writers, *readers])lines 1773–1773conn.close()

Requirements

REQ-DDB-SCHEMA-005

load_shared_key_patterns

tuple[
    list[AccessorPattern | NamePrefixPattern],
    list[AccessorPattern | NamePrefixPattern],
] clew.shared_key_edges.load_shared_key_patterns(Path|dict path)

Parse a shared-key-patterns YAML file into (writers, readers).

clew/shared_key_edges.py:487

Source · 40 lines
def load_shared_key_patterns(
    path: Path | dict,
) -> tuple[
    list[AccessorPattern | NamePrefixPattern],
    list[AccessorPattern | NamePrefixPattern],
]:
    """Load the writer/reader accessor-pattern config. Each entry is EITHER
    the argument-based convention (`pattern` + `key_arg_index`) OR the
    name-based convention (`name_prefix`) — never both.

    Expected shape::

        writers:
          - pattern: "STORE_SET_*"      # argument-based: shared accessor
            key_arg_index: 0
          - name_prefix: "STORE_SET_"    # name-based: one func per key
        readers:
          - pattern: "STORE_GET_*"
            key_arg_index: 0
          - name_prefix: "STORE_GET_"

    No target-repo-specific pattern names are ever hardcoded in this
    module — they are supplied entirely by this external config file.

    Accepts an already-parsed mapping as well as a path, so the same document
    can arrive either as a standalone `--shared-key-patterns` file or as the
    `shared_key_patterns` section of the repo's `.clew.yaml` — one format,
    one parser, two delivery routes.

    @brief Load writer/reader accessor patterns from YAML.
    @version 6
    """
    data = path if isinstance(path, dict) else _read_patterns_yaml(path)
    origin = declaration_origin(path, SECTION_SHARED_KEY)
    return (
        [_parse_pattern_entry(e, f"{origin}: writers") for e in data.get("writers", []) or []],
        [_parse_pattern_entry(e, f"{origin}: readers") for e in data.get("readers", []) or []],
    )

Activity · 3 steps
lines 519–519data = path if isinstance(path, dict) else _read_patterns_yaml(path)lines 520–520origin = declaration_origin(path, SECTION_SHARED_KEY)lines 521–524return ( [_parse_pattern_entry(e, f"{origin}: writers") for e in data.get("writers", []) or []], [_parse_pattern_entry(e, f"{origin}: readers") for e in data.get("readers", []) or []], )

Requirements

REQ-DDB-SCHEMA-005

resolve_key_alias_prefixes

LayeredResolution clew.shared_key_edges.resolve_key_alias_prefixes(Path|dict|None path, Path|dict|None extra=None)

Resolve the key-alias prefixes through the five-tier precedence rule.

clew/shared_key_edges.py:348

Source · 59 lines
def resolve_key_alias_prefixes(
    path: Path | dict | None,
    extra: Path | dict | None = None,
) -> LayeredResolution:
    """THE SECOND CONSUMER of `tiers.resolve_layered`, and the only other constant
    the gh#319 audit found combining wrongly.

    `DEFAULT_KEY_ALIAS_PREFIXES` is TIER 4 — a known-ecosystem signature — so it
    accumulates and a declaration can add to it but not remove it. There is no
    tier-3 and no tier-5 layer for this option: nothing about a repo's enum naming
    is a language fact, and there are no name-shape guesses here to displace. A
    target stating nothing therefore resolves to the ingot defaults alone, and the
    recorded tier reads `heuristic` — which for an option with an EMPTY tier-5
    layer means "nothing was stated", not "a guess was used".

    THE TWO SOURCES ARE ONE STATED LAYER, and the source type only LABELS the tier.
    `path` and `extra` are different SECTIONS of a target's declaration — the
    accessor manifest and the dispatch manifest's key-wrapper half — not competing
    statements of the same thing, and they have always contributed additively here
    (as they still do for writers and readers). Making them compete because one
    arrived as a flag would drop a repo's `shared_key_wrappers` prefixes the moment
    an operator passed `--shared-key-patterns`, which is a second silent collapse of
    exactly the shape gh#319 exists to remove. A test asserting the opposite is what
    caught the first draft doing it.

    So the tier is a LABEL over the union: `cli._declared_or_flag` hands back a
    `Path` for an explicit `--shared-key-patterns` and the parsed mapping for a
    declaration, so tier 1 is distinguishable without a second argument to keep in
    sync. Only a source that actually CONTRIBUTED a prefix can set it — a manifest
    passed by flag that declares no `key_alias_prefixes` has stated nothing about
    them, and recording `explicit` there would be a provenance record that is
    checkable and wrong.

    PURE, and deliberately so: `cli` calls this a second time to stamp the winning
    tier, because the resolution is computed deep inside the inferred pass where the
    stamping stage cannot reach it. Two calls on identical arguments cannot disagree
    — which is a weaker guarantee than holding one value, so
    `tests/test_tiers.py` pins the two against each other rather than trusting it.

    @brief Resolve the alias prefixes and their provenance.
    @return The LayeredResolution for `key_alias_prefixes`.
    @version 1
    """
    stated: list[str] = []
    by_flag = False
    for source in (path, extra):
        if source is None:
            continue
        contributed = _declared_alias_prefixes(source)
        stated += contributed
        by_flag = by_flag or (bool(contributed) and not isinstance(source, dict))
    return resolve_layered(
        facts=(),
        ecosystem=DEFAULT_KEY_ALIAS_PREFIXES,
        explicit=stated if by_flag else None,
        declared=None if by_flag else (stated or None),
    )

Activity · 9 steps
lines 391–391stated: list[str] = []lines 392–392by_flag = Falselines 393–393◇ for source in (path, extra)lines 394–394◇ if source is Nonelines 395–395continuelines 396–396contributed = _declared_alias_prefixes(source)lines 397–397stated += contributedlines 398–398by_flag = by_flag or (bool(contributed) and not isinstance(source, dict))lines 399–404return resolve_layered( facts=(), ecosystem=DEFAULT_KEY_ALIAS_PREFIXES, explicit=stated if by_flag else None, declared=None if by_flag else (stated or None), )

Requirements

REQ-DDB-CONFIG-006 REQ-DDB-SCHEMA-005

resolve_shared_key_patterns

tuple[
    list[AccessorPattern | NamePrefixPattern],
    list[AccessorPattern | NamePrefixPattern],
    tuple[str, ...],
] clew.shared_key_edges.resolve_shared_key_patterns(Path|dict|None path, Path|dict|None extra=None)

Resolve the writer/reader patterns to use, merging any declared source over the built-in ingot defaults.

clew/shared_key_edges.py:278

Source · 63 lines
def resolve_shared_key_patterns(
    path: Path | dict | None,
    extra: Path | dict | None = None,
) -> tuple[
    list[AccessorPattern | NamePrefixPattern],
    list[AccessorPattern | NamePrefixPattern],
    tuple[str, ...],
]:
    """Start from the built-in ingot accessor defaults and extend with any
    declared source (parallel to how threads merge declared spawn patterns over
    the built-in primitives). The defaults fire only where matching accessors
    exist, so merging is safe on repos that use a different convention.

    `extra` exists so `dispatch.shared_key_wrappers` — which IS the argument-keyed
    half of this manifest, just written where the rest of the indirection story
    lives — feeds the same parser and the same matcher rather than growing a
    second one.

    DECLARED PATTERNS COME FIRST, and the order is the whole fix. `_match_accessor` is
    FIRST-MATCH, and this function used to append declared patterns AFTER the built-in
    defaults — so a declared pattern whose prefix collides with a default could never
    match, and the default's `dispatch_mode` was used instead. Silently: the edge still
    appeared, carrying the wrong accessor-class provenance, which is worse than no edge
    because it is a plausible answer.

    That inverted this repo's precedence rule — a DECLARATION always beats a built-in
    default (`scope.py`'s declaration > guard > Doxyfile, the CLI flag winning over
    `.clew.yaml`). The merge here was the single place that had it backwards.

    ORDER IS NOT THE SAME QUESTION AS MEMBERSHIP, and conflating them is what the
    gh#319 audit found. Declared patterns come FIRST because `_match_accessor` is
    first-match and a declaration must be able to correct a default's `dispatch_mode`.
    They do not come INSTEAD: the built-ins stay in the list, because they fire only
    where their accessors exist and removing them could only lose edges. That is
    precisely the tier-4 accumulate rule, arrived at here before it had a name — and
    the alias prefixes, from the SAME generator, were doing the opposite one screenful
    away until `resolve_key_alias_prefixes` took over.

    A shadowed default is also WARNED about, because an owner who declares
    `Store_Set` without realising a built-in already claims that prefix should be told
    which one won rather than left to infer it from edge counts.

    @brief Merge declared shared-key patterns ahead of the ingot defaults.
    @return (writers, readers, alias prefixes).
    @version 6
    """
    declared_w: list[AccessorPattern | NamePrefixPattern] = []
    declared_r: list[AccessorPattern | NamePrefixPattern] = []
    for source in (path, extra):
        if source is None:
            continue
        w, r = load_shared_key_patterns(source)
        declared_w += w
        declared_r += r
    _warn_shadowed_defaults(declared_w, DEFAULT_SHARED_KEY_WRITERS, "writer")
    _warn_shadowed_defaults(declared_r, DEFAULT_SHARED_KEY_READERS, "reader")
    return (
        declared_w + list(DEFAULT_SHARED_KEY_WRITERS),
        declared_r + list(DEFAULT_SHARED_KEY_READERS),
        resolve_key_alias_prefixes(path, extra).values,
    )

Activity · 11 steps
lines 324–324declared_w: list[AccessorPattern | NamePrefixPattern] = []lines 325–325declared_r: list[AccessorPattern | NamePrefixPattern] = []lines 326–326◇ for source in (path, extra)lines 327–327◇ if source is Nonelines 328–328continuelines 329–329w, r = load_shared_key_patterns(source)lines 330–330declared_w += wlines 331–331declared_r += rlines 332–332_warn_shadowed_defaults(declared_w, DEFAULT_SHARED_KEY_WRITERS, "writer")lines 333–333_warn_shadowed_defaults(declared_r, DEFAULT_SHARED_KEY_READERS, "reader")lines 334–338return ( declared_w + list(DEFAULT_SHARED_KEY_WRITERS), declared_r + list(DEFAULT_SHARED_KEY_READERS), resolve_key_alias_prefixes(path, extra).values, )

Requirements

REQ-DDB-CONFIG-006 REQ-DDB-SCHEMA-005

shared_key_harvester

Harvester clew.shared_key_edges.shared_key_harvester(Path|dict|None patterns_path=None, Path|dict|None extra=None)

Layer 5a's harvester for one resolved accessor vocabulary.

clew/shared_key_edges.py:1221

Source · 19 lines
def shared_key_harvester(
    patterns_path: Path | dict | None = None,
    extra: Path | dict | None = None,
) -> Harvester:
    """The ONE construction site. It matters more here than for the other stages
    because `resolve_shared_key_patterns` WARNS about declared prefixes that shadow a
    built-in default: resolving twice per build would print that warning twice and
    invite the reader to look for two declarations.

    @brief Build this stage's harvester.
    @version 1
    """
    writers, readers, alias_prefixes = resolve_shared_key_patterns(patterns_path, extra)
    return _SharedKeyHarvester(
        _SharedKeyPatterns(writers, readers, alias_prefixes),
        _inferred_cache_key(patterns_path, extra),
    )

Activity · 2 steps
lines 1233–1233writers, readers, alias_prefixes = resolve_shared_key_patterns(patterns_path, extra)lines 1234–1237return _SharedKeyHarvester( _SharedKeyPatterns(writers, readers, alias_prefixes), _inferred_cache_key(patterns_path, extra), )

Requirements

REQ-DDB-SCHEMA-005

subscribe_harvester

Harvester | None clew.shared_key_edges.subscribe_harvester(Path|dict|None mqtt_dispatch_path=None)

Layer 5c's harvester, or None when no manifest declares subscribe functions.

clew/shared_key_edges.py:2304

Source · 14 lines
def subscribe_harvester(mqtt_dispatch_path: Path | dict | None = None) -> Harvester | None:
    """None means "this stage is inert", and the shared parse pass must be told that
    rather than left to warm a payload nobody will read — an undeclared MQTT
    vocabulary matches nothing, so the cost would be pure waste.

    @brief Build this stage's harvester, or None when it is inert.
    @version 1
    """
    if mqtt_dispatch_path is None:
        return None
    patterns = _load_subscribe_patterns(mqtt_dispatch_path)
    return _SubscribeHarvester({p.fn_name: p for p in patterns}, manifest_key(mqtt_dispatch_path))

Activity · 4 steps
lines 2312–2312◇ if mqtt_dispatch_path is Nonelines 2313–2313return Nonelines 2314–2314patterns = _load_subscribe_patterns(mqtt_dispatch_path)lines 2315–2315return _SubscribeHarvester({p.fn_name: p for p in patterns}, manifest_key(mqtt_dispatch_path))

Requirements

REQ-DDB-SCHEMA-005