ripbi-core 0.2.2

Static analysis engine for Power BI semantic models: TMDL and PBIR ingestion, DAX reference extraction, dependency graph, and reachability
Documentation
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
//! The dependency graph: one [`petgraph`] DAG over the semantic model and the
//! reports that share it, plus the reachability analysis that isolates dead
//! objects.
//!
//! # Shape
//!
//! Nodes are [`ObjectId`]s — every table, column, measure, partition,
//! hierarchy, relationship, role, calculation item, shared expression,
//! user-defined function, and report measure, whether or not anything
//! references them. Edges point from user to used and carry their
//! [`Provenance`] as first-class data, so a reverse query
//! ([`consumers_of`](DependencyGraph::consumers_of)) is a pure read and a
//! second view over the graph (`ripbi deps`) is pure rendering in the CLI.
//! Report sites — visuals, pages, bookmarks — are not model objects, so their
//! bindings live beside the graph as [`roots`](DependencyGraph::roots) with
//! full provenance.
//!
//! # Liveness policy (conservative — what "unused" means)
//!
//! Reachability starts from the roots: every
//! [`ReportModel::bindings`](crate::ReportModel::bindings) target and every
//! role (roles are security configuration, never dead weight; their filter
//! edges keep the referenced columns alive). From there, two passes over the
//! edge catalog decide liveness — the full catalog with the reasoning behind
//! every rule lives in `docs/graph.md` beside this module:
//!
//! - **DAX references** (`dax::bind`, every candidate — an unqualified
//!   `[Name]` keeps the measure *and* the home-table column alive) and their
//!   extended candidates (hierarchies, calculation items, and, for a
//!   reference matching nothing, its qualifying table). A reference that
//!   matches nothing and has no resolvable part keeps nothing alive.
//! - **M references** (`m::bind`, same conservatism). The pipeline is M →
//!   tables/columns → DAX → reports, so M is upstream of everything and
//!   deletion flows one way. A **table or shared expression** named in M — a
//!   merge source, a referenced parameter query — keeps alive: deleting it
//!   deletes the query another partition reads, which breaks refresh. A
//!   **column** named in M is the column's *supply chain*, not a consumer:
//!   the query keeps producing it and the model just stops mapping it, so
//!   unloading cannot break refresh and there is deliberately no edge.
//!   Only Data columns qualify — an M step can only name a column it
//!   produces, so a calculated column matching an M name (the auto date/time
//!   columns named like Desktop's date-template query) is not recorded.
//!   Instead the naming expressions ride along on the finding
//!   ([`UnusedObject::named_by_m`]) — the what-a-full-removal-must-edit
//!   context. Liveness still flows through the owner, so a dead table's
//!   partition keeps nothing alive.
//! - **Report bindings** with their provenance, report measures shadowing
//!   model measures of the same name. An unused report measure is dead like
//!   any other node — its body's references stay alive only through it.
//! - **Containment**: a used member (column, measure, hierarchy, calculation
//!   item) keeps its table alive; a used table keeps its partitions,
//!   relationships, and engine-managed columns (calculated-table columns,
//!   calculation-group columns, calendar columns) alive.
//! - **Relationships**: live if either endpoint table is reachable. An
//!   **active** relationship keeps both key columns alive — but a key column
//!   kept alive *only* as a relationship endpoint does **not** keep its table
//!   alive, so a table referenced by nothing but a relationship is still
//!   unused. An **inactive** relationship is live only when a live DAX
//!   reference (`USERELATIONSHIP`) activates it — switching one on at query
//!   time is DAX's job, and nothing else can. Unactivated, it is a finding
//!   itself, and its key columns are findings chained under it.
//!
//! The conservatism rule from name resolution governs everything: marking an
//! object used too many is harmless; marking one too few tells a user to
//! delete live code. A model scanned with no reports and no roles therefore
//! reports *everything* as unused — callers decide whether that is a finding
//! or a missing report.
//!
//! # Examples
//!
//! ```
//! use ripbi_core::{
//!     Column, FieldTarget, FieldWell, Measure, NameKey, Page, Projection,
//!     ReportModel, Table, TabularDatabase, Visual,
//! };
//! use ripbi_core::graph::DependencyGraph;
//!
//! let db = TabularDatabase {
//!     tables: vec![Table {
//!         name: "Sales".to_string(),
//!         columns: vec![
//!             Column { name: "Amount".to_string(), ..Default::default() },
//!             Column { name: "Legacy".to_string(), ..Default::default() },
//!         ],
//!         measures: vec![Measure {
//!             name: "Total".to_string(),
//!             expression: "SUM('Sales'[Amount])".to_string(),
//!             ..Default::default()
//!         }],
//!         ..Default::default()
//!     }],
//!     ..Default::default()
//! };
//! // One visual projecting the Total measure keeps it — and its column — alive.
//! let report = ReportModel {
//!     pages: vec![Page {
//!         name: NameKey::new("P1"),
//!         display_name: None,
//!         is_hidden: false,
//!         filters: Vec::new(),
//!         binding: None,
//!         visuals: vec![Visual {
//!             name: NameKey::new("V1"),
//!             visual_type: "card".to_string(),
//!             wells: vec![FieldWell {
//!                 role: "Values".to_string(),
//!                 projections: vec![Projection {
//!                     target: FieldTarget::Measure {
//!                         home_table: Some(NameKey::new("Sales")),
//!                         measure: NameKey::new("Total"),
//!                     },
//!                     query_ref: None,
//!                     active: true,
//!                 }],
//!             }],
//!             filters: Vec::new(),
//!             sorts: Vec::new(),
//!             conditional_formatting: Vec::new(),
//!             alt_text: Vec::new(),
//!             tooltip_page: None,
//!         }],
//!     }],
//!     ..Default::default()
//! };
//!
//! let graph = DependencyGraph::build(&db, &[&report]);
//!
//! // The visual well is a root with provenance…
//! assert_eq!(graph.roots().len(), 1);
//! let total = ripbi_core::ObjectId::Measure {
//!     table: NameKey::new("Sales"),
//!     measure: NameKey::new("Total"),
//! };
//! assert_eq!(graph.roots_of(&total).len(), 1);
//! // …and nothing touches `Legacy`, so it is the one unused object.
//! let unused = graph.unused_objects();
//! assert_eq!(unused.len(), 1);
//! assert_eq!(unused[0].id.to_string(), "'Sales'[Legacy]");
//! assert!(unused[0].used_by.is_empty(), "nothing references it at all");
//! ```

use std::collections::{HashMap, HashSet};

use petgraph::Direction;
use petgraph::graph::{DiGraph, NodeIndex};
use petgraph::visit::EdgeRef;

pub mod provenance;

mod builder;
mod reachability;

pub use provenance::{BindingEdge, BindingSite, Provenance, StructuralEdge};
pub use reachability::{UnusedObject, UsedBy};

use crate::identity::{NameKey, ObjectId, fold_name};
use crate::model::TabularDatabase;
use crate::report::ReportModel;

/// The dependency graph of one semantic model and the reports sharing it.
///
/// Build it once with [`DependencyGraph::build`], then query: who uses an
/// object ([`consumers_of`](DependencyGraph::consumers_of)), what an object
/// uses ([`producers_of`](DependencyGraph::producers_of)), and what nothing
/// reaches ([`unused_objects`](DependencyGraph::unused_objects)).
#[derive(Debug)]
pub struct DependencyGraph {
    /// The object-to-object edges, user → used, weighted by provenance.
    graph: DiGraph<ObjectId, Provenance>,
    /// Node key → petgraph index. Every model and report object has a node.
    nodes: HashMap<ObjectId, NodeIndex>,
    /// The reachability roots: report bindings pointing at model objects, with
    /// their binding provenance, in report order.
    roots: Vec<(ObjectId, Provenance)>,
    /// Data columns named by M expressions: the supply chain that is
    /// deliberately *not* edges. Key: the column. Value: the naming
    /// expressions, sorted. Engine-computed columns are excluded — an M step
    /// can only name a column it produces.
    m_named: HashMap<ObjectId, Vec<ObjectId>>,
}

impl DependencyGraph {
    /// Builds the graph for one model and every report that shares it.
    ///
    /// Never fails: resolution misses are data, never errors. Passing no
    /// reports leaves every model object unused unless a role keeps it alive.
    #[must_use]
    pub fn build(db: &TabularDatabase, reports: &[&ReportModel]) -> Self {
        builder::build(db, reports)
    }

