Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 26 additions & 13 deletions .github/workflows/realapps.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,21 @@ jobs:
with:
python-version: ${{ matrix.python }}

- name: Install flwrcrate (with Flower)
- name: Install flwrcrate (with Flower and rocrate-validator)
run: |
python -m pip install --upgrade pip
pip install -e .
pip install -e ".[validate]"

- name: Fill the rocrate-validator cache
# Validation reads the JSON-LD contexts and profiles from this cache, so
# neither the check after the run nor the step below needs the network.
# Fetching them can fail on a network blip, so try up to three times.
run: |
for i in 1 2 3; do
rocrate-validator cache warm -p ro-crate-1.2 -p process-run-crate-0.6 && exit 0
sleep 15
done
exit 1

- name: Fetch the app from the Flower Hub
working-directory: ${{ runner.temp }}
Expand All @@ -58,7 +69,7 @@ jobs:
- name: Run the federation
working-directory: ${{ runner.temp }}/${{ matrix.app }}
run: |
rm -rf /tmp/flwrcrate-ro-crate
rm -rf /tmp/flwrcrate-ro-crate /tmp/flwrcrate.log
# flwr run detaches the simulation when there's no TTY, so we kick it
# off and then poll for the crate within this same step (keeping the
# step alive so the background sim isn't killed).
Expand All @@ -70,18 +81,20 @@ jobs:
sleep 5
done

- name: Check flwrCrate validated the crate after the run
# FLCrateTracker validates the crate right after writing it, and the CI
# ServerApp logs that to /tmp/flwrcrate.log. Wait for the result.
run: |
for i in $(seq 1 24); do
grep -qs "rocrate-validator found no problems" /tmp/flwrcrate.log && break
sleep 5
done
cat /tmp/flwrcrate.log
grep -q "rocrate-validator found no problems" /tmp/flwrcrate.log

- name: Validate the generated crate
# rocrate-validator needs rich<14, which current Flower cannot share, so it
# gets its own virtual environment. The federation has finished by now.
# flwrcrate goes in without its dependencies (as in tests.yml), plus
# ro-crate-py, so the script can import flwrcrate.validation.
# offline=True only reads the validator's cache, so fill it first.
run: |
python -m venv /tmp/validator
/tmp/validator/bin/pip install "roc-validator>=0.13" "rocrate>=0.15"
/tmp/validator/bin/pip install -e . --no-deps
/tmp/validator/bin/rocrate-validator cache warm -p ro-crate-1.2 -p process-run-crate-0.5
/tmp/validator/bin/python tests/e2e/validate_crate.py \
python tests/e2e/validate_crate.py \
/tmp/flwrcrate-ro-crate/ro-crate-metadata.json \
"${{ matrix.strategy }}" "${{ matrix.framework }}"

Expand Down
13 changes: 9 additions & 4 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,18 @@ jobs:
# works without a Flower install.
run: |
python -m pip install --upgrade pip
pip install pytest pytest-cov "rocrate>=0.15" "roc-validator>=0.13" "tomli>=2.0; python_version < '3.11'"
pip install pytest pytest-cov "rocrate>=0.15" "roc-validator>=0.14" "tomli>=2.0; python_version < '3.11'"
pip install -e . --no-deps

- name: Cache the validator's profile resources
# The tests validate with offline=True, which only reads rocrate-validator's
# cache. A fresh runner's cache is empty, so fill it first.
run: rocrate-validator cache warm -p ro-crate-1.2 -p process-run-crate-0.5
# cache. A fresh runner's cache is empty, so fill it first, trying up to
# three times in case of a network blip.
run: |
for i in 1 2 3; do
rocrate-validator cache warm -p ro-crate-1.2 -p process-run-crate-0.6 && exit 0
sleep 15
done
exit 1

- name: Run tests with coverage
run: pytest -q --cov=flwrcrate --cov-report=term-missing --cov-fail-under=85
44 changes: 35 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ grep -rn "flwr.serverapp\|strategy.start\|server_fn\|ServerAppComponents" <app>/
- `flwr.serverapp` **and** `strategy.start` → ✅ compatible
- `server_fn` or `ServerAppComponents` → ❌ classic API, not supported (yet)

