Skip to content

Provenance

provenance

Provenance of experiment runs: W3C PROV and Workflow Run RO-Crate.

A run's record says which program ran, on which data, under which configuration, and what it produced. prov_document states this in the W3C PROV data model, serialized as PROV-JSON: one bundle per run, in which the run is an activity that used the program, its source files, its data, and its configuration (entities), was associated with the quivers engine (a software agent), and generated the result, which was derived from the program and the data. Every entity carries its content hash; a source file also carries its Software Heritage identifier (SWHID), the intrinsic identifier under which the archive serves the file once it is archived.

write_crate packages an experiment as a Workflow Run RO-Crate: the module declaring the experiment is the crate's main workflow (its formal parameters are the names the experiment gives values to), every run is a CreateAction whose instrument is the workflow, whose objects are the data files and values it used, and whose results are its record and its PROV document, and the root dataset conforms to the Process Run Crate, Workflow Run Crate, and Workflow RO-Crate profiles.

PROV_NAMESPACE module-attribute

PROV_NAMESPACE = 'https://quivers.dev/ns/experiment#'

The namespace of the qvr: attributes and types of a PROV document.

RUN_NAMESPACE module-attribute

RUN_NAMESPACE = 'urn:qvr:experiment:'

The namespace of a PROV document's identifiers: a run's hash names it.

RO_CRATE_CONTEXT module-attribute

RO_CRATE_CONTEXT = 'https://w3id.org/ro/crate/1.1/context'

The JSON-LD context of the crate's metadata.

CRATE_PROFILES module-attribute

CRATE_PROFILES = ('https://w3id.org/ro/wfrun/process/0.5', 'https://w3id.org/ro/wfrun/workflow/0.5', 'https://w3id.org/workflowhub/workflow-ro-crate/1.0')

The profiles a crate's root dataset conforms to.

FORMAL_PARAMETER_PROFILE module-attribute

FORMAL_PARAMETER_PROFILE = 'https://bioschemas.org/profiles/FormalParameter/1.0-RELEASE'

The Bioschemas profile each input and output parameter of a crate conforms to.

COMPUTATIONAL_WORKFLOW_PROFILE module-attribute

COMPUTATIONAL_WORKFLOW_PROFILE = 'https://bioschemas.org/profiles/ComputationalWorkflow/1.0-RELEASE'

The Bioschemas profile a crate's main workflow entity conforms to.

outputs_digest

outputs_digest(record: JsonValue) -> str

The content hash of a record's outputs.

PARAMETER DESCRIPTION
record

A run record.

TYPE: JsonValue

RETURNS DESCRIPTION
str

The digest of the outputs' canonical JSON.

RAISES DESCRIPTION
ExperimentError

If the record has no outputs.

Source code in src/quivers/experiments/provenance.py
def outputs_digest(record: JsonValue) -> str:
    """The content hash of a record's outputs.

    Parameters
    ----------
    record : JsonValue
        A run record.

    Returns
    -------
    str
        The digest of the outputs' canonical JSON.

    Raises
    ------
    ExperimentError
        If the record has no outputs.
    """
    outputs = _object(record, "record").get("outputs")
    if outputs is None:
        raise ExperimentError("experiment-record", "a record has no outputs")
    return tagged_digest("experiment-outputs", cast(CoreJson, outputs))

prov_document

prov_document(record: JsonValue) -> dict[str, JsonValue]

The W3C PROV account of one run, as a PROV-JSON document.

PARAMETER DESCRIPTION
record

A run record (run_experiment).

TYPE: JsonValue

RETURNS DESCRIPTION
dict[str, JsonValue]

A PROV-JSON document holding one bundle, named by the run's hash, with the run activity, its entities and agent, and the relations between them.

RAISES DESCRIPTION
ExperimentError

If the record is malformed.

