diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..c181c3b --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 SECORO AG (secoro.uni-bremen.de) +# Author: Vamsi Kalagaturu + +name: Tests (Python 3.12 and 3.14) + +on: + push: + branches: [main, dev] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.12", "3.14"] + services: + mariadb: + image: mariadb:11 + env: + MARIADB_DATABASE: rec_test + MARIADB_USER: rec + MARIADB_PASSWORD: rec + MARIADB_ROOT_PASSWORD: root + ports: + - 3306:3306 + options: >- + --health-cmd="healthcheck.sh --connect --innodb_initialized" + --health-interval=10s + --health-timeout=5s + --health-retries=5 + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: secorolab/metamodels + ref: main + path: metamodels + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - run: sudo apt-get update + - run: sudo apt-get install --yes libmariadb-dev + - run: pip install -e ".[mariadb,dev]" + - run: pytest -q + env: + MARIADB_USER: rec + MARIADB_PASSWORD: rec + MARIADB_HOST: 127.0.0.1 + MARIADB_PORT: 3306 + REC_TEST_MARIADB_DATABASE: rec_test + REC_METAMODELS_DIR: metamodels diff --git a/README.md b/README.md index 2c30014..6bc5fed 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,113 @@ # Robot Execution Catalog (REC) -REC is a tool that aims to make data in robot executions [FAIR](https://www.go-fair.org/fair-principles/). -It is designed to configure, manage, organize and consolidate (meta)data used or generated by robots executing tasks or tests. +REC makes the data of robot executions [FAIR](https://www.go-fair.org/fair-principles/): it records +each run's lifecycle in [PROV](https://www.w3.org/TR/prov-o/), on the +[rec and prov-extension vocabularies](https://secorolab.github.io/metamodels/), as a provenance +bundle written with [rdf-utils](https://github.com/minhnh/rdf-utils). ## Installation -In your terminal, go to where you have cloned this repository and install it in editable mode: - ```shell -pip install -e . +pip install -e . # file stores +pip install -e ".[mariadb]" # and the MariaDB store ``` -## Examples +## Recording a run -The current skeleton of the code allows you to run two examples: The `MariaDBObserver` and a `Run`. +A `Run` is a handle on one run in one store: `queue()`, `start()`, `beat()`, `end(verdict)`, +`cancel()` and `lifecycle()`. `run(work)` does the steps for you around `work(run)`: -### Observers +```python +from rec.run import Run +from rec.stores.file_store import FileStore -An Observer is an interface to a type of data storage. For now, we have added a `MariaDBObserver` with some basic functionality. To test it you can run the following in your terminal: -```shell -python rec/observers/mariadb_observer.py +def pick_and_place(run): + return "placed" + + +Run(FileStore("runs/prov"), "pick-place-1").run(pick_and_place) ``` -### Creating a run +`run(work)` starts the run (recording the machine it runs on), beats every `beat_interval` +seconds while `work` runs, and ends the run as `passed`, `failed` (`work` raised) or `error` +(interrupted, e.g. `KeyboardInterrupt` or `SystemExit`, which `run` raises again once recorded). +It returns what `work` returned; rec does not record it. -The [example](examples/decentral_run.py) shows how to create a run object, attach an observer, and define the `main` function of your tests. You can test its basic functionality by running the script: +Each step changes only its own triples in the run's bundle: the store parses the bundle under its +lock, the step checks the run's state and sets what it changes, and the store writes it back. +rdf-utils writes the bundle (`create_bundle`), rec as its software agent (`load_pkg_prov`), the +execution (`load_execution_prov`) and its instants (`add_wall_instant`), each once. -```shell -python examples/decentral_run.py +What a run executes, the software and files it uses or generates, and its steps, are recorded by +the tool that knows them, with rdf-utils' `add_file_entity`, `add_activity` and the `load_*_prov` +helpers, in that tool's own bundle. + +### Queueing and cancelling + +State lives in the store, so any `Run` with the same id sees and changes the same run: + +```python +Run(MariaDBStore(), "drawer-2").queue() + +# elsewhere, e.g. a scheduler with its own connection +Run(MariaDBStore(), "drawer-2").cancel() +``` + +| State when cancelled | Result | +|---|---| +| `queued` | `canceled`; it never started, so it has no beginning or end | +| `in-progress` | `canceling`; `work` sees `run.lifecycle()[0] is State.CANCELING`, returns, and the run ends `canceled`; `work` that raises instead ends `complete` with its verdict | +| anything else | `RuntimeError` | + +The store decides every step under a lock (`flock` for files, the run's row for MariaDB): only a +new run is queued, only a new or queued run starts. A started run beats every `beat_interval` +seconds, recorded as `rec:heartbeat-time`; a beat that fails is logged and the next one tried. + +## Stores + +| Store | Keeps a run as | +|---|---| +| `FileStore(dir)` | its bundle, `.ld.json` | +| `MariaDBStore(db_name, prefix)` | its bundle as JSON-LD in a row of `_runs` (`id`, `run_id`, `bundle`) | + +`load(run_id)` returns the run's bundle as an rdflib `Dataset`; `Run.lifecycle()` gives its state +and verdict. A run is recorded in one store, and a stored run holds only rec's bundle. +`MariaDBStore` takes a prefix of letters, digits and `_`, as it becomes part of a table name. + +## The PROV bundle + +```trig + { + a prov:Bundle ; + prov:wasAttributedTo . + + + a prov-ext:Execution, oslc_auto:AutomationResult ; + oslc_auto:state oslc_auto:complete ; + oslc_auto:verdict oslc_auto:passed ; + prov:wasAssociatedWith ; + time:hasBeginning ; + time:hasEnd ; + prov:atLocation . +} ``` +The bundle is attributed to the rec that first recorded the run (e.g. a scheduler that queued it); +the run is associated with the rec that started it. The run takes its state and verdict terms from +OSLC Automation 2.1; it is not a conformant `oslc_auto:AutomationResult`, which also needs an +automation plan, a title and an identifier. + +A run id is RFC 3986 unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none +gets a UUID. The run's node is ``, `base` given to the `Run`. + +## Examples -## Connecting to MariaDB +```shell +python examples/robot_runs.py # passed, failed, cancelled while queued, stopped while running +``` -Create an `.env` file at the root of this repository and update the contents with your credentials and the IP of the server where its deployed: +It records the runs as bundle files under `runs/prov`, then in MariaDB, so it needs the `mariadb` extra and an `.env` at the repository root: ```dotenv MARIADB_USER="user" @@ -43,6 +116,19 @@ MARIADB_HOST="localhost" MARIADB_PORT=3306 ``` +## Tests + +```shell +pip install -e ".[dev]" +pytest +``` + +The conformance tests validate runs against the shapes of a +[metamodels](https://github.com/secorolab/metamodels) checkout beside this repository or at +`REC_METAMODELS_DIR`. MariaDB tests need the `mariadb` extra and a disposable database named by +`REC_TEST_MARIADB_DATABASE`. + ## Acknowledgments -This tool is inspired by [sacred](https://github.com/IDSIA/sacred/tree/master), a tool to organize experiments for Machine Learning. We borrow small pieces of code under the [MIT License](https://opensource.org/license/MIT), but have rewritten and simplified the framework for robotics. +Inspired by [sacred](https://github.com/IDSIA/sacred/tree/master); small pieces of its code are +used under the [MIT License](https://opensource.org/license/MIT). diff --git a/examples/decentral_run.py b/examples/decentral_run.py deleted file mode 100644 index 700d804..0000000 --- a/examples/decentral_run.py +++ /dev/null @@ -1,17 +0,0 @@ -from rec.run import Run -from rec.observers.mariadb_observer import MariaDBObserver - - -def main(): - import time - - print("\tThis the main of the run") - time.sleep(15) - - -if __name__ == "__main__": - run = Run() - run.main = main - run.observers.append(MariaDBObserver()) - - run.run() diff --git a/examples/robot_runs.py b/examples/robot_runs.py new file mode 100644 index 0000000..5bb5def --- /dev/null +++ b/examples/robot_runs.py @@ -0,0 +1,73 @@ +"""Record robot runs, first as bundle files and then in MariaDB: one passes, one fails, one is +cancelled while queued and one is stopped while it runs. Every invocation records new runs. + +Needs the `mariadb` extra and the connection settings in `.env` (see the README). +""" + +import logging +import threading +import time +from uuid import uuid4 + +from rec import State +from rec.run import Run +from rec.stores.file_store import FileStore +from rec.stores.mariadb_store import MariaDBStore + +logger = logging.getLogger("robot_runs") +MOTIONS = ("approach", "grasp", "lift", "transport", "place", "retreat") +# How far the drawer handle is from its modelled pose, and how far the gripper reaches, in metres. +HANDLE_OFFSET, REACH = 0.04, 0.02 + + +def pick_and_place(run): + """Pick an object and place it, checking between motions whether the run was asked to stop.""" + for done, motion in enumerate(MOTIONS): + if run.lifecycle()[0] is State.CANCELING: + logger.info("%s: stopped before %s", run.id, motion) + return f"stopped after {done} of {len(MOTIONS)} motions" + logger.info("%s: %s", run.id, motion) + time.sleep(0.5) + return "placed" + + +def open_drawer(run): + """Open a drawer, failing when the handle is further from its modelled pose than the gripper reaches.""" + logger.info("%s: looking for the handle", run.id) + time.sleep(0.5) + if HANDLE_OFFSET > REACH: + raise RuntimeError(f"handle is {HANDLE_OFFSET} m from its modelled pose -- the gripper reaches {REACH} m") + return "opened" + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO, format="%(message)s") + session = uuid4().hex[:8] + for make_store in (lambda: FileStore("runs/prov"), lambda: MariaDBStore(db_name="logbook", prefix="logs")): + # A scheduler holds only the run ids, and its own store on the same files or tables. + store, scheduler = make_store(), make_store() + + passed = Run(store, f"pick-place-{session}-1") + # A short beat, so the run records a few heartbeats while it moves. + passed.beat_interval = 1 + passed.run(pick_and_place) + + failed = Run(store, f"drawer-{session}-1") + failed.run(open_drawer) + + queued = Run(store, f"pick-place-{session}-2") + queued.queue() + Run(scheduler, queued.id).cancel() + + stopped = Run(store, f"pick-place-{session}-3") + running = threading.Thread(target=stopped.run, args=(pick_and_place,)) + running.start() + time.sleep(1.2) + Run(scheduler, stopped.id).cancel() + running.join() + + for run in (passed, failed, queued, stopped): + print(type(store).__name__, run.id, *run.lifecycle()) + if isinstance(store, MariaDBStore): + store.close() + scheduler.close() diff --git a/pyproject.toml b/pyproject.toml index 079209c..34cd12c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,15 +1,17 @@ [build-system] -requires = ["setuptools >= 61.0"] -build-backend = "setuptools.build_meta" +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[tool.hatch.version] +source = "vcs" [project] name = "rec" description = "Robot Execution Catalog (REC) is a python library to manage data from robot runs" dynamic = ["version"] dependencies = [ - "click>=8.1.7", - "dotenv", - "mariadb" + "rdflib>=7.6.0", + "rdf-utils @ git+https://github.com/minhnh/rdf-utils@bad7c02ca44de57c2461a354e3543e6d5a09341b", ] requires-python = ">= 3.12" readme = "README.md" @@ -18,8 +20,11 @@ maintainers = [ ] [project.optional-dependencies] -dev = ["black>=24.4.2"] +mariadb = ["dotenv", "mariadb"] +dev = ["pytest", "pyshacl"] -[tool.setuptools.packages.find] -where = ["."] # list of folders that contain the packages (["."] by default) +[tool.hatch.metadata] +allow-direct-references = true +[tool.hatch.build.targets.wheel] +packages = ["rec"] diff --git a/rec/__init__.py b/rec/__init__.py index e69de29..b307ca3 100644 --- a/rec/__init__.py +++ b/rec/__init__.py @@ -0,0 +1,19 @@ +"""Where a run is and how it turned out: OSLC Automation state and verdict, by their rec.json terms.""" + +from enum import StrEnum + + +class State(StrEnum): + NEW = "new" + QUEUED = "queued" + IN_PROGRESS = "in-progress" + CANCELING = "canceling" + CANCELED = "canceled" + COMPLETE = "complete" + + +class Verdict(StrEnum): + UNAVAILABLE = "unavailable" + PASSED = "passed" + FAILED = "failed" + ERROR = "error" diff --git a/rec/feature.py b/rec/feature.py deleted file mode 100644 index 3643d0e..0000000 --- a/rec/feature.py +++ /dev/null @@ -1,17 +0,0 @@ -class Feature: - def __init__(self, name, **kwargs): - self.name = name - - # Decorators - def capture(self, function): - pass - - def config(self, function): - pass - - # Public methods - def add_config(self, config, **kwargs): - pass - - def add_named_config(self, name, config, **kwargs): - pass diff --git a/rec/observers/__init__.py b/rec/observers/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/rec/observers/base.py b/rec/observers/base.py deleted file mode 100644 index 09de856..0000000 --- a/rec/observers/base.py +++ /dev/null @@ -1,29 +0,0 @@ -from datetime import timedelta, datetime - - -class BaseObserver: - def log_run_heartbeat(self, run_id: int, beat_time: datetime, result): - raise NotImplementedError - - def log_cancelled_run(self, run_id: int, cancelled_time: datetime): - raise NotImplementedError - - def log_queued_run(self, run_id: int, queued_time: datetime): - raise NotImplementedError - - def log_started_run( - self, run_id: int, started_time: datetime, trigger=None, starter=None - ): - raise NotImplementedError - - def log_completed_run(self, run_id: int, completed_time: datetime): - raise NotImplementedError - - def log_interrupted_run(self, run_id: int, elapsed_time: timedelta): - raise NotImplementedError - - def log_failed_run(self, run_id: int, elapsed_time: timedelta): - raise NotImplementedError - - def close(self): - raise NotImplementedError diff --git a/rec/observers/mariadb_observer.py b/rec/observers/mariadb_observer.py deleted file mode 100644 index 9d6fa3d..0000000 --- a/rec/observers/mariadb_observer.py +++ /dev/null @@ -1,229 +0,0 @@ -import sys -import os -import json -import datetime as dt -from datetime import timedelta, datetime - -import mariadb - -from dotenv import load_dotenv - -from rec.observers.base import BaseObserver - - -class MariaDBObserver(BaseObserver): - def __init__(self, db_name="logbook", table="logs", **kwargs): - """ - Observer in a run that writes to a MariaDB database - - :param db_name: Name of the table - :param kwargs: - """ - - self.db_name = db_name - self.table = table - - load_dotenv() - - # Connect to MariaDB Platform - try: - self.conn = mariadb.connect( - user=os.getenv("MARIADB_USER"), - password=os.getenv("MARIADB_PASSWORD"), - host=os.getenv("MARIADB_HOST"), - port=int(os.getenv("MARIADB_PORT")), - database=db_name, - ) - self.conn.autocommit = True # optional for simplicity - except mariadb.Error as e: - print(f"Error connecting to MariaDB Platform: {e}") - sys.exit(1) - - # Get Cursor - self.cursor = self.conn.cursor() - print(f"Connected to MariaDB Platform: {self.db_name}") - - # Create the table if it doesn't exist - try: - self.cursor.execute( - f""" - CREATE TABLE IF NOT EXISTS {self.table} ( - id INT AUTO_INCREMENT PRIMARY KEY, - status VARCHAR(20) NOT NULL, - scenario_id VARCHAR(20), - host_info JSON, - sources JSON, - repositories JSON, - dependencies JSON, - metrics JSON, - agents JSON, - resources JSON, - artefacts JSON, - run_info JSON, - data JSON - ) - """ - ) - print(f"Table '{self.table}' created or already exists.") - except mariadb.Error as e: - print(f"Error creating table: {e}") - self.conn.rollback() # Rollback in case of DDL error - - # self.cursor.execute("DESCRIBE logs;") - # for x in self.cursor: - # print(x) - - def add_run( - self, status: str, start_t: datetime = None, queue_t: datetime = None - ) -> int: - """ - Saves a new run to the MariaDB database - :param status: The status of the run being added (RUNNING or QUEUED) - :param start_t: The start time of the run - :param queue_t: The queue time of the run - :return: The run_id - """ - if start_t is not None: - assert status == "RUNNING" - run_info = {"start_time": start_t.isoformat()} - elif queue_t is not None: - assert status == "QUEUED" - run_info = {"queue_time": queue_t.isoformat()} - template = f"INSERT INTO {self.table} (status, run_info) VALUES (?, ?);" - try: - self.cursor.execute(template, (status, json.dumps(run_info))) - # print(f"Inserted {self.cursor.rowcount} rows.") - # print(f"Last inserted ID: {self.cursor.lastrowid}") - except mariadb.Error as e: - print(f"Error: {e}") - - return self.cursor.lastrowid - - def update_run_data(self, run_id: int, column: str, data): - """ - Updates the data of a run in a particular column - :param run_id: - :param column: - :param data: - :return: - """ - if column in ["status", "scenario_id"]: - d = data - else: - d = json.dumps(data) - - try: - self.cursor.execute( - f"UPDATE {self.table} SET {column} = ? WHERE id = ?", - (d, run_id), - ) - except mariadb.Error as e: - print(f"An error occurred: {e}") - self.conn.rollback() # Rollback in case of DDL error - sys.exit(1) - - def get_run(self, run_id: int): - """ - Queries the MariaDB database for a run's data - :param run_id: - :return: - """ - cols = [ - "status", - "scenario_id", - "host_info", - "sources", - "repositories", - "dependencies", - "metrics", - "agents", - "resources", - "artefacts", - "run_info", - ] - try: - self.cursor.execute( - "SELECT {} FROM {} WHERE id=?;".format(", ".join(cols), self.table), - (run_id,), - ) - except mariadb.Error as e: - print(f"An error occurred: {e}") - sys.exit(1) - - for row in self.cursor: - d = dict(status=row[0], scenario_id=row[1]) - for k, v in zip(cols[2:], row[2:]): - if v is not None: - d[k] = json.loads(v) - - return d - - def query_active_run(self): - try: - self.cursor.execute( - f"SELECT id, status FROM {self.table} WHERE status ='RUNNING'" - ) - except mariadb.Error as e: - print(f"An error occurred: {e}") - sys.exit(1) - - for row in self.cursor: - return row[0] - - def log_run_heartbeat(self, run_id: int, beat_time: datetime, result): - pass - - def log_cancelled_run(self, run_id: int, cancelled_time: datetime): - pass - - def log_queued_run(self, run_id: int, queued_time: datetime): - pass - - def log_started_run( - self, run_id: int, started_time: datetime, trigger=None, starter=None - ): - if run_id is None: - return self.add_run("RUNNING", started_time) - else: - print(f"Run {run_id} was already started at {started_time}") - - def log_completed_run(self, run_id: int, completed_time: datetime): - self.update_run_data(run_id, "status", "COMPLETED") - - # TODO Update the run_info dictionary - run_info = {"completed_time": completed_time.isoformat()} - - def log_interrupted_run(self, run_id: int, elapsed_time: timedelta): - pass - - def log_failed_run(self, run_id: int, elapsed_time: timedelta): - pass - - def close(self): - """ - This method must be called when the run is over to close the connection to the DB - :return: - """ - self.cursor.close() - # self.conn.close() - - -if __name__ == "__main__": - db = MariaDBObserver() - print("Writing to the DB dummy data") - run_id = db.add_run("RUNNING", datetime.now(dt.UTC)) - info = db.get_run(run_id) - print(info) - - db.update_run_data(run_id, "scenario_id", "db-test-01") - db.update_run_data( - run_id, "agents", {"agent_id": "robot-01", "agent_type": "SoftwareAgent"} - ) - db.query_active_run() - db.update_run_data(run_id, "status", "COMPLETED") - - print("Getting run info") - info = db.get_run(run_id) - print(info) - - db.close() diff --git a/rec/provenance.py b/rec/provenance.py new file mode 100644 index 0000000..b8c4efb --- /dev/null +++ b/rec/provenance.py @@ -0,0 +1,42 @@ +"""The vocabulary of a run's provenance bundle: prov-extension, rec, and OSLC Automation state and verdict.""" + +import re + +from rdflib import XSD, Namespace +from rdflib.namespace import PROV, SDO, TIME + +from rec import State, Verdict + +RUN_BASE = "https://secoro.uni-bremen.de/rec/run/" +# RFC 3986 unreserved characters (2.3), so an id is the same in an IRI, a file name and a database row. +RUN_ID = re.compile(r"(?!\.\.?$)[A-Za-z0-9._~-]+") +REC = Namespace("https://secorolab.github.io/metamodels/rec#") +PROV_EXT = Namespace("https://secorolab.github.io/metamodels/prov#") +OSLC_AUTO = Namespace("http://open-services.net/ns/auto#") + +STATES = { + State.NEW: OSLC_AUTO.new, + State.QUEUED: OSLC_AUTO.queued, + State.IN_PROGRESS: OSLC_AUTO.inProgress, + State.CANCELING: OSLC_AUTO.canceling, + State.CANCELED: OSLC_AUTO.canceled, + State.COMPLETE: OSLC_AUTO.complete, +} +VERDICTS = { + Verdict.UNAVAILABLE: OSLC_AUTO.unavailable, + Verdict.PASSED: OSLC_AUTO.passed, + Verdict.FAILED: OSLC_AUTO.failed, + Verdict.ERROR: OSLC_AUTO.error, +} +HOST_TERMS = {"hostname": SDO.identifier, "os": REC.os, "python": REC.runtime, "cpu": REC.cpu} +PREFIXES = { + "prov": PROV, + "prov-ext": PROV_EXT, + "rec": REC, + "oslc_auto": OSLC_AUTO, + "schema": SDO, + "time": TIME, + "xsd": XSD, +} +# The JSON-LD context the stores serialize with, compacting on the prefixes. +CONTEXT = {prefix: str(namespace) for prefix, namespace in PREFIXES.items()} diff --git a/rec/run.py b/rec/run.py index 5a1cbf8..31b03d6 100644 --- a/rec/run.py +++ b/rec/run.py @@ -1,298 +1,199 @@ -import datetime -import threading -from typing import Sequence - -from rec.observers.base import BaseObserver +"""A run and its lifecycle, recorded in a store as the run's provenance bundle.""" +from __future__ import annotations -class IntervalTimer(threading.Thread): - @classmethod - def create(cls, func, interval=10): - stop_event = threading.Event() - timer_thread = cls(stop_event, func, interval) - return stop_event, timer_thread - - def __init__(self, event, func, interval=10.0): - super().__init__() - self.stopped = event - self.func = func - self.interval = interval +import logging +import platform +import socket +import threading +import traceback +from collections.abc import Callable +from contextlib import contextmanager +from datetime import UTC, datetime +from typing import TYPE_CHECKING +from uuid import uuid4 - def run(self): - while not self.stopped.wait(self.interval): - self.func() - self.func() +from rdf_utils.models.prov import create_bundle, get_py_pkg_info, load_execution_prov, load_pkg_prov +from rdf_utils.models.time import add_wall_instant +from rdflib import XSD, Literal, URIRef +from rdflib.namespace import PROV, RDF, TIME +from rec import State, Verdict +from rec.provenance import HOST_TERMS, OSLC_AUTO, PROV_EXT, REC, RUN_BASE, RUN_ID, STATES, VERDICTS -class Run: - def __init__( - self, - observers: Sequence[BaseObserver] = [], - ingredients: list = [], - run_id: int = None, - scenario=None, - pre_run_hooks: list = [], - post_run_hooks: list = [], - **kwargs, - ): - self._id = run_id - self.observers = observers - self.ingredients = ingredients - self.start_time = None - self.end_time = None - self.status = None - self.result = None - self.pre_run_hooks = pre_run_hooks - self.post_run_hooks = post_run_hooks +if TYPE_CHECKING: + # The MariaDB driver is an optional extra. + from rec.stores.file_store import FileStore + from rec.stores.mariadb_store import MariaDBStore - self.heartbeat = None - self.beat_interval = 10 +logger = logging.getLogger(__name__) - def _get_active_run(self): - if self._id is not None: - # We start with a known ID, we probably don't need to do anything - pass - if self._id is None: - # First query the DB to see if there is any run marked as active. - _id = self.observers[0].query_active_run() - # If no run is marked as active, create one in the DB and return the ID - return _id - def _stop_time(self): - self.stop_time = datetime.datetime.now(datetime.UTC) - elapsed_time = datetime.timedelta( - seconds=round((self.stop_time - self.start_time).total_seconds()) +class Run: + """A run, recorded in its store as a `prov-ext:Execution` and an `oslc_auto:AutomationResult`. + + The run lives in its own `prov:Bundle`, attributed to the rec that first recorded it. Every + step is one edit of the bundle the store parsed under its lock: the run's state is checked and + only the step's triples change. Any holder of the id reaches the same run through the store. + """ + + def __init__(self, store: FileStore | MariaDBStore, run_id: str | None = None, base: str = RUN_BASE): + """ + :param store: Where the run's bundle is kept + :param run_id: The run's id; a UUID is minted when none is given + :param base: IRI base of the run's node, ```` + :raises ValueError: ``run_id`` is not a run id (``rec.provenance.RUN_ID``) + """ + self.id = run_id or str(uuid4()) + if not RUN_ID.fullmatch(self.id): + raise ValueError(f"'{self.id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") + self.store = store + self.node = URIRef(base + self.id) + # Read once: it inspects rec's checkout, and every step holds the store's lock. + self.recorder = get_py_pkg_info("rec") + self.beat_interval = 10.0 + + @contextmanager + def _step(self, allowed: tuple[URIRef, ...], refusal: str): + """Yield the run's bundle and current state under the store's lock; the bundle is created on the first step. + + :param allowed: The states the step may start from + :param refusal: Why the step is refused from any other state + :raises RuntimeError: The run is in a state not ``allowed`` + """ + with self.store.edit(self.id) as ds: + bundle = next((graph for graph in ds.graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph), None) + if bundle is None: + bundle = ds.graph(create_bundle(ds, self.recorder.purl)) + load_pkg_prov(bundle, self.recorder) + bundle.add((self.node, RDF.type, PROV_EXT.Execution)) + bundle.add((self.node, RDF.type, OSLC_AUTO.AutomationResult)) + bundle.add((self.node, OSLC_AUTO.state, OSLC_AUTO.new)) + bundle.add((self.node, OSLC_AUTO.verdict, OSLC_AUTO.unavailable)) + state = bundle.value(self.node, OSLC_AUTO.state) + if state not in allowed: + raise RuntimeError(f"run '{self.id}' is {state.fragment} -- {refusal}") + yield bundle, state + + def lifecycle(self) -> tuple[State, Verdict]: + """The run's state and verdict as the store keeps them; a run not stored is new.""" + ds = self.store.load(self.id) + if ds is None: + return State.NEW, Verdict.UNAVAILABLE + ds.default_union = True + state, verdict = ds.value(self.node, OSLC_AUTO.state), ds.value(self.node, OSLC_AUTO.verdict) + return ( + next(name for name, iri in STATES.items() if iri == state), + next(name for name, iri in VERDICTS.items() if iri == verdict), ) - return elapsed_time - - def _start_heartbeat(self): - if self.beat_interval > 0: - self._stop_heartbeat_event, self._heartbeat = IntervalTimer.create( - self._emit_heartbeat, self.beat_interval - ) - self._heartbeat.start() - - def _stop_heartbeat(self): - # only stop if heartbeat was started - if self._heartbeat is not None: - self._stop_heartbeat_event.set() - self._heartbeat.join(timeout=2) - - def _emit_heartbeat(self): - beat_time = datetime.datetime.now(datetime.UTC) - print("Running....") - - # Update info on observers - for observer in self.observers: - observer.log_run_heartbeat(self._id, beat_time, result=self.result) - - def _emit_cancelled(self): - self.status = RunStatus.CANCELLED - cancelled_time = datetime.datetime.now(datetime.UTC) - - # Update info on observers - for observer in self.observers: - observer.log_cancelled_run(self._id, cancelled_time) - - def _emit_queued(self): - self.status = RunStatus.QUEUED - queued_time = datetime.datetime.now(datetime.UTC) - - # Update info on observers - for observer in self.observers: - observer.log_queued_run(self._id, queued_time) - - def _emit_started(self, trigger=None, starter=None): - """ - Records the metadata of the starting run - :param trigger: An entity that triggers the run - :param starter: The activity that generated the trigger - :return: - """ - self.status = RunStatus.RUNNING - self._id = self._get_active_run() - self.start_time = datetime.datetime.now(datetime.UTC) - - # Update info on observers - for observer in self.observers: - _id = observer.log_started_run( - self._id, - self.start_time, - trigger=trigger, - starter=starter, - ) - if self._id is None: - self._id = _id - print("Starting run with ID {}".format(self._id)) - - def _emit_completed(self): - self.status = RunStatus.COMPLETED - elapsed_time = self._stop_time() - print("Completed after {}".format(elapsed_time)) - - # Update info on observers - for observer in self.observers: - observer.log_completed_run(self._id, self.stop_time) - - def _emit_interrupted(self): - self.status = RunStatus.INTERRUPTED - elapsed_time = self._stop_time() - - # Update info on observers - for observer in self.observers: - observer.log_interrupted_run(self._id, elapsed_time) - - def _emit_failed(self): - self.status = RunStatus.FAILED - elapsed_time = self._stop_time() - - # Update info on observers - for observer in self.observers: - observer.log_failed_run(self._id, elapsed_time) - - def _execute_hooks(self, hooks): - for hook in hooks: - hook() - - def main(self): - pass - - def run(self): - """ - A centralized runner can start and complete a run. Decentralized runners should not use this method. - :return: - """ + def queue(self): + """Record a new run as queued, before a runner starts it.""" + with self._step((OSLC_AUTO.new,), "only a new run can be queued") as (bundle, _): + bundle.set((self.node, OSLC_AUTO.state, OSLC_AUTO.queued)) + bundle.add((self.node, REC["queued-time"], Literal(datetime.now(UTC)))) + logger.info("Queued run %s", self.id) + + def start(self): + """Record a new or queued run as in progress, executed by this rec on this machine.""" + host = { + "hostname": socket.gethostname(), + "os": platform.platform(), + "python": platform.python_version(), + "cpu": platform.processor() or None, + } + with self._step((OSLC_AUTO.new, OSLC_AUTO.queued), "only a run that has not started can start") as (bundle, _): + # The rec that starts the run executes it; another rec may have queued it. + if (self.recorder.purl, RDF.type, PROV.Agent) not in bundle: + load_pkg_prov(bundle, self.recorder) + started = add_wall_instant(bundle, datetime.now(UTC), instant_id=URIRef(f"{self.node}/beginning")) + load_execution_prov(bundle, self.node, (), self.recorder.purl, started) + bundle.set((self.node, OSLC_AUTO.state, OSLC_AUTO.inProgress)) + node = URIRef(f"{self.node}/host") + bundle.add((node, RDF.type, REC.Host)) + bundle.add((node, RDF.type, PROV.Location)) + for key, predicate in HOST_TERMS.items(): + if host[key]: + bundle.add((node, predicate, Literal(host[key]))) + bundle.add((self.node, PROV.atLocation, node)) + logger.info("Started run %s", self.id) + + def beat(self): + """Record that the started run is still alive.""" + with self._step((OSLC_AUTO.inProgress, OSLC_AUTO.canceling), "only a started run beats") as (bundle, _): + bundle.set((self.node, REC["heartbeat-time"], Literal(datetime.now(UTC)))) + + def end(self, verdict: Verdict, fail_trace: str | None = None): + """End the started run with its verdict: a canceling run that passed ends canceled, any other ends complete. + + :param verdict: ``passed``, ``failed`` (an exception ended it) or ``error`` (it was interrupted) + :param fail_trace: The trace of what ended a failed or error run; none for a passed one + :raises ValueError: The verdict is unavailable, or a passed run has a trace + """ + if verdict is Verdict.UNAVAILABLE: + raise ValueError(f"run '{self.id}' cannot end without a verdict -- end it as passed, failed or error") + if verdict is Verdict.PASSED and fail_trace: + raise ValueError(f"run '{self.id}' passed with a fail trace -- only a failed or error run has one") + with self._step((OSLC_AUTO.inProgress, OSLC_AUTO.canceling), "only a started run can end") as (bundle, state): + ended = add_wall_instant(bundle, datetime.now(UTC), instant_id=URIRef(f"{self.node}/end")) + bundle.add((self.node, TIME.hasEnd, ended)) + # A run that failed while canceling did not stop as asked: its verdict stands. + if state == OSLC_AUTO.canceling and verdict is Verdict.PASSED: + bundle.set((self.node, OSLC_AUTO.state, OSLC_AUTO.canceled)) + else: + bundle.set((self.node, OSLC_AUTO.state, OSLC_AUTO.complete)) + bundle.set((self.node, OSLC_AUTO.verdict, VERDICTS[verdict])) + if fail_trace: + bundle.add((self.node, REC["fail-trace"], Literal(fail_trace, datatype=XSD.string))) + logger.log(logging.INFO if verdict is Verdict.PASSED else logging.ERROR, "Ended run %s as %s", self.id, verdict) + + def cancel(self): + """Cancel a queued run, or ask one in progress to stop: it ends canceled once its work returns. + + A queued run that is cancelled never started, so it has neither a beginning nor an end. + """ + refusal = "only a queued run or one in progress can be cancelled" + with self._step((OSLC_AUTO.queued, OSLC_AUTO.inProgress), refusal) as (bundle, state): + bundle.set((self.node, OSLC_AUTO.state, OSLC_AUTO.canceled if state == OSLC_AUTO.queued else OSLC_AUTO.canceling)) + logger.info("Cancelled run %s", self.id) + + def run(self, work: Callable[[Run], object]) -> object: + """Start the run, do ``work(self)`` while the run beats, and end it by how the work ended. + + ``work`` sees a cancel request as ``self.lifecycle()[0] is State.CANCELING``. + + :returns: What ``work`` returned, None if it raised; rec does not record it + :raises BaseException: What interrupted ``work``, e.g. ``KeyboardInterrupt``, once the run is ended as error + """ + self.start() + stopped = threading.Event() + + def beat_until_stopped(): + while not stopped.wait(self.beat_interval): + # A store briefly out of reach must not stop the beats that follow. + try: + self.beat() + except Exception: + logger.exception("Run %s could not record its heartbeat", self.id) + + beating = threading.Thread(target=beat_until_stopped, daemon=True) + error, result = None, None try: - self._emit_started() - self._start_heartbeat() - self._execute_hooks(self.pre_run_hooks) - self.result = self.main() - print("Result: {}".format(self.result)) - self._emit_completed() - self._stop_heartbeat() - self._execute_hooks(self.post_run_hooks) - except KeyboardInterrupt as k: - self._stop_heartbeat() - self._emit_interrupted() - except Exception as ex: - self._stop_heartbeat() - self._emit_failed() + beating.start() + result = work(self) + except BaseException as caught: + error = caught finally: - for observer in self.observers: - observer.close() - - return self.result - - def log_scalar(self, metric_name, value, step: int = None): - """Log a measurement at runtime - - :param metric_name: Name of the metric being logged - :param value: The measured value - :param step: Optional. Integer value representing the iteration number - :return: - """ - pass - - def log_sources(self): - """Log the source code files used to execute this run (e.g., file name/path, md5) - :return: - """ - pass - - def log_repositories(self): - """ - Log the git information of the sources used in this run (url, commit/tag, uncommited changes) - :return: - """ - pass - - def log_dependencies(self): - """ - Log the dependencies of the sources used in this run (e.g., package name, version) - :return: - """ - pass - - def log_host_info(self): - """ - Log information about the machine executing this run (e.g., cpu, gpu, OS, user, hostname, python version and venv, env variables, etc.) - :return: - """ - pass - - def add_agent(self, agent_id: str, agent_type: str, **kwargs): - """ - Add an agent (e.g., a robot) to the run - :param agent_id: A unique ID for this agent - :param agent_type: The type of agent being added, e.g., software agent, robot etc. - :param kwargs: - :return: - """ - pass - - def add_resource( - self, - filename, - usage_activity=None, - usage_time=None, - title=None, - **kwargs, - ): - """ - Add a resource to the run - - This method only records the filename and minimal metadata. - If you need to process file contents in some way, use a Feature. - - :param filename: The file path of the resource - :param usage_activity: The activity that uses this resource. Default: This run - :param usage_time: The time this resource is used by the activity. - :param title: A short title for the resource. Default: The file name - :param kwargs: - :return: - """ - if usage_time is None: - usage_time = datetime.datetime.now(datetime.UTC) - - def add_artefact( - self, - filename, - gen_activity=None, - generated_time=None, - title=None, - **kwargs, - ): - """ - Add an artefact to the run - - This method only records the filename and minimal metadata. - If you need to process file contents in some way, use a Feature. - - :param filename: he file path of the generated artefact - :param gen_activity: The generating activity. Default: This run - :param generated_time: The time the artefact was generated - :param title: A short title for the generated artefact - :param kwargs: - :return: - """ - if generated_time is None: - generated_time = datetime.datetime.now(datetime.UTC) - - def info(self): - """Print out a summary of the run data - - :return: - """ - pass - - -class RunStatus: - RUNNING = "RUNNING" - COMPLETED = "COMPLETED" - FAILED = "FAILED" - INTERRUPTED = "INTERRUPTED" - CANCELLED = "CANCELLED" - QUEUED = "QUEUED" - TIMED_OUT = "TIMED_OUT" - DEAD = "DEAD" + stopped.set() + # Bounded: a beat stuck on the store must not keep the run from ending. + beating.join(timeout=self.beat_interval) + try: + if error is None: + self.end(Verdict.PASSED) + else: + self.end(Verdict.FAILED if isinstance(error, Exception) else Verdict.ERROR, "".join(traceback.format_exception(error))) + finally: + # An interrupt is the process being asked to stop: passed on even when the end cannot be recorded. + if error is not None and not isinstance(error, Exception): + raise error + return result diff --git a/rec/scenario.py b/rec/scenario.py deleted file mode 100644 index 5de242a..0000000 --- a/rec/scenario.py +++ /dev/null @@ -1,18 +0,0 @@ -from rec.run import Run -from rec.feature import Feature - - -class Scenario(Feature): - def __init__(self, name, ingredients: list, **kwargs): - self.name = name - self.ingredients = ingredients - self.observers = kwargs.get("observers", []) - self.current_run = None - - def run(self): - # Create a run object - self.current_run = Run(observers=self.observers) - - # Call it so it runs - self.current_run.run() - return self.current_run diff --git a/rec/stores/__init__.py b/rec/stores/__init__.py new file mode 100644 index 0000000..2b9d5b7 --- /dev/null +++ b/rec/stores/__init__.py @@ -0,0 +1 @@ +"""Where runs' provenance bundles are kept: ``FileStore`` and ``MariaDBStore``, each with ``load`` and a locked ``edit``.""" diff --git a/rec/stores/file_store.py b/rec/stores/file_store.py new file mode 100644 index 0000000..ca13689 --- /dev/null +++ b/rec/stores/file_store.py @@ -0,0 +1,52 @@ +"""A store keeping each run's provenance bundle as a JSON-LD file in a directory.""" + +import fcntl +from contextlib import contextmanager +from pathlib import Path + +from rdf_utils import DatasetFormat +from rdflib import Dataset + +from rec.provenance import CONTEXT + + +class FileStore: + def __init__(self, directory): + """ + :param directory: Where the files go, ``.ld.json`` each; created on first write + """ + self.directory = Path(directory) + + def path(self, run_id: str) -> Path: + """Return the run's file, ``.ld.json`` in the directory. + + :raises ValueError: ``run_id`` would name a file outside the directory, e.g. ``../x`` + """ + path = self.directory / f"{run_id}.{DatasetFormat.JSON_LD.extension}" + if path.parent != self.directory: + raise ValueError(f"'{run_id}' names a file outside '{self.directory}' -- a run's file is in the store's directory") + return path + + def load(self, run_id: str) -> Dataset | None: + """Return the run's bundle as stored, or None if the run is not stored.""" + path = self.path(run_id) + if not path.exists(): + return None + return Dataset().parse(path, format=DatasetFormat.JSON_LD) + + @contextmanager + def edit(self, run_id: str): + """Yield the run's dataset under an ``flock`` on ``.lock``, empty if the run is new, and save it when the block exits. + + The file is replaced whole, through a temporary file; if the block raises, it is left as it was. + """ + path = self.path(run_id) + self.directory.mkdir(parents=True, exist_ok=True) + # The lock file stays: removing it would let a waiting process lock a file no longer in the directory. + with open(path.with_name(f"{run_id}.lock"), "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + ds = Dataset().parse(path, format=DatasetFormat.JSON_LD) if path.exists() else Dataset() + yield ds + temporary = path.with_name(f"{path.name}.tmp") + temporary.write_text(ds.serialize(format=DatasetFormat.JSON_LD, context=CONTEXT, indent=2)) + temporary.replace(path) diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py new file mode 100644 index 0000000..4d7760e --- /dev/null +++ b/rec/stores/mariadb_store.py @@ -0,0 +1,85 @@ +"""A store keeping runs in MariaDB: a row per run, holding its provenance bundle as JSON-LD.""" + +import os +import re +import threading +from contextlib import contextmanager + +import mariadb +from dotenv import load_dotenv +from rdf_utils import DatasetFormat +from rdflib import Dataset + +from rec.provenance import CONTEXT + + +class MariaDBStore: + def __init__(self, db_name: str = "logbook", prefix: str = "logs"): + """ + Store in MariaDB tables, connecting with ``MARIADB_USER``, ``MARIADB_PASSWORD``, + ``MARIADB_HOST`` and ``MARIADB_PORT`` from the environment or a ``.env`` file + + :param db_name: Name of the database + :param prefix: Prefix of the table name: ``_runs`` has a row per run, ``id`` in the + order runs were added and ``bundle`` its provenance bundle as JSON-LD + """ + # The prefix is part of a table name, which SQL cannot take as a bound parameter. + if not re.fullmatch(r"[A-Za-z0-9_]{1,59}", prefix): + raise ValueError(f"'{prefix}' is not a table prefix -- use up to 59 letters, digits or '_'") + load_dotenv() + self.prefix = prefix + self.conn = mariadb.connect( + user=os.getenv("MARIADB_USER"), + password=os.getenv("MARIADB_PASSWORD"), + host=os.getenv("MARIADB_HOST"), + port=int(os.getenv("MARIADB_PORT")), + database=db_name, + ) + self.conn.autocommit = True + self.cursor = self.conn.cursor() + # One connection for every thread using the store, so one statement or transaction at a time. + self._lock = threading.RLock() + # Binary ASCII: a run id is case-sensitive, and the default collation would fold `Pick-1` into `pick-1`. + self.cursor.execute( + f"CREATE TABLE IF NOT EXISTS {prefix}_runs (" + "id INT AUTO_INCREMENT PRIMARY KEY, " + "run_id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE, " + "bundle LONGTEXT)" + ) + + def load(self, run_id: str) -> Dataset | None: + """Return the run's bundle as stored, or None if the run is not stored.""" + with self._lock: + self.cursor.execute(f"SELECT bundle FROM {self.prefix}_runs WHERE run_id = ?", (run_id,)) + row = self.cursor.fetchone() + if row is None or row[0] is None: + return None + return Dataset().parse(data=row[0], format=DatasetFormat.JSON_LD) + + @contextmanager + def edit(self, run_id: str): + """Yield the run's dataset in one transaction, empty if the run is new, and save it when the block exits; roll back if it raises.""" + with self._lock: + self.conn.begin() + try: + # Locks the run's row, inserting it if new. A SELECT ... FOR UPDATE of a missing row takes + # only a gap lock, which two edits of new runs both get, and then deadlock on their inserts. + self.cursor.execute( + f"INSERT INTO {self.prefix}_runs (run_id) VALUES (?) ON DUPLICATE KEY UPDATE run_id = run_id", (run_id,) + ) + self.cursor.execute(f"SELECT bundle FROM {self.prefix}_runs WHERE run_id = ?", (run_id,)) + bundle = self.cursor.fetchone()[0] + ds = Dataset().parse(data=bundle, format=DatasetFormat.JSON_LD) if bundle else Dataset() + yield ds + self.cursor.execute( + f"UPDATE {self.prefix}_runs SET bundle = ? WHERE run_id = ?", + (ds.serialize(format=DatasetFormat.JSON_LD, context=CONTEXT), run_id), + ) + except BaseException: + self.conn.rollback() + raise + self.conn.commit() + + def close(self) -> None: + self.cursor.close() + self.conn.close() diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py new file mode 100644 index 0000000..053765d --- /dev/null +++ b/tests/test_mariadb_store.py @@ -0,0 +1,65 @@ +import os +from pathlib import Path +from uuid import uuid4 + +import pytest +from pyshacl import validate +from rdflib import Graph + +pytest.importorskip("mariadb", reason="the MariaDB driver is an optional extra") +from rec import State, Verdict # noqa: E402 +from rec.run import Run # noqa: E402 +from rec.stores.mariadb_store import MariaDBStore # noqa: E402 + +METAMODELS = Path(os.getenv("REC_METAMODELS_DIR", Path(__file__).resolve().parents[2] / "metamodels")) +SHAPES = Graph() +for name in ("prov.shacl.ttl", "prov-extension.shacl.ttl", "rec/rec.shacl.ttl"): + SHAPES.parse(METAMODELS / name, format="turtle") +TEST_DATABASE = os.getenv("REC_TEST_MARIADB_DATABASE") +pytestmark = pytest.mark.skipif( + not TEST_DATABASE, + reason="set REC_TEST_MARIADB_DATABASE to run MariaDB integration tests", +) + + +@pytest.fixture +def store(): + prefix = f"rec_test_{uuid4().hex}" + db = MariaDBStore(db_name=TEST_DATABASE, prefix=prefix) + yield db + db.cursor.execute(f"DROP TABLE IF EXISTS {prefix}_runs") + db.close() + + +def succeed(run): + return "ok" + + +def test_a_row_keeps_the_run_as_a_valid_bundle(store): + run = Run(store, "run-0") + run.run(succeed) + assert run.lifecycle() == (State.COMPLETE, Verdict.PASSED) + ok, _, report = validate(store.load("run-0"), shacl_graph=SHAPES, inference="rdfs") + assert ok, report + + +def test_a_queued_run_is_cancelled_by_id_from_another_connection(store): + run = Run(store, "queued") + run.queue() + scheduler = MariaDBStore(db_name=TEST_DATABASE, prefix=store.prefix) + Run(scheduler, "queued").cancel() + scheduler.close() + assert run.lifecycle() == (State.CANCELED, Verdict.UNAVAILABLE) + + +def test_run_ids_differing_in_case_are_two_runs(store): + Run(store, "Pick-1").run(succeed) + Run(store, "pick-1").queue() + assert Run(store, "Pick-1").lifecycle() == (State.COMPLETE, Verdict.PASSED) + assert Run(store, "pick-1").lifecycle() == (State.QUEUED, Verdict.UNAVAILABLE) + + +@pytest.mark.parametrize("prefix", ["team-a", "logs; DROP TABLE x", ""]) +def test_a_prefix_that_is_not_a_table_name_is_refused(prefix): + with pytest.raises(ValueError, match="is not a table prefix"): + MariaDBStore(db_name=TEST_DATABASE, prefix=prefix) diff --git a/tests/test_run.py b/tests/test_run.py new file mode 100644 index 0000000..33e4038 --- /dev/null +++ b/tests/test_run.py @@ -0,0 +1,213 @@ +import os +import threading +from pathlib import Path + +import pytest +from pyshacl import validate +from rdflib import Graph, URIRef +from rdflib.namespace import PROV, RDF, TIME + +from rec import State, Verdict +from rec.provenance import OSLC_AUTO, PROV_EXT, REC, RUN_BASE +from rec.run import Run +from rec.stores.file_store import FileStore + +METAMODELS = Path(os.getenv("REC_METAMODELS_DIR", Path(__file__).resolve().parents[2] / "metamodels")) +SHAPES = Graph() +for name in ("prov.shacl.ttl", "prov-extension.shacl.ttl", "rec/rec.shacl.ttl"): + SHAPES.parse(METAMODELS / name, format="turtle") + + +def calibrate(run): + return "calibrated" + + +def drop_gripper(run): + raise ValueError("no gripper attached") + + +def interrupt(run): + raise KeyboardInterrupt + + +def exit_process(run): + raise SystemExit(3) + + +def stop_when_asked(run): + # A scheduler holding only the id asks the run to stop while it is in progress. + Run(run.store, run.id).cancel() + return "stopped" if run.lifecycle()[0] is State.CANCELING else "finished" + + +def jam_while_stopping(run): + Run(run.store, run.id).cancel() + raise ValueError("gripper jammed while releasing") + + +def wait_a_little(run): + threading.Event().wait(0.05) + + +def end_then_interrupt(run): + # Ended by someone else before the work returns, so the run's own end is refused. + Run(run.store, run.id).end(Verdict.PASSED) + raise KeyboardInterrupt + + +@pytest.fixture +def store(tmp_path): + return FileStore(tmp_path) + + +def test_a_completed_run_is_an_execution_by_rec_in_a_bundle_attributed_to_rec(store): + run = Run(store, "run-1") + assert run.run(calibrate) == "calibrated" + + ds = store.load("run-1") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + [bundle] = [graph for graph in ds.graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph] + node = URIRef(RUN_BASE + "run-1") + assert (node, RDF.type, PROV_EXT.Execution) in bundle + assert bundle.value(bundle.identifier, PROV.wasAttributedTo) == run.recorder.purl == bundle.value(node, PROV.wasAssociatedWith) + assert bundle.value(bundle.value(node, PROV.atLocation), RDF.type) is not None + assert run.lifecycle() == (State.COMPLETE, Verdict.PASSED) + + +def test_a_run_keeps_one_bundle_through_its_lifecycle(store): + run = Run(store, "run-b") + run.queue() + queued = {graph.identifier for graph in store.load("run-b").graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph} + run.run(calibrate) + ended = {graph.identifier for graph in store.load("run-b").graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph} + assert len(queued) == 1 and ended == queued + + +def test_a_step_changes_only_its_own_triples(store): + """A triple another tool put in the run's bundle survives rec's later steps.""" + Run(store, "run-k").queue() + with store.edit("run-k") as ds: + [bundle] = [graph for graph in ds.graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph] + bundle.add((URIRef(RUN_BASE + "run-k"), PROV.wasInfluencedBy, URIRef("https://example.org/schedule/1"))) + Run(store, "run-k").run(calibrate) + ds = store.load("run-k") + ds.default_union = True + assert (URIRef(RUN_BASE + "run-k"), PROV.wasInfluencedBy, URIRef("https://example.org/schedule/1")) in ds + + +def test_a_queued_run_has_not_executed_yet(store): + Run(store, "run-q").queue() + ds = store.load("run-q") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + ds.default_union = True + node = URIRef(RUN_BASE + "run-q") + assert {PROV_EXT.Execution, OSLC_AUTO.AutomationResult} <= set(ds.objects(node, RDF.type)) + assert ds.value(node, TIME.hasBeginning) is None and ds.value(node, PROV.wasAssociatedWith) is None + assert ds.value(node, REC["queued-time"]) is not None + + +def test_a_run_whose_work_raises_fails_with_its_trace(store): + run = Run(store, "run-f") + assert run.run(drop_gripper) is None + assert run.lifecycle() == (State.COMPLETE, Verdict.FAILED) + ds = store.load("run-f") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + ds.default_union = True + assert "ValueError: no gripper attached" in str(ds.value(URIRef(RUN_BASE + "run-f"), REC["fail-trace"])) + + +@pytest.mark.parametrize(("work", "raised"), [(interrupt, KeyboardInterrupt), (exit_process, SystemExit)]) +def test_an_interrupted_run_ends_as_error_and_the_interrupt_goes_on(store, work, raised): + run = Run(store, "run-i") + with pytest.raises(raised): + run.run(work) + assert run.lifecycle() == (State.COMPLETE, Verdict.ERROR) + ok, _, report = validate(store.load("run-i"), shacl_graph=SHAPES, inference="rdfs") + assert ok, report + + +def test_an_interrupt_goes_on_when_the_end_cannot_be_recorded(store): + with pytest.raises(KeyboardInterrupt): + Run(store, "run-e").run(end_then_interrupt) + + +@pytest.mark.parametrize( + ("verdict", "trace", "message"), + [(Verdict.UNAVAILABLE, None, "without a verdict"), (Verdict.PASSED, "Traceback", "passed with a fail trace")], + ids=["no verdict", "passed with a trace"], +) +def test_a_contradictory_end_is_refused_and_the_run_kept_running(store, verdict, trace, message): + run = Run(store, "run-v") + run.start() + with pytest.raises(ValueError, match=message): + run.end(verdict, trace) + assert run.lifecycle() == (State.IN_PROGRESS, Verdict.UNAVAILABLE) + + +def test_only_a_queued_run_or_one_in_progress_is_cancelled(store): + queued = Run(store, "run-q") + queued.queue() + # A scheduler holding only the id cancels a run it did not create, and the store decides. + Run(store, "run-q").cancel() + assert queued.lifecycle() == (State.CANCELED, Verdict.UNAVAILABLE) + with pytest.raises(RuntimeError, match="is canceled"): + queued.run(calibrate) + ds = store.load("run-q") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + ds.default_union = True + # It never started, so it has neither a beginning nor an end. + assert ds.value(URIRef(RUN_BASE + "run-q"), TIME.hasBeginning) is None + assert ds.value(URIRef(RUN_BASE + "run-q"), TIME.hasEnd) is None + + done = Run(store, "run-d") + done.run(calibrate) + with pytest.raises(RuntimeError, match="only a queued run or one in progress"): + Run(store, "run-d").cancel() + assert done.lifecycle() == (State.COMPLETE, Verdict.PASSED) + + +def test_a_run_in_progress_stops_when_cancelled(store): + run = Run(store, "run-s") + assert run.run(stop_when_asked) == "stopped" + assert run.lifecycle() == (State.CANCELED, Verdict.UNAVAILABLE) + ds = store.load("run-s") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + ds.default_union = True + node = URIRef(RUN_BASE + "run-s") + assert ds.value(node, TIME.hasBeginning) is not None and ds.value(node, TIME.hasEnd) is not None + + +def test_a_run_that_fails_while_stopping_keeps_its_verdict(store): + run = Run(store, "run-c") + run.run(jam_while_stopping) + assert run.lifecycle() == (State.COMPLETE, Verdict.FAILED) + ok, _, report = validate(store.load("run-c"), shacl_graph=SHAPES, inference="rdfs") + assert ok, report + + +def test_a_running_run_beats(store): + run = Run(store, "run-h") + run.beat_interval = 0.01 + run.run(wait_a_little) + ds = store.load("run-h") + ds.default_union = True + assert ds.value(URIRef(RUN_BASE + "run-h"), REC["heartbeat-time"]) is not None + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + + +@pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run", "a run", "läuft", ".", ".."]) +def test_a_run_id_is_unreserved_characters_only(store, run_id): + with pytest.raises(ValueError, match="is not a run id"): + Run(store, run_id) + + +@pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run"]) +def test_a_file_store_reads_no_file_outside_its_directory(store, run_id): + with pytest.raises(ValueError, match="names a file outside"): + store.load(run_id)