File size: 34,347 Bytes
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
f530297
c1fc133
 
f530297
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f530297
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f530297
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
f530297
 
 
 
f462120
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
f530297
 
 
c1fc133
f462120
c1fc133
 
 
 
 
 
 
 
f530297
c1fc133
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f530297
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f530297
 
 
 
 
 
c1fc133
f530297
 
c1fc133
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f530297
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f530297
c1fc133
f530297
 
 
 
c1fc133
f530297
 
c1fc133
 
f530297
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
f530297
c1fc133
f530297
 
 
 
c1fc133
f530297
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
c1fc133
f530297
 
 
 
c1fc133
 
 
 
 
f530297
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
"""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: `"<label> is used by 2 views and 1 Route"`, or `''` when nothing depends.

    β›” ZERO-COUNT KINDS ARE ABSENT BY CONSTRUCTION, because `dependents()` never emitted one. The
    empty string is the "nothing depends on this" answer: a caller renders a refusal only when
    this is truthy, so there is no sentence that can accidentally say "used by nothing".
    """
    parts = [f"{item['count']} {item['label']}" for item in (found or ())
             if int(item.get('count') or 0) > 0]
    if not parts:
        return ''
    if len(parts) == 1:
        listed = parts[0]
    else:
        listed = ', '.join(parts[:-1]) + ' and ' + parts[-1]
    name = str(label or '').strip() or 'This database'
    return f'{name} is used by {listed}'


# ═══════════════════════════════════════════════ the store readers the providers share


def _table_doc(st, database, *, assignments=False):
    """The raw `<key>_table_workspace` document, or `{}`. Never migrates β€” see the module note."""
    bucket = view_templates.workspace_key(str(database or '').strip())
    if not bucket:
        return {}
    from core import store_pg
    rows = store_pg._view_settings_backend(st, bucket)
    if rows is not None:
        if assignments:
            return rows.read((ASSIGNED_KEY,))
        return store_pg._get_view_workspace(rows.name, rows.tenant_slug)
    try:
        return dict(st.get(bucket) or {})
    except Exception:
        return {}


def walk_views(st, database):
    """`[(owner, view_id, view)]` for every PERSONAL saved View on one database.

    β›” THE RESERVED STRATA ARE SKIPPED. `__shared__` holds field annotations (and, before wave 48,
    a retired legacy view map); `__assigned__` holds recipient projections, which are counted by
    `_assigned_ids` as dependents OF a source view rather than as views in their own right.
    """
    out = []
    for owner, workspace in _table_doc(st, database).items():
        if owner in (SHARED_KEY, ASSIGNED_KEY) or not isinstance(workspace, dict):
            continue
        for view_id, view in (workspace.get('views') or {}).items():
            if isinstance(view, dict):
                out.append((str(owner), str(view_id), view))
    return out


def _assigned_ids(st, database, source_view_id):
    """Ids of the recipient ASSIGNMENTS minted from one source view.

    These are real dependents: `grid_events`' owner-delete path removes them with the source, so
    a disclosure that omitted them would understate what the delete destroys.
    """
    stratum = _table_doc(st, database, assignments=True).get(ASSIGNED_KEY)
    if not isinstance(stratum, dict):
        return []
    found = []
    for recipient, workspace in stratum.items():
        if not isinstance(workspace, dict):
            continue
        for view_id, view in (workspace.get('views') or {}).items():
            if not isinstance(view, dict):
                continue
            source = view.get('sourceViewId') or view.get('sourceId') or view.get('source')
            if str(source or '').strip() == str(source_view_id):
                found.append(f'{recipient}:{view_id}')
    return found


def _defs(st):
    """`{table_key: definition-without-rows}`. `all_defs` falls back to the whole read itself."""
    try:
        return dict(user_tables.all_defs(st=st) or {})
    except Exception:
        return {}


def _fields(definition):
    return [f for f in ((definition or {}).get('fields') or []) if isinstance(f, dict)]


def _link_bag(field):
    """The link DICT of a link field, else None. β›” Branches on `type` before touching `link`."""
    if str((field or {}).get('type') or '') != 'link':
        return None
    bag = (field or {}).get('link')
    return bag if isinstance(bag, dict) else None


