Skip to content

ontometer_corpus.pipeline.db

SQLite corpus registry.

About

Defines the corpus_registry and fetch_attempts table schemas, provides a connection factory, and handles idempotent seeding from manifest.jsonl (Phase 0).

The corpus_registry is the single source of truth for the processing pipeline. One row per ontology file version, covering: - Raw file provenance (from manifest; Phase 0 seed) - Parse status and extracted metadata (Phase 1 parse) - Deduplication decisions (Phase 2 dedup)

The database lives in the corpus directory as <corpus>/corpus.db (see CorpusPaths.db_path).

Columns added after the initial schema are applied to existing databases by _migrate_schema (guarded ALTER TABLE), so additive schema changes never need a re-seed. Registry metadata is projected to a field allowlist before storage, and parse errors are bounded (see MAX_PARSE_ERROR_CHARS).

Attributes

MAX_PARSE_ERROR_CHARS = 2000 module-attribute

Functions:

get_connection(db_path)

Open (or create) the SQLite corpus database.

Returns a connection with: - WAL journal for concurrent read safety - Row factory set to sqlite3.Row (column-name access) - Foreign keys enabled

Source code in ontometer_corpus/pipeline/db.py
def get_connection(db_path: Path) -> sqlite3.Connection:
    """
    Open (or create) the SQLite corpus database.

    Returns a connection with:
    - WAL journal for concurrent read safety
    - Row factory set to sqlite3.Row (column-name access)
    - Foreign keys enabled
    """
    conn = sqlite3.connect(str(db_path), check_same_thread=False)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA foreign_keys=ON")
    return conn

create_schema(conn)

Create all tables and indexes (idempotent — safe to call on every run).

Source code in ontometer_corpus/pipeline/db.py
def create_schema(conn: sqlite3.Connection) -> None:
    """Create all tables and indexes (idempotent — safe to call on every run)."""
    conn.executescript(_DDL)
    conn.commit()
    _migrate_schema(conn)

seed_from_manifest(conn, manifest_path)

Read manifest.jsonl and seed both tables from it:

  • fetch_attempts — EVERY attempt (status ok and fail), so capture rates are queryable. Idempotent via UNIQUE(source_id, retrieval_date, status).
  • corpus_registry — only successful attempts (status == 'ok'), one row per source_id. Idempotent on source_id (re-runs never duplicate rows).

A record without a status field is treated as successful ('ok').

Parameters:

Name Type Description Default
conn Connection

Open SQLite connection with schema already created.

required
manifest_path Path

Path to the manifest.jsonl written by the fetcher orchestrator.

required

Returns:

Type Description
dict

Counts keyed corpus_inserted, corpus_skipped and

dict

attempts_inserted.

Source code in ontometer_corpus/pipeline/db.py
def seed_from_manifest(conn: sqlite3.Connection, manifest_path: Path) -> dict:
    """
    Read manifest.jsonl and seed both tables from it:

      * fetch_attempts — EVERY attempt (status ok and fail), so capture rates
        are queryable. Idempotent via UNIQUE(source_id, retrieval_date, status).
      * corpus_registry — only successful attempts (status == 'ok'), one row
        per source_id. Idempotent on source_id (re-runs never duplicate rows).

    A record without a ``status`` field is treated as successful ('ok').

    Args:
        conn: Open SQLite connection with schema already created.
        manifest_path: Path to the manifest.jsonl written by the fetcher
            orchestrator.

    Returns:
        Counts keyed ``corpus_inserted``, ``corpus_skipped`` and
        ``attempts_inserted``.
    """
    counts = {"corpus_inserted": 0, "corpus_skipped": 0, "attempts_inserted": 0}

    if not manifest_path.exists():
        print(f"  [warn] manifest not found: {manifest_path}")
        return counts

    now = _now()

    # Bad lines are logged with their line number and skipped.
    for rec in iter_jsonl(manifest_path, strict=False):
        source_id = rec.get("source_id", "")
        if not source_id:
            continue

        if rec.get("source_registry", "") in _EXCLUDED_REGISTRIES:
            # Registries excluded from seeding: manifest.jsonl is never
            # truncated or rewritten, so their entries can remain in it.
            # This skip keeps them out of fetch_attempts / corpus_registry.
            continue

        status = rec.get("status", "ok")
        retrieval_date = rec.get("retrieval_date", now)

        # ---- fetch_attempts: record every attempt (ok + fail) ----------
        cur = conn.execute(
            """
            INSERT OR IGNORE INTO fetch_attempts (
                source_id, source_registry, canonical_url, status,
                file_hash, retrieved_file, source_version, error,
                retrieval_date, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                source_id,
                rec.get("source_registry", ""),
                redact_secrets(rec.get("canonical_url", "")),
                status,
                rec.get("file_hash") or None,
                rec.get("retrieved_file") or None,
                rec.get("source_version") or None,
                # A manifest written before redaction can hold keys in URLs.
                redact_secrets(rec.get("error")) or None,
                retrieval_date,
                now,
            ),
        )
        if cur.rowcount:
            counts["attempts_inserted"] += 1

        # ---- corpus_registry: successful fetches only ------------------
        if status != "ok":
            continue

        retrieved_file = rec.get("retrieved_file", "")
        if not retrieved_file:
            continue

        existing = conn.execute(
            "SELECT id FROM corpus_registry WHERE source_id = ?",
            (source_id,),
        ).fetchone()
        if existing:
            counts["corpus_skipped"] += 1
            continue

        conn.execute(
            """
            INSERT INTO corpus_registry (
                source_id, source_registry, canonical_url,
                retrieved_file, file_hash, source_version, source_version_date,
                retrieval_date,
                source_registry_metadata,
                created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                source_id,
                rec.get("source_registry", ""),
                rec.get("canonical_url", ""),
                retrieved_file,
                rec.get("file_hash") or None,
                rec.get("source_version") or None,
                rec.get("source_version_date") or None,
                retrieval_date,
                # Projected here as well as at fetch time: a manifest may
                # hold the full registry response, and seeding from it must
                # not put that response into the database.
                json.dumps(
                    project_registry_metadata(rec.get("source_registry_metadata", {})),
                    sort_keys=True,
                ),
                now,
                now,
            ),
        )
        counts["corpus_inserted"] += 1

    conn.commit()
    print(
        f"  Manifest seed: corpus +{counts['corpus_inserted']} "
        f"({counts['corpus_skipped']} already present), "
        f"attempts +{counts['attempts_inserted']}"
    )
    return counts

