Skip to content
Tech Interview Prep
Technical interview guide

Bioinformatics Pipelines & Reproducibility

How multi-tool genomics analyses are made repeatable and portable: workflow managers, containerization, and the reproducibility practices the field has had to learn the hard way.

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

Scope: Nextflow 25.x; Snakemake 9.26; CWL 1.2.1; WDL 1.2; OCI image specification; current nf-core, RO-Crate 1.1, FAIR and GA4GH WES 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-1

Design and defend a workflow mechanism for workflow graph.

Answer

Assumptions I'd state first: a batch pipeline, 10³–10⁵ tasks, artifacts are files on shared storage, tasks are idempotent, one cluster. If any of those is false the design changes: I flag where at the end.

Core answer. Build the workflow as an explicit DAG in which every task declares its inputs and outputs as content-addressed artifacts. The engine topologically sorts the DAG, runs every task whose inputs exist and whose cache key is absent, and records the key on completion. The dependency edge, not submission order, is the source of truth, so a change recomputes exactly the affected subgraph and nothing else. Snakemake, Nextflow and Argo all implement this shape; for file-based scientific pipelines I'd pick Snakemake because caching and restart come free.

Mechanism.

  1. Parse rules; instantiate wildcards into concrete jobs.
  2. Build the DAG: nodes are jobs, an edge runs producer→consumer when one job's output path equals another's input path. Kahn's algorithm gives the order in O(V+E); nodes left with in-degree > 0 are a cycle, and the error names the path.
  3. Schedule: ready set = in-degree 0, bounded by cores and memory. Each job runs in a container with only its declared inputs mounted read-only.
  4. Cache: key = SHA-256(input hashes ‖ command ‖ tool version ‖ params). Match → skip.
Python
rule align:                      # Snakemake 8.x
    input:  "trimmed/{sample}.fastq"
    output: "aln/{sample}.bam"
    threads: 8
    shell:  "bwa mem -t {threads} ref.fa {input} | samtools sort -o {output}"

Trace. Jobs: A trim (raw.fastq 2.1 GB → trimmed.fastq), B align, C call, D qc. Edges A→B, A→D, B→C. In-degrees A0 B1 C1 D1 → run A (4 min). Then B and D are ready and run in parallel. Then C. Change a param in C: only C's key changes, only C reruns. Change raw.fastq: A's hash changes, all four rerun. Hashing 2.1 GB at ~1.5 GB/s costs ~1.4 s: cheap next to a 4-minute trim.

Failure modes and how I'd catch them.

failuresymptomdetection
hidden dependencypasses on the dev box, fails on a clean node; stale cachecontainer mounts only declared inputs; strace -f -e trace=openat
wildcard ambiguityjob count ≠ expected--dry-run prints the job DAG; assert the count
fan-out identity losstwo samples write one pathengine errors on two producers for one artifact
cycleDAG build errorsKahn leftover nodes; report the cycle path
order relied on without an edgeresults change when submission order is shuffledshuffle order in a test run

Trade-offs. Make-style timestamp dependencies are cheaper but lie across NFS and clock skew, and miss command changes; content hashing costs a hash of every input but is correct. Airflow's central scheduler DB suits long-running, time-triggered, heterogeneous workflows; at 10⁵ short tasks that DB is the bottleneck, which is why Snakemake and Nextflow keep the DAG in the driver process. Nextflow's dataflow channels pass values in memory: good for streaming, but you lose free caching and restartability that file-based rules give you.

When not to use this. Long-lived services with human-in-the-loop steps, or tasks that are not idempotent. A DAG engine will happily re-run a task that charged a credit card. Use a durable-execution engine such as Temporal with explicit compensation instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design and defend a workflow mechanism for task idempotence.

Answer

Core answer

Assume at-least-once delivery: Airflow retries a task, Temporal replays an activity, SQS redelivers. The task will run more than once and can be killed mid-run. Idempotence means the committed state after N runs equals the state after 1 run, for a fixed (task_id, declared inputs).

The mechanism is two layers. Compute in a task-scoped scratch directory on the same filesystem as the publish target, then commit with a single compare-and-set keyed by a deterministic digest of (task_id, inputs). Nothing outside the scratch dir is touched until the commit. If the commit primitive is a rename, it is atomic; if it is a unique index, it is a conditional insert.

Why atomic publication gives idempotence

A partial attempt can only contaminate a later run if it is visible. Writing to scratch and renaming means the published name either does not exist or holds a complete file: there is no state where it holds half. os.replace maps to rename(2), atomic within one filesystem; across filesystems it degrades to copy+unlink and is not atomic, which is why scratch must live under the publish directory, not /tmp.

Determinism is the second half. If two attempts race and both rename, the last writer wins: benign only if both wrote identical bytes. So the output must exclude wall-clock timestamps, hostnames and iteration order: sort keys, and put run metadata in a separate sidecar.

Alternatives

mechanismcommit primitivecostuse when
deterministic key + atomic renameos.replace / S3 PUTcheapest; needs same-fs scratchoutput is a file or object
unique index + ON CONFLICT DO NOTHINGPostgres 9.5+one extra index; 0 rows on replayside effect is a DB row
vendor idempotency keyStripe Idempotency-Key headervendor retains keys 24hexternal API call
intent record + reapertwo writes plus a sweeperextra state machine, stuck-intent cleanupnon-idempotent API with no key
transactional outboxsame DB txn as the writehighest; needs a relayexactly-once downstream

Decision rule: if the side effect has a natural unique key and a compare-and-set primitive, use it. If it is an external call, use the vendor's key and know its retention window: Stripe's is 24 hours, so a retry at hour 25 double-charges. If neither exists, you cannot get idempotence; you need compensation, not retries.

Failure modes and detection

  • Partial overwrite: attempt A truncates the target, dies. Detect: output checksum differs from the manifest. Fix: rename-only publish.
  • Duplicate insert: two retries race the same row. Detect: unique-violation count above 0 in logs, or row count above expected. Fix: ON CONFLICT DO NOTHING.
  • Shared temp collision: two tasks write /tmp/out.json. Detect: checksums differ across identical runs. Fix: mkdtemp per task.
  • Retry after side effect: charge succeeds, ack lost. Detect: duplicate entries in the vendor ledger. Fix: idempotency key.
  • Output from a failed attempt: validation fails after publish. Detect: manifest missing the final checksum. Fix: validate before rename, never after.

Code and trace

Python
# Python 3.12
import hashlib, json, os, tempfile

def run(task_id, inputs, publish_dir):
    key = hashlib.sha256(json.dumps(
        {"task": task_id, "inputs": inputs}, sort_keys=True).encode()).hexdigest()
    final = os.path.join(publish_dir, f"{key}.json")
    if os.path.exists(final):
        return final                      # earlier attempt already committed
    scratch = tempfile.mkdtemp(prefix=".tmp-", dir=publish_dir)  # same fs
    out = os.path.join(scratch, "out.json")
    with open(out, "w") as f:
        json.dump(compute(inputs), f, sort_keys=True)
    os.replace(out, final)                # atomic rename
    os.rmdir(scratch)
    return final

Trace, two attempts racing on task etl-42, inputs {"date": "2025-06-01"}:

  1. A and B both derive the same digest from the same sorted JSON, so both target the same final path.
  2. A checks os.path.exists → False, computes, renames at t=1.2s. final now exists.
  3. B checked at t=0.1s → False, computes anyway, renames at t=1.9s, overwriting with byte-identical content.
  4. Result: one file, one set of bytes. The check is a TOCTOU race and that is fine: determinism makes the loser's write a no-op in effect.

If compute embeds time.time(), step 3 writes different bytes and the "idempotent" task silently produces two different outputs across retries. That is the failure the manifest checksum catches.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and defend a workflow mechanism for determinism.

Answer

Core

Assume an offline batch workflow (Python 3.11 + NumPy, run in a pinned container) that emits artifacts other teams consume. The mechanism I'd defend is a two-run replay gate: run the workflow twice in the same container with the same explicit seed, canonicalize both outputs, and compare a digest plus per-field tolerances. It fails the build on any diff.

Why two runs and not one golden file? A golden file only catches drift from the recorded run. Two runs in the same environment isolate nondeterminism in the current code from environment drift, which is the thing you actually want to gate on.

Mechanism

  1. Pin the environment: container digest, lockfile, PYTHONHASHSEED=0, TZ=UTC, LC_ALL=C.UTF-8. The seed is a parameter, never read from the clock.
  2. Run twice into separate workdirs.
  3. Canonicalize: sort records by a declared key, sort dict keys, round floats to a fixed number of digits, drop volatile fields (timestamps, hostname, temp paths, durations).
  4. Compare: exact digest for integer/categorical fields, rtol/atol for floats, set-equality for unordered collections.
  5. On diff, fail and keep both artifacts for triage.
Python
import hashlib, json

VOLATILE = {"ts", "host", "workdir", "duration_ms"}

def canonical(records, key, digits=6):
    rows = sorted(records, key=lambda r: r[key])          # stable, total order
    out = [
        {k: (round(v, digits) if isinstance(v, float) else v)
         for k, v in sorted(r.items()) if k not in VOLATILE}
        for r in rows
    ]
    return json.dumps(out, sort_keys=True, separators=(",", ":"))

def digest(records, key):
    return hashlib.sha256(canonical(records, key).encode()).hexdigest()

What the gate catches

sourcesymptomdetectionfix
hash-seeded set iterationrecord order differs across processesrun with PYTHONHASHSEED=0 and =1, diff digestssorted() at the source
unstable sortequal keys reordershuffle input, re-runstable sort or total-order key
float reduction orderlast-bit diffsOMP_NUM_THREADS=1 vs defaultfixed partition + ordered reduce, or math.fsum
embedded timestampbytes differ, semantics samegzip -lv, or grep for ISO-8601SOURCE_DATE_EPOCH, gzip -n
temp path in outputabsolute /tmp/... in artifactgrep for /tmp/deterministic workdir

Worked trace

A stage does tags = list(set(raw_tags)). Run A (PYTHONHASHSEED=0) and Run B (PYTHONHASHSEED=1) produce the same records but the tags list comes out in different orders. The canonicalizer sorts records by id and dict keys, but it cannot reorder a list that was already materialized from a set, so the digests differ and the gate fails. The fix is sorted(set(raw_tags)) at the source, not a smarter comparator. This is the point: canonicalization catches serialization variance, but ordering that leaks into a list must be fixed where it is produced.

Trade-offs

  • Cost: 2x runtime. Acceptable for a nightly gate; too slow for per-commit on a large pipeline, where a single-run golden file is the cheaper, weaker alternative.
  • Tolerance tuning: too loose hides real regressions, too tight flakes. Start at rtol=1e-9 for float fields and tighten only with evidence.
  • Scope: a passing gate proves determinism within the pinned environment, not across machines or library versions. Cross-machine determinism needs the same container digest on both sides.
  • Alternative: record/replay of nondeterministic sources (clock, RNG, network) is stronger but requires instrumenting every source; the two-run gate is the cheaper 80%.