def _rollup_bag(field):
    """The rollup bag of a rollup field, else None."""
    if str((field or {}).get('type') or '') != 'rollup':
        return None
    bag = (field or {}).get('rollup')
    return bag if isinstance(bag, dict) else None


def _routes(st):
    try:
        return [r for r in (route_system.list_routes(st) or ()) if isinstance(r, dict)]
    except Exception:
        return []


def _zones(st, table_key):
    try:
        return [z for z in (route_system.list_zones(st, table_key=table_key) or ())
                if isinstance(z, dict)]
    except Exception:
        return []


def _charts(st):
    try:
        return [c for c in (chart_system.list_charts(st) or ()) if isinstance(c, dict)]
    except Exception:
        return []


def share_audience(st, view_id):
    """`{'owner': str|None, 'names': [...], 'count': n}` for one saved View β€” R32's first half.

    β›” `by` PROVENANCE IS STRIPPED HERE ON PURPOSE. `shares.grants` carries *who placed* each grant
    (D-474), and its own docstring names the cost of returning that verbatim: it widens "who has
    this?" into "who let them in?". A delete dialog needs only the audience, so this door hands
    back names and a count and nothing else.
    """
    record = shares.grants('view', str(view_id or ''), st=st)
    names = [str(entry.get('user') or '') for entry in (record.get('entries') or ())
             if str(entry.get('user') or '')]
    return {'owner': record.get('owner'), 'names': names, 'count': len(names)}


def audience_sentence(audience):
    """`"Shared with anna and 2 others"`, `"Shared with anna"`, or `''`. No dash, ever."""
    names = [str(n) for n in ((audience or {}).get('names') or ()) if str(n or '').strip()]
    if not names:
        return ''
    everyone = [n for n in names if n == shares.EVERYONE]
    if everyone:
        return 'Shared with everyone in this workspace'
    if len(names) == 1:
        return f'Shared with {names[0]}'
    if len(names) == 2:
        return f'Shared with {names[0]} and 1 other'
    return f'Shared with {names[0]} and {len(names) - 1} others'


# ═══════════════════════════════════════════════ the six providers this lane owns


def view_dependents(st, target):
    """Saved Views that depend on the target.

    * table  -> every personal saved View filed on that database
    * view   -> the recipient ASSIGNMENTS minted from it (deleting the source deletes them)
    * field  -> every View whose config NAMES the column (visible / filter leaf / sort / group)
    """
    kind, key, database = target['kind'], target['key'], target['database']
    if kind == 'table':
        items = [_dependent_item(vid, view.get('name') or vid, data_hash(key, view=vid))
                 for _owner, vid, view in walk_views(st, key) if vid not in PINNED_VIEW_IDS]
        return _dependent('view', [item['id'] for item in items], items=items)
    if kind == 'view':
        if not database:
            return None
        ids = _assigned_ids(st, database, key)
        assignments = _table_doc(st, database, assignments=True).get(ASSIGNED_KEY) or {}
        items = []
        for item_id in ids:
            recipient, _, view_id = item_id.partition(':')
            view = assignments[recipient]['views'][view_id]
            label = f'{recipient}: {view.get("name") or view_id}'
            items.append(_dependent_item(item_id, label, data_hash(database, view=view_id)))
        return _dependent('view', ids, items=items)
    items = []
    for _owner, view_id, view in walk_views(st, database):
        if view_id not in PINNED_VIEW_IDS and _view_names_field(view, key):
            items.append(_dependent_item(view_id, view.get('name') or view_id,
                                         data_hash(database, view=view_id)))
    return _dependent('view', [item['id'] for item in items], items=items)


def _view_names_field(view, field_key):
    """Does one saved View's config reference this column anywhere a delete would break?"""
    config = (view or {}).get('config')
    if not isinstance(config, dict):
        return False
    wanted = str(field_key)
    if wanted in [str(c) for c in (config.get('visible') or ())]:
        return True
    if str(config.get('groupBy') or '') == wanted:
        return True
    for sort in (config.get('sorts') or ()):
        if isinstance(sort, dict) and str(sort.get('colId') or sort.get('field') or '') == wanted:
            return True
    return _filters_name_field(config.get('filters'), wanted)