fetch_capture_stats(conn)

Return per-registry fetch capture statistics from fetch_attempts.

Each row has: source_registry, captured, failed, attempts, pct_captured. 'pct_captured' is captured / attempts as a percentage (one decimal place).

Source code in ontometer_corpus/pipeline/db.py
def fetch_capture_stats(conn: sqlite3.Connection) -> list[sqlite3.Row]:
    """
    Return per-registry fetch capture statistics from fetch_attempts.

    Each row has: source_registry, captured, failed, attempts, pct_captured.
    'pct_captured' is captured / attempts as a percentage (one decimal place).
    """
    return conn.execute(
        """
        SELECT
            source_registry,
            SUM(status = 'ok')                                  AS captured,
            SUM(status = 'fail')                                AS failed,
            COUNT(*)                                            AS attempts,
            ROUND(100.0 * SUM(status = 'ok') / COUNT(*), 1)     AS pct_captured
        FROM fetch_attempts
        GROUP BY source_registry
        ORDER BY source_registry
        """
    ).fetchall()

update_parse_ok(conn, row_id, *, parse_format, ontology_iri, ontology_version_iri, ontology_version_info, triple_count, class_count, property_count, individual_count, imports, content_hash, referenced_namespaces=None, own_namespaces=None, iri_source=None, declared_individual_count=None, skos_concept_count=None, licence=None)

Write a successful parse result back to corpus_registry.

Source code in ontometer_corpus/pipeline/db.py
def update_parse_ok(
    conn: sqlite3.Connection,
    row_id: int,
    *,
    parse_format: str,
    ontology_iri: str | None,
    ontology_version_iri: str | None,
    ontology_version_info: str | None,
    triple_count: int,
    class_count: int,
    property_count: int,
    individual_count: int,
    imports: list[str],
    content_hash: str | None,
    referenced_namespaces: list[str] | None = None,
    own_namespaces: list[str] | None = None,
    iri_source: str | None = None,
    declared_individual_count: int | None = None,
    skos_concept_count: int | None = None,
    licence: list[str] | None = None,
) -> None:
    """Write a successful parse result back to corpus_registry."""
    now = _now()
    conn.execute(
        """
        UPDATE corpus_registry SET
            parse_status          = 'ok',
            parse_error           = NULL,
            parse_date            = ?,
            parse_format          = ?,
            ontology_iri          = ?,
            ontology_version_iri  = ?,
            ontology_version_info = ?,
            triple_count          = ?,
            class_count           = ?,
            property_count        = ?,
            individual_count      = ?,
            declared_individual_count = ?,
            skos_concept_count    = ?,
            imports               = ?,
            content_hash          = ?,
            referenced_namespaces = ?,
            own_namespaces        = ?,
            iri_source            = ?,
            licence               = ?,
            updated_at            = ?
        WHERE id = ?
        """,
        (
            now,
            parse_format,
            ontology_iri,
            ontology_version_iri,
            ontology_version_info,
            triple_count,
            class_count,
            property_count,
            individual_count,
            declared_individual_count,
            skos_concept_count,
            json.dumps(imports),
            content_hash,
            json.dumps(referenced_namespaces) if referenced_namespaces is not None else None,
            json.dumps(own_namespaces) if own_namespaces is not None else None,
            iri_source,
            json.dumps(licence) if licence is not None else None,
            now,
            row_id,
        ),
    )
    conn.commit()