    /// Assembles a finished graph from its parts. Only the builder calls this.
    pub(super) fn assemble(
        graph: DiGraph<ObjectId, Provenance>,
        nodes: HashMap<ObjectId, NodeIndex>,
        roots: Vec<(ObjectId, Provenance)>,
        m_named: HashMap<ObjectId, Vec<ObjectId>>,
    ) -> Self {
        Self {
            graph,
            nodes,
            roots,
            m_named,
        }
    }

    /// Every object in the graph, in build order (model order, then
    /// relationships, roles, shared expressions, functions, report measures).
    pub fn object_ids(&self) -> impl Iterator<Item = &ObjectId> {
        self.graph.node_indices().map(|index| &self.graph[index])
    }

    /// The objects that use `id`, with what kind of use each edge records —
    /// the query the `ripbi deps` view is built on. Report bindings are not
    /// object-to-object edges; they are answered by
    /// [`roots_of`](DependencyGraph::roots_of).
    pub fn consumers_of(&self, id: &ObjectId) -> Vec<(ObjectId, Provenance)> {
        self.neighbors(id, Direction::Incoming)
    }

    /// The objects that `id` uses, with what kind of use each edge records.
    pub fn producers_of(&self, id: &ObjectId) -> Vec<(ObjectId, Provenance)> {
        self.neighbors(id, Direction::Outgoing)
    }

    /// Every reachability root: the report bindings, with their targets and
    /// provenance, in report order. Deterministic for a given set of reports.
    pub fn roots(&self) -> &[(ObjectId, Provenance)] {
        &self.roots
    }

    /// The provenance of every report binding that targets `id`.
    pub fn roots_of(&self, id: &ObjectId) -> Vec<&Provenance> {
        self.roots
            .iter()
            .filter(|(target, _)| target == id)
            .map(|(_, provenance)| provenance)
            .collect()
    }

    /// The M expressions that name `id` — its Power Query supply chain. A
    /// name is not a consumer: unloading a column these expressions produce
    /// cannot break refresh. But removing the column *entirely* — model and
    /// script — means editing each of them, which is what this answers.
    /// Non-empty only ever for Data columns: an M step can only name a column
    /// it produces, so an engine-computed column matching an M name is
    /// coincidence, not supply chain.
    pub fn named_by_m(&self, id: &ObjectId) -> &[ObjectId] {
        self.m_named.get(id).map(Vec::as_slice).unwrap_or_default()
    }

    /// Every object reachability never reached, sorted by object identity:
    /// the `scan` findings. Each finding names who still references it —
    /// empty for a true orphan, and every referencing object is either
    /// itself unused, a key column kept alive only as an active relationship
    /// endpoint, or the table of an inactive relationship it cannot keep
    /// alive.
    pub fn unused_objects(&self) -> Vec<UnusedObject> {
        let reach = reachability::Reachability::compute(self);
        let mut out: Vec<UnusedObject> = self
            .graph
            .node_indices()
            .filter(|index| !reach.is_live(&self.graph[*index]))
            .map(|index| {
                let id = self.graph[index].clone();
                let mut used_by: Vec<UsedBy> = self
                    .graph
                    .edges_directed(index, Direction::Incoming)
                    .map(|edge| UsedBy {
                        id: self.graph[edge.source()].clone(),
                        provenance: edge.weight().clone(),
                        also_unused: !reach.is_live(&self.graph[edge.source()]),
                    })
                    .collect();
                used_by.sort_by(|a, b| a.id.cmp(&b.id));
                let named_by_m = self.named_by_m(&id).to_vec();
                UnusedObject {
                    id,
                    used_by,
                    named_by_m,
                }
            })
            .collect();
        out.sort_by(|a, b| a.id.cmp(&b.id));
        out
    }

    /// Every auto date/time table — flagged at ingestion or matching the
    /// engine's `LocalDateTable_` / `DateTableTemplate_` name prefixes — with
    /// the second verdict over the same graph the reachability findings come
    /// from, sorted by object identity.
    ///
    /// The verdict is deliberately *not* reachability. The engine's own
    /// relationship to the user's date column keeps the machinery alive for
    /// as long as that column is used, so "alive" says nothing about whether
    /// a report binds it; a table counts as used only when a report binding
    /// ([`Provenance::Binding`]) lands on the table itself or on one of its
    /// members. This is the same data the reachability findings are computed
    /// from, read with a different question — not a separate analysis.
    pub fn auto_date_time_tables(&self, db: &TabularDatabase) -> Vec<AutoDateTimeVerdict> {
        let reach = reachability::Reachability::compute(self);
        let mut out: Vec<AutoDateTimeVerdict> = db
            .tables
            .iter()
            .filter(|table| table.is_local_date_table || table.is_template_date_table)
            .map(|table| {
                let id = ObjectId::Table {
                    table: NameKey::new(&table.name),
                };
                let verdict = if self.bound_with_reports(&id) {
                    AutoDateTimeStatus::InUse
                } else if !reach.is_live(&id) {
                    AutoDateTimeStatus::Dead
                } else {
                    AutoDateTimeStatus::UnusedByReports
                };
                AutoDateTimeVerdict {
                    id,
                    verdict,
                    source_column: variation_source_column(db, &table.name),
                }
            })
            .collect();
        out.sort_by(|a, b| a.id.cmp(&b.id));
        out
    }

    /// Whether any report binding lands on the table itself or on one of its
    /// members (columns, measures, hierarchies, partitions, calculation
    /// items). Binding roots are not edges, so both the root list and the
    /// incoming `Binding` edges (the calculation-item selection case) count.
    /// A binding on the *varied* (user-side) column does not count: the
    /// framework relationship is not a consumer.
    fn bound_with_reports(&self, table: &ObjectId) -> bool {
        let ObjectId::Table { table: name } = table else {
            return false;
        };
        let is_member = |id: &ObjectId| match id {
            ObjectId::Column { table, .. }
            | ObjectId::Measure { table, .. }
            | ObjectId::Hierarchy { table, .. }
            | ObjectId::Partition { table, .. }
            | ObjectId::CalculationItem { table, .. } => table == name,
            _ => false,
        };
        let is_binding = |provenance: &Provenance| matches!(provenance, Provenance::Binding(_));
        self.roots.iter().any(|(target, provenance)| {
            is_binding(provenance) && (target == table || is_member(target))
        }) || self
            .consumers_of(table)
            .iter()
            .any(|(_, provenance)| is_binding(provenance))
    }

    fn neighbors(&self, id: &ObjectId, direction: Direction) -> Vec<(ObjectId, Provenance)> {
        let Some(&index) = self.nodes.get(id) else {
            return Vec::new();
        };
        self.graph
            .edges_directed(index, direction)
            .map(|edge| {
                let other = match direction {
                    Direction::Incoming => edge.source(),
                    Direction::Outgoing => edge.target(),
                };
                (self.graph[other].clone(), edge.weight().clone())
            })
            .collect()
    }

    /// The petgraph indices reachability starts from: every root target and
    /// every role.
    pub(super) fn seed_indices(&self) -> Vec<NodeIndex> {
        let mut seeds: Vec<NodeIndex> = self
            .roots
            .iter()
            .filter_map(|(id, _)| self.nodes.get(id).copied())
            .collect();
        seeds.extend(
            self.nodes
                .iter()
                .filter(|(id, _)| matches!(id, ObjectId::Role { .. }))
                .map(|(_, &index)| index),
        );
        seeds
    }

    /// The set of nodes reachable from `seeds` over the edges `allowed`.
    pub(super) fn reach(
        &self,
        seeds: impl IntoIterator<Item = NodeIndex>,
        allowed: fn(&Provenance) -> bool,
    ) -> HashSet<NodeIndex> {
        let mut seen: HashSet<NodeIndex> = seeds.into_iter().collect();
        let mut queue: Vec<NodeIndex> = seen.iter().copied().collect();
        while let Some(index) = queue.pop() {
            for edge in self.graph.edges_directed(index, Direction::Outgoing) {
                if !allowed(edge.weight()) {
                    continue;
                }
                if seen.insert(edge.target()) {
                    queue.push(edge.target());
                }
            }
        }
        seen
    }