Failure modes of the gate itself

  • Tolerance set so loose that a real regression passes: detect by seeding a known-bad change and confirming the gate fails.
  • Unpinned dependency makes the gate flaky: detect by diffing the lockfile between runs.
  • Someone adds || true to the CI step: detect by asserting the gate's exit code in the pipeline config, not just its log output.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and defend a workflow mechanism for configuration.

Answer

First 90 seconds. I'd pin down what "configuration" means before designing: boot-time settings a process reads once at startup, not runtime feature flags. Those are a different mechanism with different failure modes. Assumptions: one service, containerized, secrets come from a secret manager (Vault or AWS Secrets Manager), and the same image is promoted across environments. Under those, the workflow is: resolve layers → validate → redact → fingerprint → stamp. Five layers with fixed precedence, schema validation that rejects unknown keys, per-key provenance, and a content hash of the resolved config written into every log line and deploy manifest.

The mechanism. Layers, lowest to highest precedence: code defaults, a base file, a profile overlay (prod/staging), environment variables, CLI flags. Each layer is a flat map of key to value. Resolution walks the layers in order and the last writer wins; every key records which layer set it. Validation runs after resolution, not per layer, so a value that is legal in isolation but illegal in combination still fails. Unknown keys are rejected, not ignored: a typo like db_pool_sze should crash the process at startup, not silently fall back to the default. Secrets are declared as secret-typed fields in the schema; they are redacted in the serialized config and in provenance output, and never enter the hash input.

Python
# Python 3.12
import hashlib, json

LAYERS = ["defaults", "file", "profile", "env", "cli"]

def resolve(layers):
    values, origin = {}, {}
    for name in LAYERS:
        for key, val in layers.get(name, {}).items():
            values[key] = val
            origin[key] = name
    return values, origin

def fingerprint(values):
    blob = json.dumps(values, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode()).hexdigest()[:12]

Trace. Feed it:

Python
layers = {
    "defaults": {"db_pool_size": 10, "timeout_ms": 3000},
    "file":     {"db_pool_size": 20},
    "profile":  {"timeout_ms": 5000},
    "env":      {"db_pool_size": 50},
    "cli":      {},
}

resolve walks defaults first: values become {db_pool_size: 10, timeout_ms: 3000}, both origins defaults. The file layer overwrites db_pool_size to 20, origin file. The profile layer sets timeout_ms to 5000, origin profile. The env layer overwrites db_pool_size to 50, origin env. CLI is empty. Final values: {db_pool_size: 50, timeout_ms: 5000}; origins: db_pool_size from env, timeout_ms from profile. fingerprint serializes with sorted keys and no spaces to {"db_pool_size":50,"timeout_ms":5000} and returns the first 12 hex characters of its SHA-256. That 12-char string goes into the startup log and the deploy manifest, so a result can be traced back to the exact config that produced it.

Defence. Two alternatives I'd reject for boot config. Env-vars-only: no types, no schema, no provenance, and every child process inherits the values. Fine for a small service, painful once you have 40 keys and a typo takes down prod. A live config service (etcd, Consul, AWS AppConfig): right when you need to change behavior without a restart, wrong for boot config because it adds a network dependency and a startup failure mode. I'd use one for feature flags and keep boot config static and hashed.

Failure modes and how each is caught.

failuredetection
hidden default changegolden-config test: resolve a fixed input set, assert the fingerprint is unchanged; a library upgrade that flips a default fails CI
profile precedence inversionunit test per layer asserting that layer wins over the one below
environment injectionassert in CI that no key in the prod profile resolves with origin env
secret loggingredaction test greps the serialized config and provenance for known secret values
unrecognized typoschema rejects unknown keys; process exits non-zero at startup
unit mismatchunits in the field name (timeout_ms, ttl_seconds) and typed ranges (ge=1, le=200)
config detached from resultcompare the fingerprint in the run log to the one in the deploy manifest

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Design and defend a workflow mechanism for metadata schemas.

Answer

Assumptions and core answer

Assume bulk RNA-seq intake: metadata arrives as CSV/TSV from the wet lab, one row per sample-library pair, feeding a pipeline; free-text fields may carry PHI. The mechanism is a schema-versioned intake gate that runs before any pipeline work. It has three parts: a registry of immutable, semver'd schemas; a manifest naming the exact version the sheet was written against; and a validator that runs cheapest checks first and reports row, field and rule with PII redacted. The gate is the only place metadata is interpreted, so every downstream consumer reads validated rows.

Why versioning is the load-bearing part

A column's meaning belongs to the schema version, not the column name. If v2 treated strandedness as free text and v3 constrains it to an enum, a v2 sheet read under v3 must fail loudly rather than be silently misread. So the validator resolves schemas/sample/v3.json from the manifest's schema_version: 3: never "latest". JSON Schema draft 2020-12 is the format; the checks run in cost order:

  1. Encoding and delimiter: read the first 64 KiB, strip a BOM, choose the delimiter by counting candidates in the header line. Ambiguous → fail.
  2. Structure: required columns present; types coerced explicitly, never silently.
  3. Identity: unique sample_id; unique (sample_id, library_id).
  4. Cross-field: strandedness ∈ {forward, reverse, unstranded}; layout == paired requires read2_path.
  5. Policy: PHI scan on fields tagged pii: true.

The validator, and a trace

Python
# Python 3.12, jsonschema 4.x
import json
from jsonschema import Draft202012Validator

SCHEMA = json.load(open("schemas/sample/v3.json"))
V = Draft202012Validator(SCHEMA)

def check(row, lineno):
    out = []
    for e in V.iter_errors(row):
        field = e.path[-1] if e.path else e.message.split("'")[1]
        pii = SCHEMA["properties"].get(field, {}).get("pii", False)
        out.append((lineno, field, e.validator,
                    "<redacted>" if pii else row.get(field)))
    return out

Trace row 42 = {"sample_id": "S1", "strandedness": "Reverse", "read1": "a.fq", "read2": "b.fq"} against v3, where strandedness is an enum and donor_name is required with pii: true. iter_errors yields the enum violation: e.path is ['strandedness'], e.validator is "enum", so check returns (42, "strandedness", "enum", "Reverse"). Drop donor_name and the required error has an empty e.path; e.message is "'donor_name' is a required property", so field resolves to donor_name, pii is true, and the value comes back "<redacted>". The row number and field survive; the PHI does not.

Trade-offs

decisionstrictpermissivecriterion
unknown columnfailwarndoes any consumer read it?
error reportingfail-fast, one errorcollect-all, full passsheet size; it's one pass either way
schema changemajor bump + migrationadditive optional columndoes it change interpretation?

Additive changes (a new optional column) can be auto-accepted. A rename or retype changes interpretation, so it needs a major bump and a migration; the alternative, one evolving schema with a per-row schema_version, allows mixed sheets but forces every consumer to branch on version, which is worse than one gate.

Failure modes and how they surface

  • Duplicate sample: caught by the stage-3 unique constraint. If it slips through, the downstream merge doubles counts silently: detected by comparing expected vs observed sample count in the QC report.
  • Delimiter: a TSV with commas inside quoted fields; detected by column-count mismatch on more than 1% of rows.
  • Missing pairing: stage 4.
  • Wrong strandedness: the schema cannot catch this. reverse is a legal value. Only a cross-check against the recorded prep kit catches it. That is the honest limit of schema validation.
  • Spreadsheet coercion: 00123 → 123, 1-3 → a date; detected by leading-zero loss or date-typed values in an ID column.
  • PHI in logs: scan the log stream, not the sheet.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and defend a workflow mechanism for output contracts.

Answer

Assume a batch pipeline: producers write Parquet to object storage, Airflow orchestrates, and the producer and consumer teams are separate. The mechanism is a staging prefix, a contract manifest, and a gate task that is the only thing allowed to mark the run successful. Downstream reads only from the promoted prefix, never from staging.

The producer writes to staging/run_id=.../ and emits _CONTRACT.json alongside the data: schema hash, row count, byte size, SHA-256 of the part files, the partition list, a watermark (max event timestamp), a 100-row sample, and an explicit expected_empty flag. The gate runs as its own task between producer and consumer and reads the manifest and file footers, not the data, so it adds seconds, not minutes. Ownership is split on purpose: the producer owns the manifest, the platform owns the gate, the consumer owns the domain invariants.

Ordering matters because cheap checks fail fast and expensive ones only run on plausible output: existence, then byte size, then schema hash, then row count, then watermark, then checksum, then domain invariants such as count(distinct id) = count(*).

#GatePasses whenFirst production miss it catches
1ExistenceManifest and all listed parts presentPartial shard: 7 of 8 partitions written
2Byte sizebytes > 0 unless expected_emptyZero-byte success: exit 0, empty file
3Schema hashManifest hash equals actual footer hashSilent column rename or type widening
4Row countManifest rows equal actual rowsIndex mismatch after a retry overwrote a part
5Watermarkmax(event_ts) at or past the SLA watermarkStale output: yesterday's data re-promoted
6ChecksumSHA-256 matchesTruncated compression: missing Parquet footer
7InvariantsConsumer SQL assertions holdSemantically invalid rows that are well-formed
Python
def gate(manifest, actual):
    if not manifest["expected_empty"] and actual["bytes"] == 0:
        return "FAIL: zero-byte success"
    if manifest["schema_hash"] != actual["schema_hash"]:
        return "FAIL: schema drift"
    if not manifest["expected_empty"] and actual["rows"] == 0:
        return "FAIL: empty no-hit"
    if actual["rows"] != manifest["rows"]:
        return "FAIL: index mismatch"
    if actual["watermark"] < manifest["sla_watermark"]:
        return "FAIL: stale output"
    return "PASS"

Trace one run: expected_empty=False, bytes=0. The first branch fires and returns FAIL: zero-byte success; nothing else is evaluated. Trace a legitimate no-hit: expected_empty=True, bytes=0, rows=0, schema matches, watermark current. The first branch is skipped because expected_empty is true, schema passes, the third branch is skipped for the same reason, 0 == 0 passes, watermark passes, so it returns PASS. That is the whole point of the flag: an empty result is a valid answer, and only the contract can tell it apart from a crash.

Three places could validate, and the choice is the trade-off. Inline in the producer costs no extra task but is self-certification: the bug that writes zero bytes also writes the manifest claiming success. An independent gate costs one task and is the only design where the success signal is not the producer's own claim. Consumer-side validation catches everything but only after you have paid for downstream compute. Decide by the cost of a bad output reaching downstream: if a bad partition triggers a 40-minute downstream job, the gate pays for itself; if downstream is a cheap idempotent read, inline checks are enough.

Detection is per gate, not a runbook: zero-byte success shows as gate 2 failing with exit 0 upstream; stale output as gate 5 failing while every other gate passes; truncated compression as gate 6 failing with a footer parse error; empty no-hit versus crash as gate 3 failing only when expected_empty is false.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and defend a workflow mechanism for immutable references.