def _filters_name_field(node, wanted, depth=0):
    """A filter tree is nested groups of leaves; a leaf names its column as `colId`/`field`."""
    if depth > 8:
        return False
    if isinstance(node, (list, tuple)):
        return any(_filters_name_field(item, wanted, depth + 1) for item in node)
    if not isinstance(node, dict):
        return False
    if str(node.get('colId') or node.get('field') or '') == wanted:
        return True
    return _filters_name_field(node.get('items') or node.get('children'), wanted, depth + 1)


def route_dependents(st, target):
    """Routes and Zones built ON the target.

    A Route pins the saved View it was planned from (`sourceViewId`), so deleting that View or
    switching off its database leaves the Route pointing at nothing. Zones carry the same pin plus
    a `geographicField`, which is what makes them a FIELD dependent too.
    """
    kind, key, database = target['kind'], target['key'], target['database']
    routes, matched_routes, matched_zones = _routes(st), [], []
    if kind == 'view':
        matched_routes = [r for r in routes if str(r.get('sourceViewId') or '') == key]
        matched_zones = [z for z in _zones(st, database or None)
                         if str(z.get('sourceViewId') or '') == key]
    elif kind == 'table':
        view_ids = {vid for _owner, vid, _v in walk_views(st, key)
                    if vid not in PINNED_VIEW_IDS}
        # A-QI7: Routes store no source database and are created only from customer_data.
        # The database test must therefore use the target table key, not the tenant-wide Route
        # list or a shared view id. Zones already carry their own table scope.
        if str(key) == route_system.DEFAULT_ZONE_TABLE:
            matched_routes = [r for r in routes if str(r.get('sourceViewId') or '') in view_ids]
        matched_zones = _zones(st, key)
    else:
        matched_zones = [z for z in _zones(st, database)
                         if str(z.get('geographicField') or '') == key]
    items = [_dependent_item(str(r.get('id')), r.get('name') or r.get('id'),
                             data_hash(route_system.DEFAULT_ZONE_TABLE, route=r.get('id')))
             for r in matched_routes]
    for zone in matched_zones:
        name = zone.get('name') or zone.get('id')
        items.append(_dependent_item(str(zone.get('id')), name, reason=
                     f'{name} has no direct address. Edit this zone in the Map view Zones menu.'))
    return _dependent('route', [item['id'] for item in items], items=items)


def link_dependents(st, target):
    """INBOUND Link fields: the columns on OTHER databases that point at the target.

    ⚠ A link field the target itself owns is not a dependent, it is part of the thing being
    removed. What breaks is the column on the far side, which is why only `link['table']` (and,
    for a field target, `link['inverse']`) is matched.
    """
    kind, key = target['kind'], target['key']
    if kind == 'view':
        return None
    items = []
    for table_key, definition in _defs(st).items():
        for field in _fields(definition):
            bag = _link_bag(field)
            if bag is None:
                continue
            if kind == 'table' and str(bag.get('table') or '') == key and str(table_key) != key:
                items.append(_field_item(table_key, field))
            elif kind == 'field' and str(bag.get('inverse') or '') == key \
                    and str(bag.get('table') or '') == str(target['database']):
                items.append(_field_item(table_key, field))
    return _dependent('link', [item['id'] for item in items], items=items)


