Skip to content
Tech Interview Prep
Technical interview guide

Biological Databases & Ontologies

The major public repositories a computational biologist works against daily (NCBI/GenBank, Ensembl, UniProt, and Gene Ontology) what each holds and how they cross-reference each other.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Current NCBI E-utilities and data policies; Ensembl release 116; UniProt, RCSB PDB, Gene Ontology, OBO Foundry, Sequence Ontology, HGNC, Identifiers.org and OLS guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Design and defend a knowledge-data workflow for namespaced accessions.

Answer

Core answer (first 90 seconds)

Assume a knowledge base that ingests from several providers, stores entities, and exports to downstream consumers: the same entity arrives under different identifiers and prefixes get deprecated. My design is two-layer identity. The primary key is an internal surrogate that never changes. The external identity is a CURIE: prefix:accession, e.g. HGNC:11998, UniProtKB:P04637, GO:0008150: stored as a unique index next to a version and a resolution timestamp. Every prefix is resolved through a registry (identifiers.org, OBO Foundry PURLs, Bioregistry) at ingest time; nothing is hardcoded. That gives stable joins internally and portable identity at the boundary.

Workflow

  1. Ingest and normalize (pipeline). Reject anything failing the CURIE regex ^[A-Za-z][A-Za-z0-9._-]*:[A-Za-z0-9._:-]+$. Trim whitespace, lowercase the prefix, preserve accession case.
  2. Registry lookup (pipeline). Prefix → namespace, expected entity type, URL pattern, status (active / deprecated / replaced-by).
  3. Type and species check. The resolved record's entity type must match the expected type, and its taxid must match the expected taxid (9606 for human).
  4. Version pin. Store accession + provider version + resolution timestamp + registry snapshot hash.
  5. Resolve and cache. Fetch via the registry URL, cache with a TTL, fall back to the stored snapshot when the provider is down.
  6. Store. Surrogate PK, CURIE unique index, version column.
  7. Monitor. Unresolved rate, deprecated-prefix count, resolver error rate.

Trade-offs

optionstabilityreadableresolution costcollision riskuse it for
compact CURIE HGNC:11998prefix can be deprecatedhighone registry lookuplow if registry-checkedstorage, joins, APIs
URI https://identifiers.org/hgnc:11998host can movemediumnone, self-resolvinglowcitations, exports, RDF
internal surrogate 8812never changesnonenonenoneprimary key, foreign keys

Defense: CURIE is the stored external identity because it survives a host change; the URI is generated only at export; the surrogate is the PK because prefixes do get deprecated and you do not want to rewrite foreign keys when they do. If your consumers are all RDF, invert this and store the URI, accepting that a provider host move becomes a migration.

Failure modes

failuremechanismdetection
namespace collisiontwo registries register the same prefix for different entity typesregistry lookup returns >1 namespace, or resolved entity type ≠ expected
deprecated prefixregistry marks the prefix replaced-by anotherregistry status field = deprecated
wrong speciesaccession is valid but from another organismtaxid on record ≠ expected taxid
URL stored as identityprovider changes host, key breakskey fails the CURIE regex
provider outageresolver returns 5xx or times outresolver error rate; fall back to snapshot
spreadsheet coercionExcel turns 1-2 into a date, long digits into 1.23E+15round-trip test on ingest

Trace

Ingest P04637 → prefix uniprotkb → registry returns namespace, entity type protein, URL pattern → resolve → record taxid 9606, expected 9606 → store surrogate 8812, curie UniProtKB:P04637, version from the provider, resolved_at now. Later the provider moves its host: the CURIE is unchanged, only the registry URL pattern changes, and the snapshot keeps reads working until the next successful resolve.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and defend a knowledge-data workflow for record versions.

Answer

Clarify first

The question doesn't name a domain, so I'd pin it before designing. I'll assume a reference knowledge base of sequence records plus derived annotations, ~10^8 records, ~10^5 new versions/day, consumers are analysis pipelines and search indexes, and past analyses must be reproducible. If reproducibility isn't required, the design collapses to a much cheaper one: I'll say where.

Core design

Split identity from content. An accession is stable and names the record; a version is immutable and names one exact byte sequence. A version is never edited: a change mints version N+1 as a new object.

Every version row carries: accession, version, sha256 of the canonical serialization, release date, provenance (source + pipeline version), and a tombstone flag. Writes go to an immutable blob store; a separate mutable table holds the latest pointer per accession.

The read API has two endpoints and they are not interchangeable:

  • get(accession, version): pinned, reproducible.
  • resolve_latest(accession): returns the version it resolved, so the caller can log it.

Derived artefacts (indexes, coordinate maps, annotations) store source_accession, source_version, source_checksum. A version bump produces a new artefact keyed by version; it does not invalidate the old one in place. Retirement writes a tombstone, never a delete.

Defence and alternatives

  • Mutable-in-place + audit log. Cheaper storage, but a reader mid-update sees torn state. Only safe with a single writer and readers that tolerate it.
  • Pure content-addressed store, no accession. Dedupes identical content, but loses the "same record over time" lineage reviewers need.
  • Event-sourced log. Full replayable history, but the read path still needs a materialized view, so you pay both costs.

Deciding criterion: does any consumer need to reproduce a past analysis? If yes, pinning is mandatory and the alternatives are non-starters. If no, mutable-in-place is fine.

Failure modes and detection

FailureDetection
Version stripped at ingestRecompute checksum on read; nightly reconciliation job flags mismatch
Mutable latest read twice in one runLog resolved version per pipeline stage; assert equality
Annotation/sequence version confusionCoordinate bounds check against sequence length
Retired record served as emptyTombstone metric; return 410, not 200-empty
Checksum omittedReject null checksum at write
Stale cacheCache key must include version; TTL only on the latest pointer

Worked trace

Record NC_000001.10 gets a corrected base at position 5000.

  1. Ingest mints NC_000001.11, computes new sha256, writes blob.
  2. latest pointer flips 10 → 11. Version 10 blob is untouched.
  3. A pipeline that pinned .10 keeps reading .10; its annotation artefact still cites .10.
  4. A pipeline that called resolve_latest logs 11 and rebuilds its artefact under .11.
  5. Nightly job recomputes hashes for both; both match.

Arithmetic (hypothetical)

10^8 records × 5 versions × 3 KB ≈ 1.5 TB of blobs. Checksums at 32 bytes × 5×10^8 ≈ 16 GB. Keeping every version is cheap relative to the sequences; GC only unreferenced artefacts, not versions.

What a strong candidate says in 90 seconds

"Stable accession, immutable version, checksum on every version, pinned reads by default, latest as an explicit separate call that returns what it resolved, derived artefacts keyed by source version, tombstones not deletes. I'd defend it against mutable-in-place and pure content-addressing by asking whether past analyses must reproduce, if they must, pinning is the only option."

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Design and defend a knowledge-data workflow for gene symbols.

Answer

Assumptions: human data is primary, but mouse data arrives from collaborators; sources are spreadsheets, PDFs and a LIMS; historical reports must stay reproducible. HGNC is human-only and releases monthly.

Core answer. Key on the HGNC ID, never on the symbol. Capture the symbol exactly as written, resolve it through a ladder, store the mapping next to the HGNC release it was resolved against, and resolve at read time so a 2019 report still prints the symbol it was written with.

  1. Ingest: store symbol_as_written, species, source, source_date. Never normalise case on write.
  2. Resolve: ladder below.
  3. Store: canonical row keyed on hgnc_id with approved_symbol, status, locus_group, prev_symbols[], alias_symbols[]; plus an append-only symbol_mapping(source_symbol, hgnc_id, method, hgnc_release, valid_from).
  4. Serve: join facts to hgnc_id, render the symbol from the mapping row valid at the report's date.

Why: symbols are labels, not identifiers. HGNC changes them (SEPT1 → SEPTIN1 and MARCH1 → MARCHF1 in 2020, both to stop Excel reading them as dates), retires them, and reuses them as aliases for other genes. The ID is the only thing that survives.

stepqueryhitaction
1symbol1accept, method=symbol
2alias_symbol1accept, flag alias_used
3prev_symbol1accept, flag renamed
4withdrawn list1quarantine, do not load
—any step>1quarantine as collision
—all steps0quarantine as unresolved
Python
# Python 3.11, requests 2.31
import requests
BASE = "https://rest.genenames.org"

def resolve(symbol, species="human"):
    if species != "human":
        return None, "not_hgnc"          # route to MGI / RGD
    for field in ("symbol", "alias_symbol", "prev_symbol"):
        r = requests.get(f"{BASE}/fetch/{field}/{symbol}",
                         headers={"Accept": "application/json"}, timeout=5)
        r.raise_for_status()
        docs = r.json()["response"]["docs"]
        if len(docs) == 1:
            return docs[0]["hgnc_id"], field
        if len(docs) > 1:
            return None, f"collision:{field}"
    return None, "unresolved"

Trace: resolve("TP53") hits step 1 and returns ("HGNC:11998", "symbol"). resolve("p53") misses step 1, hits step 2 and returns ("HGNC:11998", "alias_symbol"). resolve("Trp53", species="mouse") returns (None, "not_hgnc").

Trade-offs. HGNC ID is human-only, curated and stable across monthly releases: the right canonical key for human. Ensembl ENSG is stable per gene but tied to an assembly and annotation version, so it is a join key, not a primary key. NCBI Gene ID is cross-species, so if mouse data is first-class, key on NCBI Gene ID or a local surrogate with species-qualified cross-references. Write-time resolution is one lookup and fast, but bakes in the release and cannot be corrected; read-time resolution keeps history reproducible but needs an indexed mapping table and a cache. Use write-time capture plus read-time resolution.

Failure modes, with detection.

  • Alias collision: a symbol approved for one gene is an alias for another, so step 2 returns more than one doc. Detection: the ladder returns collision:alias_symbol; quarantine and require a curator. Cost: a silent many-to-one join that merges two genes' expression rows.
  • Withdrawn symbol: HGNC status Entry Withdrawn. Detection: check status on the resolved record and diff against withdrawn.txt each release. Cost: reporting on a gene that no longer exists.
  • Excel conversion: MARCH1 becomes 1-Mar on save. Detection: regex ^\d{1,2}-(Jan|Feb|Mar|...)$ over every symbol column on ingest, plus a round-trip write/read test. Cost: silent row loss.
  • Mouse/human confusion: mouse Trp53 versus human TP53. Detection: human symbols are all-caps; flag any title-case symbol in a human table. Cost: cross-species joins.
  • Capitalisation loss: a case-insensitive collation makes SEPT1 and Sept1 the same key. Detection: store symbols in a case-sensitive column (utf8mb4_bin, COLLATE "C") and assert a round-trip.
  • Historical report rewritten: re-resolving at read time without pinning the release. Detection: hash the rendered report; if the hash changes with no data change, the mapping moved.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How should CURIEs, URIs, and persistent identifiers be structured to prevent namespace collisions and maintain stable entity resolution across biological databases?

Answer

Core answer