Answer

What I'd say first

Assume the setting is a genomics pipeline: alignments and variant calls are coordinates into a reference FASTA, and the same reference is shared by several pipelines over several years. The mechanism I'd defend is a content-addressed reference bundle: a directory named by the SHA-256 of its manifest, holding the FASTA, its derived indexes, the annotation, and a manifest that records each file's checksum, the source accession, the exact build commands and the tool versions. Pipelines pin the bundle digest in a lock file committed to the pipeline repo, and every run verifies checksums before it starts.

Why bytes, not paths

A BAM position is an offset into the reference. Change one base in chr1 and every coordinate downstream of it names a different base. The SAM spec puts an M5 tag (the MD5 of the uppercased contig sequence, whitespace removed) on every @SQ header line, so a BAM carries the fingerprint of the reference it was aligned against. That tag is the hook the design hangs on: it lets you detect a reference swap after the fact, not just prevent it.

Concretely, GRCh37 chr1 is 249,250,621 bp and GRCh38 chr1 is 248,956,422 bp. A call at chr1:100,000 in a GRCh37 BAM and chr1:100,000 in a GRCh38 BAM are different bases; the difference is a mix of insertions and deletions, not a uniform shift, so coordinate liftover needs a chain file and re-alignment, not arithmetic.

The bundle

refs/GRCh38_no_alt/<sha256-of-manifest>/
  GRCh38.fa
  GRCh38.fa.fai                    # samtools faidx
  GRCh38.dict                      # gatk CreateSequenceDictionary
  GRCh38.fa.{amb,ann,bwt,pac,sa}   # bwa index
  genes.gtf
  manifest.sha256                  # sha256sum -c format
  manifest.json                    # accession, build commands, tool versions

Verification at pipeline start, checked with samtools 1.19:

Shell
set -euo pipefail
sha256sum -c manifest.sha256
samtools dict GRCh38.fa | grep '^@SQ' | cut -f2,3,4 | sort > /tmp/now.sq
grep '^@SQ' GRCh38.dict | cut -f2,3,4 | sort > /tmp/pinned.sq
diff /tmp/pinned.sq /tmp/now.sq

diff prints nothing when the bundle is intact. A single changed base shows up as an M5 line difference; a renamed contig shows up as an SN difference.

Trade-offs

optioncosthow it fails
mutable path, /refs/GRCh38.fanothing to set upsilent: file replaced in place, old BAMs become inconsistent, found at re-analysis
content-addressed bundle + lock file~8 GB per version (3 GB FASTA + ~5 GB BWA index) and a promotion stepthe manifest is mutable unless its digest is pinned in git
reference baked into a container imageimage size, registry storage, rebuild when tools changecouples reference to toolchain; awkward to share across languages

Deciding criterion: if results must be reproducible across years and teams, pay for the bundle. For a one-off exploration, a mutable path is fine. Bake into an image when you also need the toolchain pinned.

Failure modes and how you catch them

  • Patch mismatch (GRCh38.p13 vs p14): contigs added or changed. Caught by the M5 diff above.
  • Decoy omission (hs37d5 vs plain GRCh37): reads from decoy regions misalign to primary contigs and inflate coverage. Caught by comparing the contig name set.
  • chr prefix (UCSC chr1 vs Ensembl 1): identical bytes, different SN. Caught by the same name-set diff; downstream joins on contig name silently drop rows.
  • Stale index: a .bwt built from a different FASTA. Caught by rebuilding the index and diffing; a stale index against changed bytes gives misaligned reads or a crash rather than a clean error.
  • Annotation-build mismatch: a GRCh37 GTF applied to a GRCh38 BAM. Caught by checking the GTF's ##sequence-region lengths against the .dict.
  • Mutable URL: .../latest/GRCh38.fa changes under you. Caught by checksumming on download and pinning the digest.
  • Corrupted shared cache: NFS bit rot or a partial download. Caught by the sha256 check, which fails fast.

Where the design fails

Content-addressing proves the bytes are the bytes you pinned; it says nothing about whether they're the right bytes. A masked reference used for variant calling, or a reference with the wrong decoys, passes every checksum. That's a review question, not a checksum question. And the manifest is only as immutable as its own pin, if the lock file lives on a mutable branch, you've moved the problem, not solved it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and defend a workflow mechanism for checksums.

Answer

Core answer

Put the digest computation at the trust boundary, the moment bytes enter a system you control, and verify it at every hop after. Store {algorithm, digest, byte_length} in a manifest that is itself signed and append-only, because a checksum you can edit is not evidence. Defend the design on three axes: what it detects (bit corruption, truncation, unintended substitution), what it does not (meaning, consent, adversarial tamper of the manifest), and what it costs.

Mechanism

A checksum works because the digest is a deterministic function of the exact byte sequence. Verification is: recompute over the received bytes, compare to the recorded digest, and compare the byte length too. A digest match on a truncated stream is effectively impossible, but length catches the case where the digest was recorded for a different object. Ingestion is the trusted point because it is the only moment where you know the bytes are the ones you intended; every later copy is a claim to be checked, not a source of truth.

Manifest tamper is the gap. A plain digest file is only as trustworthy as its storage. Sign the manifest (HMAC-SHA-256 with a key held outside the data path, or an asymmetric signature if multiple parties must verify) and write it to append-only storage so a rewrite is detectable.

Algorithm choice

algorithmspeed (approx, per core)use
CRC32CGB/s, hardware-acceleratedtransport framing, disk sectors; detects bit flips only
MD5 / SHA-1fastdo not use for integrity against an adversary; collision-broken
SHA-256~1-2 GB/s with SHA-NIdefault for content addressing and manifests
BLAKE3multi-GB/s, parallellarge artifacts where SHA-256 throughput is the bottleneck

CRC32C is fine for detecting random corruption in transit; it is not collision-resistant, so never use it where someone could substitute content. MD5 and SHA-1 are broken for adversarial use: a chosen-prefix collision is practical, so a "valid" digest proves nothing against an attacker.

Trade-offs

Checksums vs Merkle trees vs signed manifests. A flat checksum verifies a whole object in one pass; a Merkle tree lets you verify a chunk without the whole file and localizes corruption to a subtree: worth it for multi-GB artifacts or resumable transfer. A signed manifest adds authenticity; a bare checksum does not. Do not use checksums alone when the threat is a malicious writer with storage access: that needs signatures and append-only logs.

Failure modes

  • Weak hash: MD5/SHA-1 accepted as integrity. Detect by a policy check on the algorithm field.
  • Compressed vs decompressed confusion: digest computed on the gzip bytes, verified against the decompressed stream. Detect by recording which representation the digest covers.
  • Manifest tamper: digest edited alongside the data. Detect via signature verification failure.
  • Wrong sample, valid hash: the bytes are intact but they are the wrong object. Detect by binding identity (sample ID, schema) into the manifest.
  • Partial multipart upload: only some parts landed. Detect by part count and per-part digests.
  • Digest dropped after transformation: a re-encode loses the manifest. Detect by requiring the transform to emit a new manifest.

Worked trace: multipart upload

Upload a 3-part object, 5 MiB parts, SHA-256 per part plus a whole-object digest.

  • Part 1: 5,242,880 bytes, digest A. Part 2: 5,242,880 bytes, digest B. Part 3: 1,048,576 bytes, digest C.
  • Server recomputes each part digest on arrival; a mismatch fails that part and it is retried.
  • After all parts, server computes SHA-256 over the concatenation and compares to the manifest's whole-object digest.
  • If part 3 never arrived, the part count is 2, not 3, and the whole-object digest cannot match: caught before the object is marked complete.

That is the design: digest at the boundary, signed manifest, verify every hop, and fail closed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How do you pin reference genome and annotation versions across a pipeline, and keep coordinates consistent between builds: including when you lift over from hg19 to GRCh38?

Answer

Pin references by content, not by name. "GRCh38" names a family of assemblies (no-alt analysis set, with-alt, plus decoys, plus HLA) and "hg19" is not GRCh37: it is GRCh37 with UCSC chr prefixes and the old NC_001807 mitochondrial sequence in place of the rCRS NC_012920. So the pinning unit is a manifest that resolves each role to an immutable artefact plus its digest, checked into the repo and never resolved at runtime.

Assumptions: human germline, GRCh38 no-alt analysis set, GENCODE annotation, BWA-MEM/GATK-class tools that need .fai and .dict.

yaml assembly: name: GRCh38 accession: GCA_000001405.15 # no-alt analysis set fasta: s3://refs/sha256/3b1a.../GRCh38_no_alt.fa sha256: 3b1a... fai_sha256: 9c02... dict_sha256: 44de... annotation: source: GENCODE release: 44 # tracks Ensembl 110 gtf: s3://refs/sha256/7f31.../gencode.v44.annotation.gtf sha256: 7f31... chrom_naming: ucsc # chr1..chrX, chrM

nf-core pipelines resolve this from a genome config (--genome GRCh38) with --fasta/--gtf overrides; the resolved paths belong in the run report, not in a shell history.

Content-addressed paths matter for the cache, not just for tidiness. Nextflow's -resume hashes an input file by path, size and last-modified time, so overwriting GRCh38.fa in place either misses the change or invalidates every downstream task; a digest in the path makes the cache key change exactly when the bytes change. Snakemake's ancient() marks a reference as not triggering a re-run when it is re-downloaded.

Coordinates are where builds actually bite:

trapexamplesymptom
contig namingEnsembl GTF 1, UCSC BAM chr1features silently dropped
mitochondrionMT vs chrMmtDNA variants vanish
base conventionBED 0-based half-open, GTF/VCF 1-based inclusiveoff-by-one at every boundary
contig orderhg19 vs GRCh38 unplaced ordertabix index rejects the file
stale index.fai/.dict from another FASTAdict MD5 != recomputed

Lift-over is lossy and one-directional in cost. A chain file (hg19ToHg38.over.chain.gz) is a set of blocks, some on the minus strand; liftOver defaults to -minMatch=0.95 and writes anything it cannot map to a separate unmapped file. Worked example, coordinates hypothetical: a hg19 SNV chr1:1,234,567 A>G falls in a plus-strand chain block with offset +36,667, giving GRCh38 chr1:1,271,234; you then assert the GRCh38 reference base there is A. If the block were minus-strand, REF/ALT must be reverse-complemented (A>G becomes T>C). Picard LiftoverVcf does both checks and writes failures to a REJECT file with a reason; a non-empty REJECT file is the signal, not an exception. Expect low single-digit percent rejection genome-wide, concentrated in the MHC and segmental duplications.

Never lift a BAM or CRAM. CRAM is reference-compressed and carries a per-contig M5 MD5 of the reference sequence, so the reference is part of the file's meaning; a mismatched reference errors or silently decodes wrong bases. Reads get realigned to the target build: that is the only route to correct genotypes. Liftover is for intervals, summary statistics and annotation.