    /// The node key at a petgraph index.
    pub(super) fn object_at(&self, index: NodeIndex) -> &ObjectId {
        &self.graph[index]
    }
}

/// One auto date/time table with the second, provenance-based verdict: does a
/// report *bind* the machinery, or is it kept alive only by the engine's own
/// relationship?
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AutoDateTimeVerdict {
    /// The auto date/time table.
    pub id: ObjectId,
    /// The verdict.
    pub verdict: AutoDateTimeStatus,
    /// The user's date column the machinery serves, when a variation
    /// declaration or the hidden relationship ties the table to one — the
    /// `for 'Date'[OrderDate]` display. `None` for the template table, which
    /// relates to nothing.
    pub source_column: Option<ObjectId>,
}

/// The provenance-based verdict for one auto date/time table — the three
/// states of issue #16, none of which plain reachability can produce.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AutoDateTimeStatus {
    /// A report binding lands on the table or one of its members: the
    /// machinery is in use, and the advice is to replace it with a real date
    /// table.
    InUse,
    /// No report binding touches it, yet the machinery is still live: the
    /// framework relationship to a used date column keeps it alive. Pure
    /// bloat — disable auto date/time.
    UnusedByReports,
    /// Reachability never reached it at all: dead with its dead chain.
    Dead,
}

