Skip to content

ontocast.tool.ontology_manager

Ontology management tool for OntoCast.

This module provides functionality for managing multiple ontologies, including loading, updating, and retrieving ontologies by name or IRI. Tracks version lineage using hash-based identifiers.

Attributes

logger = logging.getLogger(__name__) module-attribute

Classes

OntologyManager

Bases: Tool

The catalog: every ontology this process holds, with its versions.

For each IRI it holds the stamped versions it has seen, identified by their version IRIs and linked by prior_version_iris. The head of an ontology is the version nothing names as prior; an ontology with several heads is diverged and cannot be extended until merged.

Attributes:

Name Type Description
ontology_versions dict[str, list[Ontology]]

Stamped versions per ontology IRI.

Source code in ontocast/tool/ontology_manager.py
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
class OntologyManager(Tool):
    """The catalog: every ontology this process holds, with its versions.

    For each IRI it holds the stamped versions it has seen, identified by
    their version IRIs and linked by ``prior_version_iris``. The *head* of an
    ontology is the version nothing names as prior; an ontology with several
    heads is diverged and cannot be extended until merged.

    Attributes:
        ontology_versions: Stamped versions per ontology IRI.
    """

    ontology_versions: dict[str, list[Ontology]] = Field(default_factory=dict)

    def __init__(self, **kwargs: Any):
        """Initialize the ontology manager.

        Args:
            **kwargs: Additional keyword arguments passed to the parent class.
        """
        super().__init__(**kwargs)
        # IRI -> version IRI of its head. Updated when a version is added.
        self._cached_ontologies: dict[str, str] = {}
        self._patch_retriever: OntologyPatchRetriever | None = None
        self._triple_store_manager: TripleStoreManager | None = None
        # The id each IRI was registered with; ids may repeat across IRIs.
        self._iri_to_ontology_id: dict[str, str] = {}
        # Lowercased alias (ontology_id, author prefix, the IRI) → the IRIs
        # holding it. Only an IRI is unique; a short alias may name several.
        self._alias_to_iri: dict[str, set[str]] = {}
        # The catalog's prefix table, per set of extra graphs (the shapes);
        # dropped whenever the catalog changes.
        self._prefix_tables: dict[tuple[tuple[str, str], ...], PrefixTable] = {}
        # Content-addressed caches. An entry can never go stale on read: a
        # concurrent writer produces a *new* key, which is a miss, never an
        # incorrect hit. Both are bounded -- they hold whole rdflib graphs, and
        # a long-lived server would otherwise grow without limit.
        #
        # _graph_cache is keyed by version IRI (the named graph a version was
        # read from); the version IRIs cached per ontology are tracked for
        # eviction.
        self._graph_cache: OrderedDict[str, Ontology] = OrderedDict()
        self._graph_uris_by_iri: dict[str, set[str]] = {}
        self._merged_cache: OrderedDict[
            frozenset[str], tuple[RDFGraph, dict[str, str]]
        ] = OrderedDict()
        self._graph_cache_hits = 0
        self._graph_cache_misses = 0
        self._merged_cache_hits = 0
        self._merged_cache_misses = 0
        # Union of every served ontology's IRIs, keyed by the served version
        # set so it is rebuilt exactly when the catalog changes. Read per unit
        # by the deterministic repairs; see :meth:`catalog_terms`.
        self._catalog_terms_memo: tuple[frozenset[str], set[str]] | None = None
        self._surface_index_memo: tuple[frozenset[str], CatalogSurfaceIndex] | None = (
            None
        )
        self._roles_memo: tuple[frozenset[str], CatalogRoles] | None = None
        self._identity_memo: tuple[frozenset[str], IdentityDeclarations] | None = None

    @staticmethod
    def _primary_ontology_id(ontology: Ontology) -> str:
        identity = (ontology.ontology_id or "").strip().lower()
        if not identity:
            raise ValueError(
                "Ontology identity is missing: ontology_id is required for catalog registration"
            )
        return identity

    def _collect_aliases(self, ontology: Ontology) -> list[tuple[str, str]]:
        """Collect ``(alias, kind)`` pairs; kind is ``ontology_id`` or ``prefix``.

        When ``ontology_id`` and author prefix coincide, the alias keeps the
        stricter ``ontology_id`` kind.
        """
        aliases: list[tuple[str, str]] = []
        seen: set[str] = set()
        for candidate, kind in (
            (ontology.ontology_id, "ontology_id"),
            (ontology.prefix, "prefix"),
        ):
            if not candidate:
                continue
            cleaned = candidate.strip().lower()
            if cleaned and cleaned not in seen:
                seen.add(cleaned)
                aliases.append((cleaned, kind))
        return aliases

    def validate_identity_uniqueness(self, ontology: Ontology) -> None:
        """Refuse an ontology whose IRI is registered under another id.

        The IRI is the identity. An id or an author prefix may repeat across
        IRIs: a short reference that names several resolves to none
        (:meth:`resolve_ontology_ref`).
        """
        self._check_identity(ontology, self._iri_to_ontology_id)

    def identity_conflicts(self, ontologies: list[Ontology]) -> dict[str, str]:
        """Why each of ``ontologies`` that cannot be registered cannot, by IRI.

        Each is checked against the catalog and against the ones before it in
        the list, as :meth:`validate_identity_uniqueness` would check it once
        those were registered. Registers nothing.
        """
        iri_to_id = dict(self._iri_to_ontology_id)
        conflicts: dict[str, str] = {}
        for ontology in ontologies:
            try:
                self._check_identity(ontology, iri_to_id)
            except ValueError as exc:
                conflicts[ontology.iri] = str(exc)
                continue
            iri_to_id[ontology.iri.strip()] = self._primary_ontology_id(ontology)
        return conflicts

    def _check_identity(
        self,
        ontology: Ontology,
        iri_to_id: dict[str, str],
    ) -> None:
        iri = (ontology.iri or "").strip()
        if not iri:
            raise ValueError("Ontology IRI is missing")
        if iri == NULL_ONTOLOGY.iri:
            raise ValueError("Null ontology IRI cannot be registered")

        primary = self._primary_ontology_id(ontology)

        existing_primary = iri_to_id.get(iri)
        if existing_primary is not None and existing_primary != primary:
            raise ValueError(
                "Ontology identity conflict: IRI "
                f"'{iri}' is already bound to identity '{existing_primary}', "
                f"received '{primary}'"
            )

    def _register_identity(self, ontology: Ontology) -> None:
        iri = ontology.iri.strip()
        primary = self._primary_ontology_id(ontology)
        self._iri_to_ontology_id[iri] = primary
        aliases = [alias for alias, _kind in self._collect_aliases(ontology)]
        # The raw IRI and its normalized form resolve as well.
        aliases += [iri.lower(), normalize_ontology_iri(iri).lower()]
        for alias in aliases:
            if alias:
                self._alias_to_iri.setdefault(alias, set()).add(iri)
        self._prefix_tables.clear()

    def resolve_ontology_ref(self, ref: str) -> str | None:
        """The catalog IRI ``ref`` names: an IRI, or an id or prefix one IRI holds.

        Raises:
            AmbiguousOntologyRefError: ``ref`` is an id or a prefix that
                several catalog ontologies hold.
        """
        if not ref or not str(ref).strip():
            return None
        cleaned = str(ref).strip()
        if cleaned in self.ontology_versions:
            return cleaned
        normalized = normalize_ontology_iri(cleaned)
        if normalized in self.ontology_versions:
            return normalized
        for key in (cleaned.lower(), normalized.lower()):
            iris = self._alias_to_iri.get(key)
            if not iris:
                continue
            if len(iris) > 1:
                raise AmbiguousOntologyRefError(cleaned, sorted(iris))
            return next(iter(iris))
        return None

    def prefix_table(self, others: Sequence[RDFGraph] = ()) -> PrefixTable:
        """The catalog's prefix table: one shown prefix per namespace.

        Args:
            others: Further graphs whose bindings name namespaces, such as the
                shapes graph, whose prose the prompt shows.
        """
        # The table reads only the other graphs' bindings, so they are the key.
        key = tuple(
            sorted(
                (prefix, str(namespace))
                for graph in others
                for prefix, namespace in graph.namespaces()
                if prefix
            )
        )
        table = self._prefix_tables.get(key)
        if table is None:
            table = build_prefix_table(self.ontologies, others)
            self._prefix_tables[key] = table
        return table

    def __contains__(self, item: object) -> bool:
        """Check if an item (IRI or alias) is in the ontology manager.

        Args:
            item: The IRI, ontology_id, or author prefix to check.

        Returns:
            bool: True if the item names at least one tracked ontology.
        """
        ref = str(item).strip()
        normalized = normalize_ontology_iri(ref)
        return (
            ref in self.ontology_versions
            or normalized in self.ontology_versions
            or bool(self._alias_to_iri.get(ref.lower()))
            or bool(self._alias_to_iri.get(normalized.lower()))
        )

    def _prepare_ontology_for_catalog(self, ontology: Ontology) -> bool:
        """Validate and register a stamped version; True if it is new here.

        Raises:
            ValueError: the ontology is null, unstamped, or its identity
                collides with a registered one.
        """
        if not ontology.iri or ontology.iri == NULL_ONTOLOGY.iri:
            raise ValueError("cannot register the null ontology")
        if not ontology.version_iri:
            raise ValueError(f"ontology {ontology.iri} is not stamped as a version")

        self.validate_identity_uniqueness(ontology)
        self._register_identity(ontology)

        # A registered version is a stored one: what derives from it next
        # derives from this version.
        if not (
            len(ontology.bases) == 1
            and ontology.bases[0].version_iri == ontology.version_iri
        ):
            ontology.bases = [OntologyHeader.from_ontology(ontology)]

        versions = self.ontology_versions.setdefault(ontology.iri, [])
        if any(o.version_iri == ontology.version_iri for o in versions):
            logger.debug("Version %s already registered", ontology.version_iri)
            return False
        versions.append(ontology)
        self._cached_ontologies.pop(ontology.iri, None)
        self._prefix_tables.clear()
        logger.debug("Registered version %s", ontology.version_iri)
        return True

    def _reindex_ontology_sync(self, ontology: Ontology) -> None:
        """Sync vector reindex (caller must ensure no running event loop)."""
        if self._patch_retriever is None:
            return
        self._patch_retriever.vector_store.reindex_ontology(ontology)

    def _ensure_sync_reindex_allowed(self, *, skip_vector_index: bool) -> None:
        """Raise if sync reindex would block a running event loop."""
        if skip_vector_index or self._patch_retriever is None:
            return
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            return
        raise RuntimeError(
            "add_ontology() cannot reindex inside async code; use await aadd_ontology()"
        )

    async def _reindex_ontology_async(self, ontology: Ontology) -> None:
        if self._patch_retriever is None:
            return
        await asyncio.to_thread(
            self._patch_retriever.vector_store.reindex_ontology, ontology
        )

    def add_ontology(
        self, ontology: Ontology, *, skip_vector_index: bool = False
    ) -> None:
        """Add an ontology to the version tree for its IRI.

        If an ontology with the same hash already exists, it is not added again.
        Ensures that created_at is set if not already present.

        Args:
            ontology: The ontology to add.
            skip_vector_index: If True, do not call the vector store (caller
                already materialized embeddings, e.g. during ToolBox.initialize).

        Raises:
            RuntimeError: If vector reindex would run while an event loop is
                already active. Use :meth:`aadd_ontology` from async code.
        """
        self._ensure_sync_reindex_allowed(skip_vector_index=skip_vector_index)
        if not self._prepare_ontology_for_catalog(ontology):
            return
        if not skip_vector_index:
            self._reindex_ontology_sync(ontology)

    async def aadd_ontology(
        self, ontology: Ontology, *, skip_vector_index: bool = False
    ) -> None:
        """Async variant of :meth:`add_ontology` (reindex off the event loop)."""
        if not self._prepare_ontology_for_catalog(ontology):
            return
        if not skip_vector_index:
            await self._reindex_ontology_async(ontology)

    def replace_version(self, ontology: Ontology) -> None:
        """Replace a tracked version in place (e.g. after writing a tombstone).

        Raises:
            ValueError: ``ontology`` is unstamped, or no version with its
                ``version_iri`` is held.
        """
        if not ontology.version_iri:
            raise ValueError(f"ontology {ontology.iri} is not stamped as a version")
        versions = self.ontology_versions.get(ontology.iri, [])
        for index, held in enumerate(versions):
            if held.version_iri == ontology.version_iri:
                versions[index] = ontology
                self._cached_ontologies.pop(ontology.iri, None)
                self._graph_cache[ontology.version_iri] = ontology
                self._graph_cache.move_to_end(ontology.version_iri)
                return
        raise ValueError(f"no tracked version {ontology.version_iri}")

    def remove_ontology_by_iri(self, iri: str) -> None:
        """Drop all tracked versions for an ontology IRI and clear caches."""
        for graph_uri in self._graph_uris_by_iri.pop(iri, set()):
            self._graph_cache.pop(graph_uri, None)
        for ontology in self.ontology_versions.get(iri, []):
            if ontology.version_iri:
                self._graph_cache.pop(ontology.version_iri, None)
        stale_merges = [
            key
            for key in self._merged_cache
            if any(versioned.startswith(f"{iri}#") for versioned in key)
        ]
        for key in stale_merges:
            del self._merged_cache[key]
        self.ontology_versions.pop(iri, None)
        self._cached_ontologies.pop(iri, None)
        self._iri_to_ontology_id.pop(iri, None)
        # Drop this IRI from every alias; an alias no IRI holds goes.
        for alias in list(self._alias_to_iri):
            held = self._alias_to_iri[alias]
            held.discard(iri)
            if not held:
                del self._alias_to_iri[alias]
        self._prefix_tables.clear()

    def register_vector_store(self, retriever: "OntologyPatchRetriever") -> None:
        """Register a patch retriever for vector context lookups."""
        self._patch_retriever = retriever

    def register_triple_store(self, manager: TripleStoreManager | None) -> None:
        """Register the triple store this catalog reads through on a cache miss."""
        self._triple_store_manager = manager

    def reset_catalog(self) -> None:
        """Drop every tracked ontology, identity binding, and cached graph.

        Called when the active tenant/project changes: the catalog, the alias
        collision ledger, and the graph caches are all partition-scoped, and
        carrying them across a switch leaks one tenant's ontologies into another's
        requests.
        """
        self.ontology_versions.clear()
        self._cached_ontologies.clear()
        self._iri_to_ontology_id.clear()
        self._alias_to_iri.clear()
        self._prefix_tables.clear()
        self._graph_cache.clear()
        self._graph_uris_by_iri.clear()
        self._merged_cache.clear()

    @property
    def has_triple_store(self) -> bool:
        """Whether a triple store is registered, so heads are read from its headers."""
        return self._triple_store_manager is not None

    def _require_triple_store(self) -> TripleStoreManager:
        if self._triple_store_manager is None:
            raise RuntimeError(
                "OntologyManager has no triple store registered; "
                "call register_triple_store() before reading the catalog"
            )
        return self._triple_store_manager

    async def aget_catalog_headers(self) -> list[OntologyHeader]:
        """Read ontology header metadata for every stored version.

        Deliberately **not** cached. Headers are what terminal-version selection
        runs on, so caching them would let this process miss another worker's
        writes to a shared store -- the one thing the graph cache cannot go wrong
        about, and the one thing this would.

        Returns:
            list[OntologyHeader]: One header per stored ontology version.
        """
        return await self._require_triple_store().afetch_ontology_catalog()

    async def aget_ontologies_by_iri(self, iris: Sequence[str]) -> list[Ontology]:
        """Return the heads of ``iris``, fetching only cache misses.

        Head selection always runs against freshly read headers; only the
        graph bytes come from cache, keyed by version IRI.

        Args:
            iris: Ontology IRIs to resolve. Empty means "no restriction", matching
                :meth:`~ontocast.tool.triple_manager.core.TripleStoreManager.afetch_ontologies_by_iri`.

        Returns:
            list[Ontology]: Terminal ontologies with graphs. Callers must treat
            these as shared read-only references.
        """
        store = self._require_triple_store()
        headers = head_headers(await self.aget_catalog_headers())
        if iris:
            wanted = set(iris)
            headers = [header for header in headers if header.iri in wanted]

        resolved: list[Ontology] = []
        missing_iris: list[str] = []
        graph_uri_by_iri: dict[str, str] = {}
        for header in headers:
            cached = self._graph_cache.get(header.graph_uri)
            if cached is not None:
                self._graph_cache_hits += 1
                self._graph_cache.move_to_end(header.graph_uri)
                resolved.append(cached)
            else:
                self._graph_cache_misses += 1
                missing_iris.append(header.iri)
                graph_uri_by_iri[header.iri] = header.graph_uri

        if missing_iris:
            fetched = await store.afetch_ontologies_by_iri(missing_iris)
            for ontology in fetched:
                self._cache_graph(ontology, graph_uri_by_iri.get(ontology.iri))
            resolved.extend(fetched)
        return resolved

    async def aget_merged_graph(
        self, ontologies: Sequence[Ontology]
    ) -> tuple[RDFGraph, dict[str, str]]:
        """Return the prefix-bound union of ``ontologies``, cached by version set.

        The induced-subgraph builder reads this union without mutating it, so one
        merge can be shared by every content unit that selects the same ontology
        versions -- which is the common case inside a document.

        Args:
            ontologies: Ontology versions to merge.

        Returns:
            tuple: ``(merged_graph, prefix_map)``. The graph **must not be mutated
            by callers**; it is shared.
        """
        from .sparql import merge_ontology_graphs

        key = frozenset(onto.version_iri or onto.iri for onto in ontologies)
        cached = self._merged_cache.get(key)
        if cached is not None:
            self._merged_cache_hits += 1
            self._merged_cache.move_to_end(key)
            return cached

        self._merged_cache_misses += 1
        merged = await asyncio.to_thread(merge_ontology_graphs, list(ontologies))
        self._merged_cache[key] = merged
        while len(self._merged_cache) > _MERGED_CACHE_MAX_ENTRIES:
            self._merged_cache.popitem(last=False)
        return merged

    def catalog_cache_stats(self) -> dict[str, int]:
        """Cache hit/miss counters, for tests and retrieval diagnostics."""
        return {
            "catalog_graph_cache_hits": self._graph_cache_hits,
            "catalog_graph_cache_misses": self._graph_cache_misses,
            "catalog_merge_cache_hits": self._merged_cache_hits,
            "catalog_merge_cache_misses": self._merged_cache_misses,
        }

    def catalog_terms(self) -> set[str]:
        """Every IRI the held ontologies declare or reference, as one set.

        The union of :func:`collect_catalog_terms` over every ontology this
        manager holds -- the terminal versions registered in memory and the
        graphs read through the triple store and resident in the graph cache.
        Built lazily and memoised on the content-addressed identifiers of that
        set, so it is recomputed only when an ontology is added, superseded,
        removed, or newly read from the store.

        The per-unit repairs read it for membership: a term present here is a
        real catalog term even when a unit's retrieved snapshot omits it, and
        must never be rewritten toward a look-alike the snapshot does carry.

        Returns:
            set[str]: Shared across units -- treat as read-only.
        """
        held = self._held_ontologies()
        key = frozenset(held)
        memo = self._catalog_terms_memo
        if memo is not None and memo[0] == key:
            return memo[1]
        terms: set[str] = set()
        for ontology in held.values():
            terms |= collect_catalog_terms(ontology.graph)
        self._catalog_terms_memo = (key, terms)
        return terms

    def _held_ontologies(self) -> dict[str, Ontology]:
        """Every held ontology, by version IRI: the heads and the graph cache."""
        held: dict[str, Ontology] = {
            ontology.version_iri or ontology.iri: ontology
            for ontology in self.get_heads_by_iri(None)
        }
        for graph_uri, ontology in self._graph_cache.items():
            held.setdefault(graph_uri, ontology)
        return held

    def catalog_roles(self) -> CatalogRoles:
        """What every held ontology says each term is, and the class hierarchy.

        Built over the same set as :meth:`catalog_terms` and memoised the same
        way. The repairs read it to tell a property from a class, and the facts
        gate to tell a value class, over the whole catalog rather than a unit's
        snapshot.

        Returns:
            CatalogRoles: Shared across units -- treat as read-only.
        """
        held = self._held_ontologies()
        key = frozenset(held)
        memo = self._roles_memo
        if memo is not None and memo[0] == key:
            return memo[1]
        roles = CatalogRoles.of(o.graph for o in held.values())
        self._roles_memo = (key, roles)
        return roles

    def identity_declarations(self) -> IdentityDeclarations:
        """What the catalog heads declare about identity across documents.

        Read from the heads only, not the graph cache, so the result depends on
        the catalog state alone and not on which graphs this process happened
        to read. Memoised on the heads' version IRIs.

        Returns:
            IdentityDeclarations: Shared -- treat as read-only.
        """
        heads = self.get_heads_by_iri(None)
        key = frozenset(o.version_iri or o.iri for o in heads)
        memo = self._identity_memo
        if memo is not None and memo[0] == key:
            return memo[1]
        declarations = IdentityDeclarations.of(o.graph for o in heads)
        self._identity_memo = (key, declarations)
        return declarations

    def catalog_surface_index(self) -> CatalogSurfaceIndex:
        """Labels, notations and local names of every held term, case-insensitive.

        Built over the same set as :meth:`catalog_terms` and memoised the same
        way. Read by the duplicate checks, which must see the whole catalog:
        under vector retrieval a re-minted term duplicates one the unit's
        snapshot did not contain.

        Returns:
            CatalogSurfaceIndex: Shared across units -- treat as read-only.
        """
        held = self._held_ontologies()
        key = frozenset(held)
        memo = self._surface_index_memo
        if memo is not None and memo[0] == key:
            return memo[1]
        index = build_catalog_surface_index(o.graph for o in held.values())
        self._surface_index_memo = (key, index)
        return index

    def term_definitions(self, terms: Iterable[str]) -> RDFGraph:
        """The statements that define ``terms`` in the held catalog.

        For each term, its type, labels, notes, domain, range and parents, taken
        from the first held ontology that states any of them -- the heads come
        before the graph cache, so the current version wins. Objects that are
        blank nodes are left out: a partial structure would mislead more than
        its absence. The prefix each source binds for a term's namespace is
        bound in the result. A term no held ontology defines contributes nothing.

        Args:
            terms: Term IRIs to look up.

        Returns:
            RDFGraph: A new graph; empty when nothing is defined.
        """
        out = RDFGraph()
        held = list(self._held_ontologies().values())
        for term_iri in terms:
            term = URIRef(term_iri)
            for ontology in held:
                triples = [
                    (term, predicate, obj)
                    for predicate in _DEFINITION_PREDICATES
                    for obj in ontology.graph.objects(term, predicate)
                    if not isinstance(obj, BNode)
                ]
                if not triples:
                    continue
                for triple in triples:
                    out.add(triple)
                for prefix, namespace in ontology.graph.namespaces():
                    if prefix and term_iri.startswith(str(namespace)):
                        out.bind(prefix, namespace, override=False)
                break
        return out

    def _cache_graph(self, ontology: Ontology, graph_uri: str | None = None) -> None:
        """Register a store-read ``ontology`` under the graph URI it was read from.

        Only ever called with graphs that came *from* the triple store. Seeding the
        cache from :meth:`add_ontology` instead would be tempting -- those graphs are
        already in memory -- but a registered ontology and its persisted form are not
        byte-identical: writing round-trips through deterministic Turtle, which
        relabels blank nodes. Snapshot expansion tie-breaks on ``str(triple)``, so
        mixing the two makes retrieval depend on whether a graph happened to be
        written by this process.

        Args:
            ontology: Ontology materialized from the triple store.
            graph_uri: Named graph it was read from; defaults to its version IRI.
        """
        key = graph_uri or ontology.version_iri
        if not key:
            return
        self._graph_cache.setdefault(key, ontology)
        self._graph_cache.move_to_end(key)
        self._graph_uris_by_iri.setdefault(ontology.iri, set()).add(key)
        while len(self._graph_cache) > _GRAPH_CACHE_MAX_ENTRIES:
            evicted_key, evicted = self._graph_cache.popitem(last=False)
            uris = self._graph_uris_by_iri.get(evicted.iri)
            if uris is not None:
                uris.discard(evicted_key)
                if not uris:
                    self._graph_uris_by_iri.pop(evicted.iri, None)

    def _effective_patch_top_k(self, top_k: int | None) -> int:
        if top_k is not None:
            return top_k
        if self._patch_retriever is not None:
            return self._patch_retriever.vector_store.store_config.top_k
        return 10

    def _fallback_patch_results(
        self, queries: list[str]
    ) -> list[tuple[RDFGraph | None, list[str]]]:
        """Per-query independent copies of the catalog's one head graph."""
        fallback = self.get_head_by_iri(None)
        if fallback is None:
            return [(None, []) for _ in queries]
        sources = [fallback.iri]
        return [(fallback.graph.copy(), sources) for _ in queries]

    @staticmethod
    def _normalize_patch_graph(
        graph: RDFGraph, sources: list[str]
    ) -> tuple[RDFGraph, list[str]]:
        return (graph, sources) if len(graph) > 0 else (RDFGraph(), sources)

    def get_patch_context(
        self,
        query: str,
        top_k: int | None = None,
        subgraph_depth: int | None = None,
        max_total_triples: int | None = None,
        estimated_triples_per_query: int | None = None,
    ) -> RDFGraph | None:
        """Retrieve multi-ontology patch context for a query.

        Falls back to the freshest available ontology graph if vector retrieval
        is not configured or yields no atoms.
        """
        graph, _ = self.get_patch_context_with_sources(
            query=query,
            top_k=top_k,
            subgraph_depth=subgraph_depth,
            max_total_triples=max_total_triples,
            estimated_triples_per_query=estimated_triples_per_query,
        )
        return graph

    async def aget_patch_context(
        self,
        query: str,
        top_k: int | None = None,
        subgraph_depth: int | None = None,
        max_total_triples: int | None = None,
        estimated_triples_per_query: int | None = None,
    ) -> RDFGraph | None:
        """Async variant of :meth:`get_patch_context`."""
        graph, _ = await self.aget_patch_context_with_sources(
            query=query,
            top_k=top_k,
            subgraph_depth=subgraph_depth,
            max_total_triples=max_total_triples,
            estimated_triples_per_query=estimated_triples_per_query,
        )
        return graph

    def get_patch_context_with_sources(
        self,
        query: str,
        top_k: int | None = None,
        subgraph_depth: int | None = None,
        max_total_triples: int | None = None,
        estimated_triples_per_query: int | None = None,
    ) -> tuple[RDFGraph | None, list[str]]:
        """Retrieve patch context and contributing ontology IRIs."""
        results = self.get_patch_contexts_with_sources(
            queries=[query],
            top_k=top_k,
            subgraph_depth=subgraph_depth,
            max_total_triples=max_total_triples,
            estimated_triples_per_query=estimated_triples_per_query,
        )
        if not results:
            return None, []
        return results[0]

    async def aget_patch_context_with_sources(
        self,
        query: str,
        top_k: int | None = None,
        subgraph_depth: int | None = None,
        max_total_triples: int | None = None,
        estimated_triples_per_query: int | None = None,
    ) -> tuple[RDFGraph | None, list[str]]:
        """Async variant of :meth:`get_patch_context_with_sources`."""
        results = await self.aget_patch_contexts_with_sources(
            queries=[query],
            top_k=top_k,
            subgraph_depth=subgraph_depth,
            max_total_triples=max_total_triples,
            estimated_triples_per_query=estimated_triples_per_query,
        )
        if not results:
            return None, []
        return results[0]

    def get_patch_contexts_with_sources(
        self,
        queries: list[str],
        top_k: int | None = None,
        subgraph_depth: int | None = None,
        max_total_triples: int | None = None,
        estimated_triples_per_query: int | None = None,
    ) -> list[tuple[RDFGraph | None, list[str]]]:
        """Retrieve patch contexts for many queries in a batched pass.

        With a patch retriever, the list has length 1 (ensemble graph + sources).
        Without it, length matches ``queries`` (fallback ontology per query).

        Raises:
            RuntimeError: If called while an event loop is running. Use
                :meth:`aget_patch_contexts_with_sources` from async code.
        """
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            return asyncio.run(
                self.aget_patch_contexts_with_sources(
                    queries=queries,
                    top_k=top_k,
                    subgraph_depth=subgraph_depth,
                    max_total_triples=max_total_triples,
                    estimated_triples_per_query=estimated_triples_per_query,
                )
            )
        raise RuntimeError(
            "get_patch_contexts_with_sources() cannot be called from async code; "
            "use await aget_patch_contexts_with_sources()"
        )

    async def aget_patch_contexts_with_sources(
        self,
        queries: list[str],
        top_k: int | None = None,
        subgraph_depth: int | None = None,
        max_total_triples: int | None = None,
        estimated_triples_per_query: int | None = None,
    ) -> list[tuple[RDFGraph | None, list[str]]]:
        """Async patch retrieval (vector + induced subgraph) for many queries.

        With a patch retriever, returns a one-element list: a single induced graph for
        the union of hits over ``queries``, plus contributing ontology IRIs.
        """
        if not queries:
            return []
        if self._patch_retriever is not None:
            graph, sources = await self._patch_retriever.aretrieve_ensemble(
                queries=queries,
                top_k=self._effective_patch_top_k(top_k),
                subgraph_depth=subgraph_depth,
                max_total_triples=max_total_triples,
                estimated_triples_per_query=estimated_triples_per_query,
            )
            return [self._normalize_patch_graph(graph, sources)]

        return self._fallback_patch_results(queries)

    def get_heads_by_iri(self, iri: str | None = None) -> list[Ontology]:
        """The heads held for ``iri``, or for every ontology when ``iri`` is None.

        A head is a live version that no live version descends from; descent
        walks through tombstoned versions.
        """
        if iri:
            versions = list(self.ontology_versions.get(iri, []))
        else:
            versions = [o for group in self.ontology_versions.values() for o in group]
        if not versions:
            return []
        by_version_iri = {o.version_iri: o for o in versions if o.version_iri}
        heads = heads_by_iri([OntologyHeader.from_ontology(o) for o in versions])
        return [
            by_version_iri[header.version_iri]
            for group in heads.values()
            for header in group
            if header.version_iri in by_version_iri
        ]

    def get_heads(self, ontology_id: str | None = None) -> list[Ontology]:
        """The heads of the ontology ``ontology_id`` names (id, alias or IRI)."""
        if ontology_id:
            iri = self.resolve_ontology_ref(ontology_id)
            if iri is None:
                return []
            return self.get_heads_by_iri(iri)
        return self.get_heads_by_iri(None)

    def get_head_by_iri(self, iri: str | None = None) -> Ontology | None:
        """The one head of ``iri``, or None when nothing is held for it.

        With ``iri`` None, the head of the single held ontology (None when
        several are held: there is no "the" head across ontologies).

        Raises:
            DivergedOntologyError: the ontology has several heads.
        """
        heads = self.get_heads_by_iri(iri)
        if not heads:
            return None
        if iri is None:
            iris = {o.iri for o in heads}
            if len(iris) != 1:
                return None
            iri = heads[0].iri
            heads = [o for o in heads if o.iri == iri]
        if len(heads) > 1:
            raise DivergedOntologyError(iri, [o.version_iri or "" for o in heads])
        return heads[0]

    def get_head(self, ontology_id: str | None = None) -> Ontology | None:
        """The one head of the ontology ``ontology_id`` names (id, alias or IRI).

        Raises:
            DivergedOntologyError: the ontology has several heads.
        """
        if ontology_id:
            iri = self.resolve_ontology_ref(ontology_id)
            if iri is None:
                return None
            return self.get_head_by_iri(iri)
        return self.get_head_by_iri(None)

    def get_ontology_versions_by_iri(self, iri: str) -> list[Ontology]:
        """Get all versions of an ontology by IRI.

        Args:
            iri: The IRI to retrieve versions for.

        Returns:
            list[Ontology]: List of all versions of the ontology.
        """
        return self.ontology_versions.get(iri, [])

    def get_ontology_versions(self, ontology_id: str) -> list[Ontology]:
        """Get all versions of an ontology by ontology_id, alias, or IRI.

        Args:
            ontology_id: The ontology_id / alias / IRI to retrieve versions for.

        Returns:
            list[Ontology]: List of all versions of the ontology.
        """
        iri = self.resolve_ontology_ref(ontology_id)
        if iri is None:
            return []
        return self.get_ontology_versions_by_iri(iri)

    def get_lineage_graph_by_iri(self, iri: str) -> "nx.DiGraph | None":
        """The version DAG held for ``iri`` (nodes are version IRIs), or None."""
        if iri not in self.ontology_versions:
            return None
        return Ontology.build_lineage_graph(self.ontology_versions[iri])

    def get_lineage_graph(self, ontology_id: str) -> "nx.DiGraph | None":
        """Get the lineage graph for a specific ontology_id, alias, or IRI.

        Args:
            ontology_id: The ontology_id / alias / IRI to get the lineage graph for.

        Returns:
            networkx.DiGraph: The lineage graph for the ontology, or None if not found.
        """
        iri = self.resolve_ontology_ref(ontology_id)
        if iri is None:
            return None
        return self.get_lineage_graph_by_iri(iri)

    def get_ontology(
        self,
        ontology_id: str | None = None,
        ontology_iri: str | None = None,
        version_iri: str | None = None,
    ) -> Ontology:
        """Get an ontology by IRI, id/alias, or a specific version IRI.

        Without ``version_iri`` the head is returned (the newest head of a
        diverged ontology). IRI is preferred over ``ontology_id``.

        Raises:
            AmbiguousOntologyRefError: only ``ontology_id`` is given and
                several catalog ontologies hold it.

        Returns:
            Ontology: The matching ontology, NULL_ONTOLOGY when none.
        """
        if version_iri:
            for versions in self.ontology_versions.values():
                for o in versions:
                    if o.version_iri == version_iri:
                        return o

        resolved_iri: str | None = None
        if ontology_iri is not None:
            resolved_iri = self.resolve_ontology_ref(ontology_iri)
        if resolved_iri is None and ontology_id is not None:
            resolved_iri = self.resolve_ontology_ref(ontology_id)

        if resolved_iri is not None and resolved_iri in self.ontology_versions:
            versions = self.ontology_versions[resolved_iri]
            if not version_iri:
                heads = self.get_heads_by_iri(resolved_iri)
                if heads:
                    return heads[0]
                if versions:
                    return versions[0]

        return NULL_ONTOLOGY

    def get_ontology_iris(self) -> list[str]:
        """Get a list of all ontology IRIs.

        Returns:
            list[str]: List of ontology IRIs.
        """
        return list(self.ontology_versions.keys())

    def get_ontology_names(self) -> list[str]:
        """Return unique catalog ``ontology_id`` values currently tracked.

        Returns:
            list[str]: Sorted unique ontology short names.
        """
        names = set()
        for versions in self.ontology_versions.values():
            for o in versions:
                if o.ontology_id:
                    names.add(o.ontology_id)
        return sorted(list(names))

    @property
    def has_ontologies(self) -> bool:
        """Check if there are any ontologies available.

        Returns:
            bool: True if there are any ontologies, False otherwise.
        """
        return len(self._cached_ontologies) > 0 or len(self.ontology_versions) > 0

    @property
    def ontologies(self) -> list[Ontology]:
        """The head of each held ontology, one per IRI.

        A diverged ontology (several heads) is left out: nothing extracts
        against it until it is merged.

        Returns:
            list[Ontology]: One head per IRI, in IRI order.
        """
        result: list[Ontology] = []
        for iri in sorted(self.ontology_versions):
            cached = self._cached_ontologies.get(iri)
            if cached is not None:
                head = next(
                    (o for o in self.ontology_versions[iri] if o.version_iri == cached),
                    None,
                )
                if head is not None:
                    result.append(head)
                    continue
            try:
                head = self.get_head_by_iri(iri)
            except DivergedOntologyError as exc:
                logger.error("%s", exc)
                continue
            if head is not None and head.version_iri:
                self._cached_ontologies[iri] = head.version_iri
                result.append(head)
        for removed_iri in set(self._cached_ontologies) - set(self.ontology_versions):
            del self._cached_ontologies[removed_iri]
        return result

