11 tháng 02, 2026

Chuyển pipeline nội bộ sang workflow manager: khung xác thực ba bước

Chuyển pipeline nội bộ sang workflow manager: khung xác thực ba bước

Dù một lab dùng script bash, workflow Python, pipeline Snakemake hay giải pháp tự viết, pipeline nội bộ thường chạy tốt ở cục bộ. Nó có thể đã chạy nhiều năm. Nhưng khi nghiên cứu mở rộng, chính pipeline đó trở nên khó tái lập giữa các nhóm và cần sửa thủ công thường xuyên.

Workflow manager giúp giải quyết việc này, nhưng trước khi chuyển toàn bộ pipeline sang Nextflow (hoặc bất kỳ workflow manager chuyên nghiệp nào), cần trả lời câu hỏi khó nhất trước: pipeline mới có cho ra cùng kết quả không? Bài này mô tả một khung ba bước để chuyển một pipeline bioinformatics mà vẫn giữ kết quả có thể so sánh được: thiết lập baseline tái lập, kiểm soát hành vi phi tất định, và xác thực output so với baseline. Với việc chuyển sang Nextflow cụ thể, nf-test có thể tự động hoá phần lớn bước xác thực.

Vì sao workflow manager giúp ích

Một pipeline nội bộ (bash, Python, Snakemake, hoặc tự viết) thường không mở rộng ra ngoài chiếc máy nó được viết. Chuyển sang workflow manager thay đổi một số điều:

Vấn đề của pipeline nội bộ:

  • Chạy trên máy của một người, và chỉ một người hiểu nó
  • Phiên bản công cụ không được ghi lại và lệch giữa các môi trường
  • Kết quả khó tái lập giữa các thành viên, nền tảng, hoặc theo thời gian
  • Mở rộng từ 10 mẫu lên 1000 thường đòi hỏi sửa lại đáng kể
  • Khó chia sẻ với cộng tác viên, khó công bố cùng nghiên cứu, khó tích hợp với hệ thống tính toán của tổ chức
  • Không có audit trail cho yêu cầu pháp lý hoặc tuân thủ

Lợi ích của workflow manager (Nextflow, Snakemake, hoặc CWL):

  • Đóng gói container, quản lý bằng version control, tự ghi tài liệu
  • Kết quả tái lập đến từng byte trên nhiều nền tảng (từ laptop đến HPC đến cloud)
  • Mở rộng từ 1 mẫu lên nhiều mẫu mà không cần sửa
  • Có thể chia sẻ, trích dẫn, kiểm toán
  • Tích hợp với hệ thống HPC, nền tảng cloud, và pipeline dữ liệu của tổ chức
  • Hỗ trợ gốc cho giám sát, logging và phục hồi khi lỗi

Rủi ro tiềm ẩn khi chuyển pipeline

Một pipeline nội bộ là một khối tri thức của tổ chức. Nó thường được xây dần theo thời gian, chưa bao giờ được thiết kế để tái lập giữa các nhóm, và có thể chứa những điểm đặc thù không được ghi lại mà nhờ đó nó chạy được. Viết lại nó bằng Nextflow rồi giả định kết quả giống hệt là điều rủi ro.

Việc chuyển đổi có thể đưa vào những lỗi tinh vi khó phát hiện: một biến thể được gọi khác đi, một read bị lọc mất, một ngưỡng hơi khác, một file được xử lý theo thứ tự khác. Đôi khi tác động sinh học là nhỏ, nhưng nếu không có cách truy vết đã thay đổi điều gì, sự khác biệt sẽ khó giải thích.

Trước khi thay pipeline nội bộ bằng workflow manager, cần ba thứ:

  1. Một snapshot baseline (checksum MD5) về cái "đúng" trông như thế nào từ pipeline gốc
  2. Kiểm soát tường minh hành vi phi tất định (seed ngẫu nhiên hard-code)
  3. Xác thực từng byte rằng pipeline mới khớp với pipeline cũ

Khung này giống nhau bất kể nguồn là gì. Công cụ khác nhau tuỳ đích: với việc chuyển sang Nextflow, nf-test có thể tự động hoá phần lớn quá trình này.


Bước 1: Thiết lập baseline tái lập bằng snapshot MD5

Bước đầu tiên là một "golden standard": output đã được xác minh từ pipeline nội bộ gốc, dùng làm tham chiếu. Baseline này độc lập với workflow manager đích.