Source code in src/quivers/experiments/provenance.py
def prov_document(record: JsonValue) -> dict[str, JsonValue]:
    """The W3C PROV account of one run, as a PROV-JSON document.

    Parameters
    ----------
    record : JsonValue
        A run record (`run_experiment`).

    Returns
    -------
    dict[str, JsonValue]
        A PROV-JSON document holding one bundle, named by the run's hash,
        with the run activity, its entities and agent, and the relations
        between them.

    Raises
    ------
    ExperimentError
        If the record is malformed.
    """
    fields = _object(record, "record")
    inputs = _object(fields.get("inputs"), "inputs")
    run_hash = _text(fields.get("hash"), "hash")
    bundle_id = f"run:{run_hash}"
    activity = f"run:{run_hash}.run"
    program = f"run:{run_hash}.program"
    configuration = f"run:{run_hash}.configuration"
    result = f"run:{run_hash}.result"
    agent = "run:quivers"
    entities: dict[str, JsonValue] = {
        program: {
            "prov:type": {"$": "qvr:Program", "type": "prov:QUALIFIED_NAME"},
            "prov:label": _text(inputs.get("program"), "program"),
            "qvr:entry": _text(inputs.get("entry"), "entry"),
            "qvr:entryKind": _text(inputs.get("entry_kind"), "entry kind"),
            "qvr:contentHash": _text(inputs.get("entry_hash"), "entry hash"),
        },
        configuration: {
            "prov:type": {"$": "qvr:Configuration", "type": "prov:QUALIFIED_NAME"},
            "qvr:method": _text(inputs.get("method"), "method"),
            "qvr:options": json.dumps(inputs.get("options"), sort_keys=True),
            "qvr:values": json.dumps(inputs.get("values"), sort_keys=True),
            "qvr:seed": cast(int, inputs.get("seed")),
            "qvr:links": json.dumps(inputs.get("links"), sort_keys=True),
            "qvr:handlers": json.dumps(inputs.get("handlers")),
        },
        result: {
            "prov:type": {"$": "qvr:Result", "type": "prov:QUALIFIED_NAME"},
            "prov:label": f"outputs of experiment {_text(fields.get('experiment'), 'experiment')}",
            "qvr:contentHash": outputs_digest(record),
            "qvr:experimentHash": _text(
                fields.get("experiment_hash"), "experiment hash"
            ),
        },
    }
    used: dict[str, JsonValue] = {}
    derived: dict[str, JsonValue] = {}
    started = _text(fields.get("started"), "start time")
    ended = _text(fields.get("ended"), "end time")
    usages = [program, configuration]
    for index, source in enumerate(_list(inputs.get("sources"), "sources")):
        item = _object(source, "source")
        identifier = f"run:{run_hash}.source{index}"
        entities[identifier] = {
            "prov:type": {"$": "qvr:SourceFile", "type": "prov:QUALIFIED_NAME"},
            "prov:location": _text(item.get("path"), "source path"),
            "qvr:module": _text(item.get("module"), "source module"),
            "qvr:blake3": _text(item.get("digest"), "source digest"),
            "qvr:swhid": _text(item.get("swhid"), "source identifier"),
        }
        derived[f"_:program_from_source{index}"] = {
            "prov:generatedEntity": program,
            "prov:usedEntity": identifier,
        }
        usages.append(identifier)
    for index, data in enumerate(_list(inputs.get("data"), "data")):
        item = _object(data, "data")
        identifier = f"run:{run_hash}.data{index}"
        entities[identifier] = {
            "prov:type": {"$": "qvr:Data", "type": "prov:QUALIFIED_NAME"},
            "prov:label": _text(item.get("name"), "data name"),
            "prov:location": _text(item.get("path"), "data path"),
            "qvr:blake3": _text(item.get("digest"), "data digest"),
        }
        derived[f"_:result_from_data{index}"] = {
            "prov:generatedEntity": result,
            "prov:usedEntity": identifier,
            "prov:activity": activity,
        }
        usages.append(identifier)
    for index, entity in enumerate(usages):
        used[f"_:used{index}"] = {
            "prov:activity": activity,
            "prov:entity": entity,
            "prov:time": started,
        }
    derived["_:result_from_program"] = {
        "prov:generatedEntity": result,
        "prov:usedEntity": program,
        "prov:activity": activity,
    }
    bundle: dict[str, JsonValue] = {
        "entity": entities,
        "activity": {
            activity: {
                "prov:startTime": started,
                "prov:endTime": ended,
                "prov:type": {"$": "qvr:ExperimentRun", "type": "prov:QUALIFIED_NAME"},
                "prov:label": f"run of experiment {fields.get('experiment')}",
                "qvr:engine": _text(fields.get("engine"), "engine"),
            }
        },
        "agent": {
            agent: {
                "prov:type": {"$": "prov:SoftwareAgent", "type": "prov:QUALIFIED_NAME"},
                "prov:label": "quivers",
                "qvr:version": _text(fields.get("quivers"), "version"),
            }
        },
        "used": used,
        "wasGeneratedBy": {
            "_:generated": {
                "prov:entity": result,
                "prov:activity": activity,
                "prov:time": ended,
            }
        },
        "wasAssociatedWith": {
            "_:associated": {"prov:activity": activity, "prov:agent": agent}
        },
        "wasDerivedFrom": derived,
        "wasAttributedTo": {
            "_:attributed": {"prov:entity": result, "prov:agent": agent}
        },
    }
    return {
        "prefix": {"qvr": PROV_NAMESPACE, "run": RUN_NAMESPACE},
        "entity": {
            bundle_id: {
                "prov:type": {"$": "prov:Bundle", "type": "prov:QUALIFIED_NAME"},
                "prov:label": f"provenance of a run of experiment {fields.get('experiment')}",
            }
        },
        "bundle": {bundle_id: bundle},
    }