Alternatives: if you control the cohort, re-call against GRCh38 and keep hg19 only as a projection for legacy consumers. If you must serve both, keep two manifests and a chain file, and record which one produced each output in the run metadata (WES run request, RO-Crate) so a downstream join cannot mix builds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and defend a workflow mechanism for reference-data lifecycle.

Answer

Core answer (first 90 seconds). Make reference data immutable and content-addressed, and make the only mutable thing a pointer that names a digest. A run resolves the pointer once, records the digest it resolved, and reads only that bundle. Promotion is an atomic swap of the pointer, gated by CI checks and a recorded human approval. Reproducibility then comes for free, an old run names its bundle, and drift becomes detectable, because every run carries the digest it used and any change of digest without a promotion event is a bug.

The workflow. Six steps, each with a trigger and an owner:

  1. Ingest: data engineer, on an upstream release. Fetch, record source URL, retrieval timestamp and upstream version, compute SHA-256 per file.
  2. Validate: CI, on pull request. Verify checksums, check the schema against the consumer contract, check the license against an allowlist, diff row counts and code coverage against the current bundle.
  3. Benchmark: CI, on pull request. Run the pinned benchmark suite against the candidate and emit metric deltas.
  4. Review: data owner plus one consumer owner, on pull request. They approve the diff report; the approval is written into the manifest.
  5. Promote: release automation, on merge. Atomic compare-and-swap of the pointer, then emit an event.
  6. Retain: storage lifecycle job. Nothing is deleted while any recorded run references it.

The manifest is the unit of review. Its id is the SHA-256 of the canonical JSON with the id field removed, so the id cannot be forged by editing the file list:

JSON
{
  "id": "sha256:9f2c…",
  "source": {"url": "…/release-2025-03", "retrieved": "2025-03-11T08:02:11Z"},
  "license": "CC-BY-4.0",
  "schema_version": 7,
  "files": [{"path": "taxonomy.csv", "sha256": "3ab1…", "bytes": 18432011, "rows": 412887}],
  "approved_by": ["data-owner", "consumer-owner"],
  "benchmark": {"suite": "refdata-bench@2025-02", "deltas": {"coverage": -0.004, "unmapped_codes": 118}}
}

Defending it against the alternatives. Three credible designs:

  • Mutable path, updated in place. Cheapest, no consumer changes. Fails the moment anyone asks why last month's number moved.
  • Versioned directories (v1, v2) behind a symlink. Reproducible if you never rewrite a directory, but nothing verifies that you didn't, and v2 is not proof of content.
  • Per-consumer snapshot copies. Maximum isolation; storage cost scales with consumer count.

Pick content addressing when results are audited or reproduced across teams and storage is cheap relative to a wrong number; pick versioned directories when the data is small and one team owns both ends. The deciding criteria: does anyone need to re-run an old result, how many consumers resolve the same name, and what a wrong number costs.

Failure modes and how you catch them.

failuredetection
silent result driftevery run logs its resolved digest; alert when a run's digest differs from the previous run's for the same logical name with no promotion event
stale indexindex metadata records the bundle digest; a nightly job compares it to the pointer
license changelicense field checked against the allowlist in CI; PR fails
download corruptionSHA-256 verified after fetch; retry from mirror, then fail
taxonomy remapdiff report shows removed/added codes; a mapping table is required before merge
cache not invalidatedcache key includes the bundle digest, so hit rate drops to zero on promotion: assert that
old run unreproducibleweekly job resolves the digest recorded by every run in the retention window

Costs. Content addressing stores a full copy per version; deduplicate at the file level so unchanged files are shared. The pointer swap needs strong read-after-write consistency, S3 has provided it for PUTs since December 2020, or a Git commit, which is atomic by construction. Consumers must change from paths to digests, which is the real migration cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and defend a workflow mechanism for container pinning.

Answer

Assumptions: Kubernetes, images pulled from a registry you control or a public one, deploys driven by a GitOps repo (Argo CD or Flux), multi-arch nodes. If any of those is false the enforcement point moves but the shape holds.

Core answer. Pin by digest in the deployment repo, sign at build, verify at admission. The mechanism is a chain with one non-bypassable gate: CI builds and signs, a bot writes the digest into Git, and the cluster's admission controller refuses any pod whose image is not a digest or whose signature does not verify. Everything before admission is convenience; admission is the enforcement.

StageWhoWhenEnforcement
BuildCImerge to mainpush image, capture digest, cosign sign keyless via OIDC, attach SBOM + provenance
PinCI botsame runwrite repo@sha256:... into the GitOps repo; keep the tag only as a comment
UpdateRenovateweeklyopens a PR bumping the digest; the PR re-runs the build gate
Verifyadmission controller (Kyverno/OPA)every pod admitreject non-digest refs; cosign verify against expected identity; check image platform vs node arch
Auditplatform teammonthlydiff running digests against the lockfile

Why these choices. A tag is a mutable pointer: latest or even v1.4.2 can be repointed to different bytes after you validated it, so the digest, a content hash, is the only reference that names exact content. I put the gate at admission rather than CI because CI is bypassable: a manual kubectl apply or a hotfix branch skips the pipeline, and the cluster is the last place every pod passes through.

Trade-offs. Digest pinning alone freezes you out of base-image patches, so it is only safe paired with automated bumps: without Renovate you drift and ship known CVEs. Every bump is a full re-validation, so cadence is a real cost: weekly for internet-facing services, monthly for internal ones. Looser pinning is defensible in dev/staging (tags are fine) and for internal-only images with no external consumers, where a moving tag plus a short TTL is cheaper than the bump machinery. Pinning the per-platform digest instead of the manifest-list digest breaks the other architecture: pin the index digest.

Failure modes and detection.

  • Tag drift: someone repoints a tag. Detected by the admission controller rejecting non-digest refs, plus an alert when a running digest differs from the lockfile.
  • Registry GC or deletion: the digest becomes unfetchable. Detected by a pre-deploy pull check; mitigated by mirroring to an internal registry.
  • Architecture mismatch: amd64 digest scheduled onto an arm node, exec format error. Detected by comparing the image platform to the node's kubernetes.io/arch label in policy.
  • Compromised base rebuilt under the same tag: detected by SBOM diff between builds and by cosign verify failing when the signing identity changes.
  • Signature bypass: verifying with the wrong key or identity. Detected by a policy test that asserts an unsigned image is rejected.
YAML
# GitOps manifest — digest is the reference, tag is documentation
image: ghcr.io/acme/api@sha256:9f2c...e41  # was v1.4.2
Shell
# admission policy runs the equivalent of:
cosign verify ghcr.io/acme/api@sha256:9f2c...e41 \
  --certificate-identity-regexp '^https://github.com/acme/api/.github/workflows/build.yml@refs/heads/main$' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com

If that verify fails, the pod never schedules. That is the whole defence: the digest names the bytes, the signature names who built them, and admission is where both are checked.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design and defend a workflow mechanism for environment locking.

Answer

What a strong candidate says first. Assume "environment" means a shared mutable resource (one staging cluster, a shared test database, a hardware bench) that several teams and CI jobs mutate, where two concurrent writers produce results nobody can trust. The mechanism is a lease: a lock record with an owner, an expiry, and a fencing token, kept in a small central store, renewed by heartbeat, released explicitly or by expiry. Everything below is detail on those four fields.

The lock record and acquire path. Store it where you already have consensus: a Postgres row is enough for a handful of environments.

SQL
-- Postgres 16
CREATE TABLE env_lock (
  env_id        text PRIMARY KEY,
  owner         text NOT NULL,
  fencing_token bigint NOT NULL,
  expires_at    timestamptz NOT NULL
);

-- Acquire: succeeds only if the current lock is dead.
INSERT INTO env_lock (env_id, owner, fencing_token, expires_at)
VALUES ($1, $2, 1, now() + interval '30 minutes')
ON CONFLICT (env_id) DO UPDATE
  SET owner = EXCLUDED.owner,
      fencing_token = env_lock.fencing_token + 1,
      expires_at = EXCLUDED.expires_at
  WHERE env_lock.expires_at < now()
RETURNING fencing_token;

No row returned means someone holds a live lock; the caller waits or fails. Renewal is an UPDATE ... WHERE env_id=$1 AND owner=$2 AND fencing_token=$3 every 10 seconds against a 30-minute TTL: three missed heartbeats is a dead holder.

Why the fencing token, not just the TTL. A TTL alone gives you split brain: a holder paused by a GC stop or a VM freeze past its expiry resumes and writes while the next holder is mid-run. The token is a monotonic counter bumped on every acquisition; the environment's gateway records the highest token it has seen and rejects any write carrying a lower one. The stale holder gets a 409 and aborts.

Trace. t=0 CI job A acquires, token 1, expires t=30m. t=10m A's node freezes. t=30m the lease expires. t=31m job B acquires, token 2. t=32m A resumes and writes with token 1; the gateway has seen 2 and returns 409; A's renewal also fails on the owner mismatch, so A exits. No corrupt run.

Alternatives and when not to lock. A manual lock with an explicit release recovers only if the holder is honest: a crashed holder blocks the environment forever, which is why the TTL exists. A database advisory lock dies with its connection and cannot cover a cluster-wide environment. The real alternative is not locking at all: give each PR its own ephemeral namespace so there is nothing to contend for. Lock only when the resource is genuinely singular and expensive: a hardware bench, a licensed third-party sandbox, a staging cluster with production-shaped data. If contention is high, queue instead of locking.

Failure modes and detection. Stale lock after a crash: lock age exceeds TTL with no heartbeat. Alert when now() - expires_at > 0 for more than one renewal interval. Split brain: gateway 409 count above zero. Starvation: p95 wait time per team. Heartbeat loss from a network partition: renewal failure counter; the holder must treat a failed renewal as "I no longer own this" and stop, not retry blindly.

Sizing. Eight teams, two 30-minute holds a day each, is 8 hours of lock time: fine. One 4-hour soak test blocks everyone, so cap the default TTL at 30 minutes and require a ticket and an admin grant for longer. Break-glass force-release bumps the fencing token, which is what makes it safe.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and defend a workflow mechanism for executor portability.

Answer

The first two minutes

Assume one DAG, three execution sites (a laptop, a Slurm cluster, a Kubernetes namespace) with inputs on a shared POSIX filesystem at one site and in S3 at another. The mechanism is a three-layer split: the workflow declares an abstract resource contract, a profile binds that contract to a site, and an executor/storage plugin is the only code in the system that knows a scheduler or a URL scheme exists.

In Snakemake the contract is threads: plus the resources: directive (mem_mb, runtime, tmpdir()). A profile is a directory of config.yaml that --profile merges over the command line; it sets executor:, default-resources, default-storage-provider and the software-deployment method. The executor plugin is what turns a job into sbatch --cpus-per-task=… --mem=…; the storage plugin rewrites s3://bucket/x to a local path before the job starts and uploads after it exits. Nextflow does the same job with profiles { } blocks in nextflow.config and process.executor.