Don't make URLs your primary keys. Store a normalized CURIE, prefix:accession, as the canonical key, validate the accession against the registry's regex at ingestion, and expand to a URI only at the presentation edge. Pin the prefix map to a version and record that version alongside each identifier, so a later registry change can't silently rewrite what an old row meant.

Raw identifier ingestion
  "GO:0008150" | "http://purl.obolibrary.org/obo/GO_0008150" | "go:GO:0008150"
       |
       v
Registry validation & decomposition (Identifiers.org / Bioregistry / OBO Foundry)
  - strip redundant embedded prefix ("go:GO:0008150" -> accession "0008150")
  - validate accession against registry regex (GO: ^\d{7}$)
  - map namespace synonym to canonical prefix ("go" -> "go")
       |
       v
Canonical storage form: go:0008150   (+ raw string, + registry version hash)
       |
       v
URI expansion, lazily, at the edge
  - OWL / Semantic Web: http://purl.obolibrary.org/obo/GO_0008150
  - Resolvable web URL:  https://identifiers.org/GO:0008150

Trade-offs: what else you could key on

SchemeSurvives domain/PURL changeCarries authorityCross-database joinWhat it costs you
Registry-governed CURIE (go:0008150)Yes, if the prefix map is pinnedYes: authority + accessionYes, when both sides use the same registryRegistry drift, banana prefixes, regex upkeep
Opaque UUID + mapping tableYesNoOnly through your own resolverYou own the lookup service; no external tool can dereference it
LSID (urn:lsid:...)Yes by designYesIn principleResolver infrastructure is largely unmaintained; few clients
Hash of the canonical string (e.g. SHA-256)Yes, for identical contentNoDedup onlyAny content edit mints a new ID
Plain URI as the keyNoYesYesBreaks the day the domain or PURL retires

When registry-governed CURIEs are the wrong choice

  • Single-authority internal data with no external joins: an integer PK or a plain URI is enough; the registry buys you nothing.
  • Entities no registry covers (you mint them): use a local prefix you control and keep it out of the shared namespace until you register it.
  • Legacy accessions the registry regex rejects: keep the raw string in a quarantine column rather than dropping the row.
  • Hot-path joins at scale: expanding a CURIE to a URI per row is a network call. Materialize the canonical CURIE once and join on that.

Implementation requirements

  1. Namespace normalization. Prefixes resolve against a centralized, versioned registry schema: uniprot, UniProtKB, and uniprot.org collapse to one internal prefix key.
  2. Banana prefixes. Resources embed their namespace in the accession (CHEBI:15377, HGNC:1100, GO:0008150), so a naive join yields chebi:CHEBI:15377. Store prefix and accession separately, or strip a leading prefix:/prefix_ when the remainder already begins with the same prefix, case-insensitively, repeating until the form is idempotent.
  3. Pattern validation. Reject at the ingestion boundary when the accession fails the registry regex: Ensembl genes ^ENS[A-Z]*G\d{11}(\.\d+)?$, PDB ^[0-9][A-Za-z0-9]{3}$.
  4. Prefix map immutability. Store the raw ingested string, the resolved CURIE, and the registry version hash together. Never call DNS or HTTP during batch processing.
Failure boundaryRoot causePrevention and recovery
Namespace collisionTwo authorities share a prefix (PR for Protein Ontology vs PRIDE)Explicit prefix governance table mapped to registry authority URLs
Prefix doublingA serializer prefixes an already-namespaced identifier (go:GO:0008150)Regex-driven normalization at parser ingress, applied to idempotence
URI fragilityHardcoded domains move or a provider retiresKey on the CURIE; generate URIs from configuration-driven templates
Case driftJoins fail on UniProtKB:P12345 vs uniprotkb:p12345Lower-case prefixes; preserve canonical accession casing where it is case-sensitive (UniProt, PDB)

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and defend a knowledge-data workflow for identifier mapping.

Answer

What a strong candidate says first. Pin four things before designing anything: source namespace, target namespace, species, and the release of each source. Then ask the consumer one question: does it need a target ID, or the set of target IDs? That answer decides the design, because identifier mapping is a relation, not a function, and most of it is many-to-many.

The workflow, three layers.

  1. Ingest. Pull edges from primary sources at pinned releases: UniProt (releases are named 2024_01, 2024_02), Ensembl (numbered, e.g. 112), HGNC, ChEMBL, and store them as an edge table: (source_ns, source_id, target_ns, target_id, relation, source_release, evidence). Store edges, never a pre-resolved single ID. BridgeDb ships prebuilt mapping files in exactly this shape if you don't want to build the ingest yourself; the UniProt ID mapping service and MyGene.info are the hosted alternatives.
  2. Resolve. The API takes a set of IDs plus a declared policy and returns every matching edge with a status: mapped, ambiguous, obsolete, unmapped.
  3. Policy. The caller declares cardinality (one | many) and on_ambiguity (fail | best_hit | all). Policy lives at the call site, not in the table.

Why it behaves this way. The mapping graph is a bipartite multigraph. Gene→transcript→protein is 1:many, protein→gene is many:1, orthology is many:many. So "one ID in, one ID out" is always a policy decision; hide it in the loader and every downstream count inherits it silently.

Trade-offs.

policyreturnsgood forbreaks when
allevery target + statusenrichment, network analysiscounts inflate
best_hitone target, rankeddisplay, single-ID joinsranking is arbitrary and silent
one_to_oneonly 1:1 edgesstrict joinsdrops most of the graph

Deciding criterion: if the consumer aggregates (counts, sums, joins to a fact table) use all and dedupe explicitly. If it displays, best_hit is fine, but log the discarded candidates.

Worked trace. Edge list for one gene, in insertion order:

Python
edges = [
    ("ENSG00000146648", "P00533",   "canonical"),
    ("ENSG00000146648", "P00533-2", "isoform"),
    ("ENSG00000146648", "P00533-3", "isoform"),
]

def resolve(gene, edges, policy):
    hits = [t for (s, t, rel) in edges if s == gene]
    if policy == "all":        return hits
    if policy == "best_hit":   return hits[:1]
    if policy == "one_to_one": return [t for (s, t, rel) in edges
                                       if s == gene and rel == "canonical"]

resolve("ENSG00000146648", edges, "all") → ['P00533', 'P00533-2', 'P00533-3']. best_hit → ['P00533'], but only because the canonical edge happens to be first; shuffle edges and it returns P00533-3. one_to_one → ['P00533']. Summed over a proteome, all and one_to_one differ by the isoform multiplicity: illustrative, but that gap is the count inflation people ship.

Failure modes and how to detect them.

  • First-hit selection. hits[:1] is order-dependent. Detect: rerun against a shuffled edge list; if the answer moves, the ranking isn't deterministic.
  • Isoform loss. Collapsing to canonical drops P00533-2/-3. Detect: compare all vs one_to_one counts per gene.
  • Cross-species leakage. Ortholog edges belong in their own namespace; a mouse Ensembl ID in a human column is a silent join failure. Detect: assert the namespace prefix on every ID.
  • Merged and obsolete IDs. UniProt keeps the retired accession as a secondary accession on the merged entry, so a lookup still resolves, but only if you ingest secondary accessions. Detect: query a known-retired accession and require obsolete plus a redirect. Splits are the asymmetric case; check the release notes.
  • Duplicate expansion. Joining edges to a fact table without deduping triples a 3-isoform gene's rows. Detect: row count before and after the join.
  • Many-to-many inflation. Same root cause, different symptom. Detect: compare COUNT(*) against COUNT(DISTINCT target_id).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design and defend a knowledge-data workflow for archive and knowledgebase.

Answer

Assumptions. A research knowledgebase: ~50k submissions/month, ~2 MB each, 3 curators, downstream services query it with a 50 ms p99 budget, releases ship monthly. Evidence is immutable once submitted; interpretations change. If your KB is a wiki nobody queries programmatically, most of this is overkill.

Core answer. Split the system into two stores with different write rules, and make the knowledgebase a build product of both.

  1. Archive: append-only, content-addressed. Every submission gets a monotonic accession, the submitter identity, and a SHA-256 of the payload; the object is written under object-lock (WORM) so it cannot be overwritten. Nothing here is ever edited.
  2. Curation store: append-only assertions. An assertion is (accession set, method, curator, timestamp, confidence, review status). A correction is a new assertion that supersedes the old one; the old row stays.
  3. Release: a manifest pinning a set of assertion versions and an evidence release id, with hashes. Downstream reads only releases, never the live curation tables.

Why it behaves that way. Evidence answers "what was submitted"; an assertion answers "what we concluded, by what method, on what date". Those have different lifecycles: evidence never changes, conclusions do. Keeping them in one mutable table means a curator's edit silently rewrites history, and you can no longer answer "what did we believe on 2024-03-01, and on what evidence?", which is the question auditors, downstream models, and your own incident reviews actually ask. The release manifest is what makes an answer reproducible: same manifest hash, same answer.

Alternatives. A single table with a current boolean is simpler and fine if you never need point-in-time answers. Full event sourcing gives the same audit trail but pushes reconstruction cost onto every read; the release-manifest approach pays it once per month. Bitemporal tables (valid-time + transaction-time) are the right call when you must query "as of" arbitrary dates interactively: more schema, more index cost.

Failure modes and detection.

failuredetection
curation treated as experiment (method changes mid-stream)method-version field; drift report when a curator's method changes without a new assertion
circular validation (KB used to validate the evidence that produced it)dependency check at release build: no assertion's evidence set may contain a KB-derived record
stale interpretationjoin assertion.release against latest evidence release per accession; alert when behind
submitter errorcross-submitter concordance; single-submitter assertions flagged, not silently trusted
missing evidencereferential integrity at release build; build fails, release does not ship
mixed releasesmanifest hash check at query time; mismatch is a hard error, not a warning

Artefact. The release manifest is the contract:

JSON
{
  "release_id": "kb-2024-06",
  "evidence_release": "ev-2024-06",
  "assertions": [{"id": 88123, "version": 4, "sha256": "..."}],
  "manifest_sha256": "..."
}

Storage arithmetic (illustrative): 50k × 2 MB = 100 GB/month raw; five years ≈ 6 TB; at S3 Standard's $0.023/GB-month that's ≈ $138/month before curation, which is noise next to the cost of an unreproducible answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and defend a knowledge-data workflow for ontology DAGs.

Answer

Core answer. Treat the ontology as a versioned edge set, not a tree. Pipeline: extract (child, relation, parent) triples from the source release → validate with a topological sort → store edges plus a materialized closure table in Postgres → serve ancestor/descendant queries through a recursive CTE that carries a path array for cycle safety and DISTINCT for diamond dedup. Defend the closure table over a live recursive CTE when reads dominate writes; keep the CTE as the fallback for same-day ontology edits.

Assumptions I'd state up front: multiple inheritance is real (a term has several parents), relation types are semantically distinct (is-a vs part-of) and must never be collapsed, and the release cadence is daily. Figures below are an illustrative scale (500k nodes, 2M edges, average 50 ancestors per node, max depth 12) not a specific vendor's numbers.

