Skip to content

ontocast.tool.agg.aggregate

Embedding-based RDF graph aggregator.

This module provides the main aggregator class that orchestrates entity disambiguation using embedding-based clustering.

Pipeline: 1. Collect entities from all content units 2. Normalize entities: e -> r(e) (string representation with semantic context) 3. Generate embedding-based identity candidates 4. Validate candidate merges with symbolic identity checks 5. Select canonical identity per validated cluster 6. Assign final URIs from canonical identity + document namespace policy 7. Rewrite graphs: apply mapping e -> e' to all triples

AggregationResult

Bases: BaseModel

Outcome of one aggregation pass, including merge bookkeeping.

Attributes:

Name Type Description
graph RDFGraph

Merged facts graph with provenance annotations.

decisions dict[URIRef, EntityDecision]

Per-entity decision records (classification, identity target, final URI).

merged_clusters dict[str, list[str]]

Final URI -> all source entities sharing the same canonical identity, restricted to clusters where >= 2 distinct entities merged. A canonical spanning several documents mints one final URI per doc base; every such final URI keys the full cross-document cluster, so a validation veto dissolves the whole merge decision rather than one document's half. Keys/values are strings so the mapping can live on :class:~ontocast.onto.state.AgentState between graph nodes.

rejected_merge_count int

Candidate merges rejected by symbolic validation (guards, roles, types, lexical bar).

key_supported_clusters list[str]

Final URIs of merged clusters containing at least one natural-key pair (a shared identifier value). The validation gate treats label disagreement inside these clusters as name variance rather than a merge signature.

Source code in ontocast/tool/agg/aggregate.py
class AggregationResult(BaseModel):
    """Outcome of one aggregation pass, including merge bookkeeping.

    Attributes:
        graph: Merged facts graph with provenance annotations.
        decisions: Per-entity decision records (classification, identity
            target, final URI).
        merged_clusters: Final URI -> all source entities sharing the same
            canonical identity, restricted to clusters where >= 2 distinct
            entities merged. A canonical spanning several documents mints one
            final URI per doc base; every such final URI keys the *full*
            cross-document cluster, so a validation veto dissolves the whole
            merge decision rather than one document's half. Keys/values are
            strings so the mapping can live on
            :class:`~ontocast.onto.state.AgentState` between graph nodes.
        rejected_merge_count: Candidate merges rejected by symbolic
            validation (guards, roles, types, lexical bar).
        key_supported_clusters: Final URIs of merged clusters containing at
            least one natural-key pair (a shared identifier value). The
            validation gate treats label disagreement inside these clusters
            as name variance rather than a merge signature.
    """

    model_config = ConfigDict(arbitrary_types_allowed=True)

    graph: RDFGraph
    decisions: dict[URIRef, EntityDecision] = Field(default_factory=dict)
    merged_clusters: dict[str, list[str]] = Field(default_factory=dict)
    rejected_merge_count: int = 0
    key_supported_clusters: list[str] = Field(default_factory=list)

EmbeddingBasedAggregator

Main aggregator using embedding-based entity disambiguation.

Pipeline stages: 1. Entity normalisation (with semantic context) 2. Parallel embedding 3. Similarity-based clustering 4. Representative selection (prefer ontology, then simplicity) 5. URI normalisation (PascalCase/camelCase under DEFAULT_IRI) 6. Graph rewriting

ContentUnit types are handled as follows: - facts: entities under base_iri are normalised. - ontology: all other entities are considered ontology entities and preserved.

Source code in ontocast/tool/agg/aggregate.py
 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