YAML
# profiles/slurm/config.yaml
executor: slurm
default-resources:
  - mem_mb=4000
  - runtime=60
software-deployment-method: [conda, apptainer]
default-storage-provider: file
Python
rule align:
    input:  "ref/{genome}.fa", "reads/{sample}.fq.gz"
    output: "bam/{sample}.bam"
    threads: 8
    resources: mem_mb=32000, runtime=240
    shell: "bwa mem -t {threads} {input} | samtools sort -o {output}"

Nothing in that rule names a partition, a queue, or a path prefix. The profile supplies all of it.

contract keylocalSlurmKubernetes
cpusprocess.cpus--cpus-per-taskresources.requests.cpu
mem_mbprocess.memory--memresources.requests.memory
runtimeignored--timeactiveDeadlineSeconds
scratchtmpdir()node-local $TMPDIRemptyDir
containerDockerApptainerDocker
storagefile://file://s3://

Defence. The alternatives are per-site forks of the workflow: cheapest to start, divergent within a quarter; container-only portability, which fixes libraries but not schedulers or storage; and CWL with a runner like cwltool or Toil, more portable in principle but weaker on dynamic DAGs and Python-native steps. The profile design costs you an indirection layer you have to debug through, and it leaks: GPUs, MPI ranks, node-local scratch, licensed software and --exclusive node allocation do not map cleanly onto one abstract key. It also churns: Snakemake 8 replaced the --cluster string with executor plugins, so 7.x profiles need rewriting. Pick it when you have two or more real sites and the graph changes more often than the sites do; with a single cluster the layer is pure overhead.

Failure modes and how you catch them

failuresymptomdetection
hard-coded shared pathjob dies before submission, FileNotFoundError on site Bgrep -rnE '/(scratch|lustre|gpfs)/' workflow/ in CI
scheduler flag inside the algorithmlocal run fails with sbatch: command not foundrun the whole DAG under --profile local (or nextflow -stub-run) on every PR
object-store semanticsMissing output files after a job that exited 0run the DAG against MinIO in CI; S3 has no atomic rename or append, and Last-Modified is second-granularity
local-only symlinkbroken link inside the containerfind . -type l in CI, then stage via --default-storage-provider s3
shell differenceSyntax error: redirection unexpectedrun the test profile in a Debian-based image where /bin/sh is dash
egress surprisewall time dominated by image pull, bill spike-with-trace realtime against %cpu; cloud egress line items
profile changes a scientific parameteridentical inputs, different results per siteallowlist profile keys in CI and hash the resolved config into provenance

The last row is the one that matters most: a profile is allowed to change where a job runs, never what it computes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and defend a workflow mechanism for resource declarations.

Answer

Core answer. Declare resources once per process as a label-scoped default, escalate on retry along only the dimension that actually failed, cap the escalation at a global ceiling, and retry only when the exit status is a recognized resource kill. Everything else terminates on the first attempt. The mechanism has three moving parts: a declaration layer (cpus, memory, time, disk, queue set on a label so a task inherits a profile instead of carrying numbers), an escalation layer (dynamic directives that multiply the base by task.attempt), and a gate (errorStrategy inspecting task.exitStatus). Without the gate, a segfault gets retried four times at four times the memory; without the cap, a mislabelled task escalates until it takes the whole cluster.

GROOVY
// nextflow.config — checked against Nextflow 24.04
process {
  errorStrategy = { task.exitStatus in [137, 143, 104] ? 'retry' : 'terminate' }
  maxRetries    = 3

  withLabel: 'small'  { cpus = 2;  memory = { check_max(  4.GB * task.attempt, 'memory' ) }; time = {  2.h * task.attempt } }
  withLabel: 'medium' { cpus = 8;  memory = { check_max( 16.GB * task.attempt, 'memory' ) }; time = {  8.h * task.attempt } }
  withLabel: 'big'    { cpus = 16; memory = { check_max( 64.GB * task.attempt, 'memory' ) }; time = { 24.h * task.attempt } }
}

def check_max(obj, type) {
  if (type == 'memory') return obj > params.max_memory ? params.max_memory : obj
  if (type == 'time')   return obj > params.max_time   ? params.max_time   : obj
  return obj
}

Worked trace. A big task with max_memory = 128.GB, maxRetries = 3, read from -with-trace:

attemptrequestedpeak_rssrealtimeexitoutcome
164 GB63.2 GB41 min137retry
2128 GB127.4 GB1 h 12 min137retry
3128 GB (capped)127.9 GB1 h 09 min137retry
4128 GB (capped)127.8 GB1 h 11 min137fail

Four attempts, 16 cpus each, ~4.5 h wall, 72 core-hours, zero output. The cap is binding: peak_rss / requested is 0.99 on every attempt, so escalation stopped helping at attempt 2. The fix is to raise max_memory or split the task, not to add retries. Contrast a task that succeeds: attempt 1 requests 8 GB, dies at 7.9 GB peak; attempt 2 requests 16 GB and finishes at 11.3 GB peak. 29% headroom, so 16 GB is the correct declaration and 32 GB would be waste.

Detection. Exit 137 alone does not mean OOM. Compare peak_rss to requested memory and realtime to the time limit: peak_rss ≥ 0.95 × requested is memory-bound; realtime ≥ 0.95 × time with peak_rss < 0.7 × requested is a walltime kill; exit 137 with both ratios under 0.5 is an external kill (preemption, node loss) and should retry without escalation. Identical exit status and identical stderr hash across attempts means the failure is deterministic and retrying is pure cost.

Trade-offs. Static over-provisioning at p99 is simpler and has no retry cost, but you pay for the tail on every task: at 16 cpus and 4.5 h that is 72 core-hours per task, every task. Profile-first-then-pin is cheapest at steady state but needs a representative input set. Adaptive escalation is the right default for heterogeneous inputs; pin the numbers instead when memory is a property of the tool, not the data (a fixed reference index), and skip escalation entirely when a retry costs more than the capacity it saves: a 4-hour GPU job should fail loudly, not re-run.

Failure modes.

failuredetectionremediation
OOM loopexit 137 every attempt, peak_rss ≈ requestedraise cap or split task
Cap bindingidentical requested memory across attempts in traceraise max_memory
Walltime read as OOMrealtime ≈ time, low peak_rssescalate time, not memory
Deterministic failure retriedsame exit status and stderr hash each attemptgate errorStrategy on exit code
Unit mismatchscontrol show job AllocMem ≠ declaredSlurm --mem is per node, --mem-per-cpu per core; 8 GB × 8 cpus is 64 GB under the latter
CPU oversubscriptiontrace %cpu > cpus × 100lower cpus or pin threads
Disk exhaustionexit 1 with ENOSPC in stderrdisk is advisory on most executors; stage to scratch and clean up

On Kubernetes the same split holds: memory over the limit is OOMKilled at exit 137, CPU over the limit is throttled via CFS quota and never killed, and requests affect scheduling while limits affect survival. Set them equal for Guaranteed QoS on latency-sensitive tasks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

A batch task dies with exit code 137 on a 64 GB node. Walk me through how you confirm the cause, retry it, and right-size the memory requests for the rest of the cohort.

Answer

First 90 seconds. Exit code 137 is a symptom, not a diagnosis: it is 128 + 9, so the task was SIGKILLed, and the kernel OOM killer is only one of several things that send SIGKILL. Before retrying anything I want a signal that names the cause: for a container, containerStatuses[].lastState.terminated.reason == "OOMKilled"; on a bare cgroup v2 host, memory.events showing oom_kill incremented for that task's cgroup; on a shared node, the kernel log line naming the killed PID. If none of those fired, the 137 came from somewhere else (scheduler preemption, walltime, an operator) and retrying with more memory burns budget without ever fixing it.

Retry with bounded escalation. Once it is an OOM, retry with more memory, but make the escalation a function of the attempt number and cap both the attempts and the ceiling:

groovy // Nextflow 24.x, DSL2 process ALIGN { memory { 8.GB * task.attempt } // attempt starts at 1 cpus { 4 * task.attempt } maxRetries 3 errorStrategy { task.exitStatus in [137, 143] ? 'retry' : 'terminate' } }

python

Snakemake 8.x

rule align: resources: mem_mb=lambda wildcards, attempt: 8000 * attempt, runtime=lambda wildcards, attempt: 60 * attempt retries: 3

8 → 16 → 32 GB with three retries means one failing task can reserve 56 GB-hours before it is declared dead. That ceiling is the thing to argue about, not the multiplier.

Right-size from measurement, not guesswork. Both engines already record the high-water mark: Nextflow's -with-trace writes peak_rss per task, Snakemake's benchmark: directive writes max_rss. Take the p99 of the last N runs, add a margin, write it back into the declaration. The payoff is arithmetic: 300 aligner tasks declared at 32 GB but peaking at 6 GB, on 64 GB nodes with 4 GB reserved, run one per node. 300 node-hours at 40 minutes each. Declared at a measured p99 of 11 GB, five fit per node: roughly 60 node-hours. Fixed declarations are not conservative, they are expensive.

Where this goes wrong.

  • Container limit diverging from the request: the scheduler grants 32 GB but the container cgroup is capped at 8 GB, so it OOMs at 8 GB forever while the retry escalates the request. Set the limit from the same variable.
  • JVM tools: -Xmx is heap only. GATK and friends are commonly run with -Xmx at roughly 75–80% of the container limit, because thread stacks, native buffers and JVM overhead live outside the heap. A fixed -Xmx4g means the extra memory a retry grants is never used.
  • Silent truncation: a tool that traps the error and exits 0 with a partial BAM. Exit codes will not catch it: samtools quickcheck, output-size sanity and checksums will.
  • Retry storms: 200 tasks failing at once and all retrying. Cap concurrency (maxErrors, --max-jobs-per-second) and cap the pool globally (--resources mem_mb=...).
  • One-way escalation: nothing ever shrinks. Schedule a job that recomputes baselines from the last N traces, or declarations only ratchet up.
  • Disk exhaustion is a different failure: No space left on device exits 1, not 137, and needs scratch cleanup and a disk directive, not more memory.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and defend a workflow mechanism for scatter gather.

Answer

What I'd say first. Scatter-gather is a fan-out/fan-in where correctness depends on the set of shards that came back, not the count. I'd design it as a four-phase workflow (plan, scatter, gather, publish) with a manifest as the contract between phases. Assumptions: a coordinator that knows the shard topology, shards that are idempotent and addressable by a stable shard_id, and a caller that can tolerate a fail-closed error but not a silently partial result.

Plan. The coordinator builds a manifest: one entry per shard, (shard_id, lo, hi) with inclusive integer key ranges. Validate coverage before dispatch: sort by lo, then assert each entry satisfies next.lo == prev.hi + 1. That one assertion catches the boundary gap and the overlap at plan time, before any network call.

Scatter. Dispatch every shard concurrently under a single deadline. Reserve roughly 10% of the budget for gather and publish so one slow shard cannot consume the whole SLO.