1.1 Ghi lại pipeline gốc

Tạo một script ghi lại mọi thứ:

#!/bin/bash
# original_pipeline.sh - Reference implementation with full documentation
set -euo pipefail
# Configuration
REFERENCE="/data/reference/hg38.fasta"
READS="/data/reads/sample.fastq"
OUTPUT_DIR="/results/baseline"
MANIFEST="${OUTPUT_DIR}/manifest.txt"
# Create output directory
mkdir -p "${OUTPUT_DIR}"
# Record software versions
echo "=== Pipeline Execution Record ===" > "${MANIFEST}"
echo "Date: $(date -Iseconds)" >> "${MANIFEST}"
echo "" >> "${MANIFEST}"
echo "=== Software Versions ===" >> "${MANIFEST}"
echo "bwa: $(bwa 2>&1 | grep Version)" >> "${MANIFEST}"
echo "samtools: $(samtools --version | head -1)" >> "${MANIFEST}"
echo "bcftools: $(bcftools --version | head -1)" >> "${MANIFEST}"
echo "" >> "${MANIFEST}"
# Record input file hashes
echo "=== Input File Checksums ===" >> "${MANIFEST}"
md5sum "${REFERENCE}" >> "${MANIFEST}"
md5sum "${READS}" >> "${MANIFEST}"
echo "" >> "${MANIFEST}"
# Step 1: Alignment
echo "=== Step 1: BWA Alignment ===" >> "${MANIFEST}"
bwa mem -t 8 "${REFERENCE}" "${READS}" | \
samtools sort -@ 4 -o "${OUTPUT_DIR}/aligned.bam" -
md5sum "${OUTPUT_DIR}/aligned.bam" >> "${MANIFEST}"
echo "aligned.bam: $(md5sum ${OUTPUT_DIR}/aligned.bam | cut -d' ' -f1)"
# Step 2: Mark Duplicates
echo "=== Step 2: Mark Duplicates ===" >> "${MANIFEST}"
samtools markdup "${OUTPUT_DIR}/aligned.bam" "${OUTPUT_DIR}/marked.bam"
md5sum "${OUTPUT_DIR}/marked.bam" >> "${MANIFEST}"
echo "marked.bam: $(md5sum ${OUTPUT_DIR}/marked.bam | cut -d' ' -f1)"
# Step 3: Call Variants
echo "=== Step 3: Call Variants ===" >> "${MANIFEST}"
bcftools mpileup -f "${REFERENCE}" "${OUTPUT_DIR}/marked.bam" | \
bcftools call -m -o "${OUTPUT_DIR}/variants.vcf"
md5sum "${OUTPUT_DIR}/variants.vcf" >> "${MANIFEST}"
echo "variants.vcf: $(md5sum ${OUTPUT_DIR}/variants.vcf | cut -d' ' -f1)"
echo ""
echo "Baseline execution complete. Manifest saved to: ${MANIFEST}"
cat "${MANIFEST}"

1.2 Chạy pipeline gốc nhiều lần

Chạy pipeline nhiều lần với cùng input để kiểm tra tính tất định:

#!/bin/bash
# Verify pipeline reproducibility
RUNS=3
REFERENCE_DIR="/results/baseline"
echo "Running original pipeline $RUNS times..."
for i in $(seq 1 $RUNS); do
OUTPUT_DIR="/results/baseline_run_$i"
bash original_pipeline.sh > /tmp/run_$i.log 2>&1
done
# Compare outputs
echo ""
echo "=== Reproducibility Check ==="
md5sum "${REFERENCE_DIR}/aligned.bam" /results/baseline_run_*/aligned.bam
md5sum "${REFERENCE_DIR}/marked.bam" /results/baseline_run_*/marked.bam
md5sum "${REFERENCE_DIR}/variants.vcf" /results/baseline_run_*/variants.vcf
# Extract just the checksums and compare
BASELINE_ALIGNED=$(md5sum "${REFERENCE_DIR}/aligned.bam" | cut -d' ' -f1)
BASELINE_MARKED=$(md5sum "${REFERENCE_DIR}/marked.bam" | cut -d' ' -f1)
BASELINE_VARIANTS=$(md5sum "${REFERENCE_DIR}/variants.vcf" | cut -d' ' -f1)
echo ""
echo "Baseline checksums:"
echo " aligned.bam: $BASELINE_ALIGNED"
echo " marked.bam: $BASELINE_MARKED"
echo " variants.vcf: $BASELINE_VARIANTS"

