Skip to content

ontocast.stategraph.node_factories

Attributes

T = TypeVar('T') module-attribute

logger = logging.getLogger(__name__) module-attribute

Classes

Functions:

clean_ontology_delta(graphs, *, external, current_domain, catalog_index, ontology_iris, home_namespace)

Apply the deterministic clean-up rules to each graph; the counts removed.

catalog_index names the terms every catalog head declares, and which are classes and properties; ontology_iris the heads' (and the home's) IRIs: statements about them are not undeclared. Without a home namespace, terms are not checked for where they were minted.

Source code in ontocast/stategraph/node_factories.py
def clean_ontology_delta(
    graphs: Sequence[RDFGraph],
    *,
    external: Sequence[str],
    current_domain: str,
    catalog_index: CatalogSurfaceIndex,
    ontology_iris: Collection[str],
    home_namespace: str | None,
) -> dict[str, int]:
    """Apply the deterministic clean-up rules to each graph; the counts removed.

    ``catalog_index`` names the terms every catalog head declares, and which
    are classes and properties; ``ontology_iris`` the heads' (and the home's) IRIs: statements about them
    are not undeclared. Without a home namespace, terms are not checked for
    where they were minted.
    """
    counts = {
        "external_subject_refused": 0,
        "example_namespace_dropped": 0,
        "minted_outside_home_dropped": 0,
        "non_term_subjects_dropped": 0,
        "datatype_ranges_normalized": 0,
        "owned_sides_listed": 0,
        "vacuous_upper_terms_dropped": 0,
        "role_crossing_parents_dropped": 0,
        "undeclared_owned_references_rewritten": 0,
        "undeclared_owned_references_dropped": 0,
    }
    catalog_terms = catalog_index.terms
    declared = {*catalog_terms, *ontology_iris}

    def owned(iri: str) -> bool:
        # The home's terms, and terms this delta mints: never a catalog's.
        if home_namespace and iri.startswith(home_namespace):
            return True
        return iri not in catalog_terms and well_known_vocabulary(iri) is None

    for graph in graphs:
        counts["external_subject_refused"] += drop_external_subjects(graph, external)
        counts["example_namespace_dropped"] += drop_example_namespace_triples(
            graph, current_domain
        )
        if home_namespace:
            counts["minted_outside_home_dropped"] += drop_terms_minted_outside_home(
                graph,
                home_namespace=home_namespace,
                catalog_terms=catalog_terms,
                current_domain=current_domain,
            )
        counts["non_term_subjects_dropped"] += drop_non_term_subjects(
            graph, declared=declared, facts_namespace=DEFAULT_IRI
        )
        counts["datatype_ranges_normalized"] += normalize_datatype_ranges(graph)
        counts["owned_sides_listed"] += list_owned_sides(graph, owned)
        counts["vacuous_upper_terms_dropped"] += drop_vacuous_upper_terms(graph)
        counts["role_crossing_parents_dropped"] += drop_role_crossing_parents(
            graph,
            catalog_classes=catalog_index.classes,
            catalog_properties=catalog_index.properties,
        )
    (
        counts["undeclared_owned_references_rewritten"],
        counts["undeclared_owned_references_dropped"],
    ) = repair_undeclared_owned_references(
        graphs, known=declared, current_domain=current_domain
    )
    return counts

external_namespaces(tools, current_domain)

Namespace stems of the catalog ontologies outside current_domain.

Each external ontology contributes its IRI and its namespace, without a trailing / or #; prefixes merely bound in its graph do not count.

Source code in ontocast/stategraph/node_factories.py
def external_namespaces(tools: ToolBox, current_domain: str) -> list[str]:
    """Namespace stems of the catalog ontologies outside ``current_domain``.

    Each external ontology contributes its IRI and its namespace, without a
    trailing ``/`` or ``#``; prefixes merely bound in its graph do not count.
    """
    stems: set[str] = set()
    for head in tools.ontology_manager.ontologies:
        if head.is_null() or not head.iri:
            continue
        if is_owned_ontology(head.iri, current_domain):
            continue
        stems.add(head.iri.rstrip("/#"))
        stems.add(normalize_namespace_iri(head.iri, context="ontology").rstrip("/#"))
        if head.namespace:
            stems.add(head.namespace.rstrip("/#"))
    return sorted(stems)

home_base_overrides(state, tools, fresh_ontologies)

A base to apply the home ontology's delta onto when it is not stored yet.

Under vector retrieval a unit renders an update against catalog patches even when the document's home ontology is new; without a base its terms would have no ontology to land in. A fresh render of the home is that base; otherwise an empty root under the home identity is.

Source code in ontocast/stategraph/node_factories.py
def home_base_overrides(
    state: AgentState, tools: ToolBox, fresh_ontologies: Sequence[Ontology]
) -> dict[str, Ontology]:
    """A base to apply the home ontology's delta onto when it is not stored yet.

    Under vector retrieval a unit renders an update against catalog patches
    even when the document's home ontology is new; without a base its terms
    would have no ontology to land in. A fresh render of the home is that
    base; otherwise an empty root under the home identity is.
    """
    home = state.home_ontology
    if home is None:
        return {}
    for fresh in fresh_ontologies:
        if fresh.iri == home.iri:
            return {home.iri: fresh}
    head = tools.ontology_manager.get_head_by_iri(home.iri)
    if head is not None and not head.is_null():
        return {}
    return {home.iri: mint_ontology(home, RDFGraph())}

make_consistency_critic_node(tools)