Stages.

  1. Extract. Parse OWL/RDF with rdflib 7.x (or OWL API 5 for Java shops) and emit one row per edge, keeping relation as a column, never folding part-of into is-a. Collapsing them silently changes inference: a part-of edge is not a subclass edge.
  2. Validate. Run Kahn's algorithm. If nodes remain after the queue drains, they sit on a cycle: quarantine the release, don't load it. This is the only cheap place to catch a bad extension.
  3. Store. Two tables:
SQL
edge(child_id, relation, parent_id, release_id,
     PRIMARY KEY (child_id, relation, parent_id, release_id))
closure(ancestor_id, descendant_id, relation, depth, path_count, release_id)
  1. Query. Ancestors of a node:
SQL
WITH RECURSIVE anc AS (
  SELECT child_id, parent_id, relation, 1 AS depth, ARRAY[child_id] AS path
  FROM edge WHERE child_id = $1 AND release_id = $2
  UNION ALL
  SELECT a.child_id, e.parent_id, e.relation, a.depth + 1, a.path || e.parent_id
  FROM anc a JOIN edge e ON e.child_id = a.parent_id AND e.release_id = $2
  WHERE NOT e.parent_id = ANY(a.path)   -- cycle guard
    AND a.depth < 32                     -- depth cap
)
SELECT DISTINCT parent_id, relation FROM anc;

Trace. Node D has parents B and C; B and C both have parent A. Depth 1 yields B, C. Depth 2 yields A via B and A via C: two rows. DISTINCT collapses them to one A. Drop DISTINCT and any "ancestor count" metric inflates on every diamond, which is most of a real ontology.

Defend the choice.

approachancestor p99 (illustrative)storage @ 500k/2Mdiamondswrite cost
recursive CTE8–40 ms0 extrahandled by DISTINCTnone
closure table1–3 ms~25M rows, ~1 GBpath_count columnrebuild per release
graph DB (Neo4j 5)2–10 ms~2–3× edge storenativenone

Pick the closure table when reads dominate and releases are daily: the ~1 GB and rebuild cost buy a 5–10× latency cut. Pick the recursive CTE when the ontology changes intra-day or storage is tight. A graph DB wins only if you already run one; otherwise it adds an operational surface for no correctness gain.

Failure modes and detection.

  • Diamond double-count: compare COUNT(*) to COUNT(DISTINCT parent_id); alert if the ratio exceeds 1.05.
  • Cycle from a bad extension: Kahn's leftover-node count > 0 at ingest; block the release.
  • Relation mixing: assert relation is never null and group QA counts by relation; a sudden part-of spike means a parser bug.
  • Path-dependent depth: shortest vs longest path give different depths. Fix one definition, store it in depth, and log whenever the depth-32 cap truncates a chain: silent truncation is the failure you won't see in tests.
  • One-parent UI loss: any view that renders a single parent drops the second lineage; detect by asserting rendered parent count equals COUNT(DISTINCT parent_id).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and defend a knowledge-data workflow for relation semantics.

Answer

Scope first. "Relation semantics" is only a question once the graph and the relations are fixed. I'll assume an OBO-style biomedical graph: Gene Ontology plus an anatomy ontology, 10^5–10^6 edges, served through a query API, rebuilt nightly. The thing I'm actually designing is: how do ancestor and descendant queries stay correct when edges carry different relation types. My answer is a per-relation closure pipeline with a declared relation registry, and I'll defend it against the three cheaper alternatives.

The workflow.

  1. Relation registry, versioned, one file. For each relation it declares domain, range, inverse, transitivity, and annotation-propagation policy. is_a: transitive, acyclic, range = class. part_of: transitive, range = structure. located_in: transitive. regulates and develops_from: not transitive. The loader reads this file; no relation name is hardcoded anywhere downstream.

  2. Normalize on ingest. Every edge is stored as (subject, relation, object, source, asserted_at) with direction canonicalized to child→parent. Inverse pairs (part_of/has_part) are stored once and inverted at query time.

  3. Validate before materializing. Domain/range check per edge; is_a must be a DAG, and a cycle rejects the load; every endpoint must resolve to an IRI in the registry, never to a label.

  4. Materialize per relation, never globally. Each transitive relation gets its own closure. Composite inference comes from declared property chains: GO's documented composition table is the model: regulates ∘ part_of → regulates, part_of ∘ part_of → part_of, and regulates ∘ regulates → nothing.

  5. Serve relation-aware ancestors. The query takes a relation set and a chain policy, so "anatomical ancestors via is_a and part_of" is one call and "regulates ancestors" is a different one.

  6. Counterexample suite in CI. Every relation gets a positive and a negative assertion, run against the materialized graph.

Defend. Three alternatives, and why I don't take them. One global transitive closure over all edges is the cheapest to build and produces false ancestors: heart part_of circulatory_system plus a global closure yields heart is_a circulatory_system, which is simply wrong. Query-time property paths (SPARQL wdt:P279*) avoid materialization but pay per query, and WDQS enforces a 60-second query timeout, so deep paths fail under load. Full OWL 2 DL reasoning is complete but expensive and hard to explain when it derives something surprising. I materialize the two or three hot relations and leave the long tail to query-time chains.

Trace. Edges: hand part_of arm, arm part_of body, body part_of organism. Closure adds hand part_of body, hand part_of organism, arm part_of organism. Now add X regulates Y and Y part_of Z: the chain gives X regulates Z. Add Y regulates Z instead, and the correct output is no new edge: that is the negative assertion in CI.

Failure modes, with detection.

FailureSymptomDetection
Direction reversedancestor query returns descendantsinverse-pair invariant check on load
All edges collapsed to is_apart_of count drops to zero in the relation histogramhistogram assertion per load
Partonomy propagated as subsumptionnucleus appears under a cell typedomain/range disjointness: is_a range must be a class
Obsolete term in closurestale ancestor survives a term mergeOBO marks these owl:deprecated true with a replaced_by pointer; assert no obsolete IRI appears in any ancestor set
Cross-ontology collisiontwo "heart" nodes, one ancestor setresolve by IRI namespace, never by label
Label-based guessingedge endpoint is a string, not an IRIregistry lookup on every endpoint

Each of these is a load-time assertion, not a review checklist: the pipeline fails the build rather than shipping a wrong ancestor.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and defend a knowledge-data workflow for synonym scope.

Answer

Assumptions I'd state before designing anything: the corpus is a product knowledge base with a controlled vocabulary, search runs on Elasticsearch 8.x, and the deciding constraint is asymmetric. A wrong merge costs more trust than a missed expansion. A user who searches "car" and gets a truck retypes nothing; they leave. A user who gets zero hits retypes. So the workflow is built to under-expand by default and earn expansion with evidence.

Core answer. Every synonym edge carries two things: a scope and a provenance record. Scope decides how the edge expands at query time. Provenance (source, editor, date, confidence) decides who is allowed to change it. Exact synonyms expand always and rank as if the user typed the canonical term. Broad, narrow and related expand only under a gate, with a lower boost, and never on the default search box. Canonical definitions are what we display; synonyms are only what we match against.

Why the four scopes behave differently. In SKOS terms, skos:altLabel is the exact synonym and skos:broadMatch / narrowMatch / relatedMatch are the rest. The mechanism is direction relative to the query term. Expanding "car" to a narrower term ("sedan") can only add documents that are already about cars: the narrower set is a subset, so it is recall-safe. Expanding to a broader term ("vehicle") adds trucks and motorcycles: possibly relevant, not guaranteed. Related terms ("driving") are tangential by construction. That is the whole reason one policy cannot cover all four.

scopeSKOS relationexpandsboostsurface
exactaltLabelalways1.0default search
narrownarrowMatchalways (subset, safe)0.8default search
broadbroadMatchonly if unexpanded hits < 200.3default search, gated
relatedrelatedMatchnever by default—browse / "related terms" panel

Worked trace (figures hypothetical, 1M-document corpus). Query "car" matches 40,000 docs.

  • Add exact "automobile": 12,000 docs, 9,000 already in the car set → union 43,000 (+7.5%).
  • Add narrow "sedan": 8,000 docs, all inside the car set → union stays 43,000; it re-ranks, it does not widen.
  • Add broad "vehicle": 300,000 docs, 35,000 overlap → union 308,000, a 7.7× jump. On a frozen 200-query set, precision@10 falls from 0.82 to 0.41.
  • Add related "driving": 90,000 docs → union ~370,000.

That is why broad expansion sits behind a recall gate: it only fires when the unexpanded query returns fewer than 20 hits, where the alternative is an empty page.

Failure modes and how each is detected.

  1. False exact match: "Java" the island merged with the language as an altLabel. Detect: sample 50 queries per merged cluster weekly; if more than 10% of clicks land on documents from a disjoint topic cluster, demote the edge to relatedMatch.
  2. Acronym collision: "AC" as air conditioning, alternating current, assistant commissioner. Detect: cluster purity, if a merged cluster's documents split into two groups whose centroids sit below 0.2 cosine similarity, flag for review.
  3. Synonym promoted to canonical ID: an altLabel accidentally given its own concept ID, so one concept has two IDs and its counts split. Detect: nightly check for two concepts sharing three or more altLabels or an identical definition string.
  4. Precision collapse: nDCG@10 on the frozen query set drops more than 5% after any expansion-policy change; roll back automatically.

Trade-offs. Index-time expansion (the synonym token filter, expand: true by default) is cheap at query time but bakes policy into the index: changing a scope means reindexing. Query-time synonym_graph handles multi-word synonyms and lets policy change without a reindex, at the cost of per-query CPU. Default to query-time for broad and related edges, which change often; index-time for exact edges, which are stable. Do not expand at all on identifier-like fields (SKUs, error codes, version strings) where exact match is the only correct behaviour.

Owners and loop. The taxonomy editor owns edges and provenance; the search engineer owns expansion policy; both read the weekly precision report and the cluster-purity flags. A scope change is a reviewed commit, not a config tweak.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and defend a knowledge-data workflow for obsolete terms.

Answer

Core answer (first 90 seconds)

Assume the source is SNOMED CT International Edition (~350,000 active concepts, monthly releases) and the consumers are a FHIR terminology service, a search index, and a claims pipeline. One rule decides the whole design: an obsolete term is never deleted. The concept ID stays, the concept is marked inactive, and the release carries a historical association saying what it became. So the workflow is: ingest the delta, read the inactivation reason and the association, auto-map only the single-valued identity associations, queue everything else for a terminology steward, then propagate through a versioned ConceptMap.