Output mong đợi nếu pipeline tất định:

98a4d5f8c7b2e9f3a1d6c4b5 /results/baseline/aligned.bam
98a4d5f8c7b2e9f3a1d6c4b5 /results/baseline_run_1/aligned.bam
98a4d5f8c7b2e9f3a1d6c4b5 /results/baseline_run_2/aligned.bam
98a4d5f8c7b2e9f3a1d6c4b5 /results/baseline_run_3/aligned.bam
All checksums match - Pipeline is deterministic!

1.3 Ghi lại các công cụ phi tất định

Một số công cụ bioinformatics sinh output phi tất định theo thiết kế (seed ngẫu nhiên, độ chính xác dấu phẩy động, thứ tự luồng). Cần xác định và xử lý chúng tường minh:

Terminal window
# Tools that need seed control
# These must be configured with hard-coded seeds
# Example 1: Tools with random sampling (seqtk)
seqtk sample -s 42 reads.fastq 0.5 > sampled.fastq
# Example 2: Tools with randomized output order (bowtie2 with threading)
bowtie2 --seed 42 -p 8 -x index -U reads.fastq -S output.sam
# Example 3: Python-based tools with numpy/scipy randomness
python process.py --seed 42
# Example 4: R-based tools
# In R script:
set.seed(42)

Tạo một tài liệu ánh xạ:

# Non-Deterministic Tools in Our Pipeline
| Tool | Reason | Solution |
| ------------------- | ---------------------- | -------------------- |
| seqtk sample | Random sampling | Use --seed 42 |
| bowtie2 | Thread-based shuffling | Use --seed 42 |
| custom_py_script.py | numpy random | Set seed in code |
| variant_filter.R | R randomization | set.seed(42) in code |
All tools must use hard-coded seeds (42 chosen arbitrarily).

1.4 Lưu manifest baseline

Tạo một baseline có đánh phiên bản mà các pipeline về sau phải khớp:

Terminal window
# baseline_checksums.txt
# Generated: 2026-02-11T10:30:00Z
# Pipeline Version: 1.0
# Tools: bwa-0.7.17, samtools-1.18, bcftools-1.18
aligned.bam:98a4d5f8c7b2e9f3a1d6c4b5e2f3g4h5
marked.bam: a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7
variants.vcf: x9y8z7w6v5u4t3s2r1q0p9o8n7m6l5k4

Bước 2: Chuyển sang Nextflow với kiểm soát seed

Bước tiếp theo là chuyển pipeline bash sang Nextflow trong khi giữ hành vi tất định thông qua kiểm soát seed.

2.1 Tạo các process Nextflow với seed

Chuyển từng bước bash thành một process Nextflow, đặt seed tường minh:

modules/bwa_align.nf
process BWA_ALIGN {
tag "$meta.id"
label 'process_high'
container 'community.wave.seqera.io/library/bwa_samtools:56c9f8d5201889a4'
input:
tuple val(meta), path(reads)
path reference
path reference_index
output:
tuple val(meta), path("*.bam"), emit: bam
path "versions.yml", emit: versions
script:
"""
# Seed control: bwa uses thread-based order
# To maintain determinism, use single-threaded or
# use sorted output from samtools
bwa mem \\
-t ${task.cpus} \\
${reference} \\
${reads} | \\
samtools sort \\
-@ ${task.cpus} \\
-o ${meta.id}.bam \\
-
# Verify output
samtools view -c ${meta.id}.bam
cat <<-END_VERSIONS > versions.yml
"${task.process}":
bwa: \$(echo \$(bwa 2>&1) | sed 's/^.*Version: //; s/Contact:.*\$//')
samtools: \$(echo \$(samtools --version 2>&1) | sed 's/^.*samtools //; s/Using.*\$//')
END_VERSIONS
"""
}
modules/mark_duplicates.nf
process MARK_DUPLICATES {
tag "$meta.id"
label 'process_medium'
container 'community.wave.seqera.io/library/samtools:1.18'
input:
tuple val(meta), path(bam)
output:
tuple val(meta), path("*marked.bam"), emit: bam
path "versions.yml", emit: versions
script:
"""
# samtools markdup is deterministic when input is sorted
samtools markdup \\
-M \\
${bam} \\
${meta.id}.marked.bam
cat <<-END_VERSIONS > versions.yml
"${task.process}":
samtools: \$(echo \$(samtools --version 2>&1) | sed 's/^.*samtools //; s/Using.*\$//')
END_VERSIONS
"""
}
modules/call_variants.nf
process CALL_VARIANTS {
tag "$meta.id"
label 'process_medium'
container 'community.wave.seqera.io/library/bcftools:1.18'
input:
tuple val(meta), path(bam)
path reference
output:
tuple val(meta), path("*.vcf"), emit: vcf
path "versions.yml", emit: versions
script:
"""
# bcftools is deterministic when output format is sorted
bcftools mpileup \\
-f ${reference} \\
${bam} | \\
bcftools call \\
-m \\
-o ${meta.id}.variants.vcf
# Sort VCF for reproducibility
vcf-sort ${meta.id}.variants.vcf > ${meta.id}.variants.sorted.vcf
mv ${meta.id}.variants.sorted.vcf ${meta.id}.variants.vcf
cat <<-END_VERSIONS > versions.yml
"${task.process}":
bcftools: \$(echo \$(bcftools --version 2>&1) | sed 's/^.*bcftools //; s/ .*\$//')
END_VERSIONS
"""
}