Source code in ontocast/stategraph/node_factories.py
def make_consistency_critic_node(tools: ToolBox):
    def consistency_critic(state: AgentState) -> AgentState:
        """Global consistency critic over candidate ontology atoms using vector re-query."""
        doc_onto = document_ontology_access(state)
        artifacts = [
            ontology
            for ontology in doc_onto.reduced_artifacts()
            if not ontology.is_null() and len(ontology.graph) > 0
        ]
        if (
            state.ontology_context_mode
            != OntologyContextMode.SELECTED_VECTOR_SEARCH_ONTOLOGY
            or tools.vector_store is None
            or not artifacts
        ):
            state.status = Status.SUCCESS
            return state

        merged_graph = RDFGraph()
        for ontology in artifacts:
            merged_graph += ontology.graph
        query_terms = _extract_consistency_queries(merged_graph)
        if not query_terms:
            state.status = Status.SUCCESS
            return state

        allowed_sources = set(all_unit_patch_source_iris(state))
        for ontology in artifacts:
            if ontology.iri:
                allowed_sources.add(ontology.iri)
        # ``search_patch_hits`` returns rank-fused scores, not raw similarities.
        threshold = (
            tools.config.tool_config.vector_store.consistency_critic_min_fused_score
        )
        conflicts: list[str] = []
        for query in query_terms:
            hits = tools.vector_store.search_patch_hits(query=query, top_k=3)
            for hit in hits:
                if (
                    hit.score >= threshold
                    and hit.atom.ontology_iri
                    and hit.atom.ontology_iri not in allowed_sources
                ):
                    conflicts.append(
                        f"Potential cross-ontology conflict for '{query}' with "
                        f"source {hit.atom.ontology_iri} (score={hit.score:.2f})."
                    )
            if len(conflicts) >= 5:
                break

        if conflicts:
            state.improvements_suggestions.extend(conflicts[:5])
            logger.warning(
                "Consistency critic detected %s potential cross-ontology conflicts",
                len(conflicts),
            )
        state.retrieval_metrics[RetrievalMetric.CONSISTENCY_CONFLICTS] = len(conflicts)
        state.status = Status.SUCCESS
        return state

    return consistency_critic

make_merge_facts_node(tools)

Source code in ontocast/stategraph/node_factories.py
def make_merge_facts_node(tools: ToolBox):
    def merge_facts(state: AgentState) -> AgentState:
        if not state.facts_units:
            state.aggregated_facts = RDFGraph()
            if state.status != Status.FAILED:
                state.status = Status.SUCCESS
            return state

        ontology_graph, document_metadata = _facts_aggregation_inputs(state, tools)
        result = tools.aggregator.postprocess_facts_units(
            units=state.facts_units,
            ontology_graph=ontology_graph,
            doc_iri=state.doc_iri,
            document_metadata=document_metadata,
            doc_namespace=state.doc_namespace,
        )
        _store_aggregation(state, result)
        aggregator = tools.aggregator
        if aggregator.llm_coreference and len(state.facts_units) > 1:
            state.coreference_candidates = coreference_candidates(
                unconfirmed_merges=result.unconfirmed_merges,
                lexical_near_misses=result.lexical_near_misses,
                units=state.facts_units,
                final_uri={
                    str(entity): str(decision.final_uri)
                    for entity, decision in result.decisions.items()
                    if decision.final_uri is not None
                },
                max_pairs=aggregator.llm_coreference_max_pairs,
            )
        if len(state.aggregated_facts) == 0:
            logger.warning(
                "Facts aggregation produced an empty graph from "
                f"{len(state.facts_units)} successful unit(s)."
            )
        state.status = Status.SUCCESS
        return state

    return merge_facts

make_normalize_ontology_node(tools)

Normalize is largely handled in the map stage via namespace apply.

Kept as a no-op success node when artifacts already carry catalog lineage, so the graph topology (map → normalize → …) stays stable.

Source code in ontocast/stategraph/node_factories.py
def make_normalize_ontology_node(tools: ToolBox):
    """Normalize is largely handled in the map stage via namespace apply.

    Kept as a no-op success node when artifacts already carry catalog lineage,
    so the graph topology (map → normalize → …) stays stable.
    """

    def normalize_ontology_updates(state: AgentState) -> AgentState:
        if (
            not state.ontology_units
            and not document_ontology_access(state).reduced_artifacts()
        ):
            state.ontology_provenance_artifact = RDFGraph()
            state.status = Status.SUCCESS
            return state

        # Artifacts from map already applied onto catalog bases. Ensure indexes.
        artifacts = document_ontology_access(state).reduced_artifacts()
        state.reduced_ontology_by_anchor = _index_ontologies_by_anchor(artifacts)
        state.ontology_provenance_artifact = (
            state.ontology_provenance_artifact or RDFGraph()
        )
        state.ontology_reduce_metrics["normalized_ontology_updates"] = len(artifacts)
        state.status = Status.SUCCESS
        return state

    return normalize_ontology_updates

make_render_facts_node(tools)

Source code in ontocast/stategraph/node_factories.py
 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