/// The user's date column whose variation points at `table` — through the
/// variation's relationship or its default-hierarchy reference.
fn variation_source_column(db: &TabularDatabase, table: &str) -> Option<ObjectId> {
    let target = fold_name(table);
    for t in &db.tables {
        for column in &t.columns {
            for variation in &column.variations {
                let via_hierarchy = variation
                    .default_hierarchy
                    .as_ref()
                    .is_some_and(|reference| fold_name(&reference.table) == target);
                let via_relationship = variation
                    .relationship
                    .as_ref()
                    .and_then(|name| {
                        db.relationships
                            .iter()
                            .find(|rel| rel.name.as_deref() == Some(name.as_str()))
                    })
                    .is_some_and(|rel| {
                        fold_name(&rel.from_table) == target || fold_name(&rel.to_table) == target
                    });
                if via_hierarchy || via_relationship {
                    return Some(ObjectId::Column {
                        table: NameKey::new(&t.name),
                        column: NameKey::new(&column.name),
                    });
                }
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::identity::NameKey;
    use crate::model::{
        Column, ColumnKind, DaxExpressionKind, Function, Hierarchy, HierarchyLevel, HierarchyRef,
        Measure, Partition, PartitionSource, Relationship, Role, SharedExpression, Table,
        TablePermission, Variation,
    };
    use crate::report::{
        Bookmark, BookmarkSection, BookmarkVisual, FieldTarget, FieldWell, Filter, Page,
        Projection, Visual,
    };

    fn column(name: &str) -> Column {
        Column {
            name: name.to_string(),
            ..Default::default()
        }
    }

    fn measure(name: &str, expression: &str) -> Measure {
        Measure {
            name: name.to_string(),
            expression: expression.to_string(),
            ..Default::default()
        }
    }

    fn m_partition(name: &str, expression: &str) -> Partition {
        Partition {
            name: name.to_string(),
            source: PartitionSource::M {
                expression: expression.to_string(),
            },
        }
    }

    fn table(name: &str) -> Table {
        Table {
            name: name.to_string(),
            ..Default::default()
        }
    }

    fn table_id(name: &str) -> ObjectId {
        ObjectId::Table {
            table: NameKey::new(name),
        }
    }

    fn column_id(table: &str, column: &str) -> ObjectId {
        ObjectId::Column {
            table: NameKey::new(table),
            column: NameKey::new(column),
        }
    }

    fn measure_id(table: &str, measure: &str) -> ObjectId {
        ObjectId::Measure {
            table: NameKey::new(table),
            measure: NameKey::new(measure),
        }
    }

    fn report_measure_id(name: &str) -> ObjectId {
        ObjectId::ReportMeasure {
            measure: NameKey::new(name),
        }
    }

    /// A visual on page `page` projecting `targets` into its Values well.
    fn visual_page(page: &str, visual: &str, targets: &[FieldTarget]) -> ReportModel {
        ReportModel {
            name: Some("Mini".to_string()),
            pages: vec![Page {
                name: NameKey::new(page),
                display_name: None,
                is_hidden: false,
                filters: Vec::new(),
                binding: None,
                visuals: vec![Visual {
                    name: NameKey::new(visual),
                    visual_type: "card".to_string(),
                    wells: vec![FieldWell {
                        role: "Values".to_string(),
                        projections: targets
                            .iter()
                            .map(|target| Projection {
                                target: target.clone(),
                                query_ref: None,
                                active: true,
                            })
                            .collect(),
                    }],
                    filters: Vec::new(),
                    sorts: Vec::new(),
                    conditional_formatting: Vec::new(),
                    alt_text: Vec::new(),
                    tooltip_page: None,
                }],
            }],
            ..Default::default()
        }
    }

    fn measure_target(table: &str, name: &str) -> FieldTarget {
        FieldTarget::Measure {
            home_table: Some(NameKey::new(table)),
            measure: NameKey::new(name),
        }
    }

    fn column_target(table: &str, column: &str) -> FieldTarget {
        FieldTarget::Column {
            table: NameKey::new(table),
            column: NameKey::new(column),
        }
    }

    /// The finding for `id`, panicking with a readable message when absent.
    fn find<'a>(unused: &'a [UnusedObject], id: &ObjectId) -> &'a UnusedObject {
        unused
            .iter()
            .find(|finding| &finding.id == id)
            .unwrap_or_else(|| panic!("{id} expected in the unused set"))
    }

    fn not_unused(unused: &[UnusedObject], id: &ObjectId) {
        assert!(
            !unused.iter().any(|finding| &finding.id == id),
            "{id} must be live"
        );
    }

    mod construction {
        use super::*;

        #[test]
        fn every_model_object_gets_a_node_even_when_isolated() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![column("Amount")],
                    ..Default::default()
                }],
                functions: vec![Function {
                    name: "MyFunc".to_string(),
                    expression: "1".to_string(),
                    is_hidden: false,
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);

            let ids: Vec<_> = graph.object_ids().cloned().collect();
            assert!(ids.contains(&table_id("Sales")));
            assert!(ids.contains(&column_id("Sales", "Amount")));
            assert!(ids.contains(&ObjectId::Function {
                name: NameKey::new("MyFunc")
            }));
        }

        #[test]
        fn identical_edges_are_deduped_but_distinct_provenance_is_kept() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![column("Amount")],
                    measures: vec![measure(
                        "Total",
                        "SUM('Sales'[Amount]) + SUM('Sales'[Amount])",
                    )],
                    ..Default::default()
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);

            // The measure's outgoing edges: containment in its table, plus
            // exactly ONE DAX edge to the column even though the reference is
            // written twice.
            let producers = graph.producers_of(&measure_id("Sales", "Total"));
            assert_eq!(producers.len(), 2);
            assert_eq!(
                producers
                    .iter()
                    .filter(|(id, _)| *id == column_id("Sales", "Amount"))
                    .count(),
                1,
                "identical (from, to, provenance) triples dedupe"
            );
            // …while the column's only consumer is the measure's DAX edge; its
            // containment edge points the other way, at the table.
            let consumers = graph.consumers_of(&column_id("Sales", "Amount"));
            assert_eq!(consumers.len(), 1);
            assert!(matches!(
                consumers[0].1,
                Provenance::Dax {
                    kind: DaxExpressionKind::Measure
                }
            ));
            assert_eq!(consumers[0].0, measure_id("Sales", "Total"));
            assert!(
                graph
                    .consumers_of(&table_id("Sales"))
                    .iter()
                    .any(|(id, p)| *id == column_id("Sales", "Amount")
                        && matches!(
                            p,
                            Provenance::Structural {
                                role: StructuralEdge::TableMember
                            }
                        ))
            );
        }

        /// A shared expression whose M text names itself keeps nothing alive:
        /// self-references are dropped rather than recorded.
        #[test]
        fn self_references_are_dropped() {
            let db = TabularDatabase {
                expressions: vec![SharedExpression {
                    name: "Recursive".to_string(),
                    expression: "Recursive + 1".to_string(),
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);
            let id = ObjectId::Expression {
                name: NameKey::new("Recursive"),
            };

            assert!(graph.producers_of(&id).is_empty());
            assert!(graph.consumers_of(&id).is_empty());
        }
    }

    mod liveness {
        use super::*;

        /// The far-table policy: a live table keeps its relationship and both
        /// key columns alive, but the far table stays unused — its key column,
        /// alive only as a relationship endpoint, cannot keep it.
        #[test]
        fn a_relationship_does_not_keep_its_far_table_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        columns: vec![column("Key")],
                        partitions: vec![m_partition("Sales", "let Source = 1 in Source")],
                        ..Default::default()
                    },
                    Table {
                        name: "DimOld".to_string(),
                        columns: vec![column("Key"), column("Notes")],
                        partitions: vec![m_partition("DimOld", "let Source = 2 in Source")],
                        ..Default::default()
                    },
                ],
                relationships: vec![Relationship {
                    name: None,
                    from_table: "Sales".to_string(),
                    from_column: "Key".to_string(),
                    to_table: "DimOld".to_string(),
                    to_column: "Key".to_string(),
                    is_active: true,
                }],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[column_target("Sales", "Key")]);
            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            // The used side is entirely live, weak parts included.
            not_unused(&unused, &table_id("Sales"));
            not_unused(&unused, &column_id("Sales", "Key"));
            not_unused(
                &unused,
                &ObjectId::Relationship {
                    from_table: NameKey::new("Sales"),
                    from_column: NameKey::new("Key"),
                    to_table: NameKey::new("DimOld"),
                    to_column: NameKey::new("Key"),
                },
            );

            // The far table is unused despite its live key column…
            let dim_old = find(&unused, &table_id("DimOld"));
            assert_eq!(dim_old.used_by.len(), 2, "its two columns contain it");
            let by_key = dim_old
                .used_by
                .iter()
                .find(|used| used.id == column_id("DimOld", "Key"))
                .expect("the key column references its table");
            assert!(
                !by_key.also_unused,
                "the key column is live, kept by the relationship endpoint"
            );
            assert!(matches!(
                by_key.provenance,
                Provenance::Structural {
                    role: StructuralEdge::TableMember
                }
            ));

            // …and so are its other column and its partition, annotated.
            let notes = find(&unused, &column_id("DimOld", "Notes"));
            assert!(notes.used_by.is_empty(), "an orphan has no consumers");
            let partition = find(
                &unused,
                &ObjectId::Partition {
                    table: NameKey::new("DimOld"),
                    partition: NameKey::new("DimOld"),
                },
            );
            assert_eq!(partition.used_by.len(), 1);
            assert!(partition.used_by[0].also_unused);
            assert_eq!(partition.used_by[0].id, table_id("DimOld"));
        }

        /// An inactive relationship nothing activates is itself a finding,
        /// and its key columns are findings pointing back at it — the
        /// `only used by … (also unused)` chain shape. Only a live
        /// `USERELATIONSHIP` reference can switch it on at query time.
        #[test]
        fn an_unactivated_inactive_relationship_is_a_finding_with_its_keys() {
            let relationship_id = ObjectId::Relationship {
                from_table: NameKey::new("Sales"),
                from_column: NameKey::new("Key"),
                to_table: NameKey::new("DimOld"),
                to_column: NameKey::new("Key"),
            };
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        columns: vec![column("Amt"), column("Key")],
                        measures: vec![measure("Total", "SUM('Sales'[Amt])")],
                        partitions: vec![m_partition("Sales", "let Source = 1 in Source")],
                        ..Default::default()
                    },
                    Table {
                        name: "DimOld".to_string(),
                        columns: vec![column("Key"), column("Notes")],
                        partitions: vec![m_partition("DimOld", "let Source = 2 in Source")],
                        ..Default::default()
                    },
                ],
                relationships: vec![Relationship {
                    name: None,
                    from_table: "Sales".to_string(),
                    from_column: "Key".to_string(),
                    to_table: "DimOld".to_string(),
                    to_column: "Key".to_string(),
                    is_active: false,
                }],
                ..Default::default()
            };
            // Only `Total` is bound: `Sales` is live, `DimOld` is not, and
            // the inactive relationship must not rescue its keys — or itself.
            let report = visual_page("P1", "V1", &[measure_target("Sales", "Total")]);
            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            not_unused(&unused, &table_id("Sales"));

            // The relationship is a finding; its two tables are the recorded
            // consumers that could not keep it alive — `Sales` live, `DimOld`
            // itself unused.
            let relationship = find(&unused, &relationship_id);
            assert_eq!(relationship.used_by.len(), 2);
            assert!(relationship.used_by.iter().all(|used| matches!(
                &used.provenance,
                Provenance::Structural {
                    role: StructuralEdge::InactiveRelationship
                }
            )));
            let sales_side = relationship
                .used_by
                .iter()
                .find(|used| used.id == table_id("Sales"))
                .expect("the from table references the relationship");
            assert!(!sales_side.also_unused);

            // Both keys point back at the unactivated relationship — the
            // `only used by … (also unused)` chain shape.
            for (table_name, column_name) in [("Sales", "Key"), ("DimOld", "Key")] {
                let finding = find(&unused, &column_id(table_name, column_name));
                assert_eq!(
                    finding.used_by.len(),
                    1,
                    "the inactive relationship is the only reference"
                );
                assert!(finding.used_by[0].also_unused);
                assert_eq!(finding.used_by[0].id, relationship_id);
                assert!(matches!(
                    &finding.used_by[0].provenance,
                    Provenance::Structural {
                        role: StructuralEdge::InactiveRelationshipEndpoint
                    }
                ));
            }
            // And `DimOld` is still a finding: a dead key column must not
            // pull its own table along.
            find(&unused, &table_id("DimOld"));
        }

        /// The other half of the rule: a live measure switching the inactive
        /// relationship on with `USERELATIONSHIP` is an ordinary DAX
        /// reference, and it keeps both key columns alive.
        #[test]
        fn a_live_userelationship_measure_keeps_inactive_keys_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        columns: vec![column("Amt"), column("Key")],
                        measures: vec![measure(
                            "Old Total",
                            "CALCULATE(SUM('Sales'[Amt]), USERELATIONSHIP('Sales'[Key], 'DimOld'[Key]))",
                        )],
                        partitions: vec![m_partition("Sales", "let Source = 1 in Source")],
                        ..Default::default()
                    },
                    Table {
                        name: "DimOld".to_string(),
                        columns: vec![column("Key"), column("Notes")],
                        partitions: vec![m_partition("DimOld", "let Source = 2 in Source")],
                        ..Default::default()
                    },
                ],
                relationships: vec![Relationship {
                    name: None,
                    from_table: "Sales".to_string(),
                    from_column: "Key".to_string(),
                    to_table: "DimOld".to_string(),
                    to_column: "Key".to_string(),
                    is_active: false,
                }],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[measure_target("Sales", "Old Total")]);
            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            not_unused(&unused, &column_id("Sales", "Key"));
            not_unused(&unused, &column_id("DimOld", "Key"));
            // The live measure's call is the activation edge itself: the
            // relationship stays alive even though no table needs it.
            not_unused(
                &unused,
                &ObjectId::Relationship {
                    from_table: NameKey::new("Sales"),
                    from_column: NameKey::new("Key"),
                    to_table: NameKey::new("DimOld"),
                    to_column: NameKey::new("Key"),
                },
            );
            // The measure's `USERELATIONSHIP` arguments are ordinary DAX
            // references, so containment applies on top: `DimOld` stays alive
            // through its live key column, and only `Notes` is left dead.
            not_unused(&unused, &table_id("DimOld"));
            let notes = find(&unused, &column_id("DimOld", "Notes"));
            assert!(notes.used_by.is_empty());
        }

        /// An RLS filter is rooted at its role: the filtered column stays alive
        /// even though no report binding and no DAX references it.
        #[test]
        fn an_rls_filter_keeps_its_column_and_table_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![column("Region")],
                    ..Default::default()
                }],
                roles: vec![Role {
                    name: "Reader".to_string(),
                    table_permissions: vec![TablePermission {
                        table: "Sales".to_string(),
                        filter_expression: Some("'Sales'[Region] = \"West\"".to_string()),
                    }],
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            assert!(
                unused.is_empty(),
                "the role seeds the filter, the filter keeps the column, the column keeps the table"
            );
            let consumers = graph.consumers_of(&column_id("Sales", "Region"));
            assert_eq!(consumers.len(), 1);
            assert_eq!(
                consumers[0].0,
                ObjectId::Role {
                    role: NameKey::new("Reader")
                }
            );
            assert!(matches!(
                consumers[0].1,
                Provenance::Dax {
                    kind: DaxExpressionKind::RlsFilter
                }
            ));
        }

        /// A metadata-only role permission keeps the granted table alive.
        #[test]
        fn a_metadata_only_permission_keeps_its_table_alive() {
            let db = TabularDatabase {
                tables: vec![table("Sales")],
                roles: vec![Role {
                    name: "Reader".to_string(),
                    table_permissions: vec![TablePermission {
                        table: "Sales".to_string(),
                        filter_expression: None,
                    }],
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);

            assert!(graph.unused_objects().is_empty());
        }

        /// With no reports and no roles, nothing is reachable: everything is
        /// unused, which is the caller's signal that no roots were found.
        #[test]
        fn a_model_with_no_roots_reports_everything_unused() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![column("Amount")],
                    partitions: vec![m_partition("Sales", "let Source = 1 in Source")],
                    ..Default::default()
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);

            assert_eq!(graph.unused_objects().len(), 3);
            assert!(graph.roots().is_empty());
        }

        /// An unused report measure is dead, and what only it references
        /// carries the "also unused" annotation.
        #[test]
        fn an_unused_report_measure_is_dead_and_annotates_its_chain() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![column("Amount"), column("Old")],
                    measures: vec![measure("Total", "SUM('Sales'[Amount])")],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let mut report = visual_page("P1", "V1", &[measure_target("Sales", "Total")]);
            report.measures.push(crate::report::ReportMeasure {
                name: NameKey::new("Local"),
                expression: "SUM('Sales'[Old])".to_string(),
                format_string: None,
            });

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            let local = find(&unused, &report_measure_id("Local"));
            assert!(local.used_by.is_empty(), "no visual binds it");
            let old = find(&unused, &column_id("Sales", "Old"));
            assert_eq!(old.used_by.len(), 1);
            assert_eq!(old.used_by[0].id, report_measure_id("Local"));
            assert!(old.used_by[0].also_unused);
            not_unused(&unused, &column_id("Sales", "Amount"));
        }

        /// A visual can bind a report measure directly; the report measure
        /// shadows a model measure of the same name, which then reads as
        /// unreferenced from this report.
        #[test]
        fn a_visual_binding_resolves_to_the_shadowing_report_measure() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    measures: vec![measure("Total", "0")],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let mut report = visual_page("P1", "V1", &[measure_target("Sales", "Total")]);
            report.measures.push(crate::report::ReportMeasure {
                name: NameKey::new("Total"),
                expression: "[Model Total]".to_string(),
                format_string: None,
            });

            let graph = DependencyGraph::build(&db, &[&report]);

            // The binding landed on the report measure, not the model measure.
            assert_eq!(graph.roots_of(&report_measure_id("Total")).len(), 1);
            assert!(graph.roots_of(&measure_id("Sales", "Total")).is_empty());
            let unused = graph.unused_objects();
            not_unused(&unused, &report_measure_id("Total"));
            let shadowed = find(&unused, &measure_id("Sales", "Total"));
            assert!(shadowed.used_by.is_empty());
        }

        /// Sort-by chains: an unused sorted column drags its unused sort
        /// column along, with the annotation naming the chain.
        #[test]
        fn a_sort_by_chain_is_annotated() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Date".to_string(),
                    columns: vec![
                        Column {
                            name: "Month Name".to_string(),
                            sort_by_column: Some("Month Num".to_string()),
                            ..Default::default()
                        },
                        column("Month Num"),
                    ],
                    ..Default::default()
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            let month_name = find(&unused, &column_id("Date", "Month Name"));
            assert!(month_name.used_by.is_empty());
            let month_num = find(&unused, &column_id("Date", "Month Num"));
            assert_eq!(month_num.used_by.len(), 1);
            assert_eq!(month_num.used_by[0].id, column_id("Date", "Month Name"));
            assert!(month_num.used_by[0].also_unused);
            assert!(matches!(
                month_num.used_by[0].provenance,
                Provenance::Structural {
                    role: StructuralEdge::SortByColumn
                }
            ));
        }

        /// Group-by chains mirror sort-by: an unused grouping column drags
        /// its unused group column along, with the annotation naming the chain.
        #[test]
        fn a_group_by_chain_is_annotated() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![
                        Column {
                            name: "Amount".to_string(),
                            group_by_columns: vec!["Bucket".to_string()],
                            ..Default::default()
                        },
                        column("Bucket"),
                    ],
                    ..Default::default()
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            let amount = find(&unused, &column_id("Sales", "Amount"));
            assert!(amount.used_by.is_empty());
            let bucket = find(&unused, &column_id("Sales", "Bucket"));
            assert_eq!(bucket.used_by.len(), 1);
            assert_eq!(bucket.used_by[0].id, column_id("Sales", "Amount"));
            assert!(bucket.used_by[0].also_unused);
            assert!(matches!(
                bucket.used_by[0].provenance,
                Provenance::Structural {
                    role: StructuralEdge::GroupByColumn
                }
            ));
        }

        /// A used column keeps its group-by column alive: grouping is part of
        /// how the engine aggregates the column, so a column referenced only
        /// through a group-by is not dead.
        #[test]
        fn a_used_column_keeps_its_group_by_column_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![
                        Column {
                            name: "Amount".to_string(),
                            group_by_columns: vec!["Bucket".to_string()],
                            ..Default::default()
                        },
                        column("Bucket"),
                    ],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[column_target("Sales", "Amount")]);

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(graph.unused_objects().is_empty());
        }

        /// A dead hierarchy keeps its level columns from being orphans: they
        /// are referenced only by the hierarchy, which is itself unused.
        #[test]
        fn a_dead_hierarchy_annotates_its_level_columns() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Date".to_string(),
                    columns: vec![column("Year")],
                    hierarchies: vec![crate::model::Hierarchy {
                        name: "Calendar".to_string(),
                        levels: vec![crate::model::HierarchyLevel {
                            name: "Year".to_string(),
                            column: "Year".to_string(),
                        }],
                        is_hidden: false,
                    }],
                    ..Default::default()
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            let hierarchy = find(
                &unused,
                &ObjectId::Hierarchy {
                    table: NameKey::new("Date"),
                    hierarchy: NameKey::new("Calendar"),
                },
            );
            assert!(hierarchy.used_by.is_empty());
            let year = find(&unused, &column_id("Date", "Year"));
            assert_eq!(year.used_by.len(), 1);
            assert!(matches!(
                year.used_by[0].provenance,
                Provenance::Structural {
                    role: StructuralEdge::HierarchyLevel
                }
            ));
            assert!(year.used_by[0].also_unused);
        }

        /// A hierarchy referenced from DAX (`ISINSCOPE('Date'[Calendar])`) is
        /// an extended-resolution candidate the plain binder does not know.
        #[test]
        fn dax_keeps_a_referenced_hierarchy_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Date".to_string(),
                    columns: vec![column("Year")],
                    hierarchies: vec![crate::model::Hierarchy {
                        name: "Calendar".to_string(),
                        levels: vec![crate::model::HierarchyLevel {
                            name: "Year".to_string(),
                            column: "Year".to_string(),
                        }],
                        is_hidden: false,
                    }],
                    measures: vec![measure("In Scope", "ISINSCOPE('Date'[Calendar])")],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[measure_target("Date", "In Scope")]);

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(graph.unused_objects().is_empty());
        }

        /// A report binding on a calculation-group column keeps every item of
        /// its group alive: a slicer or filter over the column can select any
        /// item by name at query time. Structural liveness of the group alone
        /// does not: the dead-chain fixture pins an unselected item staying
        /// dead when only another item's explicit DAX use keeps the table up.
        #[test]
        fn a_binding_on_a_calculation_group_column_keeps_its_items_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        columns: vec![column("Amount")],
                        measures: vec![measure("Total", "SUM('Sales'[Amount])")],
                        ..Default::default()
                    },
                    Table {
                        name: "Date Role".to_string(),
                        columns: vec![column("Date Role")],
                        calculation_group: Some(crate::model::CalculationGroup {
                            items: vec![
                                crate::model::CalculationItem {
                                    name: "By Ship Date".to_string(),
                                    expression: "SELECTEDMEASURE()".to_string(),
                                    format_string_expression: None,
                                },
                                crate::model::CalculationItem {
                                    name: "By Due Date".to_string(),
                                    expression: "SELECTEDMEASURE()".to_string(),
                                    format_string_expression: None,
                                },
                            ],
                            ..Default::default()
                        }),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            };
            let report = visual_page(
                "P1",
                "Slicer",
                &[
                    measure_target("Sales", "Total"),
                    column_target("Date Role", "Date Role"),
                ],
            );

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(
                graph.unused_objects().is_empty(),
                "the bound column keeps the group, the group's items, and the model alive"
            );
            let consumers = graph.consumers_of(&ObjectId::CalculationItem {
                table: NameKey::new("Date Role"),
                item: NameKey::new("By Ship Date"),
            });
            assert!(
                consumers.iter().any(|(id, provenance)| {
                    *id == column_id("Date Role", "Date Role")
                        && matches!(provenance, Provenance::Binding(_))
                }),
                "the column's binding edge names the item, with the binding site as provenance"
            );
        }

        /// A qualified reference into a calculation group keeps the named
        /// calculation item alive.
        #[test]
        fn dax_keeps_a_referenced_calculation_item_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        measures: vec![measure(
                            "YTD Sales",
                            "CALCULATE(SUM('Sales'[Amount]), 'Time Intelligence'[YTD])",
                        )],
                        ..Default::default()
                    },
                    Table {
                        name: "Time Intelligence".to_string(),
                        calculation_group: Some(crate::model::CalculationGroup {
                            items: vec![
                                crate::model::CalculationItem {
                                    name: "YTD".to_string(),
                                    expression: "SELECTEDMEASURE()".to_string(),
                                    format_string_expression: None,
                                },
                                crate::model::CalculationItem {
                                    name: "MTD".to_string(),
                                    expression: "SELECTEDMEASURE()".to_string(),
                                    format_string_expression: None,
                                },
                            ],
                            ..Default::default()
                        }),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[measure_target("Sales", "YTD Sales")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();
            let unused_ids: Vec<&ObjectId> = unused.iter().map(|finding| &finding.id).collect();

            assert_eq!(
                unused_ids,
                [&ObjectId::CalculationItem {
                    table: NameKey::new("Time Intelligence"),
                    item: NameKey::new("MTD"),
                }],
                "only the unselected calculation item is unused"
            );
        }

        /// A qualified reference matching nothing keeps its qualifying table
        /// alive — the nearest resolvable candidate.
        #[test]
        fn an_unresolved_qualified_reference_keeps_its_table_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        measures: vec![measure("M", "'Ghost'[Nope]")],
                        ..Default::default()
                    },
                    table("Ghost"),
                ],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[measure_target("Sales", "M")]);

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(graph.unused_objects().is_empty(), "Ghost stays alive");
        }

        /// A reference whose table does not exist either keeps nothing alive.
        #[test]
        fn an_unresolved_reference_without_a_resolvable_part_keeps_nothing_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    measures: vec![measure("M", "'Ghost'[Nope] + [Also Nope]")],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[measure_target("Sales", "M")]);

            let graph = DependencyGraph::build(&db, &[&report]);

            assert_eq!(graph.unused_objects().len(), 0, "only Sales and M exist");
        }

        /// A shared expression named in an M partition is referenced by it —
        /// and if the partition's table is dead, the annotation says so.
        #[test]
        fn m_references_keep_shared_expressions_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        partitions: vec![m_partition(
                            "Sales",
                            "let Source = Sql.Database(ServerName) in Source",
                        )],
                        ..Default::default()
                    },
                    Table {
                        name: "DimOld".to_string(),
                        partitions: vec![m_partition(
                            "DimOld",
                            "let Source = LegacyParam in Source",
                        )],
                        ..Default::default()
                    },
                ],
                expressions: vec![
                    SharedExpression {
                        name: "ServerName".to_string(),
                        expression: "\"localhost\"".to_string(),
                    },
                    SharedExpression {
                        name: "LegacyParam".to_string(),
                        expression: "5".to_string(),
                    },
                ],
                ..Default::default()
            };
            // The visual binds a column that does not exist; the written form
            // still keeps its qualifying table alive.
            let report = visual_page("P1", "V1", &[column_target("Sales", "Anything")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            not_unused(
                &unused,
                &ObjectId::Expression {
                    name: NameKey::new("ServerName"),
                },
            );
            let legacy = find(
                &unused,
                &ObjectId::Expression {
                    name: NameKey::new("LegacyParam"),
                },
            );
            assert_eq!(legacy.used_by.len(), 1);
            assert_eq!(
                legacy.used_by[0].id,
                ObjectId::Partition {
                    table: NameKey::new("DimOld"),
                    partition: NameKey::new("DimOld"),
                }
            );
            assert!(legacy.used_by[0].also_unused);
            assert!(matches!(legacy.used_by[0].provenance, Provenance::M));
        }

        /// Shared expressions reference each other: a partition keeps its
        /// staging query alive, and the staging query keeps the parameter it
        /// names alive — one M edge per hop.
        #[test]
        fn an_m_chain_keeps_shared_expressions_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    partitions: vec![m_partition(
                        "Sales",
                        "let Source = Sql.Database(#\"Staging Query\") in Source",
                    )],
                    ..Default::default()
                }],
                expressions: vec![
                    SharedExpression {
                        name: "Staging Query".to_string(),
                        expression: "ServerName".to_string(),
                    },
                    SharedExpression {
                        name: "ServerName".to_string(),
                        expression: "\"localhost\"".to_string(),
                    },
                ],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[column_target("Sales", "Anything")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            not_unused(
                &unused,
                &ObjectId::Expression {
                    name: NameKey::new("Staging Query"),
                },
            );
            not_unused(
                &unused,
                &ObjectId::Expression {
                    name: NameKey::new("ServerName"),
                },
            );

            // The second hop is the M-to-M edge: the staging query, not the
            // partition, is what names ServerName.
            assert_eq!(
                graph.consumers_of(&ObjectId::Expression {
                    name: NameKey::new("ServerName"),
                }),
                [(
                    ObjectId::Expression {
                        name: NameKey::new("Staging Query"),
                    },
                    Provenance::M
                )]
            );
        }

        /// A column named only inside its own table's Power Query partition
        /// is **not** kept alive. M produces the column and the model maps
        /// onto the query's output, so unloading the column cannot break
        /// refresh — the issue #39 keep was inverted. What the partition's
        /// mention is worth rides on the finding instead
        /// ([`UnusedObject::named_by_m`]): removing the column from the
        /// *script* too means editing those steps.
        #[test]
        fn an_m_partition_names_its_columns_without_keeping_them_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![
                        column("Pk"),
                        column("Amount"),
                        column("Region"),
                        column("Orphaned"),
                    ],
                    partitions: vec![m_partition(
                        "Sales",
                        concat!(
                            "let\n",
                            "    Source = Sql.Database(ServerName, \"db\"),\n",
                            "    Typed = Table.TransformColumnTypes(Source, {{\"Amount\", type text}}),\n",
                            "    Expanded = Table.ExpandTableColumn(Typed, \"Detail\", {\"Region\"}),\n",
                            "    Filtered = Table.SelectRows(Expanded, each [Orphaned] = \"West\")\n",
                            "in\n",
                            "    Filtered",
                        ),
                    )],
                    ..Default::default()
                }],
                expressions: vec![SharedExpression {
                    name: "ServerName".to_string(),
                    expression: "\"localhost\"".to_string(),
                }],
                ..Default::default()
            };
            // The report binds Pk only: that keeps the table (and with it the
            // partition) alive, while Amount, Region, and Orphaned have no
            // DAX or report binding anywhere.
            let report = visual_page("P1", "V1", &[column_target("Sales", "Pk")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            let partition = ObjectId::Partition {
                table: NameKey::new("Sales"),
                partition: NameKey::new("Sales"),
            };
            let expected_named = [partition];
            for name in ["Amount", "Region", "Orphaned"] {
                let finding = find(&unused, &column_id("Sales", name));
                assert!(
                    finding.used_by.is_empty(),
                    "M names are not consumers: no edge points at the column"
                );
                assert_eq!(finding.named_by_m, expected_named);
            }
            // The shared expression the partition's M reads is still kept —
            // the liveness half of the rule.
            not_unused(
                &unused,
                &ObjectId::Expression {
                    name: NameKey::new("ServerName"),
                },
            );
        }

        /// A liveness edge must never outrun its owner: when the table is
        /// dead, its partition is unreachable and keeps nothing alive — the
        /// columns die with the table they belong to.
        #[test]
        fn a_dead_tables_partition_keeps_nothing_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "DimOld".to_string(),
                    columns: vec![column("Key")],
                    partitions: vec![m_partition(
                        "DimOld",
                        "let Source = Table.SelectRows(#\"DimOld\", each [Key] <> null) in Source",
                    )],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            find(&unused, &column_id("DimOld", "Key"));
            // The partition names DimOld itself and [Key]; the self-table
            // reference is dropped, but nothing else could keep the table
            // alive either.
            find(&unused, &table_id("DimOld"));
        }

        /// A table consumed only as another query's merge source is
        /// refresh-critical: `#"DimOld"` in a NestedJoin deletes the query the
        /// join reads when the table goes, so the table keeps alive. Its
        /// *column* does not — the `{"Key"}` strings merely name it.
        #[test]
        fn an_m_merge_source_keeps_the_joined_table_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        columns: vec![column("Key")],
                        partitions: vec![m_partition(
                            "Sales",
                            concat!(
                                "let\n",
                                "    Source = Sql.Database(ServerName, \"db\"),\n",
                                "    Joined = Table.NestedJoin(Source, {\"Key\"}, #\"DimOld\", {\"Key\"}, \"Dim\")\n",
                                "in\n",
                                "    Joined",
                            ),
                        )],
                        ..Default::default()
                    },
                    Table {
                        name: "DimOld".to_string(),
                        columns: vec![column("Key")],
                        partitions: vec![m_partition("DimOld", "let Source = DimOld in Source")],
                        ..Default::default()
                    },
                ],
                expressions: vec![SharedExpression {
                    name: "ServerName".to_string(),
                    expression: "\"localhost\"".to_string(),
                }],
                ..Default::default()
            };
            // Sales is reachable only through a relationship-free report
            // binding on its column; DimOld has no binding anywhere.
            let report = visual_page("P1", "V1", &[column_target("Sales", "Key")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            not_unused(&unused, &table_id("DimOld"));
            // The join keys are named, not kept: Sales' partition rides on
            // DimOld's column finding as supply-chain context.
            let finding = find(&unused, &column_id("DimOld", "Key"));
            assert_eq!(
                finding.named_by_m,
                [ObjectId::Partition {
                    table: NameKey::new("Sales"),
                    partition: NameKey::new("Sales"),
                }]
            );
        }

        /// A qualified field access names the query it reads from:
        /// `#"DimOld"[Key]` keeps the whole DimOld table alive even when no
        /// argument-position mention of the table exists anywhere.
        #[test]
        fn a_qualified_m_field_access_keeps_the_named_table_alive() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        columns: vec![column("Key")],
                        partitions: vec![m_partition(
                            "Sales",
                            "let Source = #\"DimOld\"[Key] in Source",
                        )],
                        ..Default::default()
                    },
                    Table {
                        name: "DimOld".to_string(),
                        columns: vec![column("Key")],
                        partitions: vec![m_partition("DimOld", "let Source = DimOld in Source")],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[column_target("Sales", "Key")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            not_unused(&unused, &table_id("DimOld"));
        }

        /// The lexer narrowed the old substring match, deliberately: a shared
        /// expression whose name appears only inside an M comment or an
        /// unrelated string is no longer "referenced".
        #[test]
        fn a_name_inside_an_m_comment_or_string_keeps_nothing_alive() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    partitions: vec![m_partition(
                        "Sales",
                        concat!(
                            "let\n",
                            "    // ServerName was renamed; this step is retired.\n",
                            "    Text = \"ServerName is mentioned here as data\",\n",
                            "    Source = 1\n",
                            "in\n",
                            "    Source",
                        ),
                    )],
                    ..Default::default()
                }],
                expressions: vec![SharedExpression {
                    name: "ServerName".to_string(),
                    expression: "\"localhost\"".to_string(),
                }],
                ..Default::default()
            };
            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            find(
                &unused,
                &ObjectId::Expression {
                    name: NameKey::new("ServerName"),
                },
            );
        }

        /// A bookmark's saved filter is a root like a live one.
        #[test]
        fn a_bookmark_saved_filter_is_a_root() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![column("Region")],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let report = ReportModel {
                bookmarks: vec![Bookmark {
                    name: NameKey::new("B1"),
                    display_name: None,
                    filters: Vec::new(),
                    sections: vec![BookmarkSection {
                        page: NameKey::new("P1"),
                        filters: Vec::new(),
                        visuals: vec![BookmarkVisual {
                            visual: NameKey::new("V1"),
                            wells: Vec::new(),
                            filters: vec![Filter {
                                target: Some(column_target("Sales", "Region")),
                                ..Default::default()
                            }],
                        }],
                    }],
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(graph.unused_objects().is_empty());
            let roots = graph.roots();
            assert_eq!(roots.len(), 1);
            assert!(matches!(
                &roots[0].1,
                Provenance::Binding(edge) if edge.bookmark.is_some()
            ));
        }

        /// Engine-managed columns ride along with their table: calculated-table
        /// columns cannot be dropped independently.
        #[test]
        fn calculated_table_columns_stay_with_their_table() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Top Products".to_string(),
                    columns: vec![Column {
                        name: "Product".to_string(),
                        kind: ColumnKind::CalculatedTableColumn,
                        ..Default::default()
                    }],
                    partitions: vec![Partition {
                        name: "Top Products".to_string(),
                        source: PartitionSource::Calculated {
                            expression: "TOPN(10, 'Product')".to_string(),
                        },
                    }],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[column_target("Top Products", "Product")]);

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(graph.unused_objects().is_empty());
        }

        /// Calendar-bound columns ride along with their table: the engine
        /// materializes them through the calendar, so a column referenced
        /// only through a calendar is not dead.
        #[test]
        fn calendar_columns_stay_with_their_table() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Date".to_string(),
                    columns: vec![column("Day")],
                    calendars: vec![crate::model::Calendar {
                        name: "Fiscal Calendar".to_string(),
                        columns: vec!["Day".to_string()],
                    }],
                    measures: vec![measure("Rows", "COUNTROWS('Date')")],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[measure_target("Date", "Rows")]);

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(graph.unused_objects().is_empty());
        }

        /// A dead table drags its calendar-bound columns along, annotated:
        /// the calendar is the only thing that ever referenced them.
        #[test]
        fn a_dead_table_annotates_its_calendar_columns() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Date".to_string(),
                    columns: vec![column("Day")],
                    calendars: vec![crate::model::Calendar {
                        name: "Fiscal Calendar".to_string(),
                        columns: vec!["Day".to_string()],
                    }],
                    ..Default::default()
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            let day = find(&unused, &column_id("Date", "Day"));
            assert_eq!(day.used_by.len(), 1);
            assert_eq!(day.used_by[0].id, table_id("Date"));
            assert!(day.used_by[0].also_unused);
            assert!(matches!(
                day.used_by[0].provenance,
                Provenance::Structural {
                    role: StructuralEdge::EngineManaged
                }
            ));
        }
    }

    mod queries {
        use super::*;

        #[test]
        fn queries_on_an_unknown_object_are_empty() {
            let graph = DependencyGraph::build(&TabularDatabase::default(), &[]);

            assert!(graph.consumers_of(&table_id("Nope")).is_empty());
            assert!(graph.producers_of(&table_id("Nope")).is_empty());
            assert!(graph.roots_of(&table_id("Nope")).is_empty());
        }

        #[test]
        fn unused_objects_are_sorted_by_identity() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![column("B"), column("A")],
                    ..Default::default()
                }],
                ..Default::default()
            };

            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();
            let ids: Vec<&ObjectId> = unused.iter().map(|finding| &finding.id).collect();
            let mut sorted = ids.clone();
            sorted.sort();

            assert_eq!(ids, sorted);
        }

        #[test]
        fn the_root_carries_the_full_binding_provenance() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    measures: vec![measure("Total", "0")],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let report = visual_page("P2", "Card", &[measure_target("Sales", "Total")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let roots = graph.roots();

            assert_eq!(roots.len(), 1);
            assert_eq!(roots[0].0, measure_id("Sales", "Total"));
            let Provenance::Binding(edge) = &roots[0].1 else {
                panic!("a root carries binding provenance");
            };
            let BindingEdge {
                kind,
                report: report_name,
                page,
                visual,
                bookmark,
            } = edge.as_ref();
            assert!(matches!(kind, BindingSite::FieldWell { role } if role == "Values"));
            assert_eq!(report_name.as_ref().map(NameKey::as_str), Some("Mini"));
            assert_eq!(page.as_ref().map(NameKey::as_str), Some("P2"));
            assert_eq!(visual.as_ref().map(NameKey::as_str), Some("Card"));
            assert!(bookmark.is_none());
        }
    }

    /// The auto date/time story end to end: a varied date column, the engine's
    /// hidden `LocalDateTable_*`, and the three verdicts no reachability pass
    /// can produce on its own.
    mod auto_date_time {
        use super::*;

        fn hierarchy_level_target(
            table: &str,
            hierarchy: &str,
            level: &str,
            via_column: Option<&str>,
            via_variation: Option<&str>,
        ) -> FieldTarget {
            FieldTarget::HierarchyLevel {
                table: NameKey::new(table),
                hierarchy: NameKey::new(hierarchy),
                level: NameKey::new(level),
                via_column: via_column.map(NameKey::new),
                via_variation: via_variation.map(NameKey::new),
            }
        }

        /// `'Sales'[Date]` varying through `LocalDateTable_x` — the model's
        /// declaration plus the hidden relationship it names.
        fn varied_model(variation: Option<Variation>) -> TabularDatabase {
            let local_date_table = Table {
                name: "LocalDateTable_9e0bbdfc-9803-41d0-b204-481ce398f228".to_string(),
                is_local_date_table: true,
                is_hidden: true,
                columns: vec![column("Date"), column("Year"), column("Month")],
                hierarchies: vec![Hierarchy {
                    name: "Date Hierarchy".to_string(),
                    levels: vec![
                        HierarchyLevel {
                            name: "Year".to_string(),
                            column: "Year".to_string(),
                        },
                        HierarchyLevel {
                            name: "Month".to_string(),
                            column: "Month".to_string(),
                        },
                    ],
                    ..Default::default()
                }],
                ..Default::default()
            };
            let mut date = column("Date");
            date.variations = variation.into_iter().collect();
            TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        columns: vec![date, column("Amount")],
                        ..Default::default()
                    },
                    local_date_table,
                ],
                relationships: vec![Relationship {
                    from_table: "Sales".to_string(),
                    from_column: "Date".to_string(),
                    to_table: "LocalDateTable_9e0bbdfc-9803-41d0-b204-481ce398f228".to_string(),
                    to_column: "Date".to_string(),
                    ..Default::default()
                }],
                ..Default::default()
            }
        }

        fn declared_variation() -> Variation {
            Variation {
                name: "Variation".to_string(),
                is_default: true,
                relationship: Some("b10a0bfa-b7fe-4437-8b2d-85624b0f085f".to_string()),
                default_hierarchy: Some(HierarchyRef {
                    table: "LocalDateTable_9e0bbdfc-9803-41d0-b204-481ce398f228".to_string(),
                    hierarchy: "Date Hierarchy".to_string(),
                }),
            }
        }

        fn local_table_id() -> ObjectId {
            table_id("LocalDateTable_9e0bbdfc-9803-41d0-b204-481ce398f228")
        }

        fn hierarchy_id() -> ObjectId {
            ObjectId::Hierarchy {
                table: NameKey::new("LocalDateTable_9e0bbdfc-9803-41d0-b204-481ce398f228"),
                hierarchy: NameKey::new("Date Hierarchy"),
            }
        }

        /// The headline fix: a visual's date hierarchy over a varied column
        /// resolves through the variation declaration onto the hidden table's
        /// hierarchy, and the whole machinery goes alive.
        #[test]
        fn a_variation_bound_date_hierarchy_keeps_the_machinery_alive() {
            let db = varied_model(Some(declared_variation()));
            let report = visual_page(
                "P1",
                "V1",
                &[hierarchy_level_target(
                    "Sales",
                    "Date Hierarchy",
                    "Year",
                    Some("Date"),
                    Some("Variation"),
                )],
            );

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            assert_eq!(
                graph.roots_of(&hierarchy_id()).len(),
                1,
                "the binding lands on the date table's hierarchy"
            );
            not_unused(&unused, &hierarchy_id());
            not_unused(&unused, &local_table_id());
            not_unused(
                &unused,
                &column_id(
                    "LocalDateTable_9e0bbdfc-9803-41d0-b204-481ce398f228",
                    "Year",
                ),
            );
            // The machinery is bound, so the verdict is InUse and names the
            // varied column.
            let verdicts = graph.auto_date_time_tables(&db);
            assert_eq!(verdicts.len(), 1);
            assert_eq!(verdicts[0].verdict, AutoDateTimeStatus::InUse);
            assert_eq!(verdicts[0].source_column, Some(column_id("Sales", "Date")));
        }

        /// A serialization that dropped the variation object still carries the
        /// relationship — and the flag marks which related table is the
        /// machinery.
        #[test]
        fn the_relationship_fallback_resolves_without_the_declaration() {
            let db = varied_model(None);
            let report = visual_page(
                "P1",
                "V1",
                &[hierarchy_level_target(
                    "Sales",
                    "Date Hierarchy",
                    "Month",
                    Some("Date"),
                    None,
                )],
            );

            let graph = DependencyGraph::build(&db, &[&report]);

            assert_eq!(graph.roots_of(&hierarchy_id()).len(), 1);
            let unused = graph.unused_objects();
            not_unused(&unused, &local_table_id());
            not_unused(
                &unused,
                &column_id(
                    "LocalDateTable_9e0bbdfc-9803-41d0-b204-481ce398f228",
                    "Month",
                ),
            );
        }

        /// The flag keeps the fallback honest: a related table that is not
        /// date machinery does not absorb the binding.
        #[test]
        fn a_related_table_that_is_not_date_machinery_does_not_resolve() {
            let mut db = varied_model(None);
            db.tables[1].is_local_date_table = false;
            let report = visual_page(
                "P1",
                "V1",
                &[hierarchy_level_target(
                    "Sales",
                    "Date Hierarchy",
                    "Year",
                    Some("Date"),
                    None,
                )],
            );

            let graph = DependencyGraph::build(&db, &[&report]);

            assert!(graph.roots_of(&hierarchy_id()).is_empty());
            // The coarse fallback still keeps the table the binding named.
            assert_eq!(graph.roots_of(&table_id("Sales")).len(), 1);
        }

        /// The verdict no reachability pass can produce: DAX keeps the
        /// machinery alive, so it is not dead — but no report binds it, which
        /// is the bloat the scan findings cannot express.
        #[test]
        fn machinery_alive_only_through_dax_is_unused_by_reports() {
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Sales".to_string(),
                        measures: vec![measure("Years", "COUNTROWS('LocalDateTable_x')")],
                        ..Default::default()
                    },
                    Table {
                        name: "LocalDateTable_x".to_string(),
                        is_local_date_table: true,
                        columns: vec![column("Year")],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            };
            let report = visual_page("P1", "V1", &[measure_target("Sales", "Years")]);

            let graph = DependencyGraph::build(&db, &[&report]);
            let unused = graph.unused_objects();

            not_unused(&unused, &local_table_id());
            let verdicts = graph.auto_date_time_tables(&db);
            assert_eq!(verdicts.len(), 1);
            assert_eq!(verdicts[0].verdict, AutoDateTimeStatus::UnusedByReports);
            assert_eq!(verdicts[0].source_column, None);
        }

        /// With no DAX and no variation keeping it alive, the machinery is
        /// simply dead.
        #[test]
        fn unbound_unreferenced_machinery_is_dead() {
            let db = varied_model(Some(declared_variation()));

            let graph = DependencyGraph::build(&db, &[]);
            let unused = graph.unused_objects();

            let dead = find(&unused, &local_table_id());
            assert!(dead.used_by.iter().all(|used| used.also_unused));
            let verdicts = graph.auto_date_time_tables(&db);
            assert_eq!(verdicts[0].verdict, AutoDateTimeStatus::Dead);
            assert_eq!(verdicts[0].source_column, Some(column_id("Sales", "Date")));
        }
    }
}