2.2 Tạo workflow chính

nextflow.config
process {
shell = ['/bin/bash', '-euo', 'pipefail']
withLabel: process_high {
cpus = 8
memory = { 16.GB * task.attempt }
time = { 4.h * task.attempt }
}
withLabel: process_medium {
cpus = 4
memory = { 8.GB * task.attempt }
time = { 2.h * task.attempt }
}
}
profiles {
docker {
docker.enabled = true
}
singularity {
singularity.enabled = true
}
standard {
process.executor = 'local'
}
}
main.nf
include { BWA_ALIGN } from './modules/bwa_align'
include { MARK_DUPLICATES } from './modules/mark_duplicates'
include { CALL_VARIANTS } from './modules/call_variants'
workflow {
// Input channel
input_samples = Channel
.fromPath(params.input_dir + '/*.fastq')
.map { file ->
def meta = [id: file.baseName]
tuple(meta, file)
}
// Reference files
reference = file(params.reference)
reference_index = file(params.reference + '.bwt')
// Run pipeline
BWA_ALIGN(input_samples, reference, reference_index)
MARK_DUPLICATES(BWA_ALIGN.out.bam)
CALL_VARIANTS(MARK_DUPLICATES.out.bam, reference)
}
params.yaml
input_dir: './data/reads'
reference: './data/reference/hg38.fasta'

Bước 3: Xác thực bằng so sánh MD5

Sau khi chạy pipeline Nextflow, so sánh output với baseline một cách có hệ thống.

3.1 Tạo script xác thực

#!/bin/bash
# validate_migration.sh - Compare Nextflow outputs with bash baseline
set -euo pipefail
BASELINE_DIR="/results/baseline"
NEXTFLOW_DIR="/results/nextflow"
VALIDATION_REPORT="/results/validation_report.txt"
{
echo "=== Pipeline Migration Validation Report ==="
echo "Generated: $(date -Iseconds)"
echo ""
# Function to compare checksums
compare_file() {
local filename=$1
local baseline="${BASELINE_DIR}/${filename}"
local migrated="${NEXTFLOW_DIR}/${filename}"
if [ ! -f "$baseline" ]; then
echo "BASELINE MISSING: $filename"
return 1
fi
if [ ! -f "$migrated" ]; then
echo "MIGRATED MISSING: $filename"
return 1
fi
local baseline_md5=$(md5sum "$baseline" | cut -d' ' -f1)
local migrated_md5=$(md5sum "$migrated" | cut -d' ' -f1)
if [ "$baseline_md5" == "$migrated_md5" ]; then
echo "PASS: $filename"
echo " MD5: $baseline_md5"
return 0
else
echo "FAIL: $filename"
echo " Baseline MD5: $baseline_md5"
echo " Migrated MD5: $migrated_md5"
return 1
fi
}
# Compare all output files
echo "=== File Comparisons ==="
declare -i pass=0
declare -i fail=0
for file in aligned.bam marked.bam variants.vcf; do
if compare_file "$file"; then
((pass++))
else
((fail++))
fi
done
echo ""
echo "=== Summary ==="
echo "Passed: $pass"
echo "Failed: $fail"
echo ""
if [ $fail -eq 0 ]; then
echo "VALIDATION SUCCESSFUL: All outputs match baseline!"
exit 0
else
echo "VALIDATION FAILED: $fail file(s) differ from baseline"
exit 1
fi
} | tee "$VALIDATION_REPORT"

