Metadata-Version: 2.4
Name: sfprov
Version: 0.1.5
Summary: Extract and store workflow provenance from RO-Crate and Nextflow DAG files.
Author-email: Jaffar GURA <jaffar.gura@dauphine.psl.eu>
License-Expression: AGPL-3.0-only
Project-URL: Repository, https://gitlab.liris.cnrs.fr/sharefair/provenance/sfprov
Project-URL: Bug Tracker, https://gitlab.liris.cnrs.fr/sharefair/provenance/sfprov/-/issues
Project-URL: Changelog, https://gitlab.liris.cnrs.fr/sharefair/provenance/sfprov/-/blob/master/CHANGELOG.md
Keywords: provenance,nextflow,nf-core,bioinformatics,genomics,ngs,workflow,lineage,ro-crate,fair,neo4j,opensearch
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: English
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Database
Classifier: Topic :: System :: Archiving
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: neo4j>=5.0
Requires-Dist: pydantic>=2.0
Requires-Dist: argcomplete>=3.0
Requires-Dist: opensearch-py>=2.0
Requires-Dist: biopython>=1.80
Requires-Dist: pdfminer.six>=20221105
Requires-Dist: openpyxl>=3.0
Requires-Dist: xlrd>=2.0
Requires-Dist: pyBigWig>=0.3.0
Provides-Extra: dev
Requires-Dist: ruff; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: import-linter; extra == "dev"
Dynamic: license-file

# sfprov

Capture the provenance of a Nextflow run and make it queryable.

sfprov reads the three provenance outputs a Nextflow run can produce, merges them
into one model, and stores it in two places:

- **Neo4j**: the provenance graph. Which workflow, steps and channels were *planned*,
  which tasks *ran*, which files they read and wrote, with which tools, containers
  and parameters.
- **OpenSearch**: what is *inside* the files. Read counts, quality and GC for FASTQ,
  mapping and duplication rates for BAM, organism and genome build, headers and text.

Both stores share the same file ids, so you can ask questions that need both, such
as *"which tasks produced the BAM files with more than 50% duplicates?"*