The workflow

  1. Ingest. Load the monthly delta into staging; diff the active concept set against the previous release to get newly inactivated concepts. Owner: platform.
  2. Enrich. Join two refsets: the Concept inactivation indicator (reason: ambiguous, duplicate, erroneous, limited, moved elsewhere, outdated, non-conformance) and the Historical association refset (association type: SAME AS, REPLACED BY, POSSIBLY EQUIVALENT TO, MOVED TO, MOVED FROM, ALTERNATIVE, WAS A). Owner: platform.
  3. Classify and route, per the table. Owner: platform routes, steward decides.
  4. Apply. Never delete. In FHIR, set CodeSystem.concept.inactive = true and attach the association as a concept property; publish a ConceptMap with a version. Owner: platform.
  5. Propagate. Reindex, invalidate caches keyed by release ID, notify downstream owners. Owner: each consumer.
Association typeCardinalityAction
SAME AS1auto-map
REPLACED BY1auto-map
POSSIBLY EQUIVALENT TO1..nreview
ALTERNATIVE1..nreview
MOVED TO / MOVED FROM1update hierarchy, no term map
WAS A1history only, no forward map
none0review, dead end

Worked trace

Concept X is inactivated with reason "outdated" and two POSSIBLY EQUIVALENT TO targets, Y and Z. The classifier sees cardinality 2, so it routes to review. The steward reads the FSNs, picks Y, and records the decision with reviewer ID and date. The ConceptMap gets X → Y with equivalence relatedto, not equivalent. A pipeline that took the first association would have written X → Y as equivalent and silently dropped Z: that is the wrong-replacement failure, and it is invisible until a downstream query returns the wrong concept.

Arithmetic (illustrative)

A monthly release inactivates ~1,000 concepts. If 60% carry a single SAME AS or REPLACED BY, that is 600 auto-mapped. 150 are POSSIBLY EQUIVALENT TO or ALTERNATIVE and 250 have no association. At 20 concepts per steward-hour the queue is 400/20 = 20 hours per release: one steward, half a week. That number decides whether you can afford to review rather than guess.

Trade-offs, and when not to automate

Automate only single-valued identity associations. Do not automate POSSIBLY EQUIVALENT TO or ALTERNATIVE: the terminology authors are explicitly saying the target is a guess. Do not automate when the consumer is lossy: mapping SNOMED CT into a smaller billing code set is many-to-one and the right target depends on the claim, so it needs a human. If the review queue outgrows the release cadence, narrow the auto-map to SAME AS only; do not widen it.

Failure modes and detection

  • History loss: a consumer deletes the row. Detect by replaying last month's codes against the new service; a 404 instead of inactive-plus-association is the signal.
  • Wrong replacement: auto-mapped to a different meaning. Detect with a 5% re-review sample and track the disagreement rate.
  • Label collision: two concepts share a term string, so a text-keyed lookup returns the wrong ID. Detect with a uniqueness constraint on the term index; alert when a newly inactive concept's term collides with an active one.
  • ID reuse: a vendor reuses a retired code. Detect with a nightly assertion that an inactive code never becomes active again.
  • Cache inconsistency: $lookup cached for 24h while the release is monthly. Detect by keying the cache on release ID; a stale hit shows the old mapping.
  • Migration without provenance: a backfill rewrites stored codes with no source. Detect by requiring a provenance column and auditing rows where mapped_code != original_code and provenance is null.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do asserted and inferred class hierarchies differ in OWL DL, and how do reasoners like ELK and HermiT validate subsumption and prevent cycles in biomedical ontologies?

Answer

What I'd say first

I'll assume OWL 2 and a curated ontology, GO or ChEBI, where curators write the axioms and a reasoner does the rest. The distinction is: the asserted hierarchy is exactly the SubClassOf axioms in the file. The inferred hierarchy is the deductive closure: every subsumption that follows from those axioms plus the class definitions, whether or not anyone wrote it down.

That matters because in a genus–differentia ontology most of the taxonomy is never written. Take apoptotic process. A curator writes it as equivalent to programmed cell death and has_part some apoptotic cell clearance. Nobody writes apoptotic process SubClassOf programmed cell death. The reasoner derives it, because the definition is an intersection and every member of an intersection is a member of each conjunct. Multiply that by tens of thousands of terms in GO and you see why the inferred hierarchy is the one you ship.

How the two reasoners get there

ELK works on OWL 2 EL. It's a consequence-based saturation: it starts from the asserted axioms and repeatedly applies inference rules, adding new subsumptions to a table until nothing new appears. No search, no backtracking, so it's polynomial in the size of the ontology. On full GO (roughly 40,000 terms) that's seconds, which is why it runs in CI on every build.

HermiT is a hypertableau reasoner for full OWL 2 DL. It does model construction with branching on disjunctions, so the worst case is 2-NEXPTIME. On a full biomedical ontology it typically runs for minutes and often exhausts the heap. You use it on small modules where you actually need disjunction, negation, inverse properties or nominals: things the EL profile doesn't allow.

Cycles

Here's the part people get wrong: OWL DL doesn't require the asserted graph to be acyclic, and a cycle doesn't hang the reasoner. The semantics is model-theoretic: the reasoner isn't walking parent pointers, so there's no loop to get stuck in. ELK's saturation just reaches a fixpoint.

What a cycle means is entailment. If you assert A SubClassOf B and B SubClassOf A, the reasoner derives A equivalent to B. That's not automatically an error; it's often intended. The OBO Foundry's acyclicity principle is a curation convention, not a DL constraint.

The real failure signals are two. First, an unsatisfiable class: if C is inferred below both A and B and A and B are declared disjoint, C is equivalent to owl:Nothing. A release build should fail on that. Second, unintended equivalence between two distinct named classes: the same mutual-subsumption pattern, but not what the curator meant. ROBOT's reason command exposes this directly with --equivalent-classes-allowed none, which fails the build when the reasoner finds an equivalence that isn't asserted.

Trade-off

If your ontology fits EL, use ELK: seconds, deterministic, catches unsatisfiability and unintended equivalence. One gotcha: ELK ignores axioms outside the profile rather than failing, so a stray universal restriction just drops out of the classification; check the ignored-axiom log. If you need disjunction or negation, you're in DL and you pay for it, so scope HermiT to the module you're debugging rather than the whole release.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and defend a knowledge-data workflow for cross-ontology mappings.

Answer

Assumptions: Two ontologies (say GO and SNOMED CT) must be joined for federated query. Mappings are class-to-class and property-to-property. The consumer either runs a reasoner over the union (OBDA-style) or only searches it. That split decides every choice below.

Core answer (first 90 seconds): Four stages, each leaving an artefact that outlives the run.

  1. Candidate generation: string and structure matchers (OAEI systems such as LogMap or AML) emit candidates with method and score. Nothing enters the store unreviewed.
  2. Validation: domain/range, disjointness, and a closure check against mappings already stored.
  3. Governance: a human signs off on any mapping that will be asserted as logical equivalence; everything else stays non-logical.
  4. Release: every row is versioned against the ontology version IRI, and superseded rows are deprecated, not deleted.

The predicate rule: owl:sameAs only for vetted identity; skos:exactMatch for interchangeable-but-not-merged; closeMatch/broadMatch/narrowMatch/relatedMatch for the rest. Store each mapping reified (or in a named graph) with predicate, source IRI, target IRI, method, score, reviewer, ontology version, release.

Mechanism: owl:sameAs between two class IRIs makes them one class. Every instance of one is an instance of the other, and every axiom about one applies to the other. That is what OBDA needs and what breaks browsing. SKOS mapping properties are object properties with no equivalence semantics: the reasoner records the link and derives no class-level entailment, so a wrong closeMatch costs a bad search result rather than an unsatisfiable ontology. skos:exactMatch is not a free pass either: the SKOS Reference declares it an owl:TransitiveProperty and a subproperty of skos:closeMatch, so a chain of exactMatch still collapses a hierarchy for retrieval even though it never merges classes.

Artefact 1: predicate choice

PredicateSemanticsReasoning effectUse when
owl:sameAsSame denotation; symmetric, transitiveMerges the two classes/individuals; full OWL 2 DL entailmentsOnly after human sign-off, only for true identity
skos:exactMatchInterchangeable for retrieval; transitive; subproperty of closeMatchNone at class levelExact match you must not merge
skos:closeMatchSimilar, not interchangeable; not transitiveNoneSearch/browse
skos:broadMatch / narrowMatchTarget broader / narrower than sourceNoneHierarchy alignment
skos:relatedMatchAssociativeNone"See also"

Artefact 2: closure query, traced

SPARQL
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?x ?y WHERE { ?x owl:sameAs+ ?y }

Over this graph:

TURTLE
a:Heart            owl:sameAs b:CardiacStructure .
b:CardiacStructure owl:sameAs c:HeartOrgan .

+ matches paths of length ≥ 1. The paths are A→B (length 1), B→C (length 1), A→B→C (length 2). Three rows come back: (a:Heart, b:CardiacStructure), (b:CardiacStructure, c:HeartOrgan), and (a:Heart, c:HeartOrgan). The third is inferred, never asserted. A chain of n classes yields n(n−1)/2 unordered pairs: n=20 gives 190.

Artefact 3: worked OWL trace

TURTLE
a:Heart            owl:sameAs b:CardiacStructure .
a:Heart            rdfs:subClassOf a:Organ .
b:CardiacStructure owl:disjointWith a:Organ .
  1. sameAs makes a:Heart and b:CardiacStructure the same class.
  2. So b:CardiacStructure ⊑ a:Organ, inherited from a:Heart.
  3. Disjointness gives b:CardiacStructure ⊓ a:Organ ⊑ ⊥.
  4. Therefore b:CardiacStructure ⊑ ⊥: the class is unsatisfiable. HermiT or Konclude report an unsatisfiable class; the ontology is still consistent, because nothing is asserted to be a member.
  5. Add a:myHeart a a:Heart and the ontology becomes inconsistent: the individual must belong to a class that cannot have members.

That distinction is the review rule: an unsatisfiable class is a modelling bug you can ship around; an inconsistency breaks every query over the union.

Trade-offs: all-sameAs gives full reasoning and lets one bad mapping poison the union. No mappings is safe and siloed: federated query degenerates to manual joins. Probabilistic or embedding-based mappings are good for ranking candidates and never for entailment; 0.93 is not a truth value. Decision rule: if the consumer reasons over the union, only vetted equivalence enters the logical layer, and everything else lives in a separate annotation graph the reasoner never loads. That is how you get both.

Failure modes and detection

  • sameAs overreach: run the reasoner; check for unsatisfiable classes and for equivalences absent from the mapping store.
  • Chain explosion: count closure pairs with the query above; alert above a threshold set from ontology size (e.g. 1000).
  • Version drift: store the ontology version IRI on every row and validate on load; a mapping written against 2023-01-01 loaded against 2024-01-01 is quarantined.
  • Reversed property mapping: partOf has domain Cell, range Nucleus; hasPart has domain Nucleus, range Cell. Mapping partOf→hasPart directly swaps them, which the domain/range check catches.
  • Label collision: "cold" (temperature) vs "cold" (illness); catch with a 5% random human spot-check plus context-aware embeddings for the remainder.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do you handle ontology versioning, class obsolescence, and term merges using replaced_by and consider tags without breaking downstream annotation pipelines?

Answer

Core answer