def make_render_facts_node(tools: ToolBox):
    async def render_facts(state: AgentState) -> AgentState:
        if not state.content_units:
            state.facts_units = []
            if state.status != Status.FAILED:
                state.status = Status.SUCCESS
            return state

        worker_limit = max(1, tools.config.server.parallel_workers)
        semaphore = asyncio.Semaphore(worker_limit)

        # Built once for the whole document, not once per unit. It reads only
        # reduced_ontology_artifacts, which the ontology stage froze upstream,
        # so every unit would otherwise pay an identical full rdflib merge plus
        # two graph copies -- synchronously, on the event loop, stalling every
        # other unit's in-flight provider call. None means no ontology stage ran
        # (facts-only mode); units then resolve their own context as before.
        merged_context = build_merged_document_ontology_context(
            UnitLoopContext.from_agent_state(state),
            tools.ontology_manager.get_head_by_iri,
        )
        if (
            merged_context is None
            and tools.config.server.ontology_context_scope
            == OntologyContextScope.DOCUMENT
        ):
            # No ontology stage ran, so there is nothing to merge -- but the
            # deployment has asked for one chapter per document rather than one
            # per unit. Resolve every unit's context up front and union it, so
            # the fan-out shares a prompt prefix instead of N distinct ones.
            merged_context = await build_unioned_document_ontology_context(
                UnitLoopContext.from_agent_state(state), tools, state.content_units
            )
        if merged_context is not None:
            merged_context = admit_facts_context_terms(
                merged_context,
                state.ontology_plan,
                tools,
                budget_tracker=state.budget_tracker,
            )
            # Hand the same graph to merge/validate downstream instead of
            # letting each rebuild it.
            state.facts_ontology_context = merged_context.snapshot.graph

        async def process_unit(
            unit_index: int,
        ) -> tuple[int, UnitFactsState, str, list[str], OntologyAssemblyMode]:
            async with _unit_slot(semaphore) as worker_wait:
                unit_budget = BudgetTracker()
                # No-op when the ontology fan-out already summarised this unit;
                # does the work when facts run without an ontology stage.
                await ensure_unit_summary(state, unit_index, tools, unit_budget)
                unit_context = UnitLoopContext.from_agent_state(state, unit_budget)
                conformance_chapter, contract_terms, selection_pending = (
                    tools.shapes_prompt_contract()
                )
                facts_state = UnitFactsState(
                    content_unit=state.content_units[unit_index],
                    ontology_snapshot=_empty_unit_snapshot(),
                    ontology_patch_sources=[],
                    facts_user_instruction=state.facts_user_instruction,
                    conformance_chapter=conformance_chapter,
                    shapes_contract_terms=contract_terms,
                    conformance_selection_pending=selection_pending,
                    budget_tracker=unit_budget,
                    max_visits_per_node=state.max_visits,
                    llm_graph_format=state.llm_graph_format,
                    llm_output_layout=tools.config.server.llm_output_layout,
                    ontology_context_max_triples=tools.config.server.ontology_context_max_triples,
                    ontology_chapter_format=tools.config.server.ontology_chapter_format,
                    ontology_text_caps=tools.config.server.ontology_text_caps,
                )
                loop_start = time.perf_counter()
                result = await facts_loop(
                    facts_state,
                    tools,
                    unit_context,
                    pre_resolved_context=merged_context,
                )
                result.budget_tracker.add_duration(
                    f"{WorkflowNode.RENDER_FACTS}{UNIT_SUM_SUFFIX}",
                    time.perf_counter() - loop_start,
                )
                result.budget_tracker.add_duration(
                    f"{WorkflowNode.RENDER_FACTS}/worker_wait", worker_wait
                )
                # Per-unit resolver metrics previously landed on a discarded
                # deep copy; fold them back (last writer wins on shared keys).
                state.retrieval_metrics.update(unit_context.retrieval_metrics)
                return (
                    unit_index,
                    result,
                    result.assembly_anchor_iri,
                    list(result.ontology_patch_sources),
                    result.assembly_mode_used,
                )

        raw_results, unit_errors = await _gather_units_with_warmup(
            WorkflowNode.RENDER_FACTS,
            state,
            process_unit,
            warmup=tools.config.server.fanout_warmup_units,
        )
        ordered_results = sorted(raw_results, key=lambda item: item[0])

        facts_units: list[ContentUnit] = []
        failed_without_output_count = unit_errors
        salvaged_failed_count = 0
        # Accumulated over *every* unit, whether or not it ran a repair render,
        # so the residual has "units" as its denominator.
        findings_residual = 0
        mandatory_residual = 0
        mandatory_by_kind: Counter[str] = Counter()
        subject_gaps_rendered = 0
        subject_gaps_left = 0
        critic_fixes_applied = 0
        critic_fixes_residual = 0
        critic_fixes_noop = 0
        critic_fixes_rolled_back = 0
        critic_fixes_junk_refused = 0
        critic_fixes_unresolved_prefix = 0
        critic_units_unreviewed = 0
        critic_units_skipped = 0
        unit_contexts: dict[int, tuple[str, list[str], OntologyAssemblyMode]] = {}
        for (
            unit_index,
            result,
            anchor_iri,
            patch_sources,
            assembly_mode,
        ) in ordered_results:
            state.budget_tracker.merge_from(result.budget_tracker)
            findings_residual += len(result.deterministic_findings)
            mandatory_residual += sum(
                1 for finding in result.deterministic_findings if finding.mandatory
            )
            mandatory_by_kind.update(
                str(finding.kind)
                for finding in result.deterministic_findings
                if finding.mandatory
            )
            subject_gaps_rendered += result.statements_without_subject_rendered
            subject_gaps_left += sum(
                1
                for finding in result.deterministic_findings
                if finding.kind == FactsUnitFindingKind.STATEMENT_WITHOUT_SUBJECT
            )
            critic_fixes_applied += result.critic_fixes_applied
            critic_fixes_residual += result.critic_fixes_residual
            critic_fixes_noop += result.critic_fixes_noop
            critic_fixes_rolled_back += result.critic_fixes_rolled_back
            critic_fixes_junk_refused += result.critic_fixes_junk_refused
            critic_fixes_unresolved_prefix += result.critic_fixes_unresolved_prefix
            # A unit whose critic call failed used to leave the loop SUCCESS,
            # indistinguishable from one the critic accepted; a unit the loop
            # never sent to the critic looked the same. Both are counted.
            critic_units_unreviewed += result.critic_outcome == "unavailable"
            critic_units_skipped += result.critic_outcome == "skipped"
            if result.attempt_log:
                state.facts_loop_telemetry[unit_index] = list(result.attempt_log)
            if result.applied_repairs:
                state.facts_repairs_applied[unit_index] = list(result.applied_repairs)
            unit_contexts[unit_index] = (anchor_iri, patch_sources, assembly_mode)
            has_output = len(result.content_unit.graph) > 0
            if not has_output:
                failed_without_output_count += 1
                state.unit_failures.append(
                    UnitFailure(
                        unit_index=unit_index,
                        phase="facts",
                        stage=(
                            result.failure_stage.value
                            if result.failure_stage is not None
                            else None
                        ),
                        reason=result.failure_reason,
                    )
                )
                continue

            facts_units.append(result.content_unit)
            if result.status != Status.SUCCESS:
                salvaged_failed_count += 1

        if failed_without_output_count:
            logger.warning(
                "Parallel facts map failed without usable output for "
                f"{failed_without_output_count}/{len(state.content_units)} unit(s)"
            )
        if salvaged_failed_count:
            logger.warning(
                "Parallel facts map salvaged output from non-converged loop(s): "
                f"{salvaged_failed_count}/{len(state.content_units)} unit(s)"
            )

        if merged_context is None and (
            tools.config.get_tool_config().facts_validation.context_from_units
        ):
            # No ontology stage ran, so build_merged_document_ontology_context
            # had nothing to merge. Without this both MERGE_FACTS and
            # VALIDATE_FACTS run against an empty ontology graph although every
            # unit rendered against a real one.
            unit_ontology_context = _union_unit_ontology_context(ordered_results)
            if len(unit_ontology_context) > 0:
                state.facts_ontology_context = unit_ontology_context
                state.retrieval_metrics[RetrievalMetric.ONTOLOGY_SNAPSHOT_TRIPLES] = (
                    len(unit_ontology_context)
                )

        _, state.unit_patch_sources, _, anchor_counts = aggregate_writable_metrics(
            unit_contexts
        )
        state.unit_context_sources = {
            **state.unit_context_sources,
            "facts": dict(state.unit_patch_sources),
        }
        state.retrieval_metrics[RetrievalMetric.FACTS_ANCHOR_COUNT] = len(anchor_counts)
        state.retrieval_metrics[RetrievalMetric.FACTS_ANCHOR_UNITS] = sum(
            anchor_counts.values()
        )
        all_attempts = [
            attempt
            for attempts in state.facts_loop_telemetry.values()
            for attempt in attempts
        ]
        # Patch passes undone for leaving the unit worse -- deleting without
        # writing, shrinking without resolving, or manufacturing new mandatory
        # findings. Non-zero means the critique is provoking data-destroying
        # responses, the failure mode that has cost runs a large share of their
        # value nodes while logging nothing a run could be judged by.
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_PATCHES_ROLLED_BACK] = sum(
            1 for attempt in all_attempts if attempt.patch_rolled_back
        )
        # Residual is read off each unit's final findings, not off the attempt
        # log. Summing `attempts[-1]` where `kind == "llm_repair"` silently
        # contributed 0 for every unit that never ran a repair render -- the
        # clean ones and the ones whose loop exhausted its retries -- so the
        # metric's denominator was "units that needed repair", not "units", and
        # a change that made *fewer* units enter repair read as a drop in
        # residual findings. It also summed total findings, so advisory
        # NUMERIC_COVERAGE (which fires on nearly every unit of numeric prose)
        # dominated the number that was supposed to track mandatory defects.
        state.retrieval_metrics[RetrievalMetric.FACTS_FINDINGS_RESIDUAL] = (
            findings_residual
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_MANDATORY_RESIDUAL] = (
            mandatory_residual
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_MANDATORY_RESIDUAL_BY_KIND] = (
            dict(sorted(mandatory_by_kind.items()))
        )
        state.retrieval_metrics[
            RetrievalMetric.FACTS_STATEMENTS_WITHOUT_SUBJECT_RENDERED
        ] = subject_gaps_rendered
        state.retrieval_metrics[RetrievalMetric.FACTS_STATEMENTS_WITHOUT_SUBJECT] = (
            subject_gaps_left
        )
        # The critic's own ledger. `node_visits` counting CRITICISE_FACTS lived
        # on the per-unit state copy and died with it, so the number of critic
        # calls a run bought was not recoverable from its own artifacts.
        critic_attempts = [a for a in all_attempts if a.kind == "critic"]
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_CALLS] = len(
            critic_attempts
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_ACCEPTED] = sum(
            1 for attempt in critic_attempts if attempt.success
        )
        # What the critique actually produced, split by outcome. The
        # loop used to discard every fix on an accepted render, so the honest
        # value of these two together was once "far less than the call count
        # suggests" -- and nothing recorded it.
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_FIXES_APPLIED] = (
            critic_fixes_applied
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_FIXES_RESIDUAL] = (
            critic_fixes_residual
        )
        # Fixes that removed exactly what they re-added. A critique made mostly
        # of these is a critic producing motion rather than corrections, which
        # nothing could see before: they used to be counted as fixes that
        # landed.
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_FIXES_NOOP] = (
            critic_fixes_noop
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_FIXES_ROLLED_BACK] = (
            critic_fixes_rolled_back
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_FIXES_JUNK_REFUSED] = (
            critic_fixes_junk_refused
        )
        state.retrieval_metrics[
            RetrievalMetric.FACTS_CRITIC_FIXES_UNRESOLVED_PREFIX
        ] = critic_fixes_unresolved_prefix
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_UNITS_UNREVIEWED] = (
            critic_units_unreviewed
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_CRITIC_UNITS_SKIPPED] = (
            critic_units_skipped
        )
        # The insert-only completion pass, read off the attempt log like the
        # critic's own ledger: calls made, inserts that stayed, and missed
        # measurements the inventory stopped listing.
        completion_attempts = [a for a in all_attempts if a.kind == "completion"]
        state.retrieval_metrics[RetrievalMetric.FACTS_COMPLETION_CALLS] = len(
            completion_attempts
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_COMPLETION_TRIPLES_INSERTED] = (
            sum(a.n_triples_inserted for a in completion_attempts)
        )
        state.retrieval_metrics[
            RetrievalMetric.FACTS_COMPLETION_MEASUREMENTS_RECOVERED
        ] = sum(a.n_measurements_recovered for a in completion_attempts)
        state.retrieval_metrics[RetrievalMetric.FACTS_COMPLETION_DETACHED_LINKED] = sum(
            a.n_detached_linked for a in completion_attempts
        )
        domain_repairs = [a for a in all_attempts if a.kind == "domain_repair"]
        state.retrieval_metrics[RetrievalMetric.FACTS_DOMAIN_REPAIR_CALLS] = len(
            domain_repairs
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_DOMAIN_REPAIR_FIXED] = sum(
            a.n_fixes_applied for a in domain_repairs
        )
        state.retrieval_metrics[RetrievalMetric.FACTS_DOMAIN_VIOLATIONS_DROPPED] = sum(
            record.triple_count
            for records in state.facts_repairs_applied.values()
            for record in records
            if record.kind == FactsGateRepairKind.DOMAIN_VIOLATION_DROPPED
        )
        state.facts_units = facts_units
        state.status = _map_stage_status(
            failed_without_output_count, len(state.content_units)
        )
        return state

    return render_facts