Other requirements: Python ≥ 3.11, `rocrate ≥ 0.15`.
Other requirements: Python ≥ 3.11, `rocrate ≥ 0.15`, and optionally
`roc-validator ≥ 0.14` to validate each crate (see [Validation](#validation)).

## Install

Expand All @@ -73,6 +74,10 @@ Declaring it as a dependency guarantees flwrcrate lands in the same
environment as your app, and it is reinstalled automatically whenever you
set the project up in a new environment or on another machine.

To also check each crate with
[rocrate-validator](https://github.com/crs4/rocrate-validator) after the run,
depend on `"flwrcrate[validate]>=0.5.0"` instead (see [Validation](#validation)).

For a quick experiment in a scratch environment you can install it
directly instead:

Expand Down Expand Up @@ -192,6 +197,7 @@ as absolute paths.
| `author` | no | `"Name"` or `{"name": ..., "orcid": ..., "affiliation": ...}` — becomes a `Person` entity (ORCID as `@id`) |
| `license` | no | License for the crate root, e.g. an SPDX URL `"http://spdx.org/licenses/MIT"` |
| `agent` | no | Who executed the run, same format as `author`. Defaults to the author |
| `validation` | no | `"required"` (default) checks the crate after it is written, if the `validate` extra is installed; `"recommended"` also lists suggestions; `None` turns it off. See [Validation](#validation) |

### Semantic metric identifiers

Expand Down Expand Up @@ -249,15 +255,35 @@ series.

### Validation

With the `validate` extra installed (`flwrcrate[validate]`), flwrCrate checks
each crate right after writing it, using
[`rocrate-validator`](https://github.com/crs4/rocrate-validator) at the
REQUIRED level, against the `ro-crate-1.2` and `process-run-crate-0.6`
profiles. Problems are logged as warnings, with a hint where your settings can
fix them, such as a missing `license`. Validation never stops a run: the crate
has already been written.

Pass `validation="recommended"` to also see the profiles' suggestions while
developing (many are about how flwrCrate itself writes the crate), or
`validation=None` to skip validation.

The validator needs a few files from the web, such as the RO-Crate JSON-LD
context, and caches them. flwrCrate lets it go online when it can, and
otherwise validates from that cache. On a machine without internet access,
fill the cache once while it is online:

```bash
rocrate-validator cache warm -p ro-crate-1.2 -p process-run-crate-0.6
```

Crates declare and validate against **RO-Crate 1.2**: flwrCrate sets the
version explicitly, so the output does not depend on which `ro-crate-py` is
installed. The test suite and the end-to-end workflow check generated crates
with [`rocrate-validator`](https://github.com/crs4/rocrate-validator) at the
REQUIRED level, against the `ro-crate-1.2` and `process-run-crate-0.5`
profiles. Process Run Crate 0.5 is based on RO-Crate 1.1, so its inherited
checks are not reported; the RO-Crate 1.2 check covers the base rules.
The validator's opt-in extra checks are enabled too; they flag likely mistakes,
such as a plain string where a link to another entity was meant.
installed. Process Run Crate 0.6 also inherits the RO-Crate 1.3 checks, which
a 1.2 crate can't meet, so its inherited checks are not reported; the RO-Crate
1.2 check covers the base rules. The validator's opt-in extra checks are
enabled too; they flag likely mistakes, such as a plain string where a link to
another entity was meant. The test suite and the end-to-end workflow run the
same checks on generated crates.

## Tested with

Expand Down Expand Up @@ -305,7 +331,7 @@ it produced.

```bash
pip install -e ".[dev]" # installs pytest + pytest-cov and roc-validator
rocrate-validator cache warm -p ro-crate-1.2 -p process-run-crate-0.5 # once, for the validation tests
rocrate-validator cache warm -p ro-crate-1.2 -p process-run-crate-0.6 # once, for the validation tests
pytest # run the full unit + integration suite
pytest --cov=flwrcrate --cov-report=term-missing # with a coverage report
```
Expand Down
28 changes: 26 additions & 2 deletions flwrcrate/tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
)
torch.save(result.arrays.to_torch_state_dict(), "final_model.pt")
tracker.record_result(result, model_path="final_model.pt")
# On clean exit, output_dir itself becomes the RO-Crate.
# On clean exit, output_dir itself becomes the RO-Crate. With the `validate`
# extra installed, the crate is then checked with rocrate-validator.
"""

import json
Expand Down Expand Up @@ -49,7 +50,12 @@
class FLCrateTracker:
def __init__(self, context, strategy, output_dir=None,
pyproject_path="pyproject.toml", app_name=None,
author=None, license=None, agent=None):
author=None, license=None, agent=None, validation="required"):
if validation not in ("required", "recommended", None):
raise ValueError(
f'validation must be "required", "recommended" or None, not {validation!r}'
)
self.validation = validation
self.output_dir = Path(output_dir) if output_dir else (Path.cwd() / "flwrcrate-ro-crate")
self.output_dir.mkdir(parents=True, exist_ok=True)
self.pyproject_path = pyproject_path
Expand Down Expand Up @@ -222,6 +228,23 @@ def _warn_about_unrelated_files(self):
"such as data or secrets.", self.crate_dir, ", ".join(others)
)

def _validate(self):
"""Check the crate with rocrate-validator, if it's installed.

Never raises: the crate is already written, so problems are only logged.
"""
if not self.validation:
return
try:
from .validation import check_crate
except ImportError:
logger.info("Install flwrcrate[validate] to check the RO-Crate with rocrate-validator.")
return
try:
check_crate(self.crate_dir, self.validation)
except Exception as e:
logger.warning("Could not validate the RO-Crate: %r", e)

def build(self):
"""Write the RO-Crate. Called automatically on clean exit."""
if self._built:
Expand All @@ -242,6 +265,7 @@ def build(self):
self.capture_path.unlink(missing_ok=True)
self._warn_about_unrelated_files()
logger.info("RO-Crate written to %s", self.crate_dir)
self._validate()
return self.crate_dir

# ---- context manager -------------------------------------------------
Expand Down
121 changes: 114 additions & 7 deletions flwrcrate/validation.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,63 @@
"""Validate RO-Crates with rocrate-validator.
Shared by the test suite and the end-to-end check, and meant for validating
crates after a run.

Used by FLCrateTracker to check each crate after a run (when the `validate`
extra is installed), and shared by the test suite and the end-to-end check.
"""

import logging
import urllib.request
from io import StringIO

from rocrate_validator import models, services
from rocrate_validator import errors, models, services
from rocrate_validator.utils.io_helpers.output.console import Console
from rocrate_validator.utils.io_helpers.output.text import TextOutputFormatter

logger = logging.getLogger("flwrcrate")

LEVELS = {
"required": models.Severity.REQUIRED,
"recommended": models.Severity.RECOMMENDED,
}

# The profiles a crate is checked against, with their extra settings. Process
# Run Crate 0.6 also inherits the RO-Crate 1.3 checks, which a 1.2 crate can't
# meet; the RO-Crate 1.2 profile already covers the base rules, so only the
# Process Run Crate profile's own checks are reported.
PROFILES = {
"ro-crate-1.2": {},
"process-run-crate-0.6": {"disable_inherited_profiles_issue_reporting": True},
}

# How to fix the problems that come from FLCrateTracker's settings, by check.
_NOT_INSTALLED = ("flwrCrate couldn't find this package where the ServerApp runs, "
"so it couldn't record its version: install it there.")
HINTS = {
"ro-crate-1.2_13.3": 'Pass license=... to FLCrateTracker, e.g. license="http://spdx.org/licenses/MIT".',
"ro-crate-1.2_32.3": _NOT_INSTALLED,
"process-run-crate-0.6_4.1": _NOT_INSTALLED,
"process-run-crate-0.6_8.6": "Pass author=... (or agent=...) to FLCrateTracker.",
"ro-crate-1.2_80.1": 'Give the author a name, e.g. author={"name": "Your Name", ...}.',
"ro-crate-1.2_80.2": 'Add the author\'s affiliation, e.g. author={..., "affiliation": "Your University"}.',
"ro-crate-1.2_91.0": 'Use the author\'s ORCID, e.g. author={..., "orcid": "https://orcid.org/0000-0000-0000-0000"}.',
}

# The command that fills the validator's cache, so it can validate offline.
CACHE_WARM_COMMAND = "rocrate-validator cache warm " + " ".join(f"-p {p}" for p in PROFILES)

def validate(crate_dir, profile, **settings):
"""Validate a crate folder against one profile: REQUIRED level, offline, extra checks on."""
# What the validator needs first; fetched to see whether it can go online.
_CONTEXT_URL = "https://w3id.org/ro/crate/1.2/context"


def validate(crate_dir, profile, level="required", offline=True, **settings):
"""Validate a crate folder against one profile, with extra checks on.

Offline by default: then only the validator's cache is read.
"""
return services.validate(services.ValidationSettings(
rocrate_uri=str(crate_dir),
profile_identifier=profile,
requirement_severity=models.Severity.REQUIRED,
offline=True,
requirement_severity=LEVELS[level],
offline=offline,
extra_checks=True,
**settings,
))
Expand All @@ -29,3 +70,69 @@ def report(result):
console.register_formatter(TextOutputFormatter())
console.print(result)
return out.getvalue()


def check_crate(crate_dir, level="required"):
"""Validate a crate after a run and log what to fix.

Goes online when it can, so the validator can fetch anything missing from its
cache; otherwise validates offline, from the cache alone.
"""
offline = not _online()
try:
results = _validate_all(crate_dir, level, offline)
except (errors.ValidationExecutionError, OSError) as e: # e.g. the network went away
if offline:
raise
logger.debug("Online validation failed (%s); validating from the cache instead", e)
offline = True
results = _validate_all(crate_dir, level, offline)

problems = list(dict.fromkeys(p for result in results for p in _problems(result)))
if offline and any("Unable to retrieve the JSON-LD context" in p for p in problems):
logger.warning(
"Could not validate the RO-Crate: there is no internet connection, and "
"rocrate-validator has no cached copy of the files it needs. To validate "
"offline, run this once while online: %s", CACHE_WARM_COMMAND
)
return
if not problems:
logger.info("rocrate-validator found no problems with the RO-Crate (%s level).", level)
return
logger.warning(
"rocrate-validator found %d problem(s) with the RO-Crate in %s (%s level):\n%s\n"
"Set the flwrcrate logger to DEBUG for the validator's full report.",
len(problems), crate_dir, level, "\n".join(problems),
)
if logger.isEnabledFor(logging.DEBUG):
for result in results:
logger.debug("rocrate-validator report:\n%s", report(result))


def _online(timeout=5):
"""Whether the validator can fetch what it needs.

Checked with a short timeout because the validator sets none: on a network
that silently drops connections, it would hang for minutes.
"""
try:
urllib.request.urlopen(_CONTEXT_URL, timeout=timeout).close()
except OSError: # no network, refused, timed out, or an HTTP error
return False
return True


def _validate_all(crate_dir, level, offline):
return [validate(crate_dir, profile, level, offline=offline, **settings)
for profile, settings in PROFILES.items()]


def _problems(result):
"""One line per issue, plus a hint when the user's settings can fix it."""
found = [(i.check.identifier, i.violatingEntity, i.message) for i in result.get_issues()]
found += [(e.identifier, e.violating_entity, e.message) for e in result.extra_checks]
for check, entity, message in found:
line = f" - {message} [{check}" + (f", on {entity}]" if entity else "]")
if check in HINTS:
line += f"\n To fix: {HINTS[check]}"
yield line
Loading
Loading