Obsolete terms never leave the ontology. That's the whole design constraint: the pipeline's job is to resolve migration hints at ingestion time and never let an unresolved term reach the annotation store. replaced_by (IAO:0100001 in OWL) is a 1:1 redirect, so I rewrite automatically. consider is a candidate list, so a curator decides. Anything with neither gets pinned to the last good snapshot and flagged.

Assumptions I'd state before going further: OBO Foundry-style ontologies (GO, ChEBI, Uberon) where a URI is never deleted, only marked owl:deprecated true and moved under an obsolete root. Annotations live in GAF/GPAD or a triple store I control. I don't control the release cadence, so I have to handle whatever diff arrives.

Mechanism

Each release, diff against the previous one. For every class that flipped to obsolete, walk the replaced_by chain to a terminal active class. Chains are real: A gets merged into B, B gets merged into C two releases later, and annotations still pointing at A need to land on C.

Python
def resolve(term_id, graph):
    seen, cur = {term_id}, graph[term_id]
    while cur.obsolete and cur.replaced_by:
        nxt = cur.replaced_by
        if nxt in seen:
            raise CycleError(nxt)
        seen.add(nxt)
        cur = graph[nxt]
    if not cur.obsolete:
        return ("rewrite", cur.id)
    return ("quarantine", cur.consider)

Trace it on A→B→C: seen={A}, cur=A; A is obsolete with replaced_by=B, so seen={A,B}, cur=B; B is obsolete with replaced_by=C, so seen={A,B,C}, cur=C; C is active, return ("rewrite", "C"). On A→B→A the second hop finds A already in seen and raises. On an obsolete term with no replaced_by the loop never runs and it falls through to quarantine with whatever consider candidates exist.

Routing:

CaseActionGuardrail
ActivePass through, refresh closurenone
Obsolete + replaced_byRewrite annotation, log old ID in historyalert on chains > 2 hops
Obsolete + consider or nothingPin to previous snapshot, drop from serving index, emit curation taskpage if quarantines exceed my threshold (0.5% of corpus per release is a reasonable start)

Failure modes

Blind consider substitution is the one that bites. Picking the first candidate creates false gene-function associations that look fine in the annotation file and only show up as a distribution shift in enrichment output, so I'd gate it behind a curator and check enrichment against the previous release.

Stale closure indexes are the second. If you cache the expanded transitive closure, an obsolete term's subgraph breaks queries. Build the closure as a complete read-only artifact per release and swap it atomically.

The third is a merge that never needed a rewrite: when two terms merge, the survivor usually carries the dead ID as an alt_id (secondary identifier). If the loader indexes alt_id, those annotations resolve without touching them at all. I'd check for that before rewriting anything.

If pushed

The alternative to all of this is version-pinning: freeze the ontology at R and re-annotate from scratch on upgrade. That's defensible when your annotation volume is small or you're re-running a pipeline anyway, and it's what I'd do if the migration graph were mostly consider tags. It stops working once annotations are expensive to regenerate, which, for something like GO, they are.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How do you distinguish between and apply experimental vs. computational evidence codes when modeling gene and protein functional annotations?

Answer

Evidence codes define the provenance and epistemological foundation of an annotation. In the Gene Ontology (GO) and Evidence & Conclusion Ontology (ECO), annotations are never bare assertions; they are tuples coupling an entity (DB_Object_ID), a GO term (GO_ID), an evidence code, and supporting reference/context (DB:Reference and With/From).

The fundamental distinction lies in manual human curation versus automated inference, and direct bench assay versus computational propagation:

  1. Direct Experimental Evidence (Manual):
  • IDA (Inferred from Direct Assay) / ECO:0000314: The function/localization is directly assayed for that specific gene product (e.g., enzyme kinetics assay, cell fractionation Western blot).
  • IPI (Inferred from Physical Interaction) / ECO:0000353: The annotation is derived from an assay showing binding or direct interaction (e.g., co-immunoprecipitation, yeast two-hybrid). Crucially, the With/From field (GAF Col 8) must contain the identifier of the interacting partner.
  1. Curated Computational Evidence (Manual Review):
  • ISS (Inferred from Sequence or Structural Similarity) / ECO:0000250: An expert human curator evaluated a sequence alignment or structural homology and transferred the functional assertion. The With/From field must reference the accession of the curated query/homolog used as the transfer template.
  1. Unreviewed Automated Evidence:
  • IEA (Inferred from Electronic Annotation) / ECO:0000501: Machine-generated pipelines with no manual curator review (e.g., automated InterPro2GO mappings, Ensembl Compara orthology pipelines, UniProtKB-Keyword mappings). While IEA accounts for >90% of all GO annotations in databases like UniProt-GOA, it carries high risk of circular error propagation.
CodeECO MappingHuman Curated?Requires With/From?Primary Risk / Failure Mode
IDAECO:0000314YesOptionalConflating in vitro artificial substrate activity with physiological function.
IPIECO:0000353YesMandatory (Col 8)High-throughput false-positive interaction screen (e.g., sticky bait in AP-MS).
ISSECO:0000250YesMandatory (Col 8)Transitive homology drift across paralogs or multidomain gene fusions.
IEAECO:0000501NoMandatoryFeedback loops where IEA assertions are used to train the next prediction cycle.

Application & Storage Strategy

In relational or graph schemas, never collapse evidence codes to an enum string without mapping to ECO identifiers (e.g., store both go_evidence_code = 'IDA' and eco_id = 'ECO:0000314'). ECO is an ontology with strict transitive relations (e.g., ECO:0000314 is a subclass of ECO:0000006 experimental evidence), which allows downstream queries to filter hierarchically (e.g., WHERE eco_term IS_A ECO:0000006) without hardcoding lists of experimental codes.

Production Filtering Rules

  • Target Identification / Gene Essentiality: Filter strictly to experimental codes (EXP, IDA, IPI, IMP, IGI, IEP). IEA must be rejected due to transitive annotation drift.
  • Over-Representation Analysis (ORA / GSEA): If IEA annotations are retained to maximize genome coverage, the background universe and gene sets must explicitly record evidence tiers, or run dual analyses (curated-only vs all). Mixed sets without weighting artificially inflate statistical significance.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Design and defend a knowledge-data workflow for annotation qualifiers.

Answer

The 90-second answer. Assume a clinical or biomedical corpus where a mention of a concept can be negated, hypothetical, historical, or attributed to someone other than the patient, and annotations arrive as spans carrying key-value qualifier fields (BioC infons, PubAnnotation attributes, or BRAT relations). The workflow is: extract spans and qualifiers as separate fields, normalize qualifier values to a controlled vocabulary, validate against a schema, store qualifiers as first-class triples, index them in separate fields, and render them in the UI. The one non-negotiable: a negated mention never enters a positive count.

Why. Search and enrichment both compute over mentions. If "no evidence of pneumonia" is indexed as a pneumonia mention, every downstream prevalence number is inflated by the negation rate. In a corpus where roughly 10-15% of disease mentions are negated (hypothetical figure, but the order of magnitude is typical for clinical notes), collapsing negation inflates the positive count by that fraction and biases any cohort query.

The workflow, with owners.

stepownertooling / formatoutput
1. Extractannotators or NER modelBioC infons, PubAnnotation attributes, BRAT .annspan + qualifier key-values
2. Normalizecuration leadmapping table to a controlled set such as the ConText dimensions (negation, temporality, experiencer, hypothetical)controlled values
3. Validatedata engineerJSON Schema or SHACL shapesaccept / reject
4. Storedata engineerRDF-star or named graphs; qualifier as its own triplequeryable graph
5. Indexsearch engineerseparate fields: negated:bool, certainty:enumindex
6. Displayfront-endqualifier badge on the spanUI
7. ReviewQAstratified sample, Krippendorff's alphaagreement score

Worked trace. Sentence: "No evidence of pneumonia, but possible early COPD."

  • pneumonia → span [15,24], negation=yes, certainty=high, temporality=current.
  • COPD → span [45,49], negation=no, certainty=low, temporality=hypothetical.

Step 5 indexes pneumonia under negated=true, so a query for "patients with pneumonia" excludes it. COPD is indexed as positive but certainty=low, so a prevalence query can filter on certainty. Step 6 renders "pneumonia (negated)" and "COPD (possible)".

Alternatives and when to use them. If the corpus is small and single-purpose, a boolean negated flag on the annotation is enough: no qualifier graph needed. If qualifiers are only ever consumed by one model, keep them in that model's native format and skip normalization. The graph and controlled vocabulary earn their cost when multiple consumers (search, enrichment, display, export) read the same annotations and must agree.

Failure modes and detection. NOT ignored: diff negated vs. positive counts against a hand-labelled sample. Negation propagated as positive: run a cohort query and check it does not return known-negative patients. Context lost: check that a qualifier's scope span covers the mention. Multiple qualifiers split incorrectly: schema validation on cardinality. Absence confused with negative evidence: make the default unknown, not no, and assert that a missing qualifier never equals negation=no.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and defend a knowledge-data workflow for true-path propagation.

Answer

Clarify first. I'll assume an OBO-style DAG ontology, GO or HPO, where an annotation is a tuple (entity, term, relation, qualifier, evidence, source), and the question is how an annotation to a specific term becomes an annotation to its ancestors. If the ontology were a tree with a single parent per node, propagation would be trivial; the design work is entirely in the DAG, the relations, and the qualifiers. I'll also assume we store direct annotations and derive the rest, rather than storing a pre-expanded set as the source of truth.

Core answer. The true-path rule: if entity X is annotated to term T, X is implicitly annotated to every ancestor of T reachable by relations declared transitive for propagation. In GO that is is_a and part_of; regulates and its signed children do not propagate. So propagation is graph reachability over a restricted edge set, not over the whole DAG. Store direct annotations only, compute the closure, and tag every inferred annotation with the path that produced it and an inferred evidence code (IC or IEA): never reuse the direct EXP code. Pin the ontology release (GO ships dated releases; the .obo header carries data-version), because the closure changes when the graph changes.

Why it holds. The ontology asserts subsumption: D is_a B means every D is a B. Reachability over propagatable edges is exactly the transitive closure of that assertion. The moment you propagate over a non-subsuming edge, regulates, the inference is false, which is why the edge allowlist is the load-bearing decision.

Alternatives.

ApproachQuery costFreshnessCost
Materialize full closureO(1) lookupStale until rebuildStorage blows up; diamond terms duplicated
Query-time recursive traversalDepth-bounded recursion per queryAlways currentSlow on hot paths; needs memoization
Hybrid: materialize is_a, compute part_of at query timeFast common casepart_of currentTwo code paths to keep consistent

Choose materialized closure when the graph is stable and reads dominate; choose query-time when the ontology updates weekly and you cannot afford a rebuild window. Do not materialize if you cannot pin the release: you will silently mix two graph versions.

Worked trace (hypothetical DAG). Terms: A root; B is_a A; C is_a A; D is_a B; D is_a C. Entity X annotated directly to D.

  • Naive DFS from D: visit B → A; visit C → A again. A counted twice.
  • Dedupe by term ID: closure = {D, B, C, A}, size 4.
  • If X were annotated NOT D: inferred set is empty. Negation does not propagate.