make_render_ontology_node(tools)

Source code in ontocast/stategraph/node_factories.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
def make_render_ontology_node(tools: ToolBox):
    async def render_ontology_updates(state: AgentState) -> AgentState:
        if not state.content_units:
            state.ontology_units = []
            # Do not overwrite an upstream failure: conversion and chunking set
            # FAILED and the graph edge into this node is unconditional, so
            # clobbering it here turned a failed conversion into HTTP 200.
            if state.status != Status.FAILED:
                state.status = Status.SUCCESS
            return state

        worker_limit = max(1, tools.config.server.parallel_workers)
        semaphore = asyncio.Semaphore(worker_limit)

        async def process_unit(
            unit_index: int,
        ) -> tuple[int, UnitOntologyState, str, list[str], OntologyAssemblyMode]:
            async with _unit_slot(semaphore) as worker_wait:
                unit_budget = BudgetTracker()
                # Before building the unit state: the loop deep-copies the
                # content unit, so a later write would not be visible to it.
                await ensure_unit_summary(state, unit_index, tools, unit_budget)
                unit_context = UnitLoopContext.from_agent_state(state, unit_budget)
                ontology_state = UnitOntologyState(
                    content_unit=state.content_units[unit_index],
                    ontology_snapshot=_empty_unit_snapshot(),
                    ontology_patch_sources=[],
                    ontology_user_instruction=state.ontology_user_instruction,
                    budget_tracker=unit_budget,
                    max_visits_per_node=state.max_visits,
                    current_domain=state.current_domain,
                    home_ontology=state.home_ontology,
                    ontology_plan=state.ontology_plan,
                    ontology_max_triples=tools.config.server.ontology_max_triples,
                    llm_graph_format=state.llm_graph_format,
                    llm_output_layout=tools.config.server.llm_output_layout,
                    ontology_context_max_triples=tools.config.server.ontology_context_max_triples,
                )
                loop_start = time.perf_counter()
                result = await ontology_loop(ontology_state, tools, unit_context)
                result.budget_tracker.add_duration(
                    f"{WorkflowNode.RENDER_ONTOLOGY_UPDATE}{UNIT_SUM_SUFFIX}",
                    time.perf_counter() - loop_start,
                )
                result.budget_tracker.add_duration(
                    f"{WorkflowNode.RENDER_ONTOLOGY_UPDATE}/worker_wait", worker_wait
                )
                # Per-unit resolver metrics previously landed on a discarded
                # deep copy; fold them back (last writer wins on shared keys).
                state.retrieval_metrics.update(unit_context.retrieval_metrics)
                return (
                    unit_index,
                    result,
                    result.assembly_anchor_iri,
                    list(result.writable_iris or result.ontology_patch_sources),
                    result.assembly_mode_used,
                )

        raw_results, unit_errors = await _gather_units_with_warmup(
            WorkflowNode.RENDER_ONTOLOGY_UPDATE,
            state,
            process_unit,
            warmup=tools.config.server.fanout_warmup_units,
        )
        ordered_results = sorted(raw_results, key=lambda item: item[0])

        ontology_units: list[ContentUnit] = []
        unit_deltas: list[OntologyDelta] = []
        # Deletes of units whose context was a retrieved subset: kept only
        # where the document redeclares their subject.
        deletes_on_partial_view = RDFGraph()
        fresh_ontologies: list[Ontology] = []
        failed_without_output_count = unit_errors
        salvaged_failed_count = 0
        unit_contexts: dict[int, tuple[str, list[str], OntologyAssemblyMode]] = {}
        all_writable: list[str] = []
        seen_writable: set[str] = set()

        # Accumulated over *every* unit (see the facts reduce below): the
        # residual's denominator is "units", not "units that ran a critic".
        ontology_findings_residual = 0
        ontology_mandatory_residual = 0
        # For consolidation: the findings left on each unit, and which units
        # minted each term (their text is the term's evidence).
        residual_findings: list[OntologyUnitFinding] = []
        term_units: dict[str, set[int]] = {}
        for (
            unit_index,
            result,
            primary_iri,
            writable_iris,
            assembly_mode,
        ) in ordered_results:
            state.budget_tracker.merge_from(result.budget_tracker)
            ontology_findings_residual += len(result.deterministic_findings)
            ontology_mandatory_residual += sum(
                1 for finding in result.deterministic_findings if finding.mandatory
            )
            residual_findings.extend(result.deterministic_findings)
            if result.attempt_log:
                state.ontology_loop_telemetry[unit_index] = list(result.attempt_log)
            unit_contexts[unit_index] = (
                primary_iri,
                list(result.ontology_patch_sources),
                assembly_mode,
            )
            for iri in writable_iris:
                if iri and iri not in seen_writable:
                    seen_writable.add(iri)
                    all_writable.append(iri)

            has_output = bool(result.all_updates) or result.working_graph_changed()
            if (
                result.fresh_ontology is not None
                and not result.fresh_ontology.is_null()
            ):
                fresh_ontologies.append(result.fresh_ontology)
                has_output = True

            if not has_output:
                failed_without_output_count += 1
                state.unit_failures.append(
                    UnitFailure(
                        unit_index=unit_index,
                        phase="ontology",
                        stage=(
                            result.failure_stage.value
                            if result.failure_stage is not None
                            else None
                        ),
                        reason=result.failure_reason,
                    )
                )
                continue

            content_unit = result.content_unit
            delta = result.build_delta()
            unit_graphs = [delta.inserts]
            if result.fresh_ontology is not None:
                unit_graphs.append(result.fresh_ontology.graph)
            for graph in unit_graphs:
                for subject in set(graph.subjects()):
                    if isinstance(subject, URIRef):
                        term_units.setdefault(str(subject), set()).add(unit_index)
            if not delta.is_empty():
                unit_deltas.append(delta)
            if result.ontology_snapshot.partial:
                deletes_on_partial_view += delta.deletes
            if len(delta.inserts) > 0:
                ontology_units.append(
                    ContentUnit(
                        text=content_unit.text,
                        index=content_unit.index,
                        doc_iri=content_unit.doc_iri,
                        graph=delta.inserts,
                        type=OutputType.ONTOLOGIES,
                    )
                )
            if result.status != Status.SUCCESS:
                salvaged_failed_count += 1

        if failed_without_output_count:
            logger.warning(
                "Parallel ontology map failed without usable output for "
                f"{failed_without_output_count}/{len(state.content_units)} unit(s)"
            )
        if salvaged_failed_count:
            logger.warning(
                "Parallel ontology map salvaged output from non-converged loop(s): "
                f"{salvaged_failed_count}/{len(state.content_units)} unit(s)"
            )

        _, state.unit_patch_sources, _, primary_counts = aggregate_writable_metrics(
            unit_contexts
        )
        state.unit_context_sources = {
            **state.unit_context_sources,
            "ontology": dict(state.unit_patch_sources),
        }
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_WRITABLE_COUNT] = len(
            seen_writable
        )
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_PRIMARY_UNITS] = sum(
            primary_counts.values()
        )
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_FINDINGS_RESIDUAL] = (
            ontology_findings_residual
        )
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_MANDATORY_RESIDUAL] = (
            ontology_mandatory_residual
        )
        # The ontology critic's own ledger, mirroring the facts block: without
        # it, whether the critic ran (ONTOLOGY_CRITIC_PASSES) and what it
        # accepted are unrecoverable from a run's artifacts.
        ontology_critic_attempts = [
            attempt
            for attempts in state.ontology_loop_telemetry.values()
            for attempt in attempts
            if attempt.kind == "critic"
        ]
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_CRITIC_CALLS] = len(
            ontology_critic_attempts
        )
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_CRITIC_ACCEPTED] = sum(
            1 for attempt in ontology_critic_attempts if attempt.success
        )
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_CRITIC_UNITS_SKIPPED] = sum(
            1
            for attempts in state.ontology_loop_telemetry.values()
            if any(attempt.kind == "critic_skipped" for attempt in attempts)
        )
        ontology_patch_attempts = [
            attempt
            for attempts in state.ontology_loop_telemetry.values()
            for attempt in attempts
            if attempt.kind == "critic_patch"
        ]
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_CRITIC_FIXES_APPLIED] = sum(
            attempt.n_fixes_applied for attempt in ontology_patch_attempts
        )
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_CRITIC_FIXES_NOOP] = sum(
            attempt.n_fixes_noop for attempt in ontology_patch_attempts
        )
        state.retrieval_metrics[RetrievalMetric.ONTOLOGY_CRITIC_PATCHES_ROLLED_BACK] = (
            sum(1 for attempt in ontology_patch_attempts if attempt.patch_rolled_back)
        )

        # Document-level insert/delete consensus + namespace apply onto catalog bases.
        merged_delta = merge_unit_deltas(unit_deltas)
        if _insert_only(tools):
            _count_insert_only_drops(state, drop_all_deletes(merged_delta))

        # A unit that saw its ontologies whole judged its deletes on full
        # evidence; only deletes judged on a partial view need a redeclaration.
        state.ontology_reduce_metrics["deletes_dropped_unredeclared"] = (
            enforce_redeclared_deletes(merged_delta, deletes_on_partial_view)
        )

        # Clean-up without a model, before anything reviews the delta:
        # consolidation and duplicate detection should not spend a decision on
        # a triple that is never written.
        home = state.home_ontology
        hygiene = clean_ontology_delta(
            [
                merged_delta.inserts,
                merged_delta.deletes,
                *(o.graph for o in fresh_ontologies),
            ],
            external=external_namespaces(tools, state.current_domain),
            current_domain=state.current_domain,
            catalog_index=tools.ontology_manager.catalog_surface_index(),
            ontology_iris=[
                *(head.iri for head in tools.ontology_manager.ontologies if head.iri),
                *([home.iri] if home is not None else []),
            ],
            home_namespace=home.namespace if home is not None else None,
        )
        state.ontology_reduce_metrics.update(
            {key: value for key, value in hygiene.items() if value}
        )

        # Minted-duplicate reconciliation against the whole catalog, not the
        # units' snapshots: under vector retrieval a term the retrieval failed
        # to surface gets re-minted under a fresh IRI. 'detect' (default) only
        # measures; 'rewrite' substitutes once the matches are shown to be
        # true duplicates.
        reconcile_mode = (
            tools.config.get_tool_config().ontology_validation.reconcile_minted_terms
        )
        duplicates: list[MintedDuplicate] = []
        if reconcile_mode != "off" and len(merged_delta.inserts) > 0:
            duplicates = detect_minted_duplicates(
                merged_delta.inserts, tools.ontology_manager.catalog_surface_index()
            )
            state.ontology_reduce_metrics["minted_duplicates"] = len(duplicates)
            if duplicates:
                state.ontology_reduce_metrics["minted_duplicate_pairs"] = [
                    duplicate.model_dump() for duplicate in duplicates
                ]
                for duplicate in duplicates:
                    logger.warning(
                        "Minted term <%s> duplicates catalog term <%s> "
                        "(surface %r, role %s)%s",
                        duplicate.minted_iri,
                        duplicate.catalog_iri,
                        duplicate.surface,
                        duplicate.role,
                        " — rewriting" if reconcile_mode == "rewrite" else "",
                    )
                if reconcile_mode == "rewrite":
                    state.ontology_reduce_metrics["minted_duplicates_rewritten"] = (
                        apply_minted_duplicate_rewrites(
                            merged_delta.inserts, duplicates
                        )
                    )

        fresh_ontologies, fresh_metrics = reconcile_fresh_ontologies(fresh_ontologies)
        state.ontology_reduce_metrics.update(fresh_metrics)

        # The document-level decision on every minted term: candidates the
        # plan did not name are held back, consolidation (when on) decides
        # each term, and the decisions are compiled into both carriers.
        await decide_minted_terms(
            state,
            tools,
            merged_inserts=merged_delta.inserts,
            fresh_ontologies=fresh_ontologies,
            findings=residual_findings,
            term_units=term_units,
            duplicates=duplicates,
        )
        fresh_ontologies = [o for o in fresh_ontologies if len(o.graph) > 0]

        base_overrides = home_base_overrides(state, tools, fresh_ontologies)
        if state.home_ontology is not None and state.home_ontology.iri not in (
            seen_writable
        ):
            seen_writable.add(state.home_ontology.iri)
            all_writable.append(state.home_ontology.iri)

        # A fresh render is filed by subject like an update: what it states
        # about another ontology's terms joins the delta for that ontology.
        refiled = unowned = 0
        for fresh in fresh_ontologies:
            moved, dropped = refile_fresh_statements(
                fresh,
                writable_iris=all_writable,
                ontology_manager=tools.ontology_manager,
                current_domain=state.current_domain,
                base_overrides=base_overrides,
            )
            for triple in moved:
                merged_delta.inserts.add(triple)
            refiled += len(moved)
            unowned += dropped
        if refiled:
            state.ontology_reduce_metrics["fresh_triples_refiled"] = refiled
        if unowned:
            state.ontology_reduce_metrics["fresh_triples_unattributed"] = unowned

        catalog_index = tools.ontology_manager.catalog_surface_index()
        catalog_subjects = catalog_index.terms
        state.ontology_minted_classes = sorted(
            minted_class_iris(
                merged_delta.inserts, *(o.graph for o in fresh_ontologies)
            )
            - catalog_subjects
        )
        state.ontology_reduce_metrics["minted_classes"] = len(
            state.ontology_minted_classes
        )

        # A fresh render whose every statement was filed elsewhere is not an
        # ontology the document wrote.
        artifacts: list[Ontology] = [
            o for o in fresh_ontologies if set(o.graph.subjects()) - {URIRef(o.iri)}
        ]
        if not merged_delta.is_empty() and all_writable:
            partitioned_inserts, unattributed = partition_triples_by_namespace(
                merged_delta.inserts,
                writable_iris=all_writable,
                ontology_manager=tools.ontology_manager,
                current_domain=state.current_domain,
                base_overrides=base_overrides,
            )
            state.ontology_reduce_metrics["unattributed_insert_triples"] = unattributed
            partitioned_deletes, unattributed_deletes = partition_triples_by_namespace(
                merged_delta.deletes,
                writable_iris=all_writable,
                ontology_manager=tools.ontology_manager,
                current_domain=state.current_domain,
                base_overrides=base_overrides,
            )
            state.ontology_reduce_metrics["unattributed_delete_triples"] = (
                unattributed_deletes
            )
            applied, apply_metrics, applied_updates = apply_partitioned_updates(
                partitioned_inserts,
                ontology_manager=tools.ontology_manager,
                normalize_units_fn=normalize_ontology_units,
                tools=tools,
                partitioned_deletes=partitioned_deletes,
                base_overrides=base_overrides,
            )
            # A fresh home the delta was applied onto is superseded by the result.
            applied_iris = {artifact.iri for artifact in applied}
            artifacts = [a for a in artifacts if a.iri not in applied_iris]
            artifacts.extend(applied)
            for iri, updates in applied_updates.items():
                state.ontology_updates_by_iri.setdefault(iri, []).extend(updates)
            state.ontology_reduce_metrics.update(apply_metrics)
        elif not merged_delta.is_empty() and not all_writable:
            logger.warning(
                "Ontology map produced %s complement / %s delete triples but no "
                "writable catalog IRIs; skipping catalog apply",
                len(merged_delta.inserts),
                len(merged_delta.deletes),
            )

        state.ontology_artifacts = artifacts
        state.reduced_ontology_artifacts = list(artifacts)
        state.reduced_ontology_by_anchor = _index_ontologies_by_anchor(artifacts)
        state.ontology_reduce_metrics["reduced_artifact_count"] = len(artifacts)
        state.ontology_units = ontology_units
        state.status = _map_stage_status(
            failed_without_output_count, len(state.content_units)
        )
        return state

    return render_ontology_updates