class EmbeddingBasedAggregator:
    """Main aggregator using embedding-based entity disambiguation.

    Pipeline stages:
    1. Entity normalisation (with semantic context)
    2. Parallel embedding
    3. Similarity-based clustering
    4. Representative selection (prefer ontology, then simplicity)
    5. URI normalisation (PascalCase/camelCase under DEFAULT_IRI)
    6. Graph rewriting

    ContentUnit types are handled as follows:
    - ``facts``: entities under ``base_iri`` are normalised.
    - ``ontology``: all other entities are considered ontology entities and preserved.
    """

    def __init__(
        self,
        config: AggregationConfig | None = None,
        *,
        add_sameas_links: bool = True,
        base_iri: str = DEFAULT_IRI,
        candidate_similarity_threshold: float | None = None,
    ):
        """Initialise the embedding-based aggregator.

        Every tunable lives on :class:`AggregationConfig`, so ``settings.py``
        stays the single source of their defaults rather than restating them in
        this signature and again at the call site.

        Args:
            config: Aggregation tunables. Defaults to :class:`AggregationConfig`,
                i.e. the environment-resolved settings.
            add_sameas_links: Whether to add ``owl:sameAs`` for merged entities.
                Not config-driven: callers choose it per use, and the entity
                aligner wants different behaviour from the pipeline.
            base_iri: Base IRI for fact entity URIs. Entities under this
                namespace are facts; everything else is treated as an ontology
                entity and left unchanged.
            candidate_similarity_threshold: Overrides the configured permissive
                candidate threshold. The entity aligner pins it to its own
                similarity threshold rather than the pipeline's.
        """
        cfg = config or AggregationConfig()

        self.base_iri = base_iri
        self.candidate_similarity_threshold = (
            cfg.candidate_similarity_threshold
            if candidate_similarity_threshold is None
            else candidate_similarity_threshold
        )
        self.lexical_label_jaccard = cfg.lexical_label_jaccard
        self.lexical_sequence_ratio = cfg.lexical_sequence_ratio
        self.lexical_token_jaccard = cfg.lexical_token_jaccard
        self.functional_min_empirical_support = cfg.functional_min_empirical_support
        self.sibling_guard_scope = str(cfg.sibling_guard_scope)
        self.literal_conflict_guard = cfg.literal_conflict_guard
        self.initials_distinct_guard = cfg.initials_distinct_guard
        self.natural_key_merge = cfg.natural_key_merge
        self.type_guard_untyped = str(cfg.type_guard_untyped)

        # Pipeline components (EntityClusterer imports sklearn/ST lazily).
        # The clusterer runs at the permissive candidate threshold: candidates
        # are validated symbolically afterwards, so there is exactly one
        # clustering threshold on this path.
        from .clustering import EntityClusterer

        self.normalizer = EntityNormalizer(facts_iri=self.base_iri)
        self.clusterer = EntityClusterer(
            embedding_model=cfg.embedding_model,
            similarity_threshold=self.candidate_similarity_threshold,
        )
        self.selector = ClusterRepresentativeSelector()
        self.uri_builder = URIBuilder(base_iri=self.base_iri)
        self.rewriter = GraphRewriter(
            add_sameas_links=add_sameas_links,
            blocked_sameas_namespaces=(self.base_iri,),
        )

    @staticmethod
    def _entity_in_namespace(entity: URIRef, namespace: URIRef | str | None) -> bool:
        """Return True when *entity* is under the provided namespace."""
        if namespace is None:
            return False
        return is_in_namespace(str(entity), str(namespace), context="auto")

    def _is_fact_entity_in_unit(self, entity: URIRef, unit: ContentUnit) -> bool:
        """Classify whether an entity should be treated as a fact in this unit.

        Facts are entities in either:
        - the configured base facts namespace (``base_iri``), or
        - the unit document namespace (``unit.doc_iri``).
        """
        return self._entity_in_namespace(
            entity, self.base_iri
        ) or self._entity_in_namespace(entity, unit.doc_iri)

    @staticmethod
    def _is_standard_ontology_entity(entity: URIRef) -> bool:
        """Return True for entities from built-in standard RDF vocabularies."""
        entity_str = str(entity)
        return any(entity_str.startswith(prefix) for prefix in _STANDARD_NAMESPACES)

    def _build_known_ontology_entities(
        self, ontology_graph: RDFGraph | None
    ) -> set[URIRef]:
        """Build a set of known ontology entities from ontology and std vocabularies."""
        known_entities: set[URIRef] = set()

        if ontology_graph is not None:
            for s, p, o in ontology_graph:
                if isinstance(s, URIRef):
                    known_entities.add(s)
                if isinstance(p, URIRef):
                    known_entities.add(p)
                if isinstance(o, URIRef):
                    known_entities.add(o)

        return known_entities

    @staticmethod
    def _tokenize(text: str) -> set[str]:
        # Short tokens stay: initials and single-letter identifiers
        # ("company S." vs "company T.") are often the only distinguishing
        # mark, and dropping them made such labels compare identical.
        return set(label_tokens(text))

    @staticmethod
    def _role_key(representation: EntityRepresentation) -> str:
        role = (
            representation.role
            if representation.role is not None
            else EntityRole.INSTANCE
        )
        return str(role)

    @staticmethod
    def _jaccard(left: set[str], right: set[str]) -> float:
        if not left and not right:
            return 1.0
        union = left | right
        return len(left & right) / len(union)

    @staticmethod
    def _instance_like_local_name(entity: URIRef) -> str | None:
        """Return normalized local name when URI ends with numeric suffix."""
        local_name = normalize_uri_local_name(entity).replace(" ", "")
        if not local_name:
            return None
        match = _INSTANCE_LOCAL_NAME_RE.match(local_name)
        if match is None:
            return None
        if len(match.group("stem")) < 3:
            return None
        return local_name

    def _are_roles_compatible(
        self,
        left: URIRef,
        right: URIRef,
        representations: dict[URIRef, EntityRepresentation],
    ) -> bool:
        left_rep = representations.get(left)
        right_rep = representations.get(right)
        if left_rep is None or right_rep is None:
            return False
        return self._role_key(left_rep) == self._role_key(right_rep)

    def _are_types_compatible(
        self,
        left: URIRef,
        right: URIRef,
        representations: dict[URIRef, EntityRepresentation],
    ) -> bool:
        left_rep = representations.get(left)
        right_rep = representations.get(right)
        if left_rep is None or right_rep is None:
            return False
        left_types = set(left_rep.types)
        right_types = set(right_rep.types)
        if not left_types or not right_types:
            if self.type_guard_untyped == "strict":
                # Strict mode fails a typed-vs-untyped pair closed; two
                # untyped entities stay comparable — there is no type
                # evidence in either direction.
                return not left_types and not right_types
            return True
        return bool(left_types & right_types)

    def _entity_label_values(self, rep: EntityRepresentation) -> set[str]:
        """Normalized name strings an entity is identified by.

        ``alt_labels`` (string literals from arbitrary domain predicates)
        stand in only when the entity carries no ``rdfs:label``: for a
        labeled entity they are payload, not names — an honorific or role
        literal shared by several people must not read as label agreement.
        """
        source = rep.labels if rep.labels else rep.alt_labels
        return {
            self.normalizer.normalize_string(label) for label in source if label.strip()
        }

    def _are_lexical_aliases(
        self,
        left: URIRef,
        right: URIRef,
        representations: dict[URIRef, EntityRepresentation],
    ) -> bool:
        left_rep = representations.get(left)
        right_rep = representations.get(right)
        if left_rep is None or right_rep is None:
            return False
        if left_rep.normal_form == right_rep.normal_form:
            return True

        left_instance_name = self._instance_like_local_name(left)
        right_instance_name = self._instance_like_local_name(right)
        if (
            left_instance_name is not None
            and right_instance_name is not None
            and left_instance_name == right_instance_name
        ):
            return True

        left_label_tokens = self._entity_label_values(left_rep)
        right_label_tokens = self._entity_label_values(right_rep)
        if left_label_tokens & right_label_tokens:
            return True

        # Abbreviation-aware tier: "baranov d" vs "dmitry baranov" alias when
        # every token of one label matches a token of the other exactly or as
        # a single-character initial, with at least one shared full token.
        if self._labels_alias_with_initials(left_label_tokens, right_label_tokens):
            return True

        # Guard-literal-bearing entities (measurements, dated events) are
        # individuated by their payload, not their phrasing: "PL red shift of
        # SL1" vs "PL red shift of SL2" share most tokens yet denote distinct
        # values. Only the exact tiers above may merge them. String literals
        # (names, descriptions) do not raise this bar — disjoint identifier
        # strings are handled by _have_conflicting_literals instead.
        if left_rep.has_guard_literal and right_rep.has_guard_literal:
            return False

        if left_label_tokens and right_label_tokens:
            max_label_overlap = 0.0
            for left_label in left_label_tokens:
                left_tokens = self._tokenize(left_label)
                for right_label in right_label_tokens:
                    right_tokens = self._tokenize(right_label)
                    overlap = self._jaccard(left_tokens, right_tokens)
                    max_label_overlap = max(max_label_overlap, overlap)
            if max_label_overlap >= self.lexical_label_jaccard:
                return True

        left_normalized = left_rep.normal_form.strip()
        right_normalized = right_rep.normal_form.strip()
        if left_normalized and right_normalized:
            if left_normalized != right_normalized and (
                left_normalized.startswith(f"{right_normalized} ")
                or right_normalized.startswith(f"{left_normalized} ")
            ):
                return False

        ratio = SequenceMatcher(
            None, left_rep.normal_form, right_rep.normal_form
        ).ratio()
        if ratio >= self.lexical_sequence_ratio:
            return True

        left_tokens = self._tokenize(left_rep.normal_form)
        right_tokens = self._tokenize(right_rep.normal_form)
        if len(left_tokens) >= 2 and len(right_tokens) >= 2:
            if self._jaccard(left_tokens, right_tokens) >= self.lexical_token_jaccard:
                return True

        return False

    # Thin delegates: the shared implementations live in ``signatures`` so the
    # validation gate can consult the same string-compatibility notion without
    # importing the aggregator.
    _tokens_alias_compatible = staticmethod(tokens_alias_compatible)
    _labels_alias_with_initials = staticmethod(labels_alias_with_initials)
    _string_values_compatible = staticmethod(string_values_compatible)

    @classmethod
    def _have_conflicting_literals(
        cls,
        left_rep: EntityRepresentation,
        right_rep: EntityRepresentation,
    ) -> bool:
        """Return True when the entities assert disjoint values per predicate.

        A shared predicate with two non-empty, disjoint canonical value sets
        (numeric/temporal) marks the entities as distinct individuals; overlap
        or one-sided values read as re-mention/enrichment and stay mergeable.
        String payloads (identifiers, codes) conflict only when NO cross-pair
        is compatible (equality, prefix, or initial-abbreviation) — "d" vs
        "dmitry" is a re-mention, "S-2024-001" vs "S-2024-002" is a conflict.
        """
        for predicate, left_values in left_rep.predicate_literals.items():
            right_values = right_rep.predicate_literals.get(predicate)
            if not right_values or not left_values:
                continue
            if left_values.isdisjoint(right_values):
                return True
        for predicate, left_strings in left_rep.predicate_string_literals.items():
            right_strings = right_rep.predicate_string_literals.get(predicate)
            if not right_strings or not left_strings:
                continue
            if not any(
                cls._string_values_compatible(left_value, right_value)
                for left_value in left_strings
                for right_value in right_strings
            ):
                return True
        return False

    @staticmethod
    def _have_conflicting_functional_objects(
        left_rep: EntityRepresentation,
        right_rep: EntityRepresentation,
        functional_predicates: set[URIRef],
    ) -> bool:
        """Return True when a max-1 object predicate points at disjoint IRIs.

        Catches conflicts invisible to value comparison — e.g. two "10"
        quantities whose ``qudt:unit`` objects are ``DEG_C`` vs ``KiloHZ``.
        """
        if not functional_predicates:
            return False
        for predicate, left_objects in left_rep.predicate_iri_objects.items():
            if predicate not in functional_predicates:
                continue
            right_objects = right_rep.predicate_iri_objects.get(predicate)
            if not right_objects or not left_objects:
                continue
            if left_objects.isdisjoint(right_objects):
                return True
        return False

    def _labels_confirm_identity(
        self,
        left: URIRef,
        right: URIRef,
        representations: dict[URIRef, EntityRepresentation],
    ) -> bool:
        """Exact or initials-aware label agreement strong enough to skip cosine."""
        left_rep = representations.get(left)
        right_rep = representations.get(right)
        if left_rep is None or right_rep is None:
            return False
        left_labels = self._entity_label_values(left_rep)
        right_labels = self._entity_label_values(right_rep)
        if not left_labels or not right_labels:
            return False
        if left_labels & right_labels:
            return True
        return self._labels_alias_with_initials(left_labels, right_labels)

    def _labels_mark_distinct_entities(
        self,
        left_rep: EntityRepresentation,
        right_rep: EntityRepresentation,
    ) -> bool:
        """Label pairs identical except for conflicting initials mark distinctness."""
        if not self.initials_distinct_guard:
            return False
        return labels_differ_only_by_initials(
            self._entity_label_values(left_rep),
            self._entity_label_values(right_rep),
        )

    def _pair_distinctness_veto(
        self,
        left: URIRef,
        right: URIRef,
        representations: dict[URIRef, EntityRepresentation],
        direct_relation_pairs: set[frozenset[URIRef]] | None = None,
        guard_context: MergeGuardContext | None = None,
    ) -> bool:
        """Positive evidence that *left* and *right* denote distinct entities.

        Unlike the absence of a lexical alias — which merely fails to support
        a merge — a veto is grounds to keep the pair apart in *any* identity
        cluster, including transitively: two entities that a guard separates
        must not end up merged through a chain of intermediate aliases.
        """
        pair = frozenset((left, right))
        if direct_relation_pairs is not None and pair in direct_relation_pairs:
            return True
        left_rep = representations.get(left)
        right_rep = representations.get(right)
        if guard_context is not None:
            if pair in guard_context.sibling_pairs:
                return True
            if left_rep is not None and right_rep is not None:
                if self.literal_conflict_guard and self._have_conflicting_literals(
                    left_rep, right_rep
                ):
                    return True
                if self._have_conflicting_functional_objects(
                    left_rep, right_rep, guard_context.functional_predicates
                ):
                    return True
        if left_rep is not None and right_rep is not None:
            if self._labels_mark_distinct_entities(left_rep, right_rep):
                return True
        if not self._are_roles_compatible(left, right, representations):
            return True
        if not self._are_types_compatible(left, right, representations):
            return True
        return False

    def _can_merge_as_identity(
        self,
        left: URIRef,
        right: URIRef,
        representations: dict[URIRef, EntityRepresentation],
        direct_relation_pairs: set[frozenset[URIRef]] | None = None,
        guard_context: MergeGuardContext | None = None,
        key_pairs: set[frozenset[URIRef]] | None = None,
    ) -> bool:
        if self._pair_distinctness_veto(
            left,
            right,
            representations,
            direct_relation_pairs=direct_relation_pairs,
            guard_context=guard_context,
        ):
            return False
        if key_pairs is not None and frozenset((left, right)) in key_pairs:
            # A shared value on a single-valued identifier-like predicate is
            # positive identity evidence in its own right; the guards above
            # still had their say.
            return True
        return self._are_lexical_aliases(left, right, representations)

    def _collect_natural_key_pairs(
        self,
        representations: dict[URIRef, EntityRepresentation],
        schema_functional_predicates: set[URIRef],
    ) -> set[frozenset[URIRef]]:
        """Instance pairs sharing a value on a single-valued identifier predicate.

        Every guard in this module is a veto; this is the one source of
        *positive* symbolic identity evidence: two instances asserting the
        same value for a predicate that behaves like an identifier (declared
        max-1 by the schema, or observed single-valued on every subject) are
        candidate re-mentions of one entity — "Application no. 36760/06" is
        the same case wherever its number appears. Pairs found here are still
        subject to all distinctness vetoes; string values only (dates and
        numbers are coordinates, not identifiers), short values only (prose
        payloads such as notes and descriptions are not keys), and values
        shared too widely are treated as generic rather than identifying.
        """
        instance_role = str(EntityRole.INSTANCE)
        by_predicate: dict[URIRef, dict[URIRef, set[str]]] = {}
        for entity, rep in representations.items():
            if self._role_key(rep) != instance_role:
                continue
            for predicate, values in rep.predicate_string_literals.items():
                filtered = {
                    value
                    for value in values
                    if 0 < len(value) <= _NATURAL_KEY_MAX_VALUE_LENGTH
                }
                if filtered:
                    by_predicate.setdefault(predicate, {})[entity] = filtered

        pairs: set[frozenset[URIRef]] = set()
        for predicate, entity_values in by_predicate.items():
            if predicate not in schema_functional_predicates:
                if len(entity_values) < self.functional_min_empirical_support:
                    continue
                if any(len(values) != 1 for values in entity_values.values()):
                    continue
            value_index: dict[str, list[URIRef]] = {}
            for entity, values in entity_values.items():
                for value in values:
                    value_index.setdefault(value, []).append(entity)
            for value, entities in value_index.items():
                if not 2 <= len(entities) <= _NATURAL_KEY_MAX_VALUE_ENTITIES:
                    continue
                for left, right in combinations(sorted(entities, key=str), 2):
                    pairs.add(frozenset((left, right)))
        return pairs

    @staticmethod
    def _merge_candidate_clusters_by_key_pairs(
        candidate_clusters: list[list[URIRef]],
        key_pairs: set[frozenset[URIRef]],
    ) -> list[list[URIRef]]:
        """Join candidate clusters bridged by a natural-key pair.

        Embedding clustering only proposes pairs that read alike; two mentions
        of one entity under different surface forms ("Application no. X" vs
        "Case A v. B") never co-cluster, so a key pair spanning two candidate
        clusters must pull them into one before symbolic validation — which
        still adjudicates every pair inside the joined cluster.
        """
        if not key_pairs:
            return candidate_clusters
        cluster_of: dict[URIRef, int] = {}
        for index, cluster in enumerate(candidate_clusters):
            for entity in cluster:
                cluster_of[entity] = index

        parent = list(range(len(candidate_clusters)))

        def find(index: int) -> int:
            while parent[index] != index:
                parent[index] = parent[parent[index]]
                index = parent[index]
            return index

        for pair in key_pairs:
            left, right = tuple(pair)
            left_index = cluster_of.get(left)
            right_index = cluster_of.get(right)
            if left_index is None or right_index is None:
                continue
            left_root, right_root = find(left_index), find(right_index)
            if left_root != right_root:
                parent[max(left_root, right_root)] = min(left_root, right_root)

        grouped: dict[int, list[URIRef]] = {}
        for index, cluster in enumerate(candidate_clusters):
            grouped.setdefault(find(index), []).extend(cluster)
        return list(grouped.values())

    def _cluster_entities_by_role(
        self, representations: dict[URIRef, EntityRepresentation]
    ) -> tuple[list[list[URIRef]], dict[URIRef, np.ndarray]]:
        grouped_entities: dict[str, dict[URIRef, EntityRepresentation]] = {}
        for entity, representation in representations.items():
            grouped_entities.setdefault(self._role_key(representation), {})[entity] = (
                representation
            )

        all_clusters: list[list[URIRef]] = []
        all_embeddings: dict[URIRef, np.ndarray] = {}
        for role_representations in grouped_entities.values():
            role_clusters, role_embeddings = self.clusterer.cluster_entities(
                role_representations
            )
            all_clusters.extend(role_clusters)
            all_embeddings.update(role_embeddings)
        return all_clusters, all_embeddings

    @staticmethod
    def _candidate_similarity(
        left: URIRef,
        right: URIRef,
        embeddings: dict[URIRef, np.ndarray],
    ) -> float | None:
        left_embedding = embeddings.get(left)
        right_embedding = embeddings.get(right)
        if left_embedding is None or right_embedding is None:
            return None

        denominator = float(
            np.linalg.norm(left_embedding) * np.linalg.norm(right_embedding)
        )
        if denominator == 0:
            return None
        return float(np.dot(left_embedding, right_embedding) / denominator)

    def _merge_validation_failures(
        self,
        left: URIRef,
        right: URIRef,
        representations: dict[URIRef, EntityRepresentation],
        guard_context: MergeGuardContext | None = None,
    ) -> list[str]:
        failures: list[str] = []
        if guard_context is not None:
            if frozenset((left, right)) in guard_context.sibling_pairs:
                failures.append("sibling")
            left_rep = representations.get(left)
            right_rep = representations.get(right)
            if left_rep is not None and right_rep is not None:
                if self.literal_conflict_guard and self._have_conflicting_literals(
                    left_rep, right_rep
                ):
                    failures.append("literal_conflict")
                if self._have_conflicting_functional_objects(
                    left_rep, right_rep, guard_context.functional_predicates
                ):
                    failures.append("functional_iri_conflict")
                if self._labels_mark_distinct_entities(left_rep, right_rep):
                    failures.append("initials_conflict")
        if not self._are_roles_compatible(left, right, representations):
            failures.append("role")
        if not self._are_types_compatible(left, right, representations):
            failures.append("type")
        if not self._are_lexical_aliases(left, right, representations):
            failures.append("lexical")
        return failures

    def _build_identity_clusters(
        self,
        candidate_clusters: list[list[URIRef]],
        representations: dict[URIRef, EntityRepresentation],
        embeddings: dict[URIRef, np.ndarray],
        direct_relation_pairs: set[frozenset[URIRef]] | None = None,
        guard_context: MergeGuardContext | None = None,
        key_pairs: set[frozenset[URIRef]] | None = None,
    ) -> tuple[
        list[list[URIRef]], list[tuple[URIRef, URIRef, float | None, tuple[str, ...]]]
    ]:
        validated_clusters: list[list[URIRef]] = []
        rejected_merges: list[tuple[URIRef, URIRef, float | None, tuple[str, ...]]] = []

        for candidate_cluster in candidate_clusters:
            if len(candidate_cluster) <= 1:
                validated_clusters.append(candidate_cluster)
                continue

            ordered_cluster = sorted(candidate_cluster, key=str)
            parents: dict[URIRef, URIRef] = {
                entity: entity for entity in ordered_cluster
            }
            members: dict[URIRef, set[URIRef]] = {
                entity: {entity} for entity in ordered_cluster
            }

            # Distinctness vetoes hold cluster-wide: an accepted A–B edge and
            # an accepted B–C edge must not merge a vetoed A–C pair through
            # transitive closure. Computed for every pair up front (the guards
            # are cheap symbolic checks) so unions can be checked against all
            # current members of both sides.
            vetoed_pairs: set[frozenset[URIRef]] = {
                frozenset((left, right))
                for left, right in combinations(ordered_cluster, 2)
                if self._pair_distinctness_veto(
                    left,
                    right,
                    representations,
                    direct_relation_pairs=direct_relation_pairs,
                    guard_context=guard_context,
                )
            }

            def find(entity: URIRef) -> URIRef:
                root = parents[entity]
                if root != entity:
                    parents[entity] = find(root)
                return parents[entity]

            def union_blocked(left_root: URIRef, right_root: URIRef) -> bool:
                left_members = members[left_root]
                right_members = members[right_root]
                return any(
                    frozenset((left_member, right_member)) in vetoed_pairs
                    for left_member in left_members
                    for right_member in right_members
                )

            def union(left: URIRef, right: URIRef) -> None:
                left_root = find(left)
                right_root = find(right)
                if left_root == right_root:
                    return
                if str(left_root) <= str(right_root):
                    parents[right_root] = left_root
                    members[left_root] |= members.pop(right_root)
                else:
                    parents[left_root] = right_root
                    members[right_root] |= members.pop(left_root)

            for left, right in combinations(ordered_cluster, 2):
                pair = frozenset((left, right))
                score = self._candidate_similarity(left, right, embeddings)
                if score is not None and score < self.candidate_similarity_threshold:
                    # Label-confirmed and key-confirmed pairs bypass the cosine
                    # gate (mirrors EntityAligner): short-string embeddings of
                    # aliases like "Baranov, D." vs "Dmitry Baranov" hover
                    # around the threshold, which made identity linking
                    # nondeterministic — and a shared identifier value needs no
                    # embedding agreement at all.
                    if not (
                        (key_pairs is not None and pair in key_pairs)
                        or self._labels_confirm_identity(left, right, representations)
                    ):
                        continue
                if self._can_merge_as_identity(
                    left,
                    right,
                    representations,
                    direct_relation_pairs=direct_relation_pairs,
                    guard_context=guard_context,
                    key_pairs=key_pairs,
                ):
                    left_root = find(left)
                    right_root = find(right)
                    if left_root == right_root:
                        continue
                    if union_blocked(left_root, right_root):
                        # The pair itself is mergeable, but somewhere in the
                        # two groups sits a vetoed pair — accepting the edge
                        # would chain around that guard.
                        rejected_merges.append((left, right, score, ("cluster_veto",)))
                        continue
                    union(left, right)
                    continue
                rejected_merges.append(
                    (
                        left,
                        right,
                        score,
                        tuple(
                            self._merge_validation_failures(
                                left,
                                right,
                                representations,
                                guard_context=guard_context,
                            )
                        ),
                    )
                )

            grouped: dict[URIRef, list[URIRef]] = {}
            for entity in ordered_cluster:
                grouped.setdefault(find(entity), []).append(entity)

            for group in grouped.values():
                sorted_group = sorted(group, key=str)
                validated_clusters.append(sorted_group)

        return validated_clusters, rejected_merges

    def _select_ontology_anchor_candidates(
        self,
        tentative_entities: list[URIRef],
        tentative_representations: dict[URIRef, EntityRepresentation],
        tentative_doc_iris: dict[URIRef, URIRef],
        ontology_graph: RDFGraph | None,
        known_ontology_entities: set[URIRef],
    ) -> dict[URIRef, URIRef]:
        """Pick ontology anchors and preserve the triggering document IRI."""
        if (
            ontology_graph is None
            or not tentative_entities
            or not known_ontology_entities
        ):
            return {}

        ontology_entities = [
            entity
            for entity in known_ontology_entities
            if not self._is_standard_ontology_entity(entity)
        ]
        if not ontology_entities:
            return {}

        ontology_graphs = {entity: ontology_graph for entity in ontology_entities}
        ontology_representations = self.normalizer.create_representations_batch(
            ontology_entities, ontology_graphs
        )

        token_index: dict[str, set[URIRef]] = {}
        for entity, representation in ontology_representations.items():
            for token in self._tokenize(representation.representation):
                token_index.setdefault(token, set()).add(entity)

        selected: dict[URIRef, URIRef] = {}
        for tentative_entity in tentative_entities:
            tentative_representation = tentative_representations.get(tentative_entity)
            if tentative_representation is None:
                continue
            tentative_doc_iri = tentative_doc_iris.get(tentative_entity)
            if tentative_doc_iri is None:
                continue
            tentative_tokens = self._tokenize(tentative_representation.representation)
            if not tentative_tokens:
                continue

            candidate_pool: set[URIRef] = set()
            for token in tentative_tokens:
                candidate_pool.update(token_index.get(token, set()))

            if not candidate_pool:
                continue

            scored: list[tuple[int, URIRef]] = []
            for candidate in candidate_pool:
                candidate_representation = ontology_representations.get(candidate)
                if candidate_representation is None:
                    continue
                candidate_tokens = self._tokenize(
                    candidate_representation.representation
                )
                overlap = len(tentative_tokens & candidate_tokens)
                if overlap >= 2:
                    scored.append((overlap, candidate))

            scored.sort(key=lambda item: (-item[0], str(item[1])))
            for _, candidate in scored[:3]:
                selected.setdefault(candidate, tentative_doc_iri)

        return selected

    def _classify_entity_for_unit(
        self,
        entity: URIRef,
        unit: ContentUnit,
        known_ontology_entities: set[URIRef],
    ) -> EntityClassification:
        """Classify an entity as fact, known ontology, or tentative ontology."""
        if unit.type == OutputType.ONTOLOGIES:
            return EntityClassification.KNOWN_ONTOLOGY

        if self._is_fact_entity_in_unit(entity, unit):
            return EntityClassification.FACT

        if entity in known_ontology_entities or self._is_standard_ontology_entity(
            entity
        ):
            return EntityClassification.KNOWN_ONTOLOGY

        return EntityClassification.TENTATIVE_ONTOLOGY

    @staticmethod
    def _classification_priority(classification: EntityClassification) -> int:
        """Return priority for multi-unit classification merging."""
        if classification == EntityClassification.KNOWN_ONTOLOGY:
            return 3
        if classification == EntityClassification.TENTATIVE_ONTOLOGY:
            return 2
        return 1

    @staticmethod
    def _merge_into_context_graph(target: RDFGraph, source: RDFGraph) -> None:
        """Merge source triples/namespaces into a per-entity context graph."""
        target += source

    def _register_entity(
        self,
        *,
        entity: URIRef,
        unit: ContentUnit,
        state: _EntityCollectionState,
    ) -> None:
        """Register one URI entity with merged context and stable classification."""
        state.entities.add(entity)
        state.source_entities.add(entity)
        if entity not in state.entity_graphs:
            state.entity_graphs[entity] = unit.graph.copy()
        else:
            self._merge_into_context_graph(state.entity_graphs[entity], unit.graph)
        state.entity_doc_iris.setdefault(entity, unit.doc_iri)
        current = state.entity_classification.get(entity, EntityClassification.FACT)
        candidate = self._classify_entity_for_unit(entity, unit, state.known_entities)
        state.entity_classification[entity] = (
            candidate
            if self._classification_priority(candidate)
            >= self._classification_priority(current)
            else current
        )

    @staticmethod
    def _register_direct_relation(
        state: _EntityCollectionState,
        subject: URIRef,
        obj: URIRef,
    ) -> None:
        """Record direct subject-object URI relation pair in collection state."""
        if subject == obj:
            return
        state.direct_relation_pairs.add(frozenset((subject, obj)))

    def _collect_all_entities(
        self,
        units: list[ContentUnit],
        known_ontology_entities: set[URIRef] | None = None,
    ) -> tuple[
        list[URIRef],
        set[URIRef],
        dict[URIRef, RDFGraph],
        dict[URIRef, URIRef],
        dict[URIRef, EntityClassification],
        set[frozenset[URIRef]],
        dict[tuple[URIRef, URIRef], set[URIRef]],
    ]:
        """Collect all entities from all content unit graphs.

        Each entity is associated with the graph it was found in and the
        ``doc_iri`` of the :class:`ContentUnit` that produced it.  When an
        entity appears in several units the *last-seen* ``doc_iri`` wins (in
        practice most pipelines aggregate chunks of the same document, so all
        ``doc_iri`` values are identical).

        Args:
            units: List of content units to aggregate.

        Returns:
            Tuple of (
                entities,
                entity_to_graph,
                entity_to_doc_iri,
                entity_to_is_ontology,
            ).
        """
        state = _EntityCollectionState(known_entities=known_ontology_entities or set())

        for unit in units:
            if unit.graph is None:
                continue
            unit.graph.sanitize_prefixes_namespaces()
            # Keep collection in the same URI space that rewrite/merge consumes
            # (unit.graph). Using graph_absolute here causes mapping keys to miss
            # during rewrite, because unit.graph still contains the original terms.
            for s, p, o in unit.graph:
                if isinstance(s, URIRef) and isinstance(o, URIRef):
                    self._register_direct_relation(state=state, subject=s, obj=o)
                    if isinstance(p, URIRef) and p != RDF.type:
                        state.object_groups.setdefault((s, p), set()).add(o)
                for term in (s, p, o):
                    if isinstance(term, URIRef):
                        self._register_entity(entity=term, unit=unit, state=state)

        return (
            list(state.entities),
            state.source_entities,
            state.entity_graphs,
            state.entity_doc_iris,
            state.entity_classification,
            state.direct_relation_pairs,
            state.object_groups,
        )

    def aggregate_graphs(
        self,
        units: list[ContentUnit],
        ontology_graph: RDFGraph,
        merge_vetoes: set[frozenset[URIRef]] | None = None,
    ) -> AggregationResult:
        """Aggregate multiple content unit graphs with embedding-based disambiguation.

        Args:
            units: List of ContentUnits to aggregate.
            ontology_graph: Selected ontology graph used to distinguish
                known ontology entities from tentative ontology-like aliases.
            merge_vetoes: Extra entity pairs that must never identity-merge —
                the targeted un-merge lever used by the post-aggregation
                validation gate. Unioned into the direct-relation veto set.

        Returns:
            :class:`AggregationResult` with the merged graph and merge
            bookkeeping (decisions, merged clusters, rejection count).
        """
        logger.info(f"Starting aggregation with metadata for {len(units)} units")
        if ontology_graph is None:
            raise ValueError("ontology_graph must not be None for facts aggregation")

        if not units:
            return AggregationResult(graph=RDFGraph())

        # Steps 1-3: Collect, normalise, candidate clustering
        known_ontology_entities = self._build_known_ontology_entities(ontology_graph)
        (
            entities,
            source_entities,
            entity_graphs,
            entity_doc_iris,
            entity_classification,
            direct_relation_pairs,
            object_groups,
        ) = self._collect_all_entities(units, known_ontology_entities)
        if merge_vetoes:
            direct_relation_pairs = direct_relation_pairs | merge_vetoes
        schema_functional_predicates = harvest_max_one_predicates(ontology_graph)
        guard_context = MergeGuardContext(
            sibling_pairs=build_sibling_pairs(
                object_groups, scope=self.sibling_guard_scope
            ),
            functional_predicates=schema_functional_predicates
            | empirically_functional_predicates(
                object_groups,
                min_support=self.functional_min_empirical_support,
            ),
        )
        representations = self.normalizer.create_representations_batch(
            entities, entity_graphs
        )
        decisions: dict[URIRef, EntityDecision] = {
            entity: EntityDecision(
                classification=classification,
                identity_target=entity,
            )
            for entity, classification in entity_classification.items()
        }
        tentative_entities = [
            entity
            for entity, decision in decisions.items()
            if decision.classification == EntityClassification.TENTATIVE_ONTOLOGY
        ]
        anchor_candidates = self._select_ontology_anchor_candidates(
            tentative_entities=tentative_entities,
            tentative_representations=representations,
            tentative_doc_iris=entity_doc_iris,
            ontology_graph=ontology_graph,
            known_ontology_entities=known_ontology_entities,
        )
        if anchor_candidates:
            for ontology_entity, anchor_doc_iri in anchor_candidates.items():
                if ontology_entity in entity_graphs:
                    continue
                entities.append(ontology_entity)
                entity_graphs[ontology_entity] = ontology_graph
                entity_doc_iris[ontology_entity] = anchor_doc_iri
                entity_classification[ontology_entity] = (
                    EntityClassification.KNOWN_ONTOLOGY
                )
                decisions[ontology_entity] = EntityDecision(
                    classification=EntityClassification.KNOWN_ONTOLOGY,
                    identity_target=ontology_entity,
                )
                representations[ontology_entity] = (
                    self.normalizer.create_representation(
                        ontology_entity, ontology_graph
                    )
                )
        entity_is_known_ontology = {
            entity: decision.classification == EntityClassification.KNOWN_ONTOLOGY
            for entity, decision in decisions.items()
        }
        if logger.isEnabledFor(logging.INFO):
            known_count = sum(
                1 for is_known in entity_is_known_ontology.values() if is_known
            )
            fact_count = sum(
                1
                for decision in decisions.values()
                if decision.classification == EntityClassification.FACT
            )
            logger.info(
                "Aggregation entity classification stats: fact=%d known_ontology=%d "
                "tentative_ontology=%d",
                fact_count,
                known_count,
                len(tentative_entities),
            )

        candidate_clusters, embeddings = self._cluster_entities_by_role(representations)
        key_pairs: set[frozenset[URIRef]] = set()
        if self.natural_key_merge:
            key_pairs = self._collect_natural_key_pairs(
                representations, schema_functional_predicates
            )
            if key_pairs:
                logger.info(
                    "Natural-key evidence proposed %d candidate pair(s)",
                    len(key_pairs),
                )
                candidate_clusters = self._merge_candidate_clusters_by_key_pairs(
                    candidate_clusters, key_pairs
                )
        clusters, rejected_merges = self._build_identity_clusters(
            candidate_clusters=candidate_clusters,
            representations=representations,
            embeddings=embeddings,
            direct_relation_pairs=direct_relation_pairs,
            guard_context=guard_context,
            key_pairs=key_pairs or None,
        )
        if rejected_merges:
            logger.info(
                "Rejected %d candidate merges after symbolic validation",
                len(rejected_merges),
            )
            for left, right, score, failed_checks in rejected_merges:
                logger.debug(
                    "Rejected candidate merge: %s <-> %s (score=%s, failed=%s)",
                    left,
                    right,
                    f"{score:.3f}" if score is not None else "n/a",
                    ",".join(failed_checks) if failed_checks else "unknown",
                )

        # Step 4: Canonical identity mapping (no URI policy yet)
        identity_mapping = self.selector.create_mapping(
            clusters,
            representations,
            entity_is_known_ontology=entity_is_known_ontology,
        )

        # Keep known ontology entities stable. Tentative ontology-like entities are:
        # - mapped to known ontology representatives when present in a mixed cluster
        # - preserved as-is when only tentative entities are present
        suppress_sameas_origins: set[URIRef] = set()
        suppress_fact_subject_sources: set[URIRef] = set()
        for cluster in clusters:
            known_ontology_entities_in_cluster = [
                entity
                for entity in cluster
                if decisions.get(entity) is not None
                and decisions[entity].classification
                == EntityClassification.KNOWN_ONTOLOGY
            ]
            tentative_entities_in_cluster = [
                entity
                for entity in cluster
                if decisions.get(entity) is not None
                and decisions[entity].classification
                == EntityClassification.TENTATIVE_ONTOLOGY
            ]
            fact_entities_in_cluster = [
                entity
                for entity in cluster
                if decisions.get(entity) is not None
                and decisions[entity].classification == EntityClassification.FACT
            ]

            for entity in known_ontology_entities_in_cluster:
                identity_mapping[entity] = entity

            if known_ontology_entities_in_cluster:
                canonical_known_ontology = self.selector.select_representative(
                    known_ontology_entities_in_cluster,
                    representations,
                    entity_is_known_ontology=entity_is_known_ontology,
                )
                for tentative_entity in tentative_entities_in_cluster:
                    if self._can_merge_as_identity(
                        tentative_entity,
                        canonical_known_ontology,
                        representations,
                        direct_relation_pairs=direct_relation_pairs,
                        guard_context=guard_context,
                    ):
                        identity_mapping[tentative_entity] = canonical_known_ontology
                        decisions[tentative_entity].suppress_sameas = True
                    else:
                        identity_mapping[tentative_entity] = tentative_entity
                for fact_entity in fact_entities_in_cluster:
                    if self._can_merge_as_identity(
                        fact_entity,
                        canonical_known_ontology,
                        representations,
                        direct_relation_pairs=direct_relation_pairs,
                        guard_context=guard_context,
                    ):
                        identity_mapping[fact_entity] = canonical_known_ontology
                        decisions[fact_entity].suppress_sameas = True
                        decisions[fact_entity].suppress_fact_subject_assertions = True
                    else:
                        identity_mapping[fact_entity] = fact_entity

            elif tentative_entities_in_cluster:
                # In mixed FACT + TENTATIVE clusters with no known ontology
                # entity, prefer the FACT side when symbolic identity checks
                # agree (e.g. hallucinated ontology prefix on an instance).
                if fact_entities_in_cluster:
                    canonical_fact = self.selector.select_representative(
                        fact_entities_in_cluster,
                        representations,
                        entity_is_known_ontology=entity_is_known_ontology,
                    )
                    for fact_entity in fact_entities_in_cluster:
                        identity_mapping[fact_entity] = canonical_fact
                    for tentative_entity in tentative_entities_in_cluster:
                        if self._can_merge_as_identity(
                            tentative_entity,
                            canonical_fact,
                            representations,
                            direct_relation_pairs=direct_relation_pairs,
                            guard_context=guard_context,
                        ):
                            identity_mapping[tentative_entity] = canonical_fact
                            decisions[tentative_entity].suppress_sameas = True
                        else:
                            identity_mapping[tentative_entity] = tentative_entity
                else:
                    for tentative_entity in tentative_entities_in_cluster:
                        identity_mapping[tentative_entity] = tentative_entity

        for entity, target in identity_mapping.items():
            if entity in decisions:
                decisions[entity].identity_target = target

        suppress_sameas_origins = {
            entity for entity, decision in decisions.items() if decision.suppress_sameas
        }
        suppress_fact_subject_sources = {
            entity
            for entity, decision in decisions.items()
            if decision.suppress_fact_subject_assertions
        }

        # Step 5: URI assignment from canonical identity + namespace policy
        final_mapping = self.uri_builder.create_entity_uri_mapping(
            identity_mapping=identity_mapping,
            representations=representations,
            entity_doc_iris=entity_doc_iris,
            entity_is_ontology={
                entity: (
                    decisions.get(entity) is not None
                    and decisions[entity].classification != EntityClassification.FACT
                )
                for entity in representations
            },
        )
        for entity, final_uri in final_mapping.items():
            if entity in decisions:
                decisions[entity].final_uri = final_uri
        known_ontology_entities_all = {
            entity
            for entity, decision in decisions.items()
            if decision.classification == EntityClassification.KNOWN_ONTOLOGY
        }
        assert all(
            identity_mapping.get(entity, entity) == entity
            for entity in known_ontology_entities_all
        ), "Known ontology entities must remain identity-mapped"
        assert not (known_ontology_entities_all & suppress_sameas_origins), (
            "Known ontology entities cannot be suppress_sameas origins"
        )
        assert not (known_ontology_entities_all & suppress_fact_subject_sources), (
            "Known ontology entities cannot be suppress_fact_subject origins"
        )
        assert all(entity in decisions for entity in source_entities), (
            "Every source entity must have a decision record"
        )
        final_mapping = {
            entity: mapped
            for entity, mapped in final_mapping.items()
            if entity in source_entities
        }

        # Step 7: Rewrite and merge with provenance
        active_units = [u for u in units if u.graph is not None and len(u.graph) > 0]
        merged_graph = self.rewriter.merge_graphs_with_provenance(
            active_units,
            final_mapping,
            suppress_sameas_origins=suppress_sameas_origins,
            suppress_fact_subject_sources=suppress_fact_subject_sources,
        )

        merged_clusters = build_merged_clusters(final_mapping, identity_mapping)
        key_supported_clusters = sorted(
            {
                str(final_mapping[left])
                for pair in key_pairs
                for left, right in [tuple(pair)]
                if left in final_mapping
                and final_mapping.get(right) == final_mapping[left]
            }
        )

        logger.info("Aggregation with metadata complete")
        return AggregationResult(
            graph=merged_graph,
            decisions=decisions,
            merged_clusters=merged_clusters,
            rejected_merge_count=len(rejected_merges),
            key_supported_clusters=key_supported_clusters,
        )

    def postprocess_facts_units(
        self,
        units: list[ContentUnit],
        ontology_graph: RDFGraph,
        *,
        doc_iri: URIRef | None = None,
        document_metadata: dict[str, Any] | None = None,
        doc_namespace: str | None = None,
        merge_vetoes: set[frozenset[URIRef]] | None = None,
    ) -> AggregationResult:
        """Sanitize facts units, then run aggregation/normalization.

        This method is intentionally safe for both single-unit and multi-unit
        inputs so unit-pipeline and graph-pipeline paths share the same
        post-processing behavior.

        When ``doc_iri`` and non-empty ``document_metadata`` are provided,
        caller-asserted document identity triples are attached to the merged
        facts graph. Business-oriented keys mint typed entities under
        ``doc_namespace`` (defaults to the document facts namespace).

        Args:
            units: Facts content units to aggregate.
            ontology_graph: Merged ontology context for classification/guards.
            doc_iri: Document IRI for metadata provenance attachment.
            document_metadata: Caller-asserted document identity metadata.
            doc_namespace: Namespace for metadata-minted entities.
            merge_vetoes: Entity pairs that must never identity-merge
                (validation-gate un-merge lever).

        Returns:
            :class:`AggregationResult`; its ``graph`` carries the merged facts
            plus any document-metadata provenance.
        """
        for unit in units:
            unit.sanitize()
        result = self.aggregate_graphs(
            units=units, ontology_graph=ontology_graph, merge_vetoes=merge_vetoes
        )
        if doc_iri is not None and document_metadata:
            apply_document_metadata_provenance(
                doc_iri,
                document_metadata,
                result.graph,
                entity_namespace=doc_namespace,
            )
        # Cross-unit prefix conflicts surface only on the merged graph (e.g.
        # aliases of one namespace arriving from different units), so sanitize
        # once more after aggregation.
        result.graph.sanitize_prefixes_namespaces()
        return result