Gather. Collect into a dict keyed by shard_id. Unknown ids are dropped and counted; duplicates keep the first and increment a counter. Then diff the manifest keys against the result keys: that diff is the completeness signal.

Publish. Emit only when the missing set is empty, or when the caller explicitly opted into partial results, in which case the response carries complete: false.

Python
import asyncio

async def scatter_gather(shards, fetch, budget_s=0.5, reserve_s=0.05):
    manifest = {s.shard_id: s for s in shards}
    loop = asyncio.get_running_loop()
    deadline = loop.time() + budget_s - reserve_s

    async def one(s):
        remaining = deadline - loop.time()
        if remaining <= 0:
            return s.shard_id, None
        try:
            return s.shard_id, await asyncio.wait_for(fetch(s), remaining)
        except Exception:
            return s.shard_id, None

    results = {}
    for shard_id, rows in await asyncio.gather(*(one(s) for s in shards)):
        if shard_id in manifest and rows is not None:
            results[shard_id] = rows

    missing = manifest.keys() - results.keys()
    return results, missing

Trace with four shards, budget_s=0.5, reserve_s=0.05, so the deadline lands at t=0.45 s:

shardreturns atoutcome
A0.12 skept
B0.30 skept
C0.44 skept
D0.60 swait_for cancels at 0.45 s → None

missing = {D}. Retry once with a fresh 0.45 s deadline; if it fails again, fail closed. Note that a count check would have passed with four shards if D had been duplicated: set identity is what makes this safe.

Trade-offs:

strategycompletenesstail latencyuse when
barrier (wait all)strictp99 = slowest shardcorrectness-critical
quorum k-of-nprobabilisticp99 = k-th fastestapproximate analytics
hedged requestsstrictcuts p99, ~5% extra loadduplicate work is cheap
streaming mergestrict if watermarklow first-bytelarge result sets

Failure modes and how each is detected:

  • Missing shard: manifest diff non-empty; metric scatter_missing_shards; retry once, then fail closed.
  • Duplicate shard: same id twice; dedupe, count scatter_duplicate_shards.
  • Overlapping records: ranges overlap; caught at plan time by the contiguity assertion, or at gather by key-range validation.
  • Gap at boundary: off-by-one in hi; same contiguity assertion.
  • Wrong reference: a shard returns a key outside [lo, hi]; validate each row, reject the shard.
  • Nondeterministic gather order: sort by shard_id before merge so output is stable and diffable.
  • Partial publish: gate on missing == set(); never emit a partial result without an explicit flag.

Defense. The manifest is the mechanism. It turns "did we get everything?" from a count into a set comparison, and it lets every other check (coverage, dedupe, range validation) run against one source of truth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and defend a workflow mechanism for cache keys.

Answer

Assume we're talking about a build or CI cache (Bazel, Turborepo, ccache, GitHub Actions cache) shared across runners, where a wrong hit ships a wrong artifact. Correctness beats hit rate: a 0% hit rate costs money, a bad hit costs an incident. So the mechanism is designed to fail closed.

A cache key is a hash over a canonical serialization of everything that can change the output. Two layers. The action key covers the command, the toolchain, and the declared input set. Each input contributes its content digest, not its path or mtime:

key = sha256(
  "v1" + "\n" +
  command + "\n" +
  toolchain_digest + "\n" +
  env_subset_digest + "\n" +
  join(sorted(f"{path}:{sha256(bytes)}" for path in declared_inputs))
)

The v1 prefix is the escape hatch. When you discover a missing input, you bump it and every key changes, so you never have to reason about which existing entries are now wrong.

Why content digests and not mtimes: a fresh git clone or git checkout rewrites mtime to now. An mtime-keyed cache misses on every clean CI run, 0% hit rate, while a content-keyed cache hits, because the bytes are identical. Content digests also catch the reverse case, which is the dangerous one: a file changed but kept its mtime, so an mtime key silently reuses a stale artifact.