make_resolve_coreference_node(tools)

Source code in ontocast/stategraph/node_factories.py
def make_resolve_coreference_node(tools: ToolBox):
    async def resolve_coreference(state: AgentState) -> AgentState:
        """Put the pairs aggregation could not settle to the model, then re-aggregate.

        ``same`` verdicts merge like a shared key and ``different`` ones veto;
        the aggregator's guards still apply. The verdicts are kept on the state
        so the facts gate's own re-aggregation honours them.
        """
        candidates = state.coreference_candidates
        if not candidates:
            return state
        verdicts = await judge_coreference(state, tools, candidates)
        metrics = state.retrieval_metrics
        metrics[RetrievalMetric.FACTS_COREFERENCE_PAIRS] = len(candidates)
        metrics[RetrievalMetric.FACTS_COREFERENCE_SAME] = sum(
            1 for v in verdicts.values() if v == "same"
        )
        metrics[RetrievalMetric.FACTS_COREFERENCE_DIFFERENT] = sum(
            1 for v in verdicts.values() if v == "different"
        )
        vetoes, confirmations = verdict_pairs(candidates, verdicts)
        if not vetoes and not confirmations:
            return state
        state.coreference_vetoes = stored_pairs(vetoes)
        state.coreference_confirmations = stored_pairs(confirmations)
        ontology_graph, document_metadata = _facts_aggregation_inputs(state, tools)
        result = tools.aggregator.postprocess_facts_units(
            units=state.facts_units,
            ontology_graph=ontology_graph,
            doc_iri=state.doc_iri,
            document_metadata=document_metadata,
            doc_namespace=state.doc_namespace,
            merge_vetoes=vetoes,
            confirmed_pairs=confirmations,
        )
        _store_aggregation(state, result)
        return state

    return resolve_coreference

