Skip to content

ontometer_corpus.pipeline.parse

Phase 1: Parse.

About

Processes all corpus_registry rows with parse_status IS NULL. For each row, attempts to parse the raw ontology file and extract:

  • Ontology IRI (declared by the file, else recovered from the registry's source_id — see _registry_declared_iri), version IRI, version info
  • Triple count, class count, property count, individual count (with its declared and SKOS-concept subsets — see _individual_counts)
  • owl:imports list
  • Content hash (SHA-256 of sorted class+property IRIs, blank nodes excluded)
  • Namespace footprint (referenced_namespaces / own_namespaces), which feeds the dependency network's namespace-usage edges
  • A per-file structural sidecar (subclass edges + entities), written to ONTOMETER_STORE/cache/structure/v//.parquet

Parse strategy (in order): 0. files whose estimated decompressed size exceeds _STREAM_THRESHOLD_BYTES go to a bounded-memory streaming path (pyoxigraph, read as N-Triples) 1. rdflib — tries 'xml', 'turtle', 'n3', 'json-ld', 'nt', 'trig' 2. custom parsers — offline, lightweight parsers for OBO and OWL/XML 3. owlready2 — fallback helper (strips imports to prevent network requests)

Results are written back to corpus_registry via db.py helpers. Failures are recorded as parse_status='fail' with parse_error populated.

Workers run in a bounded ProcessPoolExecutor (capped max_workers, max_tasks_per_child=1) over tasks sorted by estimated decompressed size. Structural sidecars are written inside each worker, so large hierarchies never cross the process-pool boundary — only scalar metadata does. See ontometer_corpus/network/README.md for how the sidecars are consumed.

No graph-isomorphism digest is computed: rdflib's canonicalisation can run unboundedly long on blank-node-dense graphs. Dedup relies on content_hash plus the raw-bytes file_hash instead.

Attributes

LICENCE_PREDICATES = frozenset({'http://purl.org/dc/terms/license', 'http://purl.org/dc/terms/rights', 'http://purl.org/dc/elements/1.1/rights', 'http://creativecommons.org/ns#license', 'http://schema.org/license', 'https://schema.org/license', 'http://www.w3.org/1999/xhtml/vocab#license'}) module-attribute

MAX_LICENCE_VALUES = 5 module-attribute

MAX_LICENCE_CHARS = 500 module-attribute

STREAM_FORMATS = {'xml': (RdfFormat.RDF_XML,), 'turtle_like': (RdfFormat.TRIG, RdfFormat.N_QUADS)} module-attribute

Classes

Functions:

try_rdflib(raw)

Try rdflib formats against the file content, cheapest path first.

Returns

(graph, format_used, error) graph — populated Graph on success, None on failure format_used — format string that worked, None on failure error — last exception message on failure, None on success

Source code in ontometer_corpus/pipeline/parse.py
def try_rdflib(raw: bytes) -> tuple[rdflib.Graph | None, str | None, str | None]:
    """
    Try rdflib formats against the file content, cheapest path first.

    Returns
    -------
    (graph, format_used, error)
        graph       — populated Graph on success, None on failure
        format_used — format string that worked, None on failure
        error       — last exception message on failure, None on success
    """
    # Normalise Windows CRLF and bare CR line endings to LF before parsing.
    # rdflib's Turtle parser treats \r as part of prefixed names, which breaks
    # files saved by Windows tools.
    normalised = raw.replace(b"\r\n", b"\n").replace(b"\r", b"\n")

    graph, fmt, error = _attempt_parse(normalised)
    if graph is not None:
        return graph, fmt, None

    # Only pay for the speculative regex-based syntax repairs (multiple extra
    # full-content string copies) once the cheap raw attempt has failed for
    # every candidate format — most files parse fine unmodified.
    repaired = _apply_syntax_repairs(normalised)
    if repaired is normalised:
        return None, None, error
    return _attempt_parse(repaired)

try_owlready2(content, orig_suffix)

Fall back to owlready2 (handles OWL/XML and OBO). Converts the ontology to N-Triples, then loads into rdflib.

content is the already-read file bytes (reused from the caller to avoid a redundant full-file read) and orig_suffix is the source file's extension, used to pick the temp-file suffix owlready2 infers format from.

Returns (graph, 'owlready2', None) on success, (None, None, error) on failure.

Source code in ontometer_corpus/pipeline/parse.py
def try_owlready2(
    content: bytes, orig_suffix: str
) -> tuple[rdflib.Graph | None, str | None, str | None]:
    """
    Fall back to owlready2 (handles OWL/XML and OBO).
    Converts the ontology to N-Triples, then loads into rdflib.

    `content` is the already-read file bytes (reused from the caller to
    avoid a redundant full-file read) and `orig_suffix` is the source file's
    extension, used to pick the temp-file suffix owlready2 infers format from.

    Returns (graph, 'owlready2', None) on success, (None, None, error) on failure.
    """
    try:
        import owlready2  # optional dependency — imported lazily

        is_obo = content.lstrip().startswith(b"format-version:")

        # Strip imports to prevent network calls and local import resolution crashes
        cleaned_content = _strip_imports(content)

        # owlready2 infers format from extension. OBO files MUST end with .obo
        suffix = ".obo" if is_obo else orig_suffix
        if not suffix or suffix.lower() not in (".obo", ".owl", ".rdf", ".xml"):
            suffix = ".owl"

        tmp_onto_path: str | None = None
        tmp_nt_path: str | None = None

        try:
            # Create a cleaned version of the ontology file locally
            with tempfile.NamedTemporaryFile(
                suffix=suffix, delete=False, dir=scratch_dir()
            ) as tmp_onto:
                tmp_onto.write(cleaned_content)
                tmp_onto_path = tmp_onto.name

            with tempfile.NamedTemporaryFile(
                suffix=".nt", delete=False, dir=scratch_dir()
            ) as tmp_nt:
                tmp_nt_path = tmp_nt.name

            with contextlib.redirect_stderr(io.StringIO()):
                onto = owlready2.get_ontology(
                    f"file://{Path(tmp_onto_path).resolve().as_posix()}"
                ).load()
                onto.save(file=tmp_nt_path, format="ntriples")

            g = rdflib.Graph()
            g.parse(tmp_nt_path, format="nt")
            return g, "owlready2", None

        finally:
            if tmp_onto_path and os.path.exists(tmp_onto_path):
                os.remove(tmp_onto_path)
            if tmp_nt_path and os.path.exists(tmp_nt_path):
                os.remove(tmp_nt_path)

    except Exception as exc:
        return None, None, str(exc)

compute_content_hash(graph)

Compute a stable content fingerprint for deduplication.

Algorithm
  1. Collect all non-blank-node subjects declared as one of _CLASS_TYPES + _PROPERTY_TYPES.
  2. Sort the IRI strings lexicographically.
  3. Join with newlines, encode UTF-8, SHA-256.

Blank nodes are excluded because they vary across serialisations of the same logical ontology.

The type list is shared with class_count/property_count via _CLASS_TYPES / _PROPERTY_TYPES — see the note there for why that coupling is mandatory.

Source code in ontometer_corpus/pipeline/parse.py
def compute_content_hash(graph: rdflib.Graph) -> str:
    """
    Compute a stable content fingerprint for deduplication.

    Algorithm:
      1. Collect all non-blank-node subjects declared as one of
         _CLASS_TYPES + _PROPERTY_TYPES.
      2. Sort the IRI strings lexicographically.
      3. Join with newlines, encode UTF-8, SHA-256.

    Blank nodes are excluded because they vary across serialisations of the
    same logical ontology.

    The type list is shared with class_count/property_count via _CLASS_TYPES /
    _PROPERTY_TYPES — see the note there for why that coupling is mandatory.
    """
    iris: set[str] = set()

    for rdf_type in _CLASS_TYPES + _PROPERTY_TYPES:
        for s in graph.subjects(RDF.type, rdf_type):
            if isinstance(s, URIRef):
                iris.add(str(s))

    canonical = "\n".join(sorted(iris))
    return text_hash(canonical)

extract_metadata(graph, source_id=None)

Extract all parse (Phase 1) metadata fields from a parsed rdflib Graph.

Returns a dict with keys matching corpus_registry columns, plus the transient structural keys (subclass_edges, entities) that parse_worker diverts to the sidecar rather than the DB.

source_id is optional and used only to recover an ontology IRI the file itself never declares — see _registry_declared_iri.

Source code in ontometer_corpus/pipeline/parse.py
def extract_metadata(graph: rdflib.Graph, source_id: str | None = None) -> dict:
    """
    Extract all parse (Phase 1) metadata fields from a parsed rdflib Graph.

    Returns a dict with keys matching corpus_registry columns, plus the
    transient structural keys (subclass_edges, entities) that parse_worker
    diverts to the sidecar rather than the DB.

    source_id is optional and used only to recover an ontology IRI the file
    itself never declares — see _registry_declared_iri.
    """
    onto_subject = _detect_ontology_iri(graph)

    ontology_iri: str | None = _uri_or_none(onto_subject) if onto_subject else None

    # Fall back to the registry's declared IRI when the file declares none of
    # its own. Recorded as 'registry' rather than 'declared' so a derived
    # identity is never mistaken for one the artifact actually asserts.
    iri_source = "declared" if ontology_iri else None
    if not ontology_iri:
        ontology_iri = _registry_declared_iri(source_id)
        if ontology_iri:
            iri_source = "registry"
    ontology_version_iri: str | None = None
    ontology_version_info: str | None = None

    if onto_subject is not None:
        # owl:versionIRI
        for obj in graph.objects(onto_subject, _OWL_VERSION_IRI):
            if isinstance(obj, URIRef):
                ontology_version_iri = str(obj)
                break
        # owl:versionInfo
        ontology_version_info = _first_literal(graph, onto_subject, _OWL_VERSION_INFO)

    # Licences come from every header subject, not only onto_subject, which
    # skips the file: IRI that `<> a owl:Ontology` resolves to.
    headers = sorted(
        {s for t in _HEADER_TYPES for s in graph.subjects(RDF.type, URIRef(t))}, key=str
    )
    licence = _licence_values(
        o
        for s in headers
        for p in sorted(LICENCE_PREDICATES)
        for o in sorted(graph.objects(s, URIRef(p)), key=str)
        if not isinstance(o, BNode)  # a blank node's label differs on every parse
    )

    # Metrics
    triple_count = len(graph)

    class_iris: set[str] = set()
    for rdf_type in _CLASS_TYPES:
        for s in graph.subjects(RDF.type, rdf_type):
            if isinstance(s, URIRef):
                class_iris.add(str(s))

    # _PROPERTY_TYPES includes rdf:Property: plain RDF/RDFS vocabularies
    # predating OWL conventions declare their terms `a rdf:Property` only, so
    # counting owl:* property types alone would report zero properties for
    # them. compute_content_hash counts the same set, so the dedup guard stays
    # valid.
    property_iris: set[str] = set()
    for rdf_type in _PROPERTY_TYPES:
        for s in graph.subjects(RDF.type, rdf_type):
            if isinstance(s, URIRef):
                property_iris.add(str(s))

    individual_iris: set[str] = set()
    for s in graph.subjects(RDF.type, _OWL_NAMED_IND):
        if isinstance(s, URIRef):
            individual_iris.add(str(s))

    typed_iris: set[str] = set()
    skos_concept_iris: set[str] = set()
    for s, o in graph.subject_objects(RDF.type):
        if isinstance(s, URIRef) and isinstance(o, URIRef) and _is_instance_type(str(o)):
            typed_iris.add(str(s))
            if str(o) == _SKOS_CONCEPT_IRI:
                skos_concept_iris.add(str(s))
    headers = {str(s) for s in graph.subjects(RDF.type, _OWL_ONTOLOGY) if isinstance(s, URIRef)}

    imports: list[str] = []
    if onto_subject is not None:
        for obj in graph.objects(onto_subject, _OWL_IMPORTS):
            iri = _uri_or_none(obj)
            if iri:
                imports.append(iri)

    own_ns = _namespaces_of(class_iris | property_iris | individual_iris)
    own_iri_ns = _iri_namespace(ontology_iri)
    if own_iri_ns:
        own_ns.add(own_iri_ns)
    own_ns -= _UNOWNABLE_NAMESPACES
    referenced_ns = _collect_referenced_namespaces_rdflib(graph)

    return {
        "ontology_iri": ontology_iri,
        "iri_source": iri_source,
        "ontology_version_iri": ontology_version_iri,
        "ontology_version_info": ontology_version_info,
        "licence": licence,
        "triple_count": triple_count,
        "class_count": len(class_iris),
        "property_count": len(property_iris),
        **_individual_counts(
            individual_iris, typed_iris, skos_concept_iris, class_iris | property_iris, headers
        ),
        "imports": sorted(imports),
        "content_hash": compute_content_hash(graph),
        "referenced_namespaces": sorted(referenced_ns),
        "own_namespaces": sorted(own_ns),
        "subclass_edges": _collect_subclass_edges(graph),
        "entities": _collect_entities_rdflib(graph),
        "skos_concepts": sorted(skos_concept_iris),
    }

configure_paths(paths)

Point this module's path helpers at paths for the current process.

Source code in ontometer_corpus/pipeline/parse.py
def configure_paths(paths: CorpusPaths | None) -> None:
    """Point this module's path helpers at *paths* for the current process."""
    global _PATHS, _SCRATCH_DIR_CACHE, _SCRATCH_DIR_RESOLVED
    _PATHS = paths
    _SCRATCH_DIR_CACHE = None
    _SCRATCH_DIR_RESOLVED = False

scratch_dir()

Return a disk-backed directory for decompression temp files, or None to fall back to tempfile's platform default (only relevant when no object store is configured, e.g. when parse.py is used outside the normal pipeline).

Source code in ontometer_corpus/pipeline/parse.py
def scratch_dir() -> str | None:
    """
    Return a disk-backed directory for decompression temp files, or None to
    fall back to tempfile's platform default (only relevant when no object
    store is configured, e.g. when parse.py is used outside the normal
    pipeline).
    """
    global _SCRATCH_DIR_CACHE, _SCRATCH_DIR_RESOLVED
    if _SCRATCH_DIR_RESOLVED:
        return _SCRATCH_DIR_CACHE

    try:
        scratch = _current_paths().scratch_dir
        scratch.mkdir(parents=True, exist_ok=True)
        _SCRATCH_DIR_CACHE = str(scratch)
    except (MissingStore, OSError):
        _SCRATCH_DIR_CACHE = None

    _SCRATCH_DIR_RESOLVED = True
    return _SCRATCH_DIR_CACHE

estimate_real_size(filepath)

Cheaply estimate a file's decompressed size without fully decompressing it, so oversized archives route to the streaming parser and run_parse's scheduling sort reflects actual parse cost rather than on-disk size. Returns (estimated_bytes, kind, zip_member_name_or_None).

Source code in ontometer_corpus/pipeline/parse.py
def estimate_real_size(filepath: Path) -> tuple[int, str, str | None]:
    """
    Cheaply estimate a file's *decompressed* size without fully decompressing
    it, so oversized archives route to the streaming parser and run_parse's
    scheduling sort reflects actual parse cost rather than on-disk size.
    Returns (estimated_bytes, kind, zip_member_name_or_None).
    """
    try:
        with open(filepath, "rb") as f:
            sig = f.read(4)
    except OSError:
        return 0, "plain", None

    if sig.startswith(b"PK\x03\x04"):
        try:
            with zipfile.ZipFile(filepath, "r") as z:
                member = _pick_zip_member(z.namelist())
                if member is None:
                    return 0, "zip", None
                return z.getinfo(member).file_size, "zip", member
        except zipfile.BadZipFile:
            return filepath.stat().st_size, "plain", None
    elif sig.startswith(b"\x1f\x8b"):
        size = _gzip_real_size(filepath)
        return (size if size is not None else filepath.stat().st_size), "gzip", None
    elif sig.startswith(b"BZh"):
        # No cheap trailer for bzip2 — on-disk size underestimates the real
        # size, but it's the best O(1) signal available.
        return filepath.stat().st_size, "bzip2", None

    try:
        return filepath.stat().st_size, "plain", None
    except OSError:
        return 0, "plain", None

open_content_stream(filepath, kind, zip_member)

Open a fresh, from-byte-zero binary stream over the actual (decompressed) content. Returns (stream, extra_handle_to_close_or_None) — the zip case needs the ZipFile itself kept open and closed alongside its member stream.

Source code in ontometer_corpus/pipeline/parse.py
def open_content_stream(filepath: Path, kind: str, zip_member: str | None):
    """
    Open a fresh, from-byte-zero binary stream over the actual (decompressed)
    content. Returns (stream, extra_handle_to_close_or_None) — the zip case
    needs the ZipFile itself kept open and closed alongside its member stream.
    """
    if kind == "zip":
        if zip_member is None:
            raise ValueError("ZIP content requires a selected member")
        z = zipfile.ZipFile(filepath, "r")
        return z.open(zip_member), z
    elif kind == "gzip":
        return gzip.open(filepath, "rb"), None
    elif kind == "bzip2":
        return bz2.open(filepath, "rb"), None
    return open(filepath, "rb"), None

ntriples_lines(byte_stream, rdf_format)

Stream byte_stream as canonical N-Triples lines, one triple at a time, so memory stays bounded at any file size. Raises SyntaxError where the input stops being valid rdf_format. Parsing is lenient about malformed IRIs and language tags, which published files carry and the in-memory rdflib path also accepts.

Source code in ontometer_corpus/pipeline/parse.py
def ntriples_lines(byte_stream, rdf_format: RdfFormat) -> Iterator[str]:
    """
    Stream `byte_stream` as canonical N-Triples lines, one triple at a time,
    so memory stays bounded at any file size. Raises SyntaxError where the
    input stops being valid `rdf_format`. Parsing is lenient about malformed
    IRIs and language tags, which published files carry and the in-memory
    rdflib path also accepts.
    """
    if rdf_format == RdfFormat.RDF_XML:
        byte_stream = io.BufferedReader(_ChunkReader(_utf8_xml_chunks(byte_stream)))
    for quad in pyoxigraph.parse(
        input=byte_stream, format=rdf_format, base_iri=_STREAM_BASE_IRI, lenient=True
    ):
        yield f"{quad.subject} {quad.predicate} {quad.object} .\n"

parse_worker(task_info)

Multiprocessing worker function to parse a single ontology file. Does not use/share database connections directly.

The task is (row_id, retrieved_file, store_dir, source_id, file_hash, corpus_dir). It carries both roots alongside the already-resolved file path, because a worker is a separate process: under spawn it re-imports this module with no inherited state, so it configures its own paths from the task rather than assuming the parent's or the environment's. source_id is only consulted to recover an ontology IRI the file itself never declares (see _registry_declared_iri).

Source code in ontometer_corpus/pipeline/parse.py
def parse_worker(
    task_info: tuple[int, str, str | None, str | None, str | None, str],
) -> tuple[int, str, str | None, dict | None, str | None]:
    """
    Multiprocessing worker function to parse a single ontology file.
    Does not use/share database connections directly.

    The task is (row_id, retrieved_file, store_dir, source_id, file_hash, corpus_dir).
    It carries both roots alongside the already-resolved file path, because a
    worker is a separate process: under `spawn` it re-imports this module with
    no inherited state, so it configures its own paths from the task rather
    than assuming the parent's or the environment's. source_id is only consulted to recover an
    ontology IRI the file itself never declares (see _registry_declared_iri).
    """
    row_id, retrieved_file, store_dir, source_id, file_hash, corpus_dir = task_info
    if store_dir:
        configure_paths(CorpusPaths.resolve(corpus_dir=corpus_dir, store_dir=store_dir))
    filepath = Path(retrieved_file)

    if not filepath.exists():
        return row_id, "missing", None, None, "File not found on disk"
    if filepath.stat().st_size == 0:
        return row_id, "fail", None, None, "Empty file"

    real_size, size_kind, zip_member = estimate_real_size(filepath)
    if real_size >= _STREAM_THRESHOLD_BYTES:
        streamed = _parse_worker_streaming(row_id, filepath, size_kind, zip_member)
        if streamed is not None:
            return _finalize_result(streamed, source_id, file_hash)
        # Streaming path didn't recognise the format — fall through to the
        # classic rdflib/custom-parser path below as a last resort.

    temp_filepath = None
    try:
        # Detect archive signatures (ZIP or GZIP)
        with open(filepath, "rb") as f:
            sig = f.read(4)

        # ZIP file
        if sig.startswith(b"PK\x03\x04"):
            import zipfile

            with zipfile.ZipFile(filepath, "r") as z:
                names = z.namelist()
                chosen = _pick_zip_member(names)
                if not chosen:
                    error = (
                        "Zip file is empty"
                        if not names
                        else "Zip file contains no supported ontology member"
                    )
                    return row_id, "unsupported", None, None, error

                suffix = Path(chosen).suffix or ".owl"
                with tempfile.NamedTemporaryFile(
                    suffix=suffix, delete=False, dir=scratch_dir()
                ) as tmpf:
                    tmpf.write(z.read(chosen))
                    temp_filepath = Path(tmpf.name)
                filepath = temp_filepath

        # GZIP file (starts with \x1f\x8b)
        elif sig.startswith(b"\x1f\x8b"):
            import gzip

            suffix = filepath.suffix.lower() or ".owl"
            if suffix == ".gz":
                suffix = filepath.with_suffix("").suffix or ".owl"
            with gzip.open(filepath, "rb") as gf:
                decomp_bytes = gf.read()
            with tempfile.NamedTemporaryFile(
                suffix=suffix, delete=False, dir=scratch_dir()
            ) as tmpf:
                tmpf.write(decomp_bytes)
                temp_filepath = Path(tmpf.name)
            filepath = temp_filepath

        # BZIP2 file (starts with 'BZh')
        elif sig.startswith(b"BZh"):
            import bz2

            suffix = filepath.suffix.lower() or ".owl"
            if suffix == ".bz2":
                suffix = filepath.with_suffix("").suffix or ".owl"
            try:
                decomp_bytes = bz2.decompress(filepath.read_bytes())
            except OSError as exc:
                return row_id, "fail", None, None, f"Error processing bzip2 archive: {exc}"
            with tempfile.NamedTemporaryFile(
                suffix=suffix, delete=False, dir=scratch_dir()
            ) as tmpf:
                tmpf.write(decomp_bytes)
                temp_filepath = Path(tmpf.name)
            filepath = temp_filepath

    except Exception as exc:
        return row_id, "fail", None, None, f"Error processing compressed archive: {exc}"

    # Everything from here on operates on `filepath` (the decompressed temp
    # file, if one was created) — wrapped in try/finally so temp_filepath is
    # always removed, even on an exception type none of the branches below
    # anticipated, and an interrupted parse leaves no decompressed file
    # behind.
    try:
        try:
            raw_bytes = filepath.read_bytes()
        except OSError as exc:
            return row_id, "fail", None, None, f"Error reading file: {exc}"

        # Check if the file is an RSS/Atom feed or Manchester OWL Syntax before attempting RDF parsing
        head = raw_bytes[:10000]  # 10k to check past long license comment headers

        if looks_like_feed(head):
            return row_id, "feed", None, None, "Detected XML RSS/Atom feed instead of ontology"

        # Check for Manchester / Functional OWL Syntax
        head_lower = head.lower()
        is_manchester = False
        is_functional = False

        # If it has Prefix: but no @prefix (Turtle) and is not XML, it's Manchester OWL syntax
        if b"prefix:" in head_lower and b"@prefix" not in head_lower and b"xmlns" not in head_lower:
            is_manchester = True
        elif b"ontology:" in head_lower and b"prefix:" in head_lower:
            is_manchester = True
        elif b"prefix(" in head_lower or head_lower.strip().startswith(b"prefix("):
            is_functional = True

        if is_manchester or is_functional:
            fmt_desc = "Manchester OWL Syntax" if is_manchester else "Functional OWL Syntax"
            return row_id, "unsupported", None, None, f"{fmt_desc} is not natively supported"

        static_imports = _extract_imports(raw_bytes)
        meta = None
        graph = None
        fmt = None
        error = None
        status = "fail"

        # 1. Try rdflib first
        graph, fmt, error = try_rdflib(raw_bytes)
        if graph is not None:
            try:
                meta = extract_metadata(graph, source_id)
                meta["imports"] = sorted(list(set(meta["imports"]).union(static_imports)))
                status = "ok"
            except Exception as exc:
                graph = None
                error = f"Metadata extraction error: {exc}"

        # 2. Try custom parsers
        if graph is None:
            is_obo = (
                b"format-version:" in head_lower
                or b"default-namespace:" in head_lower
                or b"[term]" in head_lower
            )

            if is_obo:
                _, fmt, error, meta = _parse_obo(raw_bytes, filepath.stem)
                if meta is not None:
                    meta["imports"] = sorted(list(set(meta["imports"]).union(static_imports)))
                    status = "ok"
                    graph = True

            else:
                is_owl_xml = (
                    b"<ontology" in head_lower
                    and b"xmlns=" in head_lower
                    and b"rdf:rdf" not in head_lower
                )

                if is_owl_xml:
                    _, fmt, error, meta = _parse_owl_xml(raw_bytes, filepath.stem)
                    if meta is not None:
                        meta["imports"] = sorted(list(set(meta["imports"]).union(static_imports)))
                        status = "ok"
                        graph = True

        # 3. Fall back to owlready2
        if graph is None:
            graph, fmt, error = try_owlready2(raw_bytes, filepath.suffix)
            if graph is not None:
                try:
                    meta = extract_metadata(graph, source_id)
                    meta["imports"] = static_imports
                    status = "ok"
                except Exception as exc:
                    graph = None
                    error = f"Metadata extraction error under owlready2 fallback: {exc}"

        if status != "ok":
            return row_id, "fail", None, None, error or "Unknown parse error"

        return _finalize_result((row_id, status, fmt, meta, None), source_id, file_hash)

    except Exception as exc:
        # Safety net: an unanticipated exception anywhere above must still
        # yield a normal "fail" result rather than propagating out of the
        # worker (which, under ProcessPoolExecutor, would surface from
        # future.result() and crash the entire run_parse batch).
        return row_id, "fail", None, None, f"Unexpected parse error: {exc}"

    finally:
        if temp_filepath and temp_filepath.exists():
            try:
                os.remove(temp_filepath)
            except OSError:
                pass

run_parse(db_path, batch_size=500, max_workers=None, parallel=True, paths=None)

Parse all unparsed rows in corpus_registry.

parallel=True (default) uses a ProcessPoolExecutor with the concurrency and memory-safety measures below. parallel=False processes rows one at a time in the current process instead — useful when a file is suspected of causing runaway CPU/memory (e.g. a ZIP-wrapped ontology that decompresses to hundreds of MB), since it isolates that cost to a single, easily Ctrl+C-able process instead of spreading it across worker processes whose shutdown blocks on in-flight tasks.

Concurrency and memory-safety measures (parallel=True only): - max_workers is capped (see _DEFAULT_MAX_WORKERS) instead of defaulting to os.cpu_count(), bounding peak concurrent RAM. - max_tasks_per_child=1 recycles each worker process after a single file, so memory that the interpreter/native extensions don't return to the OS (common with lxml/owlready2 on large files) can't accumulate across the whole run. - Tasks are sorted by estimated size ascending and submitted in batch_size chunks (each chunk fully drains before the next is submitted), so large ontologies are less likely to land on workers simultaneously and a crash only loses progress within the current chunk. The sort key is the estimated decompressed size (ZIP member size, gzip ISIZE); bzip2 has no cheap size trailer, so a bzip2 file sorts by its on-disk size and can still decompress to something far larger.

Source code in ontometer_corpus/pipeline/parse.py
def run_parse(
    db_path: Path,
    batch_size: int = 500,
    max_workers: int | None = None,
    parallel: bool = True,
    paths: CorpusPaths | None = None,
) -> dict:
    """
    Parse all unparsed rows in corpus_registry.

    parallel=True (default) uses a ProcessPoolExecutor with the concurrency
    and memory-safety measures below. parallel=False processes rows one at a
    time in the current process instead — useful when a file is suspected of
    causing runaway CPU/memory (e.g. a ZIP-wrapped ontology that decompresses
    to hundreds of MB), since it isolates that cost to a single, easily
    Ctrl+C-able process instead of spreading it across worker processes whose
    shutdown blocks on in-flight tasks.

    Concurrency and memory-safety measures (parallel=True only):
      - max_workers is capped (see _DEFAULT_MAX_WORKERS) instead of defaulting
        to os.cpu_count(), bounding peak concurrent RAM.
      - max_tasks_per_child=1 recycles each worker process after a single
        file, so memory that the interpreter/native extensions don't return
        to the OS (common with lxml/owlready2 on large files) can't
        accumulate across the whole run.
      - Tasks are sorted by estimated size ascending and submitted in batch_size
        chunks (each chunk fully drains before the next is submitted), so
        large ontologies are less likely to land on workers simultaneously
        and a crash only loses progress within the current chunk. The sort
        key is the estimated decompressed size (ZIP member size, gzip ISIZE);
        bzip2 has no cheap size trailer, so a bzip2 file sorts by its
        on-disk size and can still decompress to something far larger.
    """
    paths = paths or CorpusPaths.resolve()
    configure_paths(paths)
    print(f"Mode: {'concurrent' if parallel else 'sequential'}")

    conn = get_connection(db_path)
    counts = {"ok": 0, "fail": 0, "missing": 0, "feed": 0, "unsupported": 0}

    pending = conn.execute(
        "SELECT id, retrieved_file, source_id, file_hash FROM corpus_registry "
        "WHERE parse_status IS NULL ORDER BY id"
    ).fetchall()

    total = len(pending)
    print(f"Rows to parse: {total}")

    if total == 0:
        conn.close()
        return counts

    # Resolve each stored path against the object store here, in the parent,
    # so a worker receives an absolute path and never has to know the layout.
    # `retrieved_file` is stored relative to the store root precisely so a
    # corpus captured on one machine can be parsed on another.
    store = str(paths.store_dir) if paths.store_dir else None
    tasks = [
        (
            row["id"],
            str(paths.resolve_object(row["retrieved_file"])),
            store,
            row["source_id"],
            row["file_hash"],
            str(paths.corpus_dir),
        )
        for row in pending
    ]

    def _real_size(task: tuple[int, str, str | None, str | None, str | None, str]) -> int:
        # Estimated *decompressed* size, not on-disk size — a small ZIP/GZIP
        # file can unpack to something far larger than it looks, and sorting
        # by on-disk size would schedule it among the small files.
        try:
            return estimate_real_size(Path(task[1]))[0]
        except OSError:
            return 0

    tasks.sort(key=_real_size)

    if not parallel:
        for completed, task in enumerate(tasks, start=1):
            row_id, status, fmt, meta, error = parse_worker(task)
            filepath = Path(task[1])
            print(f"  [{completed}/{total}] {filepath.name} -> [{status}]", flush=True)
            _record_result(conn, counts, row_id, status, fmt, meta, error)

        conn.close()
        print("\nParse summary:")
        print(f"  ok={counts['ok']}")
        print(f"  fail={counts['fail']}")
        print(f"  feed={counts['feed']}")
        print(f"  unsupported={counts['unsupported']}")
        print(f"  missing={counts['missing']}")
        return counts

    from concurrent.futures import ProcessPoolExecutor, as_completed

    workers = max_workers or _DEFAULT_MAX_WORKERS
    completed = 0

    with ProcessPoolExecutor(max_workers=workers, max_tasks_per_child=1) as executor:
        for batch_start in range(0, total, batch_size):
            batch = tasks[batch_start : batch_start + batch_size]
            futures = {executor.submit(parse_worker, task): task for task in batch}

            for future in as_completed(futures):
                row_id, status, fmt, meta, error = future.result()
                task = futures[future]
                filepath = Path(task[1])
                completed += 1

                print(f"  [{completed}/{total}] {filepath.name} -> [{status}]", flush=True)
                _record_result(conn, counts, row_id, status, fmt, meta, error)

    conn.close()

    print("\nParse summary:")
    print(f"  ok={counts['ok']}")
    print(f"  fail={counts['fail']}")
    print(f"  feed={counts['feed']}")
    print(f"  unsupported={counts['unsupported']}")
    print(f"  missing={counts['missing']}")

    return counts