3.2 Chạy so sánh

#!/bin/bash
# Run the migration validation
# First, ensure baseline exists
if [ ! -d "/results/baseline" ]; then
echo "Error: Baseline not found. Run original_pipeline.sh first."
exit 1
fi
# Run Nextflow pipeline
echo "Running Nextflow migration..."
nextflow run main.nf \
--input_dir ./data/reads \
--reference ./data/reference/hg38.fasta \
-profile docker \
-resume
# Validate outputs
echo ""
echo "Validating migration..."
bash validate_migration.sh

3.3 Phân tích diff chi tiết cho file không khớp

Nếu checksum không khớp, hãy điều tra khác biệt:

#!/bin/bash
# deep_diff.sh - Detailed analysis of differences
BASELINE=$1
MIGRATED=$2
FILENAME=$(basename "$BASELINE")
echo "=== Detailed Comparison: $FILENAME ==="
# 1. Check file sizes
BASELINE_SIZE=$(stat -f%z "$BASELINE" 2>/dev/null || stat -c%s "$BASELINE")
MIGRATED_SIZE=$(stat -f%z "$MIGRATED" 2>/dev/null || stat -c%s "$MIGRATED")
echo "File sizes:"
echo " Baseline: $BASELINE_SIZE bytes"
echo " Migrated: $MIGRATED_SIZE bytes"
if [ "$BASELINE_SIZE" != "$MIGRATED_SIZE" ]; then
echo " Size difference detected"
fi
# 2. For BAM files: compare with samtools
if [[ "$FILENAME" == *.bam ]]; then
echo ""
echo "BAM file analysis:"
# Compare read counts
BASELINE_READS=$(samtools view -c "$BASELINE")
MIGRATED_READS=$(samtools view -c "$MIGRATED")
echo " Baseline reads: $BASELINE_READS"
echo " Migrated reads: $MIGRATED_READS"
if [ "$BASELINE_READS" != "$MIGRATED_READS" ]; then
echo " Read count mismatch!"
fi
# Compare first 10 reads
echo ""
echo " First 10 reads comparison:"
echo " --- Baseline ---"
samtools view "$BASELINE" | head -10
echo " --- Migrated ---"
samtools view "$MIGRATED" | head -10
fi
# 3. For VCF files: compare variants
if [[ "$FILENAME" == *.vcf ]]; then
echo ""
echo "VCF file analysis:"
# Count variants (skip header)
BASELINE_VARS=$(grep -v "^#" "$BASELINE" | wc -l)
MIGRATED_VARS=$(grep -v "^#" "$MIGRATED" | wc -l)
echo " Baseline variants: $BASELINE_VARS"
echo " Migrated variants: $MIGRATED_VARS"
if [ "$BASELINE_VARS" != "$MIGRATED_VARS" ]; then
echo " Variant count mismatch!"
fi
# Show first differences
echo ""
echo " First 5 variants (baseline vs migrated):"
diff <(grep -v "^#" "$BASELINE" | head -5) <(grep -v "^#" "$MIGRATED" | head -5) || true
fi
# 4. Compare line-by-line for text files
if [[ "$FILENAME" == *.vcf || "$FILENAME" == *.txt ]]; then
echo ""
echo "Line-by-line diff (first 20 differences):"
diff "$BASELINE" "$MIGRATED" | head -20 || true
fi

3.4 Xử lý khác biệt được chấp nhận

Một số khác biệt là chấp nhận được. Hãy ghi lại chúng:

# Known Acceptable Differences Between Bash and Nextflow
## 1. Tool Versions
- Bash: bwa 0.7.17, samtools 1.18
- Nextflow: bwa 0.7.17, samtools 1.18
→ If versions match, output should be identical
## 2. Threading Order (BAM files)
- Threading can affect read order in BAM files
- Solution: Use `samtools sort` or deterministic sort
- Verification: Extract and compare SAM headers + sort order
## 3. VCF Header Timestamps
- VCF files may have different generation timestamps
- Solution: Strip headers before comparison
Terminal window
# Compare VCF ignoring header differences
compare_vcf_body() {
local baseline=$1
local migrated=$2
diff \
<(grep -v "^##" "$baseline" | grep -v "^#CHROM" | sort) \
<(grep -v "^##" "$migrated" | grep -v "^#CHROM" | sort)
}
# Compare BAM files by extracting SAM
compare_bam_content() {
local baseline=$1
local migrated=$2
diff \
<(samtools view "$baseline" | sort -k1,1) \
<(samtools view "$migrated" | sort -k1,1)
}