make_structural_check_node(tools)

Source code in ontocast/stategraph/node_factories.py
def make_structural_check_node(tools: ToolBox):
    del tools

    def structural_check(state: AgentState) -> AgentState:
        """Run lightweight structural checks over the stitched ontology before the final critic."""
        doc_onto = document_ontology_access(state)
        artifacts = doc_onto.reduced_artifacts()
        if artifacts:
            component_counts: list[int] = []
            for ontology in artifacts:
                if ontology.is_null() or len(ontology.graph) == 0:
                    continue
                ontology_validation = RDFGraphConnectivityValidator(
                    ontology.graph
                ).validate_connectivity()
                component_counts.append(ontology_validation.num_components)
                if not ontology_validation.is_fully_connected:
                    state.improvements_suggestions.append(
                        f"Structural check ({ontology.iri}): ontology has disconnected components; "
                        "prefer linking classes/properties explicitly."
                    )
                if ontology_validation.missing_labels:
                    state.improvements_suggestions.append(
                        f"Structural check ({ontology.iri}): ontology predicates missing labels were detected."
                    )
            if component_counts:
                state.retrieval_metrics[
                    RetrievalMetric.STRUCTURAL_ONTOLOGY_COMPONENTS_MAX
                ] = max(component_counts)
        state.status = Status.SUCCESS
        return state

    return structural_check