Attributes

has_ontologies property

Check if there are any ontologies available.

Returns:

Name Type Description
bool bool

True if there are any ontologies, False otherwise.

has_triple_store property

Whether a triple store is registered, so heads are read from its headers.

ontologies property

The head of each held ontology, one per IRI.

A diverged ontology (several heads) is left out: nothing extracts against it until it is merged.

Returns:

Type Description
list[Ontology]

list[Ontology]: One head per IRI, in IRI order.

ontology_versions = Field(default_factory=dict) class-attribute instance-attribute

Methods:

__contains__(item)

Check if an item (IRI or alias) is in the ontology manager.

Parameters:

Name Type Description Default
item object

The IRI, ontology_id, or author prefix to check.

required

Returns:

Name Type Description
bool bool

True if the item names at least one tracked ontology.

Source code in ontocast/tool/ontology_manager.py
def __contains__(self, item: object) -> bool:
    """Check if an item (IRI or alias) is in the ontology manager.

    Args:
        item: The IRI, ontology_id, or author prefix to check.

    Returns:
        bool: True if the item names at least one tracked ontology.
    """
    ref = str(item).strip()
    normalized = normalize_ontology_iri(ref)
    return (
        ref in self.ontology_versions
        or normalized in self.ontology_versions
        or bool(self._alias_to_iri.get(ref.lower()))
        or bool(self._alias_to_iri.get(normalized.lower()))
    )