__init__(config=None, *, add_sameas_links=True, base_iri=DEFAULT_IRI, candidate_similarity_threshold=None)

Initialise the embedding-based aggregator.

Every tunable lives on :class:AggregationConfig, so settings.py stays the single source of their defaults rather than restating them in this signature and again at the call site.

Parameters:

Name Type Description Default
config AggregationConfig | None

Aggregation tunables. Defaults to :class:AggregationConfig, i.e. the environment-resolved settings.

None
add_sameas_links bool

Whether to add owl:sameAs for merged entities. Not config-driven: callers choose it per use, and the entity aligner wants different behaviour from the pipeline.

True
base_iri str

Base IRI for fact entity URIs. Entities under this namespace are facts; everything else is treated as an ontology entity and left unchanged.

DEFAULT_IRI
candidate_similarity_threshold float | None

Overrides the configured permissive candidate threshold. The entity aligner pins it to its own similarity threshold rather than the pipeline's.

None
Source code in ontocast/tool/agg/aggregate.py
def __init__(
    self,
    config: AggregationConfig | None = None,
    *,
    add_sameas_links: bool = True,
    base_iri: str = DEFAULT_IRI,
    candidate_similarity_threshold: float | None = None,
):
    """Initialise the embedding-based aggregator.

    Every tunable lives on :class:`AggregationConfig`, so ``settings.py``
    stays the single source of their defaults rather than restating them in
    this signature and again at the call site.

    Args:
        config: Aggregation tunables. Defaults to :class:`AggregationConfig`,
            i.e. the environment-resolved settings.
        add_sameas_links: Whether to add ``owl:sameAs`` for merged entities.
            Not config-driven: callers choose it per use, and the entity
            aligner wants different behaviour from the pipeline.
        base_iri: Base IRI for fact entity URIs. Entities under this
            namespace are facts; everything else is treated as an ontology
            entity and left unchanged.
        candidate_similarity_threshold: Overrides the configured permissive
            candidate threshold. The entity aligner pins it to its own
            similarity threshold rather than the pipeline's.
    """
    cfg = config or AggregationConfig()

    self.base_iri = base_iri
    self.candidate_similarity_threshold = (
        cfg.candidate_similarity_threshold
        if candidate_similarity_threshold is None
        else candidate_similarity_threshold
    )
    self.lexical_label_jaccard = cfg.lexical_label_jaccard
    self.lexical_sequence_ratio = cfg.lexical_sequence_ratio
    self.lexical_token_jaccard = cfg.lexical_token_jaccard
    self.functional_min_empirical_support = cfg.functional_min_empirical_support
    self.sibling_guard_scope = str(cfg.sibling_guard_scope)
    self.literal_conflict_guard = cfg.literal_conflict_guard
    self.initials_distinct_guard = cfg.initials_distinct_guard
    self.natural_key_merge = cfg.natural_key_merge
    self.type_guard_untyped = str(cfg.type_guard_untyped)

    # Pipeline components (EntityClusterer imports sklearn/ST lazily).
    # The clusterer runs at the permissive candidate threshold: candidates
    # are validated symbolically afterwards, so there is exactly one
    # clustering threshold on this path.
    from .clustering import EntityClusterer

    self.normalizer = EntityNormalizer(facts_iri=self.base_iri)
    self.clusterer = EntityClusterer(
        embedding_model=cfg.embedding_model,
        similarity_threshold=self.candidate_similarity_threshold,
    )
    self.selector = ClusterRepresentativeSelector()
    self.uri_builder = URIBuilder(base_iri=self.base_iri)
    self.rewriter = GraphRewriter(
        add_sameas_links=add_sameas_links,
        blocked_sameas_namespaces=(self.base_iri,),
    )

