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.
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
Requirements
_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.
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
Requirements
_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.
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
Requirements
_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.
Called by _table_edges, extract_threads, import_mqtt_dispatch_edges, import_shared_key_edges_declared
Calls none
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
Requirements
_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.
Called by annotate_thread_boundaries, import_mqtt_dispatch_edges, import_shared_key_edges_declared, import_shared_key_edges_inferred, schema_db
Calls bool_check
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
Requirements
_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.
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
Requirements
_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.
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
Requirements
_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.
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
Requirements
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.
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
Requirements
harvest
Any clew.shared_key_edges._SharedKeyHarvester.harvest(self, Any tree, bytes src_bytes)
Harvest one file's writer/reader key sites.
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
Any clew.shared_key_edges._SubscribeHarvester.harvest(self, Any tree, bytes src_bytes)
Harvest one file's subscribe call 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
Requirements
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.
Called by _build_stages
Tested by
Calls _build_keyed_edges, _definition_preferring_name_index, _ensure_shared_key_edges_table, _harvest_subscribe_sites, _insert_declared_edges, subscribe_harvester
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
Requirements
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).
Called by _build_stages, run_real_stages
Tested by 7 tests
test_declared_edge_triggered_and_dispatch_mode_set, test_declared_edge_triggered_null_without_manifest_field, test_declared_manifest_invalid_dispatch_mode_fails_closed, test_import_shared_key_edges_declared_dedups_decl_def_rows, test_import_shared_key_edges_declared_event_edge, test_import_shared_key_edges_declared_no_path_skips, test_import_shared_key_edges_declared_yaml_manifest
Calls _definition_preferring_name_index, _ensure_shared_key_edges_table, _insert_declared_edges, _load_declared_keys, _resolve_declared_edges
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
Requirements
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.
Called by _build_stages, _shared_key_shape, measure_shared_key, run_real_stages
Tested by 19 tests
test_a_declared_alias_prefix_does_not_displace_the_ingot_default, test_a_declared_alias_prefix_still_normalizes_its_own_spelling, test_an_undeclared_alias_spelling_is_not_normalized, test_annotate_thread_boundaries_marks_queue_hop_crossing, test_declared_key_wrapper_produces_the_dataflow_edge, test_declared_wrapper_direction_selects_the_matcher_list, test_import_shared_key_edges_inferred_case_label_is_a_reader_site, test_import_shared_key_edges_inferred_default_case_is_not_a_match, test_import_shared_key_edges_inferred_ingot_defaults_fire, test_import_shared_key_edges_inferred_literal_key_match, test_import_shared_key_edges_inferred_name_prefix_key_in_callee_name, test_import_shared_key_edges_inferred_no_patterns_uses_ingot_defaults 7 more
test_import_shared_key_edges_inferred_non_literal_key_unresolved, test_import_shared_key_edges_inferred_queue_handle_pointer_unwrapped, test_inferred_dispatch_mode_defaults_unknown, test_inferred_dispatch_mode_from_writer_pattern, test_inferred_invalid_dispatch_mode_fails_closed, test_name_prefix_exact_prefix_match_has_no_key_remainder, test_without_the_declaration_the_same_dataflow_is_invisible
Calls _build_inferred_edges, _ensure_shared_key_edges_table, _group_sites_by_key, _insert_inferred_edges, _log_suppressed_keys, _log_undeclared_accessor_hint, _walk_all_files_for_shared_keys, _writer_dispatch_map, shared_key_harvester
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
Requirements
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).
Called by resolve_shared_key_patterns
Tested by
Calls _parse_pattern_entry, _read_patterns_yaml, declaration_origin
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
Requirements
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.
Called by _build_stages, resolve_shared_key_patterns
Tested by 6 tests
test_a_declared_alias_prefix_does_not_drop_the_ingot_default, test_a_manifest_that_states_no_prefixes_does_not_claim_the_tier, test_a_target_declaring_no_alias_prefixes_gets_the_ingot_defaults, test_an_explicit_manifest_file_outranks_a_declared_section, test_the_alias_tier_is_stamped_beside_the_entry_pattern_tier, test_the_stamped_alias_resolution_matches_the_one_the_pass_uses
Calls _declared_alias_prefixes, resolve_layered
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
Requirements
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.
Called by _active_prefixes, collect, shared_key_harvester
Tested by 6 tests
test_a_declared_shared_key_pattern_beats_a_built_in_default, test_alias_prefixes_accumulate_exactly_as_their_siblings_do, test_no_builtin_python_accessor_default_exists, test_py_declared_accessors_pair_enum_keys, test_py_shared_key_walk_is_empty_without_a_declaration, test_the_stamped_alias_resolution_matches_the_one_the_pass_uses
Calls _warn_shadowed_defaults, list, load_shared_key_patterns, resolve_key_alias_prefixes
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
Requirements
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.
Called by build_harvest_plan, import_shared_key_edges_inferred
Calls _inferred_cache_key, resolve_shared_key_patterns
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
Requirements
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.
Called by build_harvest_plan, import_mqtt_dispatch_edges
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))