__init__(**kwargs)

Initialize the ontology manager.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments passed to the parent class.

{}
Source code in ontocast/tool/ontology_manager.py
def __init__(self, **kwargs: Any):
    """Initialize the ontology manager.

    Args:
        **kwargs: Additional keyword arguments passed to the parent class.
    """
    super().__init__(**kwargs)
    # IRI -> version IRI of its head. Updated when a version is added.
    self._cached_ontologies: dict[str, str] = {}
    self._patch_retriever: OntologyPatchRetriever | None = None
    self._triple_store_manager: TripleStoreManager | None = None
    # The id each IRI was registered with; ids may repeat across IRIs.
    self._iri_to_ontology_id: dict[str, str] = {}
    # Lowercased alias (ontology_id, author prefix, the IRI) → the IRIs
    # holding it. Only an IRI is unique; a short alias may name several.
    self._alias_to_iri: dict[str, set[str]] = {}
    # The catalog's prefix table, per set of extra graphs (the shapes);
    # dropped whenever the catalog changes.
    self._prefix_tables: dict[tuple[tuple[str, str], ...], PrefixTable] = {}
    # Content-addressed caches. An entry can never go stale on read: a
    # concurrent writer produces a *new* key, which is a miss, never an
    # incorrect hit. Both are bounded -- they hold whole rdflib graphs, and
    # a long-lived server would otherwise grow without limit.
    #
    # _graph_cache is keyed by version IRI (the named graph a version was
    # read from); the version IRIs cached per ontology are tracked for
    # eviction.
    self._graph_cache: OrderedDict[str, Ontology] = OrderedDict()
    self._graph_uris_by_iri: dict[str, set[str]] = {}
    self._merged_cache: OrderedDict[
        frozenset[str], tuple[RDFGraph, dict[str, str]]
    ] = OrderedDict()
    self._graph_cache_hits = 0
    self._graph_cache_misses = 0
    self._merged_cache_hits = 0
    self._merged_cache_misses = 0
    # Union of every served ontology's IRIs, keyed by the served version
    # set so it is rebuilt exactly when the catalog changes. Read per unit
    # by the deterministic repairs; see :meth:`catalog_terms`.
    self._catalog_terms_memo: tuple[frozenset[str], set[str]] | None = None
    self._surface_index_memo: tuple[frozenset[str], CatalogSurfaceIndex] | None = (
        None
    )
    self._roles_memo: tuple[frozenset[str], CatalogRoles] | None = None
    self._identity_memo: tuple[frozenset[str], IdentityDeclarations] | None = None