Ví dụ thực tế: một lần chuyển đổi trọn vẹn

Pipeline bash gốc

variant_calling_pipeline.sh
#!/bin/bash
set -euo pipefail
SAMPLE="sample_001"
REFERENCE="/ref/hg38.fasta"
READS="/data/${SAMPLE}.fastq.gz"
OUTPUT_DIR="/results/bash_original"
mkdir -p "$OUTPUT_DIR"
# Step 1: Alignment
bwa mem -t 8 "$REFERENCE" <(gunzip -c "$READS") | \
samtools sort -@ 4 -o "$OUTPUT_DIR/${SAMPLE}.aligned.bam" -
# Step 2: Mark Duplicates
samtools markdup "$OUTPUT_DIR/${SAMPLE}.aligned.bam" \
"$OUTPUT_DIR/${SAMPLE}.marked.bam"
# Step 3: Index
samtools index "$OUTPUT_DIR/${SAMPLE}.marked.bam"
# Step 4: Call variants
bcftools mpileup -f "$REFERENCE" "$OUTPUT_DIR/${SAMPLE}.marked.bam" | \
bcftools call -m -o "$OUTPUT_DIR/${SAMPLE}.vcf"
# Generate checksums
cd "$OUTPUT_DIR"
md5sum *.bam *.vcf > checksums.txt

Chuyển sang Nextflow

// main.nf - Migrated to Nextflow
workflow VARIANT_CALLING {
Channel
.fromPath(params.reads)
.map { file -> [file.baseName, file] }
.set { input_reads }
BWA_ALIGN(input_reads, params.reference)
MARK_DUPLICATES(BWA_ALIGN.out.bam)
CALL_VARIANTS(MARK_DUPLICATES.out.bam, params.reference)
}

Kết quả xác thực

Terminal window
$ bash validate_migration.sh
=== Pipeline Migration Validation Report ===
Generated: 2026-02-11T15:45:30Z
=== File Comparisons ===
PASS: sample_001.aligned.bam
MD5: 98a4d5f8c7b2e9f3a1d6c4b5e2f3g4h5
PASS: sample_001.marked.bam
MD5: a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7
PASS: sample_001.vcf
MD5: x9y8z7w6v5u4t3s2r1q0p9o8n7m6l5k4
=== Summary ===
Passed: 3
Failed: 0
VALIDATION SUCCESSFUL: All outputs match baseline!

Tự động hoá xác thực với nf-test (cho việc chuyển sang Nextflow)

Cách xác thực thủ công ở trên hoạt động cho mọi lần chuyển pipeline nội bộ. Với việc chuyển sang Nextflow cụ thể, nf-test có thể tự động hoá một phần công việc đó.

nf-test là một framework kiểm thử cho pipeline Nextflow. Nó hỗ trợ quy trình snapshot MD5 và xác thực ở trên, giúp việc xác thực chuyển đổi có thể tái lập hơn.

Vì sao nf-test giúp ích cho việc chuyển sang Nextflow

Cách xác thực thủ công:

  • Sinh checksum baseline thủ công
  • Tạo script xác thực tuỳ biến
  • Duy trì logic so sánh riêng
  • Khó chia sẻ với các thành viên trong nhóm

Cách dùng nf-test:

  • Sinh snapshot tự động
  • Quản lý snapshot bằng version control trong git
  • So sánh MD5 có sẵn
  • Chạy trong pipeline CI/CD
  • Thân thiện với nhóm: snapshot được theo dõi bằng git

Dùng nf-test để xác thực việc chuyển đổi

tests/modules/bwa_align.nf.test
nextflow_process {
name "Test BWA_ALIGN"
script "modules/bwa_align.nf"
process "BWA_ALIGN"
test("Should align reads to reference") {
when {
process {
input[0] = [[id: "sample1"], file("data/reads.fastq")]
input[1] = file("data/reference.fasta")
input[2] = file("data/reference.fasta.bwt")
}
}
then {
assertAll(
{ assert process.success },
{ assert snapshot(process.out.bam).match() },
{ assert path(process.out.bam[0][1]).exists() }
)
}
}
}