| Input | Produced by | Gives |
|---|---|---|
| `ro-crate-metadata.json` | the [nf-prov](https://github.com/nextflow-io/nf-prov) plugin (Workflow Run RO-Crate) | the run, tasks, files, tools, parameters (required) |
| `dag.dot` or `dag.json` | Nextflow `dag` with `verbose = true` (`dag.json` needs Graphviz on the Nextflow host; `dag.dot` does not) | processes, operators, channels, subworkflows (optional) |
| `.lineage/` | Nextflow data lineage | task inputs/outputs, task → run links, checksums, sizes, containers (required by `ingest`; optional for `parse`, but without it task-level questions have no answer) |

---

## Install

```bash
pip install sfprov
```

Requirements:

- Python ≥ 3.10
- Docker with Compose V2, for the Neo4j and OpenSearch services that `sfprov init`
  starts. Not needed where only the pipeline, `parse` and `enrich` run (see
  [Running on an HPC cluster](#running-on-an-hpc-cluster-no-docker))
- Nextflow with the `nf-prov` plugin and data lineage (`lineage.enabled = true`,
  which `sfprov init` sets)
- Optional, for some file formats: `samtools` (SAM/BAM/CRAM) and `bcftools` (BCF) on
  `PATH`. Without them those files are skipped with a warning.

---

## Quick start

Run these from the folder you launch Nextflow from (your project folder with
`main.nf`, or any folder for a remote pipeline such as `nextflow run nf-core/rnaseq`).

```bash
# 1. One-time setup: starts Neo4j + OpenSearch and enables provenance in Nextflow
sfprov init

# 2. Run the pipeline as usual, from the same folder
nextflow run main.nf

# 3. Ingest the run
sfprov ingest

# 4. Ask questions
sfprov query run-tasks --run-id '<run id from provenance.json>'
sfprov query low-quality --min-quality 28 --type fastq
```

Then browse the graph at http://localhost:7474 (user `neo4j`, password from `.env`).

`sfprov init` writes into the folder:

| File | Purpose |
|---|---|
| `nextflow.sfprov.config` | enables nf-prov (`ro-crate-metadata.json`), the verbose DAG (`dag.dot`) and lineage |
| `nextflow.config` | gets an `includeConfig 'nextflow.sfprov.config'` line, once (created if missing) |
| `docker-compose.yml` | Neo4j 5 (7474, 7687), OpenSearch 2 (9200), OpenSearch Dashboards (5601) |
| `.env` | connection settings read by `ingest`, `load` and `query` (kept if it already exists) |

The two Nextflow files are always written. The last two, and the container start,
need Docker: without `docker` on `PATH`, `init` writes the Nextflow files, warns and
exits 0. `--no-services` does the same without the warning. Without `main.nf` in the
folder `init` says so and continues (`--remote` skips that line); Nextflow reads
`nextflow.config` from the launch folder for remote pipelines too.

> `sfprov ingest` expects `main.nf`, `ro-crate-metadata.json` and `.lineage/` (and
> optionally `dag.json` or `dag.dot`) in the folder it runs in, and stops with an explanation if
> `.lineage/` is missing. For a pipeline launched from elsewhere (for example
> `nextflow run nf-core/rnaseq`), or a run without lineage, use `sfprov parse` with
> explicit paths instead.

---

## How it works

```
 ro-crate-metadata.json ┐
 dag.dot | dag.json     ├─ parse ─► provenance.json ─► enrich ─► features.jsonl
 .lineage/              ┘                │                            │
                                         └────────── load ◄───────────┘
                                                  Neo4j   OpenSearch
```

1. **parse**: load the inputs, keep only the lineage records of this run (including
   tasks that a `-resume` reused from earlier runs of the same session), and merge
   everything into one model. Files seen by several sources (RO-Crate id, lineage
   `lid://`, work-dir path, published path) become one file, identified by checksum
   when available.
2. **provenance.json**: the merged model, saved before anything is written to a
   database. It is the source of truth: the databases can always be rebuilt from it.
3. **enrich**: find each file on disk, pick an extractor by format, and extract its
   features. Runs in parallel and uses a cache, so a file that has not changed is
   never read twice.
4. **load**: write the graph to Neo4j and the features to OpenSearch.

`sfprov ingest` runs all four. The steps also exist as separate commands, so a failed
database write can be retried without parsing or extracting again.

---

## Commands

| Command | What it does |
|---|---|
| `sfprov init` | Set up the Nextflow config and, with Docker, the services in a folder (`--remote`, `--no-services`) |
| `sfprov ingest` | Parse → save → enrich → load, for the run in the current folder |
| `sfprov parse` | Parse explicitly given inputs; optionally save JSON and/or write to the stores |
| `sfprov enrich` | Extract features for a saved `provenance.json` into `features.jsonl` |
| `sfprov load` | Write a saved `provenance.json` / `features.jsonl` into Neo4j and OpenSearch |
| `sfprov query` | Canned provenance questions (see below) |

Run `sfprov <command> --help` for all options. The common ones:

```bash
sfprov ingest [--work-dir DIR] [--no-neo4j] [--no-opensearch]
              [--publish-dirs results,out] [--workers N] [--no-cache]
              [--neo4j-clear] [--opensearch-clear]

sfprov parse --ro-crate ro-crate-metadata.json [--dag dag.dot|dag.json] [--lineage .lineage]
             [-o provenance.json] [--to-neo4j] [--to-opensearch] [--files-base-dir DIR]

sfprov enrich [--work-dir DIR] [--files-base-dir DIR] [--workers N] [--no-cache]

sfprov load [--work-dir DIR] [--no-neo4j] [--no-opensearch]
```

- `--dag`: `dag.dot` (what Nextflow writes) or `dag.json` (the same through Graphviz's
  `dot -Tjson`); both give the same result. The format comes from the extension, else
  from the content. `ingest` takes `dag.json` if present, else `dag.dot`, and logs which.
- `--publish-dirs`: folder names whose files count as published outputs (default `results`).
- `--workers`: extraction processes (default: one per CPU; `1` runs without a pool).
- `--no-cache`: don't read or write the feature cache.

### Running on an HPC cluster (no Docker)

On a cluster (Slurm, no Docker) run the pipeline, `parse` and `enrich` there, and
`load` on a host that can run the databases.

On the cluster, from the launch folder:

```bash
sfprov init --no-services          # writes nextflow.sfprov.config + nextflow.config only
nextflow run nf-core/rnaseq -profile test,singularity --outdir results
sfprov parse --ro-crate ro-crate-metadata.json --dag dag.dot --lineage .lineage \
             --output provenance.json
sfprov enrich                      # reads provenance.json, writes features.jsonl
```

Copy `provenance.json` and `features.jsonl` to a host with Docker. There, in the folder
holding the two files:

```bash
sfprov init --remote               # writes docker-compose.yml + .env, starts the services
sfprov load                        # provenance.json → Neo4j, features.jsonl → OpenSearch
sfprov query run-tasks --run-id '<run id from provenance.json>'
```

`docker compose up -d` in that folder restarts the services later. `enrich` must run
where the data files are: `features.jsonl` carries the extracted content, so `load`
never needs the files themselves.
- `--files-base-dir`: where relative file paths are resolved (default: the RO-Crate's
  folder for `parse`, `--work-dir` for `enrich`).

Neo4j write counts are the relationships that exist after the write. A link whose
target node is not in the graph is reported as skipped (`ingest` lists them), so
gaps in the provenance are visible instead of silently missing.

### Queries

Graph only (Neo4j):

| Query | Question |
|---|---|
| `lineage --file REF` | Which task produced this file, from which inputs, in which run? `REF` is a file id, path (e.g. `results/star_salmon/x.bam`), alias or file name |
| `run-tasks --run-id ID` | Which tasks ran, with status and container? |
| `run-software --run-id ID` | Which tools and containers did each task use? |
| `run-params --run-id ID` | Which parameters did the run use? |
| `downstream-routing --process NAME [--hide-versions]` | Which processes receive this process's outputs (through any number of operators)? Each row gives the operator count and channel labels; `--hide-versions` leaves out links that only carry tool-version files |
| `file-routing --file-name NAME` | Which task and process produced this file, through which channels and operators, and which processes feed that process? |

Graph + content (Neo4j and OpenSearch):

| Query | Question |
|---|---|
| `low-quality [--min-quality Q] [--max-gc F] [--min-reads N] [--type T]` | Which files fail these thresholds, and which tasks produced them? |
| `quality-by-run --run-id ID` | Quality metrics of every indexed file in a run |
| `by-sample --sample-id ID` | All files of a sample, with provenance |
| `by-organism --organism NAME [--genome-build B]` | All files of an organism/build, with provenance |
| `high-duplication-provenance [--threshold F]` | BAM files above a duplicate rate, with their producing process, upstream routing and upstream processes |

All queries take `--format table|json`.

---

## Configuration

Connection settings come from, in order: command-line flags, environment variables,
then the `.env` file in the working folder.

| Variable | Default written by `sfprov init` |
|---|---|
| `NEO4J_URI` | `bolt://localhost:7687` |
| `NEO4J_USER` | `neo4j` |
| `NEO4J_PASSWORD` | `provenance123` |
| `NEO4J_DATABASE` | *(empty: default database)* |
| `OPENSEARCH_URL` | `http://localhost:9200` |
| `OPENSEARCH_USER`, `OPENSEARCH_PASSWORD` | *(empty)* |

The OpenSearch index defaults to `workflow-artifacts` (`--opensearch-index`).

### Files sfprov writes

| Path | Content |
|---|---|
| `provenance.json` | The merged model: indented JSON with a `schema_version`; empty fields are left out. Files from another sfprov version are refused: re-run `parse` or `ingest` |
| `features.jsonl` | One line of extracted features per file, keyed by the same file id as Neo4j |
| `~/.sfprov/ingested.json` | Run ids already ingested (re-ingesting warns; Neo4j writes are idempotent) |
| `~/.sfprov/cache/features/` | Feature cache, shared by all projects; safe to delete |

---

## Supported file formats

Each file is matched by its RO-Crate `encodingFormat` or its extension; the first
matching extractor in this table wins.

| Format | Extensions | Extracted | Needs |
|---|---|---|---|
| FASTQ | `.fastq` `.fq` (`.gz`) | read count; GC (G+C over A+C+G+T) and base quality from the first 100 reads; Phred+33/+64 detected | |
| SAM/BAM/CRAM | `.sam` `.bam` `.cram` | header (reference, sample, aligner, sort order), mapping/duplicate/pairing rates | `samtools` |
| VCF/BCF | `.vcf` `.vcf.gz` `.bcf` | header, caller, genome build | `bcftools` for BCF |
| FASTA | `.fa` `.fasta` `.fna` (`.gz`) | headers, organism, genome build | |
| GTF | `.gtf` | gene ids and names, gene count, annotation source | |
| BED / bedGraph | `.bed` `.bedgraph` | chromosomes, interval count | |
| TSV | `.tsv` `.tab` | header, first rows, column count | |
| PDF | `.pdf` | text, page count | |
| Excel | `.xlsx` `.xls` | sheet names and cell text | |
| BigWig | `.bigwig` `.bw` | chromosome names | |
| Text | `.txt` `.log` `.yml` `.json` `.stats` `.flagstat` … | text | |

Directories, remote URLs and files missing on disk are skipped.

---

## The graph

Every node has an `id` and one extra label: `:Prospective` for the plan (from the
DAG) or `:Retrospective` for what ran (from the RO-Crate and lineage).

| Relationship | Meaning |
|---|---|
| `SubWorkflow -CONTAINED_IN_WORKFLOW-> Workflow` | subworkflow of a workflow |
| `SubWorkflow -NESTED_IN-> SubWorkflow` | nested subworkflow |
| `Process -CONTAINED_IN-> SubWorkflow` | process defined in a subworkflow |
| `Channel -EMITTED_BY-> Process\|Operator` | channel source |
| `Channel -FEEDS_INTO-> Process\|Operator` | channel destination |
| `Process -FLOWS_TO-> Process` | the first processes a process's outputs reach, through any number of operators; properties `operators`, `channels` (labels on the shortest path), `versions_only` |
| `WorkflowRun -SPECIFIED_BY-> Workflow` | the workflow that was run |
| `WorkflowRun -USES_PARAMETER-> Parameter` | run parameters |
| `Parameter -INSTANTIATES-> Parameter` | value of a formal parameter |
| `WorkflowRun -HAS_INPUT-> File`, `WorkflowRun -HAS_OUTPUT-> File` | run inputs and outputs |
| `Task -PART_OF_RUN-> WorkflowRun` | task of a run |
| `Task -HAS_INPUT-> File`, `Task -HAS_OUTPUT-> File` | task inputs and outputs |
| `Task -RAN_WITH-> SoftwareTool` | tool the task ran |
| `SoftwareTool -HAS_PART-> SoftwareTool` | tool components |
| `Task -RESOLVES_TO-> Process` | the planned process a task executed |
| `Task -USED-> Channel`, `Channel -WAS_GENERATED_BY-> Task` | PROV-O style links derived from the two above |

---

## Python API

```python
from workflow_provenance import parse_provenance

result = parse_provenance("ro-crate-metadata.json", dag="dag.json", lineage=".lineage")
print(result.run_count, result.task_count, result.file_count)

result.to_json("provenance.json")
result.to_neo4j()  # NEO4J_* env vars
result.to_opensearch(cache_dir="~/.sfprov/cache/features")  # OPENSEARCH_* env vars
```

`result.model` is a typed `ProvenanceModel` (`model.runs`, `model.tasks`,
`model.files`, …). Lower-level steps are in `workflow_provenance.pipeline`.

---

## Known limitations

- `sfprov ingest` checks that the services answer at `localhost:7474` and
  `localhost:9200`, even when other URLs are configured.
- `sfprov parse` without `--lineage`: tasks have no input/output file links and no
  `PART_OF_RUN` link to their run (both come from lineage), so `lineage`,
  `file-routing`, `run-tasks`, `run-software` and the producing task in the hybrid
  queries return nothing for that run.
- Run inputs/outputs that are folders (RO-Crate `Dataset`) or pipeline asset files
  (e.g. MultiQC config) are not linked; they are listed under
  `diagnostics.unresolved_run_refs` in `provenance.json`.
- The people or organisations recorded as task agents are not in the graph yet.
- FASTQ: the read count is lines ÷ 4, so wrapped (multi-line) FASTQ is miscounted;
  GC and quality describe the first 100 reads only.

---

## Development

```bash
pip install -e '.[dev]'
pytest
ruff check .
lint-imports        # layering rules, see [tool.importlinter] in pyproject.toml
```

The package is layered; `lint-imports` (run in CI) fails on any import that goes
the wrong way:

```
cli ─► api ─► pipeline | queries ─► sources | merge | enrich | storage | sinks ─► domain | config
```

Higher layers may import lower ones, never the reverse; modules on the same layer
(`|`) may not import each other. The CLI reaches the write side only through
`pipeline`.

Code layout (`workflow_provenance/`):

| Package | Role |
|---|---|
| `domain/` | entities, `ProvenanceModel`, `FileFeatures` — no dependencies |
| `sources/` | read RO-Crate, DAG and lineage, each into a partial `ProvenanceModel` |
| `merge/` | merge the partial models: file `identity`, `workflows` naming, `merge_models` |
| `enrich/` | file resolution, extractors, cache, parallel runner |
| `storage/` | `provenance.json`, `features.jsonl`, ingest ledger |
| `sinks/` | Neo4j (graph schema declared in `neo4j/schema.py`) and OpenSearch writers behind one `Sink` interface |
| `queries/` | read-only queries: `connections`, `graph` (Cypher), `content` (OpenSearch), `hybrid` (both) |
| `pipeline.py` | the only module that chains the steps |
| `cli/` | command-line wiring (`main.py`), one module per command in `commands/` |
| `api.py` | Python API over `pipeline` |

## Citing

sfprov is described in:

> Jaffar Gura, Khalid Belhajjame, Frédéric Lemoine, Sarah Cohen-Boulakia.
> **From Execution Traces to Queryable Provenance in Nextflow Workflows.**
> 22nd IEEE International Conference on e-Science (eScience 2026), Naples, Italy, 2026.
> [hal-05757229](https://hal.science/hal-05757229)

```bibtex
@inproceedings{gura:hal-05757229,
  TITLE = {{From Execution Traces to Queryable Provenance in Nextflow Workflows}},
  AUTHOR = {Gura, Jaffar and Belhajjame, Khalid and Lemoine, Fr{\'e}d{\'e}ric and Cohen-Boulakia, Sarah},
  URL = {https://hal.science/hal-05757229},
  BOOKTITLE = {{2026 IEEE 22nd International Conference on e-Science (e-Science)}},
  ADDRESS = {Naples, Italy},
  ORGANIZATION = {{IEEE}},
  PUBLISHER = {{IEEE}},
  YEAR = {2026},
  MONTH = Sep,
  KEYWORDS = {Neo4j ; RO-Crate ; knowledge graph ; Nextflow ; provenance ; scientific workflows},
  PDF = {https://hal.science/hal-05757229v1/file/2026274892.pdf},
  HAL_ID = {hal-05757229},
  HAL_VERSION = {v1},
}
```

## License

GNU Affero General Public License v3.0, see [LICENSE](LICENSE).