aggregate_graphs(units, ontology_graph, merge_vetoes=None)

Aggregate multiple content unit graphs with embedding-based disambiguation.

Parameters:

Name Type Description Default
units list[ContentUnit]

List of ContentUnits to aggregate.

required
ontology_graph RDFGraph

Selected ontology graph used to distinguish known ontology entities from tentative ontology-like aliases.

required
merge_vetoes set[frozenset[URIRef]] | None

Extra entity pairs that must never identity-merge — the targeted un-merge lever used by the post-aggregation validation gate. Unioned into the direct-relation veto set.

None

Returns:

Type Description
AggregationResult
AggregationResult

bookkeeping (decisions, merged clusters, rejection count).

Source code in ontocast/tool/agg/aggregate.py
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
def aggregate_graphs(
    self,
    units: list[ContentUnit],
    ontology_graph: RDFGraph,
    merge_vetoes: set[frozenset[URIRef]] | None = None,
) -> AggregationResult:
    """Aggregate multiple content unit graphs with embedding-based disambiguation.

    Args:
        units: List of ContentUnits to aggregate.
        ontology_graph: Selected ontology graph used to distinguish
            known ontology entities from tentative ontology-like aliases.
        merge_vetoes: Extra entity pairs that must never identity-merge —
            the targeted un-merge lever used by the post-aggregation
            validation gate. Unioned into the direct-relation veto set.

    Returns:
        :class:`AggregationResult` with the merged graph and merge
        bookkeeping (decisions, merged clusters, rejection count).
    """
    logger.info(f"Starting aggregation with metadata for {len(units)} units")
    if ontology_graph is None:
        raise ValueError("ontology_graph must not be None for facts aggregation")

    if not units:
        return AggregationResult(graph=RDFGraph())

    # Steps 1-3: Collect, normalise, candidate clustering
    known_ontology_entities = self._build_known_ontology_entities(ontology_graph)
    (
        entities,
        source_entities,
        entity_graphs,
        entity_doc_iris,
        entity_classification,
        direct_relation_pairs,
        object_groups,
    ) = self._collect_all_entities(units, known_ontology_entities)
    if merge_vetoes:
        direct_relation_pairs = direct_relation_pairs | merge_vetoes
    schema_functional_predicates = harvest_max_one_predicates(ontology_graph)
    guard_context = MergeGuardContext(
        sibling_pairs=build_sibling_pairs(
            object_groups, scope=self.sibling_guard_scope
        ),
        functional_predicates=schema_functional_predicates
        | empirically_functional_predicates(
            object_groups,
            min_support=self.functional_min_empirical_support,
        ),
    )
    representations = self.normalizer.create_representations_batch(
        entities, entity_graphs
    )
    decisions: dict[URIRef, EntityDecision] = {
        entity: EntityDecision(
            classification=classification,
            identity_target=entity,
        )
        for entity, classification in entity_classification.items()
    }
    tentative_entities = [
        entity
        for entity, decision in decisions.items()
        if decision.classification == EntityClassification.TENTATIVE_ONTOLOGY
    ]
    anchor_candidates = self._select_ontology_anchor_candidates(
        tentative_entities=tentative_entities,
        tentative_representations=representations,
        tentative_doc_iris=entity_doc_iris,
        ontology_graph=ontology_graph,
        known_ontology_entities=known_ontology_entities,
    )
    if anchor_candidates:
        for ontology_entity, anchor_doc_iri in anchor_candidates.items():
            if ontology_entity in entity_graphs:
                continue
            entities.append(ontology_entity)
            entity_graphs[ontology_entity] = ontology_graph
            entity_doc_iris[ontology_entity] = anchor_doc_iri
            entity_classification[ontology_entity] = (
                EntityClassification.KNOWN_ONTOLOGY
            )
            decisions[ontology_entity] = EntityDecision(
                classification=EntityClassification.KNOWN_ONTOLOGY,
                identity_target=ontology_entity,
            )
            representations[ontology_entity] = (
                self.normalizer.create_representation(
                    ontology_entity, ontology_graph
                )
            )
    entity_is_known_ontology = {
        entity: decision.classification == EntityClassification.KNOWN_ONTOLOGY
        for entity, decision in decisions.items()
    }
    if logger.isEnabledFor(logging.INFO):
        known_count = sum(
            1 for is_known in entity_is_known_ontology.values() if is_known
        )
        fact_count = sum(
            1
            for decision in decisions.values()
            if decision.classification == EntityClassification.FACT
        )
        logger.info(
            "Aggregation entity classification stats: fact=%d known_ontology=%d "
            "tentative_ontology=%d",
            fact_count,
            known_count,
            len(tentative_entities),
        )

    candidate_clusters, embeddings = self._cluster_entities_by_role(representations)
    key_pairs: set[frozenset[URIRef]] = set()
    if self.natural_key_merge:
        key_pairs = self._collect_natural_key_pairs(
            representations, schema_functional_predicates
        )
        if key_pairs:
            logger.info(
                "Natural-key evidence proposed %d candidate pair(s)",
                len(key_pairs),
            )
            candidate_clusters = self._merge_candidate_clusters_by_key_pairs(
                candidate_clusters, key_pairs
            )
    clusters, rejected_merges = self._build_identity_clusters(
        candidate_clusters=candidate_clusters,
        representations=representations,
        embeddings=embeddings,
        direct_relation_pairs=direct_relation_pairs,
        guard_context=guard_context,
        key_pairs=key_pairs or None,
    )
    if rejected_merges:
        logger.info(
            "Rejected %d candidate merges after symbolic validation",
            len(rejected_merges),
        )
        for left, right, score, failed_checks in rejected_merges:
            logger.debug(
                "Rejected candidate merge: %s <-> %s (score=%s, failed=%s)",
                left,
                right,
                f"{score:.3f}" if score is not None else "n/a",
                ",".join(failed_checks) if failed_checks else "unknown",
            )

    # Step 4: Canonical identity mapping (no URI policy yet)
    identity_mapping = self.selector.create_mapping(
        clusters,
        representations,
        entity_is_known_ontology=entity_is_known_ontology,
    )

    # Keep known ontology entities stable. Tentative ontology-like entities are:
    # - mapped to known ontology representatives when present in a mixed cluster
    # - preserved as-is when only tentative entities are present
    suppress_sameas_origins: set[URIRef] = set()
    suppress_fact_subject_sources: set[URIRef] = set()
    for cluster in clusters:
        known_ontology_entities_in_cluster = [
            entity
            for entity in cluster
            if decisions.get(entity) is not None
            and decisions[entity].classification
            == EntityClassification.KNOWN_ONTOLOGY
        ]
        tentative_entities_in_cluster = [
            entity
            for entity in cluster
            if decisions.get(entity) is not None
            and decisions[entity].classification
            == EntityClassification.TENTATIVE_ONTOLOGY
        ]
        fact_entities_in_cluster = [
            entity
            for entity in cluster
            if decisions.get(entity) is not None
            and decisions[entity].classification == EntityClassification.FACT
        ]

        for entity in known_ontology_entities_in_cluster:
            identity_mapping[entity] = entity

        if known_ontology_entities_in_cluster:
            canonical_known_ontology = self.selector.select_representative(
                known_ontology_entities_in_cluster,
                representations,
                entity_is_known_ontology=entity_is_known_ontology,
            )
            for tentative_entity in tentative_entities_in_cluster:
                if self._can_merge_as_identity(
                    tentative_entity,
                    canonical_known_ontology,
                    representations,
                    direct_relation_pairs=direct_relation_pairs,
                    guard_context=guard_context,
                ):
                    identity_mapping[tentative_entity] = canonical_known_ontology
                    decisions[tentative_entity].suppress_sameas = True
                else:
                    identity_mapping[tentative_entity] = tentative_entity
            for fact_entity in fact_entities_in_cluster:
                if self._can_merge_as_identity(
                    fact_entity,
                    canonical_known_ontology,
                    representations,
                    direct_relation_pairs=direct_relation_pairs,
                    guard_context=guard_context,
                ):
                    identity_mapping[fact_entity] = canonical_known_ontology
                    decisions[fact_entity].suppress_sameas = True
                    decisions[fact_entity].suppress_fact_subject_assertions = True
                else:
                    identity_mapping[fact_entity] = fact_entity

        elif tentative_entities_in_cluster:
            # In mixed FACT + TENTATIVE clusters with no known ontology
            # entity, prefer the FACT side when symbolic identity checks
            # agree (e.g. hallucinated ontology prefix on an instance).
            if fact_entities_in_cluster:
                canonical_fact = self.selector.select_representative(
                    fact_entities_in_cluster,
                    representations,
                    entity_is_known_ontology=entity_is_known_ontology,
                )
                for fact_entity in fact_entities_in_cluster:
                    identity_mapping[fact_entity] = canonical_fact
                for tentative_entity in tentative_entities_in_cluster:
                    if self._can_merge_as_identity(
                        tentative_entity,
                        canonical_fact,
                        representations,
                        direct_relation_pairs=direct_relation_pairs,
                        guard_context=guard_context,
                    ):
                        identity_mapping[tentative_entity] = canonical_fact
                        decisions[tentative_entity].suppress_sameas = True
                    else:
                        identity_mapping[tentative_entity] = tentative_entity
            else:
                for tentative_entity in tentative_entities_in_cluster:
                    identity_mapping[tentative_entity] = tentative_entity

    for entity, target in identity_mapping.items():
        if entity in decisions:
            decisions[entity].identity_target = target

    suppress_sameas_origins = {
        entity for entity, decision in decisions.items() if decision.suppress_sameas
    }
    suppress_fact_subject_sources = {
        entity
        for entity, decision in decisions.items()
        if decision.suppress_fact_subject_assertions
    }

    # Step 5: URI assignment from canonical identity + namespace policy
    final_mapping = self.uri_builder.create_entity_uri_mapping(
        identity_mapping=identity_mapping,
        representations=representations,
        entity_doc_iris=entity_doc_iris,
        entity_is_ontology={
            entity: (
                decisions.get(entity) is not None
                and decisions[entity].classification != EntityClassification.FACT
            )
            for entity in representations
        },
    )
    for entity, final_uri in final_mapping.items():
        if entity in decisions:
            decisions[entity].final_uri = final_uri
    known_ontology_entities_all = {
        entity
        for entity, decision in decisions.items()
        if decision.classification == EntityClassification.KNOWN_ONTOLOGY
    }
    assert all(
        identity_mapping.get(entity, entity) == entity
        for entity in known_ontology_entities_all
    ), "Known ontology entities must remain identity-mapped"
    assert not (known_ontology_entities_all & suppress_sameas_origins), (
        "Known ontology entities cannot be suppress_sameas origins"
    )
    assert not (known_ontology_entities_all & suppress_fact_subject_sources), (
        "Known ontology entities cannot be suppress_fact_subject origins"
    )
    assert all(entity in decisions for entity in source_entities), (
        "Every source entity must have a decision record"
    )
    final_mapping = {
        entity: mapped
        for entity, mapped in final_mapping.items()
        if entity in source_entities
    }

    # Step 7: Rewrite and merge with provenance
    active_units = [u for u in units if u.graph is not None and len(u.graph) > 0]
    merged_graph = self.rewriter.merge_graphs_with_provenance(
        active_units,
        final_mapping,
        suppress_sameas_origins=suppress_sameas_origins,
        suppress_fact_subject_sources=suppress_fact_subject_sources,
    )

    merged_clusters = build_merged_clusters(final_mapping, identity_mapping)
    key_supported_clusters = sorted(
        {
            str(final_mapping[left])
            for pair in key_pairs
            for left, right in [tuple(pair)]
            if left in final_mapping
            and final_mapping.get(right) == final_mapping[left]
        }
    )

    logger.info("Aggregation with metadata complete")
    return AggregationResult(
        graph=merged_graph,
        decisions=decisions,
        merged_clusters=merged_clusters,
        rejected_merge_count=len(rejected_merges),
        key_supported_clusters=key_supported_clusters,
    )