Điều gì xảy ra:

  1. Lần chạy đầu: nf-test sinh một snapshot checksum MD5 của file BAM
  2. Snapshot được lưu trong tests/modules/bwa_align.nf.test.snap
  3. Các lần chạy sau: nf-test so sánh output với snapshot
  4. Nếu có gì thay đổi: nf-test báo cáo khác biệt
  5. Cập nhật snapshot bằng nf-test test tests/modules/bwa_align.nf.test --update-snapshot khi thay đổi là có chủ đích

Ví dụ file snapshot (được sinh tự động)

tests/modules/bwa_align.nf.test.snap
{
"Should align reads to reference": {
"content": [
{
"0": [
[
{
"id": "sample1"
},
"sample1.bam:98a4d5f8c7b2e9f3a1d6c4b5e2f3g4h5"
]
],
"bam": [
[
{
"id": "sample1"
},
"sample1.bam:98a4d5f8c7b2e9f3a1d6c4b5e2f3g4h5"
]
]
}
],
"timestamp": "2026-02-11T15:45:30Z"
}
}

Kiểm thử toàn bộ việc chuyển đổi với nf-test

Tạo các test toàn diện cho cả pipeline:

tests/workflows/variant_calling.nf.test
nextflow_workflow {
name "Test Complete Variant Calling Pipeline"
script "workflows/variant_calling.nf"
workflow "VARIANT_CALLING"
test("Complete pipeline: reads to variants") {
when {
workflow {
input[0] = [[id: "sample1"], file("data/reads.fastq.gz")]
}
}
then {
assertAll(
{ assert workflow.success },
// Snapshot bam output
{ assert snapshot(workflow.out.bam).match() },
// Snapshot vcf output
{ assert snapshot(workflow.out.vcf).match() },
// Verify intermediate files
{ assert path(workflow.out.bam[0][1]).exists() },
{ assert path(workflow.out.vcf[0][1]).exists() }
)
}
}
}

Chạy nf-test trong quy trình chuyển đổi

Terminal window
# Generate initial snapshots from your Nextflow pipeline
nf-test test tests/main.nf.test --update-snapshot
# Compare against baseline (this is your validation step 3!)
nf-test test tests/main.nf.test
# If tests fail, review the diff
# If diff is intentional, update snapshots
nf-test test tests/main.nf.test --update-snapshot
# Run specific test file
nf-test test tests/workflows/variant_calling.nf.test
# Run in CI/CD to catch regressions
# .github/workflows/test.yml
- name: Test Nextflow Pipeline
run: nf-test test tests/ --profile docker

Quy trình chuyển đổi trọn vẹn với nf-test

  1. Bước 1 (pipeline gốc): sinh snapshot MD5 làm baseline

  2. Bước 2 (chuyển sang Nextflow): viết pipeline Nextflow và các test nf-test

  3. Bước 3 (xác thực với nf-test):

    Terminal window
    # Generate initial snapshots from migrated Nextflow pipeline
    nf-test test tests/main.nf.test --update-snapshot
    # Run: nf-test test tests/main.nf.test
    # nf-test automatically compares against baseline!

Lợi ích của nf-test so với xác thực thủ công

Aspect Manual Validation nf-test
Snapshot generation Manual scripting Automatic
Version control External files Git-tracked
Team collaboration Share scripts Share snapshots
Regression detection Manual comparison Automatic CI/CD
Update process Rerun scripts nf-test test --update-snapshot
Documentation Separate docs Tests are docs
Maintenance High effort Low effort

Những điểm cần cân nhắc và best practices

1. Pin phiên bản

Pin phiên bản công cụ trong cả hai pipeline:

Terminal window
# Bash
bwa 0.7.17
samtools 1.18.0
bcftools 1.18
# Nextflow (container)
container 'community.wave.seqera.io/library/bwa_samtools:56c9f8d5201889a4'
# Container hash includes specific versions

2. Xử lý độ chính xác dấu phẩy động

Một số công cụ sinh giá trị dấu phẩy động hơi khác nhau do khác biệt về biên dịch hoặc CPU:

Terminal window
# For VCF QUAL scores, allow small differences
compare_vcf_quality() {
local baseline=$1
local migrated=$2
local tolerance=0.1
# Extract QUAL scores and compare with tolerance
paste \
<(grep -v "^#" "$baseline" | awk '{print $6}') \
<(grep -v "^#" "$migrated" | awk '{print $6}') | \
awk -v tol=$tolerance '{
diff = ($1 - $2)
if (diff < 0) diff = -diff
if (diff > tol && $1 != ".") {
print "DIFFER: " $1 " vs " $2
}
}'
}

3. Mẫu tài liệu

Một checklist chuyển đổi:

# Pipeline Migration Checklist
## Pre-Migration
- [ ] Document original bash pipeline
- [ ] Record all tool versions
- [ ] Generate baseline MD5 checksums
- [ ] Test reproducibility (3+ runs)
- [ ] Identify non-deterministic components
## Migration
- [ ] Convert each step to Nextflow process
- [ ] Set seeds for random operations
- [ ] Configure containerization
- [ ] Implement resource directives
- [ ] Add error handling
## Validation
- [ ] Run Nextflow with same inputs
- [ ] Generate MD5 checksums
- [ ] Compare all outputs
- [ ] Document acceptable differences
- [ ] Validate on multiple samples
## Sign-Off
- [ ] All checksums match or differences documented
- [ ] Code review completed
- [ ] Team approval
- [ ] Migration complete

Tóm tắt

Dù chuyển từ script bash, workflow Python, pipeline Snakemake, công cụ C++ tự viết, hay bất cứ thứ gì khác, cùng một khung xác thực ba bước đều áp dụng được. Cách tiếp cận dựa trên MD5 không phụ thuộc ngôn ngữ.

Bước 1: Thiết lập baseline

  • Chạy pipeline gốc nhiều lần
  • Kiểm tra tính tất định (cùng input = cùng output)
  • Ghi lại checksum MD5 của mọi output
  • Ghi lại phiên bản công cụ và seed
  • Áp dụng cho: bash, Python, Snakemake, code tự viết, v.v.

Bước 2: Chuyển đổi với kiểm soát seed

  • Chuyển từng bước pipeline sang định dạng đích
  • Hard-code seed cho các thao tác ngẫu nhiên
  • Dùng container để khớp phiên bản công cụ
  • Giữ cấu hình tài nguyên giống nhau
  • Đích: Nextflow, Snakemake, CWL, v.v.

Bước 3: Xác thực bằng checksum

  • Chạy pipeline mới với cùng input
  • Sinh checksum MD5 cho mọi output
  • So sánh với baseline
  • Ghi lại những khác biệt chấp nhận được
  • Xác nhận hoàn tất chuyển đổi

Nếu đích là Nextflow: nf-test có thể tự động hoá một phần bước 2 và 3 với quản lý snapshot và tích hợp CI/CD.

Những điểm chính

  1. Khung ba bước áp dụng cho mọi pipeline nội bộ — dù từ bash, Python, Snakemake hay code tự viết, cách tiếp cận dựa trên MD5 không phụ thuộc ngôn ngữ.
  2. Checksum MD5 là tham chiếu — chúng xác minh từng byte rằng output giống hệt nhau, bất kể định dạng nguồn hay đích.
  3. Tái lập đòi hỏi kiểm soát seed tường minh — mọi thao tác phi tất định nên dùng seed hard-code (42 là lựa chọn tuỳ ý; hãy dùng con số phù hợp với nhóm của bạn).
  4. Pin phiên bản quan trọng — dùng container để đảm bảo phiên bản công cụ giống nhau giữa pipeline gốc và pipeline đã chuyển.
  5. Ghi lại mọi thứ — ghi lại phiên bản, seed, checksum và những khác biệt chấp nhận được để nhóm hiểu.
  6. Xác thực trên nhiều mẫu — khác biệt có thể chỉ xuất hiện với một số đặc điểm dữ liệu hoặc trường hợp biên.
  7. Nếu chuyển sang Nextflow, cân nhắc nf-test — nó tự động hoá một phần quy trình xác thực với snapshot được quản lý bằng version control và tích hợp CI/CD.
  8. Làm cho lỗi hiển thị rõ — dùng set -o pipefail và kiểm tra lỗi tường minh trong cả hai pipeline.

Sau khi output đã được xác thực, pipeline nội bộ có thể được thay bằng workflow manager mà vẫn giữ kết quả có thể so sánh được, đồng thời nhận các lợi ích của quản lý workflow chuyên nghiệp.

Tài liệu tham khảo

Bài viết liên quan

Xem tất cả bài viết →