Failure modes and detection.

  • Propagating NOT. A NOT annotation means X lacks the function; pushing it to ancestors is wrong. Detect: assert zero inferred annotations whose source row carried a NOT qualifier.
  • Invalid relation. Propagating over regulates. Detect: assert every inferred edge is in the allowlist {is_a, part_of}.
  • Double counting. Diamond DAGs inflate ancestor counts. Detect: compare raw DFS visit count against deduped closure size; alert on any mismatch.
  • Obsolete term. Annotations to retired terms must be remapped or dropped. Detect: join against is_obsolete; alert if any survive.
  • Root inflation. Everything reaches the root, so the root carries nearly every entity and is useless for enrichment. Detect: exclude roots from statistics.
  • Inferred presented as direct. Detect: assert no inferred row carries an EXP-family code.

Defence. The workflow is defensible because each inferred annotation is reproducible from a pinned graph, a declared edge allowlist, and a recorded path: you can re-derive any row and audit it against the release it came from.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and defend a knowledge-data workflow for annotation propagation.

Answer

What I'd say first

Assume the graph is a typed entity-relation store (Postgres 15 or Neo4j 5), annotations are (entity, term) pairs attached to a document span, and "propagation" means an annotation on a leaf entity also applies to its ancestors along declared transitive predicates. I'd keep direct and inferred annotations in separate tables so nothing downstream can confuse them, cap traversal depth, and deduplicate per (entity, term) by shortest path. The rest is versioning and the failure modes that fall out of that choice.

Data model

SQL
-- Postgres 15
CREATE TABLE edge (
  subject_id bigint, predicate text, object_id bigint,
  doc_id bigint, confidence real,
  valid_from date, valid_to date          -- NULL = current
);
CREATE TABLE annotation (                  -- direct only
  entity_id bigint, term_id text, doc_id bigint,
  span int4range, created_at timestamptz
);
CREATE TABLE propagated (                  -- inferred only
  entity_id bigint, term_id text, start_id bigint,
  path bigint[], depth int, graph_version bigint
);

is_inferred is structural: it lives in a different table, so a query that forgets to filter cannot silently mix them.

Propagation step

SQL
WITH RECURSIVE up AS (
  SELECT a.entity_id AS start_id, a.entity_id AS node_id, a.term_id,
         ARRAY[a.entity_id] AS path, 0 AS depth
  FROM annotation a
  UNION ALL
  SELECT u.start_id, e.object_id, u.term_id,
         u.path || e.object_id, u.depth + 1
  FROM up u JOIN edge e ON e.subject_id = u.node_id
  WHERE u.depth < 4 AND e.valid_to IS NULL
    AND NOT e.object_id = ANY(u.path)      -- cycle guard
)
SELECT DISTINCT ON (start_id, node_id, term_id)
       start_id, node_id, term_id, path, depth
FROM up
ORDER BY start_id, node_id, term_id, depth, path;

Trace on edges 1→2, 2→3, 1→3, annotation (1, T):

  • depth 0: (1,1,T,[1],0)
  • depth 1: (1,2,T,[1,2],1), (1,3,T,[1,3],1)
  • depth 2: from node 2, (1,3,T,[1,2,3],2)

DISTINCT ON keeps the depth-1 path for node 3 and drops [1,2,3], so (1,3,T) has one row, not two. That is the double-counting fix, and it is why the dedup key includes term_id and orders by depth before path.

Trade-offs

approachread costwrite costwhen
recursive CTE on readgrows with depthnonesmall graphs, fresh results
materialized propagatedO(1) lookupone edge can invalidate many pathsread-heavy serving

I'd materialize and recompute per graph_version. Depth cap 4 is a guess to defend with data: on a hypothetical 12M-edge graph, depth 5 on a hub with ~50k descendants is where the closure stops fitting in memory. Don't propagate along non-transitive predicates (authored, located_in for some ontologies) or when the term is leaf-specific, like a CVE id: declare transitive predicates per analysis.

Failure modes and detection

  • Double counting: support_count exceeds distinct shortest paths. Detect by comparing COUNT(*) against COUNT(DISTINCT path) per (entity, term).
  • Root dominance: a generic root collects everything. Alert when one node holds more than a set share of propagated rows.
  • Mixed evidence: direct and inferred in one result. The separate table makes this a schema bug, not a query bug.
  • Update drift: closure stale after an edge change. Track graph_version lag between edge and propagated.
  • Inferred shown as direct: the API must return path and depth; a null path on a propagated row is the alarm.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

When modeling complex biological relationships like drug-target or phenotype-disease associations, how do you decide between reification, named graphs, and W3C PROV-O for statement-level provenance?

Answer

To choose between RDF reification, named graphs, and PROV-O, map your architectural driver: query ergonomics vs. ingestion/partitioning boundary vs. deep causal and protocol tracking.