postprocess_facts_units(units, ontology_graph, *, doc_iri=None, document_metadata=None, doc_namespace=None, merge_vetoes=None)

Sanitize facts units, then run aggregation/normalization.

This method is intentionally safe for both single-unit and multi-unit inputs so unit-pipeline and graph-pipeline paths share the same post-processing behavior.

When doc_iri and non-empty document_metadata are provided, caller-asserted document identity triples are attached to the merged facts graph. Business-oriented keys mint typed entities under doc_namespace (defaults to the document facts namespace).

Parameters:

Name Type Description Default
units list[ContentUnit]

Facts content units to aggregate.

required
ontology_graph RDFGraph

Merged ontology context for classification/guards.

required
doc_iri URIRef | None

Document IRI for metadata provenance attachment.

None
document_metadata dict[str, Any] | None

Caller-asserted document identity metadata.

None
doc_namespace str | None

Namespace for metadata-minted entities.

None
merge_vetoes set[frozenset[URIRef]] | None

Entity pairs that must never identity-merge (validation-gate un-merge lever).

None

Returns:

Type Description
AggregationResult
AggregationResult

plus any document-metadata provenance.

Source code in ontocast/tool/agg/aggregate.py
def postprocess_facts_units(
    self,
    units: list[ContentUnit],
    ontology_graph: RDFGraph,
    *,
    doc_iri: URIRef | None = None,
    document_metadata: dict[str, Any] | None = None,
    doc_namespace: str | None = None,
    merge_vetoes: set[frozenset[URIRef]] | None = None,
) -> AggregationResult:
    """Sanitize facts units, then run aggregation/normalization.

    This method is intentionally safe for both single-unit and multi-unit
    inputs so unit-pipeline and graph-pipeline paths share the same
    post-processing behavior.

    When ``doc_iri`` and non-empty ``document_metadata`` are provided,
    caller-asserted document identity triples are attached to the merged
    facts graph. Business-oriented keys mint typed entities under
    ``doc_namespace`` (defaults to the document facts namespace).

    Args:
        units: Facts content units to aggregate.
        ontology_graph: Merged ontology context for classification/guards.
        doc_iri: Document IRI for metadata provenance attachment.
        document_metadata: Caller-asserted document identity metadata.
        doc_namespace: Namespace for metadata-minted entities.
        merge_vetoes: Entity pairs that must never identity-merge
            (validation-gate un-merge lever).

    Returns:
        :class:`AggregationResult`; its ``graph`` carries the merged facts
        plus any document-metadata provenance.
    """
    for unit in units:
        unit.sanitize()
    result = self.aggregate_graphs(
        units=units, ontology_graph=ontology_graph, merge_vetoes=merge_vetoes
    )
    if doc_iri is not None and document_metadata:
        apply_document_metadata_provenance(
            doc_iri,
            document_metadata,
            result.graph,
            entity_namespace=doc_namespace,
        )
    # Cross-unit prefix conflicts surface only on the merged graph (e.g.
    # aliases of one namespace arriving from different units), so sanitize
    # once more after aggregation.
    result.graph.sanitize_prefixes_namespaces()
    return result