make_validate_facts_node(tools)

Source code in ontocast/stategraph/node_factories.py
def make_validate_facts_node(tools: ToolBox):
    def validate_facts(state: AgentState) -> AgentState:
        """Post-aggregation invariant gate with two LLM-free repair stages.

        Delegates to :func:`~ontocast.stategraph.facts_gate.run_facts_gate`,
        which the single-unit entry path shares. The document path enables the
        un-merge repair: it has many units to re-aggregate against each other.
        """
        if not state.facts_units or len(state.aggregated_facts) == 0:
            record_unused_minted_classes(state)
            if state.status != Status.FAILED:
                state.status = Status.SUCCESS
            return state

        ontology_graph, document_metadata = _facts_aggregation_inputs(state, tools)
        run_facts_gate(
            state,
            ontology_graph,
            tools,
            merge_repair=True,
            document_metadata=document_metadata,
        )
        record_unused_minted_classes(state)
        state.status = Status.SUCCESS
        return state

    return validate_facts

record_unused_minted_classes(state)

Count the classes this document minted that none of its facts types.

Recorded only when the run rendered both lanes, so a class can have been instantiated. A minted class no fact of its own document uses is the clearest sign the class names that document rather than its domain.

Source code in ontocast/stategraph/node_factories.py
def record_unused_minted_classes(state: AgentState) -> None:
    """Count the classes this document minted that none of its facts types.

    Recorded only when the run rendered both lanes, so a class can have been
    instantiated. A minted class no fact of its own document uses is the
    clearest sign the class names that document rather than its domain.
    """
    if not (state.render_ontology and state.render_facts):
        return
    if not state.ontology_minted_classes:
        return
    used = {
        str(obj)
        for obj in state.aggregated_facts.objects(None, RDF.type)
        if isinstance(obj, URIRef)
    }
    unused = [iri for iri in state.ontology_minted_classes if iri not in used]
    state.ontology_reduce_metrics["unused_minted_classes"] = len(unused)
    state.ontology_reduce_metrics["unused_minted_class_iris"] = unused