Worked trace (Turborepo-style build task on package api; digests abbreviated, timings illustrative). Declared inputs: src/**, package.json, tsconfig.json, pnpm-lock.yaml, NODE_ENV, Node version.

runwhat changedkeyresult
1commit A, cold9d4e…miss, build 42 s, upload 18 MB
2commit A, fresh runner9d4e…hit, restore 1.4 s
3commit B, one line in src/index.ts1a88…miss: output genuinely differs
4commit B, NODE_ENV → staging5e02…miss: correct
5generated/config.json changes, not declared1a88…hit: stale artifact restored

Run 5 is the failure the design exists to prevent. Detection: a CI job that runs the task cold, then warm, and diffs the outputs; plus a mutation test that touches each declared input and asserts the key changes.

Trade-offs. Declared inputs vs auto-detected: Bazel requires explicit deps. Precise, but a missing dep is a silent stale hit, and you pay maintenance. Turborepo globs inputs: cheap to set up, coarser, so an unrelated file in the glob busts the cache. Choose explicit when a bad hit is expensive (compiled artifacts, migrations), globs when it's cheap (lint, docs). Key granularity: a whole-repo key is simple and near-zero hit rate in a monorepo; a per-package key hits often but multiplies keys to manage. Env vars: hash too few and you go stale; hash all of env and every run misses because CI, RUNNER_NAME and timestamps differ. Hash an explicit allowlist.

Failure modes and how they surface.

  • Undeclared input → stale hit. Cold/warm diff catches it.
  • Mutable tag in the key (node:18, ubuntu-latest) → key stable while the image changes underneath. Pin by digest.
  • Timestamp or random value inside the artifact → never hits across runs even when inputs match. Reproducible-build check: build twice, diff -r.
  • Cross-trust-boundary contamination: a fork PR writing to a cache that main reads. Scope keys by branch/trust and verify the artifact digest on restore.
  • Corruption: a truncated upload. Verify the restored artifact's digest against the key before use, or it fails deep inside the build with a confusing error.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and defend a workflow mechanism for failure classification.

Answer

What I'd say first (60–120s)

Before classifying anything I'd fix three assumptions: the unit of work is idempotent (or carries an idempotency key), the downstream is a separate failure domain, and I own the retry policy rather than the caller. Then the mechanism is one classifier that maps every failure to one of five classes, plus a policy table that maps each class to an action. Retry logic reads the class; it never inspects raw error strings at the call site.

The classifier

classsignalspolicy
TRANSIENTgRPC UNAVAILABLE / DEADLINE_EXCEEDED, HTTP 500/502/504, connection resetretry with exponential backoff + full jitter, max 5 attempts, counts against budget
THROTTLEDHTTP 429, gRPC RESOURCE_EXHAUSTED, Retry-After headersleep the advertised delay (backoff if absent), retry, does not count against budget
DETERMINISTICHTTP 400/422, gRPC INVALID_ARGUMENT / FAILED_PRECONDITION / PERMISSION_DENIEDfail fast, no retry, emit the input
POISON200 response that fails to parse, or the same input fails identically twicequarantine to DLQ, alert on cardinality
UNKNOWNanything unmappedfail fast and page; do not guess

Backoff: sleep = random(0, min(20s, 100ms * 2^attempt)). Full jitter, base 100 ms, cap 20 s. Retry budget: retries ≤ 10% of successful requests per minute; over that, the circuit breaker opens after 20 consecutive failures or a 50% error rate in a 30 s window.

Worked trace: one job against a flaky API:

  1. attempt 0 → HTTP 503, Retry-After: 2 → THROTTLED → sleep 2 s, retry. Budget untouched.
  2. attempt 1 → connection reset → TRANSIENT → sleep random(0, 200 ms) = 137 ms.
  3. attempt 2 → HTTP 500 → TRANSIENT → sleep random(0, 400 ms) = 61 ms.
  4. attempt 3 → HTTP 200, body fails JSON parse → POISON → stop retrying, write the input hash to the DLQ.
  5. Job ends quarantined, not failed. DLQ depth increments; input count reconciles.

Had attempt 3 returned HTTP 422 instead, the job fails fast there with the payload logged: no attempts 4–5.

When this is the wrong mechanism

If the work is not idempotent, retrying a TRANSIENT after a partial side effect double-charges; you need a reconciliation step or a transactional outbox instead. If the downstream is saturated, retries amplify the outage: the budget and breaker exist for that, but the honest answer is to shed load, not retry. And if most failures land in UNKNOWN, the classifier is wrong; fix the mapping before adding retries.

Failure modes and how I'd detect them

  • Retry storm: retry rate exceeds the 10% budget, or the breaker opens. Alert on both.
  • Partial side effect: idempotency-key replay returns 409, or a reconciliation job finds a mismatch.
  • Input bug masked: the same DETERMINISTIC class appears across many distinct input hashes. Alert on cardinality, not count.
  • Nondeterministic success: the same input hash succeeds on retry. Log the hash on every attempt.
  • Lost original log: the first-attempt error must be written before any retry; assert the log line exists.
  • Silently dropped sample: DLQ depth plus quarantined count must reconcile against input count every run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and defend a workflow mechanism for provenance.

Answer

I'd design a content-addressed provenance ledger. Every task attempt emits a signed, versioned record that binds run, task, and attempt IDs to SHA-256 digests of inputs and outputs. Lineage is reconstructed by joining on those digests: if task B's input digest equals task A's output digest, A is B's parent. This beats logs because logs are unstructured and rotate away; it beats a central orchestrator DB because that misses out-of-band tasks and is mutable.

Assume a workflow orchestrator (Argo Workflows 3.x, Airflow 2.x) and a shared object store (S3, GCS). The orchestrator runs a sidecar per task. The sidecar computes SHA-256 of each input and output file or directory (Merkle tree for directories). It writes a JSON record to an append-only log, Kafka topic or S3 bucket with object lock, and signs it with Sigstore/cosign using the in-toto attestation format v1. Schema: OpenLineage 1.x with custom facets for image, command, and executor.

JSON
{
  "schema": "openlineage/v1",
  "run_id": "01H8...",
  "task_id": "extract",
  "attempt": 1,
  "workflow_revision": "git:9f3a1c2",
  "inputs": [{"name": "raw.csv", "digest": "sha256:abc..."}],
  "outputs": [{"name": "clean.parquet", "digest": "sha256:def..."}],
  "config": {"shards": 4},
  "image": "registry/extract@sha256:123...",
  "command": ["python", "extract.py", "--shards", "4"],
  "executor": {"host": "ip-10-0-1-5", "start": "2025-01-15T10:00:00Z", "end": "2025-01-15T10:02:13Z"},
  "signature": "cosign:..."
}

To reconstruct lineage, query all records for a run. Build a map from output digest to record. For each record, for each input digest, look up the producing record. That edge is the lineage. Example: task A outputs sha256:def; task B inputs sha256:def. The join yields A -> B. If an input digest has no producer, that's a missing transitive input: alert.

Trade-offs: Hashing costs CPU. On a 2023 x86 core, SHA-256 runs at ~1.5 GB/s, so hashing a 10 GB artifact adds ~7 seconds. For large artifacts, hash a Merkle tree of chunks or hash only metadata. Storage: each record is ~1 KB; 1 million tasks/day is ~1 GB/day. Alternatives: parsing logs is cheap but unreliable. No schema, rotation loses data, and you can't join on digests. A central orchestrator DB is easy but misses tasks launched outside the orchestrator and is mutable. When not to use: for ephemeral, low-stakes jobs where the cost of hashing and storage exceeds the value of lineage.

Failure modes and detection:

FailureDetection
Missing transitive inputInput digest has no matching output digest in ledger; alert on orphan.
Clock skewUse monotonic sequence numbers per run; compare wall clocks across records; alert if drift > 1s.
Log rotationAppend-only store with retention; detect gaps in sequence numbers.
Secrets in commandRedact or hash commands; scan for patterns (AWS keys, passwords).
Mutable identifierUse content-addressed digests, not paths; verify digest matches content on read.
Cache lineage omittedInclude cache key and hit/miss in record; compare cache key to input digest.
Provenance written after failure onlyEmit record on start and completion; on failure, emit partial record; detect missing completion.

This mechanism is robust because content-addressing makes lineage independent of names and paths. Signing prevents tampering. The append-only log gives an audit trail. The cost is bounded and measurable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and defend a workflow mechanism for replayable operations.

Answer

Assumptions. Batch pipeline; each task is deterministic given its declared inputs; outputs are files; "replay" means reproducing a past run months later, or re-running after a failure without redoing work.

Core answer. Make every task a pure function of a content-addressed key, and append every attempt to a journal. Replay re-derives the key, then either reuses the recorded output (after verifying it) or re-executes. The key is the mechanism; the journal is the evidence. An exit code of zero proves the process ended, not that the outputs are the ones the inputs imply.

Key function (Python 3.12):

Python
import hashlib, json

def digest(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

def task_key(cmd, inputs, params, image, env):
    material = {
        "cmd": cmd,
        "inputs": {n: digest(p) for n, p in sorted(inputs.items())},
        "params": params,
        "image": image,          # "sha256:...", never "latest"
        "env": env,              # PYTHONHASHSEED=0, TZ=UTC, LC_ALL=C
    }
    blob = json.dumps(material, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()

Trace. Run 1: task_key returns a3f1…; the task executes; the journal appends {key: a3f1…, output: 9c02…, attempt: 1}. Run 2 (replay): the key recomputes to a3f1…; the engine finds the entry, re-hashes the output file, gets 9c02…, and skips execution. If the output file was edited in place, the digest differs and the task re-executes. If a param changed, the key changes and a new entry is written: the old entry stays, so the earlier run is still reproducible.

Alternatives.

mechanismreplay unitguaranteescost
content-addressed memoization (Nextflow -resume, Bazel action cache)task keysame key → same outputkey must capture every input; cache storage
event-sourced replay (Temporal)workflow historydeterministic re-execution of codehistory capped at 51,200 events / 50 MB, so long workflows need Continue-As-New; code must be deterministic
process checkpoint (CRIU)memory imageexact resume of a running processnot portable across kernels; no logical replay

Failure modes and detection.

  • Nondeterminism (unseeded RNG, dict iteration order, wall-clock). Detect by running the same key twice and comparing output digests; a mismatch is a determinism bug, not a flake.
  • Incomplete key: an input read but not hashed, e.g. a reference database loaded from a fixed path. Detect by running under a sandbox that denies reads outside declared inputs, then diffing the opened-file list against the key.
  • Stale output: verify the output digest on every cache hit, not only at write time.
  • Container drift: pin images by digest, never by tag; the digest is part of the key.
  • Partial cohort: assert the expected shard count from the manifest before merging; a missing shard otherwise merges silently.

Arithmetic (illustrative). A 400-task pipeline runs in 6 h. A one-line parameter change invalidates that task and its 12 downstream tasks; 388 tasks hit cache, so replay is ~15 min instead of 6 h. Cache storage is the bill: keeping every intermediate at ~2 GB average is ~800 GB per run, so apply a retention policy. Keep outputs of published runs, evict the rest.

When not to use it. Content-addressed memoization assumes determinism. Nondeterministic training (GPU kernels, sampling) breaks it: record the seed and library version in the key, or fall back to event-sourced replay that records the actual outputs. If you cannot enumerate a task's inputs, no key scheme saves you: fix the interface first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How do you build positive and negative controls, spike-ins and truth samples into a pipeline so that a run which is reproducible but biologically wrong is caught before results are reported?

Answer

Reproducibility tells you the pipeline did the same thing twice. It says nothing about whether the thing was right. A sample swap, a reference built from the wrong assembly, or a library prepped with the wrong index all reproduce perfectly. So controls have to assert on content, and they have to be gates inside the workflow, not a MultiQC section someone reads on Friday.

Three tiers, cheapest first.

  1. Process controls: PhiX spike-in (Illumina, ~1% of reads) or ERCC mixes for RNA. These exercise the instrument and the base-calling, trimming and alignment path. PhiX is 5,386 bp, ~45% GC, no homology to human, so an alignment rate below ~90% or a mismatch rate above ~1% means the run itself is bad.
  2. Identity controls: a genotype fingerprint (24–100 SNPs) checked against the expected sample, X/Y coverage for a sex check, and VerifyBamID FREEMIX. FREEMIX above 0.02–0.03 flags contamination or a swap. These catch what reproducibility cannot: the right pipeline on the wrong tube.
  3. Truth-sample regression: NA12878/HG001 run end to end and scored against GIAB v4.2.1 with hap.py or vcfeval. The v4.2.1 high-confidence regions cover roughly 2.5 Gb of GRCh38, so SNV and indel precision/recall are meaningful numbers rather than vibes.
controlcatchespass criterion (example)blind spot
PhiX spike-ininstrument, base-call, trim failure≥90% aligned, mismatch ≤1%human-specific steps (BQSR, variant calling)
ERCC mix 1/2library prep and normalizationobserved fold-change within 2x of expected, R² ≥ 0.95DNA pipelines
SNP fingerprint / sex checksample swap, mislabeling≥95% concordance; X/Y coverage matches declared sexswap between two samples of the same sex and similar ancestry
VerifyBamID FREEMIXcross-contamination< 0.02contamination below detection
NA12878 vs GIAB v4.2.1caller, reference, filtering regressionsSNV F1 ≥ 0.99, indel F1 ≥ 0.97overfitting if the caller was tuned on NA12878

The gate has to be code. In Nextflow:

groovy process CHECK_CONTROLS { input: path metrics output: path 'control.ok' script: """ python check_controls.py --metrics $metrics --min-snv-f1 0.99 touch control.ok """ }

check_controls.py exits non-zero, the task fails, the run stops before publish. Snakemake is the same shape: a rule whose script raises. nf-core pipelines do this with -profile test plus nf-test assertions in CI, and the same assertions should run on every production batch, not only in CI.

Why 1% PhiX is enough: 400M reads × 1% = 4M PhiX reads × 151 bp ≈ 600M bases. At a 0.5% error rate that is ~3M errors, so the standard error on the error rate is about 1/√3M ≈ 0.06%: a doubling is obvious. Dropping to a 0.1% spike-in still gives ~60M bases, fine for error rate but too thin for phasing.

Where this goes wrong. The control runs on a side path the production samples never take (a --test profile that swaps the real aligner). The control result is cached and never re-executed: Nextflow's cache key covers a task's inputs, script and container, not the pipeline revision, so a change in a module the control does not touch leaves the stale control in place. The threshold gets loosened during an incident and never restored. The truth sample is the one the caller was tuned on, so F1 stays high while real samples regress. Detect all four by versioning control thresholds in the repo, running the truth sample on a fixed cadence with a fresh work directory, and alerting when the gate is skipped rather than when it fails.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and defend a workflow mechanism for workflow testing.

Answer

Assumptions first. "Workflow" here means a DAG orchestrator: Nextflow 24.04 or Snakemake 8: running containerised steps over files. "Testing" means catching a regression before it reaches production data, not proving the science is right. The mechanism I'd defend is a three-layer harness whose contract is a pinned semantic summary, not a byte-for-byte golden file.

The mechanism.

  1. Process contract tests (nf-test for Nextflow, --dry-run plus pytest for Snakemake). Each process gets a ~50 KB fixture and asserts on its own output: file exists, row count, header, one checksum of a normalised body.
  2. End-to-end tiny run. A licensed ~2 MB input with deliberate edge cases (one empty sample, one multi-allelic site, reads containing N) run through the whole DAG. The assertion is a 40-line summary TSV: per-step record counts, output file sizes, and a checksum of the sorted, normalised output body. Sorting and normalising is what makes it stable across thread counts and tool patch versions.
  3. Failure injection and resume. Kill the run with SIGKILL after the third process, rerun with nextflow run main.nf -profile test -resume, and assert the first three report CACHED while the rest execute, and that the final summary is identical to the uninterrupted run.

Why this shape, and what I rejected.

mechanismcatchesmissesCI cost
process unit tests onlywrong params, bad parsingcross-step format drift~10 s
byte-level golden fileseverything, loudlynothing, but fails on every tool bump~90 s
e2e + pinned semantic summaryadapter/format drift, wiringtool-internal numeric drift~90 s
failure injection + resumenon-idempotent steps, lost state—~2 min

The deciding criteria are false-failure rate and coverage of the failure you actually see. Byte-level goldens fail on thread-count-dependent ordering and on any container bump, so teams start ignoring them: that is worse than no test. Mocks never exercise the real adapter, and adapter and cross-step format errors only appear when actual formats and metadata flow end to end. So the spine is layers 2 and 3; layer 1 exists only to give a 10-second signal before the 90-second run.

Failure modes and how each is detected.

  • Stale golden summary. A legitimate algorithm change updates the summary. Detect it by requiring the summary file to change in the same commit as the code, and failing CI if the summary changed without an explicit --update-golden flag in the message.
  • Snapshot blessing a bug. A pinned summary will happily record a regression. Pair it with invariants that are independent of the snapshot: e.g. no emitted variant with QUAL < 20, no output row with a null sample ID, so a snapshot cannot ratify a known bug.
  • Toy data unlike production. The tiny input must contain at least one instance of each edge case you have seen in production; a fixture with only happy-path records passes while production fails.
  • Hidden network. Run CI in a container with egress blocked and assert the run still succeeds. If it needs the network, that is the finding.

The 90-second defence. A candidate should be able to say: the full pipeline takes ~6 hours on 4 cores; this harness takes ~90 seconds and catches the class of bug we actually ship. A changed field name between two steps. It does not catch a numerically wrong variant caller, and I would not claim it does. That is what the invariant assertions and a separate nightly full-data run are for. The resume test is the one people skip and the one that pays: it is the only layer that proves a killed production run can be restarted without recomputing or corrupting completed work.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and defend a workflow mechanism for continuous integration.

Answer

Assumptions I'd state first: GitHub Actions, one service repo, ~40 PRs/day, Python 3.12, image pushed to GHCR, main deploys continuously. If main is a staging branch with a nightly deploy instead, the merge-queue half of this is overkill.

The answer in 90 seconds. One reusable workflow, pinned by commit SHA, triggered on both pull_request and merge_group. Four stages, each consuming the previous stage's artifact: build → test → verify → publish. The build produces an image and records its digest; every later stage references ghcr.io/acme/api@sha256:…, never a tag. The authoritative gate is the merge_group run, because that runs on the commit that actually lands: two individually green PRs can still break main when merged.

Mechanism.

YAML
on: [pull_request, merge_group]
concurrency: {group: ci-${{ github.ref }}, cancel-in-progress: true}
jobs:
  build:
    runs-on: ubuntu-24.04
    timeout-minutes: 15
    permissions: {contents: read, packages: write, id-token: write}
    outputs: {digest: ${{ steps.push.outputs.digest }}}
    steps:
      - uses: actions/checkout@v4
      - uses: docker/build-push-action@v6
        id: push
        with: {push: true, tags: ghcr.io/acme/api:sha-${{ github.sha }}}
      - run: cosign sign --yes ghcr.io/acme/api@${{ steps.push.outputs.digest }}
  test:
    needs: build
    strategy: {matrix: {group: [1,2,3,4]}}
    steps:
      - run: pytest --splits 4 --group ${{ matrix.group }}
        env: {IMAGE: ghcr.io/acme/api@${{ needs.build.outputs.digest }}}
  verify:
    needs: [build, test]
    steps:
      - run: cosign verify ghcr.io/acme/api@${{ needs.build.outputs.digest }}
          --certificate-identity-regexp '^https://github.com/acme/api/\.github/workflows/ci\.yml@'
          --certificate-oidc-issuer https://token.actions.githubusercontent.com

id-token: write is what lets the build job sign keylessly through Fulcio; without it there is no signature for verify to check. timeout-minutes: 15 matters because a hung registry push otherwise sits for the 6-hour job default.

Arithmetic. 1,840 tests, 11m20s serial on a 2-vCPU runner. Four shards → longest shard 3m05s, so wall time ≈ 3m05s + 35s image pull. actions/cache@v4 keyed on hashFiles('poetry.lock') takes dependency install from 95s to 9s on a hit. PR feedback lands near 4 minutes; the merge_group re-run costs the same again.

Trade-off. Three trigger strategies:

strategytests what lands?costpick when
PR-only, merge on greennocheapestmain is staging, nightly deploy
merge queueyes+1 full run per PR, merges serializemain deploys continuously
post-merge verify + auto-revertyes, after the factrevert automation + rollback SLOvery high merge rate, minutes of bad main tolerable

Deciding criterion: cost of a broken main × how often it happens, versus the queue's added latency. At 40 PRs/day with continuous deploy, the queue wins.

Failure modes and detection.

  • Registry outage: build fails at push; detect from stage duration and the GHCR status page; the 15-minute timeout stops it hanging.
  • Mutable tag: assert the digest in the deploy manifest equals the build output; cosign verify fails on a digest mismatch.
  • Stale base image: pin FROM python:3.12-slim@sha256:…; a floating base is the usual cause of "works in CI, not in prod".
  • Platform mismatch: build --platform linux/amd64,linux/arm64 and smoke-test both; docker buildx imagetools inspect shows whether both manifests exist.
  • Skipped integration: a required check that never reports blocks the merge queue; keep the check name stable and don't gate it on draft or path filters.
  • Secret-dependent test: run the suite nightly with secrets unset; tests needing prod credentials are the ones that pass locally and fail in CI.
  • Workflow revision drift: uses: acme/ci/…@main moves under you; pin to a SHA and lint for @main/@v1 refs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and defend a workflow mechanism for privacy and isolation.

Answer

What I'd say first

Assume a multi-tenant batch pipeline that ingests PHI (FASTQ/VCF) and emits analysis results. The threat I'm defending against is reidentification and cross-tenant leakage through the workflow's own artifacts (logs, scratch, metadata) not a compromised host. If the host is compromised, isolation is gone; that's a different control.

The mechanism is a run-scoped identity boundary: every run gets a fresh 256-bit random salt, participant identifiers are replaced by HMAC-SHA256(salt, participant_id) truncated to 128 bits, compute runs in a per-run namespace with ephemeral volumes, and the salt is destroyed when the run ends. The only durable outputs are the de-identified result and an audit record. Because the salt never persists, two runs over the same participant produce unlinkable pseudonyms: that's the property the design defends.

How it works

Three layers, each with a job:

  • Identity: pseudonym = HMAC-SHA256(run_salt, participant_id)[:16]. The salt lives only in the run's secret, never in the output. 128-bit truncation keeps collision probability negligible for cohorts under 10^9.
  • Isolation: each run is a Kubernetes namespace with a NetworkPolicy denying cross-namespace traffic, an ephemeral emptyDir or CSI ephemeral volume, and a service account scoped to that run's bucket prefix only.
  • Cleanup: volumes are deleted on pod termination; failed-task scratch is deleted by a finalizer that runs even on abort.
Python
import hmac, hashlib, os

def pseudonym(participant_id: str, run_salt: bytes) -> str:
    return hmac.new(run_salt, participant_id.encode(), hashlib.sha256).hexdigest()[:32]

# run_salt = os.urandom(32), held in the run's secret, destroyed at run end

Trade-offs

The alternative is a stable, global pseudonym (one salt for the whole system). That lets you join a participant's results across runs, necessary for longitudinal cohorts, but it makes the pseudonym a persistent identifier: anyone who learns one mapping can link every run. Run-scoped salts trade joinability for unlinkability. Criterion: if the study needs cross-run joins, use a global salt held in an HSM and accept the linkage; if it doesn't, run-scoped is strictly safer. Don't use run-scoped when downstream analysis must reconcile the same participant across batches: you'll be forced to keep a mapping table, which reintroduces the linkage you removed.

Failure modes and detection

  • Scratch residue: a node keeps a failed task's volume. Detect with a node-level disk audit that lists files under the scratch root after each run; alert on any non-empty directory.
  • Telemetry leakage: the container runtime ships env vars or command lines to a log aggregator. Detect by scanning egress logs for the salt or participant IDs; the salt should never appear outside the run.
  • Backup outside retention: a snapshot of the run volume lands in a bucket with a 90-day lifecycle. Detect by scanning the backup catalog for run-scoped volumes and asserting zero.
LayerMechanismFailure it preventsDetection
Identityper-run 256-bit salt, HMAC-SHA256[:16]cross-run linkagesalt absent from all logs
Isolationper-run namespace + NetworkPolicy + scoped SAcross-tenant readegress log review
Cleanupephemeral volume + finalizerscratch residuepost-run disk audit

That's the design; the defense is that the salt's lifetime bounds the linkage window to a single run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and defend a workflow mechanism for FAIR packaging.

Answer

What I'd say first

FAIR packaging is a layered contract, not a file format. I'd assume three things: the release is a directory of files, the repository can mint DOIs, and some files are consent-bound while others are open. Given that, the mechanism is a publish gate that emits three artefacts per release: a DataCite DOI record for citation, an RO-Crate for structure, and a BagIt manifest for fixity, and refuses to publish if any cross-check fails.

The mechanism

Stage 1, fixity. Hash every file with SHA-256 into manifest-sha256.txt (BagIt, RFC 8493). This is what lets a downstream consumer prove the bytes didn't change in transit.

Stage 2, structure. Generate ro-crate-metadata.json at the crate root: JSON-LD, Schema.org terms, conformsTo the RO-Crate 1.1 spec. One entity per file or directory, one root Dataset entity:

JSON
{
  "@context": "https://w3id.org/ro/crate/1.1/context",
  "@graph": [
    {
      "@id": "ro-crate-metadata.json",
      "@type": "CreativeWork",
      "conformsTo": {"@id": "https://w3id.org/ro/crate/1.1"},
      "about": {"@id": "./"}
    },
    {
      "@id": "./",
      "@type": "Dataset",
      "name": "Trial X aggregate outcomes",
      "license": {"@id": "https://spdx.org/licenses/CC-BY-4.0"},
      "identifier": "https://doi.org/10.5281/zenodo.0000000",
      "hasPart": [{"@id": "aggregate.csv"}, {"@id": "raw/"}]
    },
    {
      "@id": "aggregate.csv",
      "@type": "File",
      "contentUrl": "aggregate.csv",
      "conditionsOfAccess": "public"
    },
    {
      "@id": "raw/",
      "@type": "Dataset",
      "conditionsOfAccess": "controlled",
      "license": {"@id": "https://example.org/consent/2024-07"},
      "url": "https://example.org/data-access-request"
    }
  ]
}

Stage 3, citation. Mint the DOI and register the six DataCite-mandatory properties: Identifier, Creator, Title, Publisher, PublicationYear, ResourceType. The DOI goes back into the crate as the root identifier, so the crate and the DOI record point at each other.

Stage 4, access tiering. Every file entity carries conditionsOfAccess. Open files are in the payload. Controlled files are represented as a stub entity with conditionsOfAccess: controlled, a license pointing at the consent terms, and a url for the access-request endpoint. The bytes never enter the public crate.

Stage 5, the gate. Before publish: run the RO-Crate validator (rocrate-validator), validate the DataCite record against the schema, HEAD every contentUrl, and diff the license field between crate and DOI record. Any failure blocks the release.

Why this layering and not something simpler

BagIt alone gives you fixity and transport but no semantics: a consumer can verify the bytes and still not know what they are. DataCite alone describes the dataset at the DOI level; it says nothing about the internal file structure, so a 400-file crate is opaque. RO-Crate alone has no fixity guarantee and no registry. Each layer covers what the others don't. The cost is three artefacts to keep in sync, which is exactly why the gate exists.

The real trade-off is embedded vs. catalog-only metadata. Embedded metadata survives the repository dying; catalog-only dies with it. But embedded metadata goes stale when the DOI record is updated. I'd make the crate the source of truth for structure and the DOI record the source of truth for citation, and reconcile them in the gate rather than trying to keep one authoritative.

Failure modes and how I'd catch them

failuredetection
dead identifierweekly link-checker follows https://doi.org/<doi>; alert on non-200 or a redirect off the registered landing page
metadata reidentificationNER scan over every free-text field plus a k-anonymity check on quasi-identifiers, run in the gate
license driftcrate license vs. DataCite rightsList diffed in the gate; mismatch fails the build
inaccessible dependencyHEAD on every contentUrl; 404 fails the build
open derivative beyond consentPROV-O lineage: if any input entity is controlled, require a recorded human sign-off entity before publish

That's the design. The one thing I'd defend hardest is the gate: without it, the three artefacts drift and you get a crate that claims CC-BY while the DOI says all rights reserved, which is worse than no packaging at all.

Curated: · Written: · Reviewed:

Difficulty: Hard