EntityClassification

Bases: StrEnum

Classification of entities during aggregation.

Source code in ontocast/tool/agg/aggregate.py
class EntityClassification(StrEnum):
    """Classification of entities during aggregation."""

    FACT = "fact"
    KNOWN_ONTOLOGY = "known_ontology"
    TENTATIVE_ONTOLOGY = "tentative_ontology"

EntityDecision

Bases: BaseModel

Decision record for one entity across aggregation stages.

Source code in ontocast/tool/agg/aggregate.py
class EntityDecision(BaseModel):
    """Decision record for one entity across aggregation stages."""

    model_config = ConfigDict(arbitrary_types_allowed=True)

    classification: EntityClassification
    identity_target: URIRef
    final_uri: URIRef | None = None
    suppress_fact_subject_assertions: bool = False
    suppress_sameas: bool = False

apply_document_metadata_provenance(doc_iri, metadata, graph, *, entity_namespace=None)

Emit caller-asserted document identity triples on doc_iri.

Document-level identity is provenance-adjacent but intentionally kept on the facts graph (survives chunk-level strip_provenance) so query/RAG clients can filter by DOI, business id, filename, etc.

Business-oriented keys (author, project, and any non-reserved key) mint typed RDF entities under entity_namespace (defaults to the document facts namespace) so they are SPARQL-discoverable via rdf:type.