Core Trade-Offs and Selection Matrix

  1. Standard RDF Reification (rdf:Statement) / RDF-star (<< s p o >>):

    • Mechanism: Elevates an edge into a node (or native quoted triple in RDF-star) that can directly take predicates like obo:ECO_0000314 (direct assay evidence), publication identifiers (e.g., PMID:12345678), and dc:date.
    • Best used: Edge-specific attribution where multiple distinct labs assert the same relation (e.g., Imatinib inhibits BCR-ABL1) with different experimental assays (IC50 = 25 nM vs. IC50 = 40 nM) and varying evidence codes.
    • Failure mode: In standard RDF 1.1 reification, every assertion bloats triple counts 4x to 5x (rdf:subject, rdf:predicate, rdf:object, rdf:type), degrading join performance in triplestores without RDF-star index optimizations.
  2. Named Graphs (RDF Datasets / Quads):

    • Mechanism: Partitions the store into subgraphs identified by a IRI (context IRI).
    • Best used: Batch-level provenance, snapshot lifecycle, and source ingest tracking (e.g., assigning all triples from UniProtKB release 2024_02 or ClinVar monthly dump to a single graph IRI https://identifiers.org/uniprot/release/2024_02).
    • Failure mode: Graph-granularity mismatch. If named graphs are minted per individual triple to store assertion metadata, quad index sizes explode, and SPARQL queries require cross-graph unions that bypass standard index joins.
  3. W3C PROV-O (prov:Entity, prov:Activity, prov:Agent):

    • Mechanism: Models the explicit mechanistic lineage and transformations of biological data: an annotation (prov:Entity) was generated by an execution run of an algorithm or curator review (prov:Activity), which was associated with an annotator or pipeline (prov:Agent), utilizing reference genomes or primary literature (prov:used).
    • Best used: Multi-step data pipelines, electronic annotation inference (e.g., Gene Ontology IEA pipelines via Ensembl/InterProScan), or clinical-grade assertions where pipeline software version, parameters, and author lineage must be audited.
    • Failure mode: Over-modeling overhead. Querying a simple assertion requires walking 4–6 hops through prov:wasGeneratedBy, prov:wasAssociatedWith, and prov:qualifiedUsage, causing severe latency on broad graph traversals.
MechanismGranularityStorage OverheadSPARQL Query ComplexityIdeal Biological Use Case
RDF-star / ReificationSingle triple / edgeLow (RDF-star) to High (classic 4-triple)Low-Medium (nested syntax)Conflicting assay values, direct evidence codes (ECO) per publication
Named GraphsDataset / Source / BatchMinimal (1 context IRI per quad)Low (GRAPH clause)Snapshot versioning, licensing partitions, vendor ingest boundary
PROV-OEntity / Pipeline runHigh (multiple typed nodes & relations)High (multi-hop traversal)Algorithmic pipeline trace (IEA propagation, variant classification pipelines)

Production Architecture Pattern

A robust production architecture layers these approaches:

  • Use Named Graphs at the boundary to encapsulate dataset snapshots, licensing boundaries, and ingest batches.
  • Use RDF-star (or property graph edge properties) within the graph for the immediate functional attribution: publication reference, ECO code, and confidence value.
  • Attach PROV-O entities only when an assertion is derived through an algorithmic pipeline or multi-stage curation task requiring software version, container hash, or execution parameter audits.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Design and defend a knowledge-data workflow for semantic similarity.

Answer

Assumption: "Semantic similarity" is broad. I'll design for ontology-based similarity between gene products using GO and GOA annotations. If you mean text embeddings, the workflow changes.

Core answer (first 90 seconds):

Five stages: fix the task and ground truth, freeze the ontology and corpus, pick a measure, compute and validate, monitor.

  1. Task and ground truth. Similarity is only meaningful against a task: predicting protein–protein interactions, clustering genes by function. You need labelled positive pairs (known interactors) and negatives (random pairs). Without them no measure is defensible.

  2. Freeze the ontology and corpus. Pin a GO release (go-basic.obo, dated) and an annotation set (GOA). The corpus sets each term's information content: IC(t) = −log p(t), where p(t) is the fraction of gene products annotated to t or a descendant (true-path rule). Rare terms get high IC, so a shared rare ancestor counts for more than a shared broad one.

  3. Pick a measure. Resnik: sim = IC(MICA), the most informative common ancestor. Simple, unbounded, corpus-dependent. Lin: 2·IC(MICA)/(IC(t1)+IC(t2)). Bounded [0,1], comparable across corpora. Wang: edge weights over the graph, less corpus-dependent but needs curated weights. Start with Lin, fall back to Resnik for ranking, use Wang when annotations are sparse.

  4. Compute and validate. Propagate annotations up the DAG, score all pairs, evaluate ROC-AUC on the labelled pairs, tune the threshold.

  5. Monitor. IC drift, MICA distribution, relation types.

Worked example. Toy corpus, Python 3.11, stdlib only:

Python
import math
parents = {  # child -> parents (is_a)
    "GO:0006915": ["GO:0012501"],  # apoptotic process
    "GO:0012501": ["GO:0008219"],  # programmed cell death
    "GO:0008219": ["GO:0008150"],  # cell death
    "GO:0009987": ["GO:0008150"],  # cellular process
    "GO:0008150": [],              # biological_process (root)
}
annots = {"P1": {"GO:0006915"}, "P2": {"GO:0006915"},
          "P3": {"GO:0012501"}, "P4": {"GO:0008219"},
          "P5": {"GO:0009987"}, "P6": {"GO:0009987"},
          "P7": {"GO:0009987"}, "P8": {"GO:0009987"},
          "P9": {"GO:0009987"}, "P10": {"GO:0009987"}}

def ancestors(t):
    seen, stack = set(), [t]
    while stack:
        n = stack.pop()
        if n in seen: continue
        seen.add(n); stack.extend(parents[n])
    return seen

prop = {p: set().union(*(ancestors(t) for t in ts)) for p, ts in annots.items()}
N = len(prop)
ic = {t: -math.log(sum(t in s for s in prop.values()) / N) for t in parents}

def mica(a, b):
    return max(ancestors(a) & ancestors(b), key=lambda t: ic[t])
def lin(a, b):
    return 2 * ic[mica(a, b)] / (ic[a] + ic[b])

Trace: P1 and P2 propagate to {0006915, 0012501, 0008219, 0008150}; P3 to {0012501, 0008219, 0008150}; P4 to {0008219, 0008150}; P5–P10 to {0009987, 0008150}. Counts are 2, 3, 4, 6, 10 out of 10, so:

termcount/10pIC = −ln p
GO:0006915 apoptotic process20.21.609
GO:0012501 programmed cell death30.31.204
GO:0008219 cell death40.40.916
GO:0009987 cellular process60.60.511
GO:0008150 biological_process101.00.000

lin("GO:0006915","GO:0012501") → MICA 0012501 → 2(1.204)/(1.609+1.204) = 0.856. lin("GO:0006915","GO:0008219") → MICA 0008219 → 2(0.916)/(1.609+0.916) = 0.726. lin("GO:0006915","GO:0009987") → MICA is the root, IC 0 → 0.000.

The ranking is what you want: child/parent highest, cousin lower, unrelated pair zero. Change the corpus and every IC moves, so the ranking can flip: that is why the release is pinned.

Trade-offs. Resnik doesn't normalise, so scores scale with corpus size; Lin does, so it's comparable across corpora. Wang survives sparse annotations but needs hand-curated edge weights. Large stable corpus → Lin. Few annotations → Wang.

Failure modes and detection.

  • IC drift as annotations accumulate. Monitor IC of a fixed term set; >10% change → re-evaluate.
  • Root-heavy MICA: high scores that mean nothing. Track the fraction of pairs whose MICA is the root; >50% → not discriminative.
  • Wrong relations: part_of or regulates leaking in when the task is about function. Audit relation types in the paths; restrict to is_a.
  • Circular evaluation: same annotations used for IC and for scoring. Hold out 20% of gene products and compute IC on the rest.
  • Sparse new term: high IC from two annotations. Set a minimum count (e.g. 5) and fall back to the parent.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and defend a knowledge-data workflow for bulk snapshots.

Answer

Treat a bulk snapshot as an immutable, versioned artifact, not a file you download and query in place. The workflow is five stages: acquire, verify, stage, validate, activate. Only the last touches production, and it is an atomic pointer swap, so every earlier stage is reversible.

Assumptions I'd state up front: the provider publishes a stable release ID and a checksum; you have object storage with versioning (S3, GCS); you can hold two versions on disk at once; and the snapshot is large enough that re-downloading it is a cost you plan for, not a surprise.

Acquire. Pull to a staging prefix, never the live path. Use a resumable transfer (aws s3 cp multipart, or curl -C -) so a dropped connection doesn't restart a 100 GB download. Write a manifest as you go.

Verify. Compare SHA-256 against the provider's published checksum, and compare byte size. A truncated download passes a size check only if you skip the checksum; the checksum is what catches it. Reject on mismatch: do not "fix" it.

Stage. Land the verified file in an immutable, versioned location keyed by release: s3://kb/snapshots/<provider>/<release>/. The manifest travels with it (figures illustrative):

JSON
{
  "provider": "example",
  "release": "2024-01-15",
  "url": "https://.../2024-01-15/data.parquet",
  "size_bytes": 108000000000,
  "sha256": "9f2c...",
  "license": "CC-BY-4.0",
  "schema_version": 3,
  "row_count": 105000000
}

Validate. Decompress fully: a gzip CRC catches corruption that a header read misses. Check the schema hash against the expected version, row count against the manifest, and license against your policy. Fail closed.

Activate. Flip a pointer: a symlink current -> snapshots/example/2024-01-15, or a warehouse view ALTER VIEW ... AS SELECT * FROM snapshots.example_2024_01_15. The prior version stays until the next activation succeeds.

Defend it. The reason to snapshot rather than query a live API is repeatability: a frozen corpus means joins and statistical denominators don't shift under you mid-run. Live pagination changes between pages; a snapshot doesn't. The cost is staleness: a snapshot is stale by definition. If you need sub-day freshness, snapshots are the wrong tool; use CDC or streaming. If the provider publishes deltas (Wikidata daily diffs, Common Crawl incremental crawls), applying deltas trades bandwidth for complexity and a harder rollback story. Decide on three criteria: how fast the source changes, how much reproducibility matters, and how big a full re-download is.

Failure modes and detection:

failurehow it shows updetection
partial downloadfile present, shortSHA-256 mismatch
mutable filenamelatest.json overwritten in placepin to release ID + checksum, never a filename
corrupted archivedecompress fails mid-streamfull decompress during validate
schema driftnew or renamed columnschema hash vs expected
disk exhaustionstaging fills, write failspre-flight free-space check vs manifest size
license changeterms differ from last releaselicense field + policy gate
old snapshot mixed with new API datajoins return wrong rowstag every row with snapshot ID

The last one is the quiet killer: join a frozen snapshot to live API data without a snapshot tag and you get a result that is neither reproducible nor fresh, and nothing errors.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Design and defend a knowledge-data workflow for API pagination.

Answer

Core answer. Assume the source is a REST collection: Stripe-style opaque cursor, GitHub-style Link header, or S3-style continuation token, and the goal is a resumable ingest into a knowledge store. The workflow is: classify the pagination contract, fix a page size, loop fetching pages while committing rows and the checkpoint token in one transaction, and stop only on the API's terminal signal, never on an empty page alone. Defend cursor over offset because offset skips or duplicates rows whenever the collection changes mid-scan.

Workflow, in order.

  1. Classify the source: opaque cursor (Stripe starting_after + has_more), link-following (GitHub Link: rel="next"), or token (S3 ContinuationToken). Record the page-size cap: GitHub per_page max 100, Stripe limit max 100, S3 MaxKeys max 1000.
  2. Fetch one page at a fixed size with a 10 s timeout.
  3. In a single transaction: upsert rows by primary key (idempotent), then write the checkpoint token. If the process dies, rows and checkpoint agree.
  4. Validate: row count against any reported total, and unique-key count against row count.
  5. Terminate on has_more == false, an absent next link, or an absent token. An empty page that still carries a token is not the end.
  6. On cursor expiry (HTTP 400/404 with a cursor error), restart from the last committed checkpoint.

Code (Python 3.12, requests 2.32):

Python
def ingest(url, token, db):
    cursor = db.load_checkpoint()          # None on first run
    while True:
        params = {"limit": 100}
        if cursor:
            params["starting_after"] = cursor
        r = requests.get(url, params=params,
                         headers={"Authorization": f"Bearer {token}"}, timeout=10)
        r.raise_for_status()
        body = r.json()
        rows = body["data"]
        if not rows:
            break
        with db.transaction():
            db.upsert_many(rows, key="id")   # idempotent on retry
            cursor = rows[-1]["id"]
            db.save_checkpoint(cursor)       # same txn as the rows
        if not body.get("has_more"):
            break

Why cursor beats offset: a trace. Offset scan, page size 100, rows r0..r199. Fetch offset=0 → r0..r99. Delete r50. The list is now r0..r49, r51..r199. Fetch offset=100 → index 100 is r101, so r100 is skipped. Cursor scan: after page 1 the cursor is r99's id; page 2 asks for rows after r99, so a deletion before r99 changes nothing. The cursor's cost: you cannot jump to page 7, and a cheap total count is usually unavailable.

contractstable under inserts/deletesrandom accesstypical cap
offset/limitnoyes10k window (ES from+size)
keyset (id > last)yesnonone
opaque cursoryesno100 (Stripe)

Failure modes and detection.

  • Duplicate boundary: keyset on a non-unique sort key (ties in created_at) re-reads rows. Sort by (created_at, id). Detect: unique count < row count.
  • Retry duplicating rows: only safe with idempotent upsert. Detect: duplicate primary keys.
  • Partial result cached as complete: mark complete only after the terminal signal and a reconciliation count. Detect: stored count ≠ source count.
  • Ignored next link: parse rel="next"; never compute page+1. Detect: page count mismatch.
  • Cursor expiry: Elasticsearch scroll defaults to a 1-minute keep-alive. Detect: 404 on the scroll id; restart from checkpoint.

Scale. 1M rows at 100/page = 10,000 requests; at 200 ms each that is ~33 min single-threaded. Shard by disjoint key ranges across 4 workers → ~8 min, each with its own checkpoint.

When not to use cursor. If you need random page access for a UI, or the dataset is small and static, offset is fine. Cursor is wrong when the API has no stable sort key, then you must add one or accept duplicates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and defend a knowledge-data workflow for rate limits.

Answer

Core answer (first 90 seconds)

"Knowledge-data workflow" here means a pipeline that pulls third-party knowledge (docs, tickets, catalog metadata) into our own store: a one-time backfill plus a daily delta. Assumptions: the source is a REST API with a documented hourly quota, it returns X-RateLimit-Remaining and X-RateLimit-Reset, and it can return 429 or 503. I'll use GitHub's REST API as the concrete case: 5,000 requests/hour authenticated, 60 unauthenticated, plus secondary limits that fire on bursts even when the hourly quota is untouched.

The workflow has four stages: a shared token-bucket limiter sized below the documented quota; a worker pool whose concurrency is bounded by the limiter, not by CPU; conditional requests with ETag so unchanged records cost zero quota; and a retry layer that distinguishes 429 from 503 and honors Retry-After.

Why it works

The limiter is proactive; 429 handling is reactive. Reactive-only means you discover the limit by hitting it, and every 429 is a wasted request plus a stall. A token bucket refilled at the documented rate keeps you under the ceiling without guessing.

429 means you exceeded a quota: wait for Retry-After, or until X-RateLimit-Reset (epoch seconds). 503 means the server is unhealthy: back off exponentially, don't blame your quota. Conflating them either stalls you for an hour on a blip or hammers a struggling server.

Python
# Python 3.11
import time, random, requests

class Limiter:
    def __init__(self, rate_per_sec, burst):
        self.rate, self.capacity = rate_per_sec, burst
        self.tokens, self.updated = burst, time.monotonic()

    def acquire(self):
        while True:
            now = time.monotonic()
            self.tokens = min(self.capacity,
                              self.tokens + (now - self.updated) * self.rate)
            self.updated = now
            if self.tokens >= 1:
                self.tokens -= 1
                return
            time.sleep((1 - self.tokens) / self.rate)

def get(session, url, limiter, max_attempts=5):
    for attempt in range(max_attempts):
        limiter.acquire()
        r = session.get(url, timeout=10)
        if r.status_code == 200:
            return r
        if r.status_code in (429, 403) and "Retry-After" in r.headers:
            time.sleep(float(r.headers["Retry-After"]))
            continue
        if r.status_code >= 500:
            time.sleep(min(60, 2 ** attempt) * (0.5 + random.random()))
            continue
        r.raise_for_status()
    raise RuntimeError("exhausted retries")

Trace: with rate=1.39/s and burst=10, ten requests go immediately, then one every 0.72 s. A 429 carrying Retry-After: 60 sleeps 60 s and retries; a 503 backs off 2**attempt × jitter, so attempt 0 waits 0.5–1.5 s and attempt 4 waits 8–24 s, capped at 60.

Arithmetic

5,000/hour = 1.39 req/s. Eight workers at 200 ms each = 40 req/s. Unthrottled, the hourly quota is gone in 5,000 / 40 = 125 seconds, and the pipeline then blocks for the remaining ~58 minutes. The limiter turns that into a steady 1.39 req/s: same total work, no stall.

Trade-offs

strategywhen it winscost
proactive token bucketsteady backfill, documented quotamust track quota changes
reactive 429-onlyunknown or undocumented limitswasted requests, stalls
conditional ETagmostly-unchanged corporaextra 304 round-trips

Pick proactive when the quota is documented; fall back to reactive when it isn't.

Failure modes and detection

  • Retry storm: every worker retries at once after a 429. Detect: 429 rate rising after a retry wave, p99 latency spike. Fix: full jitter.
  • Permanent ban: 403 with no Retry-After and no rate-limit headers. Detect: alert on that exact shape; trip a circuit breaker.
  • Stale cache forever: ETag short-circuits revalidation. Detect: age of cached entries. Fix: max-age TTL.
  • Unbounded wait: Retry-After: 86400 honored blindly. Detect: oldest-queued-item age. Fix: cap the wait, park the job, alert.
  • Policy change unnoticed: vendor lowers the quota. Detect: alert when X-RateLimit-Limit changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and defend a knowledge-data workflow for resolvable operations.

Answer

Clarify and assume. "Resolvable" is the contract: every identifier and relation a consumer asks about either returns a canonical entity with provenance, or returns an explicit unresolved with a reason code. It never returns a silent best guess. I'll assume the sources are versioned dumps we don't control (a licensed taxonomy, a CRM export), the consumer is an ops tool that must not act on a wrong merge, and we can afford a nightly batch plus a serving cache.

The workflow, in order. Six stages, each gated on the previous.

  1. Pin. Snapshot each source release into an immutable store, record the release ID and a SHA-256 of the dump. Nothing downstream reads a live endpoint.
  2. Namespace and type. Map every source identifier into a namespaced ID (tax:Q42, crm:acct/1234) and assign an entity type from a closed vocabulary. A record that can't be typed is quarantined, not guessed.
  3. Resolve. Candidate generation by blocking on normalized keys, then scoring. Two thresholds: auto-accept at 0.92 and above, review band 0.75–0.92, reject below. (Hypothetical figures; calibrate on a labelled sample.)
  4. Attach evidence. Every accepted mapping stores the source release, the query, the matched fields, and the score.
  5. Publish. A versioned graph release with a provenance manifest; rollback is repointing to the previous release ID.
  6. Serve. Return canonical ID, confidence, and provenance; unresolved returns a reason code.

Trace. Mention "Acme Corp." → key acme corp → candidates crm:acct/1234 (Acme Corporation, 0.94) and crm:acct/9876 (Acme Corp Ltd, 0.81). 0.94 clears auto-accept, so it returns crm:acct/1234 with provenance. The bare mention "Acme" scores both inside the review band, so it returns unresolved:ambiguous, not the first hit.

Defend the ordering. Pin before resolve because a checksum mismatch caught at ingest is a re-run, while the same mismatch caught at serve is a wrong answer someone already acted on. Thresholds before publish because the review band is where a human spends time; auto-accepting at 0.75 would trade precision for recall you can't audit.

Trade-offs. Deterministic rule mapping is cheap and explainable but brittle to label drift; probabilistic entity resolution handles drift but needs a labelled sample to set thresholds; LLM-assisted matching widens recall but its scores aren't reproducible, so I'd use it only for candidate generation, never for the accept decision. Don't use any of this when the source is authoritative and single: a direct key join beats a resolver.

Failure modes and detection.

failuredetectioncost
wrong entity (false merge)weekly audit of 200 sampled accepted pairs; alert on merge-rate spikepoisoned relations propagate to every consumer
mixed releaseassert all provenance release IDs equal within a served subgraphunreproducible answers
first-hit mappingcount responses with confidence at the default; alert if > 0silent wrong answers
evidence collapseevidence-source entropy per entity; flag if one source supplies > 80%single point of failure
obsolete termdiff label sets between releases; watch unresolved raterecall drop
partial paginationcompare record count to source manifest; checksum mismatchmissing entities
unauthorized reuselicense field required at the publish gatelegal exposure
live-service driftre-fetch upstream checksum on a schedulestale graph

Budget: unresolved rate ≤ 2% per release, otherwise block publish.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and defend a knowledge-data workflow for update validation.

Answer

I'd design a staged validation pipeline with atomic activation and rollback. The core idea: treat each source release as an immutable snapshot, validate it against the current production state, and only swap when all checks pass. Let me walk through the stages, then defend the design against alternatives.

First, snapshot and integrity. We compute a SHA-256 hash of the release manifest and store it in a content-addressed store like a Git repository or an S3 bucket with versioning. This gives deduplication: if only 1% of entities change, we only store the new blobs. For a 10 GB knowledge base, a typical update might add 50 MB. We validate that every file's checksum matches the manifest, and that the schema conforms to our Avro schema registry. If the schema is incompatible, say a field changes from string to int, we reject immediately.

Second, semantic validation. We load the snapshot into a staging database, say PostgreSQL or Neo4j. We run invariant checks: referential integrity (no foreign key points to a missing entity), no cycles in the hierarchy (using a recursive CTE or DFS), and type consistency. For a graph with 1M nodes and 5M edges, these checks take about 30 seconds on a 4-core machine.

Third, diff generation. We compute entity and relation diffs against the current production snapshot. We sort entity IDs and use a merge-join diff. Output: added, removed, modified entities; added, removed relations. For a typical update, we might see 1,000 added, 200 removed, 5,000 modified entities. We store the diff for review.

Fourth, regression queries. We run a suite of 20 critical queries on both staging and production. For example, "count of active users", "average order value", "top 10 products by revenue". We set thresholds: if any count changes by more than 5%, or any query returns null where it previously returned a value, we flag for manual review. We also check for silent deletion: if the total entity count drops by more than 1% without a corresponding removal in the diff, we alert.

Fifth, atomic activation. We use a versioned pointer. For a file-based store, we atomically swap a symlink from the old snapshot to the new one. For a database, we use a transaction that updates a version table and commits. Clients read the version at the start of a request and use it for the duration. This gives snapshot isolation. If activation fails, we revert the pointer. We keep the previous snapshot for at least 7 days for rollback.

Now, defend. Why not direct in-place update? Because you can't validate before affecting production, and rollback is impossible. Why not canary? For knowledge data, consistency is global; a canary would show inconsistent views to different users. Why not full copy? Content-addressed storage makes it cheap. The trade-off is a brief window where reads see old data during the swap. We mitigate by making the swap sub-second and using a read-write lock only for the pointer update.

Failure modes: silent deletion. Detected by count checks. Identifier split: detected by fuzzy matching on names; we alert if two entities have the same name but different IDs. Hierarchy cycle: detected by cycle detection; we reject. Schema type change: detected by schema registry compatibility check. Downstream count jump: detected by regression query thresholds. Cache inconsistency: we use versioned cache keys; after activation, we publish a new version to Redis pub/sub, and caches invalidate. No rollback copy: we enforce a retention policy of 7 days.

Here's a worked example of the regression check:

CheckStagingProductionThresholdAction
Entity count1,002,0001,000,000+0.2%Pass
Active users45,00044,800+0.4%Pass
Top product revenue$1.2M$1.1M+9%Flag for review
Orphaned relations00>0Reject
Hierarchy cycles00>0Reject

The 9% revenue jump might be intended, but it's worth a human look before activation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Design and defend a knowledge-data workflow for data licensing.

Answer

What I'd say first

Assume the pipeline ingests a mix of web-scraped corpora, public research datasets, and licensed third-party data, and emits two redistributable artefacts: model weights and a retrieval index. The license question is therefore not "may I read this" but "which obligations survive into what I ship."

My design: every record carries an immutable license record at ingest, and every derivation recomputes its obligations as the union of its ancestors'. Obligations are monotonic: a derivative is at least as restricted as its strictest input. That one rule is what makes the workflow defensible: you never reason about a transformation in isolation, only about the set of inputs feeding it.

The license record

Fields: spdx_expression (SPDX license expression, e.g. CC-BY-NC-4.0, Apache-2.0 OR MIT), source_url, retrieved_at, evidence_hash (hash of the license page or file), and basis (declared | scanned | inferred). Scan with ScanCode Toolkit; a dataset card's declared license is a claim, not a fact, until the evidence hash matches the source.

Obligation table

ClassObligationPipeline action
CC0-1.0 / public domainnoneallow, keep provenance
CC-BY-4.0attributionallow, emit attribution manifest
CC-BY-SA-4.0share-alikeallow only if downstream can be SA; flag
CC-BY-NC-4.0non-commercialblock from commercial training set
Apache-2.0NOTICE, patent grantallow, retain NOTICE
GPL-2.0-onlycopyleftblock from proprietary weights
GDPR Art. 9 health dataconsent, purpose limitblock unless consent + DPIA on file

Worked trace

Record A is CC-BY-NC-4.0; record B is CC0-1.0. Merge into dataset D: D's expression is CC-BY-NC-4.0, because NC dominates CC0's no-obligation. Train model M on D: M's expression is CC-BY-NC-4.0. Ship M in a paid product: blocked at the release gate. Swap B to CC-BY-4.0 and D is still CC-BY-NC-4.0. Swap A to CC-BY-SA-4.0 and D becomes CC-BY-SA-4.0, so shipping M under proprietary terms is blocked because SA reaches the adapted material.

Trade-offs and when not to use this

Fail-closed at ingest versus quarantine-and-review: fail-closed is right when the output is irreversible (shipped weights), quarantine when it is reversible (an internal index you can rebuild). Dataset-level licenses are cheap but wrong for mixed corpora; record-level is accurate but costs a scan per record: decide by exposure, not by tidiness. If you consume only data you own end-to-end, the derivation graph is overhead; a single manifest suffices.

Failure modes and detection

  • License laundering: restricted content re-uploaded under a permissive label. Detect by MinHash near-duplicate match against known-restricted corpora.
  • Incompatible combination: Apache-2.0 plus GPL-2.0-only. Detect by an SPDX expression satisfiability check at merge time.
  • Terms changed: source flips or revokes. Detect by re-fetching source_url on a schedule and diffing evidence_hash.
  • Missing attribution: assert every CC-BY record has a manifest entry.
  • Public metadata revealing participants: scan released metadata for PII before publish.

Defence

The criteria are legal exposure if wrong, cost of the gate, and reversibility. Monotonic propagation plus a fail-closed release gate is the cheapest design that keeps a wrong answer from reaching a shipped artefact.

Curated: · Written: · Reviewed:

Difficulty: Hard