def rollup_dependents(st, target):
    """Rollups that would stop resolving.

    β›” THREE SHAPES, NOT TWO. `{'link': <field key str>, 'fn': ...}` traverses a Link column on its
    own table; `{'source': {'topic', 'on', 'groupBy', ...}}` joins through a topic dim and carries
    NO `link` at all; and a malformed bag carries neither. Each is matched separately, and the
    `link` value is read as a STRING here because a rollup's `link` is never the link field's dict.
    """
    kind, key = target['kind'], target['key']
    if kind == 'view':
        return None
    items = []
    for table_key, definition in _defs(st).items():
        fields = _fields(definition)
        by_key = {str(f.get('key') or ''): f for f in fields}
        for field in fields:
            bag = _rollup_bag(field)
            if bag is None:
                continue
            source = bag.get('source') if isinstance(bag.get('source'), dict) else None
            hop = str(bag.get('link') or '') if not isinstance(bag.get('link'), dict) else ''
            hop_field = by_key.get(hop) if hop else None
            hop_bag = _link_bag(hop_field) if hop_field else None
            if kind == 'table':
                if source and str(source.get('topic') or '') == key:
                    items.append(_field_item(table_key, field))
                elif hop_bag is not None and str(hop_bag.get('table') or '') == key:
                    items.append(_field_item(table_key, field))
                continue
            if str(target['database']) and str(table_key) != str(target['database']):
                continue
            if hop == key or str(bag.get('field') or '') == key:
                items.append(_field_item(table_key, field))
            elif source and key in (str(source.get('on') or ''), str(source.get('groupBy') or ''),
                                    str(source.get('measure') or '')):
                items.append(_field_item(table_key, field))
    return _dependent('rollup', [item['id'] for item in items], items=items)


def grant_dependents(st, target):
    """People who would lose access, read straight off the grant registry.

    * view  -> `shares.grants('view', <id>)` β€” R32's "who it is shared to"
    * table -> the `database` grant plus every `field` grant on that database's columns
    * field -> the `field` grant on `<database>:<key>`
    """
    kind, key, database = target['kind'], target['key'], target['database']

    def named_grants(names):
        subject = {'view': 'view', 'table': 'database', 'field': 'field'}[kind]
        items = [_dependent_item(name, name, reason=
                 f'{name} has no direct access address. Change their access from this '
                 f'{subject}\'s share dialog.') for name in names]
        return _dependent('grant', names, items=items)

    if kind == 'view':
        return named_grants(share_audience(st, key)['names'])
    if kind == 'field':
        if not database:
            return None
        record = shares.grants('field', shares.field_oid(database, key), st=st)
        return named_grants([str(e.get('user') or '') for e in (record.get('entries') or ())])
    holders = [str(e.get('user') or '')
               for e in (shares.grants('database', key, st=st).get('entries') or ())]
    try:
        field_oids = shares.granted_oids('field', st=st)
    except Exception:
        field_oids = ()
    for oid in field_oids:
        table_key, field_key = shares.split_field_oid(oid)
        if table_key != key or not field_key:
            continue
        for entry in (shares.grants('field', oid, st=st).get('entries') or ()):
            holders.append(str(entry.get('user') or ''))
    return named_grants(holders)