Registry keys are matched via :func:_resolve_metadata_key (case / separator / optional id affix for identifier and source keys). Keys with an identifier-shaped affix (id, ref, no, key, …) that do not resolve to a registry entry become structured dcterms:identifier blank nodes, or attach to a companion entity-link stem when one was minted in the same payload (e.g. project + project_id).

Source code in ontocast/tool/agg/aggregate.py
def apply_document_metadata_provenance(
    doc_iri: URIRef,
    metadata: dict[str, Any],
    graph: RDFGraph,
    *,
    entity_namespace: str | None = None,
) -> None:
    """Emit caller-asserted document identity triples on ``doc_iri``.

    Document-level identity is provenance-adjacent but intentionally kept on the
    facts graph (survives chunk-level ``strip_provenance``) so query/RAG clients
    can filter by DOI, business id, filename, etc.

    Business-oriented keys (``author``, ``project``, and any non-reserved key)
    mint typed RDF entities under ``entity_namespace`` (defaults to the document
    facts namespace) so they are SPARQL-discoverable via ``rdf:type``.

    Registry keys are matched via :func:`_resolve_metadata_key` (case /
    separator / optional ``id`` affix for identifier and source keys). Keys with
    an identifier-shaped affix (``id``, ``ref``, ``no``, ``key``, …) that do not
    resolve to a registry entry become structured ``dcterms:identifier`` blank
    nodes, or attach to a companion entity-link stem when one was minted in the
    same payload (e.g. ``project`` + ``project_id``).
    """
    if not metadata:
        return

    graph.bind("prov", str(PROV))
    graph.bind("foaf", str(FOAF))
    graph.bind("dcterms", str(DCTERMS))
    graph.bind("owl", str(OWL))
    graph.bind("rdfs", str(RDFS))
    graph.bind("schema", str(SCHEMA))

    graph.add((doc_iri, RDF.type, PROV.Entity))
    graph.add((doc_iri, RDF.type, FOAF.Document))

    ns = entity_namespace or normalize_namespace_iri(str(doc_iri), context="facts")
    entity_iri_by_stem: dict[str, URIRef] = {}
    deferred_affix: list[tuple[str, object, tuple[str, str]]] = []

    for raw_key, value in metadata.items():
        if value is None or value == "":
            continue
        key = _resolve_metadata_key(raw_key)
        if key == "stable_source_iri":
            graph.add((doc_iri, OWL.sameAs, _as_iri_or_literal(value)))
            continue
        if key in _DOC_METADATA_SOURCE_KEYS:
            graph.add((doc_iri, DCTERMS.source, _as_iri_or_literal(value)))
            continue
        if key in _DOC_METADATA_IDENTIFIER_KEYS:
            graph.add((doc_iri, DCTERMS.identifier, Literal(str(value))))
            continue
        if key == "identifiers":
            items = value if isinstance(value, list) else [value]
            for item in items:
                if not isinstance(item, dict):
                    continue
                scheme = item.get("scheme") or item.get("type")
                val = item.get("value")
                if scheme and val is not None and val != "":
                    _add_structured_identifier(
                        graph, doc_iri, scheme=str(scheme), value=val
                    )
            continue
        if key in _DOC_METADATA_FIRST_CLASS:
            predicate = _DOC_METADATA_FIRST_CLASS[key]
            if isinstance(value, list):
                for item in value:
                    if item is not None and item != "":
                        graph.add((doc_iri, predicate, Literal(str(item))))
            else:
                graph.add((doc_iri, predicate, Literal(str(value))))
            continue

        if key in _DOC_METADATA_ENTITY_LINKS:
            link, default_type = _DOC_METADATA_ENTITY_LINKS[key]
            minted = _emit_metadata_entities(
                graph,
                doc_iri,
                ns,
                link=link,
                default_type=default_type,
                value=value,
            )
            # Companion ``*_id`` attachment only for a singular non-list entity.
            if not isinstance(value, list) and len(minted) == 1:
                entity_iri_by_stem[key] = minted[0]
            continue

        split = _split_identifier_affix(key)
        if split is not None:
            deferred_affix.append((key, value, split))
            continue

        _emit_metadata_entities(
            graph,
            doc_iri,
            ns,
            link=_DEFAULT_ENTITY_LINK_PREDICATE,
            default_type=_DEFAULT_ENTITY_TYPE,
            value=value,
        )

    for _key, value, (stem, _affix) in deferred_affix:
        entity_iri = entity_iri_by_stem.get(stem)
        if entity_iri is not None:
            if isinstance(value, list):
                for item in value:
                    if item is not None and item != "":
                        graph.add((entity_iri, DCTERMS.identifier, Literal(str(item))))
            else:
                graph.add((entity_iri, DCTERMS.identifier, Literal(str(value))))
            continue
        if isinstance(value, list):
            for item in value:
                if item is not None and item != "":
                    _add_structured_identifier(graph, doc_iri, scheme=stem, value=item)
        else:
            _add_structured_identifier(graph, doc_iri, scheme=stem, value=value)