aadd_ontology(ontology, *, skip_vector_index=False) async

Async variant of :meth:add_ontology (reindex off the event loop).

Source code in ontocast/tool/ontology_manager.py
async def aadd_ontology(
    self, ontology: Ontology, *, skip_vector_index: bool = False
) -> None:
    """Async variant of :meth:`add_ontology` (reindex off the event loop)."""
    if not self._prepare_ontology_for_catalog(ontology):
        return
    if not skip_vector_index:
        await self._reindex_ontology_async(ontology)
add_ontology(ontology, *, skip_vector_index=False)

Add an ontology to the version tree for its IRI.

If an ontology with the same hash already exists, it is not added again. Ensures that created_at is set if not already present.

Parameters:

Name Type Description Default
ontology Ontology

The ontology to add.

required
skip_vector_index bool

If True, do not call the vector store (caller already materialized embeddings, e.g. during ToolBox.initialize).

False

Raises:

Type Description
RuntimeError

If vector reindex would run while an event loop is already active. Use :meth:aadd_ontology from async code.

Source code in ontocast/tool/ontology_manager.py
def add_ontology(
    self, ontology: Ontology, *, skip_vector_index: bool = False
) -> None:
    """Add an ontology to the version tree for its IRI.

    If an ontology with the same hash already exists, it is not added again.
    Ensures that created_at is set if not already present.

    Args:
        ontology: The ontology to add.
        skip_vector_index: If True, do not call the vector store (caller
            already materialized embeddings, e.g. during ToolBox.initialize).

    Raises:
        RuntimeError: If vector reindex would run while an event loop is
            already active. Use :meth:`aadd_ontology` from async code.
    """
    self._ensure_sync_reindex_allowed(skip_vector_index=skip_vector_index)
    if not self._prepare_ontology_for_catalog(ontology):
        return
    if not skip_vector_index:
        self._reindex_ontology_sync(ontology)