def _sheet_chart_items(st, target):
    """Sheet charts drawn over a cell that depends on `target` (W60-T12, contract C2).

    β›”β›” THE DEPENDENCY DECISION IS NOT REMADE HERE, AND THAT IS THE WHOLE DESIGN. Whether a CELL
    depends on the target is `modules/sheet.py`'s answer, and `core/` may not reach UP into
    `modules/` to ask it directly -- the same layering rule `PINNED_VIEW_IDS` is hardcoded for. So
    this reads the ALREADY-REGISTERED `sheet_cell` provider's own rows and takes the cells it
    named. One source of truth for the predicate, so a chart can never disagree with the cell it
    is drawn over; and if nothing registered `sheet_cell` there are no sheet charts to report and
    this is silent, exactly as an absent provider is everywhere else in this file.

    ⚠ A CELL WITH NO ADDRESS CONTRIBUTES NO CHART ADDRESS. `sheet_cell` answers `href: None` plus a
    cause when the destination is hidden or unreadable, and a link built anyway would open some
    OTHER cell -- which is the defect W60-T12 exists to close, not one to reintroduce one layer up.
    """
    provider = _PROVIDERS.get('sheet_cell')
    if provider is None:
        return []
    try:
        rows = provider(st, dict(target))
    except Exception:
        return []                      # a provider that raises omits its kind; so does this
    wanted = {}
    for row in rows if isinstance(rows, (list, tuple)) else ():
        if not isinstance(row, dict) or row.get('kind') != 'sheet_cell':
            continue
        href = row.get('href')
        if not isinstance(href, str) or not href.startswith('#/sheet?'):
            continue
        params = parse_qs(href.split('?', 1)[1])
        workbook_id = (params.get('wb') or [''])[0]
        tab_id = (params.get('tab') or [''])[0]
        addr = (params.get('cell') or [''])[0]
        if workbook_id and tab_id and addr:
            wanted.setdefault((workbook_id, tab_id), []).append(addr)
    if not wanted:
        return []

    from core import sheets as sheet_store
    items, seen = [], set()
    for workbook_id in dict.fromkeys(book for book, _ in wanted):
        try:
            book = sheet_store.get_workbook(st, workbook_id)
        except Exception:
            continue                   # an unreadable workbook is `sheet_cell`'s to report
        for tab in book.get('sheets') or ():
            tab_id = str(tab.get('id') or '')
            addrs = wanted.get((workbook_id, tab_id)) or []
            if not addrs:
                continue
            # ⚠ THE ADDRESS MATHS IS `core/sheets.py`'s, not a second copy. `_clean_range` accepts
            # both `"B4"` and the chart's `{col0,row0,col1,row1}` and answers the same zero-based
            # rectangle for each, so a cell and the chart over it cannot drift apart.
            cells = [rect for rect in (sheet_store._clean_range(a) for a in addrs) if rect]
            for chart in tab.get('charts') or ():
                if not isinstance(chart, dict):
                    continue
                chart_id = str(chart.get('id') or '')
                rect = sheet_store._clean_range(chart.get('range'))
                if not chart_id or chart_id in seen or not rect:
                    continue
                if not any(rect['col0'] <= c['col0'] <= rect['col1']
                           and rect['row0'] <= c['row0'] <= rect['row1'] for c in cells):
                    continue
                seen.add(chart_id)
                label = str(chart.get('name') or chart.get('title') or '').strip() or (
                    f"Chart in {book.get('name') or workbook_id} / {tab.get('name') or tab_id}")
                items.append(_dependent_item(chart_id, label, '#/sheet?' + urlencode(
                    {'wb': workbook_id, 'tab': tab_id, 'chart': chart_id})))
    return items


def chart_dependents(st, target):
    """Saved charts filed against the target DATABASE, and Sheet charts drawn over its cells.

    β›” A CHART NEVER DEPENDS ON A VIEW, and that is `chart_system`'s stated contract rather than an
    omission here: a chart's `config` is OPAQUE and this file must not start reading keys out of
    it to guess at a reference. Deleting a view cannot delete a chart, so it must not disclose one.

    ⭐ W60-T12 (combine-owned) ADDED THE SECOND SOURCE. A Sheet chart is not reachable from
    `sheet_dependents` at all -- it is a sibling of the cells, not one of them -- so before this a
    database could be switched off while a chart still drew from it, and R23's refusal would not
    have said so. Charts are not read from the sheet document here; see `_sheet_chart_items`.
    """
    kind, key = target['kind'], target['key']
    if kind != 'table':
        return None
    items = [_dependent_item(str(c.get('id')), c.get('name') or c.get('id'), c.get('href'),
                             '' if c.get('href') else
                             'This chart has no direct address. Open it from Charts.')
             for c in _charts(st) if str(c.get('database') or '') == key]
    items += _sheet_chart_items(st, target)
    row = _dependent('chart', [item['id'] for item in items], items=items)
    # ⭐ WHEN EXACTLY ONE CHART DEPENDS ON THE TARGET, THE ROW ADDRESSES ONE THING, so it carries
    # that address itself -- the single-address-on-the-dependent shape `dependents_report` already
    # preserves. β›” With several it carries none: a row-level link would have to pick one chart and
    # would silently mean the others, which is the naming-by-display defect W60-T12 closed.
    if row and len(items) == 1:
        row['href'] = items[0]['href']
        row['reason'] = items[0]['reason']
    return row


register('view', view_dependents)
register('route', route_dependents)
register('link', link_dependents)
register('rollup', rollup_dependents)
register('grant', grant_dependents)
register('chart', chart_dependents)