update_parse_fail(conn, row_id, error)

Write a parse failure back to corpus_registry.

Source code in ontometer_corpus/pipeline/db.py
def update_parse_fail(
    conn: sqlite3.Connection,
    row_id: int,
    error: str,
) -> None:
    """Write a parse failure back to corpus_registry."""
    now = _now()
    conn.execute(
        """
        UPDATE corpus_registry SET
            parse_status = 'fail',
            parse_error  = ?,
            parse_date   = ?,
            updated_at   = ?
        WHERE id = ?
        """,
        (_clamp_error(error), now, now, row_id),
    )
    conn.commit()

update_parse_feed(conn, row_id, error)

Write a feed parse status back to corpus_registry.

Source code in ontometer_corpus/pipeline/db.py
def update_parse_feed(
    conn: sqlite3.Connection,
    row_id: int,
    error: str,
) -> None:
    """Write a feed parse status back to corpus_registry."""
    now = _now()
    conn.execute(
        """
        UPDATE corpus_registry SET
            parse_status = 'feed',
            parse_error  = ?,
            parse_date   = ?,
            updated_at   = ?
        WHERE id = ?
        """,
        (_clamp_error(error), now, now, row_id),
    )
    conn.commit()

update_parse_unsupported(conn, row_id, error)

Write an unsupported parse status back to corpus_registry.

Source code in ontometer_corpus/pipeline/db.py
def update_parse_unsupported(
    conn: sqlite3.Connection,
    row_id: int,
    error: str,
) -> None:
    """Write an unsupported parse status back to corpus_registry."""
    now = _now()
    conn.execute(
        """
        UPDATE corpus_registry SET
            parse_status = 'unsupported',
            parse_error  = ?,
            parse_date   = ?,
            updated_at   = ?
        WHERE id = ?
        """,
        (_clamp_error(error), now, now, row_id),
    )
    conn.commit()

update_duplicate(conn, row_id, canonical_entry_id)

Mark a row as a duplicate pointing to the canonical winner.

Source code in ontometer_corpus/pipeline/db.py
def update_duplicate(
    conn: sqlite3.Connection,
    row_id: int,
    canonical_entry_id: int,
) -> None:
    """Mark a row as a duplicate pointing to the canonical winner."""
    now = _now()
    conn.execute(
        """
        UPDATE corpus_registry SET
            is_duplicate       = 1,
            canonical_entry_id = ?,
            updated_at         = ?
        WHERE id = ?
        """,
        (canonical_entry_id, now, row_id),
    )
    conn.commit()

reset_parse_state(conn)

Clear every parse- and dedup-derived column so the next parse re-reads all rows.

Seeded columns and structural sidecars are kept; sidecars are write-once per file hash. Returns the number of rows reset.

Source code in ontometer_corpus/pipeline/db.py
def reset_parse_state(conn: sqlite3.Connection) -> int:
    """Clear every parse- and dedup-derived column so the next parse re-reads all rows.

    Seeded columns and structural sidecars are kept; sidecars are write-once per
    file hash. Returns the number of rows reset.
    """
    assignments = ", ".join(f"{c} = NULL" for c in _PARSE_COLUMNS)
    cur = conn.execute(
        f"UPDATE corpus_registry SET {assignments}, "
        "is_duplicate = 0, is_latest_version = 0, shared_iri = 0"
    )
    conn.commit()
    return cur.rowcount

log_dedup_exclusion(log_path, source_id, reason, detail='')

Append a record of a row that was excluded (or only partially covered) by a dedup identity check, so there's a durable trail even though the exclusion itself only shows as an absence in corpus_registry.

Used for: rows with zero classes/properties excluded from Pass B's content-hash grouping (dedup.py).

Source code in ontometer_corpus/pipeline/db.py
def log_dedup_exclusion(log_path: Path, source_id: str, reason: str, detail: str = "") -> None:
    """
    Append a record of a row that was excluded (or only partially covered) by
    a dedup identity check, so there's a durable trail even though the
    exclusion itself only shows as an absence in corpus_registry.

    Used for: rows with zero classes/properties excluded from Pass B's
    content-hash grouping (dedup.py).
    """
    with log_path.open("a", encoding="utf-8") as f:
        f.write(f"{_now()}\t{source_id}\t{reason}\t{detail}\n")