build_merged_clusters(final_mapping, identity_mapping)

Group merge clusters by canonical identity, keyed by every final URI.

One canonical spanning several source documents mints one final URI per doc base; keying by final URI alone would split the same merge decision into per-document clusters, and a validation veto on one flagged URI would leave the sibling document's half of the cluster merged. Every final URI rendering a canonical therefore keys the full cross-document member set.

Source code in ontocast/tool/agg/aggregate.py
def build_merged_clusters(
    final_mapping: dict[URIRef, URIRef],
    identity_mapping: dict[URIRef, URIRef],
) -> dict[str, list[str]]:
    """Group merge clusters by canonical identity, keyed by every final URI.

    One canonical spanning several source documents mints one final URI per
    doc base; keying by final URI alone would split the same merge decision
    into per-document clusters, and a validation veto on one flagged URI would
    leave the sibling document's half of the cluster merged. Every final URI
    rendering a canonical therefore keys the *full* cross-document member set.
    """
    members_by_canonical: dict[str, set[str]] = {}
    final_uris_by_canonical: dict[str, set[str]] = {}
    for entity, final_uri in final_mapping.items():
        canonical = str(identity_mapping.get(entity, entity))
        members_by_canonical.setdefault(canonical, set()).add(str(entity))
        final_uris_by_canonical.setdefault(canonical, set()).add(str(final_uri))
    merged_clusters: dict[str, list[str]] = {}
    for canonical, final_uris in final_uris_by_canonical.items():
        members = members_by_canonical[canonical]
        if len(members) < 2:
            continue
        for final_uri in final_uris:
            merged_clusters[final_uri] = sorted(members)
    return merged_clusters