write_crate

write_crate(records: Sequence[JsonValue], *, file: str | Path, directory: str | Path) -> Path

Package an experiment's runs as a Workflow Run RO-Crate.

PARAMETER DESCRIPTION
records

The run records of one experiment (its points).

TYPE: Sequence[JsonValue]

file

The module file declaring the experiment; the paths a record names are relative to its directory.

TYPE: str | Path

directory

Where the crate is written; created if absent.

TYPE: str | Path

RETURNS DESCRIPTION
Path

The crate's ro-crate-metadata.json.

RAISES DESCRIPTION
ExperimentError

If there are no records, they belong to different experiments, or a record is malformed.

OSError

If a source or data file cannot be copied.

Source code in src/quivers/experiments/provenance.py
def write_crate(
    records: Sequence[JsonValue],
    *,
    file: str | Path,
    directory: str | Path,
) -> Path:
    """Package an experiment's runs as a Workflow Run RO-Crate.

    Parameters
    ----------
    records : Sequence[JsonValue]
        The run records of one experiment (its points).
    file : str | Path
        The module file declaring the experiment; the paths a record names
        are relative to its directory.
    directory : str | Path
        Where the crate is written; created if absent.

    Returns
    -------
    Path
        The crate's ``ro-crate-metadata.json``.

    Raises
    ------
    ExperimentError
        If there are no records, they belong to different experiments, or
        a record is malformed.
    OSError
        If a source or data file cannot be copied.
    """
    if not records:
        raise ExperimentError("experiment-record", "a crate needs at least one run")
    crate = Path(directory)
    crate.mkdir(parents=True, exist_ok=True)
    base = Path(file).resolve().parent
    first = _object(records[0], "record")
    experiment = _text(first.get("experiment"), "experiment")
    experiment_hash = _text(first.get("experiment_hash"), "experiment hash")
    workflow_path = _copy(Path(file), crate, _crate_path(Path(file).name, "sources"))
    graph: list[JsonValue] = []
    parts: list[str] = [workflow_path]
    parameters: dict[str, dict[str, JsonValue]] = {}
    actions: list[JsonValue] = []
    files: dict[str, dict[str, JsonValue]] = {}

    def parameter(name: str, additional: str) -> str:
        identifier = f"#param-{name}"
        parameters.setdefault(
            identifier,
            {
                "@id": identifier,
                "@type": "FormalParameter",
                "conformsTo": {"@id": FORMAL_PARAMETER_PROFILE},
                "name": name,
                "additionalType": additional,
            },
        )
        return identifier

    output_parameter = "#param-record"
    parameters[output_parameter] = {
        "@id": output_parameter,
        "@type": "FormalParameter",
        "conformsTo": {"@id": FORMAL_PARAMETER_PROFILE},
        "name": "record",
        "additionalType": "File",
        "description": "the run's record: inputs, content hashes, and outputs",
    }
    provenance_parameter = "#param-provenance"
    parameters[provenance_parameter] = {
        "@id": provenance_parameter,
        "@type": "FormalParameter",
        "conformsTo": {"@id": FORMAL_PARAMETER_PROFILE},
        "name": "provenance",
        "additionalType": "File",
        "description": "the run's W3C PROV account, as PROV-JSON",
    }
    for record in records:
        fields = _object(record, "record")
        if (
            fields.get("experiment") != experiment
            or fields.get("experiment_hash") != experiment_hash
        ):
            raise ExperimentError(
                "experiment-record", "a crate packages the runs of one experiment"
            )
        inputs = _object(fields.get("inputs"), "inputs")
        run_hash = _text(fields.get("hash"), "hash")
        objects: list[JsonValue] = []
        for source in _list(inputs.get("sources"), "sources"):
            item = _object(source, "source")
            written = _text(item.get("path"), "source path")
            relative = _crate_path(written, "sources")
            if relative not in files:
                _copy(base / written, crate, relative)
                files[relative] = {
                    "@id": relative,
                    "@type": ["File", "SoftwareSourceCode"],
                    "name": f"module {_text(item.get('module'), 'source module')}",
                    "encodingFormat": _encoding(relative),
                    "programmingLanguage": {"@id": _LANGUAGE},
                    "identifier": _text(item.get("swhid"), "source identifier"),
                }
        for data in _list(inputs.get("data"), "data"):
            item = _object(data, "data")
            written = _text(item.get("path"), "data path")
            relative = _crate_path(written, "data")
            name = _text(item.get("name"), "data name")
            if relative not in files:
                _copy(base / written, crate, relative)
                files[relative] = {
                    "@id": relative,
                    "@type": "File",
                    "name": written,
                    "encodingFormat": _encoding(relative),
                    "exampleOfWork": {"@id": parameter(name, "File")},
                    "identifier": f"blake3:{_text(item.get('digest'), 'data digest')}",
                }
            objects.append({"@id": relative})
        values = _object(inputs.get("values"), "values")
        for name in sorted(values):
            identifier = f"#value-{run_hash}-{name}"
            value = values[name]
            graph.append(
                {
                    "@id": identifier,
                    "@type": "PropertyValue",
                    "name": name,
                    "value": value
                    if isinstance(value, str | int | float)
                    else json.dumps(value),
                    "exampleOfWork": {"@id": parameter(name, _parameter_type(value))},
                }
            )
            objects.append({"@id": identifier})
        record_path = f"runs/{run_hash}/record.json"
        prov_path = f"runs/{run_hash}/provenance.json"
        (crate / record_path).parent.mkdir(parents=True, exist_ok=True)
        (crate / record_path).write_text(
            json.dumps(record, indent=2, sort_keys=True, allow_nan=False) + "\n",
            encoding="utf-8",
        )
        (crate / prov_path).write_text(
            json.dumps(prov_document(record), indent=2, sort_keys=True, allow_nan=False)
            + "\n",
            encoding="utf-8",
        )
        files[record_path] = {
            "@id": record_path,
            "@type": "File",
            "name": f"record of run {run_hash}",
            "encodingFormat": "application/json",
            "exampleOfWork": {"@id": output_parameter},
        }
        files[prov_path] = {
            "@id": prov_path,
            "@type": "File",
            "name": f"W3C PROV account of run {run_hash}",
            "encodingFormat": "application/json",
            "conformsTo": {"@id": "https://www.w3.org/Submission/prov-json/"},
            "exampleOfWork": {"@id": provenance_parameter},
        }
        point = _object(fields.get("point"), "point")
        label = ", ".join(
            f"{key}={json.dumps(value)}"
            for key, value in sorted(
                _object(point.get("values"), "point values").items()
            )
        )
        actions.append(
            {
                "@id": f"#run-{run_hash}",
                "@type": "CreateAction",
                "name": f"run of experiment {experiment}"
                + (f" at {label}" if label else ""),
                "description": f"run {run_hash} of experiment {experiment}, "
                f"computed by quivers {_text(fields.get('quivers'), 'version')}",
                "identifier": f"{RUN_NAMESPACE}{run_hash}",
                "instrument": {"@id": workflow_path},
                "object": objects,
                "result": [{"@id": record_path}, {"@id": prov_path}],
                "startTime": _text(fields.get("started"), "start time"),
                "endTime": _text(fields.get("ended"), "end time"),
            }
        )
    parts.extend(path for path in files if path != workflow_path)
    workflow_inputs = [
        {"@id": identifier}
        for identifier in sorted(parameters)
        if identifier not in (output_parameter, provenance_parameter)
    ]
    workflow = {
        "@id": workflow_path,
        "@type": ["File", "SoftwareSourceCode", "ComputationalWorkflow"],
        "conformsTo": {"@id": COMPUTATIONAL_WORKFLOW_PROFILE},
        "name": f"experiment {experiment}",
        "encodingFormat": _encoding(workflow_path),
        "programmingLanguage": {"@id": _LANGUAGE},
        "input": workflow_inputs,
        "output": [{"@id": output_parameter}, {"@id": provenance_parameter}],
        "identifier": f"{RUN_NAMESPACE}{experiment_hash}",
    }
    files.pop(workflow_path, None)
    root = {
        "@id": "./",
        "@type": "Dataset",
        "name": f"experiment {experiment}",
        "description": f"Runs of the QVR experiment {experiment} "
        f"(hash {experiment_hash}), with their records and W3C PROV accounts.",
        "datePublished": datetime.now(UTC).date().isoformat(),
        "license": {"@id": "https://spdx.org/licenses/CC-BY-4.0"},
        "conformsTo": [{"@id": profile} for profile in CRATE_PROFILES],
        "mainEntity": {"@id": workflow_path},
        "hasPart": [{"@id": path} for path in parts],
        "mentions": [
            {"@id": cast(dict[str, JsonValue], action)["@id"]} for action in actions
        ],
    }
    contextual: list[JsonValue] = [
        {
            "@id": "ro-crate-metadata.json",
            "@type": "CreativeWork",
            "conformsTo": [
                {"@id": "https://w3id.org/ro/crate/1.1"},
                {"@id": "https://w3id.org/workflowhub/workflow-ro-crate/1.0"},
            ],
            "about": {"@id": "./"},
        },
        root,
        workflow,
        {
            "@id": _LANGUAGE,
            "@type": "ComputerLanguage",
            "name": "QVR",
            "url": {"@id": "https://quivers.dev"},
        },
        {
            "@id": "https://spdx.org/licenses/CC-BY-4.0",
            "@type": "CreativeWork",
            "name": "Creative Commons Attribution 4.0 International",
        },
        *(
            {"@id": profile, "@type": "CreativeWork", "name": name, "version": version}
            for profile, name, version in (
                (CRATE_PROFILES[0], "Process Run Crate", "0.5"),
                (CRATE_PROFILES[1], "Workflow Run Crate", "0.5"),
                (CRATE_PROFILES[2], "Workflow RO-Crate", "1.0"),
            )
        ),
    ]
    graph = [*contextual, *files.values(), *parameters.values(), *actions, *graph]
    metadata = crate / "ro-crate-metadata.json"
    metadata.write_text(
        json.dumps({"@context": RO_CRATE_CONTEXT, "@graph": graph}, indent=2) + "\n",
        encoding="utf-8",
    )
    return metadata