aget_catalog_headers() async

Read ontology header metadata for every stored version.

Deliberately not cached. Headers are what terminal-version selection runs on, so caching them would let this process miss another worker's writes to a shared store -- the one thing the graph cache cannot go wrong about, and the one thing this would.

Returns:

Type Description
list[OntologyHeader]

list[OntologyHeader]: One header per stored ontology version.

Source code in ontocast/tool/ontology_manager.py
async def aget_catalog_headers(self) -> list[OntologyHeader]:
    """Read ontology header metadata for every stored version.

    Deliberately **not** cached. Headers are what terminal-version selection
    runs on, so caching them would let this process miss another worker's
    writes to a shared store -- the one thing the graph cache cannot go wrong
    about, and the one thing this would.

    Returns:
        list[OntologyHeader]: One header per stored ontology version.
    """
    return await self._require_triple_store().afetch_ontology_catalog()
aget_merged_graph(ontologies) async

Return the prefix-bound union of ontologies, cached by version set.

The induced-subgraph builder reads this union without mutating it, so one merge can be shared by every content unit that selects the same ontology versions -- which is the common case inside a document.

Parameters:

Name Type Description Default
ontologies Sequence[Ontology]

Ontology versions to merge.

required

Returns:

Name Type Description
tuple RDFGraph

(merged_graph, prefix_map). The graph **must not be mutated

dict[str, str]

by callers**; it is shared.

Source code in ontocast/tool/ontology_manager.py
async def aget_merged_graph(
    self, ontologies: Sequence[Ontology]
) -> tuple[RDFGraph, dict[str, str]]:
    """Return the prefix-bound union of ``ontologies``, cached by version set.

    The induced-subgraph builder reads this union without mutating it, so one
    merge can be shared by every content unit that selects the same ontology
    versions -- which is the common case inside a document.

    Args:
        ontologies: Ontology versions to merge.

    Returns:
        tuple: ``(merged_graph, prefix_map)``. The graph **must not be mutated
        by callers**; it is shared.
    """
    from .sparql import merge_ontology_graphs

    key = frozenset(onto.version_iri or onto.iri for onto in ontologies)
    cached = self._merged_cache.get(key)
    if cached is not None:
        self._merged_cache_hits += 1
        self._merged_cache.move_to_end(key)
        return cached

    self._merged_cache_misses += 1
    merged = await asyncio.to_thread(merge_ontology_graphs, list(ontologies))
    self._merged_cache[key] = merged
    while len(self._merged_cache) > _MERGED_CACHE_MAX_ENTRIES:
        self._merged_cache.popitem(last=False)
    return merged
aget_ontologies_by_iri(iris) async

Return the heads of iris, fetching only cache misses.

Head selection always runs against freshly read headers; only the graph bytes come from cache, keyed by version IRI.

Parameters:

Name Type Description Default
iris Sequence[str]

Ontology IRIs to resolve. Empty means "no restriction", matching :meth:~ontocast.tool.triple_manager.core.TripleStoreManager.afetch_ontologies_by_iri.

required

Returns:

Type Description
list[Ontology]

list[Ontology]: Terminal ontologies with graphs. Callers must treat

list[Ontology]

these as shared read-only references.

Source code in ontocast/tool/ontology_manager.py
async def aget_ontologies_by_iri(self, iris: Sequence[str]) -> list[Ontology]:
    """Return the heads of ``iris``, fetching only cache misses.

    Head selection always runs against freshly read headers; only the
    graph bytes come from cache, keyed by version IRI.

    Args:
        iris: Ontology IRIs to resolve. Empty means "no restriction", matching
            :meth:`~ontocast.tool.triple_manager.core.TripleStoreManager.afetch_ontologies_by_iri`.

    Returns:
        list[Ontology]: Terminal ontologies with graphs. Callers must treat
        these as shared read-only references.
    """
    store = self._require_triple_store()
    headers = head_headers(await self.aget_catalog_headers())
    if iris:
        wanted = set(iris)
        headers = [header for header in headers if header.iri in wanted]

    resolved: list[Ontology] = []
    missing_iris: list[str] = []
    graph_uri_by_iri: dict[str, str] = {}
    for header in headers:
        cached = self._graph_cache.get(header.graph_uri)
        if cached is not None:
            self._graph_cache_hits += 1
            self._graph_cache.move_to_end(header.graph_uri)
            resolved.append(cached)
        else:
            self._graph_cache_misses += 1
            missing_iris.append(header.iri)
            graph_uri_by_iri[header.iri] = header.graph_uri

    if missing_iris:
        fetched = await store.afetch_ontologies_by_iri(missing_iris)
        for ontology in fetched:
            self._cache_graph(ontology, graph_uri_by_iri.get(ontology.iri))
        resolved.extend(fetched)
    return resolved
aget_patch_context(query, top_k=None, subgraph_depth=None, max_total_triples=None, estimated_triples_per_query=None) async

Async variant of :meth:get_patch_context.

Source code in ontocast/tool/ontology_manager.py
async def aget_patch_context(
    self,
    query: str,
    top_k: int | None = None,
    subgraph_depth: int | None = None,
    max_total_triples: int | None = None,
    estimated_triples_per_query: int | None = None,
) -> RDFGraph | None:
    """Async variant of :meth:`get_patch_context`."""
    graph, _ = await self.aget_patch_context_with_sources(
        query=query,
        top_k=top_k,
        subgraph_depth=subgraph_depth,
        max_total_triples=max_total_triples,
        estimated_triples_per_query=estimated_triples_per_query,
    )
    return graph
