"""dependents.py — THE ONE REGISTRY THAT ANSWERS "what breaks if I remove this?" (wave 49, C3). ⭐⭐ **OWNER RULING R23, verbatim:** *"Switching off a table that something depends on is REFUSED, and the refusal NAMES the dependents ('3 views, 1 Route and 2 Sheet cells use this')."* ⭐⭐ **OWNER RULING R32, second half:** *"deleting a view must first disclose who it is shared to and which Sheet cells depend on it."* Both rulings ask the same question of different targets, so there is ONE answer path here rather than a bespoke pre-flight check per surface. A surface (the Databases tab's off switch, the view delete dialog, a Sheet cell binding) calls `dependents(st, target)` and renders what comes back. CONTRACT C3, copied so it cannot drift: register(kind: str, fn) dependents(st, target) -> list[Dependent] target = {"kind": "table"|"view"|"field", "key": str, "database"?: str} Dependent = {"kind": "view"|"route"|"link"|"rollup"|"grant"|"chart"|"sheet_cell", "label": str, "count": int, "ids": list[str]} ⛔⛔ **A ZERO-COUNT KIND IS OMITTED, NEVER REPORTED AS ZERO, AND THAT IS THE WHOLE POINT OF THE REGISTRY BEING OPEN.** "used by 0 Routes" is noise; worse, it is a claim. `sheet_cell` is registered by `platform/modules/sheet.py` AFTER the wave-49 lane merge (W49-T11, a declared handover), so until that line lands this module has no opinion about Sheet cells at all — and saying "0 Sheet cells" would be an assertion it cannot support. An unregistered kind is UNKNOWN, not empty, and the only honest rendering of unknown is silence. ⛔⛔ **A PROVIDER THAT RAISES OMITS ITS KIND. IT NEVER CONTRIBUTES A ZERO.** Same reason, arriving by a different road: a store read that failed knows nothing, and "nothing" must not be spelled the same way as "none". `dependents_report` hands the omitted kinds back to the caller as `errors` so the omission is visible rather than swallowed. ⛔ **LAYERING.** This file lives in `core/` and imports only `core/` siblings and stdlib, so `modules -> core` still points one way. In particular it does NOT copy `core/grid_events.py::_tops`, which reaches UP into `modules.customer_data` (tolerated wave-25 debt carrying a tenant-#0-only fallback bug). `core.table_store.TableStore` is instantiated directly, and the page-key -> workspace-bucket mapping comes from `core.view_templates.workspace_key`, which is already the one place that mapping lives. ⛔ **AND `TableStore.find_view` IS DELIBERATELY NOT USED HERE.** It calls `migrate_legacy_shared_views()` first — a side-effecting read that WRITES the store and can raise `LegacySharedViewMigrationError` on a malformed legacy record. A disclosure dialog is a GET; a GET that migrates data, or 500s on data it only meant to describe, is a defect. The table document is walked directly instead, exactly as the shape allows. ⚠ **THE `'link'` KEY CARRIES TWO SHAPES AND THIS IS WHERE THAT BITES.** On a field of `type == 'link'` it is a DICT (`{'table': ..., 'inverse': ...}`); on a rollup bag it is the bare FIELD KEY (a string) of the link the rollup traverses. A rollup may also carry no `link` at all (the `{'source': {...}}` shape, which joins through a topic dim). Every walker below branches on `field['type']` first and on which key is present second. W60-T31 / C3: grouped kind/label/count/ids retain their meanings. Additive `items` names each id in order and gives its address or a reason it cannot be opened. Data addresses use only the existing #/data? prefix; workbook addresses belong to the Sheet provider (C2). """ from urllib.parse import parse_qs, urlencode import core.chart_system as chart_system import core.route_system as route_system import core.shares as shares import core.user_tables as user_tables import core.view_templates as view_templates from core.table_store import ASSIGNED_KEY, SHARED_KEY #: The reading order of a refusal sentence. `sheet_cell` is listed even though nothing in this #: file registers it: the ORDER is a presentation fact and it must not depend on which lane #: happened to register first (W49-T11 registers `sheet_cell` after the merge). KIND_ORDER = ('view', 'route', 'link', 'rollup', 'grant', 'chart', 'sheet_cell') #: Built-in Default views are not dependents, including their saved owner copies. Their ids are #: shared by EVERY database, so counting them charges one database's Default view to another. #: `aios_grid.py` mints `all-customers` on every topic; its `IG_OVERVIEW_ID` is `tpl_overview`. #: Hardcoded here because `core/` may not reach UP into `aios_grid`; `verify_shared_views.py` #: pins this pair against that module so the declarations cannot drift. PINNED_VIEW_IDS = frozenset({'all-customers', 'tpl_overview'}) #: Singular / plural noun phrase per kind. ⛔ THE CASING IS R23's OWN — lowercase `views`, capital #: `Route`, capital `Sheet cells` — because the ruling quotes the sentence the user reads. _NOUNS = { 'view': ('view', 'views'), 'route': ('Route', 'Routes'), 'link': ('Link field', 'Link fields'), 'rollup': ('rollup', 'rollups'), 'grant': ('share', 'shares'), 'chart': ('chart', 'charts'), 'sheet_cell': ('Sheet cell', 'Sheet cells'), } _PROVIDERS = {} DATA_HASH_PREFIX = '#/data?' def data_hash(database, **params): """Build a #/data?database=... address. The only hash builder in this module.""" database = str(database or '').strip() if not database: return None query = {'database': database} query.update({key: str(value) for key, value in params.items() if key != 'database' and value is not None and str(value) != ''}) return DATA_HASH_PREFIX + urlencode(query) def _dependent_item(item_id, label, href=None, reason=''): """A named thing with an existing hash address or an explicit explanation.""" item_id = str(item_id or '') label = str(label or item_id) href = href if isinstance(href, str) and href.startswith((DATA_HASH_PREFIX, '#/sheet?')) else None return {'id': item_id, 'label': label, 'href': href, 'reason': str(reason or '') if href else str(reason or f'{label} has no direct address available.')} def _field_item(table_key, field): key = str(field.get('key') or '') return _dependent_item(f'{table_key}:{key}', field.get('label') or key, data_hash(table_key, field=key) if key else None) def noun(kind, count): """The noun phrase for `count` of `kind`, agreeing in number.""" pair = _NOUNS.get(str(kind or '')) if not pair: base = str(kind or '').replace('_', ' ').strip() or 'dependent' pair = (base, base + 's') return pair[0] if int(count or 0) == 1 else pair[1] def register(kind, fn): """Register `fn(st, target) -> Dependent | list[Dependent] | None` for one dependent kind. ⚠ RE-REGISTERING A KIND REPLACES IT rather than adding a second answer to one question. The combine session registers `sheet_cell` once; a module imported twice must not double-count. ⚠ THE RETURN SHAPE IS DELIBERATELY LOOSE (one dict, a list, or None). Lane A wrote `modules/sheet.py::sheet_dependents` without ever seeing this file, so the seam accepts either spelling instead of demanding the lanes agreed on something neither could read. """ key = str(kind or '').strip() if not key or not callable(fn): raise ValueError('dependents.register: a kind and a callable are both required') _PROVIDERS[key] = fn return key def registered_kinds(): """Every kind that currently has a provider, in `KIND_ORDER`.""" known = [k for k in KIND_ORDER if k in _PROVIDERS] return known + sorted(k for k in _PROVIDERS if k not in KIND_ORDER) def clean_target(target): """`{'kind', 'key', 'database'}` with kind restricted to the C3 vocabulary, else None.""" target = target if isinstance(target, dict) else {} kind = str(target.get('kind') or '').strip().lower() key = str(target.get('key') or '').strip() if kind not in ('table', 'view', 'field') or not key: return None database = str(target.get('database') or '').strip() if kind == 'table' and not database: database = key return {'kind': kind, 'key': key, 'database': database} def _dependent(kind, ids, items=None): """A Dependent, or None when nothing depends. ⛔ NONE IS THE ZERO CASE — never `count: 0`.""" seen, out = set(), [] for raw in ids or (): value = str(raw or '').strip() if value and value not in seen: seen.add(value) out.append(value) if not out: return None result = {'kind': kind, 'label': noun(kind, len(out)), 'count': len(out), 'ids': out} if items is not None: by_id = {} for item in items: by_id.setdefault(str(item.get('id') or ''), item) result['items'] = [by_id.get(value) or _dependent_item(value, value) for value in out] return result def dependents(st, target): """Every registered kind that depends on `target`, in `KIND_ORDER`. C3's shape, exactly. Zero-count kinds are absent. A provider that RAISES is absent too — see the module note; use `dependents_report` when the caller needs to know which kinds could not be answered. """ return dependents_report(st, target)['dependents'] def dependents_report(st, target): """`{'dependents': [...], 'errors': {kind: message}}` — `dependents()` plus what it could not answer. The route returns `errors` so an unanswerable kind is visible rather than swallowed.""" clean = clean_target(target) if clean is None: return {'dependents': [], 'errors': {}} found, errors = [], {} for kind in registered_kinds(): try: produced = _PROVIDERS[kind](st, dict(clean)) except Exception as exc: # noqa: BLE001 — an unanswerable kind is omitted, never zeroed errors[kind] = f'{type(exc).__name__}: {exc}' continue for item in (produced if isinstance(produced, (list, tuple)) else [produced]): if not isinstance(item, dict): continue ids = item.get('ids') or [] count = int(item.get('count') or len(ids) or 0) if count <= 0: continue normalized = {'kind': str(item.get('kind') or kind), 'label': str(item.get('label') or noun(kind, count)), 'count': count, 'ids': [str(i) for i in ids]} # Lane A may supply a single Sheet address on the dependent itself. Preserve # both that shape and per-id items; neither changes the legacy count or label. if 'href' in item: normalized['href'] = item['href'] if isinstance(item['href'], str) else None if 'reason' in item: normalized['reason'] = str(item.get('reason') or '') # W60-T12 (combine-owned), 2026-09-14: `refusal` is the OTHER half of the same fact # and was being dropped at this seam. A provider says "no address" with `href: None` # AND says WHY in `refusal`; carrying the null while dropping the cause turns an # explained dead end into an unexplained one, which is the defect R23's sentence # exists to prevent. Both keys are optional and neither changes count or label. if 'refusal' in item: normalized['refusal'] = str(item.get('refusal') or '') if isinstance(item.get('items'), list): normalized['items'] = [] for entry in item['items']: entry = entry if isinstance(entry, dict) else {'id': entry} href = entry.get('href') if isinstance(entry.get('href'), str) else None normalized['items'].append({ 'id': str(entry.get('id') or ''), 'label': str(entry.get('label') or entry.get('id') or ''), 'href': href, 'reason': str(entry.get('reason') or ('' if href else 'This dependent has no direct address available.')), }) found.append(normalized) order = {kind: index for index, kind in enumerate(KIND_ORDER)} found.sort(key=lambda item: (order.get(item['kind'], len(order)), item['kind'])) return {'dependents': found, 'errors': errors} def refusal(label, found): """R23's sentence: `"