aget_patch_context_with_sources(query, top_k=None, subgraph_depth=None, max_total_triples=None, estimated_triples_per_query=None) async

Async variant of :meth:get_patch_context_with_sources.

Source code in ontocast/tool/ontology_manager.py
async def aget_patch_context_with_sources(
    self,
    query: str,
    top_k: int | None = None,
    subgraph_depth: int | None = None,
    max_total_triples: int | None = None,
    estimated_triples_per_query: int | None = None,
) -> tuple[RDFGraph | None, list[str]]:
    """Async variant of :meth:`get_patch_context_with_sources`."""
    results = await self.aget_patch_contexts_with_sources(
        queries=[query],
        top_k=top_k,
        subgraph_depth=subgraph_depth,
        max_total_triples=max_total_triples,
        estimated_triples_per_query=estimated_triples_per_query,
    )
    if not results:
        return None, []
    return results[0]
aget_patch_contexts_with_sources(queries, top_k=None, subgraph_depth=None, max_total_triples=None, estimated_triples_per_query=None) async

Async patch retrieval (vector + induced subgraph) for many queries.

With a patch retriever, returns a one-element list: a single induced graph for the union of hits over queries, plus contributing ontology IRIs.

Source code in ontocast/tool/ontology_manager.py
async def aget_patch_contexts_with_sources(
    self,
    queries: list[str],
    top_k: int | None = None,
    subgraph_depth: int | None = None,
    max_total_triples: int | None = None,
    estimated_triples_per_query: int | None = None,
) -> list[tuple[RDFGraph | None, list[str]]]:
    """Async patch retrieval (vector + induced subgraph) for many queries.

    With a patch retriever, returns a one-element list: a single induced graph for
    the union of hits over ``queries``, plus contributing ontology IRIs.
    """
    if not queries:
        return []
    if self._patch_retriever is not None:
        graph, sources = await self._patch_retriever.aretrieve_ensemble(
            queries=queries,
            top_k=self._effective_patch_top_k(top_k),
            subgraph_depth=subgraph_depth,
            max_total_triples=max_total_triples,
            estimated_triples_per_query=estimated_triples_per_query,
        )
        return [self._normalize_patch_graph(graph, sources)]

    return self._fallback_patch_results(queries)
catalog_cache_stats()

Cache hit/miss counters, for tests and retrieval diagnostics.

Source code in ontocast/tool/ontology_manager.py
def catalog_cache_stats(self) -> dict[str, int]:
    """Cache hit/miss counters, for tests and retrieval diagnostics."""
    return {
        "catalog_graph_cache_hits": self._graph_cache_hits,
        "catalog_graph_cache_misses": self._graph_cache_misses,
        "catalog_merge_cache_hits": self._merged_cache_hits,
        "catalog_merge_cache_misses": self._merged_cache_misses,
    }
catalog_roles()

What every held ontology says each term is, and the class hierarchy.

Built over the same set as :meth:catalog_terms and memoised the same way. The repairs read it to tell a property from a class, and the facts gate to tell a value class, over the whole catalog rather than a unit's snapshot.

Returns:

Name Type Description
CatalogRoles CatalogRoles

Shared across units -- treat as read-only.

Source code in ontocast/tool/ontology_manager.py
def catalog_roles(self) -> CatalogRoles:
    """What every held ontology says each term is, and the class hierarchy.

    Built over the same set as :meth:`catalog_terms` and memoised the same
    way. The repairs read it to tell a property from a class, and the facts
    gate to tell a value class, over the whole catalog rather than a unit's
    snapshot.

    Returns:
        CatalogRoles: Shared across units -- treat as read-only.
    """
    held = self._held_ontologies()
    key = frozenset(held)
    memo = self._roles_memo
    if memo is not None and memo[0] == key:
        return memo[1]
    roles = CatalogRoles.of(o.graph for o in held.values())
    self._roles_memo = (key, roles)
    return roles
catalog_surface_index()

Labels, notations and local names of every held term, case-insensitive.

Built over the same set as :meth:catalog_terms and memoised the same way. Read by the duplicate checks, which must see the whole catalog: under vector retrieval a re-minted term duplicates one the unit's snapshot did not contain.

Returns:

Name Type Description
CatalogSurfaceIndex CatalogSurfaceIndex

Shared across units -- treat as read-only.

Source code in ontocast/tool/ontology_manager.py
def catalog_surface_index(self) -> CatalogSurfaceIndex:
    """Labels, notations and local names of every held term, case-insensitive.

    Built over the same set as :meth:`catalog_terms` and memoised the same
    way. Read by the duplicate checks, which must see the whole catalog:
    under vector retrieval a re-minted term duplicates one the unit's
    snapshot did not contain.

    Returns:
        CatalogSurfaceIndex: Shared across units -- treat as read-only.
    """
    held = self._held_ontologies()
    key = frozenset(held)
    memo = self._surface_index_memo
    if memo is not None and memo[0] == key:
        return memo[1]
    index = build_catalog_surface_index(o.graph for o in held.values())
    self._surface_index_memo = (key, index)
    return index
catalog_terms()

Every IRI the held ontologies declare or reference, as one set.

The union of :func:collect_catalog_terms over every ontology this manager holds -- the terminal versions registered in memory and the graphs read through the triple store and resident in the graph cache. Built lazily and memoised on the content-addressed identifiers of that set, so it is recomputed only when an ontology is added, superseded, removed, or newly read from the store.

The per-unit repairs read it for membership: a term present here is a real catalog term even when a unit's retrieved snapshot omits it, and must never be rewritten toward a look-alike the snapshot does carry.

Returns:

Type Description
set[str]

set[str]: Shared across units -- treat as read-only.

Source code in ontocast/tool/ontology_manager.py
def catalog_terms(self) -> set[str]:
    """Every IRI the held ontologies declare or reference, as one set.

    The union of :func:`collect_catalog_terms` over every ontology this
    manager holds -- the terminal versions registered in memory and the
    graphs read through the triple store and resident in the graph cache.
    Built lazily and memoised on the content-addressed identifiers of that
    set, so it is recomputed only when an ontology is added, superseded,
    removed, or newly read from the store.

    The per-unit repairs read it for membership: a term present here is a
    real catalog term even when a unit's retrieved snapshot omits it, and
    must never be rewritten toward a look-alike the snapshot does carry.

    Returns:
        set[str]: Shared across units -- treat as read-only.
    """
    held = self._held_ontologies()
    key = frozenset(held)
    memo = self._catalog_terms_memo
    if memo is not None and memo[0] == key:
        return memo[1]
    terms: set[str] = set()
    for ontology in held.values():
        terms |= collect_catalog_terms(ontology.graph)
    self._catalog_terms_memo = (key, terms)
    return terms
get_head(ontology_id=None)

The one head of the ontology ontology_id names (id, alias or IRI).

Raises:

Type Description
DivergedOntologyError

the ontology has several heads.

Source code in ontocast/tool/ontology_manager.py
def get_head(self, ontology_id: str | None = None) -> Ontology | None:
    """The one head of the ontology ``ontology_id`` names (id, alias or IRI).

    Raises:
        DivergedOntologyError: the ontology has several heads.
    """
    if ontology_id:
        iri = self.resolve_ontology_ref(ontology_id)
        if iri is None:
            return None
        return self.get_head_by_iri(iri)
    return self.get_head_by_iri(None)
get_head_by_iri(iri=None)

The one head of iri, or None when nothing is held for it.

With iri None, the head of the single held ontology (None when several are held: there is no "the" head across ontologies).

Raises:

Type Description
DivergedOntologyError

the ontology has several heads.

Source code in ontocast/tool/ontology_manager.py
def get_head_by_iri(self, iri: str | None = None) -> Ontology | None:
    """The one head of ``iri``, or None when nothing is held for it.

    With ``iri`` None, the head of the single held ontology (None when
    several are held: there is no "the" head across ontologies).

    Raises:
        DivergedOntologyError: the ontology has several heads.
    """
    heads = self.get_heads_by_iri(iri)
    if not heads:
        return None
    if iri is None:
        iris = {o.iri for o in heads}
        if len(iris) != 1:
            return None
        iri = heads[0].iri
        heads = [o for o in heads if o.iri == iri]
    if len(heads) > 1:
        raise DivergedOntologyError(iri, [o.version_iri or "" for o in heads])
    return heads[0]
get_heads(ontology_id=None)

The heads of the ontology ontology_id names (id, alias or IRI).

Source code in ontocast/tool/ontology_manager.py
def get_heads(self, ontology_id: str | None = None) -> list[Ontology]:
    """The heads of the ontology ``ontology_id`` names (id, alias or IRI)."""
    if ontology_id:
        iri = self.resolve_ontology_ref(ontology_id)
        if iri is None:
            return []
        return self.get_heads_by_iri(iri)
    return self.get_heads_by_iri(None)
get_heads_by_iri(iri=None)

The heads held for iri, or for every ontology when iri is None.

A head is a live version that no live version descends from; descent walks through tombstoned versions.

Source code in ontocast/tool/ontology_manager.py
def get_heads_by_iri(self, iri: str | None = None) -> list[Ontology]:
    """The heads held for ``iri``, or for every ontology when ``iri`` is None.

    A head is a live version that no live version descends from; descent
    walks through tombstoned versions.
    """
    if iri:
        versions = list(self.ontology_versions.get(iri, []))
    else:
        versions = [o for group in self.ontology_versions.values() for o in group]
    if not versions:
        return []
    by_version_iri = {o.version_iri: o for o in versions if o.version_iri}
    heads = heads_by_iri([OntologyHeader.from_ontology(o) for o in versions])
    return [
        by_version_iri[header.version_iri]
        for group in heads.values()
        for header in group
        if header.version_iri in by_version_iri
    ]
get_lineage_graph(ontology_id)

Get the lineage graph for a specific ontology_id, alias, or IRI.

Parameters:

Name Type Description Default
ontology_id str

The ontology_id / alias / IRI to get the lineage graph for.

required

Returns:

Type Description
DiGraph | None

networkx.DiGraph: The lineage graph for the ontology, or None if not found.

Source code in ontocast/tool/ontology_manager.py
def get_lineage_graph(self, ontology_id: str) -> "nx.DiGraph | None":
    """Get the lineage graph for a specific ontology_id, alias, or IRI.

    Args:
        ontology_id: The ontology_id / alias / IRI to get the lineage graph for.

    Returns:
        networkx.DiGraph: The lineage graph for the ontology, or None if not found.
    """
    iri = self.resolve_ontology_ref(ontology_id)
    if iri is None:
        return None
    return self.get_lineage_graph_by_iri(iri)
get_lineage_graph_by_iri(iri)

The version DAG held for iri (nodes are version IRIs), or None.

Source code in ontocast/tool/ontology_manager.py
def get_lineage_graph_by_iri(self, iri: str) -> "nx.DiGraph | None":
    """The version DAG held for ``iri`` (nodes are version IRIs), or None."""
    if iri not in self.ontology_versions:
        return None
    return Ontology.build_lineage_graph(self.ontology_versions[iri])
get_ontology(ontology_id=None, ontology_iri=None, version_iri=None)

Get an ontology by IRI, id/alias, or a specific version IRI.

Without version_iri the head is returned (the newest head of a diverged ontology). IRI is preferred over ontology_id.

Raises:

Type Description
AmbiguousOntologyRefError

only ontology_id is given and several catalog ontologies hold it.

Returns:

Name Type Description
Ontology Ontology

The matching ontology, NULL_ONTOLOGY when none.

Source code in ontocast/tool/ontology_manager.py
def get_ontology(
    self,
    ontology_id: str | None = None,
    ontology_iri: str | None = None,
    version_iri: str | None = None,
) -> Ontology:
    """Get an ontology by IRI, id/alias, or a specific version IRI.

    Without ``version_iri`` the head is returned (the newest head of a
    diverged ontology). IRI is preferred over ``ontology_id``.

    Raises:
        AmbiguousOntologyRefError: only ``ontology_id`` is given and
            several catalog ontologies hold it.

    Returns:
        Ontology: The matching ontology, NULL_ONTOLOGY when none.
    """
    if version_iri:
        for versions in self.ontology_versions.values():
            for o in versions:
                if o.version_iri == version_iri:
                    return o

    resolved_iri: str | None = None
    if ontology_iri is not None:
        resolved_iri = self.resolve_ontology_ref(ontology_iri)
    if resolved_iri is None and ontology_id is not None:
        resolved_iri = self.resolve_ontology_ref(ontology_id)

    if resolved_iri is not None and resolved_iri in self.ontology_versions:
        versions = self.ontology_versions[resolved_iri]
        if not version_iri:
            heads = self.get_heads_by_iri(resolved_iri)
            if heads:
                return heads[0]
            if versions:
                return versions[0]

    return NULL_ONTOLOGY
get_ontology_iris()

Get a list of all ontology IRIs.

Returns:

Type Description
list[str]

list[str]: List of ontology IRIs.

Source code in ontocast/tool/ontology_manager.py
def get_ontology_iris(self) -> list[str]:
    """Get a list of all ontology IRIs.

    Returns:
        list[str]: List of ontology IRIs.
    """
    return list(self.ontology_versions.keys())
get_ontology_names()

Return unique catalog ontology_id values currently tracked.

Returns:

Type Description
list[str]

list[str]: Sorted unique ontology short names.

Source code in ontocast/tool/ontology_manager.py
def get_ontology_names(self) -> list[str]:
    """Return unique catalog ``ontology_id`` values currently tracked.

    Returns:
        list[str]: Sorted unique ontology short names.
    """
    names = set()
    for versions in self.ontology_versions.values():
        for o in versions:
            if o.ontology_id:
                names.add(o.ontology_id)
    return sorted(list(names))
get_ontology_versions(ontology_id)

Get all versions of an ontology by ontology_id, alias, or IRI.

Parameters:

Name Type Description Default
ontology_id str

The ontology_id / alias / IRI to retrieve versions for.

required

Returns:

Type Description
list[Ontology]

list[Ontology]: List of all versions of the ontology.

Source code in ontocast/tool/ontology_manager.py
def get_ontology_versions(self, ontology_id: str) -> list[Ontology]:
    """Get all versions of an ontology by ontology_id, alias, or IRI.

    Args:
        ontology_id: The ontology_id / alias / IRI to retrieve versions for.

    Returns:
        list[Ontology]: List of all versions of the ontology.
    """
    iri = self.resolve_ontology_ref(ontology_id)
    if iri is None:
        return []
    return self.get_ontology_versions_by_iri(iri)
get_ontology_versions_by_iri(iri)

Get all versions of an ontology by IRI.

Parameters:

Name Type Description Default
iri str

The IRI to retrieve versions for.

required

Returns:

Type Description
list[Ontology]

list[Ontology]: List of all versions of the ontology.

Source code in ontocast/tool/ontology_manager.py
def get_ontology_versions_by_iri(self, iri: str) -> list[Ontology]:
    """Get all versions of an ontology by IRI.

    Args:
        iri: The IRI to retrieve versions for.

    Returns:
        list[Ontology]: List of all versions of the ontology.
    """
    return self.ontology_versions.get(iri, [])
get_patch_context(query, top_k=None, subgraph_depth=None, max_total_triples=None, estimated_triples_per_query=None)

Retrieve multi-ontology patch context for a query.

Falls back to the freshest available ontology graph if vector retrieval is not configured or yields no atoms.

Source code in ontocast/tool/ontology_manager.py
def get_patch_context(
    self,
    query: str,
    top_k: int | None = None,
    subgraph_depth: int | None = None,
    max_total_triples: int | None = None,
    estimated_triples_per_query: int | None = None,
) -> RDFGraph | None:
    """Retrieve multi-ontology patch context for a query.

    Falls back to the freshest available ontology graph if vector retrieval
    is not configured or yields no atoms.
    """
    graph, _ = self.get_patch_context_with_sources(
        query=query,
        top_k=top_k,
        subgraph_depth=subgraph_depth,
        max_total_triples=max_total_triples,
        estimated_triples_per_query=estimated_triples_per_query,
    )
    return graph
get_patch_context_with_sources(query, top_k=None, subgraph_depth=None, max_total_triples=None, estimated_triples_per_query=None)

Retrieve patch context and contributing ontology IRIs.

Source code in ontocast/tool/ontology_manager.py
def get_patch_context_with_sources(
    self,
    query: str,
    top_k: int | None = None,
    subgraph_depth: int | None = None,
    max_total_triples: int | None = None,
    estimated_triples_per_query: int | None = None,
) -> tuple[RDFGraph | None, list[str]]:
    """Retrieve patch context and contributing ontology IRIs."""
    results = self.get_patch_contexts_with_sources(
        queries=[query],
        top_k=top_k,
        subgraph_depth=subgraph_depth,
        max_total_triples=max_total_triples,
        estimated_triples_per_query=estimated_triples_per_query,
    )
    if not results:
        return None, []
    return results[0]
get_patch_contexts_with_sources(queries, top_k=None, subgraph_depth=None, max_total_triples=None, estimated_triples_per_query=None)

Retrieve patch contexts for many queries in a batched pass.

With a patch retriever, the list has length 1 (ensemble graph + sources). Without it, length matches queries (fallback ontology per query).

Raises:

Type Description
RuntimeError

If called while an event loop is running. Use :meth:aget_patch_contexts_with_sources from async code.

Source code in ontocast/tool/ontology_manager.py
def get_patch_contexts_with_sources(
    self,
    queries: list[str],
    top_k: int | None = None,
    subgraph_depth: int | None = None,
    max_total_triples: int | None = None,
    estimated_triples_per_query: int | None = None,
) -> list[tuple[RDFGraph | None, list[str]]]:
    """Retrieve patch contexts for many queries in a batched pass.

    With a patch retriever, the list has length 1 (ensemble graph + sources).
    Without it, length matches ``queries`` (fallback ontology per query).

    Raises:
        RuntimeError: If called while an event loop is running. Use
            :meth:`aget_patch_contexts_with_sources` from async code.
    """
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(
            self.aget_patch_contexts_with_sources(
                queries=queries,
                top_k=top_k,
                subgraph_depth=subgraph_depth,
                max_total_triples=max_total_triples,
                estimated_triples_per_query=estimated_triples_per_query,
            )
        )
    raise RuntimeError(
        "get_patch_contexts_with_sources() cannot be called from async code; "
        "use await aget_patch_contexts_with_sources()"
    )
identity_conflicts(ontologies)

Why each of ontologies that cannot be registered cannot, by IRI.

Each is checked against the catalog and against the ones before it in the list, as :meth:validate_identity_uniqueness would check it once those were registered. Registers nothing.

Source code in ontocast/tool/ontology_manager.py
def identity_conflicts(self, ontologies: list[Ontology]) -> dict[str, str]:
    """Why each of ``ontologies`` that cannot be registered cannot, by IRI.

    Each is checked against the catalog and against the ones before it in
    the list, as :meth:`validate_identity_uniqueness` would check it once
    those were registered. Registers nothing.
    """
    iri_to_id = dict(self._iri_to_ontology_id)
    conflicts: dict[str, str] = {}
    for ontology in ontologies:
        try:
            self._check_identity(ontology, iri_to_id)
        except ValueError as exc:
            conflicts[ontology.iri] = str(exc)
            continue
        iri_to_id[ontology.iri.strip()] = self._primary_ontology_id(ontology)
    return conflicts
identity_declarations()

What the catalog heads declare about identity across documents.

Read from the heads only, not the graph cache, so the result depends on the catalog state alone and not on which graphs this process happened to read. Memoised on the heads' version IRIs.

Returns:

Name Type Description
IdentityDeclarations IdentityDeclarations

Shared -- treat as read-only.

Source code in ontocast/tool/ontology_manager.py
def identity_declarations(self) -> IdentityDeclarations:
    """What the catalog heads declare about identity across documents.

    Read from the heads only, not the graph cache, so the result depends on
    the catalog state alone and not on which graphs this process happened
    to read. Memoised on the heads' version IRIs.

    Returns:
        IdentityDeclarations: Shared -- treat as read-only.
    """
    heads = self.get_heads_by_iri(None)
    key = frozenset(o.version_iri or o.iri for o in heads)
    memo = self._identity_memo
    if memo is not None and memo[0] == key:
        return memo[1]
    declarations = IdentityDeclarations.of(o.graph for o in heads)
    self._identity_memo = (key, declarations)
    return declarations
prefix_table(others=())

The catalog's prefix table: one shown prefix per namespace.

Parameters:

Name Type Description Default
others Sequence[RDFGraph]

Further graphs whose bindings name namespaces, such as the shapes graph, whose prose the prompt shows.

()
Source code in ontocast/tool/ontology_manager.py
def prefix_table(self, others: Sequence[RDFGraph] = ()) -> PrefixTable:
    """The catalog's prefix table: one shown prefix per namespace.

    Args:
        others: Further graphs whose bindings name namespaces, such as the
            shapes graph, whose prose the prompt shows.
    """
    # The table reads only the other graphs' bindings, so they are the key.
    key = tuple(
        sorted(
            (prefix, str(namespace))
            for graph in others
            for prefix, namespace in graph.namespaces()
            if prefix
        )
    )
    table = self._prefix_tables.get(key)
    if table is None:
        table = build_prefix_table(self.ontologies, others)
        self._prefix_tables[key] = table
    return table
register_triple_store(manager)

Register the triple store this catalog reads through on a cache miss.

Source code in ontocast/tool/ontology_manager.py
def register_triple_store(self, manager: TripleStoreManager | None) -> None:
    """Register the triple store this catalog reads through on a cache miss."""
    self._triple_store_manager = manager
register_vector_store(retriever)

Register a patch retriever for vector context lookups.

Source code in ontocast/tool/ontology_manager.py
def register_vector_store(self, retriever: "OntologyPatchRetriever") -> None:
    """Register a patch retriever for vector context lookups."""
    self._patch_retriever = retriever
remove_ontology_by_iri(iri)

Drop all tracked versions for an ontology IRI and clear caches.

Source code in ontocast/tool/ontology_manager.py
def remove_ontology_by_iri(self, iri: str) -> None:
    """Drop all tracked versions for an ontology IRI and clear caches."""
    for graph_uri in self._graph_uris_by_iri.pop(iri, set()):
        self._graph_cache.pop(graph_uri, None)
    for ontology in self.ontology_versions.get(iri, []):
        if ontology.version_iri:
            self._graph_cache.pop(ontology.version_iri, None)
    stale_merges = [
        key
        for key in self._merged_cache
        if any(versioned.startswith(f"{iri}#") for versioned in key)
    ]
    for key in stale_merges:
        del self._merged_cache[key]
    self.ontology_versions.pop(iri, None)
    self._cached_ontologies.pop(iri, None)
    self._iri_to_ontology_id.pop(iri, None)
    # Drop this IRI from every alias; an alias no IRI holds goes.
    for alias in list(self._alias_to_iri):
        held = self._alias_to_iri[alias]
        held.discard(iri)
        if not held:
            del self._alias_to_iri[alias]
    self._prefix_tables.clear()
replace_version(ontology)

Replace a tracked version in place (e.g. after writing a tombstone).

Raises:

Type Description
ValueError

ontology is unstamped, or no version with its version_iri is held.

Source code in ontocast/tool/ontology_manager.py
def replace_version(self, ontology: Ontology) -> None:
    """Replace a tracked version in place (e.g. after writing a tombstone).

    Raises:
        ValueError: ``ontology`` is unstamped, or no version with its
            ``version_iri`` is held.
    """
    if not ontology.version_iri:
        raise ValueError(f"ontology {ontology.iri} is not stamped as a version")
    versions = self.ontology_versions.get(ontology.iri, [])
    for index, held in enumerate(versions):
        if held.version_iri == ontology.version_iri:
            versions[index] = ontology
            self._cached_ontologies.pop(ontology.iri, None)
            self._graph_cache[ontology.version_iri] = ontology
            self._graph_cache.move_to_end(ontology.version_iri)
            return
    raise ValueError(f"no tracked version {ontology.version_iri}")
reset_catalog()

Drop every tracked ontology, identity binding, and cached graph.

Called when the active tenant/project changes: the catalog, the alias collision ledger, and the graph caches are all partition-scoped, and carrying them across a switch leaks one tenant's ontologies into another's requests.

Source code in ontocast/tool/ontology_manager.py
def reset_catalog(self) -> None:
    """Drop every tracked ontology, identity binding, and cached graph.

    Called when the active tenant/project changes: the catalog, the alias
    collision ledger, and the graph caches are all partition-scoped, and
    carrying them across a switch leaks one tenant's ontologies into another's
    requests.
    """
    self.ontology_versions.clear()
    self._cached_ontologies.clear()
    self._iri_to_ontology_id.clear()
    self._alias_to_iri.clear()
    self._prefix_tables.clear()
    self._graph_cache.clear()
    self._graph_uris_by_iri.clear()
    self._merged_cache.clear()
resolve_ontology_ref(ref)

The catalog IRI ref names: an IRI, or an id or prefix one IRI holds.

Raises:

Type Description
AmbiguousOntologyRefError

ref is an id or a prefix that several catalog ontologies hold.

Source code in ontocast/tool/ontology_manager.py
def resolve_ontology_ref(self, ref: str) -> str | None:
    """The catalog IRI ``ref`` names: an IRI, or an id or prefix one IRI holds.

    Raises:
        AmbiguousOntologyRefError: ``ref`` is an id or a prefix that
            several catalog ontologies hold.
    """
    if not ref or not str(ref).strip():
        return None
    cleaned = str(ref).strip()
    if cleaned in self.ontology_versions:
        return cleaned
    normalized = normalize_ontology_iri(cleaned)
    if normalized in self.ontology_versions:
        return normalized
    for key in (cleaned.lower(), normalized.lower()):
        iris = self._alias_to_iri.get(key)
        if not iris:
            continue
        if len(iris) > 1:
            raise AmbiguousOntologyRefError(cleaned, sorted(iris))
        return next(iter(iris))
    return None
term_definitions(terms)

The statements that define terms in the held catalog.

For each term, its type, labels, notes, domain, range and parents, taken from the first held ontology that states any of them -- the heads come before the graph cache, so the current version wins. Objects that are blank nodes are left out: a partial structure would mislead more than its absence. The prefix each source binds for a term's namespace is bound in the result. A term no held ontology defines contributes nothing.

Parameters:

Name Type Description Default
terms Iterable[str]

Term IRIs to look up.

required

Returns:

Name Type Description
RDFGraph RDFGraph

A new graph; empty when nothing is defined.

Source code in ontocast/tool/ontology_manager.py
def term_definitions(self, terms: Iterable[str]) -> RDFGraph:
    """The statements that define ``terms`` in the held catalog.

    For each term, its type, labels, notes, domain, range and parents, taken
    from the first held ontology that states any of them -- the heads come
    before the graph cache, so the current version wins. Objects that are
    blank nodes are left out: a partial structure would mislead more than
    its absence. The prefix each source binds for a term's namespace is
    bound in the result. A term no held ontology defines contributes nothing.

    Args:
        terms: Term IRIs to look up.

    Returns:
        RDFGraph: A new graph; empty when nothing is defined.
    """
    out = RDFGraph()
    held = list(self._held_ontologies().values())
    for term_iri in terms:
        term = URIRef(term_iri)
        for ontology in held:
            triples = [
                (term, predicate, obj)
                for predicate in _DEFINITION_PREDICATES
                for obj in ontology.graph.objects(term, predicate)
                if not isinstance(obj, BNode)
            ]
            if not triples:
                continue
            for triple in triples:
                out.add(triple)
            for prefix, namespace in ontology.graph.namespaces():
                if prefix and term_iri.startswith(str(namespace)):
                    out.bind(prefix, namespace, override=False)
            break
    return out
validate_identity_uniqueness(ontology)

Refuse an ontology whose IRI is registered under another id.

The IRI is the identity. An id or an author prefix may repeat across IRIs: a short reference that names several resolves to none (:meth:resolve_ontology_ref).

Source code in ontocast/tool/ontology_manager.py
def validate_identity_uniqueness(self, ontology: Ontology) -> None:
    """Refuse an ontology whose IRI is registered under another id.

    The IRI is the identity. An id or an author prefix may repeat across
    IRIs: a short reference that names several resolves to none
    (:meth:`resolve_ontology_ref`).
    """
    self._check_identity(ontology, self._iri_